hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
9b3959ac2ac94108845d7e10530c7d051c2ce174
| 3,021 |
package com.xq.myxuanqi.model.layoutBean;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.MenuItem;
import com.xq.myxuanqi.R;
import com.xq.myxuanqi.adapter.HomeViewPagerAdapter;
import com.xq.myxuanqi.ui.fragment.AddressFragment;
import com.xq.myxuanqi.ui.fragment.CommunicationFragment;
import com.xq.myxuanqi.ui.fragment.HomeFragment;
import com.xq.myxuanqi.ui.fragment.MeFragment;
import com.xq.myxuanqi.ui.fragment.NewsFragment;
import com.xq.myxuanqi.ui.fragment.VideoFragment;
import com.xq.myxuanqi.util.BottomNavigationViewHelper;
import java.util.ArrayList;
import java.util.List;
public class MobileUI extends MobileUIComponent {
private int selectBoardIndex = 0;
private onSelectCallBack mOnSelectCallBack;
private HomeViewPagerAdapter mViewPagerAdapter;
public interface onSelectCallBack{
void onSelectListener(int i);
}
public void setOnSelectCallBack(onSelectCallBack onSelectCallBack){
this.mOnSelectCallBack = onSelectCallBack;
}
public MobileUI() {
setClasstypename("MobileUI");
}
public int getSelectBoardIndex() {
return selectBoardIndex;
}
public void setSelectBoardIndex(int selectBoardIndex) {
this.selectBoardIndex = selectBoardIndex;
}
public int getMbBoardNumber() {
return getChildren().length;
}
public MbBoard getMbBoard(int i) {
return (MbBoard) getChildren()[i];
}
public void toAndroidUI(int mbBoardNumber, BottomNavigationView mNavigation, List<Fragment> mList, FragmentManager fm, ViewPager mVp, List<MenuItem> list1){
//动态生成底部菜单
//产生对应的fragment
MbBoard mbBoard = getMbBoard(0);
String name = mbBoard.getName();
MenuItem item = mNavigation.getMenu().add(1, 0, 0, name);
//设置菜单图片
item.setIcon(R.drawable.ic_home);
list1.add(item);
mList.add(new HomeFragment(0));
mViewPagerAdapter.notifyDataSetChanged();
///storage/emulated/0/Android/data/com.xq.myxuanqi/ICON_00000000000001aO.png
/*item.setIcon(Drawable.createFromPath(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Android"
+File.separator+"data"+File.separator+"com.xq.myxuanqi" , "ICON_00000000000001aO.png").getAbsolutePath()));*/
}
//底部菜单栏的选择监听
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
//设置监听回调
mOnSelectCallBack.onSelectListener(item.getItemId());
return true;
}
};
}
| 35.541176 | 160 | 0.707713 |
94e8317555c5341f6fcd3c9e6986def38905fe63
| 868 |
package io.github.anantharajuc.sbmdb.api.hateoas;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import io.github.anantharajuc.sbmdb.api.controller.student.StudentQueryController;
@RestController
public class RootController
{
@SuppressWarnings("rawtypes")
@GetMapping("/")
public ResponseEntity<RepresentationModel> root()
{
RepresentationModel<?> model = new RepresentationModel<>();
model.add(linkTo(methodOn(RootController.class).root()).withSelfRel());
model.add(linkTo(methodOn(StudentQueryController.class).findAllStudents()).withRel("students"));
return ResponseEntity.ok(model);
}
}
| 32.148148 | 98 | 0.806452 |
3aa782a1de3ce2d1d26d0526d6d55823c4fb97aa
| 403 |
/**
*
*/
package org.openforis.collect.persistence.jooq.tables.records;
import org.jooq.impl.TableImpl;
import org.jooq.impl.UpdatableRecordImpl;
/**
* @author M. Togna
*
*/
public class LookupRecord extends UpdatableRecordImpl<LookupRecord> {
private static final long serialVersionUID = 1L;
public LookupRecord(TableImpl<LookupRecord> table) {
super(table);
}
}
| 18.318182 | 70 | 0.702233 |
3140cb0d523b33627af3309d06a2e2ca24786abe
| 11,229 |
package me.kareluo.intensify.image;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.widget.OverScroller;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import me.kareluo.intensify.image.IntensifyImageDelegate.ImageDrawable;
/**
* Created by felix on 15/12/17.
*/
public class IntensifyImageView extends View implements IntensifyImage,
IntensifyImageDelegate.Callback {
private static final String TAG = "IntensifyImageView";
private Paint mPaint;
private Paint mTextPaint;
private Paint mBoardPaint;
private volatile Rect mDrawingRect = new Rect();
private OverScroller mScroller;
private IntensifyImageDelegate mDelegate;
private OnSingleTapListener mOnSingleTapListener;
private OnDoubleTapListener mOnDoubleTapListener;
private OnLongPressListener mOnLongPressListener;
private OnScaleChangeListener mOnScaleChangeListener;
private volatile boolean vFling = false;
private static final boolean DEBUG = false;
public IntensifyImageView(Context context) {
this(context, null, 0);
}
public IntensifyImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public IntensifyImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize(context, attrs, defStyleAttr);
}
protected void initialize(Context context, AttributeSet attrs, int defStyleAttr) {
mDelegate = new IntensifyImageDelegate(getResources().getDisplayMetrics(), this);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IntensifyImageView);
mDelegate.setScaleType(IntensifyImage.ScaleType.valueOf(
a.getInt(R.styleable.IntensifyImageView_scaleType, IntensifyImage.ScaleType.FIT_CENTER.nativeInt)));
mDelegate.setAnimateScaleType(
a.getBoolean(R.styleable.IntensifyImageView_animateScaleType, false));
mDelegate.setMinimumScale(
a.getFloat(R.styleable.IntensifyImageView_minimumScale, 0f));
mDelegate.setMaximumScale(
a.getFloat(R.styleable.IntensifyImageView_maximumScale, Float.MAX_VALUE));
mDelegate.setScale(a.getFloat(R.styleable.IntensifyImageView_scale, -1f));
a.recycle();
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
mPaint.setColor(Color.GREEN);
mPaint.setStrokeWidth(1f);
mPaint.setStyle(Paint.Style.STROKE);
mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
mTextPaint.setColor(Color.GREEN);
mTextPaint.setStrokeWidth(1f);
mTextPaint.setStyle(Paint.Style.FILL);
mTextPaint.setTextSize(24);
mBoardPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
mBoardPaint.setColor(Color.RED);
mBoardPaint.setStrokeWidth(2f);
mBoardPaint.setStyle(Paint.Style.STROKE);
new IntensifyImageAttacher(this);
mScroller = new OverScroller(context);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mDelegate.onAttached();
}
@Override
protected void onDetachedFromWindow() {
mDelegate.onDetached();
super.onDetachedFromWindow();
}
@Override
protected void onDraw(Canvas canvas) {
getDrawingRect(mDrawingRect);
List<ImageDrawable> drawables = mDelegate.obtainImageDrawables(mDrawingRect);
int save = canvas.save();
int i = 0;
for (ImageDrawable drawable : drawables) {
if (drawable == null || drawable.mBitmap.isRecycled()) {
continue;
}
canvas.drawBitmap(drawable.mBitmap, drawable.mSrc, drawable.mDst, mPaint);
if (DEBUG) {
canvas.drawRect(drawable.mDst, mPaint);
canvas.drawText(String.valueOf(++i), drawable.mDst.left + 4,
drawable.mDst.top + mTextPaint.getTextSize(), mTextPaint);
}
}
if (DEBUG) {
canvas.drawRect(mDrawingRect, mBoardPaint);
canvas.drawRect(mDelegate.getImageArea(), mBoardPaint);
}
canvas.restoreToCount(save);
}
@Override
public void setImage(String path) {
mScroller.abortAnimation();
mDelegate.load(path);
}
@Override
public void setImage(File file) {
mScroller.abortAnimation();
mDelegate.load(file);
}
@Override
public void setImage(InputStream inputStream) {
mScroller.abortAnimation();
mDelegate.load(inputStream);
}
@Override
public int getImageWidth() {
return mDelegate.getWidth();
}
@Override
public int getImageHeight() {
return mDelegate.getHeight();
}
@Override
public float getScale() {
return mDelegate.getScale();
}
@Override
public void setScaleType(IntensifyImage.ScaleType scaleType) {
mDelegate.setScaleType(scaleType);
}
@Override
public IntensifyImage.ScaleType getScaleType() {
return mDelegate.getScaleType();
}
@Override
public void setScale(float scale) {
mDelegate.setScale(scale);
}
@Override
public void addScale(float scale, float focusX, float focusY) {
mDelegate.scale(scale, focusX + getScrollX(), focusY + getScrollY());
postInvalidate();
}
@Override
public void scroll(float distanceX, float distanceY) {
getDrawingRect(mDrawingRect);
Point damping = mDelegate.damping(mDrawingRect, distanceX, distanceY);
getParent().requestDisallowInterceptTouchEvent(damping.x != 0 || damping.y != 0);
scrollBy(damping.x, damping.y);
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
postInvalidate();
} else {
if (vFling) {
getDrawingRect(mDrawingRect);
mDelegate.zoomHoming(mDrawingRect);
vFling = false;
}
}
}
@Override
protected int computeHorizontalScrollOffset() {
return mDelegate.getHorizontalOffset(getScrollX());
}
@Override
protected int computeHorizontalScrollRange() {
return mDelegate.getImageWidth();
}
@Override
protected int computeVerticalScrollOffset() {
return mDelegate.getVerticalOffset(getScrollY());
}
@Override
protected int computeVerticalScrollRange() {
return mDelegate.getImageHeight();
}
@Override
public void fling(float velocityX, float velocityY) {
getDrawingRect(mDrawingRect);
RectF imageArea = mDelegate.getImageArea();
if (!Utils.isEmpty(imageArea) && !Utils.contains(mDrawingRect, imageArea)) {
if (mDrawingRect.left <= imageArea.left && velocityX < 0
|| mDrawingRect.right >= imageArea.right && velocityX > 0) {
velocityX = 0f;
}
if (mDrawingRect.top <= imageArea.top && velocityY < 0
|| mDrawingRect.bottom >= imageArea.bottom && velocityY > 0) {
velocityY = 0f;
}
if (Float.compare(velocityX, 0f) == 0 && Float.compare(velocityY, 0f) == 0) return;
mScroller.fling(getScrollX(), getScrollY(), Math.round(velocityX), Math.round(velocityY),
Math.round(Math.min(imageArea.left, mDrawingRect.left)),
Math.round(Math.max(imageArea.right - mDrawingRect.width(), mDrawingRect.left)),
Math.round(Math.min(imageArea.top, mDrawingRect.top)),
Math.round(Math.max(imageArea.bottom - mDrawingRect.height(), mDrawingRect.top)),
100, 100);
vFling = true;
postInvalidate();
}
}
@Override
public void nextScale(float focusX, float focusY) {
getDrawingRect(mDrawingRect);
mDelegate.zoomScale(mDrawingRect, mDelegate.getNextStepScale(mDrawingRect),
focusX + getScrollX(), focusY + getScrollY());
}
@Override
public void onTouch(float x, float y) {
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
}
@Override
public void home() {
if (mScroller.isFinished()) {
getDrawingRect(mDrawingRect);
mDelegate.zoomHoming(mDrawingRect);
}
}
@Override
public void singleTap(float x, float y) {
if (mOnSingleTapListener != null) {
mOnSingleTapListener.onSingleTap(isInside(x, y));
}
}
@Override
public void doubleTap(float x, float y) {
if (mOnDoubleTapListener != null) {
if (!mOnDoubleTapListener.onDoubleTap(isInside(x, y))) {
nextScale(x, y);
}
} else nextScale(x, y);
}
@Override
public void longPress(float x, float y) {
if (mOnLongPressListener != null) {
mOnLongPressListener.onLongPress(isInside(x, y));
}
}
public boolean isInside(float x, float y) {
return mDelegate.getImageArea().contains(x, y);
}
public void setOnSingleTapListener(OnSingleTapListener listener) {
mOnSingleTapListener = listener;
}
public void setOnDoubleTapListener(OnDoubleTapListener listener) {
mOnDoubleTapListener = listener;
}
public void setOnLongPressListener(OnLongPressListener listener) {
mOnLongPressListener = listener;
}
public void setOnScaleChangeListener(OnScaleChangeListener listener) {
mOnScaleChangeListener = listener;
}
public float getBaseScale() {
return mDelegate.getBaseScale();
}
/**
* 设置过大可能会影响图片的正常显示
*
* @param scale 缩放值
*/
public void setMinimumScale(float scale) {
mDelegate.setMinimumScale(scale);
}
/**
* 设置过小可能会影响图片的正常显示
*
* @param scale 缩放值
*/
public void setMaximumScale(float scale) {
mDelegate.setMaximumScale(scale);
}
public float getMinimumScale() {
return mDelegate.getMinimumScale();
}
public float getMaximumScale() {
return mDelegate.getMaximumScale();
}
@Override
public void onRequestInvalidate() {
postInvalidate();
}
@Override
public boolean onRequestAwakenScrollBars() {
return awakenScrollBars();
}
@Override
public void onScaleChange(final float scale) {
if (mOnScaleChangeListener != null) {
post(new Runnable() {
@Override
public void run() {
mOnScaleChangeListener.onScaleChange(scale);
}
});
}
}
}
| 28.940722 | 116 | 0.636833 |
d864d6d0f2e6a846ed20d5dbd32d33bc0e8c9855
| 128 |
package com.gitee.myclouds.admin.test;
/**
* 单元测试(综合、杂项)
*
* @author xiongchun
*
*/
public class CfgCacheApiTest {
}
| 9.846154 | 38 | 0.632813 |
93282bae92e0b0e0d6756a1460257ca3e8b8e8f9
| 9,170 |
// Template Source: BaseEntityRequestBuilder.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.models.InformationProtection;
import com.microsoft.graph.models.BufferDecryptionResult;
import com.microsoft.graph.models.BufferEncryptionResult;
import com.microsoft.graph.models.SigningResult;
import com.microsoft.graph.models.VerificationResult;
import com.microsoft.graph.requests.BitlockerRequestBuilder;
import com.microsoft.graph.requests.DataLossPreventionPolicyCollectionRequestBuilder;
import com.microsoft.graph.requests.DataLossPreventionPolicyRequestBuilder;
import com.microsoft.graph.requests.SensitivityLabelCollectionRequestBuilder;
import com.microsoft.graph.requests.SensitivityLabelRequestBuilder;
import com.microsoft.graph.requests.SensitivityPolicySettingsRequestBuilder;
import com.microsoft.graph.requests.InformationProtectionPolicyRequestBuilder;
import com.microsoft.graph.requests.ThreatAssessmentRequestCollectionRequestBuilder;
import com.microsoft.graph.requests.ThreatAssessmentRequestRequestBuilder;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.BaseRequestBuilder;
import com.microsoft.graph.models.InformationProtectionDecryptBufferParameterSet;
import com.microsoft.graph.models.InformationProtectionEncryptBufferParameterSet;
import com.microsoft.graph.models.InformationProtectionSignDigestParameterSet;
import com.microsoft.graph.models.InformationProtectionVerifySignatureParameterSet;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Information Protection Request Builder.
*/
public class InformationProtectionRequestBuilder extends BaseRequestBuilder<InformationProtection> {
/**
* The request builder for the InformationProtection
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public InformationProtectionRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions);
}
/**
* Creates the request
*
* @param requestOptions the options for this request
* @return the InformationProtectionRequest instance
*/
@Nonnull
public InformationProtectionRequest buildRequest(@Nullable final com.microsoft.graph.options.Option... requestOptions) {
return buildRequest(getOptions(requestOptions));
}
/**
* Creates the request with specific requestOptions instead of the existing requestOptions
*
* @param requestOptions the options for this request
* @return the InformationProtectionRequest instance
*/
@Nonnull
public InformationProtectionRequest buildRequest(@Nonnull final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
return new com.microsoft.graph.requests.InformationProtectionRequest(getRequestUrl(), getClient(), requestOptions);
}
/**
* Gets the request builder for Bitlocker
*
* @return the BitlockerRequestBuilder instance
*/
@Nonnull
public BitlockerRequestBuilder bitlocker() {
return new BitlockerRequestBuilder(getRequestUrlWithAdditionalSegment("bitlocker"), getClient(), null);
}
/**
* Gets a request builder for the DataLossPreventionPolicy collection
*
* @return the collection request builder
*/
@Nonnull
public DataLossPreventionPolicyCollectionRequestBuilder dataLossPreventionPolicies() {
return new DataLossPreventionPolicyCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("dataLossPreventionPolicies"), getClient(), null);
}
/**
* Gets a request builder for the DataLossPreventionPolicy item
*
* @return the request builder
* @param id the item identifier
*/
@Nonnull
public DataLossPreventionPolicyRequestBuilder dataLossPreventionPolicies(@Nonnull final String id) {
return new DataLossPreventionPolicyRequestBuilder(getRequestUrlWithAdditionalSegment("dataLossPreventionPolicies") + "/" + id, getClient(), null);
}
/**
* Gets a request builder for the SensitivityLabel collection
*
* @return the collection request builder
*/
@Nonnull
public SensitivityLabelCollectionRequestBuilder sensitivityLabels() {
return new SensitivityLabelCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("sensitivityLabels"), getClient(), null);
}
/**
* Gets a request builder for the SensitivityLabel item
*
* @return the request builder
* @param id the item identifier
*/
@Nonnull
public SensitivityLabelRequestBuilder sensitivityLabels(@Nonnull final String id) {
return new SensitivityLabelRequestBuilder(getRequestUrlWithAdditionalSegment("sensitivityLabels") + "/" + id, getClient(), null);
}
/**
* Gets the request builder for SensitivityPolicySettings
*
* @return the SensitivityPolicySettingsRequestBuilder instance
*/
@Nonnull
public SensitivityPolicySettingsRequestBuilder sensitivityPolicySettings() {
return new SensitivityPolicySettingsRequestBuilder(getRequestUrlWithAdditionalSegment("sensitivityPolicySettings"), getClient(), null);
}
/**
* Gets the request builder for InformationProtectionPolicy
*
* @return the InformationProtectionPolicyRequestBuilder instance
*/
@Nonnull
public InformationProtectionPolicyRequestBuilder policy() {
return new InformationProtectionPolicyRequestBuilder(getRequestUrlWithAdditionalSegment("policy"), getClient(), null);
}
/**
* Gets a request builder for the ThreatAssessmentRequest collection
*
* @return the collection request builder
*/
@Nonnull
public ThreatAssessmentRequestCollectionRequestBuilder threatAssessmentRequests() {
return new ThreatAssessmentRequestCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("threatAssessmentRequests"), getClient(), null);
}
/**
* Gets a request builder for the ThreatAssessmentRequest item
*
* @return the request builder
* @param id the item identifier
*/
@Nonnull
public ThreatAssessmentRequestRequestBuilder threatAssessmentRequests(@Nonnull final String id) {
return new ThreatAssessmentRequestRequestBuilder(getRequestUrlWithAdditionalSegment("threatAssessmentRequests") + "/" + id, getClient(), null);
}
/**
* Gets a builder to execute the method
* @return the request builder
* @param parameters the parameters for the service method
*/
@Nonnull
public InformationProtectionDecryptBufferRequestBuilder decryptBuffer(@Nonnull final InformationProtectionDecryptBufferParameterSet parameters) {
return new InformationProtectionDecryptBufferRequestBuilder(getRequestUrlWithAdditionalSegment("microsoft.graph.decryptBuffer"), getClient(), null, parameters);
}
/**
* Gets a builder to execute the method
* @return the request builder
* @param parameters the parameters for the service method
*/
@Nonnull
public InformationProtectionEncryptBufferRequestBuilder encryptBuffer(@Nonnull final InformationProtectionEncryptBufferParameterSet parameters) {
return new InformationProtectionEncryptBufferRequestBuilder(getRequestUrlWithAdditionalSegment("microsoft.graph.encryptBuffer"), getClient(), null, parameters);
}
/**
* Gets a builder to execute the method
* @return the request builder
* @param parameters the parameters for the service method
*/
@Nonnull
public InformationProtectionSignDigestRequestBuilder signDigest(@Nonnull final InformationProtectionSignDigestParameterSet parameters) {
return new InformationProtectionSignDigestRequestBuilder(getRequestUrlWithAdditionalSegment("microsoft.graph.signDigest"), getClient(), null, parameters);
}
/**
* Gets a builder to execute the method
* @return the request builder
* @param parameters the parameters for the service method
*/
@Nonnull
public InformationProtectionVerifySignatureRequestBuilder verifySignature(@Nonnull final InformationProtectionVerifySignatureParameterSet parameters) {
return new InformationProtectionVerifySignatureRequestBuilder(getRequestUrlWithAdditionalSegment("microsoft.graph.verifySignature"), getClient(), null, parameters);
}
}
| 44.299517 | 213 | 0.754308 |
356ff914f4079e7869f939094f64819796a4ec87
| 5,853 |
/*
* Copyright 2012-2021 THALES.
*
* This file is part of AuthzForce CE.
*
* 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.ow2.authzforce.core.pdp.api.func;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import org.ow2.authzforce.core.pdp.api.expression.Expression;
import org.ow2.authzforce.core.pdp.api.expression.FunctionExpression;
import org.ow2.authzforce.core.pdp.api.expression.VariableReference;
import org.ow2.authzforce.core.pdp.api.value.AttributeValue;
import org.ow2.authzforce.core.pdp.api.value.Datatype;
import org.ow2.authzforce.core.pdp.api.value.Value;
/**
* Higher-order bag function
*
* @param <RETURN_T>
* return type
* @param <SUB_RETURN_T>
* sub-function's return (primitive) type. Only functions returning primitive type of result are compatible with higher-order functions here.
*
* @version $Id: $
*/
public abstract class HigherOrderBagFunction<RETURN_T extends Value, SUB_RETURN_T extends AttributeValue> extends BaseFunction<RETURN_T>
{
private final Datatype<RETURN_T> returnType;
private final Datatype<?> subFuncReturnType;
/**
* Instantiates higher-order bag function
*
* @param functionId
* function ID
* @param returnType
* function's return type
* @param subFunctionReturnType
* sub-function's return datatype; may be null to indicate any datatype (e.g. map function's sub-function return datatype can be any primitive type)
*/
protected HigherOrderBagFunction(final String functionId, final Datatype<RETURN_T> returnType, final Datatype<?> subFunctionReturnType)
{
super(functionId);
this.returnType = returnType;
this.subFuncReturnType = subFunctionReturnType;
}
/**
* {@inheritDoc}
*
* Returns the type of attribute value that will be returned by this function.
*/
@Override
public Datatype<RETURN_T> getReturnType()
{
return returnType;
}
/**
* Creates function call from sub-function definition and all inputs to higher-order function. To be overridden by OneBagOnlyFunctions (any-of/all-of)
*
* @param subFunc
* first-order sub-function
* @param inputsAfterSubFunc
* sub-function arguments
* @return function call
*/
protected abstract FunctionCall<RETURN_T> createFunctionCallFromSubFunction(FirstOrderFunction<SUB_RETURN_T> subFunc, List<Expression<?>> inputsAfterSubFunc);
/** {@inheritDoc} */
@Override
public final FunctionCall<RETURN_T> newCall(final List<Expression<?>> inputs) throws IllegalArgumentException
{
final int numInputs = inputs.size();
checkNumberOfArgs(numInputs);
final Iterator<? extends Expression<?>> inputsIterator = inputs.iterator();
final Expression<?> input0 = inputsIterator.next();
// first arg must be a boolean function
final Function<?> inputFunc;
if (input0 instanceof FunctionExpression)
{
inputFunc = ((FunctionExpression) input0).getValue().get();
}
else if (input0 instanceof VariableReference)
{
final Optional<? extends Value> optVal = ((VariableReference<?>) input0).getValue();
if (optVal.isEmpty())
{
throw new IllegalArgumentException(this + ": Unsupported type of first argument: " + input0
+ " cannot be evaluated to a constant (Function) value (out of context). Variable Function arg to higher-order function is not supported.");
}
final Value varValue = optVal.get();
if (!(varValue instanceof Function))
{
throw new IllegalArgumentException(this + ": Invalid type of first argument: " + varValue.getClass().getSimpleName() + ". Required: Function");
}
inputFunc = (Function<?>) varValue;
}
else
{
throw new IllegalArgumentException(this + ": Invalid type of first argument: " + input0.getClass().getSimpleName() + ". Required: Function");
}
/*
* Check whether it is a FirstOrderFunction because it is the only type of function for which we have a generic way to validate argument types as done later below
*/
if (!(inputFunc instanceof FirstOrderFunction))
{
throw new IllegalArgumentException(this + ": Invalid function in first argument: " + inputFunc + " is not supported as such argument");
}
final Datatype<?> inputFuncReturnType = inputFunc.getReturnType();
if (subFuncReturnType == null)
{
/*
* sub-function's return type can be any primitive datatype; check at least it is primitive
*/
if (inputFuncReturnType.getTypeParameter().isPresent())
{
throw new IllegalArgumentException(this + ": Invalid return type of function in first argument: " + inputFuncReturnType + " (bag type). Required: any primitive type");
}
}
else
{
if (!inputFuncReturnType.equals(subFuncReturnType))
{
throw new IllegalArgumentException(this + ": Invalid return type of function in first argument: " + inputFuncReturnType + ". Required: " + subFuncReturnType);
}
}
// so now we know we have a boolean FirstOrderFunction
@SuppressWarnings("unchecked")
final FirstOrderFunction<SUB_RETURN_T> subFunc = (FirstOrderFunction<SUB_RETURN_T>) inputFunc;
return createFunctionCallFromSubFunction(subFunc, inputs.subList(1, numInputs));
}
/**
* <p>
* checkNumberOfArgs
* </p>
*
* @param numInputs
* a int.
*/
protected abstract void checkNumberOfArgs(int numInputs);
}
| 34.839286 | 171 | 0.722877 |
cd5f683ef83be709dcff42048e477f882dca9acd
| 1,708 |
package com.cjburkey.voxicus.chunk;
import org.joml.Vector3i;
import com.cjburkey.voxicus.block.Block;
import com.cjburkey.voxicus.block.BlockState;
import com.cjburkey.voxicus.core.Util;
public class Chunk {
public static final int SIZE = 16;
private final IChunkHandler parent;
private final Vector3i chunkPos = new Vector3i();
private BlockState[] blocks;
public Chunk(IChunkHandler parent, Vector3i chunkPos) {
this.parent = parent;
this.chunkPos.set(chunkPos);
blocks = new BlockState[SIZE * SIZE * SIZE];
}
public boolean getIsAirBlock(Vector3i pos) {
BlockState at = getBlock(pos);
return at == null;
}
public void setBlock(Vector3i pos, Block block) {
if (!posInChunk(pos)) {
return;
}
blocks[getIndex(pos)] = (block == null) ? null : new BlockState(block, this, pos);
}
public BlockState getBlock(Vector3i pos) {
if (!posInChunk(pos)) {
return null;
}
return blocks[getIndex(pos)];
}
public BlockState getBlock(int i) {
if (i < 0 || i > blocks.length) {
return null;
}
return blocks[i];
}
public boolean posInChunk(Vector3i pos) {
return !(pos.x < 0 || pos.x >= SIZE || pos.y < 0 || pos.y >= SIZE || pos.z < 0 || pos.z >= SIZE);
}
public Vector3i getChunkPos() {
return new Vector3i(chunkPos);
}
public IChunkHandler getWorld() {
return parent;
}
public static int getIndex(Vector3i pos) {
return pos.z * SIZE * SIZE + pos.y * SIZE + pos.x;
}
public static Vector3i getPosition(int i) {
int z = Util.floorDiv(i, SIZE * SIZE);
i -= z * SIZE * SIZE;
int y = Util.floorDiv(i, SIZE);
return new Vector3i(i - y * SIZE, y, z);
}
}
| 24.056338 | 100 | 0.63993 |
2702c91509f546db8850143a4e2c2d3b896a5b58
| 250 |
package com.minhtetoo.PADCMMNEWS.delegates;
/**
* Created by min on 11/26/2017.
*/
public interface LoginRegisterDelegate {
void onTapLogin();
void onTapForgetPassWord();
void onTapToRegister();
void onSetTitle(String title);
}
| 16.666667 | 43 | 0.708 |
ffd9ad51b836c31c6922aebfe56651634f472a26
| 943 |
package com.sapient.productcatalogue.service.impl;
import com.sapient.productcatalogue.model.Color;
import com.sapient.productcatalogue.repository.ColorRepository;
import com.sapient.productcatalogue.service.ColorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class ColorServiceImpl implements ColorService {
@Autowired
ColorRepository colorRepository;
@Override
public Optional<List<Color>> findAll() {
return Optional.ofNullable(colorRepository.findAll());
}
@Override
public Optional<Color> getColorById(Integer id) {
return Optional.ofNullable(colorRepository.getColorById(id));
}
@Override
public Optional<List<Color>> getAllColorByCode(String code) {
return Optional.ofNullable(colorRepository.getAllColorByCode(code));
}
}
| 28.575758 | 76 | 0.772004 |
48a32b57bec2e27960a5ab57ed58d2899d0d819c
| 1,098 |
package slidingWindow;
/**
* 编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
* <p>
* 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
* <p>
* 你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。
* <p>
*
* <p>
* 示例 1:
* <p>
* 输入:["h","e","l","l","o"]
* 输出:["o","l","l","e","h"]
* 示例 2:
* <p>
* 输入:["H","a","n","n","a","h"]
* 输出:["h","a","n","n","a","H"]
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/reverse-string
*/
public class Solution344 {
public static void main(String[] args) {
Solution344 sol = new Solution344();
char[] s = {'h', 'e', 'l', 'l'};
sol.reverseString(s);
System.out.println(s);
}
/**
* 使用双指针法,不断交换指针数值,直到两个指针碰撞为止
*
* @param s
* @return
*/
private void reverseString(char[] s) {
int len = s.length;
if (len <= 1) {
return;
}
int left = 0, right = len - 1;
while (left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}
| 20.716981 | 53 | 0.467213 |
a02766d77d0fce4d6c96047397bff36a171ad9a9
| 375 |
package com.github.leleact.jtest.spring.tx.bean.mapper;
import com.github.leleact.jtest.spring.tx.bean.dto.T2;
public interface T2Mapper {
int deleteByPrimaryKey(String f1);
int insert(T2 record);
int insertSelective(T2 record);
T2 selectByPrimaryKey(String f1);
int updateByPrimaryKeySelective(T2 record);
int updateByPrimaryKey(T2 record);
}
| 20.833333 | 55 | 0.746667 |
e203c9833a8b25e45fe33cdc99721d97cf20ebec
| 512 |
package com.godaddy.asherah.crypto.keys;
import java.time.Instant;
import java.util.function.Consumer;
import java.util.function.Function;
import com.godaddy.asherah.appencryption.utils.SafeAutoCloseable;
public abstract class CryptoKey implements SafeAutoCloseable {
public abstract Instant getCreated();
public abstract boolean isRevoked();
public abstract void markRevoked();
public abstract void withKey(Consumer<byte[]> action);
public abstract <T> T withKey(Function<byte[], T> action);
}
| 25.6 | 65 | 0.787109 |
5ecd88c016c82d3d64b172206e82c3cc3a407da5
| 19,363 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.iso.dashboard.controller;
import com.iso.dashboard.component.CustomGrid;
import com.iso.dashboard.dto.Job;
import com.iso.dashboard.dto.ResultDTO;
import com.iso.dashboard.service.EmployeeMngtService;
import com.iso.dashboard.service.JobMngtService;
import com.iso.dashboard.ui.JobMngtUI;
import com.iso.dashboard.utils.BundleUtils;
import com.iso.dashboard.utils.CommonExport;
import com.iso.dashboard.utils.ComponentUtils;
import com.iso.dashboard.utils.Constants;
import com.iso.dashboard.utils.DataUtil;
import com.iso.dashboard.utils.ISOIcons;
import com.iso.dashboard.view.JobMngtView;
import com.vaadin.data.Item;
import com.vaadin.data.util.IndexedContainer;
import com.vaadin.server.FileResource;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.Page;
import com.vaadin.server.Resource;
import com.vaadin.server.VaadinService;
import com.vaadin.ui.Button;
import com.vaadin.ui.Component;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Table;
import com.vaadin.ui.UI;
import com.vaadin.ui.Window;
import com.vaadin.ui.themes.Reindeer;
import com.vaadin.ui.themes.ValoTheme;
import java.io.File;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import org.vaadin.dialogs.ConfirmDialog;
/**
*
* @author Thuclt-VNPTTech
*/
public class JobMngtController {
JobMngtView view;
JobMngtService service;
CustomGrid pagedTable;
// String[] headerName = new String[]{"Id", "Username", "Email", "Phone", ""};
String prefix = "jobMngt.list";//tien to trong file language
String headerKey = "header.jobMngt";//lay trong file cas
String[] headerName = BundleUtils.getHeaderColumnName(prefix, headerKey);
String[] headerColumn = BundleUtils.getHeaderColumn(headerKey);
String jobListLabel = "jobMngt.list";
Resource resource;
public JobMngtController(JobMngtView view) {
this.view = view;
this.pagedTable = view.getPagedTable();
initTable(JobMngtService.getInstance().listJobs(null));
doAction();
}
public void initTable(List<Job> lstJobs) {
// pagedTable.addGeneratedColumn("btnAction", new Table.ColumnGenerator() {
//// private static final long serialVersionUID = -5042109683675242407L;
//
// public Component generateCell(Table source, Object itemId, Object columnId) {
// Item item = source.getItem(itemId);
//
// Button btnEdit = new Button();
// btnEdit.setIcon(FontAwesome.EDIT);
// btnEdit.setStyleName(ValoTheme.BUTTON_BORDERLESS_COLORED);
// btnEdit.setDescription(BundleUtils.getString("common.button.edit"));
// btnEdit.addClickListener(new Button.ClickListener() {
//
// @Override
// public void buttonClick(Button.ClickEvent event) {
// String jobId = (String) item.getItemProperty("id").getValue();
// Notification.show("Edit " + jobId);
// Job dto = JobMngtService.getInstance().getJobById(jobId);
// onUpdate(dto);
// view.getBtnSearch().click();
// }
// });
// Button btnDelete = new Button();
// btnDelete.setIcon(ISOIcons.DELETE);
// btnDelete.setStyleName(ValoTheme.BUTTON_BORDERLESS_COLORED);
// btnDelete.setDescription(BundleUtils.getString("common.button.delete"));
// btnDelete.addClickListener(new Button.ClickListener() {
//
// @Override
// public void buttonClick(Button.ClickEvent event) {
// ConfirmDialog d = ConfirmDialog.show(
// UI.getCurrent(),
// BundleUtils.getString("message.warning.title"),
// BundleUtils.getString("message.warning.content"),
// BundleUtils.getString("common.confirmDelete.yes"),
// BundleUtils.getString("common.confirmDelete.no"),
// new ConfirmDialog.Listener() {
//
// public void onClose(ConfirmDialog dialog) {
// if (dialog.isConfirmed()) {
// // Confirmed to continue
// String jobId = (String) item.getItemProperty("id").getValue();
// ResultDTO res = JobMngtService.getInstance().removeJob(jobId);
// ComponentUtils.showNotification("Delete id : " + jobId + " " + res.getKey() + " " + res.getMessage());
// view.getBtnSearch().click();
// }
// }
// });
// d.setStyleName(Reindeer.WINDOW_LIGHT);
// d.setContentMode(ConfirmDialog.ContentMode.HTML);
// d.getOkButton().setIcon(ISOIcons.SAVE);
// d.getCancelButton().setIcon(ISOIcons.CANCEL);
// }
// });
//
// HorizontalLayout hori = new HorizontalLayout();
// hori.addComponent(btnEdit);
// hori.addComponent(btnDelete);
// return hori;
// }
// });
// reloadData(lstJobs);
// pagedTable.setSizeFull();
// //pagedTable.setRowHeaderMode(Table.RowHeaderMode.ICON_ONLY);
//// pagedTable.setWidth("1000px");
// pagedTable.setPageLength(10);
// pagedTable.setImmediate(true);
// pagedTable.setSelectable(true);
// pagedTable.setAlwaysRecalculateColumnWidths(true);
// pagedTable.setResponsive(true);
// pagedTable.setColumnHeaders(headerName);
IndexedContainer container = createContainer(lstJobs);
pagedTable.genGrid(container, prefix, headerColumn, null, new HandlerButtonActionGrid() {
@Override
public void actionEdit(Object obj) {
Job item = (Job) obj;
String jobId = String.valueOf(item.getId());
Notification.show("Edit " + jobId);
Job dto = JobMngtService.getInstance().getJobById(jobId);
onUpdate(dto);
view.getBtnSearch().click();
}
@Override
public void actionDelete(Object obj) {
ConfirmDialog d = ConfirmDialog.show(UI.getCurrent(),
BundleUtils.getString("message.warning.title"),
BundleUtils.getString("message.warning.content"),
BundleUtils.getString("common.confirmDelete.yes"),
BundleUtils.getString("common.confirmDelete.no"),
new ConfirmDialog.Listener() {
public void onClose(ConfirmDialog dialog) {
if (dialog.isConfirmed()) {
// Confirmed to continue
Job item = (Job) obj;
String jobId = String.valueOf(item.getId());
ResultDTO res = JobMngtService.getInstance().removeJob(jobId);
ComponentUtils.showNotification("Delete id : " + jobId + " " + res.getKey() + " " + res.getMessage());
view.getBtnSearch().click();
}
}
});
d.setStyleName(Reindeer.WINDOW_LIGHT);
d.setContentMode(ConfirmDialog.ContentMode.HTML);
d.getOkButton().setIcon(ISOIcons.SAVE);
d.getCancelButton().setIcon(ISOIcons.CANCEL);
}
@Override
public void actionSelect(Object obj) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
}
public void reloadData(List<Job> lstJobs) {
pagedTable.setContainerDataSource(pagedTable.createWrapContainer(createContainer(lstJobs)));
}
public IndexedContainer createContainer(List<Job> lstJobs) {
IndexedContainer container = new IndexedContainer();
// container.addContainerProperty("stt", String.class, null);
container.addContainerProperty("btnAction", String.class, null);
container.addContainerProperty("id", String.class, null);
container.addContainerProperty("jobTitle", String.class, null);
container.addContainerProperty("salaryGlone", String.class, null);
container.addContainerProperty("salaryWage", String.class, null);
for (Job j : lstJobs) {
Item item = container.addItem(j);
item.getItemProperty("id").setValue(String.valueOf(j.getId()));
item.getItemProperty("jobTitle").setValue(j.getJobTitle());
item.getItemProperty("salaryGlone").setValue(j.getSalaryGlone());
item.getItemProperty("salaryWage").setValue(j.getSalaryWage());
}
container.sort(new Object[]{"id"}, new boolean[]{true});
return container;
}
private void doAction() {
view.getBtnSearch().addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent event) {
onSearch();
}
});
view.getBtnAdd().addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent event) {
onInsert();
}
});
view.getBtnExport().addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent event) {
onExport();
}
});
}
public boolean validateData(JobMngtUI ui) {
if (DataUtil.isNullOrEmpty(ui.getTxtJobTitle().getValue())) {
Notification.show(BundleUtils.getString("jobMngt.list.jobTitle") + Constants.SPACE_CHARACTER + BundleUtils.getString("common.notnull"));
return false;
}
if (ui.getTxtJobTitle().getValue().length() > 20) {
Notification.show(BundleUtils.getString("jobMngt.list.jobTitle") + Constants.SPACE_CHARACTER + BundleUtils.getString("common.maxlength.20"));
return false;
}
if (DataUtil.isNullOrEmpty(ui.getTxtSalaryGlone().getValue())) {
Notification.show(BundleUtils.getString("jobMngt.list.salaryGlone") + Constants.SPACE_CHARACTER + BundleUtils.getString("common.notnull"));
return false;
}
if (ui.getTxtSalaryGlone().getValue().length() > 20) {
Notification.show(BundleUtils.getString("jobMngt.list.salaryGlone") + Constants.SPACE_CHARACTER + BundleUtils.getString("common.maxlength.20"));
return false;
}
if (DataUtil.isNullOrEmpty(ui.getTxtSalaryWage().getValue())) {
Notification.show(BundleUtils.getString("jobMngt.list.salaryWage") + Constants.SPACE_CHARACTER + BundleUtils.getString("common.notnull"));
return false;
}
if (ui.getTxtSalaryWage().getValue().length() > 20) {
Notification.show(BundleUtils.getString("jobMngt.list.salaryWage") + Constants.SPACE_CHARACTER + BundleUtils.getString("common.maxlength.20"));
return false;
}
if (DataUtil.isNullOrEmpty(ui.getTxtMinSalary().getValue())) {
Notification.show(BundleUtils.getString("jobMngt.list.minSalary") + Constants.SPACE_CHARACTER + BundleUtils.getString("common.notnull"));
return false;
}
if (ui.getTxtMinSalary().getValue().length() > 20) {
Notification.show(BundleUtils.getString("jobMngt.list.minSalary") + Constants.SPACE_CHARACTER + BundleUtils.getString("common.maxlength.20"));
return false;
}
if (DataUtil.isNullOrEmpty(ui.getTxtMaxSalary().getValue())) {
Notification.show(BundleUtils.getString("jobMngt.list.maxSalary") + Constants.SPACE_CHARACTER + BundleUtils.getString("common.notnull"));
return false;
}
if (ui.getTxtMaxSalary().getValue().length() > 20) {
Notification.show(BundleUtils.getString("jobMngt.list.maxSalary") + Constants.SPACE_CHARACTER + BundleUtils.getString("common.maxlength.20"));
return false;
}
return true;
}
private void onInsert() {
createDialog(true, new Job());
}
private void onUpdate(Job dto) {
createDialog(false, dto);
}
private void onSearch() {
List<Job> lstJob = JobMngtService.getInstance().listJobs(view.getTxtJobtitle().getValue());
EmployeeMngtService.getInstance().listEmployees("");
Notification.show("lstJob : " + lstJob.size());
reloadData(lstJob);
}
private void onExport() {
try {
List<Job> lstJobs = JobMngtService.getInstance().listJobs(view.getTxtJobtitle().getValue());
String[] header = new String[]{"export_01", "export_02", "export_03"};
String[] align = new String[]{"LEFT", "LEFT", "LEFT"};
List<AbstractMap.SimpleEntry<String, String>> headerAlign = new ArrayList<AbstractMap.SimpleEntry<String, String>>();
for (int i = 0; i < header.length; i++) {
headerAlign.add(new AbstractMap.SimpleEntry(header[i], align[i]));
}
String fileTemplate = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath()
//+ File.separator + "WEB-INF"
//+ File.separator + "templates"
//+ File.separator + "incident"
//+ File.separator + "TEMPLATE_EXPORT.xls"
+ Constants.FILE_CONF.PATH_EXPORT_TEMPLATE_XLSX;
String subTitle = Constants.EMPTY_CHARACTER;
File fileExport = CommonExport.exportFile(lstJobs,//list du lieu
headerAlign,//header
//"userMngt.list",//header prefix
jobListLabel,//header prefix
fileTemplate,//path template
BundleUtils.getString("userMngt.fileName.export"),//fileName out
7,//start row
subTitle,//sub title
4,//cell title Index
BundleUtils.getString("userMngt.report")//title
);
resource = new FileResource(fileExport);
Page.getCurrent().open(resource, null, false);
} catch (Exception e) {
}
}
private void initDataDialog(JobMngtUI ui, boolean isInsert, Job dto) {
if (isInsert) {
} else {
ui.getTxtJobTitle().setValue(dto.getJobTitle() == null ? "" : dto.getJobTitle());
ui.getTxtSalaryGlone().setValue(dto.getSalaryGlone() == null ? "" : dto.getSalaryGlone());
ui.getTxtSalaryWage().setValue(dto.getSalaryWage() == null ? "" : dto.getSalaryWage());
}
}
public void createDialog(boolean isInsert, Job dto) {
JobMngtUI ui = new JobMngtUI(isInsert ? BundleUtils.getString("common.button.add") : BundleUtils.getString("common.button.edit"));
Window window = new Window(
"",
ui);
//window.setWidth("700px");
float height = UI.getCurrent().getWidth() * 1 / 3;
window.setWidth(String.valueOf(height) + "%");
// window.setIcon(VaadinIcons.CALENDAR_USER);
initDataDialog(ui, isInsert, dto);
ui.getBtnSave().addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent event) {
boolean validate = validateData(ui);
if (validate) {
ConfirmDialog d = ConfirmDialog.show(
UI.getCurrent(),
BundleUtils.getString("message.warning.title"),
BundleUtils.getString("message.warning.content"),
BundleUtils.getString("common.confirmDelete.yes"),
BundleUtils.getString("common.confirmDelete.no"),
new ConfirmDialog.Listener() {
public void onClose(ConfirmDialog dialog) {
if (dialog.isConfirmed()) {
// Confirmed to continue
ResultDTO res = null;
getDataFromUI(ui, dto);
if (isInsert) {
res = JobMngtService.getInstance().addJob(dto);
ComponentUtils.showNotification(BundleUtils.getString("common.button.add") + " " + res.getKey() + " " + res.getMessage());
} else {
res = JobMngtService.getInstance().updateJob(dto);
ComponentUtils.showNotification(BundleUtils.getString("common.button.update") + " "
+ res.getKey() + " " + res.getMessage());
}
window.close();
view.getBtnSearch().click();
} else {
// User did not confirm
Notification.show("nok");
window.close();
}
}
});
d.setStyleName(Reindeer.LAYOUT_BLUE);
d.setContentMode(ConfirmDialog.ContentMode.HTML);
d.getOkButton().setIcon(ISOIcons.SAVE);
d.getOkButton().focus();
d.getCancelButton().setIcon(ISOIcons.CANCEL);
}
}
});
ui.getBtnCancel().addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent event) {
window.close();
}
});
ui.setWidth("100%");
ui.setHeight(Constants.STYLE_CONF.AUTO_VALUE);
window.setModal(true);
DataUtil.reloadWindow(window);
UI.getCurrent().addWindow(window);
ui.getTxtJobTitle().focus();
}
private void getDataFromUI(JobMngtUI ui, Job dto) {
dto.setJobTitle(ui.getTxtJobTitle().getValue().trim());
dto.setSalaryGlone(ui.getTxtSalaryGlone().getValue().trim());
dto.setSalaryWage(ui.getTxtSalaryWage().getValue().trim());
}
}
| 45.56 | 166 | 0.563342 |
3c552d856599c00b61d1f4b3f79e5f6640aa6cf6
| 9,296 |
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.identity.application.authenticator.samlsso;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.opensaml.Configuration;
import org.opensaml.DefaultBootstrap;
import org.opensaml.saml2.core.LogoutRequest;
import org.opensaml.saml2.core.SessionIndex;
import org.opensaml.xml.ConfigurationException;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.io.Unmarshaller;
import org.opensaml.xml.io.UnmarshallerFactory;
import org.opensaml.xml.io.UnmarshallingException;
import org.opensaml.xml.util.Base64;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus;
import org.wso2.carbon.identity.application.authentication.framework.CommonAuthenticationHandler;
import org.wso2.carbon.identity.application.authentication.framework.config.ConfigurationFacade;
import org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper;
import org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper;
import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants;
import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils;
import org.wso2.carbon.identity.application.authenticator.samlsso.exception.SAMLSSOException;
import org.wso2.carbon.identity.application.authenticator.samlsso.manager.DefaultSAML2SSOManager;
import org.wso2.carbon.identity.application.authenticator.samlsso.util.SSOConstants;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.xml.sax.SAXException;
/**
* This servlet is used to access SAML logout request.
*/
public class SAML2FederatedLogoutRequestHandler extends HttpServlet {
private static Log log = LogFactory.getLog(SAML2FederatedLogoutRequestHandler.class);
private static boolean bootStrapped = false;
public SAML2FederatedLogoutRequestHandler() {}
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException
{
log.error("--------------------- Inside doGet ----------------------- ");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
log.error("-------------------------- Inside doPost ---------------------- ");
initiateLogRequest(req, resp);
}
protected void initiateLogRequest(HttpServletRequest request, HttpServletResponse response) {
try {
log.error("Here **************1");
doBootstrap();
XMLObject samlObject = null;
Map<String, String[]> values = request.getParameterMap();
for (Map.Entry<String, String[]> entry : values.entrySet())
{
log.error("*****" + entry.getKey() + "/" + entry.getValue());
}
Enumeration<String> attrs = request.getAttributeNames();
if (request.getParameter(SSOConstants.HTTP_POST_PARAM_SAML2_AUTH_REQ) == null) {
return;
}
log.error("Here **************2");
samlObject = unmarshall(new String(Base64.decode(request.getParameter(
SSOConstants.HTTP_POST_PARAM_SAML2_AUTH_REQ))));
log.error("Here **************3");
String sessionIndex = null;
if (samlObject instanceof LogoutRequest) {
// if log out request
log.error("Here **************4");
LogoutRequest samlLogoutRequest = (LogoutRequest) samlObject;
List<SessionIndex> sessionIndexes = samlLogoutRequest.getSessionIndexes();
if (sessionIndexes != null && sessionIndexes.size() > 0) {
sessionIndex = sessionIndexes.get(0).getSessionIndex();
}
}
log.error("Recieved sessionIndex **************" + sessionIndex);
Object sessionDataKey = DefaultSAML2SSOManager.sessionIndexMap.get(sessionIndex);
log.error("Recieved session id **************" + sessionDataKey);
FrameworkUtils.removeSessionContextFromCache((String) sessionDataKey);
// CommonAuthenticationHandler commonAuthenticationHandler = new CommonAuthenticationHandler();
// CommonAuthRequestWrapper requestWrapper = new CommonAuthRequestWrapper(request);
//
// Cookie sessionCookie = new Cookie(FrameworkConstants.COMMONAUTH_COOKIE
// , (String) sessionDataKey);
//// AtomicReference<Cookie> sessionCookie = new AtomicReference<>(new Cookie("JSESSIONID", (String)
//// sessionDataKey));
//
// requestWrapper.setParameter(FrameworkConstants.COMMONAUTH_COOKIE, String.valueOf(sessionCookie));
// requestWrapper.setParameter("commonAuthLogout","true");
// requestWrapper.setParameter(FrameworkConstants.RequestParams.TYPE,"samlsso");
// requestWrapper.setParameter("commonAuthCallerPath","http://localhost:8080/travelocity.com/home.jsp");
// requestWrapper.setParameter("relyingParty","travelocity.com");
// CommonAuthResponseWrapper responseWrapper = new CommonAuthResponseWrapper(response);
// commonAuthenticationHandler.doGet(requestWrapper, responseWrapper);
} catch (Throwable e) {
e.printStackTrace();
}
}
public static void doBootstrap()
{
if (!bootStrapped) {
Thread thread = Thread.currentThread();
ClassLoader loader = thread.getContextClassLoader();
thread.setContextClassLoader(new DefaultSAML2SSOManager().getClass().getClassLoader());
try {
DefaultBootstrap.bootstrap();
bootStrapped = true;
} catch (ConfigurationException e) {
log.error("Error in bootstrapping the OpenSAML2 library", e);
} finally {
thread.setContextClassLoader(loader);
}
}
}
private XMLObject unmarshall(String samlString) throws SAMLSSOException
{
try
{
DocumentBuilderFactory documentBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory();
DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
ByteArrayInputStream is = new ByteArrayInputStream(samlString.getBytes());
Document document = docBuilder.parse(is);
Element element = document.getDocumentElement();
UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
XMLObject response = unmarshaller.unmarshall(element);
NodeList responseList = response.getDOM().getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol", "Response");
if (responseList.getLength() > 0) {
log.error("Invalid schema for the SAML2 response. Multiple Response elements found.");
throw new SAMLSSOException("Error occurred while processing SAML2 response.");
}
NodeList assertionList = response.getDOM().getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Assertion");
if (assertionList.getLength() > 1) {
log.error("Invalid schema for the SAML2 response. Multiple Assertion elements found.");
throw new SAMLSSOException("Error occurred while processing SAML2 response.");
}
return response;
} catch (ParserConfigurationException|UnmarshallingException|SAXException|IOException e) {
throw new SAMLSSOException("Error in unmarshalling SAML Request from the encoded String", e);
}
}
}
| 44.266667 | 132 | 0.691265 |
3bef961bb3e226d4116bb0dc54ee870088039232
| 6,230 |
/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal;
import java.util.Arrays;
import java.util.List;
import org.mockito.InOrder;
import org.mockito.MockSettings;
import org.mockito.exceptions.Reporter;
import org.mockito.exceptions.misusing.NotAMockException;
import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.invocation.AllInvocationsFinder;
import org.mockito.internal.invocation.Invocation;
import org.mockito.internal.progress.IOngoingStubbing;
import org.mockito.internal.progress.MockingProgress;
import org.mockito.internal.progress.ThreadSafeMockingProgress;
import org.mockito.internal.stubbing.InvocationContainer;
import org.mockito.internal.stubbing.OngoingStubbingImpl;
import org.mockito.internal.stubbing.StubberImpl;
import org.mockito.internal.util.MockUtil;
import org.mockito.internal.verification.MockAwareVerificationMode;
import org.mockito.internal.verification.VerificationDataImpl;
import org.mockito.internal.verification.VerificationModeFactory;
import org.mockito.internal.verification.api.InOrderContext;
import org.mockito.internal.verification.api.VerificationDataInOrder;
import org.mockito.internal.verification.api.VerificationDataInOrderImpl;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.DeprecatedOngoingStubbing;
import org.mockito.stubbing.OngoingStubbing;
import org.mockito.stubbing.Stubber;
import org.mockito.stubbing.VoidMethodStubbable;
import org.mockito.verification.VerificationMode;
@SuppressWarnings("unchecked")
public class MockitoCore {
private final Reporter reporter = new Reporter();
private final MockUtil mockUtil = new MockUtil();
private final MockingProgress mockingProgress = new ThreadSafeMockingProgress();
public <T> T mock(Class<T> classToMock, MockSettings mockSettings) {
T mock = mockUtil.createMock(classToMock, (MockSettingsImpl) mockSettings);
mockingProgress.mockingStarted(mock, classToMock, mockSettings);
return mock;
}
public IOngoingStubbing stub() {
IOngoingStubbing stubbing = mockingProgress.pullOngoingStubbing();
if (stubbing == null) {
mockingProgress.reset();
reporter.missingMethodInvocation();
}
return stubbing;
}
public <T> DeprecatedOngoingStubbing<T> stub(T methodCall) {
mockingProgress.stubbingStarted();
return (DeprecatedOngoingStubbing) stub();
}
public <T> OngoingStubbing<T> when(T methodCall) {
mockingProgress.stubbingStarted();
return (OngoingStubbing) stub();
}
public <T> T verify(T mock, VerificationMode mode) {
if (mock == null) {
reporter.nullPassedToVerify();
} else if (!mockUtil.isMock(mock)) {
reporter.notAMockPassedToVerify(mock.getClass());
}
mockingProgress.verificationStarted(new MockAwareVerificationMode(mock, mode));
return mock;
}
public <T> void reset(T ... mocks) {
mockingProgress.validateState();
mockingProgress.reset();
mockingProgress.resetOngoingStubbing();
for (T m : mocks) {
mockUtil.resetMock(m);
}
}
public void verifyNoMoreInteractions(Object... mocks) {
assertMocksNotEmpty(mocks);
mockingProgress.validateState();
for (Object mock : mocks) {
try {
if (mock == null) {
reporter.nullPassedToVerifyNoMoreInteractions();
}
InvocationContainer invocations = mockUtil.getMockHandler(mock).getInvocationContainer();
VerificationDataImpl data = new VerificationDataImpl(invocations, null);
VerificationModeFactory.noMoreInteractions().verify(data);
} catch (NotAMockException e) {
reporter.notAMockPassedToVerifyNoMoreInteractions();
}
}
}
public void verifyNoMoreInteractionsInOrder(List<Object> mocks, InOrderContext inOrderContext) {
mockingProgress.validateState();
AllInvocationsFinder finder = new AllInvocationsFinder();
VerificationDataInOrder data = new VerificationDataInOrderImpl(inOrderContext, finder.find(mocks), null);
VerificationModeFactory.noMoreInteractions().verifyInOrder(data);
}
private void assertMocksNotEmpty(Object[] mocks) {
if (mocks == null || mocks.length == 0) {
reporter.mocksHaveToBePassedToVerifyNoMoreInteractions();
}
}
public InOrder inOrder(Object... mocks) {
if (mocks == null || mocks.length == 0) {
reporter.mocksHaveToBePassedWhenCreatingInOrder();
}
for (Object mock : mocks) {
if (mock == null) {
reporter.nullPassedWhenCreatingInOrder();
} else if (!mockUtil.isMock(mock)) {
reporter.notAMockPassedWhenCreatingInOrder();
}
}
return new InOrderImpl(Arrays.asList(mocks));
}
public Stubber doAnswer(Answer answer) {
mockingProgress.stubbingStarted();
mockingProgress.resetOngoingStubbing();
return new StubberImpl().doAnswer(answer);
}
public <T> VoidMethodStubbable<T> stubVoid(T mock) {
MockHandlerInterface<T> handler = mockUtil.getMockHandler(mock);
mockingProgress.stubbingStarted();
return handler.voidMethodStubbable(mock);
}
public void validateMockitoUsage() {
mockingProgress.validateState();
}
/**
* For testing purposes only. Is not the part of main API.
* @return last invocation
*/
public Invocation getLastInvocation() {
OngoingStubbingImpl ongoingStubbing = ((OngoingStubbingImpl) mockingProgress.pullOngoingStubbing());
List<Invocation> allInvocations = ongoingStubbing.getRegisteredInvocations();
return allInvocations.get(allInvocations.size()-1);
}
}
| 39.43038 | 114 | 0.678331 |
67bc793b46b199d85517cc0fb223d457957348f6
| 3,170 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package treeGenerator;
import JFUtils.Range;
import codenameprojection.drawables.Vertex;
import codenameprojection.driver;
import java.awt.FlowLayout;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JSlider;
/**
*
* @author Jonnelafin
*/
public class runz {
public static void main(String[] args) {
new runz();
}
codenameprojection.driver Driver;
JFrame frame;
public runz() {
Driver = new driver();
Thread t = new Thread(){
@Override
public void run() {
super.run(); //To change body of generated methods, choose Tools | Templates.
Driver.run();
//Driver = new driver(null);
}
};
Driver.startWithNoModel = false;
t.start();
while(!Driver.running){
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(runz.class.getName()).log(Level.SEVERE, null, ex);
}
}
Driver.an_pause = true;
Driver.zero();
Driver.models.clear();
Driver.s.r.usePixelRendering = false;
Driver.s.r.drawFaces = false;
Driver.s.r.drawPoints = true;
Driver.s.r.drawLines = true;
System.out.println("Init complete!");
frame = new JFrame("\"PB3D\" Tree generator");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLayout(new FlowLayout());
JSlider step = new JSlider(0, 100, 0);
frame.add(step);
frame.setVisible(true);
float p = -1;
int a = 2;
Random r = new Random();
float x = 0;
float y = 0;
while (true) {
if(step.getValue() /100F != p){
p = step.getValue() / 100F;
Driver.zero();
float z = 0;
x = x / 2;
y = y / 2;
Driver.points.add(new Vertex(0, 0, 0));
for(int i : new Range(a)){
z = z + p;
if(r.nextInt(5) == 1){
if(r.nextBoolean()){
x = x + 0.1F;
}
else{
x = x - 0.1F;
}
}
Driver.points.add(new Vertex(x, z, y));
Driver.lines.add(new Integer[]{Driver.points.getLast().identifier, Driver.points.getFirst().identifier});
}
}
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(runz.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
| 29.351852 | 125 | 0.485489 |
7201954b9f546aa30e968d2f73cf8a480922f58a
| 3,331 |
package dev.cheun.services;
import dev.cheun.daos.AccountDAO;
import dev.cheun.daos.ClientDAO;
import dev.cheun.daos.ClientDaoPostgres;
import dev.cheun.entities.Account;
import dev.cheun.entities.Client;
import dev.cheun.exceptions.BadRequestException;
import dev.cheun.exceptions.NotFoundException;
import io.javalin.http.BadRequestResponse;
import java.util.HashSet;
import java.util.Set;
public class AccountServiceImpl implements AccountService {
private AccountDAO dao;
private ClientDAO cDao;
// Dependency injection.
// A service is created by passing in the dependency it needs.
public AccountServiceImpl(AccountDAO dao) {
this.dao = dao;
this.cDao = new ClientDaoPostgres();
}
@Override
public Account createAccount(Account account) {
// Check if client exists (throws NotFoundException if not found)
this.cDao.getClientById(account.getClientId());
// Check if account number already exists.
Set<Account> allAccounts = this.dao.getAllAccounts();
for (Account a : allAccounts) {
if (a.getAccountNumber().compareTo(account.getAccountNumber()) == 0) {
throw new BadRequestException("Account number already exists");
}
}
Account newAccount = this.dao.createAccount(account);
return newAccount;
}
@Override
public Set<Account> getAllAccounts(int clientId) {
// Check if client exists.
Client client = this.cDao.getClientById(clientId);
// Filter accounts to the respective client.
Set<Account> allAccounts = this.dao.getAllAccounts();
Set<Account> selectedAccounts = new HashSet<>();
for (Account a : allAccounts) {
if (a.getClientId() == client.getId()) {
selectedAccounts.add(a);
}
}
return selectedAccounts;
}
@Override
public Account getAccountById(int clientId, int id) {
// Check if client exists.
Client client = this.cDao.getClientById(clientId);
Account account = this.dao.getAccountById(id);
if (account.getClientId() != client.getId()) {
throw new NotFoundException("No such account exists");
}
return account;
}
@Override
public Account updateAccount(Account account) {
// getAccountById will check if client and account exists.
getAccountById(account.getClientId(), account.getId());
// Check if account number already exists.
Set<Account> allAccounts = this.dao.getAllAccounts();
for (Account a : allAccounts) {
if (a.getId() != account.getId() &&
a.getAccountNumber().compareTo(account.getAccountNumber()) == 0) {
throw new BadRequestException("Account number already exists");
}
}
Account updatedAccount = this.dao.updateAccount(account);
return updatedAccount;
}
@Override
public boolean deleteAccountById(int clientId, int id) {
// getAccountById will check if client and account exists.
Account account = getAccountById(clientId, id);
return this.dao.deleteAccountById(account.getId());
}
}
| 36.604396 | 87 | 0.636446 |
6e753c9783f2482dc20ab9613bc13e02ff986382
| 5,239 |
/*
* Copyright 2016
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* 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 de.tudarmstadt.ukp.dkpro.c4corpus.hadoop.full;
import de.tudarmstadt.ukp.dkpro.c4corpus.deduplication.impl.SimHashUtils;
import de.tudarmstadt.ukp.dkpro.c4corpus.hadoop.deduplication.DeDuplicationTextOutputReducer;
import de.tudarmstadt.ukp.dkpro.c4corpus.hadoop.deduplication.DocumentInfo;
import de.tudarmstadt.ukp.dkpro.c4corpus.hadoop.deduplication.DocumentInfoOutputFormat;
import de.tudarmstadt.ukp.dkpro.c4corpus.hadoop.io.WARCInputFormat;
import de.tudarmstadt.ukp.dkpro.c4corpus.hadoop.io.WARCWritable;
import de.tudarmstadt.ukp.dkpro.c4corpus.warc.io.WARCRecord;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.LazyOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import java.io.IOException;
import java.util.List;
import java.util.Set;
/**
* This class takes warc.gz files as input and clusters similar candidates
* according to the SimHash value. The simHash value is converted to bands of
* bits. The output is a data structure called Document Info which includes the
* doc id, simhash and length. the document info is written as a text file.
*
* @author Omnia Zayed
*/
public class Phase3Step1ExtractNearDupInfo
extends Configured
implements Tool
{
@Override
public int run(String[] args)
throws Exception
{
Job job = Job.getInstance(getConf());
job.setJarByClass(Phase3Step1ExtractNearDupInfo.class);
job.setJobName(Phase3Step1ExtractNearDupInfo.class.getName());
// mapper
job.setMapperClass(MapperClass.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(DocumentInfo.class);
// reducer
job.setReducerClass(DeDuplicationTextOutputReducer.class);
job.setOutputKeyClass(NullWritable.class);
job.setOutputValueClass(List.class);
job.setInputFormatClass(WARCInputFormat.class);
LazyOutputFormat.setOutputFormatClass(job, DocumentInfoOutputFormat.class);
// paths
String commaSeparatedInputFiles = args[0];
String outputPath = args[1];
FileInputFormat.addInputPaths(job, commaSeparatedInputFiles);
FileOutputFormat.setOutputPath(job, new Path(outputPath));
return job.waitForCompletion(true) ? 0 : 1;
}
public static void main(String[] args)
throws Exception
{
ToolRunner.run(new Phase3Step1ExtractNearDupInfo(), args);
}
public static class MapperClass
extends Mapper<LongWritable, WARCWritable, Text, DocumentInfo>
{
@Override
protected void map(LongWritable key, WARCWritable value, Context context)
throws IOException, InterruptedException
{
String docText = new String(value.getRecord().getContent());
//ID of single warc record (document)
String docID = value.getRecord().getHeader().getRecordID();
String docSimHashString = value.getRecord().getHeader()
.getField(WARCRecord.WARCRecordFieldConstants.SIMHASH);
if (docSimHashString == null) {
throw new IOException(
WARCRecord.WARCRecordFieldConstants.SIMHASH + " metadata not found");
}
long docSimHash = Long.valueOf(docSimHashString);
int docLength = docText.length();
String language = value.getRecord().getHeader()
.getField(WARCRecord.WARCRecordFieldConstants.LANGUAGE);
//get the binary representation of this document split into bands
Set<String> bandsOfBitsHashIndex = SimHashUtils.computeHashIndex(docSimHash);
// create a new container
DocumentInfo d = new DocumentInfo();
d.setDocID(new Text(docID));
d.setDocLength(new IntWritable(docLength));
d.setDocSimHash(new LongWritable(docSimHash));
d.setDocLanguage(new Text(language));
for (String bandOfBits : bandsOfBitsHashIndex) {
context.write(new Text(bandOfBits), d);
}
}
}
}
| 37.690647 | 93 | 0.706814 |
e947b5e843ff93e81849acfd6d09dcb2fd6cc798
| 460 |
package com.lihui.study.design.pattern;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @ClassName: DesignPatternApplication
* @Description: TODO
* @author: ex_lihui4
* @date: 2019-11-14 9:13
*/
@SpringBootApplication
public class DesignPatternApplication {
public static void main(String[] args) {
SpringApplication.run(DesignPatternApplication.class);
}
}
| 25.555556 | 68 | 0.767391 |
09b07a9b05a58b80e57f475774febee2b95f4585
| 284 |
package edp.vap.dto.dashboardDto;
import edp.vap.model.Dashboard;
import edp.vap.model.DashboardPortal;
import edp.vap.model.Project;
import lombok.Data;
@Data
public class DashboardWithPortal extends Dashboard {
private DashboardPortal portal;
private Project project;
}
| 18.933333 | 52 | 0.792254 |
4cf8aed75f67ce24e6061050dc458b61fb9a9b89
| 13,266 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.SwingConstants;
import javax.swing.text.DateFormatter;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;
import viveiro.Constantes;
/**
*
* @author Walas Jhony
*/
public class PainelVendaRealiza extends JPanel {
private int height;
private float preco;
private JButton buttonAdicionar;
private JButton buttonLimpar;
private JButton buttonOk;
private JButton buttonRemover;
private JLabel labelData;
private JLabel labelEspécie;
private JLabel labelQuantidade;
private JLabel labelPreco;
private JLabel labelValor;
private JPanel painel;
private JScrollPane scroll;
private JSeparator separador;
private JFormattedTextField textData;
private JFormattedTextField textValor;
public PainelVendaRealiza(ActionListener al) {
height = 33;
preco = 0;
separador = new JSeparator();
labelData = new JLabel("Data:");
labelValor = new JLabel("Valor:");
labelEspécie = new JLabel("Espécie:");
labelQuantidade = new JLabel("Quantidade:");
labelPreco = new JLabel("Preço:");
textData = new JFormattedTextField();
textValor = new JFormattedTextField();
buttonLimpar = new JButton(Constantes.clean);
buttonOk = new JButton(Constantes.ok);
buttonRemover = new JButton(Constantes.remove);
buttonAdicionar = new JButton(Constantes.add);
scroll = new JScrollPane();
painel = new JPanel();
separador.setOrientation(SwingConstants.VERTICAL);
labelData.setFont(Constantes.font); // NOI18N
labelData.setHorizontalAlignment(SwingConstants.CENTER);
labelValor.setFont(Constantes.font); // NOI18N
labelValor.setHorizontalAlignment(SwingConstants.CENTER);
labelEspécie.setFont(Constantes.font); // NOI18N
labelEspécie.setHorizontalAlignment(SwingConstants.CENTER);
labelQuantidade.setFont(Constantes.font); // NOI18N
labelQuantidade.setHorizontalAlignment(SwingConstants.CENTER);
labelPreco.setFont(Constantes.font); // NOI18N
labelPreco.setHorizontalAlignment(SwingConstants.CENTER);
textData.setFormatterFactory(new DefaultFormatterFactory(new DateFormatter()));
textData.setHorizontalAlignment(JTextField.CENTER);
textData.setFont(Constantes.font); // NOI18N
textValor.setEditable(false);
textValor.setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(new DecimalFormat("#,##0.00"))));
textValor.setHorizontalAlignment(JTextField.CENTER);
textValor.setFont(Constantes.font); // NOI18N
buttonLimpar.setFont(Constantes.font); // NOI18N
buttonOk.setFont(Constantes.font); // NOI18N
buttonRemover.setEnabled(false);
buttonRemover.setFont(Constantes.font); // NOI18N
buttonAdicionar.setFont(Constantes.font); // NOI18N
painel.setPreferredSize(new Dimension(435, 237));
scroll.setViewportView(painel);
GroupLayout layout = new GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(64, 64, 64)
.addComponent(buttonOk, GroupLayout.PREFERRED_SIZE, 85, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(buttonLimpar))
.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
.addComponent(labelData, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(textData, GroupLayout.PREFERRED_SIZE, 230, GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
.addComponent(labelValor, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(textValor, GroupLayout.PREFERRED_SIZE, 230, GroupLayout.PREFERRED_SIZE)))))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(separador, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(labelEspécie, GroupLayout.PREFERRED_SIZE, 125, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(labelQuantidade, GroupLayout.PREFERRED_SIZE, 125, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(labelPreco, GroupLayout.PREFERRED_SIZE, 125, GroupLayout.PREFERRED_SIZE)
.addGap(38, 38, 38))
.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(buttonRemover)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(buttonAdicionar)
.addContainerGap())
.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(scroll, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(separador)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(labelEspécie)
.addComponent(labelQuantidade)
.addComponent(labelPreco))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(scroll, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(buttonAdicionar)
.addComponent(buttonRemover)))
.addGroup(layout.createSequentialGroup()
.addGap(38, 38, 38)
.addComponent(labelData)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textData, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(labelValor)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textValor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(buttonLimpar)
.addComponent(buttonOk))))
.addContainerGap())
);
buttonLimpar.addActionListener(al);
buttonOk.addActionListener(al);
buttonRemover.addActionListener(al);
buttonAdicionar.addActionListener(al);
this.setPreferredSize(Constantes.dim);
this.setSize(Constantes.dim);
}
public void Limpa() {
textData.setValue(null);
textValor.setValue(null);
buttonRemover.setEnabled(false);
painel.removeAll();
scroll.setViewportView(painel);
}
public String getTextData() {
return textData.getText();
}
public void addMudas(String especie, int quant, float valor) {
if (height == 33) {
buttonRemover.setEnabled(true);
}
int i;
String res;
String aux = String.valueOf(quant * valor);
for (i = 0; i < aux.length(); i++) {
if ('.' == aux.charAt(i)) {
break;
}
}
res = aux.substring(0, i);
res += ",";
if (aux.length() > i + 3) {
res += aux.substring(i + 1, i + 3);
} else {
res += aux.substring(i+1, aux.length());
}
Dimension d = new Dimension(125, 28);
JFormattedTextField text1 = new JFormattedTextField(especie);
text1.setEditable(false);
text1.setFont(Constantes.font);
text1.setPreferredSize(d);
JFormattedTextField text2 = new JFormattedTextField();
text2.setEditable(false);
text2.setFont(Constantes.font);
text2.setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(new DecimalFormat("#,##0"))));
text2.setPreferredSize(d);
text2.setText(String.valueOf(quant));
JFormattedTextField text3 = new JFormattedTextField();
text3.setEditable(false);
text3.setFont(Constantes.font);
text3.setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(new DecimalFormat("#,##0.00"))));
text3.setPreferredSize(d);
text3.setText(res);
painel.add(text1);
painel.add(text2);
painel.add(text3);
painel.setPreferredSize(new Dimension(435, height));
height += 33;
scroll.setViewportView(painel);
}
public void remove() {
if ((height -= 33) == 33) {
buttonRemover.setEnabled(false);
}
painel.remove(painel.getComponentCount() - 1);
painel.remove(painel.getComponentCount() - 1);
painel.remove(painel.getComponentCount() - 1);
painel.setPreferredSize(new Dimension(435, height));
scroll.setViewportView(painel);
}
public String getTextQuantidade(int pos) {
return ((JFormattedTextField) painel.getComponent(pos * 3 - 2)).getText();
}
public void somaPrecoTotal(float valor) {
int i;
preco += valor;
String res;
String aux = String.valueOf(preco);
for (i = 0; i < aux.length(); i++) {
if ('.' == aux.charAt(i)) {
break;
}
}
res = aux.substring(0, i);
res += ",";
if (aux.length() > i + 3) {
res += aux.substring(i + 1, i + 3);
} else {
res += aux.substring(i+1, aux.length());
}
textValor.setText(res);
}
public void subPrecoTotal(float valor) {
int i;
preco -= valor;
String res;
String aux = String.valueOf(preco);
for (i = 0; i < aux.length(); i++) {
if ('.' == aux.charAt(i)) {
break;
}
}
res = aux.substring(0, i);
res += ",";
if (aux.length() > (i + 3)) {
res += aux.substring(i + 1, i + 3);
} else {
res += aux.substring(i, aux.length());
}
if (preco == 0) {
res = "0,0";
}
textValor.setText(res);
}
}
| 42.114286 | 131 | 0.605684 |
f7e5b436694c50af019f187025d5fe717b3b7a69
| 580 |
package de.gernd.spring.application;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.time.OffsetDateTime;
import static org.springframework.context.annotation.ScopedProxyMode.TARGET_CLASS;
@Component
@Scope(value = "request", proxyMode = TARGET_CLASS)
public class SessionInfo {
private final OffsetDateTime startTime;
public SessionInfo() {
this.startTime = OffsetDateTime.now();
}
@Override
public String toString() {
return "Session starting at " + startTime;
}
}
| 23.2 | 82 | 0.746552 |
7f35067ea1a22b64a6fb019d5372c4e460add8ca
| 1,636 |
/*
* Copyright 2012. Zoran Rilak
*
* 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.codemined.blueprint;
import org.codemined.blueprint.impl.CamelCaseResolver;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
/**
* @author Zoran Rilak
*/
@Test
public class BuilderTest {
@Test
void createsBuilder() {
Blueprint.Builder b = Blueprint.of(TestInterface.class);
assertNotNull(b);
}
@Test(dependsOnMethods = "createsBuilder")
void createsBuilderFromTree() {
TestInterface i = Blueprint.of(TestInterface.class)
.from(new TestTree().withTestDefaults())
.build();
assertEquals(i.serviceName(), "DummyService");
}
@Test(dependsOnMethods = "createsBuilderFromTree")
void createsBlueprintWithKeyResolver() {
TestTree t = new TestTree().withTestDefaults();
t.put("service_name", "DummyServiceUnderscored");
TestInterface i = Blueprint.of(TestInterface.class)
.from(t)
.withKeyResolver(new CamelCaseResolver())
.build();
assertEquals(i.serviceName(), "DummyServiceUnderscored");
}
}
| 29.214286 | 75 | 0.707824 |
99243c5e39274aa14960c6f2e6e60e95b08a5950
| 2,161 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* @author Maurice Bernard
*/
public class Table {
private int pot = 0;
private Player self = new Player();
private Player opponent = new Player();
private CommunityCards cCards = new CommunityCards();
private int smallBlind = 0;
private int bigBlind = 0;
private int amountToCall = 0;
/**
* @return the pot
*/
public int getPot() {
return pot;
}
/**
* @param pot the pot to set
*/
public void setPot(int pot) {
this.pot = pot;
}
/**
* @return the self
*/
public Player getSelf() {
return self;
}
/**
* @param self the self to set
*/
public void setSelf(Player self) {
this.self = self;
}
/**
* @return the opponent
*/
public Player getOpponent() {
return opponent;
}
/**
* @param opponent the opponent to set
*/
public void setOpponent(Player opponent) {
this.opponent = opponent;
}
/**
* @return the cCards
*/
public CommunityCards getcCards() {
return cCards;
}
/**
* @param cCards the cCards to set
*/
public void setcCards(CommunityCards cCards) {
this.cCards = cCards;
}
/**
* @return the smallBlind
*/
public int getSmallBlind() {
return smallBlind;
}
/**
* @param smallBlind the smallBlind to set
*/
public void setSmallBlind(int smallBlind) {
this.smallBlind = smallBlind;
}
/**
* @return the bigBlind
*/
public int getBigBlind() {
return bigBlind;
}
/**
* @param bigBlind the bigBlind to set
*/
public void setBigBlind(int bigBlind) {
this.bigBlind = bigBlind;
}
/**
* @return the amountToCall
*/
public int getAmountToCall() {
return amountToCall;
}
/**
* @param amountToCall the amountToCall to set
*/
public void setAmountToCall(int amountToCall) {
this.amountToCall = amountToCall;
}
}
| 18.313559 | 80 | 0.584452 |
61d93ea27cdf39674c490eb1c0a2e3acaf220abc
| 2,298 |
package org.sunbird.ruleengine.model;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name="AUDIT_USER_ACTION")
public class AuditUserAction extends AbstractMultiTenantEntity implements Serializable{
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="AUDIT_USR_ACTION_SEQ")
@SequenceGenerator(name="AUDIT_USR_ACTION_SEQ", sequenceName="AUDIT_USR_ACTION_SEQ", allocationSize=1)
private BigInteger id;
private static final long serialVersionUID = 1723925210620674919L;
public AuditUserAction() {
super();
}
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public BigInteger getRowId() {
return rowId;
}
public void setRowId(BigInteger rowId) {
this.rowId = rowId;
}
public BigInteger getActionBy() {
return actionBy;
}
public void setActionBy(BigInteger actionBy) {
this.actionBy = actionBy;
}
public Date getActionDate() {
return actionDate;
}
public void setActionDate(Date actionDate) {
this.actionDate = actionDate;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
@Column(name = "TABLE_NAME")
private String tableName;
@Column(name = "ROW_ID")
private BigInteger rowId;
@Column(name = "ACTION_BY")
private BigInteger actionBy;
@Column(name = "ORG_ID")
private BigInteger orgId;
public BigInteger getOrgId() {
return orgId;
}
public void setOrgId(BigInteger orgId) {
this.orgId = orgId;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "ACTION_DATE_TIME")
private Date actionDate;
@Column(name = "ACTION")
private String action;
}
| 17.278195 | 103 | 0.717581 |
0085c272f11ff1cdd4e2635d16d3ca946cae4ac6
| 31,927 |
/*
* 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.hop.git.model;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.io.FilenameUtils;
import org.apache.hop.core.Const;
import org.apache.hop.core.exception.HopException;
import org.apache.hop.core.exception.HopFileException;
import org.apache.hop.core.logging.LogChannel;
import org.apache.hop.core.vfs.HopVfs;
import org.apache.hop.git.model.revision.GitObjectRevision;
import org.apache.hop.git.model.revision.ObjectRevision;
import org.apache.hop.i18n.BaseMessages;
import org.apache.hop.ui.core.dialog.EnterSelectionDialog;
import org.eclipse.jgit.api.*;
import org.eclipse.jgit.api.ListBranchCommand.ListMode;
import org.eclipse.jgit.api.MergeResult.MergeStatus;
import org.eclipse.jgit.api.ResetCommand.ResetType;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.diff.DiffEntry.ChangeType;
import org.eclipse.jgit.diff.RenameDetector;
import org.eclipse.jgit.dircache.DirCacheIterator;
import org.eclipse.jgit.errors.*;
import org.eclipse.jgit.lib.*;
import org.eclipse.jgit.merge.MergeStrategy;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevObject;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.*;
import org.eclipse.jgit.transport.http.apache.HttpClientConnectionFactory;
import org.eclipse.jgit.treewalk.*;
import org.eclipse.jgit.treewalk.filter.PathFilter;
import org.eclipse.jgit.treewalk.filter.TreeFilter;
import org.eclipse.jgit.util.FileUtils;
import org.eclipse.jgit.util.RawParseUtils;
import org.eclipse.jgit.util.SystemReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.stream.Collectors;
public class UIGit extends VCS {
static {
/**
* Use Apache HTTP Client instead of Sun HTTP client. This resolves the issue that Git commands
* (e.g., push, clone) via http(s) do not work in EE. This issue is caused by the fact that weka
* plugins (namely, knowledge-flow, weka-forecasting, and weka-scoring) calls
* java.net.Authenticator.setDefault(). See here
* https://bugs.eclipse.org/bugs/show_bug.cgi?id=296201 for more details.
*/
HttpTransport.setConnectionFactory(new HttpClientConnectionFactory());
}
private Git git;
private CredentialsProvider credentialsProvider;
/* (non-Javadoc)
* @see org.apache.hop.git.spoon.model.VCS#getDirectory()
*/
public String getDirectory() {
return directory;
}
@VisibleForTesting
void setDirectory(String directory) {
this.directory = directory;
}
@VisibleForTesting
void setGit(Git git) {
this.git = git;
}
public String getAuthorName(String commitId) {
if (commitId.equals(VCS.WORKINGTREE)) {
Config config = git.getRepository().getConfig();
return config.get(UserConfig.KEY).getAuthorName()
+ " <"
+ config.get(UserConfig.KEY).getAuthorEmail()
+ ">";
} else {
RevCommit commit = resolve(commitId);
PersonIdent author = commit.getAuthorIdent();
final StringBuilder r = new StringBuilder();
r.append(author.getName());
r.append(" <"); //
r.append(author.getEmailAddress());
r.append(">"); //
return r.toString();
}
}
public String getCommitMessage(String commitId) {
if (commitId.equals(VCS.WORKINGTREE)) {
try {
String merge_msg = git.getRepository().readMergeCommitMsg();
return merge_msg == null ? "" : merge_msg;
} catch (Exception e) {
return e.getMessage();
}
} else {
RevCommit commit = resolve(commitId);
return commit.getFullMessage();
}
}
public String getCommitId(String revstr) {
ObjectId id = null;
try {
id = git.getRepository().resolve(revstr);
} catch (RevisionSyntaxException e) {
e.printStackTrace();
} catch (AmbiguousObjectException e) {
e.printStackTrace();
} catch (IncorrectObjectTypeException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (id == null) {
return null;
} else {
return id.getName();
}
}
public String getParentCommitId(String revstr) {
return getCommitId(revstr + "~");
}
public String getBranch() {
try {
Ref head = git.getRepository().exactRef(Constants.HEAD);
String branch = git.getRepository().getBranch();
if (head.getLeaf().getName().equals(Constants.HEAD)) { // if detached
return Constants.HEAD + " detached at " + branch.substring(0, 7);
} else {
return branch;
}
} catch (Exception e) {
return "";
}
}
public List<String> getLocalBranches() {
return getBranches(null);
}
public List<String> getBranches() {
return getBranches(ListMode.ALL);
}
/**
* Get a list of branches based on mode
*
* @param mode
* @return
*/
private List<String> getBranches(ListMode mode) {
try {
return git.branchList().setListMode(mode).call().stream()
.filter(ref -> !ref.getName().endsWith(Constants.HEAD))
.map(ref -> Repository.shortenRefName(ref.getName()))
.collect(Collectors.toList());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getRemote() {
try {
StoredConfig config = git.getRepository().getConfig();
RemoteConfig remoteConfig = new RemoteConfig(config, Constants.DEFAULT_REMOTE_NAME);
return remoteConfig.getURIs().iterator().next().toString();
} catch (Exception e) {
return "";
}
}
public void addRemote(String value) {
// Make sure you have only one URI for push
removeRemote();
try {
URIish uri = new URIish(value);
RemoteAddCommand cmd = git.remoteAdd();
cmd.setName(Constants.DEFAULT_REMOTE_NAME);
cmd.setUri(uri);
cmd.call();
} catch (URISyntaxException e) {
if (value.equals("")) {
removeRemote();
} else {
showMessageBox(BaseMessages.getString(PKG, "Dialog.Error"), e.getMessage());
}
} catch (GitAPIException e) {
showMessageBox(BaseMessages.getString(PKG, "Dialog.Error"), e.getMessage());
}
}
public void removeRemote() {
RemoteRemoveCommand cmd = git.remoteRemove();
cmd.setName(Constants.DEFAULT_REMOTE_NAME);
try {
cmd.call();
} catch (GitAPIException e) {
showMessageBox(BaseMessages.getString(PKG, "Dialog.Error"), e.getMessage());
}
}
public boolean hasRemote() {
StoredConfig config = git.getRepository().getConfig();
Set<String> remotes = config.getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
return remotes.contains(Constants.DEFAULT_REMOTE_NAME);
}
public boolean commit(String authorName, String message) throws HopException {
PersonIdent author = RawParseUtils.parsePersonIdent(authorName);
// Set the local time
PersonIdent author2 =
new PersonIdent(
author.getName(),
author.getEmailAddress(),
SystemReader.getInstance().getCurrentTime(),
SystemReader.getInstance().getTimezone(SystemReader.getInstance().getCurrentTime()));
try {
git.commit().setAuthor(author2).setMessage(message).call();
return true;
} catch (Exception e) {
throw new HopException("Error in git commit", e);
}
}
public List<ObjectRevision> getRevisions() {
return getRevisions(null);
}
public List<ObjectRevision> getRevisions(String path) {
List<ObjectRevision> revisions = new ArrayList<>();
try {
if (!isClean()
|| git.getRepository().getRepositoryState() == RepositoryState.MERGING_RESOLVED) {
GitObjectRevision rev =
new GitObjectRevision(WORKINGTREE, "*", new Date(), " // " + VCS.WORKINGTREE);
revisions.add(rev);
}
LogCommand logCommand = git.log();
if (path != null && !".".equals(path)) {
logCommand = logCommand.addPath(path);
}
Iterable<RevCommit> iterable = logCommand.call();
for (RevCommit commit : iterable) {
GitObjectRevision rev =
new GitObjectRevision(
commit.getName(),
commit.getAuthorIdent().getName(),
commit.getAuthorIdent().getWhen(),
commit.getShortMessage());
revisions.add(rev);
}
} catch (Exception e) {
// Do nothing
}
return revisions;
}
public List<UIFile> getUnstagedFiles() {
return getUnstagedFiles(null);
}
public List<UIFile> getUnstagedFiles(String path) {
List<UIFile> files = new ArrayList<>();
Status status = null;
try {
StatusCommand statusCommand = git.status();
if (path != null && !".".equals(path)) {
statusCommand = statusCommand.addPath(path);
}
status = statusCommand.call();
} catch (Exception e) {
e.printStackTrace();
return files;
}
status
.getUntracked()
.forEach(
name -> {
files.add(new UIFile(name, ChangeType.ADD, false));
});
status
.getModified()
.forEach(
name -> {
files.add(new UIFile(name, ChangeType.MODIFY, false));
});
status
.getConflicting()
.forEach(
name -> {
files.add(new UIFile(name, ChangeType.MODIFY, false));
});
status
.getMissing()
.forEach(
name -> {
files.add(new UIFile(name, ChangeType.DELETE, false));
});
return files;
}
public List<UIFile> getStagedFiles() {
List<UIFile> files = new ArrayList<>();
Status status = null;
try {
status = git.status().call();
} catch (Exception e) {
e.printStackTrace();
return files;
}
status
.getAdded()
.forEach(
name -> {
files.add(new UIFile(name, ChangeType.ADD, true));
});
status
.getChanged()
.forEach(
name -> {
files.add(new UIFile(name, ChangeType.MODIFY, true));
});
status
.getRemoved()
.forEach(
name -> {
files.add(new UIFile(name, ChangeType.DELETE, true));
});
return files;
}
public List<UIFile> getStagedFiles(String oldCommitId, String newCommitId) {
List<UIFile> files = new ArrayList<>();
try {
List<DiffEntry> diffs =
getDiffCommand(oldCommitId, newCommitId).setShowNameAndStatusOnly(true).call();
RenameDetector rd = new RenameDetector(git.getRepository());
rd.addAll(diffs);
diffs = rd.compute();
diffs.forEach(
diff -> {
files.add(
new UIFile(
diff.getChangeType() == ChangeType.DELETE
? diff.getOldPath()
: diff.getNewPath(),
diff.getChangeType(),
false));
});
} catch (Exception e) {
e.printStackTrace();
}
return files;
}
public boolean hasStagedFiles() {
if (git.getRepository().getRepositoryState() == RepositoryState.SAFE) {
return !getStagedFiles().isEmpty();
} else {
return git.getRepository().getRepositoryState().canCommit();
}
}
public void initRepo(String baseDirectory) throws Exception {
git = Git.init().setDirectory(new File(baseDirectory)).call();
directory = baseDirectory;
}
public void openRepo(String baseDirectory) throws Exception {
git = Git.open(new File(baseDirectory));
directory = baseDirectory;
}
public void closeRepo() {
git.close();
git = null;
}
public void add(String filePattern) throws HopException {
try {
if (filePattern.endsWith(".ours") || filePattern.endsWith(".theirs")) {
FileUtils.rename(
new File(directory, filePattern),
new File(directory, FilenameUtils.removeExtension(filePattern)),
StandardCopyOption.REPLACE_EXISTING);
filePattern = FilenameUtils.removeExtension(filePattern);
org.apache.commons.io.FileUtils.deleteQuietly(new File(directory, filePattern + ".ours"));
org.apache.commons.io.FileUtils.deleteQuietly(new File(directory, filePattern + ".theirs"));
}
git.add().addFilepattern(filePattern).call();
} catch (Exception e) {
throw new HopException("Error adding '" + filePattern + "'to git", e);
}
}
public void rm(String filepattern) {
try {
git.rm().addFilepattern(filepattern).call();
} catch (Exception e) {
showMessageBox(BaseMessages.getString(PKG, "Dialog.Error"), e.getMessage());
}
}
/** Reset to a commit (mixed) */
public void reset(String name) {
try {
git.reset().setRef(name).call();
} catch (Exception e) {
showMessageBox(BaseMessages.getString(PKG, "Dialog.Error"), e.getMessage());
}
}
/** Reset a file to HEAD (mixed) */
public void resetPath(String path) {
try {
git.reset().addPath(path).call();
} catch (Exception e) {
showMessageBox(BaseMessages.getString(PKG, "Dialog.Error"), e.getMessage());
}
}
@VisibleForTesting
void resetHard() throws Exception {
git.reset().setMode(ResetType.HARD).call();
}
public boolean rollback(String name) {
if (hasUncommittedChanges()) {
showMessageBox(
BaseMessages.getString(PKG, "Dialog.Error"),
BaseMessages.getString(PKG, "Git.Dialog.UncommittedChanges.Message"));
return false;
}
String commit = resolve(Constants.HEAD).getName();
RevertCommand cmd = git.revert();
for (int i = 0; i < getRevisions().size(); i++) {
String commitId = getRevisions().get(i).getRevisionId();
/*
* Revert commits from HEAD to the specified commit in reverse order.
*/
cmd.include(resolve(commitId));
if (commitId.equals(name)) {
break;
}
}
try {
cmd.call();
git.reset().setRef(commit).call();
return true;
} catch (Exception e) {
showMessageBox(BaseMessages.getString(PKG, "Dialog.Error"), e.getMessage());
}
return false;
}
public boolean pull() throws HopException {
if (hasUncommittedChanges()) {
throw new HopException(
"You have uncommitted changes. Please commit work before pulling changes.");
}
if (!hasRemote()) {
throw new HopException("There is no remote set up to pull from. Please set this up first.");
}
try {
// Pull = Fetch + Merge
git.fetch().setCredentialsProvider(credentialsProvider).call();
return mergeBranch(
Constants.DEFAULT_REMOTE_NAME + "/" + getBranch(), MergeStrategy.RECURSIVE.getName());
} catch (TransportException e) {
if (e.getMessage()
.contains("Authentication is required but no CredentialsProvider has been registered")
|| e.getMessage()
.contains("not authorized")) { // when the cached credential does not work
if (promptUsernamePassword()) {
return pull();
}
} else {
throw new HopException("There was an error doing a git pull", e);
}
} catch (Exception e) {
throw new HopException("There was an error doing a git pull", e);
}
return false;
}
public boolean push() throws HopException {
return push("default");
}
public boolean push(String type) throws HopException {
if (!hasRemote()) {
throw new HopException("There is no remote set up to push to. Please set this up.");
}
String name = null;
List<String> names;
EnterSelectionDialog esd;
switch (type) {
case VCS.TYPE_BRANCH:
names = getLocalBranches();
esd =
getEnterSelectionDialog(
names.toArray(new String[names.size()]),
"Select Branch",
"Select the branch to push...");
name = esd.open();
if (name == null) {
return false;
}
break;
case VCS.TYPE_TAG:
names = getTags();
esd =
getEnterSelectionDialog(
names.toArray(new String[names.size()]), "Select Tag", "Select the tag to push...");
name = esd.open();
if (name == null) {
return false;
}
break;
}
try {
name = name == null ? null : getExpandedName(name, type);
PushCommand cmd = git.push();
cmd.setCredentialsProvider(credentialsProvider);
if (name != null) {
cmd.setRefSpecs(new RefSpec(name));
}
Iterable<PushResult> resultIterable = cmd.call();
processPushResult(resultIterable);
return true;
} catch (TransportException e) {
if (e.getMessage()
.contains("Authentication is required but no CredentialsProvider has been registered")
|| e.getMessage()
.contains("not authorized")) { // when the cached credential does not work
if (promptUsernamePassword()) {
return push(type);
}
} else {
throw new HopException("There was an error doing a git push", e);
}
} catch (Exception e) {
throw new HopException("There was an error doing a git push", e);
}
return false;
}
private void processPushResult(Iterable<PushResult> resultIterable) throws Exception {
resultIterable.forEach(
result -> { // for each (push)url
StringBuilder sb = new StringBuilder();
result.getRemoteUpdates().stream()
.filter(update -> update.getStatus() != RemoteRefUpdate.Status.OK)
.filter(update -> update.getStatus() != RemoteRefUpdate.Status.UP_TO_DATE)
.forEach(
update -> { // for each failed refspec
sb.append(
result.getURI().toString()
+ "\n"
+ update.getSrcRef().toString()
+ "\n"
+ update.getStatus().toString()
+ (update.getMessage() == null ? "" : "\n" + update.getMessage())
+ "\n\n");
});
if (sb.length() == 0) {
showMessageBox(
BaseMessages.getString(PKG, "Dialog.Success"),
BaseMessages.getString(PKG, "Dialog.Success"));
} else {
showMessageBox(BaseMessages.getString(PKG, "Dialog.Error"), sb.toString());
}
});
}
public String diff(String oldCommitId, String newCommitId) throws Exception {
return diff(oldCommitId, newCommitId, null);
}
public String diff(String oldCommitId, String newCommitId, String file) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
getDiffCommand(oldCommitId, newCommitId)
.setOutputStream(out)
.setPathFilter(file == null ? TreeFilter.ALL : PathFilter.create(file))
.call();
return out.toString("UTF-8");
} catch (Exception e) {
return e.getMessage();
}
}
public InputStream open(String file, String commitId) throws HopException {
if (commitId.equals(WORKINGTREE)) {
String baseDirectory = getDirectory();
String filePath = baseDirectory + Const.FILE_SEPARATOR + file;
try {
return HopVfs.getInputStream(filePath);
} catch (HopFileException e) {
throw new HopException("Unable to find working tree file '" + filePath + "'", e);
}
}
RevCommit commit = resolve(commitId);
RevTree tree = commit.getTree();
try (TreeWalk tw = new TreeWalk(git.getRepository())) {
tw.addTree(tree);
tw.setFilter(PathFilter.create(file));
tw.setRecursive(true);
tw.next();
ObjectLoader loader = git.getRepository().open(tw.getObjectId(0));
return loader.openStream();
} catch (MissingObjectException e) {
throw new HopException(
"Unable to find file '" + file + "' for commit ID '" + commitId + "", e);
} catch (IncorrectObjectTypeException e) {
throw new HopException(
"Incorrect object type error for file '" + file + "' for commit ID '" + commitId + "", e);
} catch (CorruptObjectException e) {
throw new HopException(
"Corrupt object error for file '" + file + "' for commit ID '" + commitId + "", e);
} catch (IOException e) {
throw new HopException(
"Error reading git file '" + file + "' for commit ID '" + commitId + "", e);
}
}
public boolean cloneRepo(String directory, String uri) {
CloneCommand cmd = Git.cloneRepository();
cmd.setDirectory(new File(directory));
cmd.setURI(uri);
cmd.setCredentialsProvider(credentialsProvider);
try {
Git git = cmd.call();
git.close();
return true;
} catch (Exception e) {
if ((e instanceof TransportException)
&& ((e.getMessage()
.contains(
"Authentication is required but no CredentialsProvider has been registered")
|| e.getMessage().contains("not authorized")))) {
if (promptUsernamePassword()) {
return cloneRepo(directory, uri);
}
} else {
showMessageBox(BaseMessages.getString(PKG, "Dialog.Error"), e.getMessage());
}
}
return false;
}
public void checkout(String name) {
try {
git.checkout().setName(name).call();
} catch (Exception e) {
showMessageBox(BaseMessages.getString(PKG, "Dialog.Error"), e.getMessage());
}
}
public void checkoutBranch(String name) {
checkout(name);
}
public void checkoutTag(String name) {
checkout(name);
}
public void revertPath(String path) throws HopException {
try {
// Revert files to HEAD state
Status status = git.status().addPath(path).call();
if (status.getUntracked().size() != 0 || status.getAdded().size() != 0) {
resetPath(path);
org.apache.commons.io.FileUtils.deleteQuietly(new File(directory, path));
}
/*
* This is a work-around to discard changes of conflicting files
* Git CLI `git checkout -- conflicted.txt` discards the changes, but jgit does not
*/
git.add().addFilepattern(path).call();
git.checkout().setStartPoint(Constants.HEAD).addPath(path).call();
org.apache.commons.io.FileUtils.deleteQuietly(new File(directory, path + ".ours"));
org.apache.commons.io.FileUtils.deleteQuietly(new File(directory, path + ".theirs"));
} catch (Exception e) {
throw new HopException("Git: error reverting path '" + path + "'", e);
}
}
/**
* Get the list of files which will be reverted.
*
* @param path The path to revert
* @return The list of affected files
*/
public List<String> getRevertPathFiles(String path) throws HopException {
try {
Set<String> files = new HashSet<>();
StatusCommand statusCommand = git.status();
if (path != null && !".".equals(path)) {
statusCommand = statusCommand.addPath(path);
}
// Get files to be reverted to HEAD state
//
Status status = statusCommand.call();
files.addAll(status.getUntracked());
files.addAll(status.getAdded());
files.addAll(status.getMissing());
files.addAll(status.getChanged());
files.addAll(status.getUncommittedChanges());
return new ArrayList<>(files);
} catch (Exception e) {
throw new HopException("Git: error reverting path files for '" + path + "'", e);
}
}
public boolean createBranch(String value) {
try {
git.branchCreate().setName(value).call();
checkoutBranch(getExpandedName(value, VCS.TYPE_BRANCH));
return true;
} catch (Exception e) {
showMessageBox(BaseMessages.getString(PKG, "Dialog.Error"), e.getMessage());
return false;
}
}
public boolean deleteBranch(String name, boolean force) {
try {
git.branchDelete()
.setBranchNames(getExpandedName(name, VCS.TYPE_BRANCH))
.setForce(force)
.call();
return true;
} catch (Exception e) {
showMessageBox(BaseMessages.getString(PKG, "Dialog.Error"), e.getMessage());
return false;
}
}
private boolean mergeBranch(String value, String mergeStrategy) throws HopException {
try {
ObjectId obj = git.getRepository().resolve(value);
MergeResult result =
git.merge().include(obj).setStrategy(MergeStrategy.get(mergeStrategy)).call();
if (result.getMergeStatus().isSuccessful()) {
return true;
} else {
// TODO: get rid of message box
//
showMessageBox(
BaseMessages.getString(PKG, "Dialog.Error"), result.getMergeStatus().toString());
if (result.getMergeStatus() == MergeStatus.CONFLICTING) {
Map<String, int[][]> conflicts = result.getConflicts();
for (String path : conflicts.keySet()) {
checkout(path, Constants.HEAD, ".ours");
checkout(path, getExpandedName(value, VCS.TYPE_BRANCH), ".theirs");
}
return true;
}
}
return false;
} catch (Exception e) {
throw new HopException(
"Error merging branch '" + value + "' with strategy '" + mergeStrategy + "'", e);
}
}
private boolean hasUncommittedChanges() {
try {
return git.status().call().hasUncommittedChanges();
} catch (NoWorkTreeException | GitAPIException e) {
e.printStackTrace();
return false;
}
}
private void checkout(String path, String commitId, String postfix) throws HopException {
InputStream stream = open(path, commitId);
File file = new File(directory + Const.FILE_SEPARATOR + path + postfix);
try {
org.apache.commons.io.FileUtils.copyInputStreamToFile(stream, file);
stream.close();
} catch (IOException e) {
throw new HopException(
"Error checking out file '"
+ path
+ "' for commit ID '"
+ commitId
+ "' and postfix "
+ postfix,
e);
}
}
private DiffCommand getDiffCommand(String oldCommitId, String newCommitId) throws Exception {
return git.diff()
.setOldTree(getTreeIterator(oldCommitId))
.setNewTree(getTreeIterator(newCommitId));
}
private AbstractTreeIterator getTreeIterator(String commitId) throws Exception {
if (commitId == null) {
return new EmptyTreeIterator();
}
if (commitId.equals(WORKINGTREE)) {
return new FileTreeIterator(git.getRepository());
} else if (commitId.equals(INDEX)) {
return new DirCacheIterator(git.getRepository().readDirCache());
} else {
ObjectId id = git.getRepository().resolve(commitId);
if (id == null) { // commitId does not exist
return new EmptyTreeIterator();
} else {
CanonicalTreeParser treeIterator = new CanonicalTreeParser();
try (RevWalk rw = new RevWalk(git.getRepository())) {
RevTree tree = rw.parseTree(id);
try (ObjectReader reader = git.getRepository().newObjectReader()) {
treeIterator.reset(reader, tree.getId());
}
}
return treeIterator;
}
}
}
public String getShortenedName(String name, String type) {
if (name.length() == Constants.OBJECT_ID_STRING_LENGTH) {
return name.substring(0, 7);
} else {
return Repository.shortenRefName(name);
}
}
public boolean isClean() {
try {
return git.status().call().isClean();
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public List<String> getTags() {
try {
return git.tagList().call().stream()
.map(ref -> Repository.shortenRefName(ref.getName()))
.collect(Collectors.toList());
} catch (GitAPIException e) {
e.printStackTrace();
}
return null;
}
public boolean createTag(String name) {
try {
git.tag().setName(name).call();
return true;
} catch (Exception e) {
showMessageBox(BaseMessages.getString(PKG, "Dialog.Error"), e.getMessage());
return false;
}
}
public boolean deleteTag(String name) {
try {
git.tagDelete().setTags(getExpandedName(name, VCS.TYPE_TAG)).call();
return true;
} catch (GitAPIException e) {
showMessageBox(BaseMessages.getString(PKG, "Dialog.Error"), e.getMessage());
return false;
}
}
public String getExpandedName(String name, String type) {
switch (type) {
case TYPE_TAG:
return Constants.R_TAGS + name;
case TYPE_BRANCH:
try {
return git.getRepository().findRef(Constants.R_HEADS + name).getName();
} catch (Exception e) {
try {
return git.getRepository().findRef(Constants.R_REMOTES + name).getName();
} catch (Exception e1) {
showMessageBox(BaseMessages.getString(PKG, "Dialog.Error"), e.getMessage());
}
}
default:
return getCommitId(name);
}
}
@Override
public void setCredential(String username, String password) {
credentialsProvider = new UsernamePasswordCredentialsProvider(username, password);
}
public RevCommit resolve(String commitId) {
ObjectId id = null;
try {
id = git.getRepository().resolve(commitId);
} catch (RevisionSyntaxException e1) {
e1.printStackTrace();
} catch (AmbiguousObjectException e1) {
e1.printStackTrace();
} catch (IncorrectObjectTypeException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try (RevWalk rw = new RevWalk(git.getRepository())) {
RevObject obj = rw.parseAny(id);
RevCommit commit = (RevCommit) obj;
return commit;
} catch (MissingObjectException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@VisibleForTesting
EnterSelectionDialog getEnterSelectionDialog(String[] choices, String shellText, String message) {
return new EnterSelectionDialog(shell, choices, shellText, message);
}
public Set<String> getIgnored(String path) {
try {
StatusCommand statusCommand = git.status();
if (path != null && !".".equals(path)) {
statusCommand = statusCommand.addPath(path);
}
Status status = statusCommand.call();
return status.getIgnoredNotInIndex();
} catch (GitAPIException e) {
LogChannel.UI.logError("Error getting list of files ignored by git", e);
return new HashSet<>();
}
}
public Git getGit() {
return git;
}
}
| 32.314777 | 100 | 0.622514 |
845be138d47c4deacfd78850ec5a3c39a585a9ac
| 995 |
package com.yzh.androidquickdevlib.app;
import android.app.Activity;
import android.app.Application.ActivityLifecycleCallbacks;
import android.os.Bundle;
public class SimpleActivityLifecycleCallbacks implements ActivityLifecycleCallbacks
{
public SimpleActivityLifecycleCallbacks()
{
// TODO 自动生成的构造函数存根
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState)
{
// TODO 自动生成的方法存根
}
@Override
public void onActivityStarted(Activity activity)
{
// TODO 自动生成的方法存根
}
@Override
public void onActivityResumed(Activity activity)
{
// TODO 自动生成的方法存根
}
@Override
public void onActivityPaused(Activity activity)
{
// TODO 自动生成的方法存根
}
@Override
public void onActivityStopped(Activity activity)
{
// TODO 自动生成的方法存根
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState)
{
// TODO 自动生成的方法存根
}
@Override
public void onActivityDestroyed(Activity activity)
{
// TODO 自动生成的方法存根
}
}
| 15.307692 | 83 | 0.764824 |
894fb38bb1f6edcec9c9460d730684a23ae86438
| 2,056 |
//package com.bootdo.reserve_functions.feign_demo;
//
//import org.springframework.http.MediaType;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestBody;
//import org.springframework.web.bind.annotation.RequestParam;
//
///**
// * @Author: wushiqiang
// * @Date: Created in 11:24 2019/5/13
// * @Description:
// * @Modified By:
// */
//@FeignClient(value = "user-api", url = "${gateway.base-url}", fallbackFactory = UserFeignFactory.class)
//public interface UserLoginAPI {
//
// /**
// * 用前端传递的微信code去获取openid
// * @param wxUserCodeInDTO
// * @return 返回openid和用户的昵称
// */
// @PostMapping(value = "/monkey/user/getWxUser",consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE)
// ApiOutDTO getWxUser(@RequestBody WxUserCodeInDTO wxUserCodeInDTO);
//
// /**
// * 根据openId获取aid
// * @param getAidInDTO
// * @return aid
// */
// @PostMapping(value = "/monkey/user/getAid",consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE)
// ApiOutDTO getAid(@RequestBody GetAidInDTO getAidInDTO);
//
// /**
// * 根据aid获取太马token
// * @param memberInfoInDTO
// * @return aid
// */
// @PostMapping(value = "monkey/user/getTokenByAid",consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE)
// ApiOutDTO getTokenByAid(@RequestBody MemberInfoInDTO memberInfoInDTO);
//
// /**
// * 获取用户的会员信息
// * @param memberInfoInDTO
// * @return
// */
// @PostMapping(value = "/monkey/member/getMemberInfo",consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE)
// ApiOutDTO getMemberInfo(@RequestBody MemberInfoInDTO memberInfoInDTO);
//
// /**
// * 用户分享
// * @param url
// * @return
// */
// @GetMapping(value = "/monkey/wx/sign",consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE)
// ApiOutDTO sign(@RequestParam(value = "url", required = true) String url);
//
//}
| 34.847458 | 143 | 0.728599 |
d136d0a0edfb4c565ee17b2e33a11d91a6d44628
| 1,831 |
package com.gechen.keepwalking.kw.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.gechen.keepwalking.R;
import com.kw_support.base.BaseActivity;
import com.kw_support.utils.AppUtil;
import com.kw_support.utils.SystemFunUtil;
import com.kw_support.utils.UiUtil;
import com.kw_support.view.BounceScrollView;
@Deprecated
public class BounceScrollViewActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bounce_scroll_view);
init();
}
private void init() {
if(AppUtil.isLocationEnable(BounceScrollViewActivity.this)) {
UiUtil.showToast(BounceScrollViewActivity.this, "GPS可用");
} else {
UiUtil.showToast(BounceScrollViewActivity.this, "GPS不可用");
}
if(AppUtil.isBluetoothEnable()) {
UiUtil.showToast(BounceScrollViewActivity.this, "蓝牙可用");
} else {
UiUtil.showToast(BounceScrollViewActivity.this, "蓝牙不可用");
}
}
public void openWifiSetting(View view) {
SystemFunUtil.gotoSettingNetWork(BounceScrollViewActivity.this);
}
public void openGPSSetting(View view) {
SystemFunUtil.gotoSettingGPS(BounceScrollViewActivity.this);
}
public void openBluetoothSetting(View view) {
SystemFunUtil.openBluetoothWithRequest(BounceScrollViewActivity.this, 0x0000001);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 0x0000001) {
UiUtil.showToast(BounceScrollViewActivity.this, "Bluetooth RequestCode: " + requestCode);
}
}
}
| 31.568966 | 101 | 0.712725 |
8a6c291e4bbfc2822b0cfcaefeace41cb10cce32
| 6,292 |
package com.cerner.jwala.service.resource.impl.handler;
import com.cerner.jwala.common.domain.model.jvm.Jvm;
import com.cerner.jwala.common.domain.model.resource.ResourceIdentifier;
import com.cerner.jwala.common.domain.model.resource.ResourceTemplateMetaData;
import com.cerner.jwala.common.request.jvm.UploadJvmConfigTemplateRequest;
import com.cerner.jwala.common.request.jvm.UploadJvmTemplateRequest;
import com.cerner.jwala.persistence.jpa.domain.resource.config.template.ConfigTemplate;
import com.cerner.jwala.persistence.service.GroupPersistenceService;
import com.cerner.jwala.persistence.service.JvmPersistenceService;
import com.cerner.jwala.persistence.service.ResourceDao;
import com.cerner.jwala.service.resource.ResourceHandler;
import com.cerner.jwala.service.resource.impl.CreateResourceResponseWrapper;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Handler for a group level JVM resource identified by a "resource identifier" {@link ResourceIdentifier}
*
* Created by Jedd Cuison on 7/21/2016
*/
public class GroupLevelJvmResourceHandler extends ResourceHandler {
private final GroupPersistenceService groupPersistenceService;
private final JvmPersistenceService jvmPersistenceService;
public GroupLevelJvmResourceHandler(final ResourceDao resourceDao, final GroupPersistenceService groupPersistenceService,
final JvmPersistenceService jvmPersistenceService, final ResourceHandler successor) {
this.resourceDao = resourceDao;
this.groupPersistenceService = groupPersistenceService;
this.jvmPersistenceService = jvmPersistenceService;
this.successor = successor;
}
@Override
public ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier) {
ConfigTemplate configTemplate = null;
if (canHandle(resourceIdentifier)) {
configTemplate = resourceDao.getGroupLevelJvmResource(resourceIdentifier.resourceName, resourceIdentifier.groupName);
} else if (successor != null) {
configTemplate = successor.fetchResource(resourceIdentifier);
}
return configTemplate;
}
@Override
public CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent) {
CreateResourceResponseWrapper createResourceResponseWrapper = null;
if (canHandle(resourceIdentifier)) {
final Set<Jvm> jvms = groupPersistenceService.getGroup(resourceIdentifier.groupName).getJvms();
ConfigTemplate createdJpaJvmConfigTemplate = null;
for (final Jvm jvm : jvms) {
UploadJvmConfigTemplateRequest uploadJvmTemplateRequest = new UploadJvmConfigTemplateRequest(jvm, metaData.getTemplateName(),
templateContent, metaData.getJsonData());
uploadJvmTemplateRequest.setConfFileName(metaData.getDeployFileName());
// Since we're just creating the same template for all the JVMs, we just keep one copy of the created
// configuration template.
createdJpaJvmConfigTemplate = jvmPersistenceService.uploadJvmConfigTemplate(uploadJvmTemplateRequest);
}
final List<UploadJvmTemplateRequest> uploadJvmTemplateRequestList = new ArrayList<>();
UploadJvmConfigTemplateRequest uploadJvmTemplateRequest = new UploadJvmConfigTemplateRequest(null, metaData.getTemplateName(),
templateContent, metaData.getJsonData());
uploadJvmTemplateRequest.setConfFileName(metaData.getDeployFileName());
uploadJvmTemplateRequestList.add(uploadJvmTemplateRequest);
groupPersistenceService.populateGroupJvmTemplates(resourceIdentifier.groupName, uploadJvmTemplateRequestList);
createResourceResponseWrapper = new CreateResourceResponseWrapper(createdJpaJvmConfigTemplate);
} else if (successor != null) {
createResourceResponseWrapper = successor.createResource(resourceIdentifier, metaData, templateContent);
}
return createResourceResponseWrapper;
}
@Override
public void deleteResource(final ResourceIdentifier resourceIdentifier) {
throw new UnsupportedOperationException();
}
@Override
protected boolean canHandle(final ResourceIdentifier resourceIdentifier) {
return StringUtils.isNotEmpty(resourceIdentifier.resourceName) &&
StringUtils.isNotEmpty(resourceIdentifier.groupName) &&
"*".equalsIgnoreCase(resourceIdentifier.jvmName) &&
StringUtils.isEmpty(resourceIdentifier.webServerName) &&
StringUtils.isEmpty(resourceIdentifier.webAppName);
}
@Override
public String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData) {
if (canHandle(resourceIdentifier)) {
final String updatedMetaData = groupPersistenceService.updateGroupJvmResourceMetaData(resourceIdentifier.groupName, resourceName, metaData);
Set<Jvm> jvmSet = groupPersistenceService.getGroup(resourceIdentifier.groupName).getJvms();
for (Jvm jvm : jvmSet) {
jvmPersistenceService.updateResourceMetaData(jvm.getJvmName(), resourceName, metaData);
}
return updatedMetaData;
} else {
return successor.updateResourceMetaData(resourceIdentifier, resourceName, metaData);
}
}
@Override
public Object getSelectedValue(ResourceIdentifier resourceIdentifier) {
if (canHandle(resourceIdentifier)){
return null;
} else {
return successor.getSelectedValue(resourceIdentifier);
}
}
@Override
public List<String> getResourceNames(ResourceIdentifier resourceIdentifier) {
if (canHandle(resourceIdentifier)){
throw new UnsupportedOperationException();
} else {
return successor.getResourceNames(resourceIdentifier);
}
}
}
| 49.543307 | 152 | 0.725048 |
9d495c64782b3bf584f29021d8a55b96abb90980
| 954 |
package practice.backtracking;
import others.MasterPrinter;
import java.util.ArrayList;
import java.util.List;
public class Subsets {
List<List<Integer>> result;
public static void main(String[] args) {
Subsets subsets=new Subsets();
subsets.subsets(new int[]{1,2,3});
}
public List<List<Integer>> subsets(int[] nums) {
result=new ArrayList<>();
int start=0;
subsetHelper(nums,start,new ArrayList<>());
return result;
}
private void subsetHelper(int[] nums, int start, ArrayList<Integer> list) {
//System.out.println("list: ");
MasterPrinter.printList(list);
result.add(new ArrayList<>(list));
if(start==3)
return;
else{
for (int i=start;i<nums.length;i++){
list.add(nums[i]);
subsetHelper(nums,i+1,list);
list.remove(list.size()-1);
}
}
}
}
| 26.5 | 79 | 0.566038 |
f885a929375f493736cf3c1447973e54757221bb
| 371 |
package ru.otus.vsh.hw16.webCore.playersPage;
import ru.otus.vsh.hw16.messagesystem.MessageSystem;
import ru.otus.vsh.hw16.messagesystem.client.CallbackRegistry;
import ru.otus.vsh.hw16.messagesystem.client.MsClient;
public interface PlayersMSClientInitializer {
MsClient playersControllerMSClient(MessageSystem messageSystem, CallbackRegistry callbackRegistry);
}
| 37.1 | 103 | 0.849057 |
9202b03a194a88afa0cac7b5634d70ae4567a761
| 2,137 |
package org.ovirt.engine.core.bll.gluster;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner.Silent;
import org.ovirt.engine.core.common.action.gluster.GlusterVolumeGeoRepSessionParameters;
import org.ovirt.engine.core.common.businessentities.gluster.GeoRepSessionStatus;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterGeoRepSession;
import org.ovirt.engine.core.compat.Guid;
@RunWith(Silent.class)
public class PauseGlusterVolumeGeoRepSessionCommandTest extends GeoRepSessionCommandTest<PauseGlusterVolumeGeoRepSessionCommand> {
@Override
protected PauseGlusterVolumeGeoRepSessionCommand createCommand() {
return new PauseGlusterVolumeGeoRepSessionCommand(new GlusterVolumeGeoRepSessionParameters(), null);
}
protected GlusterGeoRepSession getGeoRepSession(Guid gSessionId, GeoRepSessionStatus status, Guid masterVolumeID) {
GlusterGeoRepSession session = super.getGeoRepSession(gSessionId, status);
session.setMasterVolumeId(startedVolumeId);
return session;
}
@Test
public void validateSucceeds() {
cmd.getParameters().setVolumeId(startedVolumeId);
cmd.setGlusterVolumeId(startedVolumeId);
cmd.getParameters().setGeoRepSessionId(geoRepSessionId);
doReturn(getGeoRepSession(geoRepSessionId, GeoRepSessionStatus.ACTIVE, startedVolumeId)).when(geoRepDao)
.getById(geoRepSessionId);
assertTrue(cmd.validate());
}
@Test
public void validateFails() {
cmd.getParameters().setVolumeId(startedVolumeId);
cmd.setGlusterVolumeId(startedVolumeId);
cmd.getParameters().setGeoRepSessionId(geoRepSessionId);
doReturn(getGeoRepSession(geoRepSessionId, GeoRepSessionStatus.PASSIVE, startedVolumeId)).when(geoRepDao)
.getById(geoRepSessionId);
assertFalse(cmd.validate());
}
@Test
public void validateFailsOnNull() {
assertFalse(cmd.validate());
}
}
| 39.574074 | 130 | 0.770707 |
2a2825aa79dd5edc869aa8fe151584fa42e0fb81
| 3,005 |
package deplacement;
public class p2 extends javax.swing.JFrame {
public p2() {
initComponents();
}
private p2(String text) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
t1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(68, 68, 68)
.addComponent(t1, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(94, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(47, 47, 47))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(44, 44, 44)
.addComponent(t1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(158, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
p1 p=new p1(t1.getText()); //lautre page recoit une chaine de caratere taper par user
this.dispose();
p.setVisible(true);
}//GEN-LAST:event_jButton1ActionPerformed
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new p2().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JTextField t1;
// End of variables declaration//GEN-END:variables
}
| 35.352941 | 135 | 0.635275 |
e26db14193e676a0e097cc835045d59893825cfc
| 892 |
package com.javadevjournal.Java;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class DateDifferenceExample {
public void calculate_difference_between_dates() throws ParseException {
String currentDate= "10/24/2017";
String finalDate= "10/28/2017";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
Date firstDate = simpleDateFormat.parse("06/24/2017");
Date secondDate = simpleDateFormat.parse("06/30/2017");
long difference = Math.abs(firstDate.getTime() - secondDate.getTime());
long differenceDates = difference / (24 * 60 * 60 * 1000);
//Convert long to String
String dayDifference = Long.toString(differenceDates);
System.out.println("Day Differnec is " + dayDifference);
}
}
| 34.307692 | 95 | 0.701794 |
fba48a52694160139b1c6e7369cd3aba743b847b
| 1,041 |
package cn.tycoding.admin.dto;
import cn.tycoding.admin.enums.StatusEnums;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* @author tycoding
* @date 2019-03-09
*/
@Data
@AllArgsConstructor
public class ResponseCode {
private Integer code;
private String msg;
private Object data;
public ResponseCode(StatusEnums enums) {
this.code = enums.getCode();
this.msg = enums.getInfo();
}
public ResponseCode(StatusEnums enums, Object data) {
this.code = enums.getCode();
this.msg = enums.getInfo();
this.data = data;
}
public ResponseCode(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public static ResponseCode success() {
return new ResponseCode(StatusEnums.SUCCESS);
}
public static ResponseCode success(Object data) {
return new ResponseCode(StatusEnums.SUCCESS, data);
}
public static ResponseCode error() {
return new ResponseCode(StatusEnums.SYSTEM_ERROR);
}
}
| 22.148936 | 59 | 0.658021 |
609607501a538a0e833e5ce2849e580578e9258c
| 758 |
package com.simple.bz.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
@Entity
@Table(name="Application")
public class ApplicationModel implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
//名称
private String name;
//说明
private String description;
private Long projectId;
private Long applicationTypeId;
private Long deploymentConfigId;
private String applicationName;
private String path;
private String domainName;
}
| 20.486486 | 55 | 0.75066 |
5826f5239057507602e166c48216cb5c31f02be3
| 1,463 |
package com.liteworm.service.impl;
import com.liteworm.beans.Other;
import com.liteworm.service.SomeService;
import com.liteworm.beans.Student;
/**
* @ClassName SomeServiceImpl
* @Decription @TOTO
* @AUthor LiteWorm
* @Date 2020/4/18 21:29
* @Version 1.0
**/
public class SomeServiceImpl implements SomeService {
@Override
public void doSome(String name, int age, Other other) {
System.out.println("SomeServiceImpl.doSome, name:" + name + ", age:" + age + ", Other:" + other);
}
@Override
public void doSome(String name, int age) {
System.out.println("SomeServiceImpl.doSome, name:" + name + ", age:" + age );
}
@Override
public String doOther() {
System.out.println("SomeServiceImpl.doOther");
return "aaa";
}
@Override
public Student doOther2() {
Student student = new Student();
student.setName("zhangsan");
student.setAge(20);
System.out.println("doOther2:"+ student);
return student;
}
@Override
public String doFirst(String name, int age) {
System.out.println("SomeServiceImpl的业务方法doFirst");
return "doFirst";
}
@Override
public void doSecond(String name, int age) {
System.out.println("SomeServiceImpl的业务方法doSecond");
int i = 10/0;
}
@Override
public void doThird() {
System.out.println("SomeServiceImpl的业务方法doThird");
int i = 10/0;
}
}
| 25.224138 | 105 | 0.628845 |
9835e0e27a1078cc9908fd8f75dd58a04a58bef1
| 581 |
package me.philippheuer.twitch4j.enums;
import lombok.Getter;
/**
* This enums data contains endpoints to Twitch Services
* @author Damian Staszewski
*/
@Getter
public enum Endpoints {
API("https://api.twitch.tv/kraken"), // default version api is v5
PUBSUB("wss://pubsub-edge.twitch.tv:443"),
IRC("wss://irc-ws.chat.twitch.tv:443"),
TMI("http://tmi.twitch.tv"),
OAUTH("https://id.twitch.tv");
private final String URL;
Endpoints(String url) {
this.URL = url;
}
public String buildUrl(String endpoint) {
return String.format("%s/%s", this.URL, endpoint);
}
}
| 21.518519 | 66 | 0.693632 |
bf188fa473a219a1a2ef168d86d90dba054f0b3d
| 7,795 |
package msfgui;
/**
*
* @author scriptjunkie
*/
public class SearchDwldOptionsDialog extends OptionsDialog {
/** Creates new form SearchDwldOptionsDialog */
public SearchDwldOptionsDialog(java.awt.Frame parent, String currentDir) {
super(parent, "Schedule Task Options", true);
initComponents();
dirField.setText(currentDir);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
okButton = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
dirField = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
officeButton = new javax.swing.JRadioButton();
win9xButton = new javax.swing.JRadioButton();
passButton = new javax.swing.JRadioButton();
customButton = new javax.swing.JRadioButton();
customField = new javax.swing.JTextField();
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
closeDialog(evt);
}
});
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(msfgui.MsfguiApp.class).getContext().getResourceMap(SearchDwldOptionsDialog.class);
okButton.setText(resourceMap.getString("okButton.text")); // NOI18N
okButton.setName("okButton"); // NOI18N
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
dirField.setText(resourceMap.getString("dirField.text")); // NOI18N
dirField.setName("dirField"); // NOI18N
jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
jLabel2.setName("jLabel2"); // NOI18N
buttonGroup1.add(officeButton);
officeButton.setSelected(true);
officeButton.setText(resourceMap.getString("officeButton.text")); // NOI18N
officeButton.setName("officeButton"); // NOI18N
buttonGroup1.add(win9xButton);
win9xButton.setText(resourceMap.getString("win9xButton.text")); // NOI18N
win9xButton.setName("win9xButton"); // NOI18N
buttonGroup1.add(passButton);
passButton.setText(resourceMap.getString("passButton.text")); // NOI18N
passButton.setName("passButton"); // NOI18N
buttonGroup1.add(customButton);
customButton.setText(resourceMap.getString("customButton.text")); // NOI18N
customButton.setName("customButton"); // NOI18N
customField.setText(resourceMap.getString("customField.text")); // NOI18N
customField.setName("customField"); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(customButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(customField, javax.swing.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE))
.addComponent(passButton)
.addComponent(win9xButton)
.addComponent(officeButton)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(dirField, javax.swing.GroupLayout.DEFAULT_SIZE, 285, Short.MAX_VALUE))
.addComponent(jLabel2)
.addComponent(okButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(dirField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(officeButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(win9xButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(passButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(customButton)
.addComponent(customField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
.addComponent(okButton)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
StringBuilder cmd = new StringBuilder("search_dwld \""+MsfguiApp.doubleBackslashes(dirField.getText())+"\"");
if(officeButton.isSelected())
cmd.append(" office");
else if(win9xButton.isSelected())
cmd.append(" win9x");
else if(passButton.isSelected())
cmd.append(" passwd");
else if(customButton.isSelected())
cmd.append(" free "+customField.getText());
command = cmd.toString();
doClose();
}//GEN-LAST:event_okButtonActionPerformed
/** Closes the dialog */
private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
doClose();
}//GEN-LAST:event_closeDialog
private void doClose() {
setVisible(false);
dispose();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JRadioButton customButton;
private javax.swing.JTextField customField;
private javax.swing.JTextField dirField;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JRadioButton officeButton;
private javax.swing.JButton okButton;
private javax.swing.JRadioButton passButton;
private javax.swing.JRadioButton win9xButton;
// End of variables declaration//GEN-END:variables
}
| 46.676647 | 191 | 0.670173 |
8de3b18ec5878ae8d90e22bae5a2322afa34c9bc
| 5,234 |
package com.jarvis.cache.serializer.protobuf;
import com.google.protobuf.Message;
import com.jarvis.cache.reflect.lambda.Lambda;
import com.jarvis.cache.reflect.lambda.LambdaFactory;
import com.jarvis.cache.serializer.ISerializer;
import com.jarvis.cache.to.CacheWrapper;
import com.jarvis.lib.util.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.SerializationUtils;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author zhengenshen@gmail.com
*/
@Slf4j
public class ProtoBufSerializer implements ISerializer<CacheWrapper<Object>> {
private ConcurrentHashMap<Class, Lambda> lambdaMap = new ConcurrentHashMap<>();
@Override
public byte[] serialize(CacheWrapper<Object> obj) {
WriteByteBuf byteBuf = new WriteByteBuf();
byteBuf.writeInt(obj.getExpire());
byteBuf.writeLong(obj.getLastLoadTime());
Object cacheObj = obj.getCacheObject();
if (cacheObj != null) {
if (cacheObj instanceof Message) {
byteBuf.writeBytes(((Message) cacheObj).toByteArray());
} else {
SerializationUtils.serialize((Serializable) cacheObj, byteBuf);
}
}
return byteBuf.toByteArray();
}
@Override
public CacheWrapper<Object> deserialize(final byte[] bytes, Type returnType) throws Exception {
if (ArrayUtils.isEmpty(bytes)) {
return null;
}
CacheWrapper<Object> cacheWrapper = new CacheWrapper<>();
val byteBuf = new ReadByteBuf(bytes);
cacheWrapper.setExpire(byteBuf.readInt());
cacheWrapper.setLastLoadTime(byteBuf.readLong());
val body = byteBuf.readableBytes();
if (ArrayUtils.isEmpty(body)) {
return cacheWrapper;
}
String typeName = null;
if (!(returnType instanceof ParameterizedType)) {
typeName = returnType.getTypeName();
}
Class clazz = ClassUtils.getClass(typeName);
if (Message.class.isAssignableFrom(clazz)) {
Lambda lambda = getLambda(clazz);
Object obj = lambda.invoke_for_Object(new ByteArrayInputStream(body));
cacheWrapper.setCacheObject(obj);
} else {
cacheWrapper.setCacheObject(SerializationUtils.deserialize(body));
}
return cacheWrapper;
}
@SuppressWarnings("unchecked")
@Override
public Object deepClone(Object obj, Type type) throws Exception {
if (null == obj) {
return null;
}
Class<?> clazz = obj.getClass();
if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation()
|| clazz.isSynthetic()) {// 常见不会被修改的数据类型
return obj;
}
if (obj instanceof Date) {
return ((Date) obj).clone();
} else if (obj instanceof Calendar) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(((Calendar) obj).getTime().getTime());
return cal;
}
if (obj instanceof CacheWrapper) {
CacheWrapper<Object> wrapper = (CacheWrapper<Object>) obj;
CacheWrapper<Object> res = new CacheWrapper<>();
res.setExpire(wrapper.getExpire());
res.setLastLoadTime(wrapper.getLastLoadTime());
res.setCacheObject(deepClone(wrapper.getCacheObject(), null));
return res;
}
if (obj instanceof Message) {
return ((Message) obj).toBuilder().build();
}
return ObjectUtils.clone(obj);
}
@Override
public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception {
if (null == args || args.length == 0) {
return args;
}
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (args.length != genericParameterTypes.length) {
throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName() + " must " + genericParameterTypes.length);
}
Object[] res = new Object[args.length];
int len = genericParameterTypes.length;
for (int i = 0; i < len; i++) {
res[i] = deepClone(args[i], null);
}
return res;
}
@SuppressWarnings("unchecked")
private Lambda getLambda(Class clazz) throws NoSuchMethodException {
Lambda lambda = lambdaMap.get(clazz);
if (lambda == null) {
Method method = clazz.getDeclaredMethod("parseFrom", InputStream.class);
try {
lambda = LambdaFactory.create(method);
lambdaMap.put(clazz, lambda);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
return lambda;
}
}
| 35.849315 | 156 | 0.631066 |
d19e0adc6ba5cb405ca7a8afef3adb31a2bfbfbb
| 1,979 |
/****************************************************************
* 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.james.blob.objectstorage.crypto;
import com.amazonaws.util.StringUtils;
import com.google.common.base.Preconditions;
import com.google.crypto.tink.subtle.Hex;
public class CryptoConfigBuilder {
private String salt;
private char[] password;
CryptoConfigBuilder() {
}
public CryptoConfigBuilder salt(String salt) {
this.salt = salt;
return this;
}
public CryptoConfigBuilder password(char[] password) {
this.password = password;
return this;
}
public CryptoConfig build() {
Preconditions.checkState(!StringUtils.isNullOrEmpty(salt));
Preconditions.checkState(password != null && password.length > 0);
return new CryptoConfig(Hex.encode(Hex.decode(salt)), password);
}
}
| 40.387755 | 74 | 0.582112 |
caa1d6418059ecd9e1a30fb302891804321982ae
| 206 |
package com.attendance.dto;
public class Join {
private String code;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
| 14.714286 | 38 | 0.597087 |
872392d6fd991966f9578002a38feec0cc725f53
| 2,169 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.easyea.edao;
import com.easyea.edao.exception.EntityException;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.List;
/**
* 定义由持久化Bean生成数据库创建语句的接口
* @author louis
*/
public interface Ddl {
/**
* 获取一个持久化bean所拥有的所有数据表,如果没有分区则只有一张数据表,如果分区表则有多条记录
* @param entity 持久化Bean的Class
* @param con
* @return
* @throws EntityException
* @throws Exception
*/
public List<String> getTables(Class entity, Connection con)
throws EntityException, Exception;
public List<String> getColumns(Class entity, Connection con)
throws EntityException, Exception;
public String getTableName(Class entity) throws EntityException, Exception;
/**
* 根据持久化Bean的属性获取该数据库添加该属性的SQL语句列表
* @param tableName
* @param field 持久化Bean的字段对象
* @return
*/
public List<String> getAddColumnSqls(String tableName, Field field);
/**
* 定义由持久化Bean获取创建对应数据表的SQL语句集合
* @param entity 持久化Bean的class
* @return
* @throws com.easyea.edao.exception.EntityException
*/
public List<String> getEntityCreateDdl(Class entity)
throws EntityException, Exception;
/**
* 根据持久化Bean的class对象以及扩展名来获取创建分区表的sql语句列表
* @param entity 实体化Bean的class对象
* @param extName
* @return
* @throws EntityException
* @throws Exception
*/
public List<String> getEntityPartitionDdl(Class entity, String extName)
throws EntityException, Exception;
/**
* 定义持久化Bean获取更新数据库结构的SQL语句的集合
* @param entity
* @param con
* @return
* @throws com.easyea.edao.exception.EntityException
*/
public List<String> getEntityUpdateDdl(Class entity, Connection con)
throws EntityException, Exception;
public List<String> getViewCreateDdl(Class view)
throws EntityException, Exception;
public List<String> getViewUpdateDdl(Class view, Connection con)
throws EntityException, Exception;
}
| 27.807692 | 79 | 0.666206 |
02336a6a33cba8838b4cfee433dbe2a196a08916
| 2,106 |
package net.simpvp.Misc;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.World.Environment;
import java.util.HashMap;
import java.util.UUID;
/**
* Shortcuts for logblock.
*/
public class AdminShortcuts implements CommandExecutor {
private static HashMap<UUID, String> LAST_X = new HashMap<>();
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
};
String scmd = command.getName();
String cmd = null;
if (scmd.equalsIgnoreCase("dw")) {
cmd = "lb lookup destroyed block diamond_ore since 8d sum players world \"world\"";
} else if (scmd.equalsIgnoreCase("dp")) {
cmd = "lb lookup destroyed block diamond_ore since 8d sum players world \"pvp\"";
} else if (scmd.equalsIgnoreCase("dn")) {
cmd = "lb lookup destroyed block ancient_debris since 8d sum players world \"world_nether\"";
} else if (scmd.equalsIgnoreCase("x")) {
if (player == null) {
sender.sendMessage("You must be a player to use this command.");
return true;
}
UUID uuid = player.getUniqueId();
String block;
String target;
if (args.length == 0) {
target = LAST_X.get(uuid);
if (target == null) {
return x_usage(sender);
}
} else if (args.length == 1) {
target = args[0];
} else {
return x_usage(sender);
}
LAST_X.put(uuid, target);
if (player.getWorld().getEnvironment() == Environment.NETHER) {
block = "ancient_debris";
} else {
block = "diamond_ore";
}
cmd = String.format("lb lookup destroyed block %s player %s time 0 coords", block, target);
} else {
return false;
}
Misc.instance.getServer().dispatchCommand(sender, cmd);
return true;
}
private boolean x_usage(CommandSender sender) {
sender.sendMessage(ChatColor.RED + "Incorrect amount of arguments\n" +
"Proper syntax is /x <player>");
return true;
}
}
| 26 | 96 | 0.681387 |
eb1a905a1e6100a195ff9a29d117b6b5338128aa
| 1,387 |
package io.sphere.sdk.payments.queries;
import io.sphere.sdk.payments.TransactionState;
import io.sphere.sdk.payments.TransactionType;
import io.sphere.sdk.queries.*;
final class TransactionCollectionQueryModelImpl<T> extends QueryModelImpl<T> implements TransactionCollectionQueryModel<T> {
public TransactionCollectionQueryModelImpl(final QueryModel<T> parent, final String pathSegment) {
super(parent, pathSegment);
}
@Override
public MoneyQueryModel<T> amount() {
return moneyModel("amount");
}
@Override
public StringQuerySortingModel<T> interactionId() {
return stringModel("interactionId");
}
@Override
public TimestampSortingModel<T> timestamp() {
return timestampSortingModel("timestamp");
}
@Override
public QueryPredicate<T> isEmpty() {
return isEmptyCollectionQueryPredicate();
}
@Override
public QueryPredicate<T> isNotEmpty() {
return isNotEmptyCollectionQueryPredicate();
}
@Override
public SphereEnumerationQueryModel<T, TransactionType> type() {
return enumerationQueryModel("type");
}
@Override
public StringQuerySortingModel<T> id() {
return stringModel("id");
}
@Override
public SphereEnumerationQueryModel<T, TransactionState> state() {
return enumerationQueryModel("state");
}
}
| 26.673077 | 124 | 0.701514 |
25f229367344f4e31ada582b99cc34eb03b8f303
| 3,722 |
package Webmagic.AutoHome.sigit_country;
/***Created by moyongzhuo
*On 2018/4/28 ***10:26.
******/
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/***Created by mo
*On 2018/4/23 ***10:04.
******/
public class sigit implements PageProcessor {
private static int myid = 0;
int size = 0;
// 抓取网站的相关配置,包括编码、抓取间隔、重试次数等
private Site site = Site.me().setRetryTimes(5).setSleepTime(1000).setTimeOut(100000).setCharset("utf-8")
.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
Calendar now = Calendar.getInstance();
String time = new SimpleDateFormat("HHmm").format(now.getTime());
@Override
public Site getSite() {
return site;
}
@Override
public void process(Page page) {
Html html = page.getHtml();
myid++;
size++;
try {
String url = page.getUrl().get();
int op = 0;
List<String> one_car = new ArrayList<>();
List<Selectable> nodes = html.xpath("//div[@class='main1_right_m']").nodes();
for (Selectable item : nodes) {
Selectable item_2 = item;
String name = item_2.xpath("//div[@class='main1_right_m1']/a/text()").get();
String province = item_2.xpath("//div[@class='main1_right_m2']/text()").get();
String year = item_2.xpath("//div[@class='main1_right_m3']/text()").get();
String all = name+"\t\t"+province+"\t\t"+year;
one_car.add(all);
}
// File file = new File("D:\\workspace\\java\\WebAnimationTest\\src\\main\\java\\Webmagic\\AutoHome\\car_brand_0423.txt");//汽车品牌
// File file = new File("D:\\data\\AutoHome"+ time+".txt");//进口,出口
File file = new File("D:\\workspace\\java\\WebAnimationTest\\src\\main\\java\\Webmagic\\AutoHome\\sigit_country\\sigits_country.txt");//进口,出口
FileUtils.writeLines(file, one_car, true);
} catch (Exception e) {
}
}
// public static void main(String[] args) throws IOException, InterruptedException {
@Test//获取品牌,车系等
public void brand_model(){
try {
long startTime, endTime;
System.out.println("开始爬取...");
startTime = System.currentTimeMillis();
//"https://www.autohome.com.cn/2951/?pvareaid=105126"
//a00/a0/a/b/c/d/suv/mpv/s/p"https://www.autohome.com.cn/3948/#levelsource=000000000_0&pvareaid=101594"
List<String> list = new ArrayList<>();
for(int i = 1; i<18; i++){
String https = "http://www.cnta.gov.cn/was5/web/search?page="+String.valueOf(i)+"&channelid=242887&orderby=-AYEAR&perpage=15&outlinepage=5&searchscope=×cope=×copecolumn=&orderby=-AYEAR&andsen=&total=&orsen=&exclude=&searchword2=&AADDRESS=&AYEAR=";
Spider.create(new sigit()).addUrl(https).thread(5).run();
endTime = System.currentTimeMillis();
System.out.println("爬取耗时:"+"\t"+ (endTime-startTime) +"\t");
Thread.sleep(10000);
}
} catch (Exception e) { }
}
}
| 39.178947 | 274 | 0.59726 |
4c503d3091148737ac360bf20b00db8d37259b04
| 3,564 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.scdn.transform.v20171115;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.scdn.model.v20171115.DescribeScdnDomainIspDataResponse;
import com.aliyuncs.scdn.model.v20171115.DescribeScdnDomainIspDataResponse.ISPProportionData;
import java.util.Map;
import com.aliyuncs.transform.UnmarshallerContext;
public class DescribeScdnDomainIspDataResponseUnmarshaller {
public static DescribeScdnDomainIspDataResponse unmarshall(DescribeScdnDomainIspDataResponse describeScdnDomainIspDataResponse, UnmarshallerContext context) {
describeScdnDomainIspDataResponse.setRequestId(context.stringValue("DescribeScdnDomainIspDataResponse.RequestId"));
describeScdnDomainIspDataResponse.setDomainName(context.stringValue("DescribeScdnDomainIspDataResponse.DomainName"));
describeScdnDomainIspDataResponse.setDataInterval(context.stringValue("DescribeScdnDomainIspDataResponse.DataInterval"));
describeScdnDomainIspDataResponse.setStartTime(context.stringValue("DescribeScdnDomainIspDataResponse.StartTime"));
describeScdnDomainIspDataResponse.setEndTime(context.stringValue("DescribeScdnDomainIspDataResponse.EndTime"));
List<ISPProportionData> value = new ArrayList<ISPProportionData>();
for (int i = 0; i < context.lengthValue("DescribeScdnDomainIspDataResponse.Value.Length"); i++) {
ISPProportionData iSPProportionData = new ISPProportionData();
iSPProportionData.setISP(context.stringValue("DescribeScdnDomainIspDataResponse.Value["+ i +"].ISP"));
iSPProportionData.setProportion(context.stringValue("DescribeScdnDomainIspDataResponse.Value["+ i +"].Proportion"));
iSPProportionData.setIspEname(context.stringValue("DescribeScdnDomainIspDataResponse.Value["+ i +"].IspEname"));
iSPProportionData.setAvgObjectSize(context.stringValue("DescribeScdnDomainIspDataResponse.Value["+ i +"].AvgObjectSize"));
iSPProportionData.setAvgResponseTime(context.stringValue("DescribeScdnDomainIspDataResponse.Value["+ i +"].AvgResponseTime"));
iSPProportionData.setBps(context.stringValue("DescribeScdnDomainIspDataResponse.Value["+ i +"].Bps"));
iSPProportionData.setQps(context.stringValue("DescribeScdnDomainIspDataResponse.Value["+ i +"].Qps"));
iSPProportionData.setAvgResponseRate(context.stringValue("DescribeScdnDomainIspDataResponse.Value["+ i +"].AvgResponseRate"));
iSPProportionData.setReqErrRate(context.stringValue("DescribeScdnDomainIspDataResponse.Value["+ i +"].ReqErrRate"));
iSPProportionData.setTotalBytes(context.stringValue("DescribeScdnDomainIspDataResponse.Value["+ i +"].TotalBytes"));
iSPProportionData.setBytesProportion(context.stringValue("DescribeScdnDomainIspDataResponse.Value["+ i +"].BytesProportion"));
iSPProportionData.setTotalQuery(context.stringValue("DescribeScdnDomainIspDataResponse.Value["+ i +"].TotalQuery"));
value.add(iSPProportionData);
}
describeScdnDomainIspDataResponse.setValue(value);
return describeScdnDomainIspDataResponse;
}
}
| 61.448276 | 159 | 0.810606 |
57c29460cfebc9cef08879c53d5bad41224a9269
| 67 |
package lk.ijse.controller;
public class DashBoardController {
}
| 11.166667 | 34 | 0.791045 |
bd7b66ed2af27f948b1e069442827a47e03676ae
| 777 |
package com.sonic.controller.models.http;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.constraints.NotNull;
/**
* @author ZhouYiXun
* @des
* @date 2021/10/13 18:45
*/
public class ChangePwd {
@NotNull
@ApiModelProperty(value = "旧密码", required = true, example = "123456")
private String oldPwd;
@NotNull
@ApiModelProperty(value = "新密码", required = true, example = "123456")
private String newPwd;
public String getOldPwd() {
return oldPwd;
}
public void setOldPwd(String oldPwd) {
this.oldPwd = oldPwd;
}
public String getNewPwd() {
return newPwd;
}
public void setNewPwd(String newPwd) {
this.newPwd = newPwd;
}
}
| 21 | 74 | 0.617761 |
5e339e769d7281757f2f61ccea3acf11a213abb3
| 418 |
package com.sanardev.instagramapijava.model.direct.messagetype;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class FbUserTags {
@SerializedName("in")
@Expose
private List<Object> in = null;
public List<Object> getIn() {
return in;
}
public void setIn(List<Object> in) {
this.in = in;
}
}
| 18.173913 | 63 | 0.679426 |
c46dfbbe85d95801ffaec4249478e3b732dfd06b
| 344 |
package pl.kkowalewski.recipeapp.exception;
import java.io.IOException;
public class ImageNotSavedException extends IOException {
public ImageNotSavedException() {
}
public ImageNotSavedException(String message) {
super(message);
}
public ImageNotSavedException(Throwable cause) {
super(cause);
}
}
| 19.111111 | 57 | 0.712209 |
e8ac159c63b49c91f82a1b3693a58b93e0e64a7b
| 1,648 |
package com.skycloud.jkb.component;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 对配置属性文件的读取.
*
* @creation 2014年3月31日 下午1:54:18
* @modification 2014年3月31日 下午1:54:18
* @company Skycloud
* @author xiweicheng
* @version 1.0
*
*/
@Component
public class PropUtil {
@Value("#{systemProperties['api.url']}")
private String apiUrl;
@Value("#{systemProperties['jkb.api.url']}")
private String jbkApiUrl;
@Value("#{systemProperties['zabbix.api.login.userid']}")
private String zabbixApiLoginUserId;
@Value("#{systemProperties['zabbix.api.login.password']}")
private String zabbixApiLoginPassword;
@Value("#{systemProperties['default.agent.port']}")
private String defaultAgentPort;
@Value("#{systemProperties['default.windows.server.tpl.id']}")
private String defaultWinServerTplId;
@Value("#{systemProperties['default.linux.server.tpl.id']}")
private String defaultLinuxServerTplId;
@Value("#{systemProperties['default.host.group.id']}")
private String defaultHostGroupId;
public String getApiUrl() {
return apiUrl;
}
public String getJbkApiUrl() {
return jbkApiUrl;
}
public String getZabbixApiLoginUserId() {
return zabbixApiLoginUserId;
}
public String getZabbixApiLoginPassword() {
return zabbixApiLoginPassword;
}
public String getDefaultAgentPort() {
return defaultAgentPort;
}
public String getDefaultWinServerTplId() {
return defaultWinServerTplId;
}
public String getDefaultLinuxServerTplId() {
return defaultLinuxServerTplId;
}
public String getDefaultHostGroupId() {
return defaultHostGroupId;
}
}
| 21.684211 | 63 | 0.752427 |
bf4991444b05fe217e908adb412a242590a8ffee
| 1,299 |
package com.ruoyi.project.house.service;
import com.ruoyi.project.house.domain.NonStreetHouse;
import java.util.List;
/**
* 非沿街住改非房屋业务层
*
* @author ruoyi
*/
public interface INonStreetHouseService
{
/**
* 根据条件分页查询非沿街住改非房屋数据
*
* @param NonStreetHouse 非沿街住改非房屋
* @return 价格数据集合信息
*/
public List<NonStreetHouse> selectNonStreetHouseList(NonStreetHouse NonStreetHouse);
/**
* 通过价格ID查询非沿街住改非房屋
*
* @param NonStreetHouseId 价格ID
* @return 价格对象信息
*/
public List<NonStreetHouse> selectNonStreetHouseById(Long NonStreetHouseId);
/**
* 新增保存非沿街住改非房屋
*
* @param nonStreetHouseList 非沿街住改非房屋
* @return 结果
*/
public int insertNonStreetHouse(List<NonStreetHouse> nonStreetHouseList);
/**
* 修改保存非沿街住改非房屋
*
* @param NonStreetHouse 非沿街住改非房屋
* @return 结果
*/
public int updateNonStreetHouse(List<NonStreetHouse> NonStreetHouse);
/**
* 通过ID删除非沿街住改非房屋
*
* @param NonStreetHouseId 价格ID
* @return 结果
*/
public int deleteNonStreetHouseById(Long NonStreetHouseId);
/**
* 批量删除非沿街住改非房屋
*
* @param NonStreetHouseIds 需要删除的价格ID
* @return 结果
*/
public int deleteNonStreetHouseByIds(Long[] NonStreetHouseIds);
}
| 19.681818 | 88 | 0.648961 |
6bdc34078c697ad4ed476c25d6928d466036e36d
| 9,433 |
/**
* Copyright 5AM Solutions Inc, ESAC, ScenPro & SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/caintegrator/LICENSE.txt for details.
*/
package gov.nih.nci.caintegrator.application.study;
import static gov.nih.nci.caintegrator.TestDataFiles.INVALID_FILE_DOESNT_EXIST;
import static gov.nih.nci.caintegrator.TestDataFiles.INVALID_FILE_EMPTY;
import static gov.nih.nci.caintegrator.TestDataFiles.INVALID_FILE_MISSING_VALUE;
import static gov.nih.nci.caintegrator.TestDataFiles.INVALID_FILE_NO_DATA;
import static gov.nih.nci.caintegrator.TestDataFiles.VALID_FILE;
import static gov.nih.nci.caintegrator.TestDataFiles.VALID_FILE_TIMEPOINT;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import gov.nih.nci.caintegrator.TestDataFiles;
import gov.nih.nci.caintegrator.application.study.AnnotationFieldDescriptor;
import gov.nih.nci.caintegrator.application.study.AnnotationFieldType;
import gov.nih.nci.caintegrator.application.study.AnnotationFile;
import gov.nih.nci.caintegrator.application.study.DelimitedTextClinicalSourceConfiguration;
import gov.nih.nci.caintegrator.application.study.StudyConfiguration;
import gov.nih.nci.caintegrator.application.study.SubjectAnnotationHandler;
import gov.nih.nci.caintegrator.application.study.ValidationException;
import gov.nih.nci.caintegrator.data.CaIntegrator2DaoStub;
import gov.nih.nci.caintegrator.domain.application.EntityTypeEnum;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import org.hamcrest.CoreMatchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
* Tests for annotation files.
*
* @author Abraham J. Evans-EL <aevansel@5amsolutions.com>
*/
public class AnnotationFileTest {
@Rule
public ExpectedException expected = ExpectedException.none();
/**
* Test method for {@link gov.nih.nci.caintegrator.application.study.DelimitedTextannotationFile#validateFile()}.
* @throws ValidationException
* @throws FileNotFoundException
*/
@Test
public void load() throws Exception {
AnnotationFile annotationFile = createAnnotationFile(VALID_FILE);
assertNotNull(annotationFile);
assertEquals(5, annotationFile.getColumns().size());
assertEquals("ID", annotationFile.getColumns().get(0).getName());
assertEquals("Col1", annotationFile.getColumns().get(1).getName());
assertEquals("Col2", annotationFile.getColumns().get(2).getName());
assertEquals("Col3", annotationFile.getColumns().get(3).getName());
}
@Test
public void loadMissingValue() throws Exception {
expected.expect(ValidationException.class);
expected.expectMessage("Number of values in line 3 inconsistent with header line. Expected 4 but found 3 values.");
createAnnotationFile(INVALID_FILE_MISSING_VALUE);
}
@Test
public void loadEmptyFile() throws Exception {
expected.expect(ValidationException.class);
expected.expectMessage("The data file was empty.");
createAnnotationFile(INVALID_FILE_EMPTY);
}
@Test
public void loadNoData() throws Exception {
expected.expect(ValidationException.class);
expected.expectMessage("The data file contained no data (header line only).");
createAnnotationFile(INVALID_FILE_NO_DATA);
}
@Test
public void loadMissingFile() throws Exception {
expected.expect(ValidationException.class);
expected.expectMessage("The file " + INVALID_FILE_DOESNT_EXIST.getAbsolutePath() + " could not be found");
createAnnotationFile(INVALID_FILE_DOESNT_EXIST);
}
@Test
public void getDescriptors() throws Exception {
AnnotationFile annotationFile = createAnnotationFile(VALID_FILE_TIMEPOINT);
annotationFile.setIdentifierColumn(annotationFile.getColumns().get(0));
annotationFile.setTimepointColumn(annotationFile.getColumns().get(1));
List<AnnotationFieldDescriptor> descriptors = annotationFile.getDescriptors();
assertEquals(AnnotationFieldType.IDENTIFIER, descriptors.get(0).getType());
assertEquals(AnnotationFieldType.TIMEPOINT, descriptors.get(1).getType());
assertEquals(AnnotationFieldType.ANNOTATION, descriptors.get(2).getType());
assertEquals("Col2", descriptors.get(3).getName());
assertEquals("Col3", descriptors.get(4).getName());
}
@Test
public void positionAtData() throws Exception {
AnnotationFile annotationFile = createAnnotationFile(VALID_FILE);
annotationFile.setId(Long.valueOf(1));
assertTrue(annotationFile.hasNextDataLine());
assertEquals("100", annotationFile.getDataValue(annotationFile.getColumns().get(0)));
assertTrue(annotationFile.hasNextDataLine());
assertEquals("101", annotationFile.getDataValue(annotationFile.getColumns().get(0)));
assertFalse(annotationFile.hasNextDataLine());
annotationFile.positionAtData();
assertTrue(annotationFile.hasNextDataLine());
assertEquals("100", annotationFile.getDataValue(annotationFile.getColumns().get(0)));
}
@Test
public void dataValue() throws Exception {
AnnotationFile annotationFile = createAnnotationFile(VALID_FILE);
annotationFile.setIdentifierColumn(annotationFile.getColumns().get(0));
annotationFile.positionAtData();
assertTrue(annotationFile.hasNextDataLine());
assertEquals("100", annotationFile.getDataValue(annotationFile.getIdentifierColumn()));
assertEquals("1", annotationFile.getDataValue(annotationFile.getColumns().get(1).getFieldDescriptor()));
assertEquals("g", annotationFile.getDataValue(annotationFile.getColumns().get(2).getFieldDescriptor()));
assertEquals("N", annotationFile.getDataValue(annotationFile.getColumns().get(3).getFieldDescriptor()));
assertEquals("1", annotationFile.getDataValue(annotationFile.getColumns().get(1)));
assertEquals("g", annotationFile.getDataValue(annotationFile.getColumns().get(2)));
assertEquals("N", annotationFile.getDataValue(annotationFile.getColumns().get(3)));
assertTrue(annotationFile.hasNextDataLine());
assertEquals("101", annotationFile.getDataValue(annotationFile.getIdentifierColumn()));
assertEquals("3", annotationFile.getDataValue(annotationFile.getColumns().get(1).getFieldDescriptor()));
assertEquals("g", annotationFile.getDataValue(annotationFile.getColumns().get(2).getFieldDescriptor()));
assertEquals("Y", annotationFile.getDataValue(annotationFile.getColumns().get(3).getFieldDescriptor()));
assertEquals("3", annotationFile.getDataValue(annotationFile.getColumns().get(1)));
assertEquals("g", annotationFile.getDataValue(annotationFile.getColumns().get(2)));
assertEquals("Y", annotationFile.getDataValue(annotationFile.getColumns().get(3)));
assertFalse(annotationFile.hasNextDataLine());
}
@Test
public void checkForValidIdentifierColumn() throws Exception {
AnnotationFile annotationFile = createAnnotationFile(VALID_FILE);
annotationFile.setIdentifierColumn(annotationFile.getColumns().get(0));
annotationFile.getIdentifierColumn().checkValidIdentifierColumn();
}
@Test
public void checkForInvalidIdentifierColumn() throws Exception {
expected.expect(ValidationException.class);
expected.expectMessage("This column cannot be an identifier column because it has a duplicate value");
AnnotationFile annotationFile = createAnnotationFile(VALID_FILE);
annotationFile.setIdentifierColumn(annotationFile.getColumns().get(2));
annotationFile.getIdentifierColumn().checkValidIdentifierColumn();
}
@Test
public void tooLongIdsThrowsValidationException() throws Exception {
expected.expect(ValidationException.class);
expected.expectMessage(CoreMatchers.containsString("Identifiers can only be up to"));
AnnotationFile annotationFile = createAnnotationFile(TestDataFiles.INVALID_FILE_TOO_LONG_IDS);
annotationFile.setIdentifierColumn(annotationFile.getColumns().get(0));
annotationFile.loadAnnontation(new SubjectAnnotationHandler(
new DelimitedTextClinicalSourceConfiguration(annotationFile, new StudyConfiguration())));
}
@Test
public void duplcateIdsThrowsValidationException() throws IOException, ValidationException {
expected.expect(ValidationException.class);
expected.expectMessage(CoreMatchers.containsString("Multiples identifiers found for"));
AnnotationFile annotationFile = createAnnotationFile(TestDataFiles.INVALID_FILE_DUPLICATE_IDS);
annotationFile.setIdentifierColumn(annotationFile.getColumns().get(0));
annotationFile.loadAnnontation(new SubjectAnnotationHandler(
new DelimitedTextClinicalSourceConfiguration(annotationFile, new StudyConfiguration())));
}
private AnnotationFile createAnnotationFile(File file) throws ValidationException, IOException {
return AnnotationFile.load(file, new CaIntegrator2DaoStub(), new StudyConfiguration(), EntityTypeEnum.SUBJECT, true);
}
}
| 49.387435 | 125 | 0.754373 |
266a2d9adeaf796ab93ccb8fba1f0e66425bf54f
| 3,555 |
// Copyright 2017 Archos SA
//
// 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.archos.mediacenter.utils;
import android.animation.Animator.AnimatorListener;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.ViewPropertyAnimator;
import android.widget.RelativeLayout;
public class GlobalResumeView extends RelativeLayout {
private static final String TAG = "GlobalResumeView";
Bitmap mImage;
public GlobalResumeView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onSizeChanged (int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (w != 0 && h != 0 && mImage != null) {
resizeImage(mImage, w, h);
mImage = null;
}
}
public void setImage(Bitmap bm) {
if (bm == null) {
setBackgroundResource(android.R.color.black);
} else {
int dstWidth = getWidth();
int dstHeight = getHeight();
if (dstWidth != 0 && dstHeight != 0) {
resizeImage(bm, dstWidth, dstHeight);
} else {
mImage = bm;
}
}
}
private void resizeImage(Bitmap bm, int dstWidth, int dstHeight) {
int xOffset, yOffset;
int rescaleWidth, rescaleHeight;
int srcWidth = bm.getWidth();
int srcHeight = bm.getHeight();
if (dstWidth >= dstHeight) {
float scaleFactor = (float)dstWidth / (float)srcWidth;
rescaleWidth = (int)(scaleFactor * (float)srcWidth);
rescaleHeight = (int)(scaleFactor * (float)srcHeight);
xOffset = 0;
yOffset = (rescaleHeight - dstHeight) / 2;
yOffset = Math.max(yOffset, 0);
} else {
float scaleFactor = (float)dstHeight / (float)srcHeight;
rescaleWidth = (int)(scaleFactor * (float)srcWidth);
rescaleHeight = (int)(scaleFactor * (float)srcHeight);
xOffset = (rescaleWidth - dstWidth) / 2;
xOffset = Math.max(xOffset, 0);
yOffset = 0;
}
Bitmap sbm = Bitmap.createScaledBitmap(bm, rescaleWidth, rescaleHeight, true);
if (sbm != bm) {
bm.recycle();
}
dstWidth = Math.min(rescaleWidth, dstWidth);
dstHeight = Math.min(rescaleHeight, dstHeight);
Bitmap cbm = Bitmap.createBitmap(sbm, xOffset, yOffset, dstWidth, dstHeight);
if (cbm != sbm) {
sbm.recycle();
}
setBackground(new BitmapDrawable(getResources(), cbm));
}
public void launchOpenAnimation(AnimatorListener listener) {
ViewPropertyAnimator a = animate();
a.scaleX(5f).scaleY(5f).alpha(0f);
a.setDuration(300);
a.setListener(listener);
}
public void resetOpenAnimation() {
setScaleX(1f);
setScaleY(1f);
setAlpha(1f);
}
}
| 33.857143 | 86 | 0.617722 |
bf3e11d124cff2ca6c03823f04c6482e835703f5
| 3,230 |
package com.yunnex.ops.erp.modules.store.basic.entity;
import com.yunnex.ops.erp.modules.store.advertiser.entity.ErpStoreAdvertiserFriends;
import com.yunnex.ops.erp.modules.store.advertiser.entity.ErpStoreAdvertiserWeibo;
import com.yunnex.ops.erp.modules.store.pay.entity.ErpStoreBank;
import com.yunnex.ops.erp.modules.store.pay.entity.ErpStorePayWeixin;
public class ErpStoreInfoParam {
private ErpStoreInfo erpStoreInfo;
private ErpStoreLinkman erpStoreLinkman;
private ErpStoreLegalPerson erpStoreLegalPerson;
private ErpStoreCredentials erpStoreCredentials;
private ErpStoreBank erpStoreBank;
private ErpStoreAdvertiserFriends erpStoreAdvertiserFriends;
private ErpStoreAdvertiserWeibo erpStoreAdvertiserWeibo;
private ErpStorePayWeixin erpStorePayWeixin;
public ErpStoreInfo getErpStoreInfo() {
return erpStoreInfo;
}
public void setErpStoreInfo(ErpStoreInfo erpStoreInfo) {
this.erpStoreInfo = erpStoreInfo;
}
public ErpStoreLinkman getErpStoreLinkman() {
return erpStoreLinkman;
}
public void setErpStoreLinkman(ErpStoreLinkman erpStoreLinkman) {
this.erpStoreLinkman = erpStoreLinkman;
}
public ErpStoreLegalPerson getErpStoreLegalPerson() {
return erpStoreLegalPerson;
}
public void setErpStoreLegalPerson(ErpStoreLegalPerson erpStoreLegalPerson) {
this.erpStoreLegalPerson = erpStoreLegalPerson;
}
public ErpStoreCredentials getErpStoreCredentials() {
return erpStoreCredentials;
}
public void setErpStoreCredentials(ErpStoreCredentials erpStoreCredentials) {
this.erpStoreCredentials = erpStoreCredentials;
}
public ErpStoreBank getErpStoreBank() {
return erpStoreBank;
}
public void setErpStoreBank(ErpStoreBank erpStoreBank) {
this.erpStoreBank = erpStoreBank;
}
public ErpStoreAdvertiserFriends getErpStoreAdvertiserFriends() {
return erpStoreAdvertiserFriends;
}
public void setErpStoreAdvertiserFriends(ErpStoreAdvertiserFriends erpStoreAdvertiserFriends) {
this.erpStoreAdvertiserFriends = erpStoreAdvertiserFriends;
}
public ErpStoreAdvertiserWeibo getErpStoreAdvertiserWeibo() {
return erpStoreAdvertiserWeibo;
}
public void setErpStoreAdvertiserWeibo(ErpStoreAdvertiserWeibo erpStoreAdvertiserWeibo) {
this.erpStoreAdvertiserWeibo = erpStoreAdvertiserWeibo;
}
public ErpStorePayWeixin getErpStorePayWeixin() {
return erpStorePayWeixin;
}
public void setErpStorePayWeixin(ErpStorePayWeixin erpStorePayWeixin) {
this.erpStorePayWeixin = erpStorePayWeixin;
}
@Override
public String toString() {
return "ErpStoreInfoParam [erpStoreInfo=" + erpStoreInfo + ", erpStoreLinkman=" + erpStoreLinkman + ", erpStoreLegalPerson=" + erpStoreLegalPerson + ", erpStoreCredentials=" + erpStoreCredentials + ",erpStoreBank=" + erpStoreBank + ",erpStoreAdvertiserWeibo=" + erpStoreAdvertiserWeibo + ",erpStoreAdvertiserWeibo=" + erpStoreAdvertiserWeibo + ",erpStorePayWeixin=" + erpStorePayWeixin + "]";
}
}
| 36.292135 | 401 | 0.741486 |
133e85259580ebc284aee0491ea8acac5548f53f
| 562 |
package com.spring.ex.inquiry.repository;
import java.util.List;
import javax.inject.Inject;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
import com.spring.ex.inquiry.domain.AnswerVO;
import com.spring.ex.inquiry.domain.InquiryVO;
@Repository
public class InquiryDAOImpl implements InquiryDAO {
@Inject
SqlSession sqlSession;
@Override
public int inquiryWrite(InquiryVO inquiryVO) throws Exception {
return sqlSession.insert("inquiryMapper.inquiryWrite", inquiryVO);
}
}
| 22.48 | 69 | 0.772242 |
4ee75470df311061002aab387bd6ca3309ecbedd
| 1,504 |
package com.iph.directly.domain;
import android.support.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.iph.directly.domain.model.Feedback;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import rx.Observable;
/**
* Created by vanya on 11/5/2016.
*/
public class FeedbackRepositoryImpl implements FeedbackRepository {
private static final String FEEDBACK_TREE = "feedbacks";
private DatabaseReference databaseReference;
private SimpleDateFormat dateFormat;
public FeedbackRepositoryImpl() {
databaseReference = FirebaseDatabase.getInstance().getReference();
dateFormat = new SimpleDateFormat("dd MM yyyy HH:mm:ss", Locale.getDefault());
}
@Override
public Observable<Feedback> putFeedback(String userId, String text) {
return Observable.create(subscriber -> {
Feedback feedback = new Feedback(text);
String date = dateFormat.format(new Date());
databaseReference.child(FEEDBACK_TREE).child(userId).child(date).setValue(feedback).addOnCompleteListener(task -> {
subscriber.onNext(feedback);
subscriber.onCompleted();
}).addOnFailureListener(subscriber::onError);
});
}
}
| 34.181818 | 127 | 0.730718 |
a467d375d5f7aed8190f16923e27a61a5642940a
| 612 |
package com.tomekl007.chapter_1;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import java.util.concurrent.TimeUnit;
/**
* run with java -jar target/benchmarks.jar MyBenchmark -f 1 -wi 3 -i 10
* f - forks
* wi - warmup iterations
* i - iteration
*/
public class MyBenchmark {
@Benchmark @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.MINUTES)
public void testMethod() {
int a = 1;
int b = 2;
int sum = a + b;
}
}
| 22.666667 | 80 | 0.704248 |
61a5ef4ed3b13e6a525eda630a8095be8c2c2a61
| 7,951 |
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.drive;
import edu.wpi.first.math.controller.HolonomicDriveController;
import edu.wpi.first.math.controller.PIDController;
import edu.wpi.first.math.controller.ProfiledPIDController;
import edu.wpi.first.math.controller.SimpleMotorFeedforward;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.geometry.Translation2d;
import edu.wpi.first.math.kinematics.ChassisSpeeds;
import edu.wpi.first.math.kinematics.MecanumDriveKinematics;
import edu.wpi.first.math.kinematics.MecanumDriveWheelSpeeds;
import edu.wpi.first.math.trajectory.Trajectory;
import edu.wpi.first.math.trajectory.TrajectoryConfig;
import edu.wpi.first.math.trajectory.TrapezoidProfile;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
import frc.robot.controller.DriveController;
import frc.robot.drive.commands.TeleopDriveCommand;
import frc.robot.imu.ImuSubsystem;
import frc.robot.misc.exceptions.UnknownTargetRobotException;
import frc.robot.misc.util.LoggingUtil;
import org.littletonrobotics.junction.Logger;
/**
* A high-level interface for the drivetrain.
*
* <p>Allows you to control all the wheels as a group (via {@link Drivebase}) as well as kinematics,
* odometry, and trajectory helpers.
*/
public class DriveSubsystem extends SubsystemBase {
public static final MecanumDriveKinematics KINEMATICS =
// The distances of wheels to the center of the robot is currently the same for all robots
new MecanumDriveKinematics(
new Translation2d(0.285, 0.285),
new Translation2d(0.285, -0.285),
new Translation2d(-0.285, 0.285),
new Translation2d(-0.285, -0.285));
/** The robot's maximum velocity in meters per second. */
public static final double MAX_VELOCITY;
/** The robot's maximum acceleration in meters per second squared. */
public static final double MAX_ACCELERATION;
/**
* The robot's maximum angular velocity in radians per second. Recorded by sitting still and
* spinning as fast as possible.
*/
public static final double MAX_ANGULAR_VELOCITY;
/** The robot's maximum angular acceleration in radians per second squared. */
public static final double MAX_ANGULAR_ACCELERATION;
/**
* The feedforward values from a SysID angular drivetrain characterization. These are different
* than the usual linear drivetrain characterization. Linear kA is determined using your mass,
* angular kA is determined using your mass distribution around the center of rotation.
*/
private static final SimpleMotorFeedforward ROBOT_ANGULAR_FEEDFORWARD;
static {
switch (Constants.getRobot()) {
case TEST_2020_BOT:
ROBOT_ANGULAR_FEEDFORWARD = new SimpleMotorFeedforward(0.12211, 0.18984, 0.010019);
break;
case COMP_BOT:
case SIM_BOT:
// TODO: Use SysID to calculate the angular drivetrain feedforward constants
ROBOT_ANGULAR_FEEDFORWARD = new SimpleMotorFeedforward(0.12211, 0.18984, 0.010019);
break;
default:
throw new UnknownTargetRobotException();
}
final var maxWheelSpeedsForward =
new MecanumDriveWheelSpeeds(
Wheel.MAX_WHEEL_VELOCITY,
Wheel.MAX_WHEEL_VELOCITY,
Wheel.MAX_WHEEL_VELOCITY,
Wheel.MAX_WHEEL_VELOCITY);
final var maxChassisSpeedsForward = KINEMATICS.toChassisSpeeds(maxWheelSpeedsForward);
final var maxWheelSpeedsSpinning =
new MecanumDriveWheelSpeeds(
Wheel.MAX_WHEEL_VELOCITY,
-Wheel.MAX_WHEEL_VELOCITY,
Wheel.MAX_WHEEL_VELOCITY,
-Wheel.MAX_WHEEL_VELOCITY);
final var maxChassisSpeedsSpinning = KINEMATICS.toChassisSpeeds(maxWheelSpeedsSpinning);
MAX_VELOCITY = Math.abs(maxChassisSpeedsForward.vxMetersPerSecond);
MAX_ANGULAR_VELOCITY = Math.abs(maxChassisSpeedsSpinning.omegaRadiansPerSecond);
MAX_ACCELERATION = Wheel.MAX_ACCELERATION;
MAX_ANGULAR_ACCELERATION = Wheel.MAX_VOLTAGE / ROBOT_ANGULAR_FEEDFORWARD.ka;
}
private static final TrapezoidProfile.Constraints MAX_ROTATION =
new TrapezoidProfile.Constraints(MAX_ANGULAR_VELOCITY, MAX_ANGULAR_ACCELERATION);
/** The acceptable amount of error between the robot's current pose and the desired pose. */
private static final Pose2d POSE_TOLERANCE = new Pose2d(0.15, 0.15, Rotation2d.fromDegrees(2));
public final TrajectoryConfig trajectoryConfig;
private final ProfiledPIDController thetaController =
new ProfiledPIDController(1, 0, 0, MAX_ROTATION, Constants.PERIOD_SECONDS);
// Used for following trajectories
public final HolonomicDriveController driveController =
new HolonomicDriveController(
// X controller
new PIDController(1, 0, 0, Constants.PERIOD_SECONDS),
// Y controller
new PIDController(1, 0, 0, Constants.PERIOD_SECONDS),
thetaController);
private final Drivebase drivebase;
private final ImuSubsystem imuSubsystem;
/** Creates a new DriveSubsystem. */
public DriveSubsystem(
DriveController controller,
ImuSubsystem imuSubsystem,
WheelIO frontLeftIO,
WheelIO frontRightIO,
WheelIO rearLeftIO,
WheelIO rearRightIO) {
drivebase = new Drivebase(frontLeftIO, frontRightIO, rearLeftIO, rearRightIO);
this.imuSubsystem = imuSubsystem;
trajectoryConfig =
new TrajectoryConfig(MAX_VELOCITY, MAX_ACCELERATION).setKinematics(KINEMATICS);
setDefaultCommand(new TeleopDriveCommand(this, controller));
driveController.setTolerance(POSE_TOLERANCE);
thetaController.enableContinuousInput(-Math.PI, Math.PI);
}
@Override
public void periodic() {
// This method will be called once per scheduler run
drivebase.periodic();
}
public void driveTeleop(
double sidewaysPercentage,
double forwardPercentage,
double thetaPercentage,
boolean fieldRelative) {
// Convert from CW+ to CCW+
thetaPercentage *= -1;
if (fieldRelative) {
driveTeleop(
sidewaysPercentage, forwardPercentage, thetaPercentage, imuSubsystem.getRotation());
} else {
driveTeleop(sidewaysPercentage, forwardPercentage, thetaPercentage, new Rotation2d());
}
}
private void driveTeleop(
double sidewaysPercentage,
double forwardPercentage,
double thetaPercentage,
Rotation2d robotHeading) {
final var chassisSpeeds =
ChassisSpeeds.fromFieldRelativeSpeeds(
forwardPercentage * MAX_VELOCITY,
-sidewaysPercentage * MAX_VELOCITY,
thetaPercentage * MAX_ANGULAR_VELOCITY,
robotHeading);
setChassisSpeeds(chassisSpeeds);
}
/** Stops all the motors. */
public void stopMotors() {
drivebase.stopMotors();
}
public void setChassisSpeeds(ChassisSpeeds chassisSpeeds) {
final var wheelSpeeds = KINEMATICS.toWheelSpeeds(chassisSpeeds);
drivebase.setWheelSpeeds(wheelSpeeds);
}
public ChassisSpeeds getChassisSpeeds() {
return KINEMATICS.toChassisSpeeds(drivebase.getWheelSpeeds());
}
public MecanumDriveWheelSpeeds getWheelSpeeds() {
return drivebase.getWheelSpeeds();
}
/**
* Used for showing a ghost robot of the expected position while following a trajectory. For
* comparing with the actual position.
*/
public void logTrajectoryPose(Trajectory.State state) {
logTrajectoryPose(state.poseMeters);
}
/**
* Used for showing a ghost robot of the expected position while following a trajectory. For
* comparing with the actual position.
*/
public void logTrajectoryPose(Pose2d pose) {
Logger.getInstance().recordOutput("Drive/TrajectoryPose", LoggingUtil.poseToArray(pose));
}
}
| 36.981395 | 100 | 0.741542 |
3d3011b943911ff145c3efcf68be7bf3fe94fa0e
| 439 |
package uk.gov.hmcts.reform.prl.models.dto.ccd;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Data;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@Builder
public class CaseDetails {
@JsonProperty("id")
private String caseId;
private String state;
@JsonProperty("case_data")
private CaseData caseData;
}
| 20.904762 | 61 | 0.774487 |
5d12c121005cd346d7c08c82e716f07ca7e2a326
| 1,836 |
package com.pokepoint.service;
import com.pokepoint.domain.TypePokemon;
import com.pokepoint.exception.DataIntegrityException;
import com.pokepoint.exception.ObjectNotFoundException;
import com.pokepoint.repository.TypePokemonRepository;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Sort.Direction;
import java.util.List;
import java.util.Optional;
@Service
public class TypePokemonService {
@Autowired
private TypePokemonRepository repo;
public TypePokemon find(String param) {
Optional<TypePokemon> obj;
try {
obj = repo.findById(Integer.parseInt(param));
} catch (Exception e) {
obj = repo.findByEnglishName(param);
}
return obj.orElseThrow(() -> new ObjectNotFoundException("Tipo de Pokemon não encontrada"));
}
public List<TypePokemon> findAll() {
return repo.findAll();
}
public Page<TypePokemon> findPage(Integer page, Integer linesPerPage, String orderBy, String direction) {
PageRequest pageRequest = PageRequest.of(page, linesPerPage, Direction.valueOf(direction), orderBy);
return repo.findAll(pageRequest);
}
public TypePokemon insert(TypePokemon type) {
type.setId(null);
return repo.save(type);
}
public void delete(Integer id) {
try {
repo.deleteById(id);
} catch (DataIntegrityViolationException e) {
throw new DataIntegrityException("Não é possivel deletar o tipo de Pokemon");
}
}
}
| 32.785714 | 109 | 0.723856 |
ee997c246850782522900cd0d362c5638a6f003a
| 1,328 |
package com.wpx.exception;
/**
* @author 不会飞的小鹏
* GitHub登录模块错误信息
*/
public enum GitHubLoginExceptionMessage implements IExceptionMessage {
/**
* GitHub登录AccessToken获取异常
*/
GITHUB_ACCESS_TOKEN_REQUEST_ERROR(5001, GitHubLoginErrorCodes.GITHUB_ACCESS_TOKEN_REQUEST_ERROR, GitHubLoginMessageCodes.GITHUB_ACCESS_TOKEN_REQUEST_ERROR),
/**
* GitHub登录获取用户信息异常
*/
GITHUB_USER_REQUEST_ERROR(5002, GitHubLoginErrorCodes.GITHUB_USER_REQUEST_ERROR, GitHubLoginMessageCodes.GITHUB_USER_REQUEST_ERROR),
;
/**
* 状态码
*/
private Integer code;
/**
* 错误码
*/
private String error;
/**
* 异常信息
*/
private String message;
/**
* 获取异常状态码
*/
@Override
public Integer getCode() {
return this.code;
}
@Override
public String getError() {
return null;
}
/**
* 获取异常信息
*/
@Override
public String getMessage() {
return this.message;
}
public void setCode(Integer code) {
this.code = code;
}
public void setMessage(String message) {
this.message = message;
}
GitHubLoginExceptionMessage(Integer code, String error, String message) {
this.code = code;
this.error = error;
this.message = message;
}
}
| 18.444444 | 160 | 0.620482 |
6ca648c5c9b3d56067dd1245fd22e31190560948
| 2,929 |
/*
* Copyright (c) 2021, the hapjs-platform Project Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package org.hapjs.common.utils;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.hapjs.bridge.HybridView;
public class SnapshotUtils {
private static final String TAG = "SnapshotUtils";
public static Bitmap createSnapshot(View host, Canvas canvas, int bgColor) {
if (host == null || canvas == null || host.getWidth() <= 0 || host.getHeight() <= 0) {
return null;
}
int w = host.getWidth();
int h = host.getHeight();
Bitmap bitmap = null;
try {
bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError e) {
Log.e(TAG, "create bitmap error: " + e.getMessage());
return null;
}
bitmap.eraseColor(bgColor);
canvas.setBitmap(bitmap);
canvas.translate(-host.getScrollX(), -host.getScrollY());
host.draw(canvas);
canvas.setBitmap(null);
return bitmap;
}
public static Uri saveSnapshot(
HybridView hybridView, Bitmap snapshot, int ref, String fileType, double quality) {
if (hybridView == null || snapshot == null) {
return null;
}
FileOutputStream fos = null;
File snapshotFile = createSnapshotFile(hybridView, ref, fileType);
Bitmap.CompressFormat format =
TextUtils.equals("jpg", fileType.toLowerCase())
? Bitmap.CompressFormat.JPEG
: Bitmap.CompressFormat.PNG;
int transformedQuality = 100;
if (quality > 0 && Double.compare(quality, 1.0) < 0) {
transformedQuality = (int) (quality * 100);
}
try {
fos = new FileOutputStream(snapshotFile);
snapshot.compress(format, transformedQuality, fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return Uri.fromFile(snapshotFile);
}
private static File createSnapshotFile(HybridView hybridView, int ref, String fileType) {
File dir = hybridView.getHybridManager().getApplicationContext().getCacheDir();
String realFileType = TextUtils.equals("jpg", fileType.toLowerCase()) ? "jpg" : "png";
String fileName = ref + "-" + System.currentTimeMillis() + "." + realFileType;
return new File(dir, fileName);
}
}
| 34.05814 | 95 | 0.598156 |
c9f313a5759c437d9b698da597efe6a168146df6
| 754 |
package com.example.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
@Data
@Entity
@Table(name="city")
public class City implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String county;
@Column(nullable = false)
private String stateCode;
@Column(nullable = false)
private String postalCode;
@Column
private String latitude;
@Column
private String longitude;
}
| 18.390244 | 52 | 0.725464 |
90bacbacf96c6ea60a0b5562705a60957a61d312
| 3,025 |
/*
* 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.geode.redis.internal;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.util.concurrent.EventExecutor;
import org.junit.Test;
import org.mockito.Mockito;
import org.apache.geode.cache.Cache;
import org.apache.geode.redis.GeodeRedisServer;
/**
* Test cases for ExecutionHandlerContext
*/
public class ExecutionHandlerContextJUnitTest {
/**
*
* @throws Exception the exception
*/
@Test
public void testChannelReadChannelHandlerContextObject() throws Exception {
Cache cache = Mockito.mock(Cache.class);
Channel ch = Mockito.mock(Channel.class);
ChannelPipeline channelPipeline = Mockito.mock(ChannelPipeline.class);
EventExecutor eventExecutor = Mockito.mock(EventExecutor.class);
ChannelHandlerContext channelHandlerContext = Mockito.mock(ChannelHandlerContext.class);
@SuppressWarnings("deprecation")
org.apache.geode.LogWriter logWriter = Mockito.mock(org.apache.geode.LogWriter.class);
Command msg = Mockito.mock(Command.class);
RegionProvider regionProvider = Mockito.mock(RegionProvider.class);
GeodeRedisServer server = Mockito.mock(GeodeRedisServer.class);
RedisCommandType redisCommandType = Mockito.mock(RedisCommandType.class);
KeyRegistrar keyRegistrar = Mockito.mock(KeyRegistrar.class);
PubSub pubSub = Mockito.mock(PubSub.class);
RedisLockService lockService = Mockito.mock(RedisLockService.class);
Mockito.when(cache.getLogger()).thenReturn(logWriter);
Mockito.when(ch.pipeline()).thenReturn(channelPipeline);
Mockito.when(channelPipeline.lastContext()).thenReturn(channelHandlerContext);
Mockito.when(channelHandlerContext.executor()).thenReturn(eventExecutor);
byte[] pwd = null;
ExecutionHandlerContext handler =
new ExecutionHandlerContext(ch, cache, regionProvider, server, pwd, keyRegistrar, pubSub,
lockService);
Mockito.when(msg.getCommandType()).thenReturn(redisCommandType);
Executor exec = Mockito.mock(Executor.class);
Mockito.when(redisCommandType.getExecutor()).thenReturn(exec);
ChannelHandlerContext ctx = null;
handler.channelRead(ctx, msg);
}
}
| 40.878378 | 100 | 0.767934 |
dbf9d1447287f1cd40001b1cec15b018c73373a0
| 422 |
package com.auth0.microblog.identity;
import javax.security.enterprise.CallerPrincipal;
public class Auth0Principal extends CallerPrincipal {
private String id;
private String picture;
Auth0Principal(String id, String name, String picture) {
super(name);
this.id = id;
this.picture = picture;
}
public String getId() {
return id;
}
public String getPicture() {
return picture;
}
}
| 18.347826 | 58 | 0.706161 |
4bf5d582cff62ee496300c422332ec6f9cd93150
| 1,043 |
/*
9:24 pm 07/05/2021
John Russ Alejandro
*/
import java.util.Scanner;
public class Alejandro_SFT {
public static void main(String[] args) {
Scanner txtmsgs_input = new Scanner(System.in);
System.out.println("SFT! How many text messages? : ");
int txtmsgs_number = txtmsgs_input.nextInt();
//If messages is 0 to 200 print no charge/free
if(txtmsgs_number>=0 && txtmsgs_number<201)
{
System.out.println("The first 200 messages are free, hence no charge incurred.");
}
//If messages is greater than 0, compute then print
else if(txtmsgs_number>200)
{
System.out.println("Charge incurred for " + txtmsgs_number + " messages is " + (txtmsgs_number*0.5) + " Pesos");
}
//Else Invalid - restart program
else
{
System.out.println("Invalid Input. \nPlease try again. \nThe program is restarting in 5 seconds.");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
main(args);
}
}
}
| 27.447368 | 116 | 0.662512 |
1dc5bee5a0ec0f3548bebd989d27aab1c561cbc5
| 1,187 |
package ru.otus.spring.quiz.shell;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import ru.otus.spring.quiz.service.QuizService;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class QuizCommandsTest {
private QuizCommands quizCommands;
private QuizService quizService;
@Before
public void setUp() throws Exception {
quizService = mock(QuizService.class);
quizCommands = new QuizCommands(quizService);
}
@Test
public void start() {
quizCommands.start();
verify(quizService, times(1)).startQuiz();
}
@Test
public void begin() {
String studentName = "TEST_STUDENT_NAME";
quizCommands.begin(studentName);
verify(quizService, times(1)).startQuiz(studentName);
}
}
| 28.95122 | 62 | 0.738837 |
eebf93a3cf1b56b3b79a1933d4d6b79333a77468
| 3,145 |
/* L2jFrozen Project - www.l2jfrozen.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, 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.
*
* http://www.gnu.org/copyleft/gpl.html
*/
package com.l2jfrozen.gameserver.managers;
import org.apache.log4j.Logger;
import com.l2jfrozen.gameserver.model.zone.type.L2FishingZone;
import com.l2jfrozen.gameserver.model.zone.type.L2WaterZone;
import javolution.util.FastList;
public class FishingZoneManager
{
// =========================================================
private static FishingZoneManager _instance;
private static final Logger LOGGER = Logger.getLogger(FishingZoneManager.class);
public static final FishingZoneManager getInstance()
{
if (_instance == null)
{
LOGGER.info("Initializing FishingZoneManager");
_instance = new FishingZoneManager();
}
return _instance;
}
// =========================================================
// =========================================================
// Data Field
private FastList<L2FishingZone> _fishingZones;
private FastList<L2WaterZone> _waterZones;
// =========================================================
// Constructor
public FishingZoneManager()
{
}
// =========================================================
// Property - Public
public void addFishingZone(final L2FishingZone fishingZone)
{
if (_fishingZones == null)
{
_fishingZones = new FastList<>();
}
_fishingZones.add(fishingZone);
}
public void addWaterZone(final L2WaterZone waterZone)
{
if (_waterZones == null)
{
_waterZones = new FastList<>();
}
_waterZones.add(waterZone);
}
/*
* isInsideFishingZone() - This function was modified to check the coordinates without caring for Z. This allows for the player to fish off bridges, into the water, or from other similar high places. One should be able to cast the line from up into the water, not only fishing whith one's feet
* wet. :) TODO: Consider in the future, limiting the maximum height one can be above water, if we start getting "orbital fishing" players... xD
*/
public final L2FishingZone isInsideFishingZone(final int x, final int y, final int z)
{
for (final L2FishingZone temp : _fishingZones)
if (temp.isInsideZone(x, y, temp.getWaterZ() - 10))
return temp;
return null;
}
public final L2WaterZone isInsideWaterZone(final int x, final int y, final int z)
{
for (final L2WaterZone temp : _waterZones)
if (temp.isInsideZone(x, y, temp.getWaterZ()))
return temp;
return null;
}
}
| 31.138614 | 294 | 0.663593 |
d24813b2a0b7ed9e3afbdda5dbcac442b331d340
| 7,573 |
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|console
operator|.
name|command
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|ArrayList
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Arrays
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Collection
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Assert
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|runner
operator|.
name|RunWith
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|runners
operator|.
name|Parameterized
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|runners
operator|.
name|Parameterized
operator|.
name|Parameters
import|;
end_import
begin_class
annotation|@
name|RunWith
argument_list|(
name|Parameterized
operator|.
name|class
argument_list|)
specifier|public
class|class
name|PurgeCommandTest
block|{
specifier|private
specifier|final
name|List
argument_list|<
name|String
argument_list|>
name|datum
decl_stmt|;
specifier|private
specifier|final
name|String
name|expected
decl_stmt|;
comment|/** * Produces the data for the test. * * @return */
annotation|@
name|Parameters
argument_list|(
name|name
operator|=
literal|"{index}: convertToSQL92({0})={1}"
argument_list|)
specifier|public
specifier|static
name|Collection
argument_list|<
name|Object
index|[]
argument_list|>
name|produceTestData
parameter_list|()
block|{
name|List
argument_list|<
name|Object
index|[]
argument_list|>
name|params
init|=
operator|new
name|ArrayList
argument_list|<>
argument_list|()
decl_stmt|;
comment|// wildcard query enclosed by single quotes must be converted into
comment|// SQL92 LIKE-statement
name|params
operator|.
name|add
argument_list|(
name|toParameterArray
argument_list|(
literal|"(JMSMessageId LIKE '%:10_')"
argument_list|,
literal|"JMSMessageId='*:10?'"
argument_list|)
argument_list|)
expr_stmt|;
comment|// query parameter containing wildcard characters but not enclosed by
comment|// single quotes must be taken as literal
name|params
operator|.
name|add
argument_list|(
name|toParameterArray
argument_list|(
literal|"(JMSMessageId=*:10?)"
argument_list|,
literal|"JMSMessageId=*:10?"
argument_list|)
argument_list|)
expr_stmt|;
name|params
operator|.
name|add
argument_list|(
name|toParameterArray
argument_list|(
literal|"(JMSMessageId=%:10_)"
argument_list|,
literal|"JMSMessageId=%:10_"
argument_list|)
argument_list|)
expr_stmt|;
comment|// query parameter not enclosed by single quotes must be taken as literal
name|params
operator|.
name|add
argument_list|(
name|toParameterArray
argument_list|(
literal|"(JMSMessageId=SOME_ID)"
argument_list|,
literal|"JMSMessageId=SOME_ID"
argument_list|)
argument_list|)
expr_stmt|;
comment|// query parameter not containing wildcard characters but enclosed by
comment|// single quotes must not be converted into a SQL92 LIKE-statement
name|params
operator|.
name|add
argument_list|(
name|toParameterArray
argument_list|(
literal|"(JMSMessageId='SOME_ID')"
argument_list|,
literal|"JMSMessageId='SOME_ID'"
argument_list|)
argument_list|)
expr_stmt|;
name|params
operator|.
name|add
argument_list|(
name|toParameterArray
argument_list|(
literal|"(JMSMessageId='%:10_')"
argument_list|,
literal|"JMSMessageId='%:10_'"
argument_list|)
argument_list|)
expr_stmt|;
comment|// multiple query parameter must be concatenated by 'AND'
name|params
operator|.
name|add
argument_list|(
name|toParameterArray
argument_list|(
literal|"(JMSMessageId LIKE '%:10_') AND (JMSPriority>5)"
argument_list|,
literal|"JMSMessageId='*:10?'"
argument_list|,
literal|"JMSPriority>5"
argument_list|)
argument_list|)
expr_stmt|;
name|params
operator|.
name|add
argument_list|(
name|toParameterArray
argument_list|(
literal|"(JMSPriority>5) AND (JMSMessageId LIKE '%:10_')"
argument_list|,
literal|"JMSPriority>5"
argument_list|,
literal|"JMSMessageId='*:10?'"
argument_list|)
argument_list|)
expr_stmt|;
comment|// a query which is already in SQL92 syntax should not be altered
name|params
operator|.
name|add
argument_list|(
name|toParameterArray
argument_list|(
literal|"((JMSPriority>5) AND (JMSMessageId LIKE '%:10_'))"
argument_list|,
literal|"(JMSPriority>5) AND (JMSMessageId LIKE '%:10_')"
argument_list|)
argument_list|)
expr_stmt|;
return|return
name|params
return|;
block|}
comment|/** * Test if the wildcard queries correctly converted into a valid SQL92 * statement. */
annotation|@
name|Test
specifier|public
name|void
name|testConvertToSQL92
parameter_list|()
block|{
name|System
operator|.
name|out
operator|.
name|print
argument_list|(
literal|"testTokens = "
operator|+
name|datum
argument_list|)
expr_stmt|;
name|System
operator|.
name|out
operator|.
name|println
argument_list|(
literal|" output = "
operator|+
name|expected
argument_list|)
expr_stmt|;
name|PurgeCommand
name|pc
init|=
operator|new
name|PurgeCommand
argument_list|()
decl_stmt|;
name|Assert
operator|.
name|assertEquals
argument_list|(
name|expected
argument_list|,
name|pc
operator|.
name|convertToSQL92
argument_list|(
name|datum
argument_list|)
argument_list|)
expr_stmt|;
block|}
comment|/** * Convert the passed parameter into an object array which is used for * the unit tests of method<code>convertToSQL92</code>. * * @param datum the tokens which are passed as list to the method * @param expected the expected value returned by the method * @return object array with the values used for the unit test */
specifier|static
name|Object
index|[]
name|toParameterArray
parameter_list|(
name|String
name|expected
parameter_list|,
name|String
modifier|...
name|tokens
parameter_list|)
block|{
return|return
operator|new
name|Object
index|[]
block|{
name|Arrays
operator|.
name|asList
argument_list|(
name|tokens
argument_list|)
block|,
name|expected
block|}
return|;
block|}
specifier|public
name|PurgeCommandTest
parameter_list|(
name|List
argument_list|<
name|String
argument_list|>
name|datum
parameter_list|,
name|String
name|expected
parameter_list|)
block|{
name|this
operator|.
name|datum
operator|=
name|datum
expr_stmt|;
name|this
operator|.
name|expected
operator|=
name|expected
expr_stmt|;
block|}
block|}
end_class
end_unit
| 18.425791 | 804 | 0.781196 |
03173d7a7f1dd38b47f107ea8d3db330df27721f
| 372 |
package com.yimuziy.mall.product.dao;
import com.yimuziy.mall.product.entity.SkuImagesEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* sku图片
*
* @author yimuziy
* @email yimuziy@gmail.com
* @date 2020-11-26 17:13:16
*/
@Mapper
public interface SkuImagesDao extends BaseMapper<SkuImagesEntity> {
}
| 20.666667 | 67 | 0.768817 |
dbee6194e0188ab01dc8b079dc609668b88a575a
| 992 |
package aceim.app.view.page.contactlist;
import java.util.List;
import aceim.app.MainActivity;
import aceim.app.dataentity.ProtocolResources;
import aceim.app.themeable.dataentity.ContactListItemThemeResource;
import aceim.app.view.page.contactlist.ContactListUpdater.ContactListModelGroup;
import android.view.View;
import android.view.ViewGroup;
public class DoubleListAdapter extends ContactListAdapter {
public DoubleListAdapter(List<ContactListModelGroup> groups, ProtocolResources resources) {
super(groups, resources);
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final MainActivity activity = (MainActivity) parent.getContext();
ContactListItemThemeResource ctr = activity.getThemesManager().getViewResources().getListItemLayout();
return constructChildViewFromThemeResource(groupPosition, childPosition, isLastChild, convertView, parent, ctr);
}
}
| 38.153846 | 123 | 0.80746 |
9512de8179c9e9be0c62dddc1c6e425b70e73dc1
| 331 |
package com.sia.main.web;
import com.sia.main.domain.Modul;
import com.sia.main.plugin.modul.Accessable;
public class AdministratorModule extends Modul implements Accessable {
private String url;
@Override
public void setUrl(String url) {
this.url = url;
}
@Override
public String getUrl() {
return this.url;
}
}
| 15.761905 | 70 | 0.73716 |
992fc5822d10989effc5650a3c20a4d39bbc0c05
| 3,527 |
package info.iconmaster.minethecrafting.screens;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.systems.RenderSystem;
import info.iconmaster.minethecrafting.MineTheCrafting;
import info.iconmaster.minethecrafting.containers.ContainerArtificersTable;
import info.iconmaster.minethecrafting.tes.TileEntityArtificersTable;
import net.minecraft.client.gui.screen.inventory.ContainerScreen;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
@OnlyIn(Dist.CLIENT)
public class ScreenArtificersTable extends ContainerScreen<ContainerArtificersTable> {
public static final int PROGRESS_TOP_X = 78, PROGRESS_TOP_Y = 43, PROGRESS_BOTTOM_X = 76,
PROGRESS_BOTTOM_Y = 84, PROGRESS_W = 17, PROGRESS_H = 19;
public static final ResourceLocation BACKGROUND = new ResourceLocation(MineTheCrafting.MOD_ID,
"textures/screen/artificing_table_bg.png"),
PROGRESS_TOP = new ResourceLocation(MineTheCrafting.MOD_ID,
"textures/screen/artificing_table_progress_bar_upper.png"),
PROGRESS_BOTTOM = new ResourceLocation(MineTheCrafting.MOD_ID,
"textures/screen/artificing_table_progress_bar_lower.png");
public ScreenArtificersTable(ContainerArtificersTable container, PlayerInventory inventory,
ITextComponent title) {
super(container, inventory, title);
titleY -= ContainerArtificersTable.HEIGHT_OFFSET;
playerInventoryTitleY = 144 - ContainerArtificersTable.HEIGHT_OFFSET;
}
@Override
protected void drawGuiContainerBackgroundLayer(MatrixStack ms, float ticks, int mouseX, int mouseY) {
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
int originX = width / 2 - ContainerArtificersTable.GUI_WIDTH / 2,
originY = height / 2 - ContainerArtificersTable.GUI_HEIGHT / 2;
getMinecraft().getTextureManager().bindTexture(BACKGROUND);
blit(ms, originX, originY, 0, 0, ContainerArtificersTable.GUI_WIDTH,
ContainerArtificersTable.GUI_HEIGHT, 256, 256);
float percentProgress = (((float) container.teData.progress) / TileEntityArtificersTable.MAX_PROGRESS);
int barHeight = (int) (PROGRESS_H * percentProgress);
getMinecraft().getTextureManager().bindTexture(PROGRESS_TOP);
blit(ms, originX + PROGRESS_TOP_X, originY + PROGRESS_TOP_Y, 0, 0, PROGRESS_W, barHeight, PROGRESS_W,
PROGRESS_H);
getMinecraft().getTextureManager().bindTexture(PROGRESS_BOTTOM);
blit(ms, originX + PROGRESS_BOTTOM_X, originY + PROGRESS_BOTTOM_Y + (PROGRESS_H - barHeight), 0,
PROGRESS_H - barHeight, PROGRESS_W, barHeight, PROGRESS_W, PROGRESS_H);
}
@Override
public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
this.renderBackground(matrixStack);
super.render(matrixStack, mouseX, mouseY, partialTicks);
this.renderHoveredTooltip(matrixStack, mouseX, mouseY);
}
}
| 54.261538 | 119 | 0.670825 |
e3ffb0f0326e1fda8acc9199888b9ad5b9daefc1
| 374 |
package io.iron.ironmq.keystone;
public class KeystoneGetTokenResponse {
Access access;
public KeystoneGetTokenResponse() {
}
public KeystoneGetTokenResponse(Access access) {
this.access = access;
}
public Access getAccess() {
return access;
}
public void setAccess(Access access) {
this.access = access;
}
}
| 17.809524 | 52 | 0.647059 |
d9c10d79b1d221e04be2a876f6dce4541c9ae6ff
| 2,198 |
/*
* Copyright 2011 <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*
* 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.ocpsoft.rewrite.servlet.config;
import javax.servlet.ServletContext;
import org.ocpsoft.rewrite.config.ConfigurationBuilder;
import org.ocpsoft.rewrite.config.Configuration;
import org.ocpsoft.rewrite.config.Direction;
import org.ocpsoft.rewrite.context.EvaluationContext;
import org.ocpsoft.rewrite.servlet.http.event.HttpServletRewrite;
/**
* @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*
*/
public class HttpRequestParameterTestProvider extends HttpConfigurationProvider
{
@Override
public int priority()
{
return 0;
}
@Override
public Configuration getConfiguration(final ServletContext context)
{
Configuration config = ConfigurationBuilder.begin()
.addRule()
.when(Direction.isInbound().and(Path.matches("/param")).and(new HttpCondition() {
@Override
public boolean evaluateHttp(HttpServletRewrite event, EvaluationContext context)
{
try {
String value = event.getRequest().getParameter("foo");
if (value == null || value.isEmpty())
{
return true;
}
return false;
}
catch (Exception e) {
return false;
}
}
}))
.perform(SendStatus.code(201));
return config;
}
}
| 33.30303 | 98 | 0.615105 |
2a6ee35ec1833daa25140eb2ca6630cbd7266595
| 2,876 |
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security.tls;
import com.yahoo.security.KeyAlgorithm;
import com.yahoo.security.KeyStoreBuilder;
import com.yahoo.security.KeyStoreType;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.SignatureAlgorithm;
import com.yahoo.security.X509CertificateBuilder;
import org.junit.Test;
import javax.security.auth.x500.X500Principal;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.Principal;
import java.security.cert.X509Certificate;
import java.time.Instant;
import static java.time.temporal.ChronoUnit.DAYS;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author bjorncs
*/
public class MutableX509KeyManagerTest {
private static final X500Principal SUBJECT = new X500Principal("CN=dummy");
@Test
public void key_manager_can_be_updated_with_new_certificate() {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC);
BigInteger serialNumberInitialCertificate = BigInteger.ONE;
KeyStore initialKeystore = generateKeystore(keyPair, serialNumberInitialCertificate);
MutableX509KeyManager keyManager = new MutableX509KeyManager(initialKeystore, new char[0]);
String[] initialAliases = keyManager.getClientAliases(keyPair.getPublic().getAlgorithm(), new Principal[]{SUBJECT});
assertThat(initialAliases).hasSize(1);
X509Certificate[] certChain = keyManager.getCertificateChain(initialAliases[0]);
assertThat(certChain).hasSize(1);
assertThat(certChain[0].getSerialNumber()).isEqualTo(serialNumberInitialCertificate);
BigInteger serialNumberUpdatedCertificate = BigInteger.TEN;
KeyStore updatedKeystore = generateKeystore(keyPair, serialNumberUpdatedCertificate);
keyManager.updateKeystore(updatedKeystore, new char[0]);
String[] updatedAliases = keyManager.getClientAliases(keyPair.getPublic().getAlgorithm(), new Principal[]{SUBJECT});
assertThat(updatedAliases).hasSize(1);
X509Certificate[] updatedCertChain = keyManager.getCertificateChain(updatedAliases[0]);
assertThat(updatedCertChain).hasSize(1);
assertThat(updatedCertChain[0].getSerialNumber()).isEqualTo(serialNumberUpdatedCertificate);
}
private static KeyStore generateKeystore(KeyPair keyPair, BigInteger serialNumber) {
X509Certificate certificate = X509CertificateBuilder.fromKeypair(
keyPair, SUBJECT, Instant.EPOCH, Instant.EPOCH.plus(1, DAYS), SignatureAlgorithm.SHA256_WITH_ECDSA, serialNumber)
.build();
return KeyStoreBuilder.withType(KeyStoreType.PKCS12)
.withKeyEntry("default", keyPair.getPrivate(), certificate)
.build();
}
}
| 44.246154 | 129 | 0.759736 |
120246bd7de945cacc5db76b9235fd6dd85187cc
| 4,390 |
package codecup2018;
import codecup2018.evaluator.CountingEvaluator;
import codecup2018.data.BitBoard;
import codecup2018.data.Board;
import codecup2018.evaluator.MedianFree;
import codecup2018.movegenerator.MaxInfluenceMoves;
import codecup2018.player.AspirationTablePlayer;
import codecup2018.player.NegaMaxPlayer;
import codecup2018.player.Player;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class PerformancePositionTest {
private static boolean first = true;
private final Board board;
public PerformancePositionTest(Board board) throws IOException {
this.board = board;
}
@Test
public void runTest() throws IOException {
CountingEvaluator eval = new CountingEvaluator(new MedianFree());
//CountingEvaluator eval = new CountingEvaluator(new IncrementalExpectedValue());
//CountingEvaluator eval = new CountingEvaluator(new ExpectedValue());
//Player unoptimized = new NegaMaxPlayer("NM_MF_MFM_11", eval, new MostFreeMax(), 11);
Player unoptimized = new NegaMaxPlayer("NM_IEV_MI_4", eval, new MaxInfluenceMoves(), 4);
//Player unoptimized = new AspirationPlayer("Unordered", eval, new MostFreeMax(), 10);
unoptimized.initialize(new BitBoard(board));
int move1 = unoptimized.move();
int unoptimizedEvaluations = eval.getnEvaluations();
//Player optimized = new AspirationPlayer("As_MF_MFM_11", eval, new MostFreeMax(), 11);
//Player optimized = new AspirationPlayer("As_IEV_MI_4", eval, new MaxInfluenceMoves(), 4);
Player optimized = new AspirationTablePlayer("AsT_IEV_MI_4", eval, new MaxInfluenceMoves(), 4);
//Player optimized = new AspirationPlayer("EV_Ordered", eval, new EvaluationOrder(new ExpectedValue(), new MostFreeMax()), 10);
optimized.initialize(new BitBoard(board));
int move2 = optimized.move();
int optimizedEvaluations = eval.getnEvaluations();
if (first) {
System.out.printf("%17s vs %s%n", optimized.getName(), unoptimized.getName());
first = false;
}
System.out.printf("Evals: %10d vs %10d (%d%%) moves: %10s vs %10s%n", optimizedEvaluations, unoptimizedEvaluations, (100 * optimizedEvaluations) / unoptimizedEvaluations, Board.moveToString(move2), Board.moveToString(move1));
}
@Parameterized.Parameters
public static Collection<Object[]> data() {
Collection<Object[]> boards = new ArrayList<>();
boards.add(new Object[]{movesToBoard("A1,A4,A5,C3,C4,B2=15,B6=15,E2=14,E3=14", true)});
boards.add(new Object[]{movesToBoard("A1,A4,A5,C3,C4,B2=15,B6=15,E2=14,E3=14,C5=12", false)});
boards.add(new Object[]{movesToBoard("A4,B5,D2,D4,E3,B2=15,C3=8,B6=14,C6=11,F2=13,F1=10,A7=12,G2=14,B3=11,C4=15,C1=10,A3=12", true)});
boards.add(new Object[]{movesToBoard("B3,B7,C2,D2,D3,B5=15,F2=14,C5=14,A2=15", true)});
boards.add(new Object[]{movesToBoard("A5,B2,B6,C2,E4,C4=15,E2=15,F2=14,C3=14,C5=13", false)});
boards.add(new Object[]{movesToBoard("B4,D4,E2,E4,F2,B2=15,B6=15", true)});
boards.add(new Object[]{movesToBoard("B4,D4,E2,E4,F2,B2=11,B6=15,C5=13", false)});
boards.add(new Object[]{movesToBoard("B2,C1,C2,C4,D1,B6=15,E2=15,F2=14,D4=14,B4=13", false)});
return boards;
}
public static Board movesToBoard(String moves, boolean player1) {
Board board = new BitBoard();
String[] ms = moves.split(",");
for (int i = 0; i < 5; i++) {
byte pos = Board.parsePos(ms[i]);
board.block(pos);
}
for (int i = 5; i < ms.length; i++) {
boolean myMove = (i % 2 == 1) == player1; // Odd because actual moves start after 5 blocks
String m = ms[i];
int move = Board.parseMove(m);
if (!myMove) {
move = Board.setMoveVal(move, (byte) -Board.getMoveVal(move));
}
board.applyMove(move);
}
return board;
}
}
| 44.795918 | 234 | 0.633713 |
75dd4c7e4945241a2d55161e72aba407ccfa214b
| 855 |
package com.zsw.tbretrofit.databox;
/**
* @描述: -
* -
* @作者:zhusw
* @创建时间:17/11/21 下午2:21
* @最后更新时间:17/11/21 下午2:21
*/
public class PostDataUtils {
public static SiginParameter getSiginParameter(){
SiginParameter loginParameter = new SiginParameter();
loginParameter.setClient_flag("android");
loginParameter.setClientMobileVersion("1.0");
loginParameter.setLocale("zh");
loginParameter.setLoginName("sunkui@visionet.com.cn");
loginParameter.setPassword("123456");
loginParameter.setModel("Samsung Galaxy Note3 N9009");
return loginParameter;
}
public static LearnParameter getLearnParameter(){
LearnParameter learnParameter = new LearnParameter();
learnParameter.setPageInfo(new LearnParameter.PageInfoBean(1,5));
return learnParameter;
}
}
| 28.5 | 73 | 0.68538 |
33ad8510791b2cc29f8a590aa3659e49b9f827e4
| 2,363 |
import java.util.ArrayList;
import java.util.ListIterator;
//import javax.swing.text.html.HTMLDocument.Iterator;
/**
* This class implements three methods. These test an array on a few
* characteristics.
*
* @author AlgoDat-Tutoren
*
*/
public class ArrayCheck {
/**
* Tests all elements of the given array,
* if they are divisible by the given divisor.
*
* @param arr
* array to be tested
* @param divisor
* number by which all elements of the given array should be divisible
* @return true if all elements are divisible by divisor
*/
public boolean allDivisibleBy(ArrayList<Integer> arr, int divisor) {
if(arr==null||arr.size()==0)
return false;
if(divisor==0)
return false;
ListIterator<Integer> myIterator = arr.listIterator();
while(myIterator.hasNext()) {
if(myIterator.next()%divisor!=0)
return false;
}
return true;
}
/**
* Tests if the given array is a part of
* the fibonacci sequence.
*
* @param arr
* array to be tested
* @return true if the elements are part of
* the fibonacci sequence
*/
public boolean isFibonacci(ArrayList<Integer> arr) {
if(arr==null||arr.size()<3)
return false;
ListIterator<Integer> arrIterator = arr.listIterator();
Integer a,b;
boolean flag;
do{
a=arrIterator.next();
b=arrIterator.next();
if(arrIterator.hasNext())
flag=true;
else
flag=false;
arrIterator.previous();
if(b<a)
return false;
} while(flag==true);
Integer x=0,y=1;
ArrayList<Integer> fibonacci=new ArrayList<Integer>();
fibonacci.add(x);
fibonacci.add(y);
while(y<b) {
y=x+y;
fibonacci.add(y);
x=y-x;
}
if(y!=b)
return false;
if(arr.size()>fibonacci.size())
return false;
arrIterator = arr.listIterator();
ListIterator<Integer> fibIterator = fibonacci.listIterator();
while(arrIterator.hasNext())
arrIterator.next();
while(fibIterator.hasNext())
fibIterator.next();
while(arrIterator.hasPrevious()) {
if(arrIterator.previous()!=fibIterator.previous())
return false;
}
return true;
}
}
| 25.684783 | 78 | 0.591198 |
33b9b0f5bb8da337a6c20f9e48aadff36474fda2
| 2,025 |
package com.wenhaiz.himusic.http.request;
import android.support.annotation.NonNull;
import com.wenhaiz.himusic.http.HttpCallback;
import com.wenhaiz.himusic.http.HttpMethod;
import com.wenhaiz.himusic.http.HttpUtil;
import java.lang.reflect.Type;
public abstract class BaseRequest<T> {
private BaseDataCallback<T> dataCallback = null;
public abstract Type getType();
public abstract HttpMethod getHttpMethod();
public void send() {
//发送请求
if (getHttpMethod() == null) {
return;
}
HttpCallback<T> callback = new HttpCallback<T>(this) {
@Override
public void onHttpSuccess(T data) {
if (dataCallback == null) {
return;
}
dataCallback.onSuccess(data);
}
@Override
public Type getType() {
return BaseRequest.this.getType();
}
@Override
public void onFailure(String code, String msg) {
if (dataCallback == null) {
return;
}
dataCallback.onFailure(code, msg);
}
};
if (dataCallback != null) {
dataCallback.beforeRequest();
}
HttpMethod method = getHttpMethod();
if (method.getRequestType() == HttpMethod.RequestType.GET) {
HttpUtil.get(method.getUrl(), method.getData(), callback);
} else if (method.getRequestType() == HttpMethod.RequestType.POST) {
HttpUtil.post(method.getUrl(), method.getData(), callback);
}
}
public BaseRequest<T> setDataCallback(BaseDataCallback<T> dataCallback) {
this.dataCallback = dataCallback;
return this;
}
public static abstract class BaseDataCallback<T> {
public abstract void onSuccess(@NonNull T data);
public abstract void onFailure(String code, String msg);
public abstract void beforeRequest();
}
}
| 26.298701 | 77 | 0.581235 |
1e06ccaddb4676383cc65346332ae8ef34bd5a6e
| 4,056 |
package com.gratex.perconik.useractivity.app.watchers;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import com.gratex.perconik.useractivity.app.EventDocument;
import com.gratex.perconik.useractivity.app.TypeUriHelper;
import com.gratex.perconik.useractivity.app.ValidationHelper;
@Singleton
@Path("/ide")
@SuppressWarnings("static-method")
public class IdeWatcherSvc {
static final WatcherSvcReqHandler watcherSvcReqHandler = new WatcherSvcReqHandler();
static final WatcherSvcReqHandler codePasteWatcherSvcReqHandler = new WatcherSvcReqHandler() {
@Override
protected final boolean beforeAddToCache(EventDocument doc) {
//handle paste from web
String pastedTextIntoIde = doc.getText();
if (!ValidationHelper.isStringNullOrWhitespace(pastedTextIntoIde)) {
WebWatcherState webWatcherState = WebWatcherState.getInstance();
pastedTextIntoIde = pastedTextIntoIde.trim();
String copiedTextFromWeb = webWatcherState.getLastCopyText();
if (copiedTextFromWeb != null && copiedTextFromWeb.equals(pastedTextIntoIde)) {
doc.setWebUrl(webWatcherState.getLastCopyUrl());
doc.setEventTypeUri(UriBuilder.fromPath(TypeUriHelper.EVENT_BASE_URI).path("ide").path("code").path("pastefromweb").build().toString());
}
}
return true;
}
};
public IdeWatcherSvc() {}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/checkin")
public Response postCheckinEvent(String eventData) throws Exception {
return watcherSvcReqHandler.handle(eventData, getBaseUri().path("checkin").build().toString());
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/find")
public Response postFindEvent(String eventData) throws Exception {
return watcherSvcReqHandler.handle(eventData, getBaseUri().path("find").build().toString());
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/code/{eventType:(selectionchanged|paste|copy|cut)}")
public Response postCodeEvent(String eventData, @PathParam("eventType") String eventType) throws Exception {
if (eventType.equals("paste")) { //handle paste from web
return codePasteWatcherSvcReqHandler.handle(eventData, getBaseUri().path("code").path(eventType).build().toString());
}
return watcherSvcReqHandler.handle(eventData, getBaseUri().path("code").path(eventType).build().toString());
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/codeelement/{eventType:(visiblestart|visibleend|editstart|editend)}")
public Response postCodeElementEvent(String eventData, @PathParam("eventType") String eventType) throws Exception {
return watcherSvcReqHandler.handle(eventData, getBaseUri().path("codeelement").path(eventType).build().toString());
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/document/{eventType:(switchto|add|open|close|remove|rename|save)}")
public Response postDocumentEvent(String eventData, @PathParam("eventType") String eventType) throws Exception {
return watcherSvcReqHandler.handle(eventData, getBaseUri().path("document").path(eventType).build().toString());
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/project/{eventType:(switchto|add|remove|rename|open|close|refresh)}")
public Response postProjectEvent(String eventData, @PathParam("eventType") String eventType) throws Exception {
return watcherSvcReqHandler.handle(eventData, getBaseUri().path("project").path(eventType).build().toString());
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/idestatechange")
public Response postIdeStateChangeEvent(String eventData) throws Exception {
return watcherSvcReqHandler.handle(eventData, getBaseUri().path("statechange").build().toString());
}
private static UriBuilder getBaseUri() {
return UriBuilder.fromPath(TypeUriHelper.EVENT_BASE_URI).path("ide");
}
}
| 40.56 | 146 | 0.755178 |
56f3e3e30d87087302fce99b65abb787d159526b
| 4,524 |
public class Sarki {
private int id;
private String sarki_adi;
private int tarih;
private String ad;
private String sanatci_adi;
private int sanatci_id;
private int album_id;
private String album_adi;
private int tur_id;
private String tur_adi;
private int sanatciId;
private String sanatciAd;
private int turId;
private String turAd;
private int albumId;
private String albumAd;
private int dinlenme;
private float sure;
private int dinlenme_sayisi;
public Sarki(int id,String sarki_adi,String sanatci_adi,String album_adi,float sure,int dinlenme_sayisi){
this.id=id;
this.sarki_adi=sarki_adi;
this.sanatci_adi=sanatci_adi;
this.album_adi=album_adi;
this.sure=sure;
this.dinlenme_sayisi=dinlenme_sayisi;
}
public Sarki(int id,String sarki_adi,String sanatci_adi,String album_adi,float sure,int dinlenme_sayisi,String tur_adi){
this.id=id;
this.sarki_adi=sarki_adi;
this.sanatci_adi=sanatci_adi;
this.album_adi=album_adi;
this.sure=sure;
this.dinlenme_sayisi=dinlenme_sayisi;
this.tur_adi=tur_adi;
}
public Sarki(int id, String ad, int tarih, String sanatciAd, String turAd, String albumAd, int dinlenme, float sure) {
this.id = id;
this.ad = ad;
this.tarih = tarih;
this.sanatciAd = sanatciAd;
this.turAd = turAd;
this.albumAd = albumAd;
this.dinlenme = dinlenme;
this.sure = sure;
}
public String getTur_adi() {
return tur_adi;
}
public void setTur_adi(String tur_adi) {
this.tur_adi = tur_adi;
}
public Sarki(int id, String sarki_adi, int tarih, String sanatci_adi, int sanatci_id, int album_id, String album_adi, int tur_id, String tur_adi, float sure, int dinlenme_sayisi) {
this.id = id;
this.sarki_adi = sarki_adi;
this.tarih = tarih;
this.sanatci_adi = sanatci_adi;
this.sanatci_id = sanatci_id;
this.album_id = album_id;
this.album_adi = album_adi;
this.tur_id = tur_id;
this.tur_adi = tur_adi;
this.sure = sure;
this.dinlenme_sayisi = dinlenme_sayisi;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSarki_adi() {
return sarki_adi;
}
public void setSarki_adi(String sarki_adi) {
this.sarki_adi = sarki_adi;
}
public String getSanatci_adi() {
return sanatci_adi;
}
public void setSanatci_adi(String sanatci_adi) {
this.sanatci_adi = sanatci_adi;
}
public String getAlbum_adi() {
return album_adi;
}
public void setAlbum_adi(String album_adi) {
this.album_adi = album_adi;
}
public float getSure() {
return sure;
}
public void setSure(float sure) {
this.sure = sure;
}
public int getDinlenme_sayisi() {
return dinlenme_sayisi;
}
public void setDinlenme_sayisi(int dinlenme_sayisi) {
this.dinlenme_sayisi = dinlenme_sayisi;
}
public String getAd() {
return ad;
}
public void setAd(String ad) {
this.ad = ad;
}
public int getTarih() {
return tarih;
}
public void setTarih(int tarih) {
this.tarih = tarih;
}
public int getSanatciId() {
return sanatciId;
}
public void setSanatciId(int sanatciId) {
this.sanatciId = sanatciId;
}
public String getSanatciAd() {
return sanatciAd;
}
public void setSanatciAd(String sanatciAd) {
this.sanatciAd = sanatciAd;
}
public int getTurId() {
return turId;
}
public void setTurId(int turId) {
this.turId = turId;
}
public String getTurAd() {
return turAd;
}
public void setTurAd(String turAd) {
this.turAd = turAd;
}
public int getAlbumId() {
return albumId;
}
public void setAlbumId(int albumId) {
this.albumId = albumId;
}
public String getAlbumAd() {
return albumAd;
}
public void setAlbumAd(String albumAd) {
this.albumAd = albumAd;
}
public int getDinlenme() {
return dinlenme;
}
public void setDinlenme(int dinlenme) {
this.dinlenme = dinlenme;
}
}
| 21.961165 | 184 | 0.605659 |
88cdaf24c95be2eda1c4a607f27732d20063c56b
| 843 |
package com.tazine.thread.cooperate.cases.bank;
/**
* BankAccount
*
* @author frank
* @date 2017/12/18
*/
public class BankAccount {
private String name;
private double balance;
public BankAccount(String name, double balance) {
this.name = name;
this.balance = balance;
}
public void deposit(double money) {
balance += money;
}
public void fetch(double money) {
if (balance >= money) {
balance -= money;
} else {
System.out.println(" 您的余额不足 ");
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
| 17.93617 | 53 | 0.563464 |
10b8e246b2a4615d9556a9f52046acb06ed521f1
| 1,573 |
package io.pity.bootstrap.publish.html;
import io.pity.api.StopExecutionException;
import io.pity.api.reporting.CollectionResults;
import io.pity.api.reporting.ReportPublisher;
import io.pity.bootstrap.publish.markdown.MarkdownCreator;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.pegdown.Extensions;
import org.pegdown.PegDownProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class HtmlReportPublisher implements ReportPublisher {
public static final Logger log = LoggerFactory.getLogger(HtmlReportPublisher.class);
@Override
public void publishReport(CollectionResults collectedResults) {
MarkdownCreator markdownCreator = new MarkdownCreator(collectedResults);
PegDownProcessor processor = new PegDownProcessor(Extensions.ALL);
String body = processor.markdownToHtml(markdownCreator.createMarkdown());
try {
FileUtils.write(new File("pity.html"), createHtmlPage(body));
} catch (IOException e) {
log.error("Unable to write html file", e);
}
}
private String createHtmlPage(String body) throws IOException {
InputStream templateStream = this.getClass().getResourceAsStream("/template.html");
String template = IOUtils.toString(templateStream);
return template.replace("__BODY__", body);
}
@Override
public void validateRequirements() throws StopExecutionException {
//NOOP
}
}
| 34.195652 | 91 | 0.744437 |
f826956bb51a3daa20b485cd60089d3ba903daa3
| 3,138 |
package org.jjche.security.auth;
import org.jjche.security.auth.sms.SmsCodeAuthenticationToken;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
/**
* <p>
* 自定义AuthenticationProvider,验证用户名或手机号或唯一标识等值
* </p>
*
* @author miaoyj
* @version 1.0.0-SNAPSHOT
* @since 2021-05-11
*/
public class AbstractAuthenticationProvider implements AuthenticationProvider {
private UserDetailsService userDetailsService;
/**
* {@inheritDoc}
*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UserDetails user = userDetailsService.loadUserByUsername((String) authentication.getPrincipal());
this.additionalAuthenticationChecks(user, authentication);
this.check(user);
SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user, user.getAuthorities());
authenticationResult.setDetails(authentication.getDetails());
return authenticationResult;
}
/**
* {@inheritDoc}
*/
@Override
public boolean supports(Class<?> aClass) {
return false;
}
/**
* <p>Getter for the field <code>userDetailsService</code>.</p>
*
* @return a {@link org.springframework.security.core.userdetails.UserDetailsService} object.
*/
public UserDetailsService getUserDetailsService() {
return userDetailsService;
}
/**
* <p>Setter for the field <code>userDetailsService</code>.</p>
*
* @param userDetailsService a {@link org.springframework.security.core.userdetails.UserDetailsService} object.
*/
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
/**
* <p>
* 额外验证内容
* </p>
*
* @param user 用户
* @param auth 认证
*/
protected void additionalAuthenticationChecks(UserDetails user, Authentication auth) {
if (user == null) {
throw new UsernameNotFoundException("user not found");
}
}
/**
* <p>
* 检查常用用户标识
* </p>
*
* @param user 用户
*/
protected void check(UserDetails user) {
if (!user.isAccountNonLocked()) {
throw new LockedException("User account is locked");
} else if (!user.isEnabled()) {
throw new DisabledException("User is disabled");
} else if (!user.isAccountNonExpired()) {
throw new AccountExpiredException("User account has expired");
}
}
}
| 31.069307 | 118 | 0.700127 |
c1d1a89193376cd2b39ff21dbd038d0a4bc9e198
| 126 |
/**
* Annotation support for actuator web endpoints.
*/
package org.springframework.boot.actuate.endpoint.web.annotation;
| 18 | 65 | 0.769841 |
10cb31ae472f06c45316b3d480e16980dce0c444
| 932 |
package br.com.projeto.Servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.com.projeto.DAO.ComentarioDAO;
@WebServlet("/buscaidHospital")
public class BuscaHospitalServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) {
String nomeEstabelecimento = request.getParameter("nomeEstabelecimento");
int idEstabelecimento=0;
ComentarioDAO dao = new ComentarioDAO();
idEstabelecimento = dao.buscarIdHospital(nomeEstabelecimento);
try {
PrintWriter out = response.getWriter();
out.println(idEstabelecimento);
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 24.526316 | 83 | 0.763948 |
c7a9e39f3c14e99e6b275648a9e666aa6d6103f7
| 839 |
package com.customeraccount.composite.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CustomerAccountManagementProcessor {
@Autowired
private OperationsHandler operationsHandler;
@Autowired
private FallbackOperationsHandler fallbackOperationsHandler;
public OperationsHandler getOperationsHandler() {
return operationsHandler;
}
public void setOperationsHandler(OperationsHandler operationsHandler) {
this.operationsHandler = operationsHandler;
}
public FallbackOperationsHandler getFallbackOperationsHandler() {
return fallbackOperationsHandler;
}
public void setFallbackOperationsHandler(
FallbackOperationsHandler fallbackOperationsHandler) {
this.fallbackOperationsHandler = fallbackOperationsHandler;
}
}
| 23.971429 | 72 | 0.840286 |
ea694f1d1a5878aa5d415986f058a88026f582d7
| 6,325 |
package io.resys.hdes.aproc;
import java.io.BufferedWriter;
/*-
* #%L
* hdes-maven-plugin
* %%
* Copyright (C) 2020 Copyright 2020 ReSys OÜ
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.compiler.util.scan.SimpleSourceInclusionScanner;
import org.codehaus.plexus.compiler.util.scan.SourceInclusionScanner;
import org.codehaus.plexus.compiler.util.scan.mapping.SuffixMapping;
import org.sonatype.plexus.build.incremental.BuildContext;
import io.resys.hdes.compiler.api.HdesCompiler.Resource;
import io.resys.hdes.compiler.api.HdesCompiler.ResourceDeclaration;
import io.resys.hdes.compiler.api.HdesCompiler.ResourceParser;
import io.resys.hdes.compiler.spi.GenericHdesCompiler;
@Mojo(name = "hdes", defaultPhase = LifecyclePhase.GENERATE_SOURCES, requiresDependencyResolution = ResolutionScope.COMPILE, requiresProject = true)
public class HdesMojo extends AbstractMojo {
@Parameter(property = "project.build.sourceEncoding")
protected String sourceEncoding;
@Parameter(property = "project", required = true, readonly = true)
protected MavenProject project;
@Parameter(defaultValue = "${basedir}/src/main/hdes")
private File sourceDirectory;
@Parameter(defaultValue = "${project.build.directory}/generated-sources/hdes")
private File outputDirectory;
@Parameter(defaultValue = "${project.build.directory}/maven-status/hdes", readonly = true)
private File statusDirectory;
@Component
private BuildContext buildContext;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
Log log = getLog();
String sourceEncoding = getEncoding(this.sourceEncoding);
log.info("HDES source: " + sourceDirectory);
log.info("HDES output: " + outputDirectory);
if (!sourceDirectory.isDirectory()) {
log.info("No HDES sources to compile in: " + sourceDirectory.getAbsolutePath());
return;
}
ResourceParser parser = GenericHdesCompiler.config().build().parser();
for (File file : getHdesFiles(sourceDirectory)) {
getLog().info("Compiling HDES source: " + file.getAbsolutePath());
parser.add(file.getAbsolutePath(), getSource(file, sourceEncoding));
}
List<Resource> code = parser.build();
File outputDirectory = getOutputDirectory(this.outputDirectory);
for (Resource resource : code) {
for(ResourceDeclaration value : resource.getDeclarations()) {
createFile(value, outputDirectory, sourceEncoding);
}
}
if (project != null) {
project.addCompileSourceRoot(outputDirectory.getPath());
}
}
private void createFile(ResourceDeclaration value, File outputDirectory, String sourceEncoding) throws MojoExecutionException {
try {
File packageDirectory = new File(outputDirectory, value.getType().getPkg().replace(".", File.separator));
if(!packageDirectory.exists()) {
packageDirectory.mkdirs();
}
File outputFile = new File(packageDirectory, value.getType().getName() + ".java");
URI relativePath = project.getBasedir().toURI().relativize(outputFile.toURI());
getLog().info("Writing file: " + relativePath);
OutputStream outputStream = buildContext.newFileOutputStream(outputFile);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, sourceEncoding));
writer.write(value.getValue());
writer.flush();
writer.close();
} catch (Exception e) {
getLog().error(e);
throw new MojoExecutionException("Failed to write file: " + value.getType().getPkg() + "." + value.getType().getName() + " because of: " + e.getMessage(), e);
}
}
private String getSource(File file, String encoding) throws MojoExecutionException {
try {
return IOUtils.toString(new FileInputStream(file), encoding);
} catch (Exception e) {
getLog().error(e);
throw new MojoExecutionException("Failed to read file: " + file.getAbsolutePath() + " because of: " + e.getMessage(), e);
}
}
private Set<File> getHdesFiles(File sourceDirectory) throws MojoExecutionException {
try {
Set<String> includes = Collections.singleton("**/*.hdes");
Set<String> excludes = Collections.emptySet();
SourceInclusionScanner scan = new SimpleSourceInclusionScanner(includes, excludes);
scan.addSourceMapping(new SuffixMapping("hdes", Collections.emptySet()));
return scan.getIncludedSources(sourceDirectory, null);
} catch (Exception e) {
getLog().error(e);
throw new MojoExecutionException("Failed to scan for source files because of: " + e.getMessage(), e);
}
}
private File getOutputDirectory(File outputDirectory) {
if (!outputDirectory.exists()) {
outputDirectory.mkdirs();
}
return outputDirectory;
}
private String getEncoding(String encoding) {
if (encoding == null) {
return Charset.defaultCharset().name();
}
return Charset.forName(encoding.trim()).name();
}
}
| 39.779874 | 164 | 0.730435 |
fe39cbda9ef9ef199b16b303ec3def10f8fe651e
| 473 |
package com.pluralsight.corejdbc.m5c3;
public class Main {
public static void main(String[] args) throws Exception {
try {
HrComponent comp = new HrComponent();
int key = comp.addEmployee(
"Williams", "Roger", "x104",
"rwilliams@classicmodelcars.com", "3",
"Sales Manager (NA)");
System.out.println("The auto-generated primary key = " + key);
} catch (Exception exception) {
util.ExceptionHandler.handleException(exception);
}
}
}
| 21.5 | 65 | 0.672304 |
ffca95aef280c85e145b1bd7a5021794545faa77
| 1,019 |
package com.InfinityRaider.AgriCraft.api.v1;
import com.google.common.hash.Hashing;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public class ItemWithMeta {
private final Item item;
private final int meta;
public ItemWithMeta(Item item, int meta) {
this.item = item;
this.meta = meta;
}
public Item getItem() {
return item;
}
public int getMeta() {
return meta;
}
public ItemStack toStack() {
return new ItemStack(item, 1, meta);
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (obj instanceof ItemWithMeta) {
ItemWithMeta item = (ItemWithMeta) obj;
return item.item == this.item && item.meta == this.meta;
}
return false;
}
@Override
public int hashCode() {
return Hashing.md5().newHasher()
.putInt(item.hashCode())
.putInt(meta).hash().asInt();
}
}
| 21.680851 | 68 | 0.58685 |
470d81079871c66c5db14c9818d9139b604ddd07
| 456 |
package frc.lib;
import edu.wpi.first.wpilibj2.command.Subsystem;
public interface ODN_State extends Subsystem {
/**
* Sets a new goal position for the subsystem
* @param pos New goal position
*/
public void setGoalLocation(double pos);
/**
* Checks whether the subsystem has reached the goal location
* @return true if subsystem has reached goal location
*/
public boolean atGoalLocation();
public void resetPosition();
}
| 21.714286 | 63 | 0.721491 |
6a6725aa29d3c16e29c9a2f62ed082b838bc9683
| 269 |
/*
org.deviceconnect.message.intent.message
Copyright (c) 2016 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
/**
* Intent用 Device ConnectのAPIを利用するためクラスを提供する。
*/
package org.deviceconnect.message.intent.message;
| 24.454545 | 49 | 0.773234 |
d87875b9a994cae2dc5a4137abf01e724d161319
| 840 |
package com.oath.cyclops.internal.stream.spliterators.push.filter;
import cyclops.reactive.Spouts;
import org.reactivestreams.Publisher;
import org.reactivestreams.tck.PublisherVerification;
import org.reactivestreams.tck.TestEnvironment;
import org.reactivestreams.tck.support.PublisherVerificationRules;
import org.testng.annotations.Test;
@Test
public class FilterRangeLongTckPublisherTest extends PublisherVerification<Long> implements PublisherVerificationRules{
public FilterRangeLongTckPublisherTest(){
super(new TestEnvironment(300L));
}
@Override
public Publisher<Long> createPublisher(long elements) {
return Spouts.rangeLong(0,elements)
.filter(i->true);
}
@Override
public Publisher<Long> createFailedPublisher() {
return null; //not possible to forEachAsync to failed Stream
}
}
| 24.705882 | 119 | 0.794048 |
253149c5ef55a8201c076ac3e2f567e37220c39a
| 2,565 |
/**
* @Project zuul-server
* @Package com.cloud.filter
* @FileName SsoFilter.java
*/
package com.cloud.filter;
import java.io.IOException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* 登录授权过滤器
* @Author zivin
* @Date 2017年10月12日
*/
@Component
public class SsoFilter extends UserFilter {
@Value("${home.baseUrl}")
private String baseUrl;
/**
* 在访问controller前判断是否登录,返回错误状态。
* @param request
* @param response
* @return true-继续往下执行,false-该filter过滤器已经处理,不继续执行其他过滤器
* @throws Exception
*/
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
HttpServletRequest httpRequest = WebUtils.toHttp(request);
HttpServletResponse httpResponse = WebUtils.toHttp(response);
httpResponse.setHeader("Access-control-Allow-Origin", baseUrl);
httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST");
httpResponse.setHeader("Access-Control-Allow-Headers", httpRequest.getHeader("Access-Control-Request-Headers"));
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpResponse.sendError(401, "授权失效,请重新登录");
return false;
}
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
HttpServletRequest httpRequest = WebUtils.toHttp(request);
HttpServletResponse httpResponse = WebUtils.toHttp(response);
httpResponse.setHeader("Access-control-Allow-Origin", baseUrl);
httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST");
httpResponse.setHeader("Access-Control-Allow-Headers", httpRequest.getHeader("Access-Control-Request-Headers"));
if (httpRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpResponse.setStatus(HttpStatus.OK.value());
return false;
}
return super.preHandle(request, response);
}
}
| 37.173913 | 121 | 0.709942 |
0e25f3e4ffba4ebb664bb7467c9a66dea26bff80
| 720 |
package com.bluedragon.guavalearning.preconditions;
import com.google.common.base.Preconditions;
/**
* @author CodeRush
* @date 2019/7/27 20:39
*/
public class PreconditionsTest {
public static void main(String[] args) {
String arg = "1";
Preconditions.checkArgument(arg.equals("1"));
// Preconditions.checkArgument(arg.equals("2"));
// Preconditions.checkArgument(arg.equals("2"),"参数不为2");
String s = Preconditions.checkNotNull(arg);
System.out.println(s);
// Object o = Preconditions.checkNotNull(null);
// Preconditions.checkState(arg.equals("2"));
int i = Preconditions.checkPositionIndex(3, 2);
System.out.println(i);
}
}
| 26.666667 | 63 | 0.651389 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.