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 |
|---|---|---|---|---|---|
960a2afcbdd8d16f4a7c557cd5ae1d747b70866b | 2,480 | /*
* 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.sling.adapter.annotations.util;
import org.codehaus.jackson.JsonNode;
import org.osgi.framework.Constants;
import org.osgi.service.component.ComponentConstants;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Util {
private static final Set<String> DYNAMIC_PROPERTIES = new HashSet<>(Arrays.asList(
ComponentConstants.COMPONENT_ID,
Constants.SERVICE_BUNDLEID
));
public static Map<String, Object> getNonDynamicPropertiesForService(final JsonNode json) {
final JsonNode props = json.get("data").get(0).get("props");
final Map<String, Object> properties = new LinkedHashMap<>();
for (final JsonNode prop : props) {
final String name = prop.get("key").getTextValue();
if (!DYNAMIC_PROPERTIES.contains(name)) {
properties.put(name, getPropertyValue(prop.get("value")));
}
}
return properties;
}
private static Object getPropertyValue(final JsonNode value) {
if (value.isBoolean()) {
return value.getBooleanValue();
}
if (value.isNumber()) {
return value.getNumberValue();
}
if (value.isTextual()) {
return value.getTextValue();
}
if (value.isArray()) {
final List<String> items = new ArrayList<>();
for (final JsonNode item : value) {
items.add(item.getTextValue());
}
return items;
}
return null;
}
}
| 35.942029 | 94 | 0.664919 |
246628fbd242144cbfae9831ccb5ec2e727e0301 | 28,654 | package com.dreamliner.lib.frame.base;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.CallSuper;
import android.support.annotation.CheckResult;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.MaterialDialog.SingleButtonCallback;
import com.dreamliner.easypermissions.AfterPermissionGranted;
import com.dreamliner.easypermissions.EasyPermissions;
import com.dreamliner.lib.customdialog.CustomButtonCallback;
import com.dreamliner.lib.customdialog.CustomDialog;
import com.dreamliner.lib.frame.R;
import com.dreamliner.lib.frame.entity.DefaultEventData;
import com.dreamliner.lib.frame.util.ConfigurationUtil;
import com.dreamliner.lib.frame.util.LogUtil;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.RxLifecycle;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.RxLifecycleAndroid;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;
import me.yokeyword.fragmentation.ExtraTransaction;
import me.yokeyword.fragmentation.ISupportActivity;
import me.yokeyword.fragmentation.ISupportFragment;
import me.yokeyword.fragmentation.SupportActivityDelegate;
import me.yokeyword.fragmentation.SupportHelper;
import me.yokeyword.fragmentation.anim.FragmentAnimator;
import static android.widget.Toast.LENGTH_LONG;
import static android.widget.Toast.LENGTH_SHORT;
import static com.dreamliner.lib.customdialog.CustomDialog.ALL_BUTTON;
import static com.dreamliner.lib.customdialog.CustomDialog.ONLY_CONFIRM_BUTTON;
import static com.dreamliner.lib.frame.util.ConfigurationUtil.CANCEL_COLOR_RES;
import static com.dreamliner.lib.frame.util.ConfigurationUtil.CANCEL_CONTENT;
import static com.dreamliner.lib.frame.util.ConfigurationUtil.OK_CONTENT;
import static com.dreamliner.lib.frame.util.ConfigurationUtil.THEME_COLOR_RES;
import static com.dreamliner.lib.frame.util.ConfigurationUtil.WARNING_COLOR_RES;
/**
* @author chenzj
* @Title: BaseCompatActivity
* @Description: 类的描述 -
* @date 2017/6/27 18:40
* @email admin@chenzhongjin.cn
*/
public abstract class BaseCompatActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks,
LifecycleProvider<ActivityEvent>, ISupportActivity {
public UUID mUUID = UUID.randomUUID();
protected int getLayoutId() {
return 0;
}
protected void initSpecialView(@Nullable Bundle savedInstanceState) {
}
protected abstract void initViews(@Nullable Bundle savedInstanceState);
protected void handleMes(Message msg) {
}
protected void getBundleExtras(Bundle extras) {
}
protected boolean isRegisterEvent() {
return true;
}
protected boolean isRequestPermissionOnResume() {
return true;
}
public MyHandler mHandler;
protected MaterialDialog mMaterialDialog;
protected CustomDialog mCustomDialog;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
lifecycleSubject.onNext(ActivityEvent.CREATE);
overridePendingTransitionIn();
super.onCreate(savedInstanceState);
mDelegate.onCreate(savedInstanceState);
//兼容DataBinding的方式的时候就不需要设置了
if (getLayoutId() != 0) {
setContentView(getLayoutId());
}
// base setup
Bundle extras = getIntent().getExtras();
if (null != extras) {
getBundleExtras(extras);
}
//Act 堆栈管理
AppManager.INSTACE.addActivity(this);
if (isRegisterEvent())
EventBus.getDefault().register(this);
mHandler = new MyHandler(this);
initSpecialView(savedInstanceState);
initViews(savedInstanceState);
}
protected void overridePendingTransitionIn() {
}
protected void overridePendingTransitionOut() {
}
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDelegate.onPostCreate(savedInstanceState);
}
@Override
@CallSuper
protected void onStart() {
super.onStart();
lifecycleSubject.onNext(ActivityEvent.START);
}
@Override
@CallSuper
protected void onPause() {
lifecycleSubject.onNext(ActivityEvent.PAUSE);
super.onPause();
}
@Override
@CallSuper
protected void onStop() {
lifecycleSubject.onNext(ActivityEvent.STOP);
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
lifecycleSubject.onNext(ActivityEvent.RESUME);
if (isRequestPermissionOnResume()) {
checkPermission();
} else {
if (!isFirstResume) {
checkPermission();
} else {
isFirstResume = false;
}
}
}
@Override
protected void onDestroy() {
//supportFra
mDelegate.onDestroy();
//RxLifecycle
lifecycleSubject.onNext(ActivityEvent.DESTROY);
//EventBus
if (isRegisterEvent()) {
EventBus.getDefault().unregister(this);
}
mHandler.removeCallbacksAndMessages(null);
hideDialog();
EasyPermissions.hidePermissionsDialog();
hideSoftInputView();
super.onDestroy();
}
@Override
public void finish() {
super.finish();
AppManager.INSTACE.removeActivity(this);
overridePendingTransitionOut();
}
/**
* startActivity
*
* @param clazz
*/
public void readyGo(Class<?> clazz) {
Intent intent = new Intent(this, clazz);
startActivity(intent);
}
/**
* startActivity with bundle
*
* @param clazz
* @param bundle
*/
public void readyGo(Class<?> clazz, Bundle bundle) {
Intent intent = new Intent(this, clazz);
if (null != bundle) {
intent.putExtras(bundle);
}
startActivity(intent);
}
/**
* startActivity then finish
*
* @param clazz
*/
public void readyGoThenKill(Class<?> clazz) {
Intent intent = new Intent(this, clazz);
startActivity(intent);
finish();
}
/**
* startActivityForResult
*
* @param clazz
* @param requestCode
*/
public void readyGoForResult(Class<?> clazz, int requestCode) {
Intent intent = new Intent(this, clazz);
startActivityForResult(intent, requestCode);
}
/**
* startActivity with bundle then finish
*
* @param clazz
* @param bundle
*/
public void readyGoThenKill(Class<?> clazz, Bundle bundle) {
Intent intent = new Intent(this, clazz);
if (null != bundle) {
intent.putExtras(bundle);
}
startActivity(intent);
finish();
}
/**
* startActivityForResult with bundle
*
* @param clazz
* @param requestCode
* @param bundle
*/
public void readyGoForResult(Class<?> clazz, int requestCode, Bundle bundle) {
Intent intent = new Intent(this, clazz);
if (null != bundle) {
intent.putExtras(bundle);
}
startActivityForResult(intent, requestCode);
}
/**
* Eventbus相关
*
* @param event
*/
public void postEvent(Object event) {
EventBus.getDefault().post(event);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void defaultEvent(DefaultEventData defaultEventData) {
//do nothing.just for somebody not Subscribe but regiest the event will crash
}
public void post(Runnable runnable) {
mHandler.post(runnable);
}
public void postDelayed(Runnable runnable, long delayMillis) {
mHandler.postDelayed(runnable, delayMillis);
}
protected static class MyHandler extends Handler {
private final WeakReference<BaseCompatActivity> mActivity;
public MyHandler(BaseCompatActivity activity) {
super(Looper.getMainLooper());
mActivity = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
BaseCompatActivity activity = mActivity.get();
if (activity != null) {
// do someThing
activity.handleMes(msg);
}
}
}
protected Toast mToast;
public Toast getToast() {
return mToast;
}
public void showToast(final String msg) {
showToast(msg, -1, LENGTH_SHORT);
}
public void showToast(@StringRes final int resId) {
showToast(null, resId, LENGTH_SHORT);
}
public void showLongToast(final String msg) {
showToast(msg, -1, LENGTH_LONG);
}
public void showLongToast(@StringRes final int resId) {
showToast(null, resId, LENGTH_LONG);
}
protected void showToast(final String msg, final @StringRes int resId, final int length) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (mToast == null) {
mToast = Toast.makeText(BaseCompatActivity.this, "", length);
}
mToast.setDuration(length);
if (TextUtils.isEmpty(msg)) {
if (resId != -1) {
try {
mToast.setText(resId);
} catch (Resources.NotFoundException ex) {
ex.printStackTrace();
}
}
} else {
mToast.setText(msg);
}
mToast.show();
}
});
}
public Snackbar showSnackBar(View contentView, String string) {
Snackbar snackbar = Snackbar.make(contentView, string, Snackbar.LENGTH_SHORT);
snackbar.show();
return snackbar;
}
public Snackbar showSnackBar(View contentView, String string, String action, View.OnClickListener clickListener) {
Snackbar snackbar = Snackbar.make(contentView, string, Snackbar.LENGTH_INDEFINITE).setAction(action, clickListener);
snackbar.show();
return snackbar;
}
public Snackbar showSnackBar(View contentView, String string, String action, View.OnClickListener clickListener,
Snackbar.Callback callback) {
Snackbar snackbar = Snackbar.make(contentView, string, Snackbar.LENGTH_INDEFINITE)
.setAction(action, clickListener).setCallback(callback);
snackbar.show();
return snackbar;
}
public Snackbar showSnackBar(View contentView, String string, Snackbar.Callback callback) {
Snackbar snackbar = Snackbar.make(contentView, string, Snackbar.LENGTH_SHORT).setCallback(callback);
snackbar.show();
return snackbar;
}
public boolean isShowIngDialog() {
boolean isShowing = false;
if (null != mCustomDialog && mCustomDialog.isShowing() || null != mMaterialDialog && mMaterialDialog.isShowing()) {
isShowing = true;
}
return isShowing;
}
public void hideDialog() {
if (null != mCustomDialog && mCustomDialog.isShowing()) {
mCustomDialog.dismiss();
}
if (null != mMaterialDialog && mMaterialDialog.isShowing()) {
mMaterialDialog.dismiss();
}
}
@ColorInt
protected int getColorInt(@ColorRes int colorRes) {
return getResources().getColor(colorRes);
}
//MD-Dialog相关
public void showOnlyContent(@NonNull CharSequence content) {
mMaterialDialog = new MaterialDialog.Builder(this).content(content).build();
mMaterialDialog.show();
}
public void showNoTitleLoadingDialog(@NonNull CharSequence content) {
mMaterialDialog = new MaterialDialog.Builder(this).content(content).progress(true, 0).cancelable(false).build();
mMaterialDialog.show();
}
public void showNoTitleLoadingDialog(@NonNull CharSequence content, boolean cancel) {
mMaterialDialog = new MaterialDialog.Builder(this).content(content).progress(true, 0).cancelable(cancel).build();
mMaterialDialog.show();
}
public void showLoadingDialog(@NonNull CharSequence title, @NonNull CharSequence content) {
mMaterialDialog = new MaterialDialog.Builder(this).title(title).content(content).progress(true, 0).cancelable(false).build();
mMaterialDialog.show();
}
public void showNoTitleMdDialog(@NonNull CharSequence content, SingleButtonCallback singleButtonCallback) {
mMaterialDialog = new MaterialDialog.Builder(this).content(content).positiveText(OK_CONTENT).negativeText(CANCEL_CONTENT)
.onPositive(singleButtonCallback).build();
mMaterialDialog.show();
}
public void showEditTextCallback(@NonNull CharSequence title, @NonNull CharSequence content, @NonNull CharSequence positiveStr,
@NonNull CharSequence hintStr, MaterialDialog.InputCallback inputCallback) {
mMaterialDialog = new MaterialDialog.Builder(this).title(title).content(content).inputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_WORDS).inputRange(2, 16)
.positiveText(positiveStr).input(hintStr, "", false, inputCallback).build();
mMaterialDialog.show();
}
//自定义Dialog相关
public void showBaseDialog(@NonNull CharSequence content, CustomButtonCallback customButtonCallback) {
showBaseDialog("", content, OK_CONTENT, CANCEL_CONTENT, customButtonCallback);
}
public void showBaseDialog(@NonNull CharSequence title, @NonNull CharSequence content, CustomButtonCallback customButtonCallback) {
showBaseDialog(title, content, OK_CONTENT, CANCEL_CONTENT, customButtonCallback);
}
public void showBaseDialog(@NonNull CharSequence content, @NonNull CharSequence positiveText,
@NonNull CharSequence negativeText, CustomButtonCallback customButtonCallback) {
showBaseDialog("", content, positiveText, negativeText, THEME_COLOR_RES, CANCEL_COLOR_RES, customButtonCallback);
}
public void showBaseDialog(@NonNull CharSequence content, @NonNull CharSequence positiveText,
@NonNull CharSequence negativeText, @ColorRes int positiveColor,
@ColorRes int negativeColor, CustomButtonCallback customButtonCallback) {
showBaseDialog("", content, positiveText, negativeText, positiveColor, negativeColor, customButtonCallback);
}
public void showBaseDialog(@NonNull CharSequence title, @NonNull CharSequence content, @NonNull CharSequence positiveText,
@NonNull CharSequence negativeText, CustomButtonCallback customButtonCallback) {
showBaseDialog(title, content, positiveText, negativeText, THEME_COLOR_RES, CANCEL_COLOR_RES, customButtonCallback);
}
public void showBaseDialog(@NonNull CharSequence title, @NonNull CharSequence content, @NonNull CharSequence positiveText,
@NonNull CharSequence negativeText, @ColorRes int positiveColor, @ColorRes int negativeColor,
CustomButtonCallback customButtonCallback) {
mCustomDialog = new CustomDialog.Builder(this).title(title).content(content).style(ALL_BUTTON)
.positiveText(positiveText).positiveColorRes(positiveColor).onPositive(customButtonCallback)
.negativeText(negativeText).negativeColorRes(negativeColor).onNegative(customButtonCallback)
.build();
mCustomDialog.show();
}
public void showWarningDialog(@NonNull CharSequence content, @NonNull CharSequence positiveText,
@NonNull CharSequence negativeText, CustomButtonCallback customButtonCallback) {
showWarningDialog("", content, positiveText, negativeText, customButtonCallback);
}
public void showWarningDialog(@NonNull CharSequence title, @NonNull CharSequence content, @NonNull CharSequence positiveText,
@NonNull CharSequence negativeText, CustomButtonCallback customButtonCallback) {
showBaseDialog(title, content, positiveText, negativeText, WARNING_COLOR_RES, CANCEL_COLOR_RES, customButtonCallback);
}
public void showOnlyConfirmCallback(@NonNull CharSequence content, CustomButtonCallback customButtonCallback) {
showOnlyConfirmCallback("", content, OK_CONTENT, THEME_COLOR_RES, customButtonCallback);
}
public void showOnlyConfirmCallback(@NonNull CharSequence content, @NonNull CharSequence onlyPositiveText,
CustomButtonCallback customButtonCallback) {
showOnlyConfirmCallback("", content, onlyPositiveText, THEME_COLOR_RES, customButtonCallback);
}
public void showOnlyConfirmCallback(@NonNull CharSequence title, @NonNull CharSequence content,
@NonNull CharSequence onlyPositiveText, CustomButtonCallback customButtonCallback) {
showOnlyConfirmCallback(title, content, onlyPositiveText, THEME_COLOR_RES, customButtonCallback);
}
public void showOnlyConfirmCallback(@NonNull CharSequence title, @NonNull CharSequence content,
@NonNull CharSequence onlyPositiveText, @ColorRes int onlyPositiveColor,
CustomButtonCallback customButtonCallback) {
mCustomDialog = new CustomDialog.Builder(this).title(title).content(content).style(ONLY_CONFIRM_BUTTON)
.onlyPositiveText(onlyPositiveText).onlyPositiveColorRes(onlyPositiveColor).onPositive(customButtonCallback)
.build();
mCustomDialog.show();
}
public void hideSoftInputView() {
InputMethodManager manager = ((InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE));
if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
if (getCurrentFocus() != null)
manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
/****************
* 运行时权限管理
****************/
private boolean isFirstResume = true;
public final static int RC_ALL_PERM = 0x100;
private boolean isNeverAskAgain = false;
protected void doPermissionsSuc() {
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@AfterPermissionGranted(RC_ALL_PERM)
protected void checkPermission() {
if (EasyPermissions.hasPermissions(this, ConfigurationUtil.getPermissionArray())) {
doPermissionsSuc();
} else {
String[] deniedPermissions = EasyPermissions.getDeniedPermissions(this, ConfigurationUtil.getPermissionArray());
if (!isNeverAskAgain) {
EasyPermissions.requestPermissions(this, getString(R.string.rationale_all), RC_ALL_PERM, deniedPermissions);
} else {
ArrayList<String> deniedList = new ArrayList<>();
Collections.addAll(deniedList, deniedPermissions);
isNeverAskAgain = EasyPermissions.checkDeniedPermissionsNeverAskAgain(this, getString(R.string.rationale_ask_again),
R.string.setting, android.R.string.cancel, deniedList);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
if (perms.size() == ConfigurationUtil.getPermissionArray().length) {
doPermissionsSuc();
} else {
LogUtil.e("BaseAct", "onPermissionsGranted: 有部分权限没有允许");
}
}
@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
isNeverAskAgain = EasyPermissions.checkDeniedPermissionsNeverAskAgain(this, getString(R.string.rationale_ask_again),
R.string.setting, android.R.string.cancel, perms);
}
/*****************
* RxJavaCycle相关
*****************/
private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create();
@Override
@NonNull
@CheckResult
public final Observable<ActivityEvent> lifecycle() {
return lifecycleSubject.hide();
}
@Override
@NonNull
@CheckResult
public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull ActivityEvent event) {
return RxLifecycle.bindUntilEvent(lifecycleSubject, event);
}
@Override
@NonNull
@CheckResult
public final <T> LifecycleTransformer<T> bindToLifecycle() {
return RxLifecycleAndroid.bindActivity(lifecycleSubject);
}
/*******************
* Fragmentation相关
*******************/
final SupportActivityDelegate mDelegate = new SupportActivityDelegate(this);
@Override
public SupportActivityDelegate getSupportDelegate() {
return mDelegate;
}
/**
* Perform some extra transactions.
* 额外的事务:自定义Tag,添加SharedElement动画,操作非回退栈Fragment
*/
@Override
public ExtraTransaction extraTransaction() {
return mDelegate.extraTransaction();
}
@Override
public FragmentAnimator getFragmentAnimator() {
return mDelegate.getFragmentAnimator();
}
@Override
public void setFragmentAnimator(FragmentAnimator fragmentAnimator) {
mDelegate.setFragmentAnimator(fragmentAnimator);
}
@Override
public FragmentAnimator onCreateFragmentAnimator() {
return mDelegate.onCreateFragmentAnimator();
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return mDelegate.dispatchTouchEvent(ev) || super.dispatchTouchEvent(ev);
}
/**
* 不建议复写该方法,请使用 {@link #onBackPressedSupport} 代替
*/
@Override
final public void onBackPressed() {
mDelegate.onBackPressed();
}
/**
* 该方法回调时机为,Activity回退栈内Fragment的数量 小于等于1 时,默认finish Activity
* 请尽量复写该方法,避免复写onBackPress(),以保证SupportFragment内的onBackPressedSupport()回退事件正常执行
*/
@Override
public void onBackPressedSupport() {
mDelegate.onBackPressedSupport();
}
/****************************************以下为可选方法(Optional methods)******************************************************/
/**
* 加载根Fragment, 即Activity内的第一个Fragment 或 Fragment内的第一个子Fragment
*
* @param containerId 容器id
* @param toFragment 目标Fragment
*/
public void loadRootFragment(int containerId, @NonNull ISupportFragment toFragment) {
mDelegate.loadRootFragment(containerId, toFragment);
}
public void loadRootFragment(int containerId, ISupportFragment toFragment, boolean addToBackStack, boolean allowAnimation) {
mDelegate.loadRootFragment(containerId, toFragment, addToBackStack, allowAnimation);
}
/**
* 加载多个同级根Fragment,类似Wechat, QQ主页的场景
*/
public void loadMultipleRootFragment(int containerId, int showPosition, ISupportFragment... toFragments) {
mDelegate.loadMultipleRootFragment(containerId, showPosition, toFragments);
}
/**
* show一个Fragment,hide其他同栈所有Fragment
* 使用该方法时,要确保同级栈内无多余的Fragment,(只有通过loadMultipleRootFragment()载入的Fragment)
* <p>
* 建议使用更明确的{@link #showHideFragment(ISupportFragment, ISupportFragment)}
*
* @param showFragment 需要show的Fragment
*/
public void showHideFragment(ISupportFragment showFragment) {
mDelegate.showHideFragment(showFragment);
}
/**
* show一个Fragment,hide一个Fragment ; 主要用于类似微信主页那种 切换tab的情况
*/
public void showHideFragment(ISupportFragment showFragment, ISupportFragment hideFragment) {
mDelegate.showHideFragment(showFragment, hideFragment);
}
/**
* It is recommended to use {@link SupportFragment#start(ISupportFragment)}.
*/
public void start(ISupportFragment toFragment) {
mDelegate.start(toFragment);
}
/**
* It is recommended to use {@link SupportFragment#start(ISupportFragment, int)}.
*
* @param launchMode Similar to Activity's LaunchMode.
*/
public void start(ISupportFragment toFragment, @ISupportFragment.LaunchMode int launchMode) {
mDelegate.start(toFragment, launchMode);
}
/**
* It is recommended to use {@link SupportFragment#startForResult(ISupportFragment, int)}.
* Launch an fragment for which you would like a result when it poped.
*/
public void startForResult(ISupportFragment toFragment, int requestCode) {
mDelegate.startForResult(toFragment, requestCode);
}
/**
* It is recommended to use {@link SupportFragment#startWithPop(ISupportFragment)}.
* Launch a fragment while poping self.
*/
public void startWithPop(ISupportFragment toFragment) {
mDelegate.startWithPop(toFragment);
}
/**
* It is recommended to use {@link SupportFragment#replaceFragment(ISupportFragment, boolean)}.
*/
public void replaceFragment(ISupportFragment toFragment, boolean addToBackStack) {
mDelegate.replaceFragment(toFragment, addToBackStack);
}
/**
* Pop the fragment.
*/
public void pop() {
mDelegate.pop();
}
/**
* Pop the last fragment transition from the manager's fragment
* back stack.
* <p>
* 出栈到目标fragment
*
* @param targetFragmentClass 目标fragment
* @param includeTargetFragment 是否包含该fragment
*/
public void popTo(Class<?> targetFragmentClass, boolean includeTargetFragment) {
mDelegate.popTo(targetFragmentClass, includeTargetFragment);
}
/**
* If you want to begin another FragmentTransaction immediately after popTo(), use this method.
* 如果你想在出栈后, 立刻进行FragmentTransaction操作,请使用该方法
*/
public void popTo(Class<?> targetFragmentClass, boolean includeTargetFragment, Runnable afterPopTransactionRunnable) {
mDelegate.popTo(targetFragmentClass, includeTargetFragment, afterPopTransactionRunnable);
}
public void popTo(Class<?> targetFragmentClass, boolean includeTargetFragment, Runnable afterPopTransactionRunnable, int popAnim) {
mDelegate.popTo(targetFragmentClass, includeTargetFragment, afterPopTransactionRunnable, popAnim);
}
/**
* 当Fragment根布局 没有 设定background属性时,
* Fragmentation默认使用Theme的android:windowbackground作为Fragment的背景,
* 可以通过该方法改变其内所有Fragment的默认背景。
*/
public void setDefaultFragmentBackground(@DrawableRes int backgroundRes) {
mDelegate.setDefaultFragmentBackground(backgroundRes);
}
/**
* 得到位于栈顶Fragment
*/
public ISupportFragment getTopFragment() {
return SupportHelper.getTopFragment(getSupportFragmentManager());
}
/**
* 获取栈内的fragment对象
*/
public <T extends ISupportFragment> T findFragment(Class<T> fragmentClass) {
return SupportHelper.findFragment(getSupportFragmentManager(), fragmentClass);
}
}
| 35.462871 | 135 | 0.67994 |
3ff0b96b9756f5a81d722295602b07029692d7fb | 3,823 | package revert.shredsheets.views;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import revert.shredsheets.models.SessionModel;
import revert.shredsheets.models.themes.ShredsheetsTheme;
public abstract class GenericView extends View {
public Context context = null;
public int y;
public int x;
public int drawnWidth;
public int drawnHeight;
//0 = unknown, 1 = portrait, 2 = landscape
public int orientation;
private float swipePosition;
public boolean isPortrait() {
return orientation == 1;
}
protected Paint backgroundPaint;
protected Paint borderPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
protected TextPaint textPaint;
protected final SessionModel session = SessionModel.getInstance();
private ShredsheetsTheme theme = SessionModel.getInstance().getTheme();
public GenericView(Context context) {
super(context, new EmptyAttributes());
}
public GenericView(Context context, LinearLayout.LayoutParams layoutParams) {
this(context, new EmptyAttributes());
this.setLayoutParams(layoutParams);
}
public GenericView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
backgroundPaint.setStyle(Paint.Style.FILL);
borderPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
borderPaint.setStyle(Paint.Style.STROKE);
textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
textPaint.setStyle(Paint.Style.STROKE);
}
public void ChangeOrientation(Resources resources) {
ChangeOrientation(resources.getConfiguration().orientation);
}
public void ChangeOrientation(int orientation) {
this.orientation = orientation;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
this.x = left;
this.y = top;
this.orientation = getResources().getConfiguration().orientation;
}
public float getSwipePosition() {
return swipePosition;
}
public void setSwipePosition(float swipePosition) {
this.swipePosition = swipePosition;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredWidth = drawnWidth != 0 ? drawnWidth : 50;
int desiredHeight = drawnHeight != 0 ? drawnHeight : 50;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
//Measure Width
if (widthMode == MeasureSpec.EXACTLY) {
//Must be this size
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
width = Math.min(desiredWidth, widthSize);
} else {
//Be whatever you want
width = desiredWidth;
}
//Measure Height
if (heightMode == MeasureSpec.EXACTLY) {
//Must be this size
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
height = Math.min(desiredHeight, heightSize);
} else {
//Be whatever you want
height = desiredHeight;
}
setMeasuredDimension(width, height);
}
}
| 31.858333 | 88 | 0.664661 |
83714e31d699efb7d6e338a9ffcbd4d9ef6beee6 | 514 | package com.github.instagram4j.instagram4j.responses.users;
import java.util.List;
import com.github.instagram4j.instagram4j.responses.IGResponse;
import lombok.Data;
@Data
public class UsersBlockedListResponse extends IGResponse {
private List<BlockedUser> blocked_list;
@Data
public static class BlockedUser{
public long user_id;
public String username;
public String full_name;
public String profile_pic_url;
public long block_at;
public boolean is_auto_block_enabled;
}
}
| 24.47619 | 63 | 0.780156 |
d679be72b848c4b6c0cedeed4d4974d50e38468c | 2,034 | /*
* Copyright © 2020 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.cdap.internal.capability;
import io.cdap.cdap.api.app.ApplicationSpecification;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* CapabilityReader interface with methods based on current capability status
*/
public interface CapabilityReader {
/**
* Throws {@link CapabilityNotAvailableException} if all capabilities are not enabled
*
* @param capabilities
* @return
* @throws IOException
*/
void checkAllEnabled(Collection<String> capabilities) throws IOException, CapabilityNotAvailableException;
/**
* Get the configuration map for the capabilities if present
*
* @param capabilities
* @return
* @throws IOException
*/
Map<String, CapabilityConfig> getConfigs(Collection<String> capabilities) throws IOException;
/**
* Throws {@link CapabilityNotAvailableException} if all capabilities in the spec are not enabled
*
* @param appSpec
* @return
* @throws IOException
*/
default void checkAllEnabled(ApplicationSpecification appSpec) throws IOException, CapabilityNotAvailableException {
Set<String> capabilities = appSpec.getPlugins().entrySet().stream()
.flatMap(pluginEntry -> pluginEntry.getValue().getPluginClass().getRequirements().getCapabilities().stream())
.collect(Collectors.toSet());
checkAllEnabled(capabilities);
}
}
| 31.78125 | 118 | 0.743363 |
69c34542645d5cce2303cb73dadbccc1af2c97a2 | 2,075 | package com.invoister.service.dto;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.Objects;
/**
* A DTO for the InvoiceItem entity.
*/
public class InvoiceItemDTO implements Serializable {
private Long id;
@NotNull
private String description;
@NotNull
private Integer quantity;
@NotNull
private Double grossCost;
private Set<InvoiceDTO> invoices = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Double getGrossCost() {
return grossCost;
}
public void setGrossCost(Double grossCost) {
this.grossCost = grossCost;
}
public Set<InvoiceDTO> getInvoices() {
return invoices;
}
public void setInvoices(Set<InvoiceDTO> invoices) {
this.invoices = invoices;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InvoiceItemDTO invoiceItemDTO = (InvoiceItemDTO) o;
if (invoiceItemDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), invoiceItemDTO.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "InvoiceItemDTO{" +
"id=" + getId() +
", description='" + getDescription() + "'" +
", quantity=" + getQuantity() +
", grossCost=" + getGrossCost() +
"}";
}
}
| 21.173469 | 64 | 0.581205 |
fba850eed080a5c8672ce2b5f7730a1251d83673 | 457 | package algorithm.leet_91_105;
import algorithm.TreeNode;
/**
* Created by songheng on 5/6/16.
*/
public class SameTree_100 {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null & q == null ){
return true;
} else if( ( p == null && q!= null)||(p!=null && q==null) ){
return false;
}
return (p.val == q.val) && (isSameTree(p.left,q.left) && isSameTree(p.right,q.right));
}
}
| 22.85 | 94 | 0.551422 |
be3caac737a600b2d2538b2843081a80a624ecf9 | 1,372 | package ru.job4j.tracker;
import java.util.function.Consumer;
/**
* @author Vasily Tungusov
* @version $Id$
* @since 0.1
*/
public class StartUI {
/**
* Получение данных от пользователя.
*/
private final Input input;
/**
* Хранилище заявок.
*/
private final Tracker tracker;
private final Consumer<String> output;
private boolean isWorking = true;
/**
* Конструтор инициализирующий поля.
*
* @param input ввод данных.
* @param tracker хранилище заявок.
* @param output
*/
public StartUI(Input input, Tracker tracker, Consumer<String> output) {
this.input = input;
this.tracker = tracker;
this.output = output;
}
/**
* Основой цикл программы.
*/
public void init() {
MenuTracker menu = new MenuTracker(this.input, this.tracker, output);
menu.fillActions(this);
while (this.isWorking) {
menu.show();
int ask = input.ask("Select:", menu.getRanges());
menu.select(ask);
}
}
public void stop() {
this.isWorking = false;
}
/**
* Запускт программы.
*
* @param args
*/
public static void main(String[] args) {
new StartUI(new ValidateInput(new ConsoleInput()), new Tracker(), System.out::println).init();
}
} | 21.4375 | 102 | 0.573615 |
ab7c9c83bb82574d3dec9823a730c513b8a920bc | 203 | package oo.heranca.desafio;
public class Ferrari extends Carro {
public Ferrari(int velocidadeMaxima) {
super(velocidadeMaxima);
}
@Override
public void acelerar() {
velocidadeAtual += 15;
}
}
| 16.916667 | 39 | 0.73399 |
114bc5975d96d9c96059d1d1dd893bf7a8aa1fa6 | 172 | package com.uNow.exceptions;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus
public class IdNotFoundException extends RuntimeException {
}
| 21.5 | 62 | 0.848837 |
15fd8992475d743b2edeaf69de8eddeba588d31b | 7,418 | package com.example.shalantor.connect4;
/*Shows the fragment where user can register a new account*/
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import java.net.Socket;
import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegisterFragment extends Fragment{
/*Regular expression to check the email validity*/
public static final Pattern VALID_EMAIL_ADDRESS_REGEX =
Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
/*Minimum password length*/
public static final int PASSWORD_MIN_LENGTH = 8;
/*Constants for shared preferences*/
public static final String USER_TYPE = "USER_TYPE";
public static final String USERNAME = "USERNAME";
public static final String EMAIL = "EMAIL";
public Activity activity;
private Socket connectSocket;
private View view;
/*Interface to communicate with register fragment*/
private RegisterFragment.registerFragmentCallback mCallback;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/* Inflate the layout for this fragment*/
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
activity = getActivity();
view = inflater.inflate(R.layout.register_fragment, container, false);
return view;
}
public interface registerFragmentCallback{
void replaceRegisterFragment();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
/* This makes sure that the container activity has implemented
the callback interface. If not, it throws an exception*/
try {
mCallback = (RegisterFragment.registerFragmentCallback) context;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement register interface");
}
}
public void adjustButtons(){
/*Get references to components*/
final EditText usernamePrompt = (EditText) activity.findViewById(R.id.register_username);
final EditText emailPrompt = (EditText) activity.findViewById(R.id.register_email);
final EditText passwordPrompt = (EditText) activity.findViewById(R.id.register_password);
final EditText passwordVerify = (EditText) activity.findViewById(R.id.register_password_verify);
Button registerButton = (Button) activity.findViewById(R.id.register_button_final);
final TextView textView = (TextView) activity.findViewById(R.id.error_messages_register);
final CheckBox remember = (CheckBox) activity.findViewById(R.id.remember_me_register);
/*Add listener to register button*/
registerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*Check if user entered anything in username prompt*/
String usernameInput = usernamePrompt.getText().toString().trim();
if (usernameInput.length() == 0){
String errorMessage = "Please enter a username";
textView.setText(errorMessage, TextView.BufferType.NORMAL);
return;
}
/*Check if email is in right format */
String emailInput = emailPrompt.getText().toString();
Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailInput);
if (!matcher.find()){
String errorMessage = "Please enter a valid email address format";
textView.setText(errorMessage, TextView.BufferType.NORMAL);
return;
}
/*Check if password prompts have the same password*/
String password = passwordPrompt.getText().toString().trim();
String verifyPassword = passwordVerify.getText().toString().trim();
/*Check password length first*/
if (password.length() < PASSWORD_MIN_LENGTH){
String errorMessage = "Password must contain at least 8 characters";
textView.setText(errorMessage, TextView.BufferType.NORMAL);
return;
}
if (!password.equals(verifyPassword)){
String errorMessage = "Passwords don't match";
textView.setText(errorMessage, TextView.BufferType.NORMAL);
return;
}
/*If user clicked remember me then save his credentials*/
if (remember.isChecked()) {
SharedPreferences preferences = activity.getSharedPreferences(activity.getPackageName(), Context.MODE_PRIVATE);
/*Store user data*/
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(USER_TYPE, 0);
editor.putString(USERNAME, usernameInput);
editor.putString(EMAIL, emailInput);
editor.apply();
}
/*Now send message to server and wait for answer*/
NetworkOperationsTask register = new NetworkOperationsTask(connectSocket,activity);
String result = "";
try {
result = register.execute("0","0","0",usernameInput,emailInput,password).get();
}
catch(ExecutionException ex){
Log.d("EXECUTION","Executionexception occured");
}
catch(InterruptedException ex){
Log.d("INTERRUPT","Interrupted exception occured");
}
/*Check result*/
if(result.equals(AccountManagementUtils.OK)) {
/*Now replace fragment*/
mCallback.replaceRegisterFragment();
}
else if (result.equals(AccountManagementUtils.ERROR)){
textView.setText(AccountManagementUtils.ALREADY_IN_USE_MESSAGE, TextView.BufferType.NORMAL);
}
else if(result.equals(AccountManagementUtils.SOCKET_TIMEOUT)){
textView.setText(AccountManagementUtils.SOCKET_TIMEOUT_MESSAGE, TextView.BufferType.NORMAL);
}
else if(result.equals(AccountManagementUtils.NO_BIND)){
textView.setText(AccountManagementUtils.NO_BIND_MESSAGE, TextView.BufferType.NORMAL);
}
else {
textView.setText(AccountManagementUtils.IOEXCEPTION_MESSAGE, TextView.BufferType.NORMAL);
}
}
});
}
/*Get socket from activity*/
public void setConnectSocket(Socket socket){
connectSocket = socket;
}
}
| 40.983425 | 131 | 0.624697 |
f5d76de51f1c787f9436627959a9d8de5cc5f9ff | 2,323 | package leetcode.interval;
import java.util.Arrays;
import java.util.PriorityQueue;
public class MeetingRoomsII {
/*
public int minMeetingRooms(int[][] intervals) {
if (intervals == null || intervals.length == 0)
return 0;
Arrays.sort(intervals, (i1, i2) -> i1[0] - i2[0]);
PriorityQueue<int[]> queue = new PriorityQueue<>((i1, i2) -> i1[1] - i2[1]);
queue.offer(intervals[0]);
for(int i = 0; i < intervals.length; i++) {
if (intervals[i][0] >= queue.peek()[1]) {
queue.poll();
}
queue.offer(intervals[i]);
}
return queue.size();
}*/
// sort the arrays by start time
// use priorityQueue to store finish time of each meeting
// poll() the value if peek() is earlier than start time of current meeting
// keep adding finish time into pq
public int minMeetingRooms(int[][] intervals) {
if (intervals == null || intervals.length == 0)
return 0;
Arrays.sort(intervals, (i1, i2) -> i1[0] - i2[0]);
PriorityQueue<Integer> queue = new PriorityQueue<>();
for (int[] interval : intervals) {
if (queue.size() > 0 && queue.peek() <= interval[0])
queue.poll();
queue.offer(interval[1]);
}
return queue.size();
}
public int minMeetingRooms_2r(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int i = 0; i < intervals.length; i++) {
int[] interval = intervals[i];
if(pq.size() != 0 && pq.peek() <= interval[0]) {
pq.poll();
}
pq.offer(interval[1]);
}
return pq.size();
}
public int minMeetingRooms_3r(int[][] intervals) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
for(int[] interval : intervals) {
int start = interval[0];
int end = interval[1];
if(!pq.isEmpty() && pq.peek() <= start) {
pq.poll();
}
pq.offer(end);
}
return pq.size();
}
}
| 28.679012 | 84 | 0.500215 |
7ad451e223e50d371b2f93629854129fa952987f | 702 | package de.wackernagel.dkq.utils;
import android.content.Context;
import android.content.pm.PackageManager;
public class AppUtils {
public static int getVersionCode(final Context context ) {
try {
return context.getPackageManager().getPackageInfo( context.getPackageName(), 0).versionCode;
} catch (PackageManager.NameNotFoundException e) {
return 0;
}
}
public static String getVersionName(final Context context ) {
try {
return context.getPackageManager().getPackageInfo( context.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
return "?";
}
}
}
| 28.08 | 104 | 0.660969 |
8a0d8a126f508026517a28fb994fcd8ba1498219 | 1,221 | package tr.com.poc.temporaldate.core.validation.validator;
import java.math.BigDecimal;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import tr.com.poc.temporaldate.core.annotations.validation.FieldLength;
/**
* Created by aziz on 11/27/17.
*/
public class FieldLenghtValidator extends ExistValidator implements ConstraintValidator<FieldLength, Number>
{
private String[] method;
private int length;
private int scale;
@Override
public void initialize(FieldLength constraint)
{
this.method = constraint.method();
this.length = constraint.length();
this.scale = constraint.scale();
}
@Override
public boolean isValid(Number value, ConstraintValidatorContext constraintValidatorContext)
{
if (isCurrentToBeValidated(method))
{
if (value != null)
{
if (value instanceof BigDecimal)
{
BigDecimal bd = (BigDecimal) value;
return !((bd.precision() - bd.scale()) > (length - scale) || bd.scale() > scale);
}
else
{
String aLong = String.valueOf(value);
return (aLong.length() <= length);
}
}
else// if fields value is null consider as valid
{
return true;
}
}
return true;
}
}
| 22.611111 | 108 | 0.707617 |
b1e7796ab8addf7534860dd9d495b0ecd1845465 | 8,200 | /*
* XML Type: ArrayOfSyncAction
* Namespace: http://schemas.microsoft.com/crm/2011/Contracts
* Java type: com.microsoft.schemas.crm._2011.contracts.ArrayOfSyncAction
*
* Automatically generated - do not modify.
*/
package com.microsoft.schemas.crm._2011.contracts.impl;
/**
* An XML ArrayOfSyncAction(@http://schemas.microsoft.com/crm/2011/Contracts).
*
* This is a complex type.
*/
public class ArrayOfSyncActionImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements com.microsoft.schemas.crm._2011.contracts.ArrayOfSyncAction
{
private static final long serialVersionUID = 1L;
public ArrayOfSyncActionImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName SYNCACTION$0 =
new javax.xml.namespace.QName("http://schemas.microsoft.com/crm/2011/Contracts", "SyncAction");
/**
* Gets array of all "SyncAction" elements
*/
public com.microsoft.schemas.crm._2011.contracts.SyncAction.Enum[] getSyncActionArray()
{
synchronized (monitor())
{
check_orphaned();
java.util.List targetList = new java.util.ArrayList();
get_store().find_all_element_users(SYNCACTION$0, targetList);
com.microsoft.schemas.crm._2011.contracts.SyncAction.Enum[] result = new com.microsoft.schemas.crm._2011.contracts.SyncAction.Enum[targetList.size()];
for (int i = 0, len = targetList.size() ; i < len ; i++)
result[i] = (com.microsoft.schemas.crm._2011.contracts.SyncAction.Enum)((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getEnumValue();
return result;
}
}
/**
* Gets ith "SyncAction" element
*/
public com.microsoft.schemas.crm._2011.contracts.SyncAction.Enum getSyncActionArray(int i)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(SYNCACTION$0, i);
if (target == null)
{
throw new IndexOutOfBoundsException();
}
return (com.microsoft.schemas.crm._2011.contracts.SyncAction.Enum)target.getEnumValue();
}
}
/**
* Gets (as xml) array of all "SyncAction" elements
*/
public com.microsoft.schemas.crm._2011.contracts.SyncAction[] xgetSyncActionArray()
{
synchronized (monitor())
{
check_orphaned();
java.util.List targetList = new java.util.ArrayList();
get_store().find_all_element_users(SYNCACTION$0, targetList);
com.microsoft.schemas.crm._2011.contracts.SyncAction[] result = new com.microsoft.schemas.crm._2011.contracts.SyncAction[targetList.size()];
targetList.toArray(result);
return result;
}
}
/**
* Gets (as xml) ith "SyncAction" element
*/
public com.microsoft.schemas.crm._2011.contracts.SyncAction xgetSyncActionArray(int i)
{
synchronized (monitor())
{
check_orphaned();
com.microsoft.schemas.crm._2011.contracts.SyncAction target = null;
target = (com.microsoft.schemas.crm._2011.contracts.SyncAction)get_store().find_element_user(SYNCACTION$0, i);
if (target == null)
{
throw new IndexOutOfBoundsException();
}
return target;
}
}
/**
* Returns number of "SyncAction" element
*/
public int sizeOfSyncActionArray()
{
synchronized (monitor())
{
check_orphaned();
return get_store().count_elements(SYNCACTION$0);
}
}
/**
* Sets array of all "SyncAction" element
*/
public void setSyncActionArray(com.microsoft.schemas.crm._2011.contracts.SyncAction.Enum[] syncActionArray)
{
synchronized (monitor())
{
check_orphaned();
arraySetterHelper(syncActionArray, SYNCACTION$0);
}
}
/**
* Sets ith "SyncAction" element
*/
public void setSyncActionArray(int i, com.microsoft.schemas.crm._2011.contracts.SyncAction.Enum syncAction)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(SYNCACTION$0, i);
if (target == null)
{
throw new IndexOutOfBoundsException();
}
target.setEnumValue(syncAction);
}
}
/**
* Sets (as xml) array of all "SyncAction" element
*/
public void xsetSyncActionArray(com.microsoft.schemas.crm._2011.contracts.SyncAction[]syncActionArray)
{
synchronized (monitor())
{
check_orphaned();
arraySetterHelper(syncActionArray, SYNCACTION$0);
}
}
/**
* Sets (as xml) ith "SyncAction" element
*/
public void xsetSyncActionArray(int i, com.microsoft.schemas.crm._2011.contracts.SyncAction syncAction)
{
synchronized (monitor())
{
check_orphaned();
com.microsoft.schemas.crm._2011.contracts.SyncAction target = null;
target = (com.microsoft.schemas.crm._2011.contracts.SyncAction)get_store().find_element_user(SYNCACTION$0, i);
if (target == null)
{
throw new IndexOutOfBoundsException();
}
target.set(syncAction);
}
}
/**
* Inserts the value as the ith "SyncAction" element
*/
public void insertSyncAction(int i, com.microsoft.schemas.crm._2011.contracts.SyncAction.Enum syncAction)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target =
(org.apache.xmlbeans.SimpleValue)get_store().insert_element_user(SYNCACTION$0, i);
target.setEnumValue(syncAction);
}
}
/**
* Appends the value as the last "SyncAction" element
*/
public void addSyncAction(com.microsoft.schemas.crm._2011.contracts.SyncAction.Enum syncAction)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().add_element_user(SYNCACTION$0);
target.setEnumValue(syncAction);
}
}
/**
* Inserts and returns a new empty value (as xml) as the ith "SyncAction" element
*/
public com.microsoft.schemas.crm._2011.contracts.SyncAction insertNewSyncAction(int i)
{
synchronized (monitor())
{
check_orphaned();
com.microsoft.schemas.crm._2011.contracts.SyncAction target = null;
target = (com.microsoft.schemas.crm._2011.contracts.SyncAction)get_store().insert_element_user(SYNCACTION$0, i);
return target;
}
}
/**
* Appends and returns a new empty value (as xml) as the last "SyncAction" element
*/
public com.microsoft.schemas.crm._2011.contracts.SyncAction addNewSyncAction()
{
synchronized (monitor())
{
check_orphaned();
com.microsoft.schemas.crm._2011.contracts.SyncAction target = null;
target = (com.microsoft.schemas.crm._2011.contracts.SyncAction)get_store().add_element_user(SYNCACTION$0);
return target;
}
}
/**
* Removes the ith "SyncAction" element
*/
public void removeSyncAction(int i)
{
synchronized (monitor())
{
check_orphaned();
get_store().remove_element(SYNCACTION$0, i);
}
}
}
| 34.745763 | 168 | 0.593415 |
5935eb19ad11df01507119c684a429647ca064de | 4,309 | /* See LICENSE.md for license information */
package org.ice4j.attribute;
import java.util.Arrays;
/**
* The USERNAME attribute is used for message integrity.
* The value of USERNAME is a variable length value.
*
* @author Sebastien Vincent
* @author Emil Ivov
*/
public class UsernameAttribute extends Attribute {
//private static final Logger logger = Logger.getLogger(UsernameAttribute.class.getName());
/**
* Username value.
*/
private byte[] username;
/**
* Constructor.
*/
UsernameAttribute() {
super(Attribute.Type.USERNAME);
}
/**
* Copies the value of the username attribute from the specified
* attributeValue.
*
* @param attributeValue a binary array containing this attribute's
* field values and NOT containing the attribute header.
* @param offset the position where attribute values begin (most often
* offset is equal to the index of the first byte after length)
* @param length the length of the binary array.
*/
@Override
void decodeAttributeBody(byte[] attributeValue, int offset, int length) {
//logger.info("decodeAttributeBody offset: " + (int) offset + " len: " + (int) length + " value: " + new String(attributeValue) + "\n" + javax.xml.bind.DatatypeConverter.printHexBinary(attributeValue) + "\n" + Arrays.toString(attributeValue));
username = new byte[length];
System.arraycopy(attributeValue, offset, username, 0, length);
//logger.info("decodeAttributeBody username: " + Arrays.toString(username));
}
/**
* Returns a binary representation of this attribute.
*
* @return a binary representation of this attribute.
*/
public byte[] encode() {
byte binValue[] = new byte[HEADER_LENGTH + getDataLength()
//add padding
+ (4 - getDataLength() % 4) % 4];
//Type
int type = getAttributeType().getType();
binValue[0] = (byte) (type >> 8);
binValue[1] = (byte) (type & 0x00FF);
//Length
binValue[2] = (byte) (getDataLength() >> 8);
binValue[3] = (byte) (getDataLength() & 0x00FF);
//username
System.arraycopy(username, 0, binValue, 4, getDataLength());
return binValue;
}
/**
* Returns the length of this attribute's body.
*
* @return the length of this attribute's value.
*/
public int getDataLength() {
return (char) username.length;
}
/**
* Returns a (cloned) byte array containing the data value of the username
* attribute.
*
* @return the binary array containing the username.
*/
public byte[] getUsername() {
return (username == null) ? null : username.clone();
}
/**
* Copies the specified binary array into the the data value of the username
* attribute.
*
* @param username the binary array containing the username.
*/
public void setUsername(byte[] username) {
if (username == null) {
this.username = null;
return;
}
this.username = new byte[username.length];
System.arraycopy(username, 0, this.username, 0, username.length);
}
/**
* Compares two STUN Attributes. Two attributes are considered equal when
* they have the same type length and value.
*
* @param obj the object to compare this attribute with.
*
* @return true if the attributes are equal and false otherwise.
*/
public boolean equals(Object obj) {
if (!(obj instanceof UsernameAttribute))
return false;
if (obj == this)
return true;
UsernameAttribute att = (UsernameAttribute) obj;
//logger.info("Equality - type: " + att.getAttributeType() + " != " + getAttributeType() + " length: " + att.getDataLength() + " != " + getDataLength() + " array equal: " + Arrays.equals(att.username, username));
if (att.getAttributeType() != getAttributeType() || att.getDataLength() != getDataLength() || !Arrays.equals(att.username, username))
return false;
return true;
}
@Override
public String toString() {
return "UsernameAttribute [username=" + new String(username) + "]";
}
}
| 31.918519 | 251 | 0.615456 |
ede243106531f5146b511b00fefb5d9814b56ab9 | 821 | package com.google.android.play.core.internal;
import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.IBinder;
final class ap implements ServiceConnection {
/* renamed from: a reason: collision with root package name */
final /* synthetic */ aq f1121a;
/* synthetic */ ap(aq aqVar) {
this.f1121a = aqVar;
}
public final void onServiceConnected(ComponentName componentName, IBinder iBinder) {
this.f1121a.c.d("ServiceConnectionImpl.onServiceConnected(%s)", componentName);
this.f1121a.r(new an(this, iBinder));
}
public final void onServiceDisconnected(ComponentName componentName) {
this.f1121a.c.d("ServiceConnectionImpl.onServiceDisconnected(%s)", componentName);
this.f1121a.r(new ao(this));
}
}
| 31.576923 | 90 | 0.713764 |
71b22b0d6d18b7e488b159087b8d34f764ac6c13 | 40,130 | /*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file in the root of the source tree. An additional
* intellectual property rights grant can be found in the file PATENTS. All
* contributing project authors may be found in the AUTHORS file in the root of
* the source tree.
*/
/*
* VoiceEngine Android test application. It starts either auto test or acts like
* a GUI test.
*/
package org.webrtc.voiceengine.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class AndroidTest extends Activity {
private byte[] _playBuffer = null;
private short[] _circBuffer = new short[8000]; // can hold 50 frames
private int _recIndex = 0;
private int _playIndex = 0;
// private int _streamVolume = 4;
private int _maxVolume = 0; // Android max level (commonly 5)
// VoE level (0-255), corresponds to level 4 out of 5
private int _volumeLevel = 204;
private Thread _playThread;
private Thread _recThread;
private Thread _autotestThread;
private static AudioTrack _at;
private static AudioRecord _ar;
private File _fr = null;
private FileInputStream _in = null;
private boolean _isRunningPlay = false;
private boolean _isRunningRec = false;
private boolean _settingSet = true;
private boolean _isCallActive = false;
private boolean _runAutotest = false; // ENABLE AUTOTEST HERE!
private int _channel = -1;
private int _codecIndex = 0;
private int _ecIndex = 0;
private int _nsIndex = 0;
private int _agcIndex = 0;
private int _vadIndex = 0;
private int _audioIndex = 3;
private int _settingMenu = 0;
private int _receivePort = 1234;
private int _destinationPort = 1234;
private String _destinationIP = "127.0.0.1";
// "Build" settings
private final boolean _playFromFile = false;
// Set to true to send data to native code and back
private final boolean _runThroughNativeLayer = true;
private final boolean enableSend = true;
private final boolean enableReceive = true;
private final boolean useNativeThread = false;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.TextView01);
tv.setText("");
final EditText ed = (EditText) findViewById(R.id.EditText01);
ed.setWidth(200);
ed.setText(_destinationIP);
final Button buttonStart = (Button) findViewById(R.id.Button01);
buttonStart.setWidth(200);
if (_runAutotest) {
buttonStart.setText("Run test");
} else {
buttonStart.setText("Start Call");
}
// button.layout(50, 50, 100, 40);
buttonStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (_runAutotest) {
startAutoTest();
} else {
if (_isCallActive) {
if (stopCall() != -1) {
_isCallActive = false;
buttonStart.setText("Start Call");
}
} else {
_destinationIP = ed.getText().toString();
if (startCall() != -1) {
_isCallActive = true;
buttonStart.setText("Stop Call");
}
}
}
// displayTextFromFile();
// recordAudioToFile();
// if(!_playFromFile)
// {
// recAudioInThread();
// }
// playAudioInThread();
}
});
final Button buttonStop = (Button) findViewById(R.id.Button02);
buttonStop.setWidth(200);
buttonStop.setText("Close app");
buttonStop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!_runAutotest) {
ShutdownVoE();
}
// This call terminates and should close the activity
finish();
// playAudioFromFile();
// if(!_playFromFile)
// {
// stopRecAudio();
// }
// stopPlayAudio();
}
});
String ap1[] = {"EC off", "AECM"};
final ArrayAdapter<String> adapterAp1 = new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_dropdown_item,
ap1);
String ap2[] =
{"NS off", "NS low", "NS moderate", "NS high",
"NS very high"};
final ArrayAdapter<String> adapterAp2 = new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_dropdown_item,
ap2);
String ap3[] = {"AGC off", "AGC adaptive", "AGC fixed"};
final ArrayAdapter<String> adapterAp3 = new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_dropdown_item,
ap3);
String ap4[] =
{"VAD off", "VAD conventional", "VAD high rate",
"VAD mid rate", "VAD low rate"};
final ArrayAdapter<String> adapterAp4 = new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_dropdown_item,
ap4);
String codecs[] = {"iSAC", "PCMU", "PCMA", "iLBC"};
final ArrayAdapter<String> adapterCodecs = new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_dropdown_item,
codecs);
final Spinner spinnerSettings1 = (Spinner) findViewById(R.id.Spinner01);
final Spinner spinnerSettings2 = (Spinner) findViewById(R.id.Spinner02);
spinnerSettings1.setMinimumWidth(200);
String settings[] =
{"Codec", "Echo Control", "Noise Suppression",
"Automatic Gain Control",
"Voice Activity Detection"};
ArrayAdapter<String> adapterSettings1 = new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_dropdown_item,
settings);
spinnerSettings1.setAdapter(adapterSettings1);
spinnerSettings1.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView adapterView, View view,
int position, long id) {
_settingMenu = position;
_settingSet = false;
if (position == 0) {
spinnerSettings2.setAdapter(adapterCodecs);
spinnerSettings2.setSelection(_codecIndex);
}
if (position == 1) {
spinnerSettings2.setAdapter(adapterAp1);
spinnerSettings2.setSelection(_ecIndex);
}
if (position == 2) {
spinnerSettings2.setAdapter(adapterAp2);
spinnerSettings2.setSelection(_nsIndex);
}
if (position == 3) {
spinnerSettings2.setAdapter(adapterAp3);
spinnerSettings2.setSelection(_agcIndex);
}
if (position == 4) {
spinnerSettings2.setAdapter(adapterAp4);
spinnerSettings2.setSelection(_vadIndex);
}
}
public void onNothingSelected(AdapterView adapterView) {
WebrtcLog("No setting1 selected");
}
});
spinnerSettings2.setMinimumWidth(200);
ArrayAdapter<String> adapterSettings2 = new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_dropdown_item,
codecs);
spinnerSettings2.setAdapter(adapterSettings2);
spinnerSettings2.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView adapterView, View view,
int position, long id) {
// avoid unintentional setting
if (_settingSet == false) {
_settingSet = true;
return;
}
// Change volume
if (_settingMenu == 0) {
WebrtcLog("Selected audio " + position);
setAudioProperties(position);
spinnerSettings2.setSelection(_audioIndex);
}
// Change codec
if (_settingMenu == 1) {
_codecIndex = position;
WebrtcLog("Selected codec " + position);
if (0 != SetSendCodec(_channel, _codecIndex)) {
WebrtcLog("VoE set send codec failed");
}
}
// Change EC
if (_settingMenu == 2) {
boolean enable = true;
int ECmode = 5; // AECM
int AESmode = 0;
_ecIndex = position;
WebrtcLog("Selected EC " + position);
if (position == 0) {
enable = false;
}
if (position > 1) {
ECmode = 4; // AES
AESmode = position - 1;
}
if (0 != SetECStatus(enable, ECmode)) {
WebrtcLog("VoE set EC status failed");
}
}
// Change NS
if (_settingMenu == 3) {
boolean enable = true;
_nsIndex = position;
WebrtcLog("Selected NS " + position);
if (position == 0) {
enable = false;
}
if (0 != SetNSStatus(enable, position + 2)) {
WebrtcLog("VoE set NS status failed");
}
}
// Change AGC
if (_settingMenu == 4) {
boolean enable = true;
_agcIndex = position;
WebrtcLog("Selected AGC " + position);
if (position == 0) {
enable = false;
position = 1; // default
}
if (0 != SetAGCStatus(enable, position + 2)) {
WebrtcLog("VoE set AGC status failed");
}
}
// Change VAD
if (_settingMenu == 5) {
boolean enable = true;
_vadIndex = position;
WebrtcLog("Selected VAD " + position);
if (position == 0) {
enable = false;
position++;
}
if (0 != SetVADStatus(_channel, enable, position - 1)) {
WebrtcLog("VoE set VAD status failed");
}
}
}
public void onNothingSelected(AdapterView adapterView) {
}
});
// Setup VoiceEngine
if (!_runAutotest && !useNativeThread) SetupVoE();
// Suggest to use the voice call audio stream for hardware volume
// controls
setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
// Get max Android volume and adjust default volume to map exactly to an
// Android level
AudioManager am =
(AudioManager) getSystemService(Context.AUDIO_SERVICE);
_maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);
if (_maxVolume <= 0) {
WebrtcLog("Could not get max volume!");
} else {
int androidVolumeLevel = (_volumeLevel * _maxVolume) / 255;
_volumeLevel = (androidVolumeLevel * 255) / _maxVolume;
}
WebrtcLog("Started Webrtc Android Test");
}
// Will be called when activity is shutdown.
// NOTE: Activity may be killed without this function being called,
// but then we should not need to clean up.
protected void onDestroy() {
super.onDestroy();
// ShutdownVoE();
}
private void SetupVoE() {
// Create VoiceEngine
Create(); // Error logging is done in native API wrapper
// Initialize
if (0 != Init(false, false)) {
WebrtcLog("VoE init failed");
}
// Create channel
_channel = CreateChannel();
if (0 != _channel) {
WebrtcLog("VoE create channel failed");
}
}
private void ShutdownVoE() {
// Delete channel
if (0 != DeleteChannel(_channel)) {
WebrtcLog("VoE delete channel failed");
}
// Terminate
if (0 != Terminate()) {
WebrtcLog("VoE terminate failed");
}
// Delete VoiceEngine
Delete(); // Error logging is done in native API wrapper
}
int startCall() {
if (useNativeThread == true) {
Create();
return 0;
}
if (enableReceive == true) {
// Set local receiver
if (0 != SetLocalReceiver(_channel, _receivePort)) {
WebrtcLog("VoE set local receiver failed");
}
if (0 != StartListen(_channel)) {
WebrtcLog("VoE start listen failed");
return -1;
}
// Route audio to earpiece
if (0 != SetLoudspeakerStatus(false)) {
WebrtcLog("VoE set louspeaker status failed");
return -1;
}
/*
* WebrtcLog("VoE start record now"); if (0 !=
* StartRecordingPlayout(_channel, "/sdcard/singleUserDemoOut.pcm",
* false)) { WebrtcLog("VoE Recording Playout failed"); }
* WebrtcLog("VoE start Recording Playout end");
*/
// Start playout
if (0 != StartPlayout(_channel)) {
WebrtcLog("VoE start playout failed");
return -1;
}
// Start playout file
// if (0 != StartPlayingFileLocally(_channel,
// "/sdcard/singleUserDemo.pcm", true)) {
// WebrtcLog("VoE start playout file failed");
// return -1;
// }
}
if (enableSend == true) {
if (0 != SetSendDestination(_channel, _destinationPort,
_destinationIP)) {
WebrtcLog("VoE set send destination failed");
return -1;
}
if (0 != SetSendCodec(_channel, _codecIndex)) {
WebrtcLog("VoE set send codec failed");
return -1;
}
/*
* if (0 != StartPlayingFileAsMicrophone(_channel,
* "/sdcard/singleUserDemo.pcm", true)) {
* WebrtcLog("VoE start playing file as microphone failed"); }
*/
if (0 != StartSend(_channel)) {
WebrtcLog("VoE start send failed");
return -1;
}
// if (0 != StartPlayingFileAsMicrophone(_channel,
// "/sdcard/singleUserDemo.pcm", true)) {
// WebrtcLog("VoE start playing file as microphone failed");
// return -1;
// }
}
return 0;
}
int stopCall() {
if (useNativeThread == true) {
Delete();
return 0;
}
if (enableSend == true) {
// Stop playing file as microphone
/*
* if (0 != StopPlayingFileAsMicrophone(_channel)) {
* WebrtcLog("VoE stop playing file as microphone failed"); return
* -1; }
*/
// Stop send
if (0 != StopSend(_channel)) {
WebrtcLog("VoE stop send failed");
return -1;
}
}
if (enableReceive == true) {
// if (0 != StopRecordingPlayout(_channel)) {
// WebrtcLog("VoE stop Recording Playout failed");
// }
// WebrtcLog("VoE stop Recording Playout ended");
// Stop listen
if (0 != StopListen(_channel)) {
WebrtcLog("VoE stop listen failed");
return -1;
}
// Stop playout file
// if (0 != StopPlayingFileLocally(_channel)) {
// WebrtcLog("VoE stop playout file failed");
// return -1;
// }
// Stop playout
if (0 != StopPlayout(_channel)) {
WebrtcLog("VoE stop playout failed");
return -1;
}
// Route audio to loudspeaker
if (0 != SetLoudspeakerStatus(true)) {
WebrtcLog("VoE set louspeaker status failed");
return -1;
}
}
return 0;
}
int startAutoTest() {
_autotestThread = new Thread(_autotestProc);
_autotestThread.start();
return 0;
}
private Runnable _autotestProc = new Runnable() {
public void run() {
// TODO(xians): choose test from GUI
// 1 = standard, not used
// 2 = extended, 2 = base
RunAutoTest(1, 2);
}
};
int setAudioProperties(int val) {
// AudioManager am = (AudioManager)
// getSystemService(Context.AUDIO_SERVICE);
if (val == 0) {
// _streamVolume =
// am.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
// am.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
// (_streamVolume+1), 0);
int androidVolumeLevel = (_volumeLevel * _maxVolume) / 255;
if (androidVolumeLevel < _maxVolume) {
_volumeLevel = ((androidVolumeLevel + 1) * 255) / _maxVolume;
if (0 != SetSpeakerVolume(_volumeLevel)) {
WebrtcLog("VoE set speaker volume failed");
}
}
} else if (val == 1) {
// _streamVolume =
// am.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
// am.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
// (_streamVolume-1), 0);
int androidVolumeLevel = (_volumeLevel * _maxVolume) / 255;
if (androidVolumeLevel > 0) {
_volumeLevel = ((androidVolumeLevel - 1) * 255) / _maxVolume;
if (0 != SetSpeakerVolume(_volumeLevel)) {
WebrtcLog("VoE set speaker volume failed");
}
}
} else if (val == 2) {
// route audio to back speaker
if (0 != SetLoudspeakerStatus(true)) {
WebrtcLog("VoE set loudspeaker status failed");
}
_audioIndex = 2;
} else if (val == 3) {
// route audio to earpiece
if (0 != SetLoudspeakerStatus(false)) {
WebrtcLog("VoE set loudspeaker status failed");
}
_audioIndex = 3;
}
return 0;
}
int displayTextFromFile() {
TextView tv = (TextView) findViewById(R.id.TextView01);
FileReader fr = null;
char[] fileBuffer = new char[64];
try {
fr = new FileReader("/sdcard/test.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
tv.setText("File not found!");
}
try {
fr.read(fileBuffer);
} catch (IOException e) {
e.printStackTrace();
}
String readString = new String(fileBuffer);
tv.setText(readString);
// setContentView(tv);
return 0;
}
int recordAudioToFile() {
File fr = null;
// final to be reachable within onPeriodicNotification
byte[] recBuffer = new byte[320];
int recBufSize =
AudioRecord.getMinBufferSize(16000,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT);
AudioRecord rec =
new AudioRecord(MediaRecorder.AudioSource.MIC, 16000,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT,
recBufSize);
fr = new File("/sdcard/record.pcm");
FileOutputStream out = null;
try {
out = new FileOutputStream(fr);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
// start recording
try {
rec.startRecording();
} catch (IllegalStateException e) {
e.printStackTrace();
}
for (int i = 0; i < 550; i++) {
// note, there is a short version of write as well!
int wrBytes = rec.read(recBuffer, 0, 320);
try {
out.write(recBuffer);
} catch (IOException e) {
e.printStackTrace();
}
}
// stop playout
try {
rec.stop();
} catch (IllegalStateException e) {
e.printStackTrace();
}
return 0;
}
int playAudioFromFile() {
File fr = null;
// final to be reachable within onPeriodicNotification
// final byte[] playBuffer = new byte [320000];
// final to be reachable within onPeriodicNotification
final byte[] playBuffer = new byte[320];
final int playBufSize =
AudioTrack.getMinBufferSize(16000,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT);
// final int playBufSize = 1920; // 100 ms buffer
// byte[] playBuffer = new byte [playBufSize];
final AudioTrack play =
new AudioTrack(AudioManager.STREAM_VOICE_CALL, 16000,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT,
playBufSize, AudioTrack.MODE_STREAM);
// implementation of the playpos callback functions
play.setPlaybackPositionUpdateListener(
new AudioTrack.OnPlaybackPositionUpdateListener() {
int count = 0;
public void onPeriodicNotification(AudioTrack track) {
// int wrBytes = play.write(playBuffer, count, 320);
count += 320;
}
public void onMarkerReached(AudioTrack track) {
}
});
// set the notification period = 160 samples
// int ret = play.setPositionNotificationPeriod(160);
fr = new File("/sdcard/record.pcm");
FileInputStream in = null;
try {
in = new FileInputStream(fr);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
// try {
// in.read(playBuffer);
// } catch (IOException e) {
// e.printStackTrace();
// }
// play all at once
// int wrBytes = play.write(playBuffer, 0, 320000);
// start playout
try {
play.play();
} catch (IllegalStateException e) {
e.printStackTrace();
}
// returns the number of samples that has been written
// int headPos = play.getPlaybackHeadPosition();
// play with multiple writes
for (int i = 0; i < 500; i++) {
try {
in.read(playBuffer);
} catch (IOException e) {
e.printStackTrace();
}
// note, there is a short version of write as well!
int wrBytes = play.write(playBuffer, 0, 320);
Log.d("testWrite", "wrote");
}
// stop playout
try {
play.stop();
} catch (IllegalStateException e) {
e.printStackTrace();
}
return 0;
}
int playAudioInThread() {
if (_isRunningPlay) {
return 0;
}
// File fr = null;
// final byte[] playBuffer = new byte[320];
if (_playFromFile) {
_playBuffer = new byte[320];
} else {
// reset index
_playIndex = 0;
}
// within
// onPeriodicNotification
// Log some info (static)
WebrtcLog("Creating AudioTrack object");
final int minPlayBufSize =
AudioTrack.getMinBufferSize(16000,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT);
WebrtcLog("Min play buf size = " + minPlayBufSize);
WebrtcLog("Min volume = " + AudioTrack.getMinVolume());
WebrtcLog("Max volume = " + AudioTrack.getMaxVolume());
WebrtcLog("Native sample rate = "
+ AudioTrack.getNativeOutputSampleRate(
AudioManager.STREAM_VOICE_CALL));
final int playBufSize = minPlayBufSize; // 3200; // 100 ms buffer
// byte[] playBuffer = new byte [playBufSize];
try {
_at = new AudioTrack(
AudioManager.STREAM_VOICE_CALL,
16000,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT,
playBufSize, AudioTrack.MODE_STREAM);
} catch (Exception e) {
WebrtcLog(e.getMessage());
}
// Log some info (non-static)
WebrtcLog("Notification marker pos = "
+ _at.getNotificationMarkerPosition());
WebrtcLog("Play head pos = " + _at.getPlaybackHeadPosition());
WebrtcLog("Pos notification dt = "
+ _at.getPositionNotificationPeriod());
WebrtcLog("Playback rate = " + _at.getPlaybackRate());
WebrtcLog("Sample rate = " + _at.getSampleRate());
// implementation of the playpos callback functions
// _at.setPlaybackPositionUpdateListener(
// new AudioTrack.OnPlaybackPositionUpdateListener() {
//
// int count = 3200;
//
// public void onPeriodicNotification(AudioTrack track) {
// // int wrBytes = play.write(playBuffer, count, 320);
// count += 320;
// }
//
// public void onMarkerReached(AudioTrack track) {
// }
// });
// set the notification period = 160 samples
// int ret = _at.setPositionNotificationPeriod(160);
if (_playFromFile) {
_fr = new File("/sdcard/singleUserDemo.pcm");
try {
_in = new FileInputStream(_fr);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
// try {
// in.read(playBuffer);
// } catch (IOException e) {
// e.printStackTrace();
// }
_isRunningPlay = true;
// buffer = new byte[3200];
_playThread = new Thread(_playProc);
// ar.startRecording();
// bytesRead = 3200;
// recording = true;
_playThread.start();
return 0;
}
int stopPlayAudio() {
if (!_isRunningPlay) {
return 0;
}
_isRunningPlay = false;
return 0;
}
private Runnable _playProc = new Runnable() {
public void run() {
// set high thread priority
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
// play all at once
// int wrBytes = play.write(playBuffer, 0, 320000);
// fill the buffer
// play.write(playBuffer, 0, 3200);
// play.flush();
// start playout
try {
_at.play();
} catch (IllegalStateException e) {
e.printStackTrace();
}
// play with multiple writes
int i = 0;
for (; i < 3000 && _isRunningPlay; i++) {
if (_playFromFile) {
try {
_in.read(_playBuffer);
} catch (IOException e) {
e.printStackTrace();
}
int wrBytes = _at.write(_playBuffer, 0 /* i * 320 */, 320);
} else {
int wrSamples =
_at.write(_circBuffer, _playIndex * 160,
160);
// WebrtcLog("Played 10 ms from buffer, _playIndex = " +
// _playIndex);
// WebrtcLog("Diff = " + (_recIndex - _playIndex));
if (_playIndex == 49) {
_playIndex = 0;
} else {
_playIndex += 1;
}
}
// WebrtcLog("Wrote 10 ms to buffer, head = "
// + _at.getPlaybackHeadPosition());
}
// stop playout
try {
_at.stop();
} catch (IllegalStateException e) {
e.printStackTrace();
}
// returns the number of samples that has been written
WebrtcLog("Test stopped, i = " + i + ", head = "
+ _at.getPlaybackHeadPosition());
int headPos = _at.getPlaybackHeadPosition();
// flush the buffers
_at.flush();
// release the object
_at.release();
_at = null;
// try {
// Thread.sleep() must be within a try - catch block
// Thread.sleep(3000);
// }catch (Exception e){
// System.out.println(e.getMessage());
// }
_isRunningPlay = false;
}
};
int recAudioInThread() {
if (_isRunningRec) {
return 0;
}
// within
// onPeriodicNotification
// reset index
_recIndex = 20;
// Log some info (static)
WebrtcLog("Creating AudioRecord object");
final int minRecBufSize = AudioRecord.getMinBufferSize(16000,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT);
WebrtcLog("Min rec buf size = " + minRecBufSize);
// WebrtcLog("Min volume = " + AudioTrack.getMinVolume());
// WebrtcLog("Max volume = " + AudioTrack.getMaxVolume());
// WebrtcLog("Native sample rate = "
// + AudioRecord
// .getNativeInputSampleRate(AudioManager.STREAM_VOICE_CALL));
final int recBufSize = minRecBufSize; // 3200; // 100 ms buffer
try {
_ar = new AudioRecord(
MediaRecorder.AudioSource.MIC,
16000,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT,
recBufSize);
} catch (Exception e) {
WebrtcLog(e.getMessage());
}
// Log some info (non-static)
WebrtcLog("Notification marker pos = "
+ _ar.getNotificationMarkerPosition());
// WebrtcLog("Play head pos = " + _ar.getRecordHeadPosition());
WebrtcLog("Pos notification dt rec= "
+ _ar.getPositionNotificationPeriod());
// WebrtcLog("Playback rate = " + _ar.getRecordRate());
// WebrtcLog("Playback rate = " + _ar.getPlaybackRate());
WebrtcLog("Sample rate = " + _ar.getSampleRate());
// WebrtcLog("Playback rate = " + _ar.getPlaybackRate());
// WebrtcLog("Playback rate = " + _ar.getPlaybackRate());
_isRunningRec = true;
_recThread = new Thread(_recProc);
_recThread.start();
return 0;
}
int stopRecAudio() {
if (!_isRunningRec) {
return 0;
}
_isRunningRec = false;
return 0;
}
private Runnable _recProc = new Runnable() {
public void run() {
// set high thread priority
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
// start recording
try {
_ar.startRecording();
} catch (IllegalStateException e) {
e.printStackTrace();
}
// keep recording to circular buffer
// for a while
int i = 0;
int rdSamples = 0;
short[] tempBuffer = new short[160]; // Only used for native case
for (; i < 3000 && _isRunningRec; i++) {
if (_runThroughNativeLayer) {
rdSamples = _ar.read(tempBuffer, 0, 160);
// audioLoop(tempBuffer, 160); // Insert into native layer
} else {
rdSamples = _ar.read(_circBuffer, _recIndex * 160, 160);
// WebrtcLog("Recorded 10 ms to buffer, _recIndex = " +
// _recIndex);
// WebrtcLog("rdSamples = " + rdSamples);
if (_recIndex == 49) {
_recIndex = 0;
} else {
_recIndex += 1;
}
}
}
// stop recording
try {
_ar.stop();
} catch (IllegalStateException e) {
e.printStackTrace();
}
// release the object
_ar.release();
_ar = null;
// try {
// Thread.sleep() must be within a try - catch block
// Thread.sleep(3000);
// }catch (Exception e){
// System.out.println(e.getMessage());
// }
_isRunningRec = false;
// returns the number of samples that has been written
// WebrtcLog("Test stopped, i = " + i + ", head = "
// + _at.getPlaybackHeadPosition());
// int headPos = _at.getPlaybackHeadPosition();
}
};
private void WebrtcLog(String msg) {
Log.d("*Webrtc*", msg);
}
// //////////////// Native function prototypes ////////////////////
private native static boolean NativeInit();
private native int RunAutoTest(int testType, int extendedSel);
private native boolean Create();
private native boolean Delete();
private native int Init(boolean enableTrace, boolean useExtTrans);
private native int Terminate();
private native int CreateChannel();
private native int DeleteChannel(int channel);
private native int SetLocalReceiver(int channel, int port);
private native int SetSendDestination(int channel, int port,
String ipaddr);
private native int StartListen(int channel);
private native int StartPlayout(int channel);
private native int StartSend(int channel);
private native int StopListen(int channel);
private native int StopPlayout(int channel);
private native int StopSend(int channel);
private native int StartPlayingFileLocally(int channel, String fileName,
boolean loop);
private native int StopPlayingFileLocally(int channel);
private native int StartRecordingPlayout(int channel, String fileName,
boolean loop);
private native int StopRecordingPlayout(int channel);
private native int StartPlayingFileAsMicrophone(int channel,
String fileName, boolean loop);
private native int StopPlayingFileAsMicrophone(int channel);
private native int NumOfCodecs();
private native int SetSendCodec(int channel, int index);
private native int SetVADStatus(int channel, boolean enable, int mode);
private native int SetNSStatus(boolean enable, int mode);
private native int SetAGCStatus(boolean enable, int mode);
private native int SetECStatus(boolean enable, int mode);
private native int SetSpeakerVolume(int volume);
private native int SetLoudspeakerStatus(boolean enable);
/*
* this is used to load the 'webrtc-voice-demo-jni'
* library on application startup.
* The library has already been unpacked into
* /data/data/webrtc.android.AndroidTest/lib/libwebrtc-voice-demo-jni.so
* at installation time by the package manager.
*/
static {
Log.d("*Webrtc*", "Loading webrtc-voice-demo-jni...");
System.loadLibrary("webrtc-voice-demo-jni");
Log.d("*Webrtc*", "Calling native init...");
if (!NativeInit()) {
Log.e("*Webrtc*", "Native init failed");
throw new RuntimeException("Native init failed");
} else {
Log.d("*Webrtc*", "Native init successful");
}
}
}
| 33.694374 | 81 | 0.49377 |
ba8a381d9cad90e489c9a3b095a666b1cc9894b8 | 1,189 | package eu.dl.worker.master.plugin.body;
import java.util.HashMap;
import java.util.List;
import eu.dl.dataaccess.dto.master.MasterBody;
import eu.dl.dataaccess.dto.matched.MatchedBody;
import eu.dl.worker.master.plugin.MasterPlugin;
import eu.dl.worker.utils.BasePlugin;
/**
* This plugin is used to master data for bodies.
*
* @param <T>
* matched items type
* @param <V>
* item type to be mastered
*/
public final class MetaDataPlugin<T extends MatchedBody, V> extends BasePlugin implements MasterPlugin<T, V, Object> {
/**
* Plugin name.
*/
public static final String PLUGIN_ID = "metaDataPlugin";
@Override
public V master(final List<T> items, final V finalItem, final List<Object> context) {
HashMap<String, Object> result = new HashMap<String, Object>();
for (MatchedBody body : items) {
if (body.getMetaData() != null) {
result.putAll(body.getMetaData());
}
}
MasterBody masterBody = (MasterBody) finalItem;
if (!result.isEmpty()) {
masterBody.setMetaData(result);
}
return finalItem;
}
}
| 25.847826 | 118 | 0.6291 |
aaf92d4cd8da912b9ede2fca58a280250deef994 | 884 | package test;
import files.CSVFile;
import files.ExcelFile;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.*;
import parse.ParseTable;
import java.util.ArrayList;
class ImportingTests {
ExcelFile excelFile;
CSVFile csvFile;
ArrayList<ParseTable> tables;
@Test
void MultipleSheetImport() {
excelFile = new ExcelFile("./testing/5 Table merge.xlsx");
tables = excelFile.getTables();
assertEquals(5,tables.size());
}
@Test
void MultipleTablesSingleSheet() {
excelFile = new ExcelFile("./testing/threeTables one sheet.xlsx");
tables = excelFile.getTables();
assertEquals(3,tables.size());
}
@Test
void TestCsvImport() {
csvFile = new CSVFile("./testing/Table1.csv");
tables = csvFile.getTables();
assertEquals(1,tables.size());
}
} | 24.555556 | 74 | 0.656109 |
aab3a6e96d56a806c15895e45e5f7529e4c85488 | 1,271 | /*
* Copyright 2016 Elizabeth Harper
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.vulpine.connectwise.api.endpoints;
public enum Endpoint
{
ACTIVITY ("ActivityApi.asmx"),
AGREEMENT ("AgreementApi.asmx"),
COMPANY ("CompanyApi.asmx"),
CONFIGURATION ("ConfigurationApi.asmx"),
CONTACT ("ContactApi.asmx"),
DOCUMENT ("DocumentApi.asmx"),
INVOICE ("InvoiceApi.asmx"),
OPPORTUNITY ("OpportunityApi.asmx"),
PRODUCT ("ProductApi.asmx"),
REPORTING ("ReportingApi.asmx"),
TIME ("TimeEntryApi.asmx");
private final String endpoint;
Endpoint( final String endpoint )
{
this.endpoint = endpoint;
}
@Override
public String toString()
{
return endpoint;
}
}
| 28.244444 | 75 | 0.690795 |
f156b2a1f2bab33fed19308d936f62f2e883f08a | 1,481 | package io.link4pay.model.management;
import com.google.gson.Gson;
import io.link4pay.model.Request;
public class ManagementRequest extends Request {
private Gson gson = new Gson();
private String merchantID;
private String payoutEndpoint;
private String tokenEndpoint;
private String certificate;
private String apiToken;
public ManagementRequest merchantID(String merchantID) {
this.merchantID = merchantID;
return this;
}
public ManagementRequest payoutEndpoint(String payoutEndpoint) {
this.payoutEndpoint = payoutEndpoint;
return this;
}
public ManagementRequest tokenEndpoint(String tokenEndpoint) {
this.tokenEndpoint = tokenEndpoint;
return this;
}
public ManagementRequest certificate(String certificate) {
this.certificate = certificate;
return this;
}
public ManagementRequest apiToken(String apiToken) {
this.apiToken = apiToken;
return this;
}
@Override
public String toJSON() {
ManagementHttpRequest managementHttpRequest = new ManagementHttpRequest();
managementHttpRequest.merchantID = merchantID;
managementHttpRequest.payoutEndpoint = payoutEndpoint;
managementHttpRequest.tokenEndpoint = tokenEndpoint;
managementHttpRequest.certificate = certificate;
managementHttpRequest.apiToken = apiToken;
return gson.toJson(managementHttpRequest);
}
}
| 29.62 | 82 | 0.711006 |
5fb25895d7c026ad7b113b5da8e62d54484ec23c | 3,134 | package com.bitlab.ui;
import com.bitlab.constant.CommandMap;
import java.util.stream.Stream;
/**
* Enum with all available command for user
* @author Jacek Giedronowicz
*/
public enum UserCommandMap {
VERSION("version"),
VERACK("verack"),
GETADDR("getaddr"),
GETDATA("getdata"),
ADDR("addr"),
PRINT("print"),
SCAN("scan"),
EXIT("exit"),
STOP("stop"),
PING("ping");
private String name;
UserCommandMap(String name) {
this.name = name;
}
public static String getInfo(UserCommandMap command) {
String response;
switch (command){
case VERSION:
response = "version\n" +
"When a node creates an outgoing connection, it will immediately advertise its version. The remote node will respond with its version. No further communication is possible until both peers have exchanged their version.";
break;
case VERACK:
response = "verack\n" +
"The verack message is sent in reply to version. This message consists of only a message header with the command string \"verack\".";
break;
case GETADDR:
response = "getaddr\n" +
"The getaddr message sends a request to a node asking for information about known active peers to help with finding potential nodes in the network. The response to receiving this message is to transmit one or more addr messages with one or more peers from a database of known active peers. The typical presumption is that a node is likely to be active if it has been sending a message within the last three hours.\n" +
"\n" +
"No additional data is transmitted with this message.";
break;
case GETDATA:
response = "getdata\n"+
"The getdata message sends a request for single block or transaction specified by hash";
break;
case ADDR:
response = "addr\n" +
"Provide information on known nodes of the network. Non-advertised nodes should be forgotten after typically 3 hours";
break;
case PRINT:
response = "print\n" +
"print list on the screen ";
break;
case STOP:
response = "stop\n"+
"ending scanning task";
break;
case PING:
response = "ping\n"+
"sending ping to target";
default:
response = "ERROR";
}
return response;
}
public static String getInfo(String command) {
for (UserCommandMap value : UserCommandMap.values()) {
if (value.name.toLowerCase().equals( command.toLowerCase() ))
return UserCommandMap.getInfo(value);
}
return "Unknown command";
}
@Override
public String toString() {
return name.toLowerCase();
}
}
| 36.44186 | 442 | 0.563816 |
e8a529f4615bab431ab9a642ee52fca4d365a284 | 264 | package org.speakright.core.render;
/**
* Represents a voicexml page.
* @author IanRaeLaptop
*
*/
public class SpeechPage implements ISpeechPage {
public SpeechForm m_form = new SpeechForm(); //one only for now
public SpeechPage()
{}
}
| 16.5 | 65 | 0.670455 |
8a639d4d2c7379042721c38c93eb7ea832a675e8 | 2,169 | package de.mickare.armortools.command.armorstand.item;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import de.mickare.armortools.ArmorToolsPlugin;
import de.mickare.armortools.Out;
import de.mickare.armortools.Permissions;
import de.mickare.armortools.command.armorstand.AbstractModifyCommand.ModifyAction.Type;
public abstract class AbstractHandCommand extends AbstractItemCommand {
public AbstractHandCommand(ArmorToolsPlugin plugin, String command, String usage, Out desc) {
super(plugin, command, usage, desc);
}
public AbstractHandCommand(ArmorToolsPlugin plugin, String command, String usage, String desc) {
super(plugin, command, usage, desc);
}
public static class HandCommand extends AbstractHandCommand {
public HandCommand(ArmorToolsPlugin plugin) {
super(plugin, "hand", "hand [area]", Out.CMD_HAND);
this.addPermission(Permissions.HAND);
}
@Override
protected ItemStack getItem(ArmorStand armor) {
return armor.getEquipment().getItemInMainHand();
}
@Override
protected void setItem(ArmorStand armor, ItemStack item) {
armor.getEquipment().setItemInMainHand(item);
}
@Override
protected void sendItemSwitchedMessage(Player player) {
Out.CMD_HAND_SWITCHED.send(player);
}
@Override
protected Type getModifyActionType() {
return Type.HAND;
}
}
public static class OffHandCommand extends AbstractHandCommand {
public OffHandCommand(ArmorToolsPlugin plugin) {
super(plugin, "offhand", "offhand [area]", Out.CMD_HAND);
this.addPermission(Permissions.OFFHAND);
}
@Override
protected ItemStack getItem(ArmorStand armor) {
return armor.getEquipment().getItemInOffHand();
}
@Override
protected void setItem(ArmorStand armor, ItemStack item) {
armor.getEquipment().setItemInOffHand(item);
}
@Override
protected void sendItemSwitchedMessage(Player player) {
Out.CMD_OFFHAND_SWITCHED.send(player);
}
@Override
protected Type getModifyActionType() {
return Type.OFFHAND;
}
}
}
| 26.45122 | 98 | 0.728446 |
02f2cb016c84a265604685eb21475420a8592e6e | 1,120 | package mod.linguardium.layingbox;
import com.swordglowsblue.artifice.api.ArtificeResourcePack;
import com.swordglowsblue.artifice.impl.ArtificeResourcePackImpl;
import mod.linguardium.layingbox.config.ChickenConfigs;
import mod.linguardium.layingbox.entity.ModEntitiesClient;
import mod.linguardium.layingbox.render.LayingBoxRenderer;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.client.rendereregistry.v1.BlockEntityRendererRegistry;
import net.minecraft.resource.ResourceType;
import static mod.linguardium.layingbox.blocks.ModBlocks.LAYING_BOX_ENTITY;
@Environment(EnvType.CLIENT)
public class LayingBoxMainClient implements ClientModInitializer {
static {
ArtificeResourcePack pack = new ArtificeResourcePackImpl(ResourceType.CLIENT_RESOURCES,(a)->{});
}
@Override
public void onInitializeClient() {
BlockEntityRendererRegistry.INSTANCE.register(LAYING_BOX_ENTITY, LayingBoxRenderer::new);
ModEntitiesClient.initClient();
ChickenConfigs.registerAssets();
}
}
| 41.481481 | 104 | 0.817857 |
2ae16e4f8a81be066a0dae9d0ec449cc21fd2c69 | 5,450 | package ca.marshallasch.veil.services;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.Process;
import android.support.annotation.Nullable;
import android.widget.Toast;
import com.google.protobuf.InvalidProtocolBufferException;
import ca.marshallasch.veil.controllers.RightMeshController;
import ca.marshallasch.veil.proto.DhtProto;
/**
* Hosts all RightMesh logic on this service thread. Also receives {@link Message}s from
* {@link ca.marshallasch.veil.MainActivity} to handle work requested from application.
*
* @author Weihan Li
* @version 1.0
* @since 2018-07-09
*/
public class VeilService extends Service {
private RightMeshController rightMeshController;
//Message Strings
public static final int ACTION_VIEW_MESH_SETTINGS = 1;
public static final int ACTION_MAIN_RESUME_MESH = 2;
public static final int ACTION_MAIN_REFRESH_PEER_LIST = 3;
public static final int ACTION_MAIN_REFRESH_FORUMS_LIST = 4;
public static final int ACTION_NOTIFY_NEW_DATA = 5;
// extra fields that can be set in the bundle to set data in the message
public static final String EXTRA_POST = "EXTRA_POST";
public static final String EXTRA_COMMENT = "EXTRA_COMMENT";
/**
* Target for clients to send messages to ServiceHandler
*/
Messenger veilMessenger = null;
/**
* ServiceHandler class for the {@link VeilService}
*/
private final class ServiceHandler extends Handler {
/**
* Creates the service handler on the given thread.
*
* @param looper the looper for the thread that the work will be run on.
*/
ServiceHandler (Looper looper){
super(looper);
}
/**
* Where messages to do work on the thread is processed
* @param msg work message
*/
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case ACTION_VIEW_MESH_SETTINGS:
rightMeshController.showMeshSettings();
break;
case ACTION_MAIN_RESUME_MESH:
rightMeshController.resumeMeshManager();
break;
case ACTION_MAIN_REFRESH_PEER_LIST:
rightMeshController.getPeers();
break;
case ACTION_MAIN_REFRESH_FORUMS_LIST:
rightMeshController.manualRefresh();
break;
case ACTION_NOTIFY_NEW_DATA:
DhtProto.Post post = null;
DhtProto.Comment comment = null;
Bundle bundle = msg.getData();
byte[] postArray = bundle.getByteArray(EXTRA_POST);
byte[] commentArray = bundle.getByteArray(EXTRA_COMMENT);
try {
if (postArray != null) {
post = DhtProto.Post.parseFrom(postArray);
}
if (commentArray != null) {
comment = DhtProto.Comment.parseFrom(commentArray);
}
}
catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
rightMeshController.notifyNewContent(post, comment);
break;
default:
super.handleMessage(msg);
}
}
}
/**
* Connects to RightMesh when service is started
*/
@Override
public void onCreate(){
super.onCreate();
//start RightMesh connection through controller using service context
rightMeshController = new RightMeshController();
rightMeshController.connect(this);
//Start up thread and make it background priority so it doesn't disrupt UI
HandlerThread veilServiceThread = new HandlerThread("VeilServiceThread",
Process.THREAD_PRIORITY_BACKGROUND);
veilServiceThread.start();
veilMessenger = new Messenger(new ServiceHandler(veilServiceThread.getLooper()));
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Veil service started.", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
/**
* Disconnects from RightMesh when service is stopped
*/
@Override
public void onDestroy(){
super.onDestroy();
Toast.makeText(this, "Veil service ended.", Toast.LENGTH_SHORT).show();
rightMeshController.disconnect();
rightMeshController = null;
//force kill service so it has no chance of recreating itself
android.os.Process.killProcess(android.os.Process.myPid());
}
/**
* Allows for binding to {@link VeilService} returning an interface to the messenger
* @param intent an intent call from the client side
* @return the default IBinder object for the messenger
*/
@Nullable
@Override
public IBinder onBind(Intent intent) {
Toast.makeText(this, "binding", Toast.LENGTH_SHORT).show();
return veilMessenger.getBinder();
}
}
| 33.231707 | 89 | 0.619083 |
1d97da93500c6b031e2d354b5954fe9ba517d442 | 720 | package cn.geekhall;
import cn.geekhall.config.IMyConfig;
import cn.geekhall.config.MyConfig;
import cn.geekhall.config.MyConfigB;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import sun.rmi.rmic.Main;
//@SpringBootApplication
public class Springboot11SpiLoaderApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot11SpiLoaderApplication.class, args);
System.out.println("test");
// IMyConfig myConfig = new MyConfig();
// IMyConfig myConfigb = new MyConfigB();
// myConfig.systemInit();
}
}
| 31.304348 | 76 | 0.765278 |
f22e1e31440851f4c4bd55829f2f6a324d6ed899 | 1,700 | package com.cursoandroid.jamiltondamasceno.aprendaingles.Activities;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.cursoandroid.jamiltondamasceno.aprendaingles.Fragments.BichosFragment;
import com.cursoandroid.jamiltondamasceno.aprendaingles.Fragments.NumerosFragment;
import com.cursoandroid.jamiltondamasceno.aprendaingles.Fragments.VogaisFragment;
import com.cursoandroid.jamiltondamasceno.aprendaingles.R;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItemAdapter;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItems;
public class MainActivity extends AppCompatActivity {
private SmartTabLayout smartTabLayout;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Configuracoes action bar
getSupportActionBar().setElevation(0);
getSupportActionBar().setTitle("Aprenda Inglês");
smartTabLayout = findViewById(R.id.smartTabLayout);
viewPager = findViewById(R.id.viewpager);
FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(
getSupportFragmentManager(),
FragmentPagerItems.with(this)
.add("Bichos", BichosFragment.class)
.add("Números", NumerosFragment.class)
.add("Vogais", VogaisFragment.class)
.create()
);
viewPager.setAdapter( adapter );
smartTabLayout.setViewPager( viewPager );
}
}
| 36.956522 | 82 | 0.743529 |
90faa19e2616c7f656a41eb54e3a47aab4ac0739 | 6,778 | /**
* 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.hadoop.yarn.logaggregation;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.fs.Path;
/**
* This class contains several utility function which could be used in different
* log tools.
*
*/
public final class LogToolUtils {
private LogToolUtils() {}
public static final String CONTAINER_ON_NODE_PATTERN =
"Container: %s on %s";
/**
* Output container log.
* @param containerId the containerId
* @param nodeId the nodeId
* @param fileName the log file name
* @param fileLength the log file length
* @param outputSize the output size
* @param lastModifiedTime the log file last modified time
* @param fis the log file input stream
* @param os the output stream
* @param buf the buffer
* @param logType the log type.
* @throws IOException if we can not access the log file.
*/
public static void outputContainerLog(String containerId, String nodeId,
String fileName, long fileLength, long outputSize,
String lastModifiedTime, InputStream fis, OutputStream os,
byte[] buf, ContainerLogAggregationType logType) throws IOException {
long toSkip = 0;
long totalBytesToRead = fileLength;
long skipAfterRead = 0;
if (outputSize < 0) {
long absBytes = Math.abs(outputSize);
if (absBytes < fileLength) {
toSkip = fileLength - absBytes;
totalBytesToRead = absBytes;
}
org.apache.hadoop.io.IOUtils.skipFully(fis, toSkip);
} else {
if (outputSize < fileLength) {
totalBytesToRead = outputSize;
skipAfterRead = fileLength - outputSize;
}
}
long curRead = 0;
long pendingRead = totalBytesToRead - curRead;
int toRead = pendingRead > buf.length ? buf.length
: (int) pendingRead;
int len = fis.read(buf, 0, toRead);
boolean keepGoing = (len != -1 && curRead < totalBytesToRead);
if (keepGoing) {
StringBuilder sb = new StringBuilder();
String containerStr = String.format(
LogToolUtils.CONTAINER_ON_NODE_PATTERN,
containerId, nodeId);
sb.append(containerStr + "\n");
sb.append("LogAggregationType: " + logType + "\n");
sb.append(StringUtils.repeat("=", containerStr.length()) + "\n");
sb.append("LogType:" + fileName + "\n");
sb.append("LogLastModifiedTime:" + lastModifiedTime + "\n");
sb.append("LogLength:" + Long.toString(fileLength) + "\n");
sb.append("LogContents:\n");
byte[] b = sb.toString().getBytes(
Charset.forName("UTF-8"));
os.write(b, 0, b.length);
}
while (keepGoing) {
os.write(buf, 0, len);
curRead += len;
pendingRead = totalBytesToRead - curRead;
toRead = pendingRead > buf.length ? buf.length
: (int) pendingRead;
len = fis.read(buf, 0, toRead);
keepGoing = (len != -1 && curRead < totalBytesToRead);
}
org.apache.hadoop.io.IOUtils.skipFully(fis, skipAfterRead);
os.flush();
}
public static void outputContainerLogThroughZeroCopy(String containerId,
String nodeId, String fileName, long fileLength, long outputSize,
String lastModifiedTime, FileInputStream fis, OutputStream os,
ContainerLogAggregationType logType) throws IOException {
long toSkip = 0;
long totalBytesToRead = fileLength;
if (outputSize < 0) {
long absBytes = Math.abs(outputSize);
if (absBytes < fileLength) {
toSkip = fileLength - absBytes;
totalBytesToRead = absBytes;
}
} else {
if (outputSize < fileLength) {
totalBytesToRead = outputSize;
}
}
if (totalBytesToRead > 0) {
// output log summary
StringBuilder sb = new StringBuilder();
String containerStr = String.format(
LogToolUtils.CONTAINER_ON_NODE_PATTERN,
containerId, nodeId);
sb.append(containerStr + "\n");
sb.append("LogAggregationType: " + logType + "\n");
sb.append(StringUtils.repeat("=", containerStr.length()) + "\n");
sb.append("LogType:" + fileName + "\n");
sb.append("LogLastModifiedTime:" + lastModifiedTime + "\n");
sb.append("LogLength:" + Long.toString(fileLength) + "\n");
sb.append("LogContents:\n");
byte[] b = sb.toString().getBytes(
Charset.forName("UTF-8"));
os.write(b, 0, b.length);
// output log content
FileChannel inputChannel = fis.getChannel();
WritableByteChannel outputChannel = Channels.newChannel(os);
long position = toSkip;
while (totalBytesToRead > 0) {
long transferred =
inputChannel.transferTo(position, totalBytesToRead, outputChannel);
totalBytesToRead -= transferred;
position += transferred;
}
os.flush();
}
}
/**
* Create the container log file under given (local directory/nodeId) and
* return the PrintStream object.
* @param localDir the Local Dir
* @param nodeId the NodeId
* @param containerId the ContainerId
* @return the printStream object
* @throws IOException if an I/O error occurs
*/
public static PrintStream createPrintStream(String localDir, String nodeId,
String containerId) throws IOException {
PrintStream out = System.out;
if(localDir != null && !localDir.isEmpty()) {
Path nodePath = new Path(localDir, LogAggregationUtils
.getNodeString(nodeId));
Files.createDirectories(Paths.get(nodePath.toString()));
Path containerLogPath = new Path(nodePath, containerId);
out = new PrintStream(containerLogPath.toString(), "UTF-8");
}
return out;
}
}
| 36.053191 | 80 | 0.671732 |
2f299e35203739bfe7ece4d7d978adc363c563e1 | 1,170 | import java.util.ArrayList;
import java.util.List;
/**
* 找到字符串中所有字母异位词
*
* @Author RUANWENJUN
* @Creat 2018-05-30 13:55
*/
public class Problem438 {
/**
* 采用暴力+异或运算符
*
* @param s
* @param p
* @return
*/
public List<Integer> findAnagrams(String s, String p) {
List<Integer> list = new ArrayList<>();
int[] index = new int[26];
boolean is = true;
for (int i = 0; i <= s.length() - p.length(); i++) {
is = true;
for (int j = 0;j<26;j++){
index[j] = 0;
}
for (int j = 0; j < p.length(); j++) {
index[p.charAt(j)-'a']++;
index[s.charAt(i+j)-'a']--;
}
for (int j =0;j<26;j++){
if(index[j] != 0){
is = false;
}
}
if(is){
list.add(i);
}
}
return list;
}
public static void main(String[] args) {
Problem438 p = new Problem438();
List<Integer> anagrams = p.findAnagrams("cbaebabacd", "abc");
System.out.println(anagrams);
}
}
| 23.4 | 69 | 0.42906 |
c97461beb03397dee668e08fd0b0eeea5b3bcf6e | 11,568 | package epicsquid.roots.tileentity;
import epicsquid.mysticallib.network.PacketHandler;
import epicsquid.mysticallib.tile.TileBase;
import epicsquid.mysticallib.util.ItemUtil;
import epicsquid.mysticallib.util.Util;
import epicsquid.roots.config.GeneralConfig;
import epicsquid.roots.init.ModItems;
import epicsquid.roots.item.ItemStaff;
import epicsquid.roots.network.fx.MessageImbueCompleteFX;
import epicsquid.roots.particle.ParticleUtil;
import epicsquid.roots.spell.FakeSpell;
import epicsquid.roots.spell.SpellBase;
import epicsquid.roots.spell.info.storage.DustSpellStorage;
import epicsquid.roots.world.data.SpellLibraryData;
import epicsquid.roots.world.data.SpellLibraryRegistry;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.Style;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.items.ItemStackHandler;
import javax.annotation.Nonnull;
import java.util.UUID;
public class TileEntityImbuer extends TileBase implements ITickable {
public ItemStackHandler inventory = new ItemStackHandler(2) {
@Override
protected void onContentsChanged(int slot) {
TileEntityImbuer.this.markDirty();
if (!world.isRemote) {
TileEntityImbuer.this.updatePacketViaState();
}
}
};
private int progress = 0;
public float angle = 0;
private UUID inserter = null;
public TileEntityImbuer() {
super();
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound tag) {
super.writeToNBT(tag);
tag.setTag("handler", inventory.serializeNBT());
tag.setInteger("progress", progress);
if (inserter != null) {
tag.setUniqueId("inserter", inserter);
}
return tag;
}
@Override
public void readFromNBT(NBTTagCompound tag) {
super.readFromNBT(tag);
inventory.deserializeNBT(tag.getCompoundTag("handler"));
progress = tag.getInteger("progress");
if (tag.hasUniqueId("inserter")) {
inserter = tag.getUniqueId("inserter");
} else {
inserter = null;
}
}
@Override
public NBTTagCompound getUpdateTag() {
return writeToNBT(new NBTTagCompound());
}
@Override
public SPacketUpdateTileEntity getUpdatePacket() {
return new SPacketUpdateTileEntity(getPos(), 0, getUpdateTag());
}
@Override
public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) {
readFromNBT(pkt.getNbtCompound());
}
@Override
public boolean activate(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull IBlockState state, @Nonnull EntityPlayer player, @Nonnull EnumHand hand, @Nonnull EnumFacing side, float hitX, float hitY, float hitZ) {
ItemStack heldItem = player.getHeldItem(hand);
if (!heldItem.isEmpty()) {
int slot = -1;
if (heldItem.getItem() == ModItems.spell_dust) {
slot = 0;
} else if (heldItem.getItem() == ModItems.staff || heldItem.getItem() == ModItems.gramary) {
slot = 1;
}
if (slot != -1) {
if (inventory.getStackInSlot(slot).isEmpty()) {
ItemStack toInsert = heldItem.copy();
toInsert.setCount(1);
ItemStack attemptedInsert = inventory.insertItem(slot, toInsert, false);
if (attemptedInsert.isEmpty()) {
inserter = player.getUniqueID();
player.getHeldItem(hand).shrink(1);
markDirty();
updatePacketViaState();
return true;
}
}
} else {
// Check for a damaged item in the other slot and see if this matches
if (inventory.getStackInSlot(0).isEmpty() && inventory.getStackInSlot(1).isEmpty()) {
if (heldItem.isItemStackDamageable() || (heldItem.isItemEnchanted() && heldItem.getItem() != Items.ENCHANTED_BOOK)) {
ItemStack toInsert = heldItem.copy();
ItemStack attemptedInsert = inventory.insertItem(1, toInsert, true);
if (attemptedInsert.isEmpty()) {
inventory.insertItem(1, toInsert, false);
player.getHeldItem(hand).shrink(1);
if (player.getHeldItem(hand).getCount() == 0) {
player.setHeldItem(hand, ItemStack.EMPTY);
}
markDirty();
updatePacketViaState();
return true;
}
}
} else {
ItemStack toRepair = inventory.getStackInSlot(1);
if (GeneralConfig.AllowImbuerRepair && !toRepair.isEmpty() && toRepair.isItemStackDamageable() && toRepair.getItem().getIsRepairable(toRepair, heldItem) && inventory.getStackInSlot(0).isEmpty()) {
ItemStack repairItem = heldItem.copy();
repairItem.setCount(1);
int repairAmount = Math.min(toRepair.getItemDamage(), toRepair.getMaxDamage() / GeneralConfig.MaxDamageDivisor);
if (repairAmount > 0) {
ItemStack result = inventory.insertItem(0, repairItem, true);
if (result.isEmpty()) {
inventory.insertItem(0, repairItem, false);
player.getHeldItem(hand).shrink(1);
if (player.getHeldItem(hand).getCount() == 0) {
player.setHeldItem(hand, ItemStack.EMPTY);
}
markDirty();
updatePacketViaState();
return true;
}
}
} else if (GeneralConfig.AllowImbuerDisenchant && !toRepair.isEmpty() && toRepair.isItemEnchanted() && heldItem.getItem() == ModItems.runic_dust) {
ItemStack runicDust = heldItem.copy();
runicDust.setCount(1);
ItemStack result = inventory.insertItem(0, runicDust, true);
if (result.isEmpty()) {
inventory.insertItem(0, runicDust, false);
player.getHeldItem(hand).shrink(1);
if (player.getHeldItem(hand).getCount() == 0) {
player.setHeldItem(hand, ItemStack.EMPTY);
}
markDirty();
updatePacketViaState();
return true;
}
}
}
}
}
if (heldItem.isEmpty() && !world.isRemote && hand == EnumHand.MAIN_HAND) {
for (int i = inventory.getSlots() - 1; i >= 0; i--) {
if (this.dropItemInInventory(inventory, i)) {
return true;
}
}
}
return false;
}
@Override
public void breakBlock(World world, BlockPos pos, IBlockState state, EntityPlayer player) {
if (!world.isRemote) {
Util.spawnInventoryInWorld(world, getPos().getX() + 0.5, getPos().getY() + 0.5, getPos().getZ() + 0.5, inventory);
}
}
@Override
public void update() {
angle++;
if (!inventory.getStackInSlot(0).isEmpty() && !inventory.getStackInSlot(1).isEmpty()) {
progress++;
angle += 2.0f;
ItemStack spellDust = inventory.getStackInSlot(0);
DustSpellStorage capability = DustSpellStorage.fromStack(spellDust);
SpellBase spell;
if (capability != null && capability.getSelectedInfo() != null) {
spell = capability.getSelectedInfo().getSpell();
} else {
spell = FakeSpell.INSTANCE;
}
if (world.isRemote) {
BlockPos pos = getPos();
float x = pos.getX();
float y = pos.getY();
float z = pos.getZ();
if (Util.rand.nextInt(2) == 0) {
ParticleUtil.spawnParticleLineGlow(world, x + 0.5f, y + 0.125f, z + 0.5f, x + 0.5f + 0.5f * (Util.rand.nextFloat() - 0.5f), y + 1.0f, z + 0.5f + 0.5f * (Util.rand.nextFloat() - 0.5f), spell.getFirstColours(0.25f), 4.0f, 40);
} else {
ParticleUtil.spawnParticleLineGlow(world, x + 0.5f, y + 0.125f, z + 0.5f, x + 0.5f + 0.5f * (Util.rand.nextFloat() - 0.5f), y + 1.0f, z + 0.5f + 0.5f * (Util.rand.nextFloat() - 0.5f), spell.getSecondColours(0.25f), 4.0f, 40);
}
}
if (progress > 200) {
progress = 0;
if (!world.isRemote) {
ItemStack inSlot = inventory.getStackInSlot(1);
if ((inSlot.getItem() == ModItems.staff || inSlot.getItem() == ModItems.gramary) && spell != FakeSpell.INSTANCE) {
boolean ejectItem = inSlot.getItem() != ModItems.gramary;
if (inserter == null) {
Util.spawnInventoryInWorld(world, getPos().getX() + 0.5, getPos().getY() + 0.5, getPos().getZ() + 0.5, inventory);
} else {
if (inSlot.getItem() == ModItems.staff) {
ItemStaff.createData(inSlot, capability);
}
SpellLibraryData library = SpellLibraryRegistry.getData(inserter);
library.addSpell(spell);
if (ejectItem) {
world.spawnEntity(new EntityItem(world, getPos().getX() + 0.5, getPos().getY() + 0.5, getPos().getZ() + 0.5, inSlot));
}
PacketHandler.sendToAllTracking(new MessageImbueCompleteFX(spell.getName(), getPos().getX() + 0.5, getPos().getY() + 0.5, getPos().getZ() + 0.5), this);
if (inserter != null) {
EntityPlayerMP player = FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerList().getPlayerByUUID(inserter);
player.sendStatusMessage(new TextComponentTranslation("roots.message.spell_imbued", new TextComponentTranslation(spell.getTranslationKey() + ".name").setStyle(new Style().setColor(spell.getTextColor()).setBold(true))), true);
}
}
inventory.extractItem(0, 1, false);
if (ejectItem) {
inventory.extractItem(1, 1, false);
}
markDirty();
updatePacketViaState();
} else {
// Handle the repair
ItemStack repairItem = inventory.extractItem(0, 1, false);
ItemStack toRepair = inventory.extractItem(1, 1, false);
if (repairItem.getItem() == ModItems.runic_dust) {
NBTTagCompound tag = ItemUtil.getOrCreateTag(toRepair);
if (tag.hasKey("ench")) {
tag.removeTag("ench");
toRepair.setTagCompound(tag);
}
} else {
int repairAmount = Math.min(toRepair.getItemDamage(), toRepair.getMaxDamage() / 4);
if (repairAmount > 0) {
toRepair.setItemDamage(toRepair.getItemDamage() - repairAmount);
}
}
world.spawnEntity(new EntityItem(world, getPos().getX() + 0.5, getPos().getY() + 0.5, getPos().getZ() + 0.5, toRepair));
markDirty();
updatePacketViaState();
PacketHandler.sendToAllTracking(new MessageImbueCompleteFX("fake_spell", getPos().getX() + 0.5, getPos().getY() + 0.5, getPos().getZ() + 0.5), this);
}
}
}
this.markDirty();
if (!world.isRemote) {
updatePacketViaState();
}
} else {
if (progress != 0) {
progress = 0;
this.markDirty();
if (!world.isRemote) {
updatePacketViaState();
}
}
}
}
} | 41.314286 | 241 | 0.619381 |
a6be3fc1d02b4e76f9df586477ac13237dcd7c9d | 516 | package game.components;
import processing.core.PApplet;
import processing.core.PVector;
public class ColorEmitter {
PApplet p;
public ColorEmitter (PApplet p) {
this.p = p;
}
public void emitColor(Player player) {
PVector location = player.getLocation();
int color = player.getColor();
int size = player.getSize();
p.fill(color);
p.stroke(color);
//Dirty! this for the Color to overlap the Player Icon
p.ellipse(location.x, location.y, size+5, size+5);
}
}
| 20.64 | 57 | 0.664729 |
52898f0a9d3f19f4838bbbea81dbb1cbc76a7cd4 | 10,290 | package gui_classes;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import org.eclipse.wb.swing.FocusTraversalOnArray;
public class UW_Shapes_Frame extends JFrame implements ActionListener{
//list of all components of the frame
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
//creates the frame
public UW_Shapes_Frame() {
//sets up the frame
setTitle("Window");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 800, 600);
setMinimumSize(new Dimension(1000,700));
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
contentPane.add(makeWindowPanel());
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.NORTH);
JPanel panel_6 = new JPanel();
panel.add(panel_6);
JLabel lblWindowTypeLabel = new JLabel("UltraWeld Shapes Series 8400");
lblWindowTypeLabel.setFont(new Font("Dialog", Font.BOLD, 14));
panel_6.add(lblWindowTypeLabel);
JPanel panel_1 = new JPanel();
panel.add(panel_1);
JLabel label_1 = new JLabel("Price");
panel_1.add(label_1);
JLabel lblxxxxxx = new JLabel("$XXXX.XX");
panel_1.add(lblxxxxxx);
setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{contentPane}));
}
//This is the panel of the home tab
protected JComponent makeWindowPanel() {
JPanel panel = new JPanel();
//panel.setLayout(new AbsoluteLayout(0,0));
panel.setLayout(null);
JPanel panel_6 = new JPanel();
panel_6.setBorder(new TitledBorder(null, "Window Shape", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel_6.setBounds(267, 52, 447, 61);
panel.add(panel_6);
panel_6.setLayout(null);
JPanel panel_4 = new JPanel();
panel_4.setBounds(6, 16, 419, 36);
panel_6.add(panel_4);
panel_4.setLayout(null);
JComboBox comboBox_4 = new JComboBox();
comboBox_4.setBounds(106, 11, 218, 20);
panel_4.add(comboBox_4);
comboBox_4.setModel(new DefaultComboBoxModel(new String[] {"Half Round", "Extended Leg Half Round", "Quarter Round", "Extended Leg Quarter Round", "Circle", "Octagon", "Hexagon", "Eyebrow", "Extended Leg Eyebrow", "Half Eyebrow", "Extended Leg Half Eyebrow", "Pentagon", "Pentagon - Left & Right", "Trapezoid", "Triangle"}));
JPanel panel_3 = new JPanel();
panel_3.setBorder(new TitledBorder(null, "Window Options", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel_3.setBounds(267, 161, 447, 452);
panel.add(panel_3);
panel_3.setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBounds(5, 18, 437, 258);
panel_3.add(panel_1);
panel_1.setLayout(null);
JComboBox comboBox_8 = new JComboBox();
comboBox_8.setModel(new DefaultComboBoxModel(new String[] {"Double Strength", "Tempered"}));
comboBox_8.setBounds(184, 79, 170, 20);
panel_1.add(comboBox_8);
JComboBox comboBox_9 = new JComboBox();
comboBox_9.setModel(new DefaultComboBoxModel(new String[] {"Colonial V-Groove", "Colonial Woodgrain", "Contoured Woodgrain", "Contoured Painted"}));
comboBox_9.setBounds(184, 105, 170, 20);
panel_1.add(comboBox_9);
JComboBox comboBox_10 = new JComboBox();
comboBox_10.setModel(new DefaultComboBoxModel(new String[] {"Tan Only", "Brown Only", "Woodgrain Interior on White", "Woodgrain Interior on Tan", "Woodgrain Interior on Brown"}));
comboBox_10.setBounds(184, 137, 170, 20);
panel_1.add(comboBox_10);
JLabel lblVinylColor = new JLabel("Vinyl Color");
lblVinylColor.setBounds(0, 137, 100, 20);
panel_1.add(lblVinylColor);
lblVinylColor.setFont(new Font("Dialog", Font.PLAIN, 14));
JLabel lblGrid = new JLabel("Grid");
lblGrid.setBounds(0, 105, 100, 20);
panel_1.add(lblGrid);
lblGrid.setFont(new Font("Dialog", Font.PLAIN, 14));
JLabel label_6 = new JLabel("Glass Strength");
label_6.setBounds(0, 79, 100, 20);
panel_1.add(label_6);
label_6.setFont(new Font("Dialog", Font.PLAIN, 14));
JLabel label_11 = new JLabel("+$XX.XX");
label_11.setFont(new Font("Tahoma", Font.BOLD, 11));
label_11.setBounds(372, 143, 53, 14);
panel_1.add(label_11);
JLabel label_12 = new JLabel("+$XX.XX");
label_12.setFont(new Font("Tahoma", Font.BOLD, 11));
label_12.setBounds(372, 111, 53, 14);
panel_1.add(label_12);
JLabel label_13 = new JLabel("+$XX.XX");
label_13.setFont(new Font("Tahoma", Font.BOLD, 11));
label_13.setBounds(372, 85, 53, 14);
panel_1.add(label_13);
JLabel label_19 = new JLabel("+$XX.XX");
label_19.setFont(new Font("Tahoma", Font.BOLD, 11));
label_19.setBounds(372, 50, 53, 14);
panel_1.add(label_19);
JComboBox comboBox_13 = new JComboBox();
comboBox_13.setModel(new DefaultComboBoxModel(new String[] {"Clear Glass", "Obscure", "Glue Chip", "Rain Glass"}));
comboBox_13.setBounds(184, 44, 170, 20);
panel_1.add(comboBox_13);
JLabel label_21 = new JLabel("Glass");
label_21.setFont(new Font("Dialog", Font.PLAIN, 14));
label_21.setBounds(0, 44, 100, 20);
panel_1.add(label_21);
JLabel label_2 = new JLabel("Window Color");
label_2.setBounds(0, 168, 97, 20);
panel_1.add(label_2);
label_2.setFont(new Font("Dialog", Font.PLAIN, 14));
JLabel lblWindowTint = new JLabel("Window Tint");
lblWindowTint.setBounds(0, 199, 97, 20);
panel_1.add(lblWindowTint);
lblWindowTint.setFont(new Font("Dialog", Font.PLAIN, 14));
JComboBox comboBox = new JComboBox();
comboBox.setBounds(184, 199, 170, 20);
panel_1.add(comboBox);
comboBox.setModel(new DefaultComboBoxModel(new String[] {"No Tint", "Bronze Tint", "Grey Tint"}));
JComboBox comboBox_2 = new JComboBox();
comboBox_2.setBounds(184, 168, 170, 20);
panel_1.add(comboBox_2);
comboBox_2.setModel(new DefaultComboBoxModel(new String[] {"No Paint", "White", "Tan", "Black", "Brick Red", "Beige", "Bronze", "Brown", "Clay", "Gary", "Green", "Architectural Bronze"}));
JLabel label_10 = new JLabel("+$XX.XX");
label_10.setBounds(372, 168, 53, 14);
panel_1.add(label_10);
label_10.setFont(new Font("Tahoma", Font.BOLD, 11));
JLabel label_18 = new JLabel("+$XX.XX");
label_18.setBounds(372, 199, 53, 14);
panel_1.add(label_18);
label_18.setFont(new Font("Tahoma", Font.BOLD, 11));
JLabel label = new JLabel("Energy Options");
label.setFont(new Font("Dialog", Font.PLAIN, 14));
label.setBounds(0, 12, 100, 20);
panel_1.add(label);
JComboBox comboBox_1 = new JComboBox();
comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"energySMART\u00AESupreme 2", "energrySMART\u00AEXL 2", "energySMART\u00AEUltimate 2", "energySMART\u00AEUltimate 2 Plus (Kryton gas)", "Muntins"}));
comboBox_1.setBounds(184, 12, 170, 20);
panel_1.add(comboBox_1);
JLabel label_1 = new JLabel("+$XX.XX");
label_1.setFont(new Font("Tahoma", Font.BOLD, 11));
label_1.setBounds(372, 18, 53, 14);
panel_1.add(label_1);
JButton button = new JButton("Add");
button.setFont(new Font("Dialog", Font.BOLD, 14));
button.setBounds(868, 569, 83, 30);
panel.add(button);
JPanel panel_4_1 = new JPanel();
panel_4_1.setBounds(267, 17, 107, 30);
panel.add(panel_4_1);
JLabel label_17 = new JLabel("Windows Size");
panel_4_1.add(label_17);
label_17.setFont(new Font("Tahoma", Font.PLAIN, 16));
JPanel panel_2_1 = new JPanel();
panel_2_1.setBounds(386, 17, 162, 30);
panel.add(panel_2_1);
JLabel label_2_1 = new JLabel("Width");
panel_2_1.add(label_2_1);
textField = new JTextField("0");
panel_2_1.add(textField);
textField.setColumns(10);
JPanel panel_3_1 = new JPanel();
panel_3_1.setBounds(553, 17, 165, 30);
panel.add(panel_3_1);
JLabel label_3_1 = new JLabel("Height");
panel_3_1.add(label_3_1);
textField_1 = new JTextField("0");
panel_3_1.add(textField_1);
textField_1.setColumns(10);
JLabel lblMinDynamicMax = new JLabel("Min: Dynamic Max: Dynamic");
lblMinDynamicMax.setFont(new Font("Dialog", Font.PLAIN, 12));
lblMinDynamicMax.setBounds(430, 0, 93, 16);
panel.add(lblMinDynamicMax);
JLabel lblMinDynamicMax_1 = new JLabel("Min: Dynamic Max: Dynamic");
lblMinDynamicMax_1.setFont(new Font("Dialog", Font.PLAIN, 12));
lblMinDynamicMax_1.setBounds(599, 0, 93, 16);
panel.add(lblMinDynamicMax_1);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
return panel;
}
public void actionPerformed(ActionEvent e){
}
}
| 39.125475 | 334 | 0.616618 |
2e97a8c4a40a485ec031c7beaf9d2bba0fda9c14 | 684 | package com.my.service_startservice;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private static String TAG = "10001";
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(MainActivity.this, MyService.class);
}
public void start_func(View view) {
startService(intent);
}
public void stop_func(View view) {
stopService(intent);
}
}
| 23.586207 | 64 | 0.714912 |
11dce974fbde49a12f1107fe8e975126037623f2 | 2,357 | package com.ange.demo.lifecycle;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.ange.demo.R;
/**
* Created by ange on 2017/7/29.
*/
public class LifecycleFragment extends Fragment {
TextView ftv,atv;
@Override
public void onAttach(Context context) {
super.onAttach(context);
setFragmentLife("f:onAttach");
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setFragmentLife("f:onCreate");
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_lifecycle,container,false);
ftv= (TextView) view.findViewById(R.id.tv_f_message);
atv= (TextView) view.findViewById(R.id.tv_a_message);
setFragmentLife("f:onCreateView");
return view;
}
@Override
public void onStart() {
super.onStart();
setFragmentLife("f:onStart");
}
@Override
public void onResume() {
super.onResume();
setFragmentLife("f:onResume");
}
@Override
public void onPause() {
super.onPause();
setFragmentLife("f:onPause");
}
@Override
public void onStop() {
super.onStop();
setFragmentLife("f:onStop");
}
@Override
public void onDestroyView() {
super.onDestroyView();
setFragmentLife("f:onDestroyView");
}
@Override
public void onDestroy() {
super.onDestroy();
setFragmentLife("f:onDestroy");
}
@Override
public void onDetach() {
super.onDetach();
setFragmentLife("f:onDetach");
}
public void setFragmentLife(String msg){
// if(ftv!=null){
// ftv.setText(msg);
// }
Log.e("TAG", "setFragmentLife: "+msg);
}
public void setActivityLife(String msg){
// if(atv!=null){
// atv.setText(msg);
// }
Log.e("TAG", "setActivityLife: "+msg);
}
}
| 21.824074 | 123 | 0.62622 |
65221b1ad76416114a6db5d8f17e3d22bef66606 | 584 | package org.motechproject.sms.audit.constants;
/**
* Utility class for storing delivery statuses.
*/
public final class DeliveryStatuses {
public static final String RECEIVED = "RECEIVED";
public static final String RETRYING = "RETRYING";
public static final String ABORTED = "ABORTED";
public static final String DISPATCHED = "DISPATCHED";
public static final String FAILURE_CONFIRMED = "FAILURE_CONFIRMED";
public static final String SCHEDULED = "SCHEDULED";
public static final String PENDING = "PENDING";
private DeliveryStatuses() {
}
}
| 29.2 | 71 | 0.729452 |
6776ca2113c2c2fe0a147841ac4ec3ad4490ceec | 115 | package miniJava.SyntacticAnalyzer;
public class Token {
private TokenType kind;
private String spelling;
}
| 12.777778 | 35 | 0.773913 |
3fff5cff3f8b391553840a051f7b5b031cdc4dd2 | 1,295 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.update;
import com.intellij.openapi.options.Configurable;
import git4idea.config.GitVcsSettings;
import git4idea.i18n.GitBundle;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
public class GitUpdateConfigurable implements Configurable {
private final GitVcsSettings mySettings;
private GitUpdateOptionsPanel myPanel;
public GitUpdateConfigurable(@NotNull GitVcsSettings settings) {
mySettings = settings;
}
@Override
@Nls
public String getDisplayName() {
return GitBundle.getString("update.options.display.name");
}
@Override
public String getHelpTopic() {
return "reference.VersionControl.Git.UpdateProject";
}
@Override
public JComponent createComponent() {
myPanel = new GitUpdateOptionsPanel(mySettings);
return myPanel.getPanel();
}
@Override
public boolean isModified() {
return myPanel.isModified();
}
@Override
public void apply() {
myPanel.applyTo();
}
@Override
public void reset() {
myPanel.updateFrom();
}
@Override
public void disposeUIResources() {
myPanel = null;
}
}
| 22.719298 | 140 | 0.738996 |
ad3943062c2e35c758029889c55cc325ee900268 | 2,493 | package fr.ignishky.fma.generator.converter;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import fr.ignishky.fma.generator.helper.CapitalProvider;
import fr.ignishky.fma.generator.merger.OsmMerger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import static fr.ignishky.fma.generator.utils.Constants.INPUT_FOLDER;
import static fr.ignishky.fma.generator.utils.Constants.OUTPUT_FOLDER;
import static java.lang.String.format;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toList;
@Slf4j
public class CountryConverter {
private final File inputFolder;
private final File outputFolder;
private final CapitalProvider capitalProvider;
private final ZoneConverter zone;
private final OsmMerger osmMerger;
@Inject
CountryConverter(@Named(INPUT_FOLDER) File inputFolder, @Named(OUTPUT_FOLDER) File outputFolder, CapitalProvider capitalProvider,
ZoneConverter zone, OsmMerger osmMerger) {
this.inputFolder = inputFolder;
this.outputFolder = outputFolder;
this.capitalProvider = capitalProvider;
this.zone = zone;
this.osmMerger = osmMerger;
}
public String convert(String countryCode) {
Path countryFile = Paths.get(outputFolder.getPath(), countryCode, countryCode + ".osm.pbf");
if(Files.exists(countryFile)) {
log.info("File {} already exists.", countryFile.toString());
return countryFile.toString();
}
String[] zones = Paths.get(inputFolder.getPath(), countryCode).toFile().list();
if (zones == null || zones.length == 0) {
throw new IllegalArgumentException(format("<inputFolder>/%s must be a valid non-empty directory.", countryCode));
}
log.info("Generate country '{}' with zones : {}", countryCode, zones);
StopWatch watch = StopWatch.createStarted();
capitalProvider.init(countryCode);
List<String> convertedZoneFiles = stream(zones)
.map(zoneCode -> zone.convert(countryCode, zoneCode, capitalProvider))
.collect(toList());
osmMerger.merge(convertedZoneFiles, countryFile);
log.info("Country {} generated in {} ms", countryCode, watch.getTime());
return countryFile.toString();
}
}
| 35.614286 | 133 | 0.702768 |
04a7b52559e7495417b23ace92afb5347e85493e | 150 | package com.fbs.rabbitears.contracts.rss;
/**
* RSS Channel Image Serialization Contract
*/
public class Image
{
public String url;
}
| 15 | 44 | 0.68 |
465b9840b7912b4337a20fd9b987094072340dcf | 2,030 | package com.acai.controller;
import com.acai.model.entidade.Frete;
import com.acai.model.regradenegocio.FreteRN;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
@ManagedBean
@ViewScoped
public class FreteBean {
private FreteRN freteRN = null;
private Frete selectedFrete;
private Frete cadastrarFrete;
public FreteBean() {
this.freteRN = new FreteRN(FreteRN.HIBERNATE_FRETE_DAO);
this.cadastrarFrete = new Frete();
}
public void adicionarFreteAction() {
this.freteRN.salvarFrete(this.cadastrarFrete);
this.cadastrarFrete = new Frete();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Frete cadastrado com sucesso!"));
}
public Frete buscarFreteAction(Integer codigo) {
return (Frete) this.freteRN.buscarFrete(codigo);
}
public void alterarFreteAction() {
this.freteRN.alterarFrete(this.selectedFrete);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ferte alterado com sucesso!"));
}
public void excluirFreteAction() {
this.freteRN.deletarFrete(this.selectedFrete);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Frete deletado com sucesso!"));
}
public List<Frete> listarAction() {
return this.freteRN.buscarTodos();
}
public FreteRN getFreteRN() {
return freteRN;
}
public void setFreteRN(FreteRN freteRN) {
this.freteRN = freteRN;
}
public Frete getSelectedFrete() {
return this.selectedFrete;
}
public void setSelectedFrete(Frete selectedFrete) {
this.selectedFrete = selectedFrete;
}
public Frete getCadastrarFrete() {
return cadastrarFrete;
}
public void setCadastrarFrete(Frete cadastrarFrete) {
this.cadastrarFrete = cadastrarFrete;
}
}
| 28.194444 | 110 | 0.692118 |
7fe859198c4409b37d9984add9549a5f491b6651 | 1,129 | package net.teamio.taam.piping;
import com.builtbroken.mc.testing.junit.AbstractTest;
import com.builtbroken.mc.testing.junit.VoltzTestRunner;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.fluids.FluidTank;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.teamio.taam.content.piping.GenericPipeTests;
import org.junit.runner.RunWith;
/**
* Created by oliver on 2017-07-03.
*/
@RunWith(VoltzTestRunner.class)
public class PipeEndFluidHandlerTest extends AbstractTest {
private PipeEndFluidHandler pipeEndFluidHandler;
private IFluidHandler fluidHandler;
private static final int CAPACITY = 10;
@Override
public void setUpForTest(String name) {
fluidHandler = new FluidTank(CAPACITY);
pipeEndFluidHandler = new PipeEndFluidHandler(null, fluidHandler, EnumFacing.UP);
}
public void testBasicFunctions() {
assertEquals(CAPACITY, pipeEndFluidHandler.getCapacity());
}
public void testGetInternalPipes() {
assertNull(pipeEndFluidHandler.getInternalPipes());
}
public void testFluidAmount() {
GenericPipeTests.testPipeEnd(pipeEndFluidHandler, CAPACITY, true);
}
}
| 27.536585 | 83 | 0.804252 |
91e88b495c2a73772ceddcc2647e232495797a8a | 356 | package com.example.productcatalogservice.services.listener;
import com.example.productcatalogservice.models.ProductOfferingAttributeValueChangeEvent;
public interface ProductOfferingAttributeValueChangeEventService {
ProductOfferingAttributeValueChangeEvent save(ProductOfferingAttributeValueChangeEvent productOfferingAttributeValueChangeEvent);
}
| 44.5 | 133 | 0.907303 |
8df1fa29408673e49517414f5d486568ee5e487c | 1,885 | /*
* Copyright 2020 Johnny850807 (Waterball) 潘冠辰
* 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 tw.waterball.judgegirl.plugins.api.match;
import tw.waterball.judgegirl.primitives.problem.JudgePluginTag;
import tw.waterball.judgegirl.plugins.api.JudgeGirlPlugin;
import tw.waterball.judgegirl.plugins.api.exceptions.MatchPolicyPluginException;
import java.nio.file.Path;
import java.util.Map;
/**
* @author - johnny850807@gmail.com (Waterball)
*/
public interface JudgeGirlMatchPolicyPlugin extends JudgeGirlPlugin {
JudgePluginTag.Type TYPE = JudgePluginTag.Type.OUTPUT_MATCH_POLICY;
/**
* Judge for the status.
*
* @param actualStandardOutputPath the file name of whose stores the actual standard output
* @param expectStandardOutputPath the file name of whose stores the expected standard output
* @param actualToExpectOutputFilePathMap the mapping each entry maps the file name of whose stores one of the
* actual output to the file name of whose stores one of the
* @return true if all actual-to-expect output files matched according to the policy
*/
boolean isMatch(Path actualStandardOutputPath, Path expectStandardOutputPath,
Map<Path, Path> actualToExpectOutputFilePathMap) throws MatchPolicyPluginException;
}
| 44.880952 | 114 | 0.73687 |
fd37759d981180c78b4648c23ea19d2d932a8cfb | 2,542 | package com.beanframework.core.converter.entity.csv;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.beanframework.common.converter.EntityCsvConverter;
import com.beanframework.common.exception.ConverterException;
import com.beanframework.common.service.ModelService;
import com.beanframework.core.csv.MediaCsv;
import com.beanframework.media.domain.Media;
@Component
public class MediaCsvEntityConverter implements EntityCsvConverter<MediaCsv, Media> {
protected static Logger LOGGER = LoggerFactory.getLogger(MediaCsvEntityConverter.class);
@Autowired
private ModelService modelService;
@Override
public Media convert(MediaCsv source) throws ConverterException {
try {
if (StringUtils.isNotBlank(source.getId())) {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(Media.ID, source.getId());
Media prototype = modelService.findOneByProperties(properties, Media.class);
if (prototype != null) {
return convertToEntity(source, prototype);
}
}
return convertToEntity(source, modelService.create(Media.class));
} catch (Exception e) {
throw new ConverterException(e.getMessage(), e);
}
}
private Media convertToEntity(MediaCsv source, Media prototype) throws ConverterException {
try {
if (StringUtils.isNotBlank(source.getId()))
prototype.setId(source.getId());
if (StringUtils.isNotBlank(source.getFileName()))
prototype.setFileName(source.getFileName());
if (StringUtils.isNotBlank(source.getFileType()))
prototype.setFileType(source.getFileType());
if (StringUtils.isNotBlank(source.getUrl()))
prototype.setUrl(source.getUrl());
if (StringUtils.isNotBlank(source.getTitle()))
prototype.setTitle(source.getTitle());
if (StringUtils.isNotBlank(source.getCaption()))
prototype.setCaption(source.getCaption());
if (StringUtils.isNotBlank(source.getAltText()))
prototype.setAltText(source.getAltText());
if (StringUtils.isNotBlank(source.getDescription()))
prototype.setDescription(source.getDescription());
} catch (Exception e) {
e.printStackTrace();
throw new ConverterException(e.getMessage(), e);
}
return prototype;
}
}
| 30.626506 | 93 | 0.725806 |
cfeac66723f5738983793eb0136ce06bd5025235 | 718 | package org.anddev.andengine.util.modifier.ease;
public class EaseExponentialOut implements IEaseFunction
{
private static EaseExponentialOut INSTANCE;
public static EaseExponentialOut getInstance() {
if (EaseExponentialOut.INSTANCE == null) {
EaseExponentialOut.INSTANCE = new EaseExponentialOut();
}
return EaseExponentialOut.INSTANCE;
}
@Override
public float getPercentageDone(final float n, final float n2, final float n3, final float n4) {
double n5;
if (n == n2) {
n5 = n3 + n4;
}
else {
n5 = n4 * (1.0 + -Math.pow(2.0, -10.0f * n / n2)) + n3;
}
return (float)n5;
}
}
| 27.615385 | 99 | 0.594708 |
dd01401504631140567774810cf436cb446ee132 | 8,402 | package com.atlassian.jira.plugins.dvcs.spi.githubenterprise.webwork;
import com.atlassian.event.api.EventPublisher;
import com.atlassian.jira.plugins.dvcs.analytics.event.DvcsType;
import com.atlassian.jira.plugins.dvcs.analytics.event.FailureReason;
import com.atlassian.jira.plugins.dvcs.auth.OAuthStore;
import com.atlassian.jira.plugins.dvcs.auth.OAuthStore.Host;
import com.atlassian.jira.plugins.dvcs.exception.SourceControlException;
import com.atlassian.jira.plugins.dvcs.exception.SourceControlException.InvalidResponseException;
import com.atlassian.jira.plugins.dvcs.model.Credential;
import com.atlassian.jira.plugins.dvcs.model.Organization;
import com.atlassian.jira.plugins.dvcs.service.OrganizationService;
import com.atlassian.jira.plugins.dvcs.spi.github.webwork.GithubOAuthUtils;
import com.atlassian.jira.plugins.dvcs.spi.githubenterprise.GithubEnterpriseCommunicator;
import com.atlassian.jira.plugins.dvcs.util.CustomStringUtils;
import com.atlassian.jira.plugins.dvcs.util.SystemUtils;
import com.atlassian.jira.plugins.dvcs.webwork.CommonDvcsConfigurationAction;
import com.atlassian.jira.security.xsrf.RequiresXsrfCheck;
import com.atlassian.plugin.spring.scanner.annotation.component.Scanned;
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;
import com.atlassian.sal.api.ApplicationProperties;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.atlassian.jira.plugins.dvcs.spi.githubenterprise.GithubEnterpriseCommunicator.GITHUB_ENTERPRISE;
@Scanned
public class AddGithubEnterpriseOrganization extends CommonDvcsConfigurationAction
{
private static final long serialVersionUID = 3680766022095591693L;
private final Logger log = LoggerFactory.getLogger(AddGithubEnterpriseOrganization.class);
private String organization;
private String oauthClientIdGhe;
private String oauthSecretGhe;
// sent by GH on the way back
private String code;
private String url;
private final OrganizationService organizationService;
private final OAuthStore oAuthStore;
private final ApplicationProperties applicationProperties;
public AddGithubEnterpriseOrganization(@ComponentImport ApplicationProperties applicationProperties,
@ComponentImport EventPublisher eventPublisher,
OAuthStore oAuthStore,
OrganizationService organizationService)
{
super(eventPublisher);
this.organizationService = organizationService;
this.oAuthStore = oAuthStore;
this.applicationProperties = applicationProperties;
}
@Override
@RequiresXsrfCheck
protected String doExecute() throws Exception
{
triggerAddStartedEvent(DvcsType.GITHUB_ENTERPRISE);
oAuthStore.store(new Host(GITHUB_ENTERPRISE, url), oauthClientIdGhe, oauthSecretGhe);
// then continue
return redirectUserToGithub();
}
GithubOAuthUtils getGithubOAuthUtils()
{
return new GithubOAuthUtils(applicationProperties.getBaseUrl(), oAuthStore.getClientId(GITHUB_ENTERPRISE), oAuthStore.getSecret(GITHUB_ENTERPRISE));
}
private String redirectUserToGithub()
{
String githubAuthorizeUrl = getGithubOAuthUtils().createGithubRedirectUrl("AddOrganizationProgressAction!default",
url, getXsrfToken(), organization, getAutoLinking(), getAutoSmartCommits());
// param "t" is holding information where to redirect from "wainting screen" (AddBitbucketOrganization, AddGithubOrganization ...)
return SystemUtils.getRedirect(this, githubAuthorizeUrl + urlEncode("&t=3"), true);
}
@Override
protected void doValidation()
{
if (StringUtils.isBlank(url) || StringUtils.isBlank(organization))
{
addErrorMessage("Please provide both url and organization parameters.");
}
if (!SystemUtils.isValid(url))
{
addErrorMessage("Please provide valid GitHub host URL.");
}
if (url.endsWith("/"))
{
url = StringUtils.chop(url);
}
//TODO validation of account is disabled because of private mode
// AccountInfo accountInfo = organizationService.getAccountInfo(url, organization);
// if (accountInfo == null)
// {
// addErrorMessage("Invalid user/team account.");
// }
if (organizationService.getByHostAndName(url, organization) != null)
{
addErrorMessage("Account is already integrated with JIRA.");
}
if (invalidInput())
{
triggerAddFailedEvent(FailureReason.VALIDATION);
}
}
public String doFinish()
{
try
{
return doAddOrganization(getGithubOAuthUtils().requestAccessToken(url, code));
} catch (InvalidResponseException ire)
{
addErrorMessage(ire.getMessage() + " Possibly bug in releases of GitHub Enterprise prior to 11.10.290.");
triggerAddFailedEvent(FailureReason.OAUTH_RESPONSE);
return INPUT;
} catch (SourceControlException sce)
{
addErrorMessage(sce.getMessage());
log.warn(sce.getMessage());
if ( sce.getCause() != null )
{
log.warn("Caused by: " + sce.getCause().getMessage());
}
triggerAddFailedEvent(FailureReason.OAUTH_SOURCECONTROL);
return INPUT;
} catch (Exception e)
{
addErrorMessage("Error obtaining access token.");
triggerAddFailedEvent(FailureReason.OAUTH_GENERIC);
return INPUT;
}
}
private String doAddOrganization(String accessToken)
{
try
{
Organization newOrganization = new Organization();
newOrganization.setName(organization);
newOrganization.setHostUrl(url);
newOrganization.setDvcsType(GithubEnterpriseCommunicator.GITHUB_ENTERPRISE);
newOrganization.setAutolinkNewRepos(hadAutolinkingChecked());
newOrganization.setCredential(new Credential(oAuthStore.getClientId(GITHUB_ENTERPRISE), oAuthStore.getSecret(GITHUB_ENTERPRISE), accessToken));
newOrganization.setSmartcommitsOnNewRepos(hadAutolinkingChecked());
organizationService.save(newOrganization);
} catch (SourceControlException e)
{
addErrorMessage("Failed adding the account: [" + e.getMessage() + "]");
log.debug("Failed adding the account: [" + e.getMessage() + "]");
e.printStackTrace();
triggerAddFailedEvent(FailureReason.OAUTH_SOURCECONTROL);
return INPUT;
}
triggerAddSucceededEvent(DvcsType.GITHUB_ENTERPRISE);
return getRedirect("ConfigureDvcsOrganizations.jspa?atl_token=" + CustomStringUtils.encode(getXsrfToken()) +
getSourceAsUrlParam());
}
public static String encode(String url)
{
return CustomStringUtils.encode(url);
}
public String getCode()
{
return code;
}
public void setCode(String code)
{
this.code = code;
}
public String getOrganization()
{
return organization;
}
public void setOrganization(String organization)
{
this.organization = organization;
}
public String getOauthClientIdGhe()
{
return oAuthStore.getClientId(GITHUB_ENTERPRISE);
}
public void setOauthClientIdGhe(String oauthClientIdGhe)
{
this.oauthClientIdGhe = oauthClientIdGhe;
}
public String getOauthSecretGhe()
{
return oAuthStore.getSecret(GITHUB_ENTERPRISE);
}
public void setOauthSecretGhe(String oauthSecretGhe)
{
this.oauthSecretGhe = oauthSecretGhe;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
private void triggerAddFailedEvent(FailureReason reason)
{
super.triggerAddFailedEvent(DvcsType.GITHUB_ENTERPRISE, reason);
}
}
| 34.719008 | 157 | 0.675077 |
7c3b20542fe4c7430f5c9bc4fac71b45eca52d69 | 2,812 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.workbench.screens.guided.dtable.client.widget.table.utilities;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import org.drools.workbench.models.guided.dtable.shared.model.DTCellValue52;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.junit.Assert.*;
@RunWith(Parameterized.class)
public class CellUtilitiesConvertToIntegerTest {
private Object expected;
private Object value;
private boolean isOtherwise;
private CellUtilities cellUtilities;
public CellUtilitiesConvertToIntegerTest( final Object expected,
final Object value,
final boolean isOtherwise ) {
this.expected = expected;
this.value = value;
this.isOtherwise = isOtherwise;
}
@Before
public void setup() {
cellUtilities = new CellUtilities();
}
@Parameterized.Parameters
public static Collection testParameters() {
return Arrays.asList( new Object[][]{
{ new Integer( "1" ), new BigDecimal( "1" ), false },
{ new Integer( "2" ), new BigInteger( "2" ), false },
{ new Integer( "3" ), new Byte( "3" ), false },
{ null, new Double( "4.0" ), false },
{ null, new Float( "5.0" ), false },
{ new Integer( "6" ), new Integer( "6" ), false },
{ new Integer( "7" ), new Long( "7" ), false },
{ new Integer( "8" ), new Short( "8" ), false },
{ new Integer( "9" ), "9", false },
{ null, true, false },
{ null, new Date(), false },
{ null, "banana", false },
{ null, null, true }
} );
}
@Test
public void conversion() {
final DTCellValue52 dcv = new DTCellValue52( value );
dcv.setOtherwise( isOtherwise );
assertEquals( expected,
cellUtilities.convertToInteger( dcv ) );
}
}
| 33.879518 | 81 | 0.605263 |
42e956fb298ea07f5473b2ba27d0675212aa0e2a | 4,229 | /* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package net.sf.mmm.util.datatype.api.color;
import org.junit.Assert;
import org.junit.Test;
import net.sf.mmm.util.lang.api.BasicHelper;
/**
* This is the test-case for {@link Color}.
*
* @author Joerg Hohwiller (hohwille at users.sourceforge.net)
* @since 1.0.0
*/
public class ColorTest extends Assert {
/**
* Positive tests of {@link Color} for legal RGB values.
*/
@Test
public void testRgbColor() {
// int step = 1;
// for speed and performance increase step...
int step = 7;
for (int i = 0; i <= 0xFFFFFF; i = i + step) {
int rgba = i | 0xFF000000;
Color color = new Color(rgba);
Integer integer = Integer.valueOf(rgba);
assertEquals(integer, color.getValue());
// test string representation
String colorString = color.toString();
String hex = BasicHelper.toUpperCase(Integer.toString(i, 16));
while (hex.length() < 6) {
hex = "0" + hex;
}
assertEquals("#" + hex, colorString);
assertEquals(colorString, color.toString());
checkColorGeneric(color, colorString);
}
}
/**
* Positive tests of {@link Color} for legal RGBA values.
*/
@Test
public void testRgbaColor() {
for (int i = 0; i <= 0xFF; i++) {
int rgba = (i << 24) | 0x1F2F3F;
Color color = new Color(rgba);
Integer rgbaInteger = Integer.valueOf(rgba);
assertEquals(rgbaInteger, color.getValue());
assertEquals(i, color.getAlpha());
assertEquals(0x1F, color.getRed());
assertEquals(0x2F, color.getGreen());
assertEquals(0x3F, color.getBlue());
// test string representation
String colorString = color.toString();
if (i == 255) {
assertEquals("#1F2F3F", colorString);
} else {
assertEquals("rgba(31,47,63," + i / 255.0 + ")", colorString);
}
checkColorGeneric(color, colorString);
}
}
/**
* Performs generic checks on the given {@link Color}.
*
* @param color is the {@link Color} to test.
* @param colorString is the expected {@link Color#toString() string representation} of the {@link Color}.
*/
private void checkColorGeneric(Color color, String colorString) {
// test copy from RGBA values
Color copy = new Color(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
assertEquals(color, copy);
// test copy from String representation
copy = Color.valueOf(colorString);
assertEquals(color, copy);
// test copy from RGBA String representation
String rgbString = "rgba(" + color.getRed() + "," + color.getGreen() + ", " + color.getBlue() + "," + new Alpha(color.getAlpha()) + ")";
copy = Color.valueOf(rgbString);
assertEquals(color, copy);
// // test copy from HSBA values
// copy = Color.fromHsba(color.getHue(), color.getSaturationHsb(), color.getBrightness(),
// color.getAlphaRate());
// assertEquals(color, copy);
// // test copy from HSLA values
// copy = Color.fromHsla(color.getHue(), color.getSaturationHsl(), color.getLightness(),
// color.getAlphaRate());
// // assertEquals(color, copy);
// if (!color.equals(copy)) {
// System.out.println(color + " -> " + copy);
// }
// regression against java.awt.Color
// test RGB
java.awt.Color awtColor = new java.awt.Color(color.getValue().intValue());
assertEquals(colorString, awtColor.getRed(), color.getRed());
assertEquals(colorString, awtColor.getGreen(), color.getGreen());
assertEquals(colorString, awtColor.getBlue(), color.getBlue());
// test HSB
// float[] hsb = java.awt.Color.RGBtoHSB(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue(),
// null);
// // double delta = 0.0000000001;
// double delta = 0.000001;
// // float hue = color.getHue();
// // assertEquals(colorString, hsb[0], hue, delta);
// // float saturation = color.getSaturationHsb();
// // assertEquals(colorString, hsb[1], saturation, delta);
// // float brightness = color.getBrightness();
// // assertEquals(colorString, hsb[2], brightness, delta);
}
}
| 34.663934 | 140 | 0.631828 |
814c47fcb9860f21df563eb6f770a35850e149dc | 833 | package de.illonis.eduras.shapecreator.templates;
import java.util.LinkedList;
import org.newdawn.slick.geom.Vector2f;
import de.illonis.eduras.math.Vector2df;
/**
* A template for editable shapes.
*
* @author illonis
*
*/
public abstract class ShapeTemplate {
private final LinkedList<Vector2f> vertices;
protected ShapeTemplate() {
vertices = new LinkedList<Vector2f>();
}
/**
* @return name of the template.
*/
public abstract String getName();
protected final void addVector2df(Vector2f v) {
vertices.add(v);
}
protected final void addVector2df(float x, float y) {
vertices.add(new Vector2df(x, y));
}
public final LinkedList<Vector2f> getDefaultVector2dfs() {
return vertices;
}
@Override
public String toString() {
return getName();
}
}
| 18.511111 | 60 | 0.679472 |
a9417c22e302f3a04f9e6f5f8f2a4c5fab31f83f | 1,469 | /*
* Copyright 2019 Vijayakumar Mohan
*
* 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.iomolecule.util;
import com.iomolecule.config.ConfigurationException;
import com.iomolecule.config.ConfigurationSource;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class ModuleUtils {
public static <T> T getConfig(String configPath,Class<T> configClass, ConfigurationSource configurationSource,T defaultConfig){
T finalConfig = defaultConfig;
if(configurationSource.isValid(configPath)){
try {
finalConfig = configurationSource.get(configPath, configClass);
} catch (ConfigurationException e) {
log.info("Unable to load config for path {}, so defaulting to {}",configPath,defaultConfig);
}
}else{
log.info("Unable to load config for path {}, so defaulting to {}",configPath,defaultConfig);
}
return finalConfig;
}
}
| 33.386364 | 131 | 0.701157 |
1b9e84cdd26fa98cdfd24f6d06ba7b10ba5a4fbf | 56 | package game;
public enum GameLevels {
MENU,
TEST,
}
| 8 | 24 | 0.696429 |
e82e157b729bfb59d66ebf54f44332840dddd47b | 725 | package com.fitzguru.mfaauction;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.widget.TextView;
/**
* Created by jtsuji on 11/14/14.
*/
public class DisplayUtils {
static Typeface pictos;
public static Typeface getPictosTypeface(Context context) {
if (pictos == null)
pictos = Typeface.createFromAsset(context.getAssets(), "fonts/HSMobilePictos.ttf");
return pictos;
}
public static int toPx(int dp) {
return (int) ((dp * Resources.getSystem().getDisplayMetrics().density) + 0.5);
}
public static void pictosifyTextView(TextView textView) {
textView.setTypeface(getPictosTypeface(textView.getContext()));
}
}
| 25.892857 | 89 | 0.735172 |
e59d91f1eddd513ff416241e58dbf7d9bda7ddb5 | 2,154 | package core.arraylist;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ArrayListTest {
@Test
public void createArrayList() {
// Create untyped ArrayList
ArrayList list = new ArrayList();
// You can add object of any type
list.add("String");
list.add(Boolean.TRUE);
assertEquals(list, Arrays.asList("String", Boolean.TRUE));
}
@Test
public void createTypedArrayList() {
// Create typed ArrayList
ArrayList<String> list = new ArrayList<>();
// You can add only String objects
list.add("String");
assertEquals(list, Collections.singletonList("String"));
// COMPILE ERROR!
// list.add(new Object());
}
@Test
public void createTypedList() {
// You can use polymorphic variable of type List
// List is an interface implemented by ArrayList
// Import java.util.List to use List
List<String> list = new ArrayList<>();
list.add("String");
assertEquals(list, Collections.singletonList("String"));
}
@Test
public void createListWithInitialCapacity() {
// Don't mess ArrayList capacity and size
// Capacity is an initial number of slots for values
// Size is a number of used slots
// Capacity is 10 by default
List<String> list1 = new ArrayList<>();
// You can set capacity using constructor of ArrayList
List<String> list2 = new ArrayList<>(20);
assertTrue(list1.isEmpty());
assertTrue(list2.isEmpty());
assertTrue(list1.equals(list2));
}
@Test
public void createListFromList() {
// Create a list of stock symbols
List<String> list = new ArrayList<>();
list.add("AAPL");
list.add("MSFT");
// Create a copy using constructor of ArrayList
List<String> copy = new ArrayList<>(list);
assertTrue(list.equals(copy));
}
@Test
public void createListWithArraysUtil() {
// Create a list of stock symbols
List<String> list = new ArrayList<>();
list.add("AAPL");
list.add("MSFT");
List<String> copy = Arrays.asList("AAPL", "MSFT");
assertTrue(list.equals(copy));
}
}
| 22.673684 | 60 | 0.701486 |
625e281792ede309c31fddff616fcf0373fe75a4 | 2,055 | /*-
* ============LICENSE_START=======================================================
* ONAP - SO
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.openecomp.mso.client.aai;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.openecomp.mso.client.aai.entities.AAIError;
public class AAIExceptionMapperTest {
@Mock private AAIError errorObj;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void nestedReplace() {
String error = "Error %1 on %2";
List<String> list = Arrays.asList("PUT", "hello %1");
AAIErrorFormatter formatter = new AAIErrorFormatter(errorObj);
String result = formatter.fillInTemplate(error, list);
assertEquals("equal", "Error PUT on hello PUT", result);
}
@Test
public void noReplace() {
String error = "Error";
List<String> list = new ArrayList<>();
AAIErrorFormatter formatter = new AAIErrorFormatter(errorObj);
String result = formatter.fillInTemplate(error, list);
assertEquals("equal", "Error", result);
}
}
| 32.109375 | 83 | 0.628224 |
856c8dd4087c91ea54e63710186eef3cf86fa05f | 694 | package de.hska.vis.webshop.core.database.model;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import de.hska.vis.webshop.core.database.model.deserializer.UserDeserializer;
import de.hska.vis.webshop.core.database.model.impl.Role;
@JsonDeserialize(using = UserDeserializer.class)
public interface IUser {
int getId();
void setId(int id);
String getUsername();
void setUsername(String username);
String getFirstname();
void setFirstname(String firstname);
String getLastname();
void setLastname(String lastname);
String getPassword();
void setPassword(String password);
Role getRole();
void setRole(Role role);
}
| 20.411765 | 77 | 0.737752 |
c923d31963f9bd62e780afe00ce5dc318b45dd8a | 277 | package com.ilvdo.ilvdo_http_android.restclient;
/**
* Created by sjy on 2018/12/24
* Describe 请求类别
*/
public enum RestType {
//post请求
POST,
//get 请求
GET,
//文件删除
DELETE,
//单文件上传
FILE,
//json上传
JSON,
// 文件参数混合上传
FILE_MULTI
}
| 12.590909 | 48 | 0.577617 |
9067110117855261ae9e67f6088c8c04c50d8104 | 747 | // InterfaceProviderSpecConstants.java is auto generated by mojom_bindings_generator.py, do not edit
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is autogenerated by:
// mojo/public/tools/bindings/mojom_bindings_generator.py
// For:
// services/service_manager/public/mojom/interface_provider_spec.mojom
//
package org.chromium.service_manager.mojom;
import androidx.annotation.IntDef;
public final class InterfaceProviderSpecConstants {
public static final String SERVICE_MANAGER_CONNECTOR_SPEC = (String) "service_manager:connector";
private InterfaceProviderSpecConstants() {}
} | 26.678571 | 101 | 0.781794 |
e85786d0281f688707f07e02e6fd23fd942a60fd | 792 | /**
* Copyright (C) 2018-2020
* All rights reserved, Designed By www.yixiang.co
* 注意:
* 本软件为www.yixiang.co开发研制,未经购买不得使用
* 购买后可获得全部源代码(禁止转卖、分享、上传到码云、github等开源平台)
* 一经发现盗用、分享等行为,将追究法律责任,后果自负
*/
package co.yixiang.modules.msh.service.dto;
import lombok.Data;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
/**
* @author cq
* @date 2020-12-25
*/
@Data
public class MshOrderAuditDto implements Serializable {
private Integer id;
/** 需求单主表ID */
private Integer demandListId;
/** 外部订单号 */
private String externalOrderId;
/** 订单状态 */
private String orderStatus;
/** 订单状态Str */
private String orderStatusStr;
/** 审核原因 */
private String auditReasons;
/** 审核人 */
private String auditName;
}
| 20.307692 | 55 | 0.690657 |
56e98449b4748a23159cf2011b1a9c5c4a056221 | 702 | package org.modernclients.ch3.samples;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.Pane;
import org.modernclients.ch3.Sample;
import java.util.function.Consumer;
/**
* @author Jonathan Giles <jonathan@jonathangiles.net>
*/
public class CheckBoxDemo implements Sample {
@Override
public void buildDemo(Pane container, Consumer<String> console) {
CheckBox cb = new CheckBox("Enable Power Plant");
cb.setIndeterminate(false);
cb.setOnAction(e -> console.accept("Action event fired"));
cb.selectedProperty().addListener(i -> console.accept("Selected state change to " + cb.isSelected()));
container.getChildren().add(cb);
}
}
| 29.25 | 110 | 0.712251 |
ee6a4b59a11666e854e66ff1df9dbcf537007dd8 | 26,305 | /*
* 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.isis.viewer.wicket.model.models;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.wicket.request.IRequestHandler;
import org.apache.wicket.request.handler.resource.ResourceStreamRequestHandler;
import org.apache.wicket.request.http.handler.RedirectRequestHandler;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.ContentDisposition;
import org.apache.wicket.util.resource.AbstractResourceStream;
import org.apache.wicket.util.resource.IResourceStream;
import org.apache.wicket.util.resource.ResourceStreamNotFoundException;
import org.apache.wicket.util.resource.StringResourceStream;
import org.apache.isis.applib.Identifier;
import org.apache.isis.applib.annotation.BookmarkPolicy;
import org.apache.isis.applib.annotation.PromptStyle;
import org.apache.isis.applib.annotation.Where;
import org.apache.isis.applib.services.routing.RoutingService;
import org.apache.isis.applib.value.Blob;
import org.apache.isis.applib.value.Clob;
import org.apache.isis.applib.value.LocalResourcePath;
import org.apache.isis.applib.value.NamedWithMimeType;
import org.apache.isis.commons.collections.Can;
import org.apache.isis.commons.internal.base._NullSafe;
import org.apache.isis.commons.internal.collections._Maps;
import org.apache.isis.metamodel.adapter.oid.Oid;
import org.apache.isis.metamodel.adapter.oid.RootOid;
import org.apache.isis.metamodel.consent.Consent;
import org.apache.isis.metamodel.consent.InteractionInitiatedBy;
import org.apache.isis.metamodel.facetapi.Facet;
import org.apache.isis.metamodel.facetapi.FacetHolder;
import org.apache.isis.metamodel.facets.object.bookmarkpolicy.BookmarkPolicyFacet;
import org.apache.isis.metamodel.facets.object.encodeable.EncodableFacet;
import org.apache.isis.metamodel.facets.object.promptStyle.PromptStyleFacet;
import org.apache.isis.metamodel.spec.ActionType;
import org.apache.isis.metamodel.spec.ManagedObject;
import org.apache.isis.metamodel.spec.ObjectSpecId;
import org.apache.isis.metamodel.spec.ObjectSpecification;
import org.apache.isis.metamodel.spec.feature.ObjectAction;
import org.apache.isis.metamodel.spec.feature.ObjectActionParameter;
import org.apache.isis.metamodel.specloader.SpecificationLoader;
import org.apache.isis.viewer.wicket.model.common.PageParametersUtils;
import org.apache.isis.viewer.wicket.model.mementos.ActionMemento;
import org.apache.isis.viewer.wicket.model.mementos.ActionParameterMemento;
import org.apache.isis.viewer.wicket.model.mementos.PageParameterNames;
import org.apache.isis.webapp.context.IsisWebAppCommonContext;
import lombok.val;
public class ActionModel extends BookmarkableModel<ManagedObject> implements FormExecutorContext {
private static final long serialVersionUID = 1L;
private static final String NULL_ARG = "$nullArg$";
private static final Pattern KEY_VALUE_PATTERN = Pattern.compile("([^=]+)=(.+)");
public ActionModel copy() {
return new ActionModel(this);
}
// -- FACTORY METHODS
/**
* @param entityModel
* @param action
* @return
*/
public static ActionModel create(EntityModel entityModel, ObjectAction action) {
val homePageActionMemento = new ActionMemento(action);
val actionModel = new ActionModel(entityModel, homePageActionMemento);
return actionModel;
}
public static ActionModel createForPersistent(
IsisWebAppCommonContext commonContext,
PageParameters pageParameters) {
val entityModel = newEntityModelFrom(commonContext, pageParameters);
val actionMemento = newActionMementoFrom(commonContext, pageParameters);
val actionModel = new ActionModel(entityModel, actionMemento);
actionModel.setArgumentsIfPossible(pageParameters);
actionModel.setContextArgumentIfPossible(pageParameters);
return actionModel;
}
/**
* Factory method for creating {@link PageParameters}.
*
* see {@link #ActionModel(PageParameters, SpecificationLoader)}
*/
public static PageParameters createPageParameters(ManagedObject adapter, ObjectAction objectAction) {
val pageParameters = PageParametersUtils.newPageParameters();
val oidStr = ManagedObject._identify(adapter).enString();
PageParameterNames.OBJECT_OID.addStringTo(pageParameters, oidStr);
val actionType = objectAction.getType();
PageParameterNames.ACTION_TYPE.addEnumTo(pageParameters, actionType);
val actionOnTypeSpec = objectAction.getOnType();
if (actionOnTypeSpec != null) {
PageParameterNames.ACTION_OWNING_SPEC.addStringTo(pageParameters, actionOnTypeSpec.getFullIdentifier());
}
val actionId = determineActionId(objectAction);
PageParameterNames.ACTION_ID.addStringTo(pageParameters, actionId);
return pageParameters;
}
public static Entry<Integer, String> parse(final String paramContext) {
final Matcher matcher = KEY_VALUE_PATTERN.matcher(paramContext);
if (!matcher.matches()) {
return null;
}
final int paramNum;
try {
paramNum = Integer.parseInt(matcher.group(1));
} catch (final Exception e) {
// ignore
return null;
}
final String oidStr;
try {
oidStr = matcher.group(2);
} catch (final Exception e) {
return null;
}
return new Map.Entry<Integer, String>() {
@Override
public Integer getKey() {
return paramNum;
}
@Override
public String getValue() {
return oidStr;
}
@Override
public String setValue(final String value) {
return null;
}
};
}
//////////////////////////////////////////////////
// BookmarkableModel
//////////////////////////////////////////////////
@Override
public PageParameters getPageParametersWithoutUiHints() {
val adapter = getTargetAdapter();
val objectAction = getAction();
val pageParameters = createPageParameters(adapter, objectAction);
// capture argument values
for(val argumentAdapter: getArgumentsAsImmutable()) {
val encodedArg = encodeArg(argumentAdapter);
PageParameterNames.ACTION_ARGS.addStringTo(pageParameters, encodedArg);
}
return pageParameters;
}
@Override
public PageParameters getPageParameters() {
return getPageParametersWithoutUiHints();
}
@Override
public String getTitle() {
val adapter = getTargetAdapter();
final ObjectAction objectAction = getAction();
final StringBuilder buf = new StringBuilder();
for(val argumentAdapter: getArgumentsAsImmutable()) {
if(buf.length() > 0) {
buf.append(",");
}
buf.append(abbreviated(titleOf(argumentAdapter), 8));
}
return adapter.titleString(null) + "." + objectAction.getName() + (buf.length()>0?"(" + buf.toString() + ")":"");
}
@Override
public boolean hasAsRootPolicy() {
return true;
}
//////////////////////////////////////////////////
// helpers
//////////////////////////////////////////////////
private static String titleOf(ManagedObject argumentAdapter) {
return argumentAdapter!=null?argumentAdapter.titleString(null):"";
}
private static String abbreviated(final String str, final int maxLength) {
return str.length() < maxLength ? str : str.substring(0, maxLength - 3) + "...";
}
private static String determineActionId(final ObjectAction objectAction) {
final Identifier identifier = objectAction.getIdentifier();
if (identifier != null) {
return identifier.toNameParmsIdentityString();
}
// fallback (used for action sets)
return objectAction.getId();
}
private final EntityModel entityModel;
private final ActionMemento actionMemento;
/**
* Lazily populated in {@link #getArgumentModel(ActionParameterMemento)}
*/
private final Map<Integer, ActionArgumentModel> arguments = _Maps.newHashMap();
private static ActionMemento newActionMementoFrom(
IsisWebAppCommonContext commonContext,
PageParameters pageParameters) {
final ObjectSpecId owningSpec = ObjectSpecId.of(PageParameterNames.ACTION_OWNING_SPEC.getStringFrom(pageParameters));
final ActionType actionType = PageParameterNames.ACTION_TYPE.getEnumFrom(pageParameters, ActionType.class);
final String actionNameParms = PageParameterNames.ACTION_ID.getStringFrom(pageParameters);
return new ActionMemento(owningSpec, actionType, actionNameParms, commonContext.getSpecificationLoader());
}
private static EntityModel newEntityModelFrom(
IsisWebAppCommonContext commonContext,
PageParameters pageParameters) {
val rootOid = oidFor(pageParameters);
if(rootOid.isTransient()) {
return null;
} else {
val memento = commonContext.mementoFor(rootOid);
return EntityModel.ofMemento(commonContext, memento);
}
}
private static RootOid oidFor(final PageParameters pageParameters) {
final String oidStr = PageParameterNames.OBJECT_OID.getStringFrom(pageParameters);
return Oid.unmarshaller().unmarshal(oidStr, RootOid.class);
}
private ActionModel(EntityModel entityModel, ActionMemento actionMemento) {
super(entityModel.getCommonContext());
this.entityModel = entityModel;
this.actionMemento = actionMemento;
}
@Override
public EntityModel getParentEntityModel() {
return entityModel;
}
/**
* Copy constructor, as called by {@link #copy()}.
* @param commonContext
*/
private ActionModel(ActionModel actionModel) {
super(actionModel.getCommonContext());
this.entityModel = actionModel.entityModel;
this.actionMemento = actionModel.actionMemento;
primeArgumentModels();
val argumentModelByIdx = actionModel.arguments;
for (val argumentModel : argumentModelByIdx.entrySet()) {
setArgument(argumentModel.getKey(), argumentModel.getValue().getObject());
}
}
private void setArgumentsIfPossible(final PageParameters pageParameters) {
final List<String> args = PageParameterNames.ACTION_ARGS.getListFrom(pageParameters);
val action = actionMemento.getAction(getSpecificationLoader());
val parameterTypes = action.getParameterTypes();
for (int paramNum = 0; paramNum < args.size(); paramNum++) {
final String encoded = args.get(paramNum);
setArgument(paramNum, parameterTypes.getOrThrow(paramNum), encoded);
}
}
private ObjectAction getAction() {
return getActionMemento().getAction(getSpecificationLoader());
}
public boolean hasParameters() {
return getAction().getParameterCount() > 0;
}
private boolean setContextArgumentIfPossible(final PageParameters pageParameters) {
final String paramContext = PageParameterNames.ACTION_PARAM_CONTEXT.getStringFrom(pageParameters);
if (paramContext == null) {
return false;
}
val action = actionMemento.getAction(getSpecificationLoader());
val parameterTypes = action.getParameterTypes();
final int parameterCount = parameterTypes.size();
final Map.Entry<Integer, String> mapEntry = parse(paramContext);
final int paramNum = mapEntry.getKey();
if (paramNum >= parameterCount) {
return false;
}
final String encoded = mapEntry.getValue();
setArgument(paramNum, parameterTypes.getOrThrow(paramNum), encoded);
return true;
}
private void setArgument(final int paramNum, final ObjectSpecification argSpec, final String encoded) {
val argumentAdapter = decodeArg(argSpec, encoded);
setArgument(paramNum, argumentAdapter);
}
private String encodeArg(ManagedObject adapter) {
if(adapter == null) {
return NULL_ARG;
}
final ObjectSpecification objSpec = adapter.getSpecification();
if(objSpec.isEncodeable()) {
final EncodableFacet encodeable = objSpec.getFacet(EncodableFacet.class);
return encodeable.toEncodedString(adapter);
}
return ManagedObject._identify(adapter).enString();
}
private ManagedObject decodeArg(final ObjectSpecification objSpec, final String encoded) {
if(NULL_ARG.equals(encoded)) {
return null;
}
if(objSpec.isEncodeable()) {
final EncodableFacet encodeable = objSpec.getFacet(EncodableFacet.class);
return encodeable.fromEncodedString(encoded);
}
try {
val rootOid = RootOid.deStringEncoded(encoded);
return ManagedObject._adapterOfRootOid(super.getSpecificationLoader(), rootOid);
} catch (final Exception e) {
return null;
}
}
private void setArgument(int paramNum, ManagedObject argumentAdapter) {
final ObjectAction action = actionMemento.getAction(getSpecificationLoader());
final ObjectActionParameter actionParam = action.getParameters().getOrThrow(paramNum);
final ActionParameterMemento apm = new ActionParameterMemento(actionParam);
final ActionArgumentModel actionArgumentModel = getArgumentModel(apm);
actionArgumentModel.setObject(argumentAdapter);
}
public ActionArgumentModel getArgumentModel(final ActionParameterMemento apm) {
final int i = apm.getNumber();
ActionArgumentModel actionArgumentModel = arguments.get(i);
if (actionArgumentModel == null) {
actionArgumentModel = new ScalarModel(entityModel, apm);
final int number = actionArgumentModel.getParameterMemento().getNumber();
arguments.put(number, actionArgumentModel);
}
return actionArgumentModel;
}
public ManagedObject getTargetAdapter() {
return entityModel.load();
}
public ActionMemento getActionMemento() {
return actionMemento;
}
@Override
protected ManagedObject load() {
// from getObject()/reExecute
detach(); // force re-execute
// TODO: think we need another field to determine if args have been populated.
val results = executeAction();
return results;
}
// REVIEW: should provide this rendering context, rather than hardcoding.
// the net effect currently is that class members annotated with
// @Hidden(where=Where.ANYWHERE) or @Disabled(where=Where.ANYWHERE) will indeed
// be hidden/disabled, but will be visible/enabled (perhaps incorrectly)
// for any other value for Where
public static final Where WHERE_FOR_ACTION_INVOCATION = Where.ANYWHERE;
private ManagedObject executeAction() {
val targetAdapter = getTargetAdapter();
val arguments = getArgumentsAsImmutable();
final ObjectAction action = getAction();
// if this action is a mixin, then it will fill in the details automatically.
val mixedInAdapter = (ManagedObject)null;
val resultAdapter =
action.executeWithRuleChecking(
targetAdapter, mixedInAdapter, arguments,
InteractionInitiatedBy.USER,
WHERE_FOR_ACTION_INVOCATION);
final Stream<RoutingService> routingServices = super.getServiceRegistry()
.select(RoutingService.class)
.stream();
val resultPojo = resultAdapter != null ? resultAdapter.getPojo() : null;
return routingServices
.filter(routingService->routingService.canRoute(resultPojo))
.map(routingService->routingService.route(resultPojo))
.filter(_NullSafe::isPresent)
.map(super.getPojoToAdapter())
.filter(_NullSafe::isPresent)
.findFirst()
.orElse(resultAdapter);
}
public String getReasonDisabledIfAny() {
val targetAdapter = getTargetAdapter();
final ObjectAction objectAction = getAction();
final Consent usability =
objectAction.isUsable(
targetAdapter,
InteractionInitiatedBy.USER,
Where.OBJECT_FORMS);
final String disabledReasonIfAny = usability.getReason();
return disabledReasonIfAny;
}
public boolean isVisible() {
val targetAdapter = getTargetAdapter();
val objectAction = getAction();
final Consent visibility =
objectAction.isVisible(
targetAdapter,
InteractionInitiatedBy.USER,
Where.OBJECT_FORMS);
return visibility.isAllowed();
}
public String getReasonInvalidIfAny() {
val targetAdapter = getTargetAdapter();
val proposedArguments = getArgumentsAsImmutable();
final ObjectAction objectAction = getAction();
final Consent validity = objectAction
.isProposedArgumentSetValid(targetAdapter, proposedArguments, InteractionInitiatedBy.USER);
return validity.isAllowed() ? null : validity.getReason();
}
@Override
public void setObject(final ManagedObject object) {
throw new UnsupportedOperationException("target adapter for ActionModel cannot be changed");
}
public Can<ManagedObject> getArgumentsAsImmutable() {
if(this.arguments.size() < getAction().getParameterCount()) {
primeArgumentModels();
}
final ObjectAction objectAction = getAction();
final ManagedObject[] arguments = new ManagedObject[objectAction.getParameterCount()];
for (int i = 0; i < arguments.length; i++) {
final ActionArgumentModel actionArgumentModel = this.arguments.get(i);
arguments[i] = actionArgumentModel.getObject();
}
return Can.ofArray(arguments);
}
@Override
public void reset() {
}
public void clearArguments() {
for (final ActionArgumentModel actionArgumentModel : arguments.values()) {
actionArgumentModel.reset();
}
}
/**
* Bookmarkable if the {@link ObjectAction action} has a {@link BookmarkPolicyFacet bookmark} policy
* of {@link BookmarkPolicy#AS_ROOT root}, and has safe {@link ObjectAction#getSemantics() semantics}.
*/
public boolean isBookmarkable() {
final ObjectAction action = getAction();
final BookmarkPolicyFacet bookmarkPolicy = action.getFacet(BookmarkPolicyFacet.class);
final boolean safeSemantics = action.getSemantics().isSafeInNature();
return bookmarkPolicy.value() == BookmarkPolicy.AS_ROOT && safeSemantics;
}
// //////////////////////////////////////
/**
* Simply executes the action.
*
* Previously there was exception handling code here also, but this has now been centralized
* within FormExecutorAbstract
*/
public ManagedObject execute() {
final ManagedObject resultAdapter = this.getObject();
return resultAdapter;
}
// //////////////////////////////////////
public static IRequestHandler redirectHandler(final Object value) {
if(value instanceof java.net.URL) {
final java.net.URL url = (java.net.URL) value;
return new RedirectRequestHandler(url.toString());
}
if(value instanceof LocalResourcePath) {
final LocalResourcePath localResourcePath = (LocalResourcePath) value;
return new RedirectRequestHandler(localResourcePath.getPath());
}
return null;
}
public static IRequestHandler downloadHandler(final Object value) {
if(value instanceof Clob) {
final Clob clob = (Clob)value;
return handlerFor(resourceStreamFor(clob), clob);
}
if(value instanceof Blob) {
final Blob blob = (Blob)value;
return handlerFor(resourceStreamFor(blob), blob);
}
return null;
}
private static IResourceStream resourceStreamFor(final Blob blob) {
final IResourceStream resourceStream = new AbstractResourceStream() {
private static final long serialVersionUID = 1L;
@Override
public InputStream getInputStream() throws ResourceStreamNotFoundException {
return new ByteArrayInputStream(blob.getBytes());
}
@Override
public String getContentType() {
return blob.getMimeType().toString();
}
@Override
public void close() throws IOException {
}
};
return resourceStream;
}
private static IResourceStream resourceStreamFor(final Clob clob) {
final IResourceStream resourceStream = new StringResourceStream(clob.getChars(), clob.getMimeType().toString());
return resourceStream;
}
private static IRequestHandler handlerFor(final IResourceStream resourceStream, final NamedWithMimeType namedWithMimeType) {
final ResourceStreamRequestHandler handler =
new ResourceStreamRequestHandler(resourceStream, namedWithMimeType.getName());
handler.setContentDisposition(ContentDisposition.ATTACHMENT);
return handler;
}
// //////////////////////////////////////
public List<ActionParameterMemento> primeArgumentModels() {
final ObjectAction objectAction = getAction();
val parameters = objectAction.getParameters();
val actionParameterMementos = buildParameterMementos(parameters);
for (val actionParameterMemento : actionParameterMementos) {
getArgumentModel(actionParameterMemento);
}
return actionParameterMementos;
}
private static List<ActionParameterMemento> buildParameterMementos(
final Can<ObjectActionParameter> parameters) {
// we copy into a new array list otherwise we get lazy evaluation =
// reference to a non-serializable object
return parameters.stream()
.map(ActionParameterMemento::new)
.collect(Collectors.toCollection(ArrayList::new));
}
//////////////////////////////////////////////////
@Override
public PromptStyle getPromptStyle() {
final ObjectAction objectAction = getAction();
final ObjectSpecification objectActionOwner = objectAction.getOnType();
if(objectActionOwner.isManagedBean()) {
// tried to move this test into PromptStyleFacetFallback,
// however it's not that easy to lookup the owning type
final PromptStyleFacet facet = getFacet(PromptStyleFacet.class);
if (facet != null) {
final PromptStyle promptStyle = facet.value();
if (promptStyle.isDialog()) {
// could be specified explicitly.
return promptStyle;
}
}
return PromptStyle.DIALOG;
}
if(objectAction.getParameterCount() == 0) {
// a bit of a hack, the point being that the UI for dialog correctly handles no-args,
// whereas for INLINE it would render a form with no fields
return PromptStyle.DIALOG;
}
final PromptStyleFacet facet = getFacet(PromptStyleFacet.class);
if(facet == null) {
// don't think this can happen actually, see PromptStyleFacetFallback
return PromptStyle.INLINE;
}
final PromptStyle promptStyle = facet.value();
if (promptStyle == PromptStyle.AS_CONFIGURED) {
// I don't think this can happen, actually...
// when the metamodel is built, it should replace AS_CONFIGURED with one of the other prompts
// (see PromptStyleConfiguration and PromptStyleFacetFallback)
return PromptStyle.INLINE;
}
return promptStyle;
}
public <T extends Facet> T getFacet(final Class<T> facetType) {
final FacetHolder facetHolder = getAction();
return facetHolder.getFacet(facetType);
}
//////////////////////////////////////////////////
private InlinePromptContext inlinePromptContext;
/**
* Further hint, to support inline prompts...
*/
@Override
public InlinePromptContext getInlinePromptContext() {
return inlinePromptContext;
}
public void setInlinePromptContext(InlinePromptContext inlinePromptContext) {
this.inlinePromptContext = inlinePromptContext;
}
}
| 36.433518 | 128 | 0.663752 |
f52e3011d113613edbbf804dac1a6216c3c1e908 | 1,841 | /*******************************************************************************
* Copyright (c) Intel Corporation
* Copyright (c) 2017
*
* 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.osc.sdk.manager.element;
import java.util.Set;
import org.osgi.annotation.versioning.ConsumerType;
/**
* This interface represents the mapping between the policies {@link ManagerPolicyElement}
* and VLAN tags defined in OSC.
*/
@ConsumerType
public interface ManagerSecurityGroupInterfaceElement {
/**
* @return the identifier of the security group interface defined by the manager
*/
String getSecurityGroupInterfaceId();
/**
* @return the name of the security group interface defined by OSC
*/
String getName();
/**
* Provides the identifier of the security group defined by security managers that support policy mapping and
* security groups
*
* @return the identifier of the security group defined by the manager
*/
String getSecurityGroupId();
/**
* Provides the context information of manager policy element
*
* @return the set of manager policy elements
*/
Set<ManagerPolicyElement> getManagerPolicyElements();
/**
* @return the encapsulation tag supported by the manager
*/
String getTag();
}
| 30.683333 | 110 | 0.677892 |
96f0a223f8544a614f8800584f6bbafa7e5053e4 | 8,307 | package org.dew.xcomm.messaging;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.dew.xcomm.nosql.json.JSON;
import org.dew.xcomm.util.WMap;
import org.dew.xcomm.util.WUtil;
public
class XMessage implements Serializable
{
private static final long serialVersionUID = -2594835917378068089L;
public static final String DEFAULT_CHANNEL_TYPE = "Unicast";
public static final String DEFAULT_INBOUND_TYPE = "Response";
public static final String DEFAULT_INBOUND_CATEGORY = "GenericResponse";
public static final String DEFAULT_OUTBOUND_TYPE = "Request";
public static final String DEFAULT_OUTBOUND_CATEGORY = "GenericRequest";
// Attributi di base
protected String id;
protected Date creation;
protected Date update;
protected String from;
protected String to;
// Attributi applicativi
protected String thread;
protected String channelType;
protected String category;
protected String type;
protected Integer payloadType;
protected String payload;
// Attributi di sistema
protected Boolean success;
protected Boolean sent;
protected String error;
public XMessage()
{
}
@SuppressWarnings("rawtypes")
public XMessage(String body)
{
if(body == null || body.length() == 0) {
return;
}
if(body.indexOf(""") >= 0) {
body = WUtil.toEscapedText(body, "");
}
Object oBody = JSON.parse(normalizeText(body));
if(!(oBody instanceof Map)) return;
Date currentDateTime = new Date();
WMap wmap = new WMap((Map) oBody);
this.thread = wmap.getString("thread");
this.channelType = wmap.getString("channelType", DEFAULT_CHANNEL_TYPE);
this.category = wmap.getString("category", DEFAULT_INBOUND_CATEGORY);
this.type = wmap.getString("type", DEFAULT_INBOUND_TYPE);
this.payloadType = wmap.getInteger("payloadType");
this.payload = wmap.getString("payload");
this.creation = wmap.getDate("creation", currentDateTime);
this.update = wmap.getDate("update", currentDateTime);
Boolean msgSucc = wmap.getBooleanObj("success");
if(payload != null && payload.length() > 2) {
Map<String,Object> mapPayload = null;
try {
mapPayload = WUtil.toMapObject(JSON.parse(payload));
if(mapPayload != null) {
Boolean payloadSuccess = WUtil.toBooleanObj(mapPayload.get("success"), null);
if(payloadSuccess != null) {
this.success = payloadSuccess;
}
else {
this.success = msgSucc != null ? msgSucc.booleanValue() : false;
}
}
else {
if(msgSucc != null) {
this.payload = "{\"success\":" + msgSucc + "}";
this.success = msgSucc.booleanValue();
}
else {
this.success = Boolean.FALSE;
}
}
}
catch(Exception ex) {
System.err.println("[XMessage] Exception during parse payload " + payload + ": " + ex);
}
}
else
if(msgSucc != null) {
this.payload = "{\"success\":" + msgSucc + "}";
this.success = msgSucc;
}
}
public XMessage(String type, String thread)
{
this.type = type;
this.thread = thread;
}
public XMessage(String category, String type, String to, String payload)
{
this.category = category;
this.type = type;
this.to = to;
this.payload = payload;
}
public XMessage(String category, String type, String to, Map<String,Object> mapPayload)
{
this.category = category;
this.type = type;
this.to = to;
if(mapPayload != null && !mapPayload.isEmpty()) {
String jsonObject = JSON.stringify(mapPayload);
String stringJson = JSON.stringify(jsonObject);
if(stringJson != null && stringJson.length() > 2) {
this.payload = stringJson.substring(1, stringJson.length()-1);
}
else {
this.payload = "{}";
}
}
else {
this.payload = "{}";
}
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getCreation() {
return creation;
}
public void setCreation(Date creation) {
this.creation = creation;
}
public Date getUpdate() {
return update;
}
public void setUpdate(Date update) {
this.update = update;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getThread() {
return thread;
}
public void setThread(String thread) {
this.thread = thread;
}
public String getChannelType() {
return channelType;
}
public void setChannelType(String channelType) {
this.channelType = channelType;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getPayloadType() {
return payloadType;
}
public void setPayloadType(Integer payloadType) {
this.payloadType = payloadType;
}
public String getPayload() {
return payload;
}
public void setPayload(String payload) {
this.payload = payload;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Boolean getSent() {
return sent;
}
public void setSent(Boolean sent) {
this.sent = sent;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
protected static
String normalizeText(String sText)
{
if (sText == null || sText.length() == 0) return "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sText.length(); i++) {
char c = sText.charAt(i);
if (c < 9) sb.append("_"); else
if (c == '\340') sb.append("a'"); else
if (c == '\350') sb.append("e'"); else
if (c == '\354') sb.append("i'"); else
if (c == '\362') sb.append("o'"); else
if (c == '\371') sb.append("u'"); else
if (c == '\341') sb.append("a'"); else
if (c == '\351') sb.append("e'"); else
if (c == '\355') sb.append("i'"); else
if (c == '\363') sb.append("o'"); else
if (c == '\372') sb.append("u'"); else
if (c == '\300') sb.append("A'"); else
if (c == '\310') sb.append("E'"); else
if (c == '\314') sb.append("I'"); else
if (c == '\322') sb.append("O'"); else
if (c == '\331') sb.append("U'"); else
if (c == '\301') sb.append("A'"); else
if (c == '\311') sb.append("E'"); else
if (c == '\315') sb.append("I'"); else
if (c == '\323') sb.append("O'"); else
if (c == '\332') sb.append("U'"); else
if (c > 127) sb.append("_");
else sb.append(c);
}
return sb.toString();
}
@Override
public int hashCode() {
if(id == null) return 0;
return id.hashCode();
}
@Override
public boolean equals(Object object) {
if(object instanceof XMessage) {
String object_Id = ((XMessage) object).getId();
if(id == null) return object_Id == null;
return id.equals(object_Id);
}
return false;
}
@Override
public String toString() {
Map<String,Object> mapValues = new HashMap<String,Object>();
if(creation != null) {
mapValues.put("creation", WUtil.toISO8601Timestamp_Offset(creation, ":"));
}
if(update != null) {
mapValues.put("update", WUtil.toISO8601Timestamp_Offset(update, ":"));
}
if(to != null) to = to.toLowerCase().trim();
mapValues.put("from", from);
mapValues.put("to", to);
mapValues.put("thread", thread);
mapValues.put("channelType", channelType);
mapValues.put("category", category);
mapValues.put("type", type);
mapValues.put("payloadType", payloadType);
mapValues.put("payload", payload);
return normalizeText(JSON.stringify(mapValues));
}
}
| 25.638889 | 95 | 0.598411 |
c97a6f859213c1731554314e748916b84047ffdc | 153 | package do1phin.mine2021.blockgen.blocks;
public class BlockGenSource9 extends BlockGenSource{
public BlockGenSource9() {
super(8);
}
}
| 19.125 | 52 | 0.718954 |
46a728ba77014f2e6dec917ad66dc163487e01b3 | 592 | package com.readlearncode.dukesbookshop.restserver.infrastructure.exceptions;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import static javax.ws.rs.core.Response.Status.NOT_FOUND;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
@Provider
public class ISBNNotFoundManager implements ExceptionMapper<ISBNNotFoundException>{
@Override
public Response toResponse(ISBNNotFoundException exception) {
return Response.status(NOT_FOUND).build();
}
} | 26.909091 | 83 | 0.778716 |
79490c9b35ce3167579ef0459588adc844e09c7d | 47,991 | /**
* Autogenerated by Thrift Compiler (0.9.2)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.xiaomi.infra.galaxy.talos.thrift;
import libthrift091.scheme.IScheme;
import libthrift091.scheme.SchemeFactory;
import libthrift091.scheme.StandardScheme;
import libthrift091.scheme.TupleScheme;
import libthrift091.protocol.TTupleProtocol;
import libthrift091.protocol.TProtocolException;
import libthrift091.EncodingUtils;
import libthrift091.TException;
import libthrift091.async.AsyncMethodCallback;
import libthrift091.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2019-5-20")
public class MessageBlock implements libthrift091.TBase<MessageBlock, MessageBlock._Fields>, java.io.Serializable, Cloneable, Comparable<MessageBlock> {
private static final libthrift091.protocol.TStruct STRUCT_DESC = new libthrift091.protocol.TStruct("MessageBlock");
private static final libthrift091.protocol.TField START_MESSAGE_OFFSET_FIELD_DESC = new libthrift091.protocol.TField("startMessageOffset", libthrift091.protocol.TType.I64, (short)1);
private static final libthrift091.protocol.TField MESSAGE_NUMBER_FIELD_DESC = new libthrift091.protocol.TField("messageNumber", libthrift091.protocol.TType.I32, (short)2);
private static final libthrift091.protocol.TField COMPRESSION_TYPE_FIELD_DESC = new libthrift091.protocol.TField("compressionType", libthrift091.protocol.TType.I32, (short)3);
private static final libthrift091.protocol.TField MESSAGE_BLOCK_FIELD_DESC = new libthrift091.protocol.TField("messageBlock", libthrift091.protocol.TType.STRING, (short)4);
private static final libthrift091.protocol.TField MESSAGE_BLOCK_SIZE_FIELD_DESC = new libthrift091.protocol.TField("messageBlockSize", libthrift091.protocol.TType.I32, (short)5);
private static final libthrift091.protocol.TField APPEND_TIMESTAMP_FIELD_DESC = new libthrift091.protocol.TField("appendTimestamp", libthrift091.protocol.TType.I64, (short)6);
private static final libthrift091.protocol.TField CREATE_TIMESTAMP_FIELD_DESC = new libthrift091.protocol.TField("createTimestamp", libthrift091.protocol.TType.I64, (short)7);
private static final libthrift091.protocol.TField CREATE_TIMESTAMP_LIST_FIELD_DESC = new libthrift091.protocol.TField("createTimestampList", libthrift091.protocol.TType.LIST, (short)8);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new MessageBlockStandardSchemeFactory());
schemes.put(TupleScheme.class, new MessageBlockTupleSchemeFactory());
}
/**
* the start message offset for this message block;
*
*/
public long startMessageOffset; // required
/**
* the messageNumber for this message, if this message is compressed, the
* messageNumber may greater than 1;
*
*/
public int messageNumber; // required
/**
* compression type for this message, default is NONE;
*
*
* @see MessageCompressionType
*/
public MessageCompressionType compressionType; // required
/**
* message data, generated by List<Message>;
*
*/
public ByteBuffer messageBlock; // required
/**
* the size for message block;
*
*/
public int messageBlockSize; // optional
/**
* the message arrive talos server timestamp, in millis;
*
*/
public long appendTimestamp; // optional
/**
* the message arrive sdk timestamp, in millis;
*
*/
public long createTimestamp; // optional
/**
* The value in createTimestampList is the Message.createTimestamp filed for
* all the messages in this MessageBlock, we can decode the messageBlock filed
* and get a list of Messages, then we will get the createTimestampList. But
* we will never decode messageBlock and directly add createTimestampList into
* MessageBlock, just as decode messageBlock is very heavy cpu operations,
* talos restServer will become poor perfmance. But add createTimestampList
* by talos sdk is very natural as sdk have the original messageList and encode
* it to messageBlock. This only add extra 8 bytes for every message fot
* network transport, and this is acceptable for us.
* When we set createTimestampList, it's size must equal messageNumber;
*
*/
public List<Long> createTimestampList; // optional
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements libthrift091.TFieldIdEnum {
/**
* the start message offset for this message block;
*
*/
START_MESSAGE_OFFSET((short)1, "startMessageOffset"),
/**
* the messageNumber for this message, if this message is compressed, the
* messageNumber may greater than 1;
*
*/
MESSAGE_NUMBER((short)2, "messageNumber"),
/**
* compression type for this message, default is NONE;
*
*
* @see MessageCompressionType
*/
COMPRESSION_TYPE((short)3, "compressionType"),
/**
* message data, generated by List<Message>;
*
*/
MESSAGE_BLOCK((short)4, "messageBlock"),
/**
* the size for message block;
*
*/
MESSAGE_BLOCK_SIZE((short)5, "messageBlockSize"),
/**
* the message arrive talos server timestamp, in millis;
*
*/
APPEND_TIMESTAMP((short)6, "appendTimestamp"),
/**
* the message arrive sdk timestamp, in millis;
*
*/
CREATE_TIMESTAMP((short)7, "createTimestamp"),
/**
* The value in createTimestampList is the Message.createTimestamp filed for
* all the messages in this MessageBlock, we can decode the messageBlock filed
* and get a list of Messages, then we will get the createTimestampList. But
* we will never decode messageBlock and directly add createTimestampList into
* MessageBlock, just as decode messageBlock is very heavy cpu operations,
* talos restServer will become poor perfmance. But add createTimestampList
* by talos sdk is very natural as sdk have the original messageList and encode
* it to messageBlock. This only add extra 8 bytes for every message fot
* network transport, and this is acceptable for us.
* When we set createTimestampList, it's size must equal messageNumber;
*
*/
CREATE_TIMESTAMP_LIST((short)8, "createTimestampList");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // START_MESSAGE_OFFSET
return START_MESSAGE_OFFSET;
case 2: // MESSAGE_NUMBER
return MESSAGE_NUMBER;
case 3: // COMPRESSION_TYPE
return COMPRESSION_TYPE;
case 4: // MESSAGE_BLOCK
return MESSAGE_BLOCK;
case 5: // MESSAGE_BLOCK_SIZE
return MESSAGE_BLOCK_SIZE;
case 6: // APPEND_TIMESTAMP
return APPEND_TIMESTAMP;
case 7: // CREATE_TIMESTAMP
return CREATE_TIMESTAMP;
case 8: // CREATE_TIMESTAMP_LIST
return CREATE_TIMESTAMP_LIST;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __STARTMESSAGEOFFSET_ISSET_ID = 0;
private static final int __MESSAGENUMBER_ISSET_ID = 1;
private static final int __MESSAGEBLOCKSIZE_ISSET_ID = 2;
private static final int __APPENDTIMESTAMP_ISSET_ID = 3;
private static final int __CREATETIMESTAMP_ISSET_ID = 4;
private byte __isset_bitfield = 0;
private static final _Fields optionals[] = {_Fields.MESSAGE_BLOCK_SIZE,_Fields.APPEND_TIMESTAMP,_Fields.CREATE_TIMESTAMP,_Fields.CREATE_TIMESTAMP_LIST};
public static final Map<_Fields, libthrift091.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, libthrift091.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, libthrift091.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.START_MESSAGE_OFFSET, new libthrift091.meta_data.FieldMetaData("startMessageOffset", libthrift091.TFieldRequirementType.REQUIRED,
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.I64)));
tmpMap.put(_Fields.MESSAGE_NUMBER, new libthrift091.meta_data.FieldMetaData("messageNumber", libthrift091.TFieldRequirementType.REQUIRED,
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.I32)));
tmpMap.put(_Fields.COMPRESSION_TYPE, new libthrift091.meta_data.FieldMetaData("compressionType", libthrift091.TFieldRequirementType.REQUIRED,
new libthrift091.meta_data.EnumMetaData(libthrift091.protocol.TType.ENUM, MessageCompressionType.class)));
tmpMap.put(_Fields.MESSAGE_BLOCK, new libthrift091.meta_data.FieldMetaData("messageBlock", libthrift091.TFieldRequirementType.REQUIRED,
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.STRING , true)));
tmpMap.put(_Fields.MESSAGE_BLOCK_SIZE, new libthrift091.meta_data.FieldMetaData("messageBlockSize", libthrift091.TFieldRequirementType.OPTIONAL,
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.I32)));
tmpMap.put(_Fields.APPEND_TIMESTAMP, new libthrift091.meta_data.FieldMetaData("appendTimestamp", libthrift091.TFieldRequirementType.OPTIONAL,
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.I64)));
tmpMap.put(_Fields.CREATE_TIMESTAMP, new libthrift091.meta_data.FieldMetaData("createTimestamp", libthrift091.TFieldRequirementType.OPTIONAL,
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.I64)));
tmpMap.put(_Fields.CREATE_TIMESTAMP_LIST, new libthrift091.meta_data.FieldMetaData("createTimestampList", libthrift091.TFieldRequirementType.OPTIONAL,
new libthrift091.meta_data.ListMetaData(libthrift091.protocol.TType.LIST,
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.I64))));
metaDataMap = Collections.unmodifiableMap(tmpMap);
libthrift091.meta_data.FieldMetaData.addStructMetaDataMap(MessageBlock.class, metaDataMap);
}
public MessageBlock() {
this.compressionType = com.xiaomi.infra.galaxy.talos.thrift.MessageCompressionType.NONE;
}
public MessageBlock(
long startMessageOffset,
int messageNumber,
MessageCompressionType compressionType,
ByteBuffer messageBlock)
{
this();
this.startMessageOffset = startMessageOffset;
setStartMessageOffsetIsSet(true);
this.messageNumber = messageNumber;
setMessageNumberIsSet(true);
this.compressionType = compressionType;
this.messageBlock = libthrift091.TBaseHelper.copyBinary(messageBlock);
}
/**
* Performs a deep copy on <i>other</i>.
*/
public MessageBlock(MessageBlock other) {
__isset_bitfield = other.__isset_bitfield;
this.startMessageOffset = other.startMessageOffset;
this.messageNumber = other.messageNumber;
if (other.isSetCompressionType()) {
this.compressionType = other.compressionType;
}
if (other.isSetMessageBlock()) {
this.messageBlock = libthrift091.TBaseHelper.copyBinary(other.messageBlock);
}
this.messageBlockSize = other.messageBlockSize;
this.appendTimestamp = other.appendTimestamp;
this.createTimestamp = other.createTimestamp;
if (other.isSetCreateTimestampList()) {
List<Long> __this__createTimestampList = new ArrayList<Long>(other.createTimestampList);
this.createTimestampList = __this__createTimestampList;
}
}
public MessageBlock deepCopy() {
return new MessageBlock(this);
}
@Override
public void clear() {
setStartMessageOffsetIsSet(false);
this.startMessageOffset = 0;
setMessageNumberIsSet(false);
this.messageNumber = 0;
this.compressionType = com.xiaomi.infra.galaxy.talos.thrift.MessageCompressionType.NONE;
this.messageBlock = null;
setMessageBlockSizeIsSet(false);
this.messageBlockSize = 0;
setAppendTimestampIsSet(false);
this.appendTimestamp = 0;
setCreateTimestampIsSet(false);
this.createTimestamp = 0;
this.createTimestampList = null;
}
/**
* the start message offset for this message block;
*
*/
public long getStartMessageOffset() {
return this.startMessageOffset;
}
/**
* the start message offset for this message block;
*
*/
public MessageBlock setStartMessageOffset(long startMessageOffset) {
this.startMessageOffset = startMessageOffset;
setStartMessageOffsetIsSet(true);
return this;
}
public void unsetStartMessageOffset() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __STARTMESSAGEOFFSET_ISSET_ID);
}
/** Returns true if field startMessageOffset is set (has been assigned a value) and false otherwise */
public boolean isSetStartMessageOffset() {
return EncodingUtils.testBit(__isset_bitfield, __STARTMESSAGEOFFSET_ISSET_ID);
}
public void setStartMessageOffsetIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __STARTMESSAGEOFFSET_ISSET_ID, value);
}
/**
* the messageNumber for this message, if this message is compressed, the
* messageNumber may greater than 1;
*
*/
public int getMessageNumber() {
return this.messageNumber;
}
/**
* the messageNumber for this message, if this message is compressed, the
* messageNumber may greater than 1;
*
*/
public MessageBlock setMessageNumber(int messageNumber) {
this.messageNumber = messageNumber;
setMessageNumberIsSet(true);
return this;
}
public void unsetMessageNumber() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __MESSAGENUMBER_ISSET_ID);
}
/** Returns true if field messageNumber is set (has been assigned a value) and false otherwise */
public boolean isSetMessageNumber() {
return EncodingUtils.testBit(__isset_bitfield, __MESSAGENUMBER_ISSET_ID);
}
public void setMessageNumberIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __MESSAGENUMBER_ISSET_ID, value);
}
/**
* compression type for this message, default is NONE;
*
*
* @see MessageCompressionType
*/
public MessageCompressionType getCompressionType() {
return this.compressionType;
}
/**
* compression type for this message, default is NONE;
*
*
* @see MessageCompressionType
*/
public MessageBlock setCompressionType(MessageCompressionType compressionType) {
this.compressionType = compressionType;
return this;
}
public void unsetCompressionType() {
this.compressionType = null;
}
/** Returns true if field compressionType is set (has been assigned a value) and false otherwise */
public boolean isSetCompressionType() {
return this.compressionType != null;
}
public void setCompressionTypeIsSet(boolean value) {
if (!value) {
this.compressionType = null;
}
}
/**
* message data, generated by List<Message>;
*
*/
public byte[] getMessageBlock() {
setMessageBlock(libthrift091.TBaseHelper.rightSize(messageBlock));
return messageBlock == null ? null : messageBlock.array();
}
public ByteBuffer bufferForMessageBlock() {
return libthrift091.TBaseHelper.copyBinary(messageBlock);
}
/**
* message data, generated by List<Message>;
*
*/
public MessageBlock setMessageBlock(byte[] messageBlock) {
this.messageBlock = messageBlock == null ? (ByteBuffer)null : ByteBuffer.wrap(Arrays.copyOf(messageBlock, messageBlock.length));
return this;
}
public MessageBlock setMessageBlock(ByteBuffer messageBlock) {
this.messageBlock = libthrift091.TBaseHelper.copyBinary(messageBlock);
return this;
}
public void unsetMessageBlock() {
this.messageBlock = null;
}
/** Returns true if field messageBlock is set (has been assigned a value) and false otherwise */
public boolean isSetMessageBlock() {
return this.messageBlock != null;
}
public void setMessageBlockIsSet(boolean value) {
if (!value) {
this.messageBlock = null;
}
}
/**
* the size for message block;
*
*/
public int getMessageBlockSize() {
return this.messageBlockSize;
}
/**
* the size for message block;
*
*/
public MessageBlock setMessageBlockSize(int messageBlockSize) {
this.messageBlockSize = messageBlockSize;
setMessageBlockSizeIsSet(true);
return this;
}
public void unsetMessageBlockSize() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __MESSAGEBLOCKSIZE_ISSET_ID);
}
/** Returns true if field messageBlockSize is set (has been assigned a value) and false otherwise */
public boolean isSetMessageBlockSize() {
return EncodingUtils.testBit(__isset_bitfield, __MESSAGEBLOCKSIZE_ISSET_ID);
}
public void setMessageBlockSizeIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __MESSAGEBLOCKSIZE_ISSET_ID, value);
}
/**
* the message arrive talos server timestamp, in millis;
*
*/
public long getAppendTimestamp() {
return this.appendTimestamp;
}
/**
* the message arrive talos server timestamp, in millis;
*
*/
public MessageBlock setAppendTimestamp(long appendTimestamp) {
this.appendTimestamp = appendTimestamp;
setAppendTimestampIsSet(true);
return this;
}
public void unsetAppendTimestamp() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __APPENDTIMESTAMP_ISSET_ID);
}
/** Returns true if field appendTimestamp is set (has been assigned a value) and false otherwise */
public boolean isSetAppendTimestamp() {
return EncodingUtils.testBit(__isset_bitfield, __APPENDTIMESTAMP_ISSET_ID);
}
public void setAppendTimestampIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __APPENDTIMESTAMP_ISSET_ID, value);
}
/**
* the message arrive sdk timestamp, in millis;
*
*/
public long getCreateTimestamp() {
return this.createTimestamp;
}
/**
* the message arrive sdk timestamp, in millis;
*
*/
public MessageBlock setCreateTimestamp(long createTimestamp) {
this.createTimestamp = createTimestamp;
setCreateTimestampIsSet(true);
return this;
}
public void unsetCreateTimestamp() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __CREATETIMESTAMP_ISSET_ID);
}
/** Returns true if field createTimestamp is set (has been assigned a value) and false otherwise */
public boolean isSetCreateTimestamp() {
return EncodingUtils.testBit(__isset_bitfield, __CREATETIMESTAMP_ISSET_ID);
}
public void setCreateTimestampIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __CREATETIMESTAMP_ISSET_ID, value);
}
public int getCreateTimestampListSize() {
return (this.createTimestampList == null) ? 0 : this.createTimestampList.size();
}
public java.util.Iterator<Long> getCreateTimestampListIterator() {
return (this.createTimestampList == null) ? null : this.createTimestampList.iterator();
}
public void addToCreateTimestampList(long elem) {
if (this.createTimestampList == null) {
this.createTimestampList = new ArrayList<Long>();
}
this.createTimestampList.add(elem);
}
/**
* The value in createTimestampList is the Message.createTimestamp filed for
* all the messages in this MessageBlock, we can decode the messageBlock filed
* and get a list of Messages, then we will get the createTimestampList. But
* we will never decode messageBlock and directly add createTimestampList into
* MessageBlock, just as decode messageBlock is very heavy cpu operations,
* talos restServer will become poor perfmance. But add createTimestampList
* by talos sdk is very natural as sdk have the original messageList and encode
* it to messageBlock. This only add extra 8 bytes for every message fot
* network transport, and this is acceptable for us.
* When we set createTimestampList, it's size must equal messageNumber;
*
*/
public List<Long> getCreateTimestampList() {
return this.createTimestampList;
}
/**
* The value in createTimestampList is the Message.createTimestamp filed for
* all the messages in this MessageBlock, we can decode the messageBlock filed
* and get a list of Messages, then we will get the createTimestampList. But
* we will never decode messageBlock and directly add createTimestampList into
* MessageBlock, just as decode messageBlock is very heavy cpu operations,
* talos restServer will become poor perfmance. But add createTimestampList
* by talos sdk is very natural as sdk have the original messageList and encode
* it to messageBlock. This only add extra 8 bytes for every message fot
* network transport, and this is acceptable for us.
* When we set createTimestampList, it's size must equal messageNumber;
*
*/
public MessageBlock setCreateTimestampList(List<Long> createTimestampList) {
this.createTimestampList = createTimestampList;
return this;
}
public void unsetCreateTimestampList() {
this.createTimestampList = null;
}
/** Returns true if field createTimestampList is set (has been assigned a value) and false otherwise */
public boolean isSetCreateTimestampList() {
return this.createTimestampList != null;
}
public void setCreateTimestampListIsSet(boolean value) {
if (!value) {
this.createTimestampList = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case START_MESSAGE_OFFSET:
if (value == null) {
unsetStartMessageOffset();
} else {
setStartMessageOffset((Long)value);
}
break;
case MESSAGE_NUMBER:
if (value == null) {
unsetMessageNumber();
} else {
setMessageNumber((Integer)value);
}
break;
case COMPRESSION_TYPE:
if (value == null) {
unsetCompressionType();
} else {
setCompressionType((MessageCompressionType)value);
}
break;
case MESSAGE_BLOCK:
if (value == null) {
unsetMessageBlock();
} else {
setMessageBlock((ByteBuffer)value);
}
break;
case MESSAGE_BLOCK_SIZE:
if (value == null) {
unsetMessageBlockSize();
} else {
setMessageBlockSize((Integer)value);
}
break;
case APPEND_TIMESTAMP:
if (value == null) {
unsetAppendTimestamp();
} else {
setAppendTimestamp((Long)value);
}
break;
case CREATE_TIMESTAMP:
if (value == null) {
unsetCreateTimestamp();
} else {
setCreateTimestamp((Long)value);
}
break;
case CREATE_TIMESTAMP_LIST:
if (value == null) {
unsetCreateTimestampList();
} else {
setCreateTimestampList((List<Long>)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case START_MESSAGE_OFFSET:
return Long.valueOf(getStartMessageOffset());
case MESSAGE_NUMBER:
return Integer.valueOf(getMessageNumber());
case COMPRESSION_TYPE:
return getCompressionType();
case MESSAGE_BLOCK:
return getMessageBlock();
case MESSAGE_BLOCK_SIZE:
return Integer.valueOf(getMessageBlockSize());
case APPEND_TIMESTAMP:
return Long.valueOf(getAppendTimestamp());
case CREATE_TIMESTAMP:
return Long.valueOf(getCreateTimestamp());
case CREATE_TIMESTAMP_LIST:
return getCreateTimestampList();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case START_MESSAGE_OFFSET:
return isSetStartMessageOffset();
case MESSAGE_NUMBER:
return isSetMessageNumber();
case COMPRESSION_TYPE:
return isSetCompressionType();
case MESSAGE_BLOCK:
return isSetMessageBlock();
case MESSAGE_BLOCK_SIZE:
return isSetMessageBlockSize();
case APPEND_TIMESTAMP:
return isSetAppendTimestamp();
case CREATE_TIMESTAMP:
return isSetCreateTimestamp();
case CREATE_TIMESTAMP_LIST:
return isSetCreateTimestampList();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof MessageBlock)
return this.equals((MessageBlock)that);
return false;
}
public boolean equals(MessageBlock that) {
if (that == null)
return false;
boolean this_present_startMessageOffset = true;
boolean that_present_startMessageOffset = true;
if (this_present_startMessageOffset || that_present_startMessageOffset) {
if (!(this_present_startMessageOffset && that_present_startMessageOffset))
return false;
if (this.startMessageOffset != that.startMessageOffset)
return false;
}
boolean this_present_messageNumber = true;
boolean that_present_messageNumber = true;
if (this_present_messageNumber || that_present_messageNumber) {
if (!(this_present_messageNumber && that_present_messageNumber))
return false;
if (this.messageNumber != that.messageNumber)
return false;
}
boolean this_present_compressionType = true && this.isSetCompressionType();
boolean that_present_compressionType = true && that.isSetCompressionType();
if (this_present_compressionType || that_present_compressionType) {
if (!(this_present_compressionType && that_present_compressionType))
return false;
if (!this.compressionType.equals(that.compressionType))
return false;
}
boolean this_present_messageBlock = true && this.isSetMessageBlock();
boolean that_present_messageBlock = true && that.isSetMessageBlock();
if (this_present_messageBlock || that_present_messageBlock) {
if (!(this_present_messageBlock && that_present_messageBlock))
return false;
if (!this.messageBlock.equals(that.messageBlock))
return false;
}
boolean this_present_messageBlockSize = true && this.isSetMessageBlockSize();
boolean that_present_messageBlockSize = true && that.isSetMessageBlockSize();
if (this_present_messageBlockSize || that_present_messageBlockSize) {
if (!(this_present_messageBlockSize && that_present_messageBlockSize))
return false;
if (this.messageBlockSize != that.messageBlockSize)
return false;
}
boolean this_present_appendTimestamp = true && this.isSetAppendTimestamp();
boolean that_present_appendTimestamp = true && that.isSetAppendTimestamp();
if (this_present_appendTimestamp || that_present_appendTimestamp) {
if (!(this_present_appendTimestamp && that_present_appendTimestamp))
return false;
if (this.appendTimestamp != that.appendTimestamp)
return false;
}
boolean this_present_createTimestamp = true && this.isSetCreateTimestamp();
boolean that_present_createTimestamp = true && that.isSetCreateTimestamp();
if (this_present_createTimestamp || that_present_createTimestamp) {
if (!(this_present_createTimestamp && that_present_createTimestamp))
return false;
if (this.createTimestamp != that.createTimestamp)
return false;
}
boolean this_present_createTimestampList = true && this.isSetCreateTimestampList();
boolean that_present_createTimestampList = true && that.isSetCreateTimestampList();
if (this_present_createTimestampList || that_present_createTimestampList) {
if (!(this_present_createTimestampList && that_present_createTimestampList))
return false;
if (!this.createTimestampList.equals(that.createTimestampList))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_startMessageOffset = true;
list.add(present_startMessageOffset);
if (present_startMessageOffset)
list.add(startMessageOffset);
boolean present_messageNumber = true;
list.add(present_messageNumber);
if (present_messageNumber)
list.add(messageNumber);
boolean present_compressionType = true && (isSetCompressionType());
list.add(present_compressionType);
if (present_compressionType)
list.add(compressionType.getValue());
boolean present_messageBlock = true && (isSetMessageBlock());
list.add(present_messageBlock);
if (present_messageBlock)
list.add(messageBlock);
boolean present_messageBlockSize = true && (isSetMessageBlockSize());
list.add(present_messageBlockSize);
if (present_messageBlockSize)
list.add(messageBlockSize);
boolean present_appendTimestamp = true && (isSetAppendTimestamp());
list.add(present_appendTimestamp);
if (present_appendTimestamp)
list.add(appendTimestamp);
boolean present_createTimestamp = true && (isSetCreateTimestamp());
list.add(present_createTimestamp);
if (present_createTimestamp)
list.add(createTimestamp);
boolean present_createTimestampList = true && (isSetCreateTimestampList());
list.add(present_createTimestampList);
if (present_createTimestampList)
list.add(createTimestampList);
return list.hashCode();
}
@Override
public int compareTo(MessageBlock other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetStartMessageOffset()).compareTo(other.isSetStartMessageOffset());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetStartMessageOffset()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.startMessageOffset, other.startMessageOffset);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetMessageNumber()).compareTo(other.isSetMessageNumber());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetMessageNumber()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.messageNumber, other.messageNumber);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetCompressionType()).compareTo(other.isSetCompressionType());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetCompressionType()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.compressionType, other.compressionType);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetMessageBlock()).compareTo(other.isSetMessageBlock());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetMessageBlock()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.messageBlock, other.messageBlock);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetMessageBlockSize()).compareTo(other.isSetMessageBlockSize());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetMessageBlockSize()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.messageBlockSize, other.messageBlockSize);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetAppendTimestamp()).compareTo(other.isSetAppendTimestamp());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetAppendTimestamp()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.appendTimestamp, other.appendTimestamp);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetCreateTimestamp()).compareTo(other.isSetCreateTimestamp());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetCreateTimestamp()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.createTimestamp, other.createTimestamp);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetCreateTimestampList()).compareTo(other.isSetCreateTimestampList());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetCreateTimestampList()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.createTimestampList, other.createTimestampList);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(libthrift091.protocol.TProtocol iprot) throws libthrift091.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(libthrift091.protocol.TProtocol oprot) throws libthrift091.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("MessageBlock(");
boolean first = true;
sb.append("startMessageOffset:");
sb.append(this.startMessageOffset);
first = false;
if (!first) sb.append(", ");
sb.append("messageNumber:");
sb.append(this.messageNumber);
first = false;
if (!first) sb.append(", ");
sb.append("compressionType:");
if (this.compressionType == null) {
sb.append("null");
} else {
sb.append(this.compressionType);
}
first = false;
if (!first) sb.append(", ");
sb.append("messageBlock:");
if (this.messageBlock == null) {
sb.append("null");
} else {
libthrift091.TBaseHelper.toString(this.messageBlock, sb);
}
first = false;
if (isSetMessageBlockSize()) {
if (!first) sb.append(", ");
sb.append("messageBlockSize:");
sb.append(this.messageBlockSize);
first = false;
}
if (isSetAppendTimestamp()) {
if (!first) sb.append(", ");
sb.append("appendTimestamp:");
sb.append(this.appendTimestamp);
first = false;
}
if (isSetCreateTimestamp()) {
if (!first) sb.append(", ");
sb.append("createTimestamp:");
sb.append(this.createTimestamp);
first = false;
}
if (isSetCreateTimestampList()) {
if (!first) sb.append(", ");
sb.append("createTimestampList:");
if (this.createTimestampList == null) {
sb.append("null");
} else {
sb.append(this.createTimestampList);
}
first = false;
}
sb.append(")");
return sb.toString();
}
public void validate() throws libthrift091.TException {
// check for required fields
// alas, we cannot check 'startMessageOffset' because it's a primitive and you chose the non-beans generator.
// alas, we cannot check 'messageNumber' because it's a primitive and you chose the non-beans generator.
if (compressionType == null) {
throw new libthrift091.protocol.TProtocolException("Required field 'compressionType' was not present! Struct: " + toString());
}
if (messageBlock == null) {
throw new libthrift091.protocol.TProtocolException("Required field 'messageBlock' was not present! Struct: " + toString());
}
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new libthrift091.protocol.TCompactProtocol(new libthrift091.transport.TIOStreamTransport(out)));
} catch (libthrift091.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new libthrift091.protocol.TCompactProtocol(new libthrift091.transport.TIOStreamTransport(in)));
} catch (libthrift091.TException te) {
throw new java.io.IOException(te);
}
}
private static class MessageBlockStandardSchemeFactory implements SchemeFactory {
public MessageBlockStandardScheme getScheme() {
return new MessageBlockStandardScheme();
}
}
private static class MessageBlockStandardScheme extends StandardScheme<MessageBlock> {
public void read(libthrift091.protocol.TProtocol iprot, MessageBlock struct) throws libthrift091.TException {
libthrift091.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == libthrift091.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // START_MESSAGE_OFFSET
if (schemeField.type == libthrift091.protocol.TType.I64) {
struct.startMessageOffset = iprot.readI64();
struct.setStartMessageOffsetIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // MESSAGE_NUMBER
if (schemeField.type == libthrift091.protocol.TType.I32) {
struct.messageNumber = iprot.readI32();
struct.setMessageNumberIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // COMPRESSION_TYPE
if (schemeField.type == libthrift091.protocol.TType.I32) {
struct.compressionType = com.xiaomi.infra.galaxy.talos.thrift.MessageCompressionType.findByValue(iprot.readI32());
struct.setCompressionTypeIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 4: // MESSAGE_BLOCK
if (schemeField.type == libthrift091.protocol.TType.STRING) {
struct.messageBlock = iprot.readBinary();
struct.setMessageBlockIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 5: // MESSAGE_BLOCK_SIZE
if (schemeField.type == libthrift091.protocol.TType.I32) {
struct.messageBlockSize = iprot.readI32();
struct.setMessageBlockSizeIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 6: // APPEND_TIMESTAMP
if (schemeField.type == libthrift091.protocol.TType.I64) {
struct.appendTimestamp = iprot.readI64();
struct.setAppendTimestampIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 7: // CREATE_TIMESTAMP
if (schemeField.type == libthrift091.protocol.TType.I64) {
struct.createTimestamp = iprot.readI64();
struct.setCreateTimestampIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 8: // CREATE_TIMESTAMP_LIST
if (schemeField.type == libthrift091.protocol.TType.LIST) {
{
libthrift091.protocol.TList _list0 = iprot.readListBegin();
struct.createTimestampList = new ArrayList<Long>(_list0.size);
long _elem1;
for (int _i2 = 0; _i2 < _list0.size; ++_i2)
{
_elem1 = iprot.readI64();
struct.createTimestampList.add(_elem1);
}
iprot.readListEnd();
}
struct.setCreateTimestampListIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
if (!struct.isSetStartMessageOffset()) {
throw new libthrift091.protocol.TProtocolException("Required field 'startMessageOffset' was not found in serialized data! Struct: " + toString());
}
if (!struct.isSetMessageNumber()) {
throw new libthrift091.protocol.TProtocolException("Required field 'messageNumber' was not found in serialized data! Struct: " + toString());
}
struct.validate();
}
public void write(libthrift091.protocol.TProtocol oprot, MessageBlock struct) throws libthrift091.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldBegin(START_MESSAGE_OFFSET_FIELD_DESC);
oprot.writeI64(struct.startMessageOffset);
oprot.writeFieldEnd();
oprot.writeFieldBegin(MESSAGE_NUMBER_FIELD_DESC);
oprot.writeI32(struct.messageNumber);
oprot.writeFieldEnd();
if (struct.compressionType != null) {
oprot.writeFieldBegin(COMPRESSION_TYPE_FIELD_DESC);
oprot.writeI32(struct.compressionType.getValue());
oprot.writeFieldEnd();
}
if (struct.messageBlock != null) {
oprot.writeFieldBegin(MESSAGE_BLOCK_FIELD_DESC);
oprot.writeBinary(struct.messageBlock);
oprot.writeFieldEnd();
}
if (struct.isSetMessageBlockSize()) {
oprot.writeFieldBegin(MESSAGE_BLOCK_SIZE_FIELD_DESC);
oprot.writeI32(struct.messageBlockSize);
oprot.writeFieldEnd();
}
if (struct.isSetAppendTimestamp()) {
oprot.writeFieldBegin(APPEND_TIMESTAMP_FIELD_DESC);
oprot.writeI64(struct.appendTimestamp);
oprot.writeFieldEnd();
}
if (struct.isSetCreateTimestamp()) {
oprot.writeFieldBegin(CREATE_TIMESTAMP_FIELD_DESC);
oprot.writeI64(struct.createTimestamp);
oprot.writeFieldEnd();
}
if (struct.createTimestampList != null) {
if (struct.isSetCreateTimestampList()) {
oprot.writeFieldBegin(CREATE_TIMESTAMP_LIST_FIELD_DESC);
{
oprot.writeListBegin(new libthrift091.protocol.TList(libthrift091.protocol.TType.I64, struct.createTimestampList.size()));
for (long _iter3 : struct.createTimestampList)
{
oprot.writeI64(_iter3);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class MessageBlockTupleSchemeFactory implements SchemeFactory {
public MessageBlockTupleScheme getScheme() {
return new MessageBlockTupleScheme();
}
}
private static class MessageBlockTupleScheme extends TupleScheme<MessageBlock> {
@Override
public void write(libthrift091.protocol.TProtocol prot, MessageBlock struct) throws libthrift091.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
oprot.writeI64(struct.startMessageOffset);
oprot.writeI32(struct.messageNumber);
oprot.writeI32(struct.compressionType.getValue());
oprot.writeBinary(struct.messageBlock);
BitSet optionals = new BitSet();
if (struct.isSetMessageBlockSize()) {
optionals.set(0);
}
if (struct.isSetAppendTimestamp()) {
optionals.set(1);
}
if (struct.isSetCreateTimestamp()) {
optionals.set(2);
}
if (struct.isSetCreateTimestampList()) {
optionals.set(3);
}
oprot.writeBitSet(optionals, 4);
if (struct.isSetMessageBlockSize()) {
oprot.writeI32(struct.messageBlockSize);
}
if (struct.isSetAppendTimestamp()) {
oprot.writeI64(struct.appendTimestamp);
}
if (struct.isSetCreateTimestamp()) {
oprot.writeI64(struct.createTimestamp);
}
if (struct.isSetCreateTimestampList()) {
{
oprot.writeI32(struct.createTimestampList.size());
for (long _iter4 : struct.createTimestampList)
{
oprot.writeI64(_iter4);
}
}
}
}
@Override
public void read(libthrift091.protocol.TProtocol prot, MessageBlock struct) throws libthrift091.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
struct.startMessageOffset = iprot.readI64();
struct.setStartMessageOffsetIsSet(true);
struct.messageNumber = iprot.readI32();
struct.setMessageNumberIsSet(true);
struct.compressionType = com.xiaomi.infra.galaxy.talos.thrift.MessageCompressionType.findByValue(iprot.readI32());
struct.setCompressionTypeIsSet(true);
struct.messageBlock = iprot.readBinary();
struct.setMessageBlockIsSet(true);
BitSet incoming = iprot.readBitSet(4);
if (incoming.get(0)) {
struct.messageBlockSize = iprot.readI32();
struct.setMessageBlockSizeIsSet(true);
}
if (incoming.get(1)) {
struct.appendTimestamp = iprot.readI64();
struct.setAppendTimestampIsSet(true);
}
if (incoming.get(2)) {
struct.createTimestamp = iprot.readI64();
struct.setCreateTimestampIsSet(true);
}
if (incoming.get(3)) {
{
libthrift091.protocol.TList _list5 = new libthrift091.protocol.TList(libthrift091.protocol.TType.I64, iprot.readI32());
struct.createTimestampList = new ArrayList<Long>(_list5.size);
long _elem6;
for (int _i7 = 0; _i7 < _list5.size; ++_i7)
{
_elem6 = iprot.readI64();
struct.createTimestampList.add(_elem6);
}
}
struct.setCreateTimestampListIsSet(true);
}
}
}
}
| 35.867713 | 187 | 0.696568 |
923bc96571ec0c934f94e9ed563dd7e3633bc924 | 592 | package uk.gov.ons.census.fwmt.rmadapter.utils;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.util.GregorianCalendar;
public final class UtilityMethods {
public static XMLGregorianCalendar getXMLGregorianCalendarNow() throws DatatypeConfigurationException {
GregorianCalendar gregorianCalendar = new GregorianCalendar();
DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
return datatypeFactory.newXMLGregorianCalendar(gregorianCalendar);
}
}
| 34.823529 | 105 | 0.837838 |
dfc4c9ce0e3b1f578b17351e240d49f79cef5193 | 731 | package seedu.address.logic.commands.arguments;
/**
* Represents an object that builds arguments.
* @param <T> the type of the argument to build
*/
public abstract class ArgumentBuilder<T> {
private final String description;
private Argument<T> argument;
ArgumentBuilder(String description) {
this.description = description;
}
public T getValue() {
return this.argument.getValue();
}
/**
* Builds the argument.
* @return the built argument
*/
public Argument<T> build() {
this.argument = argumentBuild();
return this.argument;
}
abstract Argument<T> argumentBuild();
String getDescription() {
return description;
}
}
| 20.305556 | 47 | 0.638851 |
6e6cca43f838e5da6f7b1897db313cd2997bd502 | 4,885 | /*
* Copyright 2011 LMAX Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lmax.disruptor;
import com.lmax.disruptor.util.MutableLong;
import com.lmax.disruptor.util.PaddedAtomicLong;
import java.util.concurrent.locks.LockSupport;
import static com.lmax.disruptor.util.Util.getMinimumSequence;
/**
* Strategy to be used when there are multiple publisher threads claiming sequences.
*
* This strategy requires sufficient cores to allow multiple publishers to be concurrently claiming sequences.
*/
public final class MultiThreadedClaimStrategy
implements ClaimStrategy
{
private final int bufferSize;
private final PaddedAtomicLong claimSequence = new PaddedAtomicLong(Sequencer.INITIAL_CURSOR_VALUE);
private final ThreadLocal<MutableLong> minGatingSequenceThreadLocal = new ThreadLocal<MutableLong>()
{
@Override
protected MutableLong initialValue()
{
return new MutableLong(Sequencer.INITIAL_CURSOR_VALUE);
}
};
/**
* Construct a new multi-threaded publisher {@link ClaimStrategy} for a given buffer size.
*
* @param bufferSize for the underlying data structure.
*/
public MultiThreadedClaimStrategy(final int bufferSize)
{
this.bufferSize = bufferSize;
}
@Override
public int getBufferSize()
{
return bufferSize;
}
@Override
public long getSequence()
{
return claimSequence.get();
}
@Override
public boolean hasAvailableCapacity(final int availableCapacity, final Sequence[] dependentSequences)
{
final long wrapPoint = (claimSequence.get() + availableCapacity) - bufferSize;
final MutableLong minGatingSequence = minGatingSequenceThreadLocal.get();
if (wrapPoint > minGatingSequence.get())
{
long minSequence = getMinimumSequence(dependentSequences);
minGatingSequence.set(minSequence);
if (wrapPoint > minSequence)
{
return false;
}
}
return true;
}
@Override
public long incrementAndGet(final Sequence[] dependentSequences)
{
final MutableLong minGatingSequence = minGatingSequenceThreadLocal.get();
waitForCapacity(dependentSequences, minGatingSequence);
final long nextSequence = claimSequence.incrementAndGet();
waitForFreeSlotAt(nextSequence, dependentSequences, minGatingSequence);
return nextSequence;
}
@Override
public long incrementAndGet(final int delta, final Sequence[] dependentSequences)
{
final long nextSequence = claimSequence.addAndGet(delta);
waitForFreeSlotAt(nextSequence, dependentSequences, minGatingSequenceThreadLocal.get());
return nextSequence;
}
@Override
public void setSequence(final long sequence, final Sequence[] dependentSequences)
{
claimSequence.lazySet(sequence);
waitForFreeSlotAt(sequence, dependentSequences, minGatingSequenceThreadLocal.get());
}
@Override
public void serialisePublishing(final long sequence, final Sequence cursor, final int batchSize)
{
final long expectedSequence = sequence - batchSize;
while (expectedSequence != cursor.get())
{
// busy spin
}
cursor.set(sequence);
}
private void waitForCapacity(final Sequence[] dependentSequences, final MutableLong minGatingSequence)
{
final long wrapPoint = (claimSequence.get() + 1L) - bufferSize;
if (wrapPoint > minGatingSequence.get())
{
long minSequence;
while (wrapPoint > (minSequence = getMinimumSequence(dependentSequences)))
{
LockSupport.parkNanos(1L);
}
minGatingSequence.set(minSequence);
}
}
private void waitForFreeSlotAt(final long sequence, final Sequence[] dependentSequences, final MutableLong minGatingSequence)
{
final long wrapPoint = sequence - bufferSize;
if (wrapPoint > minGatingSequence.get())
{
long minSequence;
while (wrapPoint > (minSequence = getMinimumSequence(dependentSequences)))
{
LockSupport.parkNanos(1L);
}
minGatingSequence.set(minSequence);
}
}
}
| 31.314103 | 129 | 0.677584 |
3a2ae255a3f7adeb7041685639f74185f24981b9 | 3,361 | /*
* Copyright (c) 2021, Nelson Gonçalves. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.alg.color.impl;
import boofcv.struct.image.GrayF32;
import boofcv.struct.image.Planar;
public class ImplColorCmyk {
public static void cmykToRgb_F32(Planar<GrayF32> cmyk, Planar<GrayF32> rgb) {
GrayF32 C = cmyk.getBand(0);
GrayF32 M = cmyk.getBand(1);
GrayF32 Y = cmyk.getBand(2);
GrayF32 K = cmyk.getBand(3);
GrayF32 R = rgb.getBand(0);
GrayF32 G = rgb.getBand(1);
GrayF32 B = rgb.getBand(2);
for (int row = 0; row < cmyk.height; row++) {
int indexCmyk = cmyk.startIndex + row * cmyk.stride;
int indexRgb = rgb.startIndex + row * rgb.stride;
int endRgb = indexRgb + cmyk.width;
for (; indexRgb < endRgb; indexCmyk++, indexRgb++) {
float c = C.data[indexCmyk];
float m = M.data[indexCmyk];
float y = Y.data[indexCmyk];
float k = K.data[indexCmyk];
R.data[indexRgb] = 255 * (1 - c / 100) * (1 - k / 100);
G.data[indexRgb] = 255 * (1 - m / 100) * (1 - k / 100);
B.data[indexRgb] = 255 * (1 - y / 100) * (1 - k / 100);
}
}
}
public static void rgbToCmyk_F32(Planar<GrayF32> rgb, Planar<GrayF32> cmyk) {
GrayF32 R = rgb.getBand(0);
GrayF32 G = rgb.getBand(1);
GrayF32 B = rgb.getBand(2);
GrayF32 C = cmyk.getBand(0);
GrayF32 M = cmyk.getBand(1);
GrayF32 Y = cmyk.getBand(2);
GrayF32 K = cmyk.getBand(3);
for (int row = 0; row < cmyk.height; row++) {
int indexRgb = rgb.startIndex + row * rgb.stride;
int indexCmyk = cmyk.startIndex + row * cmyk.stride;
int endRgb = indexRgb + cmyk.width;
for (; indexRgb < endRgb; indexCmyk++, indexRgb++) {
float r = R.data[indexRgb];
float g = G.data[indexRgb];
float b = B.data[indexRgb];
float percentageR = r / 255 * 100;
float percentageG = g / 255 * 100;
float percentageB = b / 255 * 100;
float k = 100 - Math.max(Math.max(percentageR, percentageG), percentageB);
K.data[indexCmyk] = k;
if (k == 100) {
C.data[indexCmyk] = 0;
M.data[indexCmyk] = 0;
Y.data[indexCmyk] = 0;
} else {
C.data[indexCmyk] = (100 - percentageR - k) / (100 - k) * 100;
M.data[indexCmyk] = (100 - percentageG - k) / (100 - k) * 100;
Y.data[indexCmyk] = (100 - percentageB - k) / (100 - k) * 100;
}
}
}
}
}
| 36.532609 | 90 | 0.537935 |
ceee51d0e190c865bda82c9d341350b3494c61cd | 3,161 | /*
* 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.sling.feature.maven.mojos;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.maven.model.Build;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.apache.sling.feature.Feature;
import org.apache.sling.feature.io.json.FeatureJSONReader;
import org.apache.sling.feature.maven.FeatureConstants;
import org.junit.Test;
import org.mockito.Mockito;
public class AttachFeaturesMojoTest {
@Test
public void testAttachArtifacts() throws Exception {
File feat_a = new File(getClass().getResource("/attach-resources/features/processed/test_a.json").toURI());
File feat_d = new File(getClass().getResource("/attach-resources/features/processed/test_d.json").toURI());
final Map<String, Feature> features = new HashMap<>();
try ( final FileReader r = new FileReader(feat_a) ) {
features.put(feat_a.getAbsolutePath(), FeatureJSONReader.read(r, feat_a.getAbsolutePath()));
}
try ( final FileReader r = new FileReader(feat_d) ) {
features.put(feat_d.getAbsolutePath(), FeatureJSONReader.read(r, feat_d.getAbsolutePath()));
}
File featuresDir = feat_a.getParentFile().getParentFile().getParentFile();
Build build = new Build();
build.setDirectory(featuresDir.getCanonicalPath());
MavenProject project = new MavenProject();
project.setGroupId("testing");
project.setArtifactId("test");
project.setVersion("1.0.1");
project.setBuild(build);
AttachFeaturesMojo af = new AttachFeaturesMojo();
af.project = project;
MavenProjectHelper helper = Mockito.mock(MavenProjectHelper.class);
af.projectHelper = helper;
af.attachClassifierFeatures(features, new ArrayList<>(), true);
Mockito.verify(helper).attachArtifact(project, FeatureConstants.PACKAGING_FEATURE, "testa", new File(featuresDir, "slingfeature-tmp" + File.separatorChar + "feature-testa.json"));
Mockito.verify(helper).attachArtifact(project, FeatureConstants.PACKAGING_FEATURE, "testd", new File(featuresDir, "slingfeature-tmp" + File.separatorChar + "feature-testd.json"));
Mockito.verifyNoMoreInteractions(helper);
}
}
| 44.521127 | 187 | 0.726985 |
e1deba19fc067d7912d50952a2f0729d822f47a7 | 6,380 | package com.oimchat.server.general.kernel.work.module.business.contact.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.oimchat.server.basic.common.util.KeyUtil;
import com.oimchat.server.general.kernel.work.module.base.contact.dao.ContactCategoryDAO;
import com.oimchat.server.general.kernel.work.module.base.contact.dao.ContactRelationDAO;
import com.oimchat.server.general.kernel.work.module.base.contact.entity.ContactCategory;
import com.oimchat.server.general.kernel.work.module.base.contact.manager.ContactCategoryManager;
import com.oimchat.server.general.kernel.work.module.base.contact.push.ContactCategoryPush;
import com.onlyxiahui.aware.basic.work.business.error.ErrorCode;
import com.onlyxiahui.common.message.result.ResultBodyMessage;
import com.onlyxiahui.common.message.result.ResultMessage;
import com.onlyxiahui.common.utils.base.lang.string.StringUtil;
import com.onlyxiahui.common.utils.base.util.time.DateUtil;
/**
*
* Date 2019-01-20 14:01:41<br>
* Description
*
* @author XiaHui<br>
* @since 1.0.0
*/
@Service
@Transactional
public class ContactCategoryService {
@Resource
private ContactCategoryDAO contactCategoryDAO;
@Resource
private ContactCategoryPush contactCategoryPush;
@Resource
private ContactRelationDAO contactRelationDAO;
@Resource
private ContactCategoryManager contactCategoryManager;
/**
*
* Date 2019-01-20 14:09:57<br>
* Description 获取所有分组
*
* @author XiaHui<br>
* @param userId
* @return
* @since 1.0.0
*/
public List<ContactCategory> getListByUserId(String userId) {
List<ContactCategory> list = contactCategoryDAO.getListByUserId(userId);
return list;
}
public ContactCategory getById(String userId, String id) {
ContactCategory category = contactCategoryDAO.get(ContactCategory.class, id);
return category;
}
/**
*
* Date 2019-01-20 14:04:32<br>
* Description 新增好友分组
*
* @author XiaHui<br>
* @param contactCategory
* @return
* @since 1.0.0
*/
public ResultBodyMessage<ContactCategory> add(ContactCategory contactCategory) {
ResultBodyMessage<ContactCategory> message = new ResultBodyMessage<>();
if (null != contactCategory) {
try {
int maxCount = 30;
String userId = contactCategory.getUserId();
long count = contactCategoryDAO.getContactCategoryCount(userId);
if (count >= maxCount) {
message.addWarning(ErrorCode.business.code("0001"), "分组已经达到最大上限!");
} else {
int sort = (int) count;
contactCategory.setSort(sort);
contactCategory.setType(ContactCategory.type_custom);
contactCategory.setCreatedDateTime(DateUtil.getCurrentDateTime());
contactCategory.setCreatedTimestamp(System.currentTimeMillis());
contactCategoryDAO.save(contactCategory);
message.setBody(contactCategory);
contactCategoryPush.pushAdd(userId, KeyUtil.getKey(), contactCategory.getId());
}
} catch (Exception e) {
e.printStackTrace();
message.addWarning(ErrorCode.system.code("500"), "系统异常!");
}
} else {
message.addWarning(ErrorCode.system.code("500"), "系统异常!");
}
return message;
}
/**
*
* Date 2019-01-20 14:06:12<br>
* Description 修改分组名称
*
* @author XiaHui<br>
* @param id
* @param name
* @return
* @since 1.0.0
*/
public ResultMessage updateName(String userId, String id, String name) {
ResultMessage message = new ResultMessage();
try {
if (StringUtil.isNotBlank(id)) {
ContactCategory contactCategory = contactCategoryDAO.get(ContactCategory.class, id);
contactCategory.setName(name);
contactCategoryDAO.update(contactCategory);
message.bodyPut("category", contactCategory);
contactCategoryPush.pushUpdateName(userId, KeyUtil.getKey(), id, name);
} else {
message.addWarning(ErrorCode.system.code("500"), "系统异常!");
}
} catch (Exception e) {
e.printStackTrace();
message.addWarning(ErrorCode.system.code("500"), "系统异常!");
}
return message;
}
/**
*
* Date 2019-01-20 17:26:21<br>
* Description 修改排序
*
* @author XiaHui<br>
* @param userId
* @param id
* @param sort
* @return
* @since 1.0.0
*/
public ResultMessage updateSort(String userId, String id, int sort) {
ResultMessage message = new ResultMessage();
try {
if (StringUtil.isNotBlank(id)) {
List<ContactCategory> list = contactCategoryDAO.getListByUserId(userId);
int size = list.size();
if (sort < size) {
int temp = 0;
for (int i = 0; i < size; i++) {
ContactCategory m = list.get(i);
if (!m.getId().equals(id)) {
if (temp == sort) {
temp++;
}
contactCategoryDAO.updateSort(m.getId(), temp);
temp++;
}
}
contactCategoryDAO.updateSort(id, sort);
}
contactCategoryPush.pushUpdateSort(userId, KeyUtil.getKey());
} else {
message.addWarning(ErrorCode.system.code("500"), "系统异常!");
}
} catch (Exception e) {
e.printStackTrace();
message.addWarning(ErrorCode.system.code("500"), "系统异常!");
}
return message;
}
/**
*
* Date 2019-01-20 16:56:33<br>
* Description
*
* @author XiaHui<br>
* @param id
* @return
* @since 1.0.0
*/
public ResultMessage delete(String userId, String id) {
ResultMessage message = new ResultMessage();
ContactCategory category = contactCategoryDAO.get(ContactCategory.class, id);
if (null != category) {
if (ContactCategory.type_default == category.getType()) {
message.addWarning(ErrorCode.business.code("001"), "不能删除默认分组!");
} else {
contactCategoryDAO.deleteById(ContactCategory.class, id);
String newCategoryId = contactCategoryManager.getOrCreateDefaultCategoryId(userId);
contactRelationDAO.updateChangeCategoryId(userId, id, newCategoryId);
contactCategoryPush.pushDelete(userId, KeyUtil.getKey(), id);
}
}
return message;
}
public void saveDefault(String userId) {
ContactCategory bean = contactCategoryDAO.getDefaultContactCategory(userId);
if (null == bean) {
ContactCategory contactCategory = new ContactCategory();// 生成默认分组信息
contactCategory.setUserId(userId);
contactCategory.setName("我的好友");
contactCategory.setSort(0);
contactCategory.setType(ContactCategory.type_default);
contactCategoryDAO.save(contactCategory);
}
}
}
| 28.868778 | 97 | 0.714734 |
8b75cce9b56e6b0a13d13993cab64f7d35bb78b4 | 2,135 | package com.twelvemonkeys.imageio.plugins.pntg;
import com.twelvemonkeys.imageio.util.ImageReaderAbstractTest;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* PNTGImageReaderTest.
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haraldk$
* @version $Id: PNTGImageReaderTest.java,v 1.0 23/03/2021 haraldk Exp$
*/
public class PNTGImageReaderTest extends ImageReaderAbstractTest<PNTGImageReader> {
@Override
protected ImageReaderSpi createProvider() {
return new PNTGImageReaderSpi();
}
@Override
protected List<TestData> getTestData() {
return Arrays.asList(new TestData(getClassLoaderResource("/mac/porsches.mac"), new Dimension(576, 720)),
new TestData(getClassLoaderResource("/mac/MARBLES.MAC"), new Dimension(576, 720)));
}
@Override
protected List<String> getFormatNames() {
return Arrays.asList("PNTG", "pntg");
}
@Override
protected List<String> getSuffixes() {
return Arrays.asList("mac", "pntg");
}
@Override
protected List<String> getMIMETypes() {
return Collections.singletonList("image/x-pntg");
}
@Override
public void testProviderCanRead() throws IOException {
// TODO: This a kind of hack...
// Currently, the provider don't claim to read the MARBLES.MAC image,
// as it lacks the MacBinary header and thus no way to identify format.
// We can still read it, so we'll include it in the other tests.
List<TestData> testData = getTestData().subList(0, 1);
for (TestData data : testData) {
ImageInputStream stream = data.getInputStream();
assertNotNull(stream);
assertTrue("Provider is expected to be able to decode data: " + data, provider.canDecodeInput(stream));
}
}
} | 32.846154 | 115 | 0.688056 |
bfb9a11efee50d6a756625b4e96db0e1b5a3be6c | 9,300 | package com.ygoular.bitmapconverter;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import java.nio.ByteBuffer;
/**
* Project : bitmapconverter
*
*
* Offer static methods to convert an Android Bitmap Object to a byte array specifically
* formatted to represent a .bmp file either in 8-bit mod or 24-bit mod depending on the configuration
*
* Useful links to understand bmp files
* https://www.javaworld.com/article/2077561/learn-java/java-tip-60--saving-bitmap-files-in-java.html
* http://paulbourke.net/dataformats/bitmaps/
* https://en.wikipedia.org/wiki/8-bit_color
* https://en.wikipedia.org/wiki/BMP_file_format
*
*/
public class BitmapConverter {
private static final int BITMAP_WIDTH_MULTIPLE_OF_CONSTRAINT = 4; // Constraint of bmp format
private static final int FILE_HEADER_SIZE = 0xE; // Fixed size due to bmp format
private static final int INFO_HEADER_SIZE = 0x28; // Fixed size for BITMAPINFOHEADER header version (Windows NT, 3,1x or later)
private static final BitmapFormat BITMAP_DEFAULT_FORMAT = BitmapFormat.BITMAP_24_BIT_COLOR;
private static final int ASCII_VALUE_B_CC = 0x42;
private static final int ASCII_VALUE_M_CC = 0x4D;
// Buffer that store data to bmp file format
private ByteBuffer buffer;
// Different properties of bmp file format
private int numberOfColors;
private int imageDataOffset;
private int bytePerPixel;
private int width;
private int height;
private int rowWidthInBytes;
private int imageDataSize;
private int fileSize;
private int[] pixels;
private byte[] dummyBytesPerRow;
private boolean needPadding;
public BitmapConverter() { /* Empty constructor */ }
/**
* Convert Android Bitmap object into bmp file default format byte array
* @param bitmap object to convert
* @return array of byte to bmp file format
*/
public byte[] convert(@NonNull final Bitmap bitmap) {
return convert(bitmap, BITMAP_DEFAULT_FORMAT);
}
/**
* Convert Android Bitmap object into bmp file specified format byte array
* @param bitmap object to convert
* @param format of the output array
*
* @see BitmapFormat
* @return array of byte to bmp file format
*/
public byte[] convert(@NonNull final Bitmap bitmap, @NonNull final BitmapFormat format) {
calculateInfoHeaderDataFromFormat(format);
// Image size
width = bitmap.getWidth();
height = bitmap.getHeight();
// An array to receive the pixels from the source image
pixels = new int[width * height];
// Row width in bytes
rowWidthInBytes = bytePerPixel * width; // Source image width * number of bytes to encode one pixel.
calculatePadding();
// The number of bytes used in the file to store raw image data (excluding file headers)
imageDataSize = (rowWidthInBytes + (needPadding ?dummyBytesPerRow.length:0)) * height;
// Final size of the file
fileSize = imageDataSize + imageDataOffset;
// Android Bitmap Image Data
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
// Buffer that will contain the data of the Bitmap
buffer = ByteBuffer.allocate(fileSize);
writeFileHeader(); /* BITMAP FILE HEADER */
writeInfoHeader(format); /* BITMAP INFO HEADER */
if(numberOfColors != 0) writeColorTable(); /* COLOR PALETTE */
writeImageData(format); /* IMAGE DATA */
return buffer.array();
}
/**
* Set the variables depending on the BitmapFormat to convert on the Bitmap object
* @param format of the bmp array output
*/
private void calculateInfoHeaderDataFromFormat(@NonNull final BitmapFormat format) {
// The use of a color palette is only needed for 8-bit color format or less
numberOfColors = format.getValue() > 8 ? 0 : (int) Math.pow(2, format.getValue());
int colorTableSize = numberOfColors * 4; // Contains BGR bytes + 0x0 as a separator
// Offset before image data (contains all required and optional headers or color table)
imageDataOffset = FILE_HEADER_SIZE + INFO_HEADER_SIZE + colorTableSize;
bytePerPixel = format.getValue() / 0x8;
}
/**
* The amount of bytes per image row must be a multiple of 4 (requirements of bmp format).
* If image row width is not a multiple of 4 dummy pixels are created
*/
private void calculatePadding() {
if(rowWidthInBytes % BITMAP_WIDTH_MULTIPLE_OF_CONSTRAINT != 0){
needPadding = true;
// Dummy bytes that needs to added on each row
dummyBytesPerRow = new byte[(BITMAP_WIDTH_MULTIPLE_OF_CONSTRAINT - (rowWidthInBytes % BITMAP_WIDTH_MULTIPLE_OF_CONSTRAINT))];
// Just fill an array with the dummy bytes we need to append at the end of each row
for(int i = 0; i < dummyBytesPerRow.length; i++){
dummyBytesPerRow[i] = (byte)0xFF;
}
}
}
/**
* Write File header into buffer
* Represent 14 octets of data
*/
private void writeFileHeader() {
// Bitmap specific signature (BM in ASCII)
buffer.put((byte) ASCII_VALUE_B_CC); // B
buffer.put((byte) ASCII_VALUE_M_CC); // M
// Size of the final file
buffer.put(writeInt(fileSize));
// Reserved bytes
buffer.put(writeShort((short)0));
buffer.put(writeShort((short)0));
// Image data offset
buffer.put(writeInt(imageDataOffset));
}
/**
* Write Info header into buffer
* Represent 40 octets of data
*/
private void writeInfoHeader(@NonNull final BitmapFormat format) {
// Size of Info Header
buffer.put(writeInt(INFO_HEADER_SIZE));
// width (row) and height (columns) of the image data
buffer.put(writeInt(width+(needPadding ?(dummyBytesPerRow.length==3?1:0):0)));
buffer.put(writeInt(height));
// Color Planes --> must be 1
buffer.put(writeShort((short)1));
// Bit count (correspond to the different bmp file format)
buffer.put(writeShort((short)format.getValue()));
// Bit compression --> 0 means none
buffer.put(writeInt(0));
// Image data size
buffer.put(writeInt(imageDataSize));
// Horizontal resolution in pixels per meter
buffer.put(writeInt(0x0B13));
// Vertical resolution in pixels per meter
buffer.put(writeInt(0x0B13));
// Number of color used --> different of 0 only if a color palette is used (2^n in this case)
// n corresponding to the number of bits per pixel
buffer.put(writeInt(numberOfColors));
// Number of color important --> 0 means all
buffer.put(writeInt(0x0));
}
/**
* Write Color palette into buffer
* Represent 1024 octets of data
*/
private void writeColorTable() {
// GrayScaled Colors
for (int i = 0 ; i < numberOfColors ; i++) {
buffer.put((byte)i);// B
buffer.put((byte)i);// G
buffer.put((byte)i);// R
buffer.put((byte)0x00); // Separator
}
}
/**
* Write Image data into buffer
* All the bytes are written starting from the end of the image data
*/
private void writeImageData(@NonNull final BitmapFormat format) {
int row = height;
int col = width;
int startPosition = (row - 1) * col;
int endPosition = row * col;
while( row > 0 ){
for(int i = startPosition; i < endPosition; i++ )
writeImageData(pixels[i], format);
if(needPadding)
buffer.put(dummyBytesPerRow);
row--;
endPosition = startPosition;
startPosition = startPosition - col;
}
}
/**
* Write gray scaled image data into a number of bytes depending on the current BitmapFormat
* !! This will not work for less than 8-bit color formats !!
* Pixels are just written x number of times
* @param pixel data
* @param format of the output byte array
*/
private void writeImageData(final int pixel, @NonNull final BitmapFormat format) {
for(int i = 0 ; i < (format.getValue()/8) ; i++)
buffer.put((byte)(pixel));
}
/**
* Write int (16 bits) in a byte array (little-endian order)
* @param value to write in a byte array
* @return the byte array containing the data
*/
private byte[] writeShort(final short value) {
byte[] b = new byte[2];
b[0] = (byte)(value & 0x00FF);
b[1] = (byte)((value & 0xFF00) >> 8);
return b;
}
/**
* Write int (32 bits) in a byte array (little-endian order)
* @param value to write in a byte array
* @return the byte array containing the data
*/
private byte[] writeInt(final int value) {
byte[] b = new byte[4];
b[0] = (byte)(value & 0x000000FF);
b[1] = (byte)((value & 0x0000FF00) >> 8);
b[2] = (byte)((value & 0x00FF0000) >> 16);
b[3] = (byte)((value & 0xFF000000) >> 24);
return b;
}
}
| 34.701493 | 137 | 0.631398 |
6c72d57dad3831f64565b15e310a983a1d9b2ec5 | 2,729 |
package mage.cards.f;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.effects.Effect;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.counter.AddCountersTargetEffect;
import mage.abilities.effects.keyword.ManifestEffect;
import mage.cards.Card;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.counters.CounterType;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.players.Player;
import mage.target.targetpointer.FixedTarget;
/**
*
* @author LevelX2
*/
public final class FierceInvocation extends CardImpl {
public FierceInvocation(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.SORCERY},"{4}{R}");
// Manifest the top card of your library, then put two +1/+1 counters on it.<i> (To manifest a card, put it onto the battlefield face down as a 2/2 creature. Turn it face up any time for its mana cost if it's a creature card.)</i>
this.getSpellAbility().addEffect(new FierceInvocationEffect());
}
private FierceInvocation(final FierceInvocation card) {
super(card);
}
@Override
public FierceInvocation copy() {
return new FierceInvocation(this);
}
}
class FierceInvocationEffect extends OneShotEffect {
public FierceInvocationEffect() {
super(Outcome.Benefit);
this.staticText = "Manifest the top card of your library, then put two +1/+1 counters on it.<i> (To manifest a card, put it onto the battlefield face down as a 2/2 creature. Turn it face up any time for its mana cost if it's a creature card.)</i>";
}
public FierceInvocationEffect(final FierceInvocationEffect effect) {
super(effect);
}
@Override
public FierceInvocationEffect copy() {
return new FierceInvocationEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Player controller = game.getPlayer(source.getControllerId());
if (controller != null) {
Card card = controller.getLibrary().getFromTop(game);
if (card != null) {
new ManifestEffect(1).apply(game, source);
Permanent permanent = game.getPermanent(card.getId());
if (permanent != null) {
Effect effect = new AddCountersTargetEffect(CounterType.P1P1.createInstance(2));
effect.setTargetPointer(new FixedTarget(permanent, game));
return effect.apply(game, source);
}
}
return true;
}
return false;
}
}
| 34.544304 | 256 | 0.676072 |
3e1ebe9fe26866b7ce248c95743635fa801ad019 | 180 | package cn.codethink.xiaoming.event;
/**
* 群临时会话消息撤回事件
*
* @author Chuanwise
*/
public interface GroupMemberMessageRecallEvent
extends Event, MemberMessageRecallEvent {
}
| 16.363636 | 46 | 0.761111 |
fc7cd07d98d0f23a87d484ec626eac5a82c5326e | 13,871 | /*
* 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 Patient;
//import all the needed methods
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import util.Controller;
import util.UIFactory;
import util.View;
/**
*
* @author SiziJayawardena
*/
//implement the class Admission Controller
public class AdmissionController implements Controller{
//create a new Admission object
private final Admission view = new Admission();
//declare needed variables
private int ad, pat, gua;
private String genderP, genderG,PID, GID;
@Override
public void initializeView() {
//action for back button
view.getBtnBack().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
UIFactory.hideUI(UIFactory.UIName.ADMISSION);
UIFactory.showUI(UIFactory.UIName.PATIENT);
}
});
//get the current consultant IDs into the combo box
view.getComboConsID().addFocusListener(new FocusListener(){
@Override
public void focusGained(FocusEvent e) {
Statement s = util.Database.getStatement();
try {
ResultSet rs = s.executeQuery("SELECT ConsID FROM Consultantx ORDER BY ConsID ASC");
view.comboConsID.removeAllItems();
view.comboConsID.setSelectedItem("Select");
while(rs.next()){
view.comboConsID.addItem(rs.getString("ConsID"));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void focusLost(FocusEvent e) {
}
});
//get the current doctor IDs nto the combo box
view.getComboDocID().addFocusListener(new FocusListener(){
@Override
public void focusGained(FocusEvent e) {
Statement s = util.Database.getStatement();
try {
ResultSet rs = s.executeQuery("SELECT DoctorID FROM Doctor");
view.comboDocID.removeAllItems();
while(rs.next()){
view.comboDocID.addItem(rs.getString("DoctorID"));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void focusLost(FocusEvent e) {
}
});
//get the current ward numbers into the combo box
view.getComboWardNo().addFocusListener(new FocusListener(){
@Override
public void focusGained(FocusEvent e) {
Statement s = util.Database.getStatement();
try {
ResultSet rs = s.executeQuery("SELECT WardNo,WardName FROM Ward ORDER BY WardNo ASC");
view.comboWardNo.removeAllItems();
while(rs.next()){
view.comboWardNo.addItem(rs.getString("WardNo")+"-"+rs.getString("WardName"));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void focusLost(FocusEvent e) {
}
});
//t the current guardian IDs into the combo box
view.getComboOldIDG().addFocusListener(new FocusListener(){
@Override
public void focusGained(FocusEvent e) {
Statement s = util.Database.getStatement();
try {
ResultSet rs = s.executeQuery("SELECT GuardianID FROM Guardian");
view.comboOldIDG.removeAllItems();
while(rs.next()){
view.comboOldIDG.addItem(rs.getString("GuardianID"));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
//and set the correponding attribute values for the selected guardian ID into the textfields when Focusi is lost from that combo box
@Override
public void focusLost(FocusEvent e) {
Statement s1 = util.Database.getStatement();
try {
ResultSet rs1 = s1.executeQuery("SELECT * FROM Guardian WHERE GuardianID = '"+view.comboOldIDG.getSelectedItem().toString()+"'");
while(rs1.next()){
view.txtAddressG.setText(rs1.getString("Address"));
view.txtFNameG.setText(rs1.getString("FName"));
view.txtLNameG.setText(rs1.getString("LName"));
view.txtTelG.setText(rs1.getString("Tel_No"));
view.txtNICG.setText(rs1.getString("NIC"));
view.txtGuardianID.setText(rs1.getString("GuardianID"));
if (rs1.getString("Gender").equals("Male")){
view.radioMaleG.setSelected(true);
}
else if (rs1.getString("Gender").equals("Female")){
view.radioFemaleG.setSelected(true);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
//generate next patientID, GuardianID and AdmissionID for the next record
view.getBtnGenerate().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ad=0;
pat=0;
gua=0;
try{
Statement s = util.Database.getStatement();
ResultSet rs = s.executeQuery("SELECT * FROM Patient,Admission,Guardian");
while(rs.next()){
ad = Integer.parseInt(rs.getString("AdmissionID")) ;
pat = Integer.parseInt(rs.getString("PatientID"));
gua = Integer.parseInt(rs.getString("GuardianID"));
}
view.txtAdmissionID.setText(Integer.toString(ad+1));
view.txtPatientID.setText(Integer.toString(pat+1));
view.txtGuardianID.setText(Integer.toString(gua+1));
}catch(Exception ae){
ae.printStackTrace();
}
}
});
//action for the Submit button
//Insert the new records into the database
view.getBtnSubmit().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
try{
Statement s = util.Database.getStatement();
if(view.radioMaleP.isSelected()){
genderP = "Male";
}
else if(view.radioFemaleP.isSelected()){
genderP = "Female";
}
if(view.radioMaleG.isSelected()){
genderG = "Male";
}
else if(view.radioFemaleG.isSelected()){
genderG = "Female";
}
if(! view.checkG.isSelected()){
s.executeUpdate("INSERT INTO Guardian(GuardianID,FName,LName,Address,NIC,Tel_No,Gender) VALUES ('"+view.txtGuardianID.getText()+"','"+view.txtFNameG.getText()+"','"+view.txtLNameG.getText()+"','"+view.txtAddressG.getText()+"','"+view.txtNICG.getText()+"','"+view.txtTelG.getText()+"','"+genderG+"')");
GID = view.txtGuardianID.getText();
}
else{
GID = view.comboOldIDG.getSelectedItem().toString();
}
s.executeUpdate("INSERT INTO Patient (FName,LName,Address,NIC,Tel_No,Age,Gender,Guardian_GuardianID,Ward_WardNo,Consultantx_ConsID,Doctor_DoctorID) VALUES ('"+view.txtFNameP.getText()+"','"+view.txtLNameP.getText()+"','"+view.txtAddressP.getText()+"','"+view.txtNICP.getText()+"','"+view.txtTelP.getText()+"','"+view.txtAgeP.getText()+"','"+genderP+"','"+GID+"','"+view.comboWardNo.getSelectedItem().toString()+"','"+view.comboConsID.getSelectedItem().toString()+"','"+view.comboDocID.getSelectedItem().toString()+"')");
//PID = view.txtOldIDP.getText();
s.executeUpdate("INSERT INTO Admission (InDate,Patient_PatientID) VALUES (DATE '"+view.txtDate.getText()+"' , '"+view.txtPatientID.getText()+"')");
UIFactory.showUI(UIFactory.UIName.SUCCESSFUL);
}catch(Exception ae){
ae.printStackTrace();
UIFactory.showUI(UIFactory.UIName.UNSUCCESSFUL);
}
}
});
//search for current PatientIDs and get the relevant details
view.getBtnSearchOldID().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
Statement s = util.Database.getStatement();
ResultSet rs = s.executeQuery("SELECT * FROM Patient WHERE Patient.NIC = '"+view.txtNICP.getText()+"'");
while(rs.next()){
view.txtFNameP.setText(rs.getString("FName"));
view.txtAddressP.setText(rs.getString("Address"));
view.txtLNameP.setText(rs.getString("LName"));
view.txtNICP.setText(rs.getString("NIC"));
view.txtTelP.setText(rs.getString("Tel_No"));
view.txtAgeP.setText(rs.getString("Age"));
if (rs.getString("Gender").equals("Male")){
view.radioMaleP.setSelected(true);
}
else if (rs.getString("Gender").equals("Female")){
view.radioFemaleP.setSelected(true);
}
}
}catch(Exception ea){
ea.printStackTrace();
UIFactory.showUI(UIFactory.UIName.UNSUCCESSFUL);
}
}
});
//clear all the fields
view.getBtnClear().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
view.txtPatientID.setText(null);
view.txtAdmissionID.setText(null);
view.txtGuardianID.setText(null);
view.txtAddressP.setText(null);
view.txtAddressG.setText(null);
view.comboOldIDG.removeAllItems();
view.comboOldIDG.addItem("Select");
view.comboOldIDG.setSelectedItem("Select");
view.comboConsID.removeAllItems();
view.comboConsID.addItem("Select");
view.comboConsID.setSelectedItem("Select");
view.txtFNameP.setText(null);
view.txtFNameG.setText(null);
view.txtLNameP.setText(null);
view.txtLNameG.setText(null);
view.comboWardNo.removeAllItems();
view.comboWardNo.addItem("Select");
view.comboWardNo.setSelectedItem("Select");
view.comboDocID.removeAllItems();
view.comboDocID.addItem("Select");
view.comboDocID.setSelectedItem("Select");
view.checkP.setSelected(false);
view.checkG.setSelected(false);
view.txtNICP.setText(null);
view.txtNICG.setText(null);
view.txtAgeP.setText(null);
view.txtTelP.setText(null);
view.txtTelG.setText(null);
view.txtDate.setText("YYYY-MM-DD");
view.buttonGroup1.clearSelection();
view.buttonGroup2.clearSelection();
}catch(Exception ae){
ae.printStackTrace();
}
}
});
}
//other abstract methods
@Override
public View getView() {
return view;
}
@Override
public void updateView() {
}
@Override
public void clearView() {
}
}
| 40.205797 | 540 | 0.490015 |
224388be3521dee6fc3b3ec5e9f654e86ff2c396 | 603 | package com.app.chx.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class ItemsController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("value", "數據");
modelAndView.setViewName("/WEB-INF/jsp/items/items_controller.jsp");
return modelAndView;
}
}
| 27.409091 | 104 | 0.80597 |
5b73eab9c8b0e20391ddcb8d8f87e617489178da | 2,888 | package com.smatechnologies.opcon.restapiclient.api.dailyschedules;
import com.smatechnologies.opcon.commons.objmapper.annotation.ObjMapperField;
import com.smatechnologies.opcon.restapiclient.criteria.AbstractResourcesCriteria;
import com.smatechnologies.opcon.restapiclient.criteria.SortedColumn;
import java.time.LocalDate;
import java.util.Collection;
/**
* @author Pierre PINON
*/
public class DailySchedulesCriteria extends AbstractResourcesCriteria<DailySchedulesCriteria.DailyScheduleColumns> {
@ObjMapperField
private Collection<String> ids;
@ObjMapperField
private Collection<Integer> uids;
@ObjMapperField
private Collection<LocalDate> dates;
@ObjMapperField
private String path;
@ObjMapperField
private String status;
@ObjMapperField
private Collection<String> categories;
@ObjMapperField
private Boolean failedJobs;
@ObjMapperField
private Boolean includeCount;
@ObjMapperField
private String name;
public Collection<String> getIds() {
return ids;
}
public void setIds(Collection<String> ids) {
this.ids = ids;
}
public Collection<Integer> getUids() {
return uids;
}
public void setUids(Collection<Integer> uids) {
this.uids = uids;
}
public Collection<LocalDate> getDates() {
return dates;
}
public void setDates(Collection<LocalDate> dates) {
this.dates = dates;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Collection<String> getCategories() {
return categories;
}
public void setCategories(Collection<String> categories) {
this.categories = categories;
}
public Boolean getFailedJobs() {
return failedJobs;
}
public void setFailedJobs(Boolean failedJobs) {
this.failedJobs = failedJobs;
}
public Boolean getIncludeCount() {
return includeCount;
}
public void setIncludeCount(Boolean includeCount) {
this.includeCount = includeCount;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
/**
* Allowed column to specify for sort order.
*/
public enum DailyScheduleColumns implements SortedColumn.Column {
PATH("path"),
DATE("date"),
STATUS("status"),
START_TIME("startTime"),
END_TIME("endTime");
private String name;
DailyScheduleColumns(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
}
} | 21.080292 | 116 | 0.647507 |
5e3208bfeedd803a439a414deab087793bf9739d | 11,439 | /**
* Copyright 2014 Conductor, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.baynote.kafka.hadoop;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import kafka.api.*;
import kafka.common.ErrorMapping;
import kafka.common.TopicAndPartition;
import kafka.consumer.SimpleConsumer;
import kafka.message.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import scala.Option;
import scala.collection.Iterator;
import scala.collection.immutable.Map;
import com.baynote.kafka.Broker;
import com.baynote.kafka.Partition;
import com.baynote.kafka.zk.ZkUtils;
/**
* @author cgreen
*/
@RunWith(MockitoJUnitRunner.class)
public class KafkaRecordReaderTest {
@Mock
private TaskAttemptContext context;
@Mock
private SimpleConsumer mockConsumer;
@Mock
private ByteBufferMessageSet mockMessage;
@Mock
private Iterator<MessageAndOffset> mockIterator;
private Configuration conf;
private KafkaInputSplit split;
private KafkaRecordReader reader;
private Partition partition;
private FetchResponse fetchResponse = mock(FetchResponse.class);;
@Before
public void setUp() throws Exception {
conf = new Configuration(false);
when(context.getConfiguration()).thenReturn(conf);
final Job job = mock(Job.class);
when(job.getConfiguration()).thenReturn(conf);
when(fetchResponse.messageSet("topic", 0)).thenReturn(mockMessage);
KafkaInputFormat.setConsumerGroup(job, "group");
KafkaInputFormat.setKafkaSocketTimeoutMs(job, 1000);
KafkaInputFormat.setKafkaBufferSizeBytes(job, 4096);
KafkaInputFormat.setKafkaFetchSizeBytes(job, 2048);
final Broker broker = new Broker("localhost", 9092, 1);
this.partition = new Partition("topic", 0, broker);
split = new KafkaInputSplit(partition, 0, 100, true);
reader = spy(new KafkaRecordReader());
reader.initialize(split, context);
}
@Test
public void testInitialize() throws Exception {
assertEquals(conf, reader.getConf());
assertEquals(split, reader.getSplit());
assertEquals("localhost", reader.getConsumer(reader.getSplit(), reader.getConf()).host());
assertEquals(9092, reader.getConsumer(reader.getSplit(), reader.getConf()).port());
assertEquals(1000, reader.getConsumer(reader.getSplit(), reader.getConf()).soTimeout());
assertEquals(4096, reader.getConsumer(reader.getSplit(), reader.getConf()).bufferSize());
assertEquals(2048, reader.getFetchSize());
assertEquals(0, reader.getStart());
assertEquals(100, reader.getEnd());
assertEquals(0, reader.getPos());
assertEquals(0, reader.getPos());
assertNull("Iterator should not have been initialized yet!", reader.getCurrentMessageItr());
assertNull("Current key should be null!", reader.getCurrentKey());
assertNull("Current value should be null!", reader.getCurrentValue());
}
@Test
public void testNextKeyValue() throws Exception {
doReturn(true).when(reader).continueItr();
doReturn(mockIterator).when(reader).getCurrentMessageItr();
final byte[] messageContent = { 1 };
final MessageAndOffset msg = new MessageAndOffset(new Message(messageContent), 100l);
when(mockIterator.next()).thenReturn(msg);
assertTrue(reader.nextKeyValue());
assertEquals(100l, reader.getPos());
assertEquals(100l, reader.getCurrentKey().get());
assertArrayEquals(messageContent, reader.getCurrentValue().getBytes());
}
@Test(expected = Exception.class)
public void testContinueItrException() throws Exception {
doReturn(mockConsumer).when(reader).getConsumer(split, conf);
reader.initialize(split, context);
when(mockConsumer.fetch(any(FetchRequest.class))).thenReturn(fetchResponse);
when(fetchResponse.hasError()).thenReturn(true);
when(fetchResponse.errorCode("topic", 0)).thenReturn(ErrorMapping.InvalidFetchSizeCode());
reader.continueItr();
fail();
}
@Test
public void testContinueItrOffsetOutOfRange() throws Exception {
doReturn(mockConsumer).when(reader).getConsumer(split, conf);
reader.initialize(split, context);
when(mockConsumer.fetch(any(FetchRequest.class))).thenReturn(fetchResponse);
when(fetchResponse.hasError()).thenReturn(true);
when(fetchResponse.errorCode("topic", 0)).thenReturn(ErrorMapping.OffsetOutOfRangeCode());
assertFalse("Should be done with split!", reader.continueItr());
}
@Test
public void testContinueItr() throws Exception {
doReturn(mockConsumer).when(reader).getConsumer(split, conf);
// unfortunately, FetchRequest does not implement equals, so we have to do any(), and validate with answer
when(mockConsumer.fetch(any(FetchRequest.class))).thenAnswer(new Answer<FetchResponse>() {
@Override
public FetchResponse answer(final InvocationOnMock invocation) throws Throwable {
final FetchRequest request = (FetchRequest) invocation.getArguments()[0];
final Map<TopicAndPartition, PartitionFetchInfo> reqInfo = request.requestInfo();
final TopicAndPartition topicAndPartition = new TopicAndPartition("topic", 0);
assertTrue(reqInfo.contains(topicAndPartition));
final Option<PartitionFetchInfo> fetchInfo = reqInfo.get(topicAndPartition);
assertEquals(0, fetchInfo.get().offset());
assertEquals(2048, fetchInfo.get().fetchSize());
return fetchResponse;
}
});
when(fetchResponse.hasError()).thenReturn(false);
when(mockMessage.iterator()).thenReturn(mockIterator);
when(mockMessage.validBytes()).thenReturn(100);
when(mockIterator.hasNext()).thenReturn(true);
reader.initialize(split, context);
assertTrue("Should be able to continue iterator!", reader.continueItr());
assertEquals(mockIterator, reader.getCurrentMessageItr());
when(mockIterator.hasNext()).thenReturn(false);
assertFalse("Should be done with split!", reader.continueItr());
// call it again just for giggles
assertFalse("Should be done with split!", reader.continueItr());
}
@Test
@SuppressWarnings("unchecked")
public void testContinueItrMultipleIterations() throws Exception {
// init split
doReturn(mockConsumer).when(reader).getConsumer(split, conf);
split.setEndOffset(4097);
reader.initialize(split, context);
// first iteration
final Iterator<MessageAndOffset> mockIterator1 = mock(Iterator.class);
when(mockConsumer.fetch(any(FetchRequest.class))).thenReturn(fetchResponse);
when(fetchResponse.hasError()).thenReturn(false);
when(mockMessage.iterator()).thenReturn(mockIterator1);
when(mockMessage.validBytes()).thenReturn(2048);
when(mockIterator1.hasNext()).thenReturn(true);
assertTrue("Should be able to continue iterator!", reader.continueItr());
// reset iterator for second iteration
when(mockIterator1.hasNext()).thenReturn(false);
final Iterator<MessageAndOffset> mockIterator2 = mock(Iterator.class);
when(mockMessage.iterator()).thenReturn(mockIterator2);
when(mockIterator2.hasNext()).thenReturn(true);
assertTrue("Should be able to continue iterator!", reader.continueItr());
// reset iterator for third iteration
when(mockIterator2.hasNext()).thenReturn(false);
final Iterator<MessageAndOffset> mockIterator3 = mock(Iterator.class);
when(mockMessage.iterator()).thenReturn(mockIterator3);
when(mockIterator3.hasNext()).thenReturn(true);
when(mockMessage.validBytes()).thenReturn(1);
assertTrue("Should be able to continue iterator!", reader.continueItr());
// out of bytes to read
when(mockIterator3.hasNext()).thenReturn(false);
assertFalse("Should be done with split!", reader.continueItr());
}
@Test
public void testGetProgress() throws Exception {
assertEquals(0f, reader.getProgress(), 0f);
doReturn(true).when(reader).continueItr();
doReturn(mockIterator).when(reader).getCurrentMessageItr();
final byte[] messageContent = { 1 };
MessageAndOffset msg = new MessageAndOffset(new Message(messageContent), 10l);
when(mockIterator.next()).thenReturn(msg);
assertTrue(reader.nextKeyValue());
assertEquals(.1f, reader.getProgress(), 0f);
msg = new MessageAndOffset(new Message(messageContent), 99l);
when(mockIterator.next()).thenReturn(msg);
assertTrue(reader.nextKeyValue());
assertTrue(reader.getProgress() < 1);
msg = new MessageAndOffset(new Message(messageContent), 100l);
when(mockIterator.next()).thenReturn(msg);
assertTrue(reader.nextKeyValue());
assertEquals(1f, reader.getProgress(), 0f);
}
@Test
public void testClose() throws Exception {
doReturn(mockConsumer).when(reader).getConsumer(split, conf);
split.setPartitionCommitter(false);
reader.initialize(split, context);
doNothing().when(reader).commitOffset();
reader.close();
verify(reader, never()).commitOffset();
verify(mockConsumer, times(1)).close();
split.setPartitionCommitter(true);
reader.initialize(split, context);
reader.close();
verify(reader, times(1)).commitOffset();
}
@Test
public void testCanCallNext() throws Exception {
doReturn(null).when(reader).getCurrentMessageItr();
assertFalse("Iterator is null, should not be able to call next on it!", reader.canCallNext());
doReturn(mockIterator).when(reader).getCurrentMessageItr();
when(mockIterator.hasNext()).thenReturn(false);
assertFalse("Iterator does not have a next item, should not be able to call next()!", reader.canCallNext());
when(mockIterator.hasNext()).thenReturn(true);
assertTrue("Iterator has elements, should be able to call next().", reader.canCallNext());
}
@Test
public void testCommitOffset() throws Exception {
final ZkUtils mockZk = mock(ZkUtils.class);
doReturn(mockZk).when(reader).getZk();
reader.commitOffset();
verify(mockZk).setLastCommit("group", partition, 0l, true);
}
}
| 41.296029 | 118 | 0.690008 |
7c55e0f027dca7509ade4a4e3346a0e12bb5a8c5 | 4,011 | package android.support.v4.view.accessibility;
import android.view.accessibility.AccessibilityNodeInfo;
class AccessibilityNodeInfoCompatKitKat {
static class CollectionInfo {
CollectionInfo() {
}
static int getColumnCount(Object info) {
return ((android.view.accessibility.AccessibilityNodeInfo.CollectionInfo) info).getColumnCount();
}
static int getRowCount(Object info) {
return ((android.view.accessibility.AccessibilityNodeInfo.CollectionInfo) info).getRowCount();
}
static boolean isHierarchical(Object info) {
return ((android.view.accessibility.AccessibilityNodeInfo.CollectionInfo) info).isHierarchical();
}
}
static class CollectionItemInfo {
CollectionItemInfo() {
}
static int getColumnIndex(Object info) {
return ((android.view.accessibility.AccessibilityNodeInfo.CollectionItemInfo) info).getColumnIndex();
}
static int getColumnSpan(Object info) {
return ((android.view.accessibility.AccessibilityNodeInfo.CollectionItemInfo) info).getColumnSpan();
}
static int getRowIndex(Object info) {
return ((android.view.accessibility.AccessibilityNodeInfo.CollectionItemInfo) info).getRowIndex();
}
static int getRowSpan(Object info) {
return ((android.view.accessibility.AccessibilityNodeInfo.CollectionItemInfo) info).getRowSpan();
}
static boolean isHeading(Object info) {
return ((android.view.accessibility.AccessibilityNodeInfo.CollectionItemInfo) info).isHeading();
}
}
static class RangeInfo {
RangeInfo() {
}
static float getCurrent(Object info) {
return ((android.view.accessibility.AccessibilityNodeInfo.RangeInfo) info).getCurrent();
}
static float getMax(Object info) {
return ((android.view.accessibility.AccessibilityNodeInfo.RangeInfo) info).getMax();
}
static float getMin(Object info) {
return ((android.view.accessibility.AccessibilityNodeInfo.RangeInfo) info).getMin();
}
static int getType(Object info) {
return ((android.view.accessibility.AccessibilityNodeInfo.RangeInfo) info).getType();
}
}
AccessibilityNodeInfoCompatKitKat() {
}
static int getLiveRegion(Object info) {
return ((AccessibilityNodeInfo) info).getLiveRegion();
}
static void setLiveRegion(Object info, int mode) {
((AccessibilityNodeInfo) info).setLiveRegion(mode);
}
static Object getCollectionInfo(Object info) {
return ((AccessibilityNodeInfo) info).getCollectionInfo();
}
static Object getCollectionItemInfo(Object info) {
return ((AccessibilityNodeInfo) info).getCollectionItemInfo();
}
public static void setCollectionInfo(Object info, Object collectionInfo) {
((AccessibilityNodeInfo) info).setCollectionInfo((android.view.accessibility.AccessibilityNodeInfo.CollectionInfo) collectionInfo);
}
public static void setCollectionItemInfo(Object info, Object collectionItemInfo) {
((AccessibilityNodeInfo) info).setCollectionItemInfo((android.view.accessibility.AccessibilityNodeInfo.CollectionItemInfo) collectionItemInfo);
}
static Object getRangeInfo(Object info) {
return ((AccessibilityNodeInfo) info).getRangeInfo();
}
public static Object obtainCollectionInfo(int rowCount, int columnCount, boolean hierarchical, int selectionMode) {
return android.view.accessibility.AccessibilityNodeInfo.CollectionInfo.obtain(rowCount, columnCount, hierarchical);
}
public static Object obtainCollectionItemInfo(int rowIndex, int rowSpan, int columnIndex, int columnSpan, boolean heading) {
return android.view.accessibility.AccessibilityNodeInfo.CollectionItemInfo.obtain(rowIndex, rowSpan, columnIndex, columnSpan, heading);
}
}
| 36.798165 | 151 | 0.701072 |
ba70c1521ebba3e24436c4d285afae92ec2f1f54 | 561 | package com.atlwj.framework;
import java.io.Serializable;
public class Url implements Serializable {
private String hostname;
private Integer port;
public Url(String hostname, Integer port) {
this.hostname = hostname;
this.port = port;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
}
| 18.7 | 47 | 0.625668 |
52e2d67a5d229d5ced20f81f364a0b7cddf88892 | 536 | package org.robobinding.widgetaddon.view;
import org.robobinding.widgetaddon.AbstractListeners;
import android.view.View;
import android.view.View.OnFocusChangeListener;
/**
*
* @since 1.0
* @version $Revision: 1.0 $
* @author Cheng Wei
*/
class OnFocusChangeListeners extends AbstractListeners<OnFocusChangeListener> implements OnFocusChangeListener {
@Override
public void onFocusChange(View view, boolean hasFocus) {
for (OnFocusChangeListener listener : listeners) {
listener.onFocusChange(view, hasFocus);
}
}
}
| 24.363636 | 112 | 0.776119 |
0088931f857d2ffb0ab628e1e86fdb598521bd93 | 1,628 | package test.Theory;
import theory.intervals.RealPred;
import theory.intervals.RealSolver;
import theory.intervals.StdRealPred;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.*;
import utilities.Quadruple;
public class TestRealPred {
RealSolver ba = new RealSolver();
@Test
public void testSat() {
RealPred p = new RealPred(0.0, false, 1.0, true);
assertTrue(ba.IsSatisfiable(p));
assertTrue(p.isSatisfiedBy(0.5));
assertTrue(p.isSatisfiedBy(0.0));
assertFalse(p.isSatisfiedBy(1.0));
RealPred p2 = new RealPred(-1.0);
assertTrue(p2.isSatisfiedBy(-1.0));
}
@Test
public void testBooleanOperators() {
RealPred p1 = StdRealPred.TRUE;
RealPred p2 = new RealPred(0.0, false, 1.0, true);
RealPred p3 = ba.MkNot(p2);
assertTrue(p3.isSatisfiedBy(-1.0));
assertFalse(p3.isSatisfiedBy(0.0));
assertTrue(p3.isSatisfiedBy(1.0));
assertTrue(ba.AreEquivalent(p1, ba.MkOr(p2,p3)));
RealPred p4 = new RealPred(-1.0, false, 0.0, false);
RealPred p5 = new RealPred(0.5, false, null, false);
RealPred p6 = ba.MkAnd(p5, p2);
assertTrue(ba.AreEquivalent(p6, new RealPred(0.5, false, 1.0, true)));
RealPred p7 = ba.MkAnd(p4, p2);
RealPred p8 = new RealPred(0.0);
assertTrue(ba.AreEquivalent(p7, p8));
}
/*
@Test
public void testGetSep() {
ArrayList<List<Double>> data = new ArrayList<List<Double>>(Arrays.asList(Arrays.asList(0.0, 1.0, 3.0), Arrays.asList(0.0, 1.0, 2.0, 3.0)));
ba.GetSeparatingPredicates(data, Long.MAX_VALUE);
}*/
}
| 26.258065 | 141 | 0.703317 |
96b5b729a2862c1c14aff6b93425eb44a9d0e8bf | 3,607 | package io.l0neman.utils.adapter;
import androidx.annotation.NonNull;
import androidx.collection.SparseArrayCompat;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
/**
* Adds additional functionality for {@link HeaderRvAdapter#addFooterView(View)}
* and {@link HeaderRvAdapter#addHeaderView(View)} to recyclerView' adapter.
* <p>Wrapper in a primitive Adapter</p>
* Created by runing on 2016/10/26.
*/
public final class HeaderRvAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int ITEM_VIEW_TYPE_HEADER = Integer.MAX_VALUE;
private static final int ITEM_VIEW_TYPE_FOOTER = Integer.MIN_VALUE;
private SparseArrayCompat<View> mHeaderViews = new SparseArrayCompat<>();
private SparseArrayCompat<View> mFooterViews = new SparseArrayCompat<>();
private RecyclerView.Adapter mAdapter;
public HeaderRvAdapter() { }
public HeaderRvAdapter(RecyclerView.Adapter<? extends RecyclerView.ViewHolder> adapter) {
this.mAdapter = adapter;
}
public void addHeaderView(View headerView) {
mHeaderViews.put(ITEM_VIEW_TYPE_HEADER - getHeaderCount(), headerView);
}
public void addFooterView(View footerView) {
mFooterViews.put(ITEM_VIEW_TYPE_FOOTER + getFooterCount(), footerView);
}
private int getHeaderCount() {
return mHeaderViews.size();
}
private int getFooterCount() {
return mFooterViews.size();
}
@Override
@NonNull
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View headerView = mHeaderViews.get(viewType);
if (headerView != null) {
return createViewHolder(headerView);
}
View footerView = mFooterViews.get(viewType);
if (footerView != null) {
return createViewHolder(footerView);
}
return mAdapter.onCreateViewHolder(parent, viewType);
}
private RecyclerView.ViewHolder createViewHolder(final View view) {
return new RecyclerView.ViewHolder(view) {};
}
@Override
public long getItemId(int position) {
int headerCount = getHeaderCount();
final int adapterPosition = position - headerCount;
if (mAdapter != null && position >= headerCount) {
final int adapterCount = mAdapter.getItemCount();
if (adapterPosition < adapterCount) {
return mAdapter.getItemId(position);
}
}
return -1;
}
@SuppressWarnings("unchecked")
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int headerCount = getHeaderCount();
if (position < headerCount) { return; }
final int adapterPosition = position - headerCount;
if (mAdapter != null) {
final int adapterCount = mAdapter.getItemCount();
if (adapterPosition < adapterCount) {
mAdapter.onBindViewHolder(holder, adapterPosition);
}
}
}
@Override
public int getItemViewType(int position) {
final int headerCount = getHeaderCount();
if (position < headerCount) {
return mHeaderViews.keyAt(position);
}
int adapterCount = 0;
final int adapterPosition = position - headerCount;
if (mAdapter != null) {
adapterCount = mAdapter.getItemCount();
if (adapterPosition < adapterCount) {
return mAdapter.getItemViewType(adapterPosition);
}
}
return mFooterViews.keyAt(adapterPosition - adapterCount);
}
@Override
public int getItemCount() {
if (mAdapter != null) {
return mAdapter.getItemCount() + getHeaderCount() + getFooterCount();
}
return getHeaderCount() + getFooterCount();
}
}
| 28.626984 | 94 | 0.715553 |
ebc4d6e9b899caaccda70b8cede7e66d694a7ded | 402 | //,temp,TestJobHistoryParsing.java,141,149,temp,TestJobHistoryParsing.java,131,139
//,3
public class xxx {
@Test(timeout = 50000)
public void testHistoryParsingWithParseErrors() throws Exception {
LOG.info("STARTING testHistoryParsingWithParseErrors()");
try {
checkHistoryParsing(3, 0, 2);
} finally {
LOG.info("FINISHED testHistoryParsingWithParseErrors()");
}
}
}; | 28.714286 | 82 | 0.71393 |
22ce7ecb06ab94fdac940661d32b712cd1296512 | 7,071 | package cesiumlanguagewritertests;
import agi.foundation.compatibility.*;
import agi.foundation.compatibility.Action;
import agi.foundation.compatibility.ArgumentException;
import agi.foundation.compatibility.AssertHelper;
import agi.foundation.compatibility.CultureInfoHelper;
import agi.foundation.compatibility.DoubleHelper;
import agi.foundation.compatibility.IEquatable;
import agi.foundation.compatibility.TestContextRule;
import agi.foundation.TypeLiteral;
import cesiumlanguagewriter.*;
import javax.annotation.Nonnull;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.runners.MethodSorters;
import org.junit.Test;
/**
* Tests the Bounds class.
*/
@SuppressWarnings( {
"unused",
"deprecation",
"serial"
})
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestBounds {
@Test
public final void testStaticInstances() {
Bounds unbounded = Bounds.getUnbounded();
Assert.assertEquals(Double.NEGATIVE_INFINITY, unbounded.getLowerBound(), 0d);
Assert.assertEquals(Double.POSITIVE_INFINITY, unbounded.getUpperBound(), 0d);
}
@Test
public final void testConstructorsAndChecks() {
Bounds unbounded = new Bounds(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
AssertHelper.assertEquals(Bounds.getUnbounded(), unbounded);
Assert.assertTrue(unbounded.getIsUnbounded());
Assert.assertFalse(unbounded.getIsFinite());
Bounds zero = new Bounds(0.0, 0.0);
Assert.assertEquals(0.0, zero.getLowerBound(), 0d);
Assert.assertEquals(0.0, zero.getUpperBound(), 0d);
Assert.assertFalse(zero.getIsUnbounded());
Assert.assertTrue(zero.getIsFinite());
Bounds finite = new Bounds(-1.0, 1.0);
Assert.assertEquals(-1.0, finite.getLowerBound(), 0d);
Assert.assertEquals(1.0, finite.getUpperBound(), 0d);
Assert.assertFalse(finite.getIsUnbounded());
Assert.assertTrue(finite.getIsFinite());
Bounds upperOnly = new Bounds(Double.NEGATIVE_INFINITY, 1.0);
Assert.assertEquals(Double.NEGATIVE_INFINITY, upperOnly.getLowerBound(), 0d);
Assert.assertEquals(1.0, upperOnly.getUpperBound(), 0d);
Assert.assertFalse(upperOnly.getIsUnbounded());
Assert.assertFalse(upperOnly.getIsFinite());
Bounds lowerOnly = new Bounds(-1.0, Double.POSITIVE_INFINITY);
Assert.assertEquals(-1.0, lowerOnly.getLowerBound(), 0d);
Assert.assertEquals(Double.POSITIVE_INFINITY, lowerOnly.getUpperBound(), 0d);
Assert.assertFalse(lowerOnly.getIsUnbounded());
Assert.assertFalse(lowerOnly.getIsFinite());
}
@Test
public final void testConstructorThrowsWithUpperLessThanLower() {
AssertHelper.<ArgumentException> assertThrows(new TypeLiteral<ArgumentException>() {}, new Action() {
public void invoke() {
Bounds unused = new Bounds(1.0, -1.0);
}
});
}
/**
* Tests that GetHashCode returns something at least reasonably random.
*/
@Test
public final void testGetHashCode() {
Bounds object1 = new Bounds(-1.0, 1.0);
Bounds object2 = new Bounds(-1.0, 1.0);
Bounds object3 = new Bounds(-1.0, 1.1);
Assert.assertEquals((int) object1.hashCode(), (int) object2.hashCode());
AssertHelper.assertNotEqual(object1.hashCode(), object3.hashCode());
}
/**
* Tests the equality and inequality methods and operators.
*/
@Test
public final void testEquality() {
Bounds first = new Bounds(-1.0, 1.0);
Bounds second = new Bounds(-1.0, 1.0);
AssertHelper.assertEquals(first, second);
AssertHelper.assertEquals(second, first);
Assert.assertTrue(Bounds.equals(first, second));
Assert.assertTrue(Bounds.equals(second, first));
Assert.assertFalse(Bounds.notEquals(first, second));
Assert.assertFalse(Bounds.notEquals(second, first));
Assert.assertTrue(first.equalsType(second));
Assert.assertTrue(second.equalsType(first));
second = new Bounds(0.0, 1.0);
AssertHelper.assertNotEqual(first, second);
AssertHelper.assertNotEqual(second, first);
Assert.assertFalse(Bounds.equals(first, second));
Assert.assertFalse(Bounds.equals(second, first));
Assert.assertTrue(Bounds.notEquals(first, second));
Assert.assertTrue(Bounds.notEquals(second, first));
Assert.assertFalse(first.equalsType(second));
Assert.assertFalse(second.equalsType(first));
second = new Bounds(-1.0, 0.0);
AssertHelper.assertNotEqual(first, second);
AssertHelper.assertNotEqual(second, first);
Assert.assertFalse(Bounds.equals(first, second));
Assert.assertFalse(Bounds.equals(second, first));
Assert.assertTrue(Bounds.notEquals(first, second));
Assert.assertTrue(Bounds.notEquals(second, first));
Assert.assertFalse(first.equalsType(second));
Assert.assertFalse(second.equalsType(first));
}
/**
* Tests the {@link Bounds#equalsEpsilon} method.
*/
@Test
public final void testEqualsEpsilon() {
Bounds first = new Bounds(1e-2, 1e-1);
Bounds second = new Bounds(1.1e-2, 1.1e-1);
Assert.assertTrue(second.equalsEpsilon(first, 1e-1));
Assert.assertTrue(second.equalsEpsilon(first, 1e-2));
Assert.assertFalse(second.equalsEpsilon(first, 1e-3));
Assert.assertFalse(second.equalsEpsilon(first, 1e-4));
Assert.assertFalse(second.equalsEpsilon(first, 1e-5));
}
/**
* Tests that the {@link Bounds#equalsEpsilon} method returns true
when the difference is exactly epsilon.
*/
@Test
public final void testEqualsEpsilonExact() {
Bounds first = new Bounds(0.1, 0.1);
Bounds second = new Bounds(0.1, 0.1);
Assert.assertTrue(second.equalsEpsilon(first, 0D));
}
/**
* Tests to ensure the equality fails when comparing incorrect type.
*/
@Test
public final void testEqualityWithWrongType() {
Bounds first = new Bounds(-1.0, 1.0);
Cartesian second = Cartesian.getZero();
// ReSharper disable once SuspiciousTypeConversion.Global
Assert.assertFalse(first.equals(second));
}
/**
* Tests ToString method
*/
@Test
public final void testToString() {
final double val1 = 1.1;
final double val2 = 2.1;
final String sep = ", ";
String result = DoubleHelper.toString(val1, CultureInfoHelper.getCurrentCulture()) + sep + DoubleHelper.toString(val2, CultureInfoHelper.getCurrentCulture());
Bounds test = new Bounds(val1, val2);
Assert.assertEquals(result, test.toString());
}
@Nonnull
private static final TestContextRule rule$testContext = new TestContextRule();
@Nonnull
@Rule
@ClassRule
public static TestContextRule getRule$testContext() {
return rule$testContext;
}
} | 39.066298 | 166 | 0.678405 |
61ebbad0c6eed186a14b251b99d26a54e5846a03 | 2,785 |
package mage.cards.r;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.ContinuousEffectImpl;
import mage.abilities.keyword.FlashbackAbility;
import mage.cards.Card;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.Layer;
import mage.constants.Outcome;
import mage.constants.SubLayer;
import mage.constants.TimingRule;
import mage.filter.FilterCard;
import mage.filter.predicate.mageobject.CardTypePredicate;
import mage.game.Game;
import mage.players.Player;
import mage.target.common.TargetCardInYourGraveyard;
/**
*
* @author cbt33, BetaSteward (PastInFlames)
*/
public final class Recoup extends CardImpl {
private static final FilterCard filter = new FilterCard("sorcery card");
static{
filter.add(new CardTypePredicate(CardType.SORCERY));
}
public Recoup(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.SORCERY},"{1}{R}");
// Target sorcery card in your graveyard gains flashback until end of turn. The flashback cost is equal to its mana cost.
this.getSpellAbility().addEffect(new RecoupEffect());
this.getSpellAbility().addTarget(new TargetCardInYourGraveyard(filter));
// Flashback {3}{R}
this.addAbility(new FlashbackAbility(new ManaCostsImpl("{3}{R}"), TimingRule.SORCERY));
}
public Recoup(final Recoup card) {
super(card);
}
@Override
public Recoup copy() {
return new Recoup(this);
}
}
class RecoupEffect extends ContinuousEffectImpl {
public RecoupEffect() {
super(Duration.EndOfTurn, Layer.AbilityAddingRemovingEffects_6, SubLayer.NA, Outcome.AddAbility);
this.staticText = "Target sorcery card in your graveyard gains flashback until end of turn. The flashback cost is equal to its mana cost";
}
public RecoupEffect(final RecoupEffect effect) {
super(effect);
}
@Override
public RecoupEffect copy() {
return new RecoupEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Player player = game.getPlayer(source.getControllerId());
if (player != null) {
Card card = game.getCard(targetPointer.getFirst(game, source));
if (card != null) {
FlashbackAbility ability = new FlashbackAbility(card.getManaCost(), TimingRule.SORCERY);
ability.setSourceId(card.getId());
ability.setControllerId(card.getOwnerId());
game.getState().addOtherAbility(card, ability);
return true;
}
}
return false;
}
} | 31.292135 | 146 | 0.694434 |
ed5b24483d9b66e61dbd97ed5f6845fa4725f578 | 2,036 | /*
* 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.axis2.rmi.metadata;
import junit.framework.TestCase;
import org.apache.axis2.rmi.metadata.service.BasicService;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestReflection extends TestCase {
public void testInvoke(){
Class basicServiceClass = BasicService.class;
try {
Method method2 = basicServiceClass.getMethod("method2",new Class[]{int.class});
Object basicService = basicServiceClass.newInstance();
method2.invoke(basicService,new Object[]{new Integer(1)});
System.out.println("OK");
Class integerClass = Integer.class;
Constructor constructor = integerClass.getConstructor(new Class[]{String.class});
Object integerObject = constructor.newInstance(new Object[]{"5"});
Object integer = integerClass.newInstance();
} catch (NoSuchMethodException e) {
fail();
} catch (IllegalAccessException e) {
fail();
} catch (InstantiationException e) {
fail();
} catch (InvocationTargetException e) {
fail();
}
}
}
| 35.719298 | 93 | 0.691552 |
c25c66a5866a9b170ef337dd8576a8f320b57643 | 289 | package gov.nih.nci.ncia.criteria;
import java.util.List;
public class ExtendedSearchResultCriteria {
private List <String> seriesIds;
public List<String> getSeriesIds() {
return seriesIds;
}
public void setSeriesIds(List<String> seriesIds) {
this.seriesIds = seriesIds;
}
}
| 18.0625 | 51 | 0.750865 |
7af4b26e5c10d02173e7fd1fb28b233ad7a53276 | 7,008 | /*
* 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.iot.model.v20180120;
import java.util.List;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.iot.transform.v20180120.GetDataAPIServiceDetailResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class GetDataAPIServiceDetailResponse extends AcsResponse {
private String requestId;
private Boolean success;
private String code;
private String errorMessage;
private Data data;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public Boolean getSuccess() {
return this.success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
public String getErrorMessage() {
return this.errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public Data getData() {
return this.data;
}
public void setData(Data data) {
this.data = data;
}
public static class Data {
private String apiSrn;
private Integer status;
private String displayName;
private String apiPath;
private Long createTime;
private Long lastUpdateTime;
private String dateFormat;
private String requestMethod;
private String requestProtocol;
private String description;
private SqlTemplateDTO sqlTemplateDTO;
public String getApiSrn() {
return this.apiSrn;
}
public void setApiSrn(String apiSrn) {
this.apiSrn = apiSrn;
}
public Integer getStatus() {
return this.status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getDisplayName() {
return this.displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getApiPath() {
return this.apiPath;
}
public void setApiPath(String apiPath) {
this.apiPath = apiPath;
}
public Long getCreateTime() {
return this.createTime;
}
public void setCreateTime(Long createTime) {
this.createTime = createTime;
}
public Long getLastUpdateTime() {
return this.lastUpdateTime;
}
public void setLastUpdateTime(Long lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
public String getDateFormat() {
return this.dateFormat;
}
public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
}
public String getRequestMethod() {
return this.requestMethod;
}
public void setRequestMethod(String requestMethod) {
this.requestMethod = requestMethod;
}
public String getRequestProtocol() {
return this.requestProtocol;
}
public void setRequestProtocol(String requestProtocol) {
this.requestProtocol = requestProtocol;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public SqlTemplateDTO getSqlTemplateDTO() {
return this.sqlTemplateDTO;
}
public void setSqlTemplateDTO(SqlTemplateDTO sqlTemplateDTO) {
this.sqlTemplateDTO = sqlTemplateDTO;
}
public static class SqlTemplateDTO {
private String originSql;
private String templateSql;
private List<RequestParamsItem> requestParams;
private List<ResponseParamsItem> responseParams;
public String getOriginSql() {
return this.originSql;
}
public void setOriginSql(String originSql) {
this.originSql = originSql;
}
public String getTemplateSql() {
return this.templateSql;
}
public void setTemplateSql(String templateSql) {
this.templateSql = templateSql;
}
public List<RequestParamsItem> getRequestParams() {
return this.requestParams;
}
public void setRequestParams(List<RequestParamsItem> requestParams) {
this.requestParams = requestParams;
}
public List<ResponseParamsItem> getResponseParams() {
return this.responseParams;
}
public void setResponseParams(List<ResponseParamsItem> responseParams) {
this.responseParams = responseParams;
}
public static class RequestParamsItem {
private String name;
private String type;
private String desc;
private String example;
private Boolean required;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public String getDesc() {
return this.desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getExample() {
return this.example;
}
public void setExample(String example) {
this.example = example;
}
public Boolean getRequired() {
return this.required;
}
public void setRequired(Boolean required) {
this.required = required;
}
}
public static class ResponseParamsItem {
private String name;
private String type;
private String desc;
private String example;
private Boolean required;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public String getDesc() {
return this.desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getExample() {
return this.example;
}
public void setExample(String example) {
this.example = example;
}
public Boolean getRequired() {
return this.required;
}
public void setRequired(Boolean required) {
this.required = required;
}
}
}
}
@Override
public GetDataAPIServiceDetailResponse getInstance(UnmarshallerContext context) {
return GetDataAPIServiceDetailResponseUnmarshaller.unmarshall(this, context);
}
}
| 20.313043 | 88 | 0.670377 |
5bea9932d9a730684ee167a47a93f5e9f65c52af | 2,844 | /*
* Copyright 2021 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.protocol.oidc.grants.ciba.channel;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.keycloak.OAuth2Constants;
import org.keycloak.protocol.oidc.grants.ciba.CibaGrantType;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
*/
public class AuthenticationChannelRequest {
@JsonProperty(CibaGrantType.BINDING_MESSAGE)
private String bindingMessage;
@JsonProperty(CibaGrantType.LOGIN_HINT)
private String loginHint;
@JsonProperty(CibaGrantType.IS_CONSENT_REQUIRED)
private Boolean consentRequired;
@JsonProperty(OAuth2Constants.ACR_VALUES)
private String acrValues;
private Map<String, Object> additionalParameters = new HashMap<>();
private String scope;
public void setBindingMessage(String bindingMessage) {
this.bindingMessage = bindingMessage;
}
public String getBindingMessage() {
return bindingMessage;
}
public void setLoginHint(String loginHint) {
this.loginHint = loginHint;
}
public String getLoginHint() {
return loginHint;
}
public void setConsentRequired(Boolean consentRequired) {
this.consentRequired = consentRequired;
}
public Boolean getConsentRequired() {
return consentRequired;
}
public String getAcrValues() {
return acrValues;
}
public void setAcrValues(String acrValues) {
this.acrValues = acrValues;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getScope() {
return scope;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalParameters() {
return additionalParameters;
}
public void setAdditionalParameters(Map<String, Object> additionalParameters) {
this.additionalParameters = additionalParameters;
}
@JsonAnySetter
public void setAdditionalParameter(String name, String value) {
additionalParameters.put(name, value);
}
}
| 27.346154 | 83 | 0.720113 |
6142b4d2e142f7c57f6022a8cf429c52ab948edc | 29,274 | package com.xunlei.tdlive;
import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.AutoScrollHelper;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.view.animation.OvershootInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import com.tencent.bugly.crashreport.crash.BuglyBroadcastRecevier;
import com.xunlei.tdlive.a.x;
import com.xunlei.tdlive.base.h;
import com.xunlei.tdlive.base.n;
import com.xunlei.tdlive.control.c.a;
import com.xunlei.tdlive.im.AllowChatMessage;
import com.xunlei.tdlive.im.BaseMessage;
import com.xunlei.tdlive.im.ChatMessage;
import com.xunlei.tdlive.im.CloseRoomMessage;
import com.xunlei.tdlive.im.DeniedChatMessage;
import com.xunlei.tdlive.im.GiftMessage;
import com.xunlei.tdlive.im.IMClient;
import com.xunlei.tdlive.im.InRoomMessage;
import com.xunlei.tdlive.im.KickMessage;
import com.xunlei.tdlive.im.LikeMessage;
import com.xunlei.tdlive.im.MessageDispatcher;
import com.xunlei.tdlive.im.MessageDispatcher.ConnectCallback;
import com.xunlei.tdlive.im.MessageDispatcher.OnMessageCallback;
import com.xunlei.tdlive.im.OutRoomMessage;
import com.xunlei.tdlive.im.RoomUserListMessage;
import com.xunlei.tdlive.im.RoomUserNumMessage;
import com.xunlei.tdlive.im.SysNotifyMessage;
import com.xunlei.tdlive.im.VoiceCloseMessage;
import com.xunlei.tdlive.im.VoiceConnectMessage;
import com.xunlei.tdlive.im.VoiceCreplyMessage;
import com.xunlei.tdlive.play.a.c;
import com.xunlei.tdlive.play.view.ChatListView;
import com.xunlei.tdlive.play.view.ConnectMicView;
import com.xunlei.tdlive.play.view.FullScreenLayout;
import com.xunlei.tdlive.play.view.NormalScreenLayout;
import com.xunlei.tdlive.play.view.ah;
import com.xunlei.tdlive.protocol.XLLiveGetGiftListRequest;
import com.xunlei.tdlive.protocol.XLLiveSetPublishStateRequest;
import com.xunlei.tdlive.sdk.XLLiveSDK;
import com.xunlei.tdlive.user.f;
import com.xunlei.tdlive.user.f.b;
import com.xunlei.tdlive.util.XLog;
import com.xunlei.tdlive.util.ac;
import com.xunlei.tdlive.util.d;
import com.xunlei.tdlive.util.e;
import com.xunlei.tdlive.util.q;
import com.xunlei.tdlive.view.AnimationSurfaceView;
import com.xunlei.xiazaibao.sdk.XZBDevice;
import java.util.Date;
@SuppressLint({"ClickableViewAccessibility"})
// compiled from: LivePlayerDialog.java
public class au extends h implements OnClickListener, i$a {
private View A;
private View B;
private View C;
private TextView D;
private int E;
private boolean F;
private final String G;
private final String H;
private int I;
private String J;
private boolean K;
private boolean L;
private boolean M;
private String N;
private boolean O;
private int P;
private int Q;
private boolean R;
private boolean S;
private CloseRoomMessage T;
private a U;
private AnimationSurfaceView V;
private fz W;
private BroadcastReceiver X;
private Handler Y;
private Runnable Z;
public NormalScreenLayout a;
private boolean aa;
private int ab;
private b ac;
private BroadcastReceiver ad;
ConnectCallback b;
OnMessageCallback<LikeMessage> c;
OnMessageCallback<ChatMessage> d;
OnMessageCallback<CloseRoomMessage> e;
OnMessageCallback<InRoomMessage> f;
OnMessageCallback<OutRoomMessage> g;
OnMessageCallback<GiftMessage> h;
OnMessageCallback<RoomUserListMessage> i;
OnMessageCallback<RoomUserNumMessage> j;
OnMessageCallback<DeniedChatMessage> k;
OnMessageCallback<AllowChatMessage> l;
OnMessageCallback<SysNotifyMessage> m;
OnMessageCallback<VoiceConnectMessage> n;
OnMessageCallback<VoiceCreplyMessage> o;
OnMessageCallback<VoiceCloseMessage> p;
private IMClient q;
private MessageDispatcher r;
private x s;
private ChatListView t;
private EditText u;
private InputMethodManager v;
private i w;
private View x;
private TextView y;
private FullScreenLayout z;
static /* synthetic */ int e(au auVar) {
int i = auVar.E;
auVar.E = i + 1;
return i;
}
static /* synthetic */ int r(au auVar) {
int i = auVar.Q + 1;
auVar.Q = i;
return i;
}
public au(Context context, boolean z, String str, String str2) {
super(context, R.style.TransparentDialogStyle);
this.F = false;
this.I = 0;
this.J = null;
this.K = false;
this.L = false;
this.M = false;
this.N = com.umeng.a.d;
this.O = false;
this.P = 0;
this.Q = 0;
this.R = false;
this.S = false;
this.aa = false;
this.ab = -1;
this.ac = new av(this);
this.ad = new bg(this);
this.b = new bi(this);
this.c = new bk(this);
this.d = new bl(this);
this.e = new bm(this);
this.f = new bn(this);
this.g = new bo(this);
this.h = new bp(this);
this.i = new bq(this);
this.j = new br(this);
this.k = new bt(this);
this.l = new bu(this);
this.m = new bv(this);
this.n = new bw(this);
this.o = new bx(this);
this.p = new by(this);
this.Y = new Handler();
this.G = str;
this.H = str2;
this.F = z;
this.I = e.a();
this.J = new StringBuilder("\u70b9\u4eae\u4e86[HEART_").append(String.format("#%X", new Object[]{Integer.valueOf(this.I)})).append("]").toString();
this.v = (InputMethodManager) context.getSystemService("input_method");
MessageDispatcher messageDispatcher = new MessageDispatcher(this.b);
this.r = messageDispatcher;
this.q = IMClient.a(context, messageDispatcher);
this.q.b();
s();
}
public void a(a aVar) {
this.U = aVar;
}
public void a(boolean z) {
this.O = z;
}
public String a() {
return this.N;
}
public boolean b() {
return this.F && this.M;
}
public boolean c() {
return !this.F && this.L;
}
public boolean d() {
return this.x.getVisibility() == 0;
}
public CloseRoomMessage e() {
return this.T;
}
public String f() {
return this.H;
}
public long g() {
return this.a != null ? this.a.getPresenter().c() : 0;
}
public int h() {
return this.P;
}
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.xllive_dialog_player);
a((Dialog) this);
this.A = findViewById(R.id.root);
this.A.setOnClickListener(this);
this.A.setOnTouchListener(new b(this));
findViewById(R.id.close_btn).setOnClickListener(new bs(this));
this.B = findViewById(R.id.movable_layout);
this.D = (TextView) findViewById(R.id.count_down_text);
this.C = findViewById(R.id.count_down_layout);
this.y = (TextView) findViewById(R.id.network_tip);
this.x = findViewById(R.id.network_tip_layout);
this.x.setVisibility(!ac.a() ? 0 : XZBDevice.Wait);
k();
l();
g(false);
o();
n();
if (this.F) {
t();
}
}
private boolean b(boolean z) {
XLog.d("LivePlayerDialog", new StringBuilder("checkIsConnectMic state:").append(this.a.mConnectMicView.getState()).toString());
if (this.a.mConnectMicView.getState() != ConnectMicView.a.c) {
return false;
}
c(z);
return true;
}
private void c(boolean z) {
int i = f.a().b(this.H) ? 1 : 0;
if (z) {
this.a.getPresenter().j().a(i, this.G, new cc(this));
} else {
this.a.getPresenter().j().c(i, this.G);
}
}
public boolean dispatchKeyEvent(KeyEvent keyEvent) {
if (keyEvent.getKeyCode() != 4 || (x() || keyEvent.getAction() != 0)) {
getWindow().clearFlags(XZBDevice.DOWNLOAD_LIST_RECYCLE);
getWindow().setDimAmount(AutoScrollHelper.RELATIVE_UNSPECIFIED);
this.a.showChatInputBar(false);
d(false);
return true;
}
if (!b(true)) {
onBackPressed();
}
return super.dispatchKeyEvent(keyEvent);
}
private void d(boolean z) {
this.V.setChatState(z);
}
public void i() {
if (this.F) {
a(true, true);
}
if (this.w != null && this.w.isShowing()) {
this.w.a();
}
}
public void j() {
if (this.F) {
a(false, false);
}
}
protected void onStart() {
super.onStart();
f.a().a(this.ac);
y();
try {
IntentFilter intentFilter = new IntentFilter("com.xunlei.tdlive.ACTION_SHOW_GIFT_DIALOG");
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
getContext().getApplicationContext().registerReceiver(this.ad, intentFilter);
} catch (Exception e) {
}
if (!this.F && ac.j()) {
this.q.a(InRoomMessage.build(f.a(getContext()).k(), this.G, ac.j() ? anet.channel.strategy.dispatch.a.ANDROID : "android_sdk", ac.g()));
}
this.a.getPresenter().k().a(this.F, this.G);
this.a.getPresenter().k().a();
if (!ac.j()) {
XLLiveSDK.getInstance(getContext()).host().limitSpeed(getContext(), com.xunlei.tdlive.modal.e.t);
}
if (this.F) {
this.Y.postDelayed(new cd(this), BuglyBroadcastRecevier.UPLOADLIMITED);
}
}
protected void onStop() {
super.onStop();
f.a().b(this.ac);
z();
if (this.Z != null) {
this.Y.removeCallbacks(this.Z);
}
try {
getContext().getApplicationContext().unregisterReceiver(this.ad);
} catch (Exception e) {
}
if (!this.F) {
this.q.a(OutRoomMessage.build(f.a(getContext()).k(), this.G, ac.j() ? anet.channel.strategy.dispatch.a.ANDROID : "android_sdk", ac.g()));
}
if (!ac.j()) {
this.q.a(KickMessage.build(f.a().k()));
this.q.c();
}
this.q.a();
this.r.a();
this.s.b();
this.a.getPresenter().k().b();
try {
q.e("user_like").a("likenum", this.P).a("votenum", this.Q).a("follow", q.e("live_room_show").d("is_follow")).a("liketime", q.e("user_like").b("time", 0) - q.e("live_room_show").b("time", 0)).a("time").b(new String[0]);
} catch (Exception e2) {
}
if (!ac.j()) {
XLLiveSDK.getInstance(getContext()).host().limitSpeed(getContext(), -1);
}
}
public void onBackPressed() {
XLog.d("LivePlayerDialog", XLog.getCallerStackTraceElement().toString());
getOwnerActivity().finish();
}
public void onClick(View view) {
boolean z = false;
int id = view.getId();
if (id == R.id.gif_btn) {
a("room", -1, this.a.mPlayButtonLayout.showRedFlagForGiftBtn(false));
} else if (id == R.id.chat_send) {
r();
} else if (id == R.id.chat_btn) {
f.a().a(getOwnerActivity(), "speak", new ce(this));
try {
q.b e = q.e("live_room_show");
q.e("speak_send").a("speak_entry").a("hostid", e.d("hostid")).a("viewernum", e.d("viewernum")).a("follow", e.d("follow")).a("hosttype", e.d("hosttype")).a("speaktime", SystemClock.elapsedRealtime() - e.b("time", 0)).b(new String[0]);
} catch (Exception e2) {
}
} else if (id == R.id.full_screen_btn || id == R.id.publish_full_sreen_btn) {
if (!this.K) {
z = true;
}
e(z);
} else if (id == R.id.laud_btn) {
q();
}
}
public void a(int i, GiftMessage giftMessage) {
if (i == 0) {
if (this.a.mGiftReminderView != null) {
String str = com.umeng.a.d;
String str2 = com.umeng.a.d;
String str3 = com.umeng.a.d;
try {
c.a f = this.a.getPresenter().f();
str = f.a.a;
str2 = f.a.b;
str3 = f.a.c;
} catch (Exception e) {
}
String str4 = null;
if (!(giftMessage.userInfo.level == null || giftMessage.userInfo.level.icon2 == null || giftMessage.userInfo.level.icon2.length() <= 0)) {
str4 = giftMessage.userInfo.level.getIcon2FullPath();
}
String a = c.a(giftMessage.giftInfo.path, giftMessage.giftid);
com.xunlei.tdlive.modal.b.a aVar = new com.xunlei.tdlive.modal.b.a(giftMessage.userInfo.userid, giftMessage.userInfo.nickname, giftMessage.userInfo.avatar, str4, str2, str, str3, giftMessage.giftid, giftMessage.giftInfo.name, giftMessage.giftInfo.content, a, giftMessage.giftInfo.continue_num);
if (!this.V.addSeniorGift(aVar)) {
this.a.mGiftReminderView.addReminding(aVar);
}
String[] b = b("onsendgift");
ChatMessage chatMessage = new ChatMessage();
chatMessage.user.userid = giftMessage.userInfo.userid;
chatMessage.user.nickname = giftMessage.userInfo.nickname;
chatMessage.user.level = giftMessage.userInfo.level;
chatMessage.content = (f.a().b(giftMessage.userInfo.userid) ? "\u6211" : com.umeng.a.d) + "\u9001\u51fa\u4e00\u4e2a[GIFTX_" + a + "]";
chatMessage.flag = 2;
chatMessage.color1 = b[0];
chatMessage.color2 = b[1];
this.s.a(chatMessage);
f(false);
}
this.a.getPresenter().b((long) giftMessage.playerInfo.total_point);
}
}
private static void a(Dialog dialog) {
if (dialog != null) {
LayoutParams attributes = dialog.getWindow().getAttributes();
attributes.x = 0;
attributes.y = 0;
attributes.width = -1;
attributes.height = -1;
dialog.getWindow().setAttributes(attributes);
}
}
private void a(boolean z, boolean z2) {
if (z) {
XLog.e("LivePlayerDialog", new StringBuilder("onResume roomid ").append(this.G).append(", StateRequest.STATE_RESUME").toString());
new XLLiveSetPublishStateRequest(f.a(getContext()).k(), f.a(getContext()).l(), this.G, 1).send(new cf(this, z2));
return;
}
XLog.e("LivePlayerDialog", new StringBuilder("onPause roomid ").append(this.G).append(", StateRequest.STATE_PAUSE").toString());
new XLLiveSetPublishStateRequest(f.a(getContext()).k(), f.a(getContext()).l(), this.G, 3).send(null);
this.Y.removeCallbacksAndMessages(null);
}
private void k() {
this.z = (FullScreenLayout) findViewById(R.id.full_screen_layout);
this.z.mFullScreenButton.setOnClickListener(new ci(this));
this.z.findViewById(R.id.publish_full_sreen_btn).setVisibility(XZBDevice.Wait);
}
private void l() {
this.a = (NormalScreenLayout) findViewById(R.id.normal_screen_layout);
this.V = this.a.mAnimationView;
this.a.setPresenter(new com.xunlei.tdlive.play.a.q(this.a, getOwnerActivity()));
this.a.mSendButton.setOnClickListener(this);
this.a.mPlayButtonLayout.chat_btn.setOnClickListener(this);
this.a.mPlayButtonLayout.full_screen_btn.setOnClickListener(this);
this.a.mPlayButtonLayout.gif_btn.setOnClickListener(this);
this.a.mPlayButtonLayout.laud_btn.setOnClickListener(this);
this.a.mPublishButtonLayout.publish_full_sreen_btn.setOnClickListener(this);
this.a.mPlayButtonLayout.setLaudBitmap(e.a(getContext(), this.I));
this.a.mConnectMicView.setTag(this.F ? com.taobao.accs.internal.b.ELECTION_KEY_HOST : "user");
this.a.getPresenter().a(new cj(this));
this.a.getPresenter().a(f.a(getContext()).k(), f.a(getContext()).l(), this.G, this.F, this.I);
this.a.getPresenter().k().a(new c(this, null));
m();
}
private void m() {
String k = f.a().k();
String l = f.a().l();
SharedPreferences sharedPreferences = XLLiveSDK.getInstance(getContext()).getSharedPreferences();
int date = new Date().getDate();
int i = sharedPreferences.getInt(k + "_red_flag_new", 0);
if (i == 0) {
this.Y.postDelayed(new aw(this), 1500);
} else if (i != date) {
new XLLiveGetGiftListRequest(k, l).send(new ax(this, sharedPreferences));
this.Z = new ay(this);
this.Y.postDelayed(this.Z, 90000);
}
}
private void a(String str) {
if (w()) {
XLog.d("LivePlayerDialog", "dialog is show, show tip 5s later");
this.Y.postDelayed(this.Z, 5000);
return;
}
this.Z = null;
SharedPreferences sharedPreferences = XLLiveSDK.getInstance(getContext()).getSharedPreferences();
String str2 = f.a().k() + "_red_flag_new";
int i = sharedPreferences.getInt(str2, 0);
int date = new Date().getDate();
if (i != date) {
this.a.mPlayButtonLayout.showRedFlagForGiftBtn(true);
this.a.mPlayButtonLayout.showTipOnGiftBtn(str);
q.e("gift_action").a("gift_action_red_show").b(new String[0]);
sharedPreferences.edit().putInt(str2, date).apply();
}
}
private void n() {
this.t = this.a.mMessagesView;
this.t.setVerticalScrollBarEnabled(false);
this.t.setExtraTouchEventHandler(new a(this, null));
this.s = new x(getContext(), 50, this.t);
this.s.a();
this.t.setAdapter(this.s);
this.t.setOnItemClickListener(new az(this));
getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new ba(this));
}
private void o() {
this.u = this.a.mInputMessageView;
this.u.setOnEditorActionListener(new bd(this));
this.u.addTextChangedListener(new be(this));
}
private String p() {
String trim = this.u.getText().toString().trim();
if (TextUtils.isEmpty(trim)) {
this.u.requestFocus();
return null;
}
boolean startsWith = trim.startsWith("debug:");
if (startsWith) {
v();
if (this.W == null) {
this.W = new fz(getContext(), this.G);
this.W.setOwnerActivity(getOwnerActivity());
}
if (!this.W.isShowing()) {
this.W.show();
}
} else {
startsWith = trim.startsWith("log:on");
if (startsWith) {
XLog.enableLog(true);
} else {
startsWith = trim.startsWith("log:off");
if (startsWith) {
XLog.enableLog(false);
}
}
}
this.u.setText(com.umeng.a.d);
return startsWith ? null : trim;
}
private void q() {
String k = f.a(getContext()).k();
if (!this.R) {
this.R = true;
this.q.a(ChatMessage.build(k, this.G, 1, this.J));
}
this.q.a(LikeMessage.build(k, this.G, String.format("#%X", new Object[]{Integer.valueOf(this.I)})));
this.V.addFloatUnit(this.I);
this.P++;
if (q.e("user_like").d("time").length() <= 0) {
q.e("user_like").a("time", SystemClock.elapsedRealtime());
}
}
private void r() {
String p = p();
if (p != null) {
if (this.a.getPresenter().h()) {
n.a(getOwnerActivity(), "\u60a8\u5f53\u524d\u65e0\u6cd5\u53d1\u8a00");
return;
}
this.q.a(ChatMessage.build(f.a(getContext()).k(), this.G, 0, p));
try {
q.e("speak_send").a("speak_send").a("speaktime", SystemClock.elapsedRealtime() - q.e("live_room_show").b("time", 0)).b(new String[0]);
} catch (Exception e) {
}
}
}
private void e(boolean z) {
if ((this.K ^ z) != 0) {
Point a = d.a(getContext());
float translationX = this.B.getTranslationX();
this.B.setTranslationX(AutoScrollHelper.RELATIVE_UNSPECIFIED);
TimeInterpolator overshootInterpolator = new OvershootInterpolator();
if (this.a.getAlpha() == 0.0f) {
this.a.setAlpha(1.0f);
}
if (!this.z.isShown()) {
this.z.setVisibility(0);
}
ObjectAnimator ofFloat;
ObjectAnimator ofFloat2;
if (z) {
ofFloat = ObjectAnimator.ofFloat(this.a, "translationX", new float[]{translationX, (float) a.x});
ofFloat.addListener(new bf(this));
ofFloat.setInterpolator(overshootInterpolator);
ofFloat.setDuration(500).start();
ofFloat2 = ObjectAnimator.ofFloat(this.z, "translationX", new float[]{(float) (-a.x), 0.0f});
ofFloat2.setInterpolator(overshootInterpolator);
ofFloat2.setDuration(500).start();
} else {
ofFloat = ObjectAnimator.ofFloat(this.z, "translationX", new float[]{translationX, (float) (-a.x)});
ofFloat.addListener(new bh(this));
ofFloat.setInterpolator(overshootInterpolator);
ofFloat.setDuration(500).start();
ofFloat2 = ObjectAnimator.ofFloat(this.a, "translationX", new float[]{(float) a.x, 0.0f});
ofFloat2.setInterpolator(overshootInterpolator);
ofFloat2.setDuration(500).start();
}
this.S = true;
}
}
private void s() {
this.r.a(this.c);
this.r.a(this.d);
this.r.a(this.e);
this.r.a(this.f);
this.r.a(this.h);
this.r.a(this.i);
this.r.a(this.j);
this.r.a(this.k);
this.r.a(this.l);
this.r.a(this.m);
this.r.a(this.n);
this.r.a(this.o);
this.r.a(this.p);
}
private void f(boolean z) {
this.s.a(z);
}
private String[] b(String str) {
String[] split;
String str2 = (String) com.xunlei.tdlive.modal.e.o.get(str);
if (str2 != null) {
split = str2.split("=");
} else {
split = null;
}
if (split != null) {
return split;
}
return new String[]{null, null};
}
private <T extends BaseMessage> void a(T t) {
int i;
Exception e;
int i2;
Object obj = null;
try {
Object obj2;
if (t instanceof GiftMessage) {
GiftMessage giftMessage = (GiftMessage) t;
if (f.a().b(giftMessage.userInfo.userid)) {
i = giftMessage.userInfo.level.current;
try {
obj2 = giftMessage.userInfo.nickname;
} catch (Exception e2) {
e = e2;
obj2 = null;
e.printStackTrace();
if (i == -1) {
}
}
try {
obj = giftMessage.userInfo.level.getIconFullPath();
} catch (Exception e3) {
e = e3;
e.printStackTrace();
if (i == -1) {
}
}
if (i == -1 && this.ab >= 0 && i > this.ab && !TextUtils.isEmpty(obj2) && !TextUtils.isEmpty(obj)) {
XLog.d("LivePlayerDialog", new StringBuilder("level upgrade from ").append(this.ab).append(" to ").append(i).toString());
this.ab = i;
try {
this.a.getPresenter().a(obj2, this.a.getPresenter().f().a.a, i, obj);
return;
} catch (Exception e4) {
e4.printStackTrace();
}
}
return;
}
return;
}
String str;
String str2;
if (t instanceof ChatMessage) {
ChatMessage chatMessage = (ChatMessage) t;
if (f.a().b(chatMessage.user.userid)) {
i2 = chatMessage.user.level.current;
try {
str = chatMessage.user.nickname;
} catch (Exception e5) {
e = e5;
i = i2;
obj2 = null;
e.printStackTrace();
if (i == -1) {
}
}
try {
obj = chatMessage.user.level.getIconFullPath();
} catch (Exception e6) {
Exception exception = e6;
i = i2;
str2 = str;
e = exception;
e.printStackTrace();
if (i == -1) {
}
}
}
return;
}
str = null;
i2 = -1;
i = i2;
str2 = str;
if (i == -1) {
}
} catch (Exception e7) {
e = e7;
obj2 = null;
i = -1;
e.printStackTrace();
if (i == -1) {
}
}
}
private void t() {
new com.xunlei.tdlive.control.c().a(this.D, this.C, this.U);
}
private void g(boolean z) {
if (z) {
this.a.setAlpha(AutoScrollHelper.RELATIVE_UNSPECIFIED);
this.z.setVisibility(0);
} else {
this.a.setAlpha(1.0f);
this.z.setVisibility(XZBDevice.Wait);
}
this.K = z;
}
private boolean u() {
if (!x()) {
return false;
}
getWindow().clearFlags(XZBDevice.DOWNLOAD_LIST_RECYCLE);
getWindow().setDimAmount(AutoScrollHelper.RELATIVE_UNSPECIFIED);
this.v.hideSoftInputFromWindow(this.u.getWindowToken(), 0);
this.a.showChatInputBar(false);
d(false);
return true;
}
private void v() {
if (!u() && !this.F) {
q();
}
}
private void a(String str, int i, boolean z) {
if (!this.F) {
if (this.w == null || !this.w.isShowing()) {
this.w = new i(getContext(), this.G, this.H, i, str, z, this);
this.w.setOwnerActivity(getOwnerActivity());
this.w.setOnDismissListener(new bz(this));
this.w.show();
this.a.mPlayButtonLayout.showAnimation(false);
u();
}
}
}
private boolean w() {
return (this.w != null && this.w.isShowing()) || this.aa;
}
private boolean x() {
return this.a.mChatEditLayout.getVisibility() != 8;
}
private void a(ah.a aVar) {
boolean z = true;
try {
if (this.F) {
aVar.l = true;
} else {
if (f.a().b(aVar.f)) {
z = false;
}
aVar.m = z;
}
aVar.q = true;
this.aa = true;
ah ahVar = new ah(getOwnerActivity());
com.xunlei.tdlive.play.view.b.a aVar2 = new com.xunlei.tdlive.play.view.b.a();
aVar2.a(getWindow());
aVar2.a(this.A);
aVar2.a(aVar);
ahVar.a(aVar2);
ahVar.b();
ahVar.a(new ca(this));
} catch (Throwable th) {
}
}
private void y() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.xunlei.tdlive.GIFT_CLICKED");
if (this.X == null) {
this.X = new cb(this);
}
LocalBroadcastManager.getInstance(getContext()).registerReceiver(this.X, intentFilter);
}
private void z() {
if (this.X != null) {
LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(this.X);
this.X = null;
}
}
}
| 35.058683 | 310 | 0.547448 |
dd902e374bedffe2495c940af916acccecbc4dec | 168 | package com.scipionyx.butterflyeffect.api.stocks.model.research;
public enum ChartPeriod {
ONE_DAY, FIVE_DAYS, ONE_MONTH, THREE_MONTHS, ONE_YEAR, FIVE_YEARS, ALL
}
| 21 | 71 | 0.803571 |
3d82cb7fcd8de4d59679e482ff269ed392d81ad0 | 1,108 | package vswe.stevescarts.Modules.Storages.Chests;
import vswe.stevescarts.Helpers.ComponentTypes;
import vswe.stevescarts.Carts.MinecartModular;
import net.minecraft.item.ItemStack;
public class ModuleEggBasket extends ModuleChest {
public ModuleEggBasket(MinecartModular cart) {
super(cart);
}
@Override
protected int getInventoryWidth()
{
return 6;
}
@Override
protected int getInventoryHeight() {
return 4;
}
@Override
protected boolean playChestSound() {
return false;
}
protected float getLidSpeed() {
return (float)(Math.PI / 150);
}
protected float chestFullyOpenAngle() {
return (float)Math.PI / 8F;
}
@Override
public byte getExtraData() {
return (byte)0; //empty, sorry :)
}
@Override
public boolean hasExtraData() {
return true;
}
@Override
public void setExtraData(byte b) {
if (b == 0) {
return; //empty, sorry :)
}
java.util.Random rand = getCart().rand;
int eggs = 1 + rand.nextInt(4) + rand.nextInt(4);
ItemStack easterEgg = ComponentTypes.PAINTED_EASTER_EGG.getItemStack(eggs);
setStack(0, easterEgg);
}
} | 19.438596 | 77 | 0.703069 |
e420afeff5e1057e8711cd9f14bd6eec4c23e048 | 349 | package com.saeyan.controller.action;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface Action {
public void execute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException;
}
| 26.846154 | 78 | 0.839542 |
d799c7a367c93da76ca4b00d0ace6781518f06e8 | 553 | package chapter3.generics;
import java.util.ArrayList;
import java.util.List;
public class UpperBoundedWildcards {
static class Sparrow extends Bird{}
static class Bird{}
public static void main( String... args ){
List<? extends Bird> birds = new ArrayList<Bird>();
// Kompiliert nicht, weil die Liste theoretisch mit Bird typisiert sein könnte.
//birds.add( new Sparrow() );
// Kompiliert nicht, weil die Liste theoretisch mit Sparrow typisiert sein könnte.
//birds.add( new Bird() );
}
} | 25.136364 | 90 | 0.669078 |
b58bdbd9dfe7ddf2eee370023ad83e653ffe5444 | 499 | package graph;
public class User implements Comparable<User>
{
private int id;
private String label;
public User(int id) {
this.id = id;
this.label = String.valueOf(id);
}
public int getID() {
return this.id;
}
public String getLabel() {
return this.label;
}
public void setLabel(String label) {
this.label = label;
}
public int compareTo(User other) {
return Integer.compare(this.id, other.id);
}
public String toString() {
return String.valueOf(id);
}
}
| 14.676471 | 46 | 0.667335 |
45328f9a9ebe4673a55a3dbc81566dba1f51fe40 | 30,373 | // MFP project, FlatGDI.java : Designed and developed by Tony Cui in 2021
package com.cyzapps.GI2DAdapter;
import com.cyzapps.JGI2D.GIEvent;
import com.cyzapps.JGI2D.Display2D;
import com.cyzapps.JGI2D.DisplayLib;
import com.cyzapps.JGI2D.DisplayLib.GraphicDisplayType;
import com.cyzapps.JGI2D.DrawLib.PaintingExtraInfo;
import com.cyzapps.JGI2D.PaintingCallBacks.PaintingCallBack;
import com.cyzapps.JGI2D.PaintingCallBacks.UpdatePaintingCallBack;
import com.cyzapps.Jfcalc.DCHelper;
import com.cyzapps.Jfcalc.DataClass;
import com.cyzapps.Jfcalc.DataClassExtObjRef;
import com.cyzapps.Jfcalc.DataClassNull;
import com.cyzapps.Jfcalc.ErrProcessor;
import com.cyzapps.MultimediaAdapter.ImageDisplay;
import com.cyzapps.MultimediaAdapter.ImageDisplay.SizeChoices;
import com.cyzapps.MultimediaAdapter.ImageMgrJava.ImageWrapper;
import com.cyzapps.VisualMFP.LineStyle;
import com.cyzapps.VisualMFP.PointStyle;
import com.cyzapps.VisualMFP.TextStyle;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingUtilities;
/**
* This class is not thread safe. Ideally, all get and set display attribute functions
* should be called in UI thread. However, to make things easier, I only call set in UI
* threads but get is called in local thread. This will avoid any exception during setting
* but get may not return right value. But considering graphics2D is shared across threads
* , the class is thread unsafe anyway. And because it is mainly to draw game display,
* animation will run quickly, user may not detect it.
* Use invokeAndWait instead of invokeLater because invokeLater may not properly set like
* resizable especially many properties are set in a batch.
* @author tony
*/
public class FlatGDI extends Display2D {
public static final String LOG_TAG = "GI2DAdapter.FlatGDI";
private static AtomicInteger sid = new AtomicInteger();
private int mnId = -1;
public int getId() {
return mnId;
}
public boolean mbHasBeenShutdown = false;
protected SizeChoices msizeChoices = new SizeChoices();
protected ConcurrentLinkedQueue<GIEvent> mqueueGIEvents = new ConcurrentLinkedQueue<>();
protected ConcurrentLinkedQueue<PaintingCallBack> mqueuePaintingCallBacks = new ConcurrentLinkedQueue<>();
protected ImageWrapper mimageBkGrnd = null; // background image.
protected int mBkgrndImgMode = 0; // 0 means actually, 1 means scaled, 2 means tiled
protected int mnBufferedWidth = 0;
protected int mnBufferedHeight = 0;
protected String mstrTitle = "";
protected boolean mbResizable = false;
@Override
public DisplayLib.GraphicDisplayType getDisplayType() {
if (isDisplayOnLive()) {
return GraphicDisplayType.SCREEN_2D_DISPLAY;
} else {
return GraphicDisplayType.INVALID_DISPLAY;
}
}
@Override
public GIEvent pullGIEvent() {
GIEvent event = mqueueGIEvents.poll();
return event;
}
@Override
public void addPaintingCallBack(PaintingCallBack paintingCallBack) {
if (paintingCallBack instanceof UpdatePaintingCallBack) {
// remove obsolete call backs first.
int idx = mqueuePaintingCallBacks.size() - 1;
for (PaintingCallBack callBack : mqueuePaintingCallBacks) {
if (callBack.isCallBackOutDated(paintingCallBack)) {
mqueuePaintingCallBacks.remove(callBack);
}
}
// seems it is much slower.
//mqueuePaintingCallBacks.removeIf(elem -> elem.isCallBackOutDated(paintingCallBack));
}
mqueuePaintingCallBacks.add(paintingCallBack);
mbPCBQueueChangedAfterDraw.set(true); //need to reset buffer because painting call back queue is changed.
}
@Override
public void clearPaintingCallBacks() {
mqueuePaintingCallBacks.clear();
}
// background color
public com.cyzapps.VisualMFP.Color mcolorBkGrnd = new com.cyzapps.VisualMFP.Color();
@Override
public void setBackgroundColor(com.cyzapps.VisualMFP.Color newColor) {
if (getGDIView() != null && !mcolorBkGrnd.isEqual(newColor)) {
mcolorBkGrnd = newColor;
try {
SwingUtilities.invokeAndWait(() -> {
getGDIView().getCanvas().setBackground(new java.awt.Color(
mcolorBkGrnd.mnR,
mcolorBkGrnd.mnG,
mcolorBkGrnd.mnB,
mcolorBkGrnd.mnAlpha)
);
});
// do not call repaint()?
} catch (InterruptedException ex) {
Logger.getLogger(FlatGDI.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(FlatGDI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
@Override
public com.cyzapps.VisualMFP.Color getBackgroundColor() {
return mcolorBkGrnd;
}
@Override
synchronized public void setBackgroundImage(DataClassExtObjRef imgHandler, int mode) {
if (getGDIView() != null) {
try {
if (imgHandler == null) {
mimageBkGrnd = null;
mBkgrndImgMode = mode;
// do not force to repaint.
mbPCBQueueChangedAfterDraw.set(true);
//repaint();
} else if (imgHandler.getExternalObject() instanceof ImageWrapper) {
// only if it is a ImageWrapper.
if ((ImageWrapper)imgHandler.getExternalObject() != mimageBkGrnd
|| mode != mBkgrndImgMode) {
mimageBkGrnd = (ImageWrapper)imgHandler.getExternalObject();
mBkgrndImgMode = mode;
// do not force to repaint.
mbPCBQueueChangedAfterDraw.set(true);
//repaint();
}
}
} catch (ErrProcessor.JFCALCExpErrException ex) {
// will not be here.
Logger.getLogger(ImageDisplay.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
@Override
synchronized public DataClass getBackgroundImage() {
if (mimageBkGrnd == null) {
return new DataClassNull();
} else {
try {
return new DataClassExtObjRef(mimageBkGrnd);
} catch (ErrProcessor.JFCALCExpErrException ex) {
return new DataClassNull(); // will not be here.
}
}
}
@Override
public int getBackgroundImageMode() {
return mBkgrndImgMode;
}
// default foreground color
public com.cyzapps.VisualMFP.Color mcolorForeGrnd = new com.cyzapps.VisualMFP.Color(255, 255, 255);
public boolean mbConfirmClose = false;
@Override
synchronized public void setSnapshotAsBackground(boolean bUpdateScreen, boolean bClearPaintingCallbacks) {
if (mflatGDIView != null) {
// sync mode
DataClass datumImg = getSnapshotImage(bUpdateScreen, 1.0, 1.0);
if (!datumImg.isNull()) {
try {
mimageBkGrnd = (ImageWrapper)(DCHelper.lightCvtOrRetDCExtObjRef(datumImg).getExternalObject());
} catch (ErrProcessor.JFCALCExpErrException ex) {
mimageBkGrnd = null;
Logger.getLogger(FlatGDI.class.getName()).log(Level.SEVERE, null, ex); // will not be here.
}
} else {
mimageBkGrnd = null;
}
if (bClearPaintingCallbacks) {
clearPaintingCallBacks();
}
mbPCBQueueChangedAfterDraw.set(true); // even if we do not clear PCB, still set it to true coz final painting result is different.
// repaint(); // do not force to repaint.
}
}
@Override
public DataClass getSnapshotImage(boolean bUpdateScreen, double wRatio, double hRatio) {
if (mflatGDIView != null) {
try {
int destW = (int) (mflatGDIView.getContentPane().getWidth() * wRatio);
int destH = (int) (mflatGDIView.getContentPane().getHeight() * hRatio);
if (destW < 1) {
destW = 1;
}
if (destH < 1) {
destH = 1;
}
BufferedImage image = new BufferedImage(destW, destH, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
// draw background color.
g.setBackground(new java.awt.Color(
mcolorBkGrnd.mnR,
mcolorBkGrnd.mnG,
mcolorBkGrnd.mnB,
mcolorBkGrnd.mnAlpha));
g.clearRect(0, 0, image.getWidth(), image.getHeight());
if (bUpdateScreen && mbPCBQueueChangedAfterDraw.get()) {
// we need to update screen
update();
repaint();
int loopCnt = 0;
do {
try {
Thread.sleep(20);// wait for UI thread until it is updated.
} catch (InterruptedException ex) {
Logger.getLogger(FlatGDI.class.getName()).log(Level.SEVERE, null, ex);
}
loopCnt ++;
} while(mbPCBQueueChangedAfterDraw.get() && loopCnt < 8);
}
synchronized(this) {
Image imgView = mflatGDIView.getImageBuffer();
if (imgView != null) {
g.drawImage(imgView, 0, 0, destW, destH, 0, 0,
mflatGDIView.getContentPane().getWidth(),
mflatGDIView.getContentPane().getHeight(),
null);
}
}
g.dispose();
return new DataClassExtObjRef(new ImageWrapper(image));
} catch (ErrProcessor.JFCALCExpErrException ex) {
Logger.getLogger(FlatGDI.class.getName()).log(Level.SEVERE, null, ex);
return new DataClassNull();
}
} else {
return new DataClassNull();
}
}
@Override
public void setDisplayConfirmClose(boolean bConfirmClose) {
mbConfirmClose = bConfirmClose;
}
@Override
public boolean getDisplayConfirmClose() {
return mbConfirmClose;
}
public AtomicBoolean mbPCBQueueChangedAfterDraw = new AtomicBoolean(false); // after last drawing painting call back queue is changed.
protected FlatGDIView mflatGDIView = null;
public void setGDIView(FlatGDIView flatGDIView) {
mflatGDIView = flatGDIView;
}
public FlatGDIView getGDIView() {
return mflatGDIView;
}
protected Graphics2D mcurrentGraphics = null;
/**
* This function can only be called in FlatGDI's UI thread, i.e. in Flat GDI View's
* Canvas class. Because in that class paint function which call setCurrentGraphics
* has been synchronized by flatGDI, no need to synchronize it again.
* @param graphics
*/
public void setCurrentGraphics(Graphics2D graphics) {
mcurrentGraphics = graphics;
}
/**
* this function prevent a situation where several statements
* continously run after open_display, where display hasn't been
* initialized.
* @return true or false
*/
@Override
public boolean isDisplayOnLive() {
return mflatGDIView != null // mcurrentGraphics might be null even when display is on live
&& mbHasBeenShutdown == false // hasn't been shutdown.
&& (mnBufferedWidth != 0 || mnBufferedHeight != 0); // a on-live display in JAVA should not be 0*0.
}
@Override
public void setDisplayOrientation(int orientation) {
// do nothing.
}
@Override
public int getDisplayOrientation() {
return -1000; // always return -1000 if in a PC.
}
protected void deprecateFlatGDI() {
mflatGDIView = null;
mcurrentGraphics = null;
clearPaintingCallBacks();
FlatGDIManager.mslistFlatGDI.remove(this); // remove from list to save memory
}
public FlatGDI() {
mnId = sid.getAndIncrement() + 1;
}
/**
* Calculates the best text to fit into the available space.
* @param text
* @param width
* @param graphics
* @return
*/
public static String getFitText(String text, double width, Graphics2D graphics) {
String newText = text;
int length = text.length();
int diff = 0;
FontMetrics metrics = graphics.getFontMetrics();
while (metrics.stringWidth(newText) > width && diff < length) {
diff++;
newText = text.substring(0, length - diff) + "...";
}
if (diff == length) {
newText = "...";
}
return newText;
}
/**
* Calculates How many characters can be placed in the width
* @param width
* @param graphics
* @return
*/
public static int getNumOfCharsInWidth(double width, Graphics2D graphics) {
if (width <= 0) {
return 0; // width cannot be negative.
}
FontMetrics metrics = graphics.getFontMetrics();
double dWWidth = metrics.stringWidth("W");
return (int) (width / dWWidth);
}
@Override
public void setDisplaySize(int width, int height) {
if (getGDIView() != null) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
getGDIView().getContentPane().setPreferredSize(new Dimension(width, height));
getGDIView().pack();
}
});
} catch (InterruptedException ex) {
Logger.getLogger(FlatGDI.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(FlatGDI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
@Override
public int[] getDisplaySize() {
if (getGDIView() != null) {
return new int[] {
mnBufferedWidth = getGDIView().getContentPane().getSize().width,
mnBufferedHeight = getGDIView().getContentPane().getSize().height
};
} else {
return new int[] {mnBufferedWidth, mnBufferedHeight};
}
}
@Override
public void setDisplayCaption(String strCaption) {
mstrTitle = strCaption;
if (getGDIView() != null) {
try {
SwingUtilities.invokeAndWait(()-> getGDIView().setTitle(mstrTitle));
} catch (InterruptedException ex) {
Logger.getLogger(FlatGDI.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(FlatGDI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
@Override
public String getDisplayCaption() {
if (getGDIView() == null) {
return mstrTitle; // havn't been initialized.
} else {
return (mstrTitle = getGDIView().getTitle());
}
}
/**
* calculate rectangular boundary of text. The text shouldn't be rotated.
* @param text : multi-line text
* @param x : x of the starting point of text
* @param y : y of the starting point of text
* @param txtStyle : text font and size
* @return boundary rectangle [x, y, w, h]
*/
@Override
public int[] calcTextBoundary(String text, int x, int y, TextStyle txtStyle) {
// Although this is not a drawing function, still has to use mcurrentGraphics.
// Otherwise, the result may not be accurate. However, a problem is
// mcurrentGraphics may not be initialized (i.e. is null) when display starts,
// so may use a newly created graphics here.
if (mcurrentGraphics == null) {
BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
int[] rect = ImageDisplay.calcTextBoundary(g, text, x, y, txtStyle);
g.dispose();
return rect;
} else {
Graphics2D g = mcurrentGraphics;
int[] rect = ImageDisplay.calcTextBoundary(g, text, x, y, txtStyle);
return rect;
}
}
/**
* calculate origin of text. The text shouldn't be rotated.
* @param text : multi-line text
* @param x : left of boundary rectangle
* @param y : top of boundary rectangle
* @param w : width of boundary rectangle
* @param h : height of boundary rectangle
* @param horAlign : horizontal alignment, -1 means left, 0 means center, 1 means right aligned.
* @param verAlign : vertical alignment, -1 means left, 0 means center, 1 means right aligned.
* @param txtStyle : text font and size
* @return boundary rectangle [x, y, w, h]
*/
@Override
public int[] calcTextOrigin(String text, int x, int y, int w, int h, int horAlign, int verAlign, TextStyle txtStyle) {
// Although this is not a drawing function, still has to use mcurrentGraphics.
// Otherwise, the result may not be accurate. However, a problem is
// mcurrentGraphics may not be initialized (i.e. is null) when display starts,
// so may use a newly created graphics here.
if (mcurrentGraphics == null) {
BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
int[] origin = ImageDisplay.calcTextOrigin(g, text, x, y, w, h, horAlign, verAlign, txtStyle);
g.dispose();
return origin;
} else {
Graphics2D g = mcurrentGraphics;
int[] origin = ImageDisplay.calcTextOrigin(g, text, x, y, w, h, horAlign, verAlign, txtStyle);
return origin;
}
}
/**
* Draw a multiple lines text. x is the starting point of first character
* and y is the pivot point
* @param text
* @param x
* @param y
* @param txtStyle
* @param dRotateRadian
* @param pei
*/
@Override
public void drawText(String text, double x, double y, TextStyle txtStyle, double dRotateRadian, PaintingExtraInfo pei) {
if (mcurrentGraphics == null) {
return; // if flat GDI hasn't been fully initialized, return.
}
ImageDisplay.drawText(mcurrentGraphics, text, x, y, txtStyle, dRotateRadian, pei);
}
@Override
public void drawPoint(double x, double y, PointStyle pointStyle, PaintingExtraInfo pei) {
if (mcurrentGraphics == null) {
return; // if flat GDI hasn't been fully initialized, return.
}
ImageDisplay.drawPoint(mcurrentGraphics, msizeChoices, x, y, pointStyle, pei);
}
@Override
public void drawLine(double x0, double y0, double x1, double y1, LineStyle lineStyle, PaintingExtraInfo pei) {
if (mcurrentGraphics == null) {
return; // if flat GDI hasn't been fully initialized, return.
}
ImageDisplay.drawLine(mcurrentGraphics, msizeChoices, x0, y0, x1, y1, lineStyle, pei);
}
/**
* draw a polygon.
* @param points : vetex of the points.
* @param color : color to fill or frame.
* @param drawMode : this is an integer parameter, if it is zero or negative, the polygon is filled,
* otherwise, the polygon is framed and the drawMode value is the border's with ( the border is always
* solid line).
* @param pei
*/
@Override
public void drawPolygon(LinkedList<double[]> points,
com.cyzapps.VisualMFP.Color color, int drawMode, PaintingExtraInfo pei) {
if (mcurrentGraphics == null) {
return; // if flat GDI hasn't been fully initialized, return.
}
ImageDisplay.drawPolygon(mcurrentGraphics, points, color, drawMode, pei);
}
/**
*
* @param x
* @param y
* @param width
* @param height
* @param color
* @param drawMode : this is an integer parameter, if it is zero or negative, the rectangle is filled,
* otherwise, the rectangle is framed and the drawMode value is the border's with ( the border is always
* solid line).
* @param pei
*/
@Override
public void drawRect(double x, double y, double width, double height,
com.cyzapps.VisualMFP.Color color, int drawMode, PaintingExtraInfo pei) {
if (mcurrentGraphics == null) {
return; // if flat GDI hasn't been fully initialized, return.
}
ImageDisplay.drawRect(mcurrentGraphics, x, y, width, height, color, drawMode, pei);
}
/**
*
* @param x
* @param y
* @param width
* @param height
*/
@Override
public void clearRect(double x, double y, double width, double height) {
if (mcurrentGraphics == null) {
return; // if flat GDI hasn't been fully initialized, return.
}
ImageDisplay.clearRect(mcurrentGraphics, x, y, width, height);
}
/**
*
* @param x
* @param y
* @param width
* @param height
* @param color
* @param drawMode : this is an integer parameter, if it is zero or negative, the oval is filled,
* otherwise, the oval is framed and the drawMode value is the border's with ( the border is always
* solid line).
* @param pei
*/
@Override
public void drawOval(double x, double y, double width, double height,
com.cyzapps.VisualMFP.Color color, int drawMode, PaintingExtraInfo pei) {
if (mcurrentGraphics == null) {
return; // if flat GDI hasn't been fully initialized, return.
}
ImageDisplay.drawOval(mcurrentGraphics, x, y, width, height, color, drawMode, pei);
}
/**
*
* @param x
* @param y
* @param width
* @param height
*/
@Override
public void clearOval(double x, double y, double width, double height) {
if (mcurrentGraphics == null) {
return; // if flat GDI hasn't been fully initialized, return.
}
ImageDisplay.clearOval(mcurrentGraphics, x, y, width, height);
}
/**
* return false if loading image fails.
* @param imgHandle
* @param left
* @param top
* @param widthRatio
* @param heightRatio
* @param pei
* @return
*/
@Override
public boolean drawImage(DataClass imgHandle, double left, double top, double widthRatio, double heightRatio, PaintingExtraInfo pei) {
if (mcurrentGraphics == null) {
return false; // if flat GDI hasn't been fully initialized, return.
}
return ImageDisplay.drawImage(mcurrentGraphics, imgHandle, left, top, widthRatio, heightRatio, pei);
}
/**
* return false if loading image fails.
* @param imgHandle
* @param srcX1
* @param srcY1
* @param srcX2
* @param srcY2
* @param dstX1
* @param dstY1
* @param dstX2
* @param dstY2
* @param pei
* @return
*/
@Override
public boolean drawImage(DataClass imgHandle,
double srcX1, double srcY1, double srcX2, double srcY2,
double dstX1, double dstY1, double dstX2, double dstY2,
PaintingExtraInfo pei) {
if (mcurrentGraphics == null) {
return false; // if flat GDI hasn't been fully initialized, return.
}
return ImageDisplay.drawImage(mcurrentGraphics, imgHandle, srcX1, srcY1, srcX2, srcY2,
dstX1, dstY1, dstX2, dstY2, pei);
}
@Override
public void repaint() {
if (getGDIView() != null && mbPCBQueueChangedAfterDraw.get()) {
getGDIView().getCanvas().validate();
getGDIView().getCanvas().repaint();
}
}
@Override
public void setDisplayResizable(boolean bResizable) {
mbResizable = bResizable;
if (getGDIView() != null) {
try {
SwingUtilities.invokeAndWait(() -> {
getGDIView().setResizable(mbResizable);
});
} catch (InterruptedException ex) {
Logger.getLogger(FlatGDI.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(FlatGDI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
@Override
public boolean getDisplayResizable() {
if (getGDIView() != null) {
return (mbResizable = getGDIView().isResizable());
} else {
return mbResizable;
}
}
/**
* This function can only be called in FlatGDI's UI thread (i.e. in Flat GDI View's
* Canvas class). Because in Flat GDI View's canvas class, paint function has been
* synchronized by flatGDI, no need to make it synchronized again.
* @param x
* @param y
* @param width
* @param height
*/
public void draw(double x, double y, double width, double height) {
if (getGDIView() != null) {
if (mimageBkGrnd != null) {
// draw background image
ImageDisplay.drawBackgroundImage(mcurrentGraphics,
getGDIView().getContentPane().getWidth(), getGDIView().getContentPane().getHeight(),
mimageBkGrnd, mBkgrndImgMode);
}
// no need to remove all obsolete painting call backs because these call backs
// have been removed when updatepainting call back is added.
double right = x + width;
double bottom = y + height;
boolean bWholeDisplayInRange = (x == 0) && (y == 0)
&& (width == getGDIView().getContentPane().getWidth()) // no need to worry about getGDIView() is null.
&& (height == getGDIView().getContentPane().getHeight());
mqueuePaintingCallBacks.stream().filter((pcb) -> (this.equals(pcb.getDisplay2D())))
.filter((pcb) -> (bWholeDisplayInRange || pcb.isInPaintingRange(x, y, right, bottom)))
.forEachOrdered((pcb) -> {
pcb.call(); // draw all the painting call backs.
}); // the same Display2D
mbPCBQueueChangedAfterDraw.set(false); //no need to reset buffer until painting call back queue is changed.
}
}
@Override
public void update() {
// TODO: this function updates some underlying logic (for example, if FLatGDI
// is for a game, this function updates some game logic), it has nothing to do
// with graphics (UI).
}
@Override
public void initialize() {
GIEvent gIEvent = new GIEvent();
gIEvent.menumEventType = GIEvent.EVENTTYPE.GDI_INITIALIZE;
mqueueGIEvents.add(gIEvent);
}
@Override
public void close() {
deprecateFlatGDI();
GIEvent gIEvent = new GIEvent();
gIEvent.menumEventType = GIEvent.EVENTTYPE.GDI_CLOSE;
mqueueGIEvents.add(gIEvent);
}
public void resize(double dWidth, double dHeight, double dOldWidth, double dOldHeight) {
mnBufferedWidth = (int)dWidth;
mnBufferedHeight = (int)dHeight;
if (dWidth != dOldWidth || dHeight != dOldHeight) {
update();
}
}
@Override
public int addRtcVideoOutput(int left, int top, int width, int height, boolean enableSlide) {
return -1; // RTC Video is not supported by ImageDisplay
}
@Override
public boolean startLocalStream(int videoOutputId) {
return false; // RTC Video is not supported by ImageDisplay
}
@Override
public void stopLocalStream() {
}
@Override
public boolean startVideoCapturer() {
return false;
}
@Override
public void stopVideoCapturer() {
}
@Override
public boolean setVideoTrackEnable(int idx, boolean enable) {
return false;
}
@Override
public boolean getVideoTrackEnable(int idx) {
return false;
}
@Override
public boolean setAudioTrackEnable(int idx, boolean enable) {
return false;
}
@Override
public boolean getAudioTrackEnable(int idx) {
return false;
}
@Override
public int[] getRtcVideoOutputLeftTop(int id) {
return new int[0]; // RTC Video is not supported by ImageDisplay
}
@Override
public int getRtcVideoOutputCount() {
return 0; // RTC Video is not supported by ImageDisplay
}
@Override
public boolean linkVideoStream(String peerId, int trackId, int videoOutputId) {
return false; // RTC Video is not supported by ImageDisplay
}
@Override
public boolean unlinkVideoStream(String peerId, int trackId) {
return false; // RTC Video is not supported by ImageDisplay
}
@Override
public int unlinkVideoStream(int videoOutputId) {
return 0; // RTC Video is not supported by ImageDisplay
}
}
| 36.905225 | 142 | 0.595167 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.