hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e17ca6ccc79468abca3df9bbd7057d8a9036cef | 1,426 | java | Java | src/main/java/com/github/klyser8/earthbounds/util/AdvancedBlockPos.java | EndsM/Earthbounds | fd1227a4d875f4ba8433820bd4730481c6fd36af | [
"MIT"
] | 4 | 2022-02-01T11:11:15.000Z | 2022-03-11T20:58:58.000Z | src/main/java/com/github/klyser8/earthbounds/util/AdvancedBlockPos.java | EndsM/Earthbounds | fd1227a4d875f4ba8433820bd4730481c6fd36af | [
"MIT"
] | 7 | 2022-01-30T17:44:01.000Z | 2022-03-21T09:32:55.000Z | src/main/java/com/github/klyser8/earthbounds/util/AdvancedBlockPos.java | EndsM/Earthbounds | fd1227a4d875f4ba8433820bd4730481c6fd36af | [
"MIT"
] | 2 | 2022-02-11T12:54:30.000Z | 2022-02-28T05:57:49.000Z | 22.634921 | 86 | 0.610098 | 10,139 | package com.github.klyser8.earthbounds.util;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import java.util.List;
/**
* Represents a {@link BlockPos} which also stores block positions of adjacent blocks.
* Can be used to check a
*/
public class AdvancedBlockPos {
private final BlockPos pos;
private final BlockPos north, east, south, west, up, down;
public AdvancedBlockPos(BlockPos pos) {
this.pos = pos;
north = pos.mutableCopy().north();
east = pos.mutableCopy().east();
south = pos.mutableCopy().south();
west = pos.mutableCopy().west();
up = pos.mutableCopy().up();
down = pos.mutableCopy().down();
}
/**
* Returns all the adjacent block positions to the main block (as an array).
*/
public BlockPos[] getAllFaces() {
return new BlockPos[]{north, east, south, west, up, down};
}
public BlockPos getPos() {
return new BlockPos(pos);
}
public BlockPos north() {
return new BlockPos(north);
}
public BlockPos east() {
return new BlockPos(east);
}
public BlockPos south() {
return new BlockPos(south);
}
public BlockPos west() {
return new BlockPos(west);
}
public BlockPos up() {
return new BlockPos(up);
}
public BlockPos down() {
return new BlockPos(down);
}
}
|
3e17cb040dc73a7936fe25d5d55b8e00dd305a91 | 5,337 | java | Java | hyracks-fullstack/hyracks/hyracks-storage-am-lsm-common/src/main/java/org/apache/hyracks/storage/am/lsm/common/impls/LSMIndexDiskComponentBulkLoader.java | simon-dew/asterixdb | 81c3249322957be261cd99bf7d6b464fcb4a3bbd | [
"Apache-2.0"
] | 200 | 2016-06-16T01:01:42.000Z | 2022-03-24T08:16:13.000Z | hyracks-fullstack/hyracks/hyracks-storage-am-lsm-common/src/main/java/org/apache/hyracks/storage/am/lsm/common/impls/LSMIndexDiskComponentBulkLoader.java | simon-dew/asterixdb | 81c3249322957be261cd99bf7d6b464fcb4a3bbd | [
"Apache-2.0"
] | 3 | 2018-01-29T21:39:26.000Z | 2021-06-17T20:11:31.000Z | hyracks-fullstack/hyracks/hyracks-storage-am-lsm-common/src/main/java/org/apache/hyracks/storage/am/lsm/common/impls/LSMIndexDiskComponentBulkLoader.java | simon-dew/asterixdb | 81c3249322957be261cd99bf7d6b464fcb4a3bbd | [
"Apache-2.0"
] | 112 | 2016-06-12T21:51:05.000Z | 2022-02-05T17:16:33.000Z | 37.584507 | 120 | 0.683905 | 10,140 | /*
* 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.hyracks.storage.am.lsm.common.impls;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.dataflow.common.data.accessors.ITupleReference;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMDiskComponent;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMDiskComponentBulkLoader;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperation;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperation.LSMIOOperationStatus;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIndexOperationContext;
import org.apache.hyracks.storage.common.IIndexBulkLoader;
import org.apache.hyracks.storage.common.buffercache.ICachedPage;
public class LSMIndexDiskComponentBulkLoader implements IIndexBulkLoader {
private final AbstractLSMIndex lsmIndex;
private final ILSMDiskComponentBulkLoader componentBulkLoader;
private final ILSMIndexOperationContext opCtx;
private boolean failed = false;
public LSMIndexDiskComponentBulkLoader(AbstractLSMIndex lsmIndex, ILSMIndexOperationContext opCtx, float fillFactor,
boolean verifyInput, long numElementsHint) throws HyracksDataException {
this.lsmIndex = lsmIndex;
this.opCtx = opCtx;
this.componentBulkLoader = opCtx.getIoOperation().getNewComponent().createBulkLoader(opCtx.getIoOperation(),
fillFactor, verifyInput, numElementsHint, false, true, true,
lsmIndex.getPageWriteCallbackFactory().createPageWriteCallback());
}
public ILSMDiskComponent getComponent() {
return opCtx.getIoOperation().getNewComponent();
}
@SuppressWarnings("squid:S1181")
@Override
public void add(ITupleReference tuple) throws HyracksDataException {
try {
componentBulkLoader.add(tuple);
} catch (Throwable th) {
opCtx.getIoOperation().setFailure(th);
throw th;
}
}
@SuppressWarnings("squid:S1181")
public void delete(ITupleReference tuple) throws HyracksDataException {
try {
componentBulkLoader.delete(tuple);
} catch (Throwable th) {
opCtx.getIoOperation().setFailure(th);
throw th;
}
}
@Override
public void end() throws HyracksDataException {
try {
presistComponentToDisk();
} catch (Throwable th) { // NOSONAR must cleanup in case of any failure
fail(th);
throw th;
} finally {
lsmIndex.getIOOperationCallback().completed(opCtx.getIoOperation());
}
}
@Override
public void abort() throws HyracksDataException {
opCtx.getIoOperation().setStatus(LSMIOOperationStatus.FAILURE);
try {
try {
componentBulkLoader.abort();
} finally {
lsmIndex.getIOOperationCallback().afterFinalize(opCtx.getIoOperation());
}
} finally {
lsmIndex.getIOOperationCallback().completed(opCtx.getIoOperation());
}
}
@Override
public void writeFailed(ICachedPage page, Throwable failure) {
throw new UnsupportedOperationException();
}
@Override
public boolean hasFailed() {
return opCtx.getIoOperation().hasFailed();
}
@Override
public Throwable getFailure() {
return opCtx.getIoOperation().getFailure();
}
private void presistComponentToDisk() throws HyracksDataException {
try {
lsmIndex.getIOOperationCallback().afterOperation(opCtx.getIoOperation());
componentBulkLoader.end();
} catch (Throwable th) { // NOSONAR Must not call afterFinalize without setting failure
fail(th);
throw th;
} finally {
lsmIndex.getIOOperationCallback().afterFinalize(opCtx.getIoOperation());
}
if (opCtx.getIoOperation().getStatus() == LSMIOOperationStatus.SUCCESS
&& opCtx.getIoOperation().getNewComponent().getComponentSize() > 0) {
lsmIndex.getHarness().addBulkLoadedComponent(opCtx.getIoOperation());
}
}
private void fail(Throwable th) {
if (!failed) {
failed = true;
final ILSMIOOperation loadOp = opCtx.getIoOperation();
loadOp.setFailure(th);
loadOp.cleanup(lsmIndex.getBufferCache());
}
}
@Override
public void force() throws HyracksDataException {
componentBulkLoader.force();
}
}
|
3e17cb4192b9349b2e421aeee1c211d98f7f1cb0 | 1,714 | java | Java | src/main/java/mediacontent/GameInfo.java | LithiumSR/media_information_service | 5a47eb4cca53d36e7ba055d4f2d1c7d0906997b2 | [
"MIT"
] | null | null | null | src/main/java/mediacontent/GameInfo.java | LithiumSR/media_information_service | 5a47eb4cca53d36e7ba055d4f2d1c7d0906997b2 | [
"MIT"
] | 1 | 2017-12-18T19:13:18.000Z | 2017-12-18T19:13:40.000Z | src/main/java/mediacontent/GameInfo.java | LithiumSR/media_information_service | 5a47eb4cca53d36e7ba055d4f2d1c7d0906997b2 | [
"MIT"
] | null | null | null | 24.84058 | 78 | 0.658693 | 10,141 | package mediacontent;
public class GameInfo extends MediaInfo {
public String vote= "Information not avaiable";
public String overview= "Information not avaiable";
public String platforms= "Information not avaiable";
public String pegi= "Information not avaiable";
public String age_required= "Information not avaiable";
public String webSite= "Information not avaiable";
public String releaseDate= "Information not avaiable";
public String wiki="Information not avaiable";
public String linkImage="Information not avaiable";
public String getVote() {
return vote;
}
public void setVote(String vote) {
this.vote = vote;
}
public String getOverview() {
return overview;
}
public void setOverview(String overview) {
this.overview = overview;
}
public String getPegi() {
return pegi;
}
public void setPegi(String pegi) {
this.pegi = pegi;
}
public void setAgeRequired(String age) {
age_required=age;
}
public void setWebSite(String webSite) {
this.webSite = webSite;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public String getWiki() { return wiki; }
public void setWiki(String wiki) { this.wiki = wiki; }
public String getLinkImage() {
return linkImage;
}
public void setLinkImage(String linkImage) {
this.linkImage = linkImage;
}
public String getPlatforms() { return platforms; }
public void setPlatforms(String platforms) { this.platforms = platforms; }
}
|
3e17cb5b4504fecbfe372226a3a4c256e8e32dd8 | 5,132 | java | Java | tlatools/test/pcal/Bug060125Test.java | yanghao/tlaplus | 298380a4b55260eb2cfb4139723e7157797a853a | [
"MIT"
] | null | null | null | tlatools/test/pcal/Bug060125Test.java | yanghao/tlaplus | 298380a4b55260eb2cfb4139723e7157797a853a | [
"MIT"
] | 1 | 2018-11-28T15:01:32.000Z | 2018-11-28T15:01:32.000Z | tlatools/test/pcal/Bug060125Test.java | yanghao/tlaplus | 298380a4b55260eb2cfb4139723e7157797a853a | [
"MIT"
] | null | null | null | 56.395604 | 89 | 0.662899 | 10,142 | /*******************************************************************************
* Copyright (c) 2018 Microsoft Research. All rights reserved.
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Contributors:
* Markus Alexander Kuppe - initial API and implementation
******************************************************************************/
package pcal;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import tlc2.output.EC;
public class Bug060125Test extends PCalModelCheckerTestCase {
public Bug060125Test() {
super("bug_06_01_25", "pcal");
}
@Test
public void testSpec() {
assertTrue(recorder.recordedWithStringValue(EC.TLC_INIT_GENERATED1, "1"));
assertTrue(recorder.recorded(EC.TLC_FINISHED));
assertFalse(recorder.recorded(EC.GENERAL));
assertTrue(recorder.recordedWithStringValues(EC.TLC_STATS, "130", "64", "0"));
assertTrue(recorder.recordedWithStringValue(EC.TLC_SEARCH_DEPTH, "15"));
assertCoverage(" line 121, col 17 to line 121, col 43 of module bug_06_01_25: 16\n" +
" line 122, col 17 to line 122, col 43 of module bug_06_01_25: 16\n" +
" line 123, col 17 to line 123, col 43 of module bug_06_01_25: 16\n" +
" line 124, col 17 to line 124, col 64 of module bug_06_01_25: 16\n" +
" line 125, col 17 to line 125, col 61 of module bug_06_01_25: 16\n" +
" line 126, col 17 to line 126, col 67 of module bug_06_01_25: 16\n" +
" line 127, col 17 to line 127, col 22 of module bug_06_01_25: 16\n" +
" line 135, col 27 to line 135, col 53 of module bug_06_01_25: 16\n" +
" line 136, col 27 to line 136, col 53 of module bug_06_01_25: 16\n" +
" line 137, col 27 to line 137, col 53 of module bug_06_01_25: 16\n" +
" line 138, col 27 to line 138, col 53 of module bug_06_01_25: 0\n" +
" line 139, col 27 to line 139, col 53 of module bug_06_01_25: 0\n" +
" line 140, col 27 to line 140, col 53 of module bug_06_01_25: 0\n" +
" line 141, col 16 to line 141, col 48 of module bug_06_01_25: 16\n" +
" line 142, col 26 to line 142, col 42 of module bug_06_01_25: 0\n" +
" line 151, col 24 to line 151, col 50 of module bug_06_01_25: 32\n" +
" line 152, col 24 to line 152, col 50 of module bug_06_01_25: 32\n" +
" line 153, col 24 to line 153, col 50 of module bug_06_01_25: 32\n" +
" line 154, col 17 to line 154, col 48 of module bug_06_01_25: 32\n" +
" line 155, col 27 to line 155, col 43 of module bug_06_01_25: 0\n" +
" line 162, col 27 to line 162, col 53 of module bug_06_01_25: 0\n" +
" line 163, col 27 to line 163, col 53 of module bug_06_01_25: 0\n" +
" line 164, col 27 to line 164, col 53 of module bug_06_01_25: 0\n" +
" line 165, col 27 to line 167, col 75 of module bug_06_01_25: 0\n" +
" line 168, col 27 to line 168, col 58 of module bug_06_01_25: 0\n" +
" line 169, col 27 to line 169, col 58 of module bug_06_01_25: 16\n" +
" line 170, col 37 to line 170, col 52 of module bug_06_01_25: 0\n" +
" line 171, col 26 to line 171, col 39 of module bug_06_01_25: 0\n" +
" line 174, col 19 to line 176, col 67 of module bug_06_01_25: 16\n" +
" line 177, col 19 to line 180, col 67 of module bug_06_01_25: 16\n" +
" line 181, col 16 to line 181, col 48 of module bug_06_01_25: 16\n" +
" line 182, col 26 to line 182, col 41 of module bug_06_01_25: 0\n" +
" line 192, col 16 to line 192, col 47 of module bug_06_01_25: 16\n" +
" line 193, col 26 to line 193, col 51 of module bug_06_01_25: 0\n" +
" line 196, col 16 to line 196, col 42 of module bug_06_01_25: 16\n" +
" line 197, col 16 to line 197, col 42 of module bug_06_01_25: 16\n" +
" line 198, col 16 to line 198, col 42 of module bug_06_01_25: 16\n" +
" line 207, col 16 to line 207, col 49 of module bug_06_01_25: 16\n" +
" line 208, col 26 to line 208, col 42 of module bug_06_01_25: 0\n" +
" line 218, col 70 to line 218, col 73 of module bug_06_01_25: 0");
}
}
|
3e17cc63d14021f186fe2ddc7ea2818a95b4d323 | 7,005 | java | Java | aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/DeletePortfolioRequest.java | jplippi/aws-sdk-java | 147eefec220e2944dc571283af6552611bc94301 | [
"Apache-2.0"
] | 1 | 2020-08-27T17:36:34.000Z | 2020-08-27T17:36:34.000Z | aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/DeletePortfolioRequest.java | jplippi/aws-sdk-java | 147eefec220e2944dc571283af6552611bc94301 | [
"Apache-2.0"
] | 3 | 2020-04-15T20:08:15.000Z | 2021-06-30T19:58:16.000Z | aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/DeletePortfolioRequest.java | jplippi/aws-sdk-java | 147eefec220e2944dc571283af6552611bc94301 | [
"Apache-2.0"
] | 1 | 2020-10-10T15:59:17.000Z | 2020-10-10T15:59:17.000Z | 23.826531 | 120 | 0.481228 | 10,143 | /*
* Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.servicecatalog.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DeletePortfolio" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeletePortfolioRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The language code.
* </p>
* <ul>
* <li>
* <p>
* <code>en</code> - English (default)
* </p>
* </li>
* <li>
* <p>
* <code>jp</code> - Japanese
* </p>
* </li>
* <li>
* <p>
* <code>zh</code> - Chinese
* </p>
* </li>
* </ul>
*/
private String acceptLanguage;
/**
* <p>
* The portfolio identifier.
* </p>
*/
private String id;
/**
* <p>
* The language code.
* </p>
* <ul>
* <li>
* <p>
* <code>en</code> - English (default)
* </p>
* </li>
* <li>
* <p>
* <code>jp</code> - Japanese
* </p>
* </li>
* <li>
* <p>
* <code>zh</code> - Chinese
* </p>
* </li>
* </ul>
*
* @param acceptLanguage
* The language code.</p>
* <ul>
* <li>
* <p>
* <code>en</code> - English (default)
* </p>
* </li>
* <li>
* <p>
* <code>jp</code> - Japanese
* </p>
* </li>
* <li>
* <p>
* <code>zh</code> - Chinese
* </p>
* </li>
*/
public void setAcceptLanguage(String acceptLanguage) {
this.acceptLanguage = acceptLanguage;
}
/**
* <p>
* The language code.
* </p>
* <ul>
* <li>
* <p>
* <code>en</code> - English (default)
* </p>
* </li>
* <li>
* <p>
* <code>jp</code> - Japanese
* </p>
* </li>
* <li>
* <p>
* <code>zh</code> - Chinese
* </p>
* </li>
* </ul>
*
* @return The language code.</p>
* <ul>
* <li>
* <p>
* <code>en</code> - English (default)
* </p>
* </li>
* <li>
* <p>
* <code>jp</code> - Japanese
* </p>
* </li>
* <li>
* <p>
* <code>zh</code> - Chinese
* </p>
* </li>
*/
public String getAcceptLanguage() {
return this.acceptLanguage;
}
/**
* <p>
* The language code.
* </p>
* <ul>
* <li>
* <p>
* <code>en</code> - English (default)
* </p>
* </li>
* <li>
* <p>
* <code>jp</code> - Japanese
* </p>
* </li>
* <li>
* <p>
* <code>zh</code> - Chinese
* </p>
* </li>
* </ul>
*
* @param acceptLanguage
* The language code.</p>
* <ul>
* <li>
* <p>
* <code>en</code> - English (default)
* </p>
* </li>
* <li>
* <p>
* <code>jp</code> - Japanese
* </p>
* </li>
* <li>
* <p>
* <code>zh</code> - Chinese
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DeletePortfolioRequest withAcceptLanguage(String acceptLanguage) {
setAcceptLanguage(acceptLanguage);
return this;
}
/**
* <p>
* The portfolio identifier.
* </p>
*
* @param id
* The portfolio identifier.
*/
public void setId(String id) {
this.id = id;
}
/**
* <p>
* The portfolio identifier.
* </p>
*
* @return The portfolio identifier.
*/
public String getId() {
return this.id;
}
/**
* <p>
* The portfolio identifier.
* </p>
*
* @param id
* The portfolio identifier.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DeletePortfolioRequest withId(String id) {
setId(id);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAcceptLanguage() != null)
sb.append("AcceptLanguage: ").append(getAcceptLanguage()).append(",");
if (getId() != null)
sb.append("Id: ").append(getId());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DeletePortfolioRequest == false)
return false;
DeletePortfolioRequest other = (DeletePortfolioRequest) obj;
if (other.getAcceptLanguage() == null ^ this.getAcceptLanguage() == null)
return false;
if (other.getAcceptLanguage() != null && other.getAcceptLanguage().equals(this.getAcceptLanguage()) == false)
return false;
if (other.getId() == null ^ this.getId() == null)
return false;
if (other.getId() != null && other.getId().equals(this.getId()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAcceptLanguage() == null) ? 0 : getAcceptLanguage().hashCode());
hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode());
return hashCode;
}
@Override
public DeletePortfolioRequest clone() {
return (DeletePortfolioRequest) super.clone();
}
}
|
3e17cc90205723e494252edc2885d08298561bba | 1,127 | java | Java | 06-Multiplayer Client/Jetris/src/model/gameLogic/logicControllers/AutomaticTickController.java | Christian1984/FUN-mit-FOPT | c15dbcb7fa3bc29228f83eefe2b4422f8ae1003a | [
"MIT"
] | 1 | 2017-01-23T17:25:11.000Z | 2017-01-23T17:25:11.000Z | 08-Jetris with JavaFX/Jetris/src/model/gameLogic/logicControllers/AutomaticTickController.java | Christian1984/FUN-mit-FOPT | c15dbcb7fa3bc29228f83eefe2b4422f8ae1003a | [
"MIT"
] | null | null | null | 08-Jetris with JavaFX/Jetris/src/model/gameLogic/logicControllers/AutomaticTickController.java | Christian1984/FUN-mit-FOPT | c15dbcb7fa3bc29228f83eefe2b4422f8ae1003a | [
"MIT"
] | null | null | null | 24.5 | 102 | 0.613132 | 10,144 | package model.gameLogic.logicControllers;
import model.gameLogic.JetrisGame;
public class AutomaticTickController extends Thread {
private JetrisGame jetrisGame;
private long delay;
private boolean isRunning;
private double levelUpTimeScale;
public AutomaticTickController(JetrisGame jetrisGame, int initialDelay, double levelUpTimeScale) {
this.jetrisGame = jetrisGame;
this.delay = initialDelay;
this.isRunning = true;
this.levelUpTimeScale = levelUpTimeScale;
this.start();
}
@Override
public void run() {
while (isRunning) {
try {
sleep(delay);
JetrisEventDispatcher.tick(jetrisGame);
} catch (InterruptedException e) {
//e.printStackTrace();
}
}
}
public synchronized void stopTicker() {
isRunning = false;
interrupt();
}
public synchronized void resetTimer() {
interrupt();
}
public synchronized void levelUp() {
delay = (long) (delay * levelUpTimeScale);
interrupt();
}
}
|
3e17ccebbefe0a3a41c9995b942271f1f6b193dd | 2,574 | java | Java | src/main/java/com/google/devtools/build/lib/query2/engine/LetExpression.java | cloudpanda/bazel | 981b7bc1ce793a484f9a39178d57f9e24bfc487a | [
"Apache-2.0"
] | 2 | 2016-02-06T16:36:44.000Z | 2019-03-30T07:56:11.000Z | src/main/java/com/google/devtools/build/lib/query2/engine/LetExpression.java | shwenzhang/bazel | 03bad4619075aa77876698c55827aa54e7426ea9 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/google/devtools/build/lib/query2/engine/LetExpression.java | shwenzhang/bazel | 03bad4619075aa77876698c55827aa54e7426ea9 | [
"Apache-2.0"
] | 2 | 2016-02-06T16:36:46.000Z | 2018-12-06T07:41:36.000Z | 32.582278 | 98 | 0.716395 | 10,145 | // Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.query2.engine;
import java.util.Collection;
import java.util.Set;
import java.util.regex.Pattern;
/**
* A let expression.
*
* <pre>expr ::= LET WORD = expr IN expr</pre>
*/
class LetExpression extends QueryExpression {
private static final String VAR_NAME_PATTERN = "[a-zA-Z_][a-zA-Z0-9_]*$";
// Variables names may be any legal identifier in the C programming language
private static final Pattern NAME_PATTERN = Pattern.compile("^" + VAR_NAME_PATTERN);
// Variable references are prepended with the "$" character.
// A variable named "x" is referenced as "$x".
private static final Pattern REF_PATTERN = Pattern.compile("^\\$" + VAR_NAME_PATTERN);
static boolean isValidVarReference(String varName) {
return REF_PATTERN.matcher(varName).matches();
}
static String getNameFromReference(String reference) {
return reference.substring(1);
}
private final String varName;
private final QueryExpression varExpr;
private final QueryExpression bodyExpr;
LetExpression(String varName, QueryExpression varExpr, QueryExpression bodyExpr) {
this.varName = varName;
this.varExpr = varExpr;
this.bodyExpr = bodyExpr;
}
@Override
public <T> Set<T> eval(QueryEnvironment<T> env) throws QueryException {
if (!NAME_PATTERN.matcher(varName).matches()) {
throw new QueryException(this, "invalid variable name '" + varName + "' in let expression");
}
Set<T> varValue = varExpr.eval(env);
Set<T> prevValue = env.setVariable(varName, varValue);
try {
return bodyExpr.eval(env);
} finally {
env.setVariable(varName, prevValue); // restore
}
}
@Override
public void collectTargetPatterns(Collection<String> literals) {
varExpr.collectTargetPatterns(literals);
bodyExpr.collectTargetPatterns(literals);
}
@Override
public String toString() {
return "let " + varName + " = " + varExpr + " in " + bodyExpr;
}
}
|
3e17cd7d720653f79f246558ab76673bfec00725 | 1,771 | java | Java | gdx-fireapp-ios-moe/tests/pl/mk5/gdx/fireapp/ios/GdxIOSAppTest.java | jeffgamedev/gdx-fireapp | f08e1ed6e2e5251420bff3c1933fde3ca494dce9 | [
"Apache-2.0"
] | null | null | null | gdx-fireapp-ios-moe/tests/pl/mk5/gdx/fireapp/ios/GdxIOSAppTest.java | jeffgamedev/gdx-fireapp | f08e1ed6e2e5251420bff3c1933fde3ca494dce9 | [
"Apache-2.0"
] | null | null | null | gdx-fireapp-ios-moe/tests/pl/mk5/gdx/fireapp/ios/GdxIOSAppTest.java | jeffgamedev/gdx-fireapp | f08e1ed6e2e5251420bff3c1933fde3ca494dce9 | [
"Apache-2.0"
] | null | null | null | 31.070175 | 88 | 0.750423 | 10,146 | /*
* Copyright 2018 mk
*
* 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 pl.mk5.gdx.fireapp.ios;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.iosmoe.IOSApplication;
import com.badlogic.gdx.utils.Timer;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.moe.natj.general.NatJ;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import pl.mk5.gdx.fireapp.GdxFIRApp;
@RunWith(PowerMockRunner.class)
@PrepareForTest({NatJ.class, Timer.class})
public abstract class GdxIOSAppTest {
// @Rule
// public PowerMockRule powerMockRule = new PowerMockRule();
@BeforeClass
public static void before() {
GdxFIRApp.setAutoSubscribePromises(false);
}
@Before
public void setup() {
PowerMockito.mockStatic(NatJ.class);
IOSApplication application = Mockito.mock(IOSApplication.class);
Mockito.when(application.getType()).thenReturn(Application.ApplicationType.iOS);
Gdx.app = application;
GdxFIRApp.setThrowFailureByDefault(false);
}
}
|
3e17cdcb30aae2ecffc24c068f26123f16555994 | 1,249 | java | Java | test/framework/src/main/java/org/elasticsearch/transport/MockTcpTransportPlugin.java | nicomak/elasticsearch | 3f6a3c01dadb1951b597ffdbd068359a2fbc84c8 | [
"Apache-2.0"
] | null | null | null | test/framework/src/main/java/org/elasticsearch/transport/MockTcpTransportPlugin.java | nicomak/elasticsearch | 3f6a3c01dadb1951b597ffdbd068359a2fbc84c8 | [
"Apache-2.0"
] | null | null | null | test/framework/src/main/java/org/elasticsearch/transport/MockTcpTransportPlugin.java | nicomak/elasticsearch | 3f6a3c01dadb1951b597ffdbd068359a2fbc84c8 | [
"Apache-2.0"
] | null | null | null | 39.03125 | 82 | 0.775821 | 10,147 | /*
* 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.transport;
import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.plugins.Plugin;
public class MockTcpTransportPlugin extends Plugin {
public static final String MOCK_TCP_TRANSPORT_NAME = "mock-socket-network";
public void onModule(NetworkModule module) {
module.registerTransport(MOCK_TCP_TRANSPORT_NAME, MockTcpTransport.class);
}
}
|
3e17ce21ff63c922e0ef95b327645e675584c0d9 | 9,019 | java | Java | kie-wb-common-cli/kie-wb-common-cli-tools/kie-wb-common-cli-forms-migration/src/main/java/org/kie/workbench/common/forms/migration/tool/FormsMigrationTool.java | tkobayas/kie-wb-common | 2c69347f0f634268fb7cca77ccf9e1311f1486e9 | [
"Apache-2.0"
] | 34 | 2017-05-21T11:28:40.000Z | 2021-07-03T13:15:03.000Z | kie-wb-common-cli/kie-wb-common-cli-tools/kie-wb-common-cli-forms-migration/src/main/java/org/kie/workbench/common/forms/migration/tool/FormsMigrationTool.java | tkobayas/kie-wb-common | 2c69347f0f634268fb7cca77ccf9e1311f1486e9 | [
"Apache-2.0"
] | 2,576 | 2017-03-14T00:57:07.000Z | 2022-03-29T07:52:38.000Z | kie-wb-common-cli/kie-wb-common-cli-tools/kie-wb-common-cli-forms-migration/src/main/java/org/kie/workbench/common/forms/migration/tool/FormsMigrationTool.java | tkobayas/kie-wb-common | 2c69347f0f634268fb7cca77ccf9e1311f1486e9 | [
"Apache-2.0"
] | 158 | 2017-03-15T08:55:40.000Z | 2021-11-19T14:07:17.000Z | 43.781553 | 264 | 0.654285 | 10,148 | /*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.kie.workbench.common.forms.migration.tool;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.guvnor.common.services.project.model.WorkspaceProject;
import org.guvnor.common.services.project.service.WorkspaceProjectService;
import org.guvnor.structure.repositories.Repository;
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.kie.workbench.common.forms.migration.legacy.model.Form;
import org.kie.workbench.common.forms.migration.legacy.services.FormSerializationManager;
import org.kie.workbench.common.forms.migration.legacy.services.impl.FormSerializationManagerImpl;
import org.kie.workbench.common.forms.migration.tool.cdi.FormsMigrationServicesCDIWrapper;
import org.kie.workbench.common.forms.migration.tool.pipelines.MigrationContext;
import org.kie.workbench.common.forms.migration.tool.pipelines.MigrationPipeline;
import org.kie.workbench.common.forms.migration.tool.util.FormsMigrationConstants;
import org.kie.workbench.common.forms.model.FormDefinition;
import org.kie.workbench.common.migration.cli.MigrationConstants;
import org.kie.workbench.common.migration.cli.MigrationServicesCDIWrapper;
import org.kie.workbench.common.migration.cli.MigrationSetup;
import org.kie.workbench.common.migration.cli.MigrationTool;
import org.kie.workbench.common.migration.cli.SystemAccess;
import org.kie.workbench.common.migration.cli.ToolConfig;
import org.uberfire.backend.server.util.Paths;
import org.uberfire.io.IOService;
import org.uberfire.java.nio.IOException;
import org.uberfire.java.nio.file.FileVisitResult;
import org.uberfire.java.nio.file.Files;
import org.uberfire.java.nio.file.SimpleFileVisitor;
import org.uberfire.java.nio.file.attribute.BasicFileAttributes;
public class FormsMigrationTool implements MigrationTool {
private FormSerializationManager legacyFormSerializer = new FormSerializationManagerImpl();
private SystemAccess system;
private ToolConfig config;
private Path niogitDir;
private WeldContainer weldContainer;
private MigrationServicesCDIWrapper migrationServicesCDIWrapper;
private FormsMigrationServicesCDIWrapper formMigrationServicesCDIWrapper;
private MigrationPipeline pipeline;
@Override
public String getTitle() {
return "Forms migration";
}
@Override
public String getDescription() {
return "Moves old jBPM Form Modeler forms into the new Forms format.";
}
@Override
public Integer getPriority() {
return 2;
}
@Override
public boolean isSystemMigration() {
return false;
}
@Override
public void run(ToolConfig config, SystemAccess system) {
this.config = config;
this.system = system;
this.niogitDir = config.getTarget();
system.out().println("\nStarting Forms migration");
if (projectMigrationWasExecuted()) {
try {
MigrationSetup.configureProperties(system,
niogitDir);
weldContainer = new Weld().initialize();
migrationServicesCDIWrapper = weldContainer.instance().select(MigrationServicesCDIWrapper.class).get();
formMigrationServicesCDIWrapper = weldContainer.instance().select(FormsMigrationServicesCDIWrapper.class).get();
if (systemMigrationWasExecuted()) {
pipeline = new MigrationPipeline();
if (!config.isBatch()) {
system.out().println(pipeline.getAllInfo());
Collection<String> validResponses = Arrays.asList("yes",
"no");
String response;
do {
response = system.console().readLine("\nDo you want to continue? [yes/no]: ").toLowerCase();
} while (!validResponses.contains(response));
if ("no".equals(response)) {
return;
}
}
WorkspaceProjectService service = weldContainer.instance().select(WorkspaceProjectService.class).get();
service.getAllWorkspaceProjects().forEach(this::processWorkspaceProject);
}
} finally {
if (weldContainer != null) {
try {
migrationServicesCDIWrapper = null;
weldContainer.close();
} catch (Exception ex) {
}
}
}
}
}
private void processWorkspaceProject(WorkspaceProject workspaceProject) {
List<FormMigrationSummary> summaries = new ArrayList<>();
Files.walkFileTree(Paths.convert(workspaceProject.getRootPath()), new SimpleFileVisitor<org.uberfire.java.nio.file.Path>() {
@Override
public FileVisitResult visitFile(org.uberfire.java.nio.file.Path visitedPath, BasicFileAttributes attrs) throws IOException {
org.uberfire.backend.vfs.Path visitedVFSPath = Paths.convert(visitedPath);
String fileName = visitedVFSPath.getFileName();
File file = visitedPath.toFile();
if (file.isFile()) {
if (fileName.endsWith("." + FormsMigrationConstants.LEGACY_FOMRS_EXTENSION)) {
try {
Form legacyForm = legacyFormSerializer.loadFormFromXML(migrationServicesCDIWrapper.getIOService().readAllString(visitedPath));
FormMigrationSummary summary = new FormMigrationSummary(new Resource<>(legacyForm, visitedVFSPath));
// Trying to lookup new form with same name!
String newFormFileName = fileName.substring(0, fileName.lastIndexOf(".") - 1) + FormsMigrationConstants.NEW_FOMRS_EXTENSION;
org.uberfire.java.nio.file.Path newFormPath = visitedPath.getParent().resolve(newFormFileName);
if (migrationServicesCDIWrapper.getIOService().exists(newFormPath)) {
Resource<FormDefinition> newFormResource = new Resource<>(formMigrationServicesCDIWrapper.getFormDefinitionSerializer().deserialize(migrationServicesCDIWrapper.getIOService().readAllString(newFormPath)), Paths.convert(newFormPath));
summary.setNewFormResource(newFormResource);
}
summaries.add(summary);
} catch (Exception e) {
system.err().println("Error reading form: " + fileName + ":\n");
e.printStackTrace(system.err());
}
}
}
return FileVisitResult.CONTINUE;
}
});
system.console().format("\nProcessing module %s: %s forms found\n", workspaceProject.getName(), summaries.size());
if(summaries.size() > 0) {
MigrationContext context = new MigrationContext(workspaceProject, weldContainer, formMigrationServicesCDIWrapper, system, summaries, migrationServicesCDIWrapper);
pipeline.migrate(context);
}
}
private boolean projectMigrationWasExecuted() {
if (!config.getTarget().resolve("system").resolve(MigrationConstants.SYSTEM_GIT).toFile().exists()) {
system.err().println(String.format("The PROJECT STRUCTURE MIGRATION must be ran before this one."));
return false;
}
return true;
}
private boolean systemMigrationWasExecuted() {
final IOService systemIoService = migrationServicesCDIWrapper.getSystemIoService();
final Repository systemRepository = migrationServicesCDIWrapper.getSystemRepository();
if (!systemIoService.exists(systemIoService.get(systemRepository.getUri()).resolve("spaces"))) {
system.err().println(String.format("The SYSTEM CONFIGURATION DIRECTORY STRUCTURE MIGRATION must be ran before this one."));
return false;
}
return true;
}
}
|
3e17ce40d0019b2c1748d9b51773c306e44ef390 | 1,590 | java | Java | blur-util/src/main/java/org/apache/blur/trace/BaseTraceStorage.java | dibbhatt/incubator-blur | 09278b07daa78c5f206f73d2bbf3e6ed6177ba5f | [
"Apache-2.0"
] | 26 | 2015-01-04T12:16:30.000Z | 2017-12-05T14:55:26.000Z | blur-util/src/main/java/org/apache/blur/trace/BaseTraceStorage.java | dibbhatt/incubator-blur | 09278b07daa78c5f206f73d2bbf3e6ed6177ba5f | [
"Apache-2.0"
] | 1 | 2015-04-10T13:23:29.000Z | 2015-04-10T13:23:29.000Z | blur-util/src/main/java/org/apache/blur/trace/BaseTraceStorage.java | dibbhatt/incubator-blur | 09278b07daa78c5f206f73d2bbf3e6ed6177ba5f | [
"Apache-2.0"
] | 31 | 2015-02-09T06:38:13.000Z | 2018-08-16T00:59:21.000Z | 30.576923 | 75 | 0.757233 | 10,149 | /**
* 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.blur.trace;
import java.util.List;
import org.apache.blur.BlurConfiguration;
public abstract class BaseTraceStorage extends TraceStorage {
private static final String NOT_SUPPORTED = "Not Supported";
public BaseTraceStorage(BlurConfiguration configuration) {
super(configuration);
}
@Override
public List<String> getTraceIds() {
throw new RuntimeException(NOT_SUPPORTED);
}
@Override
public List<String> getRequestIds(String traceId) {
throw new RuntimeException(NOT_SUPPORTED);
}
@Override
public String getRequestContentsJson(String traceId, String requestId) {
throw new RuntimeException(NOT_SUPPORTED);
}
@Override
public void removeTrace(String traceId) {
throw new RuntimeException(NOT_SUPPORTED);
}
}
|
3e17ce52d17bd765fe6983504fb984c5dec7f4d4 | 4,883 | java | Java | src/main/java/net/reallifegames/localauth/api/v2/users/get/UserGetController.java | agent6262/local-auth | 4eeb72329c1a4b8e4fbe3807f2bd16fe11308747 | [
"MIT"
] | null | null | null | src/main/java/net/reallifegames/localauth/api/v2/users/get/UserGetController.java | agent6262/local-auth | 4eeb72329c1a4b8e4fbe3807f2bd16fe11308747 | [
"MIT"
] | 1 | 2021-08-29T21:08:31.000Z | 2021-08-29T21:08:31.000Z | src/main/java/net/reallifegames/localauth/api/v2/users/get/UserGetController.java | agent6262/local-auth | 4eeb72329c1a4b8e4fbe3807f2bd16fe11308747 | [
"MIT"
] | 1 | 2020-05-10T00:21:00.000Z | 2020-05-10T00:21:00.000Z | 41.735043 | 132 | 0.695884 | 10,150 | /*
* The MIT License (MIT)
*
* Copyright (c) 2019 - Present, Tyler Bucher
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.reallifegames.localauth.api.v2.users.get;
import io.javalin.http.Context;
import net.reallifegames.localauth.LocalAuth;
import net.reallifegames.localauth.MongoDbModule;
import net.reallifegames.localauth.Permissions;
import net.reallifegames.localauth.SecurityModule;
import net.reallifegames.localauth.api.v1.ApiController;
import net.reallifegames.localauth.models.UserModel;
import javax.annotation.Nonnull;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Attempts to return the list of users in this application.
*
* @author Tyler Bucher
*/
public class UserGetController {
/**
* Default list of permissions for this endpoint.
*/
private static final List<Integer> PERMISSIONS = Arrays.asList(
Permissions.IS_USER_SUPER_ADMIN.value,
Permissions.IS_USER_ADMIN.value,
Permissions.CAN_USER_MOD_USERS.value,
Permissions.CAN_USER_DELETE_USERS.value
);
/**
* Returns a user based on the post data or a list of users.
*
* @param context the REST request context to modify.
*/
public static void getUsers(@Nonnull final Context context) throws Exception {
getUsers(context, LocalAuth.getDbModule(), LocalAuth.getSecurityModule());
}
/**
* Returns a user based on the post data or a list of users.
*
* @param context the REST request context to modify.
* @param dbModule the module instance to use.
* @param securityModule the module instance to use.
*/
public static void getUsers(@Nonnull final Context context,
@Nonnull final MongoDbModule dbModule,
@Nonnull final SecurityModule securityModule) throws Exception {
final UserModel authUserModel = ApiController.beforeApiAuthentication(context, dbModule, securityModule, new ArrayList<>());
final String[] path = context.path().split("/");
if (authUserModel.hasPermission(PERMISSIONS) && path.length == 5) {
final String pathVal = URLDecoder.decode(path[4], StandardCharsets.UTF_8);
if(pathVal.equals("*")) {
ApiController.jsonContextResponse(new UserGetRequest(convertUserModelList(dbModule.getAllUserModels())), context);
} else {
final UserModel userModel = dbModule.getUserModelByEmail(pathVal);
if (userModel != null) {
ApiController.jsonContextResponse(new UserGetRequest(convertUserModelList(userModel)), context);
} else {
context.status(400);
context.result("Bad Request");
}
}
} else {
ApiController.jsonContextResponse(new UserGetRequest(convertUserModelList(authUserModel)), context);
}
}
/**
* @param userModels the list to be converted.
* @return the new converted SafeUserModel list.
*/
private static List<SafeUserModel> convertUserModelList(@Nonnull final List<UserModel> userModels) {
final List<SafeUserModel> safeUserModels = new ArrayList<>();
userModels.forEach(userModel->safeUserModels.add(SafeUserModel.fromUserModel(userModel)));
return safeUserModels;
}
/**
* @param userModel the UserModel to be converted.
* @return the new converted SafeUserModel.
*/
@Nonnull
private static List<SafeUserModel> convertUserModelList(@Nonnull final UserModel userModel) {
return Collections.singletonList(SafeUserModel.fromUserModel(userModel));
}
}
|
3e17cf5b26e039aa45074df90473aec63aab9deb | 1,173 | java | Java | src/main/java/net/amitoj/minecraftUtilities/structures/PollManager.java | amitojsingh366/minecraft-server-utilities | fe26f2bfe1dee7d242f2e6903dad25e0e252252d | [
"MIT"
] | null | null | null | src/main/java/net/amitoj/minecraftUtilities/structures/PollManager.java | amitojsingh366/minecraft-server-utilities | fe26f2bfe1dee7d242f2e6903dad25e0e252252d | [
"MIT"
] | null | null | null | src/main/java/net/amitoj/minecraftUtilities/structures/PollManager.java | amitojsingh366/minecraft-server-utilities | fe26f2bfe1dee7d242f2e6903dad25e0e252252d | [
"MIT"
] | null | null | null | 26.066667 | 69 | 0.595908 | 10,151 | package net.amitoj.minecraftUtilities.structures;
import net.amitoj.minecraftUtilities.MinecraftUtilities;
import net.dv8tion.jda.api.interactions.Interaction;
import java.util.*;
public class PollManager {
private MinecraftUtilities _plugin;
public Map<UUID, Poll> polls = new HashMap<UUID, Poll>();
public PollManager(MinecraftUtilities plugin) {
this._plugin = plugin;
}
public Poll createPoll(PollType type, String username) {
Poll poll = new Poll(this, _plugin, type, username);
polls.put(poll.uuid, poll);
this.scheduleExpiration(this, poll);
return poll;
}
public void expirePoll(Poll poll) {
poll.onExpire();
polls.remove(poll.uuid);
}
private void scheduleExpiration(PollManager manager, Poll poll) {
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
manager.expirePoll(poll);
}
},
300000
);
}
public Poll getPoll(UUID uuid) {
return polls.get(uuid);
}
}
|
3e17cfd1b53970017bb9a74f43841bc1f71c882e | 1,862 | java | Java | core/src/main/java/org/sing_group/compi/core/loops/CommandLoopValuesGenerator.java | sing-group/compi | f6364f54bdca8a95e143dc018364904b2e4a1883 | [
"Apache-2.0"
] | 5 | 2019-06-25T20:48:10.000Z | 2021-07-18T22:12:01.000Z | core/src/main/java/org/sing_group/compi/core/loops/CommandLoopValuesGenerator.java | sing-group/compi | f6364f54bdca8a95e143dc018364904b2e4a1883 | [
"Apache-2.0"
] | 1 | 2021-08-02T17:18:54.000Z | 2021-08-02T17:18:54.000Z | core/src/main/java/org/sing_group/compi/core/loops/CommandLoopValuesGenerator.java | sing-group/compi | f6364f54bdca8a95e143dc018364904b2e4a1883 | [
"Apache-2.0"
] | null | null | null | 29.555556 | 81 | 0.6971 | 10,152 | /*-
* #%L
* Compi Core
* %%
* Copyright (C) 2016 - 2018 Daniel Glez-Peña, Osvaldo Graña-Castro, Hugo
* López-Fernández, Jesús Álvarez Casanova
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.sing_group.compi.core.loops;
import static org.sing_group.compi.core.runner.ProcessCreator.createShellCommand;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.sing_group.compi.core.pipeline.Foreach;
import org.sing_group.compi.core.resolver.VariableResolver;
public class CommandLoopValuesGenerator extends AbstractLoopValuesGenerator {
public CommandLoopValuesGenerator(VariableResolver resolver, Foreach foreach) {
super(resolver, foreach);
}
@Override
public List<String> getValuesFromResolvedSource(String source) {
final List<String> values = new ArrayList<>();
try {
Process p = new ProcessBuilder(createShellCommand(source)).start();
Thread t = new Thread(() -> {
try (Scanner sc = new Scanner(p.getInputStream())) {
while (sc.hasNextLine()) {
values.add(sc.nextLine());
}
}
});
t.start();
p.waitFor();
t.join();
return values;
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}
}
|
3e17d09f045a9e15e2fbc6a2ea2a9201d695be8f | 4,900 | java | Java | microservicio/dominio/src/main/java/com/ceiba/prestamo/servicio/ServicioCrearPrestamo.java | oscarCeiba/PrestamoComputos | 378c1ce1a30d989c975b5d661b06033c30fa73cc | [
"Apache-2.0"
] | null | null | null | microservicio/dominio/src/main/java/com/ceiba/prestamo/servicio/ServicioCrearPrestamo.java | oscarCeiba/PrestamoComputos | 378c1ce1a30d989c975b5d661b06033c30fa73cc | [
"Apache-2.0"
] | null | null | null | microservicio/dominio/src/main/java/com/ceiba/prestamo/servicio/ServicioCrearPrestamo.java | oscarCeiba/PrestamoComputos | 378c1ce1a30d989c975b5d661b06033c30fa73cc | [
"Apache-2.0"
] | null | null | null | 47.115385 | 119 | 0.742245 | 10,153 | package com.ceiba.prestamo.servicio;
import com.ceiba.dominio.excepcion.ExcepcionValorInvalido;
import com.ceiba.prestamo.modelo.dto.DtoPrestamo;
import com.ceiba.prestamo.modelo.entidad.Prestamo;
import com.ceiba.prestamo.puerto.dao.DaoPrestamo;
import com.ceiba.prestamo.puerto.repositorio.RepositorioPrestamo;
import com.ceiba.suspension.modelo.dto.DtoSuspension;
import com.ceiba.suspension.puerto.dao.DaoSuspension;
import com.ceiba.suspension.puerto.repositorio.RepositorioSuspension;
import com.ceiba.usuario.puerto.repositorio.RepositorioUsuario;
import java.time.LocalDate;
import static com.ceiba.dominio.ValidadorArgumento.*;
import static com.ceiba.prestamo.modelo.enums.EnumEstadoSolicitud.*;
import static com.ceiba.prestamo.modelo.enums.EnumRolUsuario.*;
public class ServicioCrearPrestamo {
private static final String EL_USUARIO_NO_EXISTE_EN_EL_SISTEMA = "El usuario no existe en el sistema";
private static final String EL_USUARIO_TIENE_SOLICITUD_ACTIVA = "El usuario tiene una solicitud activa";
private static final String EL_USUARIO_TIENE_SOLICITUD_SUSPENDIDA = "El usuario tiene una solicitud suspendida" +
" hasta la fecha: ";
private static final String EL_USUARIO_TIENE_ROL_NO_PERMITIDO = "El usuario tiene un rol " +
"diferente al permitido para la solicitud";
private static final String LA_SOLICITUD_CREADA_TIENE_FECHA_DE_ENTREGA = "La solicitud fue realizada con exito, " +
"la fecha maxima de entrega es: ";
private final RepositorioPrestamo repositorioPrestamo;
private final RepositorioUsuario repositorioUsuario;
private final RepositorioSuspension repositorioSuspension;
private final DaoPrestamo daoPrestamo;
private final DaoSuspension daoSuspension;
public ServicioCrearPrestamo(RepositorioPrestamo repositorioPrestamo, RepositorioUsuario repositorioUsuario,
DaoPrestamo daoPrestamo, DaoSuspension daoSuspension,
RepositorioSuspension repositorioSuspension) {
this.repositorioPrestamo = repositorioPrestamo;
this.repositorioUsuario = repositorioUsuario;
this.daoPrestamo = daoPrestamo;
this.daoSuspension = daoSuspension;
this.repositorioSuspension = repositorioSuspension;
}
public String ejecutar(Prestamo prestamo) {
validarExistenciaUsuarioSolicitud(prestamo);
validarSolicitudPrestamoExistenteEstado(prestamo);
int rol = obtenerRolUsuario(prestamo);
Prestamo prestamoCrear = new Prestamo(prestamo.getId(), prestamo.getCedula(), prestamo.getEquipoComputo(),
prestamo.getFechaCreacion(),calcularFechaEntregaPorRol(prestamo,rol),ACTIVO.ordinal());
this.repositorioPrestamo.crear(prestamoCrear);
return LA_SOLICITUD_CREADA_TIENE_FECHA_DE_ENTREGA + prestamoCrear.getFechaEntrega();
}
private void validarExistenciaUsuarioSolicitud(Prestamo prestamo) {
boolean existe = this.repositorioUsuario.existe(prestamo.getCedula());
if(!existe) {
throw new ExcepcionValorInvalido(EL_USUARIO_NO_EXISTE_EN_EL_SISTEMA);
}
}
private void validarSolicitudPrestamoExistenteEstado(Prestamo prestamo){
boolean existe = this.repositorioPrestamo.existe(prestamo.getCedula());
if(existe){
validarSolicitudPrestamoEstado(prestamo);
}
}
private void validarSolicitudPrestamoEstado(Prestamo prestamo){
DtoPrestamo prestamoEstado = this.daoPrestamo.solicitudCreada(prestamo.getCedula());
if(prestamoEstado.getEstado() == ACTIVO.ordinal()){
throw new ExcepcionValorInvalido(EL_USUARIO_TIENE_SOLICITUD_ACTIVA);
}else{
validarSuspension(prestamoEstado);
}
}
private void validarSuspension(DtoPrestamo prestamo){
DtoSuspension suspension = this.daoSuspension.solicitudCreada(prestamo.getCedula());
validarMenor(suspension.getFechaFinSuspension(), LocalDate.now(),EL_USUARIO_TIENE_SOLICITUD_SUSPENDIDA +
suspension.getFechaFinSuspension());
this.repositorioPrestamo.actualizarEstado(prestamo.getId(), INACTIVO.ordinal());
this.repositorioSuspension.eliminar(suspension.getId());
}
private int obtenerRolUsuario(Prestamo prestamo){
return this.repositorioUsuario.rolUsuario(prestamo.getCedula());
}
private LocalDate calcularFechaEntregaPorRol(Prestamo prestamo,int rol){
LocalDate fechaEntrega = null;
if(rol == ESTUDIANTES.getRol()){
fechaEntrega = sumaFecha(10,prestamo.getFechaCreacion());
}else if(rol == ADMINISTRATIVOS.getRol()){
fechaEntrega = sumaFecha(15,prestamo.getFechaCreacion());
}else{
throw new ExcepcionValorInvalido(EL_USUARIO_TIENE_ROL_NO_PERMITIDO);
}
return fechaEntrega;
}
}
|
3e17d0f6c33f6fde7a727c4f79558eafd1ae4c1f | 1,907 | java | Java | alligator/src/main/java/me/aartikov/alligator/destinations/FragmentDestination.java | aartikov/Alligator | f685301fded4e2fe8095498fd3b1ec12d2c63ef9 | [
"MIT"
] | 319 | 2017-02-18T15:24:13.000Z | 2022-03-11T14:08:12.000Z | alligator/src/main/java/me/aartikov/alligator/destinations/FragmentDestination.java | aartikov/Alligator | f685301fded4e2fe8095498fd3b1ec12d2c63ef9 | [
"MIT"
] | 27 | 2017-07-06T12:00:33.000Z | 2021-04-20T09:46:52.000Z | alligator/src/main/java/me/aartikov/alligator/destinations/FragmentDestination.java | aartikov/Alligator | f685301fded4e2fe8095498fd3b1ec12d2c63ef9 | [
"MIT"
] | 24 | 2017-06-26T03:54:49.000Z | 2021-12-26T14:31:18.000Z | 35.314815 | 140 | 0.79549 | 10,154 | package me.aartikov.alligator.destinations;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import me.aartikov.alligator.Screen;
import me.aartikov.alligator.ScreenResult;
import me.aartikov.alligator.converters.FragmentConverter;
import me.aartikov.alligator.helpers.ScreenClassHelper;
public class FragmentDestination implements Destination {
private Class<? extends Screen> mScreenClass;
private FragmentConverter<? extends Screen> mFragmentConverter;
@Nullable
private Class<? extends ScreenResult> mScreenResultClass;
private ScreenClassHelper mScreenClassHelper;
public FragmentDestination(@NonNull Class<? extends Screen> screenClass,
@NonNull FragmentConverter<? extends Screen> fragmentConverter,
@Nullable Class<? extends ScreenResult> screenResultClass,
@NonNull ScreenClassHelper screenClassHelper) {
mScreenClass = screenClass;
mFragmentConverter = fragmentConverter;
mScreenResultClass = screenResultClass;
mScreenClassHelper = screenClassHelper;
}
@SuppressWarnings("unchecked")
@NonNull
public Fragment createFragment(@NonNull Screen screen) {
checkScreenClass(screen.getClass());
Fragment fragment = ((FragmentConverter<Screen>) mFragmentConverter).createFragment(screen);
mScreenClassHelper.putScreenClass(fragment, screen.getClass());
return fragment;
}
@NonNull
public Screen getScreen(@NonNull Fragment fragment) {
return mFragmentConverter.getScreen(fragment);
}
@Nullable
public Class<? extends ScreenResult> getScreenResultClass() {
return mScreenResultClass;
}
private void checkScreenClass(@NonNull Class<? extends Screen> screenClass) {
if (!mScreenClass.isAssignableFrom(screenClass)) {
throw new IllegalArgumentException("Invalid screen class " + screenClass.getSimpleName() + ". Expected " + mScreenClass.getSimpleName());
}
}
} |
3e17d1882be677e6c4367ba32e47b1a6227285f1 | 116 | java | Java | app/src/main/java/com/example/videoapp/listener/OnItemClickListener.java | king0730/VideoApp | 82756e375663a977dfdcd9586b0c42f075edf8b2 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/videoapp/listener/OnItemClickListener.java | king0730/VideoApp | 82756e375663a977dfdcd9586b0c42f075edf8b2 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/videoapp/listener/OnItemClickListener.java | king0730/VideoApp | 82756e375663a977dfdcd9586b0c42f075edf8b2 | [
"Apache-2.0"
] | null | null | null | 23.2 | 38 | 0.801724 | 10,155 | package com.example.videoapp.listener;
public interface OnItemClickListener {
void onItemClick(int position);
} |
3e17d1d71eda7ca02af90da3574aae28b9627c3b | 12,250 | java | Java | src/ic/ce/base/Ambiente.java | victorlima02/IC | b95bcee02668b2c5e7ee3c757ad9c51a39234eb1 | [
"MIT"
] | null | null | null | src/ic/ce/base/Ambiente.java | victorlima02/IC | b95bcee02668b2c5e7ee3c757ad9c51a39234eb1 | [
"MIT"
] | null | null | null | src/ic/ce/base/Ambiente.java | victorlima02/IC | b95bcee02668b2c5e7ee3c757ad9c51a39234eb1 | [
"MIT"
] | null | null | null | 32.841823 | 119 | 0.608 | 10,156 | /*
* The MIT License
*
* Copyright 2014 Victor de Lima Soares.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* @author Victor de Lima Soares
* @version 1.0
*/
package ic.ce.base;
import ic.ce.base.Ser;
import java.util.Collection;
import java.util.Comparator;
/**
* <p>
* Abstração do conceito de ambiente em seu sentido biológico, aplicado a
* problemas de CE.
* </p>
* <p>
* Sendo dessa forma, uma entidade avaliadora para uma população/ser, que quando
* sujeita aos vários fenômenos ambientais, evoluirá no tempo.
* </p>
* <p>
* Um ambiente conterá mecanismos que permitirão uma população a evoluir em
* acordo com as pressões evolutivas impostas, implementadas na forma de métodos
* em classes mais especializadas – Operadores- que a utilizaram para avaliar
* soluções geradas.
* </p>
* <p>
* De forma generalizada, derivações de <code>Ambiente</code> avaliarão
* indivíduos em uma População, parametrizando seu percurso evolucionário ao
* atribuir um grau de adaptação a cada um e provendo objetos da classe
* <code>Comparator</code>, capazes de comprar seres em uma ordem crescente ou
* decrescente em relação ao grau de adaptação.
* </p>
* <h3>Observação sobre populações:</h3>
* <p>
* A classe foi implementada como genérica para garantir a existência de seres
* (instâncias de classes derivadas de <code>Ser</code>) de um único tipo; uma
* única classe, e suas derivadas, serão usadas em uma população. Deste modo,
* interpreta-se que seres de uma única espécie, e suas subespécies, conviverão
* em uma população.
* </p>
*
* <h3>Suposições básicas:</h3>
* <ul>
* <li>Seres de uma população pertencem a uma única família de classes derivadas
* hierarquicamente de <code>Ser</code>; mantendo, portanto, a característica de
* espécie.</li>
* <li>Uma população não pode se auto avaliar, bem como seus indivíduos. Uma vez
* que indivíduos terão um grau de adaptação variado, flutuante, em função do
* ambiente em que se encontrarão. </li>
* </ul>
*
* <h3>Responsabilidades:</h3>
* <ul>
* <li>Avaliar seres;</li>
* <li>Avaliar populações(ou coleções de seres);</li>
* <li>Comparar seres em relação ao grau de adaptação.</li>
* </ul>
*
*
* @author Victor de Lima Soares
* @version 1.0
*
* @param <G> Classe do retorno da função objetivo (Grau de adaptação):
* AtomicInteger, AtomicLong, BigDecimal, BigInteger, Byte, Double, Float,
* Integer, Long, Short.
* @param <S> Classe dos Seres.
*
* @see Ser
* @see Populacao
*/
public abstract class Ambiente<G extends Number & Comparable<G>, S extends Ser<G>> implements Comparator<S> {
private final Modo modo;
private final Comparator<S> comparador;
private final Comparator<G> comparadorGraus;
private final Comparator<S> comparadorInverso;
/**
* Construtor padrão: modo Maximização.
*
* @since 1.0
*/
public Ambiente() {
modo = Modo.MAXIMIZACAO;
comparador = (S ser1, S ser2) -> compara(ser1, ser2);
comparadorGraus = (G grau1, G grau2) -> compara(grau1, grau2);
comparadorInverso = (S ser1, S ser2) -> compara(ser2, ser1);
}
/**
* Construtor com definição do modo.
*
* @since 1.0
* @param modo Modo de comparação: Maximixação/Minimização.
*/
public Ambiente(Modo modo) {
this.modo = modo;
switch (modo) {
case MINIMIZACAO:
comparador = (S ser1, S ser2) -> compara(ser2, ser1);
comparadorGraus = (G grau1, G grau2) -> compara(grau2, grau1);
comparadorInverso = (S ser1, S ser2) -> compara(ser1, ser2);
break;
case MAXIMIZACAO:
default:
comparador = (S ser1, S ser2) -> compara(ser1, ser2);
comparadorGraus = (G grau1, G grau2) -> compara(grau1, grau2);
comparadorInverso = (S ser1, S ser2) -> compara(ser2, ser1);
}
}
/**
* Defini o modo de comparação entre os seres.
*
* <p>
* Pelo modo, o ambiente será capaz de identificar a ordem correta dos seres
* ao compará-los.</p>
* <p>
* Para problemas de minimização, um ser com menor “grau de adaptação” será
* melhor e posto após os com maiores graus – em uma ordem crescente.
* Contudo, para maximização (modo padrão), seres com graus maiores serão
* considerados melhores e quando ordenados viram após os com menores graus.
* </p>
*
*/
public enum Modo {
MAXIMIZACAO, MINIMIZACAO
};
/**
* Função de Fitness: Avalia um ser, retornando o grau de adaptação.
*
* <p>
* Atua como função objetivo em algoritmos de otimização e permite que seres
* sejam classificados em função do seu grau de adaptação, nesse ambiente.
* </p>
*
* <p>
* Essa função realiza o cálculo do grau de adaptação, sem persisti-lo no
* ser. Para realizar a avaliação e gravação utilize:<br>
* {@link Ser#setGrauDeAdaptacao(ic.populacional.Ambiente) } <br>
* ou, para coleções:<br> {@link #avalia(java.util.Collection) }
* </p>
*
* @since 1.0
* @param individuo Ser a ser avaliado.
* @return Grau de adaptação.
*
* @see Ser#setGrauDeAdaptacao(ic.populacional.Ambiente)
* @see #avalia(java.util.Collection)
*
*/
public abstract G avalia(S individuo);
/**
* Avalia uma coleção de seres.
*
* <p>
* Avalia uma coleção de seres pela chamada repetitiva de {@link #avalia(ic.populacional.Ser)
* }.
* </p>
* <p>
* Por questões de desempenho, considera-se que {@link #avalia(ic.populacional.Ser)
* } constitua-se de uma função cujo tempo computacional para execução seja
* elevado. Portanto, a coleção é usada para a geração de uma stream
* paralelizada, onde múltiplas threads são criadas para avaliar os seres
* individualmente.
* </p>
*
* <p>
* Essa função atribui a cada ser na coleção um grau de adaptação por meio
* da função: {@link Ser#setGrauDeAdaptacao(ic.populacional.Ambiente) }
* </p>
*
* @since 1.0
* @param seres Coleção a ser avaliada.
*
* @see #avalia(ic.populacional.Ser)
* @see Ser#setGrauDeAdaptacao(ic.populacional.Ambiente)
*/
public final void avalia(Collection<? extends S> seres) {
seres.parallelStream().filter(ser -> !ser.isAvaliadoPor(this)).forEach((ser) -> ser.setGrauDeAdaptacao(this));
}
/**
* Compara seres: na ordem crescente.
*
* <p>
* Compara dois seres, possibilitando sua ordenação quanto a adaptação.
* </p>
* <p>
* Em caso de empate, a ordem é determinada pelo ID do ser.
* </p>
*
* @since 1.0
* @param ser1 Ser a ser comparado pelo ambiente.
* @param ser2 Segundo Ser a ser comparado pelo ambiente.
*
* @return <ul>
* <li>Positivo se ser1 for melhor adptado.</li>
* <li>Negativo se ser2 for melhor adptado.</li>
* <li>0 se forem a mesma instância.</li>
* </ul>
*
* @see Comparable#compareTo(java.lang.Object)
*/
@Override
public final int compare(S ser1, S ser2) {
return comparador.compare(ser1, ser2);
}
/**
* Compara graus de adaptação: na ordem crescente.
*
* <p>
* Compara graus de adaptação.
* </p>
*
* @since 1.0
* @param grau1 Grau a ser comparado.
* @param grau2 Segundo grau comparado pelo ambiente.
*
* @return <ul>
* <li>Positivo se grau1 for melhor.</li>
* <li>Negativo se grau2 for melhor.</li>
* <li>0 se forem iguais.</li>
* </ul>
*
* @see Comparable#compareTo(java.lang.Object)
*/
public final int compare(G grau1, G grau2) {
return comparadorGraus.compare(grau1, grau2);
}
/**
* Compara seres: na ordem crescente.
*
* <p>
* Compara dois seres, possibilitando sua ordenação quanto a adaptação.
* </p>
* <p>
* Em caso de empate, a ordem é determinada pelo ID do ser.
* </p>
*
* @since 1.0
* @param ser1 Ser a ser comparado pelo ambiente.
* @param ser2 Segundo Ser a ser comparado pelo ambiente.
*
* @return <ul>
* <li>Positivo se ser1 for melhor adptado.</li>
* <li>Negativo se ser2 for melhor adptado.</li>
* <li>0 se forem a mesma instância(compatível com {@link Ser#equals(java.lang.Object) }).</li>
* </ul>
*
* @see Comparable#compareTo(java.lang.Object)
*/
private int compara(S ser1, S ser2) {
G grau1 = (ser1.isAvaliadoPor(this)) ? ser1.getGrauDeAdaptacao() : this.avalia(ser1);
G grau2 = (ser2.isAvaliadoPor(this)) ? ser2.getGrauDeAdaptacao() : this.avalia(ser2);
Integer comparacao = grau1.compareTo(grau2);
if (comparacao == 0) {
if (ser1 == ser2) {
return 0;
} else {
return ser1.getId().compareTo(ser2.getId());
}
}
return comparacao;
}
/**
* Compara graus de adaptação: na ordem crescente.
*
* <p>
* Compara graus de adaptação.
* </p>
*
* @since 1.0
* @param grau1 Grau a ser comparado.
* @param grau2 Segundo grau comparado pelo ambiente.
*
* @return <ul>
* <li>Positivo se grau1 for melhor.</li>
* <li>Negativo se grau2 for melhor.</li>
* <li>0 se forem iguais.</li>
* </ul>
*
* @see Comparable#compareTo(java.lang.Object)
*/
private int compara(G grau1, G grau2) {
return grau1.compareTo(grau2);
}
/**
* Acesso ao modo de comparação.
*
* @since 1.0
* @return Modo de comparação.
*/
public final Modo getModo() {
return modo;
}
/**
* Retorna um comparador de seres para a ordem invertida quanto ao grau de
* adaptação.
*
* @since 1.0
* @return Comparator para ordem invertida.
*
*/
public final Comparator<S> getComparadorInverso() {
return comparadorInverso;
}
/**
* Acesso ao comparador usado pela classe.
*
* <p>
* Esse comparador é o mesmo usado pelos métodos de comparação no ambiente,
* gerado na sua instanciação de acordo com o modo.
* </p>
*
* @return Comparador de seres.
*/
public final Comparator<S> getComparador() {
return comparador;
}
/**
* Acesso ao comparador de graus usado pela classe.
*
* <p>
* Esse comparador é o mesmo usado pelos métodos de comparação no ambiente,
* gerado na sua instanciação de acordo com o modo.
* </p>
*
* @since 1.0
* @return Comparador de graus.
*/
public final Comparator<G> getComparadorGraus() {
return comparadorGraus;
}
}
|
3e17d1d8cb732424ee3231af9fbe0b83e732d603 | 9,176 | java | Java | systests/qpid-systests-jms_1.1/src/test/java/org/apache/qpid/systests/jms_1_1/extensions/connectionlimit/MessagingConnectionLimitTest.java | mklaca/qpid-broker-j | 886486962147e4bbecf41a8a280026c580ce4644 | [
"Apache-2.0"
] | 52 | 2017-12-15T08:49:31.000Z | 2022-03-10T19:10:11.000Z | systests/qpid-systests-jms_1.1/src/test/java/org/apache/qpid/systests/jms_1_1/extensions/connectionlimit/MessagingConnectionLimitTest.java | mklaca/qpid-broker-j | 886486962147e4bbecf41a8a280026c580ce4644 | [
"Apache-2.0"
] | 42 | 2017-10-18T12:36:17.000Z | 2022-02-05T13:55:18.000Z | systests/qpid-systests-jms_1.1/src/test/java/org/apache/qpid/systests/jms_1_1/extensions/connectionlimit/MessagingConnectionLimitTest.java | mklaca/qpid-broker-j | 886486962147e4bbecf41a8a280026c580ce4644 | [
"Apache-2.0"
] | 46 | 2017-09-12T10:26:06.000Z | 2022-03-21T07:52:46.000Z | 28.408669 | 115 | 0.570837 | 10,157 | /*
* 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.qpid.systests.jms_1_1.extensions.connectionlimit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.naming.NamingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.apache.qpid.server.user.connection.limits.plugins.ConnectionLimitRule;
import org.apache.qpid.systests.JmsTestBase;
import static org.junit.Assert.fail;
public class MessagingConnectionLimitTest extends JmsTestBase
{
private static final String USER = "admin";
private static final String USER_SECRET = "admin";
private static final String RULE_BASED_VIRTUAL_HOST_USER_CONNECTION_LIMIT_PROVIDER =
"org.apache.qpid.RuleBasedVirtualHostConnectionLimitProvider";
private static final String FREQUENCY_PERIOD = "frequencyPeriod";
private static final String RULES = "rules";
@Test
public void testAuthorizationWithConnectionLimit() throws Exception
{
final int connectionLimit = 2;
configureCLT(new ConnectionLimitRule()
{
@Override
public String getPort()
{
return null;
}
@Override
public String getIdentity()
{
return USER;
}
@Override
public Boolean getBlocked()
{
return Boolean.FALSE;
}
@Override
public Integer getCountLimit()
{
return connectionLimit;
}
@Override
public Integer getFrequencyLimit()
{
return null;
}
@Override
public Long getFrequencyPeriod()
{
return null;
}
});
final List<Connection> establishedConnections = new ArrayList<>();
try
{
establishConnections(connectionLimit, establishedConnections);
verifyConnectionEstablishmentFails(connectionLimit);
establishedConnections.remove(0).close();
establishConnection(establishedConnections, connectionLimit);
}
finally
{
closeConnections(establishedConnections);
}
}
@Test
public void testAuthorizationWithConnectionFrequencyLimit() throws Exception
{
final int connectionFrequencyLimit = 1;
configureCLT(new ConnectionLimitRule()
{
@Override
public String getPort()
{
return null;
}
@Override
public String getIdentity()
{
return USER;
}
@Override
public Boolean getBlocked()
{
return Boolean.FALSE;
}
@Override
public Integer getCountLimit()
{
return null;
}
@Override
public Integer getFrequencyLimit()
{
return connectionFrequencyLimit;
}
@Override
public Long getFrequencyPeriod()
{
return 60L * 1000L;
}
});
final List<Connection> establishedConnections = new ArrayList<>();
try
{
establishConnections(connectionFrequencyLimit, establishedConnections);
verifyConnectionEstablishmentFails(connectionFrequencyLimit);
establishedConnections.remove(0).close();
verifyConnectionEstablishmentFails(connectionFrequencyLimit);
}
finally
{
closeConnections(establishedConnections);
}
}
@Test
public void testAuthorizationWithConnectionLimitAndFrequencyLimit() throws Exception
{
final int connectionFrequencyLimit = 2;
final int connectionLimit = 3;
configureCLT(new ConnectionLimitRule()
{
@Override
public String getPort()
{
return null;
}
@Override
public String getIdentity()
{
return USER;
}
@Override
public Boolean getBlocked()
{
return Boolean.FALSE;
}
@Override
public Integer getCountLimit()
{
return connectionLimit;
}
@Override
public Integer getFrequencyLimit()
{
return connectionFrequencyLimit;
}
@Override
public Long getFrequencyPeriod()
{
return 60L * 1000L;
}
});
final List<Connection> establishedConnections = new ArrayList<>();
try
{
establishConnections(connectionFrequencyLimit, establishedConnections);
verifyConnectionEstablishmentFails(connectionFrequencyLimit);
establishedConnections.remove(0).close();
verifyConnectionEstablishmentFails(connectionFrequencyLimit);
}
finally
{
closeConnections(establishedConnections);
}
}
@Test
public void testAuthorizationWithBlockedUser() throws Exception
{
configureCLT(new ConnectionLimitRule()
{
@Override
public String getPort()
{
return null;
}
@Override
public String getIdentity()
{
return USER;
}
@Override
public Boolean getBlocked()
{
return Boolean.TRUE;
}
@Override
public Integer getCountLimit()
{
return null;
}
@Override
public Integer getFrequencyLimit()
{
return null;
}
@Override
public Long getFrequencyPeriod()
{
return null;
}
});
verifyConnectionEstablishmentFails(0);
}
private void establishConnections(final int connectionNumber, final List<Connection> establishedConnections)
throws NamingException, JMSException
{
for (int i = 0; i < connectionNumber; i++)
{
establishConnection(establishedConnections, i);
}
}
private void establishConnection(List<Connection> establishedConnections, int index)
throws NamingException, JMSException
{
establishedConnections.add(getConnectionBuilder().setUsername(USER)
.setPassword(USER_SECRET)
.setClientId(getTestName() + index)
.build());
}
private void closeConnections(final List<Connection> establishedConnections) throws JMSException
{
for (final Connection c : establishedConnections)
{
try
{
c.close();
}
catch (RuntimeException e)
{
// Close all connections
}
}
}
private void verifyConnectionEstablishmentFails(final int frequencyLimit) throws NamingException
{
try
{
final Connection connection = getConnectionBuilder().setUsername(USER)
.setPassword(USER_SECRET)
.setClientId(getTestName() + frequencyLimit)
.build();
connection.close();
fail("Connection creation should fail due to exceeding limit");
}
catch (JMSException e)
{
//pass
}
}
private void configureCLT(ConnectionLimitRule... rules) throws Exception
{
final String serializedRules = new ObjectMapper().writeValueAsString(rules);
final Map<String, Object> attributes = new HashMap<>();
attributes.put(RULES, serializedRules);
attributes.put(FREQUENCY_PERIOD, "60000");
createEntityUsingAmqpManagement("clt", RULE_BASED_VIRTUAL_HOST_USER_CONNECTION_LIMIT_PROVIDER, attributes);
}
}
|
3e17d3ed054dcbf2369e3daece63b7d978832a1d | 6,124 | java | Java | communication/communication-key-value/src/test/java/org/eclipse/jnosql/communication/keyvalue/query/GetQueryParserTest.java | eclipse/diana | a62bcfc904a625f239bdde5ff57047e490a35f1e | [
"Apache-2.0"
] | 101 | 2019-02-13T06:25:18.000Z | 2022-03-26T16:55:04.000Z | communication/communication-key-value/src/test/java/org/eclipse/jnosql/communication/keyvalue/query/GetQueryParserTest.java | eclipse/diana | a62bcfc904a625f239bdde5ff57047e490a35f1e | [
"Apache-2.0"
] | 80 | 2019-02-04T23:44:08.000Z | 2022-03-31T12:56:54.000Z | communication/communication-key-value/src/test/java/org/eclipse/jnosql/communication/keyvalue/query/GetQueryParserTest.java | eclipse/diana | a62bcfc904a625f239bdde5ff57047e490a35f1e | [
"Apache-2.0"
] | 39 | 2019-02-10T19:23:06.000Z | 2021-12-16T02:42:07.000Z | 37.802469 | 104 | 0.695134 | 10,158 | /*
*
* Copyright (c) 2017 Otávio Santana and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php.
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
*
* Otavio Santana
*
*/
package org.eclipse.jnosql.communication.keyvalue.query;
import jakarta.nosql.QueryException;
import jakarta.nosql.Value;
import jakarta.nosql.keyvalue.BucketManager;
import jakarta.nosql.keyvalue.KeyValuePreparedStatement;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.verify;
class GetQueryParserTest {
private final GetQueryParser parser = new GetQueryParser();
private final BucketManager manager = Mockito.mock(BucketManager.class);
@ParameterizedTest(name = "Should parser the query {0}")
@ValueSource(strings = {"get \"Diana\""})
public void shouldReturnParserQuery1(String query) {
ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(List.class);
final Stream<Value> stream = parser.query(query, manager);
verify(manager, Mockito.never()).get(Mockito.any(Object.class));
stream.collect(Collectors.toList());
verify(manager).get(captor.capture());
List<Object> value = captor.getAllValues();
assertEquals(1, value.size());
MatcherAssert.assertThat(value, Matchers.contains("Diana"));
}
@ParameterizedTest(name = "Should parser the query {0}")
@ValueSource(strings = {"get 12"})
public void shouldReturnParserQuery2(String query) {
ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(List.class);
final Stream<Value> stream = parser.query(query, manager);
verify(manager, Mockito.never()).get(Mockito.any(Object.class));
stream.collect(Collectors.toList());
verify(manager).get(captor.capture());
List<Object> value = captor.getAllValues();
assertEquals(1, value.size());
MatcherAssert.assertThat(value, Matchers.contains(12L));
}
@ParameterizedTest(name = "Should parser the query {0}")
@ValueSource(strings = {"get {\"Ana\" : \"Sister\", \"Maria\" : \"Mother\"}"})
public void shouldReturnParserQuery3(String query) {
ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(List.class);
final Stream<Value> stream = parser.query(query, manager);
verify(manager, Mockito.never()).get(Mockito.any(Object.class));
stream.collect(Collectors.toList());
verify(manager).get(captor.capture());
List<Object> value = captor.getAllValues();
assertEquals(1, value.size());
MatcherAssert.assertThat(value, Matchers.contains("{\"Ana\":\"Sister\",\"Maria\":\"Mother\"}"));
}
@ParameterizedTest(name = "Should parser the query {0}")
@ValueSource(strings = {"get convert(\"2018-01-10\", java.time.LocalDate)"})
public void shouldReturnParserQuery4(String query) {
ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(List.class);
final Stream<Value> stream = parser.query(query, manager);
verify(manager, Mockito.never()).get(Mockito.any(Object.class));
stream.collect(Collectors.toList());
verify(manager).get(captor.capture());
List<Object> value = captor.getAllValues();
assertEquals(1, value.size());
MatcherAssert.assertThat(value, Matchers.contains(LocalDate.parse("2018-01-10")));
}
@ParameterizedTest(name = "Should parser the query {0}")
@ValueSource(strings = {"get @id"})
public void shouldReturnErrorWhenUseParameterInQuery(String query) {
assertThrows(QueryException.class, () -> parser.query(query, manager));
}
@ParameterizedTest(name = "Should parser the query {0}")
@ValueSource(strings = {"get @id"})
public void shouldReturnErrorWhenDontBindParameters(String query) {
KeyValuePreparedStatement prepare = parser.prepare(query, manager);
assertThrows(QueryException.class, prepare::getResult);
}
@ParameterizedTest(name = "Should parser the query {0}")
@ValueSource(strings = {"get @id"})
public void shouldExecutePrepareStatement(String query) {
ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(List.class);
KeyValuePreparedStatement prepare = parser.prepare(query, manager);
prepare.bind("id", 10);
prepare.getResult().collect(Collectors.toList());
verify(manager).get(captor.capture());
List<Object> value = captor.getAllValues();
assertEquals(1, value.size());
MatcherAssert.assertThat(value, Matchers.contains(10));
}
@ParameterizedTest(name = "Should parser the query {0}")
@ValueSource(strings = {"get @id, @id2"})
public void shouldExecutePrepareStatement2(String query) {
ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(List.class);
KeyValuePreparedStatement prepare = parser.prepare(query, manager);
prepare.bind("id", 10);
prepare.bind("id2", 11);
final Stream<Value> stream = prepare.getResult();
stream.collect(Collectors.toList());
verify(manager, Mockito.times(2)).get(captor.capture());
List<Object> value = captor.getAllValues();
assertEquals(2, value.size());
MatcherAssert.assertThat(value, Matchers.contains(10, 11));
}
} |
3e17d58d2d96221ab3d66ca63c1a8a0d47f8b723 | 8,136 | java | Java | metric-impl/src/main/java/io/skalogs/skaetl/service/MetricImporter.java | OES2018/SkaETL | 38514a830a50c8597859f19b1e992c738bca2e67 | [
"Apache-2.0"
] | 62 | 2018-05-11T10:04:42.000Z | 2022-02-21T03:50:36.000Z | metric-impl/src/main/java/io/skalogs/skaetl/service/MetricImporter.java | OES2018/SkaETL | 38514a830a50c8597859f19b1e992c738bca2e67 | [
"Apache-2.0"
] | 13 | 2018-08-30T11:10:57.000Z | 2022-01-21T23:21:24.000Z | metric-impl/src/main/java/io/skalogs/skaetl/service/MetricImporter.java | OES2018/SkaETL | 38514a830a50c8597859f19b1e992c738bca2e67 | [
"Apache-2.0"
] | 24 | 2018-05-14T11:11:46.000Z | 2021-08-31T07:32:45.000Z | 44.217391 | 133 | 0.705629 | 10,159 | package io.skalogs.skaetl.service;
/*-
* #%L
* metric-api
* %%
* Copyright (C) 2017 - 2018 SkaLogs
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.fasterxml.jackson.databind.JsonNode;
import io.skalogs.skaetl.admin.KafkaAdminService;
import io.skalogs.skaetl.config.KafkaConfiguration;
import io.skalogs.skaetl.config.ProcessConfiguration;
import io.skalogs.skaetl.config.RegistryConfiguration;
import io.skalogs.skaetl.domain.*;
import io.skalogs.skaetl.rules.metrics.GenericMetricProcessor;
import io.skalogs.skaetl.rules.metrics.RuleMetricExecutor;
import io.skalogs.skaetl.serdes.GenericSerdes;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.Consumed;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.Produced;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.util.*;
import static io.skalogs.skaetl.domain.ProcessConstants.TOPIC_TREAT_PROCESS;
import static java.util.stream.Collectors.toList;
@Slf4j
@AllArgsConstructor
@Component
public class MetricImporter {
private final RuleMetricExecutor ruleMetricExecutor;
private final KafkaConfiguration kafkaConfiguration;
private final ProcessConfiguration processConfiguration;
private final KafkaAdminService kafkaAdminService;
private final ApplicationContext applicationContext;
private final RegistryConfiguration registryConfiguration;
private final Map<ProcessMetric, List<KafkaStreams>> runningMetricProcessors = new HashMap();
@PostConstruct
public void init() {
sendToRegistry("addService");
}
public void activate(ProcessMetric processMetric) {
if (runningMetricProcessors.containsKey(processMetric)) {
log.info("stopping old version of {} Metric Stream Process", processMetric.getName());
deactivate(processMetric);
}
log.info("creating {} Metric Stream Process", processMetric.getName());
kafkaAdminService.buildTopic(processMetric.getFromTopic());
processMetric.getProcessOutputs()
.stream()
.filter(processOutput -> processOutput.getTypeOutput() == TypeOutput.KAFKA)
.forEach(processOutput -> kafkaAdminService.buildTopic(processOutput.getParameterOutput().getTopicOut()));
List<KafkaStreams> streams = new ArrayList<>();
for (String idProcessConsumer : processMetric.getSourceProcessConsumers()) {
streams.add(feedMergeTopic(idProcessConsumer,processMetric.getFromTopic(),processMetric.getIdProcess()));
}
if (!processMetric.getSourceProcessConsumersB().isEmpty()) {
kafkaAdminService.buildTopic(processMetric.getFromTopicB());
for (String idProcessConsumer : processMetric.getSourceProcessConsumersB()) {
streams.add(feedMergeTopic(idProcessConsumer, processMetric.getFromTopicB(), processMetric.getIdProcess()));
}
}
GenericMetricProcessor metricProcessor = ruleMetricExecutor.instanciate(processMetric);
metricProcessor.setApplicationContext(applicationContext);
Properties properties = createProperties(kafkaConfiguration.getBootstrapServers());
properties.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 1 * 1024 * 1024L);
properties.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 1000);
KafkaStreams metricStream = metricProcessor.buildStream(properties);
metricStream.start();
streams.add(metricStream);
ProcessMetric processMetricDefinition = processMetric.withTimestamp(new Date());
runningMetricProcessors.put(processMetricDefinition, streams);
}
private KafkaStreams feedMergeTopic(String id, String mergeTopic, String destId) {
StreamsBuilder builder = new StreamsBuilder();
Properties properties = createProperties(kafkaConfiguration.getBootstrapServers());
String inputTopic = id + TOPIC_TREAT_PROCESS;
properties.put(StreamsConfig.APPLICATION_ID_CONFIG, inputTopic + "merger-stream-" + destId);
KStream<String, JsonNode> stream = builder.stream(inputTopic, Consumed.with(Serdes.String(), GenericSerdes.jsonNodeSerde()));
stream.to(mergeTopic, Produced.with(Serdes.String(),GenericSerdes.jsonNodeSerde()));
final KafkaStreams streams = new KafkaStreams(builder.build(), properties);
Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
streams.start();
return streams;
}
public void deactivate(ProcessMetric processMetric) {
if (runningMetricProcessors.containsKey(processMetric)) {
log.info("deactivating {} Metric Stream Process", processMetric.getName());
runningMetricProcessors.get(processMetric).forEach((stream) -> stream.close());
runningMetricProcessors.remove(processMetric);
}
}
private Properties createProperties(String bootstrapServers) {
Properties props = new Properties();
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
props.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 10);
props.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);
return props;
}
private void sendToRegistry(String action) {
if (registryConfiguration.getActive()) {
RegistryWorker registry = null;
try {
registry = RegistryWorker.builder()
.workerType(WorkerType.METRIC_PROCESS)
.ip(InetAddress.getLocalHost().getHostName())
.name(InetAddress.getLocalHost().getHostName())
.port(processConfiguration.getPortClient())
.statusConsumerList(statusExecutor())
.build();
RestTemplate restTemplate = new RestTemplate();
HttpEntity<RegistryWorker> request = new HttpEntity<>(registry);
String url = processConfiguration.getUrlRegistry();
String res = restTemplate.postForObject(url + "/process/registry/" + action, request, String.class);
log.debug("sendToRegistry result {}", res);
} catch (Exception e) {
log.error("Exception on sendToRegistry", e);
}
}
}
public List<StatusConsumer> statusExecutor() {
return runningMetricProcessors.keySet().stream()
.map(e -> StatusConsumer.builder()
.statusProcess(StatusProcess.ENABLE)
.creation(e.getTimestamp())
.idProcessConsumer(e.getIdProcess())
.build())
.collect(toList());
}
@Scheduled(initialDelay = 20 * 1000, fixedRate = 5 * 60 * 1000)
public void refresh() {
sendToRegistry("refresh");
}
}
|
3e17d6710c26198de8245baaaed5b8e68efe3874 | 9,795 | java | Java | cloudsim-plus-master/cloudsim-plus-master/cloudsim-plus/src/main/java/org/cloudbus/cloudsim/datacenters/power/PowerDatacenterNonPowerAware.java | nnatnichas/improvedPSO_VMallocation | 0d5955d4ff32ed96936bf2a2db3d4d31f056ae2c | [
"MIT"
] | 6 | 2019-04-23T15:42:38.000Z | 2022-02-27T09:43:42.000Z | cloudsim-plus-master/cloudsim-plus-master/cloudsim-plus/src/main/java/org/cloudbus/cloudsim/datacenters/power/PowerDatacenterNonPowerAware.java | nnatnichas/improvedPSO_VMallocation | 0d5955d4ff32ed96936bf2a2db3d4d31f056ae2c | [
"MIT"
] | null | null | null | cloudsim-plus-master/cloudsim-plus-master/cloudsim-plus/src/main/java/org/cloudbus/cloudsim/datacenters/power/PowerDatacenterNonPowerAware.java | nnatnichas/improvedPSO_VMallocation | 0d5955d4ff32ed96936bf2a2db3d4d31f056ae2c | [
"MIT"
] | 4 | 2019-06-05T03:13:49.000Z | 2019-11-07T12:53:16.000Z | 40.8125 | 128 | 0.648698 | 10,160 | /*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.datacenters.power;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.cloudbus.cloudsim.datacenters.DatacenterCharacteristics;
import org.cloudbus.cloudsim.hosts.Host;
import org.cloudbus.cloudsim.util.Log;
import org.cloudbus.cloudsim.hosts.power.PowerHostSimple;
import org.cloudbus.cloudsim.vms.Vm;
import org.cloudbus.cloudsim.allocationpolicies.VmAllocationPolicy;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.CloudSimTags;
import org.cloudbus.cloudsim.core.predicates.PredicateType;
import org.cloudbus.cloudsim.resources.FileStorage;
/**
* PowerDatacenterNonPowerAware is a class that represents a <b>non-power</b>
* aware data center in the context of power-aware simulations.
*
* <br/>If you are using any algorithms, policies or workload included in the
* power package please cite the following paper:<br/>
*
* <ul>
* <li><a href="http://dx.doi.org/10.1002/cpe.1867">Anton Beloglazov, and
* Rajkumar Buyya, "Optimal Online Deterministic Algorithms and Adaptive
* Heuristics for Energy and Performance Efficient Dynamic Consolidation of
* Virtual Machines in Cloud Data Centers", Concurrency and Computation:
* Practice and Experience (CCPE), Volume 24, Issue 13, Pages: 1397-1420, John
* Wiley & Sons, Ltd, New York, USA, 2012</a>
* </ul>
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
* @todo There are lots of duplicated code from PowerDatacenter
*/
public class PowerDatacenterNonPowerAware extends PowerDatacenter {
/**
* Creates a Datacenter.
*
* @param simulation The CloudSim instance that represents the simulation the Entity is related to
* @param characteristics the Datacenter characteristics
* @param vmAllocationPolicy the vm provisioner
*
*/
public PowerDatacenterNonPowerAware(
CloudSim simulation,
DatacenterCharacteristics characteristics,
VmAllocationPolicy vmAllocationPolicy)
{
super(simulation, characteristics, vmAllocationPolicy);
}
/**
* Creates a Datacenter with the given parameters.
*
* @param simulation The CloudSim instance that represents the simulation the Entity is related to
* @param characteristics the Datacenter characteristics
* @param vmAllocationPolicy the vm provisioner
* @param storageList the storage list
* @param schedulingInterval the scheduling interval
*
* @deprecated Use the other available constructors with less parameters
* and set the remaining ones using the respective setters.
* This constructor will be removed in future versions.
*/
@Deprecated
public PowerDatacenterNonPowerAware(
CloudSim simulation,
DatacenterCharacteristics characteristics,
VmAllocationPolicy vmAllocationPolicy,
List<FileStorage> storageList,
double schedulingInterval)
{
this(simulation, characteristics, vmAllocationPolicy);
setStorageList(storageList);
setSchedulingInterval(schedulingInterval);
}
@Override
protected double updateCloudletProcessing() {
if (getLastCloudletProcessingTime() == -1 || getLastCloudletProcessingTime() == getSimulation().clock()) {
getSimulation().cancelAll(getId(), new PredicateType(CloudSimTags.VM_UPDATE_CLOUDLET_PROCESSING_EVENT));
schedule(getId(), getSchedulingInterval(), CloudSimTags.VM_UPDATE_CLOUDLET_PROCESSING_EVENT);
return Double.MAX_VALUE;
}
final double currentTime = getSimulation().clock();
if (currentTime > getLastProcessTime()) {
Log.printLine("\n");
final double dcPowerUsageForTimeSpan = getDatacenterPowerUsageForTimeSpan();
Log.printFormattedLine("\n%.2f: Consumed energy is %.2f W*sec\n", getSimulation().clock(), dcPowerUsageForTimeSpan);
Log.printLine("\n\n--------------------------------------------------------------\n\n");
final double nextCloudletFinishTime = getNextCloudletFinishTime(currentTime);
setPower(getPower() + dcPowerUsageForTimeSpan);
checkCloudletsCompletionForAllHosts();
removeFinishedVmsFromEveryHost();
Log.printLine();
migrateVmsOutIfMigrationIsEnabled();
scheduleUpdateOfCloudletsProcessingForFutureTime(nextCloudletFinishTime);
setLastProcessTime(currentTime);
return nextCloudletFinishTime;
}
return Double.MAX_VALUE;
}
/**
* Schedules the next update of Cloudlets in this Host for a future time.
*
* @param nextCloudletFinishTime the time to schedule the update of Cloudlets in this Host, that is the expected
* time of the next finishing Cloudlet among all existing Hosts.
* @see #getNextCloudletFinishTime(double)
*/
private void scheduleUpdateOfCloudletsProcessingForFutureTime(double nextCloudletFinishTime) {
if (nextCloudletFinishTime != Double.MAX_VALUE) {
getSimulation().cancelAll(getId(), new PredicateType(CloudSimTags.VM_UPDATE_CLOUDLET_PROCESSING_EVENT));
// getSimulation().cancelAll(getId(), CloudSim.SIM_ANY);
send(getId(), getSchedulingInterval(), CloudSimTags.VM_UPDATE_CLOUDLET_PROCESSING_EVENT);
}
}
/**
* Performs requested migration of VMs to another Hosts if migration from this Host is enabled.
*/
private void migrateVmsOutIfMigrationIsEnabled() {
if (isMigrationsEnabled()) {
final Map<Vm, Host> migrationMap
= getVmAllocationPolicy().optimizeAllocation(getVmList());
for (final Entry<Vm, Host> entry : migrationMap.entrySet()) {
final Host targetHost = entry.getValue();
final Host oldHost = entry.getKey().getHost();
if (oldHost.equals(Host.NULL)) {
Log.printFormattedLine(
"%.2f: Migration of VM #%d to Host #%d is started",
getSimulation().clock(),
entry.getKey().getId(),
targetHost.getId());
} else {
Log.printFormattedLine(
"%.2f: Migration of VM #%d from Host #%d to Host #%d is started",
getSimulation().clock(),
entry.getKey().getId(),
oldHost.getId(),
targetHost.getId());
}
targetHost.addMigratingInVm(entry.getKey());
incrementMigrationCount();
final double delay = timeToMigrateVm(entry.getKey(), targetHost);
send(getId(), delay, CloudSimTags.VM_MIGRATE, entry);
}
}
}
/**
* Gets the expected finish time of the next Cloudlet to finish in any of the existing Hosts.
*
* @param currentTime the current simulation time
* @return the expected finish time of the next finishing Cloudlet or {@link Double#MAX_VALUE} if not
* Cloudlet is running.
*/
private double getNextCloudletFinishTime(double currentTime) {
double minTime = Double.MAX_VALUE;
for (final PowerHostSimple host : this.<PowerHostSimple>getHostList()) {
Log.printFormattedLine("\n%.2f: Host #%d", getSimulation().clock(), host.getId());
final double nextCloudletFinishTime = host.updateProcessing(currentTime);
minTime = Math.min(nextCloudletFinishTime, minTime);
}
return minTime;
}
/**
* Gets the total power consumed by all Hosts of the Datacenter since the last time the processing
* of Cloudlets in this Host was updated.
*
* @return the total power consumed by all Hosts in the elapsed time span
*/
private double getDatacenterPowerUsageForTimeSpan() {
final double timeSpan = getSimulation().clock() - getLastProcessTime();
double datacenterPowerUsageForTimeSpan = 0;
for(PowerHostSimple host : this.<PowerHostSimple>getHostList()) {
Log.printFormattedLine("%.2f: Host #%d", getSimulation().clock(), host.getId());
final double hostPower = getHostConsumedPowerForTimeSpan(host, timeSpan);
datacenterPowerUsageForTimeSpan += hostPower;
println(String.format(
"%.2f: Host #%d utilization is %.2f%%",
getSimulation().clock(),
host.getId(),
host.getUtilizationOfCpu() * 100));
println(String.format(
"%.2f: Host #%d energy is %.2f W*sec",
getSimulation().clock(),
host.getId(),
hostPower));
}
return datacenterPowerUsageForTimeSpan;
}
/**
* Gets the power consumed by a given Host for a specific time span.
*
* @param host the Host to get the consumed power for the time span
* @param timeSpan the time elapsed since the last update of cloudlets processing
* @return
*/
private double getHostConsumedPowerForTimeSpan(PowerHostSimple host, final double timeSpan) {
double hostPower;
try {
hostPower = host.getMaxPower() * timeSpan;
} catch (IllegalArgumentException e) {
hostPower = 0;
}
return hostPower;
}
}
|
3e17d672ef16f06340a985e8da62778335262b19 | 13,793 | java | Java | src/main/java/il/co/codeguru/corewars8086/gui/CompetitionWindow.java | YoavKa/corewars8086 | 4afccfea23f296261503a38c0159c657d8752bc7 | [
"Apache-2.0"
] | 1 | 2020-10-07T00:39:28.000Z | 2020-10-07T00:39:28.000Z | src/main/java/il/co/codeguru/corewars8086/gui/CompetitionWindow.java | YoavKa/corewars8086 | 4afccfea23f296261503a38c0159c657d8752bc7 | [
"Apache-2.0"
] | 1 | 2019-01-12T12:06:46.000Z | 2019-01-12T12:06:46.000Z | src/main/java/il/co/codeguru/corewars8086/gui/CompetitionWindow.java | YoavKa/corewars8086 | 4afccfea23f296261503a38c0159c657d8752bc7 | [
"Apache-2.0"
] | 2 | 2015-12-17T17:37:58.000Z | 2020-12-09T12:18:11.000Z | 38.744382 | 161 | 0.587617 | 10,161 | package il.co.codeguru.corewars8086.gui;
import il.co.codeguru.corewars8086.war.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import javax.swing.*;
/**
* @author BS
*/
public class CompetitionWindow extends JFrame
implements ScoreEventListener, ActionListener, CompetitionEventListener {
private static final long serialVersionUID = 1L;
private Competition competition;
private ColumnGraph columnGraph;
// widgets
private JButton showAdvancedButton;
private JButton runWarButton;
private JButton showBattleButton;
private JLabel warCounterDisplay;
private JTextField battlesPerGroupField;
private JTextField warriorsPerGroupField;
private WarFrame battleFrame;
// advanced panel
private JPanel advancedPanel;
private JCheckBox tillEndCheckbox;
private JCheckBox randomRunCheckbox;
private JSlider speedSlider;
private JTextField groupToRunField;
private JTextField seedField;
private int advancedHeight;
private int warCounter;
private int totalWars;
private Thread warThread;
private boolean showBattleFrame;
private boolean competitionRunning;
public CompetitionWindow() throws IOException {
super("CodeGuru Extreme - Competition Viewer");
getContentPane().setLayout(new BorderLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
competition = new Competition(false);
competition.addCompetitionEventListener(this);
WarriorRepository warriorRepository = competition
.getWarriorRepository();
warriorRepository.addScoreEventListener(this);
columnGraph = new ColumnGraph(warriorRepository.getGroupNames());
getContentPane().add(columnGraph, BorderLayout.CENTER);
// -------------
JPanel controlArea = new JPanel();
controlArea.setLayout(new BoxLayout(controlArea, BoxLayout.Y_AXIS));
// -------------- Button Panel
JPanel buttonPanel = new JPanel();
showAdvancedButton = new JButton("Advanced Options");
showAdvancedButton.addActionListener(this);
buttonPanel.add(showAdvancedButton);
buttonPanel.add(Box.createHorizontalStrut(20));
runWarButton = new JButton("<html><font color=red>Start!</font></html>");
runWarButton.addActionListener(this);
buttonPanel.add(runWarButton);
buttonPanel.add(Box.createHorizontalStrut(20));
showBattleButton = new JButton("Show session");
showBattleButton.addActionListener(this);
buttonPanel.add(showBattleButton);
controlArea.add(buttonPanel);
// -------------
controlArea.add(new JSeparator(JSeparator.HORIZONTAL));
// ------------- Counter panel, for better graphics
JPanel counterPanel = new JPanel();
counterPanel.setLayout(new FlowLayout());
warCounterDisplay = new JLabel("No sessions were run.");
counterPanel.add(warCounterDisplay);
controlArea.add(counterPanel);
// -------------
controlArea.add(new JSeparator(JSeparator.HORIZONTAL));
// ------------ Control panel
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.add(new JLabel("Survivor group size:"));
// If total number of teams is more then four, make it the default number
int numberOfGropus = Math.min(4,
competition.getWarriorRepository().getNumberOfGroups());
warriorsPerGroupField = new JTextField(String.format("%d", numberOfGropus), 3);
controlPanel.add(warriorsPerGroupField);
controlPanel.add(new JLabel("Sessions:"));
battlesPerGroupField = new JTextField("10", 4);
controlPanel.add(battlesPerGroupField);
controlArea.add(controlPanel);
// -------------
controlArea.add(new JSeparator(JSeparator.HORIZONTAL));
// ------------- Advanced options panel
advancedPanel = new JPanel();
advancedPanel.setLayout(new BoxLayout(advancedPanel, BoxLayout.Y_AXIS));
tillEndCheckbox = new JCheckBox("Always run 200,000 rounds", competition.getTillEnd());
tillEndCheckbox.addActionListener(this);
tillEndCheckbox.setAlignmentX(Component.CENTER_ALIGNMENT);
advancedPanel.add(tillEndCheckbox);
randomRunCheckbox = new JCheckBox("Run random surivor groups", false);
randomRunCheckbox.setAlignmentX(Component.CENTER_ALIGNMENT);
advancedPanel.add(randomRunCheckbox);
JPanel speedPanel = new JPanel();
speedPanel.add(new JLabel("Default speed:"));
speedSlider = new JSlider(1, Competition.MAXIMUM_SPEED, Competition.MAXIMUM_SPEED * 9 / 10);
speedPanel.add(speedSlider);
advancedPanel.add(speedPanel);
JPanel groupToRunPanel = new JPanel();
groupToRunPanel.add(new JLabel("Only with specific group:"));
groupToRunField = new JTextField(10);
groupToRunPanel.add(groupToRunField);
groupToRunPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
advancedPanel.add(groupToRunPanel);
JPanel seedPanel = new JPanel(new FlowLayout());
seedPanel.add(new JLabel("Custom seed (a number):"));
seedField = new JTextField(10);
seedPanel.add(seedField);
seedPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
advancedPanel.add(seedPanel);
controlArea.add(advancedPanel);
// -------------
getContentPane().add(controlArea, BorderLayout.SOUTH);
pack();
advancedHeight = advancedPanel.getHeight();
advancedPanel.setVisible(false);
addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {}
public void windowClosing(WindowEvent e) {
if (warThread != null)
competition.setAbort();
if (battleFrame != null)
battleFrame.dispose();
}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
});
}
/**
* Starts a new war.
* @return whether or not a new war was started.
*/
public boolean runWar() {
try {
if (!seedField.getText().equals(""))
Long.parseLong(seedField.getText()); //to catch configuration problem early on
final int battlesPerGroup = Integer.parseInt(
battlesPerGroupField.getText().trim());
final int warriorsPerGroup = Integer.parseInt(
warriorsPerGroupField.getText().trim());
if (competition.getWarriorRepository().getNumberOfGroups() < warriorsPerGroup) {
JOptionPane.showMessageDialog(this,
"Not enough survivors (got " +
competition.getWarriorRepository().getNumberOfGroups() +
" but " + warriorsPerGroup + " are needed)");
return false;
}
warThread = new Thread("CompetitionThread") {
@Override
public void run() {
try {
if (!seedField.getText().equals("")) competition.setSeed(Long.parseLong(seedField.getText()));
competition.runAndSaveCompetition(battlesPerGroup, warriorsPerGroup, groupToRunField.getText().trim(), !randomRunCheckbox.isSelected());
} catch (Exception e) {
e.printStackTrace();
}
};
};
if (!competitionRunning) {
warThread.start();
return true;
}
} catch (NumberFormatException e2) {
JOptionPane.showMessageDialog(this, "Error in configuration");
}
return false;
}
public void scoreChanged(String name, float addedValue, int groupIndex, int subIndex) {
columnGraph.addToValue(groupIndex, subIndex, addedValue);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == runWarButton) {
if (runWarButton.getText().trim().equals("<html><font color=red>Start!</font></html>"))
{
if (runWar())
{
competitionRunning = true;
runWarButton.setText("<html><font color=red>Stop!</font></html>");
}
}
else if (runWarButton.getText().trim().equals("<html><font color=red>Stop!</font></html>"))
{
competition.setAbort();
runWarButton.setEnabled(false);
}
} else if (e.getSource() == showBattleButton) {
if (battleFrame == null) {
showBattleButton.setEnabled(false);
if (warThread == null) {
// war hasn't started yet
showBattleRoom();
} else {
// show the battle frame when the next battle starts
showBattleFrame = true;
}
}
} else if (e.getSource() == showAdvancedButton) {
setSize(getWidth(), getHeight() + advancedHeight - 2*advancedPanel.getHeight());
advancedPanel.setVisible(!advancedPanel.isVisible());
} else if (e.getSource() == tillEndCheckbox) {
competition.setTillEnd(tillEndCheckbox.isSelected());
}
}
public void onWarStart() {
if (showBattleFrame == true) {
showBattleRoom();
showBattleFrame = false;
}
}
private void showBattleRoom() {
competition.setSpeed(speedSlider.getValue());
battleFrame = new WarFrame(competition);
battleFrame.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
//System.out.println("BattleFrame=null");
battleFrame = null;
competition.setSpeed(Competition.MAXIMUM_SPEED);
if (competition.getCurrentWar() != null)
competition.getCurrentWar().setPausedFlag(false);
competition.setPausedFlag(false);
showBattleButton.setEnabled(true);
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
});
competition.addMemoryEventLister(battleFrame);
competition.addCompetitionEventListener(battleFrame);
Rectangle battleFrameRect = new Rectangle(0, getY(), 244 + Canvas.getCanvasSize().width, 222 + Canvas.getCanvasSize().height);
Rectangle screen = getGraphicsConfiguration().getBounds(); //for multiple monitors
if (getX() + getWidth() <= screen.getX() + screen.getWidth()
- battleFrameRect.width)
{
battleFrameRect.x = getX() + getWidth();
}
else if (screen.getX() + screen.getWidth() - battleFrameRect.width
- getWidth() >= screen.getX())
{
setLocation((int) (screen.getX() + screen.getWidth() - battleFrameRect.width
- getWidth()), getY());
battleFrameRect.x = getX() + getWidth();
}
else
{
setLocation((int)screen.getX(), getY());
battleFrameRect.x = getWidth();
}
battleFrame.setBounds(battleFrameRect);
battleFrame.setVisible(true);
}
public void onWarEnd(int reason, String winners) {
warCounter++;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
warCounterDisplay.setText("Sessions so far:" + warCounter +
" (out of " + totalWars + ")");
};
});
}
public void onRound(int round) {
}
public void onWarriorBirth(String warriorName) {
}
public void onWarriorDeath(String warriorName, String reason) {
}
public void onCompetitionStart() {
totalWars = competition.getTotalNumberOfWars() + warCounter;
groupToRunField.setEnabled(false);
seedField.setEnabled(false);
}
public void onCompetitionEnd() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
warCounterDisplay.setText("The competition is over. " +
warCounter + " sessions were run.");
};
});
warThread = null;
if (battleFrame == null)
{
showBattleButton.setEnabled(true);
showBattleFrame = false;
}
groupToRunField.setEnabled(true);
runWarButton.setText("<html><font color=red>Start!</font></html>");
runWarButton.setEnabled(true);
competitionRunning = false;
seedField.setEnabled(true);
}
@Override
public void onEndRound() {
}
} |
3e17d694df05043430bb927956d37410eb7bbb08 | 3,196 | java | Java | src/test/java/net/haesleinhuepf/clij2/plugins/MeanSliceBySliceSphereTest.java | clij/clij2-tests | 4ed3338277f2792debfba7a11f04f85e9095ef29 | [
"BSD-3-Clause"
] | null | null | null | src/test/java/net/haesleinhuepf/clij2/plugins/MeanSliceBySliceSphereTest.java | clij/clij2-tests | 4ed3338277f2792debfba7a11f04f85e9095ef29 | [
"BSD-3-Clause"
] | null | null | null | src/test/java/net/haesleinhuepf/clij2/plugins/MeanSliceBySliceSphereTest.java | clij/clij2-tests | 4ed3338277f2792debfba7a11f04f85e9095ef29 | [
"BSD-3-Clause"
] | null | null | null | 37.6 | 122 | 0.661452 | 10,162 | package net.haesleinhuepf.clij2.plugins;
import ij.IJ;
import ij.ImagePlus;
import ij.gui.Roi;
import ij.plugin.Duplicator;
import net.haesleinhuepf.clij.clearcl.ClearCLBuffer;
import net.haesleinhuepf.clij.clearcl.ClearCLImage;
import net.haesleinhuepf.clij.test.TestUtilities;
import net.haesleinhuepf.clijx.CLIJx;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class MeanSliceBySliceSphereTest {
@Ignore //ignore test as we know and need to accept that the tested method does not do the same its ImageJ counterpart
@Test
public void meanSliceBySlice() {
CLIJx clijx = CLIJx.getInstance();
ImagePlus testFlyBrain3D = IJ.openImage("src/test/resources/flybrain.tif");
ImagePlus testImage = new Duplicator().run(testFlyBrain3D);
IJ.run(testImage, "32-bit", "");
// do operation with ImageJ
ImagePlus reference = new Duplicator().run(testImage);
IJ.run(reference, "Mean...", "radius=1 stack");
// do operation with CLIJ
ClearCLImage inputCL = clijx.convert(testImage, ClearCLImage.class);
ClearCLImage outputCL = clijx.create(inputCL);
clijx.meanSliceBySliceSphere(inputCL, outputCL, 1, 1);
ImagePlus result = clijx.convert(outputCL, ImagePlus.class);
//new ImageJ();
//clij.show(inputCL, "inp");
//clij.show(reference, "ref");
//clij.show(result, "res");
//new WaitForUserDialog("wait").show();
assertTrue(TestUtilities.compareImages(reference, result, 30));
IJ.exit();
clijx.clear();
}
@Ignore //ignore test as we know and need to accept that the tested method does not do the same its ImageJ counterpart
@Test
public void meanSliceBySlice_Buffers() {
CLIJx clijx = CLIJx.getInstance();
ImagePlus testFlyBrain3D = IJ.openImage("src/test/resources/flybrain.tif");
ImagePlus testImage = new Duplicator().run(testFlyBrain3D);
IJ.run(testImage, "32-bit", "");
// do operation with ImageJ
ImagePlus reference = new Duplicator().run(testImage);
IJ.run(reference, "Mean...", "radius=1 stack");
// do operation with CLIJ
ClearCLBuffer inputCL = clijx.convert(testImage, ClearCLBuffer.class);
ClearCLBuffer outputCL = clijx.create(inputCL);
clijx.meanSliceBySliceSphere(inputCL, outputCL, 1, 1);
ImagePlus result = clijx.convert(outputCL, ImagePlus.class);
// ignore edges and first and last slice
reference.setRoi(new Roi(1, 1, reference.getWidth() - 2, reference.getHeight() - 2));
result.setRoi(new Roi(1, 1, reference.getWidth() - 2, reference.getHeight() - 2));
reference = new Duplicator().run(reference, 2, result.getNSlices() - 2);
result = new Duplicator().run(result, 2, result.getNSlices() - 2);
//new ImageJ();
//clij.show(inputCL, "inp");
//clij.show(reference, "ref");
//clij.show(result, "res");
//new WaitForUserDialog("wait").show();
assertTrue(TestUtilities.compareImages(reference, result, 30));
IJ.exit();
clijx.clear();
}
} |
3e17d69872242492edb3e35100387d1f948e5d5e | 195 | java | Java | src/org/pikater/shared/database/exceptions/NoResultException.java | school-engagements/pikater | eaeba78b49c73622fa2643d550d0a6f20e75282f | [
"Apache-2.0"
] | null | null | null | src/org/pikater/shared/database/exceptions/NoResultException.java | school-engagements/pikater | eaeba78b49c73622fa2643d550d0a6f20e75282f | [
"Apache-2.0"
] | null | null | null | src/org/pikater/shared/database/exceptions/NoResultException.java | school-engagements/pikater | eaeba78b49c73622fa2643d550d0a6f20e75282f | [
"Apache-2.0"
] | null | null | null | 17.727273 | 68 | 0.769231 | 10,163 | package org.pikater.shared.database.exceptions;
public class NoResultException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -4984923927726216391L;
}
|
3e17d6ab79fd94ee4d8aa92b109beb15af9a1d6f | 2,723 | java | Java | engine/test-src/org/pentaho/di/core/compress/snappy/SnappyCompressionInputStreamTest.java | biohazard120/pentaho-kettle | 0ba6941e4c4fc25e463fed765b09abf6ae14e1a2 | [
"Apache-2.0"
] | 1 | 2017-01-24T14:08:52.000Z | 2017-01-24T14:08:52.000Z | engine/test-src/org/pentaho/di/core/compress/snappy/SnappyCompressionInputStreamTest.java | biohazard120/pentaho-kettle | 0ba6941e4c4fc25e463fed765b09abf6ae14e1a2 | [
"Apache-2.0"
] | null | null | null | engine/test-src/org/pentaho/di/core/compress/snappy/SnappyCompressionInputStreamTest.java | biohazard120/pentaho-kettle | 0ba6941e4c4fc25e463fed765b09abf6ae14e1a2 | [
"Apache-2.0"
] | 1 | 2015-10-25T15:55:20.000Z | 2015-10-25T15:55:20.000Z | 29.923077 | 98 | 0.760191 | 10,164 | package org.pentaho.di.core.compress.snappy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.pentaho.di.core.compress.CompressionPluginType;
import org.pentaho.di.core.compress.CompressionProvider;
import org.pentaho.di.core.compress.CompressionProviderFactory;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.xerial.snappy.SnappyInputStream;
import org.xerial.snappy.SnappyOutputStream;
public class SnappyCompressionInputStreamTest {
public static final String PROVIDER_NAME = "Snappy";
protected CompressionProviderFactory factory = null;
protected SnappyCompressionInputStream inStream = null;
protected CompressionProvider provider = null;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
PluginRegistry.addPluginType( CompressionPluginType.getInstance() );
PluginRegistry.init( true );
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
factory = CompressionProviderFactory.getInstance();
provider = factory.getCompressionProviderByName( PROVIDER_NAME );
inStream = new SnappyCompressionInputStream( createSnappyInputStream(), provider ) {
};
}
@After
public void tearDown() throws Exception {
}
@Test
public void testCtor() {
assertNotNull( inStream );
}
@Test
public void getCompressionProvider() {
assertEquals( provider.getName(), PROVIDER_NAME );
}
@Test
public void testNextEntry() throws IOException {
assertNull( inStream.nextEntry() );
}
@Test
public void testClose() throws IOException {
inStream = new SnappyCompressionInputStream( createSnappyInputStream(), provider );
inStream.close();
}
@Test
public void testRead() throws IOException {
assertEquals( inStream.available(), inStream.read( new byte[100], 0, inStream.available() ) );
}
private SnappyInputStream createSnappyInputStream() throws IOException {
// Create an in-memory ZIP output stream for use by the input stream (to avoid exceptions)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
SnappyOutputStream sos = new SnappyOutputStream( baos );
byte[] testBytes = "Test".getBytes();
sos.write( testBytes );
ByteArrayInputStream in = new ByteArrayInputStream( baos.toByteArray() );
sos.close();
return new SnappyInputStream( in );
}
}
|
3e17d70846a5bb703c18934a024ac5f68b12d6b2 | 2,126 | java | Java | ntchart/src/main/java/ru/turbomolot/ntchart/utils/ThreadCalcParam.java | TurboMolot/NTChart | fafa074f7e379091cec53a9c4e908acb5f786a35 | [
"Apache-2.0"
] | null | null | null | ntchart/src/main/java/ru/turbomolot/ntchart/utils/ThreadCalcParam.java | TurboMolot/NTChart | fafa074f7e379091cec53a9c4e908acb5f786a35 | [
"Apache-2.0"
] | null | null | null | ntchart/src/main/java/ru/turbomolot/ntchart/utils/ThreadCalcParam.java | TurboMolot/NTChart | fafa074f7e379091cec53a9c4e908acb5f786a35 | [
"Apache-2.0"
] | null | null | null | 27.61039 | 75 | 0.607714 | 10,165 | package ru.turbomolot.ntchart.utils;
import android.util.Log;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import ru.turbomolot.ntchart.data.DataList;
import ru.turbomolot.ntchart.render.ISeriesHolder;
import ru.turbomolot.ntchart.series.ISeries;
/**
* Created by TurboMolot on 04.10.17.
*/
public class ThreadCalcParam {
private final ExecutorService es;// = Executors.newFixedThreadPool(10);
private final List<TaskItem> taskList = new DataList<>();
private final Object taskListLock = new Object();
public ThreadCalcParam() {
es = Executors.newFixedThreadPool(10, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread th = new Thread(r);
th.setName("ThCalcParam");
return th;
}
});
}
public void addTask(TaskItem task) {
synchronized (taskListLock) {
taskList.add(task);
}
}
public void invokeAll() throws InterruptedException {
synchronized (taskListLock) {
if (taskList.isEmpty())
return;
es.invokeAll(taskList);
taskList.clear();
}
}
public static class TaskItem implements Callable<Void> {
private final ISeries series;
private final ISeriesHolder holder;
public TaskItem(ISeries series, ISeriesHolder holder) {
if (series == null)
throw new NullPointerException("series can not be null");
if (holder == null)
throw new NullPointerException("holder can not be null");
this.series = series;
this.holder = holder;
}
@Override
public Void call() throws Exception {
series.calcParamRender(holder);
return null;
}
}
public void stop() {
if (!es.isShutdown() && !es.isTerminated()) {
es.shutdownNow();
}
}
}
|
3e17d7606d0b7fa893feb93f64d9ae6ccaa02937 | 4,032 | java | Java | fdb-sql-layer-rest/src/main/java/com/foundationdb/rest/resources/ViewResource.java | geophile/sql-layer | 0eab8b596b729081b9265631230a6703b854a4ec | [
"MIT"
] | null | null | null | fdb-sql-layer-rest/src/main/java/com/foundationdb/rest/resources/ViewResource.java | geophile/sql-layer | 0eab8b596b729081b9265631230a6703b854a4ec | [
"MIT"
] | null | null | null | fdb-sql-layer-rest/src/main/java/com/foundationdb/rest/resources/ViewResource.java | geophile/sql-layer | 0eab8b596b729081b9265631230a6703b854a4ec | [
"MIT"
] | null | null | null | 39.920792 | 101 | 0.676835 | 10,166 | /**
* The MIT License (MIT)
*
* Copyright (c) 2009-2015 FoundationDB, LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.foundationdb.rest.resources;
import static com.foundationdb.rest.resources.ResourceHelper.MEDIATYPE_JSON_JAVASCRIPT;
import static com.foundationdb.rest.resources.ResourceHelper.checkTableAccessible;
import static com.foundationdb.rest.resources.ResourceHelper.parseTableName;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collections;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import com.foundationdb.ais.model.TableName;
import com.foundationdb.rest.ResourceRequirements;
import com.foundationdb.rest.RestResponseBuilder;
import com.foundationdb.server.error.WrongExpressionArityException;
@Path("/view/{view}")
public class ViewResource {
private final ResourceRequirements reqs;
public ViewResource(ResourceRequirements reqs) {
this.reqs = reqs;
}
@GET
@Produces(MEDIATYPE_JSON_JAVASCRIPT)
public Response retrieveEntity(@Context final HttpServletRequest request,
@PathParam("view") String view,
@Context final UriInfo uri) {
final TableName tableName = parseTableName(request, view);
checkTableAccessible(reqs.securityService, request, tableName);
StringBuilder query = new StringBuilder();
query.append("SELECT * FROM ");
query.append(tableName.toString());
List<String> params = new ArrayList<>();
boolean first = true;
for (Map.Entry<String,List<String>> entry : uri.getQueryParameters().entrySet()) {
if (entry.getValue().size() != 1)
throw new WrongExpressionArityException(1, entry.getValue().size());
if (ResourceHelper.JSONP_ARG_NAME.equals(entry.getKey()))
continue;
if (first) {
query.append(" WHERE ");
first = false;
} else {
query.append(" AND ");
}
query.append (entry.getKey());
query.append("=?");
params.add(entry.getValue().get(0));
}
final String queryFinal = query.toString();
final List<String> parameters = Collections.unmodifiableList(params);
return RestResponseBuilder
.forRequest(request)
.body(new RestResponseBuilder.BodyGenerator() {
@Override
public void write(PrintWriter writer) throws Exception {
reqs.restDMLService.runSQLParameter(writer, request, queryFinal, parameters);
}
})
.build();
}
}
|
3e17d775bdc4be4c21c67e8334d86cd5ef45f4c7 | 2,855 | java | Java | src/main/java/com/manniwood/mmpt/typehandlers/BooleanArrayTypeHandler.java | manniwood/mmpt | 651a3eabe2888f690b49f3b5e7b4278881d8ed68 | [
"MIT"
] | 47 | 2015-10-02T12:36:06.000Z | 2022-02-11T23:13:59.000Z | src/main/java/com/manniwood/mmpt/typehandlers/BooleanArrayTypeHandler.java | manniwood/mmpt | 651a3eabe2888f690b49f3b5e7b4278881d8ed68 | [
"MIT"
] | null | null | null | src/main/java/com/manniwood/mmpt/typehandlers/BooleanArrayTypeHandler.java | manniwood/mmpt | 651a3eabe2888f690b49f3b5e7b4278881d8ed68 | [
"MIT"
] | 19 | 2015-03-01T11:30:15.000Z | 2021-11-08T02:15:40.000Z | 34.817073 | 77 | 0.722242 | 10,167 | /*
The MIT License (MIT)
Copyright (c) 2014 Manni Wood
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package com.manniwood.mmpt.typehandlers;
import java.sql.Array;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
/**
* @author Manni Wood
*/
@MappedJdbcTypes(JdbcType.OTHER)
@MappedTypes(Boolean[].class)
public class BooleanArrayTypeHandler extends BaseTypeHandler<Boolean[]> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i,
Boolean[] parameter, JdbcType jdbcType) throws SQLException {
Connection c = ps.getConnection();
Array inArray = c.createArrayOf("boolean", parameter);
ps.setArray(i, inArray);
}
@Override
public Boolean[] getNullableResult(ResultSet rs, String columnName)
throws SQLException {
Array outputArray = rs.getArray(columnName);
if (outputArray == null) {
return null;
}
return (Boolean[])outputArray.getArray();
}
@Override
public Boolean[] getNullableResult(ResultSet rs, int columnIndex)
throws SQLException {
Array outputArray = rs.getArray(columnIndex);
if (outputArray == null) {
return null;
}
return (Boolean[])outputArray.getArray();
}
@Override
public Boolean[] getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
Array outputArray = cs.getArray(columnIndex);
if (outputArray == null) {
return null;
}
return (Boolean[])outputArray.getArray();
}
} |
3e17d8d1175e89fd8fa55426d72cdff9a1d9eb81 | 10,941 | java | Java | src/main/CuboidObject.java | sorifiend/Convert-Chief-Architect-3DS-to-IFC | 3d1bd535e2a288664a260374adf86b516d954f90 | [
"MIT"
] | null | null | null | src/main/CuboidObject.java | sorifiend/Convert-Chief-Architect-3DS-to-IFC | 3d1bd535e2a288664a260374adf86b516d954f90 | [
"MIT"
] | null | null | null | src/main/CuboidObject.java | sorifiend/Convert-Chief-Architect-3DS-to-IFC | 3d1bd535e2a288664a260374adf86b516d954f90 | [
"MIT"
] | null | null | null | 33.458716 | 193 | 0.630564 | 10,168 | /*
* 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 main;
import java.util.ArrayList;
import java.util.List;
import no.myke.parser.ModelObject;
import no.myke.parser.Vector;
/**
*
* @author j.simpson
*/
public class CuboidObject extends genericObject
{
final Vector[] footPrint = new Vector[4];
private ArrayList<Vector> frontFace = new ArrayList<>();
private double length = 0;
Vector longestFaceStart, longestFaceEnd;
CuboidObject(ModelObject model, ArrayList<String> materialsToKeep)
{
super(model, materialsToKeep);
findShape();
}
private void findShape()
{
//Find object 2D extents/footprint
Vector bottomLeft = null, leftTop = null, topRight = null, rightBottom = null;
for (int f = 0; f < super.getFaceList().size(); f++)
{
Face face = super.getFaceList().get(f);
if (f == 0)
{
//Set to opposite
bottomLeft = new Vector(getMaxX(), getMaxY(), 0);
leftTop = new Vector(getMaxX(), getMinY(), 0);
topRight = new Vector(getMinX(), getMinY(), 0);
rightBottom = new Vector(getMinX(), getMaxY(), 0);
}
Vector vector = new Vector(0, 0, 0);
for (int i = 0; i < 3; i++)
{
if(i == 0)
vector = face.Point1();
else if(i == 1)
vector = face.Point2();
else
vector = face.Point3();
//Find bottomLeft most vector (Left end)
if (vector.Y() < bottomLeft.Y() || (vector.Y() == bottomLeft.Y() && vector.X() < bottomLeft.X()))
{
bottomLeft = vector;
}
//Find leftTop most vector (Top end)
if (vector.X() < leftTop.X() || (vector.X() == leftTop.X() && vector.Y() > leftTop.Y())) {
leftTop = vector;
}
//Find topRight most vector (rightBottom end)
if (vector.Y() > topRight.Y() || (vector.Y() == topRight.Y() && vector.X() > topRight.X())) {
topRight = vector;
}
//Find rightBottom most vector (bottomLeft end)
if (vector.X() > rightBottom.X() || (vector.X() == rightBottom.X() && vector.Y() < rightBottom.Y())) {
rightBottom = vector;
}
}
}
footPrint[0] = bottomLeft;
footPrint[1] = leftTop;
footPrint[2] = topRight;
footPrint[3] = rightBottom;
//Find longest side of the extents/footprint
double bottomLength = Utils.distance2D(rightBottom, bottomLeft);
double leftLength = Utils.distance2D(bottomLeft, leftTop);
double topLength = Utils.distance2D(leftTop, topRight);
double rightLength = Utils.distance2D(topRight, rightBottom);
//Check it bottom side is longest
if (bottomLength > leftLength && bottomLength > topLength && bottomLength > rightLength)
{
longestFaceStart = rightBottom;
longestFaceEnd = bottomLeft;
}
//Check it left side is longest
else if (leftLength > topLength && leftLength > rightLength)
{
longestFaceStart = bottomLeft;
longestFaceEnd = leftTop;
}
//Check it top side is longest
else if (topLength > rightLength)
{
longestFaceStart = leftTop;
longestFaceEnd = topRight;
}
//Right side is longest
else
{
longestFaceStart = topRight;
longestFaceEnd = rightBottom;
}
length = Utils.distance2D(longestFaceStart, longestFaceEnd);
//System.out.println(name + " WALL LENGTH: "+length);
//Find the object face shape along the longest side (We need this so that we can deal with walls that have multiple heights, beam pockets or angles)
//Iterates through all faces and find the faces where all vectors are on the longest face from above
ArrayList<Face> meshList = super.getFaceList();
ArrayList<Face> filteredMeshList = new ArrayList<>();
for (int m = 0; m < meshList.size(); m++)
{
if (Utils.isVectorBetween2D(longestFaceStart, longestFaceEnd, meshList.get(m).Point1())
&& Utils.isVectorBetween2D(longestFaceStart, longestFaceEnd, meshList.get(m).Point2())
&& Utils.isVectorBetween2D(longestFaceStart, longestFaceEnd, meshList.get(m).Point3()))
{
filteredMeshList.add(meshList.get(m));
}
}
// ArrayList<Vector> tempFrontFace = new ArrayList<>();
// //Then iterate through the filtered faces and find the shape of the wall elevation.
// //Start from the bottomLeft polygon/face and iterate the filteredMeshList to find the next external point.
// if (longestFaceStart.Z() < longestFaceEnd.Z())
// tempFrontFace.add(longestFaceStart);
// else
// tempFrontFace.add(longestFaceEnd);
// System.out.println("START");
// System.out.println("STR: "+longestFaceEnd.getID());
//
// while (true)
// {
// =; //All broken. First work out how to save IFC files, and then I will know how to best manipulate the polygons (Extrusion from a polyline?).
// //When an outer edge is found add it to the frontFace array
// Vector found = findNextJointVector(tempFrontFace.get(tempFrontFace.size()-1), filteredMeshList, tempFrontFace);
// //Check if shape has been completed
// if (tempFrontFace.size() > 2 && found == null
// || tempFrontFace.size() > 2 && tempFrontFace.get(0).getID().equals(found.getID()))
// {
// break;
// }
// System.out.println("OUT: "+found.getID());
// //Add vector
// tempFrontFace.add(found);
// =;
// }
// =; // frontFace needs to be created with a set of ordered points (clockwise order suggested).
// frontFace = tempFrontFace;
//Create list of lines from the filteredMeshList, but make sure there are no duplicate lines (This means that we will be removing all the internal lines and only keeping outline and openings)
ArrayList<Line> lineListAll = Utils.convertMeshToLines(filteredMeshList);
//remove all duplicates
ArrayList<Line> lineList = Utils.RemoveDuplicateLines(lineListAll);
//Create ordered list of vectors for the front face
frontFace = Utils.orderFaceShape(lineList);
}
// Boolean noDuplicateLine(Line line, ArrayList<Line> lineList)
// {
// for (int l = 0; l < lineList.size(); l++)
// {
// Line current = lineList.get(l);
// //if the line vectors match in any order then declear a match found and return false
// if ((current.first.getID().equals(line.first.getID()) && current.second.getID().equals(line.second.getID())) ||
// (current.first.getID().equals(line.second.getID()) && current.second.getID().equals(line.first.getID())))
// {
// return false;
// }
// }
// //return true if no match was found
// return true;
// }
// Vector findNextJointVector(Vector previousPoint, ArrayList<Face> listToCheck, ArrayList<Vector> doneList)
// {
// //Work clockwise from bottom left
// Face currentFace;
// Vector currentVector;
// Vector currentNextPoint = null;
// for (int f = 0; f < listToCheck.size(); f++)
// {
// currentFace = listToCheck.get(f);
// //first check if any point on the polygon/face matches
// if (previousPoint.getID().equals(currentFace.Point1().getID())
// || previousPoint.getID().equals(currentFace.Point2().getID())
// || previousPoint.getID().equals(currentFace.Point3().getID()))
// {
// //loop through vector on a face
// for (int v = 0; v < 3; v++)
// {
// if (v == 0)
// currentVector = currentFace.Point1();
// else if (v == 1)
// currentVector = currentFace.Point2();
// else
// currentVector = currentFace.Point3();
//
// //make sure it is not matching with itself
// if (false == previousPoint.getID().equals(currentVector.getID()) && false == doneList.contains(currentVector))
// {
// //Set a point to work with
// if (currentNextPoint == null)
// {
// currentNextPoint = currentVector;
// }
// //Now check for next vector in clockwise motion
// //Get next bottom most point that is to the left
// if (isAbove(previousPoint, currentVector)
// && isLeft(previousPoint, currentVector)
// && isBelow(currentNextPoint, currentVector)
// && isRight(currentNextPoint, currentVector))
// {
// currentNextPoint = currentVector;
// }
// //If none, then get next left most point that is top
// else if (isRight(previousPoint, currentVector)
// && isAbove(previousPoint, currentVector)
// && isLeft(currentNextPoint, currentVector)
// && isBelow(currentNextPoint, currentVector))
// {
// currentNextPoint = currentVector;
// }
// //If none, then get next top most point that is right
// else if (isBelow(previousPoint, currentVector)
// && isRight(previousPoint, currentVector)
// && isAbove(currentNextPoint, currentVector)
// && isLeft(currentNextPoint, currentVector))
// {
// currentNextPoint = currentVector;
// }
// //If none, then get next right most point that is bottom
// else if (isLeft(previousPoint, currentVector)
// && isBelow(previousPoint, currentVector)
// && isRight(currentNextPoint, currentVector)
// && isAbove(currentNextPoint, currentVector))
// {
// currentNextPoint = currentVector;
// }
// }
// }
// }
// }
//
// //make sure it doesnt match with itself
// return currentNextPoint;
// }
List<Vector> getFaceShape(){
return frontFace;
}
double getAngleX(){
=;
double xDiff = longestFaceEnd.X() - longestFaceStart.X();
double yDiff = longestFaceEnd.Y() - longestFaceStart.Y();
double angle = Math.toDegrees(Math.atan2(yDiff, xDiff));
if (angle < 0)
{
angle += 360;
}
return Math.sin(Math.toRadians(angle));
}
double getAngleY(){
=;
// double xDiff = 50 - 0;
// double yDiff = -10 - 0;
// double angleX = Math.toDegrees(Math.atan2(yDiff, xDiff));
// double angle;
//
// if (angleX < 0)
// {
// angle = -90-angleX;
// }
// else
// {
// angle = 90-angleX;
// }
//
// if (angle < 0)
// {
// angle += 360;
// }
// return Math.sin(Math.toRadians(angle));
double result = Math.sin(Math.toRadians(getAngleX()));
if (result == 1.0)
return 0.0;
else if (result == -1.0)
return 0.0;
else if (result == 0.0)
return 1.0;
else
return 0.0;
}
Boolean isAbove(Vector previous, Vector toCheck)
{
return previous.Z() < toCheck.Z();
}
Boolean isBelow(Vector previous, Vector toCheck)
{
return previous.Z() > toCheck.Z();
}
Boolean isLeft(Vector previous, Vector toCheck)
{
return previous.X() >= toCheck.X() && previous.Y() > toCheck.Y()
|| previous.X() > toCheck.X() && previous.Y() >= toCheck.Y();
}
Boolean isRight(Vector previous, Vector toCheck)
{
return previous.X() <= toCheck.X() && previous.Y() < toCheck.Y()
|| previous.X() < toCheck.X() && previous.Y() <= toCheck.Y();
}
Double getLength() {return length;}
}
|
3e17d8db2f8afe7a0b125e291911d9e93b731ebc | 4,907 | java | Java | testsuite/src/main/org/jboss/test/web/servlets/EJBOnStartupServlet.java | cquoss/jboss-4.2.3.GA-jdk8 | f3acab9a69c764365bb3f38c0e9a01708dd22b4b | [
"Apache-2.0"
] | null | null | null | testsuite/src/main/org/jboss/test/web/servlets/EJBOnStartupServlet.java | cquoss/jboss-4.2.3.GA-jdk8 | f3acab9a69c764365bb3f38c0e9a01708dd22b4b | [
"Apache-2.0"
] | null | null | null | testsuite/src/main/org/jboss/test/web/servlets/EJBOnStartupServlet.java | cquoss/jboss-4.2.3.GA-jdk8 | f3acab9a69c764365bb3f38c0e9a01708dd22b4b | [
"Apache-2.0"
] | null | null | null | 36.110294 | 108 | 0.665852 | 10,169 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.test.web.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.jboss.test.web.interfaces.ReferenceTest;
import org.jboss.test.web.interfaces.StatelessSession;
import org.jboss.test.web.interfaces.StatelessSessionHome;
import org.jboss.test.web.util.Util;
/** A servlet that accesses an EJB inside its init and destroy methods
to test web component startup ordering with respect to ebj components.
@author hzdkv@example.com
@version $Revision: 57211 $
*/
public class EJBOnStartupServlet extends HttpServlet
{
org.apache.log4j.Category log = org.apache.log4j.Category.getInstance(getClass());
StatelessSessionHome home;
public void init(ServletConfig config) throws ServletException
{
String param = config.getInitParameter("failOnError");
boolean failOnError = true;
if( param != null && Boolean.valueOf(param).booleanValue() == false )
failOnError = false;
try
{
// Access the Util.configureLog4j() method to test classpath resource
URL propsURL = Util.configureLog4j();
log.debug("log4j.properties = "+propsURL);
// Access an EJB to see that they have been loaded first
InitialContext ctx = new InitialContext();
home = (StatelessSessionHome) ctx.lookup("java:comp/env/ejb/OptimizedEJB");
log.debug("EJBOnStartupServlet is initialized");
}
catch(Exception e)
{
log.debug("failed", e);
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try
{
log.debug(Util.displayClassLoaders(loader));
}
catch(NamingException ne)
{
log.debug("failed", ne);
}
if( failOnError == true )
throw new ServletException("Failed to init EJBOnStartupServlet", e);
}
}
public void destroy()
{
try
{
InitialContext ctx = new InitialContext();
StatelessSessionHome home = (StatelessSessionHome) ctx.lookup("java:comp/env/ejb/OptimizedEJB");
log.debug("EJBOnStartupServlet is destroyed");
}
catch(Exception e)
{
log.debug("failed", e);
}
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
try
{
StatelessSession bean = home.create();
bean.noop(new ReferenceTest(), true);
bean.remove();
}
catch(Exception e)
{
throw new ServletException("Failed to call OptimizedEJB", e);
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>EJBOnStartupServlet</title></head>");
out.println("<body>Was initialized<br>");
out.println("Tests passed<br>Time:"+Util.getTime()+"</body>");
out.println("</html>");
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}
}
|
3e17d8e48d45c2590e67ccebd7ed105cfdd9d928 | 426 | java | Java | src/main/java/club/manhuang/project_reactive/utils/AbstractToolsUtil.java | 18792647864/project_reactive | 1febeaed54d3f668bb245faaa1c5099477e287d8 | [
"MIT"
] | null | null | null | src/main/java/club/manhuang/project_reactive/utils/AbstractToolsUtil.java | 18792647864/project_reactive | 1febeaed54d3f668bb245faaa1c5099477e287d8 | [
"MIT"
] | null | null | null | src/main/java/club/manhuang/project_reactive/utils/AbstractToolsUtil.java | 18792647864/project_reactive | 1febeaed54d3f668bb245faaa1c5099477e287d8 | [
"MIT"
] | null | null | null | 23.666667 | 66 | 0.79108 | 10,170 | package club.manhuang.project_reactive.utils;
import club.manhuang.project_reactive.rabbitmq.client.CwWebClient;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
@Log4j2
public abstract class AbstractToolsUtil {
protected CwWebClient cwWebClient;
@Autowired
public void setCwWebClient(CwWebClient cwWebClient) {
this.cwWebClient = cwWebClient;
}
}
|
3e17dae0f2c03e7319b6001791f43c476ff49c92 | 2,953 | java | Java | activemq-protobuf/src/main/java/org/apache/activemq/protobuf/UninitializedMessageException.java | apache/activemq-protobuf | 3a22cd72dc5344451500dbd376403d1dbd843bb6 | [
"Apache-2.0"
] | 13 | 2015-05-23T23:49:31.000Z | 2021-11-10T15:36:13.000Z | activemq-protobuf/src/main/java/org/apache/activemq/protobuf/UninitializedMessageException.java | apache/activemq-protobuf | 3a22cd72dc5344451500dbd376403d1dbd843bb6 | [
"Apache-2.0"
] | null | null | null | activemq-protobuf/src/main/java/org/apache/activemq/protobuf/UninitializedMessageException.java | apache/activemq-protobuf | 3a22cd72dc5344451500dbd376403d1dbd843bb6 | [
"Apache-2.0"
] | 19 | 2015-11-10T14:57:28.000Z | 2022-02-16T18:16:53.000Z | 38.350649 | 91 | 0.706739 | 10,171 | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.
// http://code.google.com/p/protobuf/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.activemq.protobuf;
import java.util.Collections;
import java.util.List;
/**
* Thrown when attempting to build a protocol message that is missing required
* fields. This is a {@code RuntimeException} because it normally represents a
* programming error: it happens when some code which constructs a message fails
* to set all the fields. {@code parseFrom()} methods <b>do not</b> throw this;
* they throw an {@link InvalidProtocolBufferException} if required fields are
* missing, because it is not a programming error to receive an incomplete
* message. In other words, {@code UninitializedMessageException} should never
* be thrown by correct code, but {@code InvalidProtocolBufferException} might
* be.
*
* @author anpch@example.com Kenton Varda
*/
public class UninitializedMessageException extends RuntimeException {
public UninitializedMessageException(List<String> missingFields) {
super(buildDescription(missingFields));
this.missingFields = missingFields;
}
private final List<String> missingFields;
/**
* Get a list of human-readable names of required fields missing from this
* message. Each name is a full path to a field, e.g. "foo.bar[5].baz".
*/
public List<String> getMissingFields() {
return Collections.unmodifiableList(missingFields);
}
/**
* Converts this exception to an {@link InvalidProtocolBufferException}.
* When a parsed message is missing required fields, this should be thrown
* instead of {@code UninitializedMessageException}.
*/
public InvalidProtocolBufferException asInvalidProtocolBufferException() {
return new InvalidProtocolBufferException(getMessage());
}
/** Construct the description string for this exception. */
private static String buildDescription(List<String> missingFields) {
StringBuilder description = new StringBuilder("Message missing required fields: ");
boolean first = true;
for (String field : missingFields) {
if (first) {
first = false;
} else {
description.append(", ");
}
description.append(field);
}
return description.toString();
}
}
|
3e17dbbfcdae1fe31a04bdfed1ad6ffe9bbc0de9 | 671 | java | Java | virtdata-lib-realer/src/main/java/io/nosqlbench/virtdata/library/realer/CountiesByPopulation.java | szimmer1/nosqlbench | b2ff36531419594f8ec6d6ed4cd92036e547e31c | [
"Apache-2.0"
] | 1 | 2022-01-19T13:00:20.000Z | 2022-01-19T13:00:20.000Z | virtdata-lib-realer/src/main/java/io/nosqlbench/virtdata/library/realer/CountiesByPopulation.java | szimmer1/nosqlbench | b2ff36531419594f8ec6d6ed4cd92036e547e31c | [
"Apache-2.0"
] | 5 | 2021-09-10T14:26:31.000Z | 2022-01-26T08:56:02.000Z | virtdata-lib-realer/src/main/java/io/nosqlbench/virtdata/library/realer/CountiesByPopulation.java | szimmer1/nosqlbench | b2ff36531419594f8ec6d6ed4cd92036e547e31c | [
"Apache-2.0"
] | null | null | null | 33.55 | 77 | 0.797317 | 10,172 | package io.nosqlbench.virtdata.library.realer;
import io.nosqlbench.virtdata.api.annotations.Categories;
import io.nosqlbench.virtdata.api.annotations.Category;
import io.nosqlbench.virtdata.api.annotations.Example;
import io.nosqlbench.virtdata.api.annotations.ThreadSafeMapper;
import io.nosqlbench.virtdata.library.basics.shared.distributions.CSVSampler;
/**
* Return a county name weighted by total population.
*/
@ThreadSafeMapper
@Categories(Category.premade)
public class CountiesByPopulation extends CSVSampler {
@Example("CountiesByPopulation()")
public CountiesByPopulation() {
super("county_name","population","simplemaps/uszips");
}
}
|
3e17dc260544707479363c026ef64c9d6938227c | 1,759 | java | Java | kaka/src/Leet_12_intToRoman.java | Darkmoon-Faire/Leetcode_Practice | 5e8f7b67dd9f10fc7d2023edc1cd179071173da7 | [
"MIT"
] | null | null | null | kaka/src/Leet_12_intToRoman.java | Darkmoon-Faire/Leetcode_Practice | 5e8f7b67dd9f10fc7d2023edc1cd179071173da7 | [
"MIT"
] | null | null | null | kaka/src/Leet_12_intToRoman.java | Darkmoon-Faire/Leetcode_Practice | 5e8f7b67dd9f10fc7d2023edc1cd179071173da7 | [
"MIT"
] | 3 | 2019-12-10T12:36:54.000Z | 2019-12-12T03:20:23.000Z | 26.651515 | 83 | 0.43718 | 10,173 | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @Author: yancheng Guo
* @Date: 2019/12/16 17:22
* @Description: 三数之和
*给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
*
* 注意:答案中不可以包含重复的三元组。
*
* 例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
*
* 满足要求的三元组集合为:
* [
* [-1, 0, 1],
* [-1, -1, 2]
* ]
*
*/
/*
[-4,-1,-1,0,1,2]
*/
public class Leet_12_intToRoman {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < nums.length; i++){
if (nums[i] > 0)return res;
if (i > 0 && nums[i] == nums[i-1])continue;
int left = i + 1;
int right = nums.length - 1;
while (left < right){
int addRes = nums[i] + nums[left] + nums[right];
if (addRes == 0){
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
//[-2,0,0,2,2]
while (left < right && nums[left] == nums[left + 1]){
left++;
}
while (left < right && nums[right] == nums[right - 1]){
right--;
}
left++;
right--;
}else if (addRes < 0){
left++;
}else {
right--;
}
}
}
return res;
}
public static void main(String[] args) {
Leet_12_intToRoman leet = new Leet_12_intToRoman();
List<List<Integer>> lists = leet.threeSum(new int[]{0,0,0});
System.out.println(lists);
}
}
|
3e17dc6cea31f1555ad3009ccd4a820b00f165ee | 700 | java | Java | codemucker-cqrs-common/src/main/java/org/codemucker/cqrs/Priorities.java | codemucker/codemucker-cqrs | 42eafd9e674df449f83583827ac71d80ad14afda | [
"Apache-2.0"
] | null | null | null | codemucker-cqrs-common/src/main/java/org/codemucker/cqrs/Priorities.java | codemucker/codemucker-cqrs | 42eafd9e674df449f83583827ac71d80ad14afda | [
"Apache-2.0"
] | null | null | null | codemucker-cqrs-common/src/main/java/org/codemucker/cqrs/Priorities.java | codemucker/codemucker-cqrs | 42eafd9e674df449f83583827ac71d80ad14afda | [
"Apache-2.0"
] | null | null | null | 22.580645 | 63 | 0.611429 | 10,174 | package org.codemucker.cqrs;
public final class Priorities {
public static final int AUTHENTICATION = 1000;
public static final int AUTHORIZATION = 2000;
public static final int HEADERS = 3000;
/**
* After message entity has been deserialised from request
*/
public static final int MESSAGE_DESERIALISED = 4000;
/**
* After handler has been matched for the given message
*/
public static final int HANDLER_MATCHED = 4100;
/**
* After ACL has been applied
*/
public static final int ACL = 4200;
/**
* After all other filters
*/
public static final int USER = 5000;
}
|
3e17dcc7f7e368abc88512312a071a59dc6782d1 | 2,737 | java | Java | communote/persistence/src/main/java/com/communote/server/persistence/tag/DefaultTagStore.java | Communote/communote-server | e6a3541054baa7ad26a4eccbbdd7fb8937dead0c | [
"Apache-2.0"
] | 26 | 2016-06-27T09:25:10.000Z | 2022-01-24T06:26:56.000Z | communote/persistence/src/main/java/com/communote/server/persistence/tag/DefaultTagStore.java | Communote/communote-server | e6a3541054baa7ad26a4eccbbdd7fb8937dead0c | [
"Apache-2.0"
] | 64 | 2016-06-28T14:50:46.000Z | 2019-05-04T15:10:04.000Z | communote/persistence/src/main/java/com/communote/server/persistence/tag/DefaultTagStore.java | Communote/communote-server | e6a3541054baa7ad26a4eccbbdd7fb8937dead0c | [
"Apache-2.0"
] | 4 | 2016-10-05T17:30:36.000Z | 2019-10-26T15:44:00.000Z | 24.4375 | 94 | 0.54768 | 10,175 | package com.communote.server.persistence.tag;
import com.communote.server.api.core.tag.TagStoreType;
import com.communote.server.model.tag.Tag;
/**
* Base class for TagStore.
*
* @author Communote GmbH - <a href="http://www.communote.com/">http://www.communote.com/</a>
*/
public class DefaultTagStore implements TagStore {
/**
* The default priority
*/
public static final int DEFAULT_PRIORITY = 1000;
private final int priority;
private final String tagStoreId;
private final TagStoreType[] types;
private final boolean multilingual;
/**
* Constructor.
*
* @param tagStoreId
* Alias of this TagStore.
* @param order
* order/priority of this tag store
* @param multilingual
* If set, this TagStore supports multiple languages.
* @param types
* Types, this TagStore can handle.
*/
public DefaultTagStore(String tagStoreId, int order, boolean multilingual,
TagStoreType... types) {
this.tagStoreId = tagStoreId;
this.priority = order;
this.multilingual = multilingual;
if (types == null) {
this.types = new TagStoreType[0];
} else {
this.types = types;
}
}
/**
* Constructor with a priority of 1000 and multilingual support.
*
* @param alias
* Alias of this TagStore.
* @param types
* Types, this TagStore can handle.
*/
public DefaultTagStore(String alias, TagStoreType... types) {
this(alias, DefaultTagStore.DEFAULT_PRIORITY, true, types);
}
/**
* {@inheritDoc}
*/
@Override
public boolean canHandle(TagStoreType type) {
for (TagStoreType innerType : types) {
if (innerType.equals(type)) {
return true;
}
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public int getOrder() {
return priority;
}
/**
* {@inheritDoc}
*/
@Override
public String getTagStoreId() {
return tagStoreId;
}
/**
* {@inheritDoc}
*/
@Override
public String getTagStoreTagId(Tag tag) {
return tag.getDefaultName().toLowerCase();
}
/**
* {@inheritDoc}
*/
@Override
public TagStoreType[] getTypes() {
return types;
}
/**
* @return True, if this TagStore supports multiple languages, else false.
*/
@Override
public boolean isMultilingual() {
return multilingual;
}
}
|
3e17dd0a3fd7955805bb9f4a4d44670da81122e6 | 92 | java | Java | dddlib-persistence/dddlib-persistence-test/src/main/java/org/dayatang/persistence/test/domain/package-info.java | ekoATgithub/dddlib | be1538ab23e4baca520e815cfc128b4dd84b01c4 | [
"Apache-2.0"
] | 504 | 2015-01-09T02:49:50.000Z | 2022-03-24T16:38:12.000Z | dddlib-persistence/dddlib-persistence-test/src/main/java/org/dayatang/persistence/test/domain/package-info.java | ekoATgithub/dddlib | be1538ab23e4baca520e815cfc128b4dd84b01c4 | [
"Apache-2.0"
] | 7 | 2015-10-22T09:16:34.000Z | 2020-03-01T16:25:47.000Z | dddlib-persistence/dddlib-persistence-test/src/main/java/org/dayatang/persistence/test/domain/package-info.java | ekoATgithub/dddlib | be1538ab23e4baca520e815cfc128b4dd84b01c4 | [
"Apache-2.0"
] | 208 | 2015-01-15T06:27:27.000Z | 2022-03-22T16:49:03.000Z | 18.4 | 45 | 0.684783 | 10,176 | /**
* 测试实体
* Created by yyang on 14-2-5.
*/
package org.dayatang.persistence.test.domain; |
3e17dd9014ab190431a8eafd9b8d3d282ddde5c8 | 12,576 | java | Java | src/main/java/org/syphr/prom/DefaultEvaluator.java | syphr42/prom | 074d67c4ebb3afb0b163fcb0bc4826ee577ac803 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/syphr/prom/DefaultEvaluator.java | syphr42/prom | 074d67c4ebb3afb0b163fcb0bc4826ee577ac803 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/syphr/prom/DefaultEvaluator.java | syphr42/prom | 074d67c4ebb3afb0b163fcb0bc4826ee577ac803 | [
"Apache-2.0"
] | null | null | null | 32.329049 | 126 | 0.523616 | 10,177 | /*
* Copyright 2010-2012 Gregory P. Moyer
*
* 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.syphr.prom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This {@link Evaluator} implementation seeks to work the same way property evaluation
* works in Ant. In other words, a reference is defined as a '$' followed by a property
* name wrapped in braces.<br>
* <br>
* For example, a reference to the property "<code>some.property</code>" would like this:
* <code>${some.property}</code>.
*
* @author Gregory P. Moyer
*/
public class DefaultEvaluator implements Evaluator
{
/**
* The pattern used to detect property references in the style of Ant.
*/
private static final Pattern PATTERN = Pattern.compile("\\$\\{(.+?)\\}");
@Override
public String evaluate(String rawValue, Retriever retriever)
{
if (rawValue == null)
{
return null;
}
Evaluation eval = new Evaluation(rawValue, retriever);
eval.parse();
return eval.getValue();
}
@Override
public Reference referenceAt(String rawValue, int position, Retriever retriever)
{
if (rawValue == null)
{
return null;
}
Evaluation eval = new Evaluation(rawValue, retriever);
eval.parse();
return eval.referenceAt(position);
}
@Override
public boolean isReferencing(String rawValue, String name, Retriever retriever)
{
if (rawValue == null)
{
return false;
}
Evaluation eval = new Evaluation(rawValue, retriever);
eval.parse();
List<Reference> references = eval.getReferences(true);
for (Reference ref : references)
{
if (ref.getName().equals(name))
{
return true;
}
}
return false;
}
@Override
public List<Reference> getReferences(String rawValue, Retriever retriever)
{
if (rawValue == null)
{
return Collections.emptyList();
}
Evaluation eval = new Evaluation(rawValue, retriever);
eval.parse();
return eval.getReferences(false);
}
/**
* This class converts a raw value into a tree of nested references. It can then be
* queried for information, such as evaluating the the raw value recursively.
*
* @author Gregory P. Moyer
*/
private static class Evaluation
{
/**
* The {@link Retriever} instance used to convert a reference to its value.
*/
private final Retriever retriever;
/**
* The root reference encapsulates the raw value that was used to create this
* instance. It has no name and its start and end encompass the entire raw value.
* This is the root of the references tree.
*/
private final Reference rootReference;
/**
* Construct a new instance with the given value as the root.
*
* @param rawValue
* the value to be parsed
* @param retriever
* the {@link Retriever} instance used to convert a reference to its
* value
*/
public Evaluation(String rawValue, Retriever retriever)
{
this.retriever = retriever;
rootReference = new Reference(null, rawValue, 0, rawValue.length());
}
/**
* Run the parser to generate a reference tree. This must be called before valid
* reference information can be returned.
*/
public void parse()
{
findReferences(rootReference);
}
/**
* Recursively find all references within the value of the given base reference.
* Any references found will be added to the base reference's list of
* sub-references.
*
* @param baseRef
* the base reference to search
*/
private void findReferences(Reference baseRef)
{
Matcher matcher = PATTERN.matcher(baseRef.getValue());
while (matcher.find())
{
String name = matcher.group(1);
String value = retriever.retrieve(name);
/*
* If the retriever has no value for the given name, then this
* is not a valid reference.
*/
if (value == null)
{
continue;
}
Reference ref = new Reference(name,
value,
matcher.start(),
matcher.end());
baseRef.addReference(ref);
findReferences(ref);
}
}
/**
* Get a list of references found in the raw value used to create this instance.
*
* @param recursive
* if <code>true</code>, this list will include nested references
* @return a list of references, immediate or recursive based on the given flag
*/
public List<Reference> getReferences(boolean recursive)
{
if (!recursive)
{
return new ArrayList<Reference>(rootReference.getReferences());
}
return getReferences(rootReference);
}
/**
* Get a recursive list of all sub-references within the the given base reference.
*
* @param baseRef
* the base reference to search
* @return a recursive list of references
*/
private List<Reference> getReferences(Reference baseRef)
{
List<Reference> baseSubReferences = baseRef.getReferences();
List<Reference> references = new ArrayList<Reference>(baseSubReferences);
for (Reference ref : baseSubReferences)
{
references.addAll(getReferences(ref));
}
return references;
}
/**
* Get the fully evaluated value after replacing all references with their
* corresponding values. This method will recursively replace all nested
* references as well.
*
* @return the fully evaluated value
*/
public String getValue()
{
StringBuilder builder = new StringBuilder(rootReference.getValue());
replaceReferences(builder, rootReference, 0);
return builder.toString();
}
/**
* Recursively replace all sub-references to the given base reference in the
* contents of the given builder.
*
* @param builder
* the builder containing the value with references to be replaced
* @param baseRef
* the base reference whose sub-references will be replaced (this
* method assumes the builder contains the value of the base reference
* as some subset)
* @param offset
* the offset used to align the start/end indices of the sub-references
* with the start/end indices of the builder (this will be non-zero
* when the value of the base reference is not the entire value of the
* builder)
*/
private void replaceReferences(StringBuilder builder, Reference baseRef, int offset)
{
/*
* We must iterate backwards here or else the start/end positions will be
* corrupted by prior replacements.
*/
for (Reference ref : ReverseIterable.wrap(baseRef.getReferences()))
{
builder.replace(offset + ref.getStartPosition(),
offset + ref.getEndPosition(),
ref.getValue());
replaceReferences(builder, ref, offset + ref.getStartPosition());
}
}
/**
* Get the reference found (if such a reference exists) at the given location in
* the raw value.
*
* @param position
* the position to check
* @return the reference at the given position if such a reference exists;
* <code>null</code> otherwise
*/
public Reference referenceAt(int position)
{
for (Reference ref : rootReference.getReferences())
{
if (ref.getStartPosition() <= position && position <= ref.getEndPosition())
{
return ref;
}
}
return null;
}
}
/**
* This class wraps a list and returns an iterator that starts at the end of the list
* and moves backwards. This is useful when using an enhanced for loop, such as:
*
* <pre>
* <code>
* List<Animal> animals = ...
*
* for (Animal animal : ReverseIterable.wrap(animals))
* {
* // feeding the animals backwards is more efficient
* animal.feed();
* }
* </code>
* </pre>
*
* @param <T>
* the type of elements in the list to be wrapped
*
* @author Gregory P. Moyer
*/
private static class ReverseIterable<T> implements Iterable<T>
{
/**
* The list wrapped by this instance.
*/
private final List<T> list;
/**
* A convenience method to construct a new instance without have to restate the
* type (it is inferred rather than explicit).<br>
* <br>
* The following are equivalent:
*
* <pre>
* <code>
* ReverseIterable<Animal> backwardsAnimals = new ReverseIterable<Animal>(new ArrayList<Animal>());
*
* ReverseIterable<Animal> backwardsAnimals = ReverseIterable.wrap(new ArrayList<Animal>());
* </code>
* </pre>
*
* @param <T>
* the type of elements in the list to be wrapped
* @param list
* the list to be wrapped
* @return a new instance
*/
public static <T> ReverseIterable<T> wrap(List<T> list)
{
return new ReverseIterable<T>(list);
}
/**
* Construct a new instance wrapping the given list.
*
* @see #wrap(List)
*
* @param list
* the list to wrap
*/
public ReverseIterable(List<T> list)
{
this.list = list;
}
@Override
public Iterator<T> iterator()
{
return new Iterator<T>()
{
private final ListIterator<T> iterator = list.listIterator(list.size());
@Override
public boolean hasNext()
{
return iterator.hasPrevious();
}
@Override
public T next()
{
return iterator.previous();
}
@Override
public void remove()
{
iterator.remove();
}
};
}
}
}
|
3e17dd90b32b581a938a62013c454545a47845ef | 684 | java | Java | test-commons/src/main/java/com/cjlu/material/testing/commons/persistence/BaseTreeDao.java | Tinnnny/Material-testing | 080af72b9c5a4d269b3e98fc0c10a856b23058b3 | [
"Apache-2.0"
] | 1 | 2019-05-21T00:39:54.000Z | 2019-05-21T00:39:54.000Z | test-commons/src/main/java/com/cjlu/material/testing/commons/persistence/BaseTreeDao.java | Tinnnny/Material-testing | 080af72b9c5a4d269b3e98fc0c10a856b23058b3 | [
"Apache-2.0"
] | 7 | 2019-09-24T02:59:25.000Z | 2021-01-20T23:46:45.000Z | test-commons/src/main/java/com/cjlu/material/testing/commons/persistence/BaseTreeDao.java | Tinnnny/Material-testing | 080af72b9c5a4d269b3e98fc0c10a856b23058b3 | [
"Apache-2.0"
] | null | null | null | 12.90566 | 54 | 0.464912 | 10,178 | package com.cjlu.material.testing.commons.persistence;
import java.util.List;
/**
* 通用的树形结构接口
*/
public interface BaseTreeDao <T extends BaseEntity>{
/**
* 查询全部数据
*
* @return
*/
List<T> selectAll();
/**
* 新增
*
* @param entity
*/
void insert(T entity);
/**
* 删除
*
* @param ids
*/
void delete(String[] ids);
/**
* 根据id查询信息
*
* @param id
* @return
*/
T getById(Long id);
/**
* 更新
*
* @param entity
*/
void update(T entity);
/**
* 根据父级节点查询所有子节点
* @param pid
* @return
*/
List<T> selectByPid(Long pid);
}
|
3e17de4d677a7750695d3166844946850ad6b7c5 | 7,030 | java | Java | service/src/main/java/com/mytiki/kgraph/features/latest/company/CompanyService.java | tiki/kgraph | c582252184ff61fdf256dba0e5ccb1a7721efb57 | [
"MIT"
] | null | null | null | service/src/main/java/com/mytiki/kgraph/features/latest/company/CompanyService.java | tiki/kgraph | c582252184ff61fdf256dba0e5ccb1a7721efb57 | [
"MIT"
] | 28 | 2021-09-06T02:34:37.000Z | 2022-03-22T18:11:06.000Z | service/src/main/java/com/mytiki/kgraph/features/latest/company/CompanyService.java | tiki/kgraph | c582252184ff61fdf256dba0e5ccb1a7721efb57 | [
"MIT"
] | 2 | 2021-12-18T06:52:47.000Z | 2022-03-19T09:19:56.000Z | 45.947712 | 116 | 0.671408 | 10,179 | package com.mytiki.kgraph.features.latest.company;
import com.mytiki.common.exception.ApiExceptionBuilder;
import com.mytiki.common.reply.ApiReplyAOMessageBuilder;
import com.mytiki.kgraph.features.latest.big_picture.BigPictureAO;
import com.mytiki.kgraph.features.latest.big_picture.BigPictureException;
import com.mytiki.kgraph.features.latest.big_picture.BigPictureService;
import com.mytiki.kgraph.features.latest.graph.GraphService;
import com.mytiki.kgraph.features.latest.graph.GraphVertexCompanyDO;
import com.mytiki.kgraph.features.latest.graph.GraphVertexDataBreachDO;
import com.mytiki.kgraph.features.latest.hibp.HibpService;
import org.springframework.http.HttpStatus;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Optional;
public class CompanyService {
private final BigPictureService bigPictureService;
private final HibpService hibpService;
private final GraphService graphService;
public CompanyService(BigPictureService bigPictureService, HibpService hibpService, GraphService graphService) {
this.bigPictureService = bigPictureService;
this.hibpService = hibpService;
this.graphService = graphService;
}
public CompanyAO findByDomain(String domain) {
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
Optional<GraphVertexCompanyDO> company = graphService.getVertex(GraphVertexCompanyDO.COLLECTION, domain);
if (
company.isEmpty() ||
company.get().getCached() == null ||
company.get().getCached().isBefore(now.minusDays(30))) {
try {
BigPictureAO bigPictureAO = bigPictureService.find(domain);
GraphVertexCompanyDO cacheDO = mergeBigPicture(
company.isEmpty() ? new GraphVertexCompanyDO() : company.get(),
bigPictureAO);
cacheDO.setCached(now);
cacheDO.setValue(domain);
cacheDO = graphService.upsertVertex(cacheDO);
return toAO(cacheDO, hibpService.findByDomain(domain));
}catch (BigPictureException ex){
throw new ApiExceptionBuilder()
.httpStatus(ex.getStatus())
.messages(new ApiReplyAOMessageBuilder()
.message(ex.getStatus().equals(HttpStatus.ACCEPTED) ?
"Indexing. Try again later (30m?)" :
ex.getStatus().getReasonPhrase())
.properties("domain", domain)
.build())
.build();
}
}else return toAO(company.get(), hibpService.findByDomain(domain));
}
public void update(BigPictureAO bigPictureAO) {
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
Optional<GraphVertexCompanyDO> company =
graphService.getVertex(GraphVertexCompanyDO.COLLECTION, bigPictureAO.getDomain());
if (company.isEmpty() || company.get().getCached().isBefore(now.minusDays(30))) {
GraphVertexCompanyDO cacheDO = mergeBigPicture(
company.isEmpty() ? new GraphVertexCompanyDO() : company.get(),
bigPictureAO);
cacheDO.setValue(bigPictureAO.getDomain());
cacheDO.setCached(now);
graphService.upsertVertex(cacheDO);
}
}
private GraphVertexCompanyDO mergeBigPicture(GraphVertexCompanyDO company, BigPictureAO bigPictureAO){
company.setAddress(bigPictureAO.getLocation());
company.setDescription(bigPictureAO.getDescription());
company.setName(bigPictureAO.getName());
company.setLogo(bigPictureAO.getLogo());
company.setPhone(bigPictureAO.getPhone());
company.setUrl(bigPictureAO.getUrl());
company.setFacebook(bigPictureAO.getFacebook().getHandle());
company.setLinkedin(bigPictureAO.getLinkedin().getHandle());
company.setTwitter(bigPictureAO.getTwitter().getHandle());
company.setIndustry(bigPictureAO.getCategory().getIndustry());
company.setSector(bigPictureAO.getCategory().getSector());
company.setSubIndustry(bigPictureAO.getCategory().getSubIndustry());
company.setTags(bigPictureAO.getTags());
company.setSensitivityScore(bigPictureService.calcScore(
company.getSector(), company.getIndustry(), company.getSubIndustry(), company.getTags()));
return company;
}
private CompanyAO toAO(GraphVertexCompanyDO companyDO, List<GraphVertexDataBreachDO> breaches) {
CompanyAOAbout about = new CompanyAOAbout();
about.setAddress(companyDO.getAddress());
about.setDomain(companyDO.getValue());
about.setName(companyDO.getName());
about.setDescription(companyDO.getDescription());
about.setLogo(companyDO.getLogo());
about.setPhone(companyDO.getPhone());
about.setUrl(companyDO.getUrl());
CompanyAOType type = new CompanyAOType();
type.setIndustry(companyDO.getIndustry());
type.setSector(companyDO.getSector());
type.setSubIndustry(companyDO.getSubIndustry());
type.setTags(companyDO.getTags());
CompanyAOSocial social = new CompanyAOSocial();
social.setFacebook(companyDO.getFacebook());
social.setLinkedin(companyDO.getLinkedin());
social.setTwitter(companyDO.getTwitter());
CompanyAOScore score = new CompanyAOScore();
score.setSensitivityScore(companyDO.getSensitivityScore());
score.setBreachScore(consolidateBreachScore(breaches));
if(score.getBreachScore() != null && score.getSensitivityScore() != null)
score.setSecurityScore(calcSecurityScore(score.getBreachScore(), score.getSensitivityScore()));
CompanyAO companyAO = new CompanyAO();
companyAO.setAbout(about);
companyAO.setType(type);
companyAO.setSocial(social);
companyAO.setScore(score);
return companyAO;
}
private BigDecimal consolidateBreachScore(List<GraphVertexDataBreachDO> breaches){
BigDecimal score = BigDecimal.valueOf(0);
for(GraphVertexDataBreachDO hibpDO : breaches){
score = score.add(hibpDO.getComboScore());
}
if(score.compareTo(BigDecimal.valueOf(1)) > 0 ) score = BigDecimal.valueOf(1);
return score.setScale(5, RoundingMode.HALF_UP);
}
private BigDecimal calcSecurityScore(BigDecimal breachScore, BigDecimal sensitivityScore){
BigDecimal breachWeight = BigDecimal.valueOf(0.65);
BigDecimal sensitivityWeight = BigDecimal.valueOf(0.35);
return breachScore
.multiply(breachWeight)
.add(sensitivityScore.multiply(sensitivityWeight))
.setScale(5, RoundingMode.HALF_UP);
}
}
|
3e17df5a692a77f4c08d4085e623c1f8835dc673 | 14,249 | java | Java | taverna-robundle/src/main/java/org/apache/taverna/robundle/manifest/RDFToManifest.java | LaudateCorpus1/incubator-taverna-language | 1a823c548486dec1c44a8ffc9cba795f823d382b | [
"Apache-2.0"
] | 27 | 2015-06-24T13:25:46.000Z | 2022-03-16T07:59:25.000Z | taverna-robundle/src/main/java/org/apache/taverna/robundle/manifest/RDFToManifest.java | LaudateCorpus1/incubator-taverna-language | 1a823c548486dec1c44a8ffc9cba795f823d382b | [
"Apache-2.0"
] | 15 | 2015-06-16T23:05:34.000Z | 2018-11-27T11:34:28.000Z | taverna-robundle/src/main/java/org/apache/taverna/robundle/manifest/RDFToManifest.java | LaudateCorpus1/incubator-taverna-language | 1a823c548486dec1c44a8ffc9cba795f823d382b | [
"Apache-2.0"
] | 44 | 2015-03-06T20:53:12.000Z | 2021-12-12T11:03:53.000Z | 33.527059 | 117 | 0.709032 | 10,180 | package org.apache.taverna.robundle.manifest;
/*
* 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.
*/
import static org.apache.jena.ontology.OntModelSpec.OWL_DL_MEM_RULE_INF;
import static org.apache.jena.rdf.model.ModelFactory.createOntologyModel;
import static org.apache.taverna.robundle.utils.PathHelper.relativizeFromBase;
import static org.apache.taverna.robundle.utils.RDFUtils.literalAsFileTime;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.jena.ontology.Individual;
import org.apache.jena.ontology.ObjectProperty;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.ontology.OntResource;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RiotException;
import org.apache.jena.util.iterator.ExtendedIterator;
import org.apache.jena.vocabulary.DCTerms;
import org.apache.taverna.ro.vocabs.bundle;
import org.apache.taverna.ro.vocabs.foaf;
import org.apache.taverna.ro.vocabs.oa;
import org.apache.taverna.ro.vocabs.ore;
import org.apache.taverna.ro.vocabs.pav;
import org.apache.taverna.ro.vocabs.prov;
import org.apache.taverna.ro.vocabs.ro;
import org.apache.taverna.robundle.Bundles;
public class RDFToManifest {
public static class ClosableIterable<T> implements AutoCloseable,
Iterable<T> {
private ExtendedIterator<T> iterator;
public ClosableIterable(ExtendedIterator<T> iterator) {
this.iterator = iterator;
}
@Override
public void close() {
iterator.close();
}
@Override
public ExtendedIterator<T> iterator() {
return iterator;
}
}
private static Logger logger = Logger.getLogger(RDFToManifest.class
.getCanonicalName());
private static <T> ClosableIterable<T> iterate(ExtendedIterator<T> iterator) {
return new ClosableIterable<T>(iterator);
}
protected static Model jsonLdAsJenaModel(InputStream jsonIn, URI base)
throws IOException, RiotException {
Model model = ModelFactory.createDefaultModel();
ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
try {
// TAVERNA-971: set context classloader so jarcache.json is consulted
// even through OSGi
Thread.currentThread().setContextClassLoader(RDFToManifest.class.getClassLoader());
// Now we can parse the JSON-LD without network access
RDFDataMgr.read(model, jsonIn, base.toASCIIString(), Lang.JSONLD);
} finally {
// Restore old context class loader (if any)
Thread.currentThread().setContextClassLoader(oldCl);
}
return model;
}
protected static URI makeBaseURI() throws URISyntaxException {
return new URI("app", UUID.randomUUID().toString(), "/", (String) null);
}
private Individual findRO(OntModel model, URI base) {
try (ClosableIterable<? extends OntResource> instances = iterate(ore.Aggregation
.listInstances())) {
for (OntResource o : instances)
// System.out.println("Woo " + o);
return o.asIndividual();
}
// Fallback - resolve as "/"
// TODO: Ensure it's an Aggregation?
return model.getIndividual(base.toString());
}
private List<Agent> getAgents(URI base, Individual in,
ObjectProperty property) {
List<Agent> creators = new ArrayList<>();
for (Individual agent : listObjectProperties(in, property)) {
Agent a = new Agent();
// Check for any ORCIDs, note that "orcid" is mapped as
// prov:alternateOf in our modified bundle.jsonld
for (Individual alternate : listObjectProperties(agent, prov.alternateOf)) {
if (alternate.isURIResource() && (
alternate.getURI().startsWith("https://orcid.org/") ||
alternate.getURI().startsWith("http://orcid.org/"))) {
// TODO: Check against https://support.orcid.org/knowledgebase/articles/116780-structure-of-the-orcid-identifier
a.setOrcid(URI.create(alternate.getURI()));
break;
}
}
if (agent.isURIResource()) {
URI agentURI = relativizeFromBase(agent.getURI(), base);
if ("orcid.org".equals(agentURI.getHost()) && a.getOrcid() == null) {
a.setOrcid(agentURI);
} else {
a.setUri(agentURI);
}
}
RDFNode name = agent.getPropertyValue(foaf.name);
if (name != null && name.isLiteral())
a.setName(name.asLiteral().getLexicalForm());
creators.add(a);
}
return creators;
}
protected OntModel getOntModel() {
OntModel ontModel = createOntologyModel(OWL_DL_MEM_RULE_INF);
ontModel.setNsPrefix("foaf", foaf.NS);
ontModel.setNsPrefix("prov", prov.NS);
ontModel.setNsPrefix("ore", ore.NS);
ontModel.setNsPrefix("pav", pav.NS);
ontModel.setNsPrefix("dct", DCTerms.NS);
// ontModel.getDocumentManager().loadImports(foaf.getOntModel());
return ontModel;
}
private Set<Individual> listObjectProperties(OntResource ontResource,
ObjectProperty prop) {
LinkedHashSet<Individual> results = new LinkedHashSet<>();
try (ClosableIterable<RDFNode> props = iterate(ontResource
.listPropertyValues(prop))) {
for (RDFNode node : props) {
if (!node.isResource() || !node.canAs(Individual.class))
continue;
results.add(node.as(Individual.class));
}
}
return results;
}
public void readTo(InputStream manifestResourceAsStream, Manifest manifest,
URI manifestResourceBaseURI) throws IOException, RiotException {
OntModel model = new RDFToManifest().getOntModel();
model.add(jsonLdAsJenaModel(manifestResourceAsStream,
manifestResourceBaseURI));
URI root = manifestResourceBaseURI.resolve("/");
Individual researchObj = findRO(model, root);
if (researchObj == null)
throw new IOException("root ResearchObject not found - "
+ "Not a valid RO Bundle manifest");
// isDescribedBy URI
for (Individual manifestResource : listObjectProperties(researchObj,
ore.isDescribedBy)) {
String uriStr = manifestResource.getURI();
if (uriStr == null) {
logger.warning("Skipping manifest without URI: "
+ manifestResource);
continue;
}
// URI relative = relativizeFromBase(uriStr, root);
Path path = manifest.getBundle().getFileSystem().provider()
.getPath(URI.create(uriStr));
manifest.getManifest().add(path);
}
// createdBy
List<Agent> creators = getAgents(root, researchObj, pav.createdBy);
if (!creators.isEmpty()) {
manifest.setCreatedBy(creators.get(0));
if (creators.size() > 1) {
logger.warning("Ignoring additional createdBy agents");
}
}
// createdOn
RDFNode created = researchObj.getPropertyValue(pav.createdOn);
manifest.setCreatedOn(literalAsFileTime(created));
// history
List<Path> history = new ArrayList<Path> ();
for (Individual histItem : listObjectProperties (researchObj, prov.AQ.has_provenance)) {
history.add(Bundles.uriToBundlePath(manifest.getBundle(), relativizeFromBase(histItem.getURI(), root)));
}
manifest.setHistory(history);
// authoredBy
List<Agent> authors = getAgents(root, researchObj, pav.authoredBy);
if (!authors.isEmpty()) {
manifest.setAuthoredBy(authors);
}
// authoredOn
RDFNode authored = researchObj.getPropertyValue(pav.authoredOn);
manifest.setAuthoredOn(literalAsFileTime(authored));
// retrievedFrom
RDFNode retrievedNode = researchObj.getPropertyValue(pav.retrievedFrom);
if (retrievedNode != null) {
try {
manifest.setRetrievedFrom(new URI(retrievedNode.asResource().getURI()));
} catch (URISyntaxException ex) {
logger.log(Level.WARNING, "Error creating URI for retrievedFrom: " +
retrievedNode.asResource().getURI(), ex);
}
}
// retrievedBy
List<Agent> retrievers = getAgents(root, researchObj, pav.retrievedBy);
if (!retrievers.isEmpty()) {
manifest.setRetrievedBy(retrievers.get(0));
if (retrievers.size() > 1) {
logger.warning("Ignoring additional retrievedBy agents");
}
}
// retrievedOn
RDFNode retrieved = researchObj.getPropertyValue(pav.retrievedOn);
manifest.setRetrievedOn(literalAsFileTime(retrieved));
// conformsTo
for (Individual standard : listObjectProperties(researchObj,
ro.conformsTo)) {
if (standard.isURIResource()) {
URI uri;
try {
uri = new URI(standard.getURI());
} catch (URISyntaxException ex) {
logger.log(Level.WARNING, "Invalid URI for conformsTo: " +
standard, ex);
continue;
}
if (! manifest.getConformsTo().contains(uri)) {
manifest.getConformsTo().add(uri);
}
}
}
// Aggregates
for (Individual aggrResource : listObjectProperties(researchObj, ore.aggregates)) {
String uriStr = aggrResource.getURI();
// PathMetadata meta = new PathMetadata();
if (uriStr == null) {
logger.warning("Skipping aggregation without URI: "
+ aggrResource);
continue;
}
PathMetadata meta = manifest.getAggregation(relativizeFromBase(
uriStr, root));
Set<Individual> proxies = listObjectProperties(aggrResource,
bundle.hasProxy);
if (proxies.isEmpty()) {
// FIXME: Jena does not follow OWL properties paths from hasProxy
proxies = listObjectProperties(aggrResource, bundle.bundledAs);
}
if (!proxies.isEmpty()) {
// Should really only be one anyway
Individual proxy = proxies.iterator().next();
String proxyUri = null;
if (proxy.getURI() != null) {
proxyUri = proxy.getURI();
} else if (proxy.getSameAs() != null) {
proxyUri = proxy.getSameAs().getURI();
}
Proxy proxyInManifest = meta.getOrCreateBundledAs();
if (proxyUri != null) {
proxyInManifest.setURI(relativizeFromBase(proxyUri, root));
}
RDFNode eName = proxy.getPropertyValue(ro.entryName);
if (eName != null && eName.isLiteral()) {
proxyInManifest.setFilename(eName.asLiteral().getString());;
}
RDFNode folder = proxy.getPropertyValue(bundle.inFolder);
if (folder != null && folder.isURIResource()) {
URI folderUri = URI.create(folder.asResource().getURI());
if (! folderUri.resolve("/").equals(manifest.getBaseURI())) {
logger.warning("Invalid bundledAs folder, outside base URI of RO: " + folderUri);
continue;
}
Path folderPath = Paths.get(folderUri);
// Note: folder need NOT exist in zip file, so we don't need to do
// Files.createDirectories(folderPath);
proxyInManifest.setFolder(folderPath);
}
}
// createdBy
creators = getAgents(root, aggrResource, pav.createdBy);
if (!creators.isEmpty()) {
meta.setCreatedBy(creators.get(0));
if (creators.size() > 1) {
logger.warning("Ignoring additional createdBy agents for "
+ meta);
}
}
// createdOn
meta.setCreatedOn(literalAsFileTime(aggrResource
.getPropertyValue(pav.createdOn)));
// retrievedFrom
RDFNode retrievedAggrNode = aggrResource.getPropertyValue(pav.retrievedFrom);
if (retrievedAggrNode != null) {
try {
meta.setRetrievedFrom(new URI(retrievedAggrNode.asResource().getURI()));
} catch (URISyntaxException ex) {
logger.log(Level.WARNING, "Error creating URI for retrievedFrom: " +
retrievedAggrNode.asResource().getURI(), ex);
}
}
// retrievedBy
List<Agent> retrieversAggr = getAgents(root, aggrResource, pav.retrievedBy);
if (!retrieversAggr.isEmpty()) {
meta.setRetrievedBy(retrieversAggr.get(0));
if (retrieversAggr.size() > 1) {
logger.warning("Ignoring additional retrievedBy agents for "
+ meta);
}
}
// retrievedOn
RDFNode retrievedAggr = aggrResource.getPropertyValue(pav.retrievedOn);
meta.setRetrievedOn(literalAsFileTime(retrievedAggr));
// conformsTo
for (Individual standard : listObjectProperties(aggrResource,
ro.conformsTo)) {
if (standard.getURI() != null) {
meta.setConformsTo(relativizeFromBase(standard.getURI(),
root));
}
}
// format
RDFNode mediaType = aggrResource.getPropertyValue(DCTerms.format);
if (mediaType != null && mediaType.isLiteral()) {
meta.setMediatype(mediaType.asLiteral().getLexicalForm());
}
}
for (Individual ann : listObjectProperties(researchObj, bundle.hasAnnotation)) {
/*
* Normally just one body per annotation, but just in case we'll
* iterate and split them out (as our PathAnnotation can only keep a
* single setContent() at a time)
*/
for (Individual body : listObjectProperties(
model.getOntResource(ann), oa.hasBody)) {
if (! body.isURIResource()) {
logger.warning("Can't find annotation body for anonymous "
+ body);
continue;
}
PathAnnotation pathAnn = new PathAnnotation();
pathAnn.setContent(relativizeFromBase(body.getURI(), root));
if (ann.getURI() != null)
pathAnn.setUri(relativizeFromBase(ann.getURI(), root));
else if (ann.getSameAs() != null
&& ann.getSameAs().getURI() != null)
pathAnn.setUri(relativizeFromBase(ann.getSameAs().getURI(),
root));
// Handle multiple about/hasTarget
for (Individual target : listObjectProperties(ann, oa.hasTarget))
if (target.getURI() != null)
pathAnn.getAboutList().add(
relativizeFromBase(target.getURI(), root));
manifest.getAnnotations().add(pathAnn);
}
}
}
}
|
3e17dfe7b3b4111b8208303c3cfed0efa05b1c6d | 3,112 | java | Java | ion-liquibase/src/main/java/liquibase/change/core/UpdateDataChange.java | iondv/ion-old-java-version-20140819 | 97173f6af432050b8d6365a5338ea3515ba7b991 | [
"Apache-2.0"
] | null | null | null | ion-liquibase/src/main/java/liquibase/change/core/UpdateDataChange.java | iondv/ion-old-java-version-20140819 | 97173f6af432050b8d6365a5338ea3515ba7b991 | [
"Apache-2.0"
] | null | null | null | ion-liquibase/src/main/java/liquibase/change/core/UpdateDataChange.java | iondv/ion-old-java-version-20140819 | 97173f6af432050b8d6365a5338ea3515ba7b991 | [
"Apache-2.0"
] | null | null | null | 30.811881 | 195 | 0.634319 | 10,181 | package liquibase.change.core;
import liquibase.change.*;
import liquibase.database.Database;
import liquibase.statement.SqlStatement;
import liquibase.statement.UpdateExecutablePreparedStatement;
import liquibase.statement.core.UpdateStatement;
import java.util.ArrayList;
import java.util.List;
@DatabaseChange(name = "update", description = "Updates data in an existing table", priority = ChangeMetaData.PRIORITY_DEFAULT, appliesTo = "table")
public class UpdateDataChange extends AbstractModifyDataChange implements ChangeWithColumns<ColumnConfig> {
private List<ColumnConfig> columns;
public UpdateDataChange() {
columns = new ArrayList<ColumnConfig>();
}
@DatabaseChangeProperty(description = "Data to update", requiredForDatabase = "all")
public List<ColumnConfig> getColumns() {
return columns;
}
public void setColumns(List<ColumnConfig> columns) {
this.columns = columns;
}
public void addColumn(ColumnConfig column) {
columns.add(column);
}
public void removeColumn(ColumnConfig column) {
columns.remove(column);
}
public SqlStatement[] generateStatements(Database database) {
boolean needsPreparedStatement = false;
for (ColumnConfig column : getColumns()) {
if (column.getValueBlobFile() != null) {
needsPreparedStatement = true;
}
if (column.getValueClobFile() != null) {
needsPreparedStatement = true;
}
}
if (needsPreparedStatement) {
UpdateExecutablePreparedStatement statement = new UpdateExecutablePreparedStatement(database, catalogName, schemaName, tableName, columns, getChangeSet(), this.getResourceAccessor());
statement.setWhereClause(where);
for (ColumnConfig whereParam : whereParams) {
if (whereParam.getName() != null) {
statement.addWhereColumnName(whereParam.getName());
}
statement.addWhereParameter(whereParam.getValueObject());
}
return new SqlStatement[] {
statement
};
}
UpdateStatement statement = new UpdateStatement(getCatalogName(), getSchemaName(), getTableName());
for (ColumnConfig column : getColumns()) {
statement.addNewColumnValue(column.getName(), column.getValueObject());
}
statement.setWhereClause(where);
for (ColumnConfig whereParam : whereParams) {
if (whereParam.getName() != null) {
statement.addWhereColumnName(whereParam.getName());
}
statement.addWhereParameter(whereParam.getValueObject());
}
return new SqlStatement[]{
statement
};
}
public String getConfirmationMessage() {
return "Data updated in " + getTableName();
}
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
}
|
3e17e07e5e5484ba95b152201ab1fd2aa898916c | 21,011 | java | Java | controller/server/src/main/java/io/pravega/controller/server/eventProcessor/ControllerEventProcessors.java | tkaitchuck/pravega | e569f7c62aee113c62e3dfa840675e8cb8f190f8 | [
"Apache-2.0"
] | null | null | null | controller/server/src/main/java/io/pravega/controller/server/eventProcessor/ControllerEventProcessors.java | tkaitchuck/pravega | e569f7c62aee113c62e3dfa840675e8cb8f190f8 | [
"Apache-2.0"
] | null | null | null | controller/server/src/main/java/io/pravega/controller/server/eventProcessor/ControllerEventProcessors.java | tkaitchuck/pravega | e569f7c62aee113c62e3dfa840675e8cb8f190f8 | [
"Apache-2.0"
] | null | null | null | 48.74942 | 151 | 0.628147 | 10,182 | /**
* Copyright (c) 2017 Dell Inc., or its subsidiaries.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.pravega.controller.server.eventProcessor;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.AbstractIdleService;
import io.pravega.client.ClientFactory;
import io.pravega.common.LoggerHelpers;
import io.pravega.common.concurrent.FutureHelpers;
import io.pravega.common.util.Retry;
import io.pravega.controller.eventProcessor.EventProcessorConfig;
import io.pravega.controller.eventProcessor.EventProcessorGroup;
import io.pravega.controller.eventProcessor.EventProcessorGroupConfig;
import io.pravega.controller.eventProcessor.EventProcessorSystem;
import io.pravega.controller.eventProcessor.ExceptionHandler;
import io.pravega.controller.eventProcessor.impl.EventProcessorGroupConfigImpl;
import io.pravega.controller.eventProcessor.impl.EventProcessorSystemImpl;
import io.pravega.shared.controller.event.ControllerEvent;
import io.pravega.shared.controller.event.ScaleEvent;
import io.pravega.controller.server.SegmentHelper;
import io.pravega.controller.store.checkpoint.CheckpointStore;
import io.pravega.controller.store.checkpoint.CheckpointStoreException;
import io.pravega.controller.store.host.HostControllerStore;
import io.pravega.controller.store.stream.StreamMetadataStore;
import io.pravega.controller.task.Stream.StreamMetadataTasks;
import io.pravega.controller.task.Stream.StreamTransactionMetadataTasks;
import io.pravega.controller.util.Config;
import io.pravega.client.stream.ScalingPolicy;
import io.pravega.client.stream.Serializer;
import io.pravega.client.stream.StreamConfiguration;
import io.pravega.client.stream.impl.ClientFactoryImpl;
import io.pravega.client.stream.impl.Controller;
import io.pravega.client.stream.impl.JavaSerializer;
import io.pravega.client.admin.stream.impl.ReaderGroupManagerImpl;
import io.pravega.client.stream.impl.netty.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.ImmutablePair;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Supplier;
import static io.pravega.controller.util.RetryHelper.RETRYABLE_PREDICATE;
import static io.pravega.controller.util.RetryHelper.withRetriesAsync;
@Slf4j
public class ControllerEventProcessors extends AbstractIdleService {
public static final Serializer<CommitEvent> COMMIT_EVENT_SERIALIZER = new JavaSerializer<>();
public static final Serializer<AbortEvent> ABORT_EVENT_SERIALIZER = new JavaSerializer<>();
public static final Serializer<ScaleEvent> SCALE_EVENT_SERIALIZER = new JavaSerializer<>();
// Retry configuration
private static final long DELAY = 100;
private static final int MULTIPLIER = 10;
private static final long MAX_DELAY = 10000;
private final String objectId;
private final ControllerEventProcessorConfig config;
private final CheckpointStore checkpointStore;
private final StreamMetadataStore streamMetadataStore;
private final HostControllerStore hostControllerStore;
private final EventProcessorSystem system;
private final SegmentHelper segmentHelper;
private final Controller controller;
private final ConnectionFactory connectionFactory;
private final ClientFactory clientFactory;
private final ScheduledExecutorService executor;
private EventProcessorGroup<CommitEvent> commitEventProcessors;
private EventProcessorGroup<AbortEvent> abortEventProcessors;
private EventProcessorGroup<ScaleEvent> scaleEventProcessors;
private ScaleRequestHandler scaleRequestHandler;
public ControllerEventProcessors(final String host,
final ControllerEventProcessorConfig config,
final Controller controller,
final CheckpointStore checkpointStore,
final StreamMetadataStore streamMetadataStore,
final HostControllerStore hostControllerStore,
final SegmentHelper segmentHelper,
final ConnectionFactory connectionFactory,
final StreamMetadataTasks streamMetadataTasks,
final ScheduledExecutorService executor) {
this(host, config, controller, checkpointStore, streamMetadataStore, hostControllerStore, segmentHelper, connectionFactory,
streamMetadataTasks, null, executor);
}
@VisibleForTesting
ControllerEventProcessors(final String host,
final ControllerEventProcessorConfig config,
final Controller controller,
final CheckpointStore checkpointStore,
final StreamMetadataStore streamMetadataStore,
final HostControllerStore hostControllerStore,
final SegmentHelper segmentHelper,
final ConnectionFactory connectionFactory,
final StreamMetadataTasks streamMetadataTasks,
final EventProcessorSystem system,
final ScheduledExecutorService executor) {
this.objectId = "ControllerEventProcessors";
this.config = config;
this.checkpointStore = checkpointStore;
this.streamMetadataStore = streamMetadataStore;
this.hostControllerStore = hostControllerStore;
this.segmentHelper = segmentHelper;
this.controller = controller;
this.connectionFactory = connectionFactory;
this.clientFactory = new ClientFactoryImpl(config.getScopeName(), controller, connectionFactory);
this.system = system == null ? new EventProcessorSystemImpl("Controller", host, config.getScopeName(), clientFactory,
new ReaderGroupManagerImpl(config.getScopeName(), controller, clientFactory)) : system;
this.scaleRequestHandler = new ScaleRequestHandler(streamMetadataTasks, streamMetadataStore, executor);
this.executor = executor;
}
public CompletableFuture<Void> notifyProcessFailure(String process) {
List<CompletableFuture<Void>> futures = new ArrayList<>();
if (commitEventProcessors != null) {
futures.add(withRetriesAsync(() -> CompletableFuture.runAsync(() -> {
try {
commitEventProcessors.notifyProcessFailure(process);
} catch (CheckpointStoreException e) {
throw new CompletionException(e);
}
}, executor), RETRYABLE_PREDICATE, Integer.MAX_VALUE, executor));
}
if (abortEventProcessors != null) {
futures.add(withRetriesAsync(() -> CompletableFuture.runAsync(() -> {
try {
abortEventProcessors.notifyProcessFailure(process);
} catch (CheckpointStoreException e) {
throw new CompletionException(e);
}
}, executor), RETRYABLE_PREDICATE, Integer.MAX_VALUE, executor));
}
if (scaleEventProcessors != null) {
futures.add(withRetriesAsync(() -> CompletableFuture.runAsync(() -> {
try {
scaleEventProcessors.notifyProcessFailure(process);
} catch (CheckpointStoreException e) {
throw new CompletionException(e);
}
}, executor), RETRYABLE_PREDICATE, Integer.MAX_VALUE, executor));
}
return FutureHelpers.allOf(futures);
}
@Override
protected void startUp() throws Exception {
long traceId = LoggerHelpers.traceEnterWithContext(log, this.objectId, "startUp");
try {
log.info("Starting controller event processors");
initialize();
log.info("Controller event processors startUp complete");
} finally {
LoggerHelpers.traceLeave(log, this.objectId, "startUp", traceId);
}
}
@Override
protected void shutDown() {
long traceId = LoggerHelpers.traceEnterWithContext(log, this.objectId, "shutDown");
try {
log.info("Stopping controller event processors");
stopEventProcessors();
log.info("Controller event processors shutDown complete");
} finally {
LoggerHelpers.traceLeave(log, this.objectId, "shutDown", traceId);
}
}
private CompletableFuture<Void> createStreams() {
StreamConfiguration commitStreamConfig =
StreamConfiguration.builder()
.scope(config.getScopeName())
.streamName(config.getCommitStreamName())
.scalingPolicy(config.getCommitStreamScalingPolicy())
.build();
StreamConfiguration abortStreamConfig =
StreamConfiguration.builder()
.scope(config.getScopeName())
.streamName(config.getAbortStreamName())
.scalingPolicy(config.getAbortStreamScalingPolicy())
.build();
StreamConfiguration scaleStreamConfig =
StreamConfiguration.builder()
.scope(config.getScopeName())
.streamName(Config.SCALE_STREAM_NAME)
.scalingPolicy(ScalingPolicy.fixed(1))
.build();
return createScope(config.getScopeName())
.thenCompose(ignore ->
CompletableFuture.allOf(createStream(commitStreamConfig),
createStream(abortStreamConfig),
createStream(scaleStreamConfig)));
}
private CompletableFuture<Void> createScope(final String scopeName) {
return FutureHelpers.toVoid(Retry.indefinitelyWithExpBackoff(DELAY, MULTIPLIER, MAX_DELAY,
e -> log.warn("Error creating event processor scope " + scopeName, e))
.runAsync(() -> controller.createScope(scopeName)
.thenAccept(x -> log.info("Created controller scope {}", scopeName)), executor));
}
private CompletableFuture<Void> createStream(final StreamConfiguration streamConfig) {
return FutureHelpers.toVoid(Retry.indefinitelyWithExpBackoff(DELAY, MULTIPLIER, MAX_DELAY,
e -> log.warn("Error creating event processor stream " + streamConfig.getStreamName(), e))
.runAsync(() -> controller.createStream(streamConfig)
.thenAccept(x ->
log.info("Created stream {}/{}", streamConfig.getScope(), streamConfig.getStreamName())),
executor));
}
public CompletableFuture<Void> bootstrap(final StreamTransactionMetadataTasks streamTransactionMetadataTasks) {
log.info("Bootstrapping controller event processors");
return createStreams().thenAcceptAsync(x ->
streamTransactionMetadataTasks.initializeStreamWriters(clientFactory, config), executor);
}
public CompletableFuture<Void> handleOrphanedReaders(final Supplier<Set<String>> processes) {
List<CompletableFuture<Void>> futures = new ArrayList<>();
if (this.commitEventProcessors != null) {
futures.add(handleOrphanedReaders(this.commitEventProcessors, processes));
}
if (this.abortEventProcessors != null) {
futures.add(handleOrphanedReaders(this.abortEventProcessors, processes));
}
if (this.scaleEventProcessors != null) {
futures.add(handleOrphanedReaders(this.scaleEventProcessors, processes));
}
return FutureHelpers.allOf(futures);
}
private CompletableFuture<Void> handleOrphanedReaders(final EventProcessorGroup<? extends ControllerEvent> group,
final Supplier<Set<String>> processes) {
return withRetriesAsync(() -> CompletableFuture.supplyAsync(() -> {
try {
return group.getProcesses();
} catch (CheckpointStoreException e) {
if (e.getType().equals(CheckpointStoreException.Type.NoNode)) {
return Collections.<String>emptySet();
}
throw new CompletionException(e);
}
}, executor), RETRYABLE_PREDICATE, Integer.MAX_VALUE, executor)
.thenComposeAsync(groupProcesses -> withRetriesAsync(() -> CompletableFuture.supplyAsync(() -> {
try {
return new ImmutablePair<>(processes.get(), groupProcesses);
} catch (Exception e) {
log.error(String.format("Error fetching current processes%s", group.toString()), e);
throw new CompletionException(e);
}
}, executor), RETRYABLE_PREDICATE, Integer.MAX_VALUE, executor))
.thenComposeAsync(pair -> {
Set<String> activeProcesses = pair.getLeft();
Set<String> registeredProcesses = pair.getRight();
if (registeredProcesses == null || registeredProcesses.isEmpty()) {
return CompletableFuture.completedFuture(null);
}
if (activeProcesses != null) {
registeredProcesses.removeAll(activeProcesses);
}
List<CompletableFuture<Void>> futureList = new ArrayList<>();
for (String process : registeredProcesses) {
futureList.add(withRetriesAsync(() -> CompletableFuture.runAsync(() -> {
try {
group.notifyProcessFailure(process);
} catch (CheckpointStoreException e) {
log.error(String.format("Error notifying failure of process=%s in event processor group %s", process,
group.toString()), e);
throw new CompletionException(e);
}
}, executor), RETRYABLE_PREDICATE, Integer.MAX_VALUE, executor));
}
return FutureHelpers.allOf(futureList);
});
}
private void initialize() throws Exception {
// region Create commit event processor
EventProcessorGroupConfig commitReadersConfig =
EventProcessorGroupConfigImpl.builder()
.streamName(config.getCommitStreamName())
.readerGroupName(config.getCommitReaderGroupName())
.eventProcessorCount(config.getCommitReaderGroupSize())
.checkpointConfig(config.getCommitCheckpointConfig())
.build();
EventProcessorConfig<CommitEvent> commitConfig =
EventProcessorConfig.<CommitEvent>builder()
.config(commitReadersConfig)
.decider(ExceptionHandler.DEFAULT_EXCEPTION_HANDLER)
.serializer(COMMIT_EVENT_SERIALIZER)
.supplier(() -> new CommitEventProcessor(streamMetadataStore, hostControllerStore, executor, segmentHelper, connectionFactory))
.build();
log.info("Creating commit event processors");
Retry.indefinitelyWithExpBackoff(DELAY, MULTIPLIER, MAX_DELAY,
e -> log.warn("Error creating commit event processor group", e))
.run(() -> {
commitEventProcessors = system.createEventProcessorGroup(commitConfig, checkpointStore);
return null;
});
// endregion
// region Create abort event processor
EventProcessorGroupConfig abortReadersConfig =
EventProcessorGroupConfigImpl.builder()
.streamName(config.getAbortStreamName())
.readerGroupName(config.getAbortReaderGroupName())
.eventProcessorCount(config.getAbortReaderGroupSize())
.checkpointConfig(config.getAbortCheckpointConfig())
.build();
EventProcessorConfig<AbortEvent> abortConfig =
EventProcessorConfig.<AbortEvent>builder()
.config(abortReadersConfig)
.decider(ExceptionHandler.DEFAULT_EXCEPTION_HANDLER)
.serializer(ABORT_EVENT_SERIALIZER)
.supplier(() -> new AbortEventProcessor(streamMetadataStore, hostControllerStore, executor, segmentHelper, connectionFactory))
.build();
log.info("Creating abort event processors");
Retry.indefinitelyWithExpBackoff(DELAY, MULTIPLIER, MAX_DELAY,
e -> log.warn("Error creating commit event processor group", e))
.run(() -> {
abortEventProcessors = system.createEventProcessorGroup(abortConfig, checkpointStore);
return null;
});
// endregion
// region Create scale event processor
EventProcessorGroupConfig scaleReadersConfig =
EventProcessorGroupConfigImpl.builder()
.streamName(config.getScaleStreamName())
.readerGroupName(config.getScaleReaderGroupName())
.eventProcessorCount(1)
.checkpointConfig(config.getScaleCheckpointConfig())
.build();
EventProcessorConfig<ScaleEvent> scaleConfig =
EventProcessorConfig.<ScaleEvent>builder()
.config(scaleReadersConfig)
.decider(ExceptionHandler.DEFAULT_EXCEPTION_HANDLER)
.serializer(SCALE_EVENT_SERIALIZER)
.supplier(() -> new ConcurrentEventProcessor<>(
scaleRequestHandler,
executor))
.build();
log.info("Creating scale event processors");
Retry.indefinitelyWithExpBackoff(DELAY, MULTIPLIER, MAX_DELAY,
e -> log.warn("Error creating scale event processor group", e))
.run(() -> {
scaleEventProcessors = system.createEventProcessorGroup(scaleConfig, checkpointStore);
return null;
});
// endregion
log.info("Awaiting start of commit event processors");
commitEventProcessors.awaitRunning();
log.info("Awaiting start of abort event processors");
abortEventProcessors.awaitRunning();
log.info("Awaiting start of scale event processors");
scaleEventProcessors.awaitRunning();
}
private void stopEventProcessors() {
if (commitEventProcessors != null) {
log.info("Stopping commit event processors");
commitEventProcessors.stopAsync();
}
if (abortEventProcessors != null) {
log.info("Stopping abort event processors");
abortEventProcessors.stopAsync();
}
if (scaleEventProcessors != null) {
log.info("Stopping scale event processors");
scaleEventProcessors.stopAsync();
}
if (commitEventProcessors != null) {
log.info("Awaiting termination of commit event processors");
commitEventProcessors.awaitTerminated();
}
if (abortEventProcessors != null) {
log.info("Awaiting termination of abort event processors");
abortEventProcessors.awaitTerminated();
}
if (scaleEventProcessors != null) {
log.info("Awaiting termination of scale event processors");
scaleEventProcessors.awaitTerminated();
}
}
}
|
3e17e08d348e7e0d7d796dd18d06af0fc1ed7ca9 | 1,201 | java | Java | src/test/java/dev/tobee/telegram/request/sendobject/SendVenueTest.java | rmuhamedgaliev/tbd-telegram | 3777ceb2b69a63b8a1026fc335b2796c6c7bbf26 | [
"MIT"
] | 7 | 2021-09-06T21:54:52.000Z | 2022-01-02T19:30:25.000Z | src/test/java/dev/tobee/telegram/request/sendobject/SendVenueTest.java | rmuhamedgaliev/tbd-telegram | 3777ceb2b69a63b8a1026fc335b2796c6c7bbf26 | [
"MIT"
] | 38 | 2021-09-24T23:54:18.000Z | 2022-01-02T14:15:12.000Z | src/test/java/dev/tobee/telegram/request/sendobject/SendVenueTest.java | rmuhamedgaliev/tbd-telegram | 3777ceb2b69a63b8a1026fc335b2796c6c7bbf26 | [
"MIT"
] | null | null | null | 38.741935 | 116 | 0.679434 | 10,183 | package dev.tobee.telegram.request.sendobject;
import java.io.IOException;
import java.util.Optional;
import java.util.OptionalInt;
import com.fasterxml.jackson.core.type.TypeReference;
import dev.tobee.telegram.model.message.Message;
import dev.tobee.telegram.model.message.ResponseWrapper;
import dev.tobee.telegram.request.body.SendVenueBody;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class SendVenueTest {
@Test
void checkValidRequest() throws IOException {
SendVenue sendVenue = new SendVenue(
new SendVenueBody(159L, 0.4f, 0.4f, "title", "address", Optional.empty(), Optional.empty(),
Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), OptionalInt.empty(),
Optional.empty(),
Optional.empty()));
Assertions.assertEquals(sendVenue.getResponseType().getType().getTypeName(),
(new TypeReference<ResponseWrapper<Message>>() {
}).getType().getTypeName());
Assertions.assertEquals("sendVenue", sendVenue.getMethod());
Assertions.assertTrue(sendVenue.getBody().isPresent());
}
}
|
3e17e0a3d8ac450891c74298da102a4a0e5c0623 | 1,227 | java | Java | NIO/part20/Server.java | gorhaf/Java | 06fe3ba1a55037458355c5e0328147efb09d9156 | [
"Apache-2.0"
] | null | null | null | NIO/part20/Server.java | gorhaf/Java | 06fe3ba1a55037458355c5e0328147efb09d9156 | [
"Apache-2.0"
] | null | null | null | NIO/part20/Server.java | gorhaf/Java | 06fe3ba1a55037458355c5e0328147efb09d9156 | [
"Apache-2.0"
] | null | null | null | 29.214286 | 71 | 0.589242 | 10,184 | package main;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
/**
* @author 【看动画,学Java】https://student-api.iyincaishijiao.com/t/Nqrff3f/
* @author 【官方网站】gorhaf.com
* @author 【微信公众号】gorhaf
* @author 【个人微信号】gorhafapp
* @author 【抖音】人人都是程序员
* @author 【B站】人人都是程序员
*/
public class Server {
public static void main(String[] args) {
try {
// 创建服务端套字节通道
ServerSocketChannel server = ServerSocketChannel.open();
// 绑定监听端口号
server.bind(new InetSocketAddress(8080));
// 等待客户端连接
SocketChannel client = server.accept();
// 创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 获取客户端消息
int length = client.read(buffer);
// 输出客户端消息
System.out.println(new String(buffer.array(), 0, length));
// 向客户端传输数据
client.write(ByteBuffer.wrap("你好,客户端!我是服务端!".getBytes()));
// 关闭连接
client.close();
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
3e17e119ff595d4dbfb7752d5f5fa67ae91adee9 | 1,730 | java | Java | addOns/network/src/main/java/org/zaproxy/addon/network/internal/server/ServerConfig.java | ekmixon/zap-extensions | e89067a64c5505d51a4b28180ce4ba8935ce9adc | [
"Apache-2.0"
] | null | null | null | addOns/network/src/main/java/org/zaproxy/addon/network/internal/server/ServerConfig.java | ekmixon/zap-extensions | e89067a64c5505d51a4b28180ce4ba8935ce9adc | [
"Apache-2.0"
] | null | null | null | addOns/network/src/main/java/org/zaproxy/addon/network/internal/server/ServerConfig.java | ekmixon/zap-extensions | e89067a64c5505d51a4b28180ce4ba8935ce9adc | [
"Apache-2.0"
] | null | null | null | 32.037037 | 100 | 0.681503 | 10,185 | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2022 The ZAP Development Team
*
* 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.zaproxy.addon.network.internal.server;
import java.util.Set;
/** The configuration of a server. */
public interface ServerConfig {
/**
* Tells whether or not the server is bound to any local address.
*
* @return {@code true} if the server is bound to any local address, {@code false} otherwise.
*/
boolean isAnyLocalAddress();
/**
* Tells whether or not the server is behind NAT.
*
* <p>When behind NAT the server will attempt to discover its public address, to correctly serve
* requests to itself.
*
* @return {@code true} if the server is behind NAT, {@code false} otherwise.
*/
boolean isBehindNat();
/**
* Gets the aliases of the server.
*
* <p>Allows to identify the server with different addresses/domains to serve those requests
* itself. For example, the {@code zap} domain.
*
* @return the aliases, never {@code null}.
*/
Set<String> getAliases();
}
|
3e17e1369e3305ed4b5a089d9972583c9ecc00c3 | 2,474 | java | Java | sources/android-28/com/android/server/wifi/hotspot2/WfaKeyStore.java | FTC-10161/FtcRobotController | ee6c7efdff947ccd0abfab64405a91176768e7c0 | [
"MIT"
] | null | null | null | sources/android-28/com/android/server/wifi/hotspot2/WfaKeyStore.java | FTC-10161/FtcRobotController | ee6c7efdff947ccd0abfab64405a91176768e7c0 | [
"MIT"
] | null | null | null | sources/android-28/com/android/server/wifi/hotspot2/WfaKeyStore.java | FTC-10161/FtcRobotController | ee6c7efdff947ccd0abfab64405a91176768e7c0 | [
"MIT"
] | null | null | null | 32.552632 | 96 | 0.668957 | 10,186 | /*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.wifi.hotspot2;
import android.os.Environment;
import android.util.Log;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Set;
/**
* WFA Keystore
*/
public class WfaKeyStore {
private static final String TAG = "WfaKeyStore";
// The WFA Root certs are checked in to /system/ca-certificates/cacerts_wfa
// The location on device is configured in the corresponding Android.mk
private static final String DEFAULT_WFA_CERT_DIR =
Environment.getRootDirectory() + "/etc/security/cacerts_wfa";
private boolean mVerboseLoggingEnabled = false;
private KeyStore mKeyStore = null;
/**
* Loads the keystore with root certificates
*/
public void load() {
if (mKeyStore != null) {
return;
}
int index = 0;
try {
mKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
mKeyStore.load(null, null);
Set<X509Certificate> certs = WfaCertBuilder.loadCertsFromDisk(DEFAULT_WFA_CERT_DIR);
for (X509Certificate cert : certs) {
mKeyStore.setCertificateEntry(String.format("%d", index), cert);
index++;
}
if (index <= 0) {
Log.wtf(TAG, "No certs loaded");
}
} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException
| IOException e) {
e.printStackTrace();
}
}
/**
* Returns the underlying keystore object
* @return KeyStore Underlying keystore object created
*/
public KeyStore get() {
return mKeyStore;
}
}
|
3e17e1c6053f0aa93d2b101fa13c9a0118539b87 | 1,351 | java | Java | processor/src/test/java/org/mapstruct/ap/test/bugs/_1561/Issue1561Test.java | incaseoftrouble/mapstruct | 7064e0bc977dc88222ff8fe8d23f9e36cc76fcdf | [
"Apache-2.0"
] | 5,133 | 2015-01-05T11:16:22.000Z | 2022-03-31T18:56:15.000Z | processor/src/test/java/org/mapstruct/ap/test/bugs/_1561/Issue1561Test.java | incaseoftrouble/mapstruct | 7064e0bc977dc88222ff8fe8d23f9e36cc76fcdf | [
"Apache-2.0"
] | 2,322 | 2015-01-01T19:20:49.000Z | 2022-03-29T16:31:25.000Z | processor/src/test/java/org/mapstruct/ap/test/bugs/_1561/Issue1561Test.java | incaseoftrouble/mapstruct | 7064e0bc977dc88222ff8fe8d23f9e36cc76fcdf | [
"Apache-2.0"
] | 820 | 2015-01-03T15:55:11.000Z | 2022-03-30T20:58:07.000Z | 27.571429 | 105 | 0.720207 | 10,187 | /*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.ap.test.bugs._1561;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mapstruct.ap.testutil.IssueKey;
import org.mapstruct.ap.testutil.ProcessorTest;
import org.mapstruct.ap.testutil.WithClasses;
import org.mapstruct.ap.testutil.runner.GeneratedSource;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Sebastian Haberey
*/
@IssueKey("1561")
@WithClasses({
Issue1561Mapper.class,
Source.class,
Target.class,
NestedTarget.class
})
public class Issue1561Test {
@RegisterExtension
final GeneratedSource generatedSource = new GeneratedSource().addComparisonToFixtureFor(
Issue1561Mapper.class
);
@ProcessorTest
public void shouldCorrectlyUseAdder() {
Source source = new Source();
source.addProperty( "first" );
source.addProperty( "second" );
Target target = Issue1561Mapper.INSTANCE.map( source );
assertThat( target.getNestedTarget().getProperties() ).containsExactly( "first", "second" );
Source mapped = Issue1561Mapper.INSTANCE.map( target );
assertThat( mapped.getProperties() ).containsExactly( "first", "second" );
}
}
|
3e17e21d84c15c0ee56e206866be562089db33c8 | 959 | java | Java | feign-hystrix-user-service/src/main/java/com/rainbow/cloud/entity/User.java | ihoney/demo | ab16b7d111dcc769f83de93fb2c836b57a7fdbc4 | [
"MIT"
] | null | null | null | feign-hystrix-user-service/src/main/java/com/rainbow/cloud/entity/User.java | ihoney/demo | ab16b7d111dcc769f83de93fb2c836b57a7fdbc4 | [
"MIT"
] | null | null | null | feign-hystrix-user-service/src/main/java/com/rainbow/cloud/entity/User.java | ihoney/demo | ab16b7d111dcc769f83de93fb2c836b57a7fdbc4 | [
"MIT"
] | null | null | null | 17.759259 | 48 | 0.599583 | 10,188 | package com.rainbow.cloud.entity;
/**
* Created by caihongli on 2017/5/26.
*/
public class User {
private String username;
private String firstName;
private String lastName;
private String email;
protected Long id;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
|
3e17e3b7793496ae899a26ab2f1311c57c57e7ad | 779 | java | Java | src/main/java/com/gustavottc/AddController.java | gustavottc/DemoMVC-Spring | aff1c755c5ed850c0d05bee265058deeae0ddd9f | [
"Unlicense"
] | 3 | 2020-10-17T10:52:52.000Z | 2021-02-10T02:13:02.000Z | src/main/java/com/gustavottc/AddController.java | gustavottc/DemoMVC-Spring | aff1c755c5ed850c0d05bee265058deeae0ddd9f | [
"Unlicense"
] | null | null | null | src/main/java/com/gustavottc/AddController.java | gustavottc/DemoMVC-Spring | aff1c755c5ed850c0d05bee265058deeae0ddd9f | [
"Unlicense"
] | null | null | null | 26.862069 | 134 | 0.77792 | 10,189 | package com.gustavottc;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.gustavottc.service.AddService;
@Controller
public class AddController
{
@RequestMapping("/add")
public ModelAndView add(@RequestParam("t1")int i, @RequestParam("t2")int j, HttpServletRequest request, HttpServletResponse response)
{
AddService as = new AddService();
int k = as.add(i, j);
ModelAndView mv = new ModelAndView();
mv.setViewName("display");
mv.addObject("result", k);
return mv;
}
}
|
3e17e5b686ffbece9d45401cb256499c5a9a168d | 2,335 | java | Java | subjectSystems/C,D/src/weka/associations/tertius/Predicate.java | austinatchley/Themis | 67d5e639e9445f1612249ae7939b3625fea138db | [
"BSD-4-Clause-UC"
] | 88 | 2017-08-14T19:44:21.000Z | 2021-11-20T00:48:01.000Z | subjectSystems/C,D/src/weka/associations/tertius/Predicate.java | kavithacd/Themis | 67d5e639e9445f1612249ae7939b3625fea138db | [
"BSD-4-Clause-UC"
] | 25 | 2017-03-07T15:33:46.000Z | 2020-06-18T01:39:26.000Z | subjectSystems/C,D/src/weka/associations/tertius/Predicate.java | kavithacd/Themis | 67d5e639e9445f1612249ae7939b3625fea138db | [
"BSD-4-Clause-UC"
] | 19 | 2017-10-11T15:25:12.000Z | 2021-08-16T01:47:43.000Z | 22.451923 | 74 | 0.66424 | 10,190 | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* Predicate.java
* Copyright (C) 2003 Peter A. Flach, Nicolas Lachiche
*
* Thanks to Amelie Deltour for porting the original C code to Java
* and integrating it into Weka.
*/
package weka.associations.tertius;
import java.io.Serializable;
import java.util.ArrayList;
/**
* @author Peter A. Flach
* @author Nicolas Lachiche
* @version $Revision: 1.2.2.1 $
*/
public class Predicate implements Serializable {
private ArrayList m_literals;
private String m_name;
private int m_index;
private boolean m_isClass;
public Predicate(String name, int index, boolean isClass) {
m_literals = new ArrayList();
m_name = name;
m_index = index;
m_isClass = isClass;
}
public void addLiteral(Literal lit) {
m_literals.add(lit);
}
public Literal getLiteral(int index) {
return (Literal) m_literals.get(index);
}
public int getIndex() {
return m_index;
}
public int indexOf(Literal lit) {
int index = m_literals.indexOf(lit);
return ((index != -1)
? index
: m_literals.indexOf(lit.getNegation()));
}
public int numLiterals() {
return m_literals.size();
}
public boolean isClass() {
return m_isClass;
}
public String toString() {
return m_name;
}
public String description() {
StringBuffer text = new StringBuffer();
text.append(this.toString() + "\n");
for (int i = 0; i < numLiterals(); i++) {
Literal lit = getLiteral(i);
Literal neg = lit.getNegation();
text.append("\t" + lit + "\t" + neg + "\n");
}
return text.toString();
}
}
|
3e17e64db04fe1615cdcf01805d3b3132181ac44 | 761 | java | Java | restapi/src/main/java/com/xmgps/framework/restapi/template/BeanAttribute.java | pmsg863/xmgps | 35de78bf2e8fd0f685cf94e8151ce6e2903cb84f | [
"Apache-2.0"
] | null | null | null | restapi/src/main/java/com/xmgps/framework/restapi/template/BeanAttribute.java | pmsg863/xmgps | 35de78bf2e8fd0f685cf94e8151ce6e2903cb84f | [
"Apache-2.0"
] | 1 | 2016-11-16T08:44:45.000Z | 2016-12-29T02:42:08.000Z | restapi/src/main/java/com/xmgps/framework/restapi/template/BeanAttribute.java | pmsg863/xmgps | 35de78bf2e8fd0f685cf94e8151ce6e2903cb84f | [
"Apache-2.0"
] | null | null | null | 21.742857 | 67 | 0.672799 | 10,191 | package com.xmgps.framework.restapi.template;
import java.util.Map;
/**
* Created by gps_hwb on 2015/8/19.
*/
public class BeanAttribute {
String fieldName;
String fieldClassName;
public BeanAttribute(String fieldName, String fieldClassName) {
this.fieldName = fieldName;
this.fieldClassName = fieldClassName;
}
public String getFieldName() {
return fieldName;
}
public BeanAttribute setFieldName(String fieldName) {
this.fieldName = fieldName;
return this;
}
public String getFieldClassName() {
return fieldClassName;
}
public BeanAttribute setFieldClassName(String fieldClassName) {
this.fieldClassName = fieldClassName;
return this;
}
}
|
3e17e68795bd73b6a9275cb6d8217e99a960290c | 5,492 | java | Java | fivm/test/java/src/com/fiji/fivm/test/MeasureTimeGaps.java | mihirlibran/cse605 | bbc1072e1eb892dc37344ec8aca7b7154630a090 | [
"Apache-2.0"
] | null | null | null | fivm/test/java/src/com/fiji/fivm/test/MeasureTimeGaps.java | mihirlibran/cse605 | bbc1072e1eb892dc37344ec8aca7b7154630a090 | [
"Apache-2.0"
] | null | null | null | fivm/test/java/src/com/fiji/fivm/test/MeasureTimeGaps.java | mihirlibran/cse605 | bbc1072e1eb892dc37344ec8aca7b7154630a090 | [
"Apache-2.0"
] | null | null | null | 36.85906 | 117 | 0.628915 | 10,192 | /*
* MeasureTimeGaps.java
* Copyright 2008, 2009, 2010, 2011, 2012, 2013 Fiji Systems Inc.
* This file is part of the FIJI VM Software licensed under the FIJI PUBLIC
* LICENSE Version 3 or any later version. A copy of the FIJI PUBLIC LICENSE is
* available at fivm/LEGAL and can also be found at
* http://www.fiji-systems.com/FPL3.txt
*
* By installing, reproducing, distributing, and/or using the FIJI VM Software
* you agree to the terms of the FIJI PUBLIC LICENSE. You may exercise the
* rights granted under the FIJI PUBLIC LICENSE subject to the conditions and
* restrictions stated therein. Among other conditions and restrictions, the
* FIJI PUBLIC LICENSE states that:
*
* a. You may only make non-commercial use of the FIJI VM Software.
*
* b. Any adaptation you make must be licensed under the same terms
* of the FIJI PUBLIC LICENSE.
*
* c. You must include a copy of the FIJI PUBLIC LICENSE in every copy of any
* file, adaptation or output code that you distribute and cause the output code
* to provide a notice of the FIJI PUBLIC LICENSE.
*
* d. You must not impose any additional conditions.
*
* e. You must not assert or imply any connection, sponsorship or endorsement by
* the author of the FIJI VM Software
*
* f. You must take no derogatory action in relation to the FIJI VM Software
* which would be prejudicial to the FIJI VM Software author's honor or
* reputation.
*
*
* The FIJI VM Software is provided as-is. FIJI SYSTEMS INC does not make any
* representation and provides no warranty of any kind concerning the software.
*
* The FIJI PUBLIC LICENSE and any rights granted therein terminate
* automatically upon any breach by you of the terms of the FIJI PUBLIC LICENSE.
*/
package com.fiji.fivm.test;
import com.fiji.util.*;
import com.fiji.fivm.*;
import com.fiji.fivm.util.*;
import com.fiji.fivm.r1.*;
public class MeasureTimeGaps {
@RuntimeImport
static native long fivmr_readCPUTimestamp();
@RuntimeImport
static native boolean fivmr_cpuTimestampIsFast();
static long preciseTime() {
if (fivmr_cpuTimestampIsFast()) {
return fivmr_readCPUTimestamp();
} else {
return Time.nanoTimePrecise();
}
}
public static void main(String[] v) throws Exception {
if (v.length!=3) {
System.err.println("Usage: MeasureTimeGaps <number of samples> <threshold> <name>");
System.err.println("Warning: only use this from MeasureTimeSlicingGaps");
System.exit(1);
}
int n=Integer.parseInt(v[0]);
long threshold=Long.parseLong(v[1]);
String name=v[2];
System.out.println(name+" starting!");
double convFactor=1.0;
if (fivmr_cpuTimestampIsFast()) {
System.out.println(name+" using CPU timestamp; measuring it.");
long beforeCPU=fivmr_readCPUTimestamp();
long beforeOS=Time.nanoTimePrecise();
Thread.sleep(20000);
long afterCPU=fivmr_readCPUTimestamp();
long afterOS=Time.nanoTimePrecise();
convFactor=
((double)(afterOS-beforeOS))/
((double)(afterCPU-beforeCPU));
System.out.println("conversion factor (CPU -> real): "+
convFactor);
}
Thread.currentThread().setPriority(ThreadPriority.MAX_PRIORITY);
Addable times;
Addable preciseTimes;
try {
times=new HistoStats(0,100000/40,210*40);
preciseTimes=new HistoStats(0,(long)(100000/40*convFactor),210*40);
} catch (OutOfMemoryError e) {
times=new SimpleStats();
preciseTimes=new SimpleStats();
}
MixingDebug preciseTimesMix=new MixingDebug(3);
long pollchecksTakenBefore=PollcheckStats.pollchecksTaken();
long lastTime=System.nanoTime();
long lastTimePrecise=preciseTime();
while (n-->0) {
long curTime=System.nanoTime();
if (curTime-lastTime >= threshold || threshold<0) {
times.add(curTime-lastTime);
}
lastTime=curTime;
long curTimePrecise=preciseTime();
// creepy horrible work-around for RTEMS time bugs
if (curTimePrecise<lastTimePrecise) {
Time.nanoTimePrecise();
lastTimePrecise=Time.nanoTimePrecise();
continue;
}
if (curTimePrecise-lastTimePrecise >= threshold || threshold<0) {
preciseTimes.add(curTimePrecise-lastTimePrecise);
}
preciseTimesMix.add(curTimePrecise-lastTimePrecise);
lastTimePrecise=curTimePrecise;
}
long pollchecksTakenAfter=PollcheckStats.pollchecksTaken();
System.out.println(name+": Pollchecks taken total so far: "+pollchecksTakenAfter);
System.out.println(name+": Pollchecks taken during test run: "+(pollchecksTakenAfter-pollchecksTakenBefore));
System.out.println(name+": Gap statistics for >= "+threshold+": "+times);
System.out.println(name+": Precise gap statistics for >= "+threshold+" :"+preciseTimes);
System.out.println(name+": Mixing Debug: "+preciseTimesMix);
}
}
|
3e17e7346a9dcb50ced5ff1d95d1f4583fb9339a | 4,632 | java | Java | md2x/src/main/java/top/touchface/md2x/utils/Helper.java | touchface/md2x | 5db815766fddbd98e68c15fc6948c239c5d41735 | [
"MIT"
] | 21 | 2018-09-27T12:40:53.000Z | 2021-12-11T05:11:10.000Z | md2x/src/main/java/top/touchface/md2x/utils/Helper.java | touchface/md2x | 5db815766fddbd98e68c15fc6948c239c5d41735 | [
"MIT"
] | 1 | 2018-12-29T07:00:44.000Z | 2018-12-29T07:00:44.000Z | md2x/src/main/java/top/touchface/md2x/utils/Helper.java | touchface/md2x | 5db815766fddbd98e68c15fc6948c239c5d41735 | [
"MIT"
] | 2 | 2019-11-22T07:52:59.000Z | 2019-12-08T06:53:54.000Z | 28.770186 | 112 | 0.435881 | 10,193 | package top.touchface.md2x.utils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* 工具类
*
* @author touchface
* date 2018-09-26 21:38
*/
public class Helper {
/**
* 解析表格
*
* @param tableRow 表格一行的Markdown标记
* @param count 表格的列数
* @return 分割好的表格内容
*/
public static List<String> splitCells(String tableRow, int count) {
String cells[] = tableRow.replaceAll("([^\\\\])\\|", "$1 |").split(" +\\| *");
for (int i = 0; i < cells.length; i++) {
cells[i] = cells[i].replaceAll("\\\\\\|", "|");
}
List<String> lcells = StringUtils.arrayToList(cells);
if (lcells.size() > count) {
lcells = lcells.subList(0, count);
} else {
while (lcells.size() < count) {
lcells.add("");
}
}
return lcells;
}
/**
* 分割单元格
*
* @param tableRow 表格一行的Markdown标记
* @return 分割好的表格内容
*/
public static List<String> splitCells(String tableRow) {
String cells[] = tableRow.replaceAll("([^\\\\])\\|", "$1 |").split(" +\\| *");
for (int i = 0; i < cells.length; i++) {
cells[i] = cells[i].replaceAll("\\\\\\|", "|");
}
return StringUtils.arrayToList(cells);
}
/**
* 解析单元格的居中方式,将单元格中的居中方式转换为left center right
*
* @param align 控制单元格居中方式的表格项目
*/
public static void parseCellsAlign(List<String> align) {
if (align == null) {
return;
}
for (int i = 0; i < align.size(); i++) {
if (RegexUtils.test("^ *-+: *$", align.get(i))) {
align.set(i, "right");
} else if (RegexUtils.test("^ *:-+: *$", align.get(i))) {
align.set(i, "center");
} else if (RegexUtils.test("^ *:-+ *$", align.get(i))) {
align.set(i, "left");
} else {
align.set(i, null);
}
}
}
/**
* @param html html文本
* @param encode 是否编码
* @return 编码后的字符串
*/
public static String escape(String html, boolean encode) {
return html.replaceAll(!encode ? "&(?!#?\\w+;)" : "&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll("\"", """)
.replaceAll("'", "'");
}
/**
* 解码操作
*
* @param html 需要进行解码的html文本
* @return 解码后的文本
*/
public static String unescape(String html) {
html = RegexUtils.replaceAll(html,
"&(#(?:\\d+)|(?:#x[0-9A-Fa-f]+)|(?:\\w+));?",
Pattern.CASE_INSENSITIVE, 1, (index, text) -> {
text = text.toLowerCase();
if (text.equals("colon")) {
return "|";
}
if (text.charAt(0) == '#') {
return text.charAt(1) == 'x' ? "" + (char) (int) Integer.valueOf(text.substring(2), 16)
: "" + (char) (int) Integer.valueOf(text.substring(1));
}
return "";
});
return html;
}
// 创建一个Map对象用于存放对象正确的根路径
private static Map<String, String> baseUrls;
static {
baseUrls = new HashMap<>();
}
/**
* 判断路径是否为完整的链接
* 如果是完整的链接返回true
* 否则返回false
*
* @param href 测试的路径
* @return 结果
*/
public static boolean originIndependentUrl(String href) {
return RegexUtils.test("^$|^[a-z][a-z0-9+.-]*:|^[?#]", Pattern.CASE_INSENSITIVE, href);
}
/**
* 生成完整的路径
*
* @param base 根路径
* @param href 路径
* @return 完整路径
*/
public static String resolveUrl(String base, String href) {
if (!baseUrls.containsKey(base)) {
if (RegexUtils.test("^[^:]+:\\/*[^/]*$", base)) {
baseUrls.put(base, base + "/");
} else {
baseUrls.put(base, base.replaceAll("[^/]*$", ""));
}
}
base = baseUrls.get(base);
href = href.replace("\\", "/");
if (href.substring(0, 2).equals("//")) {
return base.replaceAll(":[\\s\\S]*", ":") + href;
} else if (href.charAt(0) == '/') {
return base.replaceAll("(:/*[^/]*)[\\s\\S]*", "$1") + href;
} else {
return base + href;
}
}
}
|
3e17e7542a248aa5ff92e24c25e95e94745efd57 | 1,887 | java | Java | ui-adjustment-release-library/src/main/java/com/thekhaeng/library/uiadjustment/release/UIFragmentAdjustment.java | TheKhaeng/ui-adjustment-library | 258776d9cc557c48739c6c196894d8e2ec353ed1 | [
"Apache-2.0"
] | 8 | 2018-03-08T08:53:05.000Z | 2020-10-26T18:55:53.000Z | ui-adjustment-release-library/src/main/java/com/thekhaeng/library/uiadjustment/release/UIFragmentAdjustment.java | TheKhaeng/ui-adjustment-library | 258776d9cc557c48739c6c196894d8e2ec353ed1 | [
"Apache-2.0"
] | null | null | null | ui-adjustment-release-library/src/main/java/com/thekhaeng/library/uiadjustment/release/UIFragmentAdjustment.java | TheKhaeng/ui-adjustment-library | 258776d9cc557c48739c6c196894d8e2ec353ed1 | [
"Apache-2.0"
] | 2 | 2018-03-11T15:45:46.000Z | 2019-04-23T02:54:35.000Z | 23.296296 | 109 | 0.683095 | 10,194 | package com.thekhaeng.library.uiadjustment.release;
import android.annotation.SuppressLint;
import android.graphics.Color;
import android.support.annotation.ColorInt;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.TextView;
import com.thekhaeng.library.uiadjustment.core.UIAdjustmentInterface;
/**
* Created by The Khaeng on 15 Feb 2018 :)
*/
public abstract class UIFragmentAdjustment<A extends Fragment>
implements UIAdjustmentInterface{
public UIFragmentAdjustment( A fragment, View button ){
button.setVisibility( View.GONE );
}
@Override
public UIAdjustmentInterface setTitle( String title ){
// do nothing
return this;
}
@Override
public UIAdjustmentInterface setDelayMillisTime( long delay ){
return this;
}
@Override
public UIAdjustmentInterface setUseLocalStorage( boolean useLocalStorage, boolean bindDataImmediately ){
return this;
}
@Override
public UIAdjustmentInterface showKeepActivityGlobalSetting( TextView textView ){
showKeepActivityGlobalSetting( textView, Color.TRANSPARENT );
return this;
}
@SuppressLint( "SetTextI18n" )
@Override
public UIAdjustmentInterface showKeepActivityGlobalSetting( TextView textView, @ColorInt int textColor ){
textView.setVisibility( View.GONE );
return this;
}
@Override
public void onBoolean( int id, boolean value ){
// do nothing
}
@Override
public void onColor( int id, int value ){
// do nothing
}
@Override
public void onInteger( int id, int value ){
// do nothing
}
@Override
public void onRangeFloat( int id, float value ){
// do nothing
}
@Override
public void onString( int id, String value ){
// do nothing
}
}
|
3e17e94b5f5ec66745f76a9c25900764acf05491 | 1,986 | java | Java | src/leetcode/problem_0211/Solution.java | husaynhakeem/Algorithms-Playground | 25dc5a7688f49b473c004dd90a7536417655ba5a | [
"MIT"
] | 25 | 2018-09-27T10:00:38.000Z | 2022-01-19T10:54:24.000Z | src/leetcode/problem_0211/Solution.java | husaynhakeem/Algorithms-Playground | 25dc5a7688f49b473c004dd90a7536417655ba5a | [
"MIT"
] | null | null | null | src/leetcode/problem_0211/Solution.java | husaynhakeem/Algorithms-Playground | 25dc5a7688f49b473c004dd90a7536417655ba5a | [
"MIT"
] | 12 | 2018-10-30T18:14:52.000Z | 2021-09-14T13:53:16.000Z | 28.782609 | 97 | 0.415408 | 10,195 | package leetcode.problem_0211;
class Solution {
private Trie trie = new Trie();
void addWord(String word) {
trie.add(word);
}
boolean search(String word) {
return trie.search(word);
}
private class TrieNode {
char value;
boolean isLeaf;
TrieNode[] nodes = new TrieNode[26];
TrieNode(final char value) {
this.value = value;
}
}
private class Trie {
private TrieNode root = new TrieNode(' ');
void add(final String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (node.nodes[c - 'a'] == null) {
node.nodes[c - 'a'] = new TrieNode(c);
}
node = node.nodes[c - 'a'];
}
node.isLeaf = true;
}
boolean search(final String word) {
return search(word, root);
}
private boolean search(final String word, final TrieNode root) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
final char c = word.charAt(i);
if (c != '.') {
if (node.nodes[c - 'a'] == null) {
return false;
}
node = node.nodes[c - 'a'];
} else {
for (char anyChar = 'a'; anyChar <= 'z'; anyChar = (char) (anyChar + 1)) {
final TrieNode anyCharNode = node.nodes[anyChar - 'a'];
if (anyCharNode != null) {
final boolean foundWord = search(word.substring(i + 1), anyCharNode);
if (foundWord) {
return true;
}
}
}
return false;
}
}
return node.isLeaf;
}
}
}
|
3e17e9841285aed82588405154c85c2e0d509950 | 6,835 | java | Java | src/test/java/com/amazon/opendistroforelasticsearch/ad/stats/ADStatsTests.java | gaiksaya/anomaly-detection | 76589fef0144da4ab3b933e1c99c17ba53305944 | [
"ECL-2.0",
"Apache-2.0"
] | 82 | 2019-11-26T22:55:03.000Z | 2022-01-20T12:44:10.000Z | src/test/java/com/amazon/opendistroforelasticsearch/ad/stats/ADStatsTests.java | gaiksaya/anomaly-detection | 76589fef0144da4ab3b933e1c99c17ba53305944 | [
"ECL-2.0",
"Apache-2.0"
] | 284 | 2019-12-03T18:59:27.000Z | 2022-03-25T20:50:26.000Z | src/test/java/com/amazon/opendistroforelasticsearch/ad/stats/ADStatsTests.java | gaiksaya/anomaly-detection | 76589fef0144da4ab3b933e1c99c17ba53305944 | [
"ECL-2.0",
"Apache-2.0"
] | 41 | 2019-12-03T18:46:10.000Z | 2022-03-28T15:49:30.000Z | 39.057143 | 140 | 0.685004 | 10,196 | /*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazon.opendistroforelasticsearch.ad.stats;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.elasticsearch.test.ESTestCase;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import test.com.amazon.opendistroforelasticsearch.ad.util.MLUtil;
import com.amazon.opendistroforelasticsearch.ad.caching.CacheProvider;
import com.amazon.opendistroforelasticsearch.ad.caching.EntityCache;
import com.amazon.opendistroforelasticsearch.ad.ml.EntityModel;
import com.amazon.opendistroforelasticsearch.ad.ml.HybridThresholdingModel;
import com.amazon.opendistroforelasticsearch.ad.ml.ModelManager;
import com.amazon.opendistroforelasticsearch.ad.ml.ModelState;
import com.amazon.opendistroforelasticsearch.ad.stats.suppliers.CounterSupplier;
import com.amazon.opendistroforelasticsearch.ad.stats.suppliers.IndexStatusSupplier;
import com.amazon.opendistroforelasticsearch.ad.stats.suppliers.ModelsOnNodeSupplier;
import com.amazon.opendistroforelasticsearch.ad.util.IndexUtils;
import com.amazon.randomcutforest.RandomCutForest;
public class ADStatsTests extends ESTestCase {
private Map<String, ADStat<?>> statsMap;
private ADStats adStats;
private RandomCutForest rcf;
private HybridThresholdingModel thresholdingModel;
private String clusterStatName1, clusterStatName2;
private String nodeStatName1, nodeStatName2;
@Mock
private Clock clock;
@Mock
private ModelManager modelManager;
@Mock
private CacheProvider cacheProvider;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
rcf = RandomCutForest.builder().dimensions(1).sampleSize(1).numberOfTrees(1).build();
thresholdingModel = new HybridThresholdingModel(1e-8, 1e-5, 200, 10_000, 2, 5_000_000);
List<ModelState<?>> modelsInformation = new ArrayList<>(
Arrays
.asList(
new ModelState<>(rcf, "rcf-model-1", "detector-1", ModelManager.ModelType.RCF.getName(), clock, 0f),
new ModelState<>(thresholdingModel, "thr-model-1", "detector-1", ModelManager.ModelType.RCF.getName(), clock, 0f),
new ModelState<>(rcf, "rcf-model-2", "detector-2", ModelManager.ModelType.THRESHOLD.getName(), clock, 0f),
new ModelState<>(thresholdingModel, "thr-model-2", "detector-2", ModelManager.ModelType.THRESHOLD.getName(), clock, 0f)
)
);
when(modelManager.getAllModels()).thenReturn(modelsInformation);
ModelState<EntityModel> entityModel1 = MLUtil.randomNonEmptyModelState();
ModelState<EntityModel> entityModel2 = MLUtil.randomNonEmptyModelState();
List<ModelState<?>> entityModelsInformation = new ArrayList<>(Arrays.asList(entityModel1, entityModel2));
EntityCache cache = mock(EntityCache.class);
when(cacheProvider.get()).thenReturn(cache);
when(cache.getAllModels()).thenReturn(entityModelsInformation);
IndexUtils indexUtils = mock(IndexUtils.class);
when(indexUtils.getIndexHealthStatus(anyString())).thenReturn("yellow");
when(indexUtils.getNumberOfDocumentsInIndex(anyString())).thenReturn(100L);
clusterStatName1 = "clusterStat1";
clusterStatName2 = "clusterStat2";
nodeStatName1 = "nodeStat1";
nodeStatName2 = "nodeStat2";
statsMap = new HashMap<String, ADStat<?>>() {
{
put(nodeStatName1, new ADStat<>(false, new CounterSupplier()));
put(nodeStatName2, new ADStat<>(false, new ModelsOnNodeSupplier(modelManager, cacheProvider)));
put(clusterStatName1, new ADStat<>(true, new IndexStatusSupplier(indexUtils, "index1")));
put(clusterStatName2, new ADStat<>(true, new IndexStatusSupplier(indexUtils, "index2")));
}
};
adStats = new ADStats(indexUtils, modelManager, statsMap);
}
@Test
public void testStatNamesGetNames() {
assertEquals("getNames of StatNames returns the incorrect number of stats", StatNames.getNames().size(), StatNames.values().length);
}
@Test
public void testGetStats() {
Map<String, ADStat<?>> stats = adStats.getStats();
assertEquals("getStats returns the incorrect number of stats", stats.size(), statsMap.size());
for (Map.Entry<String, ADStat<?>> stat : stats.entrySet()) {
assertTrue(
"getStats returns incorrect stats",
adStats.getStats().containsKey(stat.getKey()) && adStats.getStats().get(stat.getKey()) == stat.getValue()
);
}
}
@Test
public void testGetStat() {
ADStat<?> stat = adStats.getStat(clusterStatName1);
assertTrue(
"getStat returns incorrect stat",
adStats.getStats().containsKey(clusterStatName1) && adStats.getStats().get(clusterStatName1) == stat
);
}
@Test
public void testGetNodeStats() {
Map<String, ADStat<?>> stats = adStats.getStats();
Set<ADStat<?>> nodeStats = new HashSet<>(adStats.getNodeStats().values());
for (ADStat<?> stat : stats.values()) {
assertTrue(
"getNodeStats returns incorrect stat",
(stat.isClusterLevel() && !nodeStats.contains(stat)) || (!stat.isClusterLevel() && nodeStats.contains(stat))
);
}
}
@Test
public void testGetClusterStats() {
Map<String, ADStat<?>> stats = adStats.getStats();
Set<ADStat<?>> clusterStats = new HashSet<>(adStats.getClusterStats().values());
for (ADStat<?> stat : stats.values()) {
assertTrue(
"getClusterStats returns incorrect stat",
(stat.isClusterLevel() && clusterStats.contains(stat)) || (!stat.isClusterLevel() && !clusterStats.contains(stat))
);
}
}
}
|
3e17e9d9afab49e0454aa5249d6b59eb6a4282eb | 1,616 | java | Java | src/test/java/slenium_java_training_ymbelyakova/DeleteMovie.java | ymbelyakova/selenium_java_training_ymbelyakova_lesson1 | 3da2241cb3f69befd4e15072c82955bfaa70d36f | [
"Apache-2.0"
] | null | null | null | src/test/java/slenium_java_training_ymbelyakova/DeleteMovie.java | ymbelyakova/selenium_java_training_ymbelyakova_lesson1 | 3da2241cb3f69befd4e15072c82955bfaa70d36f | [
"Apache-2.0"
] | null | null | null | src/test/java/slenium_java_training_ymbelyakova/DeleteMovie.java | ymbelyakova/selenium_java_training_ymbelyakova_lesson1 | 3da2241cb3f69befd4e15072c82955bfaa70d36f | [
"Apache-2.0"
] | null | null | null | 29.925926 | 100 | 0.689975 | 10,197 | package slenium_java_training_ymbelyakova;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.testng.*;
import org.testng.annotations.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class DeleteMovie extends selenium_java_training.TestBase {
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
@Test
public void testDeleteMovie() throws Exception {
driver.get(baseUrl + "/php4dvd/");
driver.findElement(By.cssSelector("div[class=\"title\"]")).click();
// Warning: verifyTextPresent may require manual changes
try {
assertTrue(driver.findElement(By.cssSelector("BODY")).getText().matches("Comedy"));
} catch (Error e) {
verificationErrors.append(e.toString());
}
driver.findElement(By.linkText("Remove")).click();
assertTrue(closeAlertAndGetItsText().matches("^Are you sure you want to remove this[\\s\\S]$"));
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
} |
3e17eab2ebda6164c78da809f1de5f4e678f414e | 4,039 | java | Java | eladmin-system/src/main/java/com/hqhop/modules/company/rest/ContactController.java | TomZhang187/mdm | de3b400a263e63b014f8c4cb63e3ad7410a2d9cc | [
"Apache-2.0"
] | null | null | null | eladmin-system/src/main/java/com/hqhop/modules/company/rest/ContactController.java | TomZhang187/mdm | de3b400a263e63b014f8c4cb63e3ad7410a2d9cc | [
"Apache-2.0"
] | null | null | null | eladmin-system/src/main/java/com/hqhop/modules/company/rest/ContactController.java | TomZhang187/mdm | de3b400a263e63b014f8c4cb63e3ad7410a2d9cc | [
"Apache-2.0"
] | null | null | null | 36.0625 | 121 | 0.720971 | 10,198 | package com.hqhop.modules.company.rest;
import com.hqhop.aop.log.Log;
import com.hqhop.common.dingtalk.dingtalkVo.DingUser;
import com.hqhop.modules.company.domain.Contact;
import com.hqhop.modules.company.repository.ContactRepository;
import com.hqhop.modules.company.service.ContactDingService;
import com.hqhop.modules.company.service.ContactService;
import com.hqhop.modules.company.service.dto.ContactQueryCriteria;
import com.taobao.api.ApiException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
* @author zf
* @date 2019-10-22
*/
@Api(tags = "Contact管理")
@RestController
@RequestMapping("api")
public class ContactController {
@Autowired
private ContactService contactService;
@Autowired
private ContactDingService contactDingService;
@Autowired
private ContactRepository contactRepository;
@Log("查询Contact")
@ApiOperation(value = "查询Contact")
@GetMapping(value = "/contact")
// @PreAuthorize("hasAnyRole('ADMIN','CONTACT_ALL','CONTACT_SELECT')")
public ResponseEntity getContacts(ContactQueryCriteria criteria, Pageable pageable){
return new ResponseEntity(contactService.queryAll(criteria,pageable),HttpStatus.OK);
}
@Log("新增Contact")
@ApiOperation(value = "新增Contact")
@PostMapping(value = "/contact")
@PreAuthorize("hasAnyRole('ADMIN','CONTACT_ALL','CONTACT_CREATE')")
public ResponseEntity create(@Validated @RequestBody Contact resources){
return new ResponseEntity(contactService.create(resources),HttpStatus.CREATED);
}
@Log("修改Contact")
@ApiOperation(value = "修改Contact")
@PutMapping(value = "/contact")
@PreAuthorize("hasAnyRole('ADMIN','CONTACT_ALL','CONTACT_EDIT')")
public ResponseEntity update(@Validated @RequestBody Contact resources){
contactService.update(resources);
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
@Log("删除Contact")
@ApiOperation(value = "删除Contact")
@DeleteMapping(value = "/contact/{contactKey}")
@PreAuthorize("hasAnyRole('ADMIN','CONTACT_ALL','CONTACT_DELETE')")
public ResponseEntity delete(@PathVariable Long contactKey){
contactService.delete(contactKey);
return new ResponseEntity(HttpStatus.OK);
}
@Log("联系人审批接口")
@ApiOperation(value = "联系人审批接口")
@GetMapping(value = "/contactApproval")
// @PreAuthorize("hasAnyRole('ADMIN','COMPANYINFO_ALL','COMPANYINFO_SELECT')")
public ResponseEntity addApproval(DingUser dingUser, Contact resouces)throws
ApiException {
if (resouces.getContactKey() != null && !"".equals(resouces.getContactKey()) && resouces.getContactState()==4 ) {
if(resouces.getContactName() != null && !"".equals(resouces.getContactName())){
//修改审批调用
contactDingService.updateApproval(resouces,dingUser);
}else {
//解除绑定审批
Contact contact = contactRepository.getOne(resouces.getContactKey());
contactDingService.removeApproval(contact,dingUser);
}
} else {
//新增审批调用
contactDingService.addApprovel(resouces,dingUser);
}
return new ResponseEntity(HttpStatus.OK);
}
@Log("获取联系人审批链接getDingUrl")
@ApiOperation(value = "获取联系人审批链接getDingUrl")
@GetMapping(value = "/contactDingUrl")
// @PreAuthorize("hasAnyRole('ADMIN','COMPANYUPDATE_ALL','COMPANYUPDATE_CREATE')")
public ResponseEntity getContactDingUrl(Contact resources,DingUser dingUser){
return new ResponseEntity(contactService.getDingUrl(resources,dingUser),HttpStatus.CREATED);
}
}
|
3e17ec9ebdb7d811dfb636599823fd401cc37411 | 9,084 | java | Java | commercetools-models/src/test/java/io/sphere/sdk/categories/CategoriesCustomFieldsIntegrationTest.java | FL-K/commercetools-jvm-sdk | 6c3ba0d2e29e2f9c1a4054d99ea1e3ba8cf323ac | [
"Apache-2.0"
] | null | null | null | commercetools-models/src/test/java/io/sphere/sdk/categories/CategoriesCustomFieldsIntegrationTest.java | FL-K/commercetools-jvm-sdk | 6c3ba0d2e29e2f9c1a4054d99ea1e3ba8cf323ac | [
"Apache-2.0"
] | null | null | null | commercetools-models/src/test/java/io/sphere/sdk/categories/CategoriesCustomFieldsIntegrationTest.java | FL-K/commercetools-jvm-sdk | 6c3ba0d2e29e2f9c1a4054d99ea1e3ba8cf323ac | [
"Apache-2.0"
] | null | null | null | 53.122807 | 170 | 0.687913 | 10,199 | package io.sphere.sdk.categories;
import com.fasterxml.jackson.core.type.TypeReference;
import io.sphere.sdk.categories.commands.CategoryCreateCommand;
import io.sphere.sdk.categories.commands.CategoryDeleteCommand;
import io.sphere.sdk.categories.commands.CategoryUpdateCommand;
import io.sphere.sdk.categories.commands.updateactions.SetCustomField;
import io.sphere.sdk.categories.commands.updateactions.SetCustomType;
import io.sphere.sdk.categories.queries.CategoryByIdGet;
import io.sphere.sdk.categories.queries.CategoryQuery;
import io.sphere.sdk.client.ErrorResponseException;
import io.sphere.sdk.expansion.ExpansionPath;
import io.sphere.sdk.json.TypeReferences;
import io.sphere.sdk.models.LocalizedString;
import io.sphere.sdk.models.Reference;
import io.sphere.sdk.models.TextInputHint;
import io.sphere.sdk.models.errors.RequiredField;
import io.sphere.sdk.test.IntegrationTest;
import io.sphere.sdk.types.*;
import io.sphere.sdk.types.commands.TypeCreateCommand;
import io.sphere.sdk.types.commands.TypeDeleteCommand;
import org.junit.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import static io.sphere.sdk.categories.CategoryFixtures.withCategory;
import static io.sphere.sdk.test.SphereTestUtils.*;
import static io.sphere.sdk.types.TypeFixtures.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class CategoriesCustomFieldsIntegrationTest extends IntegrationTest {
public static final Map<String, Object> CUSTOM_FIELDS_MAP = Collections.singletonMap(STRING_FIELD_NAME, "hello");
public static final TypeReference<Reference<Category>> TYPE_REFERENCE = new TypeReference<Reference<Category>>() {
};
@Test
public void createCategoryWithCustomTypeById() {
createCategoryWithCustomType(type -> CustomFieldsDraftBuilder.ofTypeId(type.getId()));
}
@Test
public void createCategoryWithCustomTypeByKey() {
createCategoryWithCustomType(type -> CustomFieldsDraftBuilder.ofTypeKey(type.getKey()));
}
private void createCategoryWithCustomType(final Function<Type, CustomFieldsDraftBuilder> draftCreator) {
withUpdateableType(client(), type -> {
final CustomFieldsDraftBuilder customFieldsDraftBuilder = draftCreator.apply(type);
final CustomFieldsDraft customFieldsDraft = customFieldsDraftBuilder.addObject(STRING_FIELD_NAME, "a value").build();
final CategoryDraft categoryDraft = CategoryDraftBuilder.of(randomSlug(), randomSlug()).custom(customFieldsDraft).build();
final Category category = client().executeBlocking(CategoryCreateCommand.of(categoryDraft));
assertThat(category.getCustom().getField(STRING_FIELD_NAME, TypeReferences.stringTypeReference())).isEqualTo("a value");
final Category updatedCategory = client().executeBlocking(CategoryUpdateCommand.of(category, SetCustomField.ofObject(STRING_FIELD_NAME, "a new value")));
assertThat(updatedCategory.getCustom().getField(STRING_FIELD_NAME, TypeReferences.stringTypeReference())).isEqualTo("a new value");
//clean up
client().executeBlocking(CategoryDeleteCommand.of(updatedCategory));
return type;
});
}
@Test
public void setCustomTypeById() {
setCustomType(type -> SetCustomType.ofTypeIdAndObjects(type.getId(), CUSTOM_FIELDS_MAP));
}
@Test
public void setCustomTypeByKey() {
setCustomType(type -> SetCustomType.ofTypeKeyAndObjects(type.getKey(), CUSTOM_FIELDS_MAP));
}
private void setCustomType(final Function<Type, SetCustomType> updateActionCreator) {
withUpdateableType(client(), type -> {
withCategory(client(), category -> {
final SetCustomType updateAction = updateActionCreator.apply(type);
final Category updatedCategory = client().executeBlocking(CategoryUpdateCommand.of(category, updateAction));
assertThat(updatedCategory.getCustom().getType()).isEqualTo(type.toReference());
assertThat(updatedCategory.getCustom().getField(STRING_FIELD_NAME, TypeReferences.stringTypeReference())).isEqualTo("hello");
final Category updated2 = client().executeBlocking(CategoryUpdateCommand.of(updatedCategory, SetCustomType.ofRemoveType()));
assertThat(updated2.getCustom()).isNull();
});
return type;
});
}
@Test
public void referenceExpansion() {
withUpdateableType(client(), type -> {
withCategory(client(), referencedCategory -> {
withCategory(client(), category -> {
final Map<String, Object> fields = Collections.singletonMap(CAT_REFERENCE_FIELD_NAME, referencedCategory.toReference());
final CategoryUpdateCommand categoryUpdateCommand = CategoryUpdateCommand.of(category, SetCustomType.ofTypeIdAndObjects(type.getId(), fields));
final ExpansionPath<Category> expansionPath = ExpansionPath.of("custom.fields." + CAT_REFERENCE_FIELD_NAME);
final Category updatedCategory = client().executeBlocking(categoryUpdateCommand.withExpansionPaths(expansionPath));
final Reference<Category> createdReference = updatedCategory.getCustom().getField(CAT_REFERENCE_FIELD_NAME, TYPE_REFERENCE);
assertThat(createdReference).isEqualTo(referencedCategory.toReference());
assertThat(createdReference.getObj()).isNotNull();
final Category loadedCat = client().executeBlocking(CategoryByIdGet.of(updatedCategory)
.withExpansionPaths(expansionPath));
assertThat(loadedCat.getCustom().getField(CAT_REFERENCE_FIELD_NAME, TYPE_REFERENCE).getObj())
.overridingErrorMessage("is expanded")
.isNotNull();
final Category updated2 = client().executeBlocking(CategoryUpdateCommand.of(updatedCategory, SetCustomType.ofRemoveType()));
assertThat(updated2.getCustom()).isNull();
});
});
return type;
});
}
@Test
public void requiredValidation() {
final FieldDefinition stringFieldDefinition =
FieldDefinition.of(StringFieldType.of(), STRING_FIELD_NAME, en("label"), true, TextInputHint.SINGLE_LINE);
final String typeKey = randomKey();
final TypeDraft typeDraft = TypeDraftBuilder.of(typeKey, en("name of the custom type"), TYPE_IDS)
.description(en("description"))
.fieldDefinitions(asList(stringFieldDefinition))
.build();
final Type type = client().executeBlocking(TypeCreateCommand.of(typeDraft));
withCategory(client(), category -> {
assertThatThrownBy(() -> client().executeBlocking(CategoryUpdateCommand.of(category, SetCustomType.ofTypeIdAndObjects(type.getId(), Collections.emptyMap()))))
.isInstanceOf(ErrorResponseException.class)
.matches(e -> {
final ErrorResponseException errorResponseException = (ErrorResponseException) e;
final String errorCode = RequiredField.CODE;
return errorResponseException.hasErrorCode(errorCode)
&& errorResponseException.getErrors().stream()
.filter(err -> err.getCode().equals(errorCode))
.anyMatch(err -> STRING_FIELD_NAME.equals(err.as(RequiredField.class).getField()));
});
});
client().executeBlocking(TypeDeleteCommand.of(type));
}
@Test
public void queryByField() {
withUpdateableType(client(), type -> {
withCategory(client(), category -> {
final Map<String, Object> fields = new HashMap<>();
fields.put(STRING_FIELD_NAME, "foo");
fields.put(LOC_STRING_FIELD_NAME, LocalizedString.of(ENGLISH, "bar"));
final CategoryUpdateCommand categoryUpdateCommand = CategoryUpdateCommand.of(category, SetCustomType.ofTypeIdAndObjects(type.getId(), fields));
final Category updatedCategory = client().executeBlocking(categoryUpdateCommand);
final CategoryQuery categoryQuery = CategoryQuery.of()
.plusPredicates(m -> m.is(category))
.plusPredicates(m -> m.custom().fields().ofString(STRING_FIELD_NAME).is("foo"))
.plusPredicates(m -> m.custom().fields().ofString("njetpresent").isNotPresent())
.plusPredicates(m -> m.custom().fields().ofLocalizedString(LOC_STRING_FIELD_NAME).locale(ENGLISH).is("bar"));
assertThat(client().executeBlocking(categoryQuery).head()).contains(updatedCategory);
});
return type;
});
}
}
|
3e17ed6d70b4f88463116fb5c6e6321f78c2cf13 | 1,475 | java | Java | src/main/java/uk/gov/hmcts/cmc/claimstore/events/claim/BreathingSpaceEvent.java | ManishParyani/cmc-claim-store | 4b96a674dd27c54f8491d587576ad26b38159bb9 | [
"MIT"
] | 13 | 2017-11-04T16:52:53.000Z | 2021-12-10T16:19:13.000Z | src/main/java/uk/gov/hmcts/cmc/claimstore/events/claim/BreathingSpaceEvent.java | ManishParyani/cmc-claim-store | 4b96a674dd27c54f8491d587576ad26b38159bb9 | [
"MIT"
] | 1,952 | 2017-09-13T10:36:57.000Z | 2022-03-07T10:32:44.000Z | src/main/java/uk/gov/hmcts/cmc/claimstore/events/claim/BreathingSpaceEvent.java | ManishParyani/cmc-claim-store | 4b96a674dd27c54f8491d587576ad26b38159bb9 | [
"MIT"
] | 18 | 2018-01-24T14:26:43.000Z | 2021-08-13T14:51:56.000Z | 32.065217 | 68 | 0.730847 | 10,200 | package uk.gov.hmcts.cmc.claimstore.events.claim;
import lombok.Getter;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import uk.gov.hmcts.cmc.ccd.domain.CCDCase;
import uk.gov.hmcts.cmc.domain.models.Claim;
import static uk.gov.hmcts.cmc.domain.utils.ToStringStyle.ourStyle;
@Getter
public class BreathingSpaceEvent {
protected final Claim claim;
protected final CCDCase ccdCase;
protected final String authorisation;
protected final String letterTemplateId;
protected final String claimantEmailTemplateId;
protected final String defendantEmailTemplateId;
protected final boolean enteredByCitizen;
protected final boolean bsLifted;
public BreathingSpaceEvent(
Claim claim,
CCDCase ccdCase,
String authorisation,
String letterTemplateId,
String claimantEmailTemplateId,
String defendantEmailTemplateId,
boolean enteredByCitizen,
boolean bsLifted
) {
this.claim = claim;
this.ccdCase = ccdCase;
this.authorisation = authorisation;
this.letterTemplateId = letterTemplateId;
this.claimantEmailTemplateId = claimantEmailTemplateId;
this.defendantEmailTemplateId = defendantEmailTemplateId;
this.enteredByCitizen = enteredByCitizen;
this.bsLifted = bsLifted;
}
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this, ourStyle());
}
}
|
3e17f0f9f9faf09a7ac6ce332b5445af9bd593a9 | 4,646 | java | Java | ir_core/src/edu/ur/ir/user/IrUserGroup.java | abhay123lp/irplus | fe811527115070e2a614a95d04006b2bdfccfb2d | [
"Apache-2.0"
] | 2 | 2020-04-01T08:51:58.000Z | 2020-12-04T18:45:54.000Z | ir_core/src/edu/ur/ir/user/IrUserGroup.java | abhay123lp/irplus | fe811527115070e2a614a95d04006b2bdfccfb2d | [
"Apache-2.0"
] | null | null | null | ir_core/src/edu/ur/ir/user/IrUserGroup.java | abhay123lp/irplus | fe811527115070e2a614a95d04006b2bdfccfb2d | [
"Apache-2.0"
] | 1 | 2021-12-28T16:05:41.000Z | 2021-12-28T16:05:41.000Z | 21.509259 | 76 | 0.633448 | 10,201 | /**
Copyright 2008 University of Rochester
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.ur.ir.user;
import java.util.Set;
import java.util.HashSet;
import java.util.Collections;
import edu.ur.ir.security.Sid;
import edu.ur.persistent.CommonPersistent;
/**
* Create a group of users for permissions.
*
* @author Nathan Sarr
*
*/
public class IrUserGroup extends CommonPersistent implements Sid{
/** type for this secure id */
public static final String GROUP_SID_TYPE = "GROUP_SID_TYPE";
/** Eclipse generated id. */
private static final long serialVersionUID = -4489281606591244383L;
/** Set of users who belong to this group. */
private Set<IrUser> users = new HashSet<IrUser>();
/** Users who can administer this user group */
private Set<IrUser> administrators = new HashSet<IrUser>();
/** Package protected constructor. */
IrUserGroup(){};
/**
* Default Public constructor.
*
* @param name of the group
*/
public IrUserGroup(String name)
{
this(name, null);
}
/**
* Default Public constructor.
*
* @param name of the group
*/
public IrUserGroup(String name, String description)
{
setName(name);
setDescription(description);
}
/**
* Get the users for this group.
*
* @return the users that are part of this group - as
* an unmodifiable list.
*/
public Set<IrUser> getUsers() {
return Collections.unmodifiableSet(users);
}
/**
* Add the user to this group.
*
* @param user - user to add to the group
*/
public void addUser(IrUser user)
{
users.add(user);
}
/**
* Remove user from this group
* @param user
*/
public boolean removeUser(IrUser user)
{
return users.remove(user);
}
/**
* Add the user to this group.
*
* @param user
*/
public void addAdministrator(IrUser user)
{
administrators.add(user);
}
/**
* Sets the name but also trims all white space to the left and right
* sides of the group name.
*
* @see edu.ur.persistent.CommonPersistent#setName(java.lang.String)
*/
public void setName(String name)
{
this.name = name.trim();
}
/**
* Remove user from this group
* @param user
*/
public boolean removeAdministrator(IrUser user)
{
return administrators.remove(user);
}
/**
* Set the users for this group.
*
* @param users
*/
void setUsers(Set<IrUser> users) {
this.users = users;
}
/**
*
* @see java.lang.Object#hashCode()
*/
public int hashCode()
{
int value = 0;
value += name == null ? 0 : name.hashCode();
return value;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object o)
{
if (this == o) return true;
if (!(o instanceof IrUserGroup)) return false;
final IrUserGroup other = (IrUserGroup) o;
if( ( name != null && !name.equals(other.getName()) ) ||
( name == null && other.getName() != null ) ) return false;
return true;
}
/**
* Return the string representation.
*
* @see java.lang.Object#toString()
*/
public String toString()
{
StringBuffer sb = new StringBuffer("[Name = ");
sb.append(name);
sb.append(" description ");
sb.append(description);
sb.append(" id = ");
sb.append(id);
sb.append(" version = ");
sb.append(version);
sb.append("]");
return sb.toString();
}
/**
* The sid type for this class.
*
* @see edu.ur.ir.security.Sid#getSidType()
*/
public String getSidType() {
return GROUP_SID_TYPE;
}
/**
* Get the list of group administrators - people who can
* administer the list.
*
* @return an Unmodifiable list of administrators
*/
public Set<IrUser> getAdministrators() {
return Collections.unmodifiableSet(administrators);
}
/**
* Set the list of administrators who can administer the list.
*
* @param administrators
*/
void setAdministrators(Set<IrUser> administrators) {
this.administrators = administrators;
}
}
|
3e17f13b89d81d9e836b2bf59a8f7155a8cf9b87 | 1,276 | java | Java | app/src/main/java/com/workable/movierama/utilities/MovieScrollListener.java | milouk/MovieRama | e5fdbc194da4eb1d6caddf39559609fca7b6df24 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/workable/movierama/utilities/MovieScrollListener.java | milouk/MovieRama | e5fdbc194da4eb1d6caddf39559609fca7b6df24 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/workable/movierama/utilities/MovieScrollListener.java | milouk/MovieRama | e5fdbc194da4eb1d6caddf39559609fca7b6df24 | [
"Apache-2.0"
] | null | null | null | 31.121951 | 84 | 0.700627 | 10,202 | package com.workable.movierama.utilities;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public abstract class MovieScrollListener extends RecyclerView.OnScrollListener {
private LinearLayoutManager layoutManager;
protected MovieScrollListener(LinearLayoutManager layoutManager) {
this.layoutManager = layoutManager;
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleItemCount = layoutManager.getChildCount();
int totalItemCount = layoutManager.getItemCount();
int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
if (!isLoading() && !isLastPage()) {
if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
&& firstVisibleItemPosition >= 0
&& totalItemCount >= getTotalPageCount()) {
loadMoreItems();
}
}
}
protected abstract void loadMoreItems();
public abstract int getTotalPageCount();
public abstract boolean isLastPage();
public abstract boolean isLoading();
}
|
3e17f191b92dcc384f095db2e6a5ef93d56428bb | 1,864 | java | Java | Student-Information-Administration-System/src/main/java/com/springmvc/interceptor/AuthorityInterceptor.java | kfoolish/USIMS | f0a43d6c218274a3f094b8582c4a65923ca94232 | [
"MIT"
] | 4 | 2019-07-25T23:43:15.000Z | 2019-10-18T00:11:11.000Z | Student-Information-Administration-System/src/main/java/com/springmvc/interceptor/AuthorityInterceptor.java | kfoolish/USIMS | f0a43d6c218274a3f094b8582c4a65923ca94232 | [
"MIT"
] | 1 | 2020-12-11T05:07:02.000Z | 2020-12-11T05:07:02.000Z | Student-Information-Administration-System/src/main/java/com/springmvc/interceptor/AuthorityInterceptor.java | kfoolish/USIMS | f0a43d6c218274a3f094b8582c4a65923ca94232 | [
"MIT"
] | 2 | 2019-07-25T23:43:26.000Z | 2019-12-10T11:29:13.000Z | 34.518519 | 162 | 0.750536 | 10,203 | package com.springmvc.interceptor;
import com.springmvc.service.OtherService;
import com.springmvc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @ClassName AuthorityInterceptor
* @Author JinZhiyun
* @Description 用户权限拦截器
* @Date 2019/5/3 12:58
* @Version 1.0
**/
public class AuthorityInterceptor implements HandlerInterceptor {
private final static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(AuthorityInterceptor.class);
@Autowired
private OtherService otherService;
/**
* @return boolean
* @Author JinZhiyun
* @Description 拦截访问修改页面的请求,如果非管理员身份,提示error.jsp
* @Date 13:18 2019/5/3
* @Param [httpServletRequest, httpServletResponse, o]
**/
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
if (otherService.ifUserIsAdmin(httpServletRequest.getSession())) {
logger.info("管理员访问:" + httpServletRequest.getRequestURI());
return true;
}
logger.info("非管理员访问:" + httpServletRequest.getRequestURI() + " 无操作权限");
httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/error");
return false;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
|
3e17f3055b1859cc89dbb3c30a08a482ef71938a | 4,554 | java | Java | app/src/main/java/com/example/sofra/data/pojo/order/OrderData.java | MohamedOmran72/Sofra | 996eb6021542bfdecff817869f77a3026140042d | [
"MIT"
] | 7 | 2020-10-14T14:15:26.000Z | 2021-01-15T19:45:58.000Z | app/src/main/java/com/example/sofra/data/pojo/order/OrderData.java | Sanaebadi97/Sofra | 996eb6021542bfdecff817869f77a3026140042d | [
"MIT"
] | 1 | 2020-12-22T01:51:07.000Z | 2020-12-22T01:51:07.000Z | app/src/main/java/com/example/sofra/data/pojo/order/OrderData.java | Sanaebadi97/Sofra | 996eb6021542bfdecff817869f77a3026140042d | [
"MIT"
] | 5 | 2020-11-13T17:49:59.000Z | 2021-06-27T18:58:34.000Z | 20.513514 | 60 | 0.628458 | 10,204 | package com.example.sofra.data.pojo.order;
import com.example.sofra.data.pojo.client.login.User;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class OrderData {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("created_at")
@Expose
private String createdAt;
@SerializedName("updated_at")
@Expose
private String updatedAt;
@SerializedName("note")
@Expose
private String note;
@SerializedName("address")
@Expose
private String address;
@SerializedName("payment_method_id")
@Expose
private String paymentMethodId;
@SerializedName("cost")
@Expose
private String cost;
@SerializedName("delivery_cost")
@Expose
private String deliveryCost;
@SerializedName("total")
@Expose
private String total;
@SerializedName("commission")
@Expose
private String commission;
@SerializedName("net")
@Expose
private String net;
@SerializedName("restaurant_id")
@Expose
private String restaurantId;
@SerializedName("delivered_at")
@Expose
private Object deliveredAt;
@SerializedName("state")
@Expose
private String state;
@SerializedName("refuse_reason")
@Expose
private Object refuseReason;
@SerializedName("client_id")
@Expose
private String clientId;
@SerializedName("client")
@Expose
private User client;
@SerializedName("items")
@Expose
private List<Item> items = null;
@SerializedName("restaurant")
@Expose
private User restaurant;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPaymentMethodId() {
return paymentMethodId;
}
public void setPaymentMethodId(String paymentMethodId) {
this.paymentMethodId = paymentMethodId;
}
public String getCost() {
return cost;
}
public void setCost(String cost) {
this.cost = cost;
}
public String getDeliveryCost() {
return deliveryCost;
}
public void setDeliveryCost(String deliveryCost) {
this.deliveryCost = deliveryCost;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public String getCommission() {
return commission;
}
public void setCommission(String commission) {
this.commission = commission;
}
public String getNet() {
return net;
}
public void setNet(String net) {
this.net = net;
}
public String getRestaurantId() {
return restaurantId;
}
public void setRestaurantId(String restaurantId) {
this.restaurantId = restaurantId;
}
public Object getDeliveredAt() {
return deliveredAt;
}
public void setDeliveredAt(Object deliveredAt) {
this.deliveredAt = deliveredAt;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Object getRefuseReason() {
return refuseReason;
}
public void setRefuseReason(Object refuseReason) {
this.refuseReason = refuseReason;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public User getClient() {
return client;
}
public void setClient(User client) {
this.client = client;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
public User getRestaurant() {
return restaurant;
}
public void setRestaurant(User restaurant) {
this.restaurant = restaurant;
}
}
|
3e17f30670e9a0f0df41f5717b13c8f00ba70577 | 506 | java | Java | security-user/src/main/java/com/lc/security/user/domain/User.java | hearthstones/lc-security | 066e8f867b4d729db7bfbefe23ebef640f695135 | [
"Apache-2.0"
] | null | null | null | security-user/src/main/java/com/lc/security/user/domain/User.java | hearthstones/lc-security | 066e8f867b4d729db7bfbefe23ebef640f695135 | [
"Apache-2.0"
] | null | null | null | security-user/src/main/java/com/lc/security/user/domain/User.java | hearthstones/lc-security | 066e8f867b4d729db7bfbefe23ebef640f695135 | [
"Apache-2.0"
] | null | null | null | 15.8125 | 42 | 0.719368 | 10,205 | package com.lc.security.user.domain;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* 用户类
*
* @author hearthstones
* @date 2021/11/8
*/
@Data
@Accessors(chain = true)
public class User {
private Integer id;
private String username;
private String password;
private String clearText;
private String mobile;
private Boolean enabled;
private Boolean accountNonLocked;
private Boolean accountNonExpired;
private Boolean credentialsNonExpired;
} |
3e17f43d2510de3c00bbc664c03fda6639a38c6b | 874 | java | Java | app/src/main/java/br/com/santander/resiliente/app/ServiceBreakingBad.java | brunonascimento/SpringCloudResilience-Example | 0d09e8338a6995f88638949c111614caac15b4b8 | [
"MIT"
] | null | null | null | app/src/main/java/br/com/santander/resiliente/app/ServiceBreakingBad.java | brunonascimento/SpringCloudResilience-Example | 0d09e8338a6995f88638949c111614caac15b4b8 | [
"MIT"
] | null | null | null | app/src/main/java/br/com/santander/resiliente/app/ServiceBreakingBad.java | brunonascimento/SpringCloudResilience-Example | 0d09e8338a6995f88638949c111614caac15b4b8 | [
"MIT"
] | null | null | null | 29.133333 | 110 | 0.736842 | 10,206 | package br.com.santander.resiliente.app;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
/**
* Created by brunonasc on 13/07/17.
*/
@Service
public class ServiceBreakingBad {
@Autowired
public RestTemplate lbRestTemplate;
@HystrixCommand(fallbackMethod = "fallbackSayMyName")
public String ReadBreakingBad() {
//String myName = new RestTemplate().getForObject("http://localhost:9000/saymyname", String.class);
String myName = this.lbRestTemplate.getForObject("http://BreakingBadService/saymyname", String.class);
return myName;
}
public String fallbackSayMyName(){
String myName = "Mr. White";
return myName;
}
}
|
3e17f4dbfc45df806ff564b02cf9e91f3a300d33 | 2,643 | java | Java | gapic/src/platform/windows/org/eclipse/swt/widgets/SwtUtil.java | m-atanassov/agi | d4d8465b130dec63f1807620220f308299f8fd69 | [
"Apache-2.0"
] | null | null | null | gapic/src/platform/windows/org/eclipse/swt/widgets/SwtUtil.java | m-atanassov/agi | d4d8465b130dec63f1807620220f308299f8fd69 | [
"Apache-2.0"
] | null | null | null | gapic/src/platform/windows/org/eclipse/swt/widgets/SwtUtil.java | m-atanassov/agi | d4d8465b130dec63f1807620220f308299f8fd69 | [
"Apache-2.0"
] | null | null | null | 33.0375 | 95 | 0.666288 | 10,207 | /*
* Copyright (C) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.eclipse.swt.widgets;
import org.eclipse.swt.SWT;
import org.eclipse.swt.internal.win32.OS;
import org.eclipse.swt.internal.win32.SCROLLINFO;
public class SwtUtil {
private SwtUtil() {
}
public static void disableAutoHideScrollbars(@SuppressWarnings("unused") Scrollable widget) {
// Do nothing.
}
public static void syncTreeAndTableScroll(Tree tree, Table table) {
Exclusive exclusive = new Exclusive();
table.getVerticalBar().addListener(SWT.Selection, e ->
exclusive.runExclusive(() -> {
int pos = table.getVerticalBar().getSelection();
SCROLLINFO info = new SCROLLINFO ();
info.cbSize = SCROLLINFO.sizeof;
info.fMask = OS.SIF_POS;
info.nPos = pos;
OS.SetScrollInfo(tree.handle, OS.SB_VERT, info, true);
OS.SendMessage(tree.handle, OS.WM_VSCROLL, OS.SB_THUMBPOSITION | (pos << 16), 0);
}));
Runnable updateTableScroll = () -> {
exclusive.runExclusive(() -> table.setTopIndex(tree.getVerticalBar().getSelection()));
};
tree.getVerticalBar().addListener(SWT.Selection, e -> updateTableScroll.run());
tree.addListener(SWT.Expand, e -> table.getDisplay().asyncExec(updateTableScroll));
tree.addListener(SWT.Collapse, e -> table.getDisplay().asyncExec(updateTableScroll));
// Make sure the rows are the same height in the table as the tree.
int[] height = { tree.getItemHeight() };
table.addListener(SWT.Paint, event -> {
height[0] = tree.getItemHeight();
if (table.getItemHeight() != height[0]) {
table.setItemHeight(height[0]);
updateTableScroll.run();
}
});
}
// Used to prevent infite loops from handling one event triggering another handled event.
private static class Exclusive {
private boolean ignore = false;
public Exclusive() {
}
public void runExclusive(Runnable run) {
if (!ignore) {
ignore = true;
try {
run.run();
} finally {
ignore = false;
}
}
}
}
}
|
3e17f7725ea8e3fcdabd08e9f9eba92dc2049e2a | 918 | java | Java | src/main/java/com/semmle/jira/addon/workflow/LgtmIssueLinkFunctionFactory.java | marcogario/lgtm-jira-addon | 70e05b595a711032bd675a644c22b278b3b8a3d9 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2020-07-02T21:00:21.000Z | 2020-10-12T17:19:28.000Z | src/main/java/com/semmle/jira/addon/workflow/LgtmIssueLinkFunctionFactory.java | marcogario/lgtm-jira-addon | 70e05b595a711032bd675a644c22b278b3b8a3d9 | [
"ECL-2.0",
"Apache-2.0"
] | 34 | 2019-02-01T16:44:05.000Z | 2020-03-24T07:40:25.000Z | src/main/java/com/semmle/jira/addon/workflow/LgtmIssueLinkFunctionFactory.java | marcogario/lgtm-jira-addon | 70e05b595a711032bd675a644c22b278b3b8a3d9 | [
"ECL-2.0",
"Apache-2.0"
] | 9 | 2019-02-01T15:23:46.000Z | 2021-11-18T11:40:58.000Z | 32.785714 | 81 | 0.809368 | 10,208 | package com.semmle.jira.addon.workflow;
import com.atlassian.jira.plugin.workflow.AbstractWorkflowPluginFactory;
import com.atlassian.jira.plugin.workflow.WorkflowPluginFunctionFactory;
import com.opensymphony.workflow.loader.AbstractDescriptor;
import java.util.Collections;
import java.util.Map;
public class LgtmIssueLinkFunctionFactory extends AbstractWorkflowPluginFactory
implements WorkflowPluginFunctionFactory {
@Override
protected void getVelocityParamsForInput(Map<String, Object> velocityParams) {}
@Override
protected void getVelocityParamsForEdit(
Map<String, Object> velocityParams, AbstractDescriptor descriptor) {}
@Override
protected void getVelocityParamsForView(
Map<String, Object> velocityParams, AbstractDescriptor descriptor) {}
@Override
public Map<String, ?> getDescriptorParams(Map<String, Object> formParams) {
return Collections.emptyMap();
}
}
|
3e17f8021da58a7d50eec95e5bdc9c9a4e2ce394 | 1,042 | java | Java | src/main/java/com/alipay/api/response/AlipayMarketingCardActivateformQueryResponse.java | Likenttt/alipay-sdk-java-all | 8eed972f188794506940093b97a73fce2f21ae06 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/alipay/api/response/AlipayMarketingCardActivateformQueryResponse.java | Likenttt/alipay-sdk-java-all | 8eed972f188794506940093b97a73fce2f21ae06 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/alipay/api/response/AlipayMarketingCardActivateformQueryResponse.java | Likenttt/alipay-sdk-java-all | 8eed972f188794506940093b97a73fce2f21ae06 | [
"Apache-2.0"
] | null | null | null | 21.265306 | 83 | 0.722649 | 10,209 | package com.alipay.api.response;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.marketing.card.activateform.query response.
*
* @author auto create
* @since 1.0, 2022-02-09 17:48:00
*/
public class AlipayMarketingCardActivateformQueryResponse extends AlipayResponse {
private static final long serialVersionUID = 4315548256423864257L;
/**
* 表单提交信息各个字段的值JSON数组
通用表单字段名称如下示例:
OPEN_FORM_FIELD_MOBILE – 手机号
OPEN_FORM_FIELD_GENDER – 性别
OPEN_FORM_FIELD_NAME – 姓名
OPEN_FORM_FIELD_BIRTHDAY – 生日
OPEN_FORM_FIELD_IDCARD – 身份证
OPEN_FORM_FIELD_EMAIL – 邮箱
OPEN_FORM_FIELD_ADDRESS – 地址
详细字段名称列表见会员卡开卡表单模板配置接口:alipay.marketing.card.formtemplate.set
注:
1. 证件类型字段(OPEN_FORM_FIELD_CERT_TYPE)返回结果取值如下:
0 -- 身份证
1 -- 护照
2 -- 港澳居民通行证
3 -- 台湾居民通行证
*/
@ApiField("infos")
private String infos;
public void setInfos(String infos) {
this.infos = infos;
}
public String getInfos( ) {
return this.infos;
}
}
|
3e17f82781e3d461a0ab5591150c748f1f7abc15 | 1,387 | java | Java | appserver/java-spring/src/main/java/com/marklogic/samplestack/domain/SparseContributor.java | marklogic/marklogic-samplestack | 5449924fe9abd1712d3ef20ca2f25f2e291578e0 | [
"Apache-2.0"
] | 73 | 2015-01-05T05:57:02.000Z | 2019-05-07T12:34:21.000Z | appserver/java-spring/src/main/java/com/marklogic/samplestack/domain/SparseContributor.java | marklogic-community/marklogic-samplestack | 5449924fe9abd1712d3ef20ca2f25f2e291578e0 | [
"Apache-2.0"
] | 435 | 2015-01-01T01:36:16.000Z | 2018-04-01T09:20:05.000Z | appserver/java-spring/src/main/java/com/marklogic/samplestack/domain/SparseContributor.java | marklogic/marklogic-samplestack | 5449924fe9abd1712d3ef20ca2f25f2e291578e0 | [
"Apache-2.0"
] | 65 | 2015-01-22T09:15:16.000Z | 2019-04-17T03:23:01.000Z | 22.015873 | 75 | 0.718097 | 10,210 | /*
* Copyright 2012-2015 MarkLogic Corporation
*
* 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.marklogic.samplestack.domain;
/**
* Wraps just those values from a Contributor object
* that are denormalized and stored with QnADocuments.
*/
public class SparseContributor {
/**
* The String identifier for this user, a primary key.
*/
public String id;
/** The contributor's display name */
public String displayName;
/** The username. */
public String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
|
3e17f8ed5edd09d71721b8f6ed64d956df8146cc | 701 | java | Java | basic/src/test/java/com/flyonsky/stack/CalcStackTest.java | flyonskycn/java-study | 84de0744d80cd5435771f9e5e39173509d2fad0f | [
"Apache-2.0"
] | null | null | null | basic/src/test/java/com/flyonsky/stack/CalcStackTest.java | flyonskycn/java-study | 84de0744d80cd5435771f9e5e39173509d2fad0f | [
"Apache-2.0"
] | null | null | null | basic/src/test/java/com/flyonsky/stack/CalcStackTest.java | flyonskycn/java-study | 84de0744d80cd5435771f9e5e39173509d2fad0f | [
"Apache-2.0"
] | null | null | null | 22.612903 | 54 | 0.623395 | 10,211 | package com.flyonsky.stack;
import org.junit.Assert;
import org.junit.Test;
/**
* CalcStack 单元测试
* @author luowengang
* @date 2020/1/4 22:36
*/
public class CalcStackTest {
@Test
public void testValidExpression1(){
String abc = "((a+b*6))";
CalcStack calcStack = new CalcStack();
boolean flag = calcStack.validExpression(abc);
System.out.println(flag);
Assert.assertTrue(flag);
}
@Test
public void testValidExpression2(){
String abc = "((a+b*6)";
CalcStack calcStack = new CalcStack();
boolean flag = calcStack.validExpression(abc);
System.out.println(flag);
Assert.assertFalse(flag);
}
}
|
3e17f926faad4718097d161680be8cf89b350091 | 803 | java | Java | shadows/framework/src/main/java/org/robolectric/shadows/ShadowHardwareRenderer.java | AospExtended/platform_external_robolectric-shadows | 5104c5ff580a3a21d524cce5df2818ffe2363554 | [
"MIT"
] | null | null | null | shadows/framework/src/main/java/org/robolectric/shadows/ShadowHardwareRenderer.java | AospExtended/platform_external_robolectric-shadows | 5104c5ff580a3a21d524cce5df2818ffe2363554 | [
"MIT"
] | null | null | null | shadows/framework/src/main/java/org/robolectric/shadows/ShadowHardwareRenderer.java | AospExtended/platform_external_robolectric-shadows | 5104c5ff580a3a21d524cce5df2818ffe2363554 | [
"MIT"
] | 2 | 2021-11-04T04:36:35.000Z | 2021-11-15T16:14:12.000Z | 29.740741 | 80 | 0.787049 | 10,212 | // BEGIN-INTERNAL
package org.robolectric.shadows;
import static android.os.Build.VERSION_CODES.Q;
import static android.os.Build.VERSION_CODES.R;
import android.graphics.HardwareRenderer;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
@Implements(value = HardwareRenderer.class, isInAndroidSdk = false, minSdk = Q)
public class ShadowHardwareRenderer {
private static long nextCreateProxy = 0;
@Implementation
protected static long nCreateProxy(boolean translucent, long rootRenderNode) {
return ++nextCreateProxy;
}
@Implementation(minSdk = R)
protected static long nCreateProxy(
boolean translucent, boolean isWideGamut, long rootRenderNode) {
return nCreateProxy(translucent, rootRenderNode);
}
}
// END-INTERNAL |
3e17faa9b94ae6e13ae1b664f853d51190511ac5 | 985 | java | Java | gravitee-apim-gateway/gravitee-apim-gateway-connector/src/main/java/io/gravitee/gateway/connector/ConnectorRegistry.java | wwjiang007/gravitee-gateway | b4e47743181fdcb6bac98c84c0783fc66248bd35 | [
"Apache-2.0"
] | 1,329 | 2015-07-23T12:19:58.000Z | 2022-02-17T14:06:09.000Z | gravitee-apim-gateway/gravitee-apim-gateway-connector/src/main/java/io/gravitee/gateway/connector/ConnectorRegistry.java | wwjiang007/gravitee-gateway | b4e47743181fdcb6bac98c84c0783fc66248bd35 | [
"Apache-2.0"
] | 261 | 2021-07-28T15:32:23.000Z | 2022-03-29T07:51:12.000Z | gravitee-apim-gateway/gravitee-apim-gateway-connector/src/main/java/io/gravitee/gateway/connector/ConnectorRegistry.java | AlexRogalskiy/gravitee-api-management | ebda3ae739dfe184b391cd78479c605325d2f5c7 | [
"Apache-2.0"
] | 337 | 2015-10-27T10:50:36.000Z | 2022-03-10T07:16:09.000Z | 35.178571 | 75 | 0.745178 | 10,213 | /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.gateway.connector;
import io.gravitee.connector.api.Connector;
import io.gravitee.connector.api.ConnectorFactory;
/**
* @author David BRASSELY (david.brassely at graviteesource.com)
* @author GraviteeSource Team
*/
public interface ConnectorRegistry {
ConnectorFactory<? extends Connector<?, ?>> getConnector(String type);
}
|
3e17fb778fcd936f7fcecae8d90cfa113d25f912 | 2,599 | java | Java | src/main/java/uk/me/richardcook/sinatra/generator/model/RoleView.java | Cook879/Sessionography-Book-Creator | f25a6e5ac146e1cfe4c435e086f2610b28582558 | [
"CC-BY-4.0"
] | null | null | null | src/main/java/uk/me/richardcook/sinatra/generator/model/RoleView.java | Cook879/Sessionography-Book-Creator | f25a6e5ac146e1cfe4c435e086f2610b28582558 | [
"CC-BY-4.0"
] | null | null | null | src/main/java/uk/me/richardcook/sinatra/generator/model/RoleView.java | Cook879/Sessionography-Book-Creator | f25a6e5ac146e1cfe4c435e086f2610b28582558 | [
"CC-BY-4.0"
] | null | null | null | 18.697842 | 69 | 0.692574 | 10,214 | package uk.me.richardcook.sinatra.generator.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Comparator;
@Entity
@Table( name = "vw_role" )
public class RoleView implements Serializable {
public static final long serialVersionUID = 1L;
@Id
@Column( name = "id" )
private int id;
@Column( name = "name" )
private String name;
@Column( name = "abbreviation" )
private String abbreviation;
@Column( name = "position" )
private int position;
// Needed for role group join
@Column( name = "group" )
private int group;
@Column( name = "role_group_name" )
private String roleGroupName;
@Column( name = "role_group_position" )
private int roleGroupPosition;
@Column( name = "arranger" )
private boolean arranger;
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
public String getAbbreviation() {
return abbreviation;
}
public void setAbbreviation( String abbreviation ) {
this.abbreviation = abbreviation;
}
public int getPosition() {
return position;
}
public void setPosition( int position ) {
this.position = position;
}
public String getRoleGroupName() {
return roleGroupName;
}
public void setRoleGroupName( String roleGroupName ) {
this.roleGroupName = roleGroupName;
}
public int getRoleGroupPosition() {
return roleGroupPosition;
}
public void setRoleGroupPosition( int roleGroupPosition ) {
this.roleGroupPosition = roleGroupPosition;
}
// TODO Never used??
@Override
public boolean equals( Object obj ) {
if ( ! obj.getClass().equals( RoleView.class ) )
return false;
RoleView role2 = (RoleView) obj;
return name.equals( role2.getName() );
}
public boolean isArranger() {
return arranger;
}
public void setArranger( boolean arranger ) {
this.arranger = arranger;
}
public int getGroup() {
return group;
}
public void setGroup( int group ) {
this.group = group;
}
public static class RoleComparator implements Comparator<RoleView> {
public int compare( RoleView a, RoleView b ) {
int groupA = a.getRoleGroupPosition();
int groupB = b.getRoleGroupPosition();
if ( groupA > groupB )
return 1;
if ( groupA < groupB )
return - 1;
int posA = a.getPosition();
int posB = b.getPosition();
if ( posA > posB )
return 1;
if ( posA < posB )
return - 1;
return 0;
}
}
}
|
3e17fc40a230dab10fdc1cbcc4aef50fbf7a434c | 957 | java | Java | src/java/data_creation/structures/HoleCardsType.java | tryabin/Poker-Calculator | 950fc0b2bad89aa4980af4da815d30713ebdbc16 | [
"Apache-2.0"
] | null | null | null | src/java/data_creation/structures/HoleCardsType.java | tryabin/Poker-Calculator | 950fc0b2bad89aa4980af4da815d30713ebdbc16 | [
"Apache-2.0"
] | null | null | null | src/java/data_creation/structures/HoleCardsType.java | tryabin/Poker-Calculator | 950fc0b2bad89aa4980af4da815d30713ebdbc16 | [
"Apache-2.0"
] | 1 | 2022-02-12T15:52:37.000Z | 2022-02-12T15:52:37.000Z | 22.255814 | 67 | 0.655172 | 10,215 | package data_creation.structures;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public enum HoleCardsType {
PAIR(""),
SUITED("s"),
OFFSUIT("o");
private String abbreviation;
private static final Map<String, HoleCardsType> ENUM_MAP;
static {
Map<String, HoleCardsType> map = new ConcurrentHashMap<>();
for (HoleCardsType instance : HoleCardsType.values()) {
map.put(instance.toString(), instance);
}
ENUM_MAP = Collections.unmodifiableMap(map);
}
HoleCardsType(String abbreviation) {
this.abbreviation = abbreviation;
}
@Override
public String toString() {
return abbreviation;
}
public static HoleCardsType get(String name) {
return ENUM_MAP.get(name);
}
public static Set<String> getAbbreviations() {
return ENUM_MAP.keySet();
}
}
|
3e17fc4f01e5f03b92f7834ae682614a29d0feeb | 953 | java | Java | common/src/main/java/com/chaoqer/common/entity/base/AuditStatus.java | thinktkj/chaoqer | ed0feb4a8e7bf9cbc8ba4dae4a447c9ec55177f7 | [
"Apache-2.0"
] | 2 | 2022-02-27T14:34:28.000Z | 2022-02-28T01:59:47.000Z | common/src/main/java/com/chaoqer/common/entity/base/AuditStatus.java | thinktkj/chaoqer | ed0feb4a8e7bf9cbc8ba4dae4a447c9ec55177f7 | [
"Apache-2.0"
] | null | null | null | common/src/main/java/com/chaoqer/common/entity/base/AuditStatus.java | thinktkj/chaoqer | ed0feb4a8e7bf9cbc8ba4dae4a447c9ec55177f7 | [
"Apache-2.0"
] | 1 | 2022-02-28T01:51:12.000Z | 2022-02-28T01:51:12.000Z | 19.854167 | 62 | 0.560336 | 10,216 | package com.chaoqer.common.entity.base;
/**
* 审核状态
*/
public enum AuditStatus {
// 未审核(静默)
DEFAULT(0, "default"),
// 需要平台审核
NEED_PLATFORM_AUDIT(1, "needPlatformAudit"),
// 审核通过
PASSED(2, "passed"),
// 第三方审核不通过
UN_PASSED_BY_THIRD_PARTY(-1, "unPassedByThirdParty"),
// 平台审核不通过
UN_PASSED_BY_PLATFORM(-2, "unPassedByPlatform");
private final int status;
private final String name;
AuditStatus(int status, String name) {
this.status = status;
this.name = name;
}
public int getStatus() {
return status;
}
public String getName() {
return name;
}
public static AuditStatus getAuditStatus(Integer status) {
if (status == null) {
return null;
}
for (AuditStatus e : AuditStatus.values()) {
if (e.status == status) {
return e;
}
}
return null;
}
}
|
3e17fe95808defe364dfd7e488edadb4cc4869ba | 3,555 | java | Java | modules/event-notifications/src/test/java/com/ibm/cloud/eventnotifications/event_notifications/v1/model/ReplaceTopicOptionsTest.java | IBM/event-notifications-java-admin-sdk | 03b921af535e6b5db61300c735615c9255c7c0a1 | [
"Apache-2.0"
] | 1 | 2022-03-31T08:20:03.000Z | 2022-03-31T08:20:03.000Z | modules/event-notifications/src/test/java/com/ibm/cloud/eventnotifications/event_notifications/v1/model/ReplaceTopicOptionsTest.java | IBM/event-notifications-java-admin-sdk | 03b921af535e6b5db61300c735615c9255c7c0a1 | [
"Apache-2.0"
] | 4 | 2022-01-11T05:57:24.000Z | 2022-03-25T07:46:25.000Z | modules/event-notifications/src/test/java/com/ibm/cloud/eventnotifications/event_notifications/v1/model/ReplaceTopicOptionsTest.java | IBM/event-notifications-java-admin-sdk | 03b921af535e6b5db61300c735615c9255c7c0a1 | [
"Apache-2.0"
] | null | null | null | 48.69863 | 156 | 0.775246 | 10,217 | /*
* (C) Copyright IBM Corp. 2022.
*
* 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.ibm.cloud.eventnotifications.event_notifications.v1.model;
import com.ibm.cloud.eventnotifications.event_notifications.v1.model.ReplaceTopicOptions;
import com.ibm.cloud.eventnotifications.event_notifications.v1.model.Rules;
import com.ibm.cloud.eventnotifications.event_notifications.v1.model.TopicUpdateSourcesItem;
import com.ibm.cloud.eventnotifications.event_notifications.v1.utils.TestUtilities;
import com.ibm.cloud.sdk.core.service.model.FileWithMetadata;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
/**
* Unit test class for the ReplaceTopicOptions model.
*/
public class ReplaceTopicOptionsTest {
final HashMap<String, InputStream> mockStreamMap = TestUtilities.createMockStreamMap();
final List<FileWithMetadata> mockListFileWithMetadata = TestUtilities.creatMockListFileWithMetadata();
@Test
public void testReplaceTopicOptions() throws Throwable {
Rules rulesModel = new Rules.Builder()
.enabled(true)
.eventTypeFilter("$.notification_event_info.event_type == 'cert_manager'")
.notificationFilter("$.notification.findings[0].severity == 'MODERATE'")
.build();
assertEquals(rulesModel.enabled(), Boolean.valueOf(true));
assertEquals(rulesModel.eventTypeFilter(), "$.notification_event_info.event_type == 'cert_manager'");
assertEquals(rulesModel.notificationFilter(), "$.notification.findings[0].severity == 'MODERATE'");
TopicUpdateSourcesItem topicUpdateSourcesItemModel = new TopicUpdateSourcesItem.Builder()
.id("e7c3b3ee-78d9-4e02-95c3-c001a05e6ea5:api")
.rules(new java.util.ArrayList<Rules>(java.util.Arrays.asList(rulesModel)))
.build();
assertEquals(topicUpdateSourcesItemModel.id(), "e7c3b3ee-78d9-4e02-95c3-c001a05e6ea5:api");
assertEquals(topicUpdateSourcesItemModel.rules(), new java.util.ArrayList<Rules>(java.util.Arrays.asList(rulesModel)));
ReplaceTopicOptions replaceTopicOptionsModel = new ReplaceTopicOptions.Builder()
.instanceId("testString")
.id("testString")
.name("testString")
.description("testString")
.sources(new java.util.ArrayList<TopicUpdateSourcesItem>(java.util.Arrays.asList(topicUpdateSourcesItemModel)))
.build();
assertEquals(replaceTopicOptionsModel.instanceId(), "testString");
assertEquals(replaceTopicOptionsModel.id(), "testString");
assertEquals(replaceTopicOptionsModel.name(), "testString");
assertEquals(replaceTopicOptionsModel.description(), "testString");
assertEquals(replaceTopicOptionsModel.sources(), new java.util.ArrayList<TopicUpdateSourcesItem>(java.util.Arrays.asList(topicUpdateSourcesItemModel)));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testReplaceTopicOptionsError() throws Throwable {
new ReplaceTopicOptions.Builder().build();
}
} |
3e17ffa263e1ef55cea7c291b384ca431cb7d324 | 45,087 | java | Java | optaplanner-core/src/main/java/org/optaplanner/core/api/score/stream/quad/QuadConstraintStream.java | mayurhole/optaplanner | 57391a824acfef81f3884542c97c5ac8eee7a8a6 | [
"Apache-2.0"
] | 20 | 2015-09-25T10:29:50.000Z | 2021-11-26T06:35:36.000Z | optaplanner-core/src/main/java/org/optaplanner/core/api/score/stream/quad/QuadConstraintStream.java | mayurhole/optaplanner | 57391a824acfef81f3884542c97c5ac8eee7a8a6 | [
"Apache-2.0"
] | 6 | 2021-03-23T00:32:23.000Z | 2022-02-16T01:15:24.000Z | optaplanner-core/src/main/java/org/optaplanner/core/api/score/stream/quad/QuadConstraintStream.java | mayurhole/optaplanner | 57391a824acfef81f3884542c97c5ac8eee7a8a6 | [
"Apache-2.0"
] | 6 | 2019-01-30T06:33:00.000Z | 2022-01-06T12:26:17.000Z | 51.469178 | 128 | 0.686872 | 10,218 | /*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.optaplanner.core.api.score.stream.quad;
import java.math.BigDecimal;
import java.util.Objects;
import java.util.function.Function;
import org.optaplanner.core.api.domain.constraintweight.ConstraintConfiguration;
import org.optaplanner.core.api.domain.constraintweight.ConstraintWeight;
import org.optaplanner.core.api.domain.entity.PlanningEntity;
import org.optaplanner.core.api.function.QuadFunction;
import org.optaplanner.core.api.function.QuadPredicate;
import org.optaplanner.core.api.function.ToIntQuadFunction;
import org.optaplanner.core.api.function.ToLongQuadFunction;
import org.optaplanner.core.api.function.TriFunction;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.api.score.constraint.ConstraintMatchTotal;
import org.optaplanner.core.api.score.stream.Constraint;
import org.optaplanner.core.api.score.stream.ConstraintCollectors;
import org.optaplanner.core.api.score.stream.ConstraintStream;
import org.optaplanner.core.api.score.stream.Joiners;
import org.optaplanner.core.api.score.stream.bi.BiConstraintStream;
import org.optaplanner.core.api.score.stream.penta.PentaJoiner;
import org.optaplanner.core.api.score.stream.tri.TriConstraintStream;
import org.optaplanner.core.api.score.stream.uni.UniConstraintStream;
/**
* A {@link ConstraintStream} that matches four facts.
*
* @param <A> the type of the first matched fact (either a problem fact or a {@link PlanningEntity planning entity})
* @param <B> the type of the second matched fact (either a problem fact or a {@link PlanningEntity planning entity})
* @param <C> the type of the third matched fact (either a problem fact or a {@link PlanningEntity planning entity})
* @param <D> the type of the fourth matched fact (either a problem fact or a {@link PlanningEntity planning entity})
* @see ConstraintStream
*/
public interface QuadConstraintStream<A, B, C, D> extends ConstraintStream {
// ************************************************************************
// Filter
// ************************************************************************
/**
* Exhaustively test each tuple of facts against the {@link QuadPredicate}
* and match if {@link QuadPredicate#test(Object, Object, Object, Object)} returns true.
* <p>
* Important: This is slower and less scalable than
* {@link TriConstraintStream#join(UniConstraintStream, QuadJoiner)} with a proper {@link QuadJoiner} predicate
* (such as {@link Joiners#equal(TriFunction, Function)},
* because the latter applies hashing and/or indexing, so it doesn't create every combination just to filter it out.
*
* @param predicate never null
* @return never null
*/
QuadConstraintStream<A, B, C, D> filter(QuadPredicate<A, B, C, D> predicate);
// ************************************************************************
// If (not) exists
// ************************************************************************
/**
* Create a new {@link BiConstraintStream} for every tuple of A, B, C and D where E exists for which the
* {@link PentaJoiner} is true (for the properties it extracts from the facts).
* <p>
* This method has overloaded methods with multiple {@link PentaJoiner} parameters.
*
* @param otherClass never null
* @param joiner never null
* @param <E> the type of the fifth matched fact
* @return never null, a stream that matches every tuple of A, B, C and D where E exists for which the
* {@link PentaJoiner} is true
*/
default <E> QuadConstraintStream<A, B, C, D> ifExists(Class<E> otherClass, PentaJoiner<A, B, C, D, E> joiner) {
return ifExists(otherClass, new PentaJoiner[] { joiner });
}
/**
* As defined by {@link #ifExists(Class, PentaJoiner)}. For performance reasons, indexing joiners must be placed
* before filtering joiners.
*
* @param otherClass never null
* @param joiner1 never null
* @param joiner2 never null
* @param <E> the type of the fifth matched fact
* @return never null, a stream that matches every tuple of A, B, C and D where E exists for which the
* {@link PentaJoiner}s are true
*/
default <E> QuadConstraintStream<A, B, C, D> ifExists(Class<E> otherClass, PentaJoiner<A, B, C, D, E> joiner1,
PentaJoiner<A, B, C, D, E> joiner2) {
return ifExists(otherClass, new PentaJoiner[] { joiner1, joiner2 });
}
/**
* As defined by {@link #ifExists(Class, PentaJoiner)}. For performance reasons, indexing joiners must be placed
* before filtering joiners.
*
* @param otherClass never null
* @param joiner1 never null
* @param joiner2 never null
* @param joiner3 never null
* @param <E> the type of the fifth matched fact
* @return never null, a stream that matches every tuple of A, B, C and D where E exists for which the
* {@link PentaJoiner}s are true
*/
default <E> QuadConstraintStream<A, B, C, D> ifExists(Class<E> otherClass, PentaJoiner<A, B, C, D, E> joiner1,
PentaJoiner<A, B, C, D, E> joiner2, PentaJoiner<A, B, C, D, E> joiner3) {
return ifExists(otherClass, new PentaJoiner[] { joiner1, joiner2, joiner3 });
}
/**
* As defined by {@link #ifExists(Class, PentaJoiner)}. For performance reasons, indexing joiners must be placed
* before filtering joiners.
*
* @param otherClass never null
* @param joiner1 never null
* @param joiner2 never null
* @param joiner3 never null
* @param joiner4 never null
* @param <E> the type of the fifth matched fact
* @return never null, a stream that matches every tuple of A, B, C and D where E exists for which the
* {@link PentaJoiner}s are true
*/
default <E> QuadConstraintStream<A, B, C, D> ifExists(Class<E> otherClass, PentaJoiner<A, B, C, D, E> joiner1,
PentaJoiner<A, B, C, D, E> joiner2, PentaJoiner<A, B, C, D, E> joiner3,
PentaJoiner<A, B, C, D, E> joiner4) {
return ifExists(otherClass, new PentaJoiner[] { joiner1, joiner2, joiner3, joiner4 });
}
/**
* As defined by {@link #ifExists(Class, PentaJoiner)}. For performance reasons, indexing joiners must be placed
* before filtering joiners.
* <p>
* This method causes <i>Unchecked generics array creation for varargs parameter</i> warnings,
* but we can't fix it with a {@link SafeVarargs} annotation because it's an interface method.
* Therefore, there are overloaded methods with up to 4 {@link PentaJoiner} parameters.
*
* @param otherClass never null
* @param joiners never null
* @param <E> the type of the fifth matched fact
* @return never null, a stream that matches every tuple of A, B, C and D where E exists for which the
* {@link PentaJoiner}s are true
*/
<E> QuadConstraintStream<A, B, C, D> ifExists(Class<E> otherClass, PentaJoiner<A, B, C, D, E>... joiners);
/**
* Create a new {@link BiConstraintStream} for every tuple of A, B, C and D where E does not exist for which the
* {@link PentaJoiner} is true (for the properties it extracts from the facts).
* <p>
* This method has overloaded methods with multiple {@link PentaJoiner} parameters.
*
* @param otherClass never null
* @param joiner never null
* @param <E> the type of the fifth matched fact
* @return never null, a stream that matches every tuple of A, B, C and D where E does not exist for which the
* {@link PentaJoiner} is true
*/
default <E> QuadConstraintStream<A, B, C, D> ifNotExists(Class<E> otherClass, PentaJoiner<A, B, C, D, E> joiner) {
return ifNotExists(otherClass, new PentaJoiner[] { joiner });
}
/**
* As defined by {@link #ifNotExists(Class, PentaJoiner)}. For performance reasons, indexing joiners must be placed
* before filtering joiners.
*
* @param otherClass never null
* @param joiner1 never null
* @param joiner2 never null
* @param <E> the type of the fifth matched fact
* @return never null, a stream that matches every tuple of A, B, C and D where E does not exist for which the
* {@link PentaJoiner}s are true
*/
default <E> QuadConstraintStream<A, B, C, D> ifNotExists(Class<E> otherClass, PentaJoiner<A, B, C, D, E> joiner1,
PentaJoiner<A, B, C, D, E> joiner2) {
return ifNotExists(otherClass, new PentaJoiner[] { joiner1, joiner2 });
}
/**
* As defined by {@link #ifNotExists(Class, PentaJoiner)}. For performance reasons, indexing joiners must be placed
* before filtering joiners.
*
* @param otherClass never null
* @param joiner1 never null
* @param joiner2 never null
* @param joiner3 never null
* @param <E> the type of the fifth matched fact
* @return never null, a stream that matches every tuple of A, B, C and D where E does not exist for which the
* {@link PentaJoiner}s are true
*/
default <E> QuadConstraintStream<A, B, C, D> ifNotExists(Class<E> otherClass, PentaJoiner<A, B, C, D, E> joiner1,
PentaJoiner<A, B, C, D, E> joiner2, PentaJoiner<A, B, C, D, E> joiner3) {
return ifNotExists(otherClass, new PentaJoiner[] { joiner1, joiner2, joiner3 });
}
/**
* As defined by {@link #ifNotExists(Class, PentaJoiner)}. For performance reasons, indexing joiners must be placed
* before filtering joiners.
*
* @param otherClass never null
* @param joiner1 never null
* @param joiner2 never null
* @param joiner3 never null
* @param joiner4 never null
* @param <E> the type of the fifth matched fact
* @return never null, a stream that matches every tuple of A, B, C and D where E does not exist for which the
* {@link PentaJoiner}s are true
*/
default <E> QuadConstraintStream<A, B, C, D> ifNotExists(Class<E> otherClass, PentaJoiner<A, B, C, D, E> joiner1,
PentaJoiner<A, B, C, D, E> joiner2, PentaJoiner<A, B, C, D, E> joiner3, PentaJoiner<A, B, C, D, E> joiner4) {
return ifNotExists(otherClass, new PentaJoiner[] { joiner1, joiner2, joiner3, joiner4 });
}
/**
* As defined by {@link #ifNotExists(Class, PentaJoiner)}. For performance reasons, indexing joiners must be placed
* before filtering joiners.
* <p>
* This method causes <i>Unchecked generics array creation for varargs parameter</i> warnings,
* but we can't fix it with a {@link SafeVarargs} annotation because it's an interface method.
* Therefore, there are overloaded methods with up to 4 {@link PentaJoiner} parameters.
*
* @param <E> the type of the fifth matched fact
* @param otherClass never null
* @param joiners never null
* @return never null, a stream that matches every tuple of A, B, C and D where E does not exist for which the
* {@link PentaJoiner}s are true
*/
<E> QuadConstraintStream<A, B, C, D> ifNotExists(Class<E> otherClass, PentaJoiner<A, B, C, D, E>... joiners);
// ************************************************************************
// Group by
// ************************************************************************
/**
* Convert the {@link QuadConstraintStream} to a {@link UniConstraintStream}, containing only a single tuple, the
* result of applying {@link QuadConstraintCollector}.
* {@link UniConstraintStream} which only has a single tuple, the result of applying
* {@link QuadConstraintCollector}.
*
* @param collector never null, the collector to perform the grouping operation with
* See {@link ConstraintCollectors} for common operations, such as {@code count()}, {@code sum()} and others.
* @param <ResultContainer_> the mutable accumulation type (often hidden as an implementation detail)
* @param <Result_> the type of a fact in the destination {@link UniConstraintStream}'s tuple
* @return never null
*/
<ResultContainer_, Result_> UniConstraintStream<Result_> groupBy(
QuadConstraintCollector<A, B, C, D, ResultContainer_, Result_> collector);
/**
* Convert the {@link QuadConstraintStream} to a {@link UniConstraintStream}, containing the set of tuples resulting
* from applying the group key mapping function on all tuples of the original stream.
* Neither tuple of the new stream {@link Objects#equals(Object, Object)} any other.
*
* @param groupKeyMapping never null, mapping function to convert each element in the stream to a different element
* @param <GroupKey_> the type of a fact in the destination {@link UniConstraintStream}'s tuple
* @return never null
*/
<GroupKey_> UniConstraintStream<GroupKey_> groupBy(QuadFunction<A, B, C, D, GroupKey_> groupKeyMapping);
/**
* Convert the {@link QuadConstraintStream} to a {@link BiConstraintStream}, consisting of unique tuples.
* <p>
* The first fact is the return value of the first group key mapping function, applied on the incoming tuple.
* The second fact is the return value of a given {@link QuadConstraintCollector} applied on all incoming tuples
* with the same first fact.
*
* @param groupKeyMapping never null, function to convert the fact in the original tuple to a different fact
* @param collector never null, the collector to perform the grouping operation with
* See {@link ConstraintCollectors} for common operations, such as {@code count()}, {@code sum()} and others.
* @param <GroupKey_> the type of the first fact in the destination {@link BiConstraintStream}'s tuple
* @param <ResultContainer_> the mutable accumulation type (often hidden as an implementation detail)
* @param <Result_> the type of the second fact in the destination {@link BiConstraintStream}'s tuple
* @return never null
*/
<GroupKey_, ResultContainer_, Result_> BiConstraintStream<GroupKey_, Result_> groupBy(
QuadFunction<A, B, C, D, GroupKey_> groupKeyMapping,
QuadConstraintCollector<A, B, C, D, ResultContainer_, Result_> collector);
/**
* Convert the {@link QuadConstraintStream} to a {@link BiConstraintStream}, consisting of unique tuples.
* <p>
* The first fact is the return value of the first group key mapping function, applied on the incoming tuple.
* The second fact is the return value of the second group key mapping function, applied on all incoming tuples with
* the same first fact.
*
* @param groupKeyAMapping never null, function to convert the facts in the original tuple to a new fact
* @param groupKeyBMapping never null, function to convert the facts in the original tuple to another new fact
* @param <GroupKeyA_> the type of the first fact in the destination {@link BiConstraintStream}'s tuple
* @param <GroupKeyB_> the type of the second fact in the destination {@link BiConstraintStream}'s tuple
* @return never null
*/
<GroupKeyA_, GroupKeyB_> BiConstraintStream<GroupKeyA_, GroupKeyB_> groupBy(
QuadFunction<A, B, C, D, GroupKeyA_> groupKeyAMapping, QuadFunction<A, B, C, D, GroupKeyB_> groupKeyBMapping);
/**
* Combines the semantics of {@link #groupBy(QuadFunction, QuadFunction)} and
* {@link #groupBy(QuadConstraintCollector)}.
* That is, the first and second facts in the tuple follow the {@link #groupBy(QuadFunction, QuadFunction)}
* semantics,
* and the third fact is the result of applying {@link QuadConstraintCollector#finisher()} on all the tuples of the
* original {@link UniConstraintStream} that belong to the group.
*
* @param groupKeyAMapping never null, function to convert the original tuple into a first fact
* @param groupKeyBMapping never null, function to convert the original tuple into a second fact
* @param collector never null, the collector to perform the grouping operation with
* See {@link ConstraintCollectors} for common operations, such as {@code count()}, {@code sum()} and others.
* @param <GroupKeyA_> the type of the first fact in the destination {@link TriConstraintStream}'s tuple
* @param <GroupKeyB_> the type of the second fact in the destination {@link TriConstraintStream}'s tuple
* @param <ResultContainer_> the mutable accumulation type (often hidden as an implementation detail)
* @param <Result_> the type of the third fact in the destination {@link TriConstraintStream}'s tuple
* @return never null
*/
<GroupKeyA_, GroupKeyB_, ResultContainer_, Result_> TriConstraintStream<GroupKeyA_, GroupKeyB_, Result_> groupBy(
QuadFunction<A, B, C, D, GroupKeyA_> groupKeyAMapping, QuadFunction<A, B, C, D, GroupKeyB_> groupKeyBMapping,
QuadConstraintCollector<A, B, C, D, ResultContainer_, Result_> collector);
/**
* Combines the semantics of {@link #groupBy(QuadFunction, QuadFunction)} and
* {@link #groupBy(QuadConstraintCollector)}.
* That is, the first and second facts in the tuple follow the {@link #groupBy(QuadFunction, QuadFunction)}
* semantics.
* The third fact is the result of applying the first {@link QuadConstraintCollector#finisher()} on all the tuples
* of the original {@link QuadConstraintStream} that belong to the group.
* The fourth fact is the result of applying the second {@link QuadConstraintCollector#finisher()} on all the tuples
* of the original {@link QuadConstraintStream} that belong to the group
*
* @param groupKeyAMapping never null, function to convert the original tuple into a first fact
* @param groupKeyBMapping never null, function to convert the original tuple into a second fact
* @param collectorC never null, the collector to perform the first grouping operation with
* See {@link ConstraintCollectors} for common operations, such as {@code count()}, {@code sum()} and others.
* @param collectorD never null, the collector to perform the second grouping operation with
* See {@link ConstraintCollectors} for common operations, such as {@code count()}, {@code sum()} and others.
* @param <GroupKeyA_> the type of the first fact in the destination {@link QuadConstraintStream}'s tuple
* @param <GroupKeyB_> the type of the second fact in the destination {@link QuadConstraintStream}'s tuple
* @param <ResultContainerC_> the mutable accumulation type (often hidden as an implementation detail)
* @param <ResultC_> the type of the third fact in the destination {@link QuadConstraintStream}'s tuple
* @param <ResultContainerD_> the mutable accumulation type (often hidden as an implementation detail)
* @param <ResultD_> the type of the fourth fact in the destination {@link QuadConstraintStream}'s tuple
* @return never null
*/
<GroupKeyA_, GroupKeyB_, ResultContainerC_, ResultC_, ResultContainerD_, ResultD_>
QuadConstraintStream<GroupKeyA_, GroupKeyB_, ResultC_, ResultD_> groupBy(
QuadFunction<A, B, C, D, GroupKeyA_> groupKeyAMapping,
QuadFunction<A, B, C, D, GroupKeyB_> groupKeyBMapping,
QuadConstraintCollector<A, B, C, D, ResultContainerC_, ResultC_> collectorC,
QuadConstraintCollector<A, B, C, D, ResultContainerD_, ResultD_> collectorD);
// ************************************************************************
// Penalize/reward
// ************************************************************************
/**
* Negatively impact the {@link Score}: subtract the constraintWeight multiplied by the match weight.
* Otherwise as defined by {@link #penalize(String, Score)}.
* <p>
* For non-int {@link Score} types use {@link #penalizeLong(String, Score, ToLongQuadFunction)} or
* {@link #penalizeBigDecimal(String, Score, QuadFunction)} instead.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param constraintWeight never null
* @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight
* @return never null
*/
default Constraint penalize(String constraintName, Score<?> constraintWeight,
ToIntQuadFunction<A, B, C, D> matchWeigher) {
return penalize(getConstraintFactory().getDefaultConstraintPackage(), constraintName, constraintWeight,
matchWeigher);
}
/**
* As defined by {@link #penalize(String, Score, ToIntQuadFunction)}.
*
* @param constraintPackage never null
* @param constraintName never null
* @param constraintWeight never null
* @param matchWeigher never null
* @return never null
*/
Constraint penalize(String constraintPackage, String constraintName, Score<?> constraintWeight,
ToIntQuadFunction<A, B, C, D> matchWeigher);
/**
* Negatively impact the {@link Score}: subtract the constraintWeight multiplied by the match weight.
* Otherwise as defined by {@link #penalize(String, Score)}.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param constraintWeight never null
* @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight
* @return never null
*/
default Constraint penalizeLong(String constraintName, Score<?> constraintWeight,
ToLongQuadFunction<A, B, C, D> matchWeigher) {
return penalizeLong(getConstraintFactory().getDefaultConstraintPackage(), constraintName, constraintWeight,
matchWeigher);
}
/**
* As defined by {@link #penalizeLong(String, Score, ToLongQuadFunction)}.
*
* @param constraintPackage never null
* @param constraintName never null
* @param constraintWeight never null
* @param matchWeigher never null
* @return never null
*/
Constraint penalizeLong(String constraintPackage, String constraintName, Score<?> constraintWeight,
ToLongQuadFunction<A, B, C, D> matchWeigher);
/**
* Negatively impact the {@link Score}: subtract the constraintWeight multiplied by the match weight.
* Otherwise as defined by {@link #penalize(String, Score)}.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param constraintWeight never null
* @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight
* @return never null
*/
default Constraint penalizeBigDecimal(String constraintName, Score<?> constraintWeight,
QuadFunction<A, B, C, D, BigDecimal> matchWeigher) {
return penalizeBigDecimal(getConstraintFactory().getDefaultConstraintPackage(), constraintName,
constraintWeight, matchWeigher);
}
/**
* As defined by {@link #penalizeBigDecimal(String, Score, QuadFunction)}.
*
* @param constraintPackage never null
* @param constraintName never null
* @param constraintWeight never null
* @param matchWeigher never null
* @return never null
*/
Constraint penalizeBigDecimal(String constraintPackage, String constraintName, Score<?> constraintWeight,
QuadFunction<A, B, C, D, BigDecimal> matchWeigher);
/**
* Negatively impact the {@link Score}: subtract the {@link ConstraintWeight} multiplied by the match weight.
* Otherwise as defined by {@link #penalizeConfigurable(String)}.
* <p>
* For non-int {@link Score} types use {@link #penalizeConfigurableLong(String, ToLongQuadFunction)} or
* {@link #penalizeConfigurableBigDecimal(String, QuadFunction)} instead.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight
* @return never null
*/
default Constraint penalizeConfigurable(String constraintName, ToIntQuadFunction<A, B, C, D> matchWeigher) {
return penalizeConfigurable(getConstraintFactory().getDefaultConstraintPackage(), constraintName, matchWeigher);
}
/**
* As defined by {@link #penalizeConfigurable(String, ToIntQuadFunction)}.
*
* @param constraintPackage never null
* @param constraintName never null
* @param matchWeigher never null
* @return never null
*/
Constraint penalizeConfigurable(String constraintPackage, String constraintName,
ToIntQuadFunction<A, B, C, D> matchWeigher);
/**
* Negatively impact the {@link Score}: subtract the {@link ConstraintWeight} multiplied by the match weight.
* Otherwise as defined by {@link #penalizeConfigurable(String)}.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight
* @return never null
*/
default Constraint penalizeConfigurableLong(String constraintName, ToLongQuadFunction<A, B, C, D> matchWeigher) {
return penalizeConfigurableLong(getConstraintFactory().getDefaultConstraintPackage(), constraintName,
matchWeigher);
}
/**
* As defined by {@link #penalizeConfigurableLong(String, ToLongQuadFunction)}.
*
* @param constraintPackage never null
* @param constraintName never null
* @param matchWeigher never null
* @return never null
*/
Constraint penalizeConfigurableLong(String constraintPackage, String constraintName,
ToLongQuadFunction<A, B, C, D> matchWeigher);
/**
* Negatively impact the {@link Score}: subtract the {@link ConstraintWeight} multiplied by the match weight.
* Otherwise as defined by {@link #penalizeConfigurable(String)}.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight
* @return never null
*/
default Constraint penalizeConfigurableBigDecimal(String constraintName,
QuadFunction<A, B, C, D, BigDecimal> matchWeigher) {
return penalizeConfigurableBigDecimal(getConstraintFactory().getDefaultConstraintPackage(), constraintName,
matchWeigher);
}
/**
* As defined by {@link #penalizeConfigurableBigDecimal(String, QuadFunction)}.
*
* @param constraintPackage never null
* @param constraintName never null
* @param matchWeigher never null
* @return never null
*/
Constraint penalizeConfigurableBigDecimal(String constraintPackage, String constraintName,
QuadFunction<A, B, C, D, BigDecimal> matchWeigher);
/**
* Positively impact the {@link Score}: add the constraintWeight multiplied by the match weight.
* Otherwise as defined by {@link #reward(String, Score)}.
* <p>
* For non-int {@link Score} types use {@link #rewardLong(String, Score, ToLongQuadFunction)} or
* {@link #rewardBigDecimal(String, Score, QuadFunction)} instead.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param constraintWeight never null
* @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight
* @return never null
*/
default Constraint reward(String constraintName, Score<?> constraintWeight,
ToIntQuadFunction<A, B, C, D> matchWeigher) {
return reward(getConstraintFactory().getDefaultConstraintPackage(), constraintName, constraintWeight,
matchWeigher);
}
/**
* As defined by {@link #reward(String, Score, ToIntQuadFunction)}.
*
* @param constraintPackage never null
* @param constraintName never null
* @param constraintWeight never null
* @param matchWeigher never null
* @return never null
*/
Constraint reward(String constraintPackage, String constraintName, Score<?> constraintWeight,
ToIntQuadFunction<A, B, C, D> matchWeigher);
/**
* Positively impact the {@link Score}: add the constraintWeight multiplied by the match weight.
* Otherwise as defined by {@link #reward(String, Score)}.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param constraintWeight never null
* @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight
* @return never null
*/
default Constraint rewardLong(String constraintName, Score<?> constraintWeight,
ToLongQuadFunction<A, B, C, D> matchWeigher) {
return rewardLong(getConstraintFactory().getDefaultConstraintPackage(), constraintName, constraintWeight, matchWeigher);
}
/**
* As defined by {@link #rewardLong(String, Score, ToLongQuadFunction)}.
*
* @param constraintPackage never null
* @param constraintName never null
* @param constraintWeight never null
* @param matchWeigher never null
* @return never null
*/
Constraint rewardLong(String constraintPackage, String constraintName, Score<?> constraintWeight,
ToLongQuadFunction<A, B, C, D> matchWeigher);
/**
* Positively impact the {@link Score}: add the constraintWeight multiplied by the match weight.
* Otherwise as defined by {@link #reward(String, Score)}.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param constraintWeight never null
* @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight
* @return never null
*/
default Constraint rewardBigDecimal(String constraintName, Score<?> constraintWeight,
QuadFunction<A, B, C, D, BigDecimal> matchWeigher) {
return rewardBigDecimal(getConstraintFactory().getDefaultConstraintPackage(), constraintName, constraintWeight,
matchWeigher);
}
/**
* As defined by {@link #rewardBigDecimal(String, Score, QuadFunction)}.
*
* @param constraintPackage never null
* @param constraintName never null
* @param constraintWeight never null
* @param matchWeigher never null
* @return never null
*/
Constraint rewardBigDecimal(String constraintPackage, String constraintName, Score<?> constraintWeight,
QuadFunction<A, B, C, D, BigDecimal> matchWeigher);
/**
* Positively impact the {@link Score}: add the {@link ConstraintWeight} multiplied by the match weight.
* Otherwise as defined by {@link #rewardConfigurable(String)}.
* <p>
* For non-int {@link Score} types use {@link #rewardConfigurableLong(String, ToLongQuadFunction)} or
* {@link #rewardConfigurableBigDecimal(String, QuadFunction)} instead.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight
* @return never null
*/
default Constraint rewardConfigurable(String constraintName, ToIntQuadFunction<A, B, C, D> matchWeigher) {
return rewardConfigurable(getConstraintFactory().getDefaultConstraintPackage(), constraintName, matchWeigher);
}
/**
* As defined by {@link #rewardConfigurable(String, ToIntQuadFunction)}.
*
* @param constraintPackage never null
* @param constraintName never null
* @param matchWeigher never null
* @return never null
*/
Constraint rewardConfigurable(String constraintPackage, String constraintName,
ToIntQuadFunction<A, B, C, D> matchWeigher);
/**
* Positively impact the {@link Score}: add the {@link ConstraintWeight} multiplied by the match weight.
* Otherwise as defined by {@link #rewardConfigurable(String)}.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight
* @return never null
*/
default Constraint rewardConfigurableLong(String constraintName, ToLongQuadFunction<A, B, C, D> matchWeigher) {
return rewardConfigurableLong(getConstraintFactory().getDefaultConstraintPackage(), constraintName,
matchWeigher);
}
/**
* As defined by {@link #rewardConfigurableLong(String, ToLongQuadFunction)}.
*
* @param constraintPackage never null
* @param constraintName never null
* @param matchWeigher never null
* @return never null
*/
Constraint rewardConfigurableLong(String constraintPackage, String constraintName,
ToLongQuadFunction<A, B, C, D> matchWeigher);
/**
* Positively impact the {@link Score}: add the {@link ConstraintWeight} multiplied by the match weight.
* Otherwise as defined by {@link #rewardConfigurable(String)}.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight
* @return never null
*/
default Constraint rewardConfigurableBigDecimal(String constraintName,
QuadFunction<A, B, C, D, BigDecimal> matchWeigher) {
return rewardConfigurableBigDecimal(getConstraintFactory().getDefaultConstraintPackage(), constraintName,
matchWeigher);
}
/**
* As defined by {@link #rewardConfigurableBigDecimal(String, QuadFunction)}.
*
* @param constraintPackage never null
* @param constraintName never null
* @param matchWeigher never null
* @return never null
*/
Constraint rewardConfigurableBigDecimal(String constraintPackage, String constraintName,
QuadFunction<A, B, C, D, BigDecimal> matchWeigher);
/**
* Positively or negatively impact the {@link Score} by the constraintWeight multiplied by the match weight.
* Otherwise as defined by {@link #impact(String, Score)}.
* <p>
* Use {@code penalize(...)} or {@code reward(...)} instead, unless this constraint can both have positive and
* negative weights.
* <p>
* For non-int {@link Score} types use {@link #impactLong(String, Score, ToLongQuadFunction)} or
* {@link #impactBigDecimal(String, Score, QuadFunction)} instead.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param constraintWeight never null
* @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight
* @return never null
*/
default Constraint impact(String constraintName, Score<?> constraintWeight,
ToIntQuadFunction<A, B, C, D> matchWeigher) {
return impact(getConstraintFactory().getDefaultConstraintPackage(), constraintName, constraintWeight,
matchWeigher);
}
/**
* As defined by {@link #impact(String, Score, ToIntQuadFunction)}.
*
* @param constraintPackage never null
* @param constraintName never null
* @param constraintWeight never null
* @param matchWeigher never null
* @return never null
*/
Constraint impact(String constraintPackage, String constraintName, Score<?> constraintWeight,
ToIntQuadFunction<A, B, C, D> matchWeigher);
/**
* Positively or negatively impact the {@link Score} by the constraintWeight multiplied by the match weight.
* Otherwise as defined by {@link #impact(String, Score)}.
* <p>
* Use {@code penalizeLong(...)} or {@code rewardLong(...)} instead, unless this constraint can both have positive
* and negative weights.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param constraintWeight never null
* @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight
* @return never null
*/
default Constraint impactLong(String constraintName, Score<?> constraintWeight,
ToLongQuadFunction<A, B, C, D> matchWeigher) {
return impactLong(getConstraintFactory().getDefaultConstraintPackage(), constraintName, constraintWeight,
matchWeigher);
}
/**
* As defined by {@link #impactLong(String, Score, ToLongQuadFunction)}.
*
* @param constraintPackage never null
* @param constraintName never null
* @param constraintWeight never null
* @param matchWeigher never null
* @return never null
*/
Constraint impactLong(String constraintPackage, String constraintName, Score<?> constraintWeight,
ToLongQuadFunction<A, B, C, D> matchWeigher);
/**
* Positively or negatively impact the {@link Score} by the constraintWeight multiplied by the match weight.
* Otherwise as defined by {@link #impact(String, Score)}.
* <p>
* Use {@code penalizeBigDecimal(...)} or {@code rewardBigDecimal(...)} instead, unless this constraint can both
* have positive and negative weights.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param constraintWeight never null
* @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight
* @return never null
*/
default Constraint impactBigDecimal(String constraintName, Score<?> constraintWeight,
QuadFunction<A, B, C, D, BigDecimal> matchWeigher) {
return impactBigDecimal(getConstraintFactory().getDefaultConstraintPackage(), constraintName,
constraintWeight, matchWeigher);
}
/**
* As defined by {@link #impactBigDecimal(String, Score, QuadFunction)}.
*
* @param constraintPackage never null
* @param constraintName never null
* @param constraintWeight never null
* @param matchWeigher never null
* @return never null
*/
Constraint impactBigDecimal(String constraintPackage, String constraintName, Score<?> constraintWeight,
QuadFunction<A, B, C, D, BigDecimal> matchWeigher);
/**
* Positively or negatively impact the {@link Score} by the {@link ConstraintWeight} for each match.
* <p>
* Use {@code penalizeConfigurable(...)} or {@code rewardConfigurable(...)} instead, unless this constraint can both
* have positive and negative weights.
* <p>
* For non-int {@link Score} types use {@link #impactConfigurableLong(String, ToLongQuadFunction)} or
* {@link #impactConfigurableBigDecimal(String, QuadFunction)} instead.
* <p>
* The constraintWeight comes from an {@link ConstraintWeight} annotated member on the
* {@link ConstraintConfiguration}, so end users can change the constraint weights dynamically.
* This constraint may be deactivated if the {@link ConstraintWeight} is zero.
* If there is no {@link ConstraintConfiguration}, use {@link #impact(String, Score)} instead.
* <p>
* The {@link Constraint#getConstraintPackage()} defaults to {@link ConstraintConfiguration#constraintPackage()}.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight
* @return never null
*/
default Constraint impactConfigurable(String constraintName, ToIntQuadFunction<A, B, C, D> matchWeigher) {
return impactConfigurable(getConstraintFactory().getDefaultConstraintPackage(), constraintName, matchWeigher);
}
/**
* As defined by {@link #impactConfigurable(String, ToIntQuadFunction)}.
*
* @param constraintPackage never null
* @param constraintName never null
* @param matchWeigher never null
* @return never null
*/
Constraint impactConfigurable(String constraintPackage, String constraintName,
ToIntQuadFunction<A, B, C, D> matchWeigher);
/**
* Positively or negatively impact the {@link Score} by the {@link ConstraintWeight} for each match.
* <p>
* Use {@code penalizeConfigurableLong(...)} or {@code rewardConfigurableLong(...)} instead, unless this constraint
* can both have positive and negative weights.
* <p>
* The constraintWeight comes from an {@link ConstraintWeight} annotated member on the
* {@link ConstraintConfiguration}, so end users can change the constraint weights dynamically.
* This constraint may be deactivated if the {@link ConstraintWeight} is zero.
* If there is no {@link ConstraintConfiguration}, use {@link #impact(String, Score)} instead.
* <p>
* The {@link Constraint#getConstraintPackage()} defaults to {@link ConstraintConfiguration#constraintPackage()}.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight
* @return never null
*/
default Constraint impactConfigurableLong(String constraintName, ToLongQuadFunction<A, B, C, D> matchWeigher) {
return impactConfigurableLong(getConstraintFactory().getDefaultConstraintPackage(), constraintName,
matchWeigher);
}
/**
* As defined by {@link #impactConfigurableLong(String, ToLongQuadFunction)}.
*
* @param constraintPackage never null
* @param constraintName never null
* @param matchWeigher never null
* @return never null
*/
Constraint impactConfigurableLong(String constraintPackage, String constraintName,
ToLongQuadFunction<A, B, C, D> matchWeigher);
/**
* Positively or negatively impact the {@link Score} by the {@link ConstraintWeight} for each match.
* <p>
* Use {@code penalizeConfigurableBigDecimal(...)} or {@code rewardConfigurableBigDecimal(...)} instead, unless this
* constraint can both have positive and negative weights.
* <p>
* The constraintWeight comes from an {@link ConstraintWeight} annotated member on the
* {@link ConstraintConfiguration}, so end users can change the constraint weights dynamically.
* This constraint may be deactivated if the {@link ConstraintWeight} is zero.
* If there is no {@link ConstraintConfiguration}, use {@link #impact(String, Score)} instead.
* <p>
* The {@link Constraint#getConstraintPackage()} defaults to {@link ConstraintConfiguration#constraintPackage()}.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight
* @return never null
*/
default Constraint impactConfigurableBigDecimal(String constraintName,
QuadFunction<A, B, C, D, BigDecimal> matchWeigher) {
return impactConfigurableBigDecimal(getConstraintFactory().getDefaultConstraintPackage(), constraintName, matchWeigher);
}
/**
* As defined by {@link #impactConfigurableBigDecimal(String, QuadFunction)}.
*
* @param constraintPackage never null
* @param constraintName never null
* @param matchWeigher never null
* @return never null
*/
Constraint impactConfigurableBigDecimal(String constraintPackage, String constraintName,
QuadFunction<A, B, C, D, BigDecimal> matchWeigher);
}
|
3e180073b23cffa522931589ea779f0a9b1bf57b | 6,765 | java | Java | src/main/java/com/sebbaindustries/warps/commands/creator/CommandFactory.java | SebbaIndustries/Warps-1.0 | a79cedec7adb7fa3b1c65a507bacb773a225cfb2 | [
"MIT"
] | null | null | null | src/main/java/com/sebbaindustries/warps/commands/creator/CommandFactory.java | SebbaIndustries/Warps-1.0 | a79cedec7adb7fa3b1c65a507bacb773a225cfb2 | [
"MIT"
] | null | null | null | src/main/java/com/sebbaindustries/warps/commands/creator/CommandFactory.java | SebbaIndustries/Warps-1.0 | a79cedec7adb7fa3b1c65a507bacb773a225cfb2 | [
"MIT"
] | null | null | null | 36.370968 | 158 | 0.648041 | 10,219 | package com.sebbaindustries.warps.commands.creator;
import com.sebbaindustries.warps.Core;
import com.sebbaindustries.warps.commands.actions.*;
import com.sebbaindustries.warps.commands.creator.completion.*;
import com.sebbaindustries.warps.utils.Color;
import com.sebbaindustries.warps.warp.Warp;
import com.sebbaindustries.warps.warp.WarpUtils;
import com.sebbaindustries.warps.warp.components.SafetyCheck;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* <b>This class contains command handling and executing to it's sub-classes</b><br>
*
* @author Sebba, Frcsty
* @version 1.0
*/
public class CommandFactory implements CommandExecutor {
private final Set<ICommand> iCommands;
/**
* Main constructor, registers commands and it's sub classes <br>
* <b>IF YOU DARE TO CREATE NEW ICommandHandler INSTANCE IN OTHER PLACE THAN GlobalCore I WILL PERSONALLY REMOVE YOU FROM EARTH.</b>
*
* @param core Core instance
*/
public CommandFactory(final @NotNull Core core) {
// Register commands
Objects.requireNonNull(core.getCommand("warps")).setExecutor(this);
final PluginCommand warp = core.getCommand("warp");
Objects.requireNonNull(warp).setExecutor(this);
Objects.requireNonNull(warp).setTabCompleter(new WarpCompletion());
final PluginCommand set = core.getCommand("setwarp");
Objects.requireNonNull(set).setExecutor(this);
Objects.requireNonNull(set).setTabCompleter(new SetCompletion());
final PluginCommand delete = core.getCommand("delwarp");
Objects.requireNonNull(delete).setExecutor(this);
Objects.requireNonNull(delete).setTabCompleter(new DeleteCompletion());
final PluginCommand move = core.getCommand("movewarp");
Objects.requireNonNull(move).setExecutor(this);
Objects.requireNonNull(move).setTabCompleter(new MoveCompletion());
final PluginCommand modify = core.getCommand("modifywarp");
Objects.requireNonNull(modify).setExecutor(this);
Objects.requireNonNull(modify).setTabCompleter(new ModifyCompletion());
final PluginCommand rate = core.getCommand("ratewarp");
Objects.requireNonNull(rate).setExecutor(this);
Objects.requireNonNull(rate).setTabCompleter(new RateCompletion());
final PluginCommand list = core.getCommand("listwarps");
Objects.requireNonNull(list).setExecutor(this);
Objects.requireNonNull(list).setTabCompleter(new ListCompletion());
// Register sub-commands
iCommands = Stream.of(
new SetWarp(),
new RateWarp(),
new MoveWarp(),
new ModifyWarp(),
new ListWarps(),
new DelWarp(),
new WarpTeleportation(),
new WarpsMenu(core)
).collect(Collectors.toSet());
// Check if every command has at least 1 permission attached to them
iCommands.forEach(iCommand -> {
if (iCommand.permissions().getPermissions().isEmpty()) throw new NoPermissionSetCommandException();
});
}
/**
* @param sender Player or console instance
* @param command Command class
* @param label command label
* @param args command arguments
* @return True ALWAYS FUCKING true, if you change this I quit.
* @see CommandExecutor
*/
@Override
public boolean onCommand(final @NotNull CommandSender sender, final @NotNull Command command, final @NotNull String label, final @NotNull String[] args) {
// Check if first argument equals to any subs
final Optional<ICommand> baseCommand = iCommands.stream().filter(cmd -> cmd.getArgument().equalsIgnoreCase(command.getName())).findAny();
if (!baseCommand.isPresent()) {
sender.sendMessage("Invalid command!");
return true;
}
final ICommand cmd = baseCommand.get();
if (cmd.isDef()) {
cmd.execute(sender, args);
return true;
}
if (cmd.getArgument().equalsIgnoreCase("warp")) {
if (!(sender instanceof Player)) {
sender.sendMessage("You cannot use this through console!");
return true;
}
final Warp warp = Core.gCore.warpStorage.getWarp(args[0]);
if (warp == null) {
sender.sendMessage("Invalid warp!");
return true;
}
if (!warp.getAccessibility()) {
sender.sendMessage("Private warp");
return true;
}
if (!SafetyCheck.isLocationSafe(warp.getLocation())) {
sender.sendMessage("Invalid warp location!");
return true;
}
((Player) sender).teleport(WarpUtils.convertWarpLocation(warp.getLocation()));
// teleport player to warp (add safety check)
return true;
}
// Check if console can execute this sub-command
// TODO add same thing for players
if (cmd.isPlayerOnly() && !(sender instanceof Player)) {
sender.sendMessage(Color.chat("&cThis command can not be executed in console!"));
return true;
}
// Check if player has permission to execute this sub-command
if (!checkPermissions(cmd, sender)) {
sender.sendMessage(Color.chat("&cYou do not have permission to execute this command Jimbo."));
return true;
}
// Check if usage is correct (prevents some nasty NPEs)
if (cmd.getMinArgs() > args.length) {
sender.sendMessage(Color.chat("Invalid Usage! Usage " + cmd.getUsage()));
return true;
}
// Finally execute this command
cmd.execute(sender, args);
return true;
}
/**
* Checks permissions for the player and returns boolean <br>
*
* @param iCommand command template instance
* @param sender Player or console instance
* @return True if player has at least 1 permission for the sub-command, false if player has none #SadTimes
* @see ICommand
* Perfected by Frosty
*/
private boolean checkPermissions(ICommand iCommand, CommandSender sender) {
return iCommand.permissions().getPermissions().stream().anyMatch(perm -> sender.hasPermission(perm.permission));
}
}
|
3e18013d6821312916ee6ed266f1cddbe59efd80 | 2,036 | java | Java | drools-wb-screens/drools-wb-globals-editor/drools-wb-globals-editor-api/src/main/java/org/drools/workbench/screens/globals/model/GlobalsEditorContent.java | kiereleaseuser/drools-wb | df5e42e2ab67935bb1166280f3016bfc740a2e61 | [
"Apache-2.0"
] | null | null | null | drools-wb-screens/drools-wb-globals-editor/drools-wb-globals-editor-api/src/main/java/org/drools/workbench/screens/globals/model/GlobalsEditorContent.java | kiereleaseuser/drools-wb | df5e42e2ab67935bb1166280f3016bfc740a2e61 | [
"Apache-2.0"
] | null | null | null | drools-wb-screens/drools-wb-globals-editor/drools-wb-globals-editor-api/src/main/java/org/drools/workbench/screens/globals/model/GlobalsEditorContent.java | kiereleaseuser/drools-wb | df5e42e2ab67935bb1166280f3016bfc740a2e61 | [
"Apache-2.0"
] | 1 | 2016-12-20T08:54:38.000Z | 2016-12-20T08:54:38.000Z | 34.508475 | 103 | 0.649312 | 10,220 | /*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.drools.workbench.screens.globals.model;
import java.util.List;
import org.guvnor.common.services.shared.metadata.model.Overview;
import org.jboss.errai.common.client.api.annotations.Portable;
import org.uberfire.commons.validation.PortablePreconditions;
@Portable
public class GlobalsEditorContent {
private GlobalsModel model;
private List<String> fullyQualifiedClassNames;
private Overview overview;
public GlobalsEditorContent() {
}
public GlobalsEditorContent( final GlobalsModel model,
final Overview overview,
final List<String> fullyQualifiedClassNames ) {
this.model = PortablePreconditions.checkNotNull( "model",
model );
this.overview = PortablePreconditions.checkNotNull( "overview",
overview );
this.fullyQualifiedClassNames = PortablePreconditions.checkNotNull( "fullyQualifiedClassNames",
fullyQualifiedClassNames );
}
public GlobalsModel getModel() {
return this.model;
}
public List<String> getFullyQualifiedClassNames() {
return this.fullyQualifiedClassNames;
}
public Overview getOverview() {
return overview;
}
}
|
3e1801554222b0a9593f6ca0dac6949cbb3d5043 | 1,837 | java | Java | clothingPOS/src/com/scau/mis/controller/BrandController.java | JodenHe/CPOS | 4bcba7fe6c6674459e552a0c12a2c00d9d5199f0 | [
"MIT"
] | null | null | null | clothingPOS/src/com/scau/mis/controller/BrandController.java | JodenHe/CPOS | 4bcba7fe6c6674459e552a0c12a2c00d9d5199f0 | [
"MIT"
] | null | null | null | clothingPOS/src/com/scau/mis/controller/BrandController.java | JodenHe/CPOS | 4bcba7fe6c6674459e552a0c12a2c00d9d5199f0 | [
"MIT"
] | null | null | null | 21.869048 | 61 | 0.657594 | 10,221 | package com.scau.mis.controller;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.jfinal.core.Controller;
import com.jfinal.log.Log;
import com.scau.mis.model.Brand;
import com.scau.mis.service.BrandService;
/**
* 品牌信息的controller
* @author jodenhe
*
*/
public class BrandController extends Controller {
public static Log log = Log.getLog(BrandController.class);
BrandService service = new BrandService();
/**
* 增加一个品牌
*/
@RequiresPermissions("goods:brand:manage")
public void add(){
Brand brand = getModel(Brand.class);
brand.setCreateTime(new Date());
renderJson(service.addBrand(brand));
}
@RequiresPermissions("goods:brand:manage")
public void delete() {
Map<String, Object> result = new HashMap<String, Object>();
long id = getParaToLong("id");
try {
if (service.delete(id)){
result.put("status", true);
result.put("msg", "操作成功!");
}
else{
result.put("status", false);
result.put("msg", "操作失败!");
}
} catch (Exception e) {
result.put("status", false);
result.put("msg", "该品牌已被使用,请先删除参照此品牌的商品!");
log.warn(e+e.getMessage());
}
renderJson(result);
}
/**
* 更新品牌信息
*/
@RequiresPermissions("goods:brand:manage")
public void update(){
Brand brand = getModel(Brand.class);
renderJson(service.updateBrand(brand));
}
/**
* 获取所有品牌信息
*/
public void getAllBrand(){
renderJson(service.getAllBrand());
}
//验证名称是否存在
public void validateName(){
String name =getPara("name");
if(null!=name&&name.length()>0){
if(service.isExist(name)){
renderJson(" {\"status\":true,\"msg\":\"名称已存在\"} ");
}else{
renderJson(" {\"status\":false,\"msg\":\"名称可用\"} ");
}
}else{
renderJson(" {\"status\":true,\"msg\":\"名称不能为空\"} ");
}
}
}
|
3e1801f5579d7f8e335feb1bcf6c0a30cc3f5b67 | 5,845 | java | Java | Programming/BinaryConversions.java | Salman1057/Java-Programs | 196cdda7d01eadab96297f44dc5175c645288d9a | [
"CC0-1.0"
] | null | null | null | Programming/BinaryConversions.java | Salman1057/Java-Programs | 196cdda7d01eadab96297f44dc5175c645288d9a | [
"CC0-1.0"
] | null | null | null | Programming/BinaryConversions.java | Salman1057/Java-Programs | 196cdda7d01eadab96297f44dc5175c645288d9a | [
"CC0-1.0"
] | null | null | null | 41.197183 | 131 | 0.655726 | 10,222 | import java.util.Scanner;
public class BinaryConversions {
/*
*
* Java Program to convert:
* (1) Binary to Decimal (4) Decimal to Binary (7) Decimal to Octal (10) Decimal to Hexa
* (2) Octal to Decimal (5) Octal to Binary (8) Binary to Octal (11) Binary to Hexa
* (3) Hexa to Decimal (6) Hexa to Binary (9) Hexa to Octal (12) Octal to Hexa
* using wrapper class of the Java.
*
*/
public static void main(String[] args) {
boolean start = true;
while (start) {
System.out.println("\n\t\t\t\t\t Welcome to Binary Calculator\n\n Author: Muhammad Salman\t\t\t\t v1.1");
System.out.println("\n\t\t\t(1) Type 'btd' to convert BINARY TO DECIMAL, 'dtb' to convert DECIMAL TO BINARY. ");
System.out.println("\n\t\t\t(2) Type 'bto' to convert BINARY TO OCTAL, 'otb' to convert OCTAL TO BINARY. ");
System.out.println("\n\t\t\t(3) Type 'bth' to convert BINARY TO HEXA, 'htb' to convert HEXA TO BINARY.");
System.out.println("\n\t\t\t(4) Type 'htd' to convert HEXA TO DECIMAL, 'dth' to convert DECIMAL TO HEXA.");
System.out.println("\n\t\t\t(5) Type 'hto' to convert HEXA TO OCTAL, 'oth' to convert OCTAL TO HEXA.");
System.out.println("\n\t\t\t(6) Type 'otd' to convert OCTAL TO DECIMAL, 'dto' to convert DECIMAL TO OCTAL.");
Scanner input = new Scanner(System.in);
System.out.print("Enter desired option: ");
String inputType = input.nextLine();
if ("btd".equals(inputType)) { // 1-a Binary to Decimal
System.out.print("Enter the Binary number to convert into Decimal: ");
String inputValue = input.nextLine();
int outBTD = Integer.parseInt(inputValue, 2);
System.out.println("Decimal of the Binary " + inputValue + " is " + outBTD + ".");
}
else if ("dtb".equals(inputType)) { // 1-b Decimal to Binary
System.out.print("Enter the Decimal to convert into Binary: ");
int DTB = input.nextInt();
System.out.println("Binary of the Decimal " + DTB + " is " + Integer.toBinaryString(DTB) + ".");
}
else if ("bto".equals(inputType)) { // 2-a Binary to Octal Conversion
System.out.print("Enter the Binary to convert into Octal: ");
String inputValue = input.nextLine();
int BTO = Integer.parseInt(inputValue, 2);
System.out.println("Octal of the binary " + inputValue + " is " + Integer.toOctalString(BTO) + ".");
}
else if ("otb".equals(inputType)) { // 2-b Octal to Binary Conversion
System.out.print("Enter the Octal to convert into Binary: ");
String inputValue = input.nextLine();
int OTB = Integer.parseInt(inputValue, 8);
System.out.println("Binary of the Octal " + inputValue + " is " + Integer.toBinaryString(OTB) + ".");
}
else if ("bth".equals(inputType)) { // 3-a Binary to Hexa Conversion
System.out.print("Enter the Binary to convert into Hexadecimal: ");
String inputValue = input.nextLine();
int BTH = Integer.parseInt(inputValue, 2);
System.out.println("Hexadecimal of the binary " + inputValue + " is " + Integer.toHexString(BTH) + ".");
}
else if ("htb".equals(inputType)) { // 3-b Hexa to Binary Conversion
System.out.print("Enter the Hexadecimal to convert into Binary: ");
String inputValue = input.nextLine();
int HTB = Integer.parseInt(inputValue, 16);
System.out.println("Binary of the Hexadecimal " + inputValue + " is " + Integer.toBinaryString(HTB) + ".");
}
else if ("htd".equals(inputType)) { // 4-a Hexa to Decimal Conversion
System.out.print("Enter the Hexadecimal to convert into Decimal: ");
String inputValue = input.nextLine();
int HTD = Integer.parseInt(inputValue, 16);
System.out.println("Decimal of the Hexadecimal " + inputValue + " is " + HTD + ".");
}
else if ("dth".equals(inputType)) { // 4-b Decimal to Hexa Conversion
System.out.print("Enter the Decimal to convert into Hexadecimal: ");
String inputValue = input.nextLine();
int DTH = Integer.parseInt(inputValue, 10);
System.out.println("Hexadecimal of the Decimal " + inputValue + " is " + Integer.toHexString(DTH) + ".");
}
else if ("hto".equals(inputType)) { // 5-a Hexadecimal to Octal Conversion
System.out.print("Enter the Hexadecimal to convert into Octal: ");
String inputValue = input.nextLine();
int HTO = Integer.parseInt(inputValue, 16);
System.out.println("Octal of the Hexadecimal " + inputValue + " is " + Integer.toOctalString(HTO) + ".");
}
else if ("oth".equals(inputType)) { // 5-b Octal to Hexadecimal Conversion
System.out.print("Enter the Octal to convert into Hexadecimal: ");
String inputValue = input.nextLine();
int OTH = Integer.parseInt(inputValue, 8);
System.out.println("Hexadecimal of the Octal " + inputValue + " is " + Integer.toHexString(OTH) + ".");
}
else if ("otd".equals(inputType)) { // 6-a Octal to Decimal Conversion
System.out.print("Enter the Octal to convert into Decimal: ");
String inputValue = input.nextLine();
int OTD = Integer.parseInt(inputValue, 8);
System.out.println("Decimal of the Octal " + inputValue + " is " + OTD + ".");
}
else if ("dto".equals(inputType)) { // 6-b Decimal to Octal Conversion
System.out.print("Enter the Decimal to convert into Octal: ");
String inputValue = input.nextLine();
int DTO = Integer.parseInt(inputValue, 10);
System.out.println("Octal of the Decimal " + inputValue + " is " + Integer.toOctalString(DTO) + ".");
}
System.out.print("Would you like to run the program again? [Y/n]");
Scanner console = new Scanner(System.in);
String exit = console.nextLine();
if ("n".equals(exit)) {
System.out.println("Thanks for using our Program. Would like to hear your suggestions. Reach me @ [<anpch@example.com>]");
start = false;
console.close();
input.close();
}
}
}
}
|
3e180376a3c0265942cd805f58f6fc4504cbd68e | 24,549 | java | Java | open-metadata-conformance-suite/open-metadata-conformance-suite-server/src/main/java/org/odpi/openmetadata/conformance/tests/repository/RepositoryConformanceTestCase.java | nctrangit/egeria | fd1a76f2510bd90770c5d69974a730de04eef73c | [
"Apache-2.0"
] | 1 | 2020-01-02T10:44:10.000Z | 2020-01-02T10:44:10.000Z | open-metadata-conformance-suite/open-metadata-conformance-suite-server/src/main/java/org/odpi/openmetadata/conformance/tests/repository/RepositoryConformanceTestCase.java | nctrangit/egeria | fd1a76f2510bd90770c5d69974a730de04eef73c | [
"Apache-2.0"
] | null | null | null | open-metadata-conformance-suite/open-metadata-conformance-suite-server/src/main/java/org/odpi/openmetadata/conformance/tests/repository/RepositoryConformanceTestCase.java | nctrangit/egeria | fd1a76f2510bd90770c5d69974a730de04eef73c | [
"Apache-2.0"
] | null | null | null | 41.608475 | 139 | 0.613671 | 10,223 | /* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.openmetadata.conformance.tests.repository;
import org.odpi.openmetadata.conformance.auditlog.ConformanceSuiteAuditCode;
import org.odpi.openmetadata.conformance.beans.OpenMetadataTestCase;
import org.odpi.openmetadata.conformance.workbenches.repository.RepositoryConformanceProfileRequirement;
import org.odpi.openmetadata.conformance.workbenches.repository.RepositoryConformanceWorkPad;
import org.odpi.openmetadata.repositoryservices.auditlog.OMRSAuditLog;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.OMRSMetadataCollection;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.MatchCriteria;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.EntityDetail;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.InstanceProperties;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.InstancePropertyValue;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.InstanceProvenanceType;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.PrimitivePropertyValue;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.typedefs.*;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.repositoryconnector.OMRSRepositoryConnector;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.repositoryconnector.OMRSRepositoryHelper;
import org.odpi.openmetadata.repositoryservices.ffdc.exception.FunctionNotSupportedException;
import java.util.*;
/**
* OpenMetadataTestCase is the superclass for an open metadata conformance test. It manages the
* test environment and reporting.
*/
public abstract class RepositoryConformanceTestCase extends OpenMetadataTestCase
{
private static final String assertion1 = "repository-test-case-base-01";
private static final String assertionMsg1 = "Repository connector supplied to conformance suite.";
private static final String assertion2 = "repository-test-case-base-02";
private static final String assertionMsg2 = "Metadata collection for repository connector supplied to conformance suite.";
protected RepositoryConformanceWorkPad repositoryConformanceWorkPad;
protected OMRSRepositoryConnector cohortRepositoryConnector = null;
private int maxSearchResults = 50;
int successfulExecutionCount = 0;
int unSuccessfulExecutionCount = 0;
/**
* Typical constructor used when the name of the test case id is fixed
*
* @param workPad location for workbench results
* @param testCaseId identifier of test case
* @param testCaseName name of test case
* @param defaultProfileId identifier of default profile (for unexpected exceptions)
* @param defaultRequirementId identifier of default required (for unexpected exceptions)
*/
protected RepositoryConformanceTestCase(RepositoryConformanceWorkPad workPad,
String testCaseId,
String testCaseName,
Integer defaultProfileId,
Integer defaultRequirementId)
{
super(workPad, testCaseId, testCaseName, defaultProfileId, defaultRequirementId);
this.repositoryConformanceWorkPad = workPad;
if (workPad != null)
{
cohortRepositoryConnector = workPad.getTutRepositoryConnector();
maxSearchResults = workPad.getMaxSearchResults();
}
}
/**
* Typical constructor used when the test case id needs to be constructed by th test case code.
*
* @param workPad location for workbench results
* @param defaultProfileId identifier of default profile (for unexpected exceptions)
* @param defaultRequirementId identifier of default required (for unexpected exceptions)
*/
protected RepositoryConformanceTestCase(RepositoryConformanceWorkPad workPad,
Integer defaultProfileId,
Integer defaultRequirementId)
{
super(workPad, defaultProfileId, defaultRequirementId);
this.repositoryConformanceWorkPad = workPad;
if (workPad != null)
{
cohortRepositoryConnector = workPad.getTutRepositoryConnector();
maxSearchResults = workPad.getMaxSearchResults();
}
}
/**
* Log that the test case is starting.
*
* @param methodName calling method name
*/
protected void logTestStart(String methodName)
{
if (workPad != null)
{
OMRSAuditLog auditLog = repositoryConformanceWorkPad.getAuditLog();
ConformanceSuiteAuditCode auditCode = ConformanceSuiteAuditCode.TEST_CASE_INITIALIZING;
auditLog.logRecord(methodName,
auditCode.getLogMessageId(),
auditCode.getSeverity(),
auditCode.getFormattedLogMessage(testCaseId,
testCaseDescriptionURL),
null,
auditCode.getSystemAction(),
auditCode.getUserAction());
}
}
/**
* Log that the test case is ending.
*
* @param methodName calling method name
*/
protected void logTestEnd(String methodName)
{
if (workPad != null)
{
Integer exceptionCount;
if (exceptionBean == null)
{
exceptionCount = 0;
}
else
{
exceptionCount = 1;
}
OMRSAuditLog auditLog = repositoryConformanceWorkPad.getAuditLog();
if (successMessage == null)
{
ConformanceSuiteAuditCode auditCode = ConformanceSuiteAuditCode.TEST_CASE_COMPLETED;
auditLog.logRecord(methodName,
auditCode.getLogMessageId(),
auditCode.getSeverity(),
auditCode.getFormattedLogMessage(testCaseId,
Integer.toString(successfulAssertions.size()),
Integer.toString(unsuccessfulAssertions.size()),
Integer.toString(exceptionCount),
Integer.toString(discoveredProperties.size())),
null,
auditCode.getSystemAction(),
auditCode.getUserAction());
}
else
{
ConformanceSuiteAuditCode auditCode = ConformanceSuiteAuditCode.TEST_CASE_COMPLETED_SUCCESSFULLY;
auditLog.logRecord(methodName,
auditCode.getLogMessageId(),
auditCode.getSeverity(),
auditCode.getFormattedLogMessage(testCaseId,
Integer.toString(successfulAssertions.size()),
Integer.toString(unsuccessfulAssertions.size()),
Integer.toString(exceptionCount),
Integer.toString(discoveredProperties.size()),
successMessage),
null,
auditCode.getSystemAction(),
auditCode.getUserAction());
}
}
}
/**
* For test cases that are invoked many times, count the successful invocations.
*/
protected void incrementSuccessfulCount()
{
successfulExecutionCount ++;
}
/**
* For test cases that are invoked many times, count the unsuccessful invocations.
*/
protected void incrementUnsuccessfulCount()
{
unSuccessfulExecutionCount ++;
}
/**
* Verify that the name of the type (which forms part of the test id) is not null.
*
* @param typeName name of the type being tested
* @param rootTestCaseId base test case Id
* @param testCaseName name of the test case
* @return typeName (or "null" if null so messages are displayed properly.)
*/
protected String updateTestIdByType(String typeName,
String rootTestCaseId,
String testCaseName)
{
String testTypeName = typeName;
if (testTypeName == null)
{
testTypeName = "<null>";
}
super.updateTestId(rootTestCaseId, rootTestCaseId + "-" + testTypeName, testCaseName);
return testTypeName;
}
/**
* Return the page size to use for testing the repository.
*
* @return page size
*/
protected int getMaxSearchResults() {
return maxSearchResults;
}
/**
* Return the repository connector generated from the cohort registration event.
*
* @return OMRSRepositoryConnector object
* @throws Exception if the connector is not properly set up.
*/
protected OMRSRepositoryConnector getRepositoryConnector() throws Exception
{
assertCondition((cohortRepositoryConnector != null),
assertion1,
assertionMsg1,
RepositoryConformanceProfileRequirement.REPOSITORY_CONNECTOR.getProfileId(),
RepositoryConformanceProfileRequirement.REPOSITORY_CONNECTOR.getRequirementId());
return cohortRepositoryConnector;
}
/**
* Return the metadata collection used to call the repository.
*
* @return OMRSMetadataCollection object
* @throws Exception if the connector is not properly set up.
*/
protected OMRSMetadataCollection getMetadataCollection() throws Exception
{
OMRSMetadataCollection metadataCollection = null;
if (cohortRepositoryConnector != null)
{
metadataCollection = cohortRepositoryConnector.getMetadataCollection();
}
assertCondition((cohortRepositoryConnector != null),
assertion1,
assertionMsg1,
RepositoryConformanceProfileRequirement.REPOSITORY_CONNECTOR.getProfileId(),
RepositoryConformanceProfileRequirement.REPOSITORY_CONNECTOR.getRequirementId());
assertCondition((metadataCollection != null),
assertion2,
assertionMsg2,
RepositoryConformanceProfileRequirement.REPOSITORY_CONNECTOR.getProfileId(),
RepositoryConformanceProfileRequirement.REPOSITORY_CONNECTOR.getRequirementId());
return metadataCollection;
}
/**
* Create a primitive property value for the requested property.
*
* @param propertyName name of the property
* @param propertyType type of the property
* @return PrimitivePropertyValue object
*/
private PrimitivePropertyValue getPrimitivePropertyValue(String propertyName,
PrimitiveDef propertyType)
{
PrimitivePropertyValue propertyValue = new PrimitivePropertyValue();
propertyValue.setPrimitiveDefCategory(propertyType.getPrimitiveDefCategory());
switch (propertyType.getPrimitiveDefCategory())
{
case OM_PRIMITIVE_TYPE_STRING:
propertyValue.setPrimitiveValue("Test" + propertyName + "Value");
break;
case OM_PRIMITIVE_TYPE_DATE:
Date date = new Date(); // Date and Time now
Long timestamp = date.getTime();
propertyValue.setPrimitiveValue(timestamp); // Dates are stored as Long values
break;
case OM_PRIMITIVE_TYPE_INT:
propertyValue.setPrimitiveValue(42);
break;
case OM_PRIMITIVE_TYPE_BOOLEAN:
propertyValue.setPrimitiveValue(true);
break;
case OM_PRIMITIVE_TYPE_SHORT:
propertyValue.setPrimitiveValue(new Short("34"));
break;
case OM_PRIMITIVE_TYPE_BYTE:
propertyValue.setPrimitiveValue(new Byte("7"));
break;
case OM_PRIMITIVE_TYPE_CHAR:
propertyValue.setPrimitiveValue(new Character('o'));
break;
case OM_PRIMITIVE_TYPE_LONG:
propertyValue.setPrimitiveValue(new Long(2452));
break;
case OM_PRIMITIVE_TYPE_FLOAT:
propertyValue.setPrimitiveValue(new Float(245332));
break;
case OM_PRIMITIVE_TYPE_DOUBLE:
propertyValue.setPrimitiveValue(new Double(2459992));
break;
case OM_PRIMITIVE_TYPE_BIGDECIMAL:
propertyValue.setPrimitiveValue(new Double(245339992));
break;
case OM_PRIMITIVE_TYPE_BIGINTEGER:
propertyValue.setPrimitiveValue(new Double(245559992));
break;
case OM_PRIMITIVE_TYPE_UNKNOWN:
break;
}
return propertyValue;
}
/**
* Return instance properties for the properties defined in the TypeDef, but do not include properties from supertypes.
*
* @param typeDefAttributes attributes defined for a specific type
* @return properties for an instance of this type
*/
protected InstanceProperties getPropertiesForInstance(List<TypeDefAttribute> typeDefAttributes)
{
InstanceProperties properties = null;
if (typeDefAttributes != null)
{
Map<String, InstancePropertyValue> propertyMap = new HashMap<>();
for (TypeDefAttribute typeDefAttribute : typeDefAttributes)
{
String attributeName = typeDefAttribute.getAttributeName();
AttributeTypeDef attributeType = typeDefAttribute.getAttributeType();
AttributeTypeDefCategory category = attributeType.getCategory();
switch(category)
{
case PRIMITIVE:
PrimitiveDef primitiveDef = (PrimitiveDef)attributeType;
propertyMap.put(attributeName, this.getPrimitivePropertyValue(attributeName, primitiveDef));
break;
}
}
if (! propertyMap.isEmpty())
{
properties = new InstanceProperties();
properties.setInstanceProperties(propertyMap);
}
}
return properties;
}
/**
* Return instance properties for the properties defined in the TypeDef and all of its supertypes.
*
* @param userId calling user
* @param typeDef the definition of the type
* @return properties for an instance of this type
* @throws Exception problem manipulating types
*/
protected InstanceProperties getAllPropertiesForInstance(String userId, TypeDef typeDef) throws Exception
{
InstanceProperties properties = null;
// Recursively gather all the TypeDefAttributes for the supertype hierarchy...
List<TypeDefAttribute> allTypeDefAttributes = getPropertiesForTypeDef(userId, typeDef);
if (allTypeDefAttributes != null)
{
Map<String, InstancePropertyValue> propertyMap = new HashMap<>();
for (TypeDefAttribute typeDefAttribute : allTypeDefAttributes)
{
String attributeName = typeDefAttribute.getAttributeName();
AttributeTypeDef attributeType = typeDefAttribute.getAttributeType();
AttributeTypeDefCategory category = attributeType.getCategory();
switch(category)
{
case PRIMITIVE:
PrimitiveDef primitiveDef = (PrimitiveDef)attributeType;
propertyMap.put(attributeName, this.getPrimitivePropertyValue(attributeName, primitiveDef));
break;
}
}
if (! propertyMap.isEmpty())
{
properties = new InstanceProperties();
properties.setInstanceProperties(propertyMap);
}
}
return properties;
}
/**
* Return instance properties for only the mandatory properties defined in the TypeDef and all of its supertypes.
*
* @param userId calling user
* @param typeDef the definition of the type
* @return properties for an instance of this type
* @throws Exception problem manipulating types
*/
protected InstanceProperties getMinPropertiesForInstance(String userId, TypeDef typeDef) throws Exception
{
/*
* Recursively gather all the TypeDefAttributes for the supertype hierarchy...
*/
List<TypeDefAttribute> allTypeDefAttributes = getPropertiesForTypeDef(userId, typeDef);
Map<String, InstancePropertyValue> propertyMap = new HashMap<>();
if (allTypeDefAttributes != null)
{
for (TypeDefAttribute typeDefAttribute : allTypeDefAttributes)
{
String attributeName = typeDefAttribute.getAttributeName();
AttributeTypeDef attributeType = typeDefAttribute.getAttributeType();
AttributeTypeDefCategory category = attributeType.getCategory();
AttributeCardinality attributeCardinality = typeDefAttribute.getAttributeCardinality();
if (attributeCardinality == AttributeCardinality.AT_LEAST_ONE_ORDERED ||
attributeCardinality == AttributeCardinality.AT_LEAST_ONE_UNORDERED) {
switch (category) {
case PRIMITIVE:
PrimitiveDef primitiveDef = (PrimitiveDef) attributeType;
propertyMap.put(attributeName, this.getPrimitivePropertyValue(attributeName, primitiveDef));
break;
}
}
}
}
/*
* Get an InstanceProperties, even if there are no properties in the propertyMap - you cannot pass a null
* to updateEntityProperties. So if necessary, pass an empty InstanceProperties object.
*/
InstanceProperties properties = new InstanceProperties();
properties.setInstanceProperties(propertyMap);
return properties;
}
/**
* Recursively walk the supertype hierarchy starting at the given typeDef, and collect all the TypeDefAttributes.
*
* This method does not use the properties defined in the TypeDef provided since that TypeDef is
* from the gallery returned by the repository connector. Instead it uses the name of the TypeDef
* to look up the TypeDef in the RepositoryHelper - using the Known types rather than the Active types.
* This is to ensure consistency with the open metadata type definition.
*
*
* @param userId the userId of the caller, needed for retrieving type definitions
* @param typeDef the definition of the type
* @return properties for an instance of this type
* @throws Exception problem manipulating types
*/
protected List<TypeDefAttribute> getPropertiesForTypeDef(String userId, TypeDef typeDef) throws Exception
{
OMRSRepositoryHelper repositoryHelper = cohortRepositoryConnector.getRepositoryHelper();
List<TypeDefAttribute> propDefs = new ArrayList<>();
/*
* Look at the supertype (if any) first and then get any properties for the current type def
*/
/*
* Move up the supertype hierarchy until you hit the top
*/
if (typeDef.getSuperType() != null)
{
TypeDefLink superTypeDefLink = typeDef.getSuperType();
String superTypeName = superTypeDefLink.getName();
TypeDef superTypeDef = repositoryHelper.getTypeDefByName(userId, superTypeName);
List<TypeDefAttribute> inheritedProps = getPropertiesForTypeDef(userId, superTypeDef);
if (inheritedProps != null && !inheritedProps.isEmpty())
{
propDefs.addAll(inheritedProps);
}
}
/*
* Add any properties defined for the current type, again using the known type from the repository helper
*/
TypeDef knownTypeDef = repositoryHelper.getTypeDefByName(userId, typeDef.getName());
List<TypeDefAttribute> currentTypePropDefs = knownTypeDef.getPropertiesDefinition();
if (currentTypePropDefs != null && !currentTypePropDefs.isEmpty())
{
propDefs.addAll(currentTypePropDefs);
}
return propDefs;
}
/**
* Returns the appropriate entity definition for the supplied entity identifiers.
* This may be the entity specified, or a subclass of the entity that is supported.
*
* @param supportedEntityDefs map of entity type name to entity type definition
* @param entityIdentifiers guid and name of desired entity definition
* @return entity definition (EntityDef)
*/
public EntityDef getEntityDef(Map<String, EntityDef> supportedEntityDefs,
TypeDefLink entityIdentifiers)
{
EntityDef entityDef = null;
OMRSRepositoryHelper repositoryHelper = cohortRepositoryConnector.getRepositoryHelper();
/*
* Need to look up entity def (or a suitable subclass).
*/
String candidateTypeDef = entityIdentifiers.getName();
for (EntityDef supportedEntityDef : supportedEntityDefs.values())
{
if (repositoryHelper.isTypeOf(cohortRepositoryConnector.getRepositoryName(), supportedEntityDef.getName(), candidateTypeDef)) {
entityDef = supportedEntityDef;
break;
}
}
return entityDef;
}
/**
* Adds an entity of the requested type to the repository.
*
* @param userId userId for the new entity
* @param metadataCollection metadata connection to access the repository
* @param entityDef type of entity to create
* @return new entity
* @throws Exception error in create
*/
public EntityDetail addEntityToRepository(String userId,
OMRSMetadataCollection metadataCollection,
EntityDef entityDef) throws Exception
{
/*
* Supply all properties for the instance, including those inherited from supertypes, since they may be mandatory.
* An alternative here would be to use getMinPropertiesForInstance, but providing all properties creates a logically
* complete entity
*/
InstanceProperties properties = this.getAllPropertiesForInstance(userId, entityDef);
return metadataCollection.addEntity(userId, entityDef.getGUID(), properties, null, null );
}
}
|
3e18046d42ed8798faaec16e2357ea6cbe83b06b | 2,127 | java | Java | common/arcus-client/src/main/java/com/iris/client/message/ClientMessageSerializer.java | eanderso/arcusplatform | a2293efa1cd8e884e6bedbe9c51bf29832ba8652 | [
"Apache-2.0"
] | null | null | null | common/arcus-client/src/main/java/com/iris/client/message/ClientMessageSerializer.java | eanderso/arcusplatform | a2293efa1cd8e884e6bedbe9c51bf29832ba8652 | [
"Apache-2.0"
] | null | null | null | common/arcus-client/src/main/java/com/iris/client/message/ClientMessageSerializer.java | eanderso/arcusplatform | a2293efa1cd8e884e6bedbe9c51bf29832ba8652 | [
"Apache-2.0"
] | null | null | null | 32.723077 | 96 | 0.707569 | 10,224 | /*
* Copyright 2019 Arcus Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iris.client.message;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.iris.gson.ClientMessageTypeAdapter;
import com.iris.gson.DateTypeAdapter;
import com.iris.gson.TypeTypeAdapterFactory;
import com.iris.messages.ClientMessage;
import java.util.Date;
public class ClientMessageSerializer {
private final Gson gson;
private static class ClientInstanceHolder {
private static final ClientMessageSerializer instance = new ClientMessageSerializer();
}
private ClientMessageSerializer() {
gson = new GsonBuilder()
.registerTypeAdapterFactory(new TypeTypeAdapterFactory())
.registerTypeAdapter(Date.class, new DateTypeAdapter())
.registerTypeAdapter(ClientMessage.class, new ClientMessageTypeAdapter())
.create();
}
private static ClientMessageSerializer instance() {
return ClientInstanceHolder.instance;
}
/**
* @param json The JSON string to deserialize
* @param clazz The class of object to deserialize into
* @param <T> Type of object deserialized
* @return The instance of the deserialized class
*/
public static <T> T deserialize(String json, Class<T> clazz) {
return instance().gson.fromJson(json, clazz);
}
/**
* @param obj The object to serialize
* @return JSON string representation of the object
*/
public static String serialize(Object obj) {
return instance().gson.toJson(obj);
}
}
|
3e1804bea89d05c00ec2233f563f8afa43612108 | 762 | java | Java | src/garethflowers/retagit/Main.java | garethflowers/retagit | c8486a0a36561f69dbce9bdb2eb346ffc453aae7 | [
"MIT"
] | 1 | 2020-11-10T05:53:53.000Z | 2020-11-10T05:53:53.000Z | src/garethflowers/retagit/Main.java | garethflowers/retagit | c8486a0a36561f69dbce9bdb2eb346ffc453aae7 | [
"MIT"
] | null | null | null | src/garethflowers/retagit/Main.java | garethflowers/retagit | c8486a0a36561f69dbce9bdb2eb346ffc453aae7 | [
"MIT"
] | null | null | null | 21.771429 | 70 | 0.485564 | 10,225 | package garethflowers.retagit;
/**
* Main
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager
.getSystemLookAndFeelClassName());
} catch (Exception ex) {
System.out.println(ex.getStackTrace());
}
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
new MainGUI();
} catch (Exception ex) {
System.out.println(ex.getStackTrace());
}
}
});
}
private Main() {
}
}
|
3e180544c4aeb070fe5fa88984bd40007b0581c8 | 2,419 | java | Java | srv/src/main/java/com/yankaizhang/movielikes/srv/util/SecurityUtils.java | dzzhyk/movielikes | 074c214adca1802dd3f202a3888e956728758dfe | [
"MIT"
] | 1 | 2022-03-18T02:27:42.000Z | 2022-03-18T02:27:42.000Z | srv/src/main/java/com/yankaizhang/movielikes/srv/util/SecurityUtils.java | dzzhyk/movielikes | 074c214adca1802dd3f202a3888e956728758dfe | [
"MIT"
] | null | null | null | srv/src/main/java/com/yankaizhang/movielikes/srv/util/SecurityUtils.java | dzzhyk/movielikes | 074c214adca1802dd3f202a3888e956728758dfe | [
"MIT"
] | null | null | null | 22.398148 | 85 | 0.610583 | 10,226 | package com.yankaizhang.movielikes.srv.util;
import com.yankaizhang.movielikes.srv.constant.HttpStatus;
import com.yankaizhang.movielikes.srv.exception.ServiceException;
import com.yankaizhang.movielikes.srv.security.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* 安全服务工具类
*
* @author ruoyi
*/
public class SecurityUtils
{
/**
* 用户ID
**/
public static Long getUserId()
{
try
{
return getLoginUser().getUserId();
}
catch (Exception e)
{
throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED);
}
}
/**
* 获取用户账户
**/
public static String getUsername()
{
try
{
return getLoginUser().getUsername();
}
catch (Exception e)
{
throw new ServiceException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
}
}
/**
* 获取用户
**/
public static LoginUser getLoginUser()
{
try
{
return (LoginUser) getAuthentication().getPrincipal();
}
catch (Exception e)
{
throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
}
}
/**
* 获取Authentication
*/
public static Authentication getAuthentication()
{
return SecurityContextHolder.getContext().getAuthentication();
}
/**
* 生成BCryptPasswordEncoder密码
*
* @param password 密码
* @return 加密字符串
*/
public static String encryptPassword(String password)
{
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.encode(password);
}
/**
* 判断密码是否相同
*
* @param rawPassword 真实密码
* @param encodedPassword 加密后字符
* @return 结果
*/
public static boolean matchesPassword(String rawPassword, String encodedPassword)
{
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.matches(rawPassword, encodedPassword);
}
/**
* 是否为管理员
*
* @param userId 用户ID
* @return 结果
*/
public static boolean isAdmin(Long userId)
{
return userId != null && 1L == userId;
}
}
|
3e1806aeaef647b333a74069ad9aead39ebab366 | 2,748 | java | Java | lia-ui/src/main/java/com/lithium/community/android/ui/components/adapters/LiSupportHomeViewPagerAdapter.java | lithiumtech/li-android-sdk | 690abbd5fac12751f0dbae6d77eb2e36d1721924 | [
"Apache-2.0"
] | 2 | 2019-01-09T15:32:27.000Z | 2019-03-03T11:43:38.000Z | lia-ui/src/main/java/com/lithium/community/android/ui/components/adapters/LiSupportHomeViewPagerAdapter.java | lithiumtech/li-android-sdk | 690abbd5fac12751f0dbae6d77eb2e36d1721924 | [
"Apache-2.0"
] | 7 | 2018-08-09T05:35:20.000Z | 2019-09-19T09:36:28.000Z | lia-ui/src/main/java/com/lithium/community/android/ui/components/adapters/LiSupportHomeViewPagerAdapter.java | lithiumtech/lia-sdk-android | 690abbd5fac12751f0dbae6d77eb2e36d1721924 | [
"Apache-2.0"
] | 2 | 2018-12-11T10:03:29.000Z | 2020-07-20T19:54:41.000Z | 33.512195 | 100 | 0.711426 | 10,227 | /*
* Copyright 2018 Lithium Technologies Pvt Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lithium.community.android.ui.components.adapters;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.ViewGroup;
import com.lithium.community.android.ui.R;
import com.lithium.community.android.ui.components.activities.LiSupportHomeActivity;
import com.lithium.community.android.ui.components.fragments.LiMessageListFragment;
import com.lithium.community.android.ui.components.fragments.LiUserActivityFragment;
/**
* {@link FragmentStatePagerAdapter} that displays the two tabs on the {@link LiSupportHomeActivity}
*/
public class LiSupportHomeViewPagerAdapter extends FragmentStatePagerAdapter {
private FragmentManager manager;
private Bundle articleFragmentBundle;
private Bundle questionFragmentBundle;
private Activity activity;
public LiSupportHomeViewPagerAdapter(Activity activity, FragmentManager manager,
Bundle articleFragmentBundle,
Bundle questionFragmentBundle) {
super(manager);
this.manager = manager;
this.articleFragmentBundle = articleFragmentBundle;
this.questionFragmentBundle = questionFragmentBundle;
this.activity = activity;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return LiMessageListFragment.newInstance(articleFragmentBundle);
case 1:
return LiUserActivityFragment.newInstance(questionFragmentBundle);
default:
return null;
}
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return activity.getResources().getString(R.string.li_support_articles);
case 1:
return activity.getResources().getString(R.string.li_support_my_questions);
default:
return null;
}
}
}
|
3e1807fbcc6d093c2a534d9050c14de02ce27f9e | 3,599 | java | Java | text/src/test/java/docs/javadsl/CharsetCodingFlowsDoc.java | gkatzioura/alpakka | 0153ae7d3cad6846742b807f06384b136f26c77a | [
"Apache-2.0"
] | 1,280 | 2016-10-13T13:38:21.000Z | 2022-03-22T14:48:37.000Z | text/src/test/java/docs/javadsl/CharsetCodingFlowsDoc.java | gkatzioura/alpakka | 0153ae7d3cad6846742b807f06384b136f26c77a | [
"Apache-2.0"
] | 2,100 | 2016-10-20T06:22:19.000Z | 2022-03-31T09:30:07.000Z | text/src/test/java/docs/javadsl/CharsetCodingFlowsDoc.java | gkatzioura/alpakka | 0153ae7d3cad6846742b807f06384b136f26c77a | [
"Apache-2.0"
] | 756 | 2016-10-20T09:44:07.000Z | 2022-03-27T10:25:32.000Z | 32.718182 | 90 | 0.70853 | 10,228 | /*
* Copyright (C) 2016-2020 Lightbend Inc. <https://www.lightbend.com>
*/
package docs.javadsl;
import akka.actor.ActorSystem;
// #encoding
import akka.stream.alpakka.testkit.javadsl.LogCapturingJunit4;
import akka.stream.alpakka.text.javadsl.TextFlow;
import akka.stream.IOResult;
import akka.stream.javadsl.FileIO;
import akka.stream.javadsl.Sink;
import akka.stream.javadsl.Source;
import akka.util.ByteString;
import java.nio.charset.StandardCharsets;
// #encoding
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CharsetCodingFlowsDoc {
@Rule public final LogCapturingJunit4 logCapturing = new LogCapturingJunit4();
private static final ActorSystem system = ActorSystem.create();
@AfterClass
public static void afterAll() {
system.terminate();
}
@Test
public void encodingExample() throws Exception {
Path targetFile = Paths.get("target/outdata.txt");
Properties properties = System.getProperties();
List<String> strings =
properties.stringPropertyNames().stream()
.map(p -> p + " -> " + properties.getProperty(p))
.collect(Collectors.toList());
// #encoding
Source<String, ?> stringSource = // ...
// #encoding
Source.from(strings);
final CompletionStage<IOResult> streamCompletion =
// #encoding
stringSource
.via(TextFlow.encoding(StandardCharsets.US_ASCII))
.intersperse(ByteString.fromString("\n"))
.runWith(FileIO.toPath(targetFile), system);
// #encoding
IOResult result = streamCompletion.toCompletableFuture().get(1, TimeUnit.SECONDS);
assertTrue("result is greater than 50 bytes", result.count() > 50L);
}
@Test
public void decodingExample() throws Exception {
ByteString utf16bytes = ByteString.fromString("äåûßêëé", StandardCharsets.UTF_16);
// #decoding
Source<ByteString, ?> byteStringSource = // ...
// #decoding
Source.single(utf16bytes);
CompletionStage<List<String>> streamCompletion =
// #decoding
byteStringSource
.via(TextFlow.decoding(StandardCharsets.UTF_16))
.runWith(Sink.seq(), system);
// #decoding
List<String> result = streamCompletion.toCompletableFuture().get(1, TimeUnit.SECONDS);
assertEquals(Arrays.asList("äåûßêëé"), result);
}
@Test
public void transcodingExample() throws Exception {
Path targetFile = Paths.get("target/outdata.txt");
ByteString utf16bytes = ByteString.fromString("äåûßêëé", StandardCharsets.UTF_16);
// #transcoding
Source<ByteString, ?> byteStringSource = // ...
// #transcoding
Source.single(utf16bytes);
CompletionStage<IOResult> streamCompletion =
// #transcoding
byteStringSource
.via(TextFlow.transcoding(StandardCharsets.UTF_16, StandardCharsets.UTF_8))
.runWith(FileIO.toPath(targetFile), system);
// #transcoding
IOResult result = streamCompletion.toCompletableFuture().get(1, TimeUnit.SECONDS);
assertTrue("result is greater than 5 bytes", result.count() > 5L);
}
}
|
3e1808c26f372198c4152244e713566b96c49845 | 1,923 | java | Java | api-stubs_intermediates/srcjars/android/telephony/TelephonyProtoEnums.java | team-miracle/android-libs | a6fbe765c2b862c25950ec339b6345b1c6bd7c43 | [
"Apache-2.0"
] | 1 | 2020-12-24T01:33:37.000Z | 2020-12-24T01:33:37.000Z | test-api-stubs_intermediates/srcjars/android/telephony/TelephonyProtoEnums.java | team-miracle/android-libs | a6fbe765c2b862c25950ec339b6345b1c6bd7c43 | [
"Apache-2.0"
] | null | null | null | test-api-stubs_intermediates/srcjars/android/telephony/TelephonyProtoEnums.java | team-miracle/android-libs | a6fbe765c2b862c25950ec339b6345b1c6bd7c43 | [
"Apache-2.0"
] | null | null | null | 42.733333 | 77 | 0.76235 | 10,229 | // Generated by protoc-gen-javastream. DO NOT MODIFY.
// source: frameworks/base/core/proto/android/telephony/enums.proto
package android.telephony;
/** @hide */
public final class TelephonyProtoEnums {
// enum DataConnectionPowerStateEnum
public static final int DATA_CONNECTION_POWER_STATE_LOW = 1;
public static final int DATA_CONNECTION_POWER_STATE_MEDIUM = 2;
public static final int DATA_CONNECTION_POWER_STATE_HIGH = 3;
public static final int DATA_CONNECTION_POWER_STATE_UNKNOWN = 2147483647;
// enum NetworkTypeEnum
public static final int NETWORK_TYPE_UNKNOWN = 0;
public static final int NETWORK_TYPE_GPRS = 1;
public static final int NETWORK_TYPE_EDGE = 2;
public static final int NETWORK_TYPE_UMTS = 3;
public static final int NETWORK_TYPE_CDMA = 4;
public static final int NETWORK_TYPE_EVDO_0 = 5;
public static final int NETWORK_TYPE_EVDO_A = 6;
public static final int NETWORK_TYPE_1XRTT = 7;
public static final int NETWORK_TYPE_HSDPA = 8;
public static final int NETWORK_TYPE_HSUPA = 9;
public static final int NETWORK_TYPE_HSPA = 10;
public static final int NETWORK_TYPE_IDEN = 11;
public static final int NETWORK_TYPE_EVDO_B = 12;
public static final int NETWORK_TYPE_LTE = 13;
public static final int NETWORK_TYPE_EHRPD = 14;
public static final int NETWORK_TYPE_HSPAP = 15;
public static final int NETWORK_TYPE_GSM = 16;
public static final int NETWORK_TYPE_TD_SCDMA = 17;
public static final int NETWORK_TYPE_IWLAN = 18;
public static final int NETWORK_TYPE_LTE_CA = 19;
// enum SignalStrengthEnum
public static final int SIGNAL_STRENGTH_NONE_OR_UNKNOWN = 0;
public static final int SIGNAL_STRENGTH_POOR = 1;
public static final int SIGNAL_STRENGTH_MODERATE = 2;
public static final int SIGNAL_STRENGTH_GOOD = 3;
public static final int SIGNAL_STRENGTH_GREAT = 4;
}
|
3e180926e25984f4770317c3c22fcd158642fb46 | 3,012 | java | Java | app/src/main/java/com/example/m8s1/umbrella/MainActivity.java | MADiazS2934/umbrella | a7374ffabcc6ab4471068ca3fc65106db6e95f30 | [
"MIT"
] | null | null | null | app/src/main/java/com/example/m8s1/umbrella/MainActivity.java | MADiazS2934/umbrella | a7374ffabcc6ab4471068ca3fc65106db6e95f30 | [
"MIT"
] | null | null | null | app/src/main/java/com/example/m8s1/umbrella/MainActivity.java | MADiazS2934/umbrella | a7374ffabcc6ab4471068ca3fc65106db6e95f30 | [
"MIT"
] | null | null | null | 27.888889 | 83 | 0.623506 | 10,230 | package com.example.m8s1.umbrella;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import static com.example.m8s1.umbrella.Umbrella.ImperialOrCelsius;
public class MainActivity extends AppCompatActivity {
private EditText userInput;
//TAG for some logs
private static final String TAG = "MainActivity";
//Static EXTRA_MESSAGE for the intent
public final static String EXTRA_MESSAGE = "com.example.m8s1.umbrella.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: ");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create andBind all Views with their correct ID
userInput = (EditText) findViewById(R.id.editText);
RadioButton radioButtonC = (RadioButton) findViewById(R.id.radioButtonC);
RadioButton radioButtonF = (RadioButton) findViewById(R.id.radioButtonF);
//When you click View.onClickListener most of the code gets auto generated
// This is to set our own listener
View.OnClickListener ourOnclickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
//onClick Method with an Intent
Intent intent = new Intent(MainActivity.this, Umbrella.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
switch(view.getId()){
case R.id.radioButtonC:
ImperialOrCelsius = 1;
break;
case R.id.radioButtonF:
ImperialOrCelsius = 2;
break;
//same for the rest
}
}
};
//Add ourListener to both RadioButtons
radioButtonC.setOnClickListener(ourOnclickListener);
radioButtonF.setOnClickListener(ourOnclickListener);
}
//Pending Implementations
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onRestart() {
Log.d(TAG, "onRestart: in");
super.onRestart();
Log.d(TAG, "onRestart: out");
}
}
|
3e18096e1d51f70f7e2cd0e409c2e75f29fdd32e | 617 | java | Java | src/main/java/com/plugin/frege/gradle/GradleFregeException.java | IntelliJ-Frege/intellij-frege | cd582ae94db84d17b12e201b17ebd8a94f5d453c | [
"Apache-2.0"
] | 31 | 2021-06-18T10:44:15.000Z | 2022-02-15T00:29:39.000Z | src/main/java/com/plugin/frege/gradle/GradleFregeException.java | IntelliJ-Frege/intellij-frege | cd582ae94db84d17b12e201b17ebd8a94f5d453c | [
"Apache-2.0"
] | 42 | 2021-06-19T00:06:23.000Z | 2022-02-20T21:42:36.000Z | src/main/java/com/plugin/frege/gradle/GradleFregeException.java | IntelliJ-Frege/intellij-frege | cd582ae94db84d17b12e201b17ebd8a94f5d453c | [
"Apache-2.0"
] | 2 | 2021-02-28T10:42:30.000Z | 2021-05-10T21:19:58.000Z | 25.708333 | 124 | 0.701783 | 10,231 | package com.plugin.frege.gradle;
public class GradleFregeException extends Exception {
public GradleFregeException() {
super();
}
public GradleFregeException(String message) {
super(message);
}
public GradleFregeException(String message, Throwable cause) {
super(message, cause);
}
public GradleFregeException(Throwable cause) {
super(cause);
}
protected GradleFregeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
3e18097df2df83980528e95501467b50e37afc1f | 3,769 | java | Java | javar/jdk8-analysis/src/com/sun/xml/internal/ws/util/pipe/StandaloneTubeAssembler.java | vitahlin/kennen | b0de36d3b6e766b59291d885a0699b6be59318a7 | [
"MIT"
] | 12 | 2018-04-04T12:47:40.000Z | 2022-01-02T04:36:38.000Z | openjdk-8u45-b14/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/util/pipe/StandaloneTubeAssembler.java | ams-ts-ikvm-bag/ikvm-src | 60009f5bdb4c9db68121f393b8b4c790a326bd32 | [
"Zlib"
] | 2 | 2020-07-19T08:29:50.000Z | 2020-07-21T01:20:56.000Z | openjdk-8u45-b14/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/util/pipe/StandaloneTubeAssembler.java | ams-ts-ikvm-bag/ikvm-src | 60009f5bdb4c9db68121f393b8b4c790a326bd32 | [
"Zlib"
] | 1 | 2020-11-04T07:02:06.000Z | 2020-11-04T07:02:06.000Z | 40.095745 | 87 | 0.695145 | 10,232 | /*
* Copyright (c) 1997, 2012, 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package com.sun.xml.internal.ws.util.pipe;
import com.sun.istack.internal.NotNull;
import com.sun.xml.internal.ws.api.pipe.ClientTubeAssemblerContext;
import com.sun.xml.internal.ws.api.pipe.ServerTubeAssemblerContext;
import com.sun.xml.internal.ws.api.pipe.Tube;
import com.sun.xml.internal.ws.api.pipe.TubelineAssembler;
/**
* Default Pipeline assembler for JAX-WS client and server side runtimes. It
* assembles various pipes into a pipeline that a message needs to be passed
* through.
*
* @author Jitendra Kotamraju
*/
public class StandaloneTubeAssembler implements TubelineAssembler {
@NotNull
public Tube createClient(ClientTubeAssemblerContext context) {
Tube head = context.createTransportTube();
head = context.createSecurityTube(head);
if (dump) {
// for debugging inject a dump pipe. this is left in the production code,
// as it would be very handy for a trouble-shooting at the production site.
head = context.createDumpTube("client", System.out, head);
}
head = context.createWsaTube(head);
head = context.createClientMUTube(head);
head = context.createValidationTube(head);
return context.createHandlerTube(head);
}
/**
* On Server-side, HandlerChains cannot be changed after it is deployed.
* During assembling the Pipelines, we can decide if we really need a
* SOAPHandlerPipe and LogicalHandlerPipe for a particular Endpoint.
*/
public Tube createServer(ServerTubeAssemblerContext context) {
Tube head = context.getTerminalTube();
head = context.createValidationTube(head);
head = context.createHandlerTube(head);
head = context.createMonitoringTube(head);
head = context.createServerMUTube(head);
head = context.createWsaTube(head);
if (dump) {
// for debugging inject a dump pipe. this is left in the production code,
// as it would be very handy for a trouble-shooting at the production site.
head = context.createDumpTube("server", System.out, head);
}
head = context.createSecurityTube(head);
return head;
}
/**
* Are we going to dump the message to System.out?
*/
public static final boolean dump;
static {
boolean b = false;
try {
b = Boolean.getBoolean(StandaloneTubeAssembler.class.getName()+".dump");
} catch (Throwable t) {
// treat it as false
}
dump = b;
}
}
|
3e180a56c2a76fcd4aa20b57d78e0f070b3e1510 | 2,615 | java | Java | api/src/main/java/au/com/digitalspider/biblegame/service/LoginService.java | digitalspider/biblegame | 54105bca1c3560713530a4991edf61615510aa7b | [
"Apache-2.0"
] | null | null | null | api/src/main/java/au/com/digitalspider/biblegame/service/LoginService.java | digitalspider/biblegame | 54105bca1c3560713530a4991edf61615510aa7b | [
"Apache-2.0"
] | null | null | null | api/src/main/java/au/com/digitalspider/biblegame/service/LoginService.java | digitalspider/biblegame | 54105bca1c3560713530a4991edf61615510aa7b | [
"Apache-2.0"
] | null | null | null | 35.337838 | 117 | 0.798088 | 10,233 | package au.com.digitalspider.biblegame.service;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import au.com.digitalspider.biblegame.model.User;
@Service
public class LoginService {
@Autowired
private TokenHelperService tokenHelperService;
@Autowired
private UserService userService;
@Autowired
private AuthenticationManager authenticationManager;
private BCryptPasswordEncoder getPasswordEncoder() {
return userService.getEncoder();
}
public User createUser(String email, String username, String password) {
userService.validateEmail(email);
userService.validateUsername(username);
userService.validatePassword(password);
User user = new User().withName(username);
userService.initUser(user);
user.setEmail(email);
user.setPassword(getPasswordEncoder().encode(password));
user.setLastLoginAt(new Date());
user = userService.save(user);
authenticate(user, password);
userService.save(user);
user.setPassword(null);
return user;
}
public User login(String username, String password) {
User user = userService.getByName(username);
if (user == null) {
throw new BadCredentialsException(username + " provided invalid credentials");
}
authenticate(user, password);
userService.initUser(user);
user.setLastLoginAt(new Date());
userService.save(user);
user.setPassword(null);
return user;
}
private boolean authenticate(User user, String password) {
if (user != null && getPasswordEncoder().matches(password, user.getPassword())) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
user, password, user.getAuthorities());
Authentication authResult = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
if (authResult.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(authResult);
user.setToken(tokenHelperService.getToken(user.getName(), password));
return true;
}
return true;
}
throw new BadCredentialsException(user.getDisplayName() + " provided invalid credentials");
}
}
|
3e180a7037585bee5c92cf83b12034bc847353ae | 226 | java | Java | account-service/api/src/test/java/com/idcf/boathouse/account/AccountServiceApplicationTests.java | Adrian-P7/boat-house | 91441f1e1d20d992ca164d139d4a1208907ff0be | [
"MIT"
] | 5 | 2020-06-18T03:36:41.000Z | 2020-11-14T06:05:54.000Z | account-service/api/src/test/java/com/idcf/boathouse/account/AccountServiceApplicationTests.java | Adrian-P7/boat-house | 91441f1e1d20d992ca164d139d4a1208907ff0be | [
"MIT"
] | 4 | 2020-12-27T03:25:17.000Z | 2022-02-21T12:44:30.000Z | account-service/api/src/test/java/com/idcf/boathouse/account/AccountServiceApplicationTests.java | Adrian-P7/boat-house | 91441f1e1d20d992ca164d139d4a1208907ff0be | [
"MIT"
] | 24 | 2020-07-15T08:53:02.000Z | 2022-01-11T04:54:35.000Z | 16.142857 | 60 | 0.79646 | 10,234 | package com.idcf.boathouse.account;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class AccountServiceApplicationTests {
@Test
void contextLoads() {
}
}
|
3e180a857fd622050ee8634e641d765362b3efb5 | 7,587 | java | Java | src/main/java/org/elasticsearch/action/admin/indices/cache/clear/TransportClearIndicesCacheAction.java | Laymo007/elasticsearch | f042b8f2e1f7c21eec5b6f2b79d9efcd9b1c6896 | [
"Apache-2.0"
] | 2 | 2017-09-14T15:55:47.000Z | 2021-04-12T22:52:31.000Z | src/main/java/org/elasticsearch/action/admin/indices/cache/clear/TransportClearIndicesCacheAction.java | Laymo007/elasticsearch | f042b8f2e1f7c21eec5b6f2b79d9efcd9b1c6896 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/elasticsearch/action/admin/indices/cache/clear/TransportClearIndicesCacheAction.java | Laymo007/elasticsearch | f042b8f2e1f7c21eec5b6f2b79d9efcd9b1c6896 | [
"Apache-2.0"
] | 2 | 2016-09-05T08:34:50.000Z | 2019-10-04T04:09:56.000Z | 45.431138 | 205 | 0.689073 | 10,235 | /*
* 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.action.admin.indices.cache.clear;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.ShardOperationFailedException;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.DefaultShardOperationFailedException;
import org.elasticsearch.action.support.broadcast.BroadcastShardOperationFailedException;
import org.elasticsearch.action.support.broadcast.TransportBroadcastOperationAction;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.routing.GroupShardsIterator;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.mapper.internal.ParentFieldMapper;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.indices.cache.query.IndicesQueryCache;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
import java.util.List;
import java.util.concurrent.atomic.AtomicReferenceArray;
import static com.google.common.collect.Lists.newArrayList;
/**
* Indices clear cache action.
*/
public class TransportClearIndicesCacheAction extends TransportBroadcastOperationAction<ClearIndicesCacheRequest, ClearIndicesCacheResponse, ShardClearIndicesCacheRequest, ShardClearIndicesCacheResponse> {
private final IndicesService indicesService;
private final IndicesQueryCache indicesQueryCache;
@Inject
public TransportClearIndicesCacheAction(Settings settings, ThreadPool threadPool, ClusterService clusterService,
TransportService transportService, IndicesService indicesService,
IndicesQueryCache indicesQueryCache, ActionFilters actionFilters) {
super(settings, ClearIndicesCacheAction.NAME, threadPool, clusterService, transportService, actionFilters,
ClearIndicesCacheRequest.class, ShardClearIndicesCacheRequest.class, ThreadPool.Names.MANAGEMENT);
this.indicesService = indicesService;
this.indicesQueryCache = indicesQueryCache;
}
@Override
protected ClearIndicesCacheResponse newResponse(ClearIndicesCacheRequest request, AtomicReferenceArray shardsResponses, ClusterState clusterState) {
int successfulShards = 0;
int failedShards = 0;
List<ShardOperationFailedException> shardFailures = null;
for (int i = 0; i < shardsResponses.length(); i++) {
Object shardResponse = shardsResponses.get(i);
if (shardResponse == null) {
// simply ignore non active shards
} else if (shardResponse instanceof BroadcastShardOperationFailedException) {
failedShards++;
if (shardFailures == null) {
shardFailures = newArrayList();
}
shardFailures.add(new DefaultShardOperationFailedException((BroadcastShardOperationFailedException) shardResponse));
} else {
successfulShards++;
}
}
return new ClearIndicesCacheResponse(shardsResponses.length(), successfulShards, failedShards, shardFailures);
}
@Override
protected ShardClearIndicesCacheRequest newShardRequest(int numShards, ShardRouting shard, ClearIndicesCacheRequest request) {
return new ShardClearIndicesCacheRequest(shard.shardId(), request);
}
@Override
protected ShardClearIndicesCacheResponse newShardResponse() {
return new ShardClearIndicesCacheResponse();
}
@Override
protected ShardClearIndicesCacheResponse shardOperation(ShardClearIndicesCacheRequest request) {
IndexService service = indicesService.indexService(request.shardId().getIndex());
if (service != null) {
IndexShard shard = service.shard(request.shardId().id());
boolean clearedAtLeastOne = false;
if (request.filterCache()) {
clearedAtLeastOne = true;
service.cache().filter().clear("api");
}
if (request.fieldDataCache()) {
clearedAtLeastOne = true;
if (request.fields() == null || request.fields().length == 0) {
service.fieldData().clear();
} else {
for (String field : request.fields()) {
service.fieldData().clearField(field);
}
}
}
if (request.queryCache()) {
clearedAtLeastOne = true;
indicesQueryCache.clear(shard);
}
if (request.recycler()) {
logger.debug("Clear CacheRecycler on index [{}]", service.index());
clearedAtLeastOne = true;
// cacheRecycler.clear();
}
if (request.idCache()) {
clearedAtLeastOne = true;
service.fieldData().clearField(ParentFieldMapper.NAME);
}
if (!clearedAtLeastOne) {
if (request.fields() != null && request.fields().length > 0) {
// only clear caches relating to the specified fields
for (String field : request.fields()) {
service.fieldData().clearField(field);
}
} else {
service.cache().clear("api");
service.fieldData().clear();
indicesQueryCache.clear(shard);
}
}
}
return new ShardClearIndicesCacheResponse(request.shardId());
}
/**
* The refresh request works against *all* shards.
*/
@Override
protected GroupShardsIterator shards(ClusterState clusterState, ClearIndicesCacheRequest request, String[] concreteIndices) {
return clusterState.routingTable().allActiveShardsGrouped(concreteIndices, true);
}
@Override
protected ClusterBlockException checkGlobalBlock(ClusterState state, ClearIndicesCacheRequest request) {
return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_WRITE);
}
@Override
protected ClusterBlockException checkRequestBlock(ClusterState state, ClearIndicesCacheRequest request, String[] concreteIndices) {
return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA_WRITE, concreteIndices);
}
}
|
3e180cc4757d84a6a377e3ce11d5187b6afe9aeb | 652 | java | Java | Java-master/mybatis-insert-generatedkey/src/main/java/com/hmkcode/spring/mybatis/vo/MyObject.java | ahmed-anas/ahmeds.xyz | 112d03b09d43f5e335746313243b1704c3a01349 | [
"MIT"
] | null | null | null | Java-master/mybatis-insert-generatedkey/src/main/java/com/hmkcode/spring/mybatis/vo/MyObject.java | ahmed-anas/ahmeds.xyz | 112d03b09d43f5e335746313243b1704c3a01349 | [
"MIT"
] | 5 | 2021-01-21T01:32:45.000Z | 2022-01-21T23:46:59.000Z | Java-master/mybatis-insert-generatedkey/src/main/java/com/hmkcode/spring/mybatis/vo/MyObject.java | ahmed-anas/ahmeds.xyz | 112d03b09d43f5e335746313243b1704c3a01349 | [
"MIT"
] | 6 | 2021-01-02T16:44:05.000Z | 2021-01-20T08:57:15.000Z | 20.375 | 97 | 0.716258 | 10,236 | package com.hmkcode.spring.mybatis.vo;
import org.apache.ibatis.type.Alias;
//@Alias("MyObject") will be used by /src/resources/com/hmkcode/spring/mybatis/mybatis-config.xml
@Alias("MyObject")
public class MyObject {
private int objectId;
private String objectName;
public int getObjectId() {
return objectId;
}
public void setObjectId(int objectId) {
this.objectId = objectId;
}
public String getObjectName() {
return objectName;
}
public void setObjectName(String objectName) {
this.objectName = objectName;
}
public String toString(){
return "\n Object [ id: "+this.objectId+" - name: "+this.objectName+ "\n]";
}
}
|
3e180cc83acd77cdce5bf7781ccf4d74ac558f31 | 1,756 | java | Java | core/src/main/java/org/primefaces/extensions/application/Html5Context.java | e-Contract/primefaces-extensions | 54a4183600690d3a954413e60a3cb0e3fc44beaa | [
"MIT"
] | 55 | 2015-03-07T14:26:07.000Z | 2020-08-16T00:16:45.000Z | core/src/main/java/org/primefaces/extensions/application/Html5Context.java | e-Contract/primefaces-extensions | 54a4183600690d3a954413e60a3cb0e3fc44beaa | [
"MIT"
] | 83 | 2015-05-21T08:33:14.000Z | 2020-08-27T17:47:26.000Z | core/src/main/java/org/primefaces/extensions/application/Html5Context.java | e-Contract/primefaces-extensions | 54a4183600690d3a954413e60a3cb0e3fc44beaa | [
"MIT"
] | 98 | 2015-01-18T12:29:05.000Z | 2020-08-26T19:24:50.000Z | 40.837209 | 102 | 0.756264 | 10,237 | /*
* Copyright (c) 2011-2022 PrimeFaces Extensions
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.primefaces.extensions.application;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextWrapper;
import javax.faces.context.ResponseWriter;
/**
* JSF generates all script tags with 'type="text/javascript"' which throws HTML5 validation warnings.
*
* @since 10.0.0
*/
public class Html5Context extends FacesContextWrapper {
public Html5Context(FacesContext context) {
super(context);
}
@Override
public void setResponseWriter(ResponseWriter responseWriter) {
super.setResponseWriter(new Html5ResponseWriter(responseWriter));
}
} |
3e180cdd98790f9f62759ecf8f7ce19e2971e556 | 4,890 | java | Java | code/java/ETFProfileandPrices/v2/src/main/java/com/factset/sdk/ETFProfileandPrices/models/InlineResponse20032DataExpenseRatio.java | factset/enterprise-sdk | 3fd4d1360756c515c9737a0c9a992c7451d7de7e | [
"Apache-2.0"
] | 6 | 2022-02-07T16:34:18.000Z | 2022-03-30T08:04:57.000Z | code/java/ETFProfileandPrices/v2/src/main/java/com/factset/sdk/ETFProfileandPrices/models/InlineResponse20032DataExpenseRatio.java | factset/enterprise-sdk | 3fd4d1360756c515c9737a0c9a992c7451d7de7e | [
"Apache-2.0"
] | 2 | 2022-02-07T05:25:57.000Z | 2022-03-07T14:18:04.000Z | code/java/ETFProfileandPrices/v2/src/main/java/com/factset/sdk/ETFProfileandPrices/models/InlineResponse20032DataExpenseRatio.java | factset/enterprise-sdk | 3fd4d1360756c515c9737a0c9a992c7451d7de7e | [
"Apache-2.0"
] | null | null | null | 32.6 | 322 | 0.749898 | 10,238 | /*
* Prime Developer Trial
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: v1
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.factset.sdk.ETFProfileandPrices.models;
import java.util.Objects;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.math.BigDecimal;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.factset.sdk.ETFProfileandPrices.JSON;
/**
* Expense ratio.
*/
@ApiModel(description = "Expense ratio.")
@JsonPropertyOrder({
InlineResponse20032DataExpenseRatio.JSON_PROPERTY_VALUE,
InlineResponse20032DataExpenseRatio.JSON_PROPERTY_POTENTIAL
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class InlineResponse20032DataExpenseRatio implements Serializable {
private static final long serialVersionUID = 1L;
public static final String JSON_PROPERTY_VALUE = "value";
private BigDecimal value;
public static final String JSON_PROPERTY_POTENTIAL = "potential";
private BigDecimal potential;
public InlineResponse20032DataExpenseRatio() {
}
public InlineResponse20032DataExpenseRatio value(BigDecimal value) {
this.value = value;
return this;
}
/**
* Typically the net total annual fee the issuer deducts from ETP assets as a management fee. Also can include where applicable acquired ETP fees, short interest expense, index fees, and financing fees. Breakeven rate is reported for commodity pools. This data is available for all the regions.
* @return value
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Typically the net total annual fee the issuer deducts from ETP assets as a management fee. Also can include where applicable acquired ETP fees, short interest expense, index fees, and financing fees. Breakeven rate is reported for commodity pools. This data is available for all the regions.")
@JsonProperty(JSON_PROPERTY_VALUE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public BigDecimal getValue() {
return value;
}
@JsonProperty(JSON_PROPERTY_VALUE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public void setValue(BigDecimal value) {
this.value = value;
}
public InlineResponse20032DataExpenseRatio potential(BigDecimal potential) {
this.potential = potential;
return this;
}
/**
* The full expense ratio before any fee waivers. This data is available fo the US and Canada regions.
* @return potential
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The full expense ratio before any fee waivers. This data is available fo the US and Canada regions.")
@JsonProperty(JSON_PROPERTY_POTENTIAL)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public BigDecimal getPotential() {
return potential;
}
@JsonProperty(JSON_PROPERTY_POTENTIAL)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public void setPotential(BigDecimal potential) {
this.potential = potential;
}
/**
* Return true if this inline_response_200_32_data_expenseRatio object is equal to o.
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InlineResponse20032DataExpenseRatio inlineResponse20032DataExpenseRatio = (InlineResponse20032DataExpenseRatio) o;
return Objects.equals(this.value, inlineResponse20032DataExpenseRatio.value) &&
Objects.equals(this.potential, inlineResponse20032DataExpenseRatio.potential);
}
@Override
public int hashCode() {
return Objects.hash(value, potential);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class InlineResponse20032DataExpenseRatio {\n");
sb.append(" value: ").append(toIndentedString(value)).append("\n");
sb.append(" potential: ").append(toIndentedString(potential)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.