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
be2044e5327e0866004f58a46e7299cd7e362dd3
377
package com.graduation.project.IQInterviewKids; import java.io.Serializable; /** * Created by Mohamed AbdelraZek on 6/17/2017. */ public class ResultBundle implements Serializable { public String Name; public String EmailAddress; public String Type; public int ActualResult; public int MaxScore; public String Date; public String State; }
16.391304
51
0.724138
80e07d8ce2cc927e8cc34d69a4aac29e95d318fd
14,845
package com.yc.bookmark.ui; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.view.Window; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.yc.bookmark.R; import com.yc.bookmarklibrary.BookmarkDataUtils; import com.yc.bookmarklibrary.bean.ChildrenBean; import com.yc.bookmarklibrary.bean.MyBookMarkNoSelectListBean; import com.yc.yclibrary.YcLogUtils; import com.yc.yclibrary.YcSPUtils; import com.yc.yclibrary.YcStringUtils; import com.yc.yclibrary.YcToastUtils; import java.util.ArrayList; import java.util.List; public class MyBookmarkAddOrEditeActivity extends Activity implements TextWatcher, View.OnClickListener { private EditText mTitleEditText; private EditText mUrlEditText; private TextView mTvAppTitleRight; private TextView mTvAppTitle; private TextView mFolderTextView; private LinearLayout mFolderSelectPanel; private String mBookmarkTitle; private String mBookmarkUrl; private String mParentId = ""; private String mType; private MyBookMarkNoSelectListBean mEditeMyBookMarkNoSelectListBean; //编辑书签的bean类 private BookmarkDataUtils mBookmarkDataUtils; private int mUpdataId; private boolean mBackCleanUpBookMark; //是否移动文件夹位置 boolean isMove = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //设置无标题 requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_my_bookmark_add_or_edite); initView(); initData(); } private void initView() { mTitleEditText = (EditText) findViewById(R.id.title_text); mUrlEditText = (EditText) findViewById(R.id.url_text); ImageView iv_tv_app_title_back = (ImageView) findViewById(R.id.iv_tv_app_title_back); iv_tv_app_title_back.setOnClickListener(this); mTvAppTitle = (TextView) findViewById(R.id.tv_app_title); mTvAppTitleRight = (TextView) findViewById(R.id.tv_app_title_right); mTvAppTitleRight.setOnClickListener(this); mFolderTextView = (TextView) findViewById(R.id.folder_text);//位置面板中的文本 mFolderSelectPanel = (LinearLayout) findViewById(R.id.folder_select_panel);//位置的整个布局 } private void initData() { mBookmarkDataUtils = BookmarkDataUtils.getInstance(this); mEditeMyBookMarkNoSelectListBean = (MyBookMarkNoSelectListBean) getIntent().getSerializableExtra("MyBookMarkListBean"); mBookmarkTitle = mEditeMyBookMarkNoSelectListBean.getName(); mBookmarkUrl = mEditeMyBookMarkNoSelectListBean.getUrl(); mFolderTextView.setText(mEditeMyBookMarkNoSelectListBean.getParentFolderName()); mParentId = mEditeMyBookMarkNoSelectListBean.getParentId(); String parentName = mEditeMyBookMarkNoSelectListBean.getParentFolderName(); mType = getIntent().getStringExtra("type"); mBackCleanUpBookMark = getIntent().getBooleanExtra("backCleanUpBookMark", false); if ("网络异常".equals(mBookmarkTitle) || "出错了!".equals(mBookmarkTitle)) mBookmarkTitle = mBookmarkUrl; if ("addBookMark".equals(mType)) { mTvAppTitle.setText("添加书签"); //获取书签列表数据(为了保证同步) , 需要区分网络和本地书签 (暂时只作本地) String add_bookmark = YcSPUtils.getInstance("MyBookmark").getString("bookmark"); mBookmarkDataUtils.setBookmark(add_bookmark); } else if ("editeBookMark".equals(mType)) { mTvAppTitle.setText("编辑书签"); mUpdataId = getIntent().getIntExtra("updataId", -1); mEditeMyBookMarkNoSelectListBean = (MyBookMarkNoSelectListBean) getIntent().getSerializableExtra("MyBookMarkListBean"); mBookmarkTitle = mEditeMyBookMarkNoSelectListBean.getName(); mBookmarkUrl = mEditeMyBookMarkNoSelectListBean.getUrl(); } mFolderTextView.setText(YcStringUtils.isEmpty(parentName) ? "书签" : parentName); mFolderTextView.setOnClickListener(this); mTvAppTitleRight.setText("保存"); mTvAppTitleRight.setVisibility(View.VISIBLE); mTitleEditText.setText(mBookmarkTitle); if (mBookmarkTitle != null) { mTitleEditText.setSelection(mBookmarkTitle.length()); } mUrlEditText.setText(mBookmarkUrl); mTitleEditText.requestFocus(); mTitleEditText.addTextChangedListener(this); mUrlEditText.addTextChangedListener(this); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { updateSaveButton(); } private void updateSaveButton() { boolean enable = !mTitleEditText.getText().toString().isEmpty() && !mUrlEditText.getText().toString().isEmpty(); if (enable) { mTvAppTitleRight.setTextColor(getResources().getColor(R.color.blue_12aaff)); } else { mTvAppTitleRight.setTextColor(getResources().getColor(R.color.colorAccent)); } mTvAppTitleRight.setEnabled(enable); } @Override public void onClick(View v) { int id = v.getId(); if (v == mFolderTextView) {//新建文件夹中的位置文本 Intent mIntent = new Intent(this, MyBookMarkTreeViewActivity.class); startActivityForResult(mIntent, 100); } else if (id == R.id.tv_app_title_right) { final String title = mTitleEditText.getText().toString().trim(); if (title.length() > 115) { YcToastUtils.normal(this, "长度不能超过115个字符").show(); return; } String url = null; // if (mIsAddToNtp || (!mIsAddToNtp && mCurrentAddToType == ADD_TO_NTP)) { // url_tmp = UrlUtilities.fixupUrl(mUrlEditText.getTrimmedText()); // } else { url = mUrlEditText.getText().toString().trim(); // } if (url == null || url.isEmpty()) { YcToastUtils.normal(this, "请输入正确的网址").show(); return; } //判断是添加书签还是编辑书签 if ("addBookMark".equals(mType)) { //添加书签 ChildrenBean childrenBean = new ChildrenBean(); childrenBean.setDate_added(System.currentTimeMillis() + ""); childrenBean.setName(title); childrenBean.setUrl(url); //添加文件夹 childrenBean.setType("url"); List<ChildrenBean> newAddFolderList = new ArrayList<>(); childrenBean.setChildren(newAddFolderList); //添加书签 String add_bookmark = mBookmarkDataUtils.addBookMark(mParentId, childrenBean); if ("添加失败".equals(add_bookmark)) { YcToastUtils.normal(this, "添加失败").show(); return; } //保存书签 , 需要区分网络和本地书签 (暂时只作本地) YcSPUtils.getInstance("MyBookmark").put("bookmark", add_bookmark); YcLogUtils.eTag("tag", add_bookmark); YcToastUtils.normal(this, "添加成功").show(); setResult(RESULT_OK); finish(); } else if ("editeBookMark".equals(mType)) { //编辑书签 if (mEditeMyBookMarkNoSelectListBean != null) { String editeBookmark = ""; if (isMove) { //先移除旧数据, 再添加新数据 String removeBookMark = mBookmarkDataUtils.removeBookMark(mUpdataId, mEditeMyBookMarkNoSelectListBean); if ("移除失败".equals(removeBookMark)) { YcToastUtils.normal(this, "编辑失败").show(); return; } ChildrenBean childrenBean = new ChildrenBean(); childrenBean.setDate_added(mEditeMyBookMarkNoSelectListBean.getDate_added()); childrenBean.setName(title); childrenBean.setUrl(url); //添加文件夹 childrenBean.setType(mEditeMyBookMarkNoSelectListBean.getType()); childrenBean.setChildren(mEditeMyBookMarkNoSelectListBean.getChildren()); //添加文件夹 editeBookmark = mBookmarkDataUtils.addBookMark(mParentId, childrenBean); if ("添加失败".equals(editeBookmark)) { YcToastUtils.normal(this, "编辑失败").show(); return; } } else { //重新设置数据 mEditeMyBookMarkNoSelectListBean.setName(title); mEditeMyBookMarkNoSelectListBean.setUrl(url); // basePresenter.editeBookMark(mEditeMyBookMarkListBean); //编辑文件夹 editeBookmark = mBookmarkDataUtils.editeBookMark(mUpdataId, mEditeMyBookMarkNoSelectListBean); if ("编辑失败".equals(editeBookmark)) { YcToastUtils.normal(this, "编辑失败").show(); return; } } YcSPUtils.getInstance("MyBookmark").put("bookmark", editeBookmark); YcLogUtils.eTag("tag", editeBookmark); YcToastUtils.normal(this, "编辑成功").show(); setResult(RESULT_OK); finish(); } } // if (!mIsAddToNtp) { // if (mCurrentAddToType == ADD_TO_BOOKMARK) { // if (mModel.getBookmarkNodeDepth(mParentId.getId()) > 31) { // ToastUtils.show(YywBookmarkAddActivity.this, "超过最大书签允许层数", ToastUtils.Style.TOAST_FAILED); // return true; // } // // boolean overwrite = false; // if (mModel.checkURLExistInParent(mParentId.getId(), url)) { // final CustomAlertDialog alertDialog = new CustomAlertDialog.Builder(this). // setMessage("已存在相同书签,是否覆盖?"). // setPositiveButton("覆盖", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // // TODO Auto-generated method stub // dialog.dismiss(); // if (mModel.addBookmark(mParentId, mModel.getChildCount(mParentId), title, url, true) != null) { // ToastUtils.show(YywBookmarkAddActivity.this, "添加成功", ToastUtils.Style.TOAST_SUCCESS); // //Toast.makeText(YywBookmarkAddActivity.this, "添加成功", Toast.LENGTH_SHORT).show(); // } // finish(); // } // }). // setNegativeButton("取消", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // // TODO Auto-generated method stub // dialog.dismiss(); // finish(); // } // }).create(); // alertDialog.show(); // return true; // } // // if (mModel.addBookmark(mParentId, mModel.getChildCount(mParentId), title, url, overwrite) != null) { // ToastUtils.show(this, "添加成功", ToastUtils.Style.TOAST_SUCCESS); // //Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show(); // } // finish(); // } else if (mCurrentAddToType == ADD_TO_NTP) { // //should_finish = NewtabManager.getInstance().addItemManul(title, url,this); // } else if (mCurrentAddToType == ADD_TO_DESKTOP) { // //Utils2.addShortcut(this, Intent.ShortcutIconResource.fromContext(this, R.mipmap.book_default_mark), title, Uri.parse(url)); // addShortCut(url, title); // } else { // assert (false); // } // } else {//手动输入--添加首页 // // should_finish = NewtabManager.getInstance().addItemManul(title, url,this); // } // if (item == mDeleteButton) { // // Log added for detecting delete button double clicking. // Log.i(TAG, "Delete button pressed by user! isFinishing() == " + isFinishing()); // mModel.deleteBookmark(mBookmarkId); // finish(); // return true; /// } } else if (id == R.id.iv_tv_app_title_back) { finish(); } } @Override protected void onDestroy() { super.onDestroy(); if ("addBookMark".equals(mType) && mBackCleanUpBookMark) //添加书签 mBookmarkDataUtils.clearData(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (data != null) { if (requestCode == 100 && resultCode == RESULT_OK) { isMove = true; mParentId = data.getStringExtra("ParentId"); mFolderTextView.setText(data.getStringExtra("Name")); } } } }
46.102484
159
0.542674
457a0691eeaceaf50d268716cfc6547c9ce99ab3
3,473
package com.centurylink.mdw.model.asset; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.HashMap; import java.util.Map; /** * Maps known asset extension to mime type. */ public class ContentTypes { public static final String DEFAULT = "application/octet-stream"; static final Map<String,String> contentTypes; static { contentTypes = new HashMap<>(); contentTypes.put("spring", "text/xml"); contentTypes.put("camel", "text/xml"); contentTypes.put("css", "text/css"); contentTypes.put("csv", "application/CSV"); contentTypes.put("xls", "application/vnd.ms-excel"); contentTypes.put("xlsx", "application/vnd.ms-excel"); contentTypes.put("docx", "application/vnd.ms-word"); contentTypes.put("pagelet", "application/json"); contentTypes.put("html", "text/html"); contentTypes.put("gif", "image/gif"); contentTypes.put("jpg", "image/jpeg"); contentTypes.put("png", "image/png"); contentTypes.put("svg", "image/svg+xml"); contentTypes.put("js", "application/javascript"); contentTypes.put("jsx", "application/javascript"); contentTypes.put("json", "application/json"); contentTypes.put("wsdl", "text/xml"); contentTypes.put("xml", "text/xml"); contentTypes.put("xsd", "text/xml"); contentTypes.put("xsl", "text/xml"); contentTypes.put("yaml", "text/yaml"); contentTypes.put("yml", "text/yaml"); contentTypes.put("md", "text/markdown"); } public static String getContentType(String extension) { if (extension == null) return DEFAULT; String contentType = contentTypes.get(extension); if (contentType == null) { if (isBinary(extension)) { contentType = DEFAULT; } else { contentType = "text/plain"; } } return contentType; } public static String getContentType(File file) throws IOException { int lastDot = file.getName().lastIndexOf('.'); if (lastDot > 0 && lastDot < file.getName().length() - 2) { String ext = file.getName().substring(lastDot + 1); return getContentType(ext); } String contentType = Files.probeContentType(file.toPath()); return contentType == null ? DEFAULT : contentType; } public static boolean isBinary(String extension) { return extension.equals("gif") || extension.equals("jpg") || extension.equals("png") || extension.equals("xls") || extension.equals("xlsx") || extension.equals("docx") || extension.equals("jar") || extension.equals("class") || extension.equals("zip") || extension.equals("eot") || extension.equals("ttf") || extension.equals("woff") || extension.equals("woff2"); } public static boolean isImage(String extension) { return extension.equals("gif") || extension.equals("jpg") || extension.equals("png") || extension.equals("svg"); } public static boolean isExcludedFromMemoryCache(String extension) { return "jar".equals(extension); // jar files not loaded into memory } }
36.177083
75
0.576735
e442840d35f3a1a5c2d485f6e79bd04c3f79be84
600
package com.boohee.model.mine; import com.boohee.utils.DateHelper; import java.io.Serializable; public class BaseRecord implements Serializable { private static final long serialVersionUID = 3429400890940214781L; public int id; public String record_on; public int getYear() { return DateHelper.getYear(DateHelper.parseString(this.record_on)); } public int getMonth() { return DateHelper.getMonth(DateHelper.parseString(this.record_on)); } public int getDay() { return DateHelper.getDay(DateHelper.parseString(this.record_on)); } }
25
75
0.718333
b89a27e808e688d48a77f03327ebbc8f891e185d
1,793
/* * 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 com.alipay.test.acts.yaml.enums; import org.apache.commons.lang.StringUtils; /** * CP type enum * * @author baishuo.lp * @version $Id: CPTypeEnum.java, v 0.1 2015年8月12日 上午11:26:13 baishuo.lp Exp $ */ public enum CPUnitTypeEnum { OBJECT("OBJECT"), DATABASE("DATABASE"), GROUP("GROUP"), MESSAGE("MESSAGE"); private String code; private CPUnitTypeEnum(String code) { this.code = code; } /** * get CPTypeEnum based on code * * @param code * @return CPTypeEnum */ public CPUnitTypeEnum getByCode(String code) { for (CPUnitTypeEnum cPTypeEnum : CPUnitTypeEnum.values()) { if (StringUtils.equals(cPTypeEnum.getCode(), code)) { return cPTypeEnum; } } return null; } /** * Getter method for property <tt>code</tt>. * * @return property value of code */ public String getCode() { return code; } }
26.367647
78
0.658115
2cd3e16ebff536de0f8b3a587097d21d1288c751
75
package net.marcoreis.dataimport.hbase; public class HBaseBulkImport { }
12.5
39
0.8
21a225fa414f65679caac0744e72a50b8af07762
7,359
package org.apache.commons.lang3; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class LocaleUtils { private static final ConcurrentMap<String, List<Locale>> cCountriesByLanguage = new ConcurrentHashMap(); private static final ConcurrentMap<String, List<Locale>> cLanguagesByCountry = new ConcurrentHashMap(); static class SyncAvoid { /* access modifiers changed from: private */ public static final List<Locale> AVAILABLE_LOCALE_LIST; /* access modifiers changed from: private */ public static final Set<Locale> AVAILABLE_LOCALE_SET; static { ArrayList arrayList = new ArrayList(Arrays.asList(Locale.getAvailableLocales())); AVAILABLE_LOCALE_LIST = Collections.unmodifiableList(arrayList); AVAILABLE_LOCALE_SET = Collections.unmodifiableSet(new HashSet(arrayList)); } SyncAvoid() { } } public static List<Locale> availableLocaleList() { return SyncAvoid.AVAILABLE_LOCALE_LIST; } public static Set<Locale> availableLocaleSet() { return SyncAvoid.AVAILABLE_LOCALE_SET; } public static List<Locale> countriesByLanguage(String str) { if (str == null) { return Collections.emptyList(); } List<Locale> list = (List) cCountriesByLanguage.get(str); if (list != null) { return list; } ArrayList arrayList = new ArrayList(); List<Locale> availableLocaleList = availableLocaleList(); int i = 0; while (true) { int i2 = i; if (i2 < availableLocaleList.size()) { Locale locale = availableLocaleList.get(i2); if (str.equals(locale.getLanguage()) && locale.getCountry().length() != 0 && locale.getVariant().isEmpty()) { arrayList.add(locale); } i = i2 + 1; } else { cCountriesByLanguage.putIfAbsent(str, Collections.unmodifiableList(arrayList)); return (List) cCountriesByLanguage.get(str); } } } public static boolean isAvailableLocale(Locale locale) { return availableLocaleList().contains(locale); } public static List<Locale> languagesByCountry(String str) { if (str == null) { return Collections.emptyList(); } List<Locale> list = (List) cLanguagesByCountry.get(str); if (list != null) { return list; } ArrayList arrayList = new ArrayList(); List<Locale> availableLocaleList = availableLocaleList(); int i = 0; while (true) { int i2 = i; if (i2 < availableLocaleList.size()) { Locale locale = availableLocaleList.get(i2); if (str.equals(locale.getCountry()) && locale.getVariant().isEmpty()) { arrayList.add(locale); } i = i2 + 1; } else { cLanguagesByCountry.putIfAbsent(str, Collections.unmodifiableList(arrayList)); return (List) cLanguagesByCountry.get(str); } } } public static List<Locale> localeLookupList(Locale locale) { return localeLookupList(locale, locale); } public static List<Locale> localeLookupList(Locale locale, Locale locale2) { ArrayList arrayList = new ArrayList(4); if (locale != null) { arrayList.add(locale); if (locale.getVariant().length() > 0) { arrayList.add(new Locale(locale.getLanguage(), locale.getCountry())); } if (locale.getCountry().length() > 0) { arrayList.add(new Locale(locale.getLanguage(), "")); } if (!arrayList.contains(locale2)) { arrayList.add(locale2); } } return Collections.unmodifiableList(arrayList); } public static Locale toLocale(String str) { if (str == null) { return null; } if (str.isEmpty()) { return new Locale("", ""); } if (str.contains("#")) { throw new IllegalArgumentException("Invalid locale format: " + str); } int length = str.length(); if (length < 2) { throw new IllegalArgumentException("Invalid locale format: " + str); } char charAt = str.charAt(0); if (charAt != '_') { char charAt2 = str.charAt(1); if (!Character.isLowerCase(charAt) || !Character.isLowerCase(charAt2)) { throw new IllegalArgumentException("Invalid locale format: " + str); } else if (length == 2) { return new Locale(str); } else { if (length < 5) { throw new IllegalArgumentException("Invalid locale format: " + str); } else if (str.charAt(2) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } else { char charAt3 = str.charAt(3); if (charAt3 == '_') { return new Locale(str.substring(0, 2), "", str.substring(4)); } char charAt4 = str.charAt(4); if (!Character.isUpperCase(charAt3) || !Character.isUpperCase(charAt4)) { throw new IllegalArgumentException("Invalid locale format: " + str); } else if (length == 5) { return new Locale(str.substring(0, 2), str.substring(3, 5)); } else { if (length < 7) { throw new IllegalArgumentException("Invalid locale format: " + str); } else if (str.charAt(5) == '_') { return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6)); } else { throw new IllegalArgumentException("Invalid locale format: " + str); } } } } } else if (length < 3) { throw new IllegalArgumentException("Invalid locale format: " + str); } else { char charAt5 = str.charAt(1); char charAt6 = str.charAt(2); if (!Character.isUpperCase(charAt5) || !Character.isUpperCase(charAt6)) { throw new IllegalArgumentException("Invalid locale format: " + str); } else if (length == 3) { return new Locale("", str.substring(1, 3)); } else { if (length < 5) { throw new IllegalArgumentException("Invalid locale format: " + str); } else if (str.charAt(3) == '_') { return new Locale("", str.substring(1, 3), str.substring(4)); } else { throw new IllegalArgumentException("Invalid locale format: " + str); } } } } }
39.564516
125
0.540291
896ac88b42ac238f5608a90c4cad89189fea96c4
1,232
package com.heaven7.java.reflecty.gson; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.lang.reflect.Type; public class ReflectyTypeAdapterFactory implements TypeAdapterFactory { private final GsonATM atm; private final float version; public ReflectyTypeAdapterFactory(GsonATM atm, float version) { this.atm = atm; this.version = version; } @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> tt) { Type type = tt.getType(); com.heaven7.java.reflecty.iota.TypeAdapter<JsonWriter, JsonReader> ta; if(type instanceof Class){ Class<?> clazz = (Class<?>) type; if(atm.getReflectyContext().isCollection(clazz) || atm.getReflectyContext().isMap(clazz)){ return null; } ta = atm.createObjectTypeAdapter(clazz, version); }else { ta = com.heaven7.java.reflecty.iota.TypeAdapter.ofType(type, atm, version); } return new ReflectyAdapter2Adapter<T>(ta); } }
33.297297
102
0.676948
2752c5734a330340f8287d8b7247007f84161810
2,112
package com.omertron.imdbapi.model; import com.fasterxml.jackson.annotation.JsonProperty; public class ImdbUserComment extends AbstractJsonMapping { @JsonProperty("user_score") private int userScore = -1; @JsonProperty("summary") private String summary = ""; @JsonProperty("user_location") private String userLocation = ""; @JsonProperty("text") private String text = ""; @JsonProperty("date") private String date = ""; @JsonProperty("status") private String status = ""; @JsonProperty("user_score_count") private int userScoreCount = -1; @JsonProperty("user_name") private String userName = ""; @JsonProperty("user_rating") private int userRating = -1; public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getUserLocation() { return userLocation; } public void setUserLocation(String userLocation) { this.userLocation = userLocation; } public int getUserScore() { return userScore; } public void setUserScore(int userScore) { this.userScore = userScore; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getUserRating() { return userRating; } public void setUserRating(int userRating) { this.userRating = userRating; } public int getUserScoreCount() { return userScoreCount; } public void setUserScoreCount(int userScoreCount) { this.userScoreCount = userScoreCount; } }
21.333333
58
0.626894
48a6a4ebe7b60789207a08c93ee2bbb4d0e7b871
676
package fi.aalto.cs.apluscourses.intellij.notifications; import static org.hamcrest.Matchers.containsString; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class IoErrorNotificationTest { @Test public void testIoErrorNotification() { IOException exception = new IOException("hello there"); IoErrorNotification notification = new IoErrorNotification(exception); Assert.assertEquals("The notification has the correct group ID", "A+", notification.getGroupId()); Assert.assertThat("The exception message is in the notification content", notification.getContent(), containsString("hello there")); } }
30.727273
77
0.761834
3947816946099c58989b335b3c6c846f403f62ad
2,199
package com.martinwong.dormcleaner; import android.content.Intent; import android.database.Cursor; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; /** * Created by Martin Wong on 2016-05-15. */ public class viewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ private Intent detailSegue; private RecyclerView recyclerView; private TextView emptyView; private CardView cv; private TextView title; private ImageView icon; private ImageButton deleteTask; viewHolder(View itemView) { super(itemView); recyclerView = (RecyclerView) itemView.findViewById(R.id.recyclerview); emptyView = (TextView) itemView.findViewById(R.id.empty_view); cv = (CardView) itemView.findViewById(R.id.cardView); title = (TextView) itemView.findViewById(R.id.title); icon = (ImageView) itemView.findViewById(R.id.taskIcon); deleteTask = (ImageButton) itemView.findViewById(R.id.deleteTask); title.setOnClickListener(this); icon.setOnClickListener(this); itemView.setOnClickListener(this); // deleteTask.setOnClickListener(this); } public void bindData(final Cursor cursor){ if(cursor!= null){ cursor.moveToFirst(); final String name = cursor.getString(cursor.getColumnIndex("TaskTitle")); final int iconId = cursor.getInt(cursor.getColumnIndex("TaskImage")); // recyclerView.setVisibility(View.VISIBLE); // emptyView.setVisibility(View.GONE); title.setText(name); icon.setImageResource(iconId); } // else{ // recyclerView.setVisibility(View.GONE); // emptyView.setVisibility(View.VISIBLE); // } } @Override public void onClick(View v) { detailSegue = new Intent(v.getContext(), Task_Detail_Activity.class); detailSegue.putExtra("Title", title.getText().toString()); v.getContext().startActivity(detailSegue); } }
34.904762
88
0.681219
bdab748fbada9bf676f07bf6eec3d46a2b530214
4,393
package com.toxsickproductions.skyland.scenes3d.generators; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.collision.*; import com.badlogic.gdx.physics.bullet.dynamics.btRigidBody; import com.toxsickproductions.data.Assets; import com.toxsickproductions.g3d.bullet.BulletConstructor; import com.toxsickproductions.g3d.bullet.BulletEntity; import com.toxsickproductions.g3d.bullet.BulletWorld; import com.toxsickproductions.skyland.scenes3d.entities.Tree; import com.toxsickproductions.skyland.scenes3d.util.BulletUserData; import reference.Models; /** * Created by Freek on 8/01/2015. */ public class TreeGenerator { public static void initWorld(BulletWorld world) { //TreeShape Model model = Assets.get(Models.MODEL_TREE_PROTOTYPE, Model.class); model.nodes.first().translation.set(0, -1.15f, 0); btCompoundShape treeShape = new btCompoundShape(); treeShape.addChildShape(new Matrix4(new Vector3(0, 0, 0), new Quaternion(), new Vector3(1, 1, 1)), new btBoxShape(new Vector3(.2f, .9f, .2f))); treeShape.addChildShape(new Matrix4(new Vector3(0, 1, 0), new Quaternion(), new Vector3(1, 1, 1)), new btSphereShape(1)); //LogShape model = Assets.get(Models.MODEL_LOG_PROTOTYPE, Model.class); model.nodes.first().translation.set(0, -1.15f, 0); world.addConstructor("log", new BulletConstructor(Assets.get(Models.MODEL_LOG_PROTOTYPE, Model.class), 75, new btBoxShape(new Vector3(.2f, .9f, .2f)))); world.addConstructor("stump", new BulletConstructor(Assets.get(Models.MODEL_STUMP_PROTOTYPE, Model.class), 0, new btCylinderShape(new Vector3(.2f, .22f, .2f)))); world.addConstructor("staticTree", new BulletConstructor(Assets.get(Models.MODEL_TREE_PROTOTYPE, Model.class), 0, treeShape)); world.addConstructor("dynamicTree", new BulletConstructor(Assets.get(Models.MODEL_TREE_PROTOTYPE, Model.class), 100, treeShape)); } public static Tree spawnStaticTree(BulletWorld world, Vector3 position) { BulletEntity stump = world.add("stump", position.x, position.y, position.z); stump.body.setCollisionFlags(stump.body.getCollisionFlags() | btCollisionObject.CollisionFlags.CF_KINEMATIC_OBJECT); stump.body.setActivationState(Collision.DISABLE_DEACTIVATION); BulletEntity staticTree = world.add("staticTree", position.x, position.y + 1.15f, position.z); staticTree.body.setCollisionFlags(staticTree.body.getCollisionFlags() | btCollisionObject.CollisionFlags.CF_KINEMATIC_OBJECT); staticTree.body.setActivationState(Collision.DISABLE_DEACTIVATION); //radius stump.radius = .5f; staticTree.radius = 1.5f; //userdata stump.body.userData = new BulletUserData("stump", stump); staticTree.body.userData = new BulletUserData("staticTree", staticTree); //random rotation int random = MathUtils.random(0, 360); stump.transform.rotate(0, 1, 0, random); staticTree.transform.rotate(0, 1, 0, random); return new Tree(stump, staticTree); } public static void spawnDynamicTree(BulletWorld world, Matrix4 worldTransform) { BulletEntity dynamicTree = world.add("dynamicTree", 0, 0, 0); dynamicTree.radius = 1.5f; dynamicTree.body.userData = new BulletUserData("dynamicTree", dynamicTree); dynamicTree.body.setWorldTransform(worldTransform); ((btRigidBody) dynamicTree.body).applyImpulse(new Vector3(MathUtils.random(50, 60) * (MathUtils.random(0, 1) > 0 ? 1 : -1), 0, MathUtils.random(50, 60) * (MathUtils.random(0, 1) > 0 ? 1 : -1)), new Vector3(0, 1, 0)); } public static BulletEntity spawnLog(BulletWorld world, Matrix4 worldTransform) { BulletEntity log = world.add("log", 0, 0, 0); log.radius = 1; log.body.userData = new BulletUserData("log", log); log.body.setWorldTransform(worldTransform); ((btRigidBody) log.body).applyImpulse(new Vector3(MathUtils.random(50, 60) * (MathUtils.random(0, 1) > 0 ? 1 : -1), 0, MathUtils.random(50, 60) * (MathUtils.random(0, 1) > 0 ? 1 : -1)), new Vector3(0, 1, 0)); return log; } }
51.682353
224
0.706806
2d1e833ecd10888cda36e4cd58d1b186fea29325
3,248
package tech.simter.embeddeddatabase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.util.FileCopyUtils; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import static org.springframework.boot.jdbc.DataSourceInitializationMode.NEVER; /** * @author RJ */ @Configuration("simterEmbeddedDatabaseConfiguration") @ComponentScan @EnableConfigurationProperties(DataSourceProperties.class) public class EmbeddedDatabaseConfiguration { private final static Logger logger = LoggerFactory.getLogger(EmbeddedDatabaseConfiguration.class); private final boolean concatSqlScript; @Autowired public EmbeddedDatabaseConfiguration(@Value("${spring.datasource.concat-sql-script:false}") boolean concatSqlScript) { this.concatSqlScript = concatSqlScript; } @Bean("simterConcatSqlScript") public String concatSqlScript(DataSourceProperties properties) throws IOException { if (!concatSqlScript || properties.getInitializationMode() == null || properties.getInitializationMode() == NEVER) return ""; ResourceLoader resourcePatternResolver = new PathMatchingResourcePatternResolver(); // concat schema and data List<String> sqlResources = new ArrayList<>(); if (properties.getSchema() != null) sqlResources.addAll(properties.getSchema()); if (properties.getData() != null) sqlResources.addAll(properties.getData()); if (sqlResources.isEmpty()) return ""; StringBuffer sql = new StringBuffer(); for (int i = 0; i < sqlResources.size(); i++) { String resourcePath = sqlResources.get(i); logger.info("Load script from {}", resourcePath); sql.append("-- copy from ").append(resourcePath).append("\r\n\r\n") .append(loadSql(resourcePath, resourcePatternResolver)); if (i < sqlResources.size() - 1) sql.append("\r\n\r\n"); } // save concatenate sql content to file String sqlStr = sql.toString(); File sqlFile = new File("target/" + properties.getPlatform() + ".sql"); logger.info("Save concatenate SQL script to {}", sqlFile.getAbsolutePath()); FileCopyUtils.copy(sqlStr.getBytes(StandardCharsets.UTF_8), sqlFile); return sqlStr; } private String loadSql(String resourcePath, ResourceLoader resourcePatternResolver) { try { return FileCopyUtils.copyToString(new InputStreamReader( resourcePatternResolver.getResource(resourcePath).getInputStream(), StandardCharsets.UTF_8 )); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } }
41.641026
120
0.766318
d90c6d68d1b3c5a07109af27f3a2155825de980f
1,331
package ru.justagod.justacore.gui.overlay.common; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; import ru.justagod.justacore.gui.overlay.ScaledOverlay; /** * Created by JustAGod on 15.10.17. */ public class TextOverlay extends ScaledOverlay { protected String text = ""; public TextOverlay(int x, int y) { super(x, y); } public TextOverlay(int x, int y, String text) { super(x, y); this.text = text; } public TextOverlay localize() { text = I18n.format(text); return this; } public String getText() { return text; } public void setText(String text) { this.text = text; } @Override protected void doDraw(double xPos, double yPos, double width, double height, float partialTick, int mouseX, int mouseY, boolean mouseInBounds) { } @Override protected void doDrawText(double xPos, double yPos, double width, double height, float partialTick, int mouseX, int mouseY, boolean mouseInBounds) { drawString(text, (int)xPos, (int)yPos, false); } @Override public double getScaledWidth() { return Minecraft.getMinecraft().fontRenderer.getStringWidth(text); } @Override public double getScaledHeight() { return 8; } }
23.350877
152
0.654395
dc5001286d4ed2508043d1e81b2f089b733b84f3
2,675
/*********************************************************************************************************************** * Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu) * * 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 eu.stratosphere.nephele.execution.librarycache; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import eu.stratosphere.core.io.IOReadableWritable; import eu.stratosphere.core.io.StringRecord; /** * A library cache profile request includes a set of library names and issues a task manager to report which of these * libraries * are currently available in its local cache. * */ public class LibraryCacheProfileRequest implements IOReadableWritable { /** * List of the required libraries' names. */ private String[] requiredLibraries; /** * Returns the names of libraries whose cache status is to be retrieved. * * @return the names of libraries whose cache status is to be retrieved */ public String[] getRequiredLibraries() { return requiredLibraries; } /** * Sets the names of libraries whose cache status is to be retrieved. * * @param requiredLibraries * the names of libraries whose cache status is to be retrieved */ public void setRequiredLibraries(final String[] requiredLibraries) { this.requiredLibraries = requiredLibraries; } @Override public void read(final DataInput in) throws IOException { // Read required jar files this.requiredLibraries = new String[in.readInt()]; for (int i = 0; i < this.requiredLibraries.length; i++) { this.requiredLibraries[i] = StringRecord.readString(in); } } @Override public void write(final DataOutput out) throws IOException { if (this.requiredLibraries == null) { throw new IOException("requiredLibraries is null"); } // Number of required jar files out.writeInt(this.requiredLibraries.length); for (int i = 0; i < this.requiredLibraries.length; i++) { StringRecord.writeString(out, this.requiredLibraries[i]); } } }
32.228916
120
0.672523
8bf8bacc6705c49ad138d73a69a8fda5e3dd070f
2,577
/* * Copyright 2020 OPPO ESA Stack Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package esa.restlight.server.bootstrap; import esa.commons.annotation.Internal; import esa.httpserver.core.AsyncRequest; import esa.httpserver.core.AsyncResponse; import esa.restlight.server.route.Route; import esa.restlight.server.schedule.RequestTask; import java.util.List; import java.util.concurrent.CompletableFuture; /** * DispatcherHandler * <p> * A full processing of a quest is spited into 2 phase: * <p> * 1. find {@link Route} and handle not found. 2. process {@link Route}. */ @Internal public interface DispatcherHandler { /** * Get all handler method invokers. * * @return handlerMethodInvokers */ List<Route> routes(); /** * this is the first phase of request processing which should find a {@link Route} for current request and handle * the not found event if there's no {@link Route} found in current context. * * @param request request * @param response response * @return route */ Route route(AsyncRequest request, AsyncResponse response); /** * process for request * * @param request request * @param response response * @param promise promise * @param route route */ void service(AsyncRequest request, AsyncResponse response, CompletableFuture<Void> promise, Route route); /** * Handle the biz task rejected. * * @param task task * @param reason error message */ void handleRejectedWork(RequestTask task, String reason); /** * Handle the biz task unfinished. this event will fired when server is about stopping. * * @param unfinishedWorkList tasks */ void handleUnfinishedWorks(List<RequestTask> unfinishedWorkList); /** * shutdown event */ default void shutdown() { } /** * biz thread pool reject counts * * @return long */ long rejectCount(); }
26.56701
117
0.664338
296f2ba6b49ce44255b1d205337afc5b3c43ab9d
734
package uk.co.reallysmall.cordova.plugin.firebase.crashlytics; import com.google.firebase.crashlytics.FirebaseCrashlytics; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.json.JSONArray; import org.apache.cordova.PluginResult; public class InitialiseHandler implements ActionHandler { @Override public boolean handle(JSONArray args, CordovaInterface cordova, final CallbackContext callbackContext) { boolean result = false; if (FirebaseCrashlytics.getInstance().didCrashOnPreviousExecution()) { result = true; } callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result)); return true; } }
29.36
108
0.757493
dceb215fe60aa206f95a1cd05290495385148ae6
9,246
/* * This file was automatically generated by EvoSuite * Mon Jun 01 13:44:49 GMT 2020 */ package com.capitalone.dashboard.model; import org.junit.Test; import static org.junit.Assert.*; import com.capitalone.dashboard.model.TestCase; import com.capitalone.dashboard.model.TestCaseStatus; import com.capitalone.dashboard.model.TestSuite; import com.capitalone.dashboard.model.TestSuiteType; import java.util.Collection; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true) public class TestSuite_ESTest extends TestSuite_ESTest_scaffolding { @Test(timeout = 4000) public void test00() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setUnknownStatusCount(2); int int0 = testSuite0.getUnknownStatusCount(); assertEquals(2, int0); } @Test(timeout = 4000) public void test01() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setUnknownStatusCount((-1479)); int int0 = testSuite0.getUnknownStatusCount(); assertEquals((-1479), int0); } @Test(timeout = 4000) public void test02() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setTotalTestCaseCount(1); int int0 = testSuite0.getTotalTestCaseCount(); assertEquals(1, int0); } @Test(timeout = 4000) public void test03() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setTotalTestCaseCount((-1479)); int int0 = testSuite0.getTotalTestCaseCount(); assertEquals((-1479), int0); } @Test(timeout = 4000) public void test04() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setTestCases((Collection<TestCase>) null); Collection<TestCase> collection0 = testSuite0.getTestCases(); assertNull(collection0); } @Test(timeout = 4000) public void test05() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setSuccessTestCaseCount(493); int int0 = testSuite0.getSuccessTestCaseCount(); assertEquals(493, int0); } @Test(timeout = 4000) public void test06() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setSuccessTestCaseCount((-762)); int int0 = testSuite0.getSuccessTestCaseCount(); assertEquals((-762), int0); } @Test(timeout = 4000) public void test07() throws Throwable { TestSuite testSuite0 = new TestSuite(); TestCaseStatus testCaseStatus0 = TestCaseStatus.Success; testSuite0.setStatus(testCaseStatus0); TestCaseStatus testCaseStatus1 = testSuite0.getStatus(); assertEquals(TestCaseStatus.Success, testCaseStatus1); } @Test(timeout = 4000) public void test08() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setStartTime(415L); long long0 = testSuite0.getStartTime(); assertEquals(415L, long0); } @Test(timeout = 4000) public void test09() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setStartTime((-1L)); long long0 = testSuite0.getStartTime(); assertEquals((-1L), long0); } @Test(timeout = 4000) public void test10() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setSkippedTestCaseCount(1); int int0 = testSuite0.getSkippedTestCaseCount(); assertEquals(1, int0); } @Test(timeout = 4000) public void test11() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setSkippedTestCaseCount((-2341)); int int0 = testSuite0.getSkippedTestCaseCount(); assertEquals((-2341), int0); } @Test(timeout = 4000) public void test12() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setId("`:Wb;"); String string0 = testSuite0.getId(); assertEquals("`:Wb;", string0); } @Test(timeout = 4000) public void test13() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setId(""); String string0 = testSuite0.getId(); assertEquals("", string0); } @Test(timeout = 4000) public void test14() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setFailedTestCaseCount((-1)); int int0 = testSuite0.getFailedTestCaseCount(); assertEquals((-1), int0); } @Test(timeout = 4000) public void test15() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setEndTime(1579L); long long0 = testSuite0.getEndTime(); assertEquals(1579L, long0); } @Test(timeout = 4000) public void test16() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setEndTime((-1L)); long long0 = testSuite0.getEndTime(); assertEquals((-1L), long0); } @Test(timeout = 4000) public void test17() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setDuration(1); long long0 = testSuite0.getDuration(); assertEquals(1L, long0); } @Test(timeout = 4000) public void test18() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setDuration((-1068L)); long long0 = testSuite0.getDuration(); assertEquals((-1068L), long0); } @Test(timeout = 4000) public void test19() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setDescription("com.capitalone.dashboard.model.TestSuite"); String string0 = testSuite0.getDescription(); assertEquals("com.capitalone.dashboard.model.TestSuite", string0); } @Test(timeout = 4000) public void test20() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setDescription(""); String string0 = testSuite0.getDescription(); assertEquals("", string0); } @Test(timeout = 4000) public void test21() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.getType(); } @Test(timeout = 4000) public void test22() throws Throwable { TestSuite testSuite0 = new TestSuite(); int int0 = testSuite0.getFailedTestCaseCount(); assertEquals(0, int0); } @Test(timeout = 4000) public void test23() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.getStatus(); } @Test(timeout = 4000) public void test24() throws Throwable { TestSuite testSuite0 = new TestSuite(); Collection<TestCase> collection0 = testSuite0.getTestCases(); testSuite0.setTestCases(collection0); assertNull(testSuite0.getType()); } @Test(timeout = 4000) public void test25() throws Throwable { TestSuite testSuite0 = new TestSuite(); String string0 = testSuite0.getId(); assertNull(string0); } @Test(timeout = 4000) public void test26() throws Throwable { TestSuite testSuite0 = new TestSuite(); long long0 = testSuite0.getEndTime(); assertEquals(0L, long0); } @Test(timeout = 4000) public void test27() throws Throwable { TestSuite testSuite0 = new TestSuite(); int int0 = testSuite0.getSuccessTestCaseCount(); assertEquals(0, int0); } @Test(timeout = 4000) public void test28() throws Throwable { TestSuite testSuite0 = new TestSuite(); long long0 = testSuite0.getDuration(); assertEquals(0L, long0); } @Test(timeout = 4000) public void test29() throws Throwable { TestSuite testSuite0 = new TestSuite(); int int0 = testSuite0.getUnknownStatusCount(); assertEquals(0, int0); } @Test(timeout = 4000) public void test30() throws Throwable { TestSuite testSuite0 = new TestSuite(); int int0 = testSuite0.getTotalTestCaseCount(); assertEquals(0, int0); } @Test(timeout = 4000) public void test31() throws Throwable { TestSuite testSuite0 = new TestSuite(); int int0 = testSuite0.getSkippedTestCaseCount(); assertEquals(0, int0); } @Test(timeout = 4000) public void test32() throws Throwable { TestSuite testSuite0 = new TestSuite(); testSuite0.setFailedTestCaseCount(1); int int0 = testSuite0.getFailedTestCaseCount(); assertEquals(1, int0); } @Test(timeout = 4000) public void test33() throws Throwable { TestSuite testSuite0 = new TestSuite(); long long0 = testSuite0.getStartTime(); assertEquals(0L, long0); } @Test(timeout = 4000) public void test34() throws Throwable { TestSuite testSuite0 = new TestSuite(); String string0 = testSuite0.getDescription(); assertNull(string0); } @Test(timeout = 4000) public void test35() throws Throwable { TestSuite testSuite0 = new TestSuite(); TestSuiteType testSuiteType0 = TestSuiteType.Unit; testSuite0.setType(testSuiteType0); TestSuiteType testSuiteType1 = testSuite0.getType(); assertEquals(TestSuiteType.Unit, testSuiteType1); } }
31.026846
176
0.678347
531793e91203867980a110e15795a68e606dd7f8
3,180
/* ************************************************************************ # # designCraft.io # # http://designcraft.io/ # # Copyright: # Copyright 2014 eTimeline, LLC. All rights reserved. # # License: # See the license.txt file in the project's top-level directory for details. # # Authors: # * Andy White # ************************************************************************ */ package dcraft.ctp.stream; import dcraft.ctp.f.FileDescriptor; import dcraft.script.StackEntry; import dcraft.util.FileUtil; import dcraft.util.StringUtil; import dcraft.xml.XElement; import io.netty.buffer.ByteBuf; public class SplitStream extends TransformStream { protected int seqnum = 1; protected int size = 10 * 1024 * 1024; protected String template = "file-%seq%.bin"; protected int currchunk = 0; public SplitStream withSize(int v) { this.size = v; return this; } // include a %seq% to be replaced, like this file-%seq%.bin public SplitStream withNameTemplate(String v) { this.template = v; return this; } public SplitStream() { } @Override public void init(StackEntry stack, XElement el) { this.seqnum = (int) stack.intFromElement(el, "StartAt", this.seqnum); String size = stack.stringFromElement(el, "Size", "10MB"); this.size = (int) FileUtil.parseFileSize(size); String temp = stack.stringFromElement(el, "Template"); if (StringUtil.isNotEmpty(temp)) this.template = temp; } // make sure we don't return without first releasing the file reference content @Override public ReturnOption handle(FileSlice slice) { if (slice == FileSlice.FINAL) return this.downstream.handle(slice); if (this.currfile == null) this.currfile = this.buildCurrent(slice.file, false); ByteBuf in = slice.data; if (in != null) { while (in.isReadable()) { int amt = Math.min(in.readableBytes(), this.size - this.currchunk); ByteBuf out = in.copy(in.readerIndex(), amt); in.skipBytes(amt); this.currchunk += amt; boolean eof = (this.currchunk == this.size) || (!in.isReadable() && slice.isEof()); this.addSlice(out, 0, eof); if (eof) { this.seqnum++; this.currchunk = 0; this.currfile = this.buildCurrent(slice.file, eof); } } in.release(); } else if (slice.isEof()) { this.addSlice(null, 0, false); } return this.handlerFlush(); } public FileDescriptor buildCurrent(FileDescriptor curr, boolean eof) { // create the output message FileDescriptor blk = new FileDescriptor(); blk.setModTime(System.currentTimeMillis()); // keep the path, just vary the name to the template blk.setPath(curr.path().resolvePeer("/" + this.template.replace("%seq%", this.seqnum + ""))); if (eof) blk.setSize(this.currchunk); else blk.setSize(0); // don't know yet return blk; } }
26.949153
102
0.571384
6d62afa3d5686e31787cfcd40d331667c1810bda
3,183
/** * 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.datayoo.moql; import org.apache.commons.lang3.Validate; import java.sql.ResultSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * @author Tang Tadin */ public class DataSetMapImpl implements DataSetMap { protected Map<String, Object> dataSetMap = new HashMap<String, Object>(); public DataSetMapImpl(){} public DataSetMapImpl(DataSetMap dataSetMap) { putAll(dataSetMap); } @Override public Set<MapEntry<String, Object>> entrySet() { // TODO Auto-generated method stub Set<MapEntry<String, Object>> entrySet = new HashSet<MapEntry<String, Object>>(); for(Map.Entry<String, Object> entry : dataSetMap.entrySet()) { MapEntryImpl<String, Object> mEntry = new MapEntryImpl<String, Object>(entry.getKey()); mEntry.setValue(entry.getValue()); entrySet.add(mEntry); } return entrySet; } @Override public Object getDataSet(String dataSetName) { // TODO Auto-generated method stub Validate.notEmpty(dataSetName, "Parameter 'dataSetName' is empty!"); return dataSetMap.get(dataSetName); } @Override public Object putDataSet(String dataSetName, Object dataSet) { // TODO Auto-generated method stub Validate.notEmpty(dataSetName, "Parameter 'dataSetName' is empty!"); Validate.notNull(dataSet, "Parameter 'dataSet' is null!"); if (!isDataSet(dataSet)) { Validate.notNull(dataSet, "Parameter 'dataSet' must be an instance of Array, Map, Iterable, RowSet or ResultSet!"); } return dataSetMap.put(dataSetName, dataSet); } @Override public Object removeDataSet(String dataSetName) { // TODO Auto-generated method stub Validate.notEmpty(dataSetName, "Parameter 'dataSetName' is empty!"); return dataSetMap.remove(dataSetName); } protected boolean isDataSet(Object dataSet) { if (dataSet.getClass().isArray()) return true; if (dataSet instanceof Map) return true; if (dataSet instanceof Iterable) return true; if (dataSet instanceof RecordSet) return true; if (dataSet instanceof ResultSet) return true; return false; } @Override public void putAll(DataSetMap dataSetMap) { // TODO Auto-generated method stub Validate.notNull(dataSetMap, "Parameter 'dataSetMap' is null!"); for(MapEntry<String, Object> entry : dataSetMap.entrySet()) { this.dataSetMap.put(entry.getKey(), entry.getValue()); } } }
30.605769
118
0.736726
ee05ce979e283d16292ac93cba14577f06699900
1,479
// // This file is part of the CNC-C implementation and // distributed under the Modified BSD License. // See LICENSE for details. // // I AM A GENERATED FILE. PLEASE DO NOT CHANGE ME!!! // package CnCParser.Ast; import lpg.runtime.*; /** *<b> *<li>Rule 31: item_type ::= item_type * *</b> */ public class PointerType extends Ast implements Iitem_type { private Iitem_type _item_type; public Iitem_type getitem_type() { return _item_type; } public PointerType(IToken leftIToken, IToken rightIToken, Iitem_type _item_type) { super(leftIToken, rightIToken); this._item_type = _item_type; initialize(); } public boolean equals(Object o) { if (o == this) return true; if (! (o instanceof PointerType)) return false; if (! super.equals(o)) return false; PointerType other = (PointerType) o; if (! _item_type.equals(other._item_type)) return false; return true; } public int hashCode() { int hash = super.hashCode(); hash = hash * 31 + (_item_type.hashCode()); return hash; } public void accept(IAstVisitor v) { if (! v.preVisit(this)) return; enter((Visitor) v); v.postVisit(this); } public void enter(Visitor v) { boolean checkChildren = v.visit(this); if (checkChildren) _item_type.accept(v); v.endVisit(this); } }
21.75
64
0.597025
fe3737891fb8c1d49b801d25f899aa873d2230dc
577
package org.math.R; import org.slf4j.LoggerFactory; public class RLogSlf4j implements RLog { @Override public void log(String text, Level level){ if(Level.OUTPUT.equals(level)){ LOGGER.debug(text); }else if(Level.INFO.equals(level)){ LOGGER.info(text); }else if(Level.WARNING.equals(level)){ LOGGER.warn(text); }else if(Level.ERROR.equals(level)){ LOGGER.error(text); }else LOGGER.trace(text); } @Override public void closeLog() { } public final static org.slf4j.Logger LOGGER = LoggerFactory.getLogger("RLogger"); }
20.607143
82
0.679376
6c89ac23ad9a1b2a23d18f16e62c8fb6b6a1c026
2,339
package com.pkrete.jsip2.messages.responses; import com.pkrete.jsip2.util.MessageUtil; import com.pkrete.jsip2.util.StringUtil; import java.util.Iterator; /** * Created by sudhishk on 9/11/16. */ public class SIP2CreateBibResponse extends SIP2CirculationTransactionResponse { /** * Instantiates a new Sip 2 create bib response. * * @param data the data */ public SIP2CreateBibResponse(String data) { super("82", data); } @Override public String countChecksum() { StringBuilder builder = new StringBuilder(); builder.append(this.code); builder.append(StringUtil.bool2Int(this.ok)); builder.append(this.transactionDate); if(this.expirationDate != null) { builder.append("BW"); builder.append(this.expirationDate); builder.append("|"); } if(this.pickupLocation != null) { builder.append("BS"); builder.append(this.pickupLocation); builder.append("|"); } builder.append("AO"); builder.append(this.institutionId); builder.append("|AA"); builder.append(this.patronIdentifier); if(this.itemIdentifier != null) { builder.append("|AB"); builder.append(this.itemIdentifier); } if(this.titleIdentifier != null) { builder.append("|AJ"); builder.append(this.titleIdentifier); } if(this.bibId != null) { builder.append("|MA"); builder.append(this.bibId); } Iterator<String> scrMessageIterator = this.screenMessage.iterator(); String msg; while(scrMessageIterator.hasNext()) { msg = scrMessageIterator.next(); builder.append("|AF"); builder.append(msg); } scrMessageIterator = this.printLine.iterator(); while(scrMessageIterator.hasNext()) { msg = scrMessageIterator.next(); builder.append("|AG"); builder.append(msg); } builder.append("|"); if(this.isSequence()) { builder.append("AY"); builder.append(this.sequence); } builder.append("AZ"); return MessageUtil.computeChecksum(builder.toString()); } }
26.885057
80
0.575887
26cbca3e94cee23396622d3c46921340fcafa43b
4,353
/** Copyright 2008 University of Rochester Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package edu.ur.hibernate.ir.item.db; import org.springframework.context.ApplicationContext; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.testng.annotations.Test; import edu.ur.hibernate.ir.test.helper.ContextHolder; import edu.ur.ir.item.GenericItem; import edu.ur.ir.item.GenericItemDAO; import edu.ur.ir.item.ItemVersion; import edu.ur.ir.item.ItemVersionDAO; import edu.ur.ir.item.VersionedItem; import edu.ur.ir.item.VersionedItemDAO; import edu.ur.ir.user.IrUser; import edu.ur.ir.user.IrUserDAO; import edu.ur.ir.user.UserEmail; /** * Test the persistence methods for Item Version Information * * @author Nathan Sarr * */ @Test(groups = { "baseTests" }, enabled = true) public class ItemVersionDAOTest { /** get the application context */ ApplicationContext ctx = ContextHolder.getApplicationContext(); /** transaction manager */ PlatformTransactionManager tm = (PlatformTransactionManager) ctx.getBean("transactionManager"); /** Transaction definition */ TransactionDefinition td = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED); /** versioned item data access */ ItemVersionDAO itemVersionDAO = (ItemVersionDAO)ctx.getBean("itemVersionDAO"); /** user data access */ IrUserDAO userDAO= (IrUserDAO) ctx.getBean("irUserDAO"); /** Versioned item data access */ VersionedItemDAO versionedItemDAO = (VersionedItemDAO) ctx.getBean("versionedItemDAO"); GenericItemDAO itemDAO= (GenericItemDAO) ctx.getBean("itemDAO"); /** * Makes sure an item version can be saved and retrieved. */ public void basicItemVersionDAOTest() { TransactionStatus ts = tm.getTransaction(td); UserEmail userEmail = new UserEmail("email"); GenericItem item = new GenericItem("myItem"); IrUser user = new IrUser("user", "password"); user.setPasswordEncoding("encoding"); user.addUserEmail(userEmail, true); VersionedItem versionedItem = new VersionedItem(user, item); ItemVersion itemVersion = versionedItem.getCurrentVersion(); userDAO.makePersistent(user); itemVersionDAO.makePersistent(itemVersion); ItemVersion otherItemVersion = itemVersionDAO.getById(itemVersion.getId(), false); versionedItem = otherItemVersion.getVersionedItem(); assert versionedItem != null : "otherItemVersion version is null " + otherItemVersion; assert versionedItem.getId() != null : "versioned item id is null " + versionedItem.getId(); assert otherItemVersion != null : "should be able to find item version with id " + itemVersion.getId(); assert otherItemVersion.equals(itemVersion) : "GenericItem version " + itemVersion + " should equal other " + otherItemVersion; tm.commit(ts); ts = tm.getTransaction(td); assert itemVersionDAO.getById(itemVersion.getId(), false) != null : "should be able to find item " + itemVersion; assert versionedItemDAO.getById(versionedItem.getId(), false) != null : "Should be able to get versionedItem " + versionedItem; versionedItemDAO.makeTransient(versionedItemDAO.getById(versionedItem.getId(), false)); assert itemVersionDAO.getById(itemVersion.getId(), false) == null : "Should not be able to find " + itemVersion.getId(); itemDAO.makeTransient(itemDAO.getById(item.getId(), false)); userDAO.makeTransient(userDAO.getById(user.getId(), true)); tm.commit(ts); } }
39.216216
133
0.726855
209f36779f2e52db3760514a0a5bdf68b9545127
225
package example.service; import example.repo.Customer1764Repository; import org.springframework.stereotype.Service; @Service public class Customer1764Service { public Customer1764Service(Customer1764Repository repo) {} }
20.454545
59
0.84
9f805b70e0600cafb7c3b65acf1606812dd96478
7,547
package cube.ware.ui.chat.activity.p2p; import android.content.Context; import android.content.Intent; import android.os.Bundle; import com.alibaba.android.arouter.facade.annotation.Route; import com.common.mvp.base.BasePresenter; import com.common.mvp.rx.RxPermissionUtil; import com.common.utils.utils.ToastUtil; import com.common.utils.utils.log.LogUtil; import com.lzy.imagepicker.ImagePicker; import com.lzy.imagepicker.bean.ImageItem; import com.lzy.imagepicker.ui.ImageGridActivity; import java.util.ArrayList; import java.util.List; import cube.service.message.model.Receiver; import cube.ware.App; import cube.ware.AppConstants; import cube.ware.R; import cube.ware.data.model.dataModel.enmu.CubeSessionType; import cube.ware.data.room.model.CubeMessage; import cube.ware.manager.MessageManager; import cube.ware.ui.chat.BaseChatActivity; import cube.ware.ui.chat.ChatCustomization; import cube.ware.ui.chat.activity.file.FileActivity; import cube.ware.ui.chat.message.MessageFragment; import cube.ware.ui.chat.panel.input.InputPanel; import cube.ware.utils.GlideImageLoader; import rx.Observable; import rx.Observer; import rx.functions.Action1; /** * Created by dth * Des: 一对一聊天页面 * Date: 2018/8/31. */ @Route(path = AppConstants.Router.P2PChatActivity) public class P2PChatActivity extends BaseChatActivity implements InputPanel.OnBottomNavigationListener { private ImagePicker mImagePicker; @Override protected int getContentViewId() { return R.layout.activity_p2p_chat; } @Override protected BasePresenter createPresenter() { return null; } @Override protected void initView() { // ARouter.getInstance().inject(this); } public static void start(Context context, String chatId, String name, ChatCustomization chatCustomization, long messageSn) { Intent intent = new Intent(); intent.putExtra(AppConstants.EXTRA_CHAT_ID, chatId); intent.putExtra(AppConstants.EXTRA_CHAT_NAME, name); intent.putExtra(AppConstants.EXTRA_CHAT_CUSTOMIZATION, chatCustomization); intent.putExtra(AppConstants.EXTRA_CHAT_MESSAGE, messageSn); intent.setClass(context, P2PChatActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); context.startActivity(intent); } @Override protected void initToolBar() { } @Override protected MessageFragment buildFragment() { Bundle arguments = getIntent().getExtras(); MessageFragment fragment = MessageFragment.newInstance(CubeSessionType.P2P, arguments); fragment.setContainerId(R.id.message_fragment_container); fragment.setBottomNavigationListener(this); return fragment; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case AppConstants.REQUEST_CODE_LOCAL_FILE: { // 发送文件 if (resultCode == FileActivity.TAKE_FILE_CODE && null != data) { ArrayList<String> filePathList = data.getStringArrayListExtra(FileActivity.TAKE_FILE_LIST); if (null != filePathList && !filePathList.isEmpty()) { Observable.from(filePathList).subscribe(new Action1<String>() { @Override public void call(String filePath) { MessageManager.getInstance().sendFileMessage(mContext, CubeSessionType.P2P, new Receiver(mChatId,mChatName), filePath, isAnonymous, false); } }); } } break; } case AppConstants.REQUEST_CODE_LOCAL_IMAGE: { // 发送本地图片 if (resultCode == ImagePicker.RESULT_CODE_ITEMS && null != data) { final List<ImageItem> imageItemList = data.getParcelableArrayListExtra(ImagePicker.EXTRA_RESULT_ITEMS); final boolean isOrigin = data.getBooleanExtra("isOrigin", false); mImagePicker.clearSelectedImages(); if (null != imageItemList && !imageItemList.isEmpty()) { Observable.from(imageItemList).subscribe(new Observer<ImageItem>() { @Override public void onNext(ImageItem imageItem) { LogUtil.i("选中图片的路径:" + imageItem.path); String imagePath = imageItem.path; MessageManager.getInstance().sendFileMessage(mContext, CubeSessionType.P2P, new Receiver(mChatId,mChatName), imagePath, isAnonymous, isOrigin); } @Override public void onCompleted() { } @Override public void onError(Throwable e) { ToastUtil.showToast(P2PChatActivity.this, 0, "图片无效"); } }); } } break; } } } public String getChatId() { return this.mChatId; } @Override public void onCameraListener() { } @Override public void onSendFileListener() { RxPermissionUtil.requestStoragePermission(this).subscribe(new Action1<Boolean>() { @Override public void call(Boolean aBoolean) { if (aBoolean) { Intent intent = new Intent(P2PChatActivity.this, FileActivity.class); intent.putExtra(FileActivity.REQUEST_CODE, AppConstants.REQUEST_CODE_LOCAL_FILE); startActivityForResult(intent, AppConstants.REQUEST_CODE_LOCAL_FILE); overridePendingTransition(R.anim.activity_open, 0); } else { ToastUtil.showToast(P2PChatActivity.this, 0, getString(R.string.request_storage_permission)); } } }); } @Override public void onSendImageListener() { mImagePicker = ImagePicker.getInstance(); mImagePicker.setImageLoader(new GlideImageLoader()); // 设置图片加载器 mImagePicker.setMultiMode(true); // 设置为多选模式 mImagePicker.setShowCamera(true); // 设置显示相机 mImagePicker.setSelectLimit(9); mImagePicker.setCrop(false); // 设置拍照后不裁剪 RxPermissionUtil.requestStoragePermission(this).subscribe(new Action1<Boolean>() { @Override public void call(Boolean aBoolean) { if (aBoolean) { Intent intent = new Intent(P2PChatActivity.this, ImageGridActivity.class); startActivityForResult(intent, AppConstants.REQUEST_CODE_LOCAL_IMAGE); overridePendingTransition(R.anim.activity_open, 0); } else { ToastUtil.showToast(P2PChatActivity.this, 0, getString(R.string.request_storage_permission)); } } }); } @Override public void onAvatarClicked(Context context, CubeMessage cubeMessage) { // ToastUtil.showToast(App.getContext(),"点击头像"); } @Override public void onAvatarLongClicked(Context context, CubeMessage cubeMessage) { // ToastUtil.showToast(App.getContext(),"长按头像"); } }
37.361386
175
0.622897
0a66b3d4c4722a6b53b0f116be8ef116a0198235
307
package de.uniks.networkparser.ext.io; import java.io.OutputStream; public class StringOutputStream extends OutputStream { StringBuilder mBuf = new StringBuilder(); @Override public String toString() { return mBuf.toString(); } @Override public void write(int b) { mBuf.append((char) b); } }
17.055556
54
0.732899
3202cd0eacab238b6c6147763656c1e08644abdd
670
package com.feihua.framework.message.dto; import feihua.jdbc.api.pojo.BaseConditionDto; /** * Created by yangwei * Created at 2018/11/2 13:30 */ public class BaseMessageTargetClientParamsDto extends BaseConditionDto { private String targetClient; private String subTargetClient; public String getTargetClient() { return targetClient; } public void setTargetClient(String targetClient) { this.targetClient = targetClient; } public String getSubTargetClient() { return subTargetClient; } public void setSubTargetClient(String subTargetClient) { this.subTargetClient = subTargetClient; } }
21.612903
72
0.714925
b5d7a6afa8f58b01ed2ee0f7c5ec18552cbfb001
6,877
package com.github.eirslett.maven.plugins.frontend.lib; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.ExecuteException; import org.apache.commons.exec.ExecuteStreamHandler; import org.apache.commons.exec.ExecuteWatchdog; import org.apache.commons.exec.Executor; import org.apache.commons.exec.LogOutputStream; import org.apache.commons.exec.PumpStreamHandler; import org.apache.commons.exec.ShutdownHookProcessDestroyer; import org.slf4j.Logger; final class ProcessExecutionException extends Exception { private static final long serialVersionUID = 1L; public ProcessExecutionException(String message) { super(message); } public ProcessExecutionException(Throwable cause) { super(cause); } } final class ProcessExecutor { private final static String PATH_ENV_VAR = "PATH"; private final Map<String, String> environment; private CommandLine commandLine; private final Executor executor; public ProcessExecutor(File workingDirectory, List<String> paths, List<String> command, Platform platform, Map<String, String> additionalEnvironment){ this(workingDirectory, paths, command, platform, additionalEnvironment, 0); } public ProcessExecutor(File workingDirectory, List<String> paths, List<String> command, Platform platform, Map<String, String> additionalEnvironment, long timeoutInSeconds) { this.environment = createEnvironment(paths, platform, additionalEnvironment); this.commandLine = createCommandLine(command); this.executor = createExecutor(workingDirectory, timeoutInSeconds); } public String executeAndGetResult(final Logger logger) throws ProcessExecutionException { ByteArrayOutputStream stdout = new ByteArrayOutputStream(); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); int exitValue = execute(logger, stdout, stderr); if (exitValue == 0) { return stdout.toString().trim(); } else { throw new ProcessExecutionException(stdout + " " + stderr); } } public int executeAndRedirectOutput(final Logger logger) throws ProcessExecutionException { OutputStream stdout = new LoggerOutputStream(logger, 0); OutputStream errorStdout = new LoggerOutputStreamError(logger,0); return execute(logger, stdout, errorStdout); } private int execute(final Logger logger, final OutputStream stdout, final OutputStream stderr) throws ProcessExecutionException { logger.debug("Executing command line {}", commandLine); try { ExecuteStreamHandler streamHandler = new PumpStreamHandler(stdout, stderr); executor.setStreamHandler(streamHandler); int exitValue = executor.execute(commandLine, environment); logger.debug("Exit value {}", exitValue); return exitValue; } catch (ExecuteException e) { if (executor.getWatchdog() != null && executor.getWatchdog().killedProcess()) { throw new ProcessExecutionException("Process killed after timeout"); } throw new ProcessExecutionException(e); } catch (IOException e) { throw new ProcessExecutionException(e); } } private CommandLine createCommandLine(List<String> command) { CommandLine commmandLine = new CommandLine(command.get(0)); for (int i = 1;i < command.size();i++) { String argument = command.get(i); commmandLine.addArgument(argument, false); } return commmandLine; } private Map<String, String> createEnvironment(final List<String> paths, final Platform platform, final Map<String, String> additionalEnvironment) { final Map<String, String> environment = new HashMap<>(System.getenv()); if (additionalEnvironment != null) { environment.putAll(additionalEnvironment); } if (platform.isWindows()) { for (final Map.Entry<String, String> entry : environment.entrySet()) { final String pathName = entry.getKey(); if (PATH_ENV_VAR.equalsIgnoreCase(pathName)) { final String pathValue = entry.getValue(); environment.put(pathName, extendPathVariable(pathValue, paths)); } } } else { final String pathValue = environment.get(PATH_ENV_VAR); environment.put(PATH_ENV_VAR, extendPathVariable(pathValue, paths)); } return environment; } private String extendPathVariable(final String existingValue, final List<String> paths) { final StringBuilder pathBuilder = new StringBuilder(); for (final String path : paths) { pathBuilder.append(path).append(File.pathSeparator); } if (existingValue != null) { pathBuilder.append(existingValue).append(File.pathSeparator); } return pathBuilder.toString(); } private Executor createExecutor(File workingDirectory, long timeoutInSeconds) { DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(workingDirectory); executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); // Fixes #41 if (timeoutInSeconds > 0) { executor.setWatchdog(new ExecuteWatchdog(timeoutInSeconds * 1000)); } return executor; } private static class LoggerOutputStream extends LogOutputStream { private final Logger logger; LoggerOutputStream(Logger logger, int logLevel) { super(logLevel); this.logger = logger; } @Override public final void flush() { // buffer processing on close() only } @Override protected void processLine(final String line, final int logLevel) { logger.info(line); } } private static class LoggerOutputStreamError extends LogOutputStream { private final Logger logger; LoggerOutputStreamError(Logger logger, int logLevel) { super(logLevel); this.logger = logger; } @Override public final void flush() { // buffer processing on close() only } @Override protected void processLine(final String line, final int logLevel) { if(Global.asyncExecuteResult == null){ logger.error(line); }else{ Global.asyncExecuteResult.addError(line); } } } }
36.194737
178
0.666133
59584d72873429030520a415e1b5cf4defdb04f3
3,001
/* ** Tim feel free to integrate this code here. ** ** This code has been placed into the Public Domain. ** This code was written by David M. Gaskin in 1999. ** */ package com.ice.tar; import java.io.IOException; import java.util.Enumeration; import java.util.NoSuchElementException; /** * Enumerate the contents of a "tar" file. * * Last updated 26th Mar 1999. * * @author David. M. Gaskin. * @version Version 1.0 Mar 1999 * @since Version 1.0 */ public class TarEntryEnumerator implements Enumeration { /** * The instance on which the enumeration works. */ private TarInputStream tis = null; /** * Has EndOfFile been reached? */ private boolean eof = false; /** * The read ahead entry (or <B><I>null</I></B> if no read ahead exists) */ private TarEntry readAhead = null; /** * Construct an instance given a TarInputStream. This method is package * private because it is not initially forseen that an instance of this class * should be constructed from outside the package. Should it become necessary * to construct an instance of this class from outside the package in which it * exists then the constructor should be made <B>protected</B> and an empty * subclass should be written in the other package. * * @param <B>tis</B> the <B>TarInputStream</B> on which this enumeration has * to be based. */ public TarEntryEnumerator( TarInputStream tis ) { this.tis = tis; eof = false; } /** * Return the next element in the enumeration. This is a required method * for implementing <B>java.util.Enumeration</B>. * * @return the next Object in the enumeration * @exception <B>NoSuchElementException</B> should an attempt be made to * read beyond EOF */ public Object nextElement() throws NoSuchElementException { if ( eof && ( readAhead == null ) ) throw new NoSuchElementException(); TarEntry rc = null; if ( readAhead != null ) { rc = readAhead; readAhead = null; } else { rc = getNext(); } return rc; } /** * Return <B>true</B> if there are more elements in the enumeration. * * @return <B>true</B> if there are more elements in the enumeration. */ public boolean hasMoreElements() { if (eof) return false; boolean rc = false; readAhead = getNext(); if ( readAhead != null ) rc = true; return rc; } /** * Return the next element of <B>null</B> if there is no next element or * if an error occured. * * @return the next element of <B>null</B> if there is no next element or * if an error occured. */ private TarEntry getNext() { TarEntry rc = null; try { rc = tis.getNextEntry(); } catch ( IOException ex ) { // null will be returned but should not occur ex.printStackTrace(); } if ( rc == null ) eof = true; return rc; } }
22.066176
80
0.624792
9d2ccc220a4d57b8824a8a7235f373860bfb3053
2,049
package com.example.mysterious.privacyshield.Adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.example.mysterious.privacyshield.Models.NavDrawItemModel; import com.example.mysterious.privacyshield.R; import java.util.List; /** * Created by aditya on 4/2/17. */ public class NavDrawAdapter extends BaseAdapter { private LayoutInflater lInflater; private List<NavDrawItemModel> listStorage; public NavDrawAdapter(Context context, List<NavDrawItemModel> customizedListView) { lInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); listStorage = customizedListView; } @Override public int getCount() { return listStorage.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder listViewHolder; if(convertView == null){ listViewHolder = new ViewHolder(); convertView = lInflater.inflate(R.layout.listview_with_text_image, parent, false); listViewHolder.textInListView = (TextView)convertView.findViewById(R.id.textView); listViewHolder.imageInListView = (ImageView)convertView.findViewById(R.id.imageView); convertView.setTag(listViewHolder); }else{ listViewHolder = (ViewHolder)convertView.getTag(); } listViewHolder.textInListView.setText(listStorage.get(position).getName()); listViewHolder.imageInListView.setImageResource(listStorage.get(position).getImageId()); return convertView; } static class ViewHolder{ TextView textInListView; ImageView imageInListView; } }
28.068493
97
0.714007
d1b0eeb715e565fdcf0e42a565c580a77e36507c
600
package info.atende.audition.appclient.spring.test; import info.atende.audition.appclient.spring.annotations.Auditable; import info.atende.audition.appclient.spring.annotations.NoAudit; import org.springframework.stereotype.Component; /** * @author Giovanni Silva. */ @Auditable @Component public class TestTargetNoAuditMethod { @NoAudit public void printSomething(){ System.out.println("The Aspect Advice should not execute after this method"); } public void doPrintSomething(){ System.out.println("The Aspect Advice should execute after this method"); } }
26.086957
85
0.753333
99ca6db16b411458911490a3bd724e95bfa34d7a
473
package com.example.ReciPleaseLogin.data; import com.example.ReciPleaseLogin.data.Recipe; import java.util.List; import java.util.Vector; public class Recipes { List<Recipe> recipes; public Recipes(){ recipes=new Vector<Recipe>(); } public List<Recipe> getRecipes(){ return recipes; } public void updateDB(){ //DB.push(this); } //fetch new data //public void updateView(){ //DB.pull(this); }
15.766667
47
0.621564
db3a17eb5b8f2fa4843d06ba6c52698d190cfdf2
1,027
package com.power.constant; /** * Created by yu on 2016/12/9. */ public class PackageConfig { private String service = "service"; private String serviceImpl = "service.impl"; private String entity = "model"; private String controller = "controller"; private String dao = "dao"; private String mapper = "mapping"; private String converter = "convert"; private String utils = "utils"; private String vo = "vo"; public String getService() { return service; } public String getServiceImpl() { return serviceImpl; } public String getEntity() { return entity; } public String getController() { return controller; } public String getMapper() { return mapper; } public String getDao() { return dao; } public String getConverter() { return converter; } public String getUtils() { return utils; } public String getVo() { return vo; } }
16.564516
48
0.591042
5ab1dcd7182d35a82a115828c5269c3882f14d61
9,571
package com.osh.rvs.entity; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * 日报KPI数据 */ public class DailyKpiDataEntity implements Serializable { private static final long serialVersionUID = -5822192201410204094L; private Date count_date; /** 保修期内返品率 */ private BigDecimal service_repair_back_rate; /** 最终检查合格率 */ private BigDecimal final_inspect_pass_rate; /** 7天内纳期遵守比率 */ private BigDecimal intime_complete_rate; private BigDecimal intime_complete_slt_rate; private BigDecimal intime_complete_medium_rate; private BigDecimal intime_complete_light_rate; /** 每日生产计划达成率 */ private BigDecimal total_plan_processed_rate; /** 翻修1课每日生产计划达成率 */ private BigDecimal section1_plan_processed_rate; /** 翻修2课每日生产计划达成率 */ private BigDecimal section2_plan_processed_rate; /** NS再生率 */ private BigDecimal ns_regenerate_rate; /** 工程直行率 */ private BigDecimal inline_passthrough_rate; /** 报价周期LT达成率 */ private BigDecimal quotation_lt_rate; /** 直送报价周期LT达成率 */ private BigDecimal direct_quotation_lt_rate; /** 半期累计出货 */ private Integer half_period_complete; /** 本月累计出货 */ private Integer month_complete; private String comment; /** 返品分析LT达成率(24小时) **/ private BigDecimal service_repair_analysis_lt24_rate; /** 返品分析LT达成率(48小时) **/ private BigDecimal service_repair_analysis_lt48_rate; private Integer status; private Date count_date_start; private Date count_date_end; private Integer weekly_of_year; // 到货受理数 private Integer registration; // 修理同意数 private Integer user_agreement; // 返回OSH修理 private Integer return_to_osh; // 未修理返回 private Integer unrepair; // 出货总数 private Integer shipment; // WIP在修数 Endoeye系列镜子不计入 private Integer work_in_process; // WIP在库数 private Integer work_in_storage; // 平均修理周期RLT private BigDecimal average_repair_lt; // 零件到达后4天内出货比率 private BigDecimal intime_work_out_rate; // 平均工作周期 private BigDecimal average_work_lt; // 当天零件BO率 private BigDecimal bo_rate; // 三天零件BO率 private BigDecimal bo_3day_rate; // 工程内直行率 (无法算) private Integer final_check_pass_count; private Integer final_check_forbid_count; private Integer[] levels; public Date getCount_date() { return count_date; } public void setCount_date(Date count_date) { this.count_date = count_date; } public BigDecimal getService_repair_back_rate() { return service_repair_back_rate; } public void setService_repair_back_rate(BigDecimal service_repair_back_rate) { this.service_repair_back_rate = service_repair_back_rate; } public BigDecimal getFinal_inspect_pass_rate() { return final_inspect_pass_rate; } public void setFinal_inspect_pass_rate(BigDecimal final_inspect_pass_rate) { this.final_inspect_pass_rate = final_inspect_pass_rate; } public BigDecimal getIntime_complete_rate() { return intime_complete_rate; } public void setIntime_complete_rate(BigDecimal intime_complete_rate) { this.intime_complete_rate = intime_complete_rate; } public BigDecimal getTotal_plan_processed_rate() { return total_plan_processed_rate; } public void setTotal_plan_processed_rate( BigDecimal total_plan_processed_rate) { this.total_plan_processed_rate = total_plan_processed_rate; } public BigDecimal getSection1_plan_processed_rate() { return section1_plan_processed_rate; } public void setSection1_plan_processed_rate( BigDecimal section1_plan_processed_rate) { this.section1_plan_processed_rate = section1_plan_processed_rate; } public BigDecimal getSection2_plan_processed_rate() { return section2_plan_processed_rate; } public void setSection2_plan_processed_rate( BigDecimal section2_plan_processed_rate) { this.section2_plan_processed_rate = section2_plan_processed_rate; } public BigDecimal getNs_regenerate_rate() { return ns_regenerate_rate; } public void setNs_regenerate_rate(BigDecimal ns_regenerate_rate) { this.ns_regenerate_rate = ns_regenerate_rate; } public BigDecimal getInline_passthrough_rate() { return inline_passthrough_rate; } public void setInline_passthrough_rate(BigDecimal inline_passthrough_rate) { this.inline_passthrough_rate = inline_passthrough_rate; } public BigDecimal getQuotation_lt_rate() { return quotation_lt_rate; } public void setQuotation_lt_rate(BigDecimal quotation_lt_rate) { this.quotation_lt_rate = quotation_lt_rate; } public BigDecimal getDirect_quotation_lt_rate() { return direct_quotation_lt_rate; } public void setDirect_quotation_lt_rate(BigDecimal direct_quotation_lt_rate) { this.direct_quotation_lt_rate = direct_quotation_lt_rate; } public Integer getHalf_period_complete() { return half_period_complete; } public void setHalf_period_complete(Integer half_period_complete) { this.half_period_complete = half_period_complete; } public Integer getMonth_complete() { return month_complete; } public void setMonth_complete(Integer month_complete) { this.month_complete = month_complete; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public BigDecimal getService_repair_analysis_lt24_rate() { return service_repair_analysis_lt24_rate; } public void setService_repair_analysis_lt24_rate( BigDecimal service_repair_analysis_lt24_rate) { this.service_repair_analysis_lt24_rate = service_repair_analysis_lt24_rate; } public BigDecimal getService_repair_analysis_lt48_rate() { return service_repair_analysis_lt48_rate; } public void setService_repair_analysis_lt48_rate( BigDecimal service_repair_analysis_lt48_rate) { this.service_repair_analysis_lt48_rate = service_repair_analysis_lt48_rate; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getCount_date_start() { return count_date_start; } public void setCount_date_start(Date count_date_start) { this.count_date_start = count_date_start; } public Date getCount_date_end() { return count_date_end; } public void setCount_date_end(Date count_date_end) { this.count_date_end = count_date_end; } public Integer getRegistration() { return registration; } public void setRegistration(Integer registration) { this.registration = registration; } public Integer getUser_agreement() { return user_agreement; } public void setUser_agreement(Integer user_agreement) { this.user_agreement = user_agreement; } public Integer getReturn_to_osh() { return return_to_osh; } public void setReturn_to_osh(Integer return_to_osh) { this.return_to_osh = return_to_osh; } public Integer getUnrepair() { return unrepair; } public void setUnrepair(Integer unrepair) { this.unrepair = unrepair; } public Integer getShipment() { return shipment; } public void setShipment(Integer shipment) { this.shipment = shipment; } public Integer getWork_in_process() { return work_in_process; } public void setWork_in_process(Integer work_in_process) { this.work_in_process = work_in_process; } public Integer getWork_in_storage() { return work_in_storage; } public void setWork_in_storage(Integer work_in_storage) { this.work_in_storage = work_in_storage; } public BigDecimal getAverage_repair_lt() { return average_repair_lt; } public void setAverage_repair_lt(BigDecimal average_repair_lt) { this.average_repair_lt = average_repair_lt; } public BigDecimal getIntime_work_out_rate() { return intime_work_out_rate; } public void setIntime_work_out_rate(BigDecimal intime_work_out_rate) { this.intime_work_out_rate = intime_work_out_rate; } public BigDecimal getAverage_work_lt() { return average_work_lt; } public void setAverage_work_lt(BigDecimal average_work_lt) { this.average_work_lt = average_work_lt; } public BigDecimal getBo_rate() { return bo_rate; } public void setBo_rate(BigDecimal bo_rate) { this.bo_rate = bo_rate; } public BigDecimal getBo_3day_rate() { return bo_3day_rate; } public void setBo_3day_rate(BigDecimal bo_3day_rate) { this.bo_3day_rate = bo_3day_rate; } public Integer getWeekly_of_year() { return weekly_of_year; } public void setWeekly_of_year(Integer weekly_of_year) { this.weekly_of_year = weekly_of_year; } public Integer getFinal_check_pass_count() { return final_check_pass_count; } public void setFinal_check_pass_count(Integer final_check_pass_count) { this.final_check_pass_count = final_check_pass_count; } public Integer getFinal_check_forbid_count() { return final_check_forbid_count; } public void setFinal_check_forbid_count(Integer final_check_forbid_count) { this.final_check_forbid_count = final_check_forbid_count; } public BigDecimal getIntime_complete_slt_rate() { return intime_complete_slt_rate; } public void setIntime_complete_slt_rate(BigDecimal intime_complete_slt_rate) { this.intime_complete_slt_rate = intime_complete_slt_rate; } public BigDecimal getIntime_complete_medium_rate() { return intime_complete_medium_rate; } public void setIntime_complete_medium_rate( BigDecimal intime_complete_medium_rate) { this.intime_complete_medium_rate = intime_complete_medium_rate; } public BigDecimal getIntime_complete_light_rate() { return intime_complete_light_rate; } public void setIntime_complete_light_rate(BigDecimal intime_complete_light_rate) { this.intime_complete_light_rate = intime_complete_light_rate; } public Integer[] getLevels() { return levels; } public void setLevels(Integer[] levels) { this.levels = levels; } }
23.808458
83
0.797827
aac012d5b637a6d6411137cba416bc182eb6c9d8
351
package com.java110.store.bmo.contractRoom; import com.java110.po.contractRoom.ContractRoomPo; import org.springframework.http.ResponseEntity; public interface IUpdateContractRoomBMO { /** * 修改合同房屋 * add by wuxw * @param contractRoomPo * @return */ ResponseEntity<String> update(ContractRoomPo contractRoomPo); }
19.5
65
0.723647
a7b4f452351439dac0e5495d7825ac48dd53ce77
726
package at.ac.fhcampus.master.monolith.user.entities; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.security.core.GrantedAuthority; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Data @Entity @Table(name = "roles") @Builder @NoArgsConstructor @AllArgsConstructor public class Role implements GrantedAuthority { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String role; @Override public String getAuthority() { return role; } }
21.352941
58
0.780992
a9349eb246e5266256646d23897decf2767c130f
2,949
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/aiplatform/v1beta1/schema/predict/prediction/tabular_regression.proto package com.google.cloud.aiplatform.v1beta1.schema.predict.prediction; public final class TabularRegressionPredictionResultProto { private TabularRegressionPredictionResultProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_aiplatform_v1beta1_schema_predict_prediction_TabularRegressionPredictionResult_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_aiplatform_v1beta1_schema_predict_prediction_TabularRegressionPredictionResult_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\nRgoogle/cloud/aiplatform/v1beta1/schema" + "/predict/prediction/tabular_regression.p" + "roto\0229google.cloud.aiplatform.v1beta1.sc" + "hema.predict.prediction\032\034google/api/anno" + "tations.proto\"\\\n!TabularRegressionPredic" + "tionResult\022\r\n\005value\030\001 \001(\002\022\023\n\013lower_bound" + "\030\002 \001(\002\022\023\n\013upper_bound\030\003 \001(\002B\316\001\n=com.goog" + "le.cloud.aiplatform.v1beta1.schema.predi" + "ct.predictionB&TabularRegressionPredicti" + "onResultProtoP\001Zcgoogle.golang.org/genpr" + "oto/googleapis/cloud/aiplatform/v1beta1/" + "schema/predict/prediction;predictionb\006pr" + "oto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.api.AnnotationsProto.getDescriptor(), }); internal_static_google_cloud_aiplatform_v1beta1_schema_predict_prediction_TabularRegressionPredictionResult_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_cloud_aiplatform_v1beta1_schema_predict_prediction_TabularRegressionPredictionResult_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_aiplatform_v1beta1_schema_predict_prediction_TabularRegressionPredictionResult_descriptor, new java.lang.String[] { "Value", "LowerBound", "UpperBound", }); com.google.api.AnnotationsProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
48.344262
136
0.779586
12197f01ec11a3c8e6f595a7242cc986759f660c
276
package com.helospark.sparktemplatingplugin.support; import java.util.Arrays; import java.util.List; public class ImplicitImportList { public static final List<String> IMPLICIT_IMPORT_LIST = Arrays.asList( "com.helospark.sparktemplatingplugin.wrapper.*"); }
27.6
74
0.771739
a20c10e688684e3f7502b0e91964ec0be394706f
800
package com.lstfight.carrieroperatorproxy.repository; import org.apache.ibatis.jdbc.SQL; import tk.mybatis.mapper.mapperhelper.MapperHelper; import tk.mybatis.mapper.mapperhelper.MapperTemplate; import java.util.List; import java.util.Map; /** * * <p>实现接口的细节,如果接口有父类的东西,实现接口可以不实现</p> * <P>使用反射自动获取对象属性</P> * * @author lst */ public class BatchInsertDao extends MapperTemplate { public BatchInsertDao(Class<?> mapperClass, MapperHelper mapperHelper) { super(mapperClass, mapperHelper); } public String listBatchInsert(List<Object> list) { //第二个花括号是代码块,代码块内在对象初始化时就可以被执行 return new SQL() {{ INSERT_INTO(""); }}.toString(); } public String mapBatchInsert(Map map) { return new SQL() {{ }}.toString(); } }
21.621622
76
0.67375
f9979f91936b761b499e8d2379e111c3eac2f2fc
639
package com.progbits.db; import java.sql.SQLException; import java.sql.Connection; /** * Used in try with resources to set Auto Commit state, and reset after done */ public class AutoSetAutoCommit implements AutoCloseable { private final Connection conn; private final boolean originalAutoCommit; public AutoSetAutoCommit(Connection conn, boolean autoCommit) throws SQLException { this.conn = conn; originalAutoCommit = conn.getAutoCommit(); conn.setAutoCommit(autoCommit); } @Override public void close() throws SQLException { conn.setAutoCommit(originalAutoCommit); } }
25.56
87
0.72457
59bc53dc4cb600aac5c66fda82fdf376d84a7af5
706
package com.openthinks.vimixer.ui.model; import com.openthinks.libs.i18n.I18n; import com.openthinks.vimixer.resources.bundles.ViMixerBundles; import com.openthinks.vimixer.ui.controller.biz.figure.DynamicPaintType; public enum ViFileStatus { NOT_START(DynamicPaintType.INITIALIZED_ALL), IN_PROCESSING(DynamicPaintType.INITIALIZED_ALL), COMPLETED( DynamicPaintType.PROCESSED_ALL); private DynamicPaintType painType; private ViFileStatus(DynamicPaintType painType) { this.painType = painType; } @Override public String toString() { return I18n.getMessage(ViMixerBundles.MODEL, this.name()); }; public DynamicPaintType paintType() { return this.painType; } }
27.153846
106
0.773371
5a62e685a3b1a15c28744c87c97bdc001c0d8592
1,308
/** * Write a description of class Card here. * * @author (your name) * @version (a version number or a date) */ public class Card { // instance variables - replace the example below with your own private String suit; private int value,weight; private String description; /** * Constructor for objects of class Card */ public Card() { // initialise instance variables } public void Card(String _description,String _suit,int _value,int _weight) { setDescription( _description); setSuit(_suit); setValue(_value); setWeight(_weight); } public void setDescription(String _description) { description=_description; } public String getDescription() { return description; } public void setSuit(String _suit) { suit=_suit; } public String getSuit() { return suit; } public void setValue(int _value) { value=_value; } public int getValue() { return value; } public void setWeight(int _weight) { weight=_weight; } public int getWeight() { return weight; } }
18.956522
78
0.544343
60c9ec3c5dacdbde48edd31e95945d83799e3741
5,860
/* * Copyright (c) 2012-2016, b3log.org & hacpai.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.b3log.symphony.processor; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import jodd.io.FileUtil; import jodd.upload.MultipartRequestInputStream; import jodd.util.MimeTypes; import jodd.util.URLDecoder; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.b3log.latke.Latkes; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.latke.util.MD5; import org.b3log.symphony.SymphonyServletListener; import org.b3log.symphony.util.Symphonys; import org.json.JSONObject; /** * File upload to local. * * @author <a href="http://88250.b3log.org">Liang Ding</a> * @version 1.1.2.1, Jul 6, 2016 * @since 1.4.0 */ @WebServlet(urlPatterns = {"/upload", "/upload/*"}, loadOnStartup = 2) public class FileUploadServlet extends HttpServlet { /** * Serial version UID. */ private static final long serialVersionUID = 1L; /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(FileUploadServlet.class); /** * Upload directory. */ private static final String UPLOAD_DIR = Symphonys.get("upload.dir"); static { if (!FileUtil.isExistingFolder(new File(UPLOAD_DIR))) { try { FileUtil.mkdirs(UPLOAD_DIR); } catch (IOException ex) { LOGGER.log(Level.ERROR, "Init upload dir error", ex); } } } /** * Qiniu enabled. */ private static final Boolean QN_ENABLED = Symphonys.getBoolean("qiniu.enabled"); @Override public void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { if (QN_ENABLED) { return; } final String uri = req.getRequestURI(); String key = uri.substring("/upload/".length()); key = StringUtils.substringBeforeLast(key, "-64.jpg"); // Erase Qiniu template key = StringUtils.substringBeforeLast(key, "-260.jpg"); // Erase Qiniu template String path = UPLOAD_DIR + key; path = URLDecoder.decode(path, "UTF-8"); if (!FileUtil.isExistingFile(new File(path))) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } final byte[] data = IOUtils.toByteArray(new FileInputStream(path)); final String ifNoneMatch = req.getHeader("If-None-Match"); final String etag = "\"" + MD5.hash(new String(data)) + "\""; resp.addHeader("Cache-Control", "public, max-age=31536000"); resp.addHeader("ETag", etag); resp.setHeader("Server", "Latke Static Server (v" + SymphonyServletListener.VERSION + ")"); if (etag.equals(ifNoneMatch)) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } final OutputStream output = resp.getOutputStream(); IOUtils.write(data, output); output.flush(); IOUtils.closeQuietly(output); } @Override public void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { if (QN_ENABLED) { return; } final MultipartRequestInputStream multipartRequestInputStream = new MultipartRequestInputStream(req.getInputStream()); multipartRequestInputStream.readBoundary(); multipartRequestInputStream.readDataHeader("UTF-8"); String fileName = multipartRequestInputStream.getLastHeader().getFileName(); final String name = StringUtils.substringBeforeLast(fileName, "."); String suffix = StringUtils.substringAfterLast(fileName, "."); if (StringUtils.isBlank(suffix)) { final String mimeType = multipartRequestInputStream.getLastHeader().getContentType(); String[] exts = MimeTypes.findExtensionsByMimeTypes(mimeType, false); if (null != exts && 0 < exts.length) { suffix = exts[0]; } else { suffix = StringUtils.substringAfter(mimeType, "/"); } } final String uuid = UUID.randomUUID().toString().replaceAll("-", ""); fileName = name + "-" + uuid + "." + suffix; fileName = StringUtils.replace(fileName, " ", "_"); final OutputStream output = new FileOutputStream(UPLOAD_DIR + fileName); IOUtils.copy(multipartRequestInputStream, output); IOUtils.closeQuietly(multipartRequestInputStream); IOUtils.closeQuietly(output); final JSONObject data = new JSONObject(); data.put("key", Latkes.getServePath() + "/upload/" + fileName); resp.setContentType("application/json"); final PrintWriter writer = resp.getWriter(); writer.append(data.toString()); writer.flush(); writer.close(); } }
33.678161
126
0.662116
980b16933cdf37b3df063430eaf7146992e70377
2,745
/* * Copyright © 2013-2016 BLT, Co., Ltd. All Rights Reserved. */ package com.blt.talk.message.server.handler.impl; import org.springframework.stereotype.Component; import com.blt.talk.common.code.IMHeader; import com.blt.talk.common.code.IMProtoMessage; import com.blt.talk.common.code.proto.IMBaseDefine; import com.blt.talk.common.code.proto.IMFile; import com.blt.talk.message.server.handler.IMFileHandle; import com.google.protobuf.MessageLite; import io.netty.channel.ChannelHandlerContext; /** * * @author 袁贵 * @version 1.0 * @since 1.0 */ @Component public class IMFileHandleImpl extends AbstractUserHandlerImpl implements IMFileHandle { /* (non-Javadoc) * @see com.blt.talk.message.server.handler.IMFileHandle#fileReq(com.blt.talk.common.code.IMHeader, com.google.protobuf.MessageLite, io.netty.channel.ChannelHandlerContext) */ @Override public void fileReq(IMHeader header, MessageLite body, ChannelHandlerContext ctx) { // TODO Auto-generated method stub } /* (non-Javadoc) * @see com.blt.talk.message.server.handler.IMFileHandle#hasOfflineReq(com.blt.talk.common.code.IMHeader, com.google.protobuf.MessageLite, io.netty.channel.ChannelHandlerContext) */ @Override public void hasOfflineReq(IMHeader header, MessageLite body, ChannelHandlerContext ctx) { IMFile.IMFileHasOfflineReq hasOfflineReq = (IMFile.IMFileHasOfflineReq)body; long userId = super.getUserId(ctx); // TODO 处理离线文件 IMFile.IMFileHasOfflineRsp.Builder rspBuilder = IMFile.IMFileHasOfflineRsp.newBuilder(); rspBuilder.setUserId(userId); IMHeader resHeader = header.clone(); resHeader.setCommandId((short)IMBaseDefine.FileCmdID.CID_FILE_HAS_OFFLINE_RES_VALUE); ctx.writeAndFlush(new IMProtoMessage<>(resHeader, rspBuilder.build())); } /* (non-Javadoc) * @see com.blt.talk.message.server.handler.IMFileHandle#addOfflineReq(com.blt.talk.common.code.IMHeader, com.google.protobuf.MessageLite, io.netty.channel.ChannelHandlerContext) */ @Override public void addOfflineReq(IMHeader header, MessageLite body, ChannelHandlerContext ctx) { // TODO Auto-generated method stub long userId = super.getUserId(ctx); } /* (non-Javadoc) * @see com.blt.talk.message.server.handler.IMFileHandle#delOfflineReq(com.blt.talk.common.code.IMHeader, com.google.protobuf.MessageLite, io.netty.channel.ChannelHandlerContext) */ @Override public void delOfflineReq(IMHeader header, MessageLite body, ChannelHandlerContext ctx) { // TODO Auto-generated method stub long userId = super.getUserId(ctx); } }
36.118421
182
0.720583
3fdc477dce22559282d193893cf26b0b3e285ee8
240
package zeroturnaround.org.jrebel4androidgettingstarted; /** * Created by shelajev on 16/12/15. */ public class Contributor { String login; String url; @Override public String toString() { return login; } }
15
56
0.658333
7dae607c70773bdfc9bea6882875186ac08a5c17
2,547
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.rds.model.v20140815; import java.util.List; import com.aliyuncs.AcsResponse; import com.aliyuncs.rds.transform.v20140815.DescribeSQLServerUpgradeVersionsResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class DescribeSQLServerUpgradeVersionsResponse extends AcsResponse { private String requestId; private List<Item> items; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public List<Item> getItems() { return this.items; } public void setItems(List<Item> items) { this.items = items; } public static class Item { private String currentVersion; private List<SQLServerUpgradeVersion> sQLServerUpgradeVersions; public String getCurrentVersion() { return this.currentVersion; } public void setCurrentVersion(String currentVersion) { this.currentVersion = currentVersion; } public List<SQLServerUpgradeVersion> getSQLServerUpgradeVersions() { return this.sQLServerUpgradeVersions; } public void setSQLServerUpgradeVersions(List<SQLServerUpgradeVersion> sQLServerUpgradeVersions) { this.sQLServerUpgradeVersions = sQLServerUpgradeVersions; } public static class SQLServerUpgradeVersion { private String version; private String enableUpgrade; public String getVersion() { return this.version; } public void setVersion(String version) { this.version = version; } public String getEnableUpgrade() { return this.enableUpgrade; } public void setEnableUpgrade(String enableUpgrade) { this.enableUpgrade = enableUpgrade; } } } @Override public DescribeSQLServerUpgradeVersionsResponse getInstance(UnmarshallerContext context) { return DescribeSQLServerUpgradeVersionsResponseUnmarshaller.unmarshall(this, context); } }
25.727273
100
0.74362
f4f27f37404be51125fe865dc83368f36a73dbec
2,943
package edu.umass.cs.reconfiguration.reconfigurationpackets; import java.net.InetSocketAddress; import org.json.JSONException; import org.json.JSONObject; import edu.umass.cs.nio.interfaces.Stringifiable; /** * @author arun * * The primary purpose of this class is just to report to an app client * that no active replica was found at the node that received the * request using the response code * {@link edu.umass.cs.reconfiguration.reconfigurationpackets.ClientReconfigurationPacket.ResponseCodes#ACTIVE_REPLICA_EXCEPTION} * . * * This class is also (ab-)used to report to the app client that the * name itself does not exist; if so, the corresponding respose code is * {@link edu.umass.cs.reconfiguration.reconfigurationpackets.ClientReconfigurationPacket.ResponseCodes#NONEXISTENT_NAME_ERROR} * . * */ public class ActiveReplicaError extends ClientReconfigurationPacket { private static enum Keys { REQUEST_ID, ERROR_CODE }; private final long requestID; private final ResponseCodes code; /** * @param initiator * @param name * @param requestID */ public ActiveReplicaError(InetSocketAddress initiator, String name, long requestID) { super(initiator, ReconfigurationPacket.PacketType.ACTIVE_REPLICA_ERROR, name, 0); this.requestID = requestID; this.makeResponse(); this.code = ResponseCodes.ACTIVE_REPLICA_EXCEPTION; } /** * @param name * @param requestID * @param crp */ public ActiveReplicaError(String name, long requestID, ClientReconfigurationPacket crp) { super(name, crp); this.type = ReconfigurationPacket.PacketType.ACTIVE_REPLICA_ERROR; this.requestID = requestID; makeResponse(); this.code = ResponseCodes.NONEXISTENT_NAME_ERROR; } /** * @param json * @throws JSONException */ public ActiveReplicaError(JSONObject json) throws JSONException { super(json); this.makeResponse(); this.requestID = json.getLong(Keys.REQUEST_ID.toString()); this.code = ResponseCodes.valueOf(json.getString(Keys.ERROR_CODE .toString())); } /** * @param json * @param unstringer * @throws JSONException */ public ActiveReplicaError(JSONObject json, Stringifiable<?> unstringer) throws JSONException { super(json, unstringer); this.makeResponse(); this.requestID = json.getLong(Keys.REQUEST_ID.toString()); this.code = ResponseCodes.valueOf(json.getString(Keys.ERROR_CODE .toString())); } public JSONObject toJSONObjectImpl() throws JSONException { JSONObject json = super.toJSONObjectImpl(); json.put(Keys.REQUEST_ID.toString(), this.requestID); json.put(Keys.ERROR_CODE.toString(), this.code); return json; } /** * @return Request ID. */ public long getRequestID() { return this.requestID; } @Override public String getSummary() { return this.code + ":" + super.getSummary() + ":" + ActiveReplicaError.this.requestID; } }
27.504673
137
0.72545
ea97fff2c481e6d0ed9c7b83eefb207cf44ccbe5
1,162
package com.booksaw.betterTeams.customEvents; import com.booksaw.betterTeams.Team; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; public class LevelupTeamEvent extends TeamEvent { private static final HandlerList HANDLERS = new HandlerList(); private final int currentLevel; private final int newLevel; private final int cost; private final boolean score; private final Player commandSender; public LevelupTeamEvent(Team team, int currentLevel, int newLevel, int cost, boolean score, Player commandSender) { super(team); this.currentLevel = currentLevel; this.newLevel = newLevel; this.cost = cost; this.score = score; this.commandSender = commandSender; } public static HandlerList getHandlerList() { return HANDLERS; } @Override public @NotNull HandlerList getHandlers() { return HANDLERS; } public int getCurrentLevel() { return currentLevel; } public int getNewLevel() { return newLevel; } public int getCost() { return cost; } public boolean isScore() { return score; } public Player getCommandSender() { return commandSender; } }
20.75
116
0.755594
b39e3486e32ab6db47ba16bc49da08c3d302cecc
507
package com.notes.designpattern.singleton; /** * 文件描述 枚举单例 **/ public enum SingletonEnum { INSTANCE; public SingletonEnum getInstance() { return INSTANCE; } public static void main(String[] args) { SingletonEnum instance = SingletonEnum.INSTANCE; SingletonEnum instance2 = SingletonEnum.INSTANCE; System.out.println("instance:" + instance); System.out.println("instance2:" + instance2); System.out.println(instance == instance2); } }
24.142857
57
0.658777
1aefc9e044b44dd74e34887c768450cdede07259
2,157
package com.miu360.taxi_check.model; public class LvyouDriverInfo extends Page { /** * 姓名 */ private String driverName; /** * 身份证号 */ private String id; /** * 电话号码 */ private String telphone; /** * 地址 */ private String address; /** * 从业资格证号 */ private String cyzgNumber; /** * 公司名 */ private String corpName; /** * 生日 */ private String birthday; /** * 初次领证时间 */ private String firstCardTime; /** * 开始时间 */ private String startTime; /** * 结束时间 */ private String endTime; /** * 从业资格状态 */ private String state; /** * 类型 */ private String type; public String getDriverName() { return driverName; } public void setDriverName(String driverName) { this.driverName = driverName; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTelphone() { return telphone; } public void setTelphone(String telphone) { this.telphone = telphone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCyzgNumber() { return cyzgNumber; } public void setCyzgNumber(String cyzgNumber) { this.cyzgNumber = cyzgNumber; } public String getCorpName() { return corpName; } public void setCorpName(String corpName) { this.corpName = corpName; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getFirstCardTime() { return firstCardTime; } public void setFirstCardTime(String firstCardTime) { this.firstCardTime = firstCardTime; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
13.48125
53
0.664812
07cec87709740f6372408c2afba1b491da415ea0
130
package se.coredev.week3; public final class Cat extends Animal { @Override public String sound() { return "Mjauu.."; } }
11.818182
39
0.684615
b0fa04ea35af9d2a38661da4bf931c0a600af6dc
4,999
package de.wwag.hackathon.team2.web.rest; import de.wwag.hackathon.team2.service.BuildingService; import de.wwag.hackathon.team2.web.rest.errors.BadRequestAlertException; import de.wwag.hackathon.team2.service.dto.BuildingDTO; import io.github.jhipster.web.util.HeaderUtil; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; /** * REST controller for managing {@link de.wwag.hackathon.team2.domain.Building}. */ @RestController @RequestMapping("/api") public class BuildingResource { private final Logger log = LoggerFactory.getLogger(BuildingResource.class); private static final String ENTITY_NAME = "building"; @Value("${jhipster.clientApp.name}") private String applicationName; private final BuildingService buildingService; public BuildingResource(BuildingService buildingService) { this.buildingService = buildingService; } /** * {@code POST /buildings} : Create a new building. * * @param buildingDTO the buildingDTO to create. * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new buildingDTO, or with status {@code 400 (Bad Request)} if the building has already an ID. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PostMapping("/buildings") public ResponseEntity<BuildingDTO> createBuilding(@Valid @RequestBody BuildingDTO buildingDTO) throws URISyntaxException { log.debug("REST request to save Building : {}", buildingDTO); if (buildingDTO.getId() != null) { throw new BadRequestAlertException("A new building cannot already have an ID", ENTITY_NAME, "idexists"); } BuildingDTO result = buildingService.save(buildingDTO); return ResponseEntity.created(new URI("/api/buildings/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString())) .body(result); } /** * {@code PUT /buildings} : Updates an existing building. * * @param buildingDTO the buildingDTO to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated buildingDTO, * or with status {@code 400 (Bad Request)} if the buildingDTO is not valid, * or with status {@code 500 (Internal Server Error)} if the buildingDTO couldn't be updated. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PutMapping("/buildings") public ResponseEntity<BuildingDTO> updateBuilding(@Valid @RequestBody BuildingDTO buildingDTO) throws URISyntaxException { log.debug("REST request to update Building : {}", buildingDTO); if (buildingDTO.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } BuildingDTO result = buildingService.save(buildingDTO); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, buildingDTO.getId().toString())) .body(result); } /** * {@code GET /buildings} : get all the buildings. * * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of buildings in body. */ @GetMapping("/buildings") public List<BuildingDTO> getAllBuildings() { log.debug("REST request to get all Buildings"); return buildingService.findAll(); } /** * {@code GET /buildings/:id} : get the "id" building. * * @param id the id of the buildingDTO to retrieve. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the buildingDTO, or with status {@code 404 (Not Found)}. */ @GetMapping("/buildings/{id}") public ResponseEntity<BuildingDTO> getBuilding(@PathVariable Long id) { log.debug("REST request to get Building : {}", id); Optional<BuildingDTO> buildingDTO = buildingService.findOne(id); return ResponseUtil.wrapOrNotFound(buildingDTO); } /** * {@code DELETE /buildings/:id} : delete the "id" building. * * @param id the id of the buildingDTO to delete. * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. */ @DeleteMapping("/buildings/{id}") public ResponseEntity<Void> deleteBuilding(@PathVariable Long id) { log.debug("REST request to delete Building : {}", id); buildingService.delete(id); return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build(); } }
42.364407
186
0.696139
ebd5c6737b5b098c86e26312c7a719b01b128269
561
package com.joanna.Model.FactoryPattern; import com.joanna.Enums.Color; import com.joanna.Interfaces.Factory; import com.joanna.Model.Hen; import com.joanna.Model.BuilderPattern.HenBuilder; public class FactoryHen implements Factory { @Override public Hen factoryHen(Color color) { return switch (color) { case WHITE -> new HenBuilder().color(Color.WHITE).build(); case RED -> new HenBuilder().color(Color.RED).build(); default -> throw new IllegalArgumentException("Color not found"); }; } }
28.05
77
0.682709
beb211a364b9a6c3c3af730d1654e07061cff0ed
2,072
package suda.sudamodweather.util; import android.content.Context; import android.util.Log; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; public class GpsUtil { private LocationClient mLocationClient; private Context context = null; /** * 初始化 */ public GpsUtil(Context ctx, BDLocationListener locationListener) { context = ctx; try { mLocationClient = new LocationClient(context.getApplicationContext()); mLocationClient.registerLocationListener(locationListener); //注册监听函数 initLocation(); mLocationClient.start(); } catch (Exception e) { Log.e("GpsUtil error : ", e.getMessage(), e); } } public void stop() { mLocationClient.stop(); } public void start() { mLocationClient.start(); } private void initLocation() { LocationClientOption option = new LocationClientOption(); option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy );//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备 //option.setCoorType("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系 //int span=1000; //option.setScanSpan(span);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的 option.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要 //option.setOpenGps(true);//可选,默认false,设置是否使用gps //option.setLocationNotify(true);//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果 //option.setIsNeedLocationDescribe(true);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近” //option.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到 option.setIgnoreKillProcess(false);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死 option.SetIgnoreCacheException(true);//可选,默认false,设置是否收集CRASH信息,默认收集 option.setEnableSimulateGps(false);//可选,默认false,设置是否需要过滤gps仿真结果,默认需要 mLocationClient.setLocOption(option); } }
37
128
0.700772
b0fa0f3f605fff5a61064f7a59a095091328f138
9,363
/* * Copyright (C) 2018 https://github.com/Minamoto54 * * 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. * * Modifications copyright (C) 2018 Robert Hjertmann Christiansen * */ package dk.hjertmann.log4j2.aws.kinesis; import java.io.IOException; import java.io.Writer; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.StringLayout; import org.apache.logging.log4j.core.appender.ManagerFactory; import org.apache.logging.log4j.core.appender.WriterManager; import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration; import com.amazonaws.retry.PredefinedRetryPolicies; import com.amazonaws.retry.RetryPolicy; import com.amazonaws.services.kinesis.AmazonKinesisAsync; import com.amazonaws.services.kinesis.AmazonKinesisAsyncClientBuilder; import com.amazonaws.services.kinesis.model.PutRecordRequest; import dk.hjertmann.log4j2.aws.kinesis.KinesisManagerFactory.InitParameters; public class KinesisManagerFactory implements ManagerFactory<WriterManager, InitParameters> { public static class KinesisWriter extends Writer { private final InitParameters params; private final ByteBuffer batchBuffer; private final ScheduledExecutorService scheduledExecutor; private AmazonKinesisAsync kinesisClient; private ScheduledFuture<?> awaitTask; public KinesisWriter(final InitParameters params) { this.params = params; initKinesisClient(); batchBuffer = ByteBuffer.allocate(1024 * params.bufferSize); scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); reScheduleTask(); } @Override public void close() throws IOException { scheduledExecutor.shutdownNow(); flushBatchBuffer(false); kinesisClient.shutdown(); } @Override public void flush() throws IOException {} private synchronized void flushBatchBuffer() { flushBatchBuffer(true); } private synchronized void flushBatchBuffer(final boolean async) { if (batchBuffer.position() > 0) { final byte[] src = new byte[batchBuffer.position()]; batchBuffer.rewind(); batchBuffer.get(src).clear(); putRecord(src, async); } } private void initKinesisClient() { ClientConfiguration clientConfiguration = new ClientConfiguration(); clientConfiguration = AwsUtil.setProxySettingsFromSystemProperties(clientConfiguration); clientConfiguration.setMaxErrorRetry(params.maxRetries); clientConfiguration .setRetryPolicy(new RetryPolicy(PredefinedRetryPolicies.DEFAULT_RETRY_CONDITION, PredefinedRetryPolicies.DEFAULT_BACKOFF_STRATEGY, params.maxRetries, true)); try { AmazonKinesisAsyncClientBuilder configuration = AmazonKinesisAsyncClientBuilder.standard() .withCredentials(new DefaultAWSCredentialsProviderChain()) .withClientConfiguration(clientConfiguration); if (StringUtils.isBlank(params.endpoint)) { configuration.withRegion(params.region); } else { EndpointConfiguration endpointConfiguration = new EndpointConfiguration(params.endpoint, params.region); configuration.withEndpointConfiguration(endpointConfiguration); } kinesisClient = configuration .build(); // Can't do this check because we get rate-limit error from AWS after release when all our // instances start up and do this check at the same time // // final DescribeStreamResult describeResult = kinesisClient.describeStream( // new DescribeStreamRequest().withStreamName(params.streamName)); // final String streamStatus = // describeResult.getStreamDescription().getStreamStatus(); // if (!StreamStatus.ACTIVE.name().equals(streamStatus)) { // throw new IllegalStateException("Stream " + params.streamName // + " is not ready (in active status) for appender: " + params.name); // } } catch (final Exception e) { throw new IllegalStateException("Stream " + params.streamName + " doesn't exist for appender: " + params.name, e); } } private void putRecord(final byte[] src) { putRecord(src, true); } private void putRecord(final byte[] src, final boolean async) { try { if (async) { kinesisClient.putRecordAsync( new PutRecordRequest().withStreamName(params.streamName) .withPartitionKey(UUID.randomUUID().toString()) .withData(ByteBuffer.wrap(src))); } else { kinesisClient .putRecord(new PutRecordRequest().withStreamName(params.streamName) .withPartitionKey(UUID.randomUUID().toString()) .withData(ByteBuffer.wrap(src))); } } catch (final Exception ex) { LogManager.getLogger() .error("Failed to schedule log entry for publishing into Kinesis stream: " + params.streamName); } } private void reScheduleTask() { if (awaitTask != null) { awaitTask.cancel(false); } awaitTask = scheduledExecutor.schedule(new Runnable() { @Override public void run() { flushBatchBuffer(); reScheduleTask(); } }, params.maxPutRecordDelay, TimeUnit.MINUTES); } private synchronized void transferData(final byte[] src) { try { batchBuffer.put(src); } catch (final BufferOverflowException e) { flushBatchBuffer(); if (src.length > batchBuffer.capacity()) { putRecord(src); } else { batchBuffer.put(src); } reScheduleTask(); } } @Override public void write(final char[] cbuf, final int off, final int len) throws IOException { final byte[] data = new String(cbuf, off, len).getBytes(params.charset); if (len > 1024000) { LogManager.getLogger() .error("A log its size larger than 1000 KB can't be sent to Kinesis.\n" + new String(cbuf, off, len)); return; } transferData(data); } } public static class InitParameters { String name; String streamName; String endpoint = ""; Charset charset = StandardCharsets.UTF_8; int maxRetries = 3; String region; int bufferSize = 1000; // KB, 5 ~ 1000. int maxPutRecordDelay = 5; // minute, 1 ~ 60. StringLayout layout; public InitParameters(final String name, final String streamName, final String endpoint, final String encoding, final int maxRetries, final String region, final int bufferSize, final int maxPutRecordDelay, final StringLayout layout) { this.name = name; if (StringUtils.isBlank(streamName)) { throw new IllegalArgumentException( "Invalid configuration - streamName cannot be null for appender: " + name); } this.streamName = streamName.trim(); if (StringUtils.isNotBlank(encoding)) { try { charset = Charset.forName(encoding.trim()); } catch (final Exception e) { } } if (StringUtils.isNotBlank(endpoint)) { this.endpoint = endpoint.trim(); } this.maxRetries = getDefaultIfZero(maxRetries, this.maxRetries); if (StringUtils.isBlank(region)) { throw new IllegalArgumentException( "Invalid configuration - region cannot be null for appender: " + name); } this.region = region.trim(); this.bufferSize = Math.min(Math.max(5, getDefaultIfZero(bufferSize, this.bufferSize)), 1000); this.maxPutRecordDelay = Math.min(Math.max(1, getDefaultIfZero(maxPutRecordDelay, this.maxPutRecordDelay)), 60); this.layout = layout; } private int getDefaultIfZero(final int test, final int def) { return test == 0 ? def : test; } } @Override public WriterManager createManager(final String name, final InitParameters params) { return new WriterManager(new KinesisWriter(params), params.streamName, params.layout, false); } }
37.452
101
0.664424
982d3ec6d32b7ca093711dae0349b6be9160b499
3,323
/******************************************************************************* * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.compiler.classfmt; abstract public class ClassFileStruct { byte[] reference; int[] constantPoolOffsets; int structOffset; public ClassFileStruct(byte[] classFileBytes, int[] offsets, int offset) { this.reference = classFileBytes; this.constantPoolOffsets = offsets; this.structOffset = offset; } public double doubleAt(int relativeOffset) { return (Double.longBitsToDouble(i8At(relativeOffset))); } public float floatAt(int relativeOffset) { return (Float.intBitsToFloat(i4At(relativeOffset))); } public int i4At(int relativeOffset) { int position = relativeOffset + this.structOffset; return ((this.reference[position++] & 0xFF) << 24) | ((this.reference[position++] & 0xFF) << 16) | ((this.reference[position++] & 0xFF) << 8) + (this.reference[position] & 0xFF); } public long i8At(int relativeOffset) { int position = relativeOffset + this.structOffset; return (((long) (this.reference[position++] & 0xFF)) << 56) | (((long) (this.reference[position++] & 0xFF)) << 48) | (((long) (this.reference[position++] & 0xFF)) << 40) | (((long) (this.reference[position++] & 0xFF)) << 32) | (((long) (this.reference[position++] & 0xFF)) << 24) | (((long) (this.reference[position++] & 0xFF)) << 16) | (((long) (this.reference[position++] & 0xFF)) << 8) | (this.reference[position++] & 0xFF); } protected void reset() { this.reference = null; this.constantPoolOffsets = null; } public int u1At(int relativeOffset) { return (this.reference[relativeOffset + this.structOffset] & 0xFF); } public int u2At(int relativeOffset) { int position = relativeOffset + this.structOffset; return ((this.reference[position++] & 0xFF) << 8) | (this.reference[position] & 0xFF); } public long u4At(int relativeOffset) { int position = relativeOffset + this.structOffset; return (((this.reference[position++] & 0xFFL) << 24) | ((this.reference[position++] & 0xFF) << 16) | ((this.reference[position++] & 0xFF) << 8) | (this.reference[position] & 0xFF)); } public char[] utf8At(int relativeOffset, int bytesAvailable) { int length = bytesAvailable; char outputBuf[] = new char[bytesAvailable]; int outputPos = 0; int readOffset = this.structOffset + relativeOffset; while (length != 0) { int x = this.reference[readOffset++] & 0xFF; length--; if ((0x80 & x) != 0) { if ((x & 0x20) != 0) { length-=2; x = ((x & 0xF) << 12) | ((this.reference[readOffset++] & 0x3F) << 6) | (this.reference[readOffset++] & 0x3F); } else { length--; x = ((x & 0x1F) << 6) | (this.reference[readOffset++] & 0x3F); } } outputBuf[outputPos++] = (char) x; } if (outputPos != bytesAvailable) { System.arraycopy(outputBuf, 0, (outputBuf = new char[outputPos]), 0, outputPos); } return outputBuf; } }
39.094118
182
0.642191
24754888b9046bff3071d29a7832952019626337
1,054
package betterwithmods.common.potion; import net.minecraft.entity.EntityLivingBase; import net.minecraft.potion.Potion; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class BWPotion extends Potion { private ResourceLocation icon; private boolean beneficial; public BWPotion(String name, boolean b, int potionColor) { super(false, potionColor); this.beneficial = b; setRegistryName(name); this.setPotionName("potion." + name); } @SideOnly(Side.CLIENT) public boolean isBeneficial() { return this.beneficial;//decides top or bottom row } public ResourceLocation getIcon() { return icon; } public void setIcon(ResourceLocation icon) { this.icon = icon; } public void tick(EntityLivingBase entity) {} @Override public Potion setIconIndex(int p_76399_1_, int p_76399_2_) { return super.setIconIndex(p_76399_1_, p_76399_2_); } }
28.486486
64
0.706831
e291f21f74ab984225f36f803dd1912d326f867f
3,398
package icc; /** * Práctica 2 del curso de Introducción a Ciencias de la Computación. * @author Joel Miguel Maya Castrejón 417112602 * @version 15/Octubre/2021. * @since Laboratorio de Introducción a Ciencias de la Computación 2022-1. */ import icc.conversiones.DecimalToDegrees; import icc.conversiones.DegreesToDecimal; import java.util.Scanner; /** * Clase que implementa una aplicacion que convierte de metros y centimetros a * pies y pulgadas y viceversa. */ public class Prueba { /** * Metodo que hace la conversión de grados decimales a grados, * minutos y segundos usando la terminal como flujo de datos. * * Ejemplo, input:63.169 output:63° 10' 8.4" * * @param int - Solo es una bandera de salida. */ public static int decimalToDegrees() { DecimalToDegrees Dtd = new DecimalToDegrees(); Scanner scn = new Scanner(System.in); double decimal; System.out.println("Este es un programa para convertir " + "de grados decimales a grados, minutos y segundos."); System.out.println("Ingresa el valor de los grados decimales:"); decimal = scn.nextDouble(); Dtd.convert(decimal); System.out.println("La conversion de " + decimal + "° " + "grados decimales a grados, minutos y segundos es de: "); System.out.println("Grados: " + Dtd.degrees() + "°"); System.out.println("Minutos: " + Dtd.minutes() + "'"); System.out.println("Segundos: " + Dtd.seconds() + "''"); scn.close(); return 0; } /** * Metodo que hace la conversión de grados, minutos y segundos * a grados decimales usando la terminal como flujo de datos. * * Ejemplo, input:63 10 8.4 output:63.169° * * @param int - Solo es una bandera de salida. */ public static int degreesToDecimal() { DegreesToDecimal dtD = new DegreesToDecimal(); Scanner scn = new Scanner(System.in); int degrees; int minutes; double seconds; System.out.println("Este es un programa para convertir " + "de grados, minutos y segundos a grados decimales."); System.out.println("Ingresa el valor de los grados en enteros:"); degrees = scn.nextInt(); System.out.println("Ingresa el valor de los minutos:"); minutes = scn.nextInt(); System.out.println("Ingresa el valor de los segundos:"); seconds = scn.nextDouble(); dtD.convert(degrees, minutes, seconds); System.out.println("La conversion de " + degrees + "° " + minutes + "' "+ seconds + "'' a grados decimales es de:"); System.out.println("Grados decimales: " + dtD.decimal() + "°"); scn.close(); return 0; } public static void main(String args[]) { double opcion; //Lo cambie a double por si el usuario no mete enteros. Scanner scn = new Scanner(System.in); System.out.println("Escribe 1 si quieres convertir de grados decimales a " + "grados, minutos y segundos."); System.out.println("Escribe cualquier otro número si quieres convertir " + "de grados, minutos y segundos a grados decimales."); opcion = scn.nextDouble(); opcion = opcion == 1 ? decimalToDegrees() : degreesToDecimal(); scn.close(); } }
30.339286
85
0.618011
e3c335f3bf84738086690ea1d087841e2b278bbf
637
package com.fema.gruposalunos.controledegrupoparaalunos.model.grupo; import lombok.*; import org.hibernate.annotations.ColumnDefault; import javax.persistence.*; @Builder @Entity @Getter @Setter @AllArgsConstructor @NoArgsConstructor @Table(name="grupo") public class Grupo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_grupo") private Long id; @Column(name = "descricao", length = 30) private String descricao; @Column(name="qtde_participantes", length = 2) private Long quantidadeParticipantes; @Column(name = "isOpenGrupo") private boolean isOpenGrupo; }
19.90625
68
0.734694
e89bceceab44c4bc11b2b15fbeaa83444d4dc24c
3,604
/* * Copyright 2018 Edmunds.com, 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.edmunds.tools.databricks.maven; import com.edmunds.rest.databricks.DTO.LanguageDTO; import com.edmunds.rest.databricks.DTO.ObjectInfoDTO; import com.edmunds.rest.databricks.DTO.ObjectTypeDTO; import com.edmunds.rest.databricks.request.ExportWorkspaceRequest; import jdk.nashorn.internal.ir.annotations.Ignore; import org.mockito.Mockito; import org.testng.annotations.BeforeMethod; import java.io.File; import java.net.URLEncoder; import java.nio.file.Paths; public class WorkspaceToolMojoTest extends BaseDatabricksMojoTest { private WorkspaceToolMojo underTest = new WorkspaceToolMojo(); @BeforeMethod public void init() throws Exception { super.init(); underTest.setDatabricksServiceFactory(databricksServiceFactory); underTest.setEnvironment("QA"); } //TODO currently does not work with maven... @Ignore public void testExportExecute() throws Exception { String basePath = "test/mycoolartifact"; underTest.setDbWorkspacePath("com.edmunds.test/mycoolartifact"); File sourceWorkspace = new File("./target/src/main/notebooks"); underTest.setSourceWorkspacePath(sourceWorkspace); underTest.setWorkspaceCommand(WorkspaceToolMojo.WorkspaceCommand.EXPORT); underTest.setWorkspacePrefix("test/mycoolartifact"); ObjectInfoDTO[] objectInfoDTOS = new ObjectInfoDTO[2]; objectInfoDTOS[0] = buildObjectInfoDTO(basePath, "myFile", ObjectTypeDTO.NOTEBOOK); objectInfoDTOS[1] = buildObjectInfoDTO(basePath, "myNested", ObjectTypeDTO.DIRECTORY); Mockito.when(workspaceService.listStatus(URLEncoder.encode(basePath, "UTF-8"))).thenReturn(objectInfoDTOS); Mockito.when(workspaceService.listStatus(URLEncoder.encode(basePath + "/myNested", "UTF-8"))).thenReturn(new ObjectInfoDTO[] { buildObjectInfoDTO(basePath + "/myNested", "myNestedFile", ObjectTypeDTO.NOTEBOOK)}); Mockito.when(workspaceService.exportWorkspace(Mockito.any(ExportWorkspaceRequest.class))).thenReturn ("MyCode!".getBytes("UTF-8")); underTest.execute(); Mockito.verify(workspaceService, Mockito.times(2)).exportWorkspace(Mockito.any(ExportWorkspaceRequest.class)); Mockito.verify(workspaceService, Mockito.times(2)).listStatus(Mockito.anyString()); assert(Paths.get(sourceWorkspace.getPath(), "test/mycoolartifact/myFile.scala").toFile().exists()); assert(Paths.get(sourceWorkspace.getPath(), "test/mycoolartifact/myNested/myNestedFile.scala").toFile() .exists()); } private ObjectInfoDTO buildObjectInfoDTO(String basePath, String fileName, ObjectTypeDTO objectTypeDTO) { ObjectInfoDTO objectInfoDTO = new ObjectInfoDTO(); objectInfoDTO.setPath(basePath + "/" + fileName); objectInfoDTO.setLanguage(LanguageDTO.SCALA); objectInfoDTO.setObjectType(objectTypeDTO); return objectInfoDTO; } }
43.95122
118
0.727248
0570068a5c4e2fe2eaec2e6aff1aabed4a2af8eb
4,418
package com.jdawg3636.icbm.common.thread; import net.minecraft.block.BlockState; import net.minecraft.nbt.CompoundNBT; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.server.ServerWorld; import java.util.ArrayList; import java.util.Random; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; public class RaytracedBlastManagerThread extends AbstractBlastManagerThread { public Supplier<Random> randomSupplier; public Function<BlockPos, BlockState> blockStateSupplier; public Function<BlockPos, TileEntity> tileEntitySupplier; public Consumer<BlockPos> decorationCallback; public double explosionCenterPosX; public double explosionCenterPosY; public double explosionCenterPosZ; public float radius; public ArrayList<RaytracedBlastWorkerThread> threadPool; public int threadCount = 4; @Override public String getRegistryName() { return "icbm:raytraced"; } @Override public void initializeLevelCallbacks(ServerWorld level) { randomSupplier = () -> level.random; blockStateSupplier = level::getBlockState; tileEntitySupplier = level::getBlockEntity; decorationCallback = (BlockPos blockPos) -> decorate(level, blockPos); } public RaytracedBlastWorkerThread getNewWorkerThread() { return new RaytracedBlastWorkerThread(); } public void decorate(World level, BlockPos blockPos) {} // Run on this thread once it is started @Override public void run() { // Initialize Workers threadPool = new ArrayList<>(); for(int threadNumber = 0; threadNumber < threadCount; ++threadNumber) { RaytracedBlastWorkerThread worker = getNewWorkerThread(); worker.randomSupplier = randomSupplier; worker.blockStateSupplier = blockStateSupplier; worker.explosionCenterPosX = explosionCenterPosX; worker.explosionCenterPosY = explosionCenterPosY; worker.explosionCenterPosZ = explosionCenterPosZ; worker.radius = radius; worker.threadCount = threadCount; worker.threadNumber = threadNumber; threadPool.add(worker); } // Begin Calculation boolean calculating = true; threadPool.forEach(RaytracedBlastWorkerThread::start); // Keep Thread Alive until All Workers have Completed while(calculating) { if(interrupted()) break; calculating = false; for(RaytracedBlastWorkerThread worker : threadPool) { if (worker.isAlive()) { calculating = true; break; } } } } @Override public Runnable getPostCompletionFunction(final ServerWorld level) { return () -> { for(RaytracedBlastWorkerThread worker : threadPool) { // Remove Blocks in World for (BlockPos blockPos : worker.blocksToBeDestroyed) { try { blockStateSupplier.apply(blockPos).onBlockExploded(level, blockPos, null); } catch (Exception ignored) {/* Using try/catch just in case the null-valued explosion parameter causes any issues */} } // Decorate Blast Crater for (BlockPos blockPos : worker.blocksToBeDecorated) { decorationCallback.accept(blockPos); } } }; } // Serialization @Override public CompoundNBT serializeNBT() { CompoundNBT nbt = super.serializeNBT(); nbt.putDouble("explosion_center_pos_x", explosionCenterPosX); nbt.putDouble("explosion_center_pos_y", explosionCenterPosY); nbt.putDouble("explosion_center_pos_z", explosionCenterPosZ); nbt.putFloat ("radius", radius); return nbt; } // Deserialization @Override public void deserializeNBT(CompoundNBT nbt) { explosionCenterPosX = nbt.getDouble("explosion_center_pos_x"); explosionCenterPosY = nbt.getDouble("explosion_center_pos_y"); explosionCenterPosZ = nbt.getDouble("explosion_center_pos_z"); radius = nbt.getFloat ("radius"); }; }
33.469697
138
0.655953
705188c1d7cb60cd51d92e5cd342e2f4222c8957
352
package com.clemble.casino.server.security; import com.clemble.casino.security.ClembleConsumerDetails; import com.clemble.casino.registration.PlayerToken; public interface PlayerTokenFactory { // TODO make a separate management effort for Tokens & token protocol PlayerToken create(String player, ClembleConsumerDetails consumerDetails); }
29.333333
78
0.818182
3ecb098bd095d4b2dcebb81a7031b2326dd6d127
122
public class Class2 { private int ab; protected int z; public void af(){} public void zf(){} public Class2(){} }
17.428571
21
0.639344
22258e262698b100fb149aaeb1d232966e514e76
2,615
package com.amazon.external.elasticmapreduce.s3distcp; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.hadoop.util.Progressable; public class ProgressableResettableBufferedFileInputStream extends InputStream { protected File file; protected Progressable progressable; private BufferedInputStream inputStream; private long mark = 0L; private long pos = 0L; public ProgressableResettableBufferedFileInputStream(File file, Progressable progressable) throws IOException { this.file = file; this.progressable = progressable; this.inputStream = new BufferedInputStream(new FileInputStream(file)); } public int available() throws IOException { return this.inputStream.available(); } public void close() throws IOException { this.inputStream.close(); } public synchronized void mark(int readlimit) { if (this.progressable != null) this.progressable.progress(); this.mark = this.pos; } public boolean markSupported() { if (this.progressable != null) this.progressable.progress(); return true; } public int read() throws IOException { if (this.progressable != null) this.progressable.progress(); int read = this.inputStream.read(); if (read != -1) { this.pos += 1L; } return read; } public int read(byte[] b, int off, int len) throws IOException { if (this.progressable != null) this.progressable.progress(); int read = this.inputStream.read(b, off, len); if (read != -1) { this.pos += read; } return read; } public int read(byte[] b) throws IOException { if (this.progressable != null) this.progressable.progress(); int read = this.inputStream.read(b); if (read != -1) { this.pos += read; } return read; } public synchronized void reset() throws IOException { if (this.progressable != null) this.progressable.progress(); this.inputStream.close(); this.inputStream = new BufferedInputStream(new FileInputStream(this.file)); this.pos = this.inputStream.skip(this.mark); } public long skip(long n) throws IOException { if (this.progressable != null) this.progressable.progress(); long skipped = this.inputStream.skip(n); this.pos += skipped; return skipped; } } /* * Location: /Users/libinpan/Work/s3/s3distcp.jar Qualified Name: * com.amazon.external.elasticmapreduce.s3distcp. * ProgressableResettableBufferedFileInputStream JD-Core Version: 0.6.2 */
26.414141
113
0.69369
034676cca23a9c66747afc495672bc05fe28712e
2,189
package xj.property.beans; import java.util.List; /** * Created by Administrator on 2015/10/20. */ public class SrroundingInfoBean { /** * status : yes * info : [{"facilitiesClassId":217,"facilitiesClassName":"美食","weight":1,"picName":"nearby_food"},{"facilitiesClassId":218,"facilitiesClassName":"娱乐","weight":1,"picName":"nearby_ktv"},{"facilitiesClassId":219,"facilitiesClassName":"洗车","weight":1,"picName":"nearby_carwash"},{"facilitiesClassId":220,"facilitiesClassName":"健身","weight":1,"picName":"nearby_tearoom"},{"facilitiesClassId":221,"facilitiesClassName":"商场","weight":1,"picName":"nearby_dime_store"}] * longitude : 116.4307 * latitude : 39.89178 */ private String status; private String message; private double longitude; private double latitude; private List<InfoEntity> info; public void setStatus(String status) { this.status = status; } public void setLongitude(double longitude) { this.longitude = longitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public void setInfo(List<InfoEntity> info) { this.info = info; } public String getStatus() { return status; } public double getLongitude() { return longitude; } public double getLatitude() { return latitude; } public List<InfoEntity> getInfo() { return info; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public static class InfoEntity { /** * name : {分类名称} * photo : {分类图片} */ private String name; private String photo; public void setName(String name) { this.name = name; } public void setPhoto(String photo) { this.photo = photo; } public String getName() { return name; } public String getPhoto() { return photo; } } }
23.793478
467
0.572864
c027febfc9130706852e41181baf56885766b314
23,907
/* * Artifactory is a binaries repository manager. * Copyright (C) 2012 JFrog Ltd. * * Artifactory is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Artifactory is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Artifactory. If not, see <http://www.gnu.org/licenses/>. */ package org.artifactory.schedule; import org.artifactory.common.ConstantValues; import org.artifactory.concurrent.LockingException; import org.artifactory.concurrent.State; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * @author Yoav Landman */ public abstract class TaskBase implements Task { private static final Logger log = LoggerFactory.getLogger(TaskBase.class); private TaskState state; //TODO: [by fsi] should use StateManager private final ReentrantLock stateSync; private final Condition stateChanged; private final Condition completed; private boolean executed; // Initialized from JobCommand annotation private boolean singleton; private boolean manuallyActivated; /** * Prevents resuming a task until all stoppers/pausers have resumed it */ private int resumeBarriersCount; private final Class<? extends TaskCallback> callbackType; @SuppressWarnings({"unchecked"}) protected TaskBase(Class<? extends TaskCallback> callbackType) { state = TaskState.VIRGIN; stateSync = new ReentrantLock(); stateChanged = stateSync.newCondition(); completed = stateSync.newCondition(); executed = false; resumeBarriersCount = 0; this.callbackType = callbackType; } @Override public State getInitialState() { return TaskState.VIRGIN; } public boolean waitingForProcess() { return state == TaskState.PAUSING || state == TaskState.STOPPING; } @Override public boolean isRunning() { return state == TaskState.RUNNING || waitingForProcess(); } public boolean processActive() { return isRunning() || state == TaskState.PAUSED; } void schedule(boolean waitForRunning) { lockState(); try { scheduleTask(); guardedTransitionToState(TaskState.SCHEDULED, waitForRunning); } finally { unlockState(); } } void cancel(boolean wait) { lockState(); try { log.trace("Entering cancel with state {} on {}", state, this); if (processActive() && !wait) { throw new IllegalStateException("Cannot cancel immediately an active task " + this); } if (processActive()) { log.trace("Waiting for active task: {} to finish.", this); if (waitingForProcess()) { guardedWaitForNextStep(); } if (processActive()) { guardedTransitionToState(TaskState.STOPPING, wait); } } if (state == TaskState.CANCELED) { log.info("Task {} already canceled.", this); } else { log.debug("Canceling task: {}.", this); guardedSetState(TaskState.CANCELED); } cancelTask(); } finally { unlockState(); } } void pause(boolean wait) { lockState(); try { log.trace("Entering pause with state {} on {}", state, this); if (state == TaskState.VIRGIN) { throw new IllegalStateException("Cannot stop a virgin task."); } else if (state == TaskState.RUNNING) { if (!wait) { throw new IllegalStateException("Cannot pause immediately a running task " + this); } resumeBarriersCount++; log.trace("resumeBarriersCount++ to {} after pause while running on {}", resumeBarriersCount, this); guardedTransitionToState(TaskState.PAUSING, wait); } else if (state == TaskState.STOPPING) { // Already stopping, waiting for stop if (!wait) { throw new IllegalStateException("Cannot pause immediately a stopping task " + this); } resumeBarriersCount++; log.trace("resumeBarriersCount++ to {} after pause while stopping on {}", resumeBarriersCount, this); guardedWaitForNextStep(); } else if (state == TaskState.PAUSED || state == TaskState.PAUSING) { // Already paused, just count the barrier resumeBarriersCount++; log.trace("resumeBarriersCount++ to {} after pause already paused on {}", resumeBarriersCount, this); } else if (state == TaskState.CANCELED) { // Task canceled, forget it => do nothing } else { // Not running, just count the barrier, and set to stop resumeBarriersCount++; log.trace("resumeBarriersCount++ to {} after pause on {}", resumeBarriersCount, this); if (state != TaskState.STOPPED) { guardedSetState(TaskState.STOPPED); } } } finally { unlockState(); } } /** * Stops but does not unschedule the task (can transition back to running state) * * @param wait */ void stop(boolean wait) { lockState(); try { log.trace("Entering stop with state {} on {}", state, this); if (state == TaskState.VIRGIN) { throw new IllegalStateException("Cannot stop a virgin task."); } else if (state == TaskState.RUNNING || state == TaskState.PAUSING) { if (!wait) { throw new IllegalStateException("Cannot stop immediately a running task " + this); } //Stop resumeBarriersCount++; log.trace("resumeBarriersCount++ to {} after stop on {}", resumeBarriersCount, this); guardedTransitionToState(TaskState.STOPPING, wait); } else if (state == TaskState.CANCELED) { // Task canceled, forget it => do nothing } else if (state == TaskState.STOPPED || state == TaskState.STOPPING) { // Already stopped, just count the barrier resumeBarriersCount++; log.trace("resumeBarriersCount++ to {} after stop already stopped on {}", resumeBarriersCount, this); if (state == TaskState.STOPPING) { guardedWaitForNextStep(); } } else { //For both stop and pause resumeBarriersCount++; log.trace("resumeBarriersCount++ to {} after stop on {}", resumeBarriersCount, this); guardedSetState(TaskState.STOPPED); } } finally { unlockState(); } } boolean resume() { lockState(); try { if (state == TaskState.CANCELED) { throw new IllegalStateException("Cannot resume a canceled task."); } if (resumeBarriersCount > 0) { resumeBarriersCount--; } else { log.info("Skipping resume since there are no active resume barriers " + "(probably invoked resume() more than needed)."); return true; } log.trace("resumeBarriersCount-- to {} after resume on {}", resumeBarriersCount, this); if (resumeBarriersCount > 0) { log.debug("Cannot resume while there are still {} resume barriers.", resumeBarriersCount); return false; } if (state == TaskState.PAUSED || state == TaskState.PAUSING) { guardedSetState(TaskState.RUNNING); } else if (state == TaskState.STOPPED || state == TaskState.STOPPING) { //Nothing to do for single execution - either resume from pause or reached stopped //if resume by a different thread if (!isSingleExecution()) { guardedSetState(TaskState.SCHEDULED); } } return true; } finally { unlockState(); } } @Override public Class<? extends TaskCallback> getType() { return callbackType; } public abstract String getToken(); /** * Starts or schedules the task */ protected abstract void scheduleTask(); /** * Stops or unschedules the task */ protected abstract void cancelTask(); /** * Needs to be called from the execution loop of the task that wants to check if to pause or to stop * * @return */ public boolean blockIfPausedAndShouldBreak() { lockState(); //if running continue, if pausing transition to pause else exit try { if (state == TaskState.PAUSING) { guardedSetState(TaskState.PAUSED); } try { log.trace("Entering wait for out of paused on: {}", this); int tries = ConstantValues.taskCompletionLockTimeoutRetries.getInt(); long timeout = ConstantValues.locksTimeoutSecs.getLong(); while (state == TaskState.PAUSED) { stateChanged.await(timeout, TimeUnit.SECONDS); tries--; if (tries <= 0) { throw new LockingException("Task " + this + " paused for more than " + ConstantValues.taskCompletionLockTimeoutRetries.getInt() + " times."); } log.trace("One wait for out of paused from on {}", this); } } catch (InterruptedException e) { catchInterrupt(TaskState.PAUSED); } return state != TaskState.RUNNING; } finally { unlockState(); } } /** * Whether this task is non-cyclic one and is canceled after a single execution * * @return */ public boolean isSingleExecution() { return false; } /** * Weather the task with this callback type should be unique on the task service. * i.e., not other task with the same type should ever be running. * * @return True if this task should be unique */ public boolean isSingleton() { return singleton; } public void setSingleton(boolean singleton) { this.singleton = singleton; } public boolean isManuallyActivated() { return manuallyActivated; } public void setManuallyActivated(boolean manuallyActivated) { this.manuallyActivated = manuallyActivated; } public boolean wasCompleted() { if (!isSingleExecution()) { throw new UnsupportedOperationException("Does not support waitForCompletion on cyclic tasks."); } return executed && (state == TaskState.STOPPED || state == TaskState.CANCELED); } /** * Wait for the task to stop running * * @return */ boolean waitForCompletion(long timeout) { if (!isSingleExecution()) { throw new UnsupportedOperationException("Does not support waitForCompletion on cyclic tasks."); } if (!isRunning()) { // The task may have already complete return true; } boolean completed = false; lockState(); try { try { //Wait forever (tries * lock timeout) until it finished the current execution if (timeout == 0) { timeout = ConstantValues.locksTimeoutSecs.getLong() * ConstantValues.taskCompletionLockTimeoutRetries.getInt(); } long start = System.currentTimeMillis(); while (true) { // If already executed (passed to running state) and now stooped or canceled // => It means already completed if (executed) { if (state == TaskState.STOPPED || state == TaskState.CANCELED) { completed = true; break; } } // Waiting on the completed condition boolean success = this.completed.await(ConstantValues.locksTimeoutSecs.getLong(), TimeUnit.SECONDS); if (success) { completed = true; break; } if (start + timeout >= System.currentTimeMillis()) { throw new LockingException("Waited for task " + this + " more than " + timeout + "ms."); } } } catch (InterruptedException e) { catchInterrupt(state); } } finally { unlockState(); } return completed; } boolean started() { boolean shouldExecute = false; lockState(); //Check if should run try { if (state == TaskState.SCHEDULED) { guardedSetState(TaskState.RUNNING); shouldExecute = true; } } finally { unlockState(); } return shouldExecute; } void completed() { lockState(); try { if (state == TaskState.STOPPED) { //Do nothing return; } if (state == TaskState.PAUSED || state == TaskState.STOPPING || state == TaskState.PAUSING) { guardedSetState(TaskState.STOPPED); } else if (state != TaskState.CANCELED) { if (isSingleExecution()) { guardedSetState(TaskState.STOPPED); } else if (state != TaskState.SCHEDULED) { //Could be on SCHEDULED if resumed after stopped guardedSetState(TaskState.SCHEDULED); } } completed.signal(); } finally { unlockState(); } } private <V> V guardedTransitionToState(TaskState newState, boolean waitForNextStep) { V result = null; if (state == newState) { return result; } guardedSetState(newState); if (waitForNextStep) { guardedWaitForNextStep(); } return result; } private TaskState guardedWaitForNextStep() { long timeout = ConstantValues.locksTimeoutSecs.getLong(); return guardedWaitForNextStep(timeout); } private TaskState guardedWaitForNextStep(long timeout) { TaskState oldState = state; TaskState newState = oldState; try { log.trace("Entering wait for next step from {} on: {}", oldState, this); while (state == oldState) { boolean success = stateChanged.await(timeout, TimeUnit.SECONDS); if (!success) { throw new LockingException( "Timeout after " + timeout + " seconds when trying to wait for next state in '" + oldState + "'." ); } newState = state; log.trace("Exiting wait for next step from {} to {} on {}", oldState, newState, this); } } catch (InterruptedException e) { catchInterrupt(oldState); } return newState; } private void guardedSetState(TaskState newState) { boolean validNewState = state.canTransitionTo(newState); if (!validNewState) { throw new IllegalArgumentException("Cannot transition from " + this.state + " to " + newState + "."); } log.trace("Changing state: {}: {}-->{}", this.toString(), this.state, newState); state = newState; if (state == TaskState.RUNNING) { executed = true; } else if (state == TaskState.SCHEDULED) { executed = false; } stateChanged.signal(); } private void lockState() { try { int holdCount = stateSync.getHoldCount(); log.trace("Thread {} trying lock (activeLocks={}) on {}", Thread.currentThread(), holdCount, this); if (holdCount > 0) { //Clean all and throw while (holdCount > 0) { stateSync.unlock(); holdCount--; } throw new LockingException("Locking an already locked task state: " + this + " active lock(s) already active!"); } boolean success = stateSync.tryLock() || stateSync.tryLock(getStateLockTimeOut(), TimeUnit.SECONDS); if (!success) { throw new LockingException( "Could not acquire state lock in " + getStateLockTimeOut() + " secs"); } } catch (InterruptedException e) { log.warn("Interrupted while trying to lock {}.", this); } } private long getStateLockTimeOut() { return ConstantValues.locksTimeoutSecs.getLong(); } private void unlockState() { log.trace("Unlocking {}", this); stateSync.unlock(); } private static void catchInterrupt(TaskState state) { log.warn("Interrupted during state wait from '{}'.", state); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof TaskBase)) { return false; } TaskBase base = (TaskBase) o; return getToken().equals(base.getToken()); } @Override public int hashCode() { return getToken().hashCode(); } @Override public String toString() { return getToken(); } public abstract void addAttribute(String key, Object value); @Override public boolean keyEquals(Object... keyValues) { JobCommand jobCommand = this.getType().getAnnotation(JobCommand.class); String[] keys = jobCommand.keyAttributes(); if (keyValues.length != keys.length) { throw new IllegalArgumentException("Cannot compare key values for task " + getType() + "\n" + "Received " + Arrays.toString(keyValues) + " and expected values for " + Arrays.toString(keys)); } for (int i = 0; i < keys.length; i++) { Object attribute = getAttribute(keys[i]); if (attribute == null) { log.warn("Task attribute is NULL: {}, given keyValues: {}", keys[i], keyValues); return false; } if (!attribute.equals(keyValues[i])) { return false; } } return true; } @Override public boolean keyEquals(Task task) { JobCommand otherJobCommand = (JobCommand) task.getType().getAnnotation(JobCommand.class); JobCommand myJobCommand = this.getType().getAnnotation(JobCommand.class); String[] myKeys = myJobCommand.keyAttributes(); String[] otherKeys = otherJobCommand.keyAttributes(); if (!Arrays.equals(myKeys, otherKeys)) { throw new IllegalArgumentException( "Cannot compare key values between task " + this + " and task " + task + "\n" + "Keys " + Arrays.toString(myKeys) + " not equals to " + Arrays.toString(otherKeys) ); } for (String key : myKeys) { if (!getAttribute(key).equals(task.getAttribute(key))) { return false; } } return true; } @Override public Object[] getKeyValues() { JobCommand myJobCommand = this.getType().getAnnotation(JobCommand.class); String[] myKeys = myJobCommand.keyAttributes(); Object[] result = new Object[myKeys.length]; for (int i = 0; i < myKeys.length; i++) { result[i] = getAttribute(myKeys[i]); } return result; } public enum TaskState implements State { VIRGIN, SCHEDULED, RUNNING, PAUSING, STOPPING, STOPPED, //Will not start if refired by the scheduler PAUSED, //Blocked by executions thread (and will not start if refired by scheduler) CANCELED; @Override @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean canTransitionTo(State newState) { Set<TaskState> states = getPossibleTransitionStates(this); return states.contains(newState); } @SuppressWarnings({"OverlyComplexMethod"}) private static Set<TaskState> getPossibleTransitionStates(TaskState oldState) { HashSet<TaskState> states = new HashSet<>(); switch (oldState) { case VIRGIN: states.add(TaskState.SCHEDULED); states.add(TaskState.CANCELED); return states; case SCHEDULED: states.add(TaskState.RUNNING); states.add(TaskState.PAUSING); states.add(TaskState.STOPPING); states.add(TaskState.STOPPED); states.add(TaskState.CANCELED); return states; case RUNNING: states.add(TaskState.PAUSING); states.add(TaskState.STOPPING); states.add(TaskState.STOPPED); states.add(TaskState.CANCELED); states.add(TaskState.SCHEDULED); return states; case PAUSING: states.add(TaskState.PAUSED); states.add(TaskState.RUNNING); states.add(TaskState.STOPPING); states.add(TaskState.STOPPED); states.add(TaskState.CANCELED); return states; case PAUSED: states.add(TaskState.RUNNING); states.add(TaskState.STOPPING); states.add(TaskState.STOPPED); states.add(TaskState.CANCELED); return states; case STOPPING: states.add(TaskState.CANCELED); case STOPPED: states.add(TaskState.STOPPED); states.add(TaskState.RUNNING); states.add(TaskState.SCHEDULED); states.add(TaskState.CANCELED); return states; case CANCELED: //Unscheduled return states; default: throw new IllegalArgumentException( "No transitions defined for state: " + oldState); } } } }
36.667178
131
0.544987
e3989fd86d489733a213f18e55857952422c4781
10,512
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.orchestrator.policy; import com.yahoo.config.provision.Zone; import com.yahoo.vespa.applicationmodel.ClusterId; import com.yahoo.vespa.applicationmodel.ServiceType; import com.yahoo.vespa.flags.BooleanFlag; import com.yahoo.vespa.flags.FetchVector; import com.yahoo.vespa.flags.FlagSource; import com.yahoo.vespa.flags.Flags; import com.yahoo.vespa.orchestrator.model.ClusterApi; import com.yahoo.vespa.orchestrator.model.VespaModelUtil; import java.util.Optional; import java.util.Set; import static com.yahoo.vespa.orchestrator.policy.HostedVespaPolicy.ENOUGH_SERVICES_UP_CONSTRAINT; public class HostedVespaClusterPolicy implements ClusterPolicy { private final BooleanFlag groupSuspensionFlag; private final Zone zone; public HostedVespaClusterPolicy(FlagSource flagSource, Zone zone) { // Note that the "group" in this flag refers to hierarchical groups of a content cluster. this.groupSuspensionFlag = Flags.GROUP_SUSPENSION.bindTo(flagSource); this.zone = zone; } @Override public SuspensionReasons verifyGroupGoingDownIsFine(ClusterApi clusterApi) throws HostStateChangeDeniedException { boolean enableContentGroupSuspension = groupSuspensionFlag .with(FetchVector.Dimension.APPLICATION_ID, clusterApi.getApplication().applicationId().serializedForm()) .value(); if (clusterApi.noServicesOutsideGroupIsDown()) { return SuspensionReasons.nothingNoteworthy(); } int percentageOfServicesAllowedToBeDown = getConcurrentSuspensionLimit(clusterApi, enableContentGroupSuspension).asPercentage(); if (clusterApi.percentageOfServicesDownIfGroupIsAllowedToBeDown() <= percentageOfServicesAllowedToBeDown) { return SuspensionReasons.nothingNoteworthy(); } Optional<SuspensionReasons> suspensionReasons = clusterApi.reasonsForNoServicesInGroupIsUp(); if (suspensionReasons.isPresent()) { return suspensionReasons.get(); } String message = percentageOfServicesAllowedToBeDown <= 0 ? "Suspension of service with type '" + clusterApi.serviceType() + "' not allowed: " + clusterApi.percentageOfServicesDown() + "% are suspended already." + clusterApi.downDescription() : "Suspension of service with type '" + clusterApi.serviceType() + "' would increase from " + clusterApi.percentageOfServicesDown() + "% to " + clusterApi.percentageOfServicesDownIfGroupIsAllowedToBeDown() + "%, over the limit of " + percentageOfServicesAllowedToBeDown + "%." + clusterApi.downDescription(); throw new HostStateChangeDeniedException(clusterApi.getNodeGroup(), ENOUGH_SERVICES_UP_CONSTRAINT, message); } @Override public void verifyGroupGoingDownPermanentlyIsFine(ClusterApi clusterApi) throws HostStateChangeDeniedException { // This policy is similar to verifyGroupGoingDownIsFine, except that services being down in the group // is no excuse to allow suspension (like it is for verifyGroupGoingDownIsFine), since if we grant // suspension in this case they will permanently be down/removed. if (clusterApi.noServicesOutsideGroupIsDown()) { return; } int percentageOfServicesAllowedToBeDown = getConcurrentSuspensionLimit(clusterApi, false).asPercentage(); if (clusterApi.percentageOfServicesDownIfGroupIsAllowedToBeDown() <= percentageOfServicesAllowedToBeDown) { return; } throw new HostStateChangeDeniedException( clusterApi.getNodeGroup(), ENOUGH_SERVICES_UP_CONSTRAINT, "Down percentage for service type " + clusterApi.serviceType() + " would increase to " + clusterApi.percentageOfServicesDownIfGroupIsAllowedToBeDown() + "%, over the limit of " + percentageOfServicesAllowedToBeDown + "%." + clusterApi.downDescription()); } // Non-private for testing purposes ConcurrentSuspensionLimitForCluster getConcurrentSuspensionLimit(ClusterApi clusterApi, boolean enableContentGroupSuspension) { if (enableContentGroupSuspension) { // Possible service clusters on a node as of 2021-01-22: // // CLUSTER ID SERVICE TYPE HEALTH ASSOCIATION // 1 CCN-controllers container-clustercontrollers Slobrok 1, 3, or 6 in content cluster // 2 CCN distributor Slobrok content cluster // 3 CCN storagenode Slobrok content cluster // 4 CCN searchnode Slobrok content cluster // 5 CCN transactionlogserver not checked content cluster // 6 JCCN container Slobrok jdisc container cluster // 7 admin slobrok not checked 1-3 in jdisc container cluster // 8 metrics metricsproxy-container Slobrok application // 9 admin logd not checked application // 10 admin config-sentinel not checked application // 11 admin configproxy not checked application // 12 admin logforwarder not checked application // 13 controller controller state/v1 controllers // 14 zone-config-servers configserver state/v1 config servers // 15 controller-host hostadmin state/v1 controller hosts // 16 configserver-host hostadmin state/v1 config server hosts // 17 tenant-host hostadmin state/v1 tenant hosts // 18 proxy-host hostadmin state/v1 proxy hosts // // CCN refers to the content cluster's name, as specified in services.xml. // JCCN refers to the jdisc container cluster's name, as specified in services.xml. // // For instance a content node will have 2-5 and 8-12 and possibly 1, while a combined // cluster node may have all 1-12. // // The services on a node can be categorized into these main types, ref association column above: // A content // B container // C tenant host // D config server // E config server host // F controller // G controller host // H proxy (same as B) // I proxy host if (clusterApi.serviceType().equals(ServiceType.CLUSTER_CONTROLLER)) { return ConcurrentSuspensionLimitForCluster.ONE_NODE; } if (Set.of(ServiceType.STORAGE, ServiceType.SEARCH, ServiceType.DISTRIBUTOR, ServiceType.TRANSACTION_LOG_SERVER) .contains(clusterApi.serviceType())) { // Delegate to the cluster controller return ConcurrentSuspensionLimitForCluster.ALL_NODES; } if (clusterApi.serviceType().equals(ServiceType.CONTAINER)) { return ConcurrentSuspensionLimitForCluster.TEN_PERCENT; } if (VespaModelUtil.ADMIN_CLUSTER_ID.equals(clusterApi.clusterId())) { if (ServiceType.SLOBROK.equals(clusterApi.serviceType())) { return ConcurrentSuspensionLimitForCluster.ONE_NODE; } return ConcurrentSuspensionLimitForCluster.ALL_NODES; } else if (ServiceType.METRICS_PROXY.equals(clusterApi.serviceType())) { return ConcurrentSuspensionLimitForCluster.ALL_NODES; } if (Set.of(ServiceType.CONFIG_SERVER, ServiceType.CONTROLLER).contains(clusterApi.serviceType())) { return ConcurrentSuspensionLimitForCluster.ONE_NODE; } if (clusterApi.serviceType().equals(ServiceType.HOST_ADMIN)) { if (Set.of(ClusterId.CONFIG_SERVER_HOST, ClusterId.CONTROLLER_HOST).contains(clusterApi.clusterId())) { return ConcurrentSuspensionLimitForCluster.ONE_NODE; } return zone.system().isCd() ? ConcurrentSuspensionLimitForCluster.FIFTY_PERCENT : ConcurrentSuspensionLimitForCluster.TWENTY_PERCENT; } // The above should cover all cases, but if not we'll return a reasonable default: return ConcurrentSuspensionLimitForCluster.TEN_PERCENT; } else { // TODO: Remove this legacy branch if (clusterApi.isStorageCluster()) { return ConcurrentSuspensionLimitForCluster.ONE_NODE; } if (ServiceType.CLUSTER_CONTROLLER.equals(clusterApi.serviceType())) { return ConcurrentSuspensionLimitForCluster.ONE_NODE; } if (ServiceType.METRICS_PROXY.equals(clusterApi.serviceType())) { return ConcurrentSuspensionLimitForCluster.ALL_NODES; } if (VespaModelUtil.ADMIN_CLUSTER_ID.equals(clusterApi.clusterId())) { if (ServiceType.SLOBROK.equals(clusterApi.serviceType())) { return ConcurrentSuspensionLimitForCluster.ONE_NODE; } return ConcurrentSuspensionLimitForCluster.ALL_NODES; } if (clusterApi.getApplication().applicationId().equals(VespaModelUtil.TENANT_HOST_APPLICATION_ID)) { return zone.system().isCd() ? ConcurrentSuspensionLimitForCluster.FIFTY_PERCENT : ConcurrentSuspensionLimitForCluster.TWENTY_PERCENT; } return ConcurrentSuspensionLimitForCluster.TEN_PERCENT; } } }
52.56
136
0.618056
0728dff55f1dd9a51b9cfa0c4a2e0d4890a2764a
257
package com.yju.bbs.mapper; import org.springframework.stereotype.Repository; import com.yju.bbs.dto.Board; @Repository("com.yju.bbs.mapper.TestMapper") public interface TestMapper { public Board test(); public void BoardInsertTest(Board board); }
18.357143
49
0.774319
27227556ba8328eb204a9d704ae113ac06a1e308
2,700
package com.twoexample.adresslist.Utils.Adapter; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.twoexample.adresslist.ContactInformation; import com.twoexample.adresslist.R; import java.util.List; /** * Created by 27837 on 2017/8/25. */ public class ContactAdapter extends RecyclerView.Adapter<ContactsViewHolder> implements View.OnClickListener,View.OnLongClickListener{ private List<Contacts> mContactsList; private Context mContext; private onItemClickListener monItemClickListener=null; private onItemLongClickListener monItemLongClickListener=null; public ContactAdapter(List<Contacts> contactsList,Context context){ mContactsList=contactsList; mContext=context; } //定义item监听事件接口 public static interface onItemClickListener{ void onItemClick(View view,int position); } public static interface onItemLongClickListener{ void onItemLongClick(View view,int position); } //对外提供接口 //短点击 public void setOnItemClickListener(onItemClickListener listener){ this.monItemClickListener=listener; } //长点击 public void setOnItemLongClickListener(onItemLongClickListener listener){ this.monItemLongClickListener=listener; } //将点击事件转移给外部调用者 //第一种短点击 @Override public void onClick(View view) { if (monItemClickListener!=null) { monItemClickListener.onItemClick(view,(int)view.getTag()); } } //第二种 长点击 @Override public boolean onLongClick(View view) { if (monItemLongClickListener!=null) { monItemLongClickListener.onItemLongClick(view,(int)view.getTag()); } return true; } @Override public ContactsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.recycler_item,parent,false); view.setOnClickListener(this); view.setOnLongClickListener(this); final ContactsViewHolder holder=new ContactsViewHolder(view); return holder; } @Override public void onBindViewHolder(ContactsViewHolder holder, int position) { Contacts contacts=mContactsList.get(position); holder.contactImage.setImageBitmap(contacts.getBitmap()); holder.contactName.setText(contacts.getName()); holder.contactView.setTag(position); } @Override public int getItemCount() { return mContactsList.size(); } }
29.032258
134
0.715556
4cb997e5409d18f6a15c832e0eab8fec46c32ff8
93
package com.reactnativenavigation.utils; public interface Task<T> { void run(T param); }
18.6
40
0.741935
31514b79a25c30dfba4a186546257b7a4bdafc07
497
package com.polidea.rxandroidble.internal; import com.polidea.rxandroidble.RxBleDevice; import com.polidea.rxandroidble.internal.connection.Connector; import com.polidea.rxandroidble.internal.connection.ConnectorImpl; import bleshadow.dagger.Binds; import bleshadow.dagger.Module; @Module abstract class DeviceModuleBinder { @Binds abstract Connector bindConnector(ConnectorImpl rxBleConnectionConnector); @Binds abstract RxBleDevice bindDevice(RxBleDeviceImpl rxBleDevice); }
27.611111
77
0.828974
ee78bcc083f684700e83faaa799eeb53c1930b9b
320
package com.github.zxh0.luago.compiler.ast.exps; import com.github.zxh0.luago.compiler.ast.Exp; import lombok.Getter; import lombok.Setter; @Getter @Setter public class FloatExp extends Exp { private double val; public FloatExp(int line, Double val) { setLine(line); this.val = val; } }
16.842105
48
0.69375
04eca30da8655662cfa52b59113138ae37ea8435
420
package org.conceptoriented.bistro.formula; import org.conceptoriented.bistro.core.Table; public class FormulaExp4j extends FormulaBase { public FormulaExp4j() { super(); isExp4j = true; isEvalex = false; } public FormulaExp4j(String formula, Table table) { super(formula, table); isExp4j = true; isEvalex = false; this.translate(formula); } }
21
54
0.635714
187932e37d9194951b95d93b6c60bce586cf7535
2,329
// 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.doris.statistics; import org.apache.doris.analysis.AnalyzeStmt; import com.google.common.collect.Maps; import org.glassfish.jersey.internal.guava.Sets; import java.util.List; import java.util.Map; import java.util.Set; import com.clearspring.analytics.util.Lists; /* Used to store statistics job info, including job status, progress, etc. */ public class StatisticsJob { public enum JobState { PENDING, SCHEDULING, RUNNING, FINISHED, CANCELLED } private long id = -1; private JobState jobState = JobState.PENDING; // optional // to be collected table stats private List<Long> tableId = Lists.newArrayList(); // to be collected column stats private Map<Long, List<String>> tableIdToColumnName = Maps.newHashMap(); private Map<String, String> properties; // end private List<StatisticsTask> taskList = Lists.newArrayList(); public long getId() { return id; } /* AnalyzeStmt: Analyze t1(c1), t2 StatisticsJob: tableId [t1, t2] tableIdToColumnName <t1, [c1]> <t2, [c1,c2,c3]> */ public static StatisticsJob fromAnalyzeStmt(AnalyzeStmt analyzeStmt) { // TODO return new StatisticsJob(); } public Set<Long> relatedTableId() { Set<Long> relatedTableId = Sets.newHashSet(); relatedTableId.addAll(tableId); relatedTableId.addAll(tableIdToColumnName.keySet()); return relatedTableId; } }
29.1125
76
0.692143
94818d04b91716b4079eefb1013bd33488d93c51
341
package fun.mortnon.flyrafter.mvn.resolver; import org.apache.maven.model.Resource; import java.io.File; import java.util.List; import java.util.Map; /** * @author Moon Wu * @date 2021/5/14 */ public interface ResourcesResolver { Map<String,Object> resolveResource(File file); Object resolveResource(File file,String key); }
17.947368
50
0.739003
ba77ea868969d328f723a99591456644424be92c
153
package com.vinners.cube_vishwakarma.core.dowloader; import java.io.File; public interface DownloadSuccessListener { void onComplete(File file); }
19.125
52
0.797386
abe2b74b7f6cab4d62361e1c2d016c076ba0a605
3,259
package com.freeter.modules.pc.entity; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableName; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.lang.reflect.InvocationTargetException; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import org.apache.commons.beanutils.BeanUtils; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.enums.FieldFill; /** * * 数据库通用操作实体类(普通增删改查) * @author xuchen * @email [email protected] * @date 2018-06-20 15:47:02 */ @TableName("t_pc") @ApiModel(value = "Pc") public class PcEntity<T> implements Serializable { private static final long serialVersionUID = 1L; public PcEntity() { } public PcEntity(T t) { try { BeanUtils.copyProperties(this, t); } catch (IllegalAccessException | InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * */ @TableId @ApiModelProperty(value = "",hidden = true) private Long pcId; /** * 电脑名称 */ @NotBlank (message = "电脑名称不能为空") @ApiModelProperty(value = "电脑名称") private String pcName; /** * 标题 */ @ApiModelProperty(value = "标题") private String title; /** * 详情 */ @ApiModelProperty(value = "详情") private String detail; /** * 备注 */ @ApiModelProperty(value = "备注") private String remark; /** * 创建时间 */ @JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss") @DateTimeFormat @TableField(fill = FieldFill.INSERT) @ApiModelProperty(value = "创建时间",hidden = true) private Date createTime; /** * 创建人 */ @TableField(fill = FieldFill.INSERT) @ApiModelProperty(value = "创建人",hidden = true) private String createBy; /** * 设置: */ public void setPcId(Long pcId) { this.pcId = pcId; } /** * 获取: */ public Long getPcId() { return pcId; } /** * 设置:电脑名称 */ public void setPcName(String pcName) { this.pcName = pcName; } /** * 获取:电脑名称 */ public String getPcName() { return pcName; } /** * 设置:标题 */ public void setTitle(String title) { this.title = title; } /** * 获取:标题 */ public String getTitle() { return title; } /** * 设置:详情 */ public void setDetail(String detail) { this.detail = detail; } /** * 获取:详情 */ public String getDetail() { return detail; } /** * 设置:备注 */ public void setRemark(String remark) { this.remark = remark; } /** * 获取:备注 */ public String getRemark() { return remark; } /** * 设置:创建时间 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * 获取:创建时间 */ public Date getCreateTime() { return createTime; } /** * 设置:创建人 */ public void setCreateBy(String createBy) { this.createBy = createBy; } /** * 获取:创建人 */ public String getCreateBy() { return createBy; } }
17.062827
74
0.660939
ebc358d8eb23df769d4a7f32bd916b8fe1c1c5f8
168
/* * Copyright (c) 2013 Villu Ruusmann */ package org.jpmml.evaluator; public interface HasConfidence extends ResultFeature { Double getConfidence(String value); }
18.666667
54
0.767857
e16f0d0c541fa75fd700dc78d730c02611a426b9
1,432
/* * Copyright 2014 lorislab.org. * * 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.lorislab.tower.treasure.service; import org.kohsuke.MetaInfServices; import org.lorislab.treasure.api.service.SecretKeyService; /** * The treasure secret key service. * * @author Andrej Petras */ @MetaInfServices public class SecretKeyServiceImpl implements SecretKeyService { /** * The key system property. */ private final static String PROP_KEY = "org.lorislab.tower.treasure.secret.key"; /** * The key. */ private static final char[] DEFAULT_KEY = {116, 111, 119, 101, 114}; /** * {@inheritDoc } */ @Override public char[] getSecretKey() { char[] result = DEFAULT_KEY; String tmp = System.getProperty(PROP_KEY); if (tmp != null) { result = tmp.toCharArray(); } return result; } }
26.518519
84
0.664804
cebebe1be29e6636db2915275a2022ff7b164f8d
2,370
/** * */ package org.flowninja.security.web.spring.types; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.flowninja.persistence.generic.types.AdminRecord; import org.flowninja.types.generic.AdminKey; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; /** * @author rainer * */ public class AdminUserDetails implements UserDetails { /** * */ private static final long serialVersionUID = -7586737046870410107L; private AdminRecord record; public AdminUserDetails() { } public AdminUserDetails(AdminRecord record) { this.record = record; } /* (non-Javadoc) * @see org.springframework.security.core.userdetails.UserDetails#getAuthorities() */ @Override public Collection<? extends GrantedAuthority> getAuthorities() { Set<SimpleGrantedAuthority> authorities = new HashSet<SimpleGrantedAuthority>(); record.getAuthorities().forEach((n) -> authorities.add(new SimpleGrantedAuthority(n.getAuthority()))); return authorities; } /* (non-Javadoc) * @see org.springframework.security.core.userdetails.UserDetails#getPassword() */ @Override public String getPassword() { return null; } /* (non-Javadoc) * @see org.springframework.security.core.userdetails.UserDetails#getUsername() */ @Override public String getUsername() { return record.getUserName(); } /* (non-Javadoc) * @see org.springframework.security.core.userdetails.UserDetails#isAccountNonExpired() */ @Override public boolean isAccountNonExpired() { return true; } /* (non-Javadoc) * @see org.springframework.security.core.userdetails.UserDetails#isAccountNonLocked() */ @Override public boolean isAccountNonLocked() { return true; } /* (non-Javadoc) * @see org.springframework.security.core.userdetails.UserDetails#isCredentialsNonExpired() */ @Override public boolean isCredentialsNonExpired() { return true; } /* (non-Javadoc) * @see org.springframework.security.core.userdetails.UserDetails#isEnabled() */ @Override public boolean isEnabled() { return true; } /** * @return the record */ public AdminRecord getRecord() { return record; } public AdminKey getKey() { return record.getKey(); } }
21.944444
104
0.740084
0d0431c26f2c7e7f875c2e404069398244c4433a
1,108
package org.openstack.android.summit.common.data_access; import org.openstack.android.summit.common.utils.RealmFactory; import org.powermock.api.mockito.PowerMockito; import io.realm.Realm; import io.realm.RealmObject; import io.realm.RealmQuery; import io.realm.RealmResults; import static org.mockito.Mockito.mock; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; /** * Created by Claudio Redi on 1/13/2016. */ public class MockSupport { public static Realm mockRealm() { mockStatic(Realm.class); Realm mockRealm = PowerMockito.mock(Realm.class); when(RealmFactory.getSession()).thenReturn(mockRealm); return mockRealm; } @SuppressWarnings("unchecked") public static <T extends RealmObject> RealmQuery<T> mockRealmQuery() { return mock(RealmQuery.class); } @SuppressWarnings("unchecked") public static <T extends RealmObject> RealmResults<T> mockRealmResults() { mockStatic(RealmResults.class); return mock(RealmResults.class); } }
27.7
78
0.734657
59ba10b6a575e0eac7b8cd6f698b4147b4fdd9cb
254
package com.callhh.nn.listener; import android.view.View; public interface OnRecyclerViewItemClick { /** * 列表 行点击 点击事件 * @param childView 视图控件 * @param position 某行下标位置 */ void onItemClick(View childView, int position); }
16.933333
51
0.669291
fd18242fc5f997d9179dbd87d8b829993d391d88
6,912
/* * * * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package org.opensingular.form.view; import org.junit.Before; import org.junit.Test; import org.opensingular.form.SDictionary; import org.opensingular.form.SInstance; import org.opensingular.form.SType; import org.opensingular.form.STypeComposite; import org.opensingular.form.STypeSimple; import org.opensingular.form.type.core.STypeDate; import org.opensingular.form.type.core.STypeInteger; import org.opensingular.form.type.core.STypeString; import org.opensingular.form.type.country.brazil.STypeCEP; import org.opensingular.form.type.country.brazil.STypeCNPJ; import org.opensingular.form.type.country.brazil.STypeCPF; import org.opensingular.lib.commons.base.SingularUtil; import static org.junit.Assert.assertEquals; public class TestViewMapperRegistry { private ViewMapperRegistry<String> mapper; @Before public void setUp() { mapper = new ViewMapperRegistry<>(); } @Test public void testBuscaHierarquiaTipo() { mapper.register(STypeSimple.class, () -> "A"); mapper.register(STypeString.class, () -> "B"); mapper.register(STypeDate.class, () -> "C"); assertResult("A", STypeInteger.class, SView.class); assertResult("B", STypeString.class, SView.class); assertResult("B", STypeCPF.class, SView.class); assertResult("C", STypeDate.class, SView.class); assertResult(null, STypeComposite.class, SView.class); } @Test public void testBuscaEspecificoDepoisDefault() { mapper.register(STypeSimple.class, () -> "A"); mapper.register(STypeString.class, () -> "B"); mapper.register(STypeString.class, ViewX.class, () -> "D"); mapper.register(STypeCNPJ.class, ViewX.class, () -> "E"); mapper.register(STypeDate.class, () -> "C"); assertResult("A", STypeInteger.class, SView.class); assertResult("B", STypeString.class, SView.class); assertResult("B", STypeCPF.class, SView.class); assertResult("B", STypeCNPJ.class, SView.class); assertResult("C", STypeDate.class, SView.class); assertResult(null, STypeComposite.class, SView.class); assertResult("A", STypeInteger.class, ViewX.class); assertResult("D", STypeString.class, ViewX.class); assertResult("D", STypeCPF.class, ViewX.class); assertResult("E", STypeCNPJ.class, ViewX.class); assertResult("C", STypeDate.class, ViewX.class); assertResult(null, STypeComposite.class, ViewX.class); assertResult("A", STypeInteger.class, ViewY.class); assertResult("B", STypeString.class, ViewY.class); assertResult("B", STypeCPF.class, ViewY.class); assertResult("B", STypeCNPJ.class, ViewY.class); assertResult("C", STypeDate.class, ViewY.class); assertResult(null, STypeComposite.class, ViewY.class); } @Test public void testAceitarViewDerivada() { mapper.register(STypeSimple.class, () -> "A"); mapper.register(STypeString.class, () -> "B"); mapper.register(STypeString.class, ViewY.class, () -> "D"); mapper.register(STypeCNPJ.class, ViewY.class, () -> "E"); mapper.register(STypeDate.class, () -> "C"); assertResult("A", STypeInteger.class, SView.class); assertResult("B", STypeString.class, SView.class); assertResult("B", STypeCPF.class, SView.class); assertResult("B", STypeCNPJ.class, SView.class); assertResult("C", STypeDate.class, SView.class); assertResult(null, STypeComposite.class, SView.class); assertResult("A", STypeInteger.class, ViewX.class); assertResult("D", STypeString.class, ViewX.class); assertResult("D", STypeCPF.class, ViewX.class); assertResult("E", STypeCNPJ.class, ViewX.class); assertResult("C", STypeDate.class, ViewX.class); assertResult(null, STypeComposite.class, ViewX.class); assertResult("A", STypeInteger.class, ViewY.class); assertResult("D", STypeString.class, ViewY.class); assertResult("D", STypeCPF.class, ViewY.class); assertResult("E", STypeCNPJ.class, ViewY.class); assertResult("C", STypeDate.class, ViewY.class); assertResult(null, STypeComposite.class, ViewY.class); } @Test public void testPrioridadeDeAcordoComDerivacao() { mapper.register(STypeSimple.class, () -> "A"); mapper.register(STypeString.class, () -> "B"); mapper.register(STypeString.class, ViewY.class, () -> "C"); mapper.register(STypeString.class, ViewX.class, () -> "D"); // Adiciona em ondem invertida do anterior para ver se dá diferença mapper.register(STypeCNPJ.class, ViewX.class, () -> "E"); mapper.register(STypeCNPJ.class, ViewY.class, () -> "F"); mapper.register(STypeCEP.class, ViewY.class, () -> "G"); assertResult("B", STypeString.class, SView.class); assertResult("B", STypeCPF.class, SView.class); assertResult("B", STypeCNPJ.class, SView.class); assertResult("B", STypeCEP.class, SView.class); assertResult("D", STypeString.class, ViewX.class); assertResult("D", STypeCPF.class, ViewX.class); assertResult("E", STypeCNPJ.class, ViewX.class); assertResult("G", STypeCEP.class, ViewX.class); assertResult("C", STypeString.class, ViewY.class); assertResult("C", STypeCPF.class, ViewY.class); assertResult("F", STypeCNPJ.class, ViewY.class); assertResult("G", STypeCEP.class, ViewY.class); } public static class ViewX extends SView { } public static class ViewY extends ViewX { } private void assertResult(String expected, Class<? extends SType> type, Class<? extends SView> view) { try { SDictionary dictionary = SDictionary.create(); assertResult(expected, dictionary.newInstance(type), view.newInstance()); } catch (InstantiationException | IllegalAccessException e) { throw SingularUtil.propagate(e); } } private void assertResult(String expected, SInstance instance, SView view) { assertEquals(expected, mapper.getMapper(instance, view).orElse(null)); } }
40.899408
106
0.66739
d61891f57425d8a2cd3748c1341fb5d9702f6a63
1,286
package mtg.parsing; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import model.catalog.KeywordAbility; @Entity public class KeywordAbilityInstance extends Ability { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int keywordAbilityInstanceId; @ManyToOne protected KeywordAbility ability; protected String amountString; protected Float amount; protected String subject; public KeywordAbilityInstance(KeywordAbility ability) { super(); this.ability = ability; } private KeywordAbilityInstance() { super(); } public KeywordAbility getAbility() { return ability; } public void setAbility(KeywordAbility ability) { this.ability = ability; } public String getAmountString() { return amountString; } public void setAmountString(String amountString) { this.amountString = amountString; } public Float getAmount() { return amount; } public void setAmount(Float amount) { this.amount = amount; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } }
19.784615
57
0.722395
52bcf91e2bae08dc7f1f41c568a5f96c6064f03f
193
package com.github.kimmokarlsson.somvis.som.ui; public interface SomVisualizerMenuItems { public static final int ITEM_CODE_OPEN = 102; public static final int ITEM_CODE_EXIT = 103; }
24.125
49
0.782383
1e50d84f3376308e2c8b575c3e7f5e2a585b43f2
1,733
package com.gocardless.errors; import java.util.Map; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableMap; /** * Representation of an individual error handling an API request. */ public class ApiError { private static final Joiner JOINER = Joiner.on(" ").skipNulls(); private final String message; private final String reason; private final String field; private final String requestPointer; private final Map<String, String> links; private ApiError(String message, String reason, String field, String requestPointer, Map<String, String> links) { this.message = message; this.reason = reason; this.field = field; this.requestPointer = requestPointer; this.links = links; } /** * Returns a message describing the problem. */ public String getMessage() { return message; } /** * Returns a key identifying the reason for this error. */ public String getReason() { return reason; } /** * Returns the field that this error applies to. */ public String getField() { return field; } /** * Returns the request pointer, indicating the exact field of the request that * triggered the validation error */ public String getRequestPointer() { return requestPointer; } /** * Returns the IDs of related objects. */ public Map<String, String> getLinks() { if (links == null) { return ImmutableMap.of(); } return ImmutableMap.copyOf(links); } @Override public String toString() { return JOINER.join(field, message); } }
24.069444
88
0.623774
be25035014c14602e86d6f4ea0d36b970a0e1ead
1,161
package tk.deftech.goeurotest; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.List; /** * Does the data processing/conversion */ public class GeoProcessor { /** * Reads a json and maps to the model class * @param json Input json * @return Populated model */ public List<GeoInputData> parseJson(String json) { Gson gson = new Gson(); return gson.fromJson(json, new TypeToken<ArrayList<GeoInputData>>() { }.getType()); } /** * Mothod converts between the input and output model * @param input Input model (json) * @return Output model (CSV) */ public static GeoOutputData inputToOutput(GeoInputData input) { if (input == null) { return null; } GeoOutputData output = new GeoOutputData(input.get_id(), input.getName(), input.getType()); if(input.getGeo_position() != null) { output.setLatitude(input.getGeo_position().getLatitude()); output.setLongitude(input.getGeo_position().getLongitude()); } return output; } }
27.642857
99
0.633936
5e27f759487a6ac9317d8bd9844b95c842652a65
11,291
/* * 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.drill.test; import org.apache.commons.lang3.reflect.FieldUtils; import org.apache.drill.categories.SlowTest; import org.apache.drill.common.exceptions.UserException; import org.apache.drill.exec.ExecConstants; import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint; import org.apache.drill.exec.server.Drillbit; import org.apache.drill.exec.server.rest.WebServer; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TestRule; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.reflect.Field; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Path; import java.util.Collection; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @Category({SlowTest.class}) public class TestGracefulShutdown extends ClusterTest { @Rule public final TestRule TIMEOUT = TestTools.getTimeoutRule(120_000); @BeforeClass public static void setUpTestData() throws Exception { for (int i = 0; i < 300; i++) { setupFile(i); } } private static ClusterFixtureBuilder builderWithEnabledWebServer() { return builderWithEnabledPortHunting() .configProperty(ExecConstants.HTTP_ENABLE, true) .configProperty(ExecConstants.HTTP_PORT_HUNT, true) .configProperty(ExecConstants.SLICE_TARGET, 10); } private static ClusterFixtureBuilder builderWithEnabledPortHunting() { return ClusterFixture.builder(dirTestWatcher) .configProperty(ExecConstants.DRILL_PORT_HUNT, true) .configProperty(ExecConstants.GRACE_PERIOD, 500) .configProperty(ExecConstants.ALLOW_LOOPBACK_ADDRESS_BINDING, true); } /* Start multiple drillbits and then shutdown a drillbit. Query the online endpoints and check if the drillbit still exists. */ @Test public void testOnlineEndPoints() throws Exception { String[] drillbits = {"db1", "db2", "db3"}; ClusterFixtureBuilder builder = builderWithEnabledPortHunting() .withLocalZk() .withBits(drillbits); try (ClusterFixture cluster = builder.build()) { Drillbit drillbit = cluster.drillbit("db2"); int zkRefresh = drillbit.getContext().getConfig().getInt(ExecConstants.ZK_REFRESH); DrillbitEndpoint drillbitEndpoint = drillbit.getRegistrationHandle().getEndPoint(); cluster.closeDrillbit("db2"); while (true) { Collection<DrillbitEndpoint> drillbitEndpoints = cluster.drillbit() .getContext() .getClusterCoordinator() .getOnlineEndPoints(); if (!drillbitEndpoints.contains(drillbitEndpoint)) { // Success return; } Thread.sleep(zkRefresh); } } } /* Test shutdown through RestApi */ @Test public void testRestApi() throws Exception { String[] drillbits = {"db1", "db2", "db3"}; ClusterFixtureBuilder builder = builderWithEnabledWebServer() .withLocalZk() .withBits(drillbits); QueryBuilder.QuerySummaryFuture listener; final String sql = "select * from dfs.root.`.`"; try (ClusterFixture cluster = builder.build(); ClientFixture client = cluster.clientFixture()) { Drillbit drillbit = cluster.drillbit("db1"); int port = drillbit.getWebServerPort(); int zkRefresh = drillbit.getContext().getConfig().getInt(ExecConstants.ZK_REFRESH); listener = client.queryBuilder().sql(sql).futureSummary(); URL url = new URL("http://localhost:" + port + "/gracefulShutdown"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } while (!listener.isDone()) { Thread.sleep(100L); } if (waitAndAssertDrillbitCount(cluster, zkRefresh, drillbits.length)) { return; } Assert.fail("Timed out"); } } /* Test default shutdown through RestApi */ @Test public void testRestApiShutdown() throws Exception { String[] drillbits = {"db1", "db2", "db3"}; ClusterFixtureBuilder builder = builderWithEnabledWebServer().withLocalZk().withBits(drillbits); QueryBuilder.QuerySummaryFuture listener; final String sql = "select * from dfs.root.`.`"; try (ClusterFixture cluster = builder.build(); final ClientFixture client = cluster.clientFixture()) { Drillbit drillbit = cluster.drillbit("db1"); int port = drillbit.getWebServerPort(); int zkRefresh = drillbit.getContext().getConfig().getInt(ExecConstants.ZK_REFRESH); listener = client.queryBuilder().sql(sql).futureSummary(); while (!listener.isDone()) { Thread.sleep(100L); } URL url = new URL("http://localhost:" + port + "/shutdown"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } if (waitAndAssertDrillbitCount(cluster, zkRefresh, drillbits.length)) { return; } Assert.fail("Timed out"); } } @Test // DRILL-6912 public void testDrillbitWithSamePortContainsShutdownThread() throws Exception { ClusterFixtureBuilder fixtureBuilder = ClusterFixture.builder(dirTestWatcher) .withLocalZk() .configProperty(ExecConstants.ALLOW_LOOPBACK_ADDRESS_BINDING, true) .configProperty(ExecConstants.INITIAL_USER_PORT, QueryTestUtil.getFreePortNumber(31170, 300)) .configProperty(ExecConstants.INITIAL_BIT_PORT, QueryTestUtil.getFreePortNumber(31180, 300)); try (ClusterFixture fixture = fixtureBuilder.build(); Drillbit drillbitWithSamePort = new Drillbit(fixture.config(), fixtureBuilder.configBuilder().getDefinitions(), fixture.serviceSet())) { // Assert preconditions : // 1. First drillbit instance should be started normally // 2. Second instance startup should fail, because ports are occupied by the first one assertNotNull("First drillbit instance should be initialized", fixture.drillbit()); try { drillbitWithSamePort.run(); fail("Invocation of 'drillbitWithSamePort.run()' should throw UserException"); } catch (UserException e) { assertThat(e.getMessage(), containsString("RESOURCE ERROR: Drillbit could not bind to port")); // Ensure that drillbit with failed startup may be safely closed assertNotNull("Drillbit.gracefulShutdownThread shouldn't be null, otherwise close() may throw NPE (if so, check suppressed exception).", drillbitWithSamePort.getGracefulShutdownThread()); } } } @Test // DRILL-7056 public void testDrillbitTempDir() throws Exception { File originalDrillbitTempDir; ClusterFixtureBuilder fixtureBuilder = ClusterFixture.builder(dirTestWatcher).withLocalZk() .configProperty(ExecConstants.ALLOW_LOOPBACK_ADDRESS_BINDING, true) .configProperty(ExecConstants.INITIAL_USER_PORT, QueryTestUtil.getFreePortNumber(31170, 300)) .configProperty(ExecConstants.INITIAL_BIT_PORT, QueryTestUtil.getFreePortNumber(31180, 300)); try (ClusterFixture fixture = fixtureBuilder.build(); Drillbit twinDrillbitOnSamePort = new Drillbit(fixture.config(), fixtureBuilder.configBuilder().getDefinitions(), fixture.serviceSet())) { // Assert preconditions : // 1. First drillbit instance should be started normally // 2. Second instance startup should fail, because ports are occupied by the first one Drillbit originalDrillbit = fixture.drillbit(); assertNotNull("First drillbit instance should be initialized", originalDrillbit); originalDrillbitTempDir = getWebServerTempDirPath(originalDrillbit); assertTrue("First drillbit instance should have a temporary Javascript dir initialized", originalDrillbitTempDir.exists()); try { twinDrillbitOnSamePort.run(); fail("Invocation of 'twinDrillbitOnSamePort.run()' should throw UserException"); } catch (UserException userEx) { assertThat(userEx.getMessage(), containsString("RESOURCE ERROR: Drillbit could not bind to port")); } } // Verify deletion assertFalse("First drillbit instance should have a temporary Javascript dir deleted", originalDrillbitTempDir.exists()); } private File getWebServerTempDirPath(Drillbit drillbit) throws IllegalAccessException { Field webServerField = FieldUtils.getField(drillbit.getClass(), "webServer", true); WebServer webServerHandle = (WebServer) FieldUtils.readField(webServerField, drillbit, true); return webServerHandle.getOrCreateTmpJavaScriptDir(); } private boolean waitAndAssertDrillbitCount(ClusterFixture cluster, int zkRefresh, int bitsNum) throws InterruptedException { while (true) { Collection<DrillbitEndpoint> drillbitEndpoints = cluster.drillbit() .getContext() .getClusterCoordinator() .getAvailableEndpoints(); if (drillbitEndpoints.size() == bitsNum - 1) { return true; } Thread.sleep(zkRefresh); } } private static void setupFile(int file_num) throws Exception { String file = "employee" + file_num + ".json"; Path path = dirTestWatcher.getRootDir().toPath().resolve(file); StringBuilder stringBuilder = new StringBuilder(); int rowsCount = 7; try (BufferedReader reader = new BufferedReader(new InputStreamReader(TestGracefulShutdown.class.getResourceAsStream("/employee.json")))) { for (int i = 0; i < rowsCount; i++) { stringBuilder.append(reader.readLine()); } } String content = stringBuilder.toString(); try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(path.toFile(), true)))) { out.println(content); } } }
40.325
144
0.711806
a53ce82e746d58f71e11785a8eac4ea9b8a8cf17
1,356
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package com.viacaoCalango.models; import java.util.HashSet; /** * * @author Lucas */ public class Onibus { //- id private String modelo; private String placa; private int qntAssentos; private String tipoAssento; private HashSet<String> paradas = new HashSet<String>(); public Onibus(String modelo, String placa, int qntAssentos, String tipoAssento) { this.modelo = modelo; this.placa = placa; this.qntAssentos = qntAssentos; this.tipoAssento = tipoAssento; } public String getModelo() { return modelo; } public void setModelo(String modelo) { this.modelo = modelo; } public String getPlaca() { return placa; } public void setPlaca(String placa) { this.placa = placa; } public int getQntAssentos() { return qntAssentos; } public void setQntAssentos(int qntAssentos) { this.qntAssentos = qntAssentos; } public String getTipoAssento() { return tipoAssento; } public void setTipoAssento(String tipoOnibus) { this.tipoAssento = tipoOnibus; } }
21.1875
101
0.646755
2c5020e525f6f417a9995e0de04f2c908d2c0279
752
public class Solution { public int maximalSquare(char[][] matrix) { if (matrix.length == 0 || matrix[0].length == 0) return 0; int m = matrix.length, n = matrix[0].length; int[][] dp = new int[m+1][n+1]; for (int i = 0; i <= m; i++) { dp[i][0] = 0; } for (int i = 0; i <= n; i++) { dp[0][i] = 0; } int max = 0; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (matrix[i-1][j-1] == '1') { dp[i][j] = Math.min(dp[i-1][j-1], Math.min(dp[i-1][j], dp[i][j-1])) + 1; max = Math.max(max, dp[i][j]); } } } return max * max; } }
31.333333
92
0.359043
489c7e2c78dec800cfe0c88696a46d05ba1033f3
7,450
package net.thevpc.nuts.runtime.standalone.io.path; import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.standalone.xtra.glob.GlobUtils; import java.util.*; import java.util.regex.Pattern; public class DirectoryScanner { private NutsPath initialPattern; // private String root; // private String patternString; // private Pattern pattern; private PathPart[] parts; // private DirectoryScannerFS fs; private NutsSession session; public DirectoryScanner(NutsPath pattern,NutsSession session) { this.initialPattern = pattern.toAbsolute().normalize(); this.session = session; parts = buildParts(initialPattern); } public static String escape(String s){ StringBuilder sb=new StringBuilder(); for (char c : s.toCharArray()) { switch (c){ case '\\': case '*': case '?':{ sb.append('\\').append(c); break; } default:{ sb.append(c); break; } } } return sb.toString(); } private static boolean containsWildcard(String name){ char[] patternChars = name.toCharArray(); for (char c : patternChars) { if (c == '*' || c == '?') { return true; } } return false; } private static PathPart[] buildParts(NutsPath initialPattern) { List<PathPart> parts = new ArrayList<>(); NutsPath h=initialPattern; while(h!=null){ String name = h.getName(); if (containsWildcard(name)) { if (name.contains("**")) { parts.add(0,new SubPathWildCardPathPart(name)); } else { parts.add(0,new NameWildCardPathPart(name)); } } else { parts.add(0,new PlainPathPart(name)); } NutsPath p = h.getParent(); if(p==h){ h=null; }else{ h=p; } } return parts.toArray(new PathPart[0]); } @Override public String toString() { return initialPattern.toString(); } public NutsPath[] toArray() { return stream().toArray(NutsPath[]::new); } public NutsStream<NutsPath> stream() { return stream(null, parts, 0); } private NutsStream<NutsPath> stream(NutsPath r, PathPart[] parts, int from) { for (int i = from; i < parts.length; i++) { if (parts[i] instanceof PlainPathPart) { if (r == null) { r = initialPattern.getRoot(); } if (r == null) { r=NutsPath.of(((PlainPathPart) parts[i]).value,session); }else { r = r.resolve(((PlainPathPart) parts[i]).value); } if(!r.exists()){ return NutsStream.ofEmpty(session); } } else if (parts[i] instanceof NameWildCardPathPart) { NameWildCardPathPart w = (NameWildCardPathPart) parts[i]; if (r == null) { r = initialPattern.getRoot(); } if (r == null) { return NutsStream.ofEmpty(session); } NutsStream<NutsPath> t = r.list().filter(x -> w.matchesName(x.getName()),"getName"); if (parts.length - i - 1 == 0) { return t; } else { int i0 = i; NutsFunction<NutsPath, NutsStream<NutsPath>> f = NutsFunction.of(x -> stream(x, parts, i0 + 1),"subStream"); return t.flatMap((NutsFunction) f); } } else if (parts[i] instanceof SubPathWildCardPathPart) { SubPathWildCardPathPart w = (SubPathWildCardPathPart) parts[i]; if (r == null) { r = initialPattern.getRoot(); } NutsStream<NutsPath> t = new SubPathWildCardPathPartIterator(w, r).stream(); if (parts.length - i - 1 == 0) { return t; } else { int i0 = i; NutsFunction<NutsPath, NutsStream<NutsPath>> f = NutsFunction.of(x -> stream(x, parts, i0 + 1),"subStream"); return t.flatMap((NutsFunction) f).distinct(); } } else { throw new NutsIllegalArgumentException(session,NutsMessage.cstyle("unsupported %s",parts[i])); } } if (r == null) { return NutsStream.ofSingleton(initialPattern.getRoot(),session); } return NutsStream.ofSingleton(r,session); } private static class PathPart { } private static class PlainPathPart extends PathPart { String value; public PlainPathPart(String value) { this.value = value; } @Override public String toString() { return "Plain{" + value + '}'; } } private static class NameWildCardPathPart extends PathPart { String value; Pattern pattern; public NameWildCardPathPart(String value) { this.value = value; this.pattern = GlobUtils.glob(value,"/\\"); } public boolean matchesName(String name) { return pattern.matcher(name).matches(); } @Override public String toString() { return "Name{" + value + '}'; } } private static class SubPathWildCardPathPart extends PathPart { String value; Pattern pattern; public SubPathWildCardPathPart(String value) { this.value = value; this.pattern = GlobUtils.glob(value,"/\\"); } public boolean matchesSubPath(NutsPath subPath) { return pattern.matcher(subPath.toString()).matches(); } @Override public String toString() { return "Path{" + value + '}'; } } private class SubPathWildCardPathPartIterator implements Iterator<NutsPath> { private final Stack<NutsPath> stack=new Stack<>(); private final SubPathWildCardPathPart w; NutsPath last; NutsPath root; public SubPathWildCardPathPartIterator(SubPathWildCardPathPart w, NutsPath root) { stack.push(root); this.w = w; this.root = root; } @Override public boolean hasNext() { last = next0(); return last != null; } @Override public NutsPath next() { return last; } public NutsPath next0() { while (!stack.isEmpty()) { NutsPath pop = stack.pop(); NutsPath[] t = pop.list().toArray(NutsPath[]::new); for (int i = t.length - 1; i >= 0; i--) { stack.push(t[i]); } if (w.matchesSubPath(pop.toRelativePath(root))) { return pop; } } return null; } public NutsStream<NutsPath> stream() { return NutsStream.of(this,session); } } }
30.785124
128
0.500671
3313e17ea80ba365b208ab5832e0d9047d77d2e3
292
package org.haobtc.onekey.event; import androidx.annotation.StringRes; /** * @author * @date 12/10/20 */ public class RefreshViewEvent { private int id; public RefreshViewEvent(@StringRes int id) { this.id = id; } public int getId() { return id; } }
15.368421
48
0.619863
50e2495e60704c3d4c61adb6f8098f1d3c82e83c
1,587
package cz.cesnet.meta.accounting.server.service; import cz.cesnet.meta.accounting.server.data.PBSRecord; import cz.cesnet.meta.accounting.server.data.PbsRecordData; import cz.cesnet.meta.accounting.server.util.Page; import org.joda.time.LocalDate; import java.util.Date; import java.util.List; import java.util.Map; public interface PbsRecordManager { List<String> saveRecords(List<PBSRecord> records, String hostname); Page getPbsRecordsForUserId(long userId, Map<String, Object> criteria, Integer pageNumber, Integer defaultPageSize, Integer pageSize, String sortColumn, Boolean ascending); PbsRecordData getPbsRecordForIdString(String id); Page getPbsRecordsForUserId(long userId, int number, Integer pageNumber, Integer defaultPageSize, Integer pageSize, String sortColumn, Boolean ascending); Page getUserjobStats(Date fromDate, Date toDate, Integer pageNumber, Integer defaultPageSize, Integer pageSize, String sortColumn, Boolean ascending); LocalDate getLocalDateOfFirstPbsRecord(); Page getAllPbsRecords(int number, Integer pageNumber, Integer defaultPageSize, Integer pageSize, String sortColumn, Boolean ascending); Page getAllPbsRecords(Map<String, Object> searchCriteria, Integer pageNumber, Integer defaultPageSize, Integer pageSize, String sortColumn, Boolean ascending); Page getUserWalltimeStats(Date fromDate, Date toDate, Integer pageNumber, Integer defaultPageSizeShort, Integer pageSize, String sortColumn, Boolean ascending); }
46.676471
177
0.767486
97056c46624b690e6b9ebafe400f07ff0ae6f2df
1,761
package weather.models; /** * temp - температура * tempMin - минимальная температура * tempMax - максимальная температура * pressure - атмосферное давление на уровне моря по усолчанию * seaLevel - атмосферное давление на уронне моря * grndLevel - атмосферное давление на уровне земли * humidity - влажность * tempKf - внутренний параметр */ public class Main { private float temp; private float tempMin; private float tempMax; private float pressure; private float seaLevel; private float grndLevel; private int humidity; private float tempKf; public float getTemp() { return temp; } public void setTemp(float temp) { this.temp = temp; } public float getTempMin() { return tempMin; } public void setTempMin(float tempMin) { this.tempMin = tempMin; } public float getTempMax() { return tempMax; } public void setTempMax(float tempMax) { this.tempMax = tempMax; } public float getPressure() { return pressure; } public void setPressure(float pressure) { this.pressure = pressure; } public float getSeaLevel() { return seaLevel; } public void setSeaLevel(float seaLevel) { this.seaLevel = seaLevel; } public float getGrndLevel() { return grndLevel; } public void setGrndLevel(float grndLevel) { this.grndLevel = grndLevel; } public int getHumidity() { return humidity; } public void setHumidity(int humidity) { this.humidity = humidity; } public float getTempKf() { return tempKf; } public void setTempKf(float tempKf) { this.tempKf = tempKf; } }
19.566667
62
0.627484
88c93a741c36ee300076f850e47c26ad13c65424
1,375
package com.didi.carrera.console.dao.mapper; import com.didi.carrera.console.dao.model.ConsumeSubscription; import com.didi.carrera.console.dao.model.ConsumeSubscriptionCriteria; import java.util.List; import org.apache.ibatis.annotations.Param; public interface ConsumeSubscriptionMapper { long countByExample(ConsumeSubscriptionCriteria example); int deleteByExample(ConsumeSubscriptionCriteria example); int deleteByPrimaryKey(Long id); int insert(ConsumeSubscription record); int insertSelective(ConsumeSubscription record); List<ConsumeSubscription> selectByExampleWithBLOBs(ConsumeSubscriptionCriteria example); List<ConsumeSubscription> selectByExample(ConsumeSubscriptionCriteria example); ConsumeSubscription selectByPrimaryKey(Long id); int updateByExampleSelective(@Param("record") ConsumeSubscription record, @Param("example") ConsumeSubscriptionCriteria example); int updateByExampleWithBLOBs(@Param("record") ConsumeSubscription record, @Param("example") ConsumeSubscriptionCriteria example); int updateByExample(@Param("record") ConsumeSubscription record, @Param("example") ConsumeSubscriptionCriteria example); int updateByPrimaryKeySelective(ConsumeSubscription record); int updateByPrimaryKeyWithBLOBs(ConsumeSubscription record); int updateByPrimaryKey(ConsumeSubscription record); }
37.162162
133
0.818909
4b58178bbc0dbdbffdf2400d0f27e1f38cb6feb2
407
package com.wp.steps; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions( dryRun=false, strict=true, monochrome=false, features= {"src/test/resources/"}, glue = {"com.wp.steps"}, plugin= { "html:target/site/cucumber-html", "json:target/cucumber1.json"} ) public class Runner { }
16.28
37
0.70516
fa49563e0f2b349bdedb17f68dceadf45b26deb5
4,995
/* * 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.pig.test; import static org.apache.pig.PigServer.ExecType.MAPREDUCE; import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Iterator; import org.junit.Before; import org.junit.Test; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pig.PigServer; import org.apache.pig.builtin.PigStorage; import org.apache.pig.data.Tuple; import junit.framework.TestCase; public class TestInfixArithmetic extends TestCase { private final Log log = LogFactory.getLog(getClass()); private static int LOOP_COUNT = 1024; MiniCluster cluster = MiniCluster.buildCluster(); private PigServer pig; @Before @Override protected void setUp() throws Exception { pig = new PigServer(MAPREDUCE, cluster.getProperties()); } @Test public void testAdd() throws Throwable { File tmpFile = File.createTempFile("test", "txt"); PrintStream ps = new PrintStream(new FileOutputStream(tmpFile)); for(int i = 0; i < LOOP_COUNT; i++) { ps.println(i + ":" + i); } ps.close(); String query = "A = foreach (load 'file:" + Util.encodeEscape(tmpFile.toString()) + "' using " + PigStorage.class.getName() + "(':')) generate $0, $0 + $1, $1;"; log.info(query); pig.registerQuery(query); Iterator it = pig.openIterator("A"); tmpFile.delete(); while(it.hasNext()) { Tuple t = (Tuple)it.next(); Double first = t.getAtomField(0).numval(); Double second = t.getAtomField(1).numval(); assertTrue(second.equals(first + first)); } } @Test public void testSubtract() throws Throwable { File tmpFile = File.createTempFile("test", "txt"); PrintStream ps = new PrintStream(new FileOutputStream(tmpFile)); for(int i = 0; i < LOOP_COUNT; i++) { ps.println(i + ":" + i); } ps.close(); String query = "A = foreach (load 'file:" + Util.encodeEscape(tmpFile.toString()) + "' using " + PigStorage.class.getName() + "(':')) generate $0, $0 - $1, $1 ;"; log.info(query); pig.registerQuery(query); Iterator it = pig.openIterator("A"); tmpFile.delete(); while(it.hasNext()) { Tuple t = (Tuple)it.next(); Double second = t.getAtomField(1).numval(); assertTrue(second.equals(0.0)); } } @Test public void testMultiply() throws Throwable { File tmpFile = File.createTempFile("test", "txt"); PrintStream ps = new PrintStream(new FileOutputStream(tmpFile)); for(int i = 0; i < LOOP_COUNT; i++) { ps.println(i + ":" + i); } ps.close(); String query = "A = foreach (load 'file:" + Util.encodeEscape(tmpFile.toString()) + "' using " + PigStorage.class.getName() + "(':')) generate $0, $0 * $1, $1 ;"; log.info(query); pig.registerQuery(query); Iterator it = pig.openIterator("A"); tmpFile.delete(); while(it.hasNext()) { Tuple t = (Tuple)it.next(); Double first = t.getAtomField(0).numval(); Double second = t.getAtomField(1).numval(); assertTrue(second.equals(first * first)); } } @Test public void testDivide() throws Throwable { File tmpFile = File.createTempFile("test", "txt"); PrintStream ps = new PrintStream(new FileOutputStream(tmpFile)); for(int i = 1; i < LOOP_COUNT; i++) { ps.println(i + ":" + i); } ps.close(); String query = "A = foreach (load 'file:" + Util.encodeEscape(tmpFile.toString()) + "' using " + PigStorage.class.getName() + "(':')) generate $0, $0 / $1, $1;"; log.info(query); pig.registerQuery(query); Iterator it = pig.openIterator("A"); tmpFile.delete(); while(it.hasNext()) { Tuple t = (Tuple)it.next(); Double second = t.getAtomField(1).numval(); assertTrue(second.equals(1.0)); } } }
35.935252
170
0.606607
b7f89784a12a3a64d1759c4cda578949f74f773e
7,911
package de.uni_hildesheim.sse.qmApp.dialogs; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.InetAddress; import java.net.UnknownHostException; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import de.uni_hildesheim.sse.qmApp.WorkspaceUtils; import de.uni_hildesheim.sse.qmApp.runtime.Infrastructure; /** * Dialog asks the user for ip, port and creates a connection. * The ip and port are stored in the eclipse metadata. * * @author Niko Nowatzki */ public class ConnectDialog extends AbstractDialog implements Serializable { private static final long serialVersionUID = -2643903468689003241L; private Text platformIP; private Text platformPort; /** * Wraps ip and port of a connection. * * @author Nowatzki */ private static class ConnectionWrapper implements Serializable { private static final long serialVersionUID = 5587500725887648543L; private String ip; private String port; /** * Constructs a ConnectionsWrapper which wraps both an ip and a port. * @param ip connection ip. * @param port connection port. */ public ConnectionWrapper(String ip, String port) { this.ip = ip; this.port = port; } } /** * Default constructor. * @param parentShell The parent shell. */ public ConnectDialog(Shell parentShell) { super(parentShell); setBlockOnOpen(true); } /** * Creates a Label with the parameter composite as parent and the parameter text as text. * @param composite parent composite. * @param text text to set. * @return cLabel Label with set parent and text. */ private Label createLabel(final Composite composite, String text) { final Label cLabel = new Label(composite, SWT.BEGINNING); cLabel.setText(text); return cLabel; } /** * Creates a {@link Text} for a given {@link Composite}. * * @param composite * The given Composite * * @return the new {@link Text} */ private Text createTextField(final Composite composite) { Text newText = new Text(composite, SWT.FILL | SWT.BORDER); final GridData data = new GridData(); data.widthHint = 350; newText.setLayoutData(data); return newText; } @Override protected Control createDialogArea(Composite parent) { Composite panel = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(2, false); panel.setLayout(layout); createLabel(panel, "Host:"); platformIP = createTextField(panel); createLabel(panel, "Port:"); platformPort = createTextField(panel); String user = Infrastructure.getUserName(); createLabel(panel, ""); String text; if (null == user || 0 == user.length()) { text = "Will try a basic connection."; } else { text = "Will try an admin connection."; } createLabel(panel, text).setToolTipText("A basic connection allows receiving monitoring data / sending low " + "priority commands.\n An admin connection requires administrative permissions and a login into QM-IConf " + "via user name / password."); try { loadPluginSettings(); } catch (FileNotFoundException e) { } return panel; }; /** * Save the ip and port of a connection. * @param address ip address. * @param port connections port. */ private void savePluginSettings(InetAddress address, String port) { ConnectionWrapper wrapper = new ConnectionWrapper(address.getHostName(), port); try { File file = getConnectionSettingsFile(); FileOutputStream fileoutputstream = new FileOutputStream(file); ObjectOutputStream outputstream = new ObjectOutputStream(fileoutputstream); outputstream.writeObject(wrapper); outputstream.close(); } catch (IOException e) { Dialogs.showErrorDialog("Storing connection settings", e.getMessage()); } } /** * Returns the connection settings file. * * @return the connection settings file */ private File getConnectionSettingsFile() { return new File(WorkspaceUtils.getMetadataFolder(), "RuntimeConnection.ser"); } /** * Load the saved data into the TextrFields. * * @throws FileNotFoundException e If file with info about the latest connection is not found. */ private void loadPluginSettings() throws FileNotFoundException { ConnectionWrapper wrapper = null; try { File file = getConnectionSettingsFile(); if (file.exists()) { FileInputStream fileIn = new FileInputStream(file); ObjectInputStream in = new ObjectInputStream(fileIn); wrapper = (ConnectionWrapper) in.readObject(); in.close(); if (wrapper != null) { platformIP.setText(wrapper.ip); platformPort.setText(wrapper.port); } } } catch (IOException | ClassNotFoundException e) { Dialogs.showErrorDialog("Loading connection settings", e.getMessage()); } } @Override protected void createButtonsForButtonBar(Composite parent) { super.createButtonsForButtonBar(parent); Button ok = getButton(IDialogConstants.OK_ID); ok.setText("Connect"); ok.setEnabled(!Infrastructure.isConnected()); setButtonLayoutData(ok); } @Override protected void okPressed() { if (!Infrastructure.isConnected()) { try { if (!platformIP.isDisposed() && platformPort != null) { String platform = platformIP.getText(); InetAddress address = InetAddress.getByName(platform); int port = Integer.parseInt(platformPort.getText()); savePluginSettings(address, Integer.toString(port)); Infrastructure.connect(address, port); } } catch (UnknownHostException e) { Dialogs.showErrorDialog("Cannot connect to QM infrastructure", "Unknown host: " + e.getMessage()); } catch (SecurityException e) { Dialogs.showErrorDialog("Cannot connect to QM infrastructure", e.getMessage()); } catch (NumberFormatException e) { Dialogs.showErrorDialog("Port number", e.getMessage()); } catch (IOException e) { Dialogs.showErrorDialog("Cannot connect to QM infrastructure", e.getMessage()); } } super.okPressed(); } @Override protected Point getIntendedSize() { return new Point(600, 150); } @Override protected String getTitle() { return "Infrastructure connection"; } @Override protected Control createContents(Composite parent) { Control result = super.createContents(parent); getShell().pack(); return result; } }
34.246753
119
0.626343
096d84b6408b680512d56fb1f8dfd1020c3bf858
880
package cn.iocoder.mall.promotionservice.rpc.price; import cn.iocoder.common.framework.vo.CommonResult; import cn.iocoder.mall.promotion.api.rpc.price.PriceRpc; import cn.iocoder.mall.promotion.api.rpc.price.dto.PriceProductCalcReqDTO; import cn.iocoder.mall.promotion.api.rpc.price.dto.PriceProductCalcRespDTO; import cn.iocoder.mall.promotionservice.manager.price.PriceManager; import org.apache.dubbo.config.annotation.DubboService; import org.springframework.beans.factory.annotation.Autowired; import static cn.iocoder.common.framework.vo.CommonResult.success; @DubboService public class PriceRpcImpl implements PriceRpc { @Autowired private PriceManager priceManager; @Override public CommonResult<PriceProductCalcRespDTO> calcProductPrice(PriceProductCalcReqDTO calcReqDTO) { return success(priceManager.calcProductPrice(calcReqDTO)); } }
35.2
102
0.822727