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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e1a303125a6a5bd8d4e314ab65d7453940f8286 | 8,467 | java | Java | src/main/resources/repairability_test_files/ground_truth/Cardumen/patch2-Math-62-Cardumen/Cardumen/00119/Cardumen_00119_t.java | HaoyeTianCoder/coming | 7bda0a99727ce614c2872a864683ba6a19f90f68 | [
"MIT"
] | 71 | 2019-01-27T12:01:13.000Z | 2022-03-18T02:34:36.000Z | src/main/resources/repairability_test_files/ground_truth/Cardumen/patch2-Math-62-Cardumen/Cardumen/00119/Cardumen_00119_t.java | HaoyeTianCoder/coming | 7bda0a99727ce614c2872a864683ba6a19f90f68 | [
"MIT"
] | 172 | 2019-02-10T09:38:22.000Z | 2022-02-01T17:24:29.000Z | src/main/resources/repairability_test_files/ground_truth/Cardumen/patch2-Math-62-Cardumen/Cardumen/00119/Cardumen_00119_t.java | HaoyeTianCoder/coming | 7bda0a99727ce614c2872a864683ba6a19f90f68 | [
"MIT"
] | 83 | 2019-02-05T16:38:59.000Z | 2021-10-10T19:00:46.000Z | 40.903382 | 168 | 0.64214 | 11,141 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math.optimization.univariate;
import java.util.Arrays;
import java.util.Comparator;
import org.apache.commons.math.FunctionEvaluationException;
import org.apache.commons.math.analysis.UnivariateRealFunction;
import org.apache.commons.math.exception.MathIllegalStateException;
import org.apache.commons.math.exception.ConvergenceException;
import org.apache.commons.math.exception.util.LocalizedFormats;
import org.apache.commons.math.random.RandomGenerator;
import org.apache.commons.math.optimization.GoalType;
import org.apache.commons.math.optimization.ConvergenceChecker;
import org.apache.commons.math.util.FastMath;
/**
* Special implementation of the {@link UnivariateRealOptimizer} interface
* adding multi-start features to an existing optimizer.
*
* This class wraps a classical optimizer to use it several times in
* turn with different starting points in order to avoid being trapped
* into a local extremum when looking for a global one.
*
* @param <FUNC> Type of the objective function to be optimized.
*
* @version $Revision$ $Date$
* @since 3.0
*/
public class MultiStartUnivariateRealOptimizer<FUNC extends UnivariateRealFunction>
implements BaseUnivariateRealOptimizer<FUNC> {
/** Underlying classical optimizer. */
private final BaseUnivariateRealOptimizer<FUNC> optimizer;
/** Maximal number of evaluations allowed. */
private int maxEvaluations;
/** Number of evaluations already performed for all starts. */
private int totalEvaluations;
/** Number of starts to go. */
private int starts;
/** Random generator for multi-start. */
private RandomGenerator generator;
/** Found optima. */
private UnivariateRealPointValuePair[] optima;
/**
* Create a multi-start optimizer from a single-start optimizer.
*
* @param optimizer Single-start optimizer to wrap.
* @param starts Number of starts to perform (including the
* first one), multi-start is disabled if value is less than or
* equal to 1.
* @param generator Random generator to use for restarts.
*/
public MultiStartUnivariateRealOptimizer(final BaseUnivariateRealOptimizer<FUNC> optimizer,
final int starts,
final RandomGenerator generator) {
this.optimizer = optimizer;
this.starts = starts;
this.generator = generator;
}
/**
* {@inheritDoc}
*/
public void setConvergenceChecker(ConvergenceChecker<UnivariateRealPointValuePair> checker) {
optimizer.setConvergenceChecker(checker);
}
/**
* {@inheritDoc}
*/
public ConvergenceChecker<UnivariateRealPointValuePair> getConvergenceChecker() {
return optimizer.getConvergenceChecker();
}
/** {@inheritDoc} */
public int getMaxEvaluations() {
return maxEvaluations;
}
/** {@inheritDoc} */
public int getEvaluations() {
return totalEvaluations;
}
/** {@inheritDoc} */
public void setMaxEvaluations(int maxEvaluations) {
this.maxEvaluations = maxEvaluations;
optimizer.setMaxEvaluations(maxEvaluations);
}
/**
* Get all the optima found during the last call to {@link
* #optimize(FUNC,GoalType,double,double) optimize}.
* The optimizer stores all the optima found during a set of
* restarts. The {@link #optimize(FUNC,GoalType,double,double) optimize}
* method returns the best point only. This method returns all the points
* found at the end of each starts, including the best one already
* returned by the {@link #optimize(FUNC,GoalType,double,double) optimize}
* method.
* <br/>
* The returned array as one element for each start as specified
* in the constructor. It is ordered with the results from the
* runs that did converge first, sorted from best to worst
* objective value (i.e in ascending order if minimizing and in
* descending order if maximizing), followed by {@code null} elements
* corresponding to the runs that did not converge. This means all
* elements will be {@code null} if the {@link
* #optimize(FUNC,GoalType,double,double) optimize} method did throw a
* {@link ConvergenceException}). This also means that if the first
* element is not {@code null}, it is the best point found across all
* starts.
*
* @return an array containing the optima.
* @throws MathIllegalStateException if {@link
* #optimize(FUNC,GoalType,double,double) optimize} has not been called.
*/
public UnivariateRealPointValuePair[] getOptima() {
if (optima == null) {
throw new MathIllegalStateException(LocalizedFormats.NO_OPTIMUM_COMPUTED_YET);
}
return optima.clone();
}
/** {@inheritDoc} */
public UnivariateRealPointValuePair optimize(final FUNC f,
final GoalType goal,
final double min, final double max)
throws FunctionEvaluationException {
return optimize(f, goal, min, max, 0);
}
/** {@inheritDoc} */
public UnivariateRealPointValuePair optimize(final FUNC f, final GoalType goal,
final double min, final double max,
final double startValue)
throws FunctionEvaluationException {
optima = new UnivariateRealPointValuePair[starts];
totalEvaluations = 0;
// Multi-start loop.
for (int i = 0; i < starts; ++i) {
try {
final double bound1 = (i == 0) ? min : min + generator.nextDouble() * (max - min);
final double bound2 = (i == 0) ? max : min + generator.nextDouble() * (max - min);
optima[i] = optimizer.optimize(f, goal, org.apache.commons.math.util.FastMath.max(min, min), org.apache.commons.math.util.FastMath.max(bound1, bound2));
} catch (FunctionEvaluationException fee) {
optima[i] = null;
} catch (ConvergenceException ce) {
optima[i] = null;
}
final int usedEvaluations = optimizer.getEvaluations();
optimizer.setMaxEvaluations(optimizer.getMaxEvaluations() - usedEvaluations);
totalEvaluations += usedEvaluations;
}
sortPairs(goal);
if (optima[0] == null) {
throw new ConvergenceException(LocalizedFormats.NO_CONVERGENCE_WITH_ANY_START_POINT,
starts);
}
// Return the point with the best objective function value.
return optima[0];
}
/**
* Sort the optima from best to worst, followed by {@code null} elements.
*
* @param goal Goal type.
*/
private void sortPairs(final GoalType goal) {
Arrays.sort(optima, new Comparator<UnivariateRealPointValuePair>() {
public int compare(final UnivariateRealPointValuePair o1,
final UnivariateRealPointValuePair o2) {
if (o1 == null) {
return (o2 == null) ? 0 : 1;
} else if (o2 == null) {
return -1;
}
final double v1 = o1.getValue();
final double v2 = o2.getValue();
return (goal == GoalType.MINIMIZE) ?
Double.compare(v1, v2) : Double.compare(v2, v1);
}
});
}
}
|
3e1a309998b7bce31c69530ad5359224767f68a5 | 277 | java | Java | x_organization_assemble_control/src/main/java/com/x/organization/assemble/control/jaxrs/PersonJaxrsFilter.java | fancylou/o2oa | e7ec39fc586fab3d38b62415ed06448e6a9d6e26 | [
"BSD-3-Clause"
] | 1 | 2019-10-05T03:47:23.000Z | 2019-10-05T03:47:23.000Z | x_organization_assemble_control/src/main/java/com/x/organization/assemble/control/jaxrs/PersonJaxrsFilter.java | Mendeling/o2oa | afd053e465b54b1b21b8db558bffbd93e7923b79 | [
"BSD-3-Clause"
] | null | null | null | x_organization_assemble_control/src/main/java/com/x/organization/assemble/control/jaxrs/PersonJaxrsFilter.java | Mendeling/o2oa | afd053e465b54b1b21b8db558bffbd93e7923b79 | [
"BSD-3-Clause"
] | null | null | null | 25.181818 | 64 | 0.808664 | 11,142 | package com.x.organization.assemble.control.jaxrs;
import javax.servlet.annotation.WebFilter;
import com.x.base.core.application.jaxrs.ManagerUserJaxrsFilter;
@WebFilter(urlPatterns = { "/jaxrs/person/*" })
public class PersonJaxrsFilter extends ManagerUserJaxrsFilter {
}
|
3e1a30e80a5c10d400bc8ae64ceebccd6198d2fa | 2,193 | java | Java | app/src/main/java/com/sscience/stopapp/widget/MoveFloatingActionButton.java | magic8421/StopApp | ebd80720615a527cda867c5450b97fd91e9e5b89 | [
"Apache-2.0"
] | 28 | 2017-03-27T11:02:03.000Z | 2021-03-19T06:26:58.000Z | app/src/main/java/com/sscience/stopapp/widget/MoveFloatingActionButton.java | PowerOlive/StopApp | 9e126174a7e1141bb479f23183a1d3e1c2a1b55c | [
"Apache-2.0"
] | 5 | 2018-03-19T06:16:45.000Z | 2020-01-06T18:20:34.000Z | app/src/main/java/com/sscience/stopapp/widget/MoveFloatingActionButton.java | PowerOlive/StopApp | 9e126174a7e1141bb479f23183a1d3e1c2a1b55c | [
"Apache-2.0"
] | 7 | 2017-02-18T11:35:55.000Z | 2020-08-30T05:14:01.000Z | 29.783784 | 100 | 0.589837 | 11,143 | package com.sscience.stopapp.widget;
import android.content.Context;
import android.support.design.widget.FloatingActionButton;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
/**
* @author SScience
* @description
* @email anpch@example.com
* @data 2017/3/29
*/
public class MoveFloatingActionButton extends FloatingActionButton implements View.OnTouchListener {
private Context mContext;
private float mPosY;
private float mCurPosY;
public MoveFloatingActionButton(Context context) {
super(context);
mContext = context;
setOnTouchListener(this);
}
public MoveFloatingActionButton(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mPosY = event.getRawY();
mCurPosY = mPosY;
break;
case MotionEvent.ACTION_MOVE:
mCurPosY = event.getRawY();
break;
case MotionEvent.ACTION_UP:
int touchSlop = ViewConfiguration.get(mContext).getScaledPagingTouchSlop();
if (mCurPosY - mPosY > 0 && (Math.abs(mCurPosY - mPosY) > touchSlop)) {
//向下滑動
if (mOnMoveListener != null) {
mOnMoveListener.onMove(false);
}
} else if (mCurPosY - mPosY < 0 &&
(Math.abs(mCurPosY - mPosY) > touchSlop)) {
//向上滑动
if (mOnMoveListener != null) {
mOnMoveListener.onMove(true);
}
}
break;
}
return false;
}
public interface OnMoveListener {
void onMove(boolean isMoveUp);
}
private OnMoveListener mOnMoveListener;
public void setOnMoveListener(OnMoveListener onMoveListener) {
mOnMoveListener = onMoveListener;
}
}
|
3e1a30f49f5214ea215d205948c790f95657a578 | 1,666 | java | Java | components/data-services/org.wso2.carbon.dataservices.core/src/test/java/org/wso2/carbon/dataservices/core/test/DataServiceBaseTestCase.java | SecondaryOrganization/carbon-data | 187d0f3027e932534215bb038d1fc0560ba6031a | [
"Apache-2.0"
] | 10 | 2016-05-17T10:01:22.000Z | 2021-01-21T13:53:16.000Z | components/data-services/org.wso2.carbon.dataservices.core/src/test/java/org/wso2/carbon/dataservices/core/test/DataServiceBaseTestCase.java | SecondaryOrganization/carbon-data | 187d0f3027e932534215bb038d1fc0560ba6031a | [
"Apache-2.0"
] | 112 | 2015-01-06T03:32:29.000Z | 2022-01-27T16:17:10.000Z | components/data-services/org.wso2.carbon.dataservices.core/src/test/java/org/wso2/carbon/dataservices/core/test/DataServiceBaseTestCase.java | SecondaryOrganization/carbon-data | 187d0f3027e932534215bb038d1fc0560ba6031a | [
"Apache-2.0"
] | 110 | 2015-01-30T17:40:44.000Z | 2021-06-08T09:21:22.000Z | 37.022222 | 125 | 0.741297 | 11,144 | /*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.dataservices.core.test;
import junit.framework.TestCase;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.utils.ServerConstants;
public abstract class DataServiceBaseTestCase extends TestCase {
protected String repository = "./target/repository";
protected String axis2Conf = "./src/test/resources/axis2.xml";
protected String baseEpr = "http://localhost:5555/axis2/services/";
protected String carbonHome = "./target/carbonHome";
public DataServiceBaseTestCase(String testName) {
super(testName);
}
protected void startTenantFlow() {
System.setProperty(ServerConstants.CARBON_HOME, carbonHome);
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID, true);
}
protected void endTenantFlow() {
PrivilegedCarbonContext.endTenantFlow();
}
}
|
3e1a32bba4e79362690acdc816bec4c6411d9fb3 | 3,315 | java | Java | net.solarnetwork.external.com.serotonin.bacnet4j/src/com/serotonin/bacnet4j/service/acknowledgement/AcknowledgementService.java | Tsvetelin98/Solar | 350341d4f6a32d53efd48778ee7a8ba89a591978 | [
"Apache-2.0"
] | null | null | null | net.solarnetwork.external.com.serotonin.bacnet4j/src/com/serotonin/bacnet4j/service/acknowledgement/AcknowledgementService.java | Tsvetelin98/Solar | 350341d4f6a32d53efd48778ee7a8ba89a591978 | [
"Apache-2.0"
] | null | null | null | net.solarnetwork.external.com.serotonin.bacnet4j/src/com/serotonin/bacnet4j/service/acknowledgement/AcknowledgementService.java | Tsvetelin98/Solar | 350341d4f6a32d53efd48778ee7a8ba89a591978 | [
"Apache-2.0"
] | null | null | null | 47.357143 | 97 | 0.668175 | 11,145 | /*
* ============================================================================
* GNU General Public License
* ============================================================================
*
* Copyright (C) 2006-2011 Serotonin Software Technologies Inc. http://serotoninsoftware.com
* @author Matthew Lohbihler
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*
* When signing a commercial license with Serotonin Software Technologies Inc.,
* the following extension to GPL is made. A special exception to the GPL is
* included to allow you to distribute a combined work that includes BAcnet4J
* without being obliged to provide the source code for any proprietary components.
*/
package com.serotonin.bacnet4j.service.acknowledgement;
import com.serotonin.bacnet4j.exception.BACnetException;
import com.serotonin.bacnet4j.service.Service;
import org.free.bacnet4j.util.ByteQueue;
abstract public class AcknowledgementService extends Service {
private static final long serialVersionUID = 3837098889443642001L;
public static AcknowledgementService createAcknowledgementService(byte type, ByteQueue queue)
throws BACnetException {
if (type == GetAlarmSummaryAck.TYPE_ID) // 3
return new GetAlarmSummaryAck(queue);
if (type == GetEnrollmentSummaryAck.TYPE_ID) // 4
return new GetEnrollmentSummaryAck(queue);
if (type == AtomicReadFileAck.TYPE_ID) // 6
return new AtomicReadFileAck(queue);
if (type == AtomicWriteFileAck.TYPE_ID) // 7
return new AtomicWriteFileAck(queue);
if (type == CreateObjectAck.TYPE_ID) // 10
return new CreateObjectAck(queue);
if (type == ReadPropertyAck.TYPE_ID) // 12
return new ReadPropertyAck(queue);
if (type == ReadPropertyConditionalAck.TYPE_ID) // 13
return new ReadPropertyConditionalAck(queue);
if (type == ReadPropertyMultipleAck.TYPE_ID) // 14
return new ReadPropertyMultipleAck(queue);
if (type == ConfirmedPrivateTransferAck.TYPE_ID) // 18
return new ConfirmedPrivateTransferAck(queue);
if (type == VtOpenAck.TYPE_ID) // 21
return new VtOpenAck(queue);
if (type == VtDataAck.TYPE_ID) // 23
return new VtDataAck(queue);
if (type == AuthenticateAck.TYPE_ID) // 24
return new AuthenticateAck(queue);
if (type == ReadRangeAck.TYPE_ID) // 26
return new ReadRangeAck(queue);
if (type == GetEventInformationAck.TYPE_ID) // 29
return new GetEventInformationAck(queue);
throw new BACnetException("Unsupported service acknowledgement: " + (type & 0xff));
}
}
|
3e1a32c6307c3fee119e06da9fa33b0feb13b9db | 582 | java | Java | module/ebdj-bdd/src/main/java/fr/qp1c/ebdj/liseuse/bdd/utils/db/DBUtils.java | RefactoringBotUser/ebdj-liseuse | 426f7a1fb81ea7b9a42db7243611a7be714ff866 | [
"MIT"
] | null | null | null | module/ebdj-bdd/src/main/java/fr/qp1c/ebdj/liseuse/bdd/utils/db/DBUtils.java | RefactoringBotUser/ebdj-liseuse | 426f7a1fb81ea7b9a42db7243611a7be714ff866 | [
"MIT"
] | null | null | null | module/ebdj-bdd/src/main/java/fr/qp1c/ebdj/liseuse/bdd/utils/db/DBUtils.java | RefactoringBotUser/ebdj-liseuse | 426f7a1fb81ea7b9a42db7243611a7be714ff866 | [
"MIT"
] | null | null | null | 18.1875 | 79 | 0.652921 | 11,146 | package fr.qp1c.ebdj.liseuse.bdd.utils.db;
import org.apache.commons.lang3.StringUtils;
/**
* Classe utilitaire permettant de réaliser des opérations élémentaires en lien
* avec la base de données.
*
* @author NICO
*
*/
public final class DBUtils {
private DBUtils() {
}
/**
* Protéger une valeur SQL comportant des quotes simples.
*
* @param str
* la chaine à protéger
* @return la chaine protégée
*/
public static String escapeSql(String str) {
if (str == null) {
return null;
}
return StringUtils.replace(str, "'", "''");
}
}
|
3e1a32e073dc767efefdd1e166e6d0306b75d343 | 12,891 | java | Java | corpus/class/eclipse.pde.ui/1878.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 15 | 2018-07-10T09:38:31.000Z | 2021-11-29T08:28:07.000Z | corpus/class/eclipse.pde.ui/1878.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 3 | 2018-11-16T02:58:59.000Z | 2021-01-20T16:03:51.000Z | corpus/class/eclipse.pde.ui/1878.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 6 | 2018-06-27T20:19:00.000Z | 2022-02-19T02:29:53.000Z | 42.68543 | 144 | 0.649523 | 11,147 | /*******************************************************************************
* Copyright (c) 2007, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.pde.api.tools.internal;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.pde.api.tools.internal.provisional.ApiPlugin;
import org.eclipse.pde.api.tools.internal.provisional.Factory;
import org.eclipse.pde.api.tools.internal.provisional.IApiDescription;
import org.eclipse.pde.api.tools.internal.provisional.ProfileModifiers;
import org.eclipse.pde.api.tools.internal.provisional.RestrictionModifiers;
import org.eclipse.pde.api.tools.internal.provisional.VisibilityModifiers;
import org.eclipse.pde.api.tools.internal.provisional.descriptors.IElementDescriptor;
import org.eclipse.pde.api.tools.internal.provisional.descriptors.IFieldDescriptor;
import org.eclipse.pde.api.tools.internal.provisional.descriptors.IMethodDescriptor;
import org.eclipse.pde.api.tools.internal.provisional.descriptors.IPackageDescriptor;
import org.eclipse.pde.api.tools.internal.provisional.descriptors.IReferenceTypeDescriptor;
import org.eclipse.pde.api.tools.internal.provisional.scanner.ScannerMessages;
import org.eclipse.pde.api.tools.internal.util.Util;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* Provides tools for scanning/loading/parsing component.xml files.
*
* @since 1.0.0
*/
public class SystemApiDescriptionProcessor {
/**
* Constructor can not be instantiated directly
*/
private SystemApiDescriptionProcessor() {
}
/**
* Parses a component XML into a string. The location may be a jar,
* directory containing the component.xml file, or the component.xml file
* itself
*
* @param location root location of the component.xml file, or the
* component.xml file itself
* @return component XML as a string or <code>null</code> if none
* @throws IOException if unable to parse
*/
public static String serializeComponentXml(File location) {
if (location.exists()) {
ZipFile jarFile = null;
InputStream stream = null;
try {
String extension = new Path(location.getName()).getFileExtension();
if (//$NON-NLS-1$
extension != null && extension.equals("jar") && location.isFile()) {
jarFile = new ZipFile(location, ZipFile.OPEN_READ);
ZipEntry manifestEntry = jarFile.getEntry(IApiCoreConstants.SYSTEM_API_DESCRIPTION_XML_NAME);
if (manifestEntry != null) {
stream = jarFile.getInputStream(manifestEntry);
}
} else if (location.isDirectory()) {
File file = new File(location, IApiCoreConstants.SYSTEM_API_DESCRIPTION_XML_NAME);
if (file.exists()) {
stream = new FileInputStream(file);
}
} else if (location.isFile()) {
if (location.getName().equals(IApiCoreConstants.SYSTEM_API_DESCRIPTION_XML_NAME)) {
stream = new FileInputStream(location);
}
}
if (stream != null) {
return new String(Util.getInputStreamAsCharArray(stream, -1, IApiCoreConstants.UTF_8));
}
} catch (IOException e) {
ApiPlugin.log(e);
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
ApiPlugin.log(e);
}
try {
if (jarFile != null) {
jarFile.close();
}
} catch (IOException e) {
ApiPlugin.log(e);
}
}
}
return null;
}
/**
* Throws an exception with the given message and underlying exception.
*
* @param message error message
* @param exception underlying exception, or <code>null</code>
* @throws CoreException
*/
private static void abort(String message, Throwable exception) throws CoreException {
IStatus status = new Status(IStatus.ERROR, ApiPlugin.PLUGIN_ID, message, exception);
throw new CoreException(status);
}
/**
* Parses the given xml document (in string format), and annotates the
* specified {@link IApiDescription} with {@link IPackageDescriptor}s,
* {@link IReferenceTypeDescriptor}s, {@link IMethodDescriptor}s and
* {@link IFieldDescriptor}s.
*
* @param settings API settings to annotate
* @param xml XML used to generate settings
* @throws CoreException
*/
public static void annotateApiSettings(IApiDescription settings, String xml) throws CoreException {
Element root = null;
try {
root = Util.parseDocument(xml);
} catch (CoreException ce) {
abort("Failed to parse API description xml file", ce);
}
if (!root.getNodeName().equals(IApiXmlConstants.ELEMENT_COMPONENT)) {
abort(ScannerMessages.ComponentXMLScanner_0, null);
}
NodeList packages = root.getElementsByTagName(IApiXmlConstants.ELEMENT_PACKAGE);
NodeList types = null;
IPackageDescriptor packdesc = null;
Element type = null;
for (int i = 0; i < packages.getLength(); i++) {
Element pkg = (Element) packages.item(i);
// package visibility comes from the MANIFEST.MF
String pkgName = pkg.getAttribute(IApiXmlConstants.ATTR_NAME);
packdesc = Factory.packageDescriptor(pkgName);
annotateDescriptor(settings, packdesc, pkg);
types = pkg.getElementsByTagName(IApiXmlConstants.ELEMENT_TYPE);
for (int j = 0; j < types.getLength(); j++) {
type = (Element) types.item(j);
String name = type.getAttribute(IApiXmlConstants.ATTR_NAME);
if (name.length() == 0) {
abort(//$NON-NLS-1$
"Missing type name", //$NON-NLS-1$
null);
}
IReferenceTypeDescriptor typedesc = packdesc.getType(name);
annotateDescriptor(settings, typedesc, type);
annotateMethodSettings(settings, typedesc, type);
annotateFieldSettings(settings, typedesc, type);
}
}
}
/**
* Annotates the backing {@link IApiDescription} from the given
* {@link Element}, by adding the visibility and restriction attributes to
* the specified {@link IElementDescriptor}
*
* @param settings the settings to annotate
* @param descriptor the current descriptor context
* @param element the current element to annotate from
*/
private static void annotateDescriptor(IApiDescription settings, IElementDescriptor descriptor, Element element) {
settings.setVisibility(descriptor, VisibilityModifiers.API);
settings.setRestrictions(descriptor, RestrictionModifiers.NO_RESTRICTIONS);
settings.setAddedProfile(descriptor, retrieveElementAttribute(element, IApiXmlConstants.ATTR_ADDED_PROFILE));
settings.setRemovedProfile(descriptor, retrieveElementAttribute(element, IApiXmlConstants.ATTR_REMOVED_PROFILE));
settings.setSuperclass(descriptor, retrieveStringElementAttribute(element, IApiXmlConstants.ATTR_SUPER_CLASS));
settings.setSuperinterfaces(descriptor, retrieveStringElementAttribute(element, IApiXmlConstants.ATTR_SUPER_INTERFACES));
settings.setInterface(descriptor, retrieveBooleanElementAttribute(element, IApiXmlConstants.ATTR_INTERFACE));
}
/**
* Tests if the given restriction exists for the given element and returns
* an updated restrictions flag.
*
* @param element XML element
* @param name attribute to test
* @param flag bit mask for attribute
* @param res flag to combine with
* @return updated flags
*/
private static int retrieveElementAttribute(Element element, String name) {
String value = element.getAttribute(name);
if (value.length() > 0) {
return Integer.parseInt(value);
}
return ProfileModifiers.NO_PROFILE_VALUE;
}
/**
* Tests if the given restriction exists for the given element and returns
* an updated restrictions flag.
*
* @param element XML element
* @param name attribute to test
* @param flag bit mask for attribute
* @param res flag to combine with
* @return updated flags
*/
private static String retrieveStringElementAttribute(Element element, String name) {
String value = element.getAttribute(name);
if (value.length() > 0) {
return value;
}
return null;
}
/**
* Tests if the given restriction exists for the given element and returns
* an updated restrictions flag.
*
* @param element XML element
* @param name attribute to test
* @param flag bit mask for attribute
* @param res flag to combine with
* @return updated flags
*/
private static boolean retrieveBooleanElementAttribute(Element element, String name) {
String value = element.getAttribute(name);
if (value.length() > 0) {
return Boolean.toString(true).equals(value);
}
return false;
}
/**
* Annotates the supplied {@link IApiDescription} from all of the field
* elements that are direct children of the specified {@link Element}.
* {@link IFieldDescriptor}s are created as needed and added as children of
* the specified {@link IReferenceTypeDescriptor}.
*
* @param settings the {@link IApiDescription} to add the new
* {@link IFieldDescriptor} to
* @param typedesc the containing type descriptor for this field
* @param type the parent {@link Element}
* @throws CoreException
*/
private static void annotateFieldSettings(IApiDescription settings, IReferenceTypeDescriptor typedesc, Element type) throws CoreException {
NodeList fields = type.getElementsByTagName(IApiXmlConstants.ELEMENT_FIELD);
Element field = null;
IFieldDescriptor fielddesc = null;
String name = null;
for (int i = 0; i < fields.getLength(); i++) {
field = (Element) fields.item(i);
name = field.getAttribute(IApiXmlConstants.ATTR_NAME);
if (name == null) {
abort(ScannerMessages.ComponentXMLScanner_1, null);
}
fielddesc = typedesc.getField(name);
annotateDescriptor(settings, fielddesc, field);
}
}
/**
* Annotates the supplied {@link IApiDescription} from all of the method
* elements that are direct children of the specified {@link Element}.
* {@link IMethodDescriptor}s are created as needed and added as children of
* the specified {@link IReferenceTypeDescriptor}.
*
* @param settings the {@link IApiDescription} to add the new
* {@link IMethodDescriptor} to
* @param typedesc the containing type descriptor for this method
* @param type the parent {@link Element}
* @throws CoreException
*/
private static void annotateMethodSettings(IApiDescription settings, IReferenceTypeDescriptor typedesc, Element type) throws CoreException {
NodeList methods = type.getElementsByTagName(IApiXmlConstants.ELEMENT_METHOD);
Element method = null;
IMethodDescriptor methoddesc = null;
String name, signature;
for (int i = 0; i < methods.getLength(); i++) {
method = (Element) methods.item(i);
name = method.getAttribute(IApiXmlConstants.ATTR_NAME);
if (name == null) {
abort(ScannerMessages.ComponentXMLScanner_2, null);
}
signature = method.getAttribute(IApiXmlConstants.ATTR_SIGNATURE);
if (signature == null) {
abort(ScannerMessages.ComponentXMLScanner_3, null);
}
methoddesc = typedesc.getMethod(name, signature);
annotateDescriptor(settings, methoddesc, method);
}
}
}
|
3e1a33c72eaced26259e61a17f4cb6fddb84b068 | 4,155 | java | Java | jt808-tcp-netty/src/main/java/cn/hylexus/jt808/util/JT808ProtocolUtils.java | cnqdbt/jt-808-protocol | d8933cea3bf49340c435d23f13673f47dcf3bc38 | [
"MIT"
] | 434 | 2017-03-04T01:11:43.000Z | 2022-03-02T01:49:14.000Z | jt808-tcp-netty/src/main/java/cn/hylexus/jt808/util/JT808ProtocolUtils.java | cnqdbt/jt-808-protocol | d8933cea3bf49340c435d23f13673f47dcf3bc38 | [
"MIT"
] | 12 | 2017-05-03T09:26:55.000Z | 2021-03-03T03:07:40.000Z | jt808-tcp-netty/src/main/java/cn/hylexus/jt808/util/JT808ProtocolUtils.java | huxiaofei658/jt-808-protocol | 455de125c93c93820f4d1863761d5ffc8d381fc9 | [
"MIT"
] | 195 | 2017-03-08T07:55:26.000Z | 2022-03-22T06:25:12.000Z | 25.181818 | 109 | 0.561252 | 11,148 | package cn.hylexus.jt808.util;
import java.io.ByteArrayOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* JT808协议转义工具类
*
* <pre>
* 0x7d01 <====> 0x7d
* 0x7d02 <====> 0x7e
* </pre>
*
* @author hylexus
*
*/
public class JT808ProtocolUtils {
private final Logger log = LoggerFactory.getLogger(getClass());
private BitOperator bitOperator;
private BCD8421Operater bcd8421Operater;
public JT808ProtocolUtils() {
this.bitOperator = new BitOperator();
this.bcd8421Operater = new BCD8421Operater();
}
/**
* 接收消息时转义<br>
*
* <pre>
* 0x7d01 <====> 0x7d
* 0x7d02 <====> 0x7e
* </pre>
*
* @param bs
* 要转义的字节数组
* @param start
* 起始索引
* @param end
* 结束索引
* @return 转义后的字节数组
* @throws Exception
*/
public byte[] doEscape4Receive(byte[] bs, int start, int end) throws Exception {
if (start < 0 || end > bs.length)
throw new ArrayIndexOutOfBoundsException("doEscape4Receive error : index out of bounds(start=" + start
+ ",end=" + end + ",bytes length=" + bs.length + ")");
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
for (int i = 0; i < start; i++) {
baos.write(bs[i]);
}
for (int i = start; i < end - 1; i++) {
if (bs[i] == 0x7d && bs[i + 1] == 0x01) {
baos.write(0x7d);
i++;
} else if (bs[i] == 0x7d && bs[i + 1] == 0x02) {
baos.write(0x7e);
i++;
} else {
baos.write(bs[i]);
}
}
for (int i = end - 1; i < bs.length; i++) {
baos.write(bs[i]);
}
return baos.toByteArray();
} catch (Exception e) {
throw e;
} finally {
if (baos != null) {
baos.close();
baos = null;
}
}
}
/**
*
* 发送消息时转义<br>
*
* <pre>
* 0x7e <====> 0x7d02
* </pre>
*
* @param bs
* 要转义的字节数组
* @param start
* 起始索引
* @param end
* 结束索引
* @return 转义后的字节数组
* @throws Exception
*/
public byte[] doEscape4Send(byte[] bs, int start, int end) throws Exception {
if (start < 0 || end > bs.length)
throw new ArrayIndexOutOfBoundsException("doEscape4Send error : index out of bounds(start=" + start
+ ",end=" + end + ",bytes length=" + bs.length + ")");
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
for (int i = 0; i < start; i++) {
baos.write(bs[i]);
}
for (int i = start; i < end; i++) {
if (bs[i] == 0x7e) {
baos.write(0x7d);
baos.write(0x02);
} else {
baos.write(bs[i]);
}
}
for (int i = end; i < bs.length; i++) {
baos.write(bs[i]);
}
return baos.toByteArray();
} catch (Exception e) {
throw e;
} finally {
if (baos != null) {
baos.close();
baos = null;
}
}
}
public int generateMsgBodyProps(int msgLen, int enctyptionType, boolean isSubPackage, int reversed_14_15) {
// [ 0-9 ] 0000,0011,1111,1111(3FF)(消息体长度)
// [10-12] 0001,1100,0000,0000(1C00)(加密类型)
// [ 13_ ] 0010,0000,0000,0000(2000)(是否有子包)
// [14-15] 1100,0000,0000,0000(C000)(保留位)
if (msgLen >= 1024)
log.warn("The max value of msgLen is 1023, but {} .", msgLen);
int subPkg = isSubPackage ? 1 : 0;
int ret = (msgLen & 0x3FF) | ((enctyptionType << 10) & 0x1C00) | ((subPkg << 13) & 0x2000)
| ((reversed_14_15 << 14) & 0xC000);
return ret & 0xffff;
}
public byte[] generateMsgHeader(String phone, int msgType, byte[] body, int msgBodyProps, int flowId)
throws Exception {
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
// 1. 消息ID word(16)
baos.write(bitOperator.integerTo2Bytes(msgType));
// 2. 消息体属性 word(16)
baos.write(bitOperator.integerTo2Bytes(msgBodyProps));
// 3. 终端手机号 bcd[6]
baos.write(bcd8421Operater.string2Bcd(phone));
// 4. 消息流水号 word(16),按发送顺序从 0 开始循环累加
baos.write(bitOperator.integerTo2Bytes(flowId));
// 消息包封装项 此处不予考虑
return baos.toByteArray();
} finally {
if (baos != null) {
baos.close();
}
}
}
}
|
3e1a34419737fc8faeed98af170473cfabc42dcd | 8,624 | java | Java | app/biz/service-impl/src/main/java/com/bbd/bdsso/biz/service/impl/SsoAccessFacadeImpl.java | jinghuaaa/sso | 9d00fecf6fd80d1788ef3eb3f4c1c9418ddc667c | [
"Apache-2.0"
] | null | null | null | app/biz/service-impl/src/main/java/com/bbd/bdsso/biz/service/impl/SsoAccessFacadeImpl.java | jinghuaaa/sso | 9d00fecf6fd80d1788ef3eb3f4c1c9418ddc667c | [
"Apache-2.0"
] | null | null | null | app/biz/service-impl/src/main/java/com/bbd/bdsso/biz/service/impl/SsoAccessFacadeImpl.java | jinghuaaa/sso | 9d00fecf6fd80d1788ef3eb3f4c1c9418ddc667c | [
"Apache-2.0"
] | null | null | null | 36.854701 | 159 | 0.625696 | 11,149 | /**
* BBD Service Inc
* All Rights Reserved @2017
*/
package com.bbd.bdsso.biz.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.bbd.bdsso.biz.service.impl.aop.AuthValidate;
import com.bbd.bdsso.biz.service.impl.template.BdssoCallBack;
import com.bbd.bdsso.biz.service.impl.template.BdssoTemplate;
import com.bbd.bdsso.common.dal.daointerface.SsoAccessDAO;
import com.bbd.bdsso.common.dal.daointerface.SsoUserDAO;
import com.bbd.bdsso.common.dal.dataobject.SsoAccessDO;
import com.bbd.bdsso.common.dal.manual.daointerface.ExtraSsoAccessDAO;
import com.bbd.bdsso.common.dal.manual.dataobject.ExSsoAccessDO;
import com.bbd.bdsso.common.dal.manual.dataobject.ExSsoAccessGroupDO;
import com.bbd.bdsso.common.service.facade.SsoAccessFacade;
import com.bbd.bdsso.common.service.facade.result.BdssoAccessResult;
import com.bbd.bdsso.common.service.facade.result.BdssoBaseResult;
import com.bbd.bdsso.common.service.facade.result.BdssoExAccessResult;
import com.bbd.bdsso.common.service.facade.result.BdssoSummaryResult;
import com.bbd.bdsso.common.service.facade.vo.SsoAccessVO;
import com.bbd.bdsso.common.util.enums.AuthCodeEnum;
import com.bbd.bdsso.common.util.enums.AuthTypeEnum;
import com.bbd.bdsso.core.model.convertor.SsoAccessConvertor;
import com.bbd.commons.lang.util.AssertUtils;
import com.bbd.commons.lang.util.page.PageList;
/**
* 用户访问服务接口服务实现
*
* @author byron
* @version $Id: SsoAccessFacadeImpl.java, v 0.1 Sep 26, 2017 4:10:41 PM byron Exp $
*/
public class SsoAccessFacadeImpl implements SsoAccessFacade {
/** 日志 */
private final Logger logger = LoggerFactory.getLogger(SsoAccessFacadeImpl.class);
/** 用户权限DAO */
@Autowired
private SsoAccessDAO ssoAccessDAO;
/** 手工用户权限DAO */
@Autowired
private ExtraSsoAccessDAO extraSsoAccessDAO;
/** 事务模板 */
@Autowired
private BdssoTemplate bdssoTransactionTemplate;
/** 用户DAO */
@Autowired
private SsoUserDAO ssoUserDAO;
/**
* @see com.bbd.bdsso.common.service.facade.SsoAccessFacade#delete(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
@AuthValidate(type = AuthTypeEnum.YES)
public BdssoBaseResult delete(String uid, String token, String id) {
final BdssoBaseResult result = new BdssoBaseResult();
bdssoTransactionTemplate.executeWithTransaction(new BdssoCallBack() {
@Override
public void check() {
// 入参检查
AssertUtils.assertStringNotBlank(id, "资源id为空");
}
@Override
public void service() {
ssoAccessDAO.delete(Integer.parseInt(id));
logger.info("删除用户访问token,[uid={}]", uid);
}
}, result);
return result;
}
/**
* @see com.bbd.bdsso.common.service.facade.SsoAccessFacade#update(java.lang.String, java.lang.String, com.bbd.bdsso.common.service.facade.vo.SsoAccessVO)
*/
@Override
@AuthValidate(type = AuthTypeEnum.YES)
public BdssoBaseResult update(String uid, String token, SsoAccessVO ssoAccessVO) {
final BdssoBaseResult result = new BdssoBaseResult();
bdssoTransactionTemplate.executeWithTransaction(new BdssoCallBack() {
@Override
public void check() {
// 入参检查
AssertUtils.assertNotNull(ssoAccessVO, "实体为空");
}
@Override
public void service() {
ssoAccessDAO.update(SsoAccessConvertor.convertVo2Do(ssoAccessVO));
logger.info("更新用户访问token,[uid={}]", uid);
}
}, result);
return result;
}
/**
* @see com.bbd.bdsso.common.service.facade.SsoAccessFacade#queryById(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
@AuthValidate(type = AuthTypeEnum.YES)
public BdssoAccessResult queryById(String uid, String token, String id) {
final BdssoAccessResult result = new BdssoAccessResult();
bdssoTransactionTemplate.executeWithTransaction(new BdssoCallBack() {
@Override
public void check() {
// 入参检查
AssertUtils.assertStringNotBlank(id, "资源id为空");
}
@Override
public void service() {
ArrayList<SsoAccessDO> list = new ArrayList<SsoAccessDO>();
// 查询
SsoAccessDO ssoAccessDO = ssoAccessDAO.query(Integer.parseInt(id));
list.add(ssoAccessDO);
// 设置结果
result.setResultList(SsoAccessConvertor.convertDos2Vos(list));
}
}, result);
return result;
}
/**
* @see com.bbd.bdsso.common.service.facade.SsoAccessFacade#fuzzyQueryForPage(java.lang.String, java.lang.String, int, int, java.lang.String)
*/
@Override
@AuthValidate(type = AuthTypeEnum.YES, authCode = AuthCodeEnum.BDSSO_COMMON_USER_A)
public BdssoExAccessResult fuzzyQueryForPage(String uid, String token, int pageSize, int pageNum, String key) {
final BdssoExAccessResult result = new BdssoExAccessResult();
bdssoTransactionTemplate.executeWithTransaction(new BdssoCallBack() {
@Override
public void check() {
// 入参检查
AssertUtils.assertPositiveIntegerNumber(pageSize, "每页条数应大于0且为整数");
AssertUtils.assertIntegerNumberGeZero(pageNum, "页码应大于等于0");
}
@Override
public void service() {
PageList pageList = extraSsoAccessDAO.fuzzyQueryForPage(key, new Date(), pageSize, pageNum);
@SuppressWarnings("unchecked")
ArrayList<ExSsoAccessDO> listCopy = (ArrayList<ExSsoAccessDO>) pageList.clone();
List<ExSsoAccessGroupDO> groupList = extraSsoAccessDAO.queryForGroup();
// 搜索出来的应用和对应人数统计
HashMap<String, HashMap<String, String>> appCount = new HashMap<String, HashMap<String, String>>();
for (ExSsoAccessGroupDO exSsoAccessGroupDO : groupList) {
if (appCount.containsKey(exSsoAccessGroupDO.getAppName())) {
HashMap<String, String> subResult = appCount.get(exSsoAccessGroupDO.getAppName());
subResult.put(exSsoAccessGroupDO.getUserName(), null);
appCount.put(exSsoAccessGroupDO.getAppName(), subResult);
} else {
HashMap<String, String> subResult = new HashMap<String, String>();
subResult.put(exSsoAccessGroupDO.getUserName(), null);
appCount.put(exSsoAccessGroupDO.getAppName(), subResult);
}
}
// 设置结果
result.setResultList(SsoAccessConvertor.convertExDos2ExVos(listCopy));
result.setPageNum(pageList.getPaginator().getPage());
result.setPageSize(pageList.getPaginator().getItemsPerPage());
result.setTotal(pageList.getPaginator().getItems());
result.setOnline(ssoAccessDAO.queryByDate(new Date()).size());
result.setTotalUser(new Long(ssoUserDAO.queryTotalUser()).intValue());
result.setAppResult(appCount);
}
}, result);
return result;
}
/**
* @see com.bbd.bdsso.common.service.facade.SsoAccessFacade#querySummaryInfo(java.lang.String, java.lang.String)
*/
@Override
@AuthValidate(type = AuthTypeEnum.NO)
public BdssoSummaryResult querySummaryInfo(String uid, String token) {
final BdssoSummaryResult result = new BdssoSummaryResult();
bdssoTransactionTemplate.executeWithTransaction(new BdssoCallBack() {
@Override
public void check() {
}
@Override
public void service() {
// 设置结果
result.setOnline(ssoAccessDAO.queryByDate(new Date()).size());
result.setTotalUser(new Long(ssoUserDAO.queryTotalUser()).intValue());
}
}, result);
return result;
}
}
|
3e1a34539f5f8b4460c612743c0999afbdf80d71 | 6,624 | java | Java | server/src/main/java/com/kylinolap/rest/service/BasicService.java | vbelakov/Kylin | 1993ab000b0dcaa8263f8d4eba11199ad8fcb0f6 | [
"Apache-2.0"
] | null | null | null | server/src/main/java/com/kylinolap/rest/service/BasicService.java | vbelakov/Kylin | 1993ab000b0dcaa8263f8d4eba11199ad8fcb0f6 | [
"Apache-2.0"
] | 1 | 2022-01-21T23:48:05.000Z | 2022-01-21T23:48:05.000Z | server/src/main/java/com/kylinolap/rest/service/BasicService.java | gaurav46/Kylin | 0e9e152f12243f7c9861245ec6e1faa6f26d2dd2 | [
"Apache-2.0"
] | null | null | null | 34.14433 | 180 | 0.677536 | 11,150 | /*
* Copyright 2013-2014 eBay Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kylinolap.rest.service;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.sql.DataSource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import com.google.common.io.Files;
import com.kylinolap.common.KylinConfig;
import com.kylinolap.cube.CubeManager;
import com.kylinolap.cube.project.ProjectInstance;
import com.kylinolap.cube.project.ProjectManager;
import com.kylinolap.job.JobManager;
import com.kylinolap.job.engine.JobEngineConfig;
import com.kylinolap.job.exception.JobException;
import com.kylinolap.metadata.MetadataManager;
import com.kylinolap.query.enumerator.OLAPQuery;
import com.kylinolap.query.relnode.OLAPContext;
import com.kylinolap.query.schema.OLAPSchemaFactory;
import com.kylinolap.rest.controller.QueryController;
public abstract class BasicService {
private static final Logger logger = LoggerFactory.getLogger(BasicService.class);
private static ConcurrentMap<String, DataSource> olapDataSources = new ConcurrentHashMap<String, DataSource>();
// @Autowired
// protected JdbcTemplate jdbcTemplate;
public KylinConfig getConfig() {
return KylinConfig.getInstanceFromEnv();
}
public void removeOLAPDataSource(String project) {
if (StringUtils.isEmpty(project))
throw new IllegalArgumentException("removeOLAPDataSource: project name not given");
project = ProjectInstance.getNormalizedProjectName(project);
olapDataSources.remove(project);
}
public static void resetOLAPDataSources() {
// brutal, yet simplest way
logger.info("resetOLAPDataSources is called.");
olapDataSources = new ConcurrentHashMap<String, DataSource>();
}
public DataSource getOLAPDataSource(String project) {
project = ProjectInstance.getNormalizedProjectName(project);
DataSource ret = olapDataSources.get(project);
if (ret == null) {
logger.debug("Creating a new data source");
logger.debug("OLAP data source pointing to " + getConfig());
File modelJson = OLAPSchemaFactory.createTempOLAPJson(project, getConfig());
try {
List<String> text = Files.readLines(modelJson, Charset.defaultCharset());
logger.debug("The new temp olap json is :");
for (String line : text)
logger.debug(line);
} catch (IOException e) {
e.printStackTrace(); // logging failure is not critical
}
DriverManagerDataSource ds = new DriverManagerDataSource();
Properties props = new Properties();
props.setProperty(OLAPQuery.PROP_SCAN_THRESHOLD, String.valueOf(KylinConfig.getInstanceFromEnv().getScanThreshold()));
ds.setConnectionProperties(props);
ds.setDriverClassName("net.hydromatic.optiq.jdbc.Driver");
ds.setUrl("jdbc:optiq:model=" + modelJson.getAbsolutePath());
ret = olapDataSources.putIfAbsent(project, ds);
if (ret == null) {
ret = ds;
}
}
return ret;
}
/**
* Reload changed cube into cache
*
* @param name
* @throws IOException
*/
@Caching(evict = { @CacheEvict(value = QueryController.SUCCESS_QUERY_CACHE, allEntries = true), @CacheEvict(value = QueryController.EXCEPTION_QUERY_CACHE, allEntries = true) })
public void cleanDataCache() {
CubeManager.removeInstance(getConfig());
ProjectManager.removeInstance(getConfig());
BasicService.resetOLAPDataSources();
}
/**
* Reload the cube desc with name {name} into cache
*
* @param name
*/
public void reloadMetadataCache() {
MetadataManager.getInstance(getConfig()).reload();
}
public KylinConfig getKylinConfig() {
KylinConfig kylinConfig = KylinConfig.getInstanceFromEnv();
if (kylinConfig == null) {
throw new IllegalArgumentException("Failed to load kylin config instance");
}
return kylinConfig;
}
public MetadataManager getMetadataManager() {
return MetadataManager.getInstance(getConfig());
}
public CubeManager getCubeManager() {
return CubeManager.getInstance(getConfig());
}
public ProjectManager getProjectManager() {
return ProjectManager.getInstance(getConfig());
}
public JobManager getJobManager() throws JobException, UnknownHostException {
KylinConfig config = KylinConfig.getInstanceFromEnv();
JobEngineConfig engineCntx = new JobEngineConfig(config);
InetAddress ia = InetAddress.getLocalHost();
return new JobManager(ia.getCanonicalHostName(), engineCntx);
}
protected static void close(ResultSet resultSet, Statement stat, Connection conn) {
OLAPContext.clearParameter();
if (resultSet != null)
try {
resultSet.close();
} catch (SQLException e) {
logger.error("failed to close", e);
}
if (stat != null)
try {
stat.close();
} catch (SQLException e) {
logger.error("failed to close", e);
}
if (conn != null)
try {
conn.close();
} catch (SQLException e) {
logger.error("failed to close", e);
}
}
}
|
3e1a34baf56edf52c985a4c6c7d238a1747181c0 | 1,558 | java | Java | content/public/android/java/src/org/chromium/content/browser/accessibility/PieWebContentsAccessibility.java | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/public/android/java/src/org/chromium/content/browser/accessibility/PieWebContentsAccessibility.java | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/public/android/java/src/org/chromium/content/browser/accessibility/PieWebContentsAccessibility.java | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | 39.948718 | 96 | 0.750963 | 11,151 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.content.browser.accessibility;
import android.annotation.TargetApi;
import android.os.Build;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.autofill.AutofillManager;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.content_public.browser.WebContents;
/**
* Subclass of WebContentsAccessibility for P
*/
@JNINamespace("content")
@TargetApi(Build.VERSION_CODES.P)
public class PieWebContentsAccessibility extends OWebContentsAccessibility {
PieWebContentsAccessibility(WebContents webContents) {
super(webContents);
AutofillManager autofillManager = mContext.getSystemService(AutofillManager.class);
if (autofillManager != null && autofillManager.isEnabled()) {
// Native accessibility is usually initialized when getAccessibilityNodeProvider is
// called, but the Autofill compatibility bridge only calls that method after it has
// received the first accessibility events. To solve the chicken-and-egg problem,
// always initialize the native parts when the user has an Autofill service enabled.
refreshState();
getAccessibilityNodeProvider();
}
}
@Override
protected void setAccessibilityNodeInfoPaneTitle(AccessibilityNodeInfo node, String title) {
node.setPaneTitle(title);
}
}
|
3e1a3517414c0f30c8668df1cf5136e0176e3e18 | 640 | java | Java | src/main/java/com/agricraft/agricore/plant/versions/v1/AgriProductList_1_12.java | nbrichau/AgriCore | f271e9cb875c21b59b96412dd923872de528ad1c | [
"MIT"
] | 8 | 2016-04-08T16:50:24.000Z | 2021-12-03T19:47:28.000Z | src/main/java/com/agricraft/agricore/plant/versions/v1/AgriProductList_1_12.java | nbrichau/AgriCore | f271e9cb875c21b59b96412dd923872de528ad1c | [
"MIT"
] | 15 | 2017-07-07T06:50:51.000Z | 2021-08-02T17:38:52.000Z | src/main/java/com/agricraft/agricore/plant/versions/v1/AgriProductList_1_12.java | nbrichau/AgriCore | f271e9cb875c21b59b96412dd923872de528ad1c | [
"MIT"
] | 11 | 2016-08-08T19:36:27.000Z | 2022-02-17T08:27:03.000Z | 24.615385 | 117 | 0.732813 | 11,152 | package com.agricraft.agricore.plant.versions.v1;
import com.agricraft.agricore.plant.AgriProductList;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class AgriProductList_1_12 {
private final List<AgriProduct_1_12> products;
public AgriProductList_1_12() {
this.products = new ArrayList<>();
}
public AgriProductList_1_12(List<AgriProduct_1_12> products) {
this.products = products;
}
public AgriProductList toNew() {
return new AgriProductList(this.products.stream().map(AgriProduct_1_12::toNew).collect(Collectors.toList()));
}
}
|
3e1a36f694b4cace7c246c8687377bbfc71e75bd | 16,699 | java | Java | tests/javaobject/PdxTests/PdxType.java | jupiternightingale/geode-native | 327a677a95670c329cf4e412b897745211552d9e | [
"Apache-2.0"
] | 48 | 2017-02-08T22:24:07.000Z | 2022-02-06T02:47:56.000Z | tests/javaobject/PdxTests/PdxType.java | jupiternightingale/geode-native | 327a677a95670c329cf4e412b897745211552d9e | [
"Apache-2.0"
] | 388 | 2017-02-13T17:09:45.000Z | 2022-03-29T22:18:39.000Z | tests/javaobject/PdxTests/PdxType.java | jupiternightingale/geode-native | 327a677a95670c329cf4e412b897745211552d9e | [
"Apache-2.0"
] | 68 | 2017-02-09T18:43:15.000Z | 2022-03-14T22:59:13.000Z | 30.034173 | 102 | 0.630397 | 11,153 | /*
* 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 PdxTests;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import org.apache.geode.pdx.PdxReader;
import org.apache.geode.pdx.PdxSerializable;
import org.apache.geode.pdx.PdxWriter;
public class PdxType implements PdxSerializable{
char m_char;
boolean m_bool;
byte m_byte;
byte m_sbyte;
short m_int16;
short m_uint16;
int m_int32;
int m_uint32;
long m_long;
long m_ulong;
float m_float;
double m_double;
String m_string;
boolean[] m_boolArray;
byte[] m_byteArray;
byte[] m_sbyteArray;
char[] m_charArray;
Date m_dateTime;
short[] m_int16Array;
short[] m_uint16Array;
int[] m_int32Array;
int[] m_uint32Array;
long[] m_longArray;
long[] m_ulongArray;
float[] m_floatArray;
double[] m_doubleArray;
byte[][] m_byteByteArray ;
String[] m_stringArray ;
Address[] m_address;
/* List<object> m_arraylist = new List<object>();
IDictionary<object, object> m_map = new Dictionary<object, object>();
Hashtable m_hashtable = new Hashtable();
ArrayList m_vector = new ArrayList();*/
ArrayList<Object> m_arraylist = new ArrayList<Object>();
Map<Object, Object> m_map = new HashMap<Object, Object>();
Hashtable m_hashtable = new Hashtable();
Vector m_vector = new Vector();
/*CacheableHashSet m_chs = CacheableHashSet.Create();
CacheableLinkedHashSet m_clhs = CacheableLinkedHashSet.Create();*/
HashSet m_chs = new HashSet();
LinkedHashSet m_clhs = new LinkedHashSet();
byte[] m_byte252 = new byte[252];
byte[] m_byte253 = new byte[253];
byte[] m_byte65535 = new byte[65535];
byte[] m_byte65536 = new byte[65536];
pdxEnumTest m_pdxEnum = pdxEnumTest.pdx2;
Object[] m_objectArray;
public PdxType()
{
init();
}
public void init()
{
m_char = 'C';
m_bool = true;
m_byte = (byte)0x74;
m_sbyte = 0x67;
m_int16 = 0xab;
m_uint16 = (short)0x2dd5;
m_int32 = 0x2345abdc;
m_uint32 = 0x2a65c434;
m_long = (long)324897980;
m_ulong = (long)238749898;
m_float = 23324.324f;
m_double = 3243298498d;
m_string = "gfestring";
m_boolArray = new boolean[] { true, false, true };
m_byteArray = new byte[] { 0x34, 0x64 };
m_sbyteArray = new byte[] { 0x34, 0x64 };
m_charArray = new char[] { 'c', 'v' };
long ticksMillis = 1310447869154L;//from epoch
m_dateTime = new Date(ticksMillis);
//m_dateTime = new Date( System.currentTimeMillis());
m_int16Array = new short[] { 0x2332, 0x4545 };
m_uint16Array = new short[] { 0x3243, 0x3232 };
m_int32Array = new int[] { 23, 676868, 34343, 2323 };
m_uint32Array = new int[] { 435, 234324, 324324, 23432432 };
m_longArray = new long[] { 324324L, 23434545L };
m_ulongArray = new long[] { 3245435, 3425435 };
m_floatArray = new float[] { 232.565f, 2343254.67f };
m_doubleArray = new double[] { 23423432d, 4324235435d };
m_byteByteArray = new byte[][]{new byte[] {0x23},
new byte[]{0x34, 0x55}
};
m_stringArray = new String[] { "one", "two" };
m_arraylist = new ArrayList<Object>();
m_arraylist.add(1);
m_arraylist.add(2);
m_map = new HashMap<Object, Object>();
m_map.put(1, 1);
m_map.put(2, 2);
m_hashtable = new Hashtable();
m_hashtable.put(1, "1111111111111111");
m_hashtable.put(2, "2222222222221111111111111111");
m_vector = new Vector();
m_vector.add(1);
m_vector.add(2);
m_vector.add(3);
m_chs.add(1);
m_clhs.add(1);
m_clhs.add(2);
m_pdxEnum = pdxEnumTest.pdx2;
m_address = new Address[10];
for (int i = 0; i < 10; i++)
{
m_address[i] = new Address(i + 1, "street" + String.valueOf(i), "city" + String.valueOf(i));
}
m_objectArray = new Object[10];
for (int i = 0; i < 10; i++)
{
m_objectArray[i] = new Address(i + 1, "street" + String.valueOf(i), "city" + String.valueOf(i));
}
}
public void fromData(PdxReader reader) {
// TODO Auto-generated method stub
byte[][] baa = reader.readArrayOfByteArrays("m_byteByteArray");
m_byteByteArray = compareByteByteArray(baa, m_byteByteArray);
m_char = GenericValCompare(reader.readChar("m_char"), m_char);
boolean bl = reader.readBoolean("m_bool");
m_bool = GenericValCompare(bl, m_bool);
m_boolArray = compareBoolArray(reader.readBooleanArray("m_boolArray"), m_boolArray);
m_byte = GenericValCompare(reader.readByte("m_byte"), m_byte);
m_byteArray = compareByteArray(reader.readByteArray("m_byteArray"), m_byteArray);
m_charArray = compareCharArray(reader.readCharArray("m_charArray"), m_charArray);
//List<Object> tmpl = new ArrayList<Object>();
Collection tmpl = (Collection)reader.readObject("m_arraylist");
m_arraylist = (ArrayList)compareCompareCollection(tmpl, m_arraylist);
HashMap<Object, Object> tmpM = (HashMap<Object, Object>)reader.readObject("m_map");
if(tmpM.size() != m_map.size())
throw new IllegalStateException("Not got expected value for type: " + m_map.toString());
Hashtable tmpH = (Hashtable)reader.readObject("m_hashtable");
if(tmpH.size()!= m_hashtable.size())
throw new IllegalStateException("Not got expected value for type: " + m_hashtable.toString());
Vector vector = (Vector)reader.readObject("m_vector");
if(vector.size()!= m_vector.size())
throw new IllegalStateException("Not got expected value for type: " + m_vector.toString());
HashSet rmpChs = (HashSet)reader.readObject("m_chs");
if (rmpChs.size() != m_chs.size())
throw new IllegalStateException("Not got expected value for type: " + m_chs.toString());
LinkedHashSet rmpClhs = (LinkedHashSet)reader.readObject("m_clhs");
if (rmpClhs.size()!= m_clhs.size())
throw new IllegalStateException("Not got expected value for type: " + m_clhs.toString());
m_string = GenericValCompare(reader.readString("m_string"), m_string);
m_dateTime = compareData(reader.readDate("m_dateTime"), m_dateTime);
m_double = GenericValCompare(reader.readDouble("m_double"), m_double);
m_doubleArray = compareDoubleArray(reader.readDoubleArray("m_doubleArray"), m_doubleArray);
m_float = GenericValCompare(reader.readFloat("m_float"), m_float);
m_floatArray = compareFloatArray(reader.readFloatArray("m_floatArray"), m_floatArray);
m_int16 = GenericValCompare(reader.readShort("m_int16"), m_int16);
m_int32 = GenericValCompare(reader.readInt("m_int32"), m_int32);
m_long = GenericValCompare(reader.readLong("m_long"), m_long);
m_int32Array = compareIntArray(reader.readIntArray("m_int32Array"), m_int32Array);
m_longArray = compareLongArray(reader.readLongArray("m_longArray"), m_longArray);
m_int16Array = compareSHortArray(reader.readShortArray("m_int16Array"), m_int16Array);
m_sbyte = GenericValCompare(reader.readByte("m_sbyte"), m_sbyte);
m_sbyteArray = compareByteArray(reader.readByteArray("m_sbyteArray"), m_sbyteArray);
m_stringArray = compareStringArray(reader.readStringArray("m_stringArray"), m_stringArray);
m_uint16 = GenericValCompare(reader.readShort("m_uint16"), m_uint16);
m_uint32 = GenericValCompare(reader.readInt("m_uint32"), m_uint32);
m_ulong = GenericValCompare(reader.readLong("m_ulong"), m_ulong);
m_uint32Array = compareIntArray(reader.readIntArray("m_uint32Array"), m_uint32Array);
m_ulongArray = compareLongArray(reader.readLongArray("m_ulongArray"), m_ulongArray);
m_uint16Array = compareSHortArray(reader.readShortArray("m_uint16Array"), m_uint16Array);
byte[] ret = reader.readByteArray("m_byte252");
if (ret.length != 252)
throw new IllegalStateException("Array len 252 not found");
ret = reader.readByteArray("m_byte253");
if (ret.length != 253)
throw new IllegalStateException("Array len 253 not found");
ret = reader.readByteArray("m_byte65535");
if (ret.length != 65535)
throw new IllegalStateException("Array len 65535 not found");
ret = reader.readByteArray("m_byte65536");
if (ret.length != 65536)
throw new IllegalStateException("Array len 65536 not found");
pdxEnumTest retEnum = (pdxEnumTest)reader.readObject("m_pdxEnum");
if(retEnum != m_pdxEnum)
throw new IllegalStateException("pdx enum is not equal");
Address[] otherA = (Address[])reader.readObject("m_address");
{
for (int i = 0; i < m_address.length; i++)
{
if (!m_address[i].equals(otherA[i]))
throw new IllegalStateException("Address array not matched " + i);
}
}
Object[] retoa = reader.readObjectArray("m_objectArray");
for (int i = 0; i < m_objectArray.length; i++)
{
if(!m_objectArray[i].equals(retoa[i]))
throw new IllegalStateException("Object array not mateched " + i);
}
}
public void toData(PdxWriter writer) {
// TODO Auto-generated method stub
writer.writeArrayOfByteArrays("m_byteByteArray", m_byteByteArray);
writer.writeChar("m_char", m_char);
writer.writeBoolean("m_bool", m_bool);
writer.writeBooleanArray("m_boolArray", m_boolArray);
writer.writeByte("m_byte", m_byte);
writer.writeByteArray("m_byteArray", m_byteArray);
writer.writeCharArray("m_charArray", m_charArray);
writer.writeObject("m_arraylist", m_arraylist);
writer.writeObject("m_map", m_map);
writer.writeObject("m_hashtable", m_hashtable);
writer.writeObject("m_vector", m_vector);
writer.writeObject("m_chs", m_chs);
writer.writeObject("m_clhs", m_clhs);
writer.writeString("m_string", m_string);
writer.writeDate("m_dateTime", m_dateTime);
writer.writeDouble("m_double", m_double);
writer.writeDoubleArray("m_doubleArray", m_doubleArray);
writer.writeFloat("m_float", m_float);
writer.writeFloatArray("m_floatArray", m_floatArray);
writer.writeShort("m_int16", m_int16);
writer.writeInt("m_int32", m_int32);
writer.writeLong("m_long", m_long);
writer.writeIntArray("m_int32Array", m_int32Array);
writer.writeLongArray("m_longArray", m_longArray);
writer.writeShortArray("m_int16Array", m_int16Array);
writer.writeByte("m_sbyte", m_sbyte);
writer.writeByteArray("m_sbyteArray", m_sbyteArray);
writer.writeStringArray("m_stringArray", m_stringArray);
writer.writeShort("m_uint16", m_uint16);
writer.writeInt("m_uint32", m_uint32);
writer.writeLong("m_ulong", m_ulong);
writer.writeIntArray("m_uint32Array", m_uint32Array);
writer.writeLongArray("m_ulongArray", m_ulongArray);
writer.writeShortArray("m_uint16Array", m_uint16Array);
writer.writeByteArray("m_byte252", m_byte252);
writer.writeByteArray("m_byte253", m_byte253);
writer.writeByteArray("m_byte65535", m_byte65535);
writer.writeByteArray("m_byte65536", m_byte65536);
writer.writeObject("m_pdxEnum", m_pdxEnum);
writer.writeObject("m_address", m_address);
writer.writeObjectArray("m_objectArray", m_objectArray);
}
byte[][] compareByteByteArray(byte[][] baa, byte[][] baa2)
{
if (baa.length == baa2.length)
{
int i = 0;
while (i < baa.length)
{
i++;
}
if (i == baa2.length)
return baa2;
}
throw new IllegalStateException("Not got expected value for type: " + baa2.toString());
}
<T> T GenericValCompare(T b, T b2)
{
if (b.equals( b2))
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.toString());
}
boolean[] compareBoolArray(boolean[] a, boolean[] a2)
{
if (a.length == a2.length)
{
int i = 0;
while (i < a.length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.toString());
}
byte[] compareByteArray(byte[] a, byte[] a2)
{
if (a.length == a2.length)
{
int i = 0;
while (i < a.length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.toString());
}
char[] compareCharArray(char[] a, char[] a2)
{
if (a.length == a2.length)
{
int i = 0;
while (i < a.length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.toString());
}
Collection compareCompareCollection(Collection c, Collection c2)
{
Object[] a = c.toArray();
Object[] a2 = c.toArray();
if (a.length== a2.length)
{
int i = 0;
while (i < a.length)
{
if (!a[i].equals(a2[i]))
break;
else
i++;
}
if (i == a2.length)
return c2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.toString());
}
Date compareData(Date b, Date b2)
{
//TODO:
System.out.println(b + " := " + b2 );
if(b.equals(b2))
//TODO:
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.toString());
}
double[] compareDoubleArray(double[] a, double[] a2)
{
if (a.length == a2.length)
{
int i = 0;
while (i < a.length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.toString());
}
float[] compareFloatArray(float[] a, float[] a2)
{
if (a.length == a2.length)
{
int i = 0;
while (i < a.length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.toString());
}
int[] compareIntArray(int[] a, int[] a2)
{
if (a.length == a2.length)
{
int i = 0;
while (i < a.length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.toString());
}
long[] compareLongArray(long[] a, long[] a2)
{
if (a.length == a2.length)
{
int i = 0;
while (i < a.length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.toString());
}
short[] compareSHortArray(short[] a, short[] a2)
{
if (a.length == a2.length)
{
int i = 0;
while (i < a.length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.toString());
}
String[] compareStringArray(String[] a, String[] a2)
{
if (a.length == a2.length)
{
int i = 0;
while (i < a.length)
{
if (!a[i].equals(a2[i]))
break;
else
i++;
}
if (i == a2.length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.toString());
}
}
|
3e1a383171591fd4e7cc0b5ede2625dcf58de707 | 2,723 | java | Java | typhon-dist/src/main/scripts/war/bs/B_s025.java | kevin70/typhon | bc43407eeb28d93c761fa4df17e3c6c7553eed12 | [
"Apache-2.0"
] | 1 | 2017-11-30T11:52:37.000Z | 2017-11-30T11:52:37.000Z | typhon-dist/src/main/scripts/war/bs/B_s025.java | weghst/typhon | bc43407eeb28d93c761fa4df17e3c6c7553eed12 | [
"Apache-2.0"
] | null | null | null | typhon-dist/src/main/scripts/war/bs/B_s025.java | weghst/typhon | bc43407eeb28d93c761fa4df17e3c6c7553eed12 | [
"Apache-2.0"
] | 1 | 2017-01-10T07:44:55.000Z | 2017-01-10T07:44:55.000Z | 30.931818 | 123 | 0.667524 | 11,154 | /*
* Copyright 2014 The Skfiy Open Association.
*
* 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 war.bs;
import org.skfiy.typhon.dobj.BSaSkill;
import org.skfiy.typhon.spi.war.AttackEntry;
import org.skfiy.typhon.spi.war.BSaScript;
import org.skfiy.typhon.spi.war.BSaWapper;
import org.skfiy.typhon.spi.war.BufferSkill;
import org.skfiy.typhon.spi.war.Direction;
import org.skfiy.typhon.spi.war.FightObject;
import org.skfiy.typhon.spi.war.FightObjectBufferSkill;
import org.skfiy.typhon.spi.war.MultiAttackResult;
import org.skfiy.typhon.spi.war.WarInfo;
/**
* 典韦, ha07.
*
* @author Kevin Zou <hzdkv@example.com>
*/
public class B_s025 extends BSaScript {
@Override
protected Object doExecute(BSaWapper bsaWapper) {
BSaSkill bsaSkill = bsaWapper.getBsaSkill();
int atk = getAtk(bsaWapper, bsaWapper.getAobj());
FightObject aobj = bsaWapper.getAobj();
MultiAttackResult mar = new MultiAttackResult();
FightObject goal = bsaWapper.getDefenderEntity().findFightGoal();
AttackEntry ae = getWarProvider().attack0(bsaWapper.getWarInfo().getTerrain(), aobj,
goal, atk, getDef(bsaWapper, goal), bsaSkill.getFactor() * bsaWapper.getFactor());
int hp = (int) ae.getVal();
goal.decrementHp(hp);
mar.addTarget(ae);
// 给自己增加一个格挡BUFF
BufferSkill bufferSkill = new MyBufferSkill(bsaWapper.getWarInfo(), bsaWapper.getAttackerEntity().getDire(), aobj);
bufferSkill.onBefore();
return mar;
}
private class MyBufferSkill extends FightObjectBufferSkill {
public MyBufferSkill(WarInfo warInfo, Direction dire, FightObject fobj) {
super(warInfo, dire, fobj);
}
@Override
public Type getType() {
return Type.BUFF;
}
@Override
protected int getTotalRound() {
return 1;
}
@Override
protected Object begin() {
fobj.setParryRate(fobj.getParryRate() + 0.5);
return null;
}
@Override
protected Object end() {
fobj.setParryRate(fobj.getParryRate() - 0.5);
return null;
}
}
}
|
3e1a38d9642dfd2a69b49414f356b027888a99b3 | 2,535 | java | Java | workspace/CardFantasyCore/src/cfvbaibai/cardfantasy/engine/skill/MagicMark.java | mkchen/CardFantasy | 8f1d70252b4193c7512d05b09cdbf029124cb11b | [
"BSD-2-Clause"
] | 21 | 2015-02-27T14:15:42.000Z | 2021-09-29T01:28:39.000Z | workspace/CardFantasyCore/src/cfvbaibai/cardfantasy/engine/skill/MagicMark.java | mkchen/CardFantasy | 8f1d70252b4193c7512d05b09cdbf029124cb11b | [
"BSD-2-Clause"
] | 9 | 2015-01-01T09:02:59.000Z | 2021-06-23T20:46:56.000Z | workspace/CardFantasyCore/src/cfvbaibai/cardfantasy/engine/skill/MagicMark.java | mkchen/CardFantasy | 8f1d70252b4193c7512d05b09cdbf029124cb11b | [
"BSD-2-Clause"
] | 45 | 2015-01-08T13:12:58.000Z | 2021-04-18T03:23:34.000Z | 43.706897 | 158 | 0.584221 | 11,155 | package cfvbaibai.cardfantasy.engine.skill;
import java.util.List;
import cfvbaibai.cardfantasy.GameUI;
import cfvbaibai.cardfantasy.Randomizer;
import cfvbaibai.cardfantasy.data.Skill;
import cfvbaibai.cardfantasy.engine.CardInfo;
import cfvbaibai.cardfantasy.engine.CardStatusItem;
import cfvbaibai.cardfantasy.engine.EntityInfo;
import cfvbaibai.cardfantasy.engine.HeroDieSignal;
import cfvbaibai.cardfantasy.engine.Player;
import cfvbaibai.cardfantasy.engine.SkillResolver;
import cfvbaibai.cardfantasy.engine.SkillUseInfo;
public class MagicMark {
public static void apply(SkillResolver resolver, SkillUseInfo skillUseInfo, EntityInfo caster, Player enemyPlayer, int victimCount) throws HeroDieSignal {
GameUI ui = resolver.getStage().getUI();
Skill skill = skillUseInfo.getSkill();
Randomizer random = Randomizer.getRandomizer();
List<CardInfo> victims = random.pickRandom(enemyPlayer.getField().toList(), victimCount, true, null);
ui.useSkill(caster, victims, skill, true);
for (CardInfo victim : victims) {
CardStatusItem statusItem = CardStatusItem.magicMark(skillUseInfo);
if (!resolver.resolveAttackBlockingSkills(caster, victim, skill, 1).isAttackable()) {
continue;
}
int magicEchoSkillResult = resolver.resolveMagicEchoSkill(caster, victim, skill);
if (magicEchoSkillResult == 1 || magicEchoSkillResult == 2) {
if (caster instanceof CardInfo) {
CardInfo attackCard = (CardInfo) caster;
if (attackCard.isDead()) {
if (magicEchoSkillResult == 1) {
continue;
}
}
else{
if (!resolver.resolveAttackBlockingSkills(victim, attackCard, skill, 1).isAttackable()) {
if (magicEchoSkillResult == 1) {
continue;
}
}
else{
ui.addCardStatus(victim, attackCard, skill, statusItem);
attackCard.addStatus(statusItem);
}
}
}
if (magicEchoSkillResult == 1) {
continue;
}
}
ui.addCardStatus(caster, victim, skill, statusItem);
victim.addStatus(statusItem);
}
}
}
|
3e1a397e689f4f1e5829fbb1661b756dce85456c | 1,156 | java | Java | smart-common-pojo/src/main/java/io/github/smart/cloud/common/pojo/bo/BooleanResultBO.java | Mu-L/smart-cloud | 752ab4a787912d93c6419d65c69bf839b07d7d32 | [
"Apache-2.0"
] | null | null | null | smart-common-pojo/src/main/java/io/github/smart/cloud/common/pojo/bo/BooleanResultBO.java | Mu-L/smart-cloud | 752ab4a787912d93c6419d65c69bf839b07d7d32 | [
"Apache-2.0"
] | null | null | null | smart-common-pojo/src/main/java/io/github/smart/cloud/common/pojo/bo/BooleanResultBO.java | Mu-L/smart-cloud | 752ab4a787912d93c6419d65c69bf839b07d7d32 | [
"Apache-2.0"
] | null | null | null | 23.12 | 75 | 0.697232 | 11,156 | /*
* Copyright © 2019 collin (kenaa@example.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.smart.cloud.common.pojo.bo;
import lombok.*;
import io.github.smart.cloud.common.pojo.Base;
/**
* boolean BO
*
* @author collin
* @date 2019-07-05
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class BooleanResultBO extends Base {
private static final long serialVersionUID = 1L;
/**
* 是否成功(通过)
*/
private Boolean success;
/**
* 提示信息
*/
private String message;
public BooleanResultBO(boolean success) {
this.success = success;
}
} |
3e1a3cf884dfd1235b023db5d523b987b2f0750b | 4,973 | java | Java | services/iec/src/main/java/com/huaweicloud/sdk/iec/v1/model/BatchReboot.java | huaweicloud/huaweicloud-sdk-java-v3 | a01cd21a3d03f6dffc807bea7c522e34adfa368d | [
"Apache-2.0"
] | 50 | 2020-05-18T11:35:20.000Z | 2022-03-15T02:07:05.000Z | services/iec/src/main/java/com/huaweicloud/sdk/iec/v1/model/BatchReboot.java | huaweicloud/huaweicloud-sdk-java-v3 | a01cd21a3d03f6dffc807bea7c522e34adfa368d | [
"Apache-2.0"
] | 45 | 2020-07-06T03:34:12.000Z | 2022-03-31T09:41:54.000Z | services/iec/src/main/java/com/huaweicloud/sdk/iec/v1/model/BatchReboot.java | huaweicloud/huaweicloud-sdk-java-v3 | a01cd21a3d03f6dffc807bea7c522e34adfa368d | [
"Apache-2.0"
] | 27 | 2020-05-28T11:08:44.000Z | 2022-03-30T03:30:37.000Z | 27.027174 | 112 | 0.570883 | 11,157 | package com.huaweicloud.sdk.iec.v1.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
/** 批量重启边缘实例对象 */
public class BatchReboot {
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "servers")
private List<BaseId> servers = null;
/** 重启类型: - SOFT:普通重启。 - HARD:强制重启。 > 重启必须指定重启类型。 */
public static final class TypeEnum {
/** Enum SOFT for value: "SOFT" */
public static final TypeEnum SOFT = new TypeEnum("SOFT");
/** Enum HARD for value: "HARD" */
public static final TypeEnum HARD = new TypeEnum("HARD");
private static final Map<String, TypeEnum> STATIC_FIELDS = createStaticFields();
private static Map<String, TypeEnum> createStaticFields() {
Map<String, TypeEnum> map = new HashMap<>();
map.put("SOFT", SOFT);
map.put("HARD", HARD);
return Collections.unmodifiableMap(map);
}
private String value;
TypeEnum(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static TypeEnum fromValue(String value) {
if (value == null) {
return null;
}
TypeEnum result = STATIC_FIELDS.get(value);
if (result == null) {
result = new TypeEnum(value);
}
return result;
}
public static TypeEnum valueOf(String value) {
if (value == null) {
return null;
}
TypeEnum result = STATIC_FIELDS.get(value);
if (result != null) {
return result;
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
@Override
public boolean equals(Object obj) {
if (obj instanceof TypeEnum) {
return this.value.equals(((TypeEnum) obj).value);
}
return false;
}
@Override
public int hashCode() {
return this.value.hashCode();
}
}
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "type")
private TypeEnum type;
public BatchReboot withServers(List<BaseId> servers) {
this.servers = servers;
return this;
}
public BatchReboot addServersItem(BaseId serversItem) {
if (this.servers == null) {
this.servers = new ArrayList<>();
}
this.servers.add(serversItem);
return this;
}
public BatchReboot withServers(Consumer<List<BaseId>> serversSetter) {
if (this.servers == null) {
this.servers = new ArrayList<>();
}
serversSetter.accept(this.servers);
return this;
}
/** 待重启的边缘实例列表。
*
* @return servers */
public List<BaseId> getServers() {
return servers;
}
public void setServers(List<BaseId> servers) {
this.servers = servers;
}
public BatchReboot withType(TypeEnum type) {
this.type = type;
return this;
}
/** 重启类型: - SOFT:普通重启。 - HARD:强制重启。 > 重启必须指定重启类型。
*
* @return type */
public TypeEnum getType() {
return type;
}
public void setType(TypeEnum type) {
this.type = type;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BatchReboot batchReboot = (BatchReboot) o;
return Objects.equals(this.servers, batchReboot.servers) && Objects.equals(this.type, batchReboot.type);
}
@Override
public int hashCode() {
return Objects.hash(servers, type);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class BatchReboot {\n");
sb.append(" servers: ").append(toIndentedString(servers)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append("}");
return sb.toString();
}
/** Convert the given object to string with each line indented by 4 spaces (except the first line). */
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
3e1a3de0717f2adfd8999f10a17318f17fdbe003 | 6,062 | java | Java | wulin/src/com/hundsun/network/gates/wulin/web/action/BaseAction.java | sodoa/ccfrt | 7df85558bcd74ef6be7867082b13bd0ed1d49594 | [
"Apache-2.0"
] | null | null | null | wulin/src/com/hundsun/network/gates/wulin/web/action/BaseAction.java | sodoa/ccfrt | 7df85558bcd74ef6be7867082b13bd0ed1d49594 | [
"Apache-2.0"
] | null | null | null | wulin/src/com/hundsun/network/gates/wulin/web/action/BaseAction.java | sodoa/ccfrt | 7df85558bcd74ef6be7867082b13bd0ed1d49594 | [
"Apache-2.0"
] | 1 | 2021-12-31T12:32:12.000Z | 2021-12-31T12:32:12.000Z | 41.806897 | 115 | 0.56615 | 11,158 | /* */ package com.hundsun.network.gates.wulin.web.action;
/* */
/* */ import com.hundsun.network.gates.luosi.common.remote.ServiceResult;
/* */ import com.hundsun.network.melody.common.web.url.URLBroker;
/* */ import java.text.DateFormat;
/* */ import java.text.DecimalFormat;
/* */ import java.text.NumberFormat;
/* */ import java.text.SimpleDateFormat;
/* */ import java.util.Date;
/* */ import java.util.Locale;
/* */ import org.apache.commons.logging.Log;
/* */ import org.apache.commons.logging.LogFactory;
/* */ import org.springframework.beans.factory.annotation.Autowired;
/* */ import org.springframework.beans.propertyeditors.CustomDateEditor;
/* */ import org.springframework.beans.propertyeditors.CustomNumberEditor;
/* */ import org.springframework.context.MessageSource;
/* */ import org.springframework.ui.Model;
/* */ import org.springframework.ui.ModelMap;
/* */ import org.springframework.web.bind.WebDataBinder;
/* */ import org.springframework.web.bind.annotation.InitBinder;
/* */
/* */ public class BaseAction
/* */ {
/* 26 */ protected final Log log = LogFactory.getLog(getClass());
/* */
/* */ @Autowired
/* */ private URLBroker appServerBroker;
/* */
/* */ @Autowired
/* */ private MessageSource messageSource;
/* */
/* */ @InitBinder
/* */ protected final void initBinderInternal(WebDataBinder binder)
/* */ {
/* 42 */ registerDefaultCustomDateEditor(binder);
/* 43 */ registerDefaultCustomNumberEditor(binder);
/* 44 */ initBinder(binder);
/* */ }
/* */
/* */ private void registerDefaultCustomNumberEditor(WebDataBinder binder)
/* */ {
/* 50 */ NumberFormat numberFormat = new DecimalFormat("#0.00");
/* 51 */ binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, numberFormat, true));
/* */ }
/* */
/* */ protected void registerDefaultCustomDateEditor(WebDataBinder binder)
/* */ {
/* 58 */ DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
/* 59 */ dateFormat.setLenient(false);
/* 60 */ binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
/* */ }
/* */
/* */ protected void initBinder(WebDataBinder binder)
/* */ {
/* */ }
/* */
/* */ protected String redirectLogin()
/* */ {
/* 72 */ return redirect("/login.htm");
/* */ }
/* */
/* */ protected String redirectIndex() {
/* 76 */ return redirect("/user/index.htm");
/* */ }
/* */
/* */ protected String redirectEmpty() {
/* 80 */ return redirect("/empty.htm");
/* */ }
/* */
/* */ protected String redirectError() {
/* 84 */ return redirect("/error.htm");
/* */ }
/* */
/* */ protected String success() {
/* 88 */ return redirect("/success.htm");
/* */ }
/* */
/* */ protected String getMessage(String code, String[] args) {
/* 92 */ return this.messageSource.getMessage(code, args, Locale.CHINA);
/* */ }
/* */
/* */ protected String error() {
/* 96 */ return "error";
/* */ }
/* */
/* */ protected String redirect(String url) {
/* 100 */ return "redirect:" + this.appServerBroker + url;
/* */ }
/* */
/* */ protected String success(Model model, String code, String[] args) {
/* 104 */ String message = this.messageSource.getMessage(code, args, Locale.CHINA);
/* 105 */ model.addAttribute("message", message);
/* 106 */ return "success";
/* */ }
/* */
/* */ protected String success(ModelMap model, String code, String[] args) {
/* 110 */ String message = this.messageSource.getMessage(code, args, Locale.CHINA);
/* 111 */ model.addAttribute("message", message);
/* 112 */ return "success";
/* */ }
/* */
/* */ protected String error(Model model, String code, String[] args) {
/* 116 */ String message = this.messageSource.getMessage(code, args, Locale.CHINA);
/* 117 */ model.addAttribute("message", message);
/* 118 */ return "error";
/* */ }
/* */
/* */ protected String error(ModelMap model, String code, String[] args) {
/* 122 */ String message = this.messageSource.getMessage(code, args, Locale.CHINA);
/* 123 */ model.addAttribute("message", message);
/* 124 */ return "error";
/* */ }
/* */
/* */ protected void setResult(ModelMap model, ServiceResult result) {
/* 128 */ if (result != null) {
/* 129 */ if (result.correct()) {
/* 130 */ model.addAttribute("success", Boolean.valueOf(true));
/* */ } else {
/* 132 */ model.addAttribute("success", Boolean.valueOf(false));
/* 133 */ model.addAttribute("errorMsg", result.getErrorInfo());
/* */ }
/* */ }
/* 136 */ else setErrorResult(model, "remote.error.null", new String[0]);
/* */ }
/* */
/* */ protected void setErrorResult(ModelMap model, String code, String[] args)
/* */ {
/* 141 */ String message = this.messageSource.getMessage(code, args, Locale.CHINA);
/* 142 */ model.addAttribute("success", Boolean.valueOf(false));
/* 143 */ model.addAttribute("errorMsg", message);
/* */ }
/* */
/* */ protected void setSuccessResult(ModelMap model) {
/* 147 */ model.addAttribute("success", Boolean.valueOf(true));
/* */ }
/* */
/* */ protected String getSourceMsg(String code, String[] args) {
/* 151 */ return this.messageSource.getMessage(code, args, Locale.CHINA);
/* */ }
/* */ }
/* Location: E:\__安装归档\linquan-20161112\deploy16\wulin\webroot\WEB-INF\classes\
* Qualified Name: com.hundsun.network.gates.wulin.web.action.BaseAction
* JD-Core Version: 0.6.0
*/ |
3e1a3e8803380ee96fd7757435b19d0f5634f1a7 | 3,593 | java | Java | domain/src/test/java/io/github/carlomicieli/catalog/catalogitems/CatalogItemFactoryTest.java | CarloMicieli/microtrains | 8124129b9e87dfc69a5540fecd3134a3a9024513 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | domain/src/test/java/io/github/carlomicieli/catalog/catalogitems/CatalogItemFactoryTest.java | CarloMicieli/microtrains | 8124129b9e87dfc69a5540fecd3134a3a9024513 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | domain/src/test/java/io/github/carlomicieli/catalog/catalogitems/CatalogItemFactoryTest.java | CarloMicieli/microtrains | 8124129b9e87dfc69a5540fecd3134a3a9024513 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 41.77907 | 94 | 0.749513 | 11,159 | /*
Copyright 2021 (C) Carlo Micieli
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.github.carlomicieli.catalog.catalogitems;
import static org.assertj.core.api.Assertions.*;
import io.github.carlomicieli.catalog.brands.BrandId;
import io.github.carlomicieli.catalog.catalogitems.deliverydates.DeliveryDate;
import io.github.carlomicieli.catalog.scales.ScaleId;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Collections;
import java.util.UUID;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.DisplayNameGeneration;
import org.junit.jupiter.api.DisplayNameGenerator;
import org.junit.jupiter.api.Test;
@DisplayName("CategoryItem factory")
@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
class CatalogItemFactoryTest {
private static final Instant FIXED_INSTANT = Instant.parse("1988-11-25T10:15:30.00Z");
private static final BrandId FIXED_BRAND_ID =
BrandId.of(UUID.fromString("e45f901f-0751-489c-910e-ce112d06ccfe"));
private static final ScaleId FIXED_SCALE_ID =
ScaleId.of(UUID.fromString("e9f5ed5a-edb6-46fa-a55a-bc8632e89d3a"));
private static final CatalogItemId FIXED_CATALOG_ITEM_ID =
CatalogItemId.of(UUID.fromString("0218a288-10da-47c4-8e19-b4dad6906579"));
private static final Clock FIXED_CLOCK = Clock.fixed(FIXED_INSTANT, ZoneId.systemDefault());
private final CatalogItemFactory factory;
public CatalogItemFactoryTest() {
this.factory = new CatalogItemFactory(FIXED_CLOCK, () -> FIXED_CATALOG_ITEM_ID);
}
@Test
void should_create_new_catalog_items() {
var itemNumber = ItemNumber.of("123456");
var deliveryDate = DeliveryDate.of(2020, 1);
var catalogItem =
factory.createNewCatalogItem(
FIXED_BRAND_ID,
"ACME",
itemNumber,
CatalogItemCategory.LOCOMOTIVES,
FIXED_SCALE_ID,
PowerMethod.DC,
"My first loco",
"My prototype description",
"My model description",
deliveryDate,
true,
Collections.emptyList());
assertThat(catalogItem).isNotNull();
assertThat(catalogItem.getId()).isEqualTo(FIXED_CATALOG_ITEM_ID);
assertThat(catalogItem.getPowerMethod()).isEqualTo(PowerMethod.DC);
assertThat(catalogItem.getItemNumber()).isEqualTo(itemNumber);
assertThat(catalogItem.getScale()).isEqualTo(FIXED_SCALE_ID);
assertThat(catalogItem.getCategory()).isEqualTo(CatalogItemCategory.LOCOMOTIVES);
assertThat(catalogItem.getDescription()).isEqualTo("My first loco");
assertThat(catalogItem.getModelDescription()).isEqualTo("My model description");
assertThat(catalogItem.getPrototypeDescription()).isEqualTo("My prototype description");
assertThat(catalogItem.getDeliveryDate()).isEqualTo(deliveryDate);
assertThat(catalogItem.getSlug()).isNotNull();
assertThat(catalogItem.getVersion()).isEqualTo(1);
assertThat(catalogItem.getCreatedDate()).isNotNull();
assertThat(catalogItem.getModifiedDate()).isNull();
}
}
|
3e1a3e98cd8f7fbbd958193fde58ad3c083abe73 | 423 | java | Java | src/pruefungsvorbereitung/VCE2014ExamCQuestion196.java | hemmerling/java-114014 | cd34f49cb4eacf52f52713f710239132f5bd8f03 | [
"Apache-2.0"
] | 1 | 2017-07-07T11:13:06.000Z | 2017-07-07T11:13:06.000Z | src/pruefungsvorbereitung/VCE2014ExamCQuestion196.java | hemmerling/java-114014 | cd34f49cb4eacf52f52713f710239132f5bd8f03 | [
"Apache-2.0"
] | null | null | null | src/pruefungsvorbereitung/VCE2014ExamCQuestion196.java | hemmerling/java-114014 | cd34f49cb4eacf52f52713f710239132f5bd8f03 | [
"Apache-2.0"
] | null | null | null | 24.882353 | 71 | 0.713948 | 11,160 | package pruefungsvorbereitung;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class VCE2014ExamCQuestion196 {
public static void main(String[] args) {
Date date = new Date();
Locale locale = Locale.ITALY;
//df.setLocale(locale);
DateFormat df = DateFormat.getDateInstance(DateFormat.FULL, locale);
String s = df.format(date);
System.out.println(s);
}
}
|
3e1a3eba5d41a3c4ea39da63c24266c2742b4706 | 1,375 | java | Java | lab6/BookStoreEJB/ejbModule/com/motek/soa/jms/JMSNewBookTopicService.java | tomaboro/soa-agh-course | b39cadf2a8b0e76fd3b6fcac4836b0a2b1e5ff01 | [
"MIT"
] | null | null | null | lab6/BookStoreEJB/ejbModule/com/motek/soa/jms/JMSNewBookTopicService.java | tomaboro/soa-agh-course | b39cadf2a8b0e76fd3b6fcac4836b0a2b1e5ff01 | [
"MIT"
] | null | null | null | lab6/BookStoreEJB/ejbModule/com/motek/soa/jms/JMSNewBookTopicService.java | tomaboro/soa-agh-course | b39cadf2a8b0e76fd3b6fcac4836b0a2b1e5ff01 | [
"MIT"
] | 1 | 2019-03-31T07:10:55.000Z | 2019-03-31T07:10:55.000Z | 29.891304 | 81 | 0.771636 | 11,161 | package com.motek.soa.jms;
import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.QueueConnectionFactory;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.jms.Session;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class JMSNewBookTopicService implements JMSService {
private InitialContext context;
private TopicConnectionFactory factory;
private Topic topic;
private TopicConnection connection;
private TopicSession session;
private TopicPublisher publisher;
public void init() throws JMSException, NamingException {
context = new InitialContext();
factory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
connection = factory.createTopicConnection("iza","obidowa1721");
session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
topic =(Topic)context.lookup("jms/topic/newBookTopic");
connection.start();
publisher = session.createPublisher(topic);
}
public void sendMessage(String msg) throws JMSException {
Message m = session.createTextMessage(msg);
publisher.send(m);
}
public void close() throws JMSException {
connection.close();
}
}
|
3e1a3efc0c807163757eb1bb8a6363278b96c6f6 | 1,685 | java | Java | jpimps-plugins/src/main/java/com/github/dkessel/jpimps/plugins/worktracker/WorkTrackerPlugin.java | dkessel/jpimps | 616e01d7e7b93eb25c4bd6e3e5296ee6fb08a60c | [
"MIT"
] | null | null | null | jpimps-plugins/src/main/java/com/github/dkessel/jpimps/plugins/worktracker/WorkTrackerPlugin.java | dkessel/jpimps | 616e01d7e7b93eb25c4bd6e3e5296ee6fb08a60c | [
"MIT"
] | null | null | null | jpimps-plugins/src/main/java/com/github/dkessel/jpimps/plugins/worktracker/WorkTrackerPlugin.java | dkessel/jpimps | 616e01d7e7b93eb25c4bd6e3e5296ee6fb08a60c | [
"MIT"
] | null | null | null | 24.071429 | 88 | 0.708605 | 11,162 | package com.github.dkessel.jpimps.plugins.worktracker;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import com.github.dkessel.jpimps.api.app.*;
import com.github.dkessel.jpimps.api.app.log.*;
import com.github.dkessel.jpimps.api.plugin.*;
import com.github.dkessel.jpimps.api.ui.*;
public class WorkTrackerPlugin implements PluginInterface {
private static final String CAT = "WorkTrackerPlugin";
private final JPimpsApplicationInterface app;
private final Logger logger;
private WorkingDay wd;
private Thread t;
private final File pluginDir;
public WorkTrackerPlugin(final JPimpsApplicationInterface app) {
this.app = app;
this.logger = app.getLogger(CAT);
this.pluginDir = this.app.getPluginContainer()
.getWorkDirectoryForPlugin(this.getClass());
}
@Override
public Map<String, ActionListener> getAvailableActions() {
final HashMap<String, ActionListener> hashMap = new HashMap<String, ActionListener>();
final ActionListener showTimeAction = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
app.ui().displayMessage(
"WorkTracker",
wd.toString() + "\nTSV: "
+ wd.toTSV().replace("\t", "; "),
ToolBoxUserInterface.INFO);
}
};
hashMap.put("Show Work Time", showTimeAction);
return hashMap;
}
@Override
public String getUIName() {
return "WorkTracker";
}
@Override
public void shutdown() {
if ((t != null) && t.isAlive()) {
t.interrupt();
}
}
@Override
public void startUp() {
logger.info("starting...");
wd = new WorkingDay();
t = new Thread(new WorkTrackerRunnable(app, wd, pluginDir),
"WorkTracker");
t.start();
}
}
|
3e1a3f09cdf0d6cfd53d2f1d622c60c5e0f4f109 | 2,038 | java | Java | sona-common/src/main/java/com/jiuye/sona/design/status/activity/State.java | huxinjian/sona | 6d987ce0a10becb6ae3c84df6783bcd009c694bf | [
"Apache-2.0"
] | 6 | 2020-07-15T03:23:24.000Z | 2020-07-15T05:36:23.000Z | sona-common/src/main/java/com/jiuye/sona/design/status/activity/State.java | huxinjian/sona | 6d987ce0a10becb6ae3c84df6783bcd009c694bf | [
"Apache-2.0"
] | null | null | null | sona-common/src/main/java/com/jiuye/sona/design/status/activity/State.java | huxinjian/sona | 6d987ce0a10becb6ae3c84df6783bcd009c694bf | [
"Apache-2.0"
] | null | null | null | 21.28125 | 61 | 0.571219 | 11,163 | package com.jiuye.sona.design.status.activity;
import com.jiuye.sona.design.status.Result;
import com.jiuye.sona.design.status.Status;
/**
* @Author: xinjian.hu
* @Date: 2020/10/12 15:49
* @Email: anpch@example.com
*/
public abstract class State {
/**
* 活动提审
*
* @param activityId
* @param currentStatus
* @return
*/
public Result arraignment(String activityId, Enum<Status>
currentStatus){
return new Result("0001", "待审核状态不可᯿复提审");
}
/**
* 审核通过
*
* @param activityId 活动ID
* @param currentStatus 当前状态
* @return 执⾏结果
*/
public Result checkPass(String activityId, Enum<Status>
currentStatus){
return new Result("0001", "编辑中不可审核通过");
}
/**
* 审核拒绝
*
* @param activityId 活动ID
* @param currentStatus 当前状态
* @return 执⾏结果
*/
public Result checkRefuse(String activityId, Enum<Status>
currentStatus){
return new Result("0001", "编辑中不可审核拒绝");
}
/**
* 撤审撤销
*
* @param activityId 活动ID
* @param currentStatus 当前状态
* @return 执⾏结果
*/
public Result checkRevoke(String activityId, Enum<Status>
currentStatus) {
return new Result("0001", "编辑中不可撤销审核");
}
/**
* 活动关闭
*
* @param activityId 活动ID
* @param currentStatus 当前状态
* @return 执⾏结果
*/
public Result close(String activityId, Enum<Status>
currentStatus) {
return new Result("0000", "活动关闭成功");
}
/**
* 活动开启
*
* @param activityId 活动ID
* @param currentStatus 当前状态
* @return 执⾏结果
*/
public Result open(String activityId, Enum<Status>
currentStatus){
return new Result("0001", "⾮关闭活动不可开启");
}
/**
* 活动执⾏
*
* @param activityId 活动ID
* @param currentStatus 当前状态
* @return 执⾏结果
*/
public Result doing(String activityId, Enum<Status>
currentStatus){
return new Result("0001", "编辑中活动不可执⾏活动中变更");
}
}
|
3e1a3f2ecdf9a4ae94e11c0316f5b512507b9fe4 | 1,485 | java | Java | tooling/conga-aem-maven-plugin/src/main/java/io/wcm/devops/conga/plugins/aem/maven/model/ContentPackageFile.java | wcm-io-devops/conga-aem-plugin | 348f9e5a04ec324743c5bd0f04d5ebbb25cc0d28 | [
"Apache-2.0"
] | 2 | 2015-11-30T13:37:44.000Z | 2018-05-04T12:26:44.000Z | tooling/conga-aem-maven-plugin/src/main/java/io/wcm/devops/conga/plugins/aem/maven/model/ContentPackageFile.java | wcm-io-devops/conga-aem-plugin | 348f9e5a04ec324743c5bd0f04d5ebbb25cc0d28 | [
"Apache-2.0"
] | 5 | 2018-03-13T13:09:13.000Z | 2021-08-02T17:27:54.000Z | tooling/conga-aem-maven-plugin/src/main/java/io/wcm/devops/conga/plugins/aem/maven/model/ContentPackageFile.java | wcm-io-devops/conga-aem-plugin | 348f9e5a04ec324743c5bd0f04d5ebbb25cc0d28 | [
"Apache-2.0"
] | 3 | 2018-04-18T12:05:24.000Z | 2021-01-28T10:58:03.000Z | 21.521739 | 75 | 0.66734 | 11,164 | /*
* #%L
* wcm.io
* %%
* Copyright (C) 2021 wcm.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.
* #L%
*/
package io.wcm.devops.conga.plugins.aem.maven.model;
import java.io.File;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
/**
* Generic representation of content package file.
*/
public interface ContentPackageFile {
/**
* @return Content package file.
*/
File getFile();
/**
* @return Package name
*/
String getName();
/**
* @return Package group
*/
String getGroup();
/**
* @return Package version
*/
String getVersion();
/**
* @return Package type
*/
String getPackageType();
/**
* @return Variants/Run modes for content package
*/
List<String> getVariants();
default String getPackageInfo() {
return StringUtils.defaultString(getGroup())
+ ":" + StringUtils.defaultString(getName())
+ ":" + StringUtils.defaultString(getVersion());
}
}
|
3e1a3f3af1b7493ed424b97701c0965131a012e0 | 7,348 | java | Java | cat-home/src/main/java/com/dianping/cat/report/page/event/service/EventReportService.java | 597730326/cat-backup | c0a8067b9dc2e49830815e7b86306917a7e92c45 | [
"Apache-2.0"
] | 120 | 2015-12-20T02:56:36.000Z | 2022-01-26T07:18:02.000Z | cat-home/src/main/java/com/dianping/cat/report/page/event/service/EventReportService.java | 597730326/cat-backup | c0a8067b9dc2e49830815e7b86306917a7e92c45 | [
"Apache-2.0"
] | 42 | 2019-12-08T18:41:13.000Z | 2021-08-28T13:08:55.000Z | cat-home/src/main/java/com/dianping/cat/report/page/event/service/EventReportService.java | 597730326/cat-backup | c0a8067b9dc2e49830815e7b86306917a7e92c45 | [
"Apache-2.0"
] | 65 | 2015-12-20T08:09:43.000Z | 2021-04-02T09:56:50.000Z | 31.809524 | 113 | 0.751225 | 11,165 | package com.dianping.cat.report.page.event.service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.unidal.dal.jdbc.DalException;
import org.unidal.dal.jdbc.DalNotFoundException;
import com.dianping.cat.Cat;
import com.dianping.cat.consumer.event.EventAnalyzer;
import com.dianping.cat.consumer.event.EventReportMerger;
import com.dianping.cat.consumer.event.model.entity.EventName;
import com.dianping.cat.consumer.event.model.entity.EventReport;
import com.dianping.cat.consumer.event.model.entity.EventType;
import com.dianping.cat.consumer.event.model.transform.BaseVisitor;
import com.dianping.cat.consumer.event.model.transform.DefaultNativeParser;
import com.dianping.cat.core.dal.DailyReport;
import com.dianping.cat.core.dal.DailyReportEntity;
import com.dianping.cat.core.dal.HourlyReport;
import com.dianping.cat.core.dal.HourlyReportContent;
import com.dianping.cat.core.dal.HourlyReportContentEntity;
import com.dianping.cat.core.dal.HourlyReportEntity;
import com.dianping.cat.core.dal.MonthlyReport;
import com.dianping.cat.core.dal.MonthlyReportEntity;
import com.dianping.cat.core.dal.WeeklyReport;
import com.dianping.cat.core.dal.WeeklyReportEntity;
import com.dianping.cat.helper.TimeHelper;
import com.dianping.cat.core.dal.DailyReportContent;
import com.dianping.cat.core.dal.DailyReportContentEntity;
import com.dianping.cat.core.dal.MonthlyReportContent;
import com.dianping.cat.core.dal.MonthlyReportContentEntity;
import com.dianping.cat.core.dal.WeeklyReportContent;
import com.dianping.cat.core.dal.WeeklyReportContentEntity;
import com.dianping.cat.report.service.AbstractReportService;
public class EventReportService extends AbstractReportService<EventReport> {
private SimpleDateFormat m_sdf = new SimpleDateFormat("yyyy-MM-dd");
private EventReport convert(EventReport report) {
Date start = report.getStartTime();
Date end = report.getEndTime();
try {
if (start != null && end != null && end.before(m_sdf.parse("2015-01-05"))) {
TpsStatistics statistics = new TpsStatistics((end.getTime() - start.getTime()) / 1000.0);
report.accept(statistics);
}
} catch (Exception e) {
Cat.logError(e);
}
return report;
}
@Override
public EventReport makeReport(String domain, Date start, Date end) {
EventReport report = new EventReport(domain);
report.setStartTime(start);
report.setEndTime(end);
return report;
}
@Override
public EventReport queryDailyReport(String domain, Date start, Date end) {
EventReportMerger merger = new EventReportMerger(new EventReport(domain));
long startTime = start.getTime();
long endTime = end.getTime();
String name = EventAnalyzer.ID;
for (; startTime < endTime; startTime = startTime + TimeHelper.ONE_DAY) {
try {
DailyReport report = m_dailyReportDao.findByDomainNamePeriod(domain, name, new Date(startTime),
DailyReportEntity.READSET_FULL);
EventReport reportModel = queryFromDailyBinary(report.getId(), domain);
reportModel.accept(merger);
} catch (DalNotFoundException e) {
// ignore
} catch (Exception e) {
Cat.logError(e);
}
}
EventReport eventReport = merger.getEventReport();
eventReport.setStartTime(start);
eventReport.setEndTime(end);
return convert(eventReport);
}
private EventReport queryFromDailyBinary(int id, String domain) throws DalException {
DailyReportContent content = m_dailyReportContentDao.findByPK(id, DailyReportContentEntity.READSET_FULL);
if (content != null) {
return DefaultNativeParser.parse(content.getContent());
} else {
return new EventReport(domain);
}
}
private EventReport queryFromHourlyBinary(int id, String domain) throws DalException {
HourlyReportContent content = m_hourlyReportContentDao.findByPK(id, HourlyReportContentEntity.READSET_FULL);
if (content != null) {
return DefaultNativeParser.parse(content.getContent());
} else {
return new EventReport(domain);
}
}
private EventReport queryFromMonthlyBinary(int id, String domain) throws DalException {
MonthlyReportContent content = m_monthlyReportContentDao.findByPK(id, MonthlyReportContentEntity.READSET_FULL);
if (content != null) {
return DefaultNativeParser.parse(content.getContent());
} else {
return new EventReport(domain);
}
}
private EventReport queryFromWeeklyBinary(int id, String domain) throws DalException {
WeeklyReportContent content = m_weeklyReportContentDao.findByPK(id, WeeklyReportContentEntity.READSET_FULL);
if (content != null) {
return DefaultNativeParser.parse(content.getContent());
} else {
return new EventReport(domain);
}
}
@Override
public EventReport queryHourlyReport(String domain, Date start, Date end) {
EventReportMerger merger = new EventReportMerger(new EventReport(domain));
long startTime = start.getTime();
long endTime = end.getTime();
String name = EventAnalyzer.ID;
for (; startTime < endTime; startTime = startTime + TimeHelper.ONE_HOUR) {
List<HourlyReport> reports = null;
try {
reports = m_hourlyReportDao.findAllByDomainNamePeriod(new Date(startTime), domain, name,
HourlyReportEntity.READSET_FULL);
} catch (DalException e) {
Cat.logError(e);
}
if (reports != null) {
for (HourlyReport report : reports) {
try {
EventReport reportModel = queryFromHourlyBinary(report.getId(), domain);
reportModel.accept(merger);
} catch (DalNotFoundException e) {
// ignore
} catch (Exception e) {
Cat.logError(e);
}
}
}
}
EventReport eventReport = merger.getEventReport();
eventReport.setStartTime(start);
eventReport.setEndTime(new Date(end.getTime() - 1));
Set<String> domains = queryAllDomainNames(start, end, EventAnalyzer.ID);
eventReport.getDomainNames().addAll(domains);
return convert(eventReport);
}
@Override
public EventReport queryMonthlyReport(String domain, Date start) {
EventReport eventReport = new EventReport(domain);
try {
MonthlyReport entity = m_monthlyReportDao.findReportByDomainNamePeriod(start, domain, EventAnalyzer.ID,
MonthlyReportEntity.READSET_FULL);
eventReport = queryFromMonthlyBinary(entity.getId(), domain);
} catch (DalNotFoundException e) {
// ignore
} catch (Exception e) {
Cat.logError(e);
}
return convert(eventReport);
}
@Override
public EventReport queryWeeklyReport(String domain, Date start) {
EventReport eventReport = new EventReport(domain);
try {
WeeklyReport entity = m_weeklyReportDao.findReportByDomainNamePeriod(start, domain, EventAnalyzer.ID,
WeeklyReportEntity.READSET_FULL);
eventReport = queryFromWeeklyBinary(entity.getId(), domain);
} catch (DalNotFoundException e) {
// ignore
} catch (Exception e) {
Cat.logError(e);
}
return convert(eventReport);
}
public class TpsStatistics extends BaseVisitor {
public double m_duration;
public TpsStatistics(double duration) {
m_duration = duration;
}
@Override
public void visitName(EventName name) {
if (m_duration > 0) {
name.setTps(name.getTotalCount() * 1.0 / m_duration);
}
}
@Override
public void visitType(EventType type) {
if (m_duration > 0) {
type.setTps(type.getTotalCount() * 1.0 / m_duration);
super.visitType(type);
}
}
}
}
|
3e1a3f8160b0fa30b2c2f89c7042ba6a87453a29 | 898 | java | Java | engine-api/src/test/java/net/cpollet/scheduler/engine/api/JobIdTest.java | cpollet/scheduler | 867ffbcbd5c52e2c46c3bc6809094630f00b96a5 | [
"Apache-2.0"
] | null | null | null | engine-api/src/test/java/net/cpollet/scheduler/engine/api/JobIdTest.java | cpollet/scheduler | 867ffbcbd5c52e2c46c3bc6809094630f00b96a5 | [
"Apache-2.0"
] | null | null | null | engine-api/src/test/java/net/cpollet/scheduler/engine/api/JobIdTest.java | cpollet/scheduler | 867ffbcbd5c52e2c46c3bc6809094630f00b96a5 | [
"Apache-2.0"
] | null | null | null | 25.657143 | 81 | 0.61804 | 11,166 | package net.cpollet.scheduler.engine.api;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
class JobIdTest {
@Test
void new_areEqual_whenUsingSameIds() {
// GIVEN
JobId existingJobId = new JobId();
// WHEN
JobId newJobId1 = new JobId(existingJobId.toString());
JobId newJobId2 = new JobId(existingJobId.toString());
// THEN
Assertions.assertThat(newJobId1)
.isEqualTo(newJobId2);
}
@Test
void new_throwsException_whenIdIsInvalidId() {
// GIVEN
String invalidId="invalid";
// WHEN
Throwable thrown = Assertions.catchThrowable(() -> new JobId(invalidId));
// THEN
Assertions.assertThat(thrown)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("[invalid] is not a valid JobId");
}
}
|
3e1a4041b37d0eaabef28773d24ff8a69331a10c | 29,668 | java | Java | log4jdbc-log4j2-jdbc3/src/test/java/net/sf/log4jdbc/log/CheckLoggingFunctionalites.java | metastable/log4jdbc-log4j2 | e73603a0533335c2adcd55757e504cf655f39153 | [
"Apache-2.0"
] | 47 | 2016-07-19T06:07:41.000Z | 2022-02-07T02:31:16.000Z | log4jdbc-log4j2-jdbc3/src/test/java/net/sf/log4jdbc/log/CheckLoggingFunctionalites.java | metastable/log4jdbc-log4j2 | e73603a0533335c2adcd55757e504cf655f39153 | [
"Apache-2.0"
] | 14 | 2017-04-17T12:36:05.000Z | 2021-05-08T09:11:24.000Z | log4jdbc-log4j2-jdbc3/src/test/java/net/sf/log4jdbc/log/CheckLoggingFunctionalites.java | metastable/log4jdbc-log4j2 | e73603a0533335c2adcd55757e504cf655f39153 | [
"Apache-2.0"
] | 38 | 2016-05-19T14:52:27.000Z | 2021-12-15T08:30:53.000Z | 37.938619 | 109 | 0.652488 | 11,167 | package net.sf.log4jdbc.log;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.never;
import org.mockito.stubbing.Answer;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.DataSource;
import net.sf.log4jdbc.TestAncestor;
import net.sf.log4jdbc.log.log4j2.Log4j2SpyLogDelegator;
import net.sf.log4jdbc.sql.jdbcapi.ConnectionSpy;
import net.sf.log4jdbc.sql.jdbcapi.DataSourceSpy;
import net.sf.log4jdbc.sql.jdbcapi.MockDriverUtils;
import net.sf.log4jdbc.sql.resultsetcollector.ResultSetCollector;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
/**
* Class which tests all the logging actions of log4jdbc-log4j2 SpyDelegator implementation
* The logger output is written in the file /test.out where it is checked.
*
* This class is used to run the same tests for the log4j2 logger or the slf4j logger.
* It is used by {@link net.sf.log4jdbc.log.log4j2.TestLoggingFunctionalitesWithLog4j2} and
* {@link net.sf.log4jdbc.log.slf4j.TestLoggingFunctionalitesWithSl4j},
* and is not meant to be run on its own.
*
* @author Mathieu Seppey
* @version 1.0
* @see net.sf.log4jdbc.log.log4j2.TestLoggingFunctionalitesWithLog4j2
* @see net.sf.log4jdbc.log.slf4j.TestLoggingFunctionalitesWithSl4j
*/
public abstract class CheckLoggingFunctionalites extends TestAncestor
{
protected static SpyLogDelegator TestSpyLogDelegator ;
/**
* Default constructor.
*/
public CheckLoggingFunctionalites()
{
super();
}
/**
* Init properties common to tests for any logger. Extending classes should override
* this method with a tag {@code BeforeClass}, and call this parent method.
*/
public static void initProperties() {
System.setProperty("log4jdbc.suppress.generated.keys.exception", "true");
}
/**
* Reinit the properties common to tests for any logger. Extending classes should override
* this method with a tag {@code AfterClass}, and call this parent method.
*/
public static void reinitProperties() {
System.clearProperty("log4jdbc.suppress.generated.keys.exception");
}
/**
* A test which goes through the whole process => Connection, statement, ResultSet
* @throws SQLException
* @throws IOException
*/
@Test
public void testWithAConnection() throws SQLException, IOException
{
// Create all fake mock objects
MockDriverUtils mock = new MockDriverUtils();
PreparedStatement mockPrep = mock(PreparedStatement.class);
ResultSet mockResu = mock(ResultSet.class);
ResultSetMetaData mockRsmd = mock(ResultSetMetaData.class);
when(mock.getMockConnection().prepareStatement("SELECT * FROM Test"))
.thenReturn(mockPrep);
when(mockPrep.executeQuery()).thenReturn(mockResu);
when(mockRsmd.getColumnCount()).thenReturn(1);
when(mockRsmd.getColumnName(1)).thenReturn("column 1");
when(mockRsmd.getColumnLabel(1)).thenReturn("column 1 renamed");
when(mockRsmd.getTableName(1)).thenReturn("mytable");
when(mockResu.getMetaData()).thenReturn(mockRsmd);
when(mockResu.next()).thenReturn(true);
when(mockResu.getString(1)).thenReturn("Ok");
// Instantiation and use of the most important classes with a log check.
String outputValue = "";
emptyLogFile();
Connection conn = DriverManager.getConnection("jdbc:log4" + MockDriverUtils.MOCKURL);
outputValue = CheckLoggingFunctionalites.readLogFile(-1);
assertTrue("The log produced by the instanciation of a ConnectionSpy is not as expected",
outputValue.contains("Connection opened")
&& outputValue.contains("Connection.new Connection returned"));
emptyLogFile();
//verify that the underlying connection has been opened
verify(mock.getMockDriver()).connect(eq(MockDriverUtils.MOCKURL),
any(java.util.Properties.class));
PreparedStatement ps = conn.prepareStatement("SELECT * FROM Test");
outputValue = CheckLoggingFunctionalites.readLogFile(-1);
assertTrue("The log produced by the instanciation of a PreparedStatementSpy is not as expected",
outputValue.contains("PreparedStatement.new PreparedStatement returned"));
emptyLogFile();
//verify the the underlying connection returned a prepared statement
verify(mock.getMockConnection()).prepareStatement(eq("SELECT * FROM Test"));
ResultSet resu = ps.executeQuery();
outputValue = CheckLoggingFunctionalites.readLogFile(-1);
assertTrue("The log produced by PreparedStatement executeQuery() is not as expected",
outputValue.contains("ResultSet.new ResultSet returned")
&& outputValue.contains("PreparedStatement.executeQuery() returned"));
//verify that the underlying prepared statement has been called
verify(mockPrep).executeQuery();
resu.next();
assertTrue("Wrong result returned by the getString() method of ResultSetSpy",
resu.getString(1) == "Ok");
//verify that the underlying resultset has been called
verify(mockResu).next();
resu.close();
ps.close();
verify(mockPrep).close();
conn.close();
verify(mock.getMockConnection()).close();
// clean all mock objects
mock.deregister();
}
/**
* Unit test related to
* {@link http://code.google.com/p/log4jdbc-log4j2/issues/detail?id=4 issue 4}.
*/
@Test
public void testCloseResultSetWithoutNext() throws SQLException
{
// Create all fake mock objects
MockDriverUtils mock = new MockDriverUtils();
PreparedStatement mockPrep = mock(PreparedStatement.class);
ResultSet mockResu = mock(ResultSet.class);
when(mock.getMockConnection().prepareStatement("SELECT * FROM Test"))
.thenReturn(mockPrep);
when(mockPrep.executeQuery()).thenReturn(mockResu);
when(mockResu.getMetaData()).thenAnswer(new Answer<ResultSetMetaData>() {
public ResultSetMetaData answer(InvocationOnMock invocation) {
try {
//if the resultset was already closed, an exception should be thrown
//when calling this method (JDBC specifications)
verify((ResultSet) invocation.getMock(), never()).close();
ResultSetMetaData mockRsmd = mock(ResultSetMetaData.class);
when(mockRsmd.getColumnCount()).thenReturn(1);
when(mockRsmd.getColumnName(1)).thenReturn("column 1");
when(mockRsmd.getColumnLabel(1)).thenReturn("column 1 renamed");
when(mockRsmd.getTableName(1)).thenReturn("mytable");
return mockRsmd;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
});
Connection conn = DriverManager.getConnection("jdbc:log4" + MockDriverUtils.MOCKURL);
PreparedStatement ps = conn.prepareStatement("SELECT * FROM Test");
ResultSet resu = ps.executeQuery();
//the bug appeared when close() was called on the ResultSet
//without any prior calls to next(),
//because log4jdbc was calling getMetaData() on a closed ResultSet
resu.close();
// clean all mock objects
mock.deregister();
}
/**
* Test the behavior of a DataSourceSpy
* @throws SQLException
* @throws IOException
*/
@Test
public void testDataSourceSpy() throws SQLException, IOException
{
// Create all fake mock objects and returns
MockDriverUtils mock = new MockDriverUtils();
DataSource mockDataSource = mock(DataSource.class);
DatabaseMetaData mockDbmd = mock(DatabaseMetaData.class);
when(mockDataSource.getConnection()).thenReturn(mock.getMockConnection());
when(mock.getMockConnection().getMetaData()).thenReturn(mockDbmd);
// Test the instantiation of a DataSourceSpy and the retrieving of a connection
String outputValue = "";
emptyLogFile();
DataSourceSpy dss = new DataSourceSpy(mockDataSource);
dss.getConnection();
outputValue = CheckLoggingFunctionalites.readLogFile(-1);
assertTrue("The log produced when the DataSourceSpy returns a connection is not as expected",
outputValue.contains("Connection opened")
&& outputValue.contains("Connection.new Connection returned") &&
outputValue.contains("DataSource.getConnection() returned"));
// verify that the underlying connection has been returned by the underlying datasource
verify(mockDataSource).getConnection();
// clean all mock objects
mock.deregister();
}
/**
* Test the functionality of setting different custom <code>SpyLogFactory</code>s
* at the <code>DataSourceSpy</code> level.
* @throws SQLException
* @throws IOException
*/
@Test
public void testDataSourceSpyCustomLog() throws SQLException
{
// Create all fake mock objects and returns
MockDriverUtils mock = new MockDriverUtils();
DataSource mockDataSource = mock(DataSource.class);
DatabaseMetaData mockDbmd = mock(DatabaseMetaData.class);
when(mockDataSource.getConnection()).thenReturn(mock.getMockConnection());
when(mock.getMockConnection().getMetaData()).thenReturn(mockDbmd);
DataSourceSpy dss = new DataSourceSpy(mockDataSource);
//mock a custom SpyLogDelegator to check that it is actually used by the DataSource
//when set
SpyLogDelegator customLog1 = mock(SpyLogDelegator.class);
when(customLog1.isJdbcLoggingEnabled()).thenReturn(true);
dss.setSpyLogDelegator(customLog1);
//get a connection and check that the custom logger was used
Connection conn1 = dss.getConnection();
verify(customLog1).connectionOpened(eq((ConnectionSpy) conn1), anyLong());
//get a new custom logger, set it to the DataSource
SpyLogDelegator customLog2 = mock(SpyLogDelegator.class);
when(customLog2.isJdbcLoggingEnabled()).thenReturn(true);
dss.setSpyLogDelegator(customLog2);
//get a new connection, the new logger should be used
Connection conn2 = dss.getConnection();
verify(customLog2).connectionOpened(eq((ConnectionSpy) conn2), anyLong());
//the first logger should not have been used anymore
verify(customLog1, times(1)).connectionOpened(any(ConnectionSpy.class), anyLong());
//if we perform an operation on the first connection, the first logger should be used,
//not the second one
conn1.close();
verify(customLog1).connectionClosed(eq((ConnectionSpy) conn1), anyLong());
verify(customLog2, never()).connectionClosed(any(ConnectionSpy.class), anyLong());
// clean all mock objects
mock.deregister();
}
/**
* Test a <code>DataSourceSpy</code> returns a standard
* <code>java.sql.Connection</code> if JDBC logging is disable.
* @throws SQLException
* @throws IOException
*/
@Test
public void testDataSourceLoggingDisabled() throws SQLException
{
// Create all fake mock objects and returns
MockDriverUtils mock = new MockDriverUtils();
DataSource mockDataSource = mock(DataSource.class);
DatabaseMetaData mockDbmd = mock(DatabaseMetaData.class);
when(mockDataSource.getConnection()).thenReturn(mock.getMockConnection());
when(mock.getMockConnection().getMetaData()).thenReturn(mockDbmd);
DataSourceSpy dss = new DataSourceSpy(mockDataSource);
//mock a custom SpyLogDelegator with JDBC logging enabled
SpyLogDelegator customLog1 = mock(SpyLogDelegator.class);
when(customLog1.isJdbcLoggingEnabled()).thenReturn(true);
dss.setSpyLogDelegator(customLog1);
//The connection should be a ConnectionSpy
Connection conn1 = dss.getConnection();
if (!(conn1 instanceof ConnectionSpy)) {
throw new AssertionError("The DataSource did not returned a ConnectionSpy " +
"when it should have");
}
//then disable JDBC logging
when(customLog1.isJdbcLoggingEnabled()).thenReturn(false);
//The connection should be a ConnectionSpy
Connection conn2 = dss.getConnection();
if (conn2 instanceof ConnectionSpy) {
throw new AssertionError("The DataSource returned a ConnectionSpy " +
"when it should not have");
}
// clean all mock objects
mock.deregister();
}
/**
* Unit test for the method isJdbcLoggingEnabled
*/
@Test
public void checkIsJdbcLoggingEnabled()
{
assertTrue("isJdbcLoggingEnabled has to return true",
TestSpyLogDelegator.isJdbcLoggingEnabled());
}
/**
* Unit test for the method exceptionOccured
*
* @throws IOException
*/
@Test
public void checkExceptionOccured() throws IOException
{
// Creation of fake parameters
Exception e = new Exception("test");
// Create a fake connection using Mockito
MockDriverUtils mock = new MockDriverUtils();
ConnectionSpy cs = new ConnectionSpy(mock.getMockConnection(),
TestSpyLogDelegator);
// Run the method after ensuring the log file is empty
emptyLogFile();
TestSpyLogDelegator.exceptionOccured(cs, "test()",e,"SELECT * FROM Test", 1000L);
// Check the result
assertTrue("The logging level used by exceptionOccured is not ERRROR as expected",
CheckLoggingFunctionalites.readLogFile(1).contains(" ERROR "));
// Read the whole output file
String outputValue = CheckLoggingFunctionalites.readLogFile(-1);
assertTrue("Incorrect output written by exceptionOccured", outputValue.contains("SELECT * FROM Test")
&& outputValue.contains("FAILED after 1000"));
// clean all mock objects
mock.deregister();
}
/**
* Check that loggers respect the property
* {@code log4jdbc.suppress.generated.keys.exception}, that is set to {@code true}
* by the method {@code #initProperties()}.
*/
@Test
public void checkFilteredExceptionOccured() throws IOException {
// Creation of fake parameters
Exception e = new Exception("test");
// Create a fake connection using Mockito
MockDriverUtils mock = new MockDriverUtils();
ConnectionSpy cs = new ConnectionSpy(mock.getMockConnection(),
TestSpyLogDelegator);
// Run the method after ensuring the log file is empty
emptyLogFile();
TestSpyLogDelegator.exceptionOccured(cs,
SpyLogDelegator.GET_GENERATED_KEYS_METHOD_CALL, e, "SELECT * FROM Test", 1L);
// Check the result
assertFalse("The logger did not respect the property " +
"log4jdbc.suppress.generated.keys.exception",
CheckLoggingFunctionalites.readLogFile(1).contains(" ERROR "));
// clean all mock objects
mock.deregister();
}
/**
* Unit test for the method methodReturned
*
* @throws IOException
*/
@Test
public void checkMethodReturned() throws IOException
{
// Create a fake connection using Mockito
MockDriverUtils mock = new MockDriverUtils();
ConnectionSpy cs = new ConnectionSpy(mock.getMockConnection(),
TestSpyLogDelegator);
// Run the method after ensuring the log file is empty
emptyLogFile();
TestSpyLogDelegator.methodReturned(cs, "test()", "TestMessage");
// Check the result
// Note, slf4j and log4j2 don't log this method with same the level.
if(TestSpyLogDelegator.getClass().getName() == Log4j2SpyLogDelegator.class.getName())
// log4j2
assertTrue("The logging level used by methodReturned is not INFO as expected",
CheckLoggingFunctionalites.readLogFile(1).contains(" INFO "));
else
// slf4j
assertTrue("The logging level used by methodReturned is not DEBUG as expected",
CheckLoggingFunctionalites.readLogFile(1).contains(" DEBUG "));
// Read the whole output file
String outputValue = CheckLoggingFunctionalites.readLogFile(-1);
assertTrue("Incorrect output written by methodReturned",
outputValue.contains("Connection.test() returned TestMessage"));
// clean all mock objects
mock.deregister();
}
/**
* Unit test for the method sqlTimingOccurred
*
* @throws IOException
*/
@Test
public void checkSqlTimingOccurred() throws IOException
{
// Create a fake connection using Mockito
MockDriverUtils mock = new MockDriverUtils();
ConnectionSpy cs = new ConnectionSpy(mock.getMockConnection(),
TestSpyLogDelegator);
// Run the method after ensuring the log file is empty
emptyLogFile();
TestSpyLogDelegator.sqlTimingOccurred(cs,1000L,"test", "SELECT * FROM Test");
// Check the result
// Note, slf4j and log4j2 don't log this method with same the level.
if(TestSpyLogDelegator.getClass().getName() == Log4j2SpyLogDelegator.class.getName())
// log4j2
assertTrue("The logging level used by sqlTimingOccurred is not INFO as expected",
CheckLoggingFunctionalites.readLogFile(1).contains(" INFO "));
else
// slf4j
assertTrue("The logging level used by sqlTimingOccurred is not DEBUG as expected",
CheckLoggingFunctionalites.readLogFile(1).contains(" DEBUG "));
// Read the whole output file
String outputValue = CheckLoggingFunctionalites.readLogFile(-1);
assertTrue("Incorrect output written by sqlTimingOccurred",
outputValue.contains("SELECT * FROM Test")
&& outputValue.contains("{executed in 1000"));
// clean all mock objects
mock.deregister();
}
/**
* Unit test for the method connectionOpened
*
* @throws IOException
*/
@Test
public void checkConnectionOpened() throws IOException
{
// Create a fake connection using Mockito
MockDriverUtils mock = new MockDriverUtils();
ConnectionSpy cs = new ConnectionSpy(mock.getMockConnection(),
TestSpyLogDelegator);
// Run the method after ensuring the log file is empty
emptyLogFile();
TestSpyLogDelegator.connectionOpened(cs,1000L);
// Check the result
assertTrue("The logging level used by connectionOpened is not INFO as expected",
CheckLoggingFunctionalites.readLogFile(1).contains(" INFO "));
assertTrue("Incorrect output written by connectionOpenend",
CheckLoggingFunctionalites.readLogFile(-1).contains("Connection opened"));
// clean all mock objects
mock.deregister();
}
/**
* Unit test for the method connectionClosed
*
* @throws IOException
*/
@Test
public void checkConnectionClosed() throws IOException
{
// Create a fake connection using Mockito
MockDriverUtils mock = new MockDriverUtils();
ConnectionSpy cs = new ConnectionSpy(mock.getMockConnection(),
TestSpyLogDelegator);
// Run the method after ensuring the log file is empty
emptyLogFile();
TestSpyLogDelegator.connectionClosed(cs,1000L);
// Check the result
assertTrue("The logging level used by connectionClosed is not INFO as expected",
CheckLoggingFunctionalites.readLogFile(1).contains(" INFO "));
assertTrue("Incorrect output written by connectionClosed",
CheckLoggingFunctionalites.readLogFile(-1).contains("Connection closed"));
// clean all mock objects
mock.deregister();
}
/**
* Unit test for the method connectionAborted
*
* @throws IOException
*/
@Test
public void checkConnectionAborted() throws IOException
{
// Create a fake connection using Mockito
MockDriverUtils mock = new MockDriverUtils();
ConnectionSpy cs = new ConnectionSpy(mock.getMockConnection(),
TestSpyLogDelegator);
// Run the method after ensuring the log file is empty
emptyLogFile();
TestSpyLogDelegator.connectionAborted(cs,1000L);
// Check the result
assertTrue("The logging level used by connectionAborted is not INFO as expected",
CheckLoggingFunctionalites.readLogFile(1).contains(" INFO "));
assertTrue("Incorrect output written by connectionAborted",
CheckLoggingFunctionalites.readLogFile(-1).contains("Connection aborted"));
// clean all mock objects
mock.deregister();
}
/**
* Unit test for the method isJdbcLoggingEnabled
*/
@Test
public void checkIsResultSetCollectionEnabled()
{
assertTrue("isResultSetCollectionEnabled has to return true",
TestSpyLogDelegator.isJdbcLoggingEnabled());
}
/**
* Unit test for the method isResultSetCollectionEnabledWithUnreadValueFillIn
*/
@Test
public void checkIsResultSetCollectionEnabledWithUnreadValueFillIn()
{
assertTrue("isResultSetCollectionEnabledWithUnreadValueFillIn has to return true",
TestSpyLogDelegator.isResultSetCollectionEnabledWithUnreadValueFillIn());
}
/**
* Unit test for the method resultSetCollected
*
* @throws IOException
*/
@Test
public void checkResultSetCollected() throws IOException
{
// Creation of fake parameters
ResultSetCollector rsc = mock(ResultSetCollector.class);
List<Object> row1 = new ArrayList<Object>();
List<Object> row2 = new ArrayList<Object>();
List<List<Object>> rows = new ArrayList<List<Object>>();
row1.add("a");
row1.add("b");
row2.add("c");
row2.add("d");
rows.add(row1);
rows.add(row2);
when(rsc.getRows()).thenReturn(rows);
when(rsc.getColumnCount()).thenReturn(2);
when(rsc.getColumnName(1)).thenReturn("Colonne1");
when(rsc.getColumnName(2)).thenReturn("Colonne2");
// Run the method after ensuring the log file is empty
emptyLogFile();
TestSpyLogDelegator.resultSetCollected(rsc);
// Check the result
assertTrue("The logging level used by resultSetCollected is not INFO as expected",
CheckLoggingFunctionalites.readLogFile(1).contains(" INFO "));
// Read the whole output file
String outputValue = CheckLoggingFunctionalites.readLogFile(-1);
assertTrue("Incorrect column header written by resultSetCollected",
outputValue.contains("|Colonne1 |Colonne2 |"));
assertTrue("Incorrect 1st line written by resultSetCollected",
outputValue.contains("|a |b |"));
assertTrue("Incorrect 2nd line written by resultSetCollected",
outputValue.contains("|c |d |"));
}
/**
* In log4jdbc-log4j2, the behavior of the
* {@link net.sf.log4jdbc.sql.resultsetcollector.DefaultResultSetCollector
* DefaultResultSetCollector} has been changed so that results are collected
* also when <code>close</code> is called on a <code>ResultSet</code>
* (and not only when calling <code>next</code> on the <code>ResultSet</code> returns
* <code>false</code>, as in the log4jdbc-remix implementation).
* This leads to print the result set twice if <code>next</code> is called
* and returns <code>false</code>, followed by a call to <code>close</code>.
* This methods check that the problem has been fixed.
*/
@Test
public void checkResultSetCollectedOnlyOnce() throws SQLException, IOException
{
// Create all fake mock objects
MockDriverUtils mock = new MockDriverUtils();
PreparedStatement mockPrep = mock(PreparedStatement.class);
ResultSet mockResu = mock(ResultSet.class);
ResultSetMetaData mockRsmd = mock(ResultSetMetaData.class);
when(mock.getMockConnection().prepareStatement("SELECT * FROM Test"))
.thenReturn(mockPrep);
when(mockPrep.executeQuery()).thenReturn(mockResu);
when(mockRsmd.getColumnCount()).thenReturn(1);
when(mockRsmd.getColumnName(1)).thenReturn("column 1");
when(mockRsmd.getColumnLabel(1)).thenReturn("column 1 renamed");
when(mockRsmd.getTableName(1)).thenReturn("mytable");
when(mockResu.getString(1)).thenReturn("1: Ok");
when(mockResu.getMetaData()).thenReturn(mockRsmd);
Connection conn = DriverManager.getConnection("jdbc:log4" + MockDriverUtils.MOCKURL);
PreparedStatement ps = conn.prepareStatement("SELECT * FROM Test");
ResultSet resu = ps.executeQuery();
emptyLogFile();
when(mockResu.next()).thenReturn(true);
resu.next();
resu.getString(1);
when(mockResu.next()).thenReturn(false);
//here, the next should trigger the print
resu.next();
String outputValue = CheckLoggingFunctionalites.readLogFile(-1);
assertTrue("next() did not trigger the printing",
outputValue.contains("|column 1 |"));
//not close
resu.close();
outputValue = CheckLoggingFunctionalites.readLogFile(-1);
Pattern pattern = Pattern.compile("\\|column 1 \\|");
Matcher matcher = pattern.matcher(outputValue);
int count = 0;
while (matcher.find()) count++;
assertEquals("The ResultSet was printed more than once", 1, count);
emptyLogFile();
when(mockResu.next()).thenReturn(true);
//here, next should not trigger the printing
resu.next();
resu.getString(1);
outputValue = CheckLoggingFunctionalites.readLogFile(-1);
assertFalse("next() did trigger the printing",
outputValue.contains("|column 1 |"));
//close should have
resu.close();
outputValue = CheckLoggingFunctionalites.readLogFile(-1);
matcher = pattern.matcher(outputValue);
count = 0;
while (matcher.find()) count++;
assertEquals("The ResultSet was printed more than once, or was not printed",
1, count);
// clean all mock objects
mock.deregister();
}
/**
* Unit test for the method debug
*
* @throws IOException
*
*/
@Test
public void checkDebug() throws IOException {
// Run the method after ensuring the log file is empty
emptyLogFile();
TestSpyLogDelegator.debug("DEBUGMESSAGE");
// Check the result
assertTrue("The logging level used by debug is not DEBUG as expected",
CheckLoggingFunctionalites.readLogFile(1).contains(" DEBUG "));
assertTrue("Incorrect output line written by debug",
CheckLoggingFunctionalites.readLogFile(-1).contains("DEBUGMESSAGE"));
}
/**
* Read and return the required line from the file test.out
*
* @param int lineNumber : The number of the required line. -1 return the whole file
*/
private static String readLogFile(int lineNumber) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader(testOutputFile));
String ret = "" ;
if(lineNumber > 0){
for(int i=1;i<=lineNumber;i++)
ret = br.readLine();
}
else
try{
for(int i=1;i<=1000;i++)
ret = ret.concat(br.readLine());
} catch(NullPointerException npe){
// Means that the end of file is reached, do nothing
}
br.close();
return ret;
}
/**
* Clear the test output file
*/
private void emptyLogFile() throws IOException{
FileOutputStream logCleaner = new FileOutputStream(testOutputFile);
logCleaner.write(1);
logCleaner.close();
}
}
|
3e1a412b236fb6805e4abad8fe2158c84b239807 | 4,432 | java | Java | Perceptron/src/Perceptron.java | DeanMiles/basics-of-artifical-inteligence | c8d704befd523a9fcc70db7e539738e7af88cfdd | [
"MIT"
] | null | null | null | Perceptron/src/Perceptron.java | DeanMiles/basics-of-artifical-inteligence | c8d704befd523a9fcc70db7e539738e7af88cfdd | [
"MIT"
] | null | null | null | Perceptron/src/Perceptron.java | DeanMiles/basics-of-artifical-inteligence | c8d704befd523a9fcc70db7e539738e7af88cfdd | [
"MIT"
] | null | null | null | 34.356589 | 99 | 0.566561 | 11,168 | import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
//Alan Franas
public class Perceptron {
//"Ax + By + C = 0";
private static List<Point> listOfTrainingCoordinates = new ArrayList<Point>();
private static List<Point> listOfTestCoordinates = new ArrayList<Point>();
private static int MIN_RANGE = -10;
private static int MAX_RANGE = 10;
private static int NUMBER_OF_EPOCHS = 15;
private static int NUMBER_OF_TRAINING_POINTS = 40;
private static int NUMBER_OF_TEST_POINTS = 80;
private static double LEARNING_RATE = 0.2;
private static double CHANGE_LEARNING_RATE = 0.01;
public static int[] ATTRIBUTES;
public static double[] score;
public static double[] weight;
public static void main(String[] args) {
chooseArguments();
prepareCollection(listOfTrainingCoordinates, NUMBER_OF_TRAINING_POINTS);
prepareCollection(listOfTestCoordinates, NUMBER_OF_TEST_POINTS);
double localError = 0;
int output;
initWeights();
for (int i = 0; i < NUMBER_OF_EPOCHS; i++) {
if (LEARNING_RATE > CHANGE_LEARNING_RATE)
LEARNING_RATE -= CHANGE_LEARNING_RATE;
for (Point point : listOfTrainingCoordinates) {
output = calculateOutput(weight, point);
localError = (point.getIsBehind() ? 1 : 0) - output;
if (localError != 0) {
weight[0] += LEARNING_RATE * localError * point.getX();
weight[1] += LEARNING_RATE * localError * point.getY();
weight[2] += LEARNING_RATE * localError;
}
}
int counter = 0;
for (Point point : listOfTestCoordinates) {
output = calculateOutput(weight, point);
if (output == (point.getIsBehind() ? 1 : 0)) {
counter++;
}
}
score[i] = (counter * 100) / NUMBER_OF_TEST_POINTS;
System.out.println("Algorithm efficiency for the era " + i + " is: " + score[i] + "%");
}
System.out.println(weight[0] + " " + weight[1] + " " + weight[2]);
displayingPointsAfterTeaching();
}
/**
* displays Points after teaching
*/
private static void displayingPointsAfterTeaching(){
for (int i = 0; i < score.length; i++) {
System.out.print(score[i] + ' ');
if (i % 10 == 0)
System.out.println('\n');
}
}
/**
* prepares weights, inits arrays
*/
private static void initWeights() {
Random r = new Random();
weight = new double[3];
score = new double[NUMBER_OF_EPOCHS];
weight[0] = r.nextInt() % 2;
weight[1] = r.nextInt() % 2;
weight[2] = r.nextInt() % 2;
}
/**
* prepares collection with rand points
* @param list List to generate points
* @param length number of elements in List
*/
private static void prepareCollection(List<Point> list, int length) {
Random r = new Random();
while (list.size() < length) {
int randomValue = r.nextInt((MAX_RANGE - MIN_RANGE) + 1) + MIN_RANGE;
int randomValue2 = r.nextInt((MAX_RANGE - MIN_RANGE) + 1) + MIN_RANGE;
Point point = new Point(randomValue, randomValue2);
if (!list.contains(point)) {
list.add(point);
}
}
}
/**
* sets arguments linear function
*/
private static void chooseArguments() {
System.out.println("Podaj argumenty prostej \"Ax + By + C = 0\" w formacie [A,B,C]");
Scanner myObj = new Scanner(System.in); // Create a Scanner object
String[] arrOfStr = myObj.nextLine().split(",", 3);
ATTRIBUTES = new int[3];
for (int i = 0; i < arrOfStr.length; i++) {
ATTRIBUTES[i] = Integer.parseInt(arrOfStr[i]);
System.out.println(ATTRIBUTES[i]);
}
}
/**
* returns either 1 or 0 using function
*
* @param weights the array of weights
* @param p the x and y input value
* @return 1 or 0
*/
private static int calculateOutput(double weights[], Point p) {
double sum = p.getX() * weights[0] + p.getY() * weights[1] + weights[2];
return sum > 0 ? 1 : 0;
}
}
|
3e1a42933621964c2d4c034939fcf3a0cf50aadf | 1,793 | java | Java | pg-search/src/main/java/com/kodality/blaze/search/BlindexDropCommand.java | kodality/blaze | a5984a7bc14241a4bfae13bf49d2b5ad0ec96e75 | [
"Apache-2.0"
] | 1 | 2019-02-05T17:39:02.000Z | 2019-02-05T17:39:02.000Z | pg-search/src/main/java/com/kodality/blaze/search/BlindexDropCommand.java | kodality/blaze | a5984a7bc14241a4bfae13bf49d2b5ad0ec96e75 | [
"Apache-2.0"
] | 1 | 2020-09-10T13:19:22.000Z | 2020-09-10T13:19:22.000Z | pg-search/src/main/java/com/kodality/blaze/search/BlindexDropCommand.java | kodality/blaze | a5984a7bc14241a4bfae13bf49d2b5ad0ec96e75 | [
"Apache-2.0"
] | 1 | 2020-09-02T05:51:04.000Z | 2020-09-02T05:51:04.000Z | 36.591837 | 106 | 0.721695 | 11,169 | /* 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.kodality.blaze.search;
import com.kodality.blaze.search.dao.BlindexDao;
import com.kodality.blaze.search.model.Blindex;
import org.apache.commons.lang3.StringUtils;
import org.apache.karaf.shell.api.action.Action;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.postgresql.util.PSQLException;
import java.util.List;
@Command(scope = "blindex", name = "drop-all", description = "drop all search indexes")
@Service
public class BlindexDropCommand implements Action {
@Reference
private BlindexDao blindexDao;
@Override
public Object execute() throws Exception {
List<Blindex> indexes = blindexDao.load();
for (Blindex blin : indexes) {
String key = blin.getKey();
try {
System.out.println("dropping " + key);
blindexDao.dropIndex(StringUtils.substringBefore(key, "."), StringUtils.substringAfter(key, "."));
} catch (Exception e) {
String err = e.getCause() instanceof PSQLException ? e.getCause().getMessage() : e.getMessage();
System.err.println("failed " + key + ": " + err);
}
}
return null;
}
}
|
3e1a43506b13576539082d64e1392648d30edab0 | 1,642 | java | Java | src/main/java/com/simibubi/create/content/contraptions/fluids/actors/HosePulleyRenderer.java | ExoPlant/Create-Refabricated | e7ff94403e281ae645dd326a8b4370a3f9251365 | [
"MIT"
] | 15 | 2019-07-19T01:12:24.000Z | 2022-01-31T15:40:19.000Z | src/main/java/com/simibubi/create/content/contraptions/fluids/actors/HosePulleyRenderer.java | ExoPlant/Create-Refabricated | e7ff94403e281ae645dd326a8b4370a3f9251365 | [
"MIT"
] | 46 | 2019-07-19T08:02:09.000Z | 2019-11-08T17:55:12.000Z | src/main/java/com/simibubi/create/content/contraptions/fluids/actors/HosePulleyRenderer.java | ExoPlant/Create-Refabricated | e7ff94403e281ae645dd326a8b4370a3f9251365 | [
"MIT"
] | 10 | 2019-10-01T12:07:25.000Z | 2021-12-11T19:40:35.000Z | 30.981132 | 107 | 0.821559 | 11,170 | package com.simibubi.create.content.contraptions.fluids.actors;
import com.simibubi.create.AllBlockPartials;
import com.simibubi.create.content.contraptions.base.KineticTileEntity;
import com.simibubi.create.content.contraptions.components.structureMovement.pulley.AbstractPulleyRenderer;
import com.simibubi.create.foundation.render.PartialBufferer;
import com.simibubi.create.foundation.render.SuperByteBuffer;
import com.simibubi.create.foundation.render.backend.core.PartialModel;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
import net.minecraft.util.Direction.Axis;
public class HosePulleyRenderer extends AbstractPulleyRenderer {
public HosePulleyRenderer(TileEntityRendererDispatcher dispatcher) {
super(dispatcher, AllBlockPartials.HOSE_HALF, AllBlockPartials.HOSE_HALF_MAGNET);
}
@Override
protected Axis getShaftAxis(KineticTileEntity te) {
return te.getBlockState()
.get(HosePulleyBlock.HORIZONTAL_FACING)
.rotateY()
.getAxis();
}
@Override
protected PartialModel getCoil() {
return AllBlockPartials.HOSE_COIL;
}
@Override
protected SuperByteBuffer renderRope(KineticTileEntity te) {
return PartialBufferer.get(AllBlockPartials.HOSE, te.getBlockState());
}
@Override
protected SuperByteBuffer renderMagnet(KineticTileEntity te) {
return PartialBufferer.get(AllBlockPartials.HOSE_MAGNET, te.getBlockState());
}
@Override
protected float getOffset(KineticTileEntity te, float partialTicks) {
return ((HosePulleyTileEntity) te).getInterpolatedOffset(partialTicks);
}
@Override
protected boolean isRunning(KineticTileEntity te) {
return true;
}
}
|
3e1a440806c4c70f7032f46f32a2f946f2c2fc03 | 281 | java | Java | cloud-provider-payment8002/src/main/java/com/liuk/cloud/dao/PaymentDao.java | liukai830/cloud2020 | 5887ae46b67ce6bb8af269a0e86e90b1727a1236 | [
"Apache-2.0"
] | null | null | null | cloud-provider-payment8002/src/main/java/com/liuk/cloud/dao/PaymentDao.java | liukai830/cloud2020 | 5887ae46b67ce6bb8af269a0e86e90b1727a1236 | [
"Apache-2.0"
] | null | null | null | cloud-provider-payment8002/src/main/java/com/liuk/cloud/dao/PaymentDao.java | liukai830/cloud2020 | 5887ae46b67ce6bb8af269a0e86e90b1727a1236 | [
"Apache-2.0"
] | null | null | null | 21.615385 | 49 | 0.768683 | 11,171 | package com.liuk.cloud.dao;
import com.liuk.cloud.entity.Payment;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface PaymentDao {
int insert(Payment payment);
Payment getPaymentById(@Param("id") Long id);
}
|
3e1a44572948f0c36bbea5a837716536f23f0f00 | 370 | java | Java | src/test/java/com/exasol/adapter/dialects/rls/RowLevelSecurityLocalIT.java | exasol/row-level-security | 4f7c272a2cd43e2a92e14837768c6d10d0d5223f | [
"MIT"
] | 5 | 2019-12-15T11:55:52.000Z | 2022-01-30T13:42:27.000Z | src/test/java/com/exasol/adapter/dialects/rls/RowLevelSecurityLocalIT.java | exasol/row-level-security | 4f7c272a2cd43e2a92e14837768c6d10d0d5223f | [
"MIT"
] | 109 | 2019-07-29T08:25:52.000Z | 2022-02-18T08:41:36.000Z | src/test/java/com/exasol/adapter/dialects/rls/RowLevelSecurityLocalIT.java | exasol/row-level-security | 4f7c272a2cd43e2a92e14837768c6d10d0d5223f | [
"MIT"
] | 3 | 2019-06-11T13:23:28.000Z | 2020-09-09T12:48:51.000Z | 24.666667 | 82 | 0.743243 | 11,172 | package com.exasol.adapter.dialects.rls;
import java.util.Map;
import org.junit.jupiter.api.Tag;
@Tag("integration")
@Tag("virtual-schema")
@Tag("slow")
class RowLevelSecurityLocalIT extends AbstractRowLevelSecurityIT {
@Override
protected Map<String, String> getConnectionSpecificVirtualSchemaProperties() {
return Map.of("IS_LOCAL", "true");
}
} |
3e1a44ef96fa85d5058d64d63ec16e8dc5e5cb0f | 1,389 | java | Java | Mage.Sets/src/mage/cards/s/SilverchaseFox.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,444 | 2015-01-02T00:25:38.000Z | 2022-03-31T13:57:18.000Z | Mage.Sets/src/mage/cards/s/SilverchaseFox.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 6,180 | 2015-01-02T19:10:09.000Z | 2022-03-31T21:10:44.000Z | Mage.Sets/src/mage/cards/s/SilverchaseFox.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,001 | 2015-01-01T01:15:20.000Z | 2022-03-30T20:23:04.000Z | 30.195652 | 125 | 0.729302 | 11,173 |
package mage.cards.s;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.common.SacrificeSourceCost;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.ExileTargetEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Zone;
import mage.target.common.TargetEnchantmentPermanent;
/**
* @author nantuko
*/
public final class SilverchaseFox extends CardImpl {
public SilverchaseFox(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{W}");
this.subtype.add(SubType.FOX);
this.power = new MageInt(2);
this.toughness = new MageInt(2);
// {1}{W}, Sacrifice Silverchase Fox: Exile target enchantment.
Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new ExileTargetEffect(), new ManaCostsImpl("{1}{W}"));
ability.addTarget(new TargetEnchantmentPermanent());
ability.addCost(new SacrificeSourceCost());
this.addAbility(ability);
}
private SilverchaseFox(final SilverchaseFox card) {
super(card);
}
@Override
public SilverchaseFox copy() {
return new SilverchaseFox(this);
}
}
|
3e1a45133f7ca0b5277b729a391ed25fc4ee054e | 1,986 | java | Java | java-maven/core/jena/src/main/java/org/nlp2rdf/core/NIFNamespaces.java | Julio-Noe/software | 5082a2e7d7e44302aee0ef61b646e0c34630db31 | [
"Apache-2.0"
] | 16 | 2015-02-02T04:48:14.000Z | 2022-02-01T11:33:34.000Z | java-maven/core/jena/src/main/java/org/nlp2rdf/core/NIFNamespaces.java | Julio-Noe/software | 5082a2e7d7e44302aee0ef61b646e0c34630db31 | [
"Apache-2.0"
] | 13 | 2015-06-03T22:34:12.000Z | 2020-05-28T19:16:43.000Z | java-maven/core/jena/src/main/java/org/nlp2rdf/core/NIFNamespaces.java | Julio-Noe/software | 5082a2e7d7e44302aee0ef61b646e0c34630db31 | [
"Apache-2.0"
] | 11 | 2015-02-02T04:49:53.000Z | 2020-10-13T19:25:06.000Z | 45.136364 | 95 | 0.490433 | 11,174 | /******************************************************************************/
/* Copyright (C) 2010-2011, Sebastian Hellmann */
/* */
/* 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.nlp2rdf.core;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.Model;
/**
* @author kurzum
*/
public class NIFNamespaces {
public static final String BASE = "http://persistence.uni-leipzig.org/nlp2rdf/ontologies/";
public static final String NIF = BASE + "nif-core#";
public static final String RLOG = BASE + "rlog#";
public static final String LExO = BASE + "vm/lexo#";
public static void addNifPrefix(Model model) {
model.setNsPrefix("nif", NIF);
}
public static void addRLOGPrefix(Model model) {
model.setNsPrefix("rlog", RLOG);
}
public static void addLExOPrefix(Model model) {
model.setNsPrefix("lexo", LExO);
}
}
|
3e1a45e698f0ddbf89a67f0ed954345aff2e481a | 509 | java | Java | mobile_app1/module606/src/main/java/module606packageJava0/Foo35.java | HiWong/android-build-eval | d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6 | [
"Apache-2.0"
] | 70 | 2021-01-22T16:48:06.000Z | 2022-02-16T10:37:33.000Z | mobile_app1/module606/src/main/java/module606packageJava0/Foo35.java | HiWong/android-build-eval | d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6 | [
"Apache-2.0"
] | 16 | 2021-01-22T20:52:52.000Z | 2021-08-09T17:51:24.000Z | mobile_app1/module606/src/main/java/module606packageJava0/Foo35.java | HiWong/android-build-eval | d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6 | [
"Apache-2.0"
] | 5 | 2021-01-26T13:53:49.000Z | 2021-08-11T20:10:57.000Z | 11.065217 | 45 | 0.546169 | 11,175 | package module606packageJava0;
import java.lang.Integer;
public class Foo35 {
Integer int0;
Integer int1;
public void foo0() {
new module606packageJava0.Foo34().foo8();
}
public void foo1() {
foo0();
}
public void foo2() {
foo1();
}
public void foo3() {
foo2();
}
public void foo4() {
foo3();
}
public void foo5() {
foo4();
}
public void foo6() {
foo5();
}
public void foo7() {
foo6();
}
public void foo8() {
foo7();
}
}
|
3e1a4774d07f8fc98432db61359ecaac850d3e2b | 2,418 | java | Java | apps/vtn/vtnrsc/src/main/java/org/onosproject/vtnrsc/DefaultAllocationPool.java | tiagullo/ONOS | ed5b14d71d76ae5cbbba85eb9459eba93dcf4e51 | [
"Apache-2.0"
] | 13 | 2017-08-04T02:16:10.000Z | 2019-11-27T16:18:50.000Z | apps/vtn/vtnrsc/src/main/java/org/onosproject/vtnrsc/DefaultAllocationPool.java | makersm/onos1.8 | 83525d166b1b8bfe2b4e9e4105296cd877cea289 | [
"Apache-2.0"
] | 15 | 2019-07-17T03:05:44.000Z | 2021-12-09T20:31:59.000Z | apps/vtn/vtnrsc/src/main/java/org/onosproject/vtnrsc/DefaultAllocationPool.java | makersm/onos1.8 | 83525d166b1b8bfe2b4e9e4105296cd877cea289 | [
"Apache-2.0"
] | 9 | 2018-06-27T09:22:36.000Z | 2021-06-29T12:06:24.000Z | 29.487805 | 80 | 0.672043 | 11,176 | /*
* Copyright 2015-present Open Networking Laboratory
*
* 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.onosproject.vtnrsc;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Objects;
import org.onlab.packet.IpAddress;
/**
* The continuous IP address range between the start address and the end address
* for the allocation pools.
*/
public final class DefaultAllocationPool implements AllocationPool {
private final IpAddress startIp;
private final IpAddress endIp;
/**
* Creates an AllocationPool by using the start IP address and the end IP
* address.
*
* @param startIp the start IP address of the allocation pool
* @param endIp the end IP address of the allocation pool
*/
public DefaultAllocationPool(IpAddress startIp, IpAddress endIp) {
checkNotNull(startIp, "StartIp cannot be null");
checkNotNull(endIp, "EndIp cannot be null");
this.startIp = startIp;
this.endIp = endIp;
}
@Override
public IpAddress startIp() {
return startIp;
}
@Override
public IpAddress endIp() {
return endIp;
}
@Override
public int hashCode() {
return Objects.hash(startIp, endIp);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof DefaultAllocationPool) {
final DefaultAllocationPool other = (DefaultAllocationPool) obj;
return Objects.equals(this.startIp, other.startIp)
&& Objects.equals(this.endIp, other.endIp);
}
return false;
}
@Override
public String toString() {
return toStringHelper(this).add("startIp", startIp).add("endIp", endIp)
.toString();
}
}
|
3e1a47aa58e965c0bcb64527d9763619802a0437 | 2,150 | java | Java | app/src/main/java/com/FornaxElit/MaturaBel/Adapter.java | nikssan123/maturiAppFornaxElit | 1830831d44477b6072e60c243ccf7ad66e4e4b89 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/FornaxElit/MaturaBel/Adapter.java | nikssan123/maturiAppFornaxElit | 1830831d44477b6072e60c243ccf7ad66e4e4b89 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/FornaxElit/MaturaBel/Adapter.java | nikssan123/maturiAppFornaxElit | 1830831d44477b6072e60c243ccf7ad66e4e4b89 | [
"Apache-2.0"
] | null | null | null | 28.666667 | 85 | 0.696279 | 11,177 | package com.FornaxElit.MaturaBel;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.myViewHolder> {
Context myContext;
List<itemForRv> myList;
int testCheck = 3;
public Adapter(Context myContext, List<itemForRv> myList, int testCheck) {
this.myContext = myContext;
this.myList = myList;
this.testCheck = testCheck;
}
@NonNull
@Override
public myViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(myContext);
View v = layoutInflater.inflate(R.layout.card_item, parent, false);
return new myViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull myViewHolder holder, int position) {
holder.authorImage.setImageResource(myList.get(position).getAuthorImage());
//holder.background.setImageResource(myList.get(position).getBackground());
holder.authorName.setText(myList.get(position).getAuthorName());
holder.button.setTag(myList.get(position).getAuthorName());
if(testCheck < 2) {
holder.button.setText("Тест");
}
}
@Override
public int getItemCount() {
return myList.size();
}
public class myViewHolder extends RecyclerView.ViewHolder{
ImageView authorImage;//, background;
TextView authorName;
Button button;
public myViewHolder(@NonNull View itemView) {
super(itemView);
authorImage = itemView.findViewById(R.id.imageViewAuthorImageForHisWork);
//background = itemView.findViewById(R.id.imageViewBackground);
authorName = itemView.findViewById(R.id.textViewAuthor);
button = itemView.findViewById(R.id.btnViewContent);
}
}
}
|
3e1a486fbce4d3bad99c7b9e4df70004c0ab6a1c | 571 | java | Java | src/main/java/com/syntifi/casper/sdk/model/storedvalue/StoredValueDeployInfo.java | mrkara/casper-sdk | 7fe51e7da7d02b249c2c7e322aa1e11ee8d7b036 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/syntifi/casper/sdk/model/storedvalue/StoredValueDeployInfo.java | mrkara/casper-sdk | 7fe51e7da7d02b249c2c7e322aa1e11ee8d7b036 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/syntifi/casper/sdk/model/storedvalue/StoredValueDeployInfo.java | mrkara/casper-sdk | 7fe51e7da7d02b249c2c7e322aa1e11ee8d7b036 | [
"Apache-2.0"
] | null | null | null | 24.826087 | 72 | 0.740806 | 11,178 | package com.syntifi.casper.sdk.model.storedvalue;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.syntifi.casper.sdk.model.deploy.DeployInfo;
import lombok.Data;
/**
* Stored Value for {@link DeployInfo}
*
* @author Alexandre Carvalho
* @author Andre Bertolace
* @see StoredValue
* @since 0.0.1
*/
@Data
@JsonTypeName("DeployInfo")
public class StoredValueDeployInfo implements StoredValue<DeployInfo> {
@JsonProperty("DeployInfo")
public DeployInfo value;
}
|
3e1a4a8693f69088eaf871ddfcc24b22d7a2edde | 5,509 | java | Java | src/cell/WatorCell.java | cndracos/cellsociety_team19 | 640dbc20362f8a990d8ccc6c4498bc6c2e0f1bab | [
"MIT"
] | null | null | null | src/cell/WatorCell.java | cndracos/cellsociety_team19 | 640dbc20362f8a990d8ccc6c4498bc6c2e0f1bab | [
"MIT"
] | null | null | null | src/cell/WatorCell.java | cndracos/cellsociety_team19 | 640dbc20362f8a990d8ccc6c4498bc6c2e0f1bab | [
"MIT"
] | null | null | null | 25.742991 | 95 | 0.664549 | 11,179 | package cell;
import java.util.ArrayList;
import java.util.Random;
import javafx.scene.paint.Color;
/**
* Class FireCell is inherited from Super class Cell,
* and is used for Fire Simulation.
* @author Yameng Liu
*
*/
public class WatorCell extends Cell{
private final double FISH_R;
private final double SHARK_R;
private final double SHARK_E;
private Random rand;
public double fishMoves;
public double sharkMoves;
public double sharkE;
private boolean isUpdated;
private final int fishE = 1;
/**
* Constructor of WatorCell class
* Assign initial state of the cell by calling constructor of super class
* Set related parameters according to different states
* @param currState current state of cell
* @param fishR number of cells the fish needs to survive to be able to survive
* @param sharkR number of cells the shark needs to survive to be able to survive
* @param sharkE initial energy amount of shark
*/
public WatorCell(String currState,double fishR,double sharkR,double sharkE){
super(currState);
FISH_R = fishR;
SHARK_R = sharkR;
SHARK_E = sharkE;
isUpdated = false;
setParam(currState);
rand = new Random();
}
@Override
/**
* find the next state to update to
* call by grid class
*/
public void findState(){
updateByRule();
}
@Override
/**
* Update states according to simple rules on course website with probability
* @return new state
*/
protected String updateByRule() {
//if the cell is a fish
if(getState().equals("FISH")){
ArrayList<WatorCell> waters = getTypes("WATER");
WatorCell nextCell = null;
//if there is an unoccupied free cell, move to it
if(waters.size() > 0){
fishMoves += 1;
int key = rand.nextInt(waters.size());
nextCell = waters.get(key);
//else just swim to the free water
this.newState ="WATER";
nextCell.newState = "FISH";
nextCell.fishMoves = this.fishMoves;
//reproduce fish, current cell becomes a fish
if(fishMoves == FISH_R){
this.newState = "FISH";
nextCell.fishMoves = 0;
}
//update changed cells
isUpdated = true;
nextCell.setUpdated(true);
this.fishMoves = 0;
}
}
//if current cell is a shark
else if(getState().equals("SHARK")){
ArrayList<WatorCell> fishs = getTypes("FISH");
ArrayList<WatorCell> waters = getTypes("WATER");
WatorCell nextCell = null;
//shark consumes 1 unit of energy at each step
sharkE -= 1;
//if a shark consumes all energy, it dies,the current cell becomes water
if(sharkE <= 0){
this.newState = "WATER";
this.sharkMoves = 0;
this.sharkE = 0;
isUpdated = true;
return newState;
}
//if shark is eligible to move
if(fishs.size() > 0 || waters.size() > 0){
sharkMoves += 1;
//if there is a fish, devour it, the current cell becomes water
if(fishs.size() > 0){
sharkE += fishE;
int key = rand.nextInt(fishs.size());
nextCell = fishs.get(key);
this.newState ="WATER";
nextCell.newState = "SHARK";
nextCell.sharkE = this.sharkE;
nextCell.sharkMoves = this.sharkMoves;
}
//otherwise if there is an unoccupied free cell, move to it, the current cell becomes water
else if(waters.size() > 0){
int key = rand.nextInt(waters.size());
nextCell = waters.get(key);
this.newState = "WATER";
nextCell.newState = "SHARK";
nextCell.sharkE = this.sharkE;
nextCell.sharkMoves = this.sharkMoves;
}
//change updated status of cells,reduce shark's energy
isUpdated = true;
nextCell.setUpdated(true);
//reproduce shark, current cell becomes shark
if(sharkMoves == SHARK_R && nextCell != null && sharkE >= SHARK_E / 2.0){
this.newState = "SHARK";
this.sharkE = SHARK_E;
nextCell.sharkMoves = 0;
}
else {
this.sharkE = 0;
}
this.sharkMoves = 0;
}
}
return newState;
}
/**
* get not updated neighbors cells of given types
* @param type given type
* @return found neighbor lists
*/
private ArrayList<WatorCell> getTypes(String type){
ArrayList<WatorCell> typeArray = new ArrayList<WatorCell>();
for(Cell myNeighbor : getNeighbors()){
if(myNeighbor.getState() == type && !((WatorCell)myNeighbor).getUpdated()){
typeArray.add((WatorCell)myNeighbor);
}
}
return typeArray;
}
/**
* Initialize related parameters according to currState
* @param currState current state of the cell
*/
private void setParam(String currState) {
if(currState == "FISH") {
this.fishMoves = 0;
}
else if(currState == "SHARK") {
this.sharkMoves = 0;
this.sharkE = SHARK_E;
}
}
/**
* check whether or not the cell is updated
* @return updated or not
*/
public boolean getUpdated() {
return isUpdated;
}
/**
* change the updated status of cell to given status
* @param isUpdated given status
*/
public void setUpdated(boolean isUpdated) {
this.isUpdated = isUpdated;
}
@Override
/**
* update the state and graphics of the cell, change updated status
*/
public void setState(){
currState = newState;
this.setFill(colorByState(currState));
isUpdated = false;
}
@Override
/**
* decide specific color of the cell according to specific rules in fire simulation
* @param state current state
* @return current color of graphics
*/
protected Color colorByState(String state) {
return state == "WATER" ? Color.BLUE : state == "FISH" ? Color.GREEN : Color.YELLOW;
}
}
|
3e1a4b1b55e2ee414a0f9171e22913729ae27cb5 | 3,892 | java | Java | log4j-plugins/src/main/java/org/apache/logging/log4j/plugins/util/PluginType.java | CrazyBills/logging-log4j2 | b5635efa03bed3098d447caf07c24b5defe8f68c | [
"Apache-2.0"
] | 3,034 | 2015-01-19T14:45:09.000Z | 2022-03-31T06:11:10.000Z | log4j-plugins/src/main/java/org/apache/logging/log4j/plugins/util/PluginType.java | CrazyBills/logging-log4j2 | b5635efa03bed3098d447caf07c24b5defe8f68c | [
"Apache-2.0"
] | 559 | 2015-03-11T15:45:08.000Z | 2022-03-31T17:56:24.000Z | log4j-plugins/src/main/java/org/apache/logging/log4j/plugins/util/PluginType.java | CrazyBills/logging-log4j2 | b5635efa03bed3098d447caf07c24b5defe8f68c | [
"Apache-2.0"
] | 1,620 | 2015-01-31T09:10:08.000Z | 2022-03-31T17:42:41.000Z | 32.165289 | 108 | 0.64517 | 11,180 | /*
* 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.logging.log4j.plugins.util;
import org.apache.logging.log4j.plugins.processor.PluginEntry;
/**
* Plugin Descriptor. This is a memento object for Plugin annotations paired to their annotated classes.
*
* @param <T> The plug-in class, which can be any kind of class.
* @see org.apache.logging.log4j.plugins.Plugin
*/
public class PluginType<T> {
private final PluginEntry pluginEntry;
private volatile Class<T> pluginClass;
private final ClassLoader classLoader;
private final String elementName;
/**
* Constructor.
* @param pluginEntry The PluginEntry.
* @param pluginClass The plugin Class.
* @param elementName The name of the element.
* @since 2.1
*/
public PluginType(final PluginEntry pluginEntry, final Class<T> pluginClass, final String elementName) {
this.pluginEntry = pluginEntry;
this.pluginClass = pluginClass;
this.elementName = elementName;
this.classLoader = null;
}
/**
* The Constructor.
* @since 3.0
* @param pluginEntry The PluginEntry.
* @param classLoader The ClassLoader to use to load the Plugin.
*/
public PluginType(final PluginEntry pluginEntry, final ClassLoader classLoader) {
this.pluginEntry = pluginEntry;
this.classLoader = classLoader;
this.elementName = pluginEntry.getName();
this.pluginClass = null;
}
public PluginEntry getPluginEntry() {
return this.pluginEntry;
}
@SuppressWarnings("unchecked")
public Class<T> getPluginClass() {
if (pluginClass == null) {
try {
pluginClass = (Class<T>) this.classLoader.loadClass(pluginEntry.getClassName());
} catch (ClassNotFoundException | LinkageError ex) {
throw new IllegalStateException("No class named " + pluginEntry.getClassName() +
" located for element " + elementName, ex);
}
}
return this.pluginClass;
}
public String getElementName() {
return this.elementName;
}
/**
* Return The plugin's key.
* @return The plugin key.
* @since 2.1
*/
public String getKey() {
return this.pluginEntry.getKey();
}
public boolean isObjectPrintable() {
return this.pluginEntry.isPrintable();
}
public boolean isDeferChildren() {
return this.pluginEntry.isDefer();
}
/**
* Return the plugin category.
* @return the Plugin category.
* @since 2.1
*/
public String getCategory() {
return this.pluginEntry.getCategory();
}
@Override
public String toString() {
return "PluginType [pluginClass=" + pluginClass +
", key=" + pluginEntry.getKey() +
", elementName=" + pluginEntry.getName() +
", isObjectPrintable=" + pluginEntry.isPrintable() +
", isDeferChildren==" + pluginEntry.isDefer() +
", category=" + pluginEntry.getCategory() +
"]";
}
}
|
3e1a4b27538fba1c6396634f96f7663231cdb956 | 2,827 | java | Java | nlpcraft/src/main/scala/org/apache/nlpcraft/model/opencensus/NCStackdriverStatsExporter.java | rahul3/incubator-nlpcraft | 7e19511724cb986a598b237512b32544dd457bfd | [
"Apache-2.0"
] | null | null | null | nlpcraft/src/main/scala/org/apache/nlpcraft/model/opencensus/NCStackdriverStatsExporter.java | rahul3/incubator-nlpcraft | 7e19511724cb986a598b237512b32544dd457bfd | [
"Apache-2.0"
] | 1 | 2021-12-14T21:58:04.000Z | 2021-12-14T21:58:04.000Z | nlpcraft/src/main/scala/org/apache/nlpcraft/model/opencensus/NCStackdriverStatsExporter.java | rahul3/incubator-nlpcraft | 7e19511724cb986a598b237512b32544dd457bfd | [
"Apache-2.0"
] | null | null | null | 43.492308 | 177 | 0.715953 | 11,181 | /*
* 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.nlpcraft.model.opencensus;
import io.opencensus.exporter.stats.stackdriver.*;
import org.apache.nlpcraft.common.*;
import org.apache.nlpcraft.common.config.*;
import org.apache.nlpcraft.model.*;
import org.slf4j.*;
import java.io.*;
/**
* Probe lifecycle component that manages OpenCensus <a target=_ href="https://cloud.google.com/stackdriver/">Stackdriver</a> stats exporter. See
* <a target=_ href="https://opencensus.io/exporters/supported-exporters/java/stackdriver-stats/">https://opencensus.io/exporters/supported-exporters/java/stackdriver-stats/</a>
* for more details. This is a probe lifecycle component - see {@link NCLifecycle} for usage information.
* <p>
* See <a target=_ href="https://nlpcraft.apache.org/server-and-probe.html">documentation</a> on how to configure probe life cycle
* components, default values, etc.
*/
public class NCStackdriverStatsExporter implements NCLifecycle {
private static class Config extends NCConfigurableJava {
private static final String pre = "nlpcraft.probe.opencensus.stackdriver";
private final String prefix = getStringOrElse(pre + ".metricsPrefix", "custom.googleapis.com/nlpcraft/probe");
private final String gpi = getString(pre + ".googleProjectId");
}
private static final Config cfg = new Config();
private static final Logger log = LoggerFactory.getLogger(NCStackdriverStatsExporter.class);
@Override
public void onInit() {
try {
StackdriverStatsExporter.createAndRegister(StackdriverStatsConfiguration.builder().
setMetricNamePrefix(cfg.prefix).
setProjectId(cfg.gpi).
build()
);
}
catch (IOException e) {
throw new NCException(
String.format("Stackdriver OpenCensus stats exporter cannot be registered for project: %s", cfg.gpi), e
);
}
log.info("Stackdriver OpenCensus stats exporter started for project: {}", cfg.gpi);
}
}
|
3e1a4dc5386fe2558b76845c6adf49a8f0a85121 | 3,568 | java | Java | idol/src/main/java/com/hp/autonomy/searchcomponents/idol/fields/IdolFieldPathNormaliserImpl.java | hpautonomy/haven-search-components | b4e07af0f7a9bdbc28eaef82e8e13055324e1697 | [
"MIT"
] | 2 | 2016-04-15T16:08:13.000Z | 2016-10-31T05:08:57.000Z | idol/src/main/java/com/hp/autonomy/searchcomponents/idol/fields/IdolFieldPathNormaliserImpl.java | hpautonomy/haven-search-components | b4e07af0f7a9bdbc28eaef82e8e13055324e1697 | [
"MIT"
] | 1 | 2020-06-16T10:27:38.000Z | 2020-06-16T10:27:38.000Z | idol/src/main/java/com/hp/autonomy/searchcomponents/idol/fields/IdolFieldPathNormaliserImpl.java | hpautonomy/haven-search-components | b4e07af0f7a9bdbc28eaef82e8e13055324e1697 | [
"MIT"
] | 8 | 2016-02-25T21:27:47.000Z | 2017-07-31T15:23:30.000Z | 48.876712 | 163 | 0.722534 | 11,182 | /*
* (c) Copyright 2015 Micro Focus or one of its affiliates.
*
* Licensed under the MIT License (the "License"); you may not use this file
* except in compliance with the License.
*
* The only warranties for products and services of Micro Focus and its affiliates
* and licensors ("Micro Focus") are as may be set forth in the express warranty
* statements accompanying such products and services. Nothing herein should be
* construed as constituting an additional warranty. Micro Focus shall not be
* liable for technical or editorial errors or omissions contained herein. The
* information contained herein is subject to change without notice.
*/
package com.hp.autonomy.searchcomponents.idol.fields;
import com.hp.autonomy.searchcomponents.core.fields.AbstractFieldPathNormaliser;
import com.hp.autonomy.searchcomponents.core.fields.FieldPathNormaliser;
import com.hp.autonomy.searchcomponents.core.parametricvalues.ParametricValuesService;
import com.hp.autonomy.types.requests.idol.actions.tags.FieldPath;
import java.util.Collection;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import static com.hp.autonomy.searchcomponents.core.fields.FieldPathNormaliser.FIELD_PATH_NORMALISER_BEAN_NAME;
/**
* Default Idol implementation of {@link FieldPathNormaliser}
*/
@Component(FIELD_PATH_NORMALISER_BEAN_NAME)
public class IdolFieldPathNormaliserImpl extends AbstractFieldPathNormaliser {
private static final String IDX_PREFIX = "DOCUMENT/";
private static final Pattern FIELD_NAME_PATTERN = Pattern.compile("(/?[^/]+)+");
private static final Pattern IDX_PATH_PATTERN = Pattern.compile("^/?(?:" + IDX_PREFIX + ")?(?<fieldPath>[^/]+)$");
private Pattern XML_PATH_PATTERN = updatePattern(Collections.singletonList("DOCUMENTS"));
// We have to do it this way to break the circular dependency between the FieldsInfo deserializer and this.
public Pattern updatePattern(final Collection<String> prefixes) {
final String XML_PREFIX = prefixes.stream()
.map(s -> Pattern.quote(s + "/"))
.collect(Collectors.joining("|"));
return XML_PATH_PATTERN = Pattern.compile("^/?(?:" + XML_PREFIX + ")?(?:" + IDX_PREFIX + ")?(?<fieldPath>[^/]+(?:/[^/]+)*)$");
}
@Override
public FieldPath normaliseFieldPath(final String fieldPath) {
if (StringUtils.isBlank(fieldPath) || !FIELD_NAME_PATTERN.matcher(fieldPath.trim()).matches()) {
throw new IllegalArgumentException("Field names may not be blank or contain only forward slashes");
}
String normalisedFieldName = fieldPath.toUpperCase();
if (!ParametricValuesService.AUTN_DATE_FIELD.equals(normalisedFieldName)) {
final Matcher idxMatcher = IDX_PATH_PATTERN.matcher(normalisedFieldName);
if (idxMatcher.find()) {
normalisedFieldName = idxMatcher.group("fieldPath");
} else {
final Matcher xmlMatcher = XML_PATH_PATTERN.matcher(normalisedFieldName);
if (xmlMatcher.find()) {
normalisedFieldName = xmlMatcher.group("fieldPath");
}
}
}
final String fieldName = normalisedFieldName.contains("/") ? normalisedFieldName.substring(normalisedFieldName.lastIndexOf('/') + 1) : normalisedFieldName;
return newFieldPath(normalisedFieldName, fieldName);
}
}
|
3e1a4eacac129e509dfe37a8e056970d11e81e62 | 8,893 | java | Java | src-plugins/Dichromacy_/src/main/java/Dichromacy_.java | robertb-r/fiji | 4eb8d690811c5c9d746e673dbd7c3297ec12dfdf | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2022-03-14T06:26:16.000Z | 2022-03-14T06:26:16.000Z | src-plugins/Dichromacy_/src/main/java/Dichromacy_.java | robertb-r/fiji | 4eb8d690811c5c9d746e673dbd7c3297ec12dfdf | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2016-09-24T16:47:43.000Z | 2016-09-24T16:47:43.000Z | src-plugins/Dichromacy_/src/main/java/Dichromacy_.java | robertb-r/fiji | 4eb8d690811c5c9d746e673dbd7c3297ec12dfdf | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | 33.149254 | 100 | 0.62787 | 11,183 | import ij.*;
import ij.plugin.*;
import ij.process.*;
import ij.gui.*;
import java.awt.*;
import java.awt.image.*;
public class Dichromacy_ implements PlugIn {
/*
Simulation of dichromatic vision (colour blindness)
This code is an implementation of an algorithm described by Hans Brettel,
Francoise Vienot and John Mollon in the Journal of the Optical Society of
America V14(10), pg 2647. (See http://vischeck.com/ for more info.).
Based on the GIMP's cdisplay_colorblind.c
by Michael Natterer <ychag@example.com>, Sven Neumann <ychag@example.com>,
Robert Dougherty <kenaa@example.com> and Alex Wade <dycjh@example.com>.
This code is written using "Scribus coding standard" as a part of the
Scribus project (www.scribus.net).
author Petr Vanek <upchh@example.com>
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// Ported to ImageJ Java plugin by G.Landini at bham ac uk from colorblind.cpp which
// is part of the Scribus desktop publishing package.
// 6 June 2010
// 24 July 2010 change non-RGB images to RGB
// Many thanks to Robert Dougherty <kenaa@example.com> and Alex Wade <dycjh@example.com>
// who clarified the gamma scaling bug..
public void run(String arg) {
ImagePlus imp = WindowManager.getCurrentImage();
if (imp==null){
IJ.error("No image!");
return;
}
int width = imp.getWidth();
int height =imp.getHeight();
String title = imp.getTitle();
if(imp.getBitDepth() != 24)
IJ.run(imp, "RGB Color", "");
boolean createWindow = true;
GenericDialog gd = new GenericDialog("Dichromacy v1.0", IJ.getInstance());
//gd.addMessage("Select subtractive colour model");
String [] type={"Protanope", "Deuteranope", "Tritanope"};
gd.addChoice("Simulate", type, type[1]);
gd.addCheckbox("Create New Window", createWindow);
gd.showDialog();
if (gd.wasCanceled())
return;
int deficiency = gd.getNextChoiceIndex();
createWindow = gd.getNextBoolean();
//boolean hideLegend = gd.getNextBoolean();
double tmp, red, green, blue;
double [] rgb2lms = new double[9];
double [] lms2rgb = new double[9];
double [] gammaRGB = new double[3];
double a1=0.0, b1=0.0, c1=0.0;
double a2=0.0, b2=0.0, c2=0.0;
double inflection=0.0;
double redOld , greenOld;
rgb2lms[0] = 0.05059983;
rgb2lms[1] = 0.08585369;
rgb2lms[2] = 0.00952420;
rgb2lms[3] = 0.01893033;
rgb2lms[4] = 0.08925308;
rgb2lms[5] = 0.01370054;
rgb2lms[6] = 0.00292202;
rgb2lms[7] = 0.00975732;
rgb2lms[8] = 0.07145979;
lms2rgb[0] = 30.830854;
lms2rgb[1] = -29.832659;
lms2rgb[2] = 1.610474;
lms2rgb[3] = -6.481468;
lms2rgb[4] = 17.715578;
lms2rgb[5] = -2.532642;
lms2rgb[6] = -0.375690;
lms2rgb[7] = -1.199062;
lms2rgb[8] = 14.273846;
gammaRGB[0] = 2.0;
gammaRGB[1] = 2.0;
gammaRGB[2] = 2.0;
double [] anchor_e= new double[3];;
double [] anchor= new double[12];
/*
Load the LMS anchor-point values for lambda = 475 & 485 nm (for
protans & deutans) and the LMS values for lambda = 575 & 660 nm
(for tritans)
*/
anchor[0] = 0.08008; anchor[1] = 0.1579; anchor[2] = 0.5897;
anchor[3] = 0.1284; anchor[4] = 0.2237; anchor[5] = 0.3636;
anchor[6] = 0.9856; anchor[7] = 0.7325; anchor[8] = 0.001079;
anchor[9] = 0.0914; anchor[10] = 0.007009; anchor[11] = 0.0;
/* We also need LMS for RGB=(1,1,1)- the equal-energy point (one of
* our anchors) (we can just peel this out of the rgb2lms transform
* matrix)
*/
anchor_e[0] = rgb2lms[0] + rgb2lms[1] + rgb2lms[2];
anchor_e[1] = rgb2lms[3] + rgb2lms[4] + rgb2lms[5];
anchor_e[2] = rgb2lms[6] + rgb2lms[7] + rgb2lms[8];
ImageProcessor ip;
ImagePlus imp2=null;
if(createWindow){
imp2 = new ImagePlus(title+"-"+type[deficiency],imp.getProcessor().duplicate());
ip = imp2.getProcessor();
}
else {
ip = imp.getProcessor();
ip.snapshot();
Undo.setup(Undo.FILTER, imp);
}
switch (deficiency) {
case 1:
/* Deuteranope */
a1 = anchor_e[1] * anchor[8] - anchor_e[2] * anchor[7];
b1 = anchor_e[2] * anchor[6] - anchor_e[0] * anchor[8];
c1 = anchor_e[0] * anchor[7] - anchor_e[1] * anchor[6];
a2 = anchor_e[1] * anchor[2] - anchor_e[2] * anchor[1];
b2 = anchor_e[2] * anchor[0] - anchor_e[0] * anchor[2];
c2 = anchor_e[0] * anchor[1] - anchor_e[1] * anchor[0];
inflection = (anchor_e[2] / anchor_e[0]);
break;
case 0 :
/* Protanope */
a1 = anchor_e[1] * anchor[8] - anchor_e[2] * anchor[7];
b1 = anchor_e[2] * anchor[6] - anchor_e[0] * anchor[8];
c1 = anchor_e[0] * anchor[7] - anchor_e[1] * anchor[6];
a2 = anchor_e[1] * anchor[2] - anchor_e[2] * anchor[1];
b2 = anchor_e[2] * anchor[0] - anchor_e[0] * anchor[2];
c2 = anchor_e[0] * anchor[1] - anchor_e[1] * anchor[0];
inflection = (anchor_e[2] / anchor_e[1]);
break;
case 2 :
/* Tritanope */
a1 = anchor_e[1] * anchor[11] - anchor_e[2] * anchor[10];
b1 = anchor_e[2] * anchor[9] - anchor_e[0] * anchor[11];
c1 = anchor_e[0] * anchor[10] - anchor_e[1] * anchor[9];
a2 = anchor_e[1] * anchor[5] - anchor_e[2] * anchor[4];
b2 = anchor_e[2] * anchor[3] - anchor_e[0] * anchor[5];
c2 = anchor_e[0] * anchor[4] - anchor_e[1] * anchor[3];
inflection = (anchor_e[1] / anchor_e[0]);
break;
}
int imagesize = width * height;
int[] pixels = (int[]) ip.getPixels();
// process the image
IJ.showStatus("Dichromacy...");
IJ.showProgress(0.5); //show that something is going on
for (int j=0; j<imagesize; j++) {
int i = pixels[j];
red = (double) ((i & 0xff0000)>>16);
green =(double) ((i & 0xff00)>>8) ;
blue = (double) (i & 0xff);
/* GL: Apply (not remove!) phosphor gamma to RGB intensities */
// GL: This is a Gimp/Scribus code bug, this way it returns values similar to those of Vischeck:
red = Math.pow(red/255.0, gammaRGB[0]);
green = Math.pow(green/255.0, gammaRGB[1]);
blue = Math.pow(blue/255.0, gammaRGB[2]);
redOld = red;
greenOld = green;
red = redOld * rgb2lms[0] + greenOld * rgb2lms[1] + blue * rgb2lms[2];
green = redOld * rgb2lms[3] + greenOld * rgb2lms[4] + blue * rgb2lms[5];
blue = redOld * rgb2lms[6] + greenOld * rgb2lms[7] + blue * rgb2lms[8];
switch (deficiency) {
case 1:
/* Deuteranope */
tmp = blue / red;
/* See which side of the inflection line we fall... */
if (tmp < inflection)
green = -(a1 * red + c1 * blue) / b1;
else
green = -(a2 * red + c2 * blue) / b2;
break;
case 0 :
/* Protanope */
tmp = blue / green;
/* See which side of the inflection line we fall... */
if (tmp < inflection)
red = -(b1 * green + c1 * blue) / a1;
else
red = -(b2 * green + c2 * blue) / a2;
break;
case 2 :
/* Tritanope */
tmp = green / red;
/* See which side of the inflection line we fall... */
if (tmp < inflection)
blue = -(a1 * red + b1 * green) / c1;
else
blue = -(a2 * red + b2 * green) / c2;
break;
}
/* Convert back to RGB (cross product with transform matrix) */
redOld = red;
greenOld = green;
red = redOld * lms2rgb[0] + greenOld * lms2rgb[1] + blue * lms2rgb[2];
green = redOld * lms2rgb[3] + greenOld * lms2rgb[4] + blue * lms2rgb[5];
blue = redOld * lms2rgb[6] + greenOld * lms2rgb[7] + blue * lms2rgb[8];
/* GL Remove (not apply!) phosphor gamma to go back to original intensities */
// GL: This is a Gimp/Scribus code bug, this way it returns values similar to those of Vischeck:
int ired =(int)Math.round(Math.pow(red, 1.0/gammaRGB[0])*255.0);
int igreen =(int)Math.round(Math.pow(green, 1.0/gammaRGB[1])*255.0);
int iblue =(int) Math.round(Math.pow(blue, 1.0/gammaRGB[2])*255.0);
/* Ensure that we stay within the RGB gamut */
/* *** FIX THIS: it would be better to desaturate than blindly clip. */
ired = (ired>255) ? 255: ( (ired<0 ) ? 0: ired);
igreen = (igreen>255) ? 255: ( (igreen<0 ) ? 0: igreen);
iblue = (iblue>255) ? 255: ( (iblue<0 ) ? 0: iblue);
pixels[j]=((ired & 0xff)<<16)+((igreen & 0xff)<<8 )+(iblue & 0xff) ;
}
IJ.showProgress(1); // erase the progress bar
if(createWindow){
imp2.show();
imp2.updateAndDraw();
}
else
imp.updateAndDraw();
}
}
|
3e1a510dc71e564665029c20ad1dcb1edd149cf7 | 1,722 | java | Java | src/viaversion/viabackwards/protocol/protocol1_13to1_13_1/packets/InventoryPackets1_13_1.java | josesilveiraa/novoline | 9146c4add3aa518d9aa40560158e50be1b076cf0 | [
"Unlicense"
] | 5 | 2022-02-04T12:57:17.000Z | 2022-03-26T16:12:16.000Z | src/viaversion/viabackwards/protocol/protocol1_13to1_13_1/packets/InventoryPackets1_13_1.java | josesilveiraa/novoline | 9146c4add3aa518d9aa40560158e50be1b076cf0 | [
"Unlicense"
] | 2 | 2022-02-25T20:10:14.000Z | 2022-03-03T14:25:03.000Z | src/viaversion/viabackwards/protocol/protocol1_13to1_13_1/packets/InventoryPackets1_13_1.java | josesilveiraa/novoline | 9146c4add3aa518d9aa40560158e50be1b076cf0 | [
"Unlicense"
] | 1 | 2021-11-28T09:59:55.000Z | 2021-11-28T09:59:55.000Z | 40.046512 | 99 | 0.756678 | 11,184 | package viaversion.viabackwards.protocol.protocol1_13to1_13_1.packets;
import net.aQU;
import net.aoy;
import net.aqN;
import net.q1;
import net.uN;
import viaversion.viabackwards.protocol.protocol1_13to1_13_1.Protocol1_13To1_13_1;
import viaversion.viaversion.api.minecraft.item.Item;
import viaversion.viaversion.api.protocol.ClientboundPacketType;
import viaversion.viaversion.api.protocol.Protocol;
import viaversion.viaversion.api.protocol.ServerboundPacketType;
import viaversion.viaversion.api.rewriters.ItemRewriter$RewriteFunction;
import viaversion.viaversion.api.type.Type;
public class InventoryPackets1_13_1 {
public static void register(Protocol var0) {
aQU var1 = new aQU(var0, InventoryPackets1_13_1::toClient, InventoryPackets1_13_1::toServer);
var1.a((ClientboundPacketType)q1.COOLDOWN);
var1.b((ClientboundPacketType)q1.WINDOW_ITEMS, Type.FLAT_ITEM_ARRAY);
var1.a((ClientboundPacketType)q1.SET_SLOT, Type.FLAT_ITEM);
var0.a((ClientboundPacketType)q1.PLUGIN_MESSAGE, new aoy());
var1.f(q1.ENTITY_EQUIPMENT, Type.FLAT_ITEM);
var1.a((ServerboundPacketType)uN.CLICK_WINDOW, Type.FLAT_ITEM);
var1.b((ServerboundPacketType)uN.CREATIVE_INVENTORY_ACTION, Type.FLAT_ITEM);
var1.a(q1.SPAWN_PARTICLE, Type.FLAT_ITEM, Type.FLOAT);
}
public static void toClient(Item var0) {
String[] var1 = aqN.a();
if(var0 != null) {
var0.setIdentifier(Protocol1_13To1_13_1.MAPPINGS.getNewItemId(var0.getIdentifier()));
}
}
public static void toServer(Item var0) {
String[] var1 = aqN.a();
if(var0 != null) {
var0.setIdentifier(Protocol1_13To1_13_1.MAPPINGS.getOldItemId(var0.getIdentifier()));
}
}
}
|
3e1a51935281f3620a5086e37168429187ecbbf3 | 834 | java | Java | instagram-crawler-service/src/main/java/com/inshop/config/InstagramConfig.java | bbotio/inshop | 78734c6964c6a817548acae9f95331518d2431f8 | [
"Unlicense"
] | null | null | null | instagram-crawler-service/src/main/java/com/inshop/config/InstagramConfig.java | bbotio/inshop | 78734c6964c6a817548acae9f95331518d2431f8 | [
"Unlicense"
] | null | null | null | instagram-crawler-service/src/main/java/com/inshop/config/InstagramConfig.java | bbotio/inshop | 78734c6964c6a817548acae9f95331518d2431f8 | [
"Unlicense"
] | null | null | null | 29.785714 | 79 | 0.708633 | 11,185 | package com.inshop.config;
import org.jinstagram.auth.InstagramAuthService;
import org.jinstagram.auth.oauth.InstagramService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class InstagramConfig {
@Value("${instagram.client_id}")
private String clientId;
@Value("${instagram.client_secret}")
private String clientSecret;
@Value("${instagram.handle_token:http://localhost:8080/login/handleToken}")
private String url;
@Bean
public InstagramService instagramService() {
return new InstagramAuthService()
.apiKey(clientId)
.apiSecret(clientSecret)
.callback(url)
.build();
}
} |
3e1a51ad9fac1fb134e5e860bbed64426eb45a38 | 4,668 | java | Java | src/main/java/org/stormpx/dl/kit/Http.java | Stormpx/m3u8dl | dfe1b1640bc5f466e46be1534118f2d0055cde1d | [
"MIT"
] | null | null | null | src/main/java/org/stormpx/dl/kit/Http.java | Stormpx/m3u8dl | dfe1b1640bc5f466e46be1534118f2d0055cde1d | [
"MIT"
] | null | null | null | src/main/java/org/stormpx/dl/kit/Http.java | Stormpx/m3u8dl | dfe1b1640bc5f466e46be1534118f2d0055cde1d | [
"MIT"
] | null | null | null | 39.897436 | 187 | 0.529777 | 11,186 | package org.stormpx.dl.kit;
import java.io.IOException;
import java.net.*;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
public class Http {
public static HttpClient client;
private static String USER_AGENT="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/99.0";
public static void build(URI proxy, String ua, Executor executor){
var builder=HttpClient.newBuilder()
.executor(executor)
.followRedirects(HttpClient.Redirect.NORMAL);
if (proxy!=null){
builder.proxy(new DownloadProxySelector(proxy));
}
if (ua!=null){
USER_AGENT=ua;
}
client=builder.build();
}
public static ReqResult request(URI uri, ByteRange byteRange) throws IOException {
try {
return requestAsync(uri,byteRange).get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e.getMessage(),e);
}
}
public static CompletableFuture<ReqResult> requestAsync(URI uri, ByteRange byteRange) {
var builder=HttpRequest.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.timeout(Duration.ofSeconds(5))
.uri(uri).GET()
.setHeader("user-agent",USER_AGENT);
if (byteRange!=null){
builder.setHeader("range",byteRange.start()+"-"+ byteRange.end());
}
return Http.client.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofInputStream())
.thenApply((response)->{
try {
if (response.statusCode()!=200&&response.statusCode()!=206){
response.body().close();
return new ReqResult(false);
}
ReqResult reqResult = new ReqResult(true);
reqResult.setTargetUri(response.uri());
reqResult.setM3u8File(
uri.getPath().endsWith(".m3u8")
||uri.getPath().endsWith(".m3u")
||response.headers().allValues("content-type").stream()
.anyMatch(str->
Objects.equals(str,"application/vnd.apple.mpegurl")||Objects.equals(str,"audio/mpegurl")||Objects.equals(str,"application/x-mpegurl"))
);
reqResult.setContentLength(response.headers().firstValue("content-length").map(Integer::valueOf).orElse(-1));
reqResult.setInputStream(response.body());
return reqResult;
} catch (IOException e) {
throw new RuntimeException(e.getMessage(),e);
}
});
}
private static class DownloadProxySelector extends ProxySelector{
private List<Proxy> proxies;
public DownloadProxySelector(URI uri) {
Objects.requireNonNull(uri);
Objects.requireNonNull(uri.getScheme());
Objects.requireNonNull(uri.getHost());
if (uri.getPort()==-1){
throw new IllegalArgumentException("port of the proxy address is undefined");
}
String scheme = uri.getScheme();
Proxy.Type type;
if (scheme.startsWith("http")){
type= Proxy.Type.HTTP;
}else if (scheme.startsWith("socks")){
type= Proxy.Type.SOCKS;
}else{
throw new IllegalArgumentException("proxy address only supported starts with ['http','socks']");
}
;
proxies=List.of(new Proxy(type,new InetSocketAddress(uri.getHost(),uri.getPort())));
}
@Override
public List<Proxy> select(URI uri) {
return proxies;
}
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
System.err.println(ioe.getLocalizedMessage());
}
}
}
|
3e1a52e591cb49891cacddf58d311c4aaed6481a | 1,680 | java | Java | src/test/java/com/cloudmersive/client/rt/model/SetFormFieldValueTest.java | Cloudmersive/Cloudmersive.APIClient.Java.RestTemplate | 4bc1c9de917eb099cc2bd9e985daa0ef570b6ea6 | [
"Apache-2.0"
] | 1 | 2021-02-14T19:52:25.000Z | 2021-02-14T19:52:25.000Z | src/test/java/com/cloudmersive/client/rt/model/SetFormFieldValueTest.java | Cloudmersive/Cloudmersive.APIClient.Java.RestTemplate | 4bc1c9de917eb099cc2bd9e985daa0ef570b6ea6 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/cloudmersive/client/rt/model/SetFormFieldValueTest.java | Cloudmersive/Cloudmersive.APIClient.Java.RestTemplate | 4bc1c9de917eb099cc2bd9e985daa0ef570b6ea6 | [
"Apache-2.0"
] | null | null | null | 22.4 | 92 | 0.680357 | 11,187 | /*
* convertapi
* Convert API lets you effortlessly convert file formats and types.
*
* 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.cloudmersive.client.rt.model;
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 org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* Model tests for SetFormFieldValue
*/
public class SetFormFieldValueTest {
private final SetFormFieldValue model = new SetFormFieldValue();
/**
* Model tests for SetFormFieldValue
*/
@Test
public void testSetFormFieldValue() {
// TODO: test SetFormFieldValue
}
/**
* Test the property 'fieldName'
*/
@Test
public void fieldNameTest() {
// TODO: test fieldName
}
/**
* Test the property 'textValue'
*/
@Test
public void textValueTest() {
// TODO: test textValue
}
/**
* Test the property 'checkboxValue'
*/
@Test
public void checkboxValueTest() {
// TODO: test checkboxValue
}
/**
* Test the property 'comboBoxSelectedIndex'
*/
@Test
public void comboBoxSelectedIndexTest() {
// TODO: test comboBoxSelectedIndex
}
}
|
3e1a535c72589a7dfcb201c0e66752a1c6412b6e | 10,570 | java | Java | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/MoveDisksCommand.java | phoenixsbk/kvmmgr | 1ed6230dc4246fe511eeb5fc9d0532d3e651b459 | [
"Apache-2.0"
] | 1 | 2019-01-12T06:46:55.000Z | 2019-01-12T06:46:55.000Z | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/MoveDisksCommand.java | phoenixsbk/kvmmgr | 1ed6230dc4246fe511eeb5fc9d0532d3e651b459 | [
"Apache-2.0"
] | null | null | null | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/MoveDisksCommand.java | phoenixsbk/kvmmgr | 1ed6230dc4246fe511eeb5fc9d0532d3e651b459 | [
"Apache-2.0"
] | 2 | 2016-03-09T16:37:23.000Z | 2022-01-19T13:12:27.000Z | 42.111554 | 133 | 0.699149 | 11,188 | package org.ovirt.engine.core.bll;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.utils.PermissionSubject;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.LiveMigrateDiskParameters;
import org.ovirt.engine.core.common.action.LiveMigrateVmDisksParameters;
import org.ovirt.engine.core.common.action.MoveDiskParameters;
import org.ovirt.engine.core.common.action.MoveDisksParameters;
import org.ovirt.engine.core.common.action.MoveOrCopyImageGroupParameters;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.businessentities.ActionGroup;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.errors.VdcBllMessages;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dao.DiskImageDAO;
import org.ovirt.engine.core.utils.collections.MultiValueMapUtils;
public class MoveDisksCommand<T extends MoveDisksParameters> extends CommandBase<T> {
private List<VdcReturnValueBase> vdcReturnValues = new ArrayList<VdcReturnValueBase>();
private List<MoveDiskParameters> moveDiskParametersList = new ArrayList<>();
private List<LiveMigrateVmDisksParameters> liveMigrateVmDisksParametersList = new ArrayList<>();
private Map<Guid, DiskImage> diskMap = new HashMap<>();
public MoveDisksCommand(Guid commandId) {
super(commandId);
}
public MoveDisksCommand(T parameters) {
super(parameters);
}
@Override
protected void executeCommand() {
updateParameters();
if (!moveDiskParametersList.isEmpty()) {
vdcReturnValues.addAll(Backend.getInstance().runMultipleActions(VdcActionType.MoveOrCopyDisk,
getParametersArrayList(moveDiskParametersList), false));
}
if (!liveMigrateVmDisksParametersList.isEmpty()) {
vdcReturnValues.addAll(Backend.getInstance().runMultipleActions(VdcActionType.LiveMigrateVmDisks,
getParametersArrayList(liveMigrateVmDisksParametersList), false));
}
handleChildReturnValue();
setSucceeded(true);
}
private void handleChildReturnValue() {
for (VdcReturnValueBase vdcReturnValue : vdcReturnValues) {
getReturnValue().getCanDoActionMessages().addAll(vdcReturnValue.getCanDoActionMessages());
getReturnValue().setCanDoAction(getReturnValue().getCanDoAction() && vdcReturnValue.getCanDoAction());
}
}
@Override
protected boolean canDoAction() {
if (getParameters().getParametersList().isEmpty()) {
return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_NO_DISKS_SPECIFIED);
}
return true;
}
@Override
protected void setActionMessageParameters() {
addCanDoActionMessage(VdcBllMessages.VAR__ACTION__MOVE);
addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM_DISK);
}
private void addDisksDeactivatedMessage(List<MoveDiskParameters> moveDiskParamsList) {
setActionMessageParameters();
addCanDoActionMessageVariable("diskAliases", StringUtils.join(getDisksAliases(moveDiskParamsList), ", "));
addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_MOVE_DISKS_MIXED_PLUGGED_STATUS);
getReturnValue().setCanDoAction(false);
}
private void addInvalidVmStateMessage(VM vm){
setActionMessageParameters();
addCanDoActionMessageVariable("VmName", vm.getName());
addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN_OR_UP);
getReturnValue().setCanDoAction(false);
}
/**
* For each specified MoveDiskParameters, decide whether it should be moved
* using offline move or live migrate command.
*/
protected void updateParameters() {
Map<VM, List<MoveDiskParameters>> vmDiskParamsMap = createVmDiskParamsMap();
for (Map.Entry<VM, List<MoveDiskParameters>> vmDiskParamsEntry : vmDiskParamsMap.entrySet()) {
VM vm = vmDiskParamsEntry.getKey();
List<MoveDiskParameters> moveDiskParamsList = vmDiskParamsEntry.getValue();
if (vm == null || vm.isDown() || areAllDisksPluggedToVm(moveDiskParamsList, false)) {
// Adding parameters for offline move
moveDiskParametersList.addAll(moveDiskParamsList);
}
else if (vm.isRunningAndQualifyForDisksMigration()) {
if (!areAllDisksPluggedToVm(moveDiskParamsList, true)) {
// Cannot live migrate and move disks concurrently
addDisksDeactivatedMessage(moveDiskParamsList);
continue;
}
// Adding parameters for live migrate
liveMigrateVmDisksParametersList.add(createLiveMigrateVmDisksParameters(moveDiskParamsList, vm.getId()));
}
else {
// Live migrate / move disk is not applicable according to VM status
addInvalidVmStateMessage(vm);
}
}
}
/**
* @return a map of VMs to relevant MoveDiskParameters list.
*/
private Map<VM, List<MoveDiskParameters>> createVmDiskParamsMap() {
Map<VM, List<MoveDiskParameters>> vmDisksMap = new HashMap<>();
for (MoveDiskParameters moveDiskParameters : getParameters().getParametersList()) {
DiskImage diskImage = getDiskImageDao().get(moveDiskParameters.getImageId());
Map<Boolean, List<VM>> allVmsForDisk = getVmDAO().getForDisk(diskImage.getId(), false);
List<VM> vmsForPluggedDisk = allVmsForDisk.get(Boolean.TRUE);
List<VM> vmsForUnpluggedDisk = allVmsForDisk.get(Boolean.FALSE);
VM vm = vmsForPluggedDisk != null ? vmsForPluggedDisk.get(0) :
vmsForUnpluggedDisk != null ? vmsForUnpluggedDisk.get(0) :
null; // null is used for floating disks indication
addDiskToMap(diskImage, vmsForPluggedDisk, vmsForUnpluggedDisk);
MultiValueMapUtils.addToMap(vm, moveDiskParameters, vmDisksMap);
}
return vmDisksMap;
}
/**
* Add the specified diskImage to diskMap; with updated 'plugged' value.
* (diskMap contains all disks specified in the parameters).
*/
private void addDiskToMap(DiskImage diskImage, List<VM> vmsForPluggedDisk, List<VM> vmsForUnpluggedDisk) {
if (vmsForPluggedDisk != null) {
diskImage.setPlugged(true);
}
else if (vmsForUnpluggedDisk != null) {
diskImage.setPlugged(false);
}
diskMap.put(diskImage.getImageId(), diskImage);
}
private LiveMigrateDiskParameters createLiveMigrateDiskParameters(MoveDiskParameters moveDiskParameters, Guid vmId) {
return new LiveMigrateDiskParameters(moveDiskParameters.getImageId(),
moveDiskParameters.getSourceDomainId(),
moveDiskParameters.getStorageDomainId(),
vmId,
moveDiskParameters.getQuotaId(),
moveDiskParameters.getDiskProfileId(),
diskMap.get(moveDiskParameters.getImageId()).getId());
}
private LiveMigrateVmDisksParameters createLiveMigrateVmDisksParameters(List<MoveDiskParameters> moveDiskParamsList, Guid vmId) {
// Create LiveMigrateDiskParameters list
List<LiveMigrateDiskParameters> liveMigrateDiskParametersList = new ArrayList<>();
for (MoveDiskParameters moveDiskParameters : moveDiskParamsList) {
liveMigrateDiskParametersList.add(createLiveMigrateDiskParameters(moveDiskParameters, vmId));
}
// Create LiveMigrateVmDisksParameters (multiple disks)
LiveMigrateVmDisksParameters liveMigrateDisksParameters =
new LiveMigrateVmDisksParameters(liveMigrateDiskParametersList, vmId);
liveMigrateDisksParameters.setParentCommand(VdcActionType.MoveDisks);
return liveMigrateDisksParameters;
}
private ArrayList<VdcActionParametersBase> getParametersArrayList(List<? extends VdcActionParametersBase> parametersList) {
for (VdcActionParametersBase parameters : parametersList) {
parameters.setSessionId(getParameters().getSessionId());
}
return new ArrayList<>(parametersList);
}
/**
* Return true if all specified disks are plugged; otherwise false.
*/
private boolean areAllDisksPluggedToVm(List<MoveDiskParameters> moveDiskParamsList, boolean plugged) {
for (MoveDiskParameters moveDiskParameters : moveDiskParamsList) {
DiskImage diskImage = diskMap.get(moveDiskParameters.getImageId());
if (diskImage.getPlugged() != plugged) {
return false;
}
}
return true;
}
private List<String> getDisksAliases(List<MoveDiskParameters> moveVmDisksParamsList) {
List<String> disksAliases = new LinkedList<>();
for (MoveDiskParameters moveDiskParameters : moveVmDisksParamsList) {
DiskImage diskImage = diskMap.get(moveDiskParameters.getImageId());
disksAliases.add(diskImage.getDiskAlias());
}
return disksAliases;
}
@Override
public List<PermissionSubject> getPermissionCheckSubjects() {
List<PermissionSubject> permissionList = new ArrayList<PermissionSubject>();
for (MoveOrCopyImageGroupParameters parameters : getParameters().getParametersList()) {
DiskImage diskImage = getDiskImageDao().get(parameters.getImageId());
if (diskImage != null) {
permissionList.add(new PermissionSubject(diskImage.getId(),
VdcObjectType.Disk,
ActionGroup.CONFIGURE_DISK_STORAGE));
}
}
return permissionList;
}
protected DiskImageDAO getDiskImageDao() {
return getDbFacade().getDiskImageDao();
}
protected List<MoveDiskParameters> getMoveDiskParametersList() {
return moveDiskParametersList;
}
protected List<LiveMigrateVmDisksParameters> getLiveMigrateVmDisksParametersList() {
return liveMigrateVmDisksParametersList;
}
}
|
3e1a53a1d37b3a764b2217518fb5aa79f10c5320 | 4,879 | java | Java | helix-admin-webapp/src/main/java/com/linkedin/helix/webapp/resources/StateModelsResource.java | prafullkotecha/helix | 83c7afd2829f58aba5832cde9514cfd6774865ef | [
"Apache-2.0"
] | null | null | null | helix-admin-webapp/src/main/java/com/linkedin/helix/webapp/resources/StateModelsResource.java | prafullkotecha/helix | 83c7afd2829f58aba5832cde9514cfd6774865ef | [
"Apache-2.0"
] | null | null | null | helix-admin-webapp/src/main/java/com/linkedin/helix/webapp/resources/StateModelsResource.java | prafullkotecha/helix | 83c7afd2829f58aba5832cde9514cfd6774865ef | [
"Apache-2.0"
] | null | null | null | 32.350993 | 155 | 0.732856 | 11,189 | /**
* Copyright (C) 2012 LinkedIn Inc <anpch@example.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.linkedin.helix.webapp.resources;
import java.io.IOException;
import java.util.List;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;
import com.linkedin.helix.HelixDataAccessor;
import com.linkedin.helix.HelixException;
import com.linkedin.helix.ZNRecord;
import com.linkedin.helix.manager.zk.ZkClient;
import com.linkedin.helix.model.StateModelDefinition;
import com.linkedin.helix.tools.ClusterSetup;
import com.linkedin.helix.webapp.RestAdminApplication;
public class StateModelsResource extends Resource
{
private final static Logger LOG = Logger.getLogger(StateModelsResource.class);
public StateModelsResource(Context context,
Request request,
Response response)
{
super(context, request, response);
getVariants().add(new Variant(MediaType.TEXT_PLAIN));
getVariants().add(new Variant(MediaType.APPLICATION_JSON));
}
@Override
public boolean allowGet()
{
return true;
}
@Override
public boolean allowPost()
{
return true;
}
@Override
public boolean allowPut()
{
return false;
}
@Override
public boolean allowDelete()
{
return false;
}
@Override
public Representation represent(Variant variant)
{
StringRepresentation presentation = null;
try
{
presentation = getStateModelsRepresentation();
}
catch(Exception e)
{
String error = ClusterRepresentationUtil.getErrorAsJsonStringFromException(e);
presentation = new StringRepresentation(error, MediaType.APPLICATION_JSON);
LOG.error("", e);
}
return presentation;
}
StringRepresentation getStateModelsRepresentation() throws JsonGenerationException, JsonMappingException, IOException
{
String clusterName = (String)getRequest().getAttributes().get("clusterName");
ZkClient zkClient = (ZkClient)getContext().getAttributes().get(RestAdminApplication.ZKCLIENT);
ClusterSetup setupTool = new ClusterSetup(zkClient);
List<String> models = setupTool.getClusterManagementTool().getStateModelDefs(clusterName);
ZNRecord modelDefinitions = new ZNRecord("modelDefinitions");
modelDefinitions.setListField("models", models);
StringRepresentation representation = new StringRepresentation(ClusterRepresentationUtil.ZNRecordToJson(modelDefinitions), MediaType.APPLICATION_JSON);
return representation;
}
@Override
public void acceptRepresentation(Representation entity)
{
try
{
String clusterName = (String)getRequest().getAttributes().get("clusterName");
ZkClient zkClient = (ZkClient)getContext().getAttributes().get(RestAdminApplication.ZKCLIENT);;
JsonParameters jsonParameters = new JsonParameters(entity);
String command = jsonParameters.getCommand();
if(command.equalsIgnoreCase(ClusterSetup.addStateModelDef))
{
ZNRecord newStateModel = jsonParameters.getExtraParameter(JsonParameters.NEW_STATE_MODEL_DEF);
HelixDataAccessor accessor = ClusterRepresentationUtil.getClusterDataAccessor(zkClient, clusterName);
accessor.setProperty(accessor.keyBuilder().stateModelDef(newStateModel.getId()), new StateModelDefinition(newStateModel) );
getResponse().setEntity(getStateModelsRepresentation());
}
else
{
throw new HelixException("Unsupported command: " + command
+ ". Should be one of [" + ClusterSetup.addStateModelDef + "]");
}
getResponse().setStatus(Status.SUCCESS_OK);
}
catch(Exception e)
{
getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e),
MediaType.APPLICATION_JSON);
getResponse().setStatus(Status.SUCCESS_OK);
LOG.error("Error in posting " + entity, e);
}
}
}
|
3e1a54140d6680daf9a7815c5dae567f6d14d14a | 5,588 | java | Java | src/main/java/frc/robot/subsystems/Maflipulator.java | lbrenn7/frc-2019 | e955a3c4887c5e01e4bad74e917ad1b86a313db1 | [
"MIT"
] | null | null | null | src/main/java/frc/robot/subsystems/Maflipulator.java | lbrenn7/frc-2019 | e955a3c4887c5e01e4bad74e917ad1b86a313db1 | [
"MIT"
] | null | null | null | src/main/java/frc/robot/subsystems/Maflipulator.java | lbrenn7/frc-2019 | e955a3c4887c5e01e4bad74e917ad1b86a313db1 | [
"MIT"
] | null | null | null | 31.044444 | 90 | 0.595562 | 11,190 | package frc.robot.subsystems;
import com.chopshop166.chopshoplib.outputs.SendableSpeedController;
import edu.wpi.first.wpilibj.PIDController;
import edu.wpi.first.wpilibj.GenericHID.Hand;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.InstantCommand;
import edu.wpi.first.wpilibj.command.PIDCommand;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.interfaces.Potentiometer;
import frc.robot.Robot;
import frc.robot.RobotMap;
public class Maflipulator extends Subsystem {
public enum MaflipulatorSide {
kFront, kBack;
}
private final static double FRONT_LOWER_ANGLE = 70;
private final static double FRONT_SCORING_ANGLE = 90;
private final static double FRONT_FLIP_POSITION = FRONT_SCORING_ANGLE;
private final static double FRONT_UPPER_ANGLE = 180;
private final static double BACK_LOWER_ANGLE = 290;
private final static double BACK_SCORING_ANGLE = 270;
private final static double BACK_FLIP_POSITION = BACK_SCORING_ANGLE;
private final static double BACK_UPPER_ANGLE = 180;
private final static double FLIP_MOTOR_SPEED = 0.2;
private MaflipulatorSide currentPosition;
private SendableSpeedController flipMotor;
private Potentiometer anglePot;
double angleCorrection;
PIDController anglePID;
public Maflipulator(final RobotMap.MaflipulatorMap map) { // NOPMD
super();
flipMotor = map.getFlipMotor();
anglePot = map.getMaflipulatorPot();
anglePID = new PIDController(.01, .0009, 0.0, 0.0, anglePot, (double value) -> {
angleCorrection = value;
});
if (anglePot.get() < 180)
currentPosition = MaflipulatorSide.kFront;
else
currentPosition = MaflipulatorSide.kBack;
}
public void addChildren() {
addChild(flipMotor);
addChild(anglePot);
}
@Override
public void initDefaultCommand() {
// Set the default command for a subsystem here.
setDefaultCommand(restrictRotate());
}
protected double restrict(double flipSpeed) {
if (currentPosition == MaflipulatorSide.kFront) {
if (flipSpeed > 0 && anglePot.get() >= FRONT_UPPER_ANGLE) {
flipSpeed = 0;
}
if (flipSpeed < 0 && anglePot.get() <= FRONT_LOWER_ANGLE) {
flipSpeed = 0;
}
} else {
if (flipSpeed > 0 && anglePot.get() <= BACK_UPPER_ANGLE) {
flipSpeed = 0;
}
if (flipSpeed < 0 && anglePot.get() >= BACK_LOWER_ANGLE) {
flipSpeed = 0;
}
}
return flipSpeed;
}
public Command restrictRotate() {
// The command is named "Restrict Rotate" and requires this subsystem.
return new Command("Restrict Rotate", this) {
@Override
protected void execute() {
double flipSpeed = Robot.xBoxCoPilot.getY(Hand.kRight) * FLIP_MOTOR_SPEED;
flipSpeed = restrict(flipSpeed);
flipMotor.set(flipSpeed);
}
@Override
protected boolean isFinished() {
return false;
}
};
}
public Command Flip() {
return new InstantCommand("Flip", this, () -> {
Command moveCommand;
if (currentPosition == MaflipulatorSide.kFront) {
moveCommand = moveToPosition(FRONT_FLIP_POSITION);
currentPosition = MaflipulatorSide.kBack;
} else {
moveCommand = moveToPosition(BACK_FLIP_POSITION);
currentPosition = MaflipulatorSide.kFront;
}
moveCommand.start();
});
}
public Command PIDScoringPosition() {
return new InstantCommand("PID Scoring Position", this, () -> {
Command moveCommand;
if (currentPosition == MaflipulatorSide.kFront)
moveCommand = moveToPosition(FRONT_SCORING_ANGLE);
else
moveCommand = moveToPosition(BACK_SCORING_ANGLE);
moveCommand.start();
});
}
public Command PIDPickupPosition() {
return new InstantCommand("PID Pickup Position", this, () -> {
Command moveCommand;
if (currentPosition == MaflipulatorSide.kFront)
moveCommand = moveToPosition(FRONT_LOWER_ANGLE);
else
moveCommand = moveToPosition(BACK_LOWER_ANGLE);
moveCommand.start();
});
}
public Command moveToPosition(double targetPosition) {
return new PIDCommand("Move to Position", .01, .0009, 0.0, this) {
@Override
protected void initialize() {
anglePID.reset();
anglePID.setSetpoint(targetPosition);
anglePID.enable();
}
@Override
protected boolean isFinished() {
return anglePID.onTarget() && Math.abs(angleCorrection) < 0.1;
}
@Override
protected void end() {
flipMotor.set(0);
}
@Override
protected double returnPIDInput() {
return anglePot.pidGet();
}
@Override
protected void usePIDOutput(double output) {
double flipSpeed = angleCorrection;
flipSpeed = restrict(flipSpeed);
flipMotor.set(flipSpeed);
}
};
}
}
|
3e1a553ddb3265eae43ab36c2b8e66804e14a02b | 535 | java | Java | services/richMediaContentSearchService/src/main/java/de/imc/advancedMediaSearch/analytics/SearchAnalytics.java | rwth-acis/ROLE-SDK | 21bf79cae618caae5c6fff20851671bccc74ca92 | [
"Apache-2.0"
] | 6 | 2015-03-13T08:34:14.000Z | 2022-03-05T17:10:09.000Z | services/richMediaContentSearchService/src/main/java/de/imc/advancedMediaSearch/analytics/SearchAnalytics.java | rwth-acis/ROLE-SDK | 21bf79cae618caae5c6fff20851671bccc74ca92 | [
"Apache-2.0"
] | 15 | 2015-03-23T08:40:03.000Z | 2022-01-21T23:14:03.000Z | services/richMediaContentSearchService/src/main/java/de/imc/advancedMediaSearch/analytics/SearchAnalytics.java | rwth-acis/ROLE-SDK | 21bf79cae618caae5c6fff20851671bccc74ca92 | [
"Apache-2.0"
] | 2 | 2015-04-21T15:06:26.000Z | 2017-02-17T14:44:57.000Z | 18.931034 | 72 | 0.73224 | 11,191 | /**
* Project: richContentMediaSearchService
* ROLE-Project
* authors: nnheo@example.com, lyhxr@example.com
* This software uses the GNU GPL
*/
package de.imc.advancedMediaSearch.analytics;
/**
* This Class provides methods and members to measure Search Performance
* @author lyhxr@example.com
*
*/
public class SearchAnalytics {
//TODO:
public AnalyticsObject analyzeCalculationTime(String timerId) {
return null;
}
//TODO:
public AnalyticsObject analyzeRequestTime(String requestId) {
return null;
}
}
|
3e1a558382781f1c430394cd74c47e04d9c3fd8b | 11,812 | java | Java | src/main/java/com/twilio/rest/preview/trustedComms/PhoneCall.java | WillBDaniels/twilio-java | 6bb7bf1e142cb57db4901ba6748e2816e29110ed | [
"MIT"
] | null | null | null | src/main/java/com/twilio/rest/preview/trustedComms/PhoneCall.java | WillBDaniels/twilio-java | 6bb7bf1e142cb57db4901ba6748e2816e29110ed | [
"MIT"
] | null | null | null | src/main/java/com/twilio/rest/preview/trustedComms/PhoneCall.java | WillBDaniels/twilio-java | 6bb7bf1e142cb57db4901ba6748e2816e29110ed | [
"MIT"
] | null | null | null | 30.595855 | 95 | 0.57409 | 11,192 | /**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
package com.twilio.rest.preview.trustedComms;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.twilio.base.Resource;
import com.twilio.converter.DateConverter;
import com.twilio.exception.ApiConnectionException;
import com.twilio.exception.ApiException;
import com.twilio.exception.RestException;
import com.twilio.http.HttpMethod;
import com.twilio.http.Request;
import com.twilio.http.Response;
import com.twilio.http.TwilioRestClient;
import com.twilio.rest.Domains;
import lombok.ToString;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.time.ZonedDateTime;
import java.util.Map;
import java.util.Objects;
/**
* PLEASE NOTE that this class contains preview products that are subject to
* change. Use them with caution. If you currently do not have developer preview
* access, please contact nnheo@example.com.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@ToString
public class PhoneCall extends Resource {
private static final long serialVersionUID = 3046006266217L;
/**
* Create a PhoneCallCreator to execute create.
*
* @param from Twilio number from which to originate the call
* @param to The terminating Phone Number
* @return PhoneCallCreator capable of executing the create
*/
public static PhoneCallCreator creator(final String from,
final String to) {
return new PhoneCallCreator(from, to);
}
/**
* Converts a JSON String into a PhoneCall object using the provided
* ObjectMapper.
*
* @param json Raw JSON String
* @param objectMapper Jackson ObjectMapper
* @return PhoneCall object represented by the provided JSON
*/
public static PhoneCall fromJson(final String json, final ObjectMapper objectMapper) {
// Convert all checked exceptions to Runtime
try {
return objectMapper.readValue(json, PhoneCall.class);
} catch (final JsonMappingException | JsonParseException e) {
throw new ApiException(e.getMessage(), e);
} catch (final IOException e) {
throw new ApiConnectionException(e.getMessage(), e);
}
}
/**
* Converts a JSON InputStream into a PhoneCall object using the provided
* ObjectMapper.
*
* @param json Raw JSON InputStream
* @param objectMapper Jackson ObjectMapper
* @return PhoneCall object represented by the provided JSON
*/
public static PhoneCall fromJson(final InputStream json, final ObjectMapper objectMapper) {
// Convert all checked exceptions to Runtime
try {
return objectMapper.readValue(json, PhoneCall.class);
} catch (final JsonMappingException | JsonParseException e) {
throw new ApiException(e.getMessage(), e);
} catch (final IOException e) {
throw new ApiConnectionException(e.getMessage(), e);
}
}
private final String accountSid;
private final String bgColor;
private final String brandSid;
private final String brandedChannelSid;
private final String businessSid;
private final String callSid;
private final String caller;
private final ZonedDateTime createdAt;
private final String fontColor;
private final String from;
private final String logo;
private final String phoneNumberSid;
private final String reason;
private final String sid;
private final String status;
private final String to;
private final URI url;
private final String useCase;
@JsonCreator
private PhoneCall(@JsonProperty("account_sid")
final String accountSid,
@JsonProperty("bg_color")
final String bgColor,
@JsonProperty("brand_sid")
final String brandSid,
@JsonProperty("branded_channel_sid")
final String brandedChannelSid,
@JsonProperty("business_sid")
final String businessSid,
@JsonProperty("call_sid")
final String callSid,
@JsonProperty("caller")
final String caller,
@JsonProperty("created_at")
final String createdAt,
@JsonProperty("font_color")
final String fontColor,
@JsonProperty("from")
final String from,
@JsonProperty("logo")
final String logo,
@JsonProperty("phone_number_sid")
final String phoneNumberSid,
@JsonProperty("reason")
final String reason,
@JsonProperty("sid")
final String sid,
@JsonProperty("status")
final String status,
@JsonProperty("to")
final String to,
@JsonProperty("url")
final URI url,
@JsonProperty("use_case")
final String useCase) {
this.accountSid = accountSid;
this.bgColor = bgColor;
this.brandSid = brandSid;
this.brandedChannelSid = brandedChannelSid;
this.businessSid = businessSid;
this.callSid = callSid;
this.caller = caller;
this.createdAt = DateConverter.iso8601DateTimeFromString(createdAt);
this.fontColor = fontColor;
this.from = from;
this.logo = logo;
this.phoneNumberSid = phoneNumberSid;
this.reason = reason;
this.sid = sid;
this.status = status;
this.to = to;
this.url = url;
this.useCase = useCase;
}
/**
* Returns Account Sid..
*
* @return Account Sid.
*/
public final String getAccountSid() {
return this.accountSid;
}
/**
* Returns Background color of the current phone call.
*
* @return Background color of the current phone call
*/
public final String getBgColor() {
return this.bgColor;
}
/**
* Returns Brand Sid..
*
* @return Brand Sid.
*/
public final String getBrandSid() {
return this.brandSid;
}
/**
* Returns Branded Channel Sid..
*
* @return Branded Channel Sid.
*/
public final String getBrandedChannelSid() {
return this.brandedChannelSid;
}
/**
* Returns Business Sid..
*
* @return Business Sid.
*/
public final String getBusinessSid() {
return this.businessSid;
}
/**
* Returns A string that uniquely identifies this phone call..
*
* @return A string that uniquely identifies this phone call.
*/
public final String getCallSid() {
return this.callSid;
}
/**
* Returns Caller name of the current phone call.
*
* @return Caller name of the current phone call
*/
public final String getCaller() {
return this.caller;
}
/**
* Returns The date this Current Call was created.
*
* @return The date this Current Call was created
*/
public final ZonedDateTime getCreatedAt() {
return this.createdAt;
}
/**
* Returns Font color of the current phone call.
*
* @return Font color of the current phone call
*/
public final String getFontColor() {
return this.fontColor;
}
/**
* Returns The originating Phone Number.
*
* @return The originating Phone Number
*/
public final String getFrom() {
return this.from;
}
/**
* Returns Logo URL of the caller.
*
* @return Logo URL of the caller
*/
public final String getLogo() {
return this.logo;
}
/**
* Returns Phone Number Sid..
*
* @return Phone Number Sid.
*/
public final String getPhoneNumberSid() {
return this.phoneNumberSid;
}
/**
* Returns The business reason for this phone call.
*
* @return The business reason for this phone call
*/
public final String getReason() {
return this.reason;
}
/**
* Returns A string that uniquely identifies this current branded phone call..
*
* @return A string that uniquely identifies this current branded phone call.
*/
public final String getSid() {
return this.sid;
}
/**
* Returns The status of the current phone call.
*
* @return The status of the current phone call
*/
public final String getStatus() {
return this.status;
}
/**
* Returns The terminating Phone Number.
*
* @return The terminating Phone Number
*/
public final String getTo() {
return this.to;
}
/**
* Returns The URL of this resource..
*
* @return The URL of this resource.
*/
public final URI getUrl() {
return this.url;
}
/**
* Returns The use case for the current phone call.
*
* @return The use case for the current phone call
*/
public final String getUseCase() {
return this.useCase;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PhoneCall other = (PhoneCall) o;
return Objects.equals(accountSid, other.accountSid) &&
Objects.equals(bgColor, other.bgColor) &&
Objects.equals(brandSid, other.brandSid) &&
Objects.equals(brandedChannelSid, other.brandedChannelSid) &&
Objects.equals(businessSid, other.businessSid) &&
Objects.equals(callSid, other.callSid) &&
Objects.equals(caller, other.caller) &&
Objects.equals(createdAt, other.createdAt) &&
Objects.equals(fontColor, other.fontColor) &&
Objects.equals(from, other.from) &&
Objects.equals(logo, other.logo) &&
Objects.equals(phoneNumberSid, other.phoneNumberSid) &&
Objects.equals(reason, other.reason) &&
Objects.equals(sid, other.sid) &&
Objects.equals(status, other.status) &&
Objects.equals(to, other.to) &&
Objects.equals(url, other.url) &&
Objects.equals(useCase, other.useCase);
}
@Override
public int hashCode() {
return Objects.hash(accountSid,
bgColor,
brandSid,
brandedChannelSid,
businessSid,
callSid,
caller,
createdAt,
fontColor,
from,
logo,
phoneNumberSid,
reason,
sid,
status,
to,
url,
useCase);
}
} |
3e1a55ab1c9116550d04c2e5cbf760a913c5181c | 6,133 | java | Java | commonsdk/src/main/java/com/common/widget/ImageTextCell.java | puming/ArchitectureNew | b054d1035679d8ba3439b41863d45be025210535 | [
"Apache-2.0"
] | 8 | 2020-03-28T08:24:49.000Z | 2021-07-09T07:54:33.000Z | commonsdk/src/main/java/com/common/widget/ImageTextCell.java | puming/ArchitectureNew | b054d1035679d8ba3439b41863d45be025210535 | [
"Apache-2.0"
] | null | null | null | commonsdk/src/main/java/com/common/widget/ImageTextCell.java | puming/ArchitectureNew | b054d1035679d8ba3439b41863d45be025210535 | [
"Apache-2.0"
] | null | null | null | 35.045714 | 114 | 0.645524 | 11,193 | package com.common.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.common.R;
/**
* @author pm
* @date 18-1-10
*/
public class ImageTextCell extends ConstraintLayout {
private View view;
public ImageView mIcon;
public TextView mText;
public ImageTextCell(Context context) {
this(context, null);
}
public ImageTextCell(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public ImageTextCell(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setClipChildren(true);
setFocusable(true);
setFocusableInTouchMode(true);
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.image_text_cell, this, true);
mIcon = view.findViewById(R.id.icon);
mText = view.findViewById(R.id.text);
}
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ImageTextCell, defStyleAttr, 0);
Drawable icon = typedArray.getDrawable(R.styleable.ImageTextCell_icon);
int iconWidth = (int) typedArray.getDimension(R.styleable.ImageTextCell_icon_width,
dp2px(getContext(), 0));
int iconHeight = (int) typedArray.getDimension(R.styleable.ImageTextCell_icon_height,
dp2px(getContext(), 0));
String text = typedArray.getString(R.styleable.ImageTextCell_text);
int textMaxWidth = (int) typedArray.getDimension(R.styleable.ImageTextCell_text_max_width,
dp2px(getContext(), 0));
int textMaxHeight = (int) typedArray.getDimension(R.styleable.ImageTextCell_text_max_height,
dp2px(getContext(), 0));
int topMargin = (int) typedArray.getDimension(R.styleable.ImageTextCell_top_margin,
dp2px(getContext(), 8));
int bottomMargin = (int) typedArray.getDimension(R.styleable.ImageTextCell_bottom_margin,
dp2px(getContext(), 8));
int defColor = 0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
defColor = getResources().getColor(R.color.color_white_eighty, null);
} else {
defColor = getResources().getColor(R.color.color_white_eighty);
}
int textColor = typedArray.getColor(R.styleable.ImageTextCell_text_color, defColor);
float textSize = typedArray.getDimension(R.styleable.ImageTextCell_text_size,
14);
typedArray.recycle();
MarginLayoutParams iconParams = (MarginLayoutParams) mIcon.getLayoutParams();
if (iconHeight != 0) {
iconParams.height = iconHeight;
}
if (iconWidth != 0) {
iconParams.width = iconWidth;
}
iconParams.setMargins(0, 0, 0, bottomMargin);
mIcon.setLayoutParams(iconParams);
mIcon.setImageDrawable(icon);
MarginLayoutParams titleParams = (MarginLayoutParams) mText.getLayoutParams();
titleParams.setMargins(0, topMargin, 0, 0);
if (textMaxWidth != 0) {
mText.setMaxWidth(textMaxWidth);
}
if (textMaxHeight != 0) {
mText.setMaxHeight(textMaxHeight);
}
mText.setText(text);
mText.setLayoutParams(titleParams);
mText.setTextColor(textColor);
mText.setTextSize(textSize);
}
private int dp2px(Context context, int dp) {
return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dp, context.getResources().getDisplayMetrics()) + 0.5f);
}
@Override
public void onHoverChanged(boolean hovered) {
super.onHoverChanged(hovered);
if (hovered) {
mText.setSelected(true);
mText.setEllipsize(TextUtils.TruncateAt.MARQUEE);
// mItemCardView.onHoverChanged(true);
} else {
mText.setEllipsize(TextUtils.TruncateAt.END);
// mItemCardView.onHoverChanged(false);
}
}
@Override
public boolean onHoverEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_HOVER_ENTER:
requestFocusFromTouch();
setHovered(true);
break;
case MotionEvent.ACTION_HOVER_MOVE:
break;
case MotionEvent.ACTION_HOVER_EXIT:
setHovered(false);
break;
default:
break;
}
return true;
}
@Override
protected void onFocusChanged(boolean gainFocus, int direction, @Nullable Rect previouslyFocusedRect) {
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
setHovered(gainFocus);
}
@Override
public boolean onInterceptHoverEvent(MotionEvent event) {
return true;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
public void setIcon(Object object) {
if (object instanceof Integer) {
int resId = (Integer) object;
mIcon.setImageResource(resId);
} else if (object instanceof Bitmap) {
Bitmap bitmap = (Bitmap) object;
mIcon.setImageBitmap(bitmap);
} else if (object instanceof Drawable) {
Drawable drawable = (Drawable) object;
mIcon.setImageDrawable(drawable);
}
}
public void setTitle(Object object) {
if (object instanceof CharSequence) {
CharSequence title = (CharSequence) object;
mText.setText(title);
}
}
}
|
3e1a55f14b687769bf68d9d84b5e929387abbd7c | 8,928 | java | Java | server/nswy-api-dev/nswy-member-service/src/main/java/com/ovit/nswy/member/service/impl/ProxyServiceImpl.java | tracy4262/zhenxingxiangcun | ea7f947814e4fc46ae872bb3477a5fa263c0a7a6 | [
"MIT"
] | 2 | 2020-10-26T04:34:07.000Z | 2021-02-24T03:02:36.000Z | server/nswy-api-dev/nswy-member-service/src/main/java/com/ovit/nswy/member/service/impl/ProxyServiceImpl.java | tracy4262/zhenxingxiangcun | ea7f947814e4fc46ae872bb3477a5fa263c0a7a6 | [
"MIT"
] | 18 | 2020-09-09T19:49:32.000Z | 2022-03-02T08:04:17.000Z | server/nswy-api-dev/nswy-member-service/src/main/java/com/ovit/nswy/member/service/impl/ProxyServiceImpl.java | tracy4262/zhenxingxiangcun | ea7f947814e4fc46ae872bb3477a5fa263c0a7a6 | [
"MIT"
] | 3 | 2019-09-25T07:05:35.000Z | 2021-01-17T08:06:39.000Z | 36.292683 | 145 | 0.614135 | 11,194 | package com.ovit.nswy.member.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ovit.nswy.member.mapper.ProxyCorpInfoMapper;
import com.ovit.nswy.member.mapper.ProxyGovInfoMapper;
import com.ovit.nswy.member.mapper.ProxyMapper;
import com.ovit.nswy.member.model.ProxyCorpInfo;
import com.ovit.nswy.member.service.ProxyService;
import com.ovit.nswy.member.util.JsonToStringUtils;
import com.ovit.nswy.member.util.PageUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class ProxyServiceImpl implements ProxyService {
@Autowired
private ProxyMapper proxyMapper;
@Autowired
private ProxyCorpInfoMapper proxyCorpInfoMapper;
@Autowired
private ProxyGovInfoMapper proxyGovInfoMapper;
private Logger logger = LogManager.getLogger(ProxyServiceImpl.class);
@Override
public PageInfo<List<Map<String,Object>>> queryList(Map<String, Object> params) {
PageUtils.initPage(params);
List<Map<String,Object>> list = proxyMapper.queryList(params);
return new PageInfo(list);
}
@Override
public void delProxy(Map<String, Object> params) {
try {
//--flag 0 企业 1机关
String flag = MapUtils.getString(params,"flag");
String TABLE_NAME;
String INFO_NAME;
if ("0".equals(flag)) {
TABLE_NAME = "proxy_corp_info";
INFO_NAME = "corp_info";
} else {
TABLE_NAME = "proxy_gov_info";
INFO_NAME = "gov_info";
}
params.put("TABLE_NAME",TABLE_NAME);
params.put("INFO_NAME",INFO_NAME);
proxyMapper.updateInfos(params);
Map<String,Object> map = proxyMapper.findInfoAccount(params);
String account = MapUtils.getString(map,"login_account");
params.put("login_account",account);
params.put("login_passwd",RandomStringUtils.randomAlphanumeric(6).toLowerCase());
proxyMapper.updateLoginPassWd(params);
proxyMapper.delProxy(params);
} catch (Exception e) {
logger.error(e);
}
}
@Override
public void delProxyInfo(Map<String, Object> params) {
try {
//--flag 0 企业 1机关
String flag = MapUtils.getString(params,"flag");
String TABLE_NAME;
if ("0".equals(flag)) {
TABLE_NAME = "corp_info";
} else {
TABLE_NAME = "gov_info";
}
params.put("TABLE_NAME",TABLE_NAME);
proxyMapper.delLoginUser(params);
proxyMapper.delProxy(params);
//取消代理
this.delProxy(params);
} catch (Exception e) {
logger.error(e);
}
}
@Override
public PageInfo<Map<String, Object>> queryStatus(Map<String, Object> params) {
PageHelper.offsetPage(Integer.parseInt(String.valueOf(params.get("pageNum"))), Integer.parseInt(String.valueOf(params.get("pageSize"))));
List<Map<String, Object>> list = null;
try {
list = proxyMapper.queryStatus(params);
} catch (Exception e) {
logger.error(e);
}
return new PageInfo<>(list);
}
@Override
public Map<String, Object> queryStatusDetail(Map<String, Object> params) {
Map<String, Object> map = new HashMap<>();
try {
// flag 0查询企业 1查询机关
String flag = MapUtils.getString(params,"flag");
if("0".equals(flag)){
map = proxyMapper.queryStatusCorpDetail(params);
}else{
map = proxyMapper.queryStatusGovDetail(params);
}
} catch (Exception e) {
logger.error(e);
}
return map;
}
@Override
public PageInfo<Map<String,Object>> queryInfo(Map<String, Object> params){
PageHelper.offsetPage(Integer.parseInt(String.valueOf(params.get("pageNum"))), Integer.parseInt(String.valueOf(params.get("pageSize"))));
List<Map<String, Object>> list = null;
try {
list = proxyMapper.queryInfo(params);
} catch (Exception e) {
logger.error(e);
}
return new PageInfo<>(list);
}
@Override
public Map<String, Object> queryInfoDetail(Map<String, Object> params) {
Map<String, Object> map = new HashMap<>();
try {
// flag 0查询企业 1查询机关
String flag = MapUtils.getString(params,"flag");
if("0".equals(flag)){
map = proxyMapper.queryInfoCorpDetail(params);
}else{
map = proxyMapper.queryInfoGovDetail(params);
}
} catch (Exception e) {
logger.error(e);
}
return map;
}
@Override
public Map<String, Object> queryStatusById(Map<String, Object> params) {
Map<String, Object> map = new HashMap<>();
try {
map = proxyMapper.queryStatusById(params);
} catch (Exception e) {
logger.error(e);
}
return map;
}
@Override
public void delProxyById(Map<String, Object> params) {
List<Integer> ids = JSONArray.parseArray(params.get("ids").toString(), Integer.class);
try {
for (Integer id : ids) {
proxyMapper.delProxyById(id);
}
} catch (Exception e) {
logger.error(e);
}
}
@Override
public void addProxy(Map<String, Object> params) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String time = String.valueOf(LocalDateTime.now().format(formatter));
//flag 为0 企业 flag 为1机关 flag 2乡村
String flag = MapUtils.getString(params,"flag");
Map<String,Object> map = new HashMap<String,Object>();
map.put("id",MapUtils.getString(params,"info_id"));
if("0".equals(flag)){
String jsonString = JSON.toJSONString(params);
ProxyCorpInfo corpInfo = JSON.parseObject(jsonString,ProxyCorpInfo.class);
//身份证照片正反面
corpInfo.setIdentificationCardUrl(JsonToStringUtils.initJson(params,"identification_card_url"));
//营业期限
corpInfo.setBusnissTerm(JsonToStringUtils.initJson(params,"busniss_term"));
//企业工商营业执照
corpInfo.setBusinessLicenseUrl(JsonToStringUtils.initJson(params,"business_license_url"));
proxyCorpInfoMapper.insert(corpInfo);
map.put("TABLE_NAME","corp_info");
}else if("1".equals(flag)){
params.put("country_type","3");
params.put("qualification_certificate_picture_list",JsonToStringUtils.initJson(params,"qualification_certificate_picture_list"));
params.put("unit_person_picture_list",JsonToStringUtils.initJson(params,"unit_person_picture_list"));
proxyGovInfoMapper.insert(params);
map.put("TABLE_NAME","gov_info");
}else if("2".equals(flag)){
params.put("country_type","5");
params.put("qualification_certificate_picture_list","");
params.put("unit_person_picture_list",JsonToStringUtils.initJson(params,"unit_person_picture_list"));
proxyGovInfoMapper.insert(params);
map.put("TABLE_NAME","gov_info");
}
proxyMapper.updateInfo(map);
}
@Override
public Map<String, Object> queryPassWord(Map<String, Object> params) {
try {
Map<String, Object> map = proxyMapper.queryPassWord(params);
if (map.get("passWord") != null) {
}
} catch (Exception e) {
logger.error(e);
}
return null;
}
@Override
public Map<String, Object> queryNameFromCorpOrGov(Map<String, Object> params) {
return proxyMapper.queryNameFromCorpOrGov(params);
}
@Override
public Map<String, Object> queryInfoById(Map<String, Object> params) {
return proxyMapper.queryInfoById(params);
}
@Override
public List<Map<String, Object>> queryProxyList(Map<String, Object> params) {
return proxyMapper.queryList(params);
}
} |
3e1a565ce6b2a27d299de6e07e08fa1e1fd5733b | 2,626 | java | Java | client-app/src/main/java/sample/web/CustomAuthorizationRequestResolver.java | jzheaux/springone2018 | 392a1eb724b7447928c750fb2e47c22ed26d144e | [
"Apache-2.0"
] | 45 | 2018-09-25T17:56:51.000Z | 2021-10-17T03:00:18.000Z | client-app/src/main/java/sample/web/CustomAuthorizationRequestResolver.java | jzheaux/springone2018 | 392a1eb724b7447928c750fb2e47c22ed26d144e | [
"Apache-2.0"
] | 2 | 2018-10-31T11:51:24.000Z | 2020-05-01T06:32:44.000Z | client-app/src/main/java/sample/web/CustomAuthorizationRequestResolver.java | jzheaux/springone2018 | 392a1eb724b7447928c750fb2e47c22ed26d144e | [
"Apache-2.0"
] | 29 | 2018-09-25T18:14:52.000Z | 2021-11-11T10:00:01.000Z | 40.4 | 113 | 0.819117 | 11,195 | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.web;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizationRequestResolver;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestResolver;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* @author Joe Grandja
*/
public class CustomAuthorizationRequestResolver implements OAuth2AuthorizationRequestResolver {
private final OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver;
public CustomAuthorizationRequestResolver(ClientRegistrationRepository clientRegistrationRepository) {
this.defaultAuthorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(
clientRegistrationRepository, "/oauth2/authorization");
}
@Override
public OAuth2AuthorizationRequest resolve(HttpServletRequest request) {
OAuth2AuthorizationRequest authorizationRequest =
this.defaultAuthorizationRequestResolver.resolve(request);
if (authorizationRequest != null) {
return customAuthorizationRequest(authorizationRequest);
}
return authorizationRequest;
}
@Override
public OAuth2AuthorizationRequest resolve(HttpServletRequest request, String clientRegistrationId) {
OAuth2AuthorizationRequest authorizationRequest =
this.defaultAuthorizationRequestResolver.resolve(request, clientRegistrationId);
if (authorizationRequest != null) {
return customAuthorizationRequest(authorizationRequest);
}
return authorizationRequest;
}
private OAuth2AuthorizationRequest customAuthorizationRequest(OAuth2AuthorizationRequest authorizationRequest) {
Set<String> scopes = new LinkedHashSet<>(authorizationRequest.getScopes());
scopes.add("contacts");
return OAuth2AuthorizationRequest.from(authorizationRequest)
.scopes(scopes)
.build();
}
} |
3e1a57eaf4b3f0e983691fefae4313d122550c60 | 1,897 | java | Java | src/ql/src/java/org/apache/hadoop/hive/ql/io/HiveRecordReader.java | pentaho/hive-0.7.0 | aeefdef0f9f262b7618bed1eeff71c902e013ffa | [
"Apache-2.0"
] | null | null | null | src/ql/src/java/org/apache/hadoop/hive/ql/io/HiveRecordReader.java | pentaho/hive-0.7.0 | aeefdef0f9f262b7618bed1eeff71c902e013ffa | [
"Apache-2.0"
] | null | null | null | src/ql/src/java/org/apache/hadoop/hive/ql/io/HiveRecordReader.java | pentaho/hive-0.7.0 | aeefdef0f9f262b7618bed1eeff71c902e013ffa | [
"Apache-2.0"
] | 12 | 2015-04-18T00:21:12.000Z | 2021-08-13T01:36:57.000Z | 27.492754 | 79 | 0.740116 | 11,196 | /*!
* Copyright 2010 - 2013 Pentaho Corporation. 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 org.apache.hadoop.hive.ql.io;
import java.io.IOException;
import org.apache.hadoop.hive.ql.exec.ExecMapper;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapred.RecordReader;
/**
* HiveRecordReader is a simple wrapper on RecordReader. It allows us to stop
* reading the data when some global flag ExecMapper.getDone() is set.
*/
public class HiveRecordReader<K extends WritableComparable, V extends Writable>
extends HiveContextAwareRecordReader<K, V> {
private final RecordReader recordReader;
public HiveRecordReader(RecordReader recordReader) throws IOException {
this.recordReader = recordReader;
}
public void doClose() throws IOException {
recordReader.close();
}
public K createKey() {
return (K) recordReader.createKey();
}
public V createValue() {
return (V) recordReader.createValue();
}
public long getPos() throws IOException {
return recordReader.getPos();
}
public float getProgress() throws IOException {
return recordReader.getProgress();
}
@Override
public boolean doNext(K key, V value) throws IOException {
if (ExecMapper.getDone()) {
return false;
}
return recordReader.next(key, value);
}
}
|
3e1a5802d8c501fc1236ba6d6fc4b620a4ace769 | 320 | java | Java | app/src/main/java/distudios/at/carcassonne/engine/logic/ZergRace.java | GustavAT/Carcassonne- | d8752fe6b0843fa690d2eab9c1deeb70fd6ef2c8 | [
"MIT"
] | 3 | 2018-03-20T09:41:52.000Z | 2018-04-08T15:35:32.000Z | app/src/main/java/distudios/at/carcassonne/engine/logic/ZergRace.java | GustavAT/Carcassonne- | d8752fe6b0843fa690d2eab9c1deeb70fd6ef2c8 | [
"MIT"
] | 23 | 2018-03-22T14:06:08.000Z | 2018-06-16T17:05:12.000Z | app/src/main/java/distudios/at/carcassonne/engine/logic/ZergRace.java | GustavAT/Carcassonne- | d8752fe6b0843fa690d2eab9c1deeb70fd6ef2c8 | [
"MIT"
] | null | null | null | 24.615385 | 54 | 0.66875 | 11,197 | package distudios.at.carcassonne.engine.logic;
public class ZergRace extends Player {
// ZERG Race is weak but can overwhelm other races
public ZergRace(int playerID) {
super(playerID);
this.peeps = 20;
this.scoreMultiplierTotal = 0.5f;
this.canSetMultiplePeeps = true;
}
}
|
3e1a5850cdb8b4dac201a3b5b7f62c87695de19e | 1,704 | java | Java | servers/zts/src/main/java/com/yahoo/athenz/zts/utils/IPPrefix.java | tatyano/athenz | 372ebdb1ecd33f9e67587534ce26837e15780b21 | [
"Apache-2.0"
] | 1 | 2019-05-07T00:19:54.000Z | 2019-05-07T00:19:54.000Z | servers/zts/src/main/java/com/yahoo/athenz/zts/utils/IPPrefix.java | tatyano/athenz | 372ebdb1ecd33f9e67587534ce26837e15780b21 | [
"Apache-2.0"
] | null | null | null | servers/zts/src/main/java/com/yahoo/athenz/zts/utils/IPPrefix.java | tatyano/athenz | 372ebdb1ecd33f9e67587534ce26837e15780b21 | [
"Apache-2.0"
] | 3 | 2017-01-15T23:41:51.000Z | 2019-04-17T07:58:08.000Z | 26.215385 | 75 | 0.693662 | 11,198 | /*
* Copyright 2018 Oath Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yahoo.athenz.zts.utils;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(include = JsonSerialize.Inclusion.ALWAYS)
public class IPPrefix {
private String ipv4Prefix;
private String ipv6Prefix;
private String region;
private String service;
@JsonProperty("ip_prefix")
public String getIpv4Prefix() {
return ipv4Prefix;
}
@JsonProperty("ip_prefix")
public void setIpv4Prefix(String ipv4Prefix) {
this.ipv4Prefix = ipv4Prefix;
}
@JsonProperty("ipv6_prefix")
public String getIpv6Prefix() {
return ipv6Prefix;
}
@JsonProperty("ipv6_prefix")
public void setIpv6Prefix(String ipv6Prefix) {
this.ipv6Prefix = ipv6Prefix;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
}
|
3e1a58b4559bb14166647f6073bc53135836d1dd | 41,924 | java | Java | src/main/java/GeoFlink/spatialOperators/TAggregateQuery.java | RackiLovro/UVPPVP | 394f98318883658c5e70c3ef04c5e8a182909f0d | [
"Apache-2.0"
] | null | null | null | src/main/java/GeoFlink/spatialOperators/TAggregateQuery.java | RackiLovro/UVPPVP | 394f98318883658c5e70c3ef04c5e8a182909f0d | [
"Apache-2.0"
] | null | null | null | src/main/java/GeoFlink/spatialOperators/TAggregateQuery.java | RackiLovro/UVPPVP | 394f98318883658c5e70c3ef04c5e8a182909f0d | [
"Apache-2.0"
] | 1 | 2021-10-06T02:30:16.000Z | 2021-10-06T02:30:16.000Z | 50.510843 | 235 | 0.600205 | 11,199 | package GeoFlink.spatialOperators;
import GeoFlink.spatialObjects.Point;
import GeoFlink.utils.HelperClass;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.api.java.tuple.Tuple4;
import org.apache.flink.api.java.tuple.Tuple5;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class TAggregateQuery implements Serializable {
//--------------- TSpatialHeatmapAggregateQuery Windowed -----------------//
//Outputs only when there is a positive value
public static DataStream<Tuple5<String, Integer, Long, Long, HashMap<String, Long>>> TSpatialHeatmapAggregateQuery(DataStream<Point> pointStream, String aggregateFunction, String windowType, long windowSize, long windowSlideStep) {
// Filtering out the cells which do not fall into the grid cells
DataStream<Point> spatialStreamWithoutNullCellID = pointStream.filter(new FilterFunction<Point>() {
@Override
public boolean filter(Point p) throws Exception {
return (p.gridID != null);
}
}).startNewChain();
// Spatial stream with Timestamps and Watermarks
// Max Allowed Lateness: windowSize
DataStream<Point> spatialStreamWithTsAndWm =
spatialStreamWithoutNullCellID.assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<Point>(Time.seconds(windowSize)) {
@Override
public long extractTimestamp(Point p) {
return p.timeStampMillisec;
}
});
if(windowType.equalsIgnoreCase("COUNT")){
DataStream<Tuple5<String, Integer, Long, Long, HashMap<String, Long>>> cWindowedCellBasedStayTime = spatialStreamWithTsAndWm
.keyBy(new gridCellKeySelector())
.countWindow(windowSize, windowSlideStep)
.process(new CountWindowProcessFunction(aggregateFunction)).name("Count Window");
return cWindowedCellBasedStayTime;
}
else { // Default TIME Window
DataStream<Tuple5<String, Integer, Long, Long, HashMap<String, Long>>> tWindowedCellBasedStayTime = spatialStreamWithTsAndWm
.keyBy(new gridCellKeySelector())
//.window(SlidingProcessingTimeWindows.of(Time.seconds(windowSize), Time.seconds(windowSlideStep)))
.window(SlidingEventTimeWindows.of(Time.seconds(windowSize), Time.seconds(windowSlideStep)))
.process(new TimeWindowProcessFunction(aggregateFunction)).name("Time Window");
return tWindowedCellBasedStayTime;
}
}
//--------------- TSpatialHeatmapAggregateQuery Inception -----------------//
// Outputs a tuple containing cellID, number of objects in the cell and its requested aggregate
//public static DataStream<Tuple3<String, Integer, HashMap<String, Long>>> TSpatialHeatmapAggregateQuery(DataStream<Point> pointStream, String aggregateFunction) {
public static DataStream<Tuple4<String, Integer, HashMap<String, Long>, Long>> TSpatialHeatmapAggregateQuery(DataStream<Point> pointStream, String aggregateFunction, Long inactiveTrajDeletionThreshold) {
// Filtering out the cells which do not fall into the grid cells
DataStream<Point> spatialStreamWithoutNullCellID = pointStream.filter(new FilterFunction<Point>() {
@Override
public boolean filter(Point p) throws Exception {
return (p.gridID != null);
}
}).startNewChain();
//DataStream<Tuple3<String, Integer, HashMap<String, Long>>> cWindowedCellBasedStayTime = spatialStreamWithoutNullCellID
DataStream<Tuple4<String, Integer, HashMap<String, Long>, Long>> cWindowedCellBasedStayTime = spatialStreamWithoutNullCellID
.keyBy(new gridCellKeySelector())
.map(new THeatmapAggregateQueryMapFunction(aggregateFunction, inactiveTrajDeletionThreshold));
return cWindowedCellBasedStayTime;
}
// User Defined Classes
// Key selector
public static class gridCellKeySelector implements KeySelector<Point,String> {
@Override
public String getKey(Point p) throws Exception {
return p.gridID;
}
}
//public static class THeatmapAggregateQueryMapFunction extends RichMapFunction<Point, Tuple3<String, Integer, HashMap<String, Long>>> {
public static class THeatmapAggregateQueryMapFunction extends RichMapFunction<Point, Tuple4<String, Integer, HashMap<String, Long>, Long>> {
private MapState<String, Long> minTimestampTrackerIDMapState;
private MapState<String, Long> maxTimestampTrackerIDMapState;
//ctor
public THeatmapAggregateQueryMapFunction() {};
String aggregateFunction;
Long inactiveTrajDeletionThreshold;
public THeatmapAggregateQueryMapFunction(String aggregateFunction, Long inactiveTrajDeletionThreshold){
this.aggregateFunction = aggregateFunction;
this.inactiveTrajDeletionThreshold = inactiveTrajDeletionThreshold;
}
@Override
public void open(Configuration config) {
MapStateDescriptor<String, Long> minTimestampTrackerIDDescriptor = new MapStateDescriptor<String, Long>(
"minTimestampTrackerIDDescriptor", // state name
BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.LONG_TYPE_INFO);
MapStateDescriptor<String, Long> maxTimestampTrackerIDDescriptor = new MapStateDescriptor<String, Long>(
"maxTimestampTrackerIDDescriptor", // state name
BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.LONG_TYPE_INFO);
this.minTimestampTrackerIDMapState = getRuntimeContext().getMapState(minTimestampTrackerIDDescriptor);
this.maxTimestampTrackerIDMapState = getRuntimeContext().getMapState(maxTimestampTrackerIDDescriptor);
}
@Override
// Outputs a tuple containing cellID, number of objects in the cell and its requested aggregate
//public Tuple3<String, Integer, HashMap<String, Long>> map(Point p) throws Exception {
public Tuple4<String, Integer, HashMap<String, Long>, Long> map(Point p) throws Exception {
// HashMap<TrackerID, timestamp>
//HashMap<String, Long> minTimestampTrackerID = new HashMap<String, Long>();
//HashMap<String, Long> maxTimestampTrackerID = new HashMap<String, Long>();
// HashMap <TrackerID, TrajLength>
HashMap<String, Long> trackerIDTrajLength = new HashMap<String, Long>();
// Restoring states from MapStates (if exist)
/*
for (Map.Entry<String, Long> entry : minTimestampTrackerIDMapState.entries()) {
String objID = entry.getKey();
Long minTimestamp = entry.getValue();
Long maxTimestamp = maxTimestampTrackerIDMapState.get(objID);
minTimestampTrackerID.put(objID, minTimestamp);
maxTimestampTrackerID.put(objID, maxTimestamp);
}
*/
// Updating maps using new data/point
//Long currMinTimestamp_ = minTimestampTrackerID.get(p.objID);
//Long currMaxTimestamp_ = maxTimestampTrackerID.get(p.objID);
Long currMinTimestamp_ = minTimestampTrackerIDMapState.get(p.objID);
Long currMaxTimestamp_ = maxTimestampTrackerIDMapState.get(p.objID);
/*
if (currMinTimestamp_ != null) { // If exists update else insert
if (p.timeStampMillisec < currMinTimestamp_) {
minTimestampTrackerID.replace(p.objID, p.timeStampMillisec);
}
if (p.timeStampMillisec > currMaxTimestamp_) {
maxTimestampTrackerID.replace(p.objID, p.timeStampMillisec);
}
} else {
minTimestampTrackerID.put(p.objID, p.timeStampMillisec);
maxTimestampTrackerID.put(p.objID, p.timeStampMillisec);
}*/
if (currMinTimestamp_ != null) { // If exists update else insert
if (p.timeStampMillisec < currMinTimestamp_) {
minTimestampTrackerIDMapState.put(p.objID, p.timeStampMillisec);
}
if (p.timeStampMillisec > currMaxTimestamp_) {
maxTimestampTrackerIDMapState.put(p.objID, p.timeStampMillisec);
}
} else {
minTimestampTrackerIDMapState.put(p.objID, p.timeStampMillisec);
maxTimestampTrackerIDMapState.put(p.objID, p.timeStampMillisec);
}
Date date = new Date();
Long latency = date.getTime() - p.ingestionTime;
//System.out.println(latency);
// Updating the state variables
//minTimestampTrackerIDMapState.clear();
//maxTimestampTrackerIDMapState.clear();
//minTimestampTrackerIDMapState.putAll(minTimestampTrackerID);
//maxTimestampTrackerIDMapState.putAll(maxTimestampTrackerID);
// Generating Output based on aggregateFunction variable
if(this.aggregateFunction.equalsIgnoreCase("ALL")){
trackerIDTrajLength.clear();
for (Map.Entry<String, Long> entry : minTimestampTrackerIDMapState.entries()) {
String objID = entry.getKey();
Long currMinTimestamp = entry.getValue();
Long currMaxTimestamp = maxTimestampTrackerIDMapState.get(objID);
// Deleting halted trajectories
deleteHaltedTrajectories(currMaxTimestamp, inactiveTrajDeletionThreshold, objID);
//Populating results
trackerIDTrajLength.put(objID, (currMaxTimestamp-currMinTimestamp));
}
//return Tuple3.of(p.gridID, trackerIDTrajLength.size(), trackerIDTrajLength);
return Tuple4.of(p.gridID, trackerIDTrajLength.size(), trackerIDTrajLength, latency);
}
else if(this.aggregateFunction.equalsIgnoreCase("SUM") || this.aggregateFunction.equalsIgnoreCase("AVG")){
trackerIDTrajLength.clear();
Long sumTrajLength = 0L;
int counter = 0;
for (Map.Entry<String, Long> entry : minTimestampTrackerIDMapState.entries()) {
String objID = entry.getKey();
Long currMinTimestamp = entry.getValue();
Long currMaxTimestamp = maxTimestampTrackerIDMapState.get(objID);
// Deleting halted trajectories
deleteHaltedTrajectories(currMaxTimestamp, inactiveTrajDeletionThreshold, objID);
counter++;
sumTrajLength += (currMaxTimestamp-currMinTimestamp);
}
if(this.aggregateFunction.equalsIgnoreCase("SUM"))
{
trackerIDTrajLength.put("", sumTrajLength);
//return Tuple3.of(p.gridID, counter, trackerIDTrajLength);
return Tuple4.of(p.gridID, counter, trackerIDTrajLength, latency);
}
else // AVG
{
Long avgTrajLength = (Long)Math.round((sumTrajLength * 1.0)/(counter * 1.0));
trackerIDTrajLength.put("", avgTrajLength);
//return Tuple3.of(p.gridID, counter, trackerIDTrajLength);
return Tuple4.of(p.gridID, counter, trackerIDTrajLength, latency);
}
}
else if(this.aggregateFunction.equalsIgnoreCase("MIN")){
Long minTrajLength = Long.MAX_VALUE;
String minTrajLengthObjID = "";
trackerIDTrajLength.clear();
int counter = 0;
for (Map.Entry<String, Long> entry : minTimestampTrackerIDMapState.entries()) {
String objID = entry.getKey();
Long currMinTimestamp = entry.getValue();
Long currMaxTimestamp = maxTimestampTrackerIDMapState.get(objID);
// Deleting halted trajectories
deleteHaltedTrajectories(currMaxTimestamp, inactiveTrajDeletionThreshold, objID);
counter++;
Long trajLength = currMaxTimestamp-currMinTimestamp;
if(trajLength < minTrajLength){
minTrajLength = trajLength;
minTrajLengthObjID = objID;
}
}
trackerIDTrajLength.put(minTrajLengthObjID, minTrajLength);
//return Tuple3.of(p.gridID, counter, trackerIDTrajLength);
return Tuple4.of(p.gridID, counter, trackerIDTrajLength, latency);
}
else if(this.aggregateFunction.equalsIgnoreCase("MAX")){
Long maxTrajLength = Long.MIN_VALUE;
String maxTrajLengthObjID = "";
trackerIDTrajLength.clear();
int counter = 0;
for (Map.Entry<String, Long> entry : minTimestampTrackerIDMapState.entries()) {
String objID = entry.getKey();
Long currMinTimestamp = entry.getValue();
Long currMaxTimestamp = maxTimestampTrackerIDMapState.get(objID);
// Deleting halted trajectories
deleteHaltedTrajectories(currMaxTimestamp, inactiveTrajDeletionThreshold, objID);
counter++;
Long trajLength = currMaxTimestamp-currMinTimestamp;
if(trajLength > maxTrajLength){
maxTrajLength = trajLength;
maxTrajLengthObjID = objID;
}
}
trackerIDTrajLength.put(maxTrajLengthObjID, maxTrajLength);
//return Tuple3.of(p.gridID, counter, trackerIDTrajLength);
return Tuple4.of(p.gridID, counter, trackerIDTrajLength, latency);
}
else{
trackerIDTrajLength.clear();
for (Map.Entry<String, Long> entry : minTimestampTrackerIDMapState.entries()) {
String objID = entry.getKey();
Long currMinTimestamp = entry.getValue();
Long currMaxTimestamp = maxTimestampTrackerIDMapState.get(objID);
trackerIDTrajLength.put(objID, (currMaxTimestamp-currMinTimestamp));
}
//return Tuple3.of(p.gridID, trackerIDTrajLength.size(), trackerIDTrajLength);
return Tuple4.of(p.gridID, trackerIDTrajLength.size(), trackerIDTrajLength, latency);
}
/*
if(this.aggregateFunction.equalsIgnoreCase("ALL")){
trackerIDTrajLength.clear();
for (Map.Entry<String, Long> entry : minTimestampTrackerID.entrySet()) {
String objID = entry.getKey();
Long currMinTimestamp = entry.getValue();
Long currMaxTimestamp = maxTimestampTrackerID.get(objID);
//Populating results
trackerIDTrajLength.put(objID, (currMaxTimestamp-currMinTimestamp));
}
return Tuple2.of(minTimestampTrackerID.size(), trackerIDTrajLength));
}
else if(this.aggregateFunction.equalsIgnoreCase("SUM") || this.aggregateFunction.equalsIgnoreCase("AVG")){
trackerIDTrajLength.clear();
Long sumTrajLength = 0L;
for (Map.Entry<String, Long> entry : minTimestampTrackerID.entrySet()) {
String objID = entry.getKey();
Long currMinTimestamp = entry.getValue();
Long currMaxTimestamp = maxTimestampTrackerID.get(objID);
sumTrajLength += (currMaxTimestamp-currMinTimestamp);
}
if(this.aggregateFunction.equalsIgnoreCase("SUM"))
{
trackerIDTrajLength.put("", sumTrajLength);
return Tuple2.of(minTimestampTrackerID.size(), trackerIDTrajLength));
}
else // AVG
{
Long avgTrajLength = (Long)Math.round((sumTrajLength * 1.0)/(minTimestampTrackerID.size() * 1.0));
trackerIDTrajLength.put("", avgTrajLength);
return Tuple2.of(minTimestampTrackerID.size(), trackerIDTrajLength));
}
}
else if(this.aggregateFunction.equalsIgnoreCase("MIN")){
Long minTrajLength = Long.MAX_VALUE;
String minTrajLengthObjID = "";
trackerIDTrajLength.clear();
for (Map.Entry<String, Long> entry : minTimestampTrackerID.entrySet()) {
String objID = entry.getKey();
Long currMinTimestamp = entry.getValue();
Long currMaxTimestamp = maxTimestampTrackerID.get(objID);
Long trajLength = currMaxTimestamp-currMinTimestamp;
if(trajLength < minTrajLength){
minTrajLength = trajLength;
minTrajLengthObjID = objID;
}
}
trackerIDTrajLength.put(minTrajLengthObjID, minTrajLength);
return Tuple2.of(minTimestampTrackerID.size(), trackerIDTrajLength));
}
else if(this.aggregateFunction.equalsIgnoreCase("MAX")){
Long maxTrajLength = Long.MIN_VALUE;
String maxTrajLengthObjID = "";
trackerIDTrajLength.clear();
for (Map.Entry<String, Long> entry : minTimestampTrackerID.entrySet()) {
String objID = entry.getKey();
Long currMinTimestamp = entry.getValue();
Long currMaxTimestamp = maxTimestampTrackerID.get(objID);
Long trajLength = currMaxTimestamp-currMinTimestamp;
if(trajLength > maxTrajLength){
maxTrajLength = trajLength;
maxTrajLengthObjID = objID;
}
}
trackerIDTrajLength.put(maxTrajLengthObjID, maxTrajLength);
return Tuple2.of(minTimestampTrackerID.size(), trackerIDTrajLength));
}
else{
trackerIDTrajLength.clear();
for (Map.Entry<String, Long> entry : minTimestampTrackerID.entrySet()) {
String objID = entry.getKey();
Long currMinTimestamp = entry.getValue();
Long currMaxTimestamp = maxTimestampTrackerID.get(objID);
trackerIDTrajLength.put(objID, (currMaxTimestamp-currMinTimestamp));
}
return Tuple2.of(minTimestampTrackerID.size(), trackerIDTrajLength));
}
*/
}
boolean deleteHaltedTrajectories(Long maxTimestamp, Long maxAllowedLateness, String objID) throws Exception {
Date date = new Date();
if (date.getTime() - maxTimestamp > maxAllowedLateness){
minTimestampTrackerIDMapState.remove(objID);
maxTimestampTrackerIDMapState.remove(objID);
return true;
}
return false;
}
}
// Count Window Process Function
//ProcessWindowFunction<IN, OUT, KEY, W extends Window>
public static class CountWindowProcessFunction extends ProcessWindowFunction<Point, Tuple5<String, Integer, Long, Long, HashMap<String, Long>>, String, GlobalWindow> {
// HashMap<ObjectID, timestamp>
HashMap<String, Long> minTimestampTrackerID = new HashMap<String, Long>();
HashMap<String, Long> maxTimestampTrackerID = new HashMap<String, Long>();
// HashMap <ObjectID, TrajLength>
HashMap<String, Long> trackerIDTrajLength = new HashMap<String, Long>();
HashMap<String, Long> trackerIDTrajLengthOutput = new HashMap<String, Long>();
String aggregateFunction;
public CountWindowProcessFunction(String aggregateFunction){
this.aggregateFunction = aggregateFunction;
}
@Override
// KEY key, Context context, Iterable<IN> elements, Collector<OUT> out
public void process(String key, Context context, Iterable<Point> input, Collector<Tuple5<String, Integer, Long, Long, HashMap<String, Long>>> output) throws Exception {
minTimestampTrackerID.clear();
maxTimestampTrackerID.clear();
trackerIDTrajLength.clear();
trackerIDTrajLengthOutput.clear();
Long minTrajLength = Long.MAX_VALUE;
String minTrajLengthObjID = "";
Long maxTrajLength = Long.MIN_VALUE;
String maxTrajLengthObjID = "";
Long sumTrajLength = 0L; // Maintains sum of all trajectories of a cell
for (Point p : input) {
Long currMinTimestamp = minTimestampTrackerID.get(p.objID);
Long currMaxTimestamp = maxTimestampTrackerID.get(p.objID);
Long minTimestamp = currMinTimestamp;
Long maxTimestamp = currMaxTimestamp;
if (currMinTimestamp != null) { // If exists replace else insert
if (p.timeStampMillisec < currMinTimestamp) {
minTimestampTrackerID.replace(p.objID, p.timeStampMillisec);
minTimestamp = p.timeStampMillisec;
}
if (p.timeStampMillisec > currMaxTimestamp) {
maxTimestampTrackerID.replace(p.objID, p.timeStampMillisec);
maxTimestamp = p.timeStampMillisec;
}
// Compute the trajectory length and update the map if needed
Long currTrajLength = trackerIDTrajLength.get(p.objID);
Long trajLength = maxTimestamp - minTimestamp;
if (!currTrajLength.equals(trajLength)) { // If exists, replace
trackerIDTrajLength.replace(p.objID, trajLength);
sumTrajLength -= currTrajLength;
sumTrajLength += trajLength;
}
// Computing MAX Trajectory Length
if(trajLength > maxTrajLength){
maxTrajLength = trajLength;
maxTrajLengthObjID = p.objID;
}
// Computing MIN Trajectory Length
if(trajLength < minTrajLength){
minTrajLength = trajLength;
minTrajLengthObjID = p.objID;
}
} else { // else insert
minTimestampTrackerID.put(p.objID, p.timeStampMillisec);
maxTimestampTrackerID.put(p.objID, p.timeStampMillisec);
trackerIDTrajLength.put(p.objID, 0L);
}
}
// Tuple5<Key/CellID, #ObjectsInCell, windowStartTime, windowEndTime, Map<TrajId, TrajLength>>
if(this.aggregateFunction.equalsIgnoreCase("ALL")){
output.collect(new Tuple5<String, Integer, Long, Long, HashMap<String, Long>>(key,
trackerIDTrajLength.size(), context.window().maxTimestamp(), context.window().maxTimestamp(), trackerIDTrajLength));
}
else if(this.aggregateFunction.equalsIgnoreCase("SUM")){
if(sumTrajLength > 0) {
trackerIDTrajLengthOutput.put("", sumTrajLength);
output.collect(new Tuple5<String, Integer, Long, Long, HashMap<String, Long>>(key,
trackerIDTrajLength.size(), context.window().maxTimestamp(), context.window().maxTimestamp(), trackerIDTrajLengthOutput));
}
}
else if(this.aggregateFunction.equalsIgnoreCase("AVG")){
if(sumTrajLength > 0) {
Long avgTrajLength = (Long) Math.round((sumTrajLength * 1.0) / (trackerIDTrajLength.size() * 1.0));
trackerIDTrajLengthOutput.put("", avgTrajLength);
output.collect(new Tuple5<String, Integer, Long, Long, HashMap<String, Long>>(key,
trackerIDTrajLength.size(), context.window().maxTimestamp(), context.window().maxTimestamp(), trackerIDTrajLengthOutput));
}
}
else if(this.aggregateFunction.equalsIgnoreCase("MIN")){
if(minTrajLength != Long.MAX_VALUE) {
trackerIDTrajLengthOutput.put(minTrajLengthObjID, minTrajLength);
output.collect(new Tuple5<String, Integer, Long, Long, HashMap<String, Long>>(key,
trackerIDTrajLength.size(), context.window().maxTimestamp(), context.window().maxTimestamp(), trackerIDTrajLengthOutput));
}
}
else if(this.aggregateFunction.equalsIgnoreCase("MAX")){
if(maxTrajLength != Long.MIN_VALUE) {
trackerIDTrajLengthOutput.put(maxTrajLengthObjID, maxTrajLength);
output.collect(new Tuple5<String, Integer, Long, Long, HashMap<String, Long>>(key,
trackerIDTrajLength.size(), context.window().maxTimestamp(), context.window().maxTimestamp(), trackerIDTrajLengthOutput));
}
}
else{
output.collect(new Tuple5<String, Integer, Long, Long, HashMap<String, Long>>(key,
trackerIDTrajLength.size(), context.window().maxTimestamp(), context.window().maxTimestamp(), trackerIDTrajLength));
}
}
}
//Time Window Process Function
//ProcessWindowFunction<IN, OUT, KEY, W extends Window>
public static class TimeWindowProcessFunction extends ProcessWindowFunction<Point, Tuple5<String, Integer, Long, Long, HashMap<String, Long>>, String, TimeWindow> {
// HashMap<TrackerID, timestamp>
HashMap<String, Long> minTimestampTrackerID = new HashMap<String, Long>();
HashMap<String, Long> maxTimestampTrackerID = new HashMap<String, Long>();
// HashMap <TrackerID, TrajLength>
HashMap<String, Long> trackerIDTrajLength = new HashMap<String, Long>();
HashMap<String, Long> trackerIDTrajLengthOutput = new HashMap<String, Long>();
String aggregateFunction;
public TimeWindowProcessFunction(String aggregateFunction){
this.aggregateFunction = aggregateFunction;
}
@Override
// KEY key, Context context, Iterable<IN> elements, Collector<OUT> out
public void process(String key, Context context, Iterable<Point> input, Collector<Tuple5<String, Integer, Long, Long, HashMap<String, Long>>> output) throws Exception {
minTimestampTrackerID.clear();
maxTimestampTrackerID.clear();
trackerIDTrajLength.clear();
trackerIDTrajLengthOutput.clear();
Long minTrajLength = Long.MAX_VALUE;
String minTrajLengthObjID = "";
Long maxTrajLength = Long.MIN_VALUE;
String maxTrajLengthObjID = "";
Long sumTrajLength = 0L;
// Iterate through all the points corresponding to a single grid-cell within the scope of the window
for (Point p : input) {
Long currMinTimestamp = minTimestampTrackerID.get(p.objID);
Long currMaxTimestamp = maxTimestampTrackerID.get(p.objID);
Long minTimestamp = currMinTimestamp;
Long maxTimestamp = currMaxTimestamp;
//System.out.println("point timestamp " + p.timeStampMillisec + " Window bounds: " + context.window().getStart() + ", " + context.window().getEnd());
if (currMinTimestamp != null) { // If exists replace else insert
if (p.timeStampMillisec < currMinTimestamp) {
minTimestampTrackerID.replace(p.objID, p.timeStampMillisec);
minTimestamp = p.timeStampMillisec;
}
if (p.timeStampMillisec > currMaxTimestamp) {
maxTimestampTrackerID.replace(p.objID, p.timeStampMillisec);
maxTimestamp = p.timeStampMillisec;
}
// Compute the trajectory length and update the map if needed
Long currTrajLength = trackerIDTrajLength.get(p.objID);
Long trajLength = maxTimestamp - minTimestamp;
if (!currTrajLength.equals(trajLength)) {
trackerIDTrajLength.replace(p.objID, trajLength);
sumTrajLength -= currTrajLength;
sumTrajLength += trajLength;
}
// Computing MAX Trajectory Length
if(trajLength > maxTrajLength){
maxTrajLength = trajLength;
maxTrajLengthObjID = p.objID;
}
// Computing MIN Trajectory Length
if(trajLength < minTrajLength){
minTrajLength = trajLength;
minTrajLengthObjID = p.objID;
}
} else {
minTimestampTrackerID.put(p.objID, p.timeStampMillisec);
maxTimestampTrackerID.put(p.objID, p.timeStampMillisec);
trackerIDTrajLength.put(p.objID, 0L);
}
}
// Tuple5<Key/CellID, #ObjectsInCell, windowStartTime, windowEndTime, Map<TrajId, TrajLength>>
if(this.aggregateFunction.equalsIgnoreCase("ALL")){
output.collect(new Tuple5<String, Integer, Long, Long, HashMap<String, Long>>(key,
trackerIDTrajLength.size(), context.window().getStart(), context.window().getEnd(), trackerIDTrajLength));
}
else if(this.aggregateFunction.equalsIgnoreCase("SUM")){
if(sumTrajLength > 0) {
trackerIDTrajLengthOutput.put("", sumTrajLength);
output.collect(new Tuple5<String, Integer, Long, Long, HashMap<String, Long>>(key,
trackerIDTrajLength.size(), context.window().getStart(), context.window().getEnd(), trackerIDTrajLengthOutput));
}
}
else if(this.aggregateFunction.equalsIgnoreCase("AVG")){
if(sumTrajLength > 0) {
Long avgTrajLength = (Long) Math.round((sumTrajLength * 1.0) / (trackerIDTrajLength.size() * 1.0));
trackerIDTrajLengthOutput.put("", avgTrajLength);
output.collect(new Tuple5<String, Integer, Long, Long, HashMap<String, Long>>(key,
trackerIDTrajLength.size(), context.window().getStart(), context.window().getEnd(), trackerIDTrajLengthOutput));
}
}
else if(this.aggregateFunction.equalsIgnoreCase("MIN")){
if(minTrajLength != Long.MAX_VALUE) {
trackerIDTrajLengthOutput.put(minTrajLengthObjID, minTrajLength);
output.collect(new Tuple5<String, Integer, Long, Long, HashMap<String, Long>>(key,
trackerIDTrajLength.size(), context.window().getStart(), context.window().getEnd(), trackerIDTrajLengthOutput));
}
}
else if(this.aggregateFunction.equalsIgnoreCase("MAX")){
if(maxTrajLength != Long.MIN_VALUE) {
trackerIDTrajLengthOutput.put(maxTrajLengthObjID, maxTrajLength);
output.collect(new Tuple5<String, Integer, Long, Long, HashMap<String, Long>>(key,
trackerIDTrajLength.size(), context.window().getStart(), context.window().getEnd(), trackerIDTrajLengthOutput));
}
}
else{
output.collect(new Tuple5<String, Integer, Long, Long, HashMap<String, Long>>(key,
trackerIDTrajLength.size(), context.window().getStart(), context.window().getEnd(), trackerIDTrajLength));
}
}
}
/*
//Time Window Process Function
//ProcessWindowFunction<IN, OUT, KEY, W extends Window>
public static class TimeWindowProcessFunction extends ProcessWindowFunction<Point, Tuple5<String, Integer, Long, Long, HashMap<String, Long>>, String, TimeWindow> {
// HashMap<TrackerID, timestamp>
HashMap<String, Long> minTimestampTrackerID = new HashMap<String, Long>();
HashMap<String, Long> maxTimestampTrackerID = new HashMap<String, Long>();
// HashMap <TrackerID, TrajLength>
HashMap<String, Long> trackerIDTrajLength = new HashMap<String, Long>();
private ValueState<Long> tuplesCounterValState;
String aggregateFunction;
public TimeWindowProcessFunction(String aggregateFunction){
this.aggregateFunction = aggregateFunction;
}
@Override
public void open(Configuration config) {
ValueStateDescriptor<Long> tuplesCounterDescriptor = new ValueStateDescriptor<Long>(
"tuplesCounterDescriptor", // state name
BasicTypeInfo.LONG_TYPE_INFO);
this.tuplesCounterValState = getRuntimeContext().getState(tuplesCounterDescriptor);
}
@Override
// KEY key, Context context, Iterable<IN> elements, Collector<OUT> out
public void process(String key, Context context, Iterable<Point> input, Collector<Tuple5<String, Integer, Long, Long, HashMap<String, Long>>> output) throws Exception {
minTimestampTrackerID.clear();
maxTimestampTrackerID.clear();
Long tuplesCounterLocal = tuplesCounterValState.value();
if(tuplesCounterLocal == null)
tuplesCounterLocal = 0L;
// Iterate through all the points corresponding to a single grid-cell within the scope of the window
for (Point p : input) {
tuplesCounterLocal++;
Long currMinTimestamp = minTimestampTrackerID.get(p.objID);
Long currMaxTimestamp = maxTimestampTrackerID.get(p.objID);
if (currMinTimestamp != null) { // If exists replace else insert
if (p.timeStampMillisec < currMinTimestamp) {
minTimestampTrackerID.replace(p.objID, p.timeStampMillisec);
} else if (p.timeStampMillisec > currMaxTimestamp) {
maxTimestampTrackerID.replace(p.objID, p.timeStampMillisec);
}
} else {
minTimestampTrackerID.put(p.objID, p.timeStampMillisec);
maxTimestampTrackerID.put(p.objID, p.timeStampMillisec);
}
}
tuplesCounterValState.update(tuplesCounterLocal);
// Generating Output based on aggregateFunction variable
// Tuple5<Key/CellID, #ObjectsInCell, windowStartTime, windowEndTime, Map<TrajId, TrajLength>>
if(this.aggregateFunction.equalsIgnoreCase("ALL")){
trackerIDTrajLength.clear();
for (Map.Entry<String, Long> entry : minTimestampTrackerID.entrySet()) {
String objID = entry.getKey();
Long currMinTimestamp = entry.getValue();
Long currMaxTimestamp = maxTimestampTrackerID.get(objID);
trackerIDTrajLength.put(objID, (currMaxTimestamp-currMinTimestamp));
}
output.collect(new Tuple5<String, Integer, Long, Long, HashMap<String, Long>>(key,
minTimestampTrackerID.size(), context.window().getStart(), context.window().getEnd(), trackerIDTrajLength));
}
else if(this.aggregateFunction.equalsIgnoreCase("SUM") || this.aggregateFunction.equalsIgnoreCase("AVG")){
trackerIDTrajLength.clear();
Long sumTrajLength = 0L;
for (Map.Entry<String, Long> entry : minTimestampTrackerID.entrySet()) {
String objID = entry.getKey();
Long currMinTimestamp = entry.getValue();
Long currMaxTimestamp = maxTimestampTrackerID.get(objID);
sumTrajLength += (currMaxTimestamp-currMinTimestamp);
}
if(this.aggregateFunction.equalsIgnoreCase("SUM"))
{
trackerIDTrajLength.put("", sumTrajLength);
output.collect(new Tuple5<String, Integer, Long, Long, HashMap<String, Long>>(key,
minTimestampTrackerID.size(), context.window().getStart(), context.window().getEnd(), trackerIDTrajLength));
}
else // AVG
{
Long avgTrajLength = (Long)Math.round((sumTrajLength * 1.0)/(minTimestampTrackerID.size() * 1.0));
trackerIDTrajLength.put("", avgTrajLength);
output.collect(new Tuple5<String, Integer, Long, Long, HashMap<String, Long>>(key,
minTimestampTrackerID.size(), context.window().getStart(), context.window().getEnd(), trackerIDTrajLength));
}
}
else if(this.aggregateFunction.equalsIgnoreCase("MIN")){
Long minTrajLength = Long.MAX_VALUE;
String minTrajLengthObjID = "";
trackerIDTrajLength.clear();
for (Map.Entry<String, Long> entry : minTimestampTrackerID.entrySet()) {
String objID = entry.getKey();
Long currMinTimestamp = entry.getValue();
Long currMaxTimestamp = maxTimestampTrackerID.get(objID);
Long trajLength = currMaxTimestamp-currMinTimestamp;
if(trajLength < minTrajLength){
minTrajLength = trajLength;
minTrajLengthObjID = objID;
}
}
trackerIDTrajLength.put(minTrajLengthObjID, minTrajLength);
output.collect(new Tuple5<String, Integer, Long, Long, HashMap<String, Long>>(key,
minTimestampTrackerID.size(), context.window().getStart(), context.window().getEnd(), trackerIDTrajLength));
}
else if(this.aggregateFunction.equalsIgnoreCase("MAX")){
Long maxTrajLength = Long.MIN_VALUE;
String maxTrajLengthObjID = "";
trackerIDTrajLength.clear();
for (Map.Entry<String, Long> entry : minTimestampTrackerID.entrySet()) {
String objID = entry.getKey();
Long currMinTimestamp = entry.getValue();
Long currMaxTimestamp = maxTimestampTrackerID.get(objID);
Long trajLength = currMaxTimestamp-currMinTimestamp;
if(trajLength > maxTrajLength){
maxTrajLength = trajLength;
maxTrajLengthObjID = objID;
}
}
trackerIDTrajLength.put(maxTrajLengthObjID, maxTrajLength);
output.collect(new Tuple5<String, Integer, Long, Long, HashMap<String, Long>>(key,
minTimestampTrackerID.size(), context.window().getStart(), context.window().getEnd(), trackerIDTrajLength));
}
else{
trackerIDTrajLength.clear();
for (Map.Entry<String, Long> entry : minTimestampTrackerID.entrySet()) {
String objID = entry.getKey();
Long currMinTimestamp = entry.getValue();
Long currMaxTimestamp = maxTimestampTrackerID.get(objID);
trackerIDTrajLength.put(objID, (currMaxTimestamp-currMinTimestamp));
}
output.collect(new Tuple5<String, Integer, Long, Long, HashMap<String, Long>>(key,
trackerIDTrajLength.size(), context.window().getStart(), context.window().getEnd(), trackerIDTrajLength));
}
}
}*/
}
|
3e1a59b5e6dc009b9fe3c8a323ca637266562a81 | 2,813 | java | Java | qinsql-main/src/main/java/com/facebook/presto/operator/scalar/JsonStringToRowCast.java | codefollower/QinSQL | d85650206b3d2d7374520d344e4745fe1847b2a5 | [
"Apache-2.0"
] | 9,782 | 2016-03-18T15:16:19.000Z | 2022-03-31T07:49:41.000Z | qinsql-main/src/main/java/com/facebook/presto/operator/scalar/JsonStringToRowCast.java | codefollower/QinSQL | d85650206b3d2d7374520d344e4745fe1847b2a5 | [
"Apache-2.0"
] | 10,310 | 2016-03-18T01:03:00.000Z | 2022-03-31T23:54:08.000Z | qinsql-main/src/main/java/com/facebook/presto/operator/scalar/JsonStringToRowCast.java | codefollower/QinSQL | d85650206b3d2d7374520d344e4745fe1847b2a5 | [
"Apache-2.0"
] | 3,803 | 2016-03-18T22:54:24.000Z | 2022-03-31T07:49:46.000Z | 37.506667 | 146 | 0.749378 | 11,200 | /*
* 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.facebook.presto.operator.scalar;
import com.facebook.presto.common.QualifiedObjectName;
import com.facebook.presto.common.type.StandardTypes;
import com.facebook.presto.metadata.BoundVariables;
import com.facebook.presto.metadata.FunctionAndTypeManager;
import com.facebook.presto.metadata.SqlScalarFunction;
import com.facebook.presto.spi.function.Signature;
import com.facebook.presto.spi.function.SqlFunctionVisibility;
import com.google.common.collect.ImmutableList;
import static com.facebook.presto.common.type.TypeSignature.parseTypeSignature;
import static com.facebook.presto.metadata.BuiltInTypeAndFunctionNamespaceManager.DEFAULT_NAMESPACE;
import static com.facebook.presto.operator.scalar.JsonToRowCast.JSON_TO_ROW;
import static com.facebook.presto.spi.function.FunctionKind.SCALAR;
import static com.facebook.presto.spi.function.Signature.withVariadicBound;
import static com.facebook.presto.spi.function.SqlFunctionVisibility.HIDDEN;
public final class JsonStringToRowCast
extends SqlScalarFunction
{
public static final JsonStringToRowCast JSON_STRING_TO_ROW = new JsonStringToRowCast();
public static final String JSON_STRING_TO_ROW_NAME = "$internal$json_string_to_row_cast";
private JsonStringToRowCast()
{
super(new Signature(
QualifiedObjectName.valueOf(DEFAULT_NAMESPACE, JSON_STRING_TO_ROW_NAME),
SCALAR,
ImmutableList.of(withVariadicBound("T", "row")),
ImmutableList.of(),
parseTypeSignature("T"),
ImmutableList.of(parseTypeSignature(StandardTypes.VARCHAR)),
false));
}
@Override
public String getDescription()
{
// Internal function, doesn't need a description
return null;
}
@Override
public boolean isDeterministic()
{
return true;
}
@Override
public final SqlFunctionVisibility getVisibility()
{
return HIDDEN;
}
@Override
public BuiltInScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, FunctionAndTypeManager functionAndTypeManager)
{
return JSON_TO_ROW.specialize(boundVariables, arity, functionAndTypeManager);
}
}
|
3e1a5a11edba7278ed22feb69b6a6eecb578da72 | 3,071 | java | Java | app/src/main/java/rs/ftn/pma/tourismobile/activities/TagDetailsActivity.java | danielkupco/Tourismobile | 6352930117b3de5b9ba3e7b44c9b91c2cd4fb025 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/rs/ftn/pma/tourismobile/activities/TagDetailsActivity.java | danielkupco/Tourismobile | 6352930117b3de5b9ba3e7b44c9b91c2cd4fb025 | [
"Apache-2.0"
] | 10 | 2016-06-13T18:28:10.000Z | 2016-07-04T00:41:34.000Z | app/src/main/java/rs/ftn/pma/tourismobile/activities/TagDetailsActivity.java | danielkupco/Tourismobile | 6352930117b3de5b9ba3e7b44c9b91c2cd4fb025 | [
"Apache-2.0"
] | null | null | null | 28.174312 | 121 | 0.700423 | 11,201 | package rs.ftn.pma.tourismobile.activities;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import org.androidannotations.annotations.AfterExtras;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OptionsItem;
import org.androidannotations.annotations.OptionsMenu;
import org.androidannotations.annotations.ViewById;
import rs.ftn.pma.tourismobile.R;
import rs.ftn.pma.tourismobile.database.dao.wrapper.TagDAOWrapper;
import rs.ftn.pma.tourismobile.model.Tag;
/**
* Created by Daniel Kupčo on 04.06.2016.
*/
@EActivity(R.layout.activity_tag_details)
@OptionsMenu(R.menu.action_bar_tag_details)
public class TagDetailsActivity extends AppCompatActivity {
private static final String TAG = TagDetailsActivity.class.getSimpleName();
@ViewById
TextView tagName;
@ViewById
TextView tagProperty;
@ViewById
TextView tagValue;
@ViewById
TextView tagDescription;
@ViewById
TextView tagDbpCanQueryBy;
@Bean
TagDAOWrapper tagDAOWrapper;
@Extra
int tagId;
@ViewById
Toolbar toolbar;
private Tag tag;
// must set toolbar after view layout is initialized
@AfterViews
void initViews() {
if (toolbar != null) {
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if(actionBar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getString(R.string.title_tag_details));
}
}
}
@AfterExtras
void injectExtra() {
tag = tagDAOWrapper.findById(tagId);
}
@AfterViews
void bindViews() {
tagName.setText(tag.getName());
tagDescription.setText(tag.getDescription());
if (tag.isDbpCanQueryBy()) {
tagProperty.setText(String.format("%s: %s", getString(R.string.label_property_name), tag.getDbpProperty()));
tagValue.setText(String.format("%s: %s", getString(R.string.label_property_value), tag.getDbpValue()));
}
else {
tagDbpCanQueryBy.setText(getString(R.string.label_dbp_can_query_by_false));
tagProperty.setVisibility(View.GONE);
tagValue.setVisibility(View.GONE);
}
}
// must set explicitly because home ID is not part of our menu layout
@OptionsItem(android.R.id.home)
void home() {
onBackPressed();
}
@OptionsItem
void actionSettings() {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
@OptionsItem
void actionTaggedDestinations() {
TaggedDestinationsActivity_.intent(this).tagID(tagId).start();
}
}
|
3e1a5b34ddfa2baaa39a32e9ff3f2d849baebe1b | 4,996 | java | Java | presto-orc/src/main/java/io/prestosql/orc/reader/AbstractNumericColumnReader.java | chandana496/hetu-core | f6976233f7d44d33b8ed1d0befd582f151beecff | [
"Apache-2.0"
] | 476 | 2020-06-30T14:24:39.000Z | 2022-03-29T13:13:33.000Z | presto-orc/src/main/java/io/prestosql/orc/reader/AbstractNumericColumnReader.java | chandana496/hetu-core | f6976233f7d44d33b8ed1d0befd582f151beecff | [
"Apache-2.0"
] | 316 | 2020-06-30T11:44:52.000Z | 2022-03-30T11:08:04.000Z | presto-orc/src/main/java/io/prestosql/orc/reader/AbstractNumericColumnReader.java | chandana496/hetu-core | f6976233f7d44d33b8ed1d0befd582f151beecff | [
"Apache-2.0"
] | 326 | 2020-06-30T11:40:14.000Z | 2022-03-31T07:55:03.000Z | 33.306667 | 151 | 0.73739 | 11,202 | /*
* 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.prestosql.orc.reader;
import io.prestosql.memory.context.LocalMemoryContext;
import io.prestosql.orc.OrcColumn;
import io.prestosql.orc.OrcCorruptionException;
import io.prestosql.orc.metadata.ColumnEncoding;
import io.prestosql.orc.metadata.ColumnMetadata;
import io.prestosql.orc.stream.BooleanInputStream;
import io.prestosql.orc.stream.InputStreamSource;
import io.prestosql.orc.stream.InputStreamSources;
import io.prestosql.orc.stream.LongInputStream;
import io.prestosql.spi.type.BigintType;
import io.prestosql.spi.type.DateType;
import io.prestosql.spi.type.IntegerType;
import io.prestosql.spi.type.SmallintType;
import io.prestosql.spi.type.Type;
import org.openjdk.jol.info.ClassLayout;
import javax.annotation.Nullable;
import java.io.IOException;
import java.time.ZoneId;
import static com.google.common.base.MoreObjects.toStringHelper;
import static io.airlift.slice.SizeOf.sizeOf;
import static io.prestosql.orc.metadata.Stream.StreamKind.DATA;
import static io.prestosql.orc.metadata.Stream.StreamKind.PRESENT;
import static io.prestosql.orc.reader.ReaderUtils.verifyStreamType;
import static io.prestosql.orc.stream.MissingInputStreamSource.missingStreamSource;
import static java.util.Objects.requireNonNull;
public abstract class AbstractNumericColumnReader<T>
implements ColumnReader<T>
{
protected static final int INSTANCE_SIZE = ClassLayout.parseClass(AbstractNumericColumnReader.class).instanceSize();
protected final OrcColumn column;
protected int readOffset;
protected int nextBatchSize;
protected InputStreamSource<BooleanInputStream> presentStreamSource = missingStreamSource(BooleanInputStream.class);
@Nullable
protected BooleanInputStream presentStream;
protected boolean[] nullVector = new boolean[0];
protected InputStreamSource<LongInputStream> dataStreamSource = missingStreamSource(LongInputStream.class);
@Nullable
protected LongInputStream dataStream;
protected boolean rowGroupOpen;
protected final LocalMemoryContext systemMemoryContext;
/**
* FIXME: KEN: why do we need to pass in type? isn't it implied already?
* @param column
* @param systemMemoryContext
* @throws OrcCorruptionException
*/
public AbstractNumericColumnReader(Type type, OrcColumn column, LocalMemoryContext systemMemoryContext)
throws OrcCorruptionException
{
requireNonNull(type, "type is null");
verifyStreamType(column, type, t -> t instanceof BigintType || t instanceof IntegerType || t instanceof SmallintType || t instanceof DateType);
this.column = requireNonNull(column, "column is null");
this.systemMemoryContext = requireNonNull(systemMemoryContext, "systemMemoryContext is null");
}
@Override
public void prepareNextRead(int batchSize)
{
readOffset += nextBatchSize;
nextBatchSize = batchSize;
}
protected void openRowGroup()
throws IOException
{
presentStream = presentStreamSource.openStream();
dataStream = dataStreamSource.openStream();
rowGroupOpen = true;
}
@Override
public void startStripe(ZoneId fileTimeZone, InputStreamSources dictionaryStreamSources, ColumnMetadata<ColumnEncoding> encoding)
{
presentStreamSource = missingStreamSource(BooleanInputStream.class);
dataStreamSource = missingStreamSource(LongInputStream.class);
readOffset = 0;
nextBatchSize = 0;
presentStream = null;
dataStream = null;
rowGroupOpen = false;
}
@Override
public void startRowGroup(InputStreamSources dataStreamSources)
{
presentStreamSource = dataStreamSources.getInputStreamSource(column, PRESENT, BooleanInputStream.class);
dataStreamSource = dataStreamSources.getInputStreamSource(column, DATA, LongInputStream.class);
readOffset = 0;
nextBatchSize = 0;
presentStream = null;
dataStream = null;
rowGroupOpen = false;
}
@Override
public String toString()
{
return toStringHelper(this)
.addValue(column)
.toString();
}
@Override
public void close()
{
systemMemoryContext.close();
nullVector = null;
}
@Override
public long getRetainedSizeInBytes()
{
return INSTANCE_SIZE + sizeOf(nullVector);
}
}
|
3e1a5c5c1a5e7a38bc06e9f6477d1a13622339f0 | 577 | java | Java | app/src/main/java/com/yetwish/weixinaudiochat/model/Recorder.java | yetwish/imooc-WeixinAudioChat | 11b1688b91634e8a41c0e35025fef812f6269386 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/yetwish/weixinaudiochat/model/Recorder.java | yetwish/imooc-WeixinAudioChat | 11b1688b91634e8a41c0e35025fef812f6269386 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/yetwish/weixinaudiochat/model/Recorder.java | yetwish/imooc-WeixinAudioChat | 11b1688b91634e8a41c0e35025fef812f6269386 | [
"Apache-2.0"
] | null | null | null | 17.484848 | 50 | 0.608319 | 11,203 | package com.yetwish.weixinaudiochat.model;
/**
* 录音信息类
* Created by yetwish on 2015-05-07
*/
public class Recorder {
private float time;
private String filePath;
public Recorder(float time, String filePath) {
this.time = time;
this.filePath = filePath;
}
public float getTime() {
return time;
}
public void setTime(float time) {
this.time = time;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
|
3e1a5d6c7586eff96c9eaf6a120ad222acb2d9e7 | 4,449 | java | Java | src/main/java/org/nuxeo/onedrive/client/OneDriveThumbnailSet.java | datheng/onedrive-java-client | 8734845bdf4289a353c8a57a54c3c3e872abcfd6 | [
"Apache-2.0"
] | 48 | 2016-03-30T06:44:03.000Z | 2022-03-10T10:40:04.000Z | src/main/java/org/nuxeo/onedrive/client/OneDriveThumbnailSet.java | datheng/onedrive-java-client | 8734845bdf4289a353c8a57a54c3c3e872abcfd6 | [
"Apache-2.0"
] | 3 | 2018-10-05T11:17:13.000Z | 2021-05-03T15:03:13.000Z | src/main/java/org/nuxeo/onedrive/client/OneDriveThumbnailSet.java | datheng/onedrive-java-client | 8734845bdf4289a353c8a57a54c3c3e872abcfd6 | [
"Apache-2.0"
] | 16 | 2016-03-11T02:43:40.000Z | 2022-03-06T22:35:57.000Z | 30.895833 | 94 | 0.606878 | 11,204 | /*
* (C) Copyright 2016 Nuxeo SA (http://nuxeo.com/) and others.
*
* 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.
*
* Contributors:
* Kevin Leturc
*/
package org.nuxeo.onedrive.client;
import java.util.Objects;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;
import com.eclipsesource.json.ParseException;
/**
* See documentation at https://dev.onedrive.com/resources/thumbnailSet.htm.
*
* @since 1.0
*/
public class OneDriveThumbnailSet extends OneDriveResource {
private final String itemId;
private final int thumbId;
OneDriveThumbnailSet(OneDriveAPI api, int thumbId) {
super(api, "root$$" + thumbId);
this.itemId = null;
this.thumbId = thumbId;
}
OneDriveThumbnailSet(OneDriveAPI api, String itemId, int thumbId) {
super(api, itemId + "$$" + thumbId);
this.itemId = Objects.requireNonNull(itemId);
this.thumbId = thumbId;
}
@Override
public boolean isRoot() {
return itemId == null;
}
public class Metadata extends OneDriveResource.Metadata {
/**
* A 48x48 cropped thumbnail.
*/
private OneDriveThumbnail.Metadata small;
/**
* A 176x176 scaled thumbnail.
*/
private OneDriveThumbnail.Metadata medium;
/**
* A 1920x1920 scaled thumbnail.
*/
private OneDriveThumbnail.Metadata large;
/**
* A custom thumbnail image or the original image used to generate other thumbnails.
*/
private OneDriveThumbnail.Metadata source;
public Metadata(JsonObject json) {
super(json);
}
public String getItemId() {
return itemId;
}
public int getThumbId() {
return thumbId;
}
public OneDriveThumbnail.Metadata getSmall() {
return small;
}
public OneDriveThumbnail.Metadata getMedium() {
return medium;
}
public OneDriveThumbnail.Metadata getLarge() {
return large;
}
public OneDriveThumbnail.Metadata getSource() {
return source;
}
@Override
protected void parseMember(JsonObject.Member member) {
super.parseMember(member);
try {
JsonValue value = member.getValue();
String memberName = member.getName();
if ("small".equals(memberName)) {
OneDriveThumbnail thumbnail = initThumbnail(OneDriveThumbnailSize.SMALL);
small = thumbnail.new Metadata(value.asObject());
} else if ("medium".equals(memberName)) {
OneDriveThumbnail thumbnail = initThumbnail(OneDriveThumbnailSize.MEDIUM);
medium = thumbnail.new Metadata(value.asObject());
} else if ("large".equals(memberName)) {
OneDriveThumbnail thumbnail = initThumbnail(OneDriveThumbnailSize.LARGE);
large = thumbnail.new Metadata(value.asObject());
} else if ("source".equals(memberName)) {
OneDriveThumbnail thumbnail = initThumbnail(OneDriveThumbnailSize.SOURCE);
source = thumbnail.new Metadata(value.asObject());
}
} catch (ParseException e) {
throw new OneDriveRuntimeException("Parse failed, maybe a bug in client.", e);
}
}
private OneDriveThumbnail initThumbnail(OneDriveThumbnailSize size) {
if (itemId == null) {
return new OneDriveThumbnail(getApi(), thumbId, size);
}
return new OneDriveThumbnail(getApi(), itemId, thumbId, size);
}
@Override
public OneDriveResource getResource() {
return OneDriveThumbnailSet.this;
}
}
}
|
3e1a5e272ec53b81684ff21063bf119d19fb9f4a | 949 | java | Java | aop-features/src/main/java/com/xiaobei/spring/aop/demo/AspectJAnnotationDemo.java | xiaobei-ihmhny/spring-demo-parent | d33b906b3e4531a4201b2a2fd2fd1fcefa78c6bd | [
"Apache-2.0"
] | null | null | null | aop-features/src/main/java/com/xiaobei/spring/aop/demo/AspectJAnnotationDemo.java | xiaobei-ihmhny/spring-demo-parent | d33b906b3e4531a4201b2a2fd2fd1fcefa78c6bd | [
"Apache-2.0"
] | 2 | 2020-08-08T15:33:36.000Z | 2020-08-16T22:29:02.000Z | aop-features/src/main/java/com/xiaobei/spring/aop/demo/AspectJAnnotationDemo.java | xiaobei-ihmhny/spring-demo-parent | d33b906b3e4531a4201b2a2fd2fd1fcefa78c6bd | [
"Apache-2.0"
] | null | null | null | 35.185185 | 81 | 0.76 | 11,205 | package com.xiaobei.spring.aop.demo;
import com.xiaobei.spring.aop.demo.config.AspectDemo;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* 注解方式激活 AspectJ
* @author <a href="mailto:dycjh@example.com">xiaobei-ihmhny</a>
* @date 2021-02-14 20:52:52
*/
@ComponentScan("com.xiaobei.spring.aop.demo")
@Configuration
public class AspectJAnnotationDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext();
applicationContext.register(AspectJAnnotationDemo.class);
applicationContext.refresh();
AspectDemo aspectDemo = applicationContext.getBean(AspectDemo.class);
System.out.println(aspectDemo);
applicationContext.close();
}
}
|
3e1a5e2abcbba5ea200b5f573b946e8debc8457e | 6,465 | java | Java | edu-services/gradebook-service/hibernate/src/java/org/sakaiproject/tool/gradebook/GradeMapping.java | danadel/sakai | 68947659150056932d0896237eaeb0ed38c3fc7f | [
"ECL-2.0"
] | 13 | 2016-05-25T16:12:49.000Z | 2021-04-09T01:49:24.000Z | edu-services/gradebook-service/hibernate/src/java/org/sakaiproject/tool/gradebook/GradeMapping.java | danadel/sakai | 68947659150056932d0896237eaeb0ed38c3fc7f | [
"ECL-2.0"
] | 265 | 2015-10-19T02:40:55.000Z | 2022-03-28T07:24:49.000Z | edu-services/gradebook-service/hibernate/src/java/org/sakaiproject/tool/gradebook/GradeMapping.java | danadel/sakai | 68947659150056932d0896237eaeb0ed38c3fc7f | [
"ECL-2.0"
] | 7 | 2016-02-08T11:41:40.000Z | 2021-06-08T18:18:02.000Z | 27.278481 | 135 | 0.653364 | 11,206 | /**********************************************************************************
*
* $Id$
*
***********************************************************************************
*
* Copyright (c) 2005, 2006, 2007, 2008 The Sakai Foundation, The MIT Corporation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.tool.gradebook;
import java.io.Serializable;
import java.util.*;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A GradeMapping provides a means to convert between an arbitrary set of grades
* (letter grades, pass / not pass, 4,0 scale) and numeric percentages.
*
*/
public class GradeMapping implements Serializable, Comparable {
protected Log log = LogFactory.getLog(GradeMapping.class);
protected Long id;
protected int version;
protected Gradebook gradebook;
protected Map<String, Double> gradeMap;
private GradingScale gradingScale;
public GradeMapping() {
}
public GradeMapping(GradingScale gradingScale) {
setGradingScale(gradingScale);
gradeMap = new HashMap<String, Double>(gradingScale.getDefaultBottomPercents());
}
public String getName() {
return getGradingScale().getName();
}
/**
* Sets the percentage values for this GradeMapping to their default values.
*/
public void setDefaultValues() {
gradeMap = new HashMap<String, Double>(getDefaultBottomPercents());
}
/**
* Backwards-compatible wrapper to get to grading scale.
*/
public Map<String, Double> getDefaultBottomPercents() {
GradingScale gradingScale = getGradingScale();
if (gradingScale != null) {
return gradingScale.getDefaultBottomPercents();
} else {
Map<String, Double> defaultBottomPercents = new HashMap<String, Double>();
Iterator defaultValuesIter = getDefaultValues().iterator();
Iterator gradesIter = getGrades().iterator();
while (gradesIter.hasNext()) {
String grade = (String)gradesIter.next();
Double value = (Double)defaultValuesIter.next();
defaultBottomPercents.put(grade, value);
}
return defaultBottomPercents;
}
}
/**
*
* @return An (ordered) collection of the available grade values
*/
public Collection<String> getGrades() {
return getGradingScale().getGrades();
}
/**
*
* @return A List of the default grade values. Only used for backward
* compatibility to pre-grading-scale mappings.
*/
public List<Double> getDefaultValues() {
throw new UnsupportedOperationException("getDefaultValues called for GradeMapping " + getName() + " in Gradebook " + getGradebook());
}
/**
* Gets the percentage mapped to a particular grade.
*/
public Double getValue(String grade) {
return (Double) gradeMap.get(grade);
}
/**
* This algorithm is slow, since it checks each grade option, starting from
* the "top" (in this case an 'A'). We can make it faster by starting in the
* middle (as in a bubble sort), but since there are so few grade options, I
* think I'll leave it for now.
*
* @see org.sakaiproject.tool.gradebook.GradeMapping#getGrade(Double)
*/
public String getGrade(Double value) {
if(value == null) {
return null;
}
for (Iterator iter = getGrades().iterator(); iter.hasNext();) {
String grade = (String) iter.next();
Double mapVal = (Double) gradeMap.get(grade);
// If the value in the map is less than the value passed, then the
// map value is the letter grade for this value
if (mapVal != null && mapVal.compareTo(value) <= 0) {
return grade;
}
}
// As long as 'F' is zero, this should never happen.
return null;
}
////// Bean accessors and mutators //////
/**
* @return Returns the id.
*/
public Long getId() {
return id;
}
/**
* @param id
* The id to set.
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return Returns the version.
*/
public int getVersion() {
return version;
}
/**
* @param version
* The version to set.
*/
public void setVersion(int version) {
this.version = version;
}
/**
* @return Returns the gradeMap.
*/
public Map<String, Double> getGradeMap() {
return gradeMap;
}
/**
* @param gradeMap
* The gradeMap to set.
*/
public void setGradeMap(Map<String, Double> gradeMap) {
this.gradeMap = gradeMap;
}
/**
* @return Returns the gradebook.
*/
public Gradebook getGradebook() {
return gradebook;
}
/**
* @param gradebook
* The gradebook to set.
*/
public void setGradebook(Gradebook gradebook) {
this.gradebook = gradebook;
}
public int compareTo(Object o) {
return getName().compareTo(((GradeMapping)o).getName());
}
public String toString() {
return new ToStringBuilder(this).
append(getName()).
append(id).toString();
}
/**
* Enable any-case input of grades (typically lowercase input
* for uppercase grades). Look for a case-insensitive match
* to the input text and if it's found, return the official
* version.
*
* @return The normalized version of the grade, or null if not found.
*/
public String standardizeInputGrade(String inputGrade) {
String standardizedGrade = null;
for (Iterator iter = getGrades().iterator(); iter.hasNext(); ) {
String grade = (String)iter.next();
if (grade.equalsIgnoreCase(inputGrade)) {
standardizedGrade = grade;
break;
}
}
return standardizedGrade;
}
/**
* @return the GradingScale used to define this mapping, or null if
* this is an old Gradebook which uses hard-coded scales
*/
public GradingScale getGradingScale() {
return gradingScale;
}
public void setGradingScale(GradingScale gradingScale) {
this.gradingScale = gradingScale;
}
}
|
3e1a5e3665d7f5459973223af8e217129a2392db | 1,431 | java | Java | deployment/provisioning/src/main/java/SimpleHasher.java | meltmedia/cadmium | bca585030e141803a73b58abb128d130157b6ddf | [
"Apache-2.0"
] | 1 | 2016-11-14T03:57:15.000Z | 2016-11-14T03:57:15.000Z | deployment/provisioning/src/main/java/SimpleHasher.java | lovehoroscoper/cadmium | bca585030e141803a73b58abb128d130157b6ddf | [
"Apache-2.0"
] | 12 | 2015-04-13T17:45:53.000Z | 2022-01-27T16:18:25.000Z | deployment/provisioning/src/main/java/SimpleHasher.java | lovehoroscoper/cadmium | bca585030e141803a73b58abb128d130157b6ddf | [
"Apache-2.0"
] | 3 | 2015-05-21T22:01:43.000Z | 2016-11-14T03:45:35.000Z | 34.902439 | 84 | 0.737945 | 11,207 | import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.crypto.hash.format.DefaultHashFormatFactory;
import org.apache.shiro.crypto.hash.format.HashFormat;
import org.apache.shiro.crypto.hash.format.Shiro1CryptFormat;
import org.apache.shiro.util.ByteSource;
public class SimpleHasher {
public static void main(String args[]) {
if(args.length < 1) {
System.err.println("Please specify a password to hash!");
System.exit(1);
}
try {
int generatedSaltSize = 128;
String algorithm = DefaultPasswordService.DEFAULT_HASH_ALGORITHM;
int iterations = DefaultPasswordService.DEFAULT_HASH_ITERATIONS;
String formatString = Shiro1CryptFormat.class.getName();
char[] passwordToHash = args[0].toCharArray();
SecureRandomNumberGenerator generator = new SecureRandomNumberGenerator();
int byteSize = generatedSaltSize / 8;
ByteSource salt = generator.nextBytes(byteSize);
SimpleHash hash = new SimpleHash(algorithm, passwordToHash, salt, iterations);
HashFormat format = new DefaultHashFormatFactory().getInstance(formatString);
String output = format.format(hash);
System.out.println(output);
} catch (Throwable t) {
System.err.println(t.getMessage());
System.exit(1);
}
}
} |
3e1a5e93448b12cac9433585b1b25bc268362b2b | 2,269 | java | Java | server/src/main/java/io/deephaven/server/table/ops/MergeTablesGrpcImpl.java | mattrunyon/deephaven-core | 80e3567e4647ab76a81e483d0a8ab542f9aadace | [
"MIT"
] | 55 | 2021-05-11T16:01:59.000Z | 2022-03-30T14:30:33.000Z | server/src/main/java/io/deephaven/server/table/ops/MergeTablesGrpcImpl.java | mattrunyon/deephaven-core | 80e3567e4647ab76a81e483d0a8ab542f9aadace | [
"MIT"
] | 943 | 2021-05-10T14:00:02.000Z | 2022-03-31T21:28:15.000Z | server/src/main/java/io/deephaven/server/table/ops/MergeTablesGrpcImpl.java | mattrunyon/deephaven-core | 80e3567e4647ab76a81e483d0a8ab542f9aadace | [
"MIT"
] | 29 | 2021-05-10T11:33:16.000Z | 2022-03-30T21:01:54.000Z | 37.816667 | 118 | 0.721022 | 11,208 | package io.deephaven.server.table.ops;
import com.google.rpc.Code;
import io.deephaven.base.verify.Assert;
import io.deephaven.engine.table.Table;
import io.deephaven.engine.updategraph.UpdateGraphProcessor;
import io.deephaven.engine.util.TableTools;
import io.deephaven.extensions.barrage.util.GrpcUtil;
import io.deephaven.proto.backplane.grpc.BatchTableRequest;
import io.deephaven.proto.backplane.grpc.MergeTablesRequest;
import io.deephaven.server.session.SessionState;
import io.grpc.StatusRuntimeException;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
import java.util.stream.Collectors;
@Singleton
public class MergeTablesGrpcImpl extends GrpcTableOperation<MergeTablesRequest> {
private final UpdateGraphProcessor updateGraphProcessor;
@Inject
public MergeTablesGrpcImpl(final UpdateGraphProcessor updateGraphProcessor) {
super(BatchTableRequest.Operation::getMerge, MergeTablesRequest::getResultId,
MergeTablesRequest::getSourceIdsList);
this.updateGraphProcessor = updateGraphProcessor;
}
@Override
public void validateRequest(final MergeTablesRequest request) throws StatusRuntimeException {
if (request.getSourceIdsList().isEmpty()) {
throw GrpcUtil.statusRuntimeException(Code.INVALID_ARGUMENT, "Cannot merge zero source tables.");
}
}
@Override
public Table create(final MergeTablesRequest request, final List<SessionState.ExportObject<Table>> sourceTables) {
Assert.gt(sourceTables.size(), "sourceTables.size()", 0);
final String keyColumn = request.getKeyColumn();
final List<Table> tables = sourceTables.stream()
.map(SessionState.ExportObject::get)
.collect(Collectors.toList());
Table result;
if (tables.stream().noneMatch(table -> table.isRefreshing())) {
result = keyColumn.isEmpty() ? TableTools.merge(tables) : TableTools.mergeSorted(keyColumn, tables);
} else {
result = updateGraphProcessor.sharedLock().computeLocked(() -> TableTools.merge(tables));
if (!keyColumn.isEmpty()) {
result = result.sort(keyColumn);
}
}
return result;
}
}
|
3e1a5ede47eb591d997015be0c59b2638bc2928f | 339 | java | Java | backend/src/main/java/com/fellas/bespoke/controller/dto/request/QuestionRequest.java | altugcagri/boun-swe-574 | 2490800f92b9439a1b0bea46abcc3716acf85ea8 | [
"Apache-2.0"
] | 7 | 2019-09-24T06:08:44.000Z | 2019-11-01T22:01:02.000Z | backend/src/main/java/com/fellas/bespoke/controller/dto/request/QuestionRequest.java | altugcagri/boun-swe-574 | 2490800f92b9439a1b0bea46abcc3716acf85ea8 | [
"Apache-2.0"
] | 71 | 2019-09-25T08:39:42.000Z | 2022-03-08T23:03:10.000Z | backend/src/main/java/com/fellas/bespoke/controller/dto/request/QuestionRequest.java | altugcagri/boun-swe-574 | 2490800f92b9439a1b0bea46abcc3716acf85ea8 | [
"Apache-2.0"
] | null | null | null | 14.73913 | 50 | 0.772861 | 11,209 | package com.fellas.bespoke.controller.dto.request;
import lombok.*;
import org.springframework.lang.NonNull;
import javax.validation.constraints.NotBlank;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class QuestionRequest {
@NonNull
private Long contentId;
@NotBlank
private String text;
}
|
3e1a5f607de5234a674c60f2e978f92a7b197e73 | 3,351 | java | Java | src/test/java/com/coyotesong/coursera/cloud/hadoop/io/AirlineFlightDelaysWritableTest.java | beargiles/coursera-cloud-capstone | fc2a86c95856c37dc0f83f748324d63497680410 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/coyotesong/coursera/cloud/hadoop/io/AirlineFlightDelaysWritableTest.java | beargiles/coursera-cloud-capstone | fc2a86c95856c37dc0f83f748324d63497680410 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/coyotesong/coursera/cloud/hadoop/io/AirlineFlightDelaysWritableTest.java | beargiles/coursera-cloud-capstone | fc2a86c95856c37dc0f83f748324d63497680410 | [
"Apache-2.0"
] | 1 | 2019-06-24T18:23:55.000Z | 2019-06-24T18:23:55.000Z | 35.273684 | 119 | 0.670845 | 11,210 | package com.coyotesong.coursera.cloud.hadoop.io;
import org.junit.Test;
import com.coyotesong.coursera.cloud.domain.AirlineFlightDelays;
import static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
/**
* Test AirlineFlightDelaysWritable.
*
* TODO test add()
* TODO test calculation of mean and standard deviation
*
* @author bgiles
*/
public class AirlineFlightDelaysWritableTest {
@Test
public void testDefaultConstructor() {
final AirlineFlightDelays actual = new AirlineFlightDelaysWritable().getAirlineFlightDelays();
assertEquals(0, actual.getAirlineId());
assertEquals(0, actual.getNumFlights());
assertEquals(0, actual.getDelay());
assertEquals(0, actual.getDelaySquared());
assertEquals(0, actual.getMaxDelay());
assertEquals(0.0, actual.getMean(), 0.0001);
assertEquals(0.0, actual.getStdDev(), 0.0001);
}
@Test
public void testConstructor() {
final int airlineId = 1;
final int delay = 2;
final AirlineFlightDelays actual = new AirlineFlightDelaysWritable(airlineId, delay).getAirlineFlightDelays();
assertEquals(airlineId, actual.getAirlineId());
assertEquals(1, actual.getNumFlights());
assertEquals(2, actual.getDelay());
assertEquals(4, actual.getDelaySquared());
assertEquals(2, actual.getMaxDelay());
assertEquals(2.0, actual.getMean(), 0.0001);
assertEquals(0.0, actual.getStdDev(), 0.0001);
}
@Test
public void testConstructorInts() {
final int airlineId = 1;
final int[] values = new int[] { 2, -3, 4, 5 };
final AirlineFlightDelays actual = new AirlineFlightDelaysWritable(airlineId, values).getAirlineFlightDelays();
assertEquals(airlineId, actual.getAirlineId());
assertEquals(values[0], actual.getNumFlights());
assertEquals(values[1], actual.getDelay());
assertEquals(values[2], actual.getDelaySquared());
assertEquals(values[3], actual.getMaxDelay());
}
@Test
public void testDataStream() throws IOException {
final int airlineId = 1;
final int delay = 2;
final AirlineFlightDelaysWritable w = new AirlineFlightDelaysWritable(airlineId, delay);
byte[] data = null;
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos)) {
w.write(out);
data = baos.toByteArray();
}
final AirlineFlightDelaysWritable dw = new AirlineFlightDelaysWritable();
try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
DataInputStream in = new DataInputStream(bais)) {
dw.readFields(in);
}
final AirlineFlightDelays actual = dw.getAirlineFlightDelays();
assertEquals(airlineId, actual.getAirlineId());
assertEquals(1, actual.getNumFlights());
assertEquals(2, actual.getDelay());
assertEquals(4, actual.getDelaySquared());
assertEquals(2, actual.getMaxDelay());
assertEquals(2.0, actual.getMean(), 0.0001);
assertEquals(0.0, actual.getStdDev(), 0.0001);
}
}
|
3e1a5fd34ddf77b25a030431731dd9e3204c800b | 1,575 | java | Java | ratis-test/src/test/java/org/apache/ratis/shell/cli/sh/StringPrintStream.java | asad-awadia/ratis | afd33f77c5e080022ff86725f66c66ae4d9e8d06 | [
"Apache-2.0"
] | null | null | null | ratis-test/src/test/java/org/apache/ratis/shell/cli/sh/StringPrintStream.java | asad-awadia/ratis | afd33f77c5e080022ff86725f66c66ae4d9e8d06 | [
"Apache-2.0"
] | null | null | null | ratis-test/src/test/java/org/apache/ratis/shell/cli/sh/StringPrintStream.java | asad-awadia/ratis | afd33f77c5e080022ff86725f66c66ae4d9e8d06 | [
"Apache-2.0"
] | null | null | null | 32.8125 | 75 | 0.751111 | 11,211 | /*
* 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.ratis.shell.cli.sh;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
class StringPrintStream {
private Charset encoding = StandardCharsets.UTF_8;
private final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
private final PrintStream printStream;
StringPrintStream() {
try {
printStream = new PrintStream(bytes, true, encoding.name());
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
}
public PrintStream getPrintStream() {
return printStream;
}
@Override
public String toString() {
return bytes.toString();
}
}
|
3e1a6000eab5a4e3c5f4df36c2e6b96f324b8825 | 1,094 | java | Java | Telegram/src/main/java/com/github/jolice/bot/telegram/attachment/TelegramPhotoAttachment.java | severnake/BotPlatform | 3a80bab3fa1725bdee6a5cd788c04225afc79209 | [
"MIT"
] | 4 | 2019-10-03T19:22:58.000Z | 2019-12-05T06:02:28.000Z | Telegram/src/main/java/com/github/jolice/bot/telegram/attachment/TelegramPhotoAttachment.java | jolice/BotPlatform | 3a80bab3fa1725bdee6a5cd788c04225afc79209 | [
"MIT"
] | null | null | null | Telegram/src/main/java/com/github/jolice/bot/telegram/attachment/TelegramPhotoAttachment.java | jolice/BotPlatform | 3a80bab3fa1725bdee6a5cd788c04225afc79209 | [
"MIT"
] | 1 | 2019-12-05T06:02:31.000Z | 2019-12-05T06:02:31.000Z | 34.1875 | 108 | 0.785192 | 11,212 | package com.github.jolice.bot.telegram.attachment;
import com.pengrad.telegrambot.model.request.InputMediaPhoto;
import com.pengrad.telegrambot.request.SendPhoto;
import com.github.jolice.bot.telegram.attachment.support.AttachmentConfigurer;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import com.github.jolice.bot.attachment.AttachmentData;
import com.github.jolice.bot.attachment.PhotoAttachment;
@EqualsAndHashCode(callSuper = false)
@ToString
public class TelegramPhotoAttachment extends TelegramAttachment implements PhotoAttachment {
private InputMediaPhoto inputMediaPhoto;
public TelegramPhotoAttachment(AttachmentData attachmentData) {
super(attachmentData);
this.inputMediaPhoto = new InputMediaPhoto(attachmentData.getPath().toFile());
}
@Override
public void caption(String text) {
this.inputMediaPhoto.caption(text);
}
@Override
public void apply(AttachmentConfigurer dynamicAttachment) {
dynamicAttachment.setOrAdd(this.inputMediaPhoto, aLong -> new SendPhoto(aLong, getPath().toFile()));
}
}
|
3e1a6009c41d6b04b4ea0e5f72d9e2234f030e71 | 706 | java | Java | android/src/main/java/com/reactnativedirectpaysdk/DirectpaySdkPackage.java | directpaylk/react-native-directpay-ipg | 806c23de6b88dc62324cfff84ebf23d93dffb6de | [
"MIT"
] | null | null | null | android/src/main/java/com/reactnativedirectpaysdk/DirectpaySdkPackage.java | directpaylk/react-native-directpay-ipg | 806c23de6b88dc62324cfff84ebf23d93dffb6de | [
"MIT"
] | null | null | null | android/src/main/java/com/reactnativedirectpaysdk/DirectpaySdkPackage.java | directpaylk/react-native-directpay-ipg | 806c23de6b88dc62324cfff84ebf23d93dffb6de | [
"MIT"
] | null | null | null | 30.695652 | 89 | 0.796034 | 11,213 | package com.reactnativedirectpaysdk;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class DirectpaySdkPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Arrays.<ViewManager>asList(new DirectpaySdkViewManager());
}
}
|
3e1a606878ab16a76bb30be0c6150c095942198d | 3,010 | java | Java | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Red_jewel.java | ninjazrb/6717_ftc_app | ab6c65265b7293106ce051065d32fb0c86df9536 | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Red_jewel.java | ninjazrb/6717_ftc_app | ab6c65265b7293106ce051065d32fb0c86df9536 | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Red_jewel.java | ninjazrb/6717_ftc_app | ab6c65265b7293106ce051065d32fb0c86df9536 | [
"MIT"
] | null | null | null | 31.030928 | 111 | 0.619601 | 11,214 | package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.ColorSensor;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.util.Range;
import com.qualcomm.robotcore.util.ThreadPool;
/**
* Created by Zach on 11/14/2017.
*/
@Autonomous
public class Red_jewel extends LinearOpMode{
// Motor Declarations
DcMotor left_f;
DcMotor right_f;
DcMotor left_b;
DcMotor right_b;
Servo gripper;
Servo hammer; // Drops left
// Sensor Declarations
ColorSensor color;
public void runOpMode() throws InterruptedException {
left_b = hardwareMap.dcMotor.get("left_b");
left_f = hardwareMap.dcMotor.get("left_f");
right_b = hardwareMap.dcMotor.get("right_b");
right_f = hardwareMap.dcMotor.get("right_f");
gripper = hardwareMap.servo.get("gripper");
hammer = hardwareMap.servo.get("hammer");
color = hardwareMap.colorSensor.get("color");
left_b.setDirection(DcMotor.Direction.REVERSE);
left_f.setDirection(DcMotor.Direction.REVERSE);
gripper.setPosition(1.0);
hammer.setPosition(0.1);
waitForStart();
// Drop the hammer
hammer.setPosition(0.17);
Thread.sleep(5000);
// If the sensor sees red
if(color.red() > color.green() && color.red() > color.blue()) {
// Rotate away (Counter-clockwise)
setDrivePower(0.0, 1.0, -1.0);
Thread.sleep(500);
setDrivePower(0.0, 0.0, 0.0);
}
// If the sensor sees blue
if(color.blue() > color.green() && color.blue() > color.red()) {
// Rotate towards (Clockwise)
setDrivePower(0.0, 1.0, 1.0);
Thread.sleep(500);
setDrivePower(0.0, 0.0, 0.0);
}
hammer.setPosition(1.1);
}
public void setDrivePower(Double angleOfTravel, double speed, double skew) {
double RobotAngle = angleOfTravel - Math.PI/4;
double lf = Range.clip(Math.sin(RobotAngle) * speed - skew, -1, 1);
double rb = Range.clip(Math.sin(RobotAngle) * speed + skew, -1, 1);
double rf = Range.clip(Math.cos(RobotAngle) * speed + skew, -1, 1);
double lb = Range.clip(Math.cos(RobotAngle) * speed - skew, -1, 1);
/*double powers[] = driveSmoothing(lf, rb, rf, lb);
lf = powers[0];
rb = powers[1];
rf = powers[2];
lb = powers[3];*/
/*telemetry.addData("Left Front/Right Front: ", two_decimal.format(lf) + "/" + two_decimal.format(rf));
telemetry.addData("Left Back/Right Back: ", two_decimal.format(lb) + "/" + two_decimal.format(rb));
telemetry.update();*/
left_b.setPower(lb);
left_f.setPower(lf);
right_f.setPower(rf);
right_b.setPower(rb);
}
}
|
3e1a61dd23c182d907c3da3a781bba6c1269008d | 7,836 | java | Java | solver/src/main/java/io/nybbles/nqueens/visualizer/SolutionsPanel.java | jeffpanici75/n-queens | fe476c01bea7ab920f5c6571aa6e2aead16c3c21 | [
"MIT"
] | null | null | null | solver/src/main/java/io/nybbles/nqueens/visualizer/SolutionsPanel.java | jeffpanici75/n-queens | fe476c01bea7ab920f5c6571aa6e2aead16c3c21 | [
"MIT"
] | null | null | null | solver/src/main/java/io/nybbles/nqueens/visualizer/SolutionsPanel.java | jeffpanici75/n-queens | fe476c01bea7ab920f5c6571aa6e2aead16c3c21 | [
"MIT"
] | 1 | 2019-12-18T07:34:39.000Z | 2019-12-18T07:34:39.000Z | 44.271186 | 100 | 0.642164 | 11,215 | package io.nybbles.nqueens.visualizer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static io.nybbles.nqueens.visualizer.ChessBoardPanel.FilterType.*;
public class SolutionsPanel extends JPanel {
private final ChessBoardPanel _chessBoardPanel = new ChessBoardPanel();
private ActionListener _solverCompletionListener;
private final class ControlsPanel extends JPanel {
private int _solutionCount;
private boolean _solutionActive;
private JButton _nextButton = new JButton("Next");
private JButton _prevButton = new JButton("Prev");
private JCheckBox _showMirror = new JCheckBox("Show Mirror");
private JLabel _countLabel = new JLabel("Solution Count: 0");
private JCheckBox _showAllLines = new JCheckBox("Show All Lines");
private JLabel _solutionNumberLabel = new JLabel("Solution #: 0");
private JLabel _executionTimeLabel = new JLabel("Execution Time: 0ms");
private JCheckBox _showStraightLines = new JCheckBox("Show Straight Lines");
private JRadioButton _allSolutionsButton = new JRadioButton("All solutions");
private JRadioButton _validSolutionsButton = new JRadioButton("Valid solutions only");
private JRadioButton _invalidSolutionsButton = new JRadioButton("Invalid solutions only");
private void setButtonState(int index) {
var text = "Solution #: 0";
_showMirror.setEnabled(_solutionCount > 0);
_showAllLines.setEnabled(_solutionCount > 0);
_showStraightLines.setEnabled(_solutionCount > 0);
_allSolutionsButton.setEnabled(_solutionActive);
_validSolutionsButton.setEnabled(_solutionActive);
_invalidSolutionsButton.setEnabled(_solutionActive);
if (_solutionCount <= 1) {
_nextButton.setEnabled(false);
_prevButton.setEnabled(false);
} else {
_prevButton.setEnabled(index > 0);
_nextButton.setEnabled(index < _solutionCount - 1);
text = String.format(
"Solution #: %d",
_chessBoardPanel.getCurrentSolutionIndex() + 1);
}
_solutionNumberLabel.setText(text);
}
public ControlsPanel() {
super();
setLayout(new FlowLayout());
setBorder(BorderFactory.createLoweredBevelBorder());
var labelPanel = new JPanel();
labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.Y_AXIS));
labelPanel.add(Box.createRigidArea(new Dimension(10, 10)));
labelPanel.add(_countLabel);
labelPanel.add(Box.createRigidArea(new Dimension(10, 10)));
labelPanel.add(_solutionNumberLabel);
labelPanel.add(Box.createRigidArea(new Dimension(10, 10)));
labelPanel.add(_executionTimeLabel);
add(labelPanel);
var buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
buttonPanel.add(Box.createRigidArea(new Dimension(10, 10)));
buttonPanel.add(_prevButton);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 10)));
buttonPanel.add(_nextButton);
add(buttonPanel);
var checkBoxPanel = new JPanel();
checkBoxPanel.setLayout(new BoxLayout(checkBoxPanel, BoxLayout.Y_AXIS));
checkBoxPanel.add(Box.createRigidArea(new Dimension(10, 10)));
checkBoxPanel.add(_showAllLines);
checkBoxPanel.add(Box.createRigidArea(new Dimension(10, 10)));
checkBoxPanel.add(_showStraightLines);
checkBoxPanel.add(Box.createRigidArea(new Dimension(10, 10)));
checkBoxPanel.add(_showMirror);
add(checkBoxPanel);
var filterPanel = new JPanel();
filterPanel.setLayout(new BoxLayout(filterPanel, BoxLayout.Y_AXIS));
filterPanel.add(Box.createRigidArea(new Dimension(10, 10)));
filterPanel.add(_allSolutionsButton);
filterPanel.add(Box.createRigidArea(new Dimension(10, 10)));
filterPanel.add(_validSolutionsButton);
filterPanel.add(Box.createRigidArea(new Dimension(10, 10)));
filterPanel.add(_invalidSolutionsButton);
add(filterPanel);
_allSolutionsButton.setSelected(true);
_allSolutionsButton.setEnabled(false);
_allSolutionsButton.addActionListener(l -> _chessBoardPanel.setFilterType(ALL));
_validSolutionsButton.setSelected(false);
_validSolutionsButton.setEnabled(false);
_validSolutionsButton.addActionListener(l -> _chessBoardPanel.setFilterType(VALID));
_invalidSolutionsButton.setSelected(false);
_invalidSolutionsButton.setEnabled(false);
_invalidSolutionsButton.addActionListener(l -> _chessBoardPanel.setFilterType(INVALID));
var filterButtonGroup = new ButtonGroup();
filterButtonGroup.add(_allSolutionsButton);
filterButtonGroup.add(_validSolutionsButton);
filterButtonGroup.add(_invalidSolutionsButton);
_showAllLines.setSelected(_chessBoardPanel.getShowAllLines());
_showAllLines.setEnabled(false);
_showAllLines.addActionListener(l -> _chessBoardPanel.toggleShowAllLines());
_showStraightLines.setSelected(_chessBoardPanel.getShowStraightLines());
_showStraightLines.setEnabled(false);
_showStraightLines.addActionListener(l -> _chessBoardPanel.toggleShowStraightLines());
_showMirror.setSelected(_chessBoardPanel.getShowMirror());
_showMirror.setEnabled(false);
_showMirror.addActionListener(l -> _chessBoardPanel.toggleShowMirror());
_prevButton.setEnabled(false);
_prevButton.addActionListener(l -> {
_chessBoardPanel.moveToPrevSolution();
setButtonState(_chessBoardPanel.getCurrentSolutionIndex());
});
_nextButton.setEnabled(false);
_nextButton.addActionListener(l -> {
_chessBoardPanel.moveToNextSolution();
setButtonState(_chessBoardPanel.getCurrentSolutionIndex());
});
_chessBoardPanel.setSolutionChangeListener(l -> {
var source = (ChessBoardPanel.SolverEvent) l.getSource();
_countLabel.setText(String.format("Count: %d", source.count));
_executionTimeLabel.setText(String.format(
"Execution Time: %s",
source.formattedExecutionTime));
_solutionCount = source.count;
_solutionActive = source.active;
setButtonState(_chessBoardPanel.getCurrentSolutionIndex());
if (_solverCompletionListener != null) {
_solverCompletionListener.actionPerformed(new ActionEvent(
this,
0,
"solved"));
}
});
}
}
public SolutionsPanel() {
super();
setBorder(BorderFactory.createLoweredBevelBorder());
setLayout(new BorderLayout());
add(_chessBoardPanel, BorderLayout.CENTER);
var controlsPanel = new ControlsPanel();
add(controlsPanel, BorderLayout.SOUTH);
}
public void setN(int n) {
_chessBoardPanel.setN(n);
}
public void solveForN() {
_chessBoardPanel.solveForN();
}
public void setSolverCompletionListener(ActionListener l) {
_solverCompletionListener = l;
}
}
|
3e1a6235dddd9129d18dfdef38f3c1d504b60993 | 327 | java | Java | POO/src/avioes/Aviao.java | osvaldosandoli/javase | 7bb2c7eb9f8bf5c18f9462b8ed19c0065dafd2bf | [
"MIT"
] | null | null | null | POO/src/avioes/Aviao.java | osvaldosandoli/javase | 7bb2c7eb9f8bf5c18f9462b8ed19c0065dafd2bf | [
"MIT"
] | null | null | null | POO/src/avioes/Aviao.java | osvaldosandoli/javase | 7bb2c7eb9f8bf5c18f9462b8ed19c0065dafd2bf | [
"MIT"
] | null | null | null | 15.571429 | 46 | 0.648318 | 11,216 | package avioes;
import carros.Carro;
public class Aviao extends Carro {
public double envergadura;
public boolean tremPouso;
/**
* aterrzar
*/
public void aterrizar() {
System.out.println("Aviao pousou________");
}
/**
* acelerar
*/
public void acelerar() {
System.out.println("Aviao");
}
}
|
3e1a644e0996f4679f45e1d32be8e7ba7c2000b7 | 763 | java | Java | src/main/java/net/minecraft/client/renderer/GLAllocation.java | grialion/Modern-Utility | 4f1f75748ca83b8ccde5ed79bf3816c52ff425ec | [
"MIT"
] | null | null | null | src/main/java/net/minecraft/client/renderer/GLAllocation.java | grialion/Modern-Utility | 4f1f75748ca83b8ccde5ed79bf3816c52ff425ec | [
"MIT"
] | null | null | null | src/main/java/net/minecraft/client/renderer/GLAllocation.java | grialion/Modern-Utility | 4f1f75748ca83b8ccde5ed79bf3816c52ff425ec | [
"MIT"
] | null | null | null | 28.259259 | 120 | 0.722149 | 11,217 | package net.minecraft.client.renderer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
public class GLAllocation
{
/**
* Creates and returns a direct byte buffer with the specified capacity. Applies native ordering to speed up access.
*/
public static synchronized ByteBuffer createDirectByteBuffer(int capacity)
{
return ByteBuffer.allocateDirect(capacity).order(ByteOrder.nativeOrder());
}
/**
* Creates and returns a direct float buffer with the specified capacity. Applies native ordering to speed up
* access.
*/
public static FloatBuffer createDirectFloatBuffer(int capacity)
{
return createDirectByteBuffer(capacity << 2).asFloatBuffer();
}
}
|
3e1a645a0a48a8970b09e8afa531b2c2eef2ad41 | 1,115 | java | Java | DBConnnection/src/com/test/ConnectionManager.java | realspeed/SOAP-Training_Allianz | 70e25833152bc35a7239b087049aff298b6a22eb | [
"Unlicense"
] | null | null | null | DBConnnection/src/com/test/ConnectionManager.java | realspeed/SOAP-Training_Allianz | 70e25833152bc35a7239b087049aff298b6a22eb | [
"Unlicense"
] | null | null | null | DBConnnection/src/com/test/ConnectionManager.java | realspeed/SOAP-Training_Allianz | 70e25833152bc35a7239b087049aff298b6a22eb | [
"Unlicense"
] | null | null | null | 27.195122 | 95 | 0.70583 | 11,218 | package com.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConnectionManager {
static Connection con=null;
public static Connection getConnection() {
try {
//Class.forName("oracle.jdbc.driver.OracleDriver");
//con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
//Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql_schema","root","root");
} catch (Exception e) {
}
return con;
}
public static void main(String[] args) throws SQLException {
Connection con=ConnectionManager.getConnection();
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("SELECT * FROM VERTRAG");
System.out.println("VERTR# | POLLFNR | STADIUM | HSP_PRODUCT");
while (rs.next()) {
System.out.print(rs.getString(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getString(3)+"\t");
System.out.print(rs.getString(4));
}
}
} |
3e1a64653759735328312678f0753a372c3657c9 | 4,094 | java | Java | src/main/java/com/cellulant/Application.java | msegeya-interview/CellulantApp | 138193fb1bee98ef89898bd59e8dcd45024a2579 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/cellulant/Application.java | msegeya-interview/CellulantApp | 138193fb1bee98ef89898bd59e8dcd45024a2579 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/cellulant/Application.java | msegeya-interview/CellulantApp | 138193fb1bee98ef89898bd59e8dcd45024a2579 | [
"Apache-2.0"
] | null | null | null | 36.230088 | 254 | 0.717391 | 11,219 | package com.cellulant;
import com.cellulant.domain.Mileage;
import com.cellulant.repository.MileageRepository;
import com.cellulant.services.CellulantMileageMockedService;
import com.cellulant.services.DateAndTimeConversionService;
import com.cellulant.services.MileageService;
import com.cellulant.services.PdfReportGenerationService;
import java.io.FileNotFoundException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application implements CommandLineRunner {
private static final Logger LOG = Logger.getLogger(Application.class.getName());
@Autowired
private DateAndTimeConversionService dateAndTimeConversionService;
@Autowired
private CellulantMileageMockedService cellulantMileageMockedService;
@Autowired
private MileageRepository mileageRepository;
@Autowired
private ApplicationBootrapComponet applicationBootrapComponet;
@Autowired
private MileageService mileageService;
@Autowired
private PdfReportGenerationService pdfReportGenerationService;
private List<Mileage> mileages;
public Application() {
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... strings)
throws Exception {
cellulantAppMultiRecordsDatabaseOperations();
generateCellulantPdfReport();
}
/**
* This methods creates H2 Database table , prepares data , fetches
* kilometer data from webservice and then inserts them to the database
* table called mileage The script is found in
* src/main/resources/sql-scripts folder
*/
private void cellulantAppMultiRecordsDatabaseOperations() {
mileageRepository.createTable();
LOG.info("========= BEFORE INSERTING MILEAGE DATA ============");
LOG.log(Level.INFO, " FOUND {0} RECORDS", mileageService.findAll().size());
mileages = mileageService.retrieveMockMileageData();
mileages.stream().map((mileageRealData) -> {
LOG.log(Level.INFO, "mileage object \n lengthid={0}miles ={1} kilometers ={2}date_modified={3}", new Object[]{mileageRealData.getLength_id(), mileageRealData.getMiles(), mileageRealData.getKilometers(), mileageRealData.getDate_modified()});
return mileageRealData;
}).forEach((mileageRealData) -> {
mileageService.save(mileageRealData);
});
LOG.info("========= AFTER INSERTING MILEAGE DATA ============");
LOG.log(Level.INFO, " FOUND {0} RECORDS", mileageService.findAll().size());
Date input=new Date();
Timestamp timestamp=dateAndTimeConversionService.getTimestamp(input);
mileageService.updateTimeStamp(timestamp);
mileageService.findAll();
}
private void cellulantAppSingleRecordsDatabaseOperations() {
Mileage mileage = new Mileage();
mileage.setKilometers("9");
mileage.setLength_id(100L);
mileage.setMiles("89");
//mileage.setDate_modified(Timestamp.from(Instant.now()));
mileageRepository.createTable();
LOG.info("saving data to database");
mileageService.save(mileage);
}
/**
* This method will retrieves saved data from database an write them in Pdf
* file using Pdf service component autowired above Everythinhg is Abstra
* ted in the pdfReportGenerationService component
*/
private void generateCellulantPdfReport() throws FileNotFoundException {
LOG.info("========= GENERATING CELLULANT PDF REPORT ============");
String dest = "src/main/resources/CellurantPdfReport.pdf";
pdfReportGenerationService.generatePdfFile(dest);
}
}
|
3e1a648375cdbef318015ada32aee0b10c98911a | 1,720 | java | Java | veeline/src/main/java/sqlline/TableNameCompleter.java | breadchen/verdictdb | e64ae67135a21d79c6c1ba7c578a1dbcdba5bba4 | [
"Apache-2.0"
] | 1 | 2018-05-07T07:29:55.000Z | 2018-05-07T07:29:55.000Z | veeline/src/main/java/sqlline/TableNameCompleter.java | breadchen/verdictdb | e64ae67135a21d79c6c1ba7c578a1dbcdba5bba4 | [
"Apache-2.0"
] | 1 | 2018-05-07T06:30:41.000Z | 2018-05-07T06:30:41.000Z | veeline/src/main/java/sqlline/TableNameCompleter.java | breadchen/verdictdb | e64ae67135a21d79c6c1ba7c578a1dbcdba5bba4 | [
"Apache-2.0"
] | null | null | null | 30.175439 | 75 | 0.736047 | 11,220 | /*
* Copyright 2017 University of Michigan
*
* 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.
*/
/*
// Licensed to Julian Hyde under one or more contributor license
// agreements. See the NOTICE file distributed with this work for
// additional information regarding copyright ownership.
//
// Julian Hyde licenses this file to you under the Modified BSD License
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at:
//
// http://opensource.org/licenses/BSD-3-Clause
*/
package sqlline;
import java.util.List;
import jline.console.completer.Completer;
import jline.console.completer.StringsCompleter;
/**
* Suggests completions for table names.
*/
class TableNameCompleter implements Completer {
private SqlLine sqlLine;
public TableNameCompleter(SqlLine sqlLine) {
this.sqlLine = sqlLine;
}
public int complete(String buf, int pos, List<CharSequence> candidates) {
if (sqlLine.getDatabaseConnection() == null) {
return -1;
}
return new StringsCompleter(
sqlLine.getDatabaseConnection().getTableNames(true))
.complete(buf, pos, candidates);
}
}
// End TableNameCompleter.java
|
3e1a6485784ffe0893bba4174b9d1456e0426a9b | 680 | java | Java | ServerV0000/src/org/reldb/rel/v0/vm/instructions/tupleIteratable/OpTupleIteratableProject.java | DaveVoorhis/Rel | c4c0fa7843747b10923d27183536641cd1fda117 | [
"Apache-2.0"
] | 89 | 2015-04-21T22:34:19.000Z | 2022-02-20T06:00:26.000Z | ServerV0000/src/org/reldb/rel/v0/vm/instructions/tupleIteratable/OpTupleIteratableProject.java | DaveVoorhis/Rel | c4c0fa7843747b10923d27183536641cd1fda117 | [
"Apache-2.0"
] | 2 | 2018-09-21T22:27:49.000Z | 2021-06-07T14:03:15.000Z | ServerV0000/src/org/reldb/rel/v0/vm/instructions/tupleIteratable/OpTupleIteratableProject.java | DaveVoorhis/Rel | c4c0fa7843747b10923d27183536641cd1fda117 | [
"Apache-2.0"
] | 9 | 2015-04-03T16:27:38.000Z | 2021-06-07T13:52:52.000Z | 27.2 | 81 | 0.747059 | 11,221 | /**
*
*/
package org.reldb.rel.v0.vm.instructions.tupleIteratable;
import org.reldb.rel.v0.types.AttributeMap;
import org.reldb.rel.v0.values.TupleIteratable;
import org.reldb.rel.v0.vm.Context;
import org.reldb.rel.v0.vm.Instruction;
public final class OpTupleIteratableProject extends Instruction {
private AttributeMap map;
public OpTupleIteratableProject(AttributeMap map) {
this.map = map;
}
public final void execute(Context context) {
// Project the TupleIteratable on the stack using the provided AttributeMap.
// POP - Value (ValueRelation)
// PUSH - Value (ValueRelation)
context.push(((TupleIteratable)context.pop()).project(map));
}
} |
3e1a65bb7ee24ca5a07a41c86b8bca8e2474236d | 1,204 | java | Java | super-devops-iam/super-devops-iam-security/src/main/java/com/wl4g/devops/iam/authc/GithubAuthenticationToken.java | zhangzhizhong520/super-devops | 31379ba623d8c81b1543d99534365b1c5e3daf75 | [
"Apache-2.0"
] | 1 | 2019-11-11T08:28:05.000Z | 2019-11-11T08:28:05.000Z | super-devops-iam/super-devops-iam-security/src/main/java/com/wl4g/devops/iam/authc/GithubAuthenticationToken.java | zhangzhizhong520/super-devops | 31379ba623d8c81b1543d99534365b1c5e3daf75 | [
"Apache-2.0"
] | null | null | null | super-devops-iam/super-devops-iam-security/src/main/java/com/wl4g/devops/iam/authc/GithubAuthenticationToken.java | zhangzhizhong520/super-devops | 31379ba623d8c81b1543d99534365b1c5e3daf75 | [
"Apache-2.0"
] | null | null | null | 34.371429 | 117 | 0.737323 | 11,222 | /*
* Copyright 2017 ~ 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wl4g.devops.iam.authc;
import com.wl4g.devops.common.bean.iam.SocialAuthorizeInfo;
/**
* Github authentication token
*
* @author Wangl.sir <envkt@example.com>
* @version v1.0
* @date 2018年11月19日
* @since
*/
public class GithubAuthenticationToken extends Oauth2SnsAuthenticationToken {
private static final long serialVersionUID = 8587329689973009598L;
public GithubAuthenticationToken(String fromAppName, String redirectUrl, SocialAuthorizeInfo social, String host) {
super(fromAppName, redirectUrl, social, host);
}
} |
3e1a6620822563c09a11bad461c0c15fcac972e5 | 2,434 | java | Java | src/cmps252/HW4_2/UnitTesting/record_150.java | issasaidi/cmps252_hw4.2 | f8e96065e2a4f172c8b685f03f954694f4810c14 | [
"MIT"
] | 1 | 2020-11-03T07:31:40.000Z | 2020-11-03T07:31:40.000Z | src/cmps252/HW4_2/UnitTesting/record_150.java | issasaidi/cmps252_hw4.2 | f8e96065e2a4f172c8b685f03f954694f4810c14 | [
"MIT"
] | 2 | 2020-10-27T17:31:16.000Z | 2020-10-28T02:16:49.000Z | src/cmps252/HW4_2/UnitTesting/record_150.java | issasaidi/cmps252_hw4.2 | f8e96065e2a4f172c8b685f03f954694f4810c14 | [
"MIT"
] | 108 | 2020-10-26T11:54:05.000Z | 2021-01-16T20:00:17.000Z | 25.395833 | 77 | 0.732568 | 11,223 | package cmps252.HW4_2.UnitTesting;
import static org.junit.jupiter.api.Assertions.*;
import java.io.FileNotFoundException;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import cmps252.HW4_2.Customer;
import cmps252.HW4_2.FileParser;
@Tag("4")
class Record_150 {
private static List<Customer> customers;
@BeforeAll
public static void init() throws FileNotFoundException {
customers = FileParser.getCustomers(Configuration.CSV_File);
}
@Test
@DisplayName("Record 150: FirstName is Noble")
void FirstNameOfRecord150() {
assertEquals("Noble", customers.get(149).getFirstName());
}
@Test
@DisplayName("Record 150: LastName is Koenemund")
void LastNameOfRecord150() {
assertEquals("Koenemund", customers.get(149).getLastName());
}
@Test
@DisplayName("Record 150: Company is Peerless Hardware Mfg Co")
void CompanyOfRecord150() {
assertEquals("Peerless Hardware Mfg Co", customers.get(149).getCompany());
}
@Test
@DisplayName("Record 150: Address is 116 Fountain St")
void AddressOfRecord150() {
assertEquals("116 Fountain St", customers.get(149).getAddress());
}
@Test
@DisplayName("Record 150: City is Philadelphia")
void CityOfRecord150() {
assertEquals("Philadelphia", customers.get(149).getCity());
}
@Test
@DisplayName("Record 150: County is Philadelphia")
void CountyOfRecord150() {
assertEquals("Philadelphia", customers.get(149).getCounty());
}
@Test
@DisplayName("Record 150: State is PA")
void StateOfRecord150() {
assertEquals("PA", customers.get(149).getState());
}
@Test
@DisplayName("Record 150: ZIP is 19127")
void ZIPOfRecord150() {
assertEquals("19127", customers.get(149).getZIP());
}
@Test
@DisplayName("Record 150: Phone is 215-482-5520")
void PhoneOfRecord150() {
assertEquals("215-482-5520", customers.get(149).getPhone());
}
@Test
@DisplayName("Record 150: Fax is 215-482-7894")
void FaxOfRecord150() {
assertEquals("215-482-7894", customers.get(149).getFax());
}
@Test
@DisplayName("Record 150: Email is hzdkv@example.com")
void EmailOfRecord150() {
assertEquals("hzdkv@example.com", customers.get(149).getEmail());
}
@Test
@DisplayName("Record 150: Web is http://www.noblekoenemund.com")
void WebOfRecord150() {
assertEquals("http://www.noblekoenemund.com", customers.get(149).getWeb());
}
}
|
3e1a675af098b8cbe61ea9ed88825a3f0b797bfe | 2,169 | java | Java | sources/com/flurry/sdk/C7508dc.java | tusharchoudhary0003/Custom-Football-Game | 47283462b2066ad5c53b3c901182e7ae62a34fc8 | [
"MIT"
] | 1 | 2019-10-01T11:34:10.000Z | 2019-10-01T11:34:10.000Z | sources/com/flurry/sdk/C7508dc.java | tusharchoudhary0003/Custom-Football-Game | 47283462b2066ad5c53b3c901182e7ae62a34fc8 | [
"MIT"
] | null | null | null | sources/com/flurry/sdk/C7508dc.java | tusharchoudhary0003/Custom-Football-Game | 47283462b2066ad5c53b3c901182e7ae62a34fc8 | [
"MIT"
] | 1 | 2020-05-26T05:10:33.000Z | 2020-05-26T05:10:33.000Z | 32.373134 | 141 | 0.552328 | 11,224 | package com.flurry.sdk;
/* renamed from: com.flurry.sdk.dc */
public final class C7508dc {
/* renamed from: a */
public static final String f14798a = C7508dc.class.getSimpleName();
/* renamed from: b */
private static C7508dc f14799b = null;
/* renamed from: c */
public boolean f14800c = false;
private C7508dc() {
}
/* renamed from: a */
public static synchronized C7508dc m16634a() {
C7508dc dcVar;
synchronized (C7508dc.class) {
if (f14799b == null) {
f14799b = new C7508dc();
}
dcVar = f14799b;
}
return dcVar;
}
/* JADX WARNING: Code restructure failed: missing block: B:12:0x0014, code lost:
return p019d.p020e.p021a.C7294e.m15872d() != null ? p019d.p020e.p021a.C7294e.m15872d() : com.flurry.sdk.C7412Lb.m16398a().mo23854c();
*/
/* renamed from: b */
/* Code decompiled incorrectly, please refer to instructions dump. */
public final synchronized java.lang.String mo23946b() {
/*
r1 = this;
monitor-enter(r1)
boolean r0 = r1.f14800c // Catch:{ all -> 0x001e }
if (r0 != 0) goto L_0x0009
r0 = 0
monitor-exit(r1)
return r0
L_0x0009:
java.lang.String r0 = p019d.p020e.p021a.C7294e.m15872d() // Catch:{ all -> 0x001e }
if (r0 == 0) goto L_0x0015
java.lang.String r0 = p019d.p020e.p021a.C7294e.m15872d() // Catch:{ all -> 0x001e }
L_0x0013:
monitor-exit(r1)
return r0
L_0x0015:
com.flurry.sdk.Lb r0 = com.flurry.sdk.C7412Lb.m16398a() // Catch:{ all -> 0x001e }
java.lang.String r0 = r0.mo23854c() // Catch:{ all -> 0x001e }
goto L_0x0013
L_0x001e:
r0 = move-exception
monitor-exit(r1)
goto L_0x0022
L_0x0021:
throw r0
L_0x0022:
goto L_0x0021
*/
throw new UnsupportedOperationException("Method not decompiled: com.flurry.sdk.C7508dc.mo23946b():java.lang.String");
}
}
|
3e1a6868f91f8da87a005d0c05dd6409aa709f31 | 493 | java | Java | graphics-by-opengl-j2se/src/main/java/com/nucleus/vulkan/structs/VertexInputBindingDescription.java | rsahlin/graphics-by-opengl | a90ad4e649967f0dfac11017a4dc0ad97a0703e2 | [
"Apache-2.0"
] | 14 | 2015-04-10T11:23:29.000Z | 2022-03-30T14:05:54.000Z | graphics-by-opengl-j2se/src/main/java/com/nucleus/vulkan/structs/VertexInputBindingDescription.java | rsahlin/graphics-by-opengl | a90ad4e649967f0dfac11017a4dc0ad97a0703e2 | [
"Apache-2.0"
] | 2 | 2015-12-21T06:27:20.000Z | 2018-06-19T08:03:02.000Z | graphics-by-opengl-j2se/src/main/java/com/nucleus/vulkan/structs/VertexInputBindingDescription.java | rsahlin/graphics-by-opengl | a90ad4e649967f0dfac11017a4dc0ad97a0703e2 | [
"Apache-2.0"
] | 4 | 2019-11-17T01:01:12.000Z | 2022-03-30T14:05:56.000Z | 20.541667 | 50 | 0.675456 | 11,225 | package com.nucleus.vulkan.structs;
/**
* Wrapper for VkVertexInputBindingDescription
*/
public class VertexInputBindingDescription {
enum VertexInputRate {
VK_VERTEX_INPUT_RATE_VERTEX(0),
VK_VERTEX_INPUT_RATE_INSTANCE(1),
VK_VERTEX_INPUT_RATE_MAX_ENUM(0x7FFFFFFF);
public final int value;
private VertexInputRate(int value) {
this.value = value;
}
};
int binding;
int stride;
VertexInputRate inputRate;
}
|
3e1a6871b9913d8b172b656af1a29b2d187e5e2c | 5,248 | java | Java | src/test/java/ConversionTest.java | DRSchlaubi/mgisdumb | 05552e401873581da029fdbbbb97f38491dc0ef3 | [
"Apache-2.0"
] | 5 | 2020-05-01T18:31:44.000Z | 2021-01-11T21:45:22.000Z | src/test/java/ConversionTest.java | DRSchlaubi/kaesk | 05552e401873581da029fdbbbb97f38491dc0ef3 | [
"Apache-2.0"
] | null | null | null | src/test/java/ConversionTest.java | DRSchlaubi/kaesk | 05552e401873581da029fdbbbb97f38491dc0ef3 | [
"Apache-2.0"
] | null | null | null | 32 | 100 | 0.704268 | 11,226 | import java.util.Arrays;
import java.util.stream.Collectors;
import me.schlaubi.kaesk.api.ArgumentDeserializer;
import me.schlaubi.kaesk.api.converters.Converters;
import org.bukkit.GameMode;
import org.bukkit.OfflinePlayer;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class ConversionTest {
@Test
public void parseNormalInt() {
testPass(1, Converters.INTEGER, Integer.class);
testPass(10, Converters.INTEGER, Integer.class);
}
@Test
public void parseInvalidInt() {
testFail("Not A number", Converters.INTEGER, Integer.class);
testFail("10.0", Converters.INTEGER, Integer.class);
}
@Test
public void parseNormalInts() {
testVarargPass(new Integer[]{1, 2, 3, 4, 5, 79}, Converters.INTEGER, Integer.class);
}
@Test
public void parseInvalidInts() {
testVarArgFail("1.0 1 9", Converters.INTEGER, Integer.class);
testVarArgFail("not a number", Converters.INTEGER, Integer.class);
}
@Test
public void parseNormalFloat() {
testPass(1F, Converters.FLOAT, Float.class);
testPass(10F, Converters.FLOAT, Float.class);
}
@Test
public void parseInvalidFloat() {
testFail("Not A number", Converters.FLOAT, Float.class);
}
@Test
public void parseNormalFloats() {
testVarargPass(new Float[]{1F, 2F, 3F, 4F, 5F, 79F}, Converters.FLOAT, Float.class);
}
@Test
public void parseInvalidFloats() {
testVarArgFail("not a number", Converters.FLOAT, Float.class);
}
@Test
public void parseNormalDouble() {
testPass(1D, Converters.DOUBLE, Double.class);
testPass(10D, Converters.DOUBLE, Double.class);
}
@Test
public void parseInvalidDouble() {
testFail("Not A number", Converters.DOUBLE, Double.class);
}
@Test
public void parseNormalDoubles() {
testVarargPass(new Double[]{1D, 2D, 3D, 4D, 5D, 79D}, Converters.DOUBLE, Double.class);
}
@Test
public void parseInvalidDobules() {
testVarArgFail("not a number", Converters.FLOAT, Float.class);
}
@Test
public void parseNormalLong() {
testPass(1L, Converters.LONG, Long.class);
testPass(10L, Converters.LONG, Long.class);
}
@Test
public void parseInvalidLong() {
testFail("Not A number", Converters.LONG, Long.class);
}
@Test
public void parseNormalLongs() {
testVarargPass(new Long[]{1L, 2L, 3L, 4L, 5L, 79L}, Converters.LONG, Long.class);
}
@Test
public void parseInvalidLongs() {
testVarArgFail("not a number", Converters.LONG, Long.class);
}
// @Test
// public void testIllegalPlayerNames() {
// testFail("Inval$id", Converters.OFFLINE_PLAYER, OfflinePlayer.class);
// testFail("to", Converters.OFFLINE_PLAYER, OfflinePlayer.class);
// testFail("sh", Converters.OFFLINE_PLAYER, OfflinePlayer.class);
// testFail("or", Converters.OFFLINE_PLAYER, OfflinePlayer.class);
// testFail("t", Converters.OFFLINE_PLAYER, OfflinePlayer.class);
// testVarArgFail("Inval$id id did __ ,,", Converters.OFFLINE_PLAYER, OfflinePlayer.class);
// testVarArgFail("to sh o rt", Converters.OFFLINE_PLAYER, OfflinePlayer.class);
// }
@Test
public void testEnums() {
var deserializers = Converters.newEnumDeserializer(GameMode[]::new);
testPass(GameMode.CREATIVE, deserializers, GameMode.class);
testPass(GameMode.ADVENTURE, deserializers, GameMode.class);
testPass(GameMode.SURVIVAL, deserializers, GameMode.class);
}
@Test
public void testInvalidEnums() {
var deserializers = Converters.newEnumDeserializer(GameMode[]::new);
testFail("GRARG", deserializers, GameMode.class);
}
private <T> void testVarargPass(T[] input, ArgumentDeserializer<T> deserializer, Class<?> clazz) {
var args = Arrays.stream(input).map(Object::toString).collect(Collectors.joining(" "));
var parsed = testVararg(args, deserializer, true, clazz);
Assertions.assertArrayEquals(input, parsed, "Parsed value should be the same");
}
private <T> void testVarArgFail(String input, ArgumentDeserializer<T> deserializer,
Class<?> clazz) {
testVararg(input, deserializer, false, clazz);
}
private <T> T[] testVararg(String input, ArgumentDeserializer<T> deserializer, boolean isValid,
Class<?> clazz) {
var args = input.split("\\s+");
Assertions.assertEquals(isValid, deserializer.varargIsValid(args, clazz),
String.format("Is valid is expected to be %s", isValid));
if (!isValid) {
return null;
}
return deserializer.deserializeVararg(args, clazz);
}
private <T> void testPass(T input, ArgumentDeserializer<T> deserializer, Class<?> clazz) {
T parsed = test(input.toString(), deserializer, true, clazz);
Assertions.assertEquals(input, parsed, "Parsed value should be the same");
}
private <T> void testFail(String input, ArgumentDeserializer<T> deserializer, Class<?> clazz) {
test(input, deserializer, false, clazz);
}
private <T> T test(String input, ArgumentDeserializer<T> deserializer, boolean isValid,
Class<?> clazz) {
Assertions.assertEquals(isValid, deserializer.isValid(input, clazz),
String.format("Is valid is expected to be %s", isValid));
if (!isValid) {
return null;
}
return deserializer.deserialize(input, clazz);
}
}
|
3e1a69eb5ef621bbd77bdffeea1ae9b552dc39ef | 3,426 | java | Java | hamster-selenium-component-html/src/main/java/com/github/grossopa/selenium/component/html/HtmlComponents.java | grossopa/hamster-selenium | e8fe83d91507b4e878f2771f7842ca4932e6662f | [
"MIT"
] | null | null | null | hamster-selenium-component-html/src/main/java/com/github/grossopa/selenium/component/html/HtmlComponents.java | grossopa/hamster-selenium | e8fe83d91507b4e878f2771f7842ca4932e6662f | [
"MIT"
] | 14 | 2020-12-11T05:41:46.000Z | 2021-11-15T13:13:07.000Z | hamster-selenium-component-html/src/main/java/com/github/grossopa/selenium/component/html/HtmlComponents.java | grossopa/hamster-selenium | e8fe83d91507b4e878f2771f7842ca4932e6662f | [
"MIT"
] | 1 | 2020-10-13T19:36:27.000Z | 2020-10-13T19:36:27.000Z | 35.6875 | 118 | 0.68272 | 11,227 | /*
* Copyright © 2021 the original author or authors.
*
* Licensed under the The MIT License (MIT) (the "License");
* You may obtain a copy of the License at
*
* https://mit-license.org/
*
* 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.github.grossopa.selenium.component.html;
import com.github.grossopa.selenium.component.html.factory.HtmlFormFieldFactory;
import com.github.grossopa.selenium.component.html.factory.HtmlSelectFactory;
import com.github.grossopa.selenium.component.html.factory.HtmlTableFactory;
import com.github.grossopa.selenium.core.component.AbstractComponents;
/**
* Contains all HTML components.
*
* @author Jack Yin
* @since 1.0
*/
public class HtmlComponents extends AbstractComponents {
/**
* Creates an HTML Form field component from the given {@link org.openqa.selenium.WebElement}.
*
* <p>
* The given element could be any container type but must contain one element with label "<label>" and input
* element "<input>".
* </p>
*
* @return the created instance of {@link HtmlFormField}
* @see HtmlFormField
*/
public HtmlFormField toFormField() {
return this.component.to(new HtmlFormFieldFactory());
}
/**
* Creates an HTML Table component from the given {@link org.openqa.selenium.WebElement}.
*
* <p>
* The given element must be "<table>" and with "<tr><th>" and/or "<tr><td>"
* </p>
*
* @return the created instance of {@link HtmlTable}
* @see HtmlTable
*/
public HtmlTable toTable() {
return this.component.to(new HtmlTableFactory());
}
/**
* Creates an HTML Select component from the given {@link org.openqa.selenium.WebElement}.
*
* <p>
* The given element must be "<select>"
* </p>
*
* @return the created instance of {@link HtmlSelect}
* @see HtmlSelect
*/
public HtmlSelect toSelect() {
return this.component.to(new HtmlSelectFactory());
}
/**
* Returns new instance of this class.
*
* <p>
* Example: {@code HtmlSelect select = driver.findComponent(By.id("cars")).as(html()).toSelect();}
* </p>
*
* @return the instance of {@link HtmlComponents}
*/
public static HtmlComponents html() {
return new HtmlComponents();
}
}
|
3e1a6a257b29702bd95092dbc04acdeab804aad7 | 2,865 | java | Java | src/main/java/hedera/starter/hederaFile/FileController.java | alexjavabraz/hedera-starter-spring | 9e85c9ff812bb712c93cbb860a6d0c72d06cdcb6 | [
"Apache-2.0"
] | 3 | 2021-02-04T21:59:29.000Z | 2022-02-14T16:23:10.000Z | src/main/java/hedera/starter/hederaFile/FileController.java | ishitaojha/hedera-starter-spring | 105e3f5a27b3568e4540c978b276a7de9629d4bb | [
"Apache-2.0"
] | null | null | null | src/main/java/hedera/starter/hederaFile/FileController.java | ishitaojha/hedera-starter-spring | 105e3f5a27b3568e4540c978b276a7de9629d4bb | [
"Apache-2.0"
] | 6 | 2021-02-04T21:57:41.000Z | 2022-03-04T11:07:47.000Z | 38.716216 | 123 | 0.682373 | 11,228 | package hedera.starter.hederaFile;
import com.hedera.hashgraph.sdk.HederaStatusException;
import com.hedera.hashgraph.sdk.file.FileInfo;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@Api("Handles management of Hedera File Service")
@RequestMapping(path = "/file")
public class FileController {
/**
* File Create
* File Delete
* File Info
* TODO: File Update
* File Append
* File Content Query
*/
@Autowired
FileService fileService;
public FileController() {
fileService = new FileService();
}
@PostMapping("")
@ApiOperation("Create a File")
@ApiImplicitParam(name = "text", type = "String", example = "Adding text to file...")
@ApiResponses(value = {@ApiResponse(code = 200, message = "File ID")})
public String createFile(@RequestParam(defaultValue = "") String text) throws HederaStatusException {
return fileService.createFile(text);
}
@DeleteMapping("/{fileId}")
@ApiOperation("Delete a file")
@ApiImplicitParam(name = "fileId", required = true, type = "String", example = "0.0.3117")
@ApiResponses(value = {@ApiResponse(code = 200, message = "success or failure")})
public boolean deleteFile(@PathVariable String fileId) throws HederaStatusException {
return fileService.deleteFile(fileId);
}
@GetMapping("/{fileId}")
@ApiOperation("Get info on a file")
@ApiImplicitParam(name = "fileId", required = true, type = "String", example = "0.0.3117")
public FileInfo getFileInfo(@PathVariable String fileId) throws HederaStatusException {
return fileService.getFileInfo(fileId);
}
@PutMapping("")
@ApiOperation("Append contents to a file")
@ApiImplicitParam(name = "fileId", required = true, type = "String", example = "0.0.3117")
@ApiImplicitParams({
@ApiImplicitParam(name = "fileId", required = true, type = "String", example = "0.0.3117"),
@ApiImplicitParam(name = "text", required = true, type = "String", example = "adding more content to file...")
})
@ApiResponses(value = {@ApiResponse(code = 200, message = "success or failure")})
public boolean appendFile(@RequestParam String fileId, @RequestParam String text) throws HederaStatusException {
return fileService.appendToFile(fileId, text);
}
@GetMapping("/content/{fileId}")
@ApiOperation("Get contents on a file")
@ApiImplicitParam(name = "fileId", required = true, type = "String", example = "0.0.3117")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Content of a file")})
public String getFileContents(@PathVariable String fileId) throws HederaStatusException {
return fileService.queryFileContent(fileId);
}
}
|
3e1a6cd019a327a0e574b6b8ff132776f4df80e9 | 1,812 | java | Java | ngraph/src/gen/java/org/bytedeco/ngraph/StringStringMap.java | oxisto/javacpp-presets | a70841e089cbe4269cd3e1b1e6de2005c3b4aa16 | [
"Apache-2.0"
] | 2,132 | 2015-01-14T10:02:38.000Z | 2022-03-31T07:51:08.000Z | ngraph/src/gen/java/org/bytedeco/ngraph/StringStringMap.java | oxisto/javacpp-presets | a70841e089cbe4269cd3e1b1e6de2005c3b4aa16 | [
"Apache-2.0"
] | 1,024 | 2015-01-11T18:35:03.000Z | 2022-03-31T14:52:22.000Z | ngraph/src/gen/java/org/bytedeco/ngraph/StringStringMap.java | oxisto/javacpp-presets | a70841e089cbe4269cd3e1b1e6de2005c3b4aa16 | [
"Apache-2.0"
] | 759 | 2015-01-15T08:41:48.000Z | 2022-03-29T17:05:57.000Z | 42.139535 | 109 | 0.707506 | 11,229 | // Targeted by JavaCPP version 1.5.6: DO NOT EDIT THIS FILE
package org.bytedeco.ngraph;
import org.bytedeco.ngraph.Allocator;
import org.bytedeco.ngraph.Function;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.ngraph.global.ngraph.*;
@Name("std::map<std::string,std::string>") @Properties(inherit = org.bytedeco.ngraph.presets.ngraph.class)
public class StringStringMap extends Pointer {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public StringStringMap(Pointer p) { super(p); }
public StringStringMap() { allocate(); }
private native void allocate();
public native @Name("operator =") @ByRef StringStringMap put(@ByRef StringStringMap x);
public boolean empty() { return size() == 0; }
public native long size();
@Index public native @StdString BytePointer get(@StdString BytePointer i);
public native StringStringMap put(@StdString BytePointer i, BytePointer value);
@ValueSetter @Index public native StringStringMap put(@StdString BytePointer i, @StdString String value);
public native void erase(@ByVal Iterator pos);
public native @ByVal Iterator begin();
public native @ByVal Iterator end();
@NoOffset @Name("iterator") public static class Iterator extends Pointer {
public Iterator(Pointer p) { super(p); }
public Iterator() { }
public native @Name("operator ++") @ByRef Iterator increment();
public native @Name("operator ==") boolean equals(@ByRef Iterator it);
public native @Name("operator *().first") @MemberGetter @StdString BytePointer first();
public native @Name("operator *().second") @MemberGetter @StdString BytePointer second();
}
}
|
3e1a6d0770a15bb272bf7af245ad1131bdd4bad6 | 5,450 | java | Java | wear/5WMessage/wear/src/main/java/io/wearbook/wmessage/WMessageWearActivity.java | smitzey/wearbooksource | e4b5ad562564f8be085775a50248c8c1b41ce708 | [
"Apache-2.0"
] | 6 | 2016-10-01T19:09:44.000Z | 2020-08-16T12:45:09.000Z | wear/5WMessage/wear/src/main/java/io/wearbook/wmessage/WMessageWearActivity.java | smitzey/wearbooksource | e4b5ad562564f8be085775a50248c8c1b41ce708 | [
"Apache-2.0"
] | null | null | null | wear/5WMessage/wear/src/main/java/io/wearbook/wmessage/WMessageWearActivity.java | smitzey/wearbooksource | e4b5ad562564f8be085775a50248c8c1b41ce708 | [
"Apache-2.0"
] | 4 | 2016-05-19T12:58:38.000Z | 2018-07-08T03:29:36.000Z | 28.385417 | 181 | 0.634495 | 11,230 | package io.wearbook.wmessage;
import android.app.Activity;
import android.content.IntentSender;
import android.os.Bundle;
import android.support.wearable.view.WatchViewStub;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;
import java.security.SecureRandom;
public class WMessageWearActivity extends Activity
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
// private TextView titleTextView;
private TextView dataTextView ;
private WatchViewStub stub ;
private String message ;
private GoogleApiClient googleApiClient ;
private boolean authInProgress = false ;
private static final int RESULT_RESOLUTION = 99 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wmessage_wear);
stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
@Override
public void onLayoutInflated(WatchViewStub stub) {
// titleTextView = (TextView) stub.findViewById(R.id.headingTextView);
dataTextView = (TextView) stub.findViewById(R.id.text);
//Log.d(TAG, "onCreate() titleTextView| dataTextView=" + titleTextView + " | " + dataTextView) ;
message = String.valueOf( new SecureRandom().nextInt()) ;
if ( message!=null) {
dataTextView.setText(message) ;
}
}
});
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onRestart() {
super.onRestart();
}
@Override
protected void onResume() {
super.onResume();
connectGoogleApiClient();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
private void connectGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.addApi(Wearable.API)
.addConnectionCallbacks( this)
.addOnConnectionFailedListener(this)
.build();
googleApiClient.connect();
Log.d(TAG, "connectGoogleApiClient() googleApiClient isConnecting=" + googleApiClient.isConnecting()) ;
}
@Override
public void onConnected(Bundle bundle) {
Log.d( TAG, "GoogleApiClient.ConnectionCallbacks::onConnected() " + Wearable.API.getName() ) ;
// send the message
sendMessage( message);
}
private void sendMessage ( final String message ) {
Log.d ( TAG, "sendMessage() gonna attempt sending message=" + message) ;
new Thread( new Runnable() {
@Override
public void run() {
NodeApi.GetConnectedNodesResult connectedNodesResult =
Wearable.NodeApi.getConnectedNodes( googleApiClient ).await() ;
Log.d ( TAG, "sendMessage() connectedNodesResult | status | connectedNodesResult.size" + connectedNodesResult + " | status= " + connectedNodesResult.getStatus() +
" | " + connectedNodesResult.getNodes().size()) ;
for(Node aNode : connectedNodesResult.getNodes()) {
MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(
googleApiClient, aNode.getId(), MESSAGE_PATH, message.getBytes() ).await();
Log.d ( TAG, "sendMessage() sent message --> nodeId/displayName/isNearby " + message + "--> [ " + aNode.getId() + "," + aNode.getDisplayName() +
", " + aNode.isNearby() + " ]" ) ;
}
}
}).start();
}
@Override
public void onConnectionSuspended(int i) {
Log.d( TAG, "GoogleApiClient.ConnectionCallbacks::onConnectionSuspended ..." );
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d( TAG, "GoogleApiClient.ConnectionCallbacks::onConnectionFailed connectionResult=" + connectionResult );
//connectionResult.getErrorCode()
if (!connectionResult.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(),
this, 0).show();
} else if ( !authInProgress) {
authInProgress = true ;
try {
connectionResult.startResolutionForResult( this, RESULT_RESOLUTION) ;
} catch ( IntentSender.SendIntentException ise) {
Log.e ( TAG, "onConnectionFailed exception ise=" + ise ) ;
}
}
}
private static final String MESSAGE_PATH = "/io.wearbook.wmessage.IMPORTANT_RANDOM_MESSAGE" ;
private static final String TAG = WMessageWearActivity.class.getName() ;
}
|
3e1a6e16c9a724bac5542110d8e307a7023130e9 | 443 | java | Java | app/src/main/java/com/aliasadi/mvvm/data/repository/movie/MovieRepository.java | gcasasbe7/Android-MVVM-Architecture | 0e39ed1526fdd6be2977ecc63f0f97e9edf88404 | [
"Apache-2.0"
] | 29 | 2021-03-27T10:27:21.000Z | 2022-03-15T23:12:00.000Z | app/src/main/java/com/aliasadi/mvvm/data/repository/movie/MovieRepository.java | gcasasbe7/Android-MVVM-Architecture | 0e39ed1526fdd6be2977ecc63f0f97e9edf88404 | [
"Apache-2.0"
] | 1 | 2021-04-16T02:41:53.000Z | 2021-12-10T13:41:14.000Z | app/src/main/java/com/aliasadi/mvvm/data/repository/movie/MovieRepository.java | gcasasbe7/Android-MVVM-Architecture | 0e39ed1526fdd6be2977ecc63f0f97e9edf88404 | [
"Apache-2.0"
] | 8 | 2021-04-03T22:24:10.000Z | 2022-02-23T18:29:50.000Z | 21.095238 | 48 | 0.706546 | 11,231 | package com.aliasadi.mvvm.data.repository.movie;
import com.aliasadi.mvvm.data.domain.Movie;
import java.util.List;
/**
* Created by Ali Asadi on 05/04/2021
*/
public interface MovieRepository {
interface LoadMoviesCallback {
void onMoviesLoaded(List<Movie> movies);
void onDataNotAvailable();
void onError();
}
void getMovies(LoadMoviesCallback callback);
void saveMovies(List<Movie> movies);
}
|
3e1a6f8f5ce04e16656b04b2a6af14ec668677c4 | 3,056 | java | Java | hutool-core/src/test/java/cn/hutool/core/bean/BeanPathTest.java | Gsealy/hutool | a9889ccabaf18ee2bd3c5be6b75ef383d5ac3e3d | [
"Apache-2.0"
] | 10 | 2019-10-10T16:23:21.000Z | 2022-03-07T02:25:55.000Z | hutool-core/src/test/java/cn/hutool/core/bean/BeanPathTest.java | 809674398/hutool | 955aca2289f79e5cd9842749d0717c379a23914b | [
"MulanPSL-1.0"
] | 6 | 2020-10-14T03:09:42.000Z | 2022-01-28T11:52:43.000Z | hutool-core/src/test/java/cn/hutool/core/bean/BeanPathTest.java | 809674398/hutool | 955aca2289f79e5cd9842749d0717c379a23914b | [
"MulanPSL-1.0"
] | 3 | 2019-02-15T07:28:47.000Z | 2019-08-16T05:41:29.000Z | 29.960784 | 76 | 0.685864 | 11,232 | package cn.hutool.core.bean;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import cn.hutool.core.lang.test.bean.ExamInfoDict;
import cn.hutool.core.lang.test.bean.UserInfoDict;
/**
* {@link BeanPath} 单元测试
*
* @author looly
*
*/
public class BeanPathTest {
Map<String, Object> tempMap;
@Before
public void init() {
// ------------------------------------------------- 考试信息列表
ExamInfoDict examInfoDict = new ExamInfoDict();
examInfoDict.setId(1);
examInfoDict.setExamType(0);
examInfoDict.setAnswerIs(1);
ExamInfoDict examInfoDict1 = new ExamInfoDict();
examInfoDict1.setId(2);
examInfoDict1.setExamType(0);
examInfoDict1.setAnswerIs(0);
ExamInfoDict examInfoDict2 = new ExamInfoDict();
examInfoDict2.setId(3);
examInfoDict2.setExamType(1);
examInfoDict2.setAnswerIs(0);
List<ExamInfoDict> examInfoDicts = new ArrayList<ExamInfoDict>();
examInfoDicts.add(examInfoDict);
examInfoDicts.add(examInfoDict1);
examInfoDicts.add(examInfoDict2);
// ------------------------------------------------- 用户信息
UserInfoDict userInfoDict = new UserInfoDict();
userInfoDict.setId(1);
userInfoDict.setPhotoPath("yx.mm.com");
userInfoDict.setRealName("张三");
userInfoDict.setExamInfoDict(examInfoDicts);
tempMap = new HashMap<String, Object>();
tempMap.put("userInfo", userInfoDict);
tempMap.put("flag", 1);
}
@Test
public void beanPathTest1() {
BeanPath pattern = new BeanPath("userInfo.examInfoDict[0].id");
Assert.assertEquals("userInfo", pattern.patternParts.get(0));
Assert.assertEquals("examInfoDict", pattern.patternParts.get(1));
Assert.assertEquals("0", pattern.patternParts.get(2));
Assert.assertEquals("id", pattern.patternParts.get(3));
}
@Test
public void beanPathTest2() {
BeanPath pattern = new BeanPath("[userInfo][examInfoDict][0][id]");
Assert.assertEquals("userInfo", pattern.patternParts.get(0));
Assert.assertEquals("examInfoDict", pattern.patternParts.get(1));
Assert.assertEquals("0", pattern.patternParts.get(2));
Assert.assertEquals("id", pattern.patternParts.get(3));
}
@Test
public void beanPathTest3() {
BeanPath pattern = new BeanPath("['userInfo']['examInfoDict'][0]['id']");
Assert.assertEquals("userInfo", pattern.patternParts.get(0));
Assert.assertEquals("examInfoDict", pattern.patternParts.get(1));
Assert.assertEquals("0", pattern.patternParts.get(2));
Assert.assertEquals("id", pattern.patternParts.get(3));
}
@Test
public void getTest() {
BeanPath pattern = BeanPath.create("userInfo.examInfoDict[0].id");
Object result = pattern.get(tempMap);
Assert.assertEquals(1, result);
}
@Test
public void setTest() {
BeanPath pattern = BeanPath.create("userInfo.examInfoDict[0].id");
pattern.set(tempMap, 2);
Object result = pattern.get(tempMap);
Assert.assertEquals(2, result);
}
}
|
3e1a7060561e9535b43b4cacb18df56e10095427 | 677 | java | Java | src/main/java/com/paas/repository/BaseRepositoryImpl.java | olegoseev/PaaS | 9a81087014e2ed64e6d059a97e6f3e4c92d88d82 | [
"MIT"
] | null | null | null | src/main/java/com/paas/repository/BaseRepositoryImpl.java | olegoseev/PaaS | 9a81087014e2ed64e6d059a97e6f3e4c92d88d82 | [
"MIT"
] | null | null | null | src/main/java/com/paas/repository/BaseRepositoryImpl.java | olegoseev/PaaS | 9a81087014e2ed64e6d059a97e6f3e4c92d88d82 | [
"MIT"
] | null | null | null | 24.178571 | 82 | 0.759232 | 11,233 | package com.paas.repository;
import java.util.List;
import com.paas.PaaSApplicationException;
public abstract class BaseRepositoryImpl<PK, T> implements BaseRepository<PK, T> {
@Override
public abstract List<T> findAll() throws PaaSApplicationException;
@Override
public List<T> findAny(T criteria) throws PaaSApplicationException {
List<T> records = findAll();
return applyFilter(records, criteria);
}
protected abstract List<T> applyFilter(List<T> records, T criteria);
@Override
public T findBy(PK pk) throws PaaSApplicationException {
List<T> records = findAll();
return filterByPk(pk, records);
}
abstract T filterByPk(PK pk, List<T> records);
}
|
3e1a706b37db8bd98d6fbb558775e95cb188cff0 | 25,110 | java | Java | java/org/l2jserver/gameserver/model/actor/instance/AuctioneerInstance.java | Williams-BR/L2JStudio-V2 | f3d3b329657c0f031dab107e6d4ceb5ddad0bea6 | [
"MIT"
] | 6 | 2020-05-14T22:52:59.000Z | 2022-02-24T01:37:23.000Z | java/org/l2jserver/gameserver/model/actor/instance/AuctioneerInstance.java | huttysa/L2JServer_C6_Interlude | f3d3b329657c0f031dab107e6d4ceb5ddad0bea6 | [
"MIT"
] | 2 | 2020-12-10T15:08:48.000Z | 2021-12-01T01:01:46.000Z | java/org/l2jserver/gameserver/model/actor/instance/AuctioneerInstance.java | huttysa/L2JServer_C6_Interlude | f3d3b329657c0f031dab107e6d4ceb5ddad0bea6 | [
"MIT"
] | 15 | 2020-05-08T20:41:06.000Z | 2022-02-24T01:36:58.000Z | 35.974212 | 310 | 0.659299 | 11,234 | /*
* This file is part of the L2JServer project.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package org.l2jserver.gameserver.model.actor.instance;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.l2jserver.gameserver.ai.CtrlIntention;
import org.l2jserver.gameserver.datatables.xml.MapRegionData;
import org.l2jserver.gameserver.instancemanager.AuctionManager;
import org.l2jserver.gameserver.instancemanager.ClanHallManager;
import org.l2jserver.gameserver.model.actor.templates.NpcTemplate;
import org.l2jserver.gameserver.model.clan.Clan;
import org.l2jserver.gameserver.model.entity.Auction;
import org.l2jserver.gameserver.model.entity.Auction.Bidder;
import org.l2jserver.gameserver.network.serverpackets.ActionFailed;
import org.l2jserver.gameserver.network.serverpackets.MyTargetSelected;
import org.l2jserver.gameserver.network.serverpackets.NpcHtmlMessage;
import org.l2jserver.gameserver.network.serverpackets.ValidateLocation;
public class AuctioneerInstance extends FolkInstance
{
private static final int COND_ALL_FALSE = 0;
private static final int COND_BUSY_BECAUSE_OF_SIEGE = 1;
private static final int COND_REGULAR = 3;
private final Map<Integer, Auction> _pendingAuctions = new HashMap<>();
public AuctioneerInstance(int objectId, NpcTemplate template)
{
super(objectId, template);
}
@Override
public void onAction(PlayerInstance player)
{
if (!canTarget(player))
{
return;
}
player.setLastFolkNPC(this);
// Check if the PlayerInstance already target the NpcInstance
if (this != player.getTarget())
{
// Set the target of the PlayerInstance player
player.setTarget(this);
// Send a Server->Client packet MyTargetSelected to the PlayerInstance player
player.sendPacket(new MyTargetSelected(getObjectId(), 0));
// Send a Server->Client packet ValidateLocation to correct the NpcInstance position and heading on the client
player.sendPacket(new ValidateLocation(this));
}
else if (!canInteract(player)) // Calculate the distance between the PlayerInstance and the NpcInstance
{
// Notify the PlayerInstance AI with AI_INTENTION_INTERACT
player.getAI().setIntention(CtrlIntention.AI_INTENTION_INTERACT, this);
}
else
{
showMessageWindow(player);
}
// Send a Server->Client ActionFailed to the PlayerInstance in order to avoid that the client wait another packet
player.sendPacket(ActionFailed.STATIC_PACKET);
}
@Override
public void onBypassFeedback(PlayerInstance player, String command)
{
final int condition = validateCondition(player);
if (condition == COND_ALL_FALSE)
{
// TODO: html
player.sendMessage("Wrong conditions.");
return;
}
if (condition == COND_BUSY_BECAUSE_OF_SIEGE)
{
// TODO: html
player.sendMessage("Busy because of siege.");
return;
}
else if (condition == COND_REGULAR)
{
final StringTokenizer st = new StringTokenizer(command, " ");
final String actualCommand = st.nextToken(); // Get actual command
String val = "";
if (st.countTokens() >= 1)
{
val = st.nextToken();
}
if (actualCommand.equalsIgnoreCase("auction"))
{
if (val.equals(""))
{
return;
}
try
{
final int days = Integer.parseInt(val);
try
{
final SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
int bid = 0;
if (st.countTokens() >= 1)
{
bid = Integer.parseInt(st.nextToken());
}
final Auction a = new Auction(player.getClan().getHasHideout(), player.getClan(), days * 86400000, bid, ClanHallManager.getInstance().getClanHallByOwner(player.getClan()).getName());
if (_pendingAuctions.get(a.getId()) != null)
{
_pendingAuctions.remove(a.getId());
}
_pendingAuctions.put(a.getId(), a);
final String filename = "data/html/auction/AgitSale3.htm";
final NpcHtmlMessage html = new NpcHtmlMessage(1);
html.setFile(filename);
html.replace("%x%", val);
html.replace("%AGIT_AUCTION_END%", format.format(a.getEndDate()));
html.replace("%AGIT_AUCTION_MINBID%", String.valueOf(a.getStartingBid()));
html.replace("%AGIT_AUCTION_MIN%", String.valueOf(a.getStartingBid()));
html.replace("%AGIT_AUCTION_DESC%", ClanHallManager.getInstance().getClanHallByOwner(player.getClan()).getDesc());
html.replace("%AGIT_LINK_BACK%", "bypass -h npc_" + getObjectId() + "_sale2");
html.replace("%objectId%", String.valueOf(getObjectId()));
player.sendPacket(html);
}
catch (Exception e)
{
player.sendMessage("Invalid bid!");
}
}
catch (Exception e)
{
player.sendMessage("Invalid auction duration!");
}
return;
}
if (actualCommand.equalsIgnoreCase("confirmAuction"))
{
try
{
final Auction a = _pendingAuctions.get(player.getClan().getHasHideout());
a.confirmAuction();
_pendingAuctions.remove(player.getClan().getHasHideout());
}
catch (Exception e)
{
player.sendMessage("Invalid auction");
}
return;
}
else if (actualCommand.equalsIgnoreCase("bidding"))
{
if (val.equals(""))
{
return;
}
try
{
final SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
final int auctionId = Integer.parseInt(val);
final String filename = "data/html/auction/AgitAuctionInfo.htm";
final Auction a = AuctionManager.getInstance().getAuction(auctionId);
final NpcHtmlMessage html = new NpcHtmlMessage(1);
html.setFile(filename);
if (a != null)
{
html.replace("%AGIT_NAME%", a.getItemName());
html.replace("%OWNER_PLEDGE_NAME%", a.getSellerClanName());
html.replace("%OWNER_PLEDGE_MASTER%", a.getSellerName());
html.replace("%AGIT_SIZE%", "30 ");
html.replace("%AGIT_LEASE%", String.valueOf(ClanHallManager.getInstance().getClanHallById(a.getItemId()).getLease()));
html.replace("%AGIT_LOCATION%", ClanHallManager.getInstance().getClanHallById(a.getItemId()).getLocation());
html.replace("%AGIT_AUCTION_END%", format.format(a.getEndDate()));
html.replace("%AGIT_AUCTION_REMAIN%", ((a.getEndDate() - System.currentTimeMillis()) / 3600000) + " hours " + (((a.getEndDate() - System.currentTimeMillis()) / 60000) % 60) + " minutes");
html.replace("%AGIT_AUCTION_MINBID%", String.valueOf(a.getStartingBid()));
html.replace("%AGIT_AUCTION_COUNT%", String.valueOf(a.getBidders().size()));
html.replace("%AGIT_AUCTION_DESC%", ClanHallManager.getInstance().getClanHallById(a.getItemId()).getDesc());
html.replace("%AGIT_LINK_BACK%", "bypass -h npc_" + getObjectId() + "_list");
html.replace("%AGIT_LINK_BIDLIST%", "bypass -h npc_" + getObjectId() + "_bidlist " + a.getId());
html.replace("%AGIT_LINK_RE%", "bypass -h npc_" + getObjectId() + "_bid1 " + a.getId());
}
else
{
LOGGER.warning("Auctioneer Auction null for AuctionId : " + auctionId);
}
player.sendPacket(html);
}
catch (Exception e)
{
player.sendMessage("Invalid auction!");
}
return;
}
else if (actualCommand.equalsIgnoreCase("bid"))
{
if (val.equals(""))
{
return;
}
try
{
final int auctionId = Integer.parseInt(val);
try
{
int bid = 0;
if (st.countTokens() >= 1)
{
bid = Integer.parseInt(st.nextToken());
}
AuctionManager.getInstance().getAuction(auctionId).setBid(player, bid);
}
catch (NumberFormatException e)
{
player.sendMessage("Invalid bid!");
}
catch (Exception e)
{
}
}
catch (Exception e)
{
player.sendMessage("Invalid auction!");
}
return;
}
else if (actualCommand.equalsIgnoreCase("bid1"))
{
if ((player.getClan() == null) || (player.getClan().getLevel() < 2))
{
player.sendMessage("Your clan's level needs to be at least 2, before you can bid in an auction");
return;
}
if (val.equals(""))
{
return;
}
if (((player.getClan().getAuctionBiddedAt() > 0) && (player.getClan().getAuctionBiddedAt() != Integer.parseInt(val))) || (player.getClan().getHasHideout() > 0))
{
player.sendMessage("You can't bid at more than one auction");
return;
}
try
{
final String filename = "data/html/auction/AgitBid1.htm";
int minimumBid = AuctionManager.getInstance().getAuction(Integer.parseInt(val)).getHighestBidderMaxBid();
if (minimumBid == 0)
{
minimumBid = AuctionManager.getInstance().getAuction(Integer.parseInt(val)).getStartingBid();
}
final NpcHtmlMessage html = new NpcHtmlMessage(1);
html.setFile(filename);
html.replace("%AGIT_LINK_BACK%", "bypass -h npc_" + getObjectId() + "_bidding " + val);
html.replace("%PLEDGE_ADENA%", String.valueOf(player.getClan().getWarehouse().getAdena()));
html.replace("%AGIT_AUCTION_MINBID%", String.valueOf(minimumBid));
html.replace("npc_%objectId%_bid", "npc_" + getObjectId() + "_bid " + val);
player.sendPacket(html);
}
catch (Exception e)
{
player.sendMessage("Invalid auction!");
}
return;
}
else if (actualCommand.equalsIgnoreCase("list"))
{
final List<Auction> auctions = AuctionManager.getInstance().getAuctions();
final SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
/** Limit for make new page, prevent client crash **/
int limit = 15;
int start;
int i = 1;
final double npage = Math.ceil((float) auctions.size() / limit);
if (val.equals(""))
{
start = 1;
}
else
{
start = (limit * (Integer.parseInt(val) - 1)) + 1;
limit *= Integer.parseInt(val);
}
String items = "";
items += "<table width=280 border=0><tr>";
for (int j = 1; j <= npage; j++)
{
items += "<td><center><a action=\"bypass -h npc_" + getObjectId() + "_list " + j + "\"> Page " + j + " </a></center></td>";
}
items += "</tr></table><table width=280 border=0>";
for (Auction a : auctions)
{
if (i > limit)
{
break;
}
else if (i < start)
{
i++;
continue;
}
else
{
i++;
}
items += "<tr><td>" + ClanHallManager.getInstance().getClanHallById(a.getItemId()).getLocation() + "</td><td><a action=\"bypass -h npc_" + getObjectId() + "_bidding " + a.getId() + "\">" + a.getItemName() + "</a></td><td>" + format.format(a.getEndDate()) + "</td><td>" + a.getStartingBid() + "</td></tr>";
}
items += "</table>";
final String filename = "data/html/auction/AgitAuctionList.htm";
final NpcHtmlMessage html = new NpcHtmlMessage(1);
html.setFile(filename);
html.replace("%AGIT_LINK_BACK%", "bypass -h npc_" + getObjectId() + "_start");
html.replace("%itemsField%", items);
player.sendPacket(html);
return;
}
else if (actualCommand.equalsIgnoreCase("bidlist"))
{
int auctionId = 0;
if (val.equals(""))
{
if (player.getClan().getAuctionBiddedAt() <= 0)
{
return;
}
auctionId = player.getClan().getAuctionBiddedAt();
}
else
{
auctionId = Integer.parseInt(val);
}
String biders = "";
final Map<Integer, Bidder> bidders = AuctionManager.getInstance().getAuction(auctionId).getBidders();
for (Bidder b : bidders.values())
{
biders += "<tr><td>" + b.getClanName() + "</td><td>" + b.getName() + "</td><td>" + b.getTimeBid().get(Calendar.YEAR) + "/" + (b.getTimeBid().get(Calendar.MONTH) + 1) + "/" + b.getTimeBid().get(Calendar.DATE) + "</td><td>" + b.getBid() + "</td></tr>";
}
final String filename = "data/html/auction/AgitBidderList.htm";
final NpcHtmlMessage html = new NpcHtmlMessage(1);
html.setFile(filename);
html.replace("%AGIT_LIST%", biders);
html.replace("%AGIT_LINK_BACK%", "bypass -h npc_" + getObjectId() + "_selectedItems");
html.replace("%x%", val);
html.replace("%objectId%", String.valueOf(getObjectId()));
player.sendPacket(html);
return;
}
else if (actualCommand.equalsIgnoreCase("selectedItems"))
{
if ((player.getClan() != null) && (player.getClan().getHasHideout() == 0) && (player.getClan().getAuctionBiddedAt() > 0))
{
final SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
final String filename = "data/html/auction/AgitBidInfo.htm";
final NpcHtmlMessage html = new NpcHtmlMessage(1);
html.setFile(filename);
final Auction a = AuctionManager.getInstance().getAuction(player.getClan().getAuctionBiddedAt());
if (a != null)
{
html.replace("%AGIT_NAME%", a.getItemName());
html.replace("%OWNER_PLEDGE_NAME%", a.getSellerClanName());
html.replace("%OWNER_PLEDGE_MASTER%", a.getSellerName());
html.replace("%AGIT_SIZE%", "30 ");
html.replace("%AGIT_LEASE%", String.valueOf(ClanHallManager.getInstance().getClanHallById(a.getItemId()).getLease()));
html.replace("%AGIT_LOCATION%", ClanHallManager.getInstance().getClanHallById(a.getItemId()).getLocation());
html.replace("%AGIT_AUCTION_END%", format.format(a.getEndDate()));
html.replace("%AGIT_AUCTION_REMAIN%", ((a.getEndDate() - System.currentTimeMillis()) / 3600000) + " hours " + (((a.getEndDate() - System.currentTimeMillis()) / 60000) % 60) + " minutes");
html.replace("%AGIT_AUCTION_MINBID%", String.valueOf(a.getStartingBid()));
html.replace("%AGIT_AUCTION_MYBID%", String.valueOf(a.getBidders().get(player.getClanId()).getBid()));
html.replace("%AGIT_AUCTION_DESC%", ClanHallManager.getInstance().getClanHallById(a.getItemId()).getDesc());
html.replace("%objectId%", String.valueOf(getObjectId()));
html.replace("%AGIT_LINK_BACK%", "bypass -h npc_" + getObjectId() + "_start");
}
else
{
LOGGER.warning("Auctioneer Auction null for AuctionBiddedAt : " + player.getClan().getAuctionBiddedAt());
}
player.sendPacket(html);
return;
}
else if ((player.getClan() != null) && (AuctionManager.getInstance().getAuction(player.getClan().getHasHideout()) != null))
{
final SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
final String filename = "data/html/auction/AgitSaleInfo.htm";
final NpcHtmlMessage html = new NpcHtmlMessage(1);
html.setFile(filename);
final Auction a = AuctionManager.getInstance().getAuction(player.getClan().getHasHideout());
if (a != null)
{
html.replace("%AGIT_NAME%", a.getItemName());
html.replace("%AGIT_OWNER_PLEDGE_NAME%", a.getSellerClanName());
html.replace("%OWNER_PLEDGE_MASTER%", a.getSellerName());
html.replace("%AGIT_SIZE%", "30 ");
html.replace("%AGIT_LEASE%", String.valueOf(ClanHallManager.getInstance().getClanHallById(a.getItemId()).getLease()));
html.replace("%AGIT_LOCATION%", ClanHallManager.getInstance().getClanHallById(a.getItemId()).getLocation());
html.replace("%AGIT_AUCTION_END%", format.format(a.getEndDate()));
html.replace("%AGIT_AUCTION_REMAIN%", ((a.getEndDate() - System.currentTimeMillis()) / 3600000) + " hours " + (((a.getEndDate() - System.currentTimeMillis()) / 60000) % 60) + " minutes");
html.replace("%AGIT_AUCTION_MINBID%", String.valueOf(a.getStartingBid()));
html.replace("%AGIT_AUCTION_BIDCOUNT%", String.valueOf(a.getBidders().size()));
html.replace("%AGIT_AUCTION_DESC%", ClanHallManager.getInstance().getClanHallById(a.getItemId()).getDesc());
html.replace("%AGIT_LINK_BACK%", "bypass -h npc_" + getObjectId() + "_start");
html.replace("%id%", String.valueOf(a.getId()));
html.replace("%objectId%", String.valueOf(getObjectId()));
}
else
{
LOGGER.warning("Auctioneer Auction null for getHasHideout : " + player.getClan().getHasHideout());
}
player.sendPacket(html);
return;
}
else if ((player.getClan() != null) && (player.getClan().getHasHideout() != 0))
{
final int ItemId = player.getClan().getHasHideout();
final String filename = "data/html/auction/AgitInfo.htm";
final NpcHtmlMessage html = new NpcHtmlMessage(1);
html.setFile(filename);
if (ClanHallManager.getInstance().getClanHallById(ItemId) != null)
{
html.replace("%AGIT_NAME%", ClanHallManager.getInstance().getClanHallById(ItemId).getName());
html.replace("%AGIT_OWNER_PLEDGE_NAME%", player.getClan().getName());
html.replace("%OWNER_PLEDGE_MASTER%", player.getClan().getLeaderName());
html.replace("%AGIT_SIZE%", "30 ");
html.replace("%AGIT_LEASE%", String.valueOf(ClanHallManager.getInstance().getClanHallById(ItemId).getLease()));
html.replace("%AGIT_LOCATION%", ClanHallManager.getInstance().getClanHallById(ItemId).getLocation());
html.replace("%AGIT_LINK_BACK%", "bypass -h npc_" + getObjectId() + "_start");
html.replace("%objectId%", String.valueOf(getObjectId()));
}
else
{
LOGGER.warning("Clan Hall ID NULL : " + ItemId + " Can be caused by concurent write in ClanHallManager");
}
player.sendPacket(html);
return;
}
}
else if (actualCommand.equalsIgnoreCase("cancelBid"))
{
final int bid = AuctionManager.getInstance().getAuction(player.getClan().getAuctionBiddedAt()).getBidders().get(player.getClanId()).getBid();
final String filename = "data/html/auction/AgitBidCancel.htm";
final NpcHtmlMessage html = new NpcHtmlMessage(1);
html.setFile(filename);
html.replace("%AGIT_BID%", String.valueOf(bid));
html.replace("%AGIT_BID_REMAIN%", String.valueOf((int) (bid * 0.9)));
html.replace("%AGIT_LINK_BACK%", "bypass -h npc_" + getObjectId() + "_selectedItems");
html.replace("%objectId%", String.valueOf(getObjectId()));
player.sendPacket(html);
return;
}
else if (actualCommand.equalsIgnoreCase("doCancelBid"))
{
if (AuctionManager.getInstance().getAuction(player.getClan().getAuctionBiddedAt()) != null)
{
AuctionManager.getInstance().getAuction(player.getClan().getAuctionBiddedAt()).cancelBid(player.getClanId());
player.sendMessage("You have succesfully canceled your bidding at the auction");
}
return;
}
else if (actualCommand.equalsIgnoreCase("cancelAuction"))
{
if (((player.getClanPrivileges() & Clan.CP_CH_AUCTION) != Clan.CP_CH_AUCTION))
{
player.sendMessage("You don't have the right privilleges to do this");
return;
}
final String filename = "data/html/auction/AgitSaleCancel.htm";
final NpcHtmlMessage html = new NpcHtmlMessage(1);
html.setFile(filename);
html.replace("%AGIT_DEPOSIT%", String.valueOf(ClanHallManager.getInstance().getClanHallByOwner(player.getClan()).getLease()));
html.replace("%AGIT_LINK_BACK%", "bypass -h npc_" + getObjectId() + "_selectedItems");
html.replace("%objectId%", String.valueOf(getObjectId()));
player.sendPacket(html);
return;
}
else if (actualCommand.equalsIgnoreCase("doCancelAuction"))
{
if (AuctionManager.getInstance().getAuction(player.getClan().getHasHideout()) != null)
{
AuctionManager.getInstance().getAuction(player.getClan().getHasHideout()).cancelAuction();
player.sendMessage("Your auction has been canceled");
}
return;
}
else if (actualCommand.equalsIgnoreCase("sale2"))
{
final String filename = "data/html/auction/AgitSale2.htm";
final NpcHtmlMessage html = new NpcHtmlMessage(1);
html.setFile(filename);
html.replace("%AGIT_LAST_PRICE%", String.valueOf(ClanHallManager.getInstance().getClanHallByOwner(player.getClan()).getLease()));
html.replace("%AGIT_LINK_BACK%", "bypass -h npc_" + getObjectId() + "_sale");
html.replace("%objectId%", String.valueOf(getObjectId()));
player.sendPacket(html);
return;
}
else if (actualCommand.equalsIgnoreCase("sale"))
{
if (((player.getClanPrivileges() & Clan.CP_CH_AUCTION) != Clan.CP_CH_AUCTION))
{
player.sendMessage("You don't have the right privilleges to do this");
return;
}
final String filename = "data/html/auction/AgitSale1.htm";
final NpcHtmlMessage html = new NpcHtmlMessage(1);
html.setFile(filename);
html.replace("%AGIT_DEPOSIT%", String.valueOf(ClanHallManager.getInstance().getClanHallByOwner(player.getClan()).getLease()));
html.replace("%AGIT_PLEDGE_ADENA%", String.valueOf(player.getClan().getWarehouse().getAdena()));
html.replace("%AGIT_LINK_BACK%", "bypass -h npc_" + getObjectId() + "_selectedItems");
html.replace("%objectId%", String.valueOf(getObjectId()));
player.sendPacket(html);
return;
}
else if (actualCommand.equalsIgnoreCase("rebid"))
{
final SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
if (((player.getClanPrivileges() & Clan.CP_CH_AUCTION) != Clan.CP_CH_AUCTION))
{
player.sendMessage("You don't have the right privileges to do this");
return;
}
try
{
final String filename = "data/html/auction/AgitBid2.htm";
final NpcHtmlMessage html = new NpcHtmlMessage(1);
html.setFile(filename);
final Auction a = AuctionManager.getInstance().getAuction(player.getClan().getAuctionBiddedAt());
if (a != null)
{
html.replace("%AGIT_AUCTION_BID%", String.valueOf(a.getBidders().get(player.getClanId()).getBid()));
html.replace("%AGIT_AUCTION_MINBID%", String.valueOf(a.getStartingBid()));
html.replace("%AGIT_AUCTION_END%", format.format(a.getEndDate()));
html.replace("%AGIT_LINK_BACK%", "bypass -h npc_" + getObjectId() + "_selectedItems");
html.replace("npc_%objectId%_bid1", "npc_" + getObjectId() + "_bid1 " + a.getId());
}
else
{
LOGGER.warning("Auctioneer Auction null for AuctionBiddedAt : " + player.getClan().getAuctionBiddedAt());
}
player.sendPacket(html);
}
catch (Exception e)
{
player.sendMessage("Invalid auction!");
}
return;
}
else if (actualCommand.equalsIgnoreCase("location"))
{
final NpcHtmlMessage html = new NpcHtmlMessage(1);
html.setFile("data/html/auction/location.htm");
html.replace("%location%", MapRegionData.getInstance().getClosestTownName(player));
html.replace("%LOCATION%", getPictureName(player));
html.replace("%AGIT_LINK_BACK%", "bypass -h npc_" + getObjectId() + "_start");
player.sendPacket(html);
return;
}
else if (actualCommand.equalsIgnoreCase("start"))
{
showMessageWindow(player);
return;
}
}
super.onBypassFeedback(player, command);
}
public void showMessageWindow(PlayerInstance player)
{
String filename; // = "data/html/auction/auction-no.htm";
final int condition = validateCondition(player);
if (condition == COND_BUSY_BECAUSE_OF_SIEGE)
{
filename = "data/html/auction/auction-busy.htm"; // Busy because of siege
}
else
{
filename = "data/html/auction/auction.htm";
}
final NpcHtmlMessage html = new NpcHtmlMessage(1);
html.setFile(filename);
html.replace("%objectId%", String.valueOf(getObjectId()));
html.replace("%npcId%", String.valueOf(getNpcId()));
html.replace("%npcname%", getName());
player.sendPacket(html);
}
private int validateCondition(PlayerInstance player)
{
if ((getCastle() != null) && (getCastle().getCastleId() > 0))
{
if (getCastle().getSiege().isInProgress())
{
return COND_BUSY_BECAUSE_OF_SIEGE; // Busy because of siege
}
return COND_REGULAR;
}
return COND_ALL_FALSE;
}
private String getPictureName(PlayerInstance plyr)
{
final int nearestTownId = MapRegionData.getInstance().getMapRegion(plyr.getX(), plyr.getY());
String nearestTown;
switch (nearestTownId)
{
case 5:
{
nearestTown = "GLUDIO";
break;
}
case 6:
{
nearestTown = "GLUDIN";
break;
}
case 7:
{
nearestTown = "DION";
break;
}
case 8:
{
nearestTown = "GIRAN";
break;
}
case 14:
{
nearestTown = "RUNE";
break;
}
case 15:
{
nearestTown = "GODARD";
break;
}
case 16:
{
nearestTown = "SCHUTTGART";
break;
}
default:
{
nearestTown = "ADEN";
break;
}
}
return nearestTown;
}
}
|
3e1a70b0a79f536bc7d990c824a914c5157edba5 | 2,537 | java | Java | hazelcast/src/main/java/com/hazelcast/client/impl/protocol/task/management/PromoteToCPMemberMessageTask.java | keith-f/hazelcast | a6e0b05a37c721c3daf1760449b8e2a47d0bcd36 | [
"Apache-2.0"
] | 2 | 2019-04-09T08:36:57.000Z | 2019-05-17T07:47:41.000Z | hazelcast/src/main/java/com/hazelcast/client/impl/protocol/task/management/PromoteToCPMemberMessageTask.java | navincm/hazelcast | f007912c9e332eaedc849567d3e658dd53883fc7 | [
"Apache-2.0"
] | 51 | 2020-09-18T02:03:15.000Z | 2022-03-30T02:05:00.000Z | hazelcast/src/main/java/com/hazelcast/client/impl/protocol/task/management/PromoteToCPMemberMessageTask.java | navincm/hazelcast | f007912c9e332eaedc849567d3e658dd53883fc7 | [
"Apache-2.0"
] | 3 | 2015-06-16T09:09:21.000Z | 2019-04-09T08:37:13.000Z | 30.566265 | 104 | 0.736697 | 11,235 | /*
* Copyright (c) 2008-2020, Hazelcast, 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.hazelcast.client.impl.protocol.task.management;
import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.impl.protocol.codec.MCPromoteToCPMemberCodec;
import com.hazelcast.client.impl.protocol.task.AbstractAsyncMessageTask;
import com.hazelcast.cp.CPSubsystemManagementService;
import com.hazelcast.instance.impl.Node;
import com.hazelcast.internal.management.ManagementCenterService;
import com.hazelcast.internal.nio.Connection;
import java.security.Permission;
import java.util.concurrent.CompletableFuture;
public class PromoteToCPMemberMessageTask extends AbstractAsyncMessageTask<Void, Void> {
public PromoteToCPMemberMessageTask(ClientMessage clientMessage, Node node, Connection connection) {
super(clientMessage, node, connection);
}
@Override
protected CompletableFuture<Void> processInternal() {
CPSubsystemManagementService cpService =
nodeEngine.getHazelcastInstance().getCPSubsystem().getCPSubsystemManagementService();
return cpService.promoteToCPMember().toCompletableFuture();
}
@Override
protected Void decodeClientMessage(ClientMessage clientMessage) {
return null;
}
@Override
protected ClientMessage encodeResponse(Object response) {
return MCPromoteToCPMemberCodec.encodeResponse();
}
@Override
public String getServiceName() {
return ManagementCenterService.SERVICE_NAME;
}
@Override
public Permission getRequiredPermission() {
return null;
}
@Override
public String getDistributedObjectName() {
return null;
}
@Override
public String getMethodName() {
return "promoteToCPMember";
}
@Override
public Object[] getParameters() {
return new Object[0];
}
@Override
public boolean isManagementTask() {
return true;
}
}
|
3e1a7132a4001aba9a89847ab55de68bc381451b | 78 | java | Java | Test/src/exception/ItemBookAlreadyExists.java | sapk-tb/INF112-BE2 | d44f2181d7e4eb7980989edcab95d148aba4d848 | [
"Unlicense"
] | null | null | null | Test/src/exception/ItemBookAlreadyExists.java | sapk-tb/INF112-BE2 | d44f2181d7e4eb7980989edcab95d148aba4d848 | [
"Unlicense"
] | null | null | null | Test/src/exception/ItemBookAlreadyExists.java | sapk-tb/INF112-BE2 | d44f2181d7e4eb7980989edcab95d148aba4d848 | [
"Unlicense"
] | null | null | null | 13 | 54 | 0.820513 | 11,236 | package exception;
public class ItemBookAlreadyExists extends Exception {
}
|
3e1a721a0e29cb57f45b7e62a3db917e12bab41e | 25,496 | java | Java | phive-rules-oioubl/src/test/java/com/helger/phive/oioubl/mock/CTestFiles.java | phax/ph-bdve-rules | a8b3cdf3d750be55a3c857e712e169763337bc07 | [
"Apache-2.0"
] | 3 | 2020-06-10T08:39:10.000Z | 2020-06-30T12:20:01.000Z | phive-rules-oioubl/src/test/java/com/helger/phive/oioubl/mock/CTestFiles.java | phax/ph-bdve-rules | a8b3cdf3d750be55a3c857e712e169763337bc07 | [
"Apache-2.0"
] | 5 | 2020-06-08T07:35:06.000Z | 2020-11-12T20:59:32.000Z | phive-rules-oioubl/src/test/java/com/helger/phive/oioubl/mock/CTestFiles.java | phax/ph-bdve-rules | a8b3cdf3d750be55a3c857e712e169763337bc07 | [
"Apache-2.0"
] | 1 | 2020-11-03T07:43:28.000Z | 2020-11-03T07:43:28.000Z | 62.034063 | 130 | 0.462033 | 11,237 | /*
* Copyright (C) 2018-2022 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helger.phive.oioubl.mock;
import static org.junit.Assert.assertTrue;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.Immutable;
import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.ReturnsMutableCopy;
import com.helger.commons.collection.impl.CommonsArrayList;
import com.helger.commons.collection.impl.ICommonsList;
import com.helger.commons.io.resource.ClassPathResource;
import com.helger.commons.io.resource.IReadableResource;
import com.helger.phive.api.executorset.VESID;
import com.helger.phive.api.executorset.ValidationExecutorSetRegistry;
import com.helger.phive.engine.mock.MockFile;
import com.helger.phive.engine.source.IValidationSourceXML;
import com.helger.phive.oioubl.OIOUBLValidation;
@Immutable
public final class CTestFiles
{
public static final ValidationExecutorSetRegistry <IValidationSourceXML> VES_REGISTRY = new ValidationExecutorSetRegistry <> ();
static
{
OIOUBLValidation.initOIOUBL (VES_REGISTRY);
}
private CTestFiles ()
{}
@Nonnull
@ReturnsMutableCopy
public static ICommonsList <MockFile> getAllTestFiles ()
{
final ICommonsList <MockFile> ret = new CommonsArrayList <> ();
for (final VESID aESID : new VESID [] { // Ancient 2.0.2
OIOUBLValidation.VID_OIOUBL_APPLICATION_RESPONSE,
OIOUBLValidation.VID_OIOUBL_CATALOGUE,
OIOUBLValidation.VID_OIOUBL_CATALOGUE_DELETION,
OIOUBLValidation.VID_OIOUBL_CATALOGUE_ITEM_SPECIFICATION_UPDATE,
OIOUBLValidation.VID_OIOUBL_CATALOGUE_PRICING_UPDATE,
OIOUBLValidation.VID_OIOUBL_CATALOGUE_REQUEST,
OIOUBLValidation.VID_OIOUBL_CREDIT_NOTE,
OIOUBLValidation.VID_OIOUBL_INVOICE,
OIOUBLValidation.VID_OIOUBL_ORDER,
OIOUBLValidation.VID_OIOUBL_ORDER_CANCELLATION,
OIOUBLValidation.VID_OIOUBL_ORDER_CHANGE,
OIOUBLValidation.VID_OIOUBL_ORDER_RESPONSE,
OIOUBLValidation.VID_OIOUBL_ORDER_RESPONSE_SIMPLE,
OIOUBLValidation.VID_OIOUBL_REMINDER,
OIOUBLValidation.VID_OIOUBL_STATEMENT,
// 1.12.3
OIOUBLValidation.VID_OIOUBL_APPLICATION_RESPONSE_1_12_3,
OIOUBLValidation.VID_OIOUBL_CATALOGUE_1_12_3,
OIOUBLValidation.VID_OIOUBL_CATALOGUE_DELETION_1_12_3,
OIOUBLValidation.VID_OIOUBL_CATALOGUE_ITEM_SPECIFICATION_UPDATE_1_12_3,
OIOUBLValidation.VID_OIOUBL_CATALOGUE_PRICING_UPDATE_1_12_3,
OIOUBLValidation.VID_OIOUBL_CATALOGUE_REQUEST_1_12_3,
OIOUBLValidation.VID_OIOUBL_CREDIT_NOTE_1_12_3,
OIOUBLValidation.VID_OIOUBL_INVOICE_1_12_3,
OIOUBLValidation.VID_OIOUBL_ORDER_1_12_3,
OIOUBLValidation.VID_OIOUBL_ORDER_CANCELLATION_1_12_3,
OIOUBLValidation.VID_OIOUBL_ORDER_CHANGE_1_12_3,
OIOUBLValidation.VID_OIOUBL_ORDER_RESPONSE_1_12_3,
OIOUBLValidation.VID_OIOUBL_ORDER_RESPONSE_SIMPLE_1_12_3,
OIOUBLValidation.VID_OIOUBL_REMINDER_1_12_3,
OIOUBLValidation.VID_OIOUBL_STATEMENT_1_12_3,
OIOUBLValidation.VID_OIOUBL_UTILITY_STATEMENT_1_12_3 })
for (final IReadableResource aRes : getAllMatchingTestFiles (aESID))
{
assertTrue ("Not existing test file: " + aRes.getPath (), aRes.exists ());
ret.add (MockFile.createGoodCase (aRes, aESID));
}
return ret;
}
@Nonnull
@ReturnsMutableCopy
public static ICommonsList <? extends IReadableResource> getAllMatchingTestFiles (@Nonnull final VESID aVESID)
{
ValueEnforcer.notNull (aVESID, "VESID");
final ICommonsList <IReadableResource> ret = new CommonsArrayList <> ();
// Ancient 2.0.2
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_APPLICATION_RESPONSE))
{
final String sPrefix = "/test-files/2.0.2/";
for (final String s : new String [] { "ApplicationResponseStor_v2p2.xml",
"BASPRO_03_01_06_ApplicationResponse_v2p2.xml",
"CATEXE_01_01_00_ApplicationResponse_v2p2.xml",
"CATEXE_02_02_07_ApplicationResponse_v2p2.xml",
"CATEXE_04_04_00_ApplicationResponse_v2p2.xml",
"CATEXE_05_05_00_ApplicationResponse_v2p2.xml",
"COMDEL_03_01_04_ApplicationResponse_v2p2.xml",
"COMDEL_04_02_04_ApplicationResponse_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_CATALOGUE))
{
final String sPrefix = "/test-files/2.0.2/";
for (final String s : new String [] { // "CATEXE_01_01_00_Catalogue_v2p2.xml",
// "CATEXE_02_02_07_Catalogue_v2p2.xml",
"CATEXE_05_05_00_Catalogue_A_v2p2.xml",
"CATEXE_05_05_00_Catalogue_B_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_CATALOGUE_DELETION))
{
final String sPrefix = "/test-files/2.0.2/";
for (final String s : new String [] { "CATEXE_06_06_00_CatalogueDeletion_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_CATALOGUE_ITEM_SPECIFICATION_UPDATE))
{
final String sPrefix = "/test-files/2.0.2/";
for (final String s : new String [] { "CATEXE_03_03_00_CatalogueItemSpecificationUpdate_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_CATALOGUE_PRICING_UPDATE))
{
final String sPrefix = "/test-files/2.0.2/";
for (final String s : new String [] { "CATEXE_04_04_00_CataloguePricingUpdate_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_CATALOGUE_REQUEST))
{
final String sPrefix = "/test-files/2.0.2/";
for (final String s : new String [] { "CATEXE_01_01_00_CatalogueRequest_v2p2.xml",
"CATEXE_02_02_07_CatalogueRequest_v2p2.xml",
"CATEXE_03_03_00_CatalogueRequest_v2p2.xml",
"CATEXE_05_05_00_CatalogueRequest_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_CREDIT_NOTE))
{
final String sPrefix = "/test-files/2.0.2/";
for (final String s : new String [] { "BASPRO_03_01_06_CreditNote_v2p2.xml",
// "CreditNoteStor_v2p2.xml"
})
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_INVOICE))
{
final String sPrefix = "/test-files/2.0.2/";
for (final String s : new String [] { "ADVORD_01_01_00_Invoice_v2p2.xml",
"ADVORD_02_02_00_Invoice_v2p2.xml",
"ADVORD_03_03_00_Invoice_v2p2.xml",
"ADVORD_04_04_00_Invoice_v2p2.xml",
"ADVORD_06_05_00_Invoice_v2p2.xml",
"BASPRO_01_01_00_Invoice_v2p2.xml",
"BASPRO_03_01_06_Invoice_B_v2p2.xml",
"BASPRO_03_01_06_Invoice_v2p2.xml",
"BASPRO_04_01_08_Invoice_v2p2.xml",
"COMDEL_01_01_00_Invoice_v2p2.xml",
"COMDEL_02_02_00_Invoice_v2p2.xml",
"COMDEL_03_01_04_Invoice_v2p2.xml",
"COMDEL_04_02_04_Invoice_v2p2.xml",
"COMORG_01_01_00_Invoice_v2p2.xml",
"COMORG_02_02_00_Invoice_v2p2.xml",
"COMORG_03_03_00_Invoice_v2p2.xml",
// "COMPAY_01_01_00_Invoice_v2p2.xml",
"COMPAY_03_03_00_Invoice_v2p2.xml",
"COMPAY_04_04_00_Invoice_v2p2.xml",
// "InvoiceStor_v2p2.xml",
})
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_ORDER))
{
final String sPrefix = "/test-files/2.0.2/";
for (final String s : new String [] { "ADVORD_03_03_00_Order_v2p2.xml",
"ADVORD_04_04_00_Order_v2p2.xml",
"ADVORD_05_04_01_Order_v2p2.xml",
"BASPRO_01_01_00_Order_v2p2.xml",
"BASPRO_02_01_02_Order_v2p2.xml",
"BASPRO_03_01_06_Order_v2p2.xml",
"BASPRO_04_01_08_Order_v2p2.xml",
"COMDEL_01_01_00_Order_v2p2.xml",
"COMDEL_02_02_00_Order_v2p2.xml",
"COMDEL_03_01_04_Order_v2p2.xml",
"COMDEL_04_02_04_Order_v2p2.xml",
"COMORG_01_01_00_Order_v2p2.xml",
"COMORG_02_02_00_Order_v2p2.xml",
"COMORG_03_03_00_Order_v2p2.xml",
"COMPAY_03_03_00_Order_v2p2.xml",
"COMPAY_04_04_00_Order_v2p2.xml",
"OrderStor_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_ORDER_CANCELLATION))
{
final String sPrefix = "/test-files/2.0.2/";
for (final String s : new String [] { "ADVORD_05_04_01_OrderCancellation_v2p2.xml",
"OrderCancellationStor_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_ORDER_CHANGE))
{
final String sPrefix = "/test-files/2.0.2/";
for (final String s : new String [] { "ADVORD_01_01_00_OrderChange_v2p2.xml",
"ADVORD_02_02_00_OrderChange_v2p2.xml",
"ADVORD_04_04_00_OrderChange_v2p2.xml",
"OrderChangeStor_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_ORDER_RESPONSE))
{
final String sPrefix = "/test-files/2.0.2/";
for (final String s : new String [] { "ADVORD_01_01_00_OrderResponse_v2p2.xml",
"ADVORD_02_02_00_OrderResponse_v2p2.xml",
"ADVORD_04_04_00_OrderResponse_v2p2.xml",
"ADVORD_05_04_01_OrderResponse_v2p2.xml",
// "COMPAY_01_01_00_OrderResponse_v2p2.xml",
"OrderResponseStor_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_ORDER_RESPONSE_SIMPLE))
{
final String sPrefix = "/test-files/2.0.2/";
for (final String s : new String [] { "ADVORD_02_02_00_OrderResponseSimple_v2p2.xml",
"ADVORD_03_03_00_OrderResponseSimple_v2p2.xml",
"ADVORD_06_05_00_OrderResponseSimple_v2p2.xml",
"BASPRO_01_01_00_OrderResponseSimple_v2p2.xml",
"BASPRO_02_01_02_OrderResponseSimple_v2p2.xml",
"BASPRO_03_01_06_OrderResponseSimple_v2p2.xml",
"BASPRO_04_01_08_OrderResponseSimple_v2p2.xml",
"COMDEL_01_01_00_OrderResponseSimple_v2p2.xml",
"COMDEL_02_02_00_OrderResponseSimple_v2p2.xml",
"COMDEL_03_01_04_OrderResponseSimple_v2p2.xml",
"COMDEL_04_02_04_OrderResponseSimple_v2p2.xml",
"COMORG_01_01_00_OrderResponseSimple_v2p2.xml",
"COMORG_02_02_00_OrderResponseSimple_v2p2.xml",
"COMORG_03_03_00_OrderResponseSimple_v2p2.xml",
"COMPAY_03_03_00_OrderResponseSimple_v2p2.xml",
"COMPAY_04_04_00_OrderResponseSimple_v2p2.xml",
"OrderResponseSimpleStor_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_REMINDER))
{
final String sPrefix = "/test-files/2.0.2/";
for (final String s : new String [] { "BASPRO_04_01_08_Reminder_v2p2.xml",
"COMPAY_03_03_00_Reminder_v2p2.xml",
// "ReminderStor_v2p2.xml",
})
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_STATEMENT))
{
final String sPrefix = "/test-files/2.0.2/";
for (final String s : new String [] {
// "StatementStor_v2p2.xml",
})
ret.add (new ClassPathResource (sPrefix + s));
}
// 1.12.3
// All of the test files are broken in regards to Saxon 11.x
if (false)
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_APPLICATION_RESPONSE_1_12_3))
{
final String sPrefix = "/test-files/1.12.3/";
for (final String s : new String [] { "OIOUBL_ApplicationResponse_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_CATALOGUE_1_12_3))
{
final String sPrefix = "/test-files/1.12.3/";
for (final String s : new String [] { "OIOUBL_Catalogue_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_CATALOGUE_DELETION_1_12_3))
{
final String sPrefix = "/test-files/1.12.3/";
for (final String s : new String [] { "OIOUBL_CatalogueDeletion_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_CATALOGUE_ITEM_SPECIFICATION_UPDATE_1_12_3))
{
final String sPrefix = "/test-files/1.12.3/";
for (final String s : new String [] { "OIOUBL_CatalogueItemSpecificationUpdate_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_CATALOGUE_PRICING_UPDATE_1_12_3))
{
final String sPrefix = "/test-files/1.12.3/";
for (final String s : new String [] { "OIOUBL_CataloguePricingUpdate_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_CATALOGUE_REQUEST_1_12_3))
{
final String sPrefix = "/test-files/1.12.3/";
for (final String s : new String [] { "OIOUBL_CatalogueRequest_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_CREDIT_NOTE_1_12_3))
{
final String sPrefix = "/test-files/1.12.3/";
for (final String s : new String [] { "OIOUBL_CreditNote_v2p2.xml",
"OIOUBL_CreditNoteCertificate.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_INVOICE_1_12_3))
{
final String sPrefix = "/test-files/1.12.3/";
for (final String s : new String [] { "OIOUBL_Invoice_UBLExtensions_v2p2.xml",
"OIOUBL_Invoice_v2p2.xml",
"OIOUBL_InvoiceCerticate.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_ORDER_1_12_3))
{
final String sPrefix = "/test-files/1.12.3/";
for (final String s : new String [] { "OIOUBL_Order_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_ORDER_CANCELLATION_1_12_3))
{
final String sPrefix = "/test-files/1.12.3/";
for (final String s : new String [] { "OIOUBL_OrderCancellation_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_ORDER_CHANGE_1_12_3))
{
final String sPrefix = "/test-files/1.12.3/";
for (final String s : new String [] { "OIOUBL_OrderChange_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_ORDER_RESPONSE_1_12_3))
{
final String sPrefix = "/test-files/1.12.3/";
for (final String s : new String [] { "OIOUBL_OrderResponse_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_ORDER_RESPONSE_SIMPLE_1_12_3))
{
final String sPrefix = "/test-files/1.12.3/";
for (final String s : new String [] { "OIOUBL_OrderResponseSimple_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_REMINDER_1_12_3))
{
final String sPrefix = "/test-files/1.12.3/";
for (final String s : new String [] { "OIOUBL_Reminder_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_STATEMENT_1_12_3))
{
final String sPrefix = "/test-files/1.12.3/";
for (final String s : new String [] { "OIOUBL_Statement_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
else
if (aVESID.equals (OIOUBLValidation.VID_OIOUBL_UTILITY_STATEMENT_1_12_3))
{
final String sPrefix = "/test-files/1.12.3/";
for (final String s : new String [] { "OIOUBL_UtilityStatement_v2p2.xml" })
ret.add (new ClassPathResource (sPrefix + s));
}
return ret;
}
}
|
3e1a727acbfdad5cd7511dd254229e3ee3f8cb60 | 3,074 | java | Java | compiler/extensions/doc/src/zserio/extension/doc/DocExtensionParameters.java | dkBrazz/zserio | 29dd8145b7d851fac682d3afe991185ea2eac318 | [
"BSD-3-Clause"
] | 86 | 2018-09-06T09:30:53.000Z | 2022-03-27T01:12:36.000Z | compiler/extensions/doc/src/zserio/extension/doc/DocExtensionParameters.java | dkBrazz/zserio | 29dd8145b7d851fac682d3afe991185ea2eac318 | [
"BSD-3-Clause"
] | 362 | 2018-09-04T20:21:24.000Z | 2022-03-30T15:14:38.000Z | compiler/extensions/doc/src/zserio/extension/doc/DocExtensionParameters.java | dkBrazz/zserio | 29dd8145b7d851fac682d3afe991185ea2eac318 | [
"BSD-3-Clause"
] | 20 | 2018-09-10T15:59:02.000Z | 2021-12-01T15:38:22.000Z | 34.539326 | 110 | 0.716005 | 11,238 | package zserio.extension.doc;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionGroup;
import zserio.extension.common.ZserioExtensionException;
import zserio.tools.ExtensionParameters;
/**
* Command line parameters for documentation extension.
*
* The class holds all command line parameters passed by core to the documentation extension, which are really
* used by documentation emitters.
*/
class DocExtensionParameters
{
public DocExtensionParameters(ExtensionParameters parameters) throws ZserioExtensionException
{
pathName = parameters.getPathName();
outputDir = parameters.getCommandLineArg(OptionDoc);
withSvgDiagrams = parameters.argumentExists(OptionWithSvgDiagrams);
dotExecutable = (parameters.argumentExists(OptionSetDotExecutable)) ?
parameters.getCommandLineArg(OptionSetDotExecutable) : DefaultDotExecutable;
if (withSvgDiagrams && !DotToSvgConverter.isDotExecAvailable(dotExecutable))
throw new ZserioExtensionException("The dot executable '" + dotExecutable + "' not found!");
}
public String getPathName()
{
return pathName;
}
public String getOutputDir()
{
return outputDir;
}
public boolean getWithSvgDiagrams()
{
return withSvgDiagrams;
}
public String getDotExecutable()
{
return dotExecutable;
}
static void registerOptions(org.apache.commons.cli.Options options)
{
Option option = new Option(OptionDoc, true, "generate HTML documentation");
option.setArgName("outputDir");
option.setRequired(false);
options.addOption(option);
final OptionGroup svgDiagramsGroup = new OptionGroup();
option = new Option(OptionWithSvgDiagrams, false, "enable generation of svg diagrams from dot files");
svgDiagramsGroup.addOption(option);
option = new Option(OptionWithoutSvgDiagrams, false,
"disable generation of svg diagrams from dot files (default)");
svgDiagramsGroup.addOption(option);
svgDiagramsGroup.setRequired(false);
options.addOptionGroup(svgDiagramsGroup);
option = new Option(OptionSetDotExecutable, true,
"set dot executable to use for conversions to svg format");
option.setArgName("dotExec");
option.setRequired(false);
options.addOption(option);
}
static boolean hasOptionDoc(ExtensionParameters parameters)
{
return parameters.argumentExists(OptionDoc);
}
private static final String OptionDoc = "doc";
private static final String OptionWithSvgDiagrams = "withSvgDiagrams";
private static final String OptionWithoutSvgDiagrams = "withoutSvgDiagrams";
private static final String OptionSetDotExecutable = "setDotExecutable";
private static final String DefaultDotExecutable = "dot";
private final String pathName;
private final String outputDir;
private final boolean withSvgDiagrams;
private final String dotExecutable;
}
|
3e1a729e908b9f2d1590ad292892f26e817069ac | 15,046 | java | Java | app/src/main/java/com/google/android/apps/exposurenotification/privateanalytics/PrivateAnalyticsMetricsRemoteConfig.java | google/exposure-notifications-android | 49859f5de60024cb4567e47de4c29a1d89a15a0e | [
"Apache-2.0"
] | 577 | 2020-05-04T16:41:57.000Z | 2022-02-10T10:51:24.000Z | app/src/main/java/com/google/android/apps/exposurenotification/privateanalytics/PrivateAnalyticsMetricsRemoteConfig.java | google/exposure-notifications-android | 49859f5de60024cb4567e47de4c29a1d89a15a0e | [
"Apache-2.0"
] | 60 | 2020-05-05T14:28:08.000Z | 2022-01-08T19:53:43.000Z | app/src/main/java/com/google/android/apps/exposurenotification/privateanalytics/PrivateAnalyticsMetricsRemoteConfig.java | google/exposure-notifications-android | 49859f5de60024cb4567e47de4c29a1d89a15a0e | [
"Apache-2.0"
] | 137 | 2020-05-04T17:47:46.000Z | 2022-01-27T03:56:51.000Z | 45.319277 | 114 | 0.784062 | 11,239 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.google.android.apps.exposurenotification.privateanalytics;
import android.net.Uri;
import androidx.annotation.VisibleForTesting;
import androidx.concurrent.futures.CallbackToFutureAdapter;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.google.android.apps.exposurenotification.common.Qualifiers.LightweightExecutor;
import com.google.android.apps.exposurenotification.common.logging.Logger;
import com.google.android.apps.exposurenotification.network.RequestQueueWrapper;
import com.google.android.apps.exposurenotification.privateanalytics.MetricsRemoteConfigs.Builder;
import com.google.android.libraries.privateanalytics.DefaultPrivateAnalyticsRemoteConfig.FetchRemoteConfigRequest;
import com.google.android.libraries.privateanalytics.PrivateAnalyticsEventListener;
import com.google.android.libraries.privateanalytics.Qualifiers.RemoteConfigUri;
import com.google.android.libraries.privateanalytics.utils.VolleyUtils;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.FluentFuture;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import javax.inject.Inject;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Remote config for metrics values (namely sampling rate and epsilon).
*/
public class PrivateAnalyticsMetricsRemoteConfig {
private static final Logger logcat = Logger.getLogger("ENPARemoteConfig");
// Metric "Periodic Exposure Interaction"
@VisibleForTesting
static final String CONFIG_METRIC_INTERACTION_COUNT_SAMPLING_PROB_KEY =
"enpa_metric_interaction_count_v1_sampling_prob";
@VisibleForTesting
static final String CONFIG_METRIC_INTERACTION_COUNT_PRIO_EPSILON_KEY =
"enpa_metric_interaction_count_v1_prio_epsilon";
// Metric "Periodic Exposure Notification"
@VisibleForTesting
static final String CONFIG_METRIC_NOTIFICATION_COUNT_SAMPLING_PROB_KEY =
"enpa_metric_notification_count_v1_sampling_prob";
@VisibleForTesting
static final String CONFIG_METRIC_NOTIFICATION_COUNT_PRIO_EPSILON_KEY =
"enpa_metric_notification_count_v1_prio_epsilon";
// Metric "Histogram"
@VisibleForTesting
static final String CONFIG_METRIC_RISK_HISTOGRAM_SAMPLING_PROB_KEY =
"enpa_metric_risk_histogram_v2_sampling_prob";
@VisibleForTesting
static final String CONFIG_METRIC_RISK_HISTOGRAM_PRIO_EPSILON_KEY =
"enpa_metric_risk_histogram_v2_prio_epsilon";
// Metric "Code Verified"
@VisibleForTesting
static final String CONFIG_METRIC_CODE_VERIFIED_SAMPLING_PROB_KEY =
"enpa_metric_code_verified_v1_sampling_prob";
@VisibleForTesting
static final String CONFIG_METRIC_CODE_VERIFIED_PRIO_EPSILON_KEY =
"enpa_metric_code_verified_v1_prio_epsilon";
// Metric "Code Verified with Report Type"
@VisibleForTesting
static final String CONFIG_METRIC_CODE_VERIFIED_WITH_REPORT_TYPE_SAMPLING_PROB_KEY =
"enpa_metric_code_verified_with_report_type_v1_sampling_prob";
@VisibleForTesting
static final String CONFIG_METRIC_CODE_VERIFIED_WITH_REPORT_TYPE_PRIO_EPSILON_KEY =
"enpa_metric_code_verified_with_report_type_v1_prio_epsilon";
// Metric "Keys Uploaded"
@VisibleForTesting
static final String CONFIG_METRIC_KEYS_UPLOADED_SAMPLING_PROB_KEY =
"enpa_metric_keys_uploaded_v1_sampling_prob";
@VisibleForTesting
static final String CONFIG_METRIC_KEYS_UPLOADED_PRIO_EPSILON_KEY =
"enpa_metric_keys_uploaded_v1_prio_epsilon";
// Metric "Keys Uploaded with Report Type"
@VisibleForTesting
static final String CONFIG_METRIC_KEYS_UPLOADED_WITH_REPORT_TYPE_SAMPLING_PROB_KEY =
"enpa_metric_keys_uploaded_with_report_type_v1_sampling_prob";
@VisibleForTesting
static final String CONFIG_METRIC_KEYS_UPLOADED_WITH_REPORT_TYPE_PRIO_EPSILON_KEY =
"enpa_metric_keys_uploaded_with_report_type_v1_prio_epsilon";
// Metric "Date Exposure"
@VisibleForTesting
static final String CONFIG_METRIC_DATE_EXPOSURE_SAMPLING_PROB_KEY =
"enpa_metric_date_exposure_v1_sampling_prob";
@VisibleForTesting
static final String CONFIG_METRIC_DATE_EXPOSURE_PRIO_EPSILON_KEY =
"enpa_metric_date_exposure_v1_prio_epsilon";
// Metric "Keys Uploaded Vaccine Status"
@VisibleForTesting
static final String CONFIG_METRIC_KEYS_UPLOADED_VACCINE_STATUS_SAMPLING_PROB_KEY =
"enpa_metric_keys_uploaded_vaccine_status_v1_sampling_prob";
@VisibleForTesting
static final String CONFIG_METRIC_KEYS_UPLOADED_VACCINE_STATUS_PRIO_EPSILON_KEY =
"enpa_metric_keys_uploaded_vaccine_status_v1_prio_epsilon";
// Metric "Exposure Notification followed by keys upload"
@VisibleForTesting
static final String CONFIG_METRIC_KEYS_UPLOADED_AFTER_NOTIFICATION_SAMPLING_PROB_KEY =
"enpa_metric_secondary_attack_v1_sampling_prob";
@VisibleForTesting
static final String CONFIG_METRIC_KEYS_UPLOADED_AFTER_NOTIFICATION_PRIO_EPSILON_KEY =
"enpa_metric_secondary_attack_v1_prio_epsilon";
// Metric "Periodic Exposure Notification followed by keys upload"
@VisibleForTesting
static final String CONFIG_METRIC_PERIODIC_EXPOSURE_NOTIFICATION_BIWEEKLY_SAMPLING_PROB_KEY =
"enpa_metric_periodic_exposure_notification_biweekly_v1_sampling_prob";
@VisibleForTesting
static final String CONFIG_METRIC_PERIODIC_EXPOSURE_NOTIFICATION_BIWEEKLY_PRIO_EPSILON_KEY =
"enpa_metric_periodic_exposure_notification_biweekly_v1_prio_epsilon";
private final static MetricsRemoteConfigs DEFAULT_REMOTE_CONFIGS = MetricsRemoteConfigs
.newBuilder().build();
private final ListeningExecutorService lightweightExecutor;
private final Uri remoteConfigUri;
private final Optional<PrivateAnalyticsEventListener> logger;
private final RequestQueueWrapper queue;
@Inject
PrivateAnalyticsMetricsRemoteConfig(
@LightweightExecutor ListeningExecutorService lightweightExecutor,
@RemoteConfigUri Uri remoteConfigUri,
RequestQueueWrapper queue,
Optional<PrivateAnalyticsEventListener> logger) {
this.lightweightExecutor = lightweightExecutor;
this.remoteConfigUri = remoteConfigUri;
this.logger = logger;
this.queue = queue;
}
public ListenableFuture<MetricsRemoteConfigs> fetchUpdatedConfigs() {
return FluentFuture.from(fetchUpdatedConfigsJson())
.transform(this::convertToRemoteConfig, lightweightExecutor)
.catching(Exception.class, e -> {
// Output the default RemoteConfigs for any exception thrown.
logcat.e("Failed to fetch or convert remote configuration.", e);
return DEFAULT_REMOTE_CONFIGS;
}, lightweightExecutor);
}
private ListenableFuture<JSONObject> fetchUpdatedConfigsJson() {
return CallbackToFutureAdapter.getFuture(
completer -> {
Listener<JSONObject> responseListener =
response -> {
logSuccess(response);
completer.set(response);
};
ErrorListener errorListener =
err -> {
logFailure(err);
completer.set(null);
};
FetchRemoteConfigRequest request = new FetchRemoteConfigRequest(remoteConfigUri,
responseListener, errorListener);
queue.add(request);
return request;
});
}
private void logSuccess(JSONObject response) {
if (logger.isPresent()) {
logger.get()
.onPrivateAnalyticsRemoteConfigCallSuccess(
response.toString().length());
}
logcat.d("Successfully fetched remote configs.");
}
private void logFailure(VolleyError err) {
if (logger.isPresent()) {
logger.get().onPrivateAnalyticsRemoteConfigCallFailure(err);
}
logcat.d("Remote Config Fetch Failed: " + VolleyUtils.getErrorBody(err).toString());
}
@VisibleForTesting
MetricsRemoteConfigs convertToRemoteConfig(JSONObject jsonObject) {
if (jsonObject == null) {
logcat.e("Invalid jsonObj, using default remote configs");
return DEFAULT_REMOTE_CONFIGS;
}
Builder remoteConfigBuilder = MetricsRemoteConfigs.newBuilder();
try {
// Notification Count Params
if (jsonObject.has(CONFIG_METRIC_NOTIFICATION_COUNT_SAMPLING_PROB_KEY)) {
remoteConfigBuilder.setNotificationCountPrioSamplingRate(
jsonObject.getDouble(CONFIG_METRIC_NOTIFICATION_COUNT_SAMPLING_PROB_KEY));
}
if (jsonObject.has(CONFIG_METRIC_NOTIFICATION_COUNT_PRIO_EPSILON_KEY)) {
remoteConfigBuilder.setNotificationCountPrioEpsilon(
jsonObject.getDouble(CONFIG_METRIC_NOTIFICATION_COUNT_PRIO_EPSILON_KEY));
}
// Notification Interaction Count Params
if (jsonObject.has(CONFIG_METRIC_INTERACTION_COUNT_SAMPLING_PROB_KEY)) {
remoteConfigBuilder.setInteractionCountPrioSamplingRate(
jsonObject.getDouble(CONFIG_METRIC_INTERACTION_COUNT_SAMPLING_PROB_KEY));
}
if (jsonObject.has(CONFIG_METRIC_INTERACTION_COUNT_PRIO_EPSILON_KEY)) {
remoteConfigBuilder.setInteractionCountPrioEpsilon(
jsonObject.getDouble(CONFIG_METRIC_INTERACTION_COUNT_PRIO_EPSILON_KEY));
}
// Risk score histogram Params
if (jsonObject.has(CONFIG_METRIC_RISK_HISTOGRAM_SAMPLING_PROB_KEY)) {
remoteConfigBuilder.setRiskScorePrioSamplingRate(
jsonObject.getDouble(CONFIG_METRIC_RISK_HISTOGRAM_SAMPLING_PROB_KEY));
}
if (jsonObject.has(CONFIG_METRIC_RISK_HISTOGRAM_PRIO_EPSILON_KEY)) {
remoteConfigBuilder.setRiskScorePrioEpsilon(
jsonObject.getDouble(CONFIG_METRIC_RISK_HISTOGRAM_PRIO_EPSILON_KEY));
}
// Code verified metric params
if (jsonObject.has(CONFIG_METRIC_CODE_VERIFIED_SAMPLING_PROB_KEY)) {
remoteConfigBuilder.setCodeVerifiedPrioSamplingRate(
jsonObject.getDouble(CONFIG_METRIC_CODE_VERIFIED_SAMPLING_PROB_KEY));
}
if (jsonObject.has(CONFIG_METRIC_CODE_VERIFIED_PRIO_EPSILON_KEY)) {
remoteConfigBuilder.setCodeVerifiedPrioEpsilon(
jsonObject.getDouble(CONFIG_METRIC_CODE_VERIFIED_PRIO_EPSILON_KEY));
}
// Code verified with report type metric params
if (jsonObject.has(CONFIG_METRIC_CODE_VERIFIED_WITH_REPORT_TYPE_SAMPLING_PROB_KEY)) {
remoteConfigBuilder.setCodeVerifiedWithReportTypePrioSamplingRate(
jsonObject.getDouble(CONFIG_METRIC_CODE_VERIFIED_WITH_REPORT_TYPE_SAMPLING_PROB_KEY));
}
if (jsonObject.has(CONFIG_METRIC_CODE_VERIFIED_WITH_REPORT_TYPE_PRIO_EPSILON_KEY)) {
remoteConfigBuilder.setCodeVerifiedWithReportTypePrioEpsilon(
jsonObject.getDouble(CONFIG_METRIC_CODE_VERIFIED_WITH_REPORT_TYPE_PRIO_EPSILON_KEY));
}
// Keys uploaded metric params
if (jsonObject.has(CONFIG_METRIC_KEYS_UPLOADED_SAMPLING_PROB_KEY)) {
remoteConfigBuilder.setKeysUploadedPrioSamplingRate(
jsonObject.getDouble(CONFIG_METRIC_KEYS_UPLOADED_SAMPLING_PROB_KEY));
}
if (jsonObject.has(CONFIG_METRIC_KEYS_UPLOADED_PRIO_EPSILON_KEY)) {
remoteConfigBuilder.setKeysUploadedPrioEpsilon(
jsonObject.getDouble(CONFIG_METRIC_KEYS_UPLOADED_PRIO_EPSILON_KEY));
}
// Keys uploaded with report type metric params
if (jsonObject.has(CONFIG_METRIC_KEYS_UPLOADED_WITH_REPORT_TYPE_SAMPLING_PROB_KEY)) {
remoteConfigBuilder.setKeysUploadedWithReportTypePrioSamplingRate(
jsonObject.getDouble(CONFIG_METRIC_KEYS_UPLOADED_WITH_REPORT_TYPE_SAMPLING_PROB_KEY));
}
if (jsonObject.has(CONFIG_METRIC_KEYS_UPLOADED_WITH_REPORT_TYPE_PRIO_EPSILON_KEY)) {
remoteConfigBuilder.setKeysUploadedWithReportTypePrioEpsilon(
jsonObject.getDouble(CONFIG_METRIC_KEYS_UPLOADED_WITH_REPORT_TYPE_PRIO_EPSILON_KEY));
}
// Keys uploaded metric params
if (jsonObject.has(CONFIG_METRIC_DATE_EXPOSURE_SAMPLING_PROB_KEY)) {
remoteConfigBuilder.setDateExposurePrioSamplingRate(
jsonObject.getDouble(CONFIG_METRIC_DATE_EXPOSURE_SAMPLING_PROB_KEY));
}
if (jsonObject.has(CONFIG_METRIC_DATE_EXPOSURE_PRIO_EPSILON_KEY)) {
remoteConfigBuilder.setDateExposurePrioEpsilon(
jsonObject.getDouble(CONFIG_METRIC_DATE_EXPOSURE_PRIO_EPSILON_KEY));
}
// Keys uploaded vaccine status metric params
if (jsonObject.has(CONFIG_METRIC_KEYS_UPLOADED_VACCINE_STATUS_SAMPLING_PROB_KEY)) {
remoteConfigBuilder.setKeysUploadedVaccineStatusPrioSamplingRate(
jsonObject.getDouble(CONFIG_METRIC_KEYS_UPLOADED_VACCINE_STATUS_SAMPLING_PROB_KEY));
}
if (jsonObject.has(CONFIG_METRIC_KEYS_UPLOADED_VACCINE_STATUS_PRIO_EPSILON_KEY)) {
remoteConfigBuilder.setKeysUploadedVaccineStatusPrioEpsilon(
jsonObject.getDouble(CONFIG_METRIC_KEYS_UPLOADED_VACCINE_STATUS_PRIO_EPSILON_KEY));
}
// Keys uploaded vaccine status metric params
if (jsonObject.has(CONFIG_METRIC_KEYS_UPLOADED_AFTER_NOTIFICATION_SAMPLING_PROB_KEY)) {
remoteConfigBuilder.setKeysUploadedAfterNotificationPrioSamplingRate(
jsonObject.getDouble(CONFIG_METRIC_KEYS_UPLOADED_AFTER_NOTIFICATION_SAMPLING_PROB_KEY));
}
if (jsonObject.has(CONFIG_METRIC_KEYS_UPLOADED_AFTER_NOTIFICATION_PRIO_EPSILON_KEY)) {
remoteConfigBuilder.setKeysUploadedAfterNotificationPrioEpsilon(
jsonObject.getDouble(CONFIG_METRIC_KEYS_UPLOADED_AFTER_NOTIFICATION_PRIO_EPSILON_KEY));
}
// Periodic exposure notification biweekly metric params
if (jsonObject.has(CONFIG_METRIC_PERIODIC_EXPOSURE_NOTIFICATION_BIWEEKLY_SAMPLING_PROB_KEY)) {
remoteConfigBuilder.setPeriodicExposureNotificationBiweeklyPrioSamplingRate(
jsonObject.getDouble(
CONFIG_METRIC_PERIODIC_EXPOSURE_NOTIFICATION_BIWEEKLY_SAMPLING_PROB_KEY));
}
if (jsonObject.has(CONFIG_METRIC_PERIODIC_EXPOSURE_NOTIFICATION_BIWEEKLY_PRIO_EPSILON_KEY)) {
remoteConfigBuilder.setPeriodicExposureNotificationBiweeklyPrioEpsilon(
jsonObject
.getDouble(CONFIG_METRIC_PERIODIC_EXPOSURE_NOTIFICATION_BIWEEKLY_PRIO_EPSILON_KEY));
}
} catch (JSONException e) {
logcat.e("Failed to parse remote config json, using defaults", e);
return DEFAULT_REMOTE_CONFIGS;
}
return remoteConfigBuilder.build();
}
}
|
3e1a72a570ca00195a91e892f06d1c15e444bb71 | 2,373 | java | Java | testing-util/src/main/java/net/morimekta/testing/matchers/InRange.java | morimekta/android-util | dc987485902f1a7d58169c89c61db97425a6226d | [
"Apache-2.0"
] | 1 | 2015-12-22T12:12:49.000Z | 2015-12-22T12:12:49.000Z | testing-util/src/main/java/net/morimekta/testing/matchers/InRange.java | morimekta/android-util | dc987485902f1a7d58169c89c61db97425a6226d | [
"Apache-2.0"
] | null | null | null | testing-util/src/main/java/net/morimekta/testing/matchers/InRange.java | morimekta/android-util | dc987485902f1a7d58169c89c61db97425a6226d | [
"Apache-2.0"
] | null | null | null | 38.274194 | 124 | 0.708386 | 11,240 | /*
* 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 net.morimekta.testing.matchers;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Numeric Value range matcher.
*/
public class InRange<T extends Number> extends BaseMatcher<T> {
private final T lowerInclusive;
private final T higherExclusive;
public InRange(T lowerInclusive, T higherExclusive) {
assertNotNull("Missing lower bound of range.", lowerInclusive);
assertNotNull("Missing upper bound of range.", higherExclusive);
assertTrue(String.format("Lower bound %s not lower than upper bound %s of range.", lowerInclusive, higherExclusive),
lowerInclusive.doubleValue() < higherExclusive.doubleValue());
this.lowerInclusive = lowerInclusive;
this.higherExclusive = higherExclusive;
}
@Override
public boolean matches(Object o) {
if (o == null || !(Number.class.isAssignableFrom(o.getClass()))) return false;
Number actual = (Number) o;
return lowerInclusive.doubleValue() <= actual.doubleValue() &&
actual.doubleValue() < higherExclusive.doubleValue();
}
@Override
public void describeTo(Description description) {
description.appendText("in range [" + lowerInclusive + " .. " + higherExclusive + ")");
}
public void describeMismatch(Object actual, Description mismatchDescription) {
mismatchDescription.appendText("was ")
.appendValue(actual);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.