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
6c35e2c19d78f08def59550bf9516b0224564d2d
271
package xyz.mizhoux.aop.domain; import xyz.mizhoux.aop.domain.base.BaseResponse; /** * 公共的业务响应 * * @author 之叶 * @date 2019/09/01 */ public class CommonResponse<T> extends BaseResponse<T> { private static final long serialVersionUID = 12820876732950294L; }
16.9375
68
0.723247
7e7f8330cc7cdb8171bbfa34af5699a6b71e915a
818
package JDK8.completableFuture; import java.util.concurrent.CompletableFuture; /**CompletableFuture可以将多个CompletableFuture进行组合。 * Created by chenyang on 2017/7/21. */ public class CompletableFutureCombine { public static Integer calc(Integer para){ System.out.println(Thread.currentThread().getName()); return para/2; } public static void main(String[] args) throws Exception{ CompletableFuture<Integer> intFuture=CompletableFuture.supplyAsync(()->calc(50)); CompletableFuture<Integer> intFuture2=CompletableFuture.supplyAsync(()->calc(25)); CompletableFuture<Void> fu= intFuture.thenCombine(intFuture2,(i,j)->(i+j)) .thenApply((str)->"\""+str+"\"") .thenAccept(System.out::println); fu.get(); } }
30.296296
90
0.663814
d41547e5a5d163ad23b6d471d7d7497ab0785023
3,827
/** * */ package com.unipg.hdfs2sql.controller; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.HashMap; import java.util.HashSet; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import com.unipg.givip.common.protoutils.HierarchyProtoBook.SingleWorkerTreeHierarchy; import com.unipg.givip.common.protoutils.HierarchyProtoBook.WorkerHierarchy; import com.unipg.hdfs2sql.db.ConnectionFactory; /** * @author maria * */ public class HierarchyReader/* implements Reader*/{ private HashMap<String, HashMap<String, HashSet<Integer>>> hierarchy; private HashMap<Integer, String> workerToHostMapping; private HashMap<String, String> hostToRackMapping; public HierarchyReader(){ hierarchy = new HashMap<String, HashMap<String, HashSet<Integer>>>(); workerToHostMapping = new HashMap<Integer, String>(); hostToRackMapping = new HashMap<String, String>(); } /* * */ public void getData(String folder, String jobID, FileSystem fileSystem) throws IOException, SQLException, NullPointerException{ InputStream inputStream = null; WorkerHierarchy parsedHierarchy = null; Path hpt = new Path(folder + File.separator + jobID + File.separator+"JobHierarchy"); inputStream = new FSDataInputStream(fileSystem.open(hpt).getWrappedStream()); parsedHierarchy = WorkerHierarchy.parseFrom(inputStream); HashSet<String> addedHostRackRelationships = new HashSet<String>(); for(SingleWorkerTreeHierarchy singleWorker: parsedHierarchy.getSingleWorkerTreeHierarchyList()){ String rack = singleWorker.getRack().substring(1); String host = singleWorker.getHostName(); int worker = singleWorker.getWorker(); workerToHostMapping.put(worker, host); hostToRackMapping.put(host, rack); if(!hierarchy.containsKey(rack)) hierarchy.put(rack, new HashMap<String, HashSet<Integer>>()); if(!hierarchy.get(rack).containsKey(host)) hierarchy.get(rack).put(host, new HashSet<Integer>()); hierarchy.get(rack).get(host).add(worker); //Insert Data Into MySql Database String insertIntoHierarchyQuery = "INSERT INTO hierarchy " + "VALUES(?,?,?)"; PreparedStatement st = null; PreparedStatement sp = null; try{ st = ConnectionFactory.prepare(insertIntoHierarchyQuery); st.setString(1, ""+singleWorker.getWorker()); st.setString(2, singleWorker.getHostName()); st.setInt(3, 0); //relation type --> 0 : worker-host st.executeUpdate(); }catch(SQLException se){ // ConnectionFactory.closeStatement(st); throw new SQLException(se); } finally { ConnectionFactory.closeStatement(st); } String builtName = singleWorker.getHostName() + "$_$" + singleWorker.getRack().substring(1); if(addedHostRackRelationships.contains(builtName)) continue; try{ sp = ConnectionFactory.prepare(insertIntoHierarchyQuery); sp.setString(1, singleWorker.getHostName()); sp.setString(2, singleWorker.getRack().substring(1)); sp.setInt(3, 1); //relation type --> 1 : host-rack sp.executeUpdate(); addedHostRackRelationships.add(builtName); }catch(SQLException se){ // ConnectionFactory.closeStatement(sp); throw new SQLException(se); } finally { sp.close(); } } } // // public HashMap<String, HashMap<String, HashSet<Integer>>> getHierarchy() { // return hierarchy; // } public HashMap<Integer, String> getWorkerToHostMapping() { return workerToHostMapping; } public HashMap<String, String> getHostToRackMapping() { return hostToRackMapping; } public HashMap<String, HashMap<String, HashSet<Integer>>> getHierarchy() { return hierarchy; } }
28.559701
129
0.725895
2abd9cf4cd4b157defd93cd86858ac8c894207d8
1,693
/* * Copyright 2013 Marcel Reutegger * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.people.mreutegg.jsinfonia; import java.util.Collections; import java.util.HashSet; import java.util.Set; public class Result { public static final Result OK = new Result(Vote.OK); public static final Result BAD_IO = new Result(Vote.BAD_IO); public static final Result BAD_FORCED = new Result(Vote.BAD_FORCED); public static final Result BAD_LOCK = new Result(Vote.BAD_LOCK); private final Set<ItemReference> failedCompares = new HashSet<>(); private final Vote vote; private Result(Vote vote) { this(vote, Collections.<ItemReference>emptyList()); } private Result(Vote vote, Iterable<ItemReference> failedCompares) { this.vote = vote; for (ItemReference ref : failedCompares) { this.failedCompares.add(ref); } } public Result(Iterable<ItemReference> failedCompares) { this(Vote.BAD_CMP, failedCompares); } public Vote getVote() { return vote; } public Iterable<ItemReference> getFailedCompares() { return failedCompares; } }
28.694915
75
0.699941
7fd2481ba109eb1d06db0e64b95ff3a4b1464744
2,753
package io.mateu.mdd.vaadin.navigation; import com.vaadin.ui.Component; import com.vaadin.ui.Window; import io.mateu.mdd.vaadin.components.ComponentWrapper; import io.mateu.mdd.vaadin.components.views.AbstractViewComponent; import io.mateu.mdd.vaadin.controllers.Controller; import java.util.Objects; import java.util.UUID; public class View implements com.vaadin.navigator.View { private String uuid = UUID.randomUUID().toString(); private Controller controller; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; View view = (View) o; return uuid.equals(view.uuid); } @Override public int hashCode() { return Objects.hash(uuid); } private final AbstractViewComponent viewComponent; private final ViewStack stack; private final Component component; private Window windowContainer; private boolean openNewWindow; public View(ViewStack stack, Component component) { this.stack = stack; this.component = component; if (component instanceof AbstractViewComponent) viewComponent = (AbstractViewComponent) component; else viewComponent = wrapComponent(null, component); if (component instanceof AbstractViewComponent) { ((AbstractViewComponent) component).setView(this); ((AbstractViewComponent)component).setStack(stack); } } public Controller getController() { return controller; } @Override public AbstractViewComponent getViewComponent() { return viewComponent; } public Component getComponent() { return component; } @Override public String toString() { return viewComponent.toString(); } private AbstractViewComponent wrapComponent(String title, Component component) { return new ComponentWrapper(title, component); } public void updateViewTitle(String newTitle) { viewComponent.updateViewTitle(newTitle); } public void setWindowContainer(Window w) { this.windowContainer = w; if (w != null) { int posx = stack.indexOf(this); if (posx > 0 && !w.equals(stack.get(posx - 1).getWindowContainer())) { viewComponent.setBackable(false); } } } public Window getWindowContainer() { return windowContainer; } public void setOpenNewWindow(boolean openNewWindow) { this.openNewWindow = openNewWindow; } public boolean isOpenNewWindow() { return openNewWindow; } public void setController(Controller c) { this.controller = c; } }
25.027273
106
0.660734
6aa86104fa5618a83f0f22a6042072618a75f837
3,287
package de.datenkraken.datenkrake.surveillance.sender; import android.location.LocationManager; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.apollographql.apollo.api.Mutation; import com.apollographql.apollo.api.Response; import com.apollographql.apollo.exception.ApolloException; import de.datenkraken.datenkrake.SubmitLocationCoordinatesMutation; import de.datenkraken.datenkrake.network.ITask; import de.datenkraken.datenkrake.network.clients.apollo.ApolloMutation; import de.datenkraken.datenkrake.surveillance.ISendProcessedData; import de.datenkraken.datenkrake.surveillance.ProcessedDataPacket; import de.datenkraken.datenkrake.surveillance.util.FormatUtil; import de.datenkraken.datenkrake.type.CreateLocationCoordinates; import de.datenkraken.datenkrake.type.LocationProviderType; import de.datenkraken.datenkrake.util.Callback; import java.util.ArrayList; import java.util.Date; import java.util.List; import timber.log.Timber; public class GPSLocationSender implements ISendProcessedData { public GPSLocationSender() { Timber.tag("GPS Sender"); } @Nullable @Override public ITask getTask(List<ProcessedDataPacket> packets, Callback callback) { List<CreateLocationCoordinates> list = new ArrayList<>(); for (ProcessedDataPacket packet : packets) { LocationProviderType providerType; switch (packet.getString("provider", "")) { case LocationManager.GPS_PROVIDER: providerType = LocationProviderType.GPS; break; case LocationManager.NETWORK_PROVIDER: providerType = LocationProviderType.NETWORK; break; default: providerType = LocationProviderType.$UNKNOWN; break; } list.add(CreateLocationCoordinates.builder() .timestamp(FormatUtil.formatDate(new Date(packet.getLong("timestamp", 0L)))) .altitude(packet.getDouble("altitude", 0.0)) .longitude(packet.getDouble("longitude", 0.0)) .latitude(packet.getDouble("latitude", 0.0)) .accuracy(packet.getFloat("accuracy", 0f)) .provider(providerType) .build()); } SubmitLocationCoordinatesMutation mutation = SubmitLocationCoordinatesMutation.builder() .list(list) .build(); return new ApolloMutation<SubmitLocationCoordinatesMutation.Data>() { @Override public Mutation getMutation() { return mutation; } @Override public void onFailure(@NonNull ApolloException e) { super.onFailure(e); callback.onFailure(); } @Override public void onResponse(@NonNull Response response) { super.onResponse(response); callback.onSuccess(); } }; } @Override public String getTaskId() { return SubmitLocationCoordinatesMutation.OPERATION_ID; } }
35.344086
96
0.632492
31027629d49de5c436751bb88c921da6fa4c5c0b
226
package eu.dareed.eplus.model.eso; import eu.dareed.eplus.model.Item; /** * @author <a href="mailto:kiril.tonev@kit.edu">Kiril Tonev</a> */ public interface ESOItem extends Item { Item getDictionaryItem(); }
20.545455
64
0.681416
d8d644ceeaff4513f2aaceb97ab382b351572dc1
1,722
package com.lhever.common.core.exception; /** * <p></p> * * @author wangzhankai 2020年04月27日 11:39 * @version V1.0 */ public class CommonException extends RuntimeException { /**错误码**/ private String errorCode; public CommonException(String msg) { super(msg); this.errorCode = CommonErrorCode.UNKNOWN_EXCEPTION.getCode(); } public CommonException(String msg, Throwable cause) { super(msg, cause); this.errorCode = CommonErrorCode.UNKNOWN_EXCEPTION.getCode(); } public CommonException(Throwable cause) { super(cause); this.errorCode = CommonErrorCode.UNKNOWN_EXCEPTION.getCode(); } public CommonException(String code, String msg){ super(msg); this.errorCode = code; } public CommonException(CommonErrorCode errorCode, String msg){ super(msg); this.errorCode = errorCode.getCode(); } public CommonException(CommonErrorCode errorCode){ super(errorCode.getMsg()); this.errorCode = errorCode.getCode(); } public CommonException(String code, String msg, Throwable throwable){ super(msg, throwable); this.errorCode = code; } public CommonException(CommonErrorCode errorCode, String msg, Throwable throwable){ super(msg, throwable); this.errorCode = errorCode.getCode(); } public CommonException(CommonErrorCode errorCode, Throwable throwable){ super(errorCode.getMsg(), throwable); this.errorCode = errorCode.getCode(); } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } }
23.27027
87
0.655052
4f71ed859b129f31eefa6d4b18b9ed7d0fdf3e23
1,826
package com.rebane2001.livemessage.mixin; import com.rebane2001.livemessage.gui.LivemessageGui; import com.rebane2001.livemessage.util.LivemessageUtil; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiNewChat; import net.minecraft.util.text.ITextComponent; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.regex.Matcher; import java.util.regex.Pattern; @Mixin(GuiNewChat.class) public abstract class GuiNewChatMixin extends Gui { @Inject(method = "printChatMessageWithOptionalDeletion", at = @At(value = "HEAD"), cancellable = true) public void printChatMessageWithOptionalDeletion(ITextComponent chatComponent, int chatLineId, CallbackInfo ci) { for (Pattern fromPattern : LivemessageUtil.FROM_PATTERNS) { Matcher matcher = fromPattern.matcher(chatComponent.getUnformattedText()); while (matcher.find()) { System.out.println("[Livemessage] New message from " + matcher.group(1) + " < " + matcher.group(2)); if (LivemessageGui.newMessage(matcher.group(1), matcher.group(2), false)) ci.cancel(); return; } } for (Pattern toPattern : LivemessageUtil.TO_PATTERNS) { Matcher matcher = toPattern.matcher(chatComponent.getUnformattedText()); while (matcher.find()) { System.out.println("[Livemessage] Message sent to " + matcher.group(1) + " > " + matcher.group(2)); if (LivemessageGui.newMessage(matcher.group(1), matcher.group(2), true)) ci.cancel(); return; } } } }
40.577778
117
0.676342
e1b103515d79cfef3c59867dbd8c8c63ea1f1efa
11,665
package com.ds365.erp.wms.pda.view.stock.putaway.activity; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.ds365.commons.AbstractServiceCallBack; import com.ds365.commons.AppConstants; import com.ds365.commons.AppGlobal; import com.ds365.commons.json.JacksonUtils; import com.ds365.commons.message.model.MessageDatebaseModel; import com.ds365.commons.utils.IntentUtils; import com.ds365.commons.utils.T; import com.ds365.commons.widget.CommonTitleTab; import com.ds365.commons.widget.CommonTitleTab.SelectChangeListener; import com.ds365.erp.pda.R; import com.ds365.erp.wms.pda.common.base.PdaConstants; import com.ds365.erp.wms.pda.common.headtitlebar.SubHeadTitleBar.ButtonClickListener; import com.ds365.erp.wms.pda.common.utils.GlobalUtils; import com.ds365.erp.wms.pda.common.utils.ListViewUtil; import com.ds365.erp.wms.pda.common.utils.RefreshListViewListener; import com.ds365.erp.wms.pda.common.utils.RefreshListViewListener.OnPullDownRefreshListener; import com.ds365.erp.wms.pda.model.putaway.PutawayTaskBillModel; import com.ds365.erp.wms.pda.model.putaway.PutawayTaskDetailModel; import com.ds365.erp.wms.pda.service.putaway.PutawayTaskBillService; import com.ds365.erp.wms.pda.view.common.activity.BasePdaMessageActivity; import com.ds365.erp.wms.pda.view.login.activity.LoginActivity; import com.ds365.erp.wms.pda.view.login.activity.MainActivity; import com.ds365.erp.wms.pda.view.stock.putaway.adapter.PutawayTaskBillAdapter; import com.ds365.erp.wms.pda.view.stock.putaway.adapter.PutawayTaskDetailForNotPutawayAdapter; import com.ds365.erp.wms.pda.view.stock.putaway.adapter.PutawayTaskDetailForNotPutawayAdapter.EditCallback; import com.ds365.erp.wms.pda.view.stock.putaway.adapter.PutawayTaskDetailForPutawayedAdapter; import com.handmark.pulltorefresh.library.PullToRefreshListView; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.RadioButton; import android.widget.TextView; public class PutawayTaskDetailActivity extends BasePdaMessageActivity implements EditCallback{ private CommonTitleTab titleTab; private PullToRefreshListView listView; private TextView putterNameValue, billCodeValue, relatedBillCodeValue; private TextView itemCountValue, unitQtyValue, minUnitQtyValue; private PutawayTaskDetailForNotPutawayAdapter putawayTaskDetailForNotPutawayAdapter; private PutawayTaskDetailForPutawayedAdapter putawayTaskDetailForPutawayedAdapter; private List<PutawayTaskDetailModel> putawayedDetails = new ArrayList<PutawayTaskDetailModel>(); private List<PutawayTaskDetailModel> notPutawayDetails = new ArrayList<PutawayTaskDetailModel>(); private List<String> titleTabList = new ArrayList<String>(); private Long billId; private static final String NOT_PUTAWAY_TAB_CODE="notPutaway"; private static final String PUTAWAYED_TAB_CODE="putawayed"; private String[] tabCodes={NOT_PUTAWAY_TAB_CODE,PUTAWAYED_TAB_CODE}; public static final String SER_KEY = PdaConstants.nextSerKey(); public static final String REQUEST_CODE = PdaConstants.nextRequestCode(); public static final String REQUEST_CODE_KEY = PutawayTaskDetailActivity.class.getName(); private PutawayTaskBillService putawayTaskBillService = new PutawayTaskBillService(); private int select = 0; private Integer editPosition; private MessageDatebaseModel message; private int resultCode; @Override protected int getContentViewId() { return R.layout.stock_putaway_task_detail; } @Override protected void initNavigation() { initHeadView(R.id.putawayTaskDetail_headerview, R.string.putaway_task_operation); } @Override protected void initActivityView() { itemCountValue = (TextView) findViewById(R.id.putawayTaskDetail_itemCount_value); unitQtyValue = (TextView) findViewById(R.id.putawayTaskDetail_unitQty_value); minUnitQtyValue = (TextView) findViewById(R.id.putawayTaskDetail_minUnitQty_value); billCodeValue = (TextView) findViewById(R.id.putawayTaskDetail_billCode_value); relatedBillCodeValue = (TextView) findViewById(R.id.putawayTaskDetail_relatedBillCode_value); listView = (PullToRefreshListView) findViewById(R.id.putawayTaskDetail_details); putterNameValue = (TextView) findViewById(R.id.putawayTaskDetail_putterName_Value); titleTab = (CommonTitleTab) findViewById(R.id.putawayTaskDetail_titleTab); titleTabList.add("待上架"); titleTabList.add("已上架"); PutawayTaskBillModel putawayTask = null; message = (MessageDatebaseModel) getIntent().getSerializableExtra(PdaConstants.MESSAGE_SER_KEY); if (message != null) { Map<String,String> map = JacksonUtils.stringToMap(message.getParamsMap()); billId = Long.valueOf(map.get(PdaConstants.MESSAGE_BILLID)); }else { //从上一页传过来 putawayTask= (PutawayTaskBillModel) getIntent().getSerializableExtra(PutawayTaskBillAdapter.SER_KEY); billId = putawayTask.getId(); putterNameValue.setText(putawayTask.getPutter().getName()); billCodeValue.setText(putawayTask.getBillCode()); relatedBillCodeValue.setText(putawayTask.getRelatedBillCode()); itemCountValue.setText(String.valueOf(putawayTask.getItemCount())); unitQtyValue.setText(String.valueOf(putawayTask.getUnitQty())); minUnitQtyValue.setText(String.valueOf(putawayTask.getMinUnitQty())); } putawayTaskDetailForNotPutawayAdapter = new PutawayTaskDetailForNotPutawayAdapter(context, notPutawayDetails,this); putawayTaskDetailForPutawayedAdapter = new PutawayTaskDetailForPutawayedAdapter(context, putawayedDetails); ListViewUtil.setOnPullDownListView(listView); } @Override protected void setListener() { listView.setOnRefreshListener(new RefreshListViewListener(listView, new OnPullDownRefreshListener() { @Override public void onPullDown() { onTabChange(); } })); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { int selectPosition = position-1; if (tabCodes[select].equals(NOT_PUTAWAY_TAB_CODE)) { Intent intent = new Intent(context, PutawayTaskDetailShowActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable(SER_KEY,notPutawayDetails.get(selectPosition)); intent.putExtras(bundle); intent.putExtra(REQUEST_CODE_KEY, REQUEST_CODE); startActivityForResult(intent, PdaConstants.PDA_REQUEST_CODE); }else if(tabCodes[select].equals(PUTAWAYED_TAB_CODE)){ Intent intent = new Intent(context, PutawayTaskDetailShowActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable(SER_KEY,putawayedDetails.get(selectPosition)); intent.putExtras(bundle); intent.putExtra(REQUEST_CODE_KEY, REQUEST_CODE); startActivityForResult(intent, PdaConstants.PDA_REQUEST_CODE); } } }); titleTab.setSelectChangeListener(new SelectChangeListener() { @Override public void onItemSelect(int selectValue, RadioButton selectRadioButton) { select = selectValue; onTabChange(); } }); titleTab.setData(titleTabList); } private void onTabChange(){ if (tabCodes[select].equals(NOT_PUTAWAY_TAB_CODE)) { listView.setAdapter(putawayTaskDetailForNotPutawayAdapter); searchPutawayTaskDetailForNotPutaway(); }else if (tabCodes[select].equals(PUTAWAYED_TAB_CODE)) { listView.setAdapter(putawayTaskDetailForPutawayedAdapter); searchPutawayTaskDetailForPutawayed(); } } private void searchPutawayTaskDetailForNotPutaway() { notPutawayDetails.clear(); putawayTaskBillService.searchPutawayTaskDetailForNotPutawayByBillId(billId, new AbstractServiceCallBack<List<PutawayTaskDetailModel>>(context) { @Override public void doSuccess(List<PutawayTaskDetailModel> result) { if (result != null && result.size() > 0) { notPutawayDetails.addAll(result); }else{ T.showShort(context, R.string.listview_no_more); } // 数据刷新后通知适配器更新UI putawayTaskDetailForNotPutawayAdapter.notifyDataSetChanged(); } }); } private void searchPutawayTaskDetailForPutawayed() { putawayedDetails.clear(); putawayTaskBillService.searchPutawayTaskDetailForPutawayedByBillId(billId, new AbstractServiceCallBack<List<PutawayTaskDetailModel>>(context) { @Override public void doSuccess(List<PutawayTaskDetailModel> result) { if (result != null && result.size() > 0) { putawayedDetails.addAll(result); }else{ T.showShort(context, R.string.listview_no_more); } putawayTaskDetailForPutawayedAdapter.notifyDataSetChanged(); } }); } private void searchPutawayTaskBillById() { putawayTaskBillService.searchPutawayTaskBillById(billId, new AbstractServiceCallBack<PutawayTaskBillModel>(context) { @Override public void doSuccess(PutawayTaskBillModel result) { if (result != null) { putterNameValue.setText(result.getPutter().getName()); billCodeValue.setText(result.getBillCode()); relatedBillCodeValue.setText(result.getRelatedBillCode()); itemCountValue.setText(String.valueOf(result.getItemCount())); unitQtyValue.setText(String.valueOf(result.getUnitQty())); minUnitQtyValue.setText(String.valueOf(result.getMinUnitQty())); }else{ T.showShort(context, R.string.listview_no_more); } } }); } @Override protected void onRestart() { super.onRestart(); if(resultCode == PutawayTaskDetailEditActivity.RESULT_CODE){ return; } onTabChange(); } @Override protected void onResume() { super.onResume(); if(message != null){ if(AppGlobal.dbManager!=null&&message.getReadFlag()==0){ AppGlobal.dbManager.updateMessageReadFlag(message.get_id()); } if(AppGlobal.TOKEN!=null&&!"".equals(AppGlobal.TOKEN)){ searchPutawayTaskBillById(); } } } @Override protected void checkUserLogin() { if(message != null){ if(GlobalUtils.getSessionUser()==null||AppGlobal.dbManager==null){ intentMainFlag = true; setHeadLeft(new ButtonClickListener() { @Override public void setLeftListener() { IntentUtils.startActivity(context,MainActivity.class); } }); IntentUtils.startActivity(context,LoginActivity.class,AppConstants.Intent_FROMMESSAGE_KEY,AppConstants.Intent_FROMMESSAGE_KEY,null); } } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){ if(intentMainFlag){ IntentUtils.startActivity(context,MainActivity.class); return true; } } return super.onKeyDown(keyCode, event); } @Override public void click(View v) { editPosition = (Integer) v.getTag(); IntentUtils.startActivityBySerialForResult(PutawayTaskDetailActivity.this, PutawayTaskDetailEditActivity.class, SER_KEY , notPutawayDetails.get(editPosition), PdaConstants.PDA_REQUEST_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (intent != null) { if (resultCode == PutawayTaskDetailEditActivity.RESULT_CODE) { this.resultCode = resultCode; PutawayTaskDetailModel putawayTaskDetail = (PutawayTaskDetailModel) intent.getSerializableExtra(PutawayTaskDetailEditActivity.SER_KEY); notPutawayDetails.set(editPosition, putawayTaskDetail); putawayTaskDetailForNotPutawayAdapter.notifyDataSetChanged(); } } } }
38.883333
139
0.775997
84fcfce84adb3df4e11e59bbdef86e1e4e859d14
6,184
package com.lengyue.frame_databinding.base; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.DrawableRes; import androidx.annotation.Nullable; import androidx.databinding.DataBindingUtil; import androidx.databinding.ViewDataBinding; import androidx.lifecycle.ViewModelProviders; import com.google.android.material.tabs.TabLayout; import com.google.gson.JsonSyntaxException; import com.lengyue.frame_databinding.R; import com.lengyue.frame_databinding.utils.ToastUtil; import com.lengyue.frame_databinding.views.CustomProgress; import com.lengyue.frame_databinding.bean.Resource; import com.lengyue.frame_databinding.network.NetWorkUtils; import com.trello.rxlifecycle2.components.support.RxFragment; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.ConnectException; import java.net.SocketTimeoutException; /** * @author linbin */ public abstract class BaseFragment<VM extends BaseViewModel, VDB extends ViewDataBinding> extends RxFragment { /** * 获取当前activity布局文件 */ protected abstract int getContentViewId(); /** * 处理逻辑业务 */ protected abstract void processLogic(Bundle savedInstanceState); public String getTitle(){ return ""; } @DrawableRes public int getIcon(){ return 0; } protected VM mViewModel; protected View mContentView; protected VDB binding; private CustomProgress dialog; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { // 避免多次从xml中加载布局文件 if (mContentView == null) { binding = DataBindingUtil.inflate(inflater, getContentViewId(), null, false); mContentView = binding.getRoot(); binding.setLifecycleOwner(this); createViewModel(); processLogic(savedInstanceState); } else { ViewGroup parent = (ViewGroup) mContentView.getParent(); if (parent != null) { parent.removeView(mContentView); } } return mContentView; } private void createViewModel() { if (mViewModel == null) { Class modelClass; Type type = getClass().getGenericSuperclass(); if (type instanceof ParameterizedType) { modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0]; } else { //如果没有指定泛型参数,则默认使用BaseViewModel modelClass = BaseViewModel.class; } mViewModel = (VM) ViewModelProviders.of(this).get(modelClass); mViewModel.setObjectLifecycleTransformer(bindToLifecycle()); } } protected void startActivity(Class classz){ Intent intent = new Intent(getActivity(), classz); startActivity(intent); } protected void startActivity(Class classz, Bundle bundle){ Intent intent = new Intent(getActivity(), classz); intent.putExtras(bundle); startActivity(intent); } protected void startActivityForResult(Class classz, Bundle bundle, int requestCode){ Intent intent = new Intent(getActivity(), classz); intent.putExtras(bundle); startActivityForResult(intent, requestCode); } protected void startActivityForResult(Class classz, int requestCode){ Intent intent = new Intent(getActivity(), classz); startActivityForResult(intent, requestCode); } public void showDialog(){ if (dialog == null) { dialog = CustomProgress.show(getActivity(), "", true, null); } if (!dialog.isShowing()) { dialog.show(); } } public void showDialog(String msg){ if (dialog == null) { dialog = CustomProgress.show(getActivity(), msg, true, null); } if (!dialog.isShowing()) { dialog.show(); } } public void hideDialog(){ if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } } public abstract class OnCallback<T> implements Resource.OnHandleCallback<T> { @Override public void onLoading(String msg) { if (dialog == null) { dialog = CustomProgress.show(getActivity(), "", true, null); } if (!TextUtils.isEmpty(msg)) { dialog.setMessage(msg); } if (!dialog.isShowing()) { dialog.show(); } } @Override public void onError(Throwable throwable) { if (!NetWorkUtils.isNetworkConnected(getContext())) { ToastUtil.showToast(getContext(),getContext().getResources().getString(R.string.result_network_error)); return; } if (throwable instanceof ConnectException) { ToastUtil.showToast(getContext(),getContext().getResources().getString(R.string.result_server_error)); } else if (throwable instanceof SocketTimeoutException) { ToastUtil.showToast(getContext(),getContext().getResources().getString(R.string.result_server_timeout)); } else if (throwable instanceof JsonSyntaxException) { ToastUtil.showToast(getContext(),getContext().getResources().getString(R.string.result_data_error)); } else { ToastUtil.showToast(getContext(),getContext().getResources().getString(R.string.result_empty_error)); } } @Override public void onFailure(String code, String msg) { ToastUtil.showToast(getContext(),msg); } @Override public void onCompleted() { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } } @Override public void onProgress(int percent, long total) { } } }
31.390863
120
0.634702
152eb7f8f6117081a97993b14730a82116ec4387
422
package cache; /** * cache/IOError.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from cache.idl * vendredi 11 avril 2014 17 h 24 CEST */ public final class IOError extends org.omg.CORBA.UserException { public IOError () { super(IOErrorHelper.id()); } // ctor public IOError (String $reason) { super(IOErrorHelper.id() + " " + $reason); } // ctor } // class IOError
16.230769
65
0.649289
397e430855996fe724de49bb337b16c626a73847
35,183
/* * Copyright LWJGL. All rights reserved. * License terms: http://lwjgl.org/license.php * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.vulkan; import java.nio.*; import org.lwjgl.*; import org.lwjgl.system.*; import static org.lwjgl.system.Checks.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.MemoryStack.*; /** * <a href="https://www.khronos.org/registry/vulkan/specs/1.0/man/html/VkSamplerCreateInfo.html">Khronos Reference Page</a><br> * <a href="https://www.khronos.org/registry/vulkan/specs/1.0-wsi_extensions/xhtml/vkspec.html#VkSamplerCreateInfo">Vulkan Specification</a> * * <p>Contains information about how a sampler object should be created.</p> * * <h5>Valid Usage</h5> * * <ul> * <li>{@code sType} <b>must</b> be {@link VK10#VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO STRUCTURE_TYPE_SAMPLER_CREATE_INFO}</li> * <li>{@code pNext} <b>must</b> be {@code NULL}</li> * <li>{@code flags} <b>must</b> be 0</li> * <li>{@code magFilter} <b>must</b> be a valid {@code VkFilter} value</li> * <li>{@code minFilter} <b>must</b> be a valid {@code VkFilter} value</li> * <li>{@code mipmapMode} <b>must</b> be a valid {@code VkSamplerMipmapMode} value</li> * <li>{@code addressModeU} <b>must</b> be a valid {@code VkSamplerAddressMode} value</li> * <li>{@code addressModeV} <b>must</b> be a valid {@code VkSamplerAddressMode} value</li> * <li>{@code addressModeW} <b>must</b> be a valid {@code VkSamplerAddressMode} value</li> * <li>The absolute value of {@code mipLodBias} <b>must</b> be less than or equal to {@link VkPhysicalDeviceLimits}{@code ::maxSamplerLodBias}</li> * <li>If the anisotropic sampling feature is not enabled, {@code anisotropyEnable} <b>must</b> be {@link VK10#VK_FALSE FALSE}</li> * <li>If {@code anisotropyEnable} is {@link VK10#VK_TRUE TRUE}, {@code maxAnisotropy} <b>must</b> be between {@code 1.0} and * {@link VkPhysicalDeviceLimits}{@code ::maxSamplerAnisotropy}, inclusive</li> * <li>If {@code unnormalizedCoordinates} is {@link VK10#VK_TRUE TRUE}, {@code minFilter} and {@code magFilter} <b>must</b> be equal</li> * <li>If {@code unnormalizedCoordinates} is {@link VK10#VK_TRUE TRUE}, {@code mipmapMode} <b>must</b> be {@link VK10#VK_SAMPLER_MIPMAP_MODE_NEAREST SAMPLER_MIPMAP_MODE_NEAREST}</li> * <li>If {@code unnormalizedCoordinates} is {@link VK10#VK_TRUE TRUE}, {@code minLod} and {@code maxLod} <b>must</b> be zero</li> * <li>If {@code unnormalizedCoordinates} is {@link VK10#VK_TRUE TRUE}, {@code addressModeU} and {@code addressModeV} <b>must</b> each be either {@link VK10#VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE} * or {@link VK10#VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER}</li> * <li>If {@code unnormalizedCoordinates} is {@link VK10#VK_TRUE TRUE}, {@code anisotropyEnable} <b>must</b> be {@link VK10#VK_FALSE FALSE}</li> * <li>If {@code unnormalizedCoordinates} is {@link VK10#VK_TRUE TRUE}, {@code compareEnable} <b>must</b> be {@link VK10#VK_FALSE FALSE}</li> * <li>If any of {@code addressModeU}, {@code addressModeV} or {@code addressModeW} are {@link VK10#VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER}, {@code borderColor} <b>must</b> * be a valid {@code VkBorderColor} value</li> * <li>If the VK_KHR_mirror_clamp_to_edge extension is not enabled, {@code addressModeU}, {@code addressModeV} and {@code addressModeW} <b>must not</b> be * {@link KHRSamplerMirrorClampToEdge#VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE}</li> * <li>If {@code compareEnable} is {@link VK10#VK_TRUE TRUE}, {@code compareOp} <b>must</b> be a valid {@code VkCompareOp} value</li> * </ul> * * <h3>Member documentation</h3> * * <ul> * <li>{@code sType} &ndash; the type of this structure. Must be: {@link VK10#VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO STRUCTURE_TYPE_SAMPLER_CREATE_INFO}</li> * <li>{@code pNext} &ndash; reserved for use by extensions</li> * <li>{@code flags} &ndash; reserved for future use</li> * <li>{@code magFilter} &ndash; the magnification filter to apply to lookups</li> * <li>{@code minFilter} &ndash; the minification filter to apply to lookups</li> * <li>{@code mipmapMode} &ndash; the mipmap filter to apply to lookups. One of:<br><table><tr><td>{@link VK10#VK_SAMPLER_MIPMAP_MODE_LINEAR SAMPLER_MIPMAP_MODE_LINEAR}</td><td>{@link VK10#VK_SAMPLER_MIPMAP_MODE_NEAREST SAMPLER_MIPMAP_MODE_NEAREST}</td></tr></table></li> * <li>{@code addressModeU} &ndash; the addressing mode for outside [0..1] range for U coordinate. One of:<br><table><tr><td>{@link VK10#VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER}</td><td>{@link VK10#VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE}</td></tr><tr><td>{@link VK10#VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT}</td><td>{@link KHRSamplerMirrorClampToEdge#VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE}</td></tr><tr><td>{@link VK10#VK_SAMPLER_ADDRESS_MODE_REPEAT SAMPLER_ADDRESS_MODE_REPEAT}</td></tr></table></li> * <li>{@code addressModeV} &ndash; the addressing mode for outside [0..1] range for V coordinate</li> * <li>{@code addressModeW} &ndash; the addressing mode for outside [0..1] range for W coordinate</li> * <li>{@code mipLodBias} &ndash; the bias to be added to mipmap LOD calculation and bias provided by image sampling functions in SPIR-V</li> * <li>{@code anisotropyEnable} &ndash; is {@link VK10#VK_TRUE TRUE} to enable anisotropic filtering, or {@link VK10#VK_FALSE FALSE} otherwise</li> * <li>{@code maxAnisotropy} &ndash; the anisotropy value clamp</li> * <li>{@code compareEnable} &ndash; is {@link VK10#VK_TRUE TRUE} to enable comparison against a reference value during lookups, or {@link VK10#VK_FALSE FALSE} otherwise</li> * <li>{@code compareOp} &ndash; the comparison function to apply to fetched data before filtering. One of:<br><table><tr><td>{@link VK10#VK_COMPARE_OP_ALWAYS COMPARE_OP_ALWAYS}</td><td>{@link VK10#VK_COMPARE_OP_EQUAL COMPARE_OP_EQUAL}</td><td>{@link VK10#VK_COMPARE_OP_GREATER COMPARE_OP_GREATER}</td><td>{@link VK10#VK_COMPARE_OP_GREATER_OR_EQUAL COMPARE_OP_GREATER_OR_EQUAL}</td></tr><tr><td>{@link VK10#VK_COMPARE_OP_LESS COMPARE_OP_LESS}</td><td>{@link VK10#VK_COMPARE_OP_LESS_OR_EQUAL COMPARE_OP_LESS_OR_EQUAL}</td><td>{@link VK10#VK_COMPARE_OP_NEVER COMPARE_OP_NEVER}</td><td>{@link VK10#VK_COMPARE_OP_NOT_EQUAL COMPARE_OP_NOT_EQUAL}</td></tr></table></li> * <li>{@code minLod} &ndash; the minimum value to which the computed level-of-detail value will be clamped</li> * <li>{@code maxLod} &ndash; the maximum value to which the computed level-of-detail value will be clamped</li> * <li>{@code borderColor} &ndash; the predefined border color to use. One of:<br><table><tr><td>{@link VK10#VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK BORDER_COLOR_FLOAT_OPAQUE_BLACK}</td><td>{@link VK10#VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE BORDER_COLOR_FLOAT_OPAQUE_WHITE}</td></tr><tr><td>{@link VK10#VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK BORDER_COLOR_FLOAT_TRANSPARENT_BLACK}</td><td>{@link VK10#VK_BORDER_COLOR_INT_OPAQUE_BLACK BORDER_COLOR_INT_OPAQUE_BLACK}</td></tr><tr><td>{@link VK10#VK_BORDER_COLOR_INT_OPAQUE_WHITE BORDER_COLOR_INT_OPAQUE_WHITE}</td><td>{@link VK10#VK_BORDER_COLOR_INT_TRANSPARENT_BLACK BORDER_COLOR_INT_TRANSPARENT_BLACK}</td></tr></table></li> * <li>{@code unnormalizedCoordinates} &ndash; controls whether to use unnormalized or normalized texel coordinates to address texels of the image</li> * </ul> * * <h3>Layout</h3> * * <pre><code>struct VkSamplerCreateInfo { VkStructureType sType; const void * pNext; VkSamplerCreateFlags flags; VkFilter magFilter; VkFilter minFilter; VkSamplerMipmapMode mipmapMode; VkSamplerAddressMode addressModeU; VkSamplerAddressMode addressModeV; VkSamplerAddressMode addressModeW; float mipLodBias; VkBool32 anisotropyEnable; float maxAnisotropy; VkBool32 compareEnable; VkCompareOp compareOp; float minLod; float maxLod; VkBorderColor borderColor; VkBool32 unnormalizedCoordinates; }</code></pre> */ public class VkSamplerCreateInfo extends Struct { /** The struct size in bytes. */ public static final int SIZEOF; public static final int ALIGNOF; /** The struct member offsets. */ public static final int STYPE, PNEXT, FLAGS, MAGFILTER, MINFILTER, MIPMAPMODE, ADDRESSMODEU, ADDRESSMODEV, ADDRESSMODEW, MIPLODBIAS, ANISOTROPYENABLE, MAXANISOTROPY, COMPAREENABLE, COMPAREOP, MINLOD, MAXLOD, BORDERCOLOR, UNNORMALIZEDCOORDINATES; static { Layout layout = __struct( __member(4), __member(POINTER_SIZE), __member(4), __member(4), __member(4), __member(4), __member(4), __member(4), __member(4), __member(4), __member(4), __member(4), __member(4), __member(4), __member(4), __member(4), __member(4), __member(4) ); SIZEOF = layout.getSize(); ALIGNOF = layout.getAlignment(); STYPE = layout.offsetof(0); PNEXT = layout.offsetof(1); FLAGS = layout.offsetof(2); MAGFILTER = layout.offsetof(3); MINFILTER = layout.offsetof(4); MIPMAPMODE = layout.offsetof(5); ADDRESSMODEU = layout.offsetof(6); ADDRESSMODEV = layout.offsetof(7); ADDRESSMODEW = layout.offsetof(8); MIPLODBIAS = layout.offsetof(9); ANISOTROPYENABLE = layout.offsetof(10); MAXANISOTROPY = layout.offsetof(11); COMPAREENABLE = layout.offsetof(12); COMPAREOP = layout.offsetof(13); MINLOD = layout.offsetof(14); MAXLOD = layout.offsetof(15); BORDERCOLOR = layout.offsetof(16); UNNORMALIZEDCOORDINATES = layout.offsetof(17); } VkSamplerCreateInfo(long address, ByteBuffer container) { super(address, container); } /** * Creates a {@link VkSamplerCreateInfo} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be * visible to the struct instance and vice versa. * * <p>The created instance holds a strong reference to the container object.</p> */ public VkSamplerCreateInfo(ByteBuffer container) { this(memAddress(container), checkContainer(container, SIZEOF)); } @Override public int sizeof() { return SIZEOF; } /** Returns the value of the {@code sType} field. */ public int sType() { return nsType(address()); } /** Returns the value of the {@code pNext} field. */ public long pNext() { return npNext(address()); } /** Returns the value of the {@code flags} field. */ public int flags() { return nflags(address()); } /** Returns the value of the {@code magFilter} field. */ public int magFilter() { return nmagFilter(address()); } /** Returns the value of the {@code minFilter} field. */ public int minFilter() { return nminFilter(address()); } /** Returns the value of the {@code mipmapMode} field. */ public int mipmapMode() { return nmipmapMode(address()); } /** Returns the value of the {@code addressModeU} field. */ public int addressModeU() { return naddressModeU(address()); } /** Returns the value of the {@code addressModeV} field. */ public int addressModeV() { return naddressModeV(address()); } /** Returns the value of the {@code addressModeW} field. */ public int addressModeW() { return naddressModeW(address()); } /** Returns the value of the {@code mipLodBias} field. */ public float mipLodBias() { return nmipLodBias(address()); } /** Returns the value of the {@code anisotropyEnable} field. */ public int anisotropyEnable() { return nanisotropyEnable(address()); } /** Returns the value of the {@code maxAnisotropy} field. */ public float maxAnisotropy() { return nmaxAnisotropy(address()); } /** Returns the value of the {@code compareEnable} field. */ public int compareEnable() { return ncompareEnable(address()); } /** Returns the value of the {@code compareOp} field. */ public int compareOp() { return ncompareOp(address()); } /** Returns the value of the {@code minLod} field. */ public float minLod() { return nminLod(address()); } /** Returns the value of the {@code maxLod} field. */ public float maxLod() { return nmaxLod(address()); } /** Returns the value of the {@code borderColor} field. */ public int borderColor() { return nborderColor(address()); } /** Returns the value of the {@code unnormalizedCoordinates} field. */ public int unnormalizedCoordinates() { return nunnormalizedCoordinates(address()); } /** Sets the specified value to the {@code sType} field. */ public VkSamplerCreateInfo sType(int value) { nsType(address(), value); return this; } /** Sets the specified value to the {@code pNext} field. */ public VkSamplerCreateInfo pNext(long value) { npNext(address(), value); return this; } /** Sets the specified value to the {@code flags} field. */ public VkSamplerCreateInfo flags(int value) { nflags(address(), value); return this; } /** Sets the specified value to the {@code magFilter} field. */ public VkSamplerCreateInfo magFilter(int value) { nmagFilter(address(), value); return this; } /** Sets the specified value to the {@code minFilter} field. */ public VkSamplerCreateInfo minFilter(int value) { nminFilter(address(), value); return this; } /** Sets the specified value to the {@code mipmapMode} field. */ public VkSamplerCreateInfo mipmapMode(int value) { nmipmapMode(address(), value); return this; } /** Sets the specified value to the {@code addressModeU} field. */ public VkSamplerCreateInfo addressModeU(int value) { naddressModeU(address(), value); return this; } /** Sets the specified value to the {@code addressModeV} field. */ public VkSamplerCreateInfo addressModeV(int value) { naddressModeV(address(), value); return this; } /** Sets the specified value to the {@code addressModeW} field. */ public VkSamplerCreateInfo addressModeW(int value) { naddressModeW(address(), value); return this; } /** Sets the specified value to the {@code mipLodBias} field. */ public VkSamplerCreateInfo mipLodBias(float value) { nmipLodBias(address(), value); return this; } /** Sets the specified value to the {@code anisotropyEnable} field. */ public VkSamplerCreateInfo anisotropyEnable(int value) { nanisotropyEnable(address(), value); return this; } /** Sets the specified value to the {@code maxAnisotropy} field. */ public VkSamplerCreateInfo maxAnisotropy(float value) { nmaxAnisotropy(address(), value); return this; } /** Sets the specified value to the {@code compareEnable} field. */ public VkSamplerCreateInfo compareEnable(int value) { ncompareEnable(address(), value); return this; } /** Sets the specified value to the {@code compareOp} field. */ public VkSamplerCreateInfo compareOp(int value) { ncompareOp(address(), value); return this; } /** Sets the specified value to the {@code minLod} field. */ public VkSamplerCreateInfo minLod(float value) { nminLod(address(), value); return this; } /** Sets the specified value to the {@code maxLod} field. */ public VkSamplerCreateInfo maxLod(float value) { nmaxLod(address(), value); return this; } /** Sets the specified value to the {@code borderColor} field. */ public VkSamplerCreateInfo borderColor(int value) { nborderColor(address(), value); return this; } /** Sets the specified value to the {@code unnormalizedCoordinates} field. */ public VkSamplerCreateInfo unnormalizedCoordinates(int value) { nunnormalizedCoordinates(address(), value); return this; } /** Initializes this struct with the specified values. */ public VkSamplerCreateInfo set( int sType, long pNext, int flags, int magFilter, int minFilter, int mipmapMode, int addressModeU, int addressModeV, int addressModeW, float mipLodBias, int anisotropyEnable, float maxAnisotropy, int compareEnable, int compareOp, float minLod, float maxLod, int borderColor, int unnormalizedCoordinates ) { sType(sType); pNext(pNext); flags(flags); magFilter(magFilter); minFilter(minFilter); mipmapMode(mipmapMode); addressModeU(addressModeU); addressModeV(addressModeV); addressModeW(addressModeW); mipLodBias(mipLodBias); anisotropyEnable(anisotropyEnable); maxAnisotropy(maxAnisotropy); compareEnable(compareEnable); compareOp(compareOp); minLod(minLod); maxLod(maxLod); borderColor(borderColor); unnormalizedCoordinates(unnormalizedCoordinates); return this; } /** Unsafe version of {@link #set(VkSamplerCreateInfo) set}. */ public VkSamplerCreateInfo nset(long struct) { memCopy(struct, address(), SIZEOF); return this; } /** * Copies the specified struct data to this struct. * * @param src the source struct * * @return this struct */ public VkSamplerCreateInfo set(VkSamplerCreateInfo src) { return nset(src.address()); } // ----------------------------------- /** Returns a new {@link VkSamplerCreateInfo} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */ public static VkSamplerCreateInfo malloc() { return create(nmemAlloc(SIZEOF)); } /** Returns a new {@link VkSamplerCreateInfo} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */ public static VkSamplerCreateInfo calloc() { return create(nmemCalloc(1, SIZEOF)); } /** Returns a new {@link VkSamplerCreateInfo} instance allocated with {@link BufferUtils}. */ public static VkSamplerCreateInfo create() { return new VkSamplerCreateInfo(BufferUtils.createByteBuffer(SIZEOF)); } /** Returns a new {@link VkSamplerCreateInfo} instance for the specified memory address or {@code null} if the address is {@code NULL}. */ public static VkSamplerCreateInfo create(long address) { return address == NULL ? null : new VkSamplerCreateInfo(address, null); } /** * Returns a new {@link VkSamplerCreateInfo.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static Buffer malloc(int capacity) { return create(nmemAlloc(capacity * SIZEOF), capacity); } /** * Returns a new {@link VkSamplerCreateInfo.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static Buffer calloc(int capacity) { return create(nmemCalloc(capacity, SIZEOF), capacity); } /** * Returns a new {@link VkSamplerCreateInfo.Buffer} instance allocated with {@link BufferUtils}. * * @param capacity the buffer capacity */ public static Buffer create(int capacity) { return new Buffer(BufferUtils.createByteBuffer(capacity * SIZEOF)); } /** * Create a {@link VkSamplerCreateInfo.Buffer} instance at the specified memory. * * @param address the memory address * @param capacity the buffer capacity */ public static Buffer create(long address, int capacity) { return address == NULL ? null : new Buffer(address, null, -1, 0, capacity, capacity); } // ----------------------------------- /** Returns a new {@link VkSamplerCreateInfo} instance allocated on the thread-local {@link MemoryStack}. */ public static VkSamplerCreateInfo mallocStack() { return mallocStack(stackGet()); } /** Returns a new {@link VkSamplerCreateInfo} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. */ public static VkSamplerCreateInfo callocStack() { return callocStack(stackGet()); } /** * Returns a new {@link VkSamplerCreateInfo} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate */ public static VkSamplerCreateInfo mallocStack(MemoryStack stack) { return create(stack.nmalloc(ALIGNOF, SIZEOF)); } /** * Returns a new {@link VkSamplerCreateInfo} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate */ public static VkSamplerCreateInfo callocStack(MemoryStack stack) { return create(stack.ncalloc(ALIGNOF, 1, SIZEOF)); } /** * Returns a new {@link VkSamplerCreateInfo.Buffer} instance allocated on the thread-local {@link MemoryStack}. * * @param capacity the buffer capacity */ public static Buffer mallocStack(int capacity) { return mallocStack(capacity, stackGet()); } /** * Returns a new {@link VkSamplerCreateInfo.Buffer} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. * * @param capacity the buffer capacity */ public static Buffer callocStack(int capacity) { return callocStack(capacity, stackGet()); } /** * Returns a new {@link VkSamplerCreateInfo.Buffer} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static Buffer mallocStack(int capacity, MemoryStack stack) { return create(stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity); } /** * Returns a new {@link VkSamplerCreateInfo.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static Buffer callocStack(int capacity, MemoryStack stack) { return create(stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity); } // ----------------------------------- /** Unsafe version of {@link #sType}. */ public static int nsType(long struct) { return memGetInt(struct + VkSamplerCreateInfo.STYPE); } /** Unsafe version of {@link #pNext}. */ public static long npNext(long struct) { return memGetAddress(struct + VkSamplerCreateInfo.PNEXT); } /** Unsafe version of {@link #flags}. */ public static int nflags(long struct) { return memGetInt(struct + VkSamplerCreateInfo.FLAGS); } /** Unsafe version of {@link #magFilter}. */ public static int nmagFilter(long struct) { return memGetInt(struct + VkSamplerCreateInfo.MAGFILTER); } /** Unsafe version of {@link #minFilter}. */ public static int nminFilter(long struct) { return memGetInt(struct + VkSamplerCreateInfo.MINFILTER); } /** Unsafe version of {@link #mipmapMode}. */ public static int nmipmapMode(long struct) { return memGetInt(struct + VkSamplerCreateInfo.MIPMAPMODE); } /** Unsafe version of {@link #addressModeU}. */ public static int naddressModeU(long struct) { return memGetInt(struct + VkSamplerCreateInfo.ADDRESSMODEU); } /** Unsafe version of {@link #addressModeV}. */ public static int naddressModeV(long struct) { return memGetInt(struct + VkSamplerCreateInfo.ADDRESSMODEV); } /** Unsafe version of {@link #addressModeW}. */ public static int naddressModeW(long struct) { return memGetInt(struct + VkSamplerCreateInfo.ADDRESSMODEW); } /** Unsafe version of {@link #mipLodBias}. */ public static float nmipLodBias(long struct) { return memGetFloat(struct + VkSamplerCreateInfo.MIPLODBIAS); } /** Unsafe version of {@link #anisotropyEnable}. */ public static int nanisotropyEnable(long struct) { return memGetInt(struct + VkSamplerCreateInfo.ANISOTROPYENABLE); } /** Unsafe version of {@link #maxAnisotropy}. */ public static float nmaxAnisotropy(long struct) { return memGetFloat(struct + VkSamplerCreateInfo.MAXANISOTROPY); } /** Unsafe version of {@link #compareEnable}. */ public static int ncompareEnable(long struct) { return memGetInt(struct + VkSamplerCreateInfo.COMPAREENABLE); } /** Unsafe version of {@link #compareOp}. */ public static int ncompareOp(long struct) { return memGetInt(struct + VkSamplerCreateInfo.COMPAREOP); } /** Unsafe version of {@link #minLod}. */ public static float nminLod(long struct) { return memGetFloat(struct + VkSamplerCreateInfo.MINLOD); } /** Unsafe version of {@link #maxLod}. */ public static float nmaxLod(long struct) { return memGetFloat(struct + VkSamplerCreateInfo.MAXLOD); } /** Unsafe version of {@link #borderColor}. */ public static int nborderColor(long struct) { return memGetInt(struct + VkSamplerCreateInfo.BORDERCOLOR); } /** Unsafe version of {@link #unnormalizedCoordinates}. */ public static int nunnormalizedCoordinates(long struct) { return memGetInt(struct + VkSamplerCreateInfo.UNNORMALIZEDCOORDINATES); } /** Unsafe version of {@link #sType(int) sType}. */ public static void nsType(long struct, int value) { memPutInt(struct + VkSamplerCreateInfo.STYPE, value); } /** Unsafe version of {@link #pNext(long) pNext}. */ public static void npNext(long struct, long value) { memPutAddress(struct + VkSamplerCreateInfo.PNEXT, value); } /** Unsafe version of {@link #flags(int) flags}. */ public static void nflags(long struct, int value) { memPutInt(struct + VkSamplerCreateInfo.FLAGS, value); } /** Unsafe version of {@link #magFilter(int) magFilter}. */ public static void nmagFilter(long struct, int value) { memPutInt(struct + VkSamplerCreateInfo.MAGFILTER, value); } /** Unsafe version of {@link #minFilter(int) minFilter}. */ public static void nminFilter(long struct, int value) { memPutInt(struct + VkSamplerCreateInfo.MINFILTER, value); } /** Unsafe version of {@link #mipmapMode(int) mipmapMode}. */ public static void nmipmapMode(long struct, int value) { memPutInt(struct + VkSamplerCreateInfo.MIPMAPMODE, value); } /** Unsafe version of {@link #addressModeU(int) addressModeU}. */ public static void naddressModeU(long struct, int value) { memPutInt(struct + VkSamplerCreateInfo.ADDRESSMODEU, value); } /** Unsafe version of {@link #addressModeV(int) addressModeV}. */ public static void naddressModeV(long struct, int value) { memPutInt(struct + VkSamplerCreateInfo.ADDRESSMODEV, value); } /** Unsafe version of {@link #addressModeW(int) addressModeW}. */ public static void naddressModeW(long struct, int value) { memPutInt(struct + VkSamplerCreateInfo.ADDRESSMODEW, value); } /** Unsafe version of {@link #mipLodBias(float) mipLodBias}. */ public static void nmipLodBias(long struct, float value) { memPutFloat(struct + VkSamplerCreateInfo.MIPLODBIAS, value); } /** Unsafe version of {@link #anisotropyEnable(int) anisotropyEnable}. */ public static void nanisotropyEnable(long struct, int value) { memPutInt(struct + VkSamplerCreateInfo.ANISOTROPYENABLE, value); } /** Unsafe version of {@link #maxAnisotropy(float) maxAnisotropy}. */ public static void nmaxAnisotropy(long struct, float value) { memPutFloat(struct + VkSamplerCreateInfo.MAXANISOTROPY, value); } /** Unsafe version of {@link #compareEnable(int) compareEnable}. */ public static void ncompareEnable(long struct, int value) { memPutInt(struct + VkSamplerCreateInfo.COMPAREENABLE, value); } /** Unsafe version of {@link #compareOp(int) compareOp}. */ public static void ncompareOp(long struct, int value) { memPutInt(struct + VkSamplerCreateInfo.COMPAREOP, value); } /** Unsafe version of {@link #minLod(float) minLod}. */ public static void nminLod(long struct, float value) { memPutFloat(struct + VkSamplerCreateInfo.MINLOD, value); } /** Unsafe version of {@link #maxLod(float) maxLod}. */ public static void nmaxLod(long struct, float value) { memPutFloat(struct + VkSamplerCreateInfo.MAXLOD, value); } /** Unsafe version of {@link #borderColor(int) borderColor}. */ public static void nborderColor(long struct, int value) { memPutInt(struct + VkSamplerCreateInfo.BORDERCOLOR, value); } /** Unsafe version of {@link #unnormalizedCoordinates(int) unnormalizedCoordinates}. */ public static void nunnormalizedCoordinates(long struct, int value) { memPutInt(struct + VkSamplerCreateInfo.UNNORMALIZEDCOORDINATES, value); } // ----------------------------------- /** An array of {@link VkSamplerCreateInfo} structs. */ public static final class Buffer extends StructBuffer<VkSamplerCreateInfo, Buffer> { /** * Creates a new {@link VkSamplerCreateInfo.Buffer} instance backed by the specified container. * * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided * by {@link VkSamplerCreateInfo#SIZEOF}, and its mark will be undefined. * * <p>The created buffer instance holds a strong reference to the container object.</p> */ public Buffer(ByteBuffer container) { super(container, container.remaining() / SIZEOF); } Buffer(long address, ByteBuffer container, int mark, int pos, int lim, int cap) { super(address, container, mark, pos, lim, cap); } @Override protected Buffer self() { return this; } @Override protected Buffer newBufferInstance(long address, ByteBuffer container, int mark, int pos, int lim, int cap) { return new Buffer(address, container, mark, pos, lim, cap); } @Override protected VkSamplerCreateInfo newInstance(long address) { return new VkSamplerCreateInfo(address, getContainer()); } @Override protected int sizeof() { return SIZEOF; } /** Returns the value of the {@code sType} field. */ public int sType() { return VkSamplerCreateInfo.nsType(address()); } /** Returns the value of the {@code pNext} field. */ public long pNext() { return VkSamplerCreateInfo.npNext(address()); } /** Returns the value of the {@code flags} field. */ public int flags() { return VkSamplerCreateInfo.nflags(address()); } /** Returns the value of the {@code magFilter} field. */ public int magFilter() { return VkSamplerCreateInfo.nmagFilter(address()); } /** Returns the value of the {@code minFilter} field. */ public int minFilter() { return VkSamplerCreateInfo.nminFilter(address()); } /** Returns the value of the {@code mipmapMode} field. */ public int mipmapMode() { return VkSamplerCreateInfo.nmipmapMode(address()); } /** Returns the value of the {@code addressModeU} field. */ public int addressModeU() { return VkSamplerCreateInfo.naddressModeU(address()); } /** Returns the value of the {@code addressModeV} field. */ public int addressModeV() { return VkSamplerCreateInfo.naddressModeV(address()); } /** Returns the value of the {@code addressModeW} field. */ public int addressModeW() { return VkSamplerCreateInfo.naddressModeW(address()); } /** Returns the value of the {@code mipLodBias} field. */ public float mipLodBias() { return VkSamplerCreateInfo.nmipLodBias(address()); } /** Returns the value of the {@code anisotropyEnable} field. */ public int anisotropyEnable() { return VkSamplerCreateInfo.nanisotropyEnable(address()); } /** Returns the value of the {@code maxAnisotropy} field. */ public float maxAnisotropy() { return VkSamplerCreateInfo.nmaxAnisotropy(address()); } /** Returns the value of the {@code compareEnable} field. */ public int compareEnable() { return VkSamplerCreateInfo.ncompareEnable(address()); } /** Returns the value of the {@code compareOp} field. */ public int compareOp() { return VkSamplerCreateInfo.ncompareOp(address()); } /** Returns the value of the {@code minLod} field. */ public float minLod() { return VkSamplerCreateInfo.nminLod(address()); } /** Returns the value of the {@code maxLod} field. */ public float maxLod() { return VkSamplerCreateInfo.nmaxLod(address()); } /** Returns the value of the {@code borderColor} field. */ public int borderColor() { return VkSamplerCreateInfo.nborderColor(address()); } /** Returns the value of the {@code unnormalizedCoordinates} field. */ public int unnormalizedCoordinates() { return VkSamplerCreateInfo.nunnormalizedCoordinates(address()); } /** Sets the specified value to the {@code sType} field. */ public VkSamplerCreateInfo.Buffer sType(int value) { VkSamplerCreateInfo.nsType(address(), value); return this; } /** Sets the specified value to the {@code pNext} field. */ public VkSamplerCreateInfo.Buffer pNext(long value) { VkSamplerCreateInfo.npNext(address(), value); return this; } /** Sets the specified value to the {@code flags} field. */ public VkSamplerCreateInfo.Buffer flags(int value) { VkSamplerCreateInfo.nflags(address(), value); return this; } /** Sets the specified value to the {@code magFilter} field. */ public VkSamplerCreateInfo.Buffer magFilter(int value) { VkSamplerCreateInfo.nmagFilter(address(), value); return this; } /** Sets the specified value to the {@code minFilter} field. */ public VkSamplerCreateInfo.Buffer minFilter(int value) { VkSamplerCreateInfo.nminFilter(address(), value); return this; } /** Sets the specified value to the {@code mipmapMode} field. */ public VkSamplerCreateInfo.Buffer mipmapMode(int value) { VkSamplerCreateInfo.nmipmapMode(address(), value); return this; } /** Sets the specified value to the {@code addressModeU} field. */ public VkSamplerCreateInfo.Buffer addressModeU(int value) { VkSamplerCreateInfo.naddressModeU(address(), value); return this; } /** Sets the specified value to the {@code addressModeV} field. */ public VkSamplerCreateInfo.Buffer addressModeV(int value) { VkSamplerCreateInfo.naddressModeV(address(), value); return this; } /** Sets the specified value to the {@code addressModeW} field. */ public VkSamplerCreateInfo.Buffer addressModeW(int value) { VkSamplerCreateInfo.naddressModeW(address(), value); return this; } /** Sets the specified value to the {@code mipLodBias} field. */ public VkSamplerCreateInfo.Buffer mipLodBias(float value) { VkSamplerCreateInfo.nmipLodBias(address(), value); return this; } /** Sets the specified value to the {@code anisotropyEnable} field. */ public VkSamplerCreateInfo.Buffer anisotropyEnable(int value) { VkSamplerCreateInfo.nanisotropyEnable(address(), value); return this; } /** Sets the specified value to the {@code maxAnisotropy} field. */ public VkSamplerCreateInfo.Buffer maxAnisotropy(float value) { VkSamplerCreateInfo.nmaxAnisotropy(address(), value); return this; } /** Sets the specified value to the {@code compareEnable} field. */ public VkSamplerCreateInfo.Buffer compareEnable(int value) { VkSamplerCreateInfo.ncompareEnable(address(), value); return this; } /** Sets the specified value to the {@code compareOp} field. */ public VkSamplerCreateInfo.Buffer compareOp(int value) { VkSamplerCreateInfo.ncompareOp(address(), value); return this; } /** Sets the specified value to the {@code minLod} field. */ public VkSamplerCreateInfo.Buffer minLod(float value) { VkSamplerCreateInfo.nminLod(address(), value); return this; } /** Sets the specified value to the {@code maxLod} field. */ public VkSamplerCreateInfo.Buffer maxLod(float value) { VkSamplerCreateInfo.nmaxLod(address(), value); return this; } /** Sets the specified value to the {@code borderColor} field. */ public VkSamplerCreateInfo.Buffer borderColor(int value) { VkSamplerCreateInfo.nborderColor(address(), value); return this; } /** Sets the specified value to the {@code unnormalizedCoordinates} field. */ public VkSamplerCreateInfo.Buffer unnormalizedCoordinates(int value) { VkSamplerCreateInfo.nunnormalizedCoordinates(address(), value); return this; } } }
54.631988
665
0.735156
7a37b5022fb21f599fa57a08ae03bd71907437ec
154
public interface Transform { public abstract void setSourceData(Object src); public abstract void calculate(); public abstract Object getResults(); }
19.25
48
0.785714
ef22239bc1a20051f9a20972e8ac41492abf76db
4,124
package ru.szhernovoy.carstore.controllers; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.FileCleanerCleanup; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileCleaningTracker; import ru.szhernovoy.carstore.dao.ImageDBManager; import ru.szhernovoy.carstore.dao.OrderDBManager; import ru.szhernovoy.carstore.model.Image; import ru.szhernovoy.carstore.model.Order; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.xml.bind.DatatypeConverter; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Created by szhernovoy on 14.01.2017. */ public class ImageServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(req); HttpSession session = req.getSession(false); Integer userId = (int)session.getAttribute("id_user"); Integer orderId = (int)session.getAttribute("currentOrder"); PrintWriter out = resp.getWriter(); JsonObject jsonObject = new JsonObject(); if(isMultipart && userId != -1 && orderId != -1){ // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Configure a repository (to ensure a secure temp location is used) ServletContext servletContext = this.getServletConfig().getServletContext(); FileCleaningTracker tracker = FileCleanerCleanup.getFileCleaningTracker(servletContext); factory.setFileCleaningTracker(tracker); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(req); for (FileItem imageFile : items){ byte[] imageByte = imageFile.get(); Order order = new Order(); order.setId(orderId); Image image = new Image(); image.setDataimage(imageByte); image.setOrder(order); new ImageDBManager().create(image); } jsonObject.addProperty("success", true); } catch (FileUploadException e) { jsonObject.addProperty("success", false); e.printStackTrace(); } } else { jsonObject.addProperty("success", false); } out.append(jsonObject.toString()); out.flush(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("image/jpeg"); PrintWriter out = resp.getWriter(); JsonArray jsonObject = new JsonArray(); int orderId = Integer.valueOf(req.getParameter("order")); Collection<Order> orderCollection = new OrderDBManager().get(orderId); List<Image> images = new ArrayList<>(); for(Order order : orderCollection){ images.addAll(order.getImageCarList()); } for(Image image : images){ jsonObject.add(String.format("data:image/jpeg;base64,%s",DatatypeConverter.printBase64Binary(image.getDataimage()))); } out.append(jsonObject.toString()); out.flush(); } }
38.542056
129
0.676043
3eff5749f624d12eb86a345ef84bf440ea28b835
2,633
package io.github.factoryfx.javafx.util; import javafx.animation.FadeTransition; import javafx.application.Platform; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.control.Label; import javafx.scene.control.ProgressIndicator; import javafx.scene.layout.BorderPane; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; import javafx.util.Duration; public class LongRunningActionExecutor { private final StackPane target=new StackPane(); public LongRunningActionExecutor() { } private Node createProgressIndicator() { ProgressIndicator indicator = new ProgressIndicator(); indicator.setMaxHeight(350); indicator.setMaxWidth(350); BorderPane borderPane = new BorderPane(); BorderPane.setMargin(indicator, new Insets(5)); borderPane.setCenter(indicator); borderPane.setStyle("-fx-background-color: rgba(230,230,230,0.7);"); return borderPane; } //** execute with progress dialog in background */ public void execute(final Runnable runnable, final String text) { Thread backgroundThread = new Thread(() -> { final Node progressIndicator = createProgressIndicator(); final Label label = new Label(text); try { Platform.runLater(() -> { target.getChildren().add(progressIndicator); FadeTransition ft = new FadeTransition(Duration.millis(500), progressIndicator); ft.setFromValue(0); ft.setToValue(1); ft.play(); label.setWrapText(true); target.getChildren().add(label); }); runnable.run(); } catch (Exception exception){ if (Thread.getDefaultUncaughtExceptionHandler()!=null){ Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(),exception); } else { exception.printStackTrace(); } } finally { Platform.runLater(() -> { target.getChildren().remove(progressIndicator); target.getChildren().remove(label); }); } }); backgroundThread.setDaemon(true); backgroundThread.start(); } public void execute(final Runnable runnable) { this.execute(runnable,""); } public Parent wrap(Pane root) { target.getChildren().add(root); return target; } }
34.644737
116
0.609191
50e0ebbdb4661b3d55515258a92d52101490d75f
7,864
package me.vilsol.nmswrapper.wraps.unparsed; import me.vilsol.nmswrapper.*; import me.vilsol.nmswrapper.reflections.*; import me.vilsol.nmswrapper.wraps.*; @ReflectiveClass(name = "EntityGuardian") public class NMSEntityGuardian extends NMSEntityMonster { public NMSEntityGuardian(Object nmsObject){ super(nmsObject); } public NMSEntityGuardian(NMSWorld world){ super("EntityGuardian", new Object[]{NMSWorld.class}, new Object[]{world}); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#E() */ @ReflectiveMethod(name = "E", types = {}) public void E(){ NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#a(net.minecraft.server.v1_9_R1.EntityGuardian, boolean) */ @ReflectiveMethod(name = "a", types = {NMSEntityGuardian.class, boolean.class}) public void a(NMSEntityGuardian entityGuardian, boolean b){ NMSWrapper.getInstance().exec(nmsObject, entityGuardian, b); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#b(net.minecraft.server.v1_9_R1.World) */ @ReflectiveMethod(name = "b", types = {NMSWorld.class}) public NMSNavigationAbstract b(NMSWorld world){ return new NMSNavigationAbstract(NMSWrapper.getInstance().exec(nmsObject, world)); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#bQ() */ @ReflectiveMethod(name = "bQ", types = {}) public int bQ(){ return (int) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#bR() */ @ReflectiveMethod(name = "bR", types = {}) public boolean bR(){ return (boolean) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#bo() */ @ReflectiveMethod(name = "bo", types = {}) public String bo(){ return (String) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#bp() */ @ReflectiveMethod(name = "bp", types = {}) public String bp(){ return (String) NMSWrapper.getInstance().exec(nmsObject); } /** * @see net.minecraft.server.v1_9_R1.EntityGuardian#canSpawn() */ @ReflectiveMethod(name = "canSpawn", types = {}) public boolean canSpawn(){ return (boolean) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#cm() */ @ReflectiveMethod(name = "cm", types = {}) public int cm(){ return (int) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#cp() */ @ReflectiveMethod(name = "cp", types = {}) public boolean cp(){ return (boolean) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#cq() */ @ReflectiveMethod(name = "cq", types = {}) public NMSEntityLiving cq(){ return new NMSEntityLiving(NMSWrapper.getInstance().exec(nmsObject)); } /** * @see net.minecraft.server.v1_9_R1.EntityGuardian#damageEntity(net.minecraft.server.v1_9_R1.DamageSource, float) */ @ReflectiveMethod(name = "damageEntity", types = {NMSDamageSource.class, float.class}) public boolean damageEntity(NMSDamageSource damageSource, float f){ return (boolean) NMSWrapper.getInstance().exec(nmsObject, damageSource, f); } /** * @see net.minecraft.server.v1_9_R1.EntityGuardian#dropDeathLoot(boolean, int) */ @ReflectiveMethod(name = "dropDeathLoot", types = {boolean.class, int.class}) public void dropDeathLoot(boolean b, int i){ NMSWrapper.getInstance().exec(nmsObject, b, i); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#g(float, float) */ @ReflectiveMethod(name = "g", types = {float.class, float.class}) public void g(float f, float f1){ NMSWrapper.getInstance().exec(nmsObject, f, f1); } /** * @see net.minecraft.server.v1_9_R1.EntityGuardian#getHeadHeight() */ @ReflectiveMethod(name = "getHeadHeight", types = {}) public float getHeadHeight(){ return (float) NMSWrapper.getInstance().exec(nmsObject); } /** * @see net.minecraft.server.v1_9_R1.EntityGuardian#getRareDrop() */ @ReflectiveMethod(name = "getRareDrop", types = {}) public void getRareDrop(){ NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#h() */ @ReflectiveMethod(name = "h", types = {}) public void h(){ NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#i(int) */ @ReflectiveMethod(name = "i", types = {int.class}) public void i(int i){ NMSWrapper.getInstance().exec(nmsObject, i); } /** * @see net.minecraft.server.v1_9_R1.EntityGuardian#initAttributes() */ @ReflectiveMethod(name = "initAttributes", types = {}) public void initAttributes(){ NMSWrapper.getInstance().exec(nmsObject); } /** * @see net.minecraft.server.v1_9_R1.EntityGuardian#isElder() */ @ReflectiveMethod(name = "isElder", types = {}) public boolean isElder(){ return (boolean) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#m() */ @ReflectiveMethod(name = "m", types = {}) public void m(){ NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#n() */ @ReflectiveMethod(name = "n", types = {}) public boolean n(){ return (boolean) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#n_() */ @ReflectiveMethod(name = "n_", types = {}) public boolean n_(){ return (boolean) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#q(float) */ @ReflectiveMethod(name = "q", types = {float.class}) public float q(float f){ return (float) NMSWrapper.getInstance().exec(nmsObject, f); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#s_() */ @ReflectiveMethod(name = "s_", types = {}) public boolean s_(){ return (boolean) NMSWrapper.getInstance().exec(nmsObject); } /** * @see net.minecraft.server.v1_9_R1.EntityGuardian#setElder(boolean) */ @ReflectiveMethod(name = "setElder", types = {boolean.class}) public void setElder(boolean b){ NMSWrapper.getInstance().exec(nmsObject, b); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#w() */ @ReflectiveMethod(name = "w", types = {}) public int w(){ return (int) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityGuardian#z() */ @ReflectiveMethod(name = "z", types = {}) public String z(){ return (String) NMSWrapper.getInstance().exec(nmsObject); } }
30.015267
118
0.630086
b409c96f9cdff2a4936bafa2ea09ef75db98575d
4,436
/* * Copyright (C) 2013-2015 RoboVM AB * * 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.bugvm.apple.foundation; /*<imports>*/ import java.io.*; import java.nio.*; import java.util.*; import com.bugvm.objc.*; import com.bugvm.objc.annotation.*; import com.bugvm.objc.block.*; import com.bugvm.rt.*; import com.bugvm.rt.annotation.*; import com.bugvm.rt.bro.*; import com.bugvm.rt.bro.annotation.*; import com.bugvm.rt.bro.ptr.*; import com.bugvm.apple.corefoundation.*; import com.bugvm.apple.uikit.*; import com.bugvm.apple.coretext.*; import com.bugvm.apple.coreanimation.*; import com.bugvm.apple.coredata.*; import com.bugvm.apple.coregraphics.*; import com.bugvm.apple.coremedia.*; import com.bugvm.apple.security.*; import com.bugvm.apple.dispatch.*; /*</imports>*/ /*<javadoc>*/ /*</javadoc>*/ /*<annotations>*//*</annotations>*/ /*<visibility>*/public/*</visibility>*/ class /*<name>*/NSFilePresenterAdapter/*</name>*/ extends /*<extends>*/NSObject/*</extends>*/ /*<implements>*/implements NSFilePresenter/*</implements>*/ { /*<ptr>*/ /*</ptr>*/ /*<bind>*/ /*</bind>*/ /*<constants>*//*</constants>*/ /*<constructors>*//*</constructors>*/ /*<properties>*/ @NotImplemented("presentedItemURL") public NSURL getPresentedItemURL() { return null; } @NotImplemented("presentedItemOperationQueue") public NSOperationQueue getPresentedItemOperationQueue() { return null; } @NotImplemented("primaryPresentedItemURL") public NSURL getPrimaryPresentedItemURL() { return null; } /*</properties>*/ /*<members>*//*</members>*/ /*<methods>*/ @NotImplemented("relinquishPresentedItemToReader:") public void relinquishPresentedItemToReader(@Block("(@Block)") VoidBlock1<Runnable> reader) {} @NotImplemented("relinquishPresentedItemToWriter:") public void relinquishPresentedItemToWriter(@Block("(@Block)") VoidBlock1<Runnable> writer) {} @NotImplemented("savePresentedItemChangesWithCompletionHandler:") public void savePresentedItemChanges(@Block VoidBlock1<NSError> completionHandler) {} @NotImplemented("accommodatePresentedItemDeletionWithCompletionHandler:") public void accommodatePresentedItemDeletion(@Block VoidBlock1<NSError> completionHandler) {} @NotImplemented("presentedItemDidMoveToURL:") public void presentedItemDidMoveToURL(NSURL newURL) {} @NotImplemented("presentedItemDidChange") public void presentedItemDidChange() {} @NotImplemented("presentedItemDidGainVersion:") public void presentedItemDidGainVersion(NSFileVersion version) {} @NotImplemented("presentedItemDidLoseVersion:") public void presentedItemDidLoseVersion(NSFileVersion version) {} @NotImplemented("presentedItemDidResolveConflictVersion:") public void presentedItemDidResolveConflictVersion(NSFileVersion version) {} @NotImplemented("accommodatePresentedSubitemDeletionAtURL:completionHandler:") public void accommodatePresentedSubitemDeletionAtURL(NSURL url, @Block VoidBlock1<NSError> completionHandler) {} @NotImplemented("presentedSubitemDidAppearAtURL:") public void presentedSubitemDidAppearAtURL(NSURL url) {} @NotImplemented("presentedSubitemAtURL:didMoveToURL:") public void presentedSubitemAtURLDidMoveToURL(NSURL oldURL, NSURL newURL) {} @NotImplemented("presentedSubitemDidChangeAtURL:") public void presentedSubitemDidChangeAtURL(NSURL url) {} @NotImplemented("presentedSubitemAtURL:didGainVersion:") public void presentedSubitemAtURLDidGainVersion(NSURL url, NSFileVersion version) {} @NotImplemented("presentedSubitemAtURL:didLoseVersion:") public void presentedSubitemAtURLDidLoseVersion(NSURL url, NSFileVersion version) {} @NotImplemented("presentedSubitemAtURL:didResolveConflictVersion:") public void presentedSubitemAtURLDidResolveConflictVersion(NSURL url, NSFileVersion version) {} /*</methods>*/ }
45.265306
116
0.751803
7672665b6f09451ebce5941791eb35a9fe9f9c9c
1,291
package rs.readahead.washington.mobile.views.activity; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.text.Html; import android.text.method.LinkMovementMethod; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import rs.readahead.washington.mobile.R; import rs.readahead.washington.mobile.util.StringUtils; public class ReportHelpActivity extends CacheWordSubscriberBaseActivity { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.data_help) TextView mSaveDataTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_report_help); ButterKnife.bind(this); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(R.string.report_help); } mSaveDataTextView.setText(Html.fromHtml(getString(R.string.save_data))); mSaveDataTextView.setMovementMethod(LinkMovementMethod.getInstance()); StringUtils.stripUnderlines(mSaveDataTextView); } }
30.023256
80
0.749032
17542d083a20981d03c611de3b65b7d189046750
1,180
package com.acmerobotics.relicrecovery.opmodes.vision; import android.graphics.Bitmap; import com.acmerobotics.library.cameraoverlay.CameraStreamServer; import com.acmerobotics.library.vision.FpsTracker; import com.acmerobotics.library.vision.VuforiaCamera; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import org.opencv.core.Mat; /** * Created by ryanbrott on 9/23/17. */ @Disabled @TeleOp(name = "FPS Vision", group = "vision") public class FpsVision extends OpMode { private VuforiaCamera camera; private FpsTracker fpsTracker; private CameraStreamServer streamServer; private Bitmap bitmap; private Mat rgba; @Override public void init() { streamServer = new CameraStreamServer(); camera = new VuforiaCamera(); fpsTracker = new FpsTracker(); camera.addTracker(fpsTracker); camera.addTracker(streamServer.getTracker()); camera.initialize(); } @Override public void start() { streamServer.stop(); } @Override public void loop() { } }
25.652174
65
0.720339
f831beb9388df250feb004d5058ab323d0317b64
3,494
package it.smartcommunitylab.aac.openid.service; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.springframework.core.convert.converter.Converter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest; import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService; import org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails; import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.core.OAuth2Error; import org.springframework.security.oauth2.core.converter.ClaimTypeConverter; import org.springframework.security.oauth2.core.oidc.OidcIdToken; import org.springframework.security.oauth2.core.oidc.OidcUserInfo; import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; import org.springframework.security.oauth2.core.oidc.user.OidcUser; import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority; import org.springframework.util.Assert; import org.springframework.util.StringUtils; public class IdTokenOidcUserService implements OAuth2UserService<OidcUserRequest, OidcUser> { // define claim converter for oidc standard values private static final Converter<Map<String, Object>, Map<String, Object>> claimConverter = new ClaimTypeConverter( OidcUserService.createDefaultClaimTypeConverters()); @Override public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException { Assert.notNull(userRequest, "userRequest cannot be null"); Assert.notNull(userRequest.getIdToken(), "id token is required"); // get id_token and extract claims OidcIdToken idToken = userRequest.getIdToken(); // leverage default converters to translate Map<String, Object> claims = claimConverter.convert(idToken.getClaims()); OidcUserInfo userInfo = new OidcUserInfo(claims); // subject MUST be defined if (userInfo.getSubject() == null) { OAuth2Error oauth2Error = new OAuth2Error("invalid_user_info_response"); throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString()); } // build default user with standard authorities Set<GrantedAuthority> authorities = new LinkedHashSet<>(); authorities.add(new OidcUserAuthority(userRequest.getIdToken(), userInfo)); OAuth2AccessToken token = userRequest.getAccessToken(); for (String authority : token.getScopes()) { authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority)); } // check if userName attribute is defined, or fallback to sub ProviderDetails providerDetails = userRequest.getClientRegistration().getProviderDetails(); String userNameAttributeName = providerDetails.getUserInfoEndpoint().getUserNameAttributeName(); if (StringUtils.hasText(userNameAttributeName)) { return new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo, userNameAttributeName); } return new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo); } }
51.382353
117
0.777046
89f8e74a9e7ffd7621c0359327046e8952af44df
2,961
/* * Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.spi.impl.packetdispatcher.impl; import com.hazelcast.logging.ILogger; import com.hazelcast.nio.Packet; import com.hazelcast.spi.impl.PacketHandler; import com.hazelcast.spi.impl.packetdispatcher.PacketDispatcher; import static com.hazelcast.instance.OutOfMemoryErrorDispatcher.inspectOutputMemoryError; import static com.hazelcast.nio.Packet.FLAG_BIND; import static com.hazelcast.nio.Packet.FLAG_EVENT; import static com.hazelcast.nio.Packet.FLAG_OP; import static com.hazelcast.nio.Packet.FLAG_WAN_REPLICATION; /** * Default {@link PacketDispatcher} implementation. */ public class PacketDispatcherImpl implements PacketDispatcher { private final ILogger logger; private final PacketHandler eventPacketHandler; private final PacketHandler wanReplicationPacketHandler; private final PacketHandler operationPacketHandler; private final PacketHandler connectionPacketHandler; public PacketDispatcherImpl(ILogger logger, PacketHandler operationPacketHandler, PacketHandler eventPacketHandler, PacketHandler wanReplicationPacketHandler, PacketHandler connectionPacketHandler) { this.logger = logger; this.operationPacketHandler = operationPacketHandler; this.eventPacketHandler = eventPacketHandler; this.wanReplicationPacketHandler = wanReplicationPacketHandler; this.connectionPacketHandler = connectionPacketHandler; } @Override public void dispatch(Packet packet) { try { if (packet.isFlagSet(FLAG_OP)) { operationPacketHandler.handle(packet); } else if (packet.isFlagSet(FLAG_EVENT)) { eventPacketHandler.handle(packet); } else if (packet.isFlagSet(FLAG_WAN_REPLICATION)) { wanReplicationPacketHandler.handle(packet); } else if (packet.isFlagSet(FLAG_BIND)) { connectionPacketHandler.handle(packet); } else { logger.severe("Unknown packet type! Header: " + packet.getFlags()); } } catch (Throwable t) { inspectOutputMemoryError(t); logger.severe("Failed to process packet:" + packet, t); } } }
40.561644
89
0.698075
e9132f85c2cb1648a843cedc50499e019c70d7d9
17,792
package co.edu.usbcali.vas.model.control; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import co.edu.usbcali.vas.dataaccess.dao.IVideoStatusDAO; import co.edu.usbcali.vas.exceptions.ZMessManager; import co.edu.usbcali.vas.model.VideoStatus; import co.edu.usbcali.vas.model.dto.VideoStatusDTO; import co.edu.usbcali.vas.utilities.Utilities; /** * @author Zathura Code Generator http://zathuracode.org/ * www.zathuracode.org * */ @Scope("singleton") @Service("VideoStatusLogic") public class VideoStatusLogic implements IVideoStatusLogic { private static final Logger log = LoggerFactory.getLogger(VideoStatusLogic.class); /** * DAO injected by Spring that manages VideoStatus entities * */ @Autowired private IVideoStatusDAO videoStatusDAO; @Transactional(readOnly = true) public List<VideoStatus> getVideoStatus() throws Exception { log.debug("finding all VideoStatus instances"); List<VideoStatus> list = new ArrayList<VideoStatus>(); try { list = videoStatusDAO.findAll(); } catch (Exception e) { log.error("finding all VideoStatus failed", e); throw new ZMessManager().new GettingException(ZMessManager.ALL + "VideoStatus"); } finally { } return list; } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public void saveVideoStatus(VideoStatus entity) throws Exception { log.debug("saving VideoStatus instance"); try { if ((entity.getCode() != null) && (Utilities.checkWordAndCheckWithlength(entity.getCode(), 255) == false)) { throw new ZMessManager().new NotValidFormatException("code"); } if (entity.getCreatedAt() == null) { throw new ZMessManager().new EmptyFieldException("createdAt"); } if (entity.getCreatedBy() == null) { throw new ZMessManager().new EmptyFieldException("createdBy"); } if ((entity.getCreatedBy() != null) && (Utilities.checkWordAndCheckWithlength( entity.getCreatedBy(), 255) == false)) { throw new ZMessManager().new NotValidFormatException( "createdBy"); } if (entity.getDescription() == null) { throw new ZMessManager().new EmptyFieldException("description"); } if ((entity.getDescription() != null) && (Utilities.checkWordAndCheckWithlength( entity.getDescription(), 255) == false)) { throw new ZMessManager().new NotValidFormatException( "description"); } if (entity.getId() == null) { throw new ZMessManager().new EmptyFieldException("id"); } if ((entity.getUpdatedBy() != null) && (Utilities.checkWordAndCheckWithlength( entity.getUpdatedBy(), 255) == false)) { throw new ZMessManager().new NotValidFormatException( "updatedBy"); } if (getVideoStatus(entity.getId()) != null) { throw new ZMessManager(ZMessManager.ENTITY_WITHSAMEKEY); } videoStatusDAO.save(entity); log.debug("save VideoStatus successful"); } catch (Exception e) { log.error("save VideoStatus failed", e); throw e; } finally { } } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public void deleteVideoStatus(VideoStatus entity) throws Exception { log.debug("deleting VideoStatus instance"); if (entity == null) { throw new ZMessManager().new NullEntityExcepcion("VideoStatus"); } if (entity.getId() == null) { throw new ZMessManager().new EmptyFieldException("id"); } try { videoStatusDAO.delete(entity); log.debug("delete VideoStatus successful"); } catch (Exception e) { log.error("delete VideoStatus failed", e); throw e; } finally { } } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public void updateVideoStatus(VideoStatus entity) throws Exception { log.debug("updating VideoStatus instance"); try { if (entity == null) { throw new ZMessManager().new NullEntityExcepcion("VideoStatus"); } if ((entity.getCode() != null) && (Utilities.checkWordAndCheckWithlength(entity.getCode(), 255) == false)) { throw new ZMessManager().new NotValidFormatException("code"); } if (entity.getCreatedAt() == null) { throw new ZMessManager().new EmptyFieldException("createdAt"); } if (entity.getCreatedBy() == null) { throw new ZMessManager().new EmptyFieldException("createdBy"); } if ((entity.getCreatedBy() != null) && (Utilities.checkWordAndCheckWithlength( entity.getCreatedBy(), 255) == false)) { throw new ZMessManager().new NotValidFormatException( "createdBy"); } if (entity.getDescription() == null) { throw new ZMessManager().new EmptyFieldException("description"); } if ((entity.getDescription() != null) && (Utilities.checkWordAndCheckWithlength( entity.getDescription(), 255) == false)) { throw new ZMessManager().new NotValidFormatException( "description"); } if (entity.getId() == null) { throw new ZMessManager().new EmptyFieldException("id"); } if ((entity.getUpdatedBy() != null) && (Utilities.checkWordAndCheckWithlength( entity.getUpdatedBy(), 255) == false)) { throw new ZMessManager().new NotValidFormatException( "updatedBy"); } videoStatusDAO.update(entity); log.debug("update VideoStatus successful"); } catch (Exception e) { log.error("update VideoStatus failed", e); throw e; } finally { } } @Transactional(readOnly = true) public List<VideoStatusDTO> getDataVideoStatus() throws Exception { try { List<VideoStatus> videoStatus = videoStatusDAO.findAll(); List<VideoStatusDTO> videoStatusDTO = new ArrayList<VideoStatusDTO>(); for (VideoStatus videoStatusTmp : videoStatus) { VideoStatusDTO videoStatusDTO2 = new VideoStatusDTO(); videoStatusDTO2.setId(videoStatusTmp.getId()); videoStatusDTO2.setCode((videoStatusTmp.getCode() != null) ? videoStatusTmp.getCode() : null); videoStatusDTO2.setCreatedAt(videoStatusTmp.getCreatedAt()); videoStatusDTO2.setCreatedBy((videoStatusTmp.getCreatedBy() != null) ? videoStatusTmp.getCreatedBy() : null); videoStatusDTO2.setDescription((videoStatusTmp.getDescription() != null) ? videoStatusTmp.getDescription() : null); videoStatusDTO2.setUpdatedAt(videoStatusTmp.getUpdatedAt()); videoStatusDTO2.setUpdatedBy((videoStatusTmp.getUpdatedBy() != null) ? videoStatusTmp.getUpdatedBy() : null); videoStatusDTO.add(videoStatusDTO2); } return videoStatusDTO; } catch (Exception e) { throw e; } } @Transactional(readOnly = true) public VideoStatus getVideoStatus(Integer id) throws Exception { log.debug("getting VideoStatus instance"); VideoStatus entity = null; try { entity = videoStatusDAO.findById(id); } catch (Exception e) { log.error("get VideoStatus failed", e); throw new ZMessManager().new FindingException("VideoStatus"); } finally { } return entity; } @Transactional(readOnly = true) public List<VideoStatus> findPageVideoStatus(String sortColumnName, boolean sortAscending, int startRow, int maxResults) throws Exception { List<VideoStatus> entity = null; try { entity = videoStatusDAO.findPage(sortColumnName, sortAscending, startRow, maxResults); } catch (Exception e) { throw new ZMessManager().new FindingException("VideoStatus Count"); } finally { } return entity; } @Transactional(readOnly = true) public Long findTotalNumberVideoStatus() throws Exception { Long entity = null; try { entity = videoStatusDAO.count(); } catch (Exception e) { throw new ZMessManager().new FindingException("VideoStatus Count"); } finally { } return entity; } /** * * @param varibles * este arreglo debera tener: * * [0] = String variable = (String) varibles[i]; representa como se llama la * variable en el pojo * * [1] = Boolean booVariable = (Boolean) varibles[i + 1]; representa si el * valor necesita o no ''(comillas simples)usado para campos de tipo string * * [2] = Object value = varibles[i + 2]; representa el valor que se va a * buscar en la BD * * [3] = String comparator = (String) varibles[i + 3]; representa que tipo * de busqueda voy a hacer.., ejemplo: where nombre=william o where nombre<>william, * en este campo iria el tipo de comparador que quiero si es = o <> * * Se itera de 4 en 4..., entonces 4 registros del arreglo representan 1 * busqueda en un campo, si se ponen mas pues el continuara buscando en lo * que se le ingresen en los otros 4 * * * @param variablesBetween * * la diferencia son estas dos posiciones * * [0] = String variable = (String) varibles[j]; la variable ne la BD que va * a ser buscada en un rango * * [1] = Object value = varibles[j + 1]; valor 1 para buscar en un rango * * [2] = Object value2 = varibles[j + 2]; valor 2 para buscar en un rango * ejempolo: a > 1 and a < 5 --> 1 seria value y 5 seria value2 * * [3] = String comparator1 = (String) varibles[j + 3]; comparador 1 * ejemplo: a comparator1 1 and a < 5 * * [4] = String comparator2 = (String) varibles[j + 4]; comparador 2 * ejemplo: a comparador1>1 and a comparador2<5 (el original: a > 1 and a < * 5) * * @param variablesBetweenDates(en * este caso solo para mysql) * [0] = String variable = (String) varibles[k]; el nombre de la variable que hace referencia a * una fecha * * [1] = Object object1 = varibles[k + 2]; fecha 1 a comparar(deben ser * dates) * * [2] = Object object2 = varibles[k + 3]; fecha 2 a comparar(deben ser * dates) * * esto hace un between entre las dos fechas. * * @return lista con los objetos que se necesiten * @throws Exception */ @Transactional(readOnly = true) public List<VideoStatus> findByCriteria(Object[] variables, Object[] variablesBetween, Object[] variablesBetweenDates) throws Exception { List<VideoStatus> list = new ArrayList<VideoStatus>(); String where = new String(); String tempWhere = new String(); if (variables != null) { for (int i = 0; i < variables.length; i++) { if ((variables[i] != null) && (variables[i + 1] != null) && (variables[i + 2] != null) && (variables[i + 3] != null)) { String variable = (String) variables[i]; Boolean booVariable = (Boolean) variables[i + 1]; Object value = variables[i + 2]; String comparator = (String) variables[i + 3]; if (booVariable.booleanValue()) { tempWhere = (tempWhere.length() == 0) ? ("(model." + variable + " " + comparator + " \'" + value + "\' )") : (tempWhere + " AND (model." + variable + " " + comparator + " \'" + value + "\' )"); } else { tempWhere = (tempWhere.length() == 0) ? ("(model." + variable + " " + comparator + " " + value + " )") : (tempWhere + " AND (model." + variable + " " + comparator + " " + value + " )"); } } i = i + 3; } } if (variablesBetween != null) { for (int j = 0; j < variablesBetween.length; j++) { if ((variablesBetween[j] != null) && (variablesBetween[j + 1] != null) && (variablesBetween[j + 2] != null) && (variablesBetween[j + 3] != null) && (variablesBetween[j + 4] != null)) { String variable = (String) variablesBetween[j]; Object value = variablesBetween[j + 1]; Object value2 = variablesBetween[j + 2]; String comparator1 = (String) variablesBetween[j + 3]; String comparator2 = (String) variablesBetween[j + 4]; tempWhere = (tempWhere.length() == 0) ? ("(" + value + " " + comparator1 + " " + variable + " and " + variable + " " + comparator2 + " " + value2 + " )") : (tempWhere + " AND (" + value + " " + comparator1 + " " + variable + " and " + variable + " " + comparator2 + " " + value2 + " )"); } j = j + 4; } } if (variablesBetweenDates != null) { for (int k = 0; k < variablesBetweenDates.length; k++) { if ((variablesBetweenDates[k] != null) && (variablesBetweenDates[k + 1] != null) && (variablesBetweenDates[k + 2] != null)) { String variable = (String) variablesBetweenDates[k]; Object object1 = variablesBetweenDates[k + 1]; Object object2 = variablesBetweenDates[k + 2]; String value = null; String value2 = null; try { Date date1 = (Date) object1; Date date2 = (Date) object2; value = Utilities.formatDateWithoutTimeInAStringForBetweenWhere(date1); value2 = Utilities.formatDateWithoutTimeInAStringForBetweenWhere(date2); } catch (Exception e) { list = null; throw e; } tempWhere = (tempWhere.length() == 0) ? ("(model." + variable + " between \'" + value + "\' and \'" + value2 + "\')") : (tempWhere + " AND (model." + variable + " between \'" + value + "\' and \'" + value2 + "\')"); } k = k + 2; } } if (tempWhere.length() == 0) { where = null; } else { where = "(" + tempWhere + ")"; } try { list = videoStatusDAO.findByCriteria(where); } catch (Exception e) { throw new Exception(e.getMessage()); } finally { } return list; } @Override @Transactional(readOnly = true) public VideoStatus getVideoStatusByCode(String code) throws Exception { log.info("VideoStatusLogic getVideoStatusByCode"); VideoStatus entity = null; try { entity = (VideoStatus) videoStatusDAO.getVideoStatusByCode(code.trim()); } catch (Exception e) { log.error("El parametro : " + code + " No existe en la base de datos", e); } log.info("VideoStatusLogic getVideoStatusByCode: "+entity.getDescription()); return entity; } }
37.774947
123
0.518885
fd9701feaf094530c108b7bf08427b7fc38bc2b9
1,545
package com.turnos.datos.vo; import io.swagger.annotations.ApiModelProperty; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; import com.fasterxml.jackson.annotation.JsonRootName; @XmlRootElement(name = "turno") @JsonRootName(value = "turno") public class TurnoBean extends ETLTBean { private static final long serialVersionUID = 74L; public enum TipoTurno { ORDINARIO, RESERVA, DESCANSO; public static TipoTurno safeValueOf(String arg) { try{return valueOf(arg);} catch(Exception e){return null;} } } private String codTurno; private String codResidencia; private TipoTurno tipo; private List<ServicioBean> servicios; public TurnoBean() { super(TurnoBean.class); } public String getCodTurno() { return codTurno; } public void setCodTurno(String codTurno) { this.codTurno = codTurno; } public String getCodResidencia() { return codResidencia; } public void setCodResidencia(String codResidencia) { this.codResidencia = codResidencia; } @ApiModelProperty(allowableValues = "ORDINARIO,RESERVA,DESCANSO") public String getTipo() { if (tipo == null) return null; return tipo.name(); } @ApiModelProperty(allowableValues = "ORDINARIO,RESERVA,DESCANSO") public void setTipo(String tipo) { this.tipo = TipoTurno.safeValueOf(tipo); } public List<ServicioBean> getServicios() { return servicios; } public void setServicios(List<ServicioBean> servicios) { this.servicios = servicios; } }
22.391304
67
0.717152
f14761103c5220db552f216cf0ad55d0308f6c6a
438
package com.edgar.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class MyServiceHandler implements InvocationHandler { private Object target; public MyServiceHandler(Object target) { this.target = target; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println(1); return method.invoke(target, args); } }
20.857143
66
0.728311
40d8bfb66303d5e0c229180809715f9189b340c7
1,498
package uk.gov.ida.verifylocalmatchingserviceexample.dataaccess; import org.jdbi.v3.core.Jdbi; import uk.gov.ida.verifylocalmatchingserviceexample.mappers.PersonMapper; import uk.gov.ida.verifylocalmatchingserviceexample.model.Person; import java.time.LocalDate; import java.util.List; import java.util.stream.Collectors; public class PersonDAO { private Jdbi jdbi; public PersonDAO(Jdbi jdbi) { this.jdbi = jdbi; } public List<Person> getMatchingUsers(List<String> surnames, LocalDate dateOfBirth) { return jdbi.withHandle(handle -> handle.createQuery("select person_id, surname, first_name, date_of_birth, postcode " + "from person " + "left outer join address " + "on person.address = address.address_id " + "where LOWER(surname) in (<surnames>) and date_of_birth = :dateOfBirth") .bindList("surnames", toLowerCase(surnames)) .bind("dateOfBirth", dateOfBirth) .map(new PersonMapper()) .list() ); } public boolean tableExists() { return jdbi.withHandle(handle -> handle.createQuery("select 1 from person") .mapTo(Integer.class) .findFirst() .isPresent() ); } private List<String> toLowerCase(List<String> surnames) { return surnames.stream() .map(String::toLowerCase) .collect(Collectors.toList()); } }
31.208333
98
0.626836
9c85ea7befb182bf98c0545a976f8bfa8afb5e83
7,482
package com.cubolabs.bibliaofflinearc.ui; import android.content.Context; import android.graphics.Color; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.widget.SearchView; import android.text.Html; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.TextView; import com.cubolabs.bibliaofflinearc.MainActivity; import com.cubolabs.bibliaofflinearc.R; import com.cubolabs.bibliaofflinearc.data.ListaDeVersiculos; import java.util.ArrayList; public class SearchResultsPopup { public static final String TAG = SearchResultsPopup.class.getSimpleName(); private MainActivity activity; private String popUpContents[]; private PopupWindow popupSearchResults; private SearchView mSearchView; private MenuItem searchItem; private ListaDeVersiculos listaDeVersiculos; public SearchResultsPopup(MainActivity activity, SearchView mSearchView, MenuItem searchItem){ this.activity = activity; this.mSearchView = mSearchView; this.searchItem = searchItem; this.popUpContents = new String[]{}; this.popupSearchResults = create(); } public PopupWindow create(){ PopupWindow popupWindow = new PopupWindow(activity); ListView listviewSearchResults = new ListView(activity) { //TODO: popupwindow 90% parent's width @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int parentWidth = MeasureSpec.getSize(widthMeasureSpec); int parentHeight = MeasureSpec.getSize(heightMeasureSpec); this.setMeasuredDimension((int)Math.round(parentWidth*0.9), parentHeight); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }; listviewSearchResults.setAdapter(versesAdapter(popUpContents)); listviewSearchResults.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) { //Context mContext = v.getContext(); //MainActivity mainActivity = ((MainActivity) mContext); // add some animation when a list item was clicked Animation fadeInAnimation = AnimationUtils.loadAnimation(v.getContext(), android.R.anim.fade_in); fadeInAnimation.setDuration(10); v.startAnimation(fadeInAnimation); while (hide()) {} String selectedItemTag = v.getTag().toString(); //Toast.makeText(mContext, selectedItemTag, Toast.LENGTH_SHORT).show(); String[] livroCapituloArr = selectedItemTag.split(",|:"); String livro = livroCapituloArr[0]; Integer capitulo = Integer.parseInt(livroCapituloArr[1].trim()); //Integer versiculo = Integer.parseInt(livroCapituloArr[2]); Fragment newFragment = VersiculosFragment.newInstance(livro, capitulo); FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction(); transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit); transaction.addToBackStack(null); FragmentUtils.clearBackStack(activity); transaction.replace(R.id.container, newFragment, TAG); transaction.commit(); } }); // some other visual settings popupWindow.setFocusable(true); //popupWindow.setTouchable(true); //popupWindow.setFocusable(true); //popupWindow.setWidth(250); popupWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT); popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); // set the list view as pop up window content popupWindow.setContentView(listviewSearchResults); return popupWindow; } private ArrayAdapter<String> versesAdapter(String verses[]) { ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, android.R.layout.simple_list_item_2, verses) { @Override public View getView(int position, View convertView, ViewGroup parent) { // setting the ID and text for every items in the list String item = getItem(position); String[] itemArr = item.split("=>"); String verseText = itemArr[0]; String bookChapterVerse = itemArr[1]; View row; if(convertView == null) { Context ctx = activity.getApplicationContext(); LayoutInflater inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(android.R.layout.simple_list_item_2, null); } else { row = convertView; } //View row = super.getView(position, convertView, parent); row.setTag(bookChapterVerse); // visual settings for the list item TextView v = (TextView) row.findViewById(android.R.id.text1); v.setText(Html.fromHtml(verseText), TextView.BufferType.SPANNABLE); v.setTextSize(16); v.setPadding(10, 10, 10, 10); v.setTextColor(Color.WHITE); v = (TextView) row.findViewById(android.R.id.text2); v.setText(bookChapterVerse); return row; } }; return adapter; } public boolean hide(){ if (popupSearchResults.isShowing()) popupSearchResults.dismiss(); else { if (!mSearchView.isIconified()) mSearchView.setIconified(true); else return false; } return true; } public void submit(String s) { if (listaDeVersiculos == null) listaDeVersiculos = new ListaDeVersiculos(activity); ArrayList<String> versiculos = listaDeVersiculos.Busca(s.trim()); update(versiculos); mSearchView.clearFocus(); InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0); popupSearchResults.getContentView().requestFocus(); } private void update(ArrayList<String> versiculos) { popUpContents = versiculos.toArray(new String[versiculos.size()]); if (popupSearchResults.isShowing()) { popupSearchResults.dismiss(); } popupSearchResults = create(); popupSearchResults.showAsDropDown(activity.findViewById(R.id.action_search), -5, 0); } }
40.010695
113
0.640738
21aa6d4d2f6a8d9ff067281e07a09c081540eab3
316
package com.lifecycle.annotation; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope public class HpLaptop implements ILaptop { @Override public String getConfiguration() { return "This is 4GB RAM, i5 intel processor, 1TB Hard Disk"; } }
19.75
62
0.787975
9dd12686a87a428fec1cadec0306b1698cb99c0e
18,779
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2011 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ package com.zimbra.qa.unittest.prov.ldap; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import com.zimbra.common.account.Key; import com.zimbra.common.service.ServiceException; import com.zimbra.cs.account.AccessManager; import com.zimbra.cs.account.Account; import com.zimbra.cs.account.DistributionList; import com.zimbra.cs.account.Domain; import com.zimbra.cs.account.Entry; import com.zimbra.cs.account.GlobalGrant; import com.zimbra.cs.account.Group; import com.zimbra.cs.account.GuestAccount; import com.zimbra.cs.account.NamedEntry; import com.zimbra.cs.account.AccessManager.ViaGrant; import com.zimbra.cs.account.accesscontrol.GranteeType; import com.zimbra.cs.account.accesscontrol.Right; import com.zimbra.cs.account.accesscontrol.RightCommand; import com.zimbra.cs.account.accesscontrol.TargetType; import com.zimbra.cs.account.accesscontrol.ZimbraACE; import com.zimbra.cs.account.accesscontrol.Rights.User; import com.zimbra.cs.account.ldap.LdapProv; import com.zimbra.cs.service.AuthProvider; import com.zimbra.qa.unittest.prov.ldap.ACLTestUtil.AllowOrDeny; import com.zimbra.qa.unittest.prov.ldap.ACLTestUtil.AsAdmin; import com.zimbra.qa.unittest.prov.ldap.ACLTestUtil.TestViaGrant; import com.zimbra.soap.type.TargetBy; public class TestACLNegativeGrant extends LdapTest { private static LdapProvTestUtil provUtil; private static LdapProv prov; private static Domain baseDomain; private static String BASE_DOMAIN_NAME; private static Account globalAdmin; @BeforeClass public static void init() throws Exception { provUtil = new LdapProvTestUtil(); prov = provUtil.getProv(); baseDomain = provUtil.createDomain(baseDomainName()); BASE_DOMAIN_NAME = baseDomain.getName(); globalAdmin = provUtil.createGlobalAdmin("globaladmin", baseDomain); ACLTestUtil.initTestRights(); } @AfterClass public static void cleanup() throws Exception { Cleanup.deleteAll(baseDomainName()); } private void grantRight(Account authedAcct, TargetType targetType, NamedEntry target, GranteeType granteeType, NamedEntry grantee, Right right, AllowOrDeny grant) throws ServiceException { RightCommand.grantRight(prov, authedAcct, targetType.getCode(), TargetBy.name, target==null?null:target.getName(), granteeType.getCode(), Key.GranteeBy.name, grantee.getName(), null, right.getName(), grant.toRightModifier()); } protected void revokeRight(Account authedAcct, TargetType targetType, NamedEntry target, GranteeType granteeType, NamedEntry grantee, Right right, AllowOrDeny grant) throws ServiceException { RightCommand.revokeRight(prov, authedAcct, targetType.getCode(), TargetBy.name, target==null?null:target.getName(), granteeType.getCode(), Key.GranteeBy.name, grantee.getName(), right.getName(), grant.toRightModifier()); } protected void verify(Account grantee, Entry target, Right right, AsAdmin asAdmin, AllowOrDeny expected, TestViaGrant expectedVia) throws Exception { AccessManager accessMgr = AccessManager.getInstance(); boolean result; // Account interface ViaGrant via = (expectedVia==null)?null:new ViaGrant(); result = accessMgr.canDo(grantee==null?null:grantee, target, right, asAdmin.yes(), via); assertEquals(expected.allow(), result); TestViaGrant.verifyEquals(expectedVia, via); // AuthToken interface via = (expectedVia==null)?null:new ViaGrant(); result = accessMgr.canDo(grantee==null?null:AuthProvider.getAuthToken(grantee), target, right, asAdmin.yes(), via); assertEquals(expected.allow(), result); TestViaGrant.verifyEquals(expectedVia, via); // String interface via = (expectedVia==null)?null:new ViaGrant(); result = accessMgr.canDo(grantee==null?null:grantee.getName(), target, right, asAdmin.yes(), via); if (grantee instanceof GuestAccount && ((GuestAccount)grantee).getAccessKey() != null) { // string interface always return denied for key grantee unless there is a pub grant // skip the test for now, unless we want to pass yet another parameter to this method // i.e. - if no pub grant: should always expect false // - if there is a pub grant: should expect the expected return; } assertEquals(expected.allow(), result); TestViaGrant.verifyEquals(expectedVia, via); } /* * Verify denied takes precedence * * Grant to two unrelated groups: one allowed, one denied * account is a member of both groups * * Expected: account should be denied */ @Test public void groupGranteeTest1() throws Exception { Account authedAcct = globalAdmin; Right right = ACLTestUtil.ADMIN_PRESET_ACCOUNT; /* * setup grantees */ Account account = provUtil.createDelegatedAdmin(genAcctNameLocalPart("acct"), baseDomain); Group group1 = provUtil.createAdminGroup(genAcctNameLocalPart("group1"), baseDomain); Group group2 = provUtil.createAdminGroup(genAcctNameLocalPart("group2"), baseDomain); prov.addGroupMembers(group1, new String[] {account.getName()}); prov.addGroupMembers(group2, new String[] {account.getName()}); /* * setup targets */ Account target = provUtil.createAccount(genAcctNameLocalPart("target"), baseDomain); grantRight(authedAcct, TargetType.account, target, GranteeType.GT_GROUP, group1, right, AllowOrDeny.ALLOW); grantRight(authedAcct, TargetType.account, target, GranteeType.GT_GROUP, group2, right, AllowOrDeny.DENY); TestViaGrant via; via = new TestViaGrant(TargetType.account, target, GranteeType.GT_GROUP, group2.getName(), right, TestViaGrant.NEGATIVE); verify(account, target, right, AsAdmin.AS_ADMIN, AllowOrDeny.DENY, via); } /* * Verify denied takes precedence * * * Membership: * G1(A) G4(D) * / \ / \ * A G2(D) A G5(A) * / \ / \ * A G3(A) A G6(D) * | | * A A * * * Grantee: * GG1(allow), GG2(deny), GG3(allow), GG4(deny), GG5(allow), GG6(deny) * * Target: * granted on the same target entry - TA * * Expected: * Denied via grants to G2 or G4 or G6 * */ public void groupGranteeTest2() throws Exception { Domain domain = provUtil.createDomain(genDomainSegmentName() + "." + BASE_DOMAIN_NAME); /* * setup authed account */ Account authedAcct = globalAdmin; Right right = ACLTestUtil.ADMIN_PRESET_ACCOUNT; /* * setup grantees */ Account account = provUtil.createDelegatedAdmin(genAcctNameLocalPart("account"), domain); /* * setup groups */ Group GG1 = provUtil.createAdminGroup(genGroupNameLocalPart("GG1"), domain); Group GG2 = provUtil.createAdminGroup(genGroupNameLocalPart("GG2"), domain); Group GG3 = provUtil.createAdminGroup(genGroupNameLocalPart("GG3"), domain); Group GG4 = provUtil.createAdminGroup(genGroupNameLocalPart("GG4"), domain); Group GG5 = provUtil.createAdminGroup(genGroupNameLocalPart("GG5"), domain); Group GG6 = provUtil.createAdminGroup(genGroupNameLocalPart("GG6"), domain); prov.addGroupMembers(GG1, new String[] {account.getName(), GG2.getName()}); prov.addGroupMembers(GG2, new String[] {account.getName(), GG3.getName()}); prov.addGroupMembers(GG3, new String[] {account.getName()}); prov.addGroupMembers(GG4, new String[] {account.getName(), GG5.getName()}); prov.addGroupMembers(GG5, new String[] {account.getName(), GG6.getName()}); prov.addGroupMembers(GG6, new String[] {account.getName()}); /* * setup targets */ Account target = provUtil.createAccount(genAcctNameLocalPart("target"), domain); grantRight(authedAcct, TargetType.account, target, GranteeType.GT_GROUP, GG1, right, AllowOrDeny.ALLOW); grantRight(authedAcct, TargetType.account, target, GranteeType.GT_GROUP, GG2, right, AllowOrDeny.DENY); grantRight(authedAcct, TargetType.account, target, GranteeType.GT_GROUP, GG3, right, AllowOrDeny.ALLOW); grantRight(authedAcct, TargetType.account, target, GranteeType.GT_GROUP, GG4, right, AllowOrDeny.DENY); grantRight(authedAcct, TargetType.account, target, GranteeType.GT_GROUP, GG5, right, AllowOrDeny.ALLOW); grantRight(authedAcct, TargetType.account, target, GranteeType.GT_GROUP, GG6, right, AllowOrDeny.DENY); TestViaGrant via; via = new TestViaGrant(TargetType.account, target, GranteeType.GT_GROUP, GG2.getName(), right, TestViaGrant.NEGATIVE); via.addCanAlsoVia(new TestViaGrant(TargetType.account, target, GranteeType.GT_GROUP, GG4.getName(), right, TestViaGrant.NEGATIVE)); via.addCanAlsoVia(new TestViaGrant(TargetType.account, target, GranteeType.GT_GROUP, GG6.getName(), right, TestViaGrant.NEGATIVE)); verify(account, target, right, AsAdmin.AS_ADMIN, AllowOrDeny.DENY, via); } /* Combining Target Scope and Grantee Scope: Grantee Relativity takes Precedence over Target Relativity For example, for this target hierarchy: domain D group G1 (allow right R to group GC) group G2 (deny right R to group GB) group G3 (deny right R to group GA) user account U And this grantee hierarchy: group GA group GB group GC (admin) account A Then A is *allowed* for right R on target account U, because GC is more specific to A than GA and GB. Even if on the target side, grant on G3(grant to GA) and G2(grant to GB) is more specific than the grant on G1(grant to GC). The above is no longer true, it should be DENIED. */ @Test public void groupGranteeTest3() throws Exception { Domain domain = provUtil.createDomain(genDomainSegmentName() + "." + BASE_DOMAIN_NAME); /* * setup authed account */ Account authedAcct = globalAdmin; Right right = ACLTestUtil.ADMIN_PRESET_ACCOUNT; /* * setup grantees */ Account account = provUtil.createDelegatedAdmin(genAcctNameLocalPart("account"), domain); /* * setup grantee groups */ Group GA = provUtil.createAdminGroup(genGroupNameLocalPart("GA"), domain); Group GB = provUtil.createAdminGroup(genGroupNameLocalPart("GB"), domain); Group GC = provUtil.createAdminGroup(genGroupNameLocalPart("GC"), domain); prov.addGroupMembers(GA, new String[] {GB.getName()}); prov.addGroupMembers(GB, new String[] {GC.getName()}); prov.addGroupMembers(GC, new String[] {account.getName()}); /* * setup targets */ TestViaGrant via; Account target = provUtil.createAccount(genAcctNameLocalPart("target"), domain); Group G1 = provUtil.createDistributionList(genGroupNameLocalPart("G1"), domain); Group G2 = provUtil.createDistributionList(genGroupNameLocalPart("G2"), domain); Group G3 = provUtil.createDistributionList(genGroupNameLocalPart("G3"), domain); prov.addGroupMembers(G1, new String[] {G2.getName()}); prov.addGroupMembers(G2, new String[] {G3.getName()}); prov.addGroupMembers(G3, new String[] {target.getName()}); grantRight(authedAcct, TargetType.dl, G1, GranteeType.GT_GROUP, GC, right, AllowOrDeny.ALLOW); grantRight(authedAcct, TargetType.dl, G2, GranteeType.GT_GROUP, GB, right, AllowOrDeny.DENY); grantRight(authedAcct, TargetType.dl, G3, GranteeType.GT_GROUP, GA, right, AllowOrDeny.DENY); /* NO longer the case // the right should be allowed via the grant on G1, granted to group GC via = new TestViaGrant(TargetType.dl, G1, GranteeType.GT_GROUP, GC.getName(), right, TestViaGrant.POSITIVE); verify(account, target, right, AsAdmin.AS_ADMIN, AllowOrDeny.ALLOW, via); */ via = new TestViaGrant(TargetType.dl, G2, GranteeType.GT_GROUP, GB.getName(), right, TestViaGrant.NEGATIVE); via.addCanAlsoVia(new TestViaGrant(TargetType.dl, G3, GranteeType.GT_GROUP, GA.getName(), right, TestViaGrant.NEGATIVE)); verify(account, target, right, AsAdmin.AS_ADMIN, AllowOrDeny.DENY, via); } /* * Original grants: * global grant (allow) * domain (deny) * group1 (allow) * group2 (deny) * target account (allow) * => should allow * * then revoke the grant on account, should deny * then revoke the grant on group2, should allow * then revoke the grant on group1, should deny * then revoke the grant on domain, should allow * then revoke the grant on global grant, should deny */ @Test public void targetPrecedence() throws Exception { Domain domain = provUtil.createDomain(genDomainSegmentName() + "." + BASE_DOMAIN_NAME); /* * setup authed account */ Account authedAcct = globalAdmin; Right right = ACLTestUtil.ADMIN_PRESET_ACCOUNT; /* * setup grantees */ Account grantee = provUtil.createDelegatedAdmin(genAcctNameLocalPart("grantee"), domain); /* * setup targets */ // 1. target account itself Account target = provUtil.createAccount(genAcctNameLocalPart("target"), domain); grantRight(authedAcct, TargetType.account, target, GranteeType.GT_USER, grantee, right, AllowOrDeny.ALLOW); // 2. groups the target account is a member of DistributionList group1 = provUtil.createDistributionList(genGroupNameLocalPart("group1"), domain); DistributionList group2 = provUtil.createDistributionList(genGroupNameLocalPart("group2"), domain); prov.addMembers(group1, new String[] {group2.getName()}); prov.addMembers(group2, new String[] {target.getName()}); grantRight(authedAcct, TargetType.dl, group2, GranteeType.GT_USER, grantee, right, AllowOrDeny.DENY); grantRight(authedAcct, TargetType.dl, group1, GranteeType.GT_USER, grantee, right, AllowOrDeny.ALLOW); // 3. domain the target account is in grantRight(authedAcct, TargetType.domain, domain, GranteeType.GT_USER, grantee, right, AllowOrDeny.DENY); // 4. global grant GlobalGrant globalGrant = prov.getGlobalGrant(); grantRight(authedAcct, TargetType.global, null, GranteeType.GT_USER, grantee, right, AllowOrDeny.ALLOW); /* * test targets */ TestViaGrant via; via = new TestViaGrant(TargetType.account, target, GranteeType.GT_USER, grantee.getName(), right, TestViaGrant.POSITIVE); verify(grantee, target, right, AsAdmin.AS_ADMIN, AllowOrDeny.ALLOW, via); // revoke the grant on target account, then grant on group2 should take effect revokeRight(authedAcct, TargetType.account, target, GranteeType.GT_USER, grantee, right, AllowOrDeny.ALLOW); via = new TestViaGrant(TargetType.dl, group2, GranteeType.GT_USER, grantee.getName(), right, TestViaGrant.NEGATIVE); verify(grantee, target, right, AsAdmin.AS_ADMIN, AllowOrDeny.DENY, via); // revoke the grant on group2, then grant on group1 should take effect revokeRight(authedAcct, TargetType.dl, group2, GranteeType.GT_USER, grantee, right, AllowOrDeny.DENY); via = new TestViaGrant(TargetType.dl, group1, GranteeType.GT_USER, grantee.getName(), right, TestViaGrant.POSITIVE); verify(grantee, target, right, AsAdmin.AS_ADMIN, AllowOrDeny.ALLOW, via); // revoke the grant on group1, then grant on domain should take effect revokeRight(authedAcct, TargetType.dl, group1, GranteeType.GT_USER, grantee, right, AllowOrDeny.ALLOW); via = new TestViaGrant(TargetType.domain, domain, GranteeType.GT_USER, grantee.getName(), right, TestViaGrant.NEGATIVE); verify(grantee, target, right, AsAdmin.AS_ADMIN, AllowOrDeny.DENY, via); // revoke the grant on domain, then grant on globalgrant shuld take effect revokeRight(authedAcct, TargetType.domain, domain, GranteeType.GT_USER, grantee, right, AllowOrDeny.DENY); via = new TestViaGrant(TargetType.global, globalGrant, GranteeType.GT_USER, grantee.getName(), right, TestViaGrant.POSITIVE); verify(grantee, target, right, AsAdmin.AS_ADMIN, AllowOrDeny.ALLOW, via); // revoke the grant on globalgrant, then there is no grant and callsite default should be honored revokeRight(authedAcct, TargetType.global, null, GranteeType.GT_USER, grantee, right, AllowOrDeny.ALLOW); via = null; verify(grantee, target, right, AsAdmin.AS_ADMIN, AllowOrDeny.DENY, via); } }
45.033573
139
0.647638
1e6f00c84cc0fae75f7a90cb4234662afefb2c12
5,686
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sk.upjs.ics.paz1c.nemocnica; import java.awt.Dialog; import javax.swing.JOptionPane; /** * * @author szoplakz */ public class LekarForm extends javax.swing.JDialog { /** * Creates new form LekarForm */ private LekarDAO lekarDao = DaoFactory.INSTANCE.getLekarDao(); public LekarForm(java.awt.Dialog parent, boolean modal) { super(parent, modal); initComponents(); this.setSize(650, 300); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); LekariTable = new javax.swing.JTable(); PridajButton = new javax.swing.JButton(); UpravButton = new javax.swing.JButton(); VymazDiagnozuButton = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); LekariTable.setModel(new LekariTableModel()); jScrollPane1.setViewportView(LekariTable); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(10, 11, 452, 240); PridajButton.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N PridajButton.setForeground(new java.awt.Color(0, 102, 0)); PridajButton.setText("Pridaj"); PridajButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { PridajButtonActionPerformed(evt); } }); getContentPane().add(PridajButton); PridajButton.setBounds(480, 30, 100, 47); UpravButton.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N UpravButton.setForeground(new java.awt.Color(0, 102, 0)); UpravButton.setText("Uprav"); UpravButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { UpravButtonActionPerformed(evt); } }); getContentPane().add(UpravButton); UpravButton.setBounds(480, 110, 100, 47); VymazDiagnozuButton.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N VymazDiagnozuButton.setForeground(new java.awt.Color(0, 102, 0)); VymazDiagnozuButton.setText("Vymaz"); VymazDiagnozuButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { VymazDiagnozuButtonActionPerformed(evt); } }); getContentPane().add(VymazDiagnozuButton); VymazDiagnozuButton.setBounds(480, 190, 100, 47); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Background.jpg"))); // NOI18N jLabel1.setVerticalAlignment(javax.swing.SwingConstants.TOP); getContentPane().add(jLabel1); jLabel1.setBounds(0, 0, 620, 270); pack(); }// </editor-fold>//GEN-END:initComponents private void PridajButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PridajButtonActionPerformed PridajUpravLekaraForm pridatForm = new PridajUpravLekaraForm(this,true,false,null); pridatForm.setVisible(true); }//GEN-LAST:event_PridajButtonActionPerformed private void UpravButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UpravButtonActionPerformed if(LekariTable.getSelectedRow()==-1){ JOptionPane.showMessageDialog(null, "Je potrebné najskôr označiť lekára."); } else { // vybratie zaznamu v tabulke int riadok = LekariTable.getSelectedRow(); Lekar lekar = ((LekariTableModel) LekariTable.getModel()).getLekarAt(riadok); PridajUpravLekaraForm pridatForm = new PridajUpravLekaraForm(this,true,true,lekar); pridatForm.setVisible(true); } }//GEN-LAST:event_UpravButtonActionPerformed private void VymazDiagnozuButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_VymazDiagnozuButtonActionPerformed if(LekariTable.getSelectedRow()==-1){ JOptionPane.showMessageDialog(null, "Je potrebné najskôr označiť lekára."); } else { // vybratie zaznamu v tabulke int riadok = LekariTable.getSelectedRow(); Lekar lekar = ((LekariTableModel) LekariTable.getModel()).getLekarAt(riadok); lekarDao.vymazLekara(lekar); LekarForm lekarForm = new LekarForm((Dialog) this.getParent(),true); this.setVisible(false); lekarForm.setVisible(true); } }//GEN-LAST:event_VymazDiagnozuButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTable LekariTable; private javax.swing.JButton PridajButton; private javax.swing.JButton UpravButton; private javax.swing.JButton VymazDiagnozuButton; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables }
40.042254
137
0.672001
24ab2ac1e2d48d91311c8a9af5569b46bdfa10a7
3,032
package com.example.rise.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.ImageView; import com.example.rise.R; import org.xutils.x; import java.util.ArrayList; import java.util.List; /** * Created by chengxi on 17/4/26. */ public class TabFragment11 extends Fragment{ private ViewPager viewPager; private ImageAdapter mPagerAdapter; private ImageView imageView1, imageView2, imageView3; private ArrayList<ImageView> pageView = new ArrayList<>(); @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view1 = inflater.inflate(R.layout.fragment_tab_1, null); x.view().inject(getActivity()); viewPager = (ViewPager) view1.findViewById(R.id.viewpager); LayoutInflater inflater1 = getLayoutInflater(savedInstanceState); View view2 = inflater1.inflate(R.layout.item04, null); imageView1 = (ImageView) view2.findViewById(R.id.imageview1); imageView2 = (ImageView) view2.findViewById(R.id.imageview2); imageView3 = (ImageView) view2.findViewById(R.id.imageview3); pageView.add(imageView1); pageView.add(imageView2); pageView.add(imageView3); mPagerAdapter = new ImageAdapter(pageView); viewPager.setAdapter(mPagerAdapter); return view1; } class ImageAdapter extends PagerAdapter{ private ArrayList<ImageView> viewlist; public ImageAdapter(ArrayList<ImageView> viewlist) { this.viewlist = viewlist; } @Override public int getCount() { //设置成最大,使用户看不到边界 return Integer.MAX_VALUE; } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public void destroyItem(ViewGroup container, int position, Object object) { //Warning:不要在这里调用removeView } @Override public Object instantiateItem(ViewGroup container, int position) { //对ViewPager页号求模取出View列表中要显示的项 position %= viewlist.size(); if (position < 0){ position = viewlist.size() + position; } ImageView view = viewlist.get(position); //如果View已经在之前添加到了一个父组件,则必须先remove,否则会抛出IllegalStateException。 ViewParent vp = view.getParent(); if (vp != null){ ViewGroup parent = (ViewGroup) vp; parent.removeView(view); } container.addView(view); //add listeners here if necessary return view; } } }
32.956522
84
0.650066
2bcbc1883c5d5d780a04fea312059d98512af11e
57
/** * Vendor-related artifacts. */ package cftc.vendor;
14.25
28
0.684211
f52c86c9154c54f93f662bc1c957a3c53424cb04
428
package ru.job4j.newtracker; import java.util.function.Consumer; public class FindAllAction implements UserAction { @Override public String name() { return "=== Show all items ===="; } @Override public boolean execute(Input input, Tracker tracker, Consumer<String> output) { for (Item e: tracker.findAll()) { output.accept(e.toString()); } return true; } }
22.526316
83
0.619159
4e96f9343d51d1b8f640328a6700b835d0ea92b5
1,002
/* * RT MAP, Home of Professional MAP * Copyright 2016 Bit Main Inc. and/or its affiliates and other contributors * as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. */ package com.muarine.aop.interfaces; /** * com.muarine.aop.interfaces.GreetingImpl * * @author Muarine<maoyun0903@163.com> * @date 16/8/16 * @since 1.0 */ public class GreetingImpl implements Greeting{ @Override public void doSomething() throws Exception { System.out.println("doSomething..."); throw new Exception("throw new Exception"); } public void before(){ System.out.println("before"); } public void after(){ System.out.println("after"); } public static void main(String[] args) throws Exception { GreetingImpl greeting = new GreetingImpl(); greeting.before(); greeting.doSomething(); greeting.after(); } }
22.266667
76
0.658683
14a686e52554b810ad48bd90f8382ef7e684b609
134
/** * 时间自然语言分析工具类: TimeNLPUtil<br> * * 注意:NLP会有一定的识别失败率,在不断迭代开发提高成功率 * * @author xkzhangsan */ package com.xkzhangsan.time.nlp;
16.75
32
0.701493
4e4b87c41957a56a9aa90048e80105c38b507b65
1,656
package at.jku.tk.hermes.protocol; /* Imports ********************************************************************/ import java.util.ArrayList; import java.util.List; import at.jku.tk.hermes.action.Action; /* Class **********************************************************************/ public abstract class AbstractProtocol implements Protocol { /* Fields *****************************************************************/ protected final List<Class<? extends Action>> actions = new ArrayList<Class<? extends Action>>(); /* Methods ****************************************************************/ /* Implementation */ public boolean supportsAction(Class<? extends Action> clazz) { if (clazz == null) { throw new NullPointerException(); } synchronized (actions) { return actions.contains(clazz); } } public List<Class<? extends Action>> getSupportedActions() { synchronized (actions) { List<Class<? extends Action>> clone = new ArrayList<Class<? extends Action>>(); for (Class<? extends Action> clazz : actions) { clone.add(clazz); } return clone; } } /* Protected */ protected boolean addSupportedAction(Class<? extends Action> clazz) { if (clazz == null) { throw new NullPointerException(); } synchronized (actions) { if (! actions.contains(clazz)) { return actions.add(clazz); } } return false; } protected boolean removeSupportedAction(Class<? extends Action> clazz) { if (clazz == null) { throw new NullPointerException(); } synchronized (actions) { return actions.remove(clazz); } } }
25.476923
99
0.542874
db4fa4f5ff348a13d485b288d91eb99be26eb025
657
package org.eno.bot.backend.messages; import com.google.gson.Gson; import javax.websocket.EncodeException; import javax.websocket.Encoder; import javax.websocket.EndpointConfig; import org.eno.bot.api.ChatMessage; public class MessageEncoder implements Encoder.Text<ChatMessage> { private static Gson gson = new Gson(); @Override public String encode(ChatMessage chatMessage) throws EncodeException { return gson.toJson(chatMessage); } @Override public void init(EndpointConfig endpointConfig) { // Custom initialization logic } @Override public void destroy() { // Close resources } }
22.655172
74
0.721461
80a550a0e5fe2d9d89003f95426378897c92c977
1,437
package io.reflectoring.coderadar.graph.projectadministration.analyzerconfig.adapter; import io.reflectoring.coderadar.analyzer.domain.AnalyzerConfiguration; import io.reflectoring.coderadar.graph.analyzer.domain.AnalyzerConfigurationEntity; import io.reflectoring.coderadar.graph.projectadministration.analyzerconfig.AnalyzerConfigurationMapper; import io.reflectoring.coderadar.graph.projectadministration.analyzerconfig.repository.AnalyzerConfigurationRepository; import io.reflectoring.coderadar.projectadministration.port.driven.analyzerconfig.CreateAnalyzerConfigurationPort; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; @Service @AllArgsConstructor public class CreateAnalyzerConfigurationAdapter implements CreateAnalyzerConfigurationPort { private final AnalyzerConfigurationRepository analyzerConfigurationRepository; private final AnalyzerConfigurationMapper analyzerConfigurationMapper = new AnalyzerConfigurationMapper(); @Override public Long create(AnalyzerConfiguration entity, long projectId) { AnalyzerConfigurationEntity analyzerConfigurationEntity = analyzerConfigurationMapper.mapDomainObject(entity); analyzerConfigurationRepository.save(analyzerConfigurationEntity, 0); analyzerConfigurationRepository.addConfigurationToProject( projectId, analyzerConfigurationEntity.getId()); return analyzerConfigurationEntity.getId(); } }
49.551724
119
0.864997
0b8de0f285c92e658e90720d4dd961f441aca9b8
746
package com.sd.lib.im.callback; /** * IM通用的结果回调 * * @param <T> 结果数据类型 */ public abstract class FIMResultCallback<T> { private static final String KEY = "$"; /** * 返回callback对应的tag,可用于ui销毁的时候移除callback * * @return */ public String getTag() { String className = getClass().getName(); final int keyIndex = className.indexOf(KEY); if (keyIndex > 0) className = className.substring(0, keyIndex); return className; } /** * 成功回调 * * @param result */ public abstract void onSuccess(T result); /** * 失败回调 * * @param code 错误码 * @param desc 失败描述 */ public abstract void onError(int code, String desc); }
18.195122
57
0.558981
85093c2466b7d0db099b0679ba39dff33b51b51d
1,027
package com.apparence.camerawesome.sensors; import io.flutter.plugin.common.EventChannel; public class SensorOrientationListener implements EventChannel.StreamHandler, SensorOrientation { EventChannel.EventSink events; @Override public void onListen(Object arguments, EventChannel.EventSink events) { this.events = events; } @Override public void onCancel(Object arguments) { this.events.endOfStream(); this.events = null; } @Override public void notify(int orientation) { if (this.events == null) { return; } switch (orientation) { case 0: events.success("PORTRAIT_UP"); break; case 90: events.success("LANDSCAPE_LEFT"); break; case 270: events.success("LANDSCAPE_RIGHT"); break; case 360: events.success("PORTRAIT_DOWN"); break; } } }
25.04878
97
0.563778
0a56d54a59140b079c130b55f01bdc4254b09c2a
542
package com.quorum.tessera.nacl.jnacl; import com.quorum.tessera.nacl.NaclFacade; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class JnaclFactoryTest { private JnaclFactory jnaclFactory; @Before public void setUp() { this.jnaclFactory = new JnaclFactory(); } @Test public void createInstance() { final NaclFacade result = jnaclFactory.create(); assertThat(result).isNotNull().isExactlyInstanceOf(Jnacl.class); } }
20.846154
72
0.712177
ea69827f455f64cf9b67a57aa6cd9af901ae3b31
2,445
package ie.gmit.dip; import java.io.Serializable; public class StudentManager implements Serializable { private static final long serialVersionUID = 777L; private static final int INITIAL_CAPACITY = 10; private Student[] students = null; public StudentManager() { students = new Student[INITIAL_CAPACITY]; } public boolean add(Student s) { for (int i = 0; i < students.length; i++) { if (students[i] == null) { students[i] = s; return true; } } int index = getExpandedIndex(); students[index] = s; return true; } private int getExpandedIndex() { // Student[] temp = new Student[students.length + 1]; // Very slow... [expanding (and copying) the array by one each time] Student[] temp = new Student[students.length * 2]; // Very fast....Amortized expansion.....! for (int i = 0; i < students.length; i++) { // Copy all from old to new array temp[i] = students[i]; } int index = students.length; students = temp; return index; } public boolean delete(String id) { for (int i = 0; i < students.length; i++) { if (students[i] != null && students[i].getSid().equals(id)) { students[i] = null; return true; } } return false; } public Student getStudentById(String id) { for (int i = 0; i < students.length; i++) { if (students[i] != null && students[i].getSid().equals(id)) { return students[i]; } } return null; } public Student[] getStudentsByFirstName(String fname) { int total = 0; for (int i = 0; i < students.length; i++) { if (students[i] != null && students[i].getFirstName().equalsIgnoreCase(fname)) { total++; } } if (total > 0) { Student[] temp = new Student[total]; int index = 0; for (int i = 0; i < students.length; i++) { if (students[i] != null && students[i].getFirstName().equalsIgnoreCase(fname)) { temp[index] = students[i]; index++; } } return temp; } else { return null; } } public Student[] listAllStudents() { for (int i = 0; i < students.length; i++) { if (students[i] != null) { System.out.println(students[i]); } } return students; } public int size() { int total = 0; for (int i = 0; i < students.length; i++) { if (students[i] != null) { total++; } } return total; } public void debug() { System.out.print("["); for (Student s : students) { System.out.print(", " + s); } System.out.println("]"); } }
21.447368
123
0.60409
be48079de5d6ee88c1be12ca34b9f340a58b05c6
1,493
package org.kuali.ole.describe.bo; import org.kuali.rice.krad.bo.PersistableBusinessObjectBase; import java.io.Serializable; /** * Created with IntelliJ IDEA. * User: Sreekanth * Date: 12/3/12 * Time: 5:08 PM * To change this template use File | Settings | File Templates. */ public class BoundwithSelection extends PersistableBusinessObjectBase implements Serializable { protected boolean selectTree1; protected boolean selectTree2; protected boolean boundWithTree; private String title; private String selectedInstance; public boolean isSelectTree1() { return selectTree1; } public void setSelectTree1(boolean selectTree1) { this.selectTree1 = selectTree1; } public boolean isSelectTree2() { return selectTree2; } public void setSelectTree2(boolean selectTree2) { this.selectTree2 = selectTree2; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public boolean isBoundWithTree() { return boundWithTree; } public void setBoundWithTree(boolean boundWithTree) { this.boundWithTree = boundWithTree; } public String getSelectedInstance() { return selectedInstance; } public void setSelectedInstance(String selectedInstance) { this.selectedInstance = selectedInstance; } }
23.698413
70
0.658406
97b838bbe42e692b0ad7b0219271b1df2e1f008f
627
package net.in.dayan.springdemo.common; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfigurer implements WebMvcConfigurer { @Autowired LogInterceptor logInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(logInterceptor).addPathPatterns("/**").excludePathPatterns("/"); } }
31.35
96
0.808612
aa7593848e10217f88b46c96525c83e097fe064b
354
package com.artarkatesoft.learncamel.springbootapps; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App01FileDbMailApplication { public static void main(String[] args) { SpringApplication.run(App01FileDbMailApplication.class, args); } }
25.285714
68
0.838983
c901022b7e2ae5ace6f385416a3fb92cd742bd07
2,549
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python; import com.intellij.openapi.SdkEditorAdditionalOptionsProvider; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.AdditionalDataConfigurable; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.webcore.packaging.PackagesNotificationPanel; import com.jetbrains.python.packaging.PyPackageManagers; import com.jetbrains.python.packaging.ui.PyInstalledPackagesPanel; import com.jetbrains.python.sdk.PythonSdkType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; public class PythonSdkEditorAdditionalOptionsProvider extends SdkEditorAdditionalOptionsProvider { protected PythonSdkEditorAdditionalOptionsProvider() { super(PythonSdkType.getInstance()); } @Nullable @Override public AdditionalDataConfigurable createOptions(@NotNull Project project, @NotNull Sdk sdk) { return new PythonSdkOptionsAdditionalDataConfigurable(project); } private static class PythonSdkOptionsAdditionalDataConfigurable implements AdditionalDataConfigurable { private final Project myProject; private Sdk mySdk; private PythonSdkOptionsAdditionalDataConfigurable(Project project) { myProject = project; } @Override public void setSdk(Sdk sdk) { mySdk = sdk; } @Nullable @Override public JComponent createComponent() { final PackagesNotificationPanel notificationsArea = new PackagesNotificationPanel(); final JComponent notificationsComponent = notificationsArea.getComponent(); JPanel panel = new JPanel(new BorderLayout()); panel.add(notificationsComponent, BorderLayout.SOUTH); PyInstalledPackagesPanel packagesPanel = new PyInstalledPackagesPanel(myProject, notificationsArea); panel.add(packagesPanel, BorderLayout.CENTER); packagesPanel.updatePackages(PyPackageManagers.getInstance().getManagementService(myProject, mySdk)); packagesPanel.updateNotifications(mySdk); return panel; } @Override public String getTabName() { return "Packages"; } @Override public boolean isModified() { return false; } @Override public void apply() throws ConfigurationException { } @Override public void reset() { } } }
32.265823
140
0.771675
babdd09606108a73cf84df060b23baa830b0c48e
477
// Given two strings, write a method to decide if one is a permutation of the other public class Permutation { public boolean permutation(String s, String t) { if(s.length() != t.length()) { return false; } int[] letters = new int[256]; char[] s_array = s.toCharArray(); for(char c : s_array) { letters[c]++; } for(int i = 0; i < t.length(); i++) { int c = (int)t.charAt(i); if(--letters[c] < 0) { return false; } } return true; } }
18.346154
83
0.587002
b43dacb2764700a6ce155b129f554233c6872ae8
197
// "Make 'b' volatile" "true" import java.util.*; public class Test { private boolean b; public void test() { whi<caret>le (b) { Thread.onSpinWait(); } } }
16.416667
32
0.517766
d8575a04826f1deb695a6a8fa86ff1879bb7865a
469
package com.fundatec.lp3.agregador.domain; import java.util.ArrayList; public class Secreto { private String debug; private ArrayList<Windows> windows = new ArrayList<Windows>(); public String getDebug() { return debug; } public void setDebug(String debug) { this.debug = debug; } public ArrayList<Windows> getWindows() { return windows; } public void setWindows(ArrayList<Windows> windows) { this.windows = windows; } }
18.76
64
0.690832
f5fa72374a8eabb569f90e7a0337e30a5c25f5fe
4,922
package com.microtracing.demo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.caucho.hessian.client.HessianProxyFactory; import com.microtracing.tracespan.Span; import com.microtracing.tracespan.Tracer; public class TimeTest { private static final Logger logger = LoggerFactory.getLogger(TimeTest.class); //auto traced: logtrace.traceMethodProcess=com.microtracing.demo.TimeTest.main; public static void main(String[] args) throws Exception{ //Tracer tracer = Tracer.getTracer(); //Span span = tracer.getCurrentSpan(); //span.start(); TimeTest t = new TimeTest(); try { t.sayHello(); Foo foo = t.new Foo(); foo.bar(); try{ t.httpConnect(); }catch(Exception ex){ ex.printStackTrace(); } }finally { //span.stop(); } } public void sayHello() { try { Thread.sleep(500); logger.info("hello world!" ); } catch (InterruptedException e) { e.printStackTrace(); } } public void httpConnect() throws Exception{ String requestUrl = "http://baidu.com"; Map<String, Object> requestParamsMap = new HashMap<String, Object>(); requestParamsMap.put("areaCode", "001"); requestParamsMap.put("areaCode1", "China"); PrintWriter printWriter = null; BufferedReader bufferedReader = null; // BufferedReader bufferedReader = null; StringBuffer responseResult = new StringBuffer(); StringBuffer params = new StringBuffer(); HttpURLConnection httpURLConnection = null; Iterator it = requestParamsMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry element = (Map.Entry) it.next(); params.append(element.getKey()); params.append("="); params.append(element.getValue()); params.append("&"); } if (params.length() > 0) { params.deleteCharAt(params.length() - 1); } try { URL realUrl = new URL(requestUrl); httpURLConnection = (HttpURLConnection) realUrl.openConnection(); httpURLConnection.setRequestProperty("accept", "*/*"); httpURLConnection.setRequestProperty("connection", "Keep-Alive"); httpURLConnection.setRequestProperty("Content-Length", String.valueOf(params.length())); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); httpURLConnection.setConnectTimeout(1000); printWriter = new PrintWriter(httpURLConnection.getOutputStream()); printWriter.write(params.toString()); printWriter.flush(); int responseCode = httpURLConnection.getResponseCode(); if (responseCode != 200) { logger.warn(" Error===" + responseCode); } else { logger.info("Post Success!"); } bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); String line; while ((line = bufferedReader.readLine()) != null) { responseResult.append("\n").append(line); } logger.info(responseResult.toString()); } catch (Exception e) { logger.warn("send post request error!" + e); throw e; } finally { if (httpURLConnection!=null) httpURLConnection.disconnect(); try { if (printWriter != null) { printWriter.close(); } if (bufferedReader != null) { bufferedReader.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } public String doSomething() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } logger.info("gen uuid"); return java.util.UUID.randomUUID().toString(); } class Foo{ public Foo(){ } public void bar(){ long time = System.currentTimeMillis(); logger.info("time:"+time); doSomething(); } } }
33.944828
110
0.561764
77467fed05ea7c1369c86a3c433b76e1776e42a4
800
package jsheargold.spring_data_jpa_bulk_techniques.jparepository_autoid; import jsheargold.spring_data_jpa_bulk_techniques.common.CarAutoId; import jsheargold.spring_data_jpa_bulk_techniques.JPABulkLoaderTest; import org.springframework.beans.factory.annotation.Autowired; import java.time.LocalDateTime; import java.util.List; import static java.time.temporal.ChronoUnit.MILLIS; public class JPABulkLoaderAutoIdTestNoBatch extends JPABulkLoaderTest { @Autowired private JPABulkLoaderAutoId jpaBulkLoaderAutoId; public long runTest() { List<CarAutoId> cars = createCarsAutoId(); LocalDateTime start = LocalDateTime.now(); jpaBulkLoaderAutoId.loadData(cars); LocalDateTime end = LocalDateTime.now(); return MILLIS.between(start, end); } }
32
72
0.78875
6e844e0be6555b73ba44d51909e5963e05745f7d
1,002
/** * Copyright 2008 - 2015 The Loon Game Engine Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * * @project loon * @author cping * @email:javachenpeng@yahoo.com * @version 0.5 */ package loon.canvas; public interface Path { Path reset(); Path close(); Path moveTo(float x, float y); Path lineTo(float x, float y); Path quadraticCurveTo(float cpx, float cpy, float x, float y); Path bezierTo(float c1x, float c1y, float c2x, float c2y, float x, float y); }
27.081081
80
0.713573
8804b9f9504cc6869e5c98d86f8cea11fdd370f5
11,035
/* * Copyright 2006-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.consol.citrus.javadsl; import com.consol.citrus.dsl.TestNGCitrusTestBuilder; import com.consol.citrus.dsl.annotations.CitrusTest; import com.consol.citrus.message.MessageType; import org.testng.annotations.Test; import java.util.*; /** * @author Christoph Deppisch */ @Test public class MessageChannelJavalTest extends TestNGCitrusTestBuilder { @CitrusTest public void MessageChannelJavalTest() { send("channelRequestSender") .payload("Hello Citrus") .header("Operation", "sayHello"); send("channelRequestSender") .payload("Goodbye Citrus") .header("Operation", "sayGoodBye"); receive("channelResponseReceiver") .selector(Collections.singletonMap("Operation", "sayGoodBye")) .messageType(MessageType.PLAINTEXT) .payload("Goodbye Citrus") .header("Operation", "sayGoodBye"); receive("channelResponseReceiver") .selector(Collections.singletonMap("Operation", "sayHello")) .messageType(MessageType.PLAINTEXT) .payload("Hello Citrus") .header("Operation", "sayHello"); echo("Test root qname message selector"); send("channelRequestSender") .payload("<HelloMessage xmlns=\"http://citrusframework.org/schema\">Hello Citrus</HelloMessage>") .header("Operation", "sayHello"); send("channelRequestSender") .payload("<GoodbyeMessage xmlns=\"http://citrusframework.org/schema\">Goodbye Citrus</GoodbyeMessage>") .header("Operation", "sayGoodBye"); receive("channelResponseReceiver") .selector(Collections.singletonMap("root-qname", "GoodbyeMessage")) .schemaValidation(false) .payload("<GoodbyeMessage xmlns=\"http://citrusframework.org/schema\">Goodbye Citrus</GoodbyeMessage>") .header("Operation", "sayGoodBye"); receive("channelResponseReceiver") .selector(Collections.singletonMap("root-qname", "HelloMessage")) .schemaValidation(false) .payload("<HelloMessage xmlns=\"http://citrusframework.org/schema\">Hello Citrus</HelloMessage>") .header("Operation", "sayHello"); echo("Test root qname message selector with namespaces"); send("channelRequestSender") .payload("<HelloMessage xmlns=\"http://citrusframework.org/helloschema\">Hello Citrus</HelloMessage>") .header("Operation", "sayHello"); send("channelRequestSender") .payload("<GoodbyeMessage xmlns=\"http://citrusframework.org/goodbyeschema\">Goodbye Citrus</GoodbyeMessage>") .header("Operation", "sayGoodBye"); receive("channelResponseReceiver") .selector(Collections.singletonMap("root-qname", "{http://citrusframework.org/goodbyeschema}GoodbyeMessage")) .schemaValidation(false) .payload("<GoodbyeMessage xmlns=\"http://citrusframework.org/goodbyeschema\">Goodbye Citrus</GoodbyeMessage>") .header("Operation", "sayGoodBye"); receive("channelResponseReceiver") .selector(Collections.singletonMap("root-qname", "{http://citrusframework.org/helloschema}HelloMessage")) .schemaValidation(false) .payload("<HelloMessage xmlns=\"http://citrusframework.org/helloschema\">Hello Citrus</HelloMessage>") .header("Operation", "sayHello"); echo("Test xpath message selector"); send("channelRequestSender") .payload("<ns:HelloMessage xmlns:ns=\"http://citrusframework.org/helloschema\">" + "<ns:text language=\"eng\">" + "<ns:value>Hello Citrus</ns:value>" + "</ns:text>" + "<ns:text language=\"de\">" + "<ns:value>Hallo Citrus</ns:value>" + "</ns:text>" + "<ns:text language=\"esp\">" + "<ns:value>Hola Citrus</ns:value>" + "</ns:text>" + "</ns:HelloMessage>") .header("Operation", "sayHello"); send("channelRequestSender") .payload("<ns:GoodbyeMessage xmlns:ns=\"http://citrusframework.org/goodbyeschema\">" + "<ns:text language=\"eng\">" + "<ns:value>Goodbye Citrus</ns:value>" + "</ns:text>" + "<ns:text language=\"de\">" + "<ns:value>Auf Wiedersehen Citrus</ns:value>" + "</ns:text>" + "<ns:text language=\"esp\">" + "<ns:value>Adios Citrus</ns:value>" + "</ns:text>" + "</ns:GoodbyeMessage>") .header("Operation", "sayGoodBye"); receive("channelResponseReceiver") .selector(Collections.singletonMap("xpath://ns:GoodbyeMessage/ns:text[@language='eng']/ns:value", "Goodbye Citrus")) .schemaValidation(false) .payload("<ns:GoodbyeMessage xmlns:ns=\"http://citrusframework.org/goodbyeschema\">" + "<ns:text language=\"eng\">" + "<ns:value>Goodbye Citrus</ns:value>" + "</ns:text>" + "<ns:text language=\"de\">" + "<ns:value>Auf Wiedersehen Citrus</ns:value>" + "</ns:text>" + "<ns:text language=\"esp\">" + "<ns:value>Adios Citrus</ns:value>" + "</ns:text>" + "</ns:GoodbyeMessage>") .header("Operation", "sayGoodBye"); Map<String, String> selectorMap = new HashMap<String, String>(); selectorMap.put("xpath://ns:HelloMessage/ns:text[@language='eng']/ns:value", "Hello Citrus"); selectorMap.put("xpath://ns:HelloMessage/ns:text[@language='de']/ns:value", "Hallo Citrus"); selectorMap.put("xpath://ns:HelloMessage/ns:text[@language='esp']/ns:value", "Hola Citrus"); receive("channelResponseReceiver") .selector(selectorMap) .schemaValidation(false) .payload("<ns:HelloMessage xmlns:ns=\"http://citrusframework.org/helloschema\">" + "<ns:text language=\"eng\">" + "<ns:value>Hello Citrus</ns:value>" + "</ns:text>" + "<ns:text language=\"de\">" + "<ns:value>Hallo Citrus</ns:value>" + "</ns:text>" + "<ns:text language=\"esp\">" + "<ns:value>Hola Citrus</ns:value>" + "</ns:text>" + "</ns:HelloMessage>") .header("Operation", "sayHello"); send("channelRequestSender") .payload("<ns:HelloMessage xmlns:ns=\"http://citrusframework.org/helloschema\">" + "<ns:text language=\"eng\">" + "<ns:value>Hello Citrus</ns:value>" + "</ns:text>" + "<ns:text language=\"de\">" + "<ns:value>Hallo Citrus</ns:value>" + "</ns:text>" + "<ns:text language=\"esp\">" + "<ns:value>Hola Citrus</ns:value>" + "</ns:text>" + "</ns:HelloMessage>") .header("Operation", "sayHello"); send("channelRequestSender") .payload("<ns:GoodbyeMessage xmlns:ns=\"http://citrusframework.org/goodbyeschema\">" + "<ns:text language=\"eng\">" + "<ns:value>Goodbye Citrus</ns:value>" + "</ns:text>" + "<ns:text language=\"de\">" + "<ns:value>Auf Wiedersehen Citrus</ns:value>" + "</ns:text>" + "<ns:text language=\"esp\">" + "<ns:value>Adios Citrus</ns:value>" + "</ns:text>" + "</ns:GoodbyeMessage>") .header("Operation", "sayGoodBye"); receive("channelResponseReceiver") .selector("xpath://ns:GoodbyeMessage/ns:text[@language='eng']/ns:value='Goodbye Citrus'") .schemaValidation(false) .payload("<ns:GoodbyeMessage xmlns:ns=\"http://citrusframework.org/goodbyeschema\">" + "<ns:text language=\"eng\">" + "<ns:value>Goodbye Citrus</ns:value>" + "</ns:text>" + "<ns:text language=\"de\">" + "<ns:value>Auf Wiedersehen Citrus</ns:value>" + "</ns:text>" + "<ns:text language=\"esp\">" + "<ns:value>Adios Citrus</ns:value>" + "</ns:text>" + "</ns:GoodbyeMessage>") .header("Operation", "sayGoodBye"); receive("channelResponseReceiver") .selector("xpath://ns:HelloMessage/ns:text[@language='eng']/ns:value='Hello Citrus'") .schemaValidation(false) .payload("<ns:HelloMessage xmlns:ns=\"http://citrusframework.org/helloschema\">" + "<ns:text language=\"eng\">" + "<ns:value>Hello Citrus</ns:value>" + "</ns:text>" + "<ns:text language=\"de\">" + "<ns:value>Hallo Citrus</ns:value>" + "</ns:text>" + "<ns:text language=\"esp\">" + "<ns:value>Hola Citrus</ns:value>" + "</ns:text>" + "</ns:HelloMessage>") .header("Operation", "sayHello"); } }
48.827434
122
0.502855
2fabf579b7967845d70e7c1b663c6dc586e789e2
128
package rs.math.oop1.z080402.solid.z018.dobarDKlijentServerPrekoKonstruktora; public interface Servis { String getInfo(); }
21.333333
77
0.804688
c2d02951625f3ac69da46fdf40a4815122913773
66
package io.sellmair.kompass.compiler_test; public class Pojc { }
13.2
42
0.787879
9aace28431f194fcaa82afa6dea5d8b4e7650246
2,309
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code, released March 31, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by Netscape are Copyright (C) 1998-1999 * Netscape Communications Corporation. All Rights Reserved. * * Contributor(s): * * IBM * - Binding to permit interfacing between Mozilla and SWT * - Copyright (C) 2003, 2012 IBM Corp. All Rights Reserved. * * ***** END LICENSE BLOCK ***** */ package org.eclipse.swt.internal.mozilla; public class nsIAuthInformation extends nsISupports { static final int LAST_METHOD_ID = nsISupports.LAST_METHOD_ID + 9; public static final String NS_IAUTHINFORMATION_IID_STR = "0d73639c-2a92-4518-9f92-28f71fea5f20"; public static final nsID NS_IAUTHINFORMATION_IID = new nsID(NS_IAUTHINFORMATION_IID_STR); public nsIAuthInformation(long /*int*/ address) { super(address); } public static final int AUTH_HOST = 1; public static final int AUTH_PROXY = 2; public static final int NEED_DOMAIN = 4; public static final int ONLY_PASSWORD = 8; public int GetRealm(long /*int*/ aRealm) { return XPCOM.VtblCall(nsISupports.LAST_METHOD_ID + 2, getAddress(), aRealm); } public int GetUsername(long /*int*/ aUsername) { return XPCOM.VtblCall(nsISupports.LAST_METHOD_ID + 4, getAddress(), aUsername); } public int SetUsername(long /*int*/ aUsername) { return XPCOM.VtblCall(nsISupports.LAST_METHOD_ID + 5, getAddress(), aUsername); } public int GetPassword(long /*int*/ aPassword) { return XPCOM.VtblCall(nsISupports.LAST_METHOD_ID + 6, getAddress(), aPassword); } public int SetPassword(long /*int*/ aPassword) { return XPCOM.VtblCall(nsISupports.LAST_METHOD_ID + 7, getAddress(), aPassword); } }
33.463768
82
0.738848
3c1fd4654a6669fc5c1c34f0d63b19f448f250db
3,440
/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils.impl; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.reflect.Whitebox; import java.io.Serializable; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Unit tests for the {@link PrepareForTestExtractorImpl} class. * */ public class PrepareForTestExtractorImplTest { /** * Makes sure that issue <a * href="http://code.google.com/p/powermock/issues/detail?id=81">81</a> is * solved. */ @Test public void assertThatInterfacesWorks() throws Exception { final PrepareForTestExtractorImpl tested = new PrepareForTestExtractorImpl(); final Set<String> hashSet = new HashSet<String>(); Whitebox.invokeMethod(tested, "addClassHierarchy", hashSet, Serializable.class); assertEquals(1, hashSet.size()); assertEquals(Serializable.class.getName(), hashSet.iterator().next()); } /** * Makes sure that issue <a * href="http://code.google.com/p/powermock/issues/detail?id=111">111</a> is * solved. */ @Test public void shouldFindClassesToPrepareForTestInTheWholeClassHierarchy() throws Exception { final PrepareForTestExtractorImpl tested = new PrepareForTestExtractorImpl(); final String[] classesToPrepare = tested.getTestClasses(PrepareForTestDemoClass.class); assertEquals(8, classesToPrepare.length); final String classPrefix = "Class"; final List<String> classesToPrepareList = Arrays.asList(classesToPrepare); final int noOfClassesExplicitlyPrepared = 5; for (int i = 0; i < noOfClassesExplicitlyPrepared; i++) { final String className = classPrefix + (i + 1); assertTrue("Should prepare " + className, classesToPrepareList.contains(className)); } // We assert that the implicit classes (the test cases) are also added. assertTrue(classesToPrepareList.contains(PrepareForTestDemoClass.class.getName())); assertTrue(classesToPrepareList.contains(PrepareForTestDemoClassParent.class.getName())); assertTrue(classesToPrepareList.contains(PrepareForTestDemoClassGrandParent.class.getName())); } } @PrepareForTest(fullyQualifiedNames = { "Class1", "Class2" }) class PrepareForTestDemoClass extends PrepareForTestDemoClassParent { } @PrepareForTest(fullyQualifiedNames = { "Class3" }) class PrepareForTestDemoClassParent extends PrepareForTestDemoClassGrandParent { } @PrepareForTest(fullyQualifiedNames = { "Class4", "Class5" }) class PrepareForTestDemoClassGrandParent { }
39.090909
103
0.713663
c4dd51783fbeb0ab6c667b7b67f383e56c5102da
833
package com.laaptu.baking.common.image; import android.webkit.URLUtil; import android.widget.ImageView; import com.squareup.picasso.Picasso; import javax.inject.Inject; import javax.inject.Singleton; import static com.laaptu.baking.utils.GeneralUtils.isValidUrl; @Singleton public class ImageLoader { @Inject public ImageLoader() { } public void loadImage(ImageLoadOptions imageLoadOptions, ImageView imageView) { if (isValidUrl(imageLoadOptions.url)) Picasso.get() .load(imageLoadOptions.url) .placeholder(imageLoadOptions.placeHolderDrawableId) .error(imageLoadOptions.errorDrawableId) .into(imageView); else Picasso.get().load(imageLoadOptions.errorDrawableId) .into(imageView); } }
26.03125
83
0.680672
a092e4be2e1d00cf6d74360025b437d277b8fe5c
7,536
/* * Copyright 2014-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wallerlab.yoink.region.partitioner; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.IntStream; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.wallerlab.yoink.api.model.bootstrap.JobParameter; import org.wallerlab.yoink.api.model.cube.Cube; import org.wallerlab.yoink.api.model.cube.GridPoint; import org.wallerlab.yoink.api.model.density.DensityPoint.DensityType; import org.wallerlab.yoink.api.model.molecule.Coord; import org.wallerlab.yoink.api.model.molecule.Molecule; import org.wallerlab.yoink.api.model.region.Region; import org.wallerlab.yoink.api.service.cube.Assigner; import org.wallerlab.yoink.api.service.cube.CubeBuilder; import org.wallerlab.yoink.api.service.region.Partitioner; import org.wallerlab.yoink.cube.domain.SimpleCube; import org.wallerlab.yoink.cube.domain.SimpleGridPoint; import org.wallerlab.yoink.molecule.domain.SimpleCoord; import org.wallerlab.yoink.molecule.domain.SimpleMolecule; import org.wallerlab.yoink.api.service.Calculator; /** * This class is to get those grid points that belong to the intersection region * of QM core region and non-QM core region. Then further calculation(dori and * sedd) will just be carried out on those grid points. * * */ @Service public class CubePartitioner implements Partitioner<List<GridPoint>, DensityType> { @Resource private CubeBuilder<Set<Molecule>> cubeBuilder; @Resource private Assigner<GridPoint, Map<Region.Name, Region>, Region.Name> gridPointAssigner; @Resource private Calculator<Double, Coord, Molecule> closestDistanceToMoleculeCalculator; @Value("${yoink.job.debug}") private boolean debug = false; @Value("${yoink.job.dis_cutoff}") private double dis_cutoff = 10.0; /** * loop over all grid points in the cube, find the grid points whose two * closest neighbours are from different regions(QM core region and non-QM * core region ). * * @param regions * - a Map, Region.Name * {@link org.wallerlab.yoink.api.model.region.Region.Name } as * key, Region * {@link org.wallerlab.yoink.api.model.region.Region} as value * @param parameters * - a Map, JobParameter * {@link org.wallerlab.yoink.api.model.bootstrap.JobParameter} * as Key, Object {@link java.lang.Object} as value * @param densityType * - * {@link org.wallerlab.yoink.api.model.density.DensityPoint.DensityType} * @return gridPointsForFurtherAnalysis - a list of gridPoint * {@link org.wallerlab.yoink.api.model.cube.GridPoint } */ public List<GridPoint> partition(Map<Region.Name, Region> regions, Map<JobParameter, Object> parameters, DensityType densityType) { // initialize double[] xyzStepSize = getXyzStepSizeByDensityType(parameters, densityType); // Cube cube = new SimpleCube(xyzStepSize); Region.Name cubeRegionName = (Region.Name) parameters .get(JobParameter.REGION_CUBE); Set<Molecule> moleculesInCube = regions.get(cubeRegionName) .getMolecules(); Cube cube = cubeBuilder.build(xyzStepSize, moleculesInCube); // gridPointsForFurtherAnalysis List<GridPoint> gridPointsForFurtherAnalysis = getGridPointsWillBeCalculated( regions, cube, cubeRegionName); return gridPointsForFurtherAnalysis; } /* * DORI and SEDD calculations use different xyz step sizes. */ private double[] getXyzStepSizeByDensityType( Map<JobParameter, Object> parameters, DensityType densityType) { double[] xyzStepSize; // get xyz step size switch (densityType) { case SEDD: xyzStepSize = (double[]) parameters.get(JobParameter.SEDD_STEPSIZE); break; case DORI: xyzStepSize = (double[]) parameters.get(JobParameter.DORI_STEPSIZE); break; default: throw new IllegalArgumentException("invalid name"); } return xyzStepSize; } private List<GridPoint> getGridPointsWillBeCalculated( Map<Region.Name, Region> regions, Cube cube, Region.Name cubeRegionName) { List<Coord> coordinates = cube.getCoordinates(); List<GridPoint> gridPointsTemp = checkEveryGridPoint(regions, cubeRegionName, coordinates); return gridPointsTemp; } private List<GridPoint> checkEveryGridPoint( Map<Region.Name, Region> regions, Region.Name cubeRegionName, List<Coord> coordinates) { if (debug) { System.out.println("before: coordinates.parallelStream().forEach" + System.currentTimeMillis()); } // get molecules within dis_cutoff for each coordinate Set<Molecule> molecules = regions.get(cubeRegionName).getMolecules(); Set[] initialValues = new Set[coordinates.size()]; List<Set> msl = Arrays.asList(initialValues); IntStream .range(0, coordinates.size()) .parallel() .forEach( nCoord -> { Set<Molecule> ms = Collections .synchronizedSet(new HashSet<Molecule>()); molecules .parallelStream() .forEach( m -> { double distance = closestDistanceToMoleculeCalculator.calculate( coordinates.get(nCoord), m); if (distance < dis_cutoff) { ms.add(m); } }); msl.set(nCoord, ms); }); if (debug) { System.out .println("start: cube partitioner ridPointsTemp.parallelStream().forEach(" + System.currentTimeMillis()); } // generate grid point for each coordinate List<GridPoint> gridPointsTemp = Collections .synchronizedList(new ArrayList<GridPoint>()); IntStream.range(0, coordinates.size()).parallel().forEach( nCoord -> { if (msl.get(nCoord).size() > 1) { SimpleGridPoint gridPoint = new SimpleGridPoint(); gridPoint.setCoordinate(coordinates.get(nCoord)); gridPoint.setIndexInCube(nCoord); gridPoint.setMolecules(msl.get(nCoord)); gridPointsTemp.add(gridPoint); } }); if (debug) { System.out .println("middle: cube partitioner gridPointsTemp.parallelStream().forEach(" + System.currentTimeMillis()); } // get gridPoints needing further analysis List<GridPoint> gridPoints = Collections .synchronizedList(new ArrayList<GridPoint>()); gridPointsTemp.parallelStream().forEach( gpt -> { Map<String, Object> properties = gridPointAssigner.assign( gpt, regions, cubeRegionName); if (!properties.isEmpty()) { gpt.setProperties(properties); gridPoints.add(gpt); } }); if (debug) { System.out .println("after: cube partitioner ridPointsTemp.parallelStream().forEach(" + System.currentTimeMillis()); System.out.println("grid points for analysis"+gridPointsTemp.size()); } return gridPoints; } }
32.068085
86
0.714968
70c719b7a555d7305098314f60e80cd1d13c7d41
375
package net.minecraft.world.level.levelgen.feature.configurations; import java.util.stream.Stream; import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; public interface FeatureConfiguration { NoneFeatureConfiguration NONE = NoneFeatureConfiguration.INSTANCE; default Stream<ConfiguredFeature<?, ?>> getFeatures() { return Stream.empty(); } }
31.25
69
0.792
0cd6f9d7c2212c2b7a84ff8df9daca1177ea2c83
8,093
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client package|; end_package begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertNotNull import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertNull import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertTrue import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|Cell import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|HBaseClassTestRule import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|HBaseTestingUtility import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|HConstants import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|KeyValue import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|MetaTableAccessor import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|testclassification operator|. name|MediumTests import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|testclassification operator|. name|MiscTests import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|After import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Before import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|ClassRule import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|experimental operator|. name|categories operator|. name|Category import|; end_import begin_comment comment|/** * Test MetaTableAccessor but without spinning up a cluster. * We mock regionserver back and forth (we do spin up a zk cluster). */ end_comment begin_class annotation|@ name|Category argument_list|( block|{ name|MiscTests operator|. name|class block|, name|MediumTests operator|. name|class block|} argument_list|) specifier|public class|class name|TestMetaTableAccessorNoCluster block|{ annotation|@ name|ClassRule specifier|public specifier|static specifier|final name|HBaseClassTestRule name|CLASS_RULE init|= name|HBaseClassTestRule operator|. name|forClass argument_list|( name|TestMetaTableAccessorNoCluster operator|. name|class argument_list|) decl_stmt|; specifier|private specifier|static specifier|final name|HBaseTestingUtility name|UTIL init|= operator|new name|HBaseTestingUtility argument_list|() decl_stmt|; annotation|@ name|Before specifier|public name|void name|before parameter_list|() throws|throws name|Exception block|{ name|UTIL operator|. name|startMiniZKCluster argument_list|() expr_stmt|; block|} annotation|@ name|After specifier|public name|void name|after parameter_list|() throws|throws name|IOException block|{ name|UTIL operator|. name|shutdownMiniZKCluster argument_list|() expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testGetHRegionInfo parameter_list|() throws|throws name|IOException block|{ name|assertNull argument_list|( name|MetaTableAccessor operator|. name|getRegionInfo argument_list|( operator|new name|Result argument_list|() argument_list|) argument_list|) expr_stmt|; name|List argument_list|< name|Cell argument_list|> name|kvs init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; name|Result name|r init|= name|Result operator|. name|create argument_list|( name|kvs argument_list|) decl_stmt|; name|assertNull argument_list|( name|MetaTableAccessor operator|. name|getRegionInfo argument_list|( name|r argument_list|) argument_list|) expr_stmt|; name|byte index|[] name|f init|= name|HConstants operator|. name|CATALOG_FAMILY decl_stmt|; comment|// Make a key value that doesn't have the expected qualifier. name|kvs operator|. name|add argument_list|( operator|new name|KeyValue argument_list|( name|HConstants operator|. name|EMPTY_BYTE_ARRAY argument_list|, name|f argument_list|, name|HConstants operator|. name|SERVER_QUALIFIER argument_list|, name|f argument_list|) argument_list|) expr_stmt|; name|r operator|= name|Result operator|. name|create argument_list|( name|kvs argument_list|) expr_stmt|; name|assertNull argument_list|( name|MetaTableAccessor operator|. name|getRegionInfo argument_list|( name|r argument_list|) argument_list|) expr_stmt|; comment|// Make a key that does not have a regioninfo value. name|kvs operator|. name|add argument_list|( operator|new name|KeyValue argument_list|( name|HConstants operator|. name|EMPTY_BYTE_ARRAY argument_list|, name|f argument_list|, name|HConstants operator|. name|REGIONINFO_QUALIFIER argument_list|, name|f argument_list|) argument_list|) expr_stmt|; name|RegionInfo name|hri init|= name|MetaTableAccessor operator|. name|getRegionInfo argument_list|( name|Result operator|. name|create argument_list|( name|kvs argument_list|) argument_list|) decl_stmt|; name|assertTrue argument_list|( name|hri operator|== literal|null argument_list|) expr_stmt|; comment|// OK, give it what it expects name|kvs operator|. name|clear argument_list|() expr_stmt|; name|kvs operator|. name|add argument_list|( operator|new name|KeyValue argument_list|( name|HConstants operator|. name|EMPTY_BYTE_ARRAY argument_list|, name|f argument_list|, name|HConstants operator|. name|REGIONINFO_QUALIFIER argument_list|, name|RegionInfo operator|. name|toByteArray argument_list|( name|RegionInfoBuilder operator|. name|FIRST_META_REGIONINFO argument_list|) argument_list|) argument_list|) expr_stmt|; name|hri operator|= name|MetaTableAccessor operator|. name|getRegionInfo argument_list|( name|Result operator|. name|create argument_list|( name|kvs argument_list|) argument_list|) expr_stmt|; name|assertNotNull argument_list|( name|hri argument_list|) expr_stmt|; name|assertTrue argument_list|( name|RegionInfo operator|. name|COMPARATOR operator|. name|compare argument_list|( name|hri argument_list|, name|RegionInfoBuilder operator|. name|FIRST_META_REGIONINFO argument_list|) operator|== literal|0 argument_list|) expr_stmt|; block|} block|} end_class end_unit
14.529623
814
0.805387
fda797b738da3949109a1f01519cc52734f60ba7
2,317
/* * Copyright 2021 The University of Manchester * * 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.acuity.visualisations.rawdatamodel.vo; import com.acuity.visualisations.rawdatamodel.util.Column; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; import java.io.Serializable; import java.util.Date; @Getter @EqualsAndHashCode(of = "id") @ToString @NoArgsConstructor @AllArgsConstructor @Builder(toBuilder = true) @AcuityEntity(version = 9) public class PkResultRaw implements HasStringId, HasSubjectId, Serializable { private String id; private String subjectId; @Column(columnName = "parameter", order = 5, displayName = "Parameter") private String parameter; @Column(columnName = "parameterValue", order = 6, displayName = "Value") private Double parameterValue; @Column(columnName = "parameterUnit", order = 7, displayName = "Unit") private String parameterUnit; @Column(columnName = "analyte", order = 1, displayName = "Analyte") private String analyte; private Date visitDate; private Integer visitNumber; @Column(columnName = "treatment", order = 8, displayName = "Nominal dose") private Double treatment; @Column(columnName = "cycle", order = 2, displayName = "Cycle") private String treatmentCycle; @Column(columnName = "protocolScheduleStartDay", order = 3, displayName = "Nominal day") private String protocolScheduleStartDay; @Column(columnName = "visit", order = 4, displayName = "Visit") private String visit; @Column(columnName = "actualDose", order = 9, displayName = "Actual administered dose") private Double actualDose; private String bestOverallResponse; }
36.777778
92
0.742339
ccf53985521239329a0e3bcb2f6d27c145cc1b64
2,585
/* * Copyright 2018 Netflix, 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.netflix.titus.common.framework.scheduler.endpoint; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.netflix.titus.common.framework.scheduler.LocalScheduler; import com.netflix.titus.common.framework.scheduler.model.Schedule; import com.netflix.titus.common.runtime.TitusRuntime; @Path("/api/diagnostic/localScheduler") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Singleton public class LocalSchedulerResource { private final LocalScheduler localScheduler; @Inject public LocalSchedulerResource(TitusRuntime titusRuntime) { this.localScheduler = titusRuntime.getLocalScheduler(); } @GET @Path("/schedules") public List<Schedule> getActiveSchedules() { return localScheduler.getActiveSchedules(); } @GET @Path("/schedules/{name}") public Schedule getActiveSchedule(@PathParam("name") String name) { return localScheduler.getActiveSchedules().stream() .filter(s -> s.getDescriptor().getName().equals(name)) .findFirst() .orElseThrow(() -> new WebApplicationException(Response.status(404).build())); } @GET @Path("/archived") public List<Schedule> getArchivedSchedules() { return localScheduler.getArchivedSchedules(); } @GET @Path("/archived/{name}") public Schedule getArchivedSchedule(@PathParam("name") String name) { return localScheduler.getArchivedSchedules().stream() .filter(s -> s.getDescriptor().getName().equals(name)) .findFirst() .orElseThrow(() -> new WebApplicationException(Response.status(404).build())); } }
33.141026
94
0.712186
a23d6994f022df27563c206179b157f66a1a274a
385
package com.wu.gulimall.gulimall_product.dao; import com.wu.gulimall.gulimall_product.entity.SpuInfoEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * spu信息 * * @author chenshun * @email 2947323341@qq.com * @date 2021-03-05 21:27:41 */ @Mapper public interface SpuInfoDao extends BaseMapper<SpuInfoEntity> { }
21.388889
63
0.771429
c7f97ca5a990439506b6b1f2800e038a359622d3
8,413
package in.nacode.nacode; import android.content.Intent; import android.graphics.Bitmap; import android.icu.text.SimpleDateFormat; import android.net.Uri; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.CardView; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.google.android.gms.tasks.Continuation; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.firestore.FieldValue; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import com.theartofdev.edmodo.cropper.CropImage; import com.theartofdev.edmodo.cropper.CropImageView; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Objects; import id.zelory.compressor.Compressor; public class CreateQuestion extends AppCompatActivity { public EditText cqTitle, cqDesc, cqCode,cqTopic; public ImageView cqImg; private Button qSubmit; SimpleDateFormat sdf; private CardView cardView; public Uri uri; private byte[] imgData; private FirebaseDatabase firebaseDatabase; private FirebaseAuth firebaseAuth; public DatabaseReference cq_databaseReference; private StorageReference firebaseStorage; private boolean na; @RequiresApi(api = Build.VERSION_CODES.N) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_question); //Firebase firebaseDatabase = FirebaseDatabase.getInstance(); firebaseStorage = FirebaseStorage.getInstance().getReference(); firebaseAuth = FirebaseAuth.getInstance(); //Getting all the details from user cqTitle = (EditText) findViewById(R.id.cq_qTitle); cqDesc = (EditText) findViewById(R.id.cq_qDesc); cqCode = (EditText) findViewById(R.id.cq_qCode); cqTopic = (EditText)findViewById(R.id.cq_qTopic); cqImg = (ImageView) findViewById(R.id.cq_qImg); qSubmit = (Button) findViewById(R.id.cq_qSubmit); sdf = new SimpleDateFormat("yyyy-MM-dd"); String date = sdf.format(new Date()); cardView = (CardView) findViewById(R.id.cq_qCardView); cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CropImage.activity() .setGuidelines(CropImageView.Guidelines.ON) .setMinCropResultSize(512, 512) .setAspectRatio(1, 1) .start(CreateQuestion.this); } }); qSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (cqTitle.getText().toString().trim().isEmpty() || cqDesc.getText().toString().isEmpty()) { Toast.makeText(CreateQuestion.this, "Please fill details", Toast.LENGTH_SHORT).show(); } else { final StorageReference mStoragePath = firebaseStorage.child("qa").child(cqTitle.getText().toString() + ".jpg"); UploadTask imagePath = mStoragePath.putBytes(imgData); Task<Uri> urlTask = imagePath.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() { @Override public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception { if (!task.isSuccessful()) { Toast.makeText(CreateQuestion.this, "Please check your Internet", Toast.LENGTH_SHORT).show(); } return mStoragePath.getDownloadUrl(); } }).addOnCompleteListener(new OnCompleteListener<Uri>() { @Override public void onComplete(@NonNull Task<Uri> task) { Uri downloadUri = task.getResult(); HashMap<String, Object> cqHashMap = new HashMap<>(); cqHashMap.put("qTitle", cqTitle.getText().toString().trim()); cqHashMap.put("qDesc", cqDesc.getText().toString()); cqHashMap.put("qCode", cqCode.getText().toString().trim()); cqHashMap.put("qTopic", cqTopic.getText().toString().trim()); cqHashMap.put("qImgUrl", downloadUri.toString()); cqHashMap.put("qTime",sdf.format(new Date())); cqHashMap.put("qUserDetails",firebaseAuth.getCurrentUser().getUid()); cq_databaseReference = FirebaseDatabase.getInstance().getReference().child("qa").child(cqTitle.getText().toString()); cq_databaseReference.setValue(cqHashMap) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(CreateQuestion.this, "Something went Wrong !", Toast.LENGTH_SHORT).show(); } }) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { Toast.makeText(CreateQuestion.this, "Successful", Toast.LENGTH_SHORT).show(); Intent goToQA = new Intent(CreateQuestion.this, MainActivity.class); startActivity(goToQA); finish(); } }); } }); } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { CropImage.ActivityResult result = CropImage.getActivityResult(data); if (resultCode == RESULT_OK) { uri = result.getUri(); if (uri.toString().isEmpty()) { Toast.makeText(this, "Please insert image !", Toast.LENGTH_SHORT).show(); } else { cqImg.setImageURI(uri); File actucalImage = new File(result.getUri().getPath()); try { Bitmap compressedImage = new Compressor(CreateQuestion.this) .setMaxHeight(250) .setMaxWidth(250) .setQuality(50) .compressToBitmap(actucalImage); ByteArrayOutputStream baos = new ByteArrayOutputStream(); compressedImage.compress(Bitmap.CompressFormat.JPEG, 50, baos); imgData = baos.toByteArray(); } catch (IOException e) { e.printStackTrace(); } } } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) { Exception error = result.getError(); } } } }
38.591743
145
0.574111
4a242012f4b7908e3f4b68fe5d0e38a40cd8c38d
1,843
package uk.gov.hmcts.reform.divorce.documentgenerator.management.test.endpoint; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import uk.gov.hmcts.reform.divorce.documentgenerator.management.test.stub.DocumentDownloadService; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @WebMvcTest(DocumentDownloadTestController.class) @TestPropertySource(properties = { "evidence-management-api.service.stub.enabled=true"}) public class DocumentDownloadTestControllerUTest { @Autowired private MockMvc mockMvc; @MockBean private DocumentDownloadService documentDownloadService; @Test public void whenDownloadDocument_thenReturnProperResponse() throws Exception { final String filename = "fileName"; final byte[] data = {1}; final String contextPath = "/test/documents/" + filename; when(documentDownloadService.getDocument(filename)).thenReturn(data); mockMvc.perform(get(contextPath)) .andExpect(status().isOk()) .andExpect(content().bytes(data)) .andExpect(content().contentType(MediaType.APPLICATION_PDF)); } }
41.886364
98
0.78242
744c356cd327ddf2af5bec40109165bbe5a6907e
3,588
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dashbuilder.backend; import static org.dashbuilder.backend.RuntimeOptions.DASHBOARD_EXTENSION; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Observes; import javax.inject.Inject; import org.dashbuilder.shared.model.DashbuilderRuntimeMode; import org.dashbuilder.shared.service.ExternalImportService; import org.dashbuilder.shared.service.RuntimeModelRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.quarkus.runtime.StartupEvent; /** * Responsible for runtime model files loading. * */ @ApplicationScoped public class RuntimeModelLoader { Logger logger = LoggerFactory.getLogger(RuntimeModelLoader.class); @Inject RuntimeModelRegistry runtimeModelRegistry; @Inject ExternalImportService externalImportService; @Inject RuntimeOptions runtimeOptions; void runtimeModelSetup(@Observes StartupEvent startupEvent) { setupBaseDir(); runtimeOptions.importFileLocation().ifPresent(this::registerStaticModel); if (runtimeOptions.isMultipleImport() && !runtimeOptions.importFileLocation().isPresent()) { runtimeModelRegistry.setMode(DashbuilderRuntimeMode.MULTIPLE_IMPORT); loadAvailableModels(); } } protected void registerStaticModel(String importFile) { var relativeLocation = Paths.get(System.getProperty("user.dir"), importFile); if (new File(importFile).exists()) { runtimeModelRegistry.registerFile(importFile); } else if (Files.exists(relativeLocation)) { runtimeModelRegistry.registerFile(relativeLocation.toString()); } else if (runtimeOptions.isAllowExternal()) { externalImportService.registerExternalImport(importFile); } else { throw new IllegalArgumentException("Not able to register default model from path: " + importFile); } runtimeModelRegistry.setMode(DashbuilderRuntimeMode.STATIC); } /** * Create, if do not exist, the base directory for runtime models */ protected void setupBaseDir() { Paths.get(runtimeOptions.getImportsBaseDir()).toFile().mkdirs(); } protected void loadAvailableModels() { logger.info("Registering existing models"); try (var walk = Files.walk(Paths.get(runtimeOptions.getImportsBaseDir()), 1)) { walk.filter(p -> p.toFile().isFile() && p.toString().toLowerCase().endsWith(DASHBOARD_EXTENSION)) .map(Object::toString) .forEach(p -> { logger.info("Registering {}", p); runtimeModelRegistry.registerFile(p); logger.info("Sucessfully Registered {}", p); }); } catch (Exception e) { throw new RuntimeException("Error registering existing models.", e); } } }
35.176471
110
0.697603
b10a99146b79971a84d3cfd6bd898c59da9870d0
3,615
/* Copyright 2012-13 Simon Farrow <simon.farrow1@nhs.net> 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 uk.nhs.digital.mait.tkwx.tk.internalservices.validation; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author sifa2 */ public class RulesetMetadataTest { private RulesetMetadata instance; public RulesetMetadataTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { instance = new RulesetMetadata(); } @After public void tearDown() { } /** * Test of getName method, of class RulesetMetadata. */ @Test public void testGetName() { System.out.println("getName"); String expResult = "name"; instance.setName(expResult); String result = instance.getName(); assertEquals(expResult, result); } /** * Test of getVersion method, of class RulesetMetadata. */ @Test public void testGetVersion() { System.out.println("getVersion"); String expResult = "version"; instance.setVersion(expResult); String result = instance.getVersion(); assertEquals(expResult, result); } /** * Test of getTimestamp method, of class RulesetMetadata. */ @Test public void testGetTimestamp() { System.out.println("getTimestamp"); String expResult = "ts"; instance.setTimestamp(expResult); String result = instance.getTimestamp(); assertEquals(expResult, result); } /** * Test of getAuthor method, of class RulesetMetadata. */ @Test public void testGetAuthor() { System.out.println("getAuthor"); String expResult = "author"; instance.setAuthor(expResult); String result = instance.getAuthor(); assertEquals(expResult, result); } /** * Test of setName method, of class RulesetMetadata. */ @Test public void testSetName() { System.out.println("setName"); String s = ""; instance.setName(s); } /** * Test of setVersion method, of class RulesetMetadata. */ @Test public void testSetVersion() { System.out.println("setVersion"); String s = ""; instance.setVersion(s); } /** * Test of setTimestamp method, of class RulesetMetadata. */ @Test public void testSetTimestamp() { System.out.println("setTimestamp"); String s = ""; instance.setTimestamp(s); } /** * Test of setAuthor method, of class RulesetMetadata. */ @Test public void testSetAuthor() { System.out.println("setAuthor"); String s = ""; instance.setAuthor(s); } }
25.457746
74
0.601383
4666215906e034dbee35f2102ef3027319575407
3,516
package org.develnext.jphp.zend.ext.standard; import org.develnext.jphp.zend.ext.standard.StringFunctions; import org.junit.Assert; import org.junit.Test; public class StringFunctionsTest { @Test public void testToUUChar() { Assert.assertEquals('`', StringFunctions.toUUChar(0)); Assert.assertEquals(' ', StringFunctions.toUUChar(64)); } @Test public void testIsWhitespace() { Assert.assertFalse(StringFunctions.isWhitespace('\u0000')); Assert.assertTrue(StringFunctions.isWhitespace('\t')); Assert.assertTrue(StringFunctions.isWhitespace('\r')); Assert.assertTrue(StringFunctions.isWhitespace('\n')); Assert.assertTrue(StringFunctions.isWhitespace(' ')); } @Test public void testToUpperCase() { Assert.assertEquals('\u0000', StringFunctions.toUpperCase('\u0000')); Assert.assertEquals('{', StringFunctions.toUpperCase('{')); Assert.assertEquals('Z', StringFunctions.toUpperCase('z')); } @Test public void testToHexChar() { Assert.assertEquals('c', StringFunctions.toHexChar(12)); Assert.assertEquals('0', StringFunctions.toHexChar(0)); } @Test public void testToUpperHexChar() { Assert.assertEquals('8', StringFunctions.toUpperHexChar(8)); Assert.assertEquals('A', StringFunctions.toUpperHexChar(10)); } @Test public void testHexToDigit() { Assert.assertEquals(0, StringFunctions.hexToDigit('0')); Assert.assertEquals(15, StringFunctions.hexToDigit('F')); Assert.assertEquals(15, StringFunctions.hexToDigit('f')); Assert.assertEquals(-1, StringFunctions.hexToDigit('`')); Assert.assertEquals(-1, StringFunctions.hexToDigit('@')); Assert.assertEquals(-1, StringFunctions.hexToDigit(' ')); Assert.assertEquals(-1, StringFunctions.hexToDigit('r')); } @Test public void testOctToDigit() { Assert.assertEquals(0, StringFunctions.octToDigit('0')); Assert.assertEquals(-1, StringFunctions.octToDigit('8')); Assert.assertEquals(-1, StringFunctions.octToDigit(' ')); } @Test public void testLtrim() { Assert.assertEquals("1a 2b 3c", StringFunctions.ltrim(" 1a 2b 3c")); Assert.assertEquals("3", StringFunctions.ltrim("3", "2")); Assert.assertEquals("", StringFunctions.ltrim("3", "A1B2C3")); } @Test public void testRtrim() { Assert.assertEquals("", StringFunctions.rtrim("1")); Assert.assertEquals("1234", StringFunctions.rtrim("1234")); Assert.assertEquals("", StringFunctions.rtrim("\'", "2")); Assert.assertEquals("1234", StringFunctions.rtrim("1234", "2")); Assert.assertEquals("a\'b\'", StringFunctions.rtrim("a\'b\'c", "1a 2b 3c")); } @Test public void testStrcoll() { Assert.assertEquals(-1, StringFunctions.strcoll(",", "bar")); Assert.assertEquals(1, StringFunctions.strcoll("foo", "bar")); Assert.assertEquals(0, StringFunctions.strcoll("foo", "foo")); } @Test public void test_substr_replace() { Assert.assertEquals("barfoobar", StringFunctions._substr_replace("foobar", "bar", 0, 0)); Assert.assertEquals("foobarbar", StringFunctions._substr_replace("foobar", "bar", 7, 0)); Assert.assertEquals("foobabarr", StringFunctions._substr_replace("foobar", "bar", -1, 0)); Assert.assertEquals("bar", StringFunctions._substr_replace("", "bar", -1, 0)); Assert.assertEquals("barr", StringFunctions._substr_replace("foobar", "bar", 0, -1)); Assert.assertEquals("bar", StringFunctions._substr_replace("foobar", "bar", 0, 7)); } }
35.16
80
0.691126
bab5f073834e7533262b5b3f6aa03f8363950777
966
package pl.sflg; public class GameState { private int money = 2000; private final int winLimit = 5000; private final double timeBetweenClick = 0.4; /** * 0 - bet * 1 - player draw two random cards * 2 - player turn, choice if draw cards * 3 - croupier turn */ GState state = GState.BET; // 0 początek double gameTime = 0.0; double clickedTime = 0.0; public int getMoney() { return money; } public void addMoney(int money) { this.money += money; } //positive win, negative lost, nautral not over public int isGameOver(){ if(money <= 0) return -1; if(money > winLimit) return 1; return 0; } public void progressTime(double delta) { gameTime += delta; clickedTime -= delta; } public void clicked(){ clickedTime = timeBetweenClick; } } enum GState { BET, CROUPIER, PLAYER, RESOULT, END; }
20.125
51
0.57971
3567877b51552f70cf9c9c97f720c6b77ab9c97f
434
package com.tngtech.archunit.lang.conditions.testobjects; public class TargetClass { public static final String publicStringField = "publicString"; public static final String appendStringMethod = "appendString"; public static final Class<?>[] appendStringParams = new Class<?>[]{String.class}; public String publicString; public String appendString(String string) { return publicString + string; } }
33.384615
85
0.737327
9eb17c974e128f13604814ac9bc1de11b75b9273
1,480
package com.hibernate.checker.model; import java.time.LocalDateTime; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import com.fasterxml.jackson.annotation.JsonBackReference; /*import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter;*/ @Entity /* * @Setter * * @Getter * * @NoArgsConstructor * * @AllArgsConstructor */ public class Posts { @Id private Integer id; @Column private LocalDateTime postDates; @ManyToOne @JoinColumn(name="user_id") private Users user; @Column private String details; // default constructor public Posts() { } // parameterized constructor public Posts(Integer id, LocalDateTime postDates, Users user, String details) { super(); this.id = id; this.postDates = postDates; this.user = user; this.details = details; } // getter & setter public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public LocalDateTime getPostDates() { return postDates; } public void setPostDates(LocalDateTime postDates) { this.postDates = postDates; } @JsonBackReference public Users getUser() { return user; } public void setUser(Users user) { this.user = user; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } }
17.209302
80
0.726351
80583e62d12fb6876478b9a3703250aac3f582a2
574
package com.lingchaomin.auth.server.web.base.swagger.response.dto.impl; import com.lingchaomin.auth.server.core.user.entity.QQUser; import com.lingchaomin.auth.server.web.base.swagger.response.dto.base.SwaggerOperateResultBaseDto; /** * @author minlingchao * @version 1.0 * @date 2017/2/24 下午1:34 * @description qq用户返回结果 */ public class QQUserOperResultDto extends SwaggerOperateResultBaseDto { private QQUser result; public QQUser getResult() { return result; } public void setResult(QQUser result) { this.result = result; } }
23.916667
98
0.731707
fb65e8b252ae9d1c53b6ec35a954ecbf76fbd27c
1,635
package org.genesis.jaxb.object.util; import org.genesis.jaxb.object.entity.User; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.File; /** * @author KG(Kelvin Gu) * @ClassName: JaxbUtil * @Package org.genesis.jaxb.object.util * @Description: jaxb util * @date 2018/8/7 10:36 */ public class JaxbUtil { public static <T> Boolean convertToXml(Object obj, Class<T> clz, File file) { try { JAXBContext jaxbContext = JAXBContext.newInstance(clz); Marshaller marshaller = jaxbContext.createMarshaller(); //格式化输出,即按标签自动换行,否则就是一行输出 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //设置编码(默认编码就是utf-8) marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); //是否省略xml头信息,默认不省略(false) marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false); marshaller.marshal(obj, file); //控制台输出 marshaller.marshal(obj, System.out); return true; } catch (JAXBException e) { e.printStackTrace(); return false; } } public static <T> T convertToJavaBean(Class<T> clz, File file) { try { JAXBContext jaxbContext = JAXBContext.newInstance(clz); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); T t = (T) unmarshaller.unmarshal(file); return t; } catch (JAXBException e) { e.printStackTrace(); } return null; } }
30.849057
81
0.626911
0e9ea24b85d22164128425f06924016f7fa53dd9
8,300
package com.networknt.eventuate.common.sync; import com.networknt.eventuate.common.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; /** * A convenience class, with a synchronous-style API that provides a simplified interface for creating and updating aggregates. * @param <T> the aggregate class, which is a subtype of CommandProcessingAggregate * @param <CT> the aggregate's command class, a subtype of command * * <p>For example: * * <pre class="code"> * public class AccountService { * private final AggregateRepository&gt;Account, AccountCommand&gt; accountRepository; * * public AccountService(AggregateRepository&gt;Account, AccountCommand&gt; accountRepository) { * this.accountRepository = accountRepository; * } * * public EntityWithIdAndVersion&gt;Account&gt; openAccount(BigDecimal initialBalance) { * return accountRepository.save(new CreateAccountCommand(initialBalance)); * } * } *</pre> * * @see CommandProcessingAggregate * @see Command */ public class AggregateRepository<T extends CommandProcessingAggregate<T, CT>, CT extends Command> { private static Logger logger = LoggerFactory.getLogger(AggregateRepository.class); private Class<T> clasz; private EventuateAggregateStore aggregateStore; private MissingApplyEventMethodStrategy missingApplyEventMethodStrategy = new DefaultMissingApplyEventMethodStrategy(); /** * Constructs a new AggregateRepository for the specified aggregate class and aggregate store * * @param clasz the class of the aggregate * @param aggregateStore the aggregate store */ public AggregateRepository(Class<T> clasz, EventuateAggregateStore aggregateStore) { this.clasz = clasz; this.aggregateStore = aggregateStore; } public void setMissingApplyEventMethodStrategy(MissingApplyEventMethodStrategy missingApplyEventMethodStrategy) { this.missingApplyEventMethodStrategy = missingApplyEventMethodStrategy; } /** * Create a new Aggregate by processing a command and persisting the events * * @param cmd the command to process * @return the newly persisted aggregate */ public EntityWithIdAndVersion<T> save(CT cmd) { return save(cmd, Optional.empty()); } /** * Create a new Aggregate by processing a command and persisting the events * * @param cmd the command to process * @param saveOptions creation options * @return the newly persisted aggregate */ public EntityWithIdAndVersion<T> save(CT cmd, Optional<SaveOptions> saveOptions) { T aggregate; try { aggregate = clasz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } List<Event> events = aggregate.processCommand(cmd); Aggregates.applyEventsToMutableAggregate(aggregate, events, missingApplyEventMethodStrategy); return new EntityWithIdAndVersion<>(aggregateStore.save(clasz, events, saveOptions), aggregate); } /** * Update the specified aggregate by processing a command and saving events * * @param entityId the id of the aggregate to update * @param cmd the command to process * @return the updated and persisted aggregate */ public EntityWithIdAndVersion<T> update(String entityId, final CT cmd) { return update(entityId, cmd, Optional.empty()); } class LoadedEntityWithMetadata { boolean success; EntityWithMetadata<T> ewmd; LoadedEntityWithMetadata(boolean success, EntityWithMetadata<T> ewmd) { this.success = success; this.ewmd = ewmd; } } private <T> T withRetry(Supplier<T> asyncRequest) { OptimisticLockingException laste = null; int MAX_RETRIES = 10; for (int attempt = 0; attempt < MAX_RETRIES; attempt++) { if (laste != null) logger.debug("got optimistic locking exception - retrying", laste); try { return asyncRequest.get(); } catch (OptimisticLockingException e) { laste = e; } } if (logger.isDebugEnabled()) logger.debug("got exception - NOT retrying: " + MAX_RETRIES, laste); throw laste; } /** * Update the specified aggregate by processing a command and saving events * * @param entityId the id of the aggregate to update * @param cmd the command to process * @param updateOptions options for updating * @return the updated and persisted aggregate */ public EntityWithIdAndVersion<T> update(final String entityId, final CT cmd, Optional<UpdateOptions> updateOptions) { return updateWithProvidedCommand(entityId, (a) -> Optional.of(cmd), updateOptions); } /** * Update the specified aggregate by processing a command and saving events * * @param entityId the id of the aggregate to update * @param commandProvider the provider of the command to process * @param updateOptions options for updating * @return the updated and persisted aggregate */ public EntityWithIdAndVersion<T> updateWithProvidedCommand(final String entityId, final Function<T, Optional<CT>> commandProvider, Optional<UpdateOptions> updateOptions) { return withRetry(() -> { final EntityWithMetadata<T> entityWithMetadata; try { entityWithMetadata = aggregateStore.find(clasz, entityId, updateOptions.map(uo -> new FindOptions().withTriggeringEvent(uo.getTriggeringEvent()))); } catch (DuplicateTriggeringEventException dtee) { return aggregateStore.find(clasz, entityId, Optional.empty()).toEntityWithIdAndVersion(); } final T aggregate = entityWithMetadata.getEntity(); List<Event> events = commandProvider.apply(aggregate).map(aggregate::processCommand).orElse(Collections.emptyList()); if (events.isEmpty()) { return entityWithMetadata.toEntityWithIdAndVersion(); } else { try { Aggregates.applyEventsToMutableAggregate(aggregate, events, missingApplyEventMethodStrategy); EntityIdAndVersion entityIdAndVersion = aggregateStore.update(clasz, entityWithMetadata.getEntityIdAndVersion(), events, withPossibleSnapshot(updateOptions, aggregate, entityWithMetadata.getSnapshotVersion(), entityWithMetadata.getEvents(), events)); return new EntityWithIdAndVersion<>(entityIdAndVersion, aggregate); } catch (DuplicateTriggeringEventException e) { // TODO this should not happen EntityWithMetadata<T> reloadedEntity = aggregateStore.find(clasz, entityId, updateOptions.map(uo -> new FindOptions().withTriggeringEvent(uo.getTriggeringEvent()))); return new EntityWithIdAndVersion<>(reloadedEntity.getEntityIdAndVersion(), aggregate); } } }); } // Duplicate private Optional<UpdateOptions> withPossibleSnapshot(Optional<UpdateOptions> updateOptions, T aggregate, Optional<Int128> snapshotVersion, List<EventWithMetadata> oldEvents, List<Event> newEvents) { Optional<UpdateOptions> optionsWithSnapshot = aggregateStore.possiblySnapshot(aggregate, snapshotVersion, oldEvents, newEvents) .flatMap(snapshot -> Optional.of(updateOptions.orElse(new UpdateOptions()).withSnapshot(snapshot))); return optionsWithSnapshot.isPresent() ? optionsWithSnapshot : updateOptions; } /** * Find an aggregate * * @param entityId the id of the aggregate to find * @return the aggregate */ public EntityWithMetadata<T> find(String entityId) { return aggregateStore.find(clasz, entityId); } /** * Find an aggregate * * @param entityId the id of the aggregate to find * @param findOptions options for finding * @return the aggregate */ public EntityWithMetadata<T> find(String entityId, FindOptions findOptions) { return aggregateStore.find(clasz, entityId, findOptions); } /** * Find an aggregate * * @param entityId the id of the aggregate to find * @param findOptions options for finding * @return the aggregate */ public EntityWithMetadata<T> find(String entityId, Optional<FindOptions> findOptions) { return aggregateStore.find(clasz, entityId, findOptions); } }
37.387387
200
0.726265
7b5a812c2eb9b441087efc9fc82f3a230344c866
8,079
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.adventure; import net.kyori.adventure.text.renderer.TranslatableComponentRenderer; import net.kyori.adventure.translation.GlobalTranslator; import net.kyori.adventure.translation.TranslationRegistry; import net.minecraft.util.text.IFormattableTextComponent; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.util.text.event.HoverEvent; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import java.text.AttributedCharacterIterator; import java.text.MessageFormat; import java.util.List; import java.util.Locale; /** * An implementation of the functionality of {@link TranslatableComponentRenderer} on native MC chat components. * * <p>This will perform in-place modification of input components -- use * {@link #apply(ITextComponent, Locale)} to safely handle copying when * necessary.</p> * * @param <C> */ public abstract class NativeComponentRenderer<C> { static final NativeComponentRenderer<Locale> INSTANCE = new NativeComponentRenderer<Locale>() { @Override public MessageFormat translate(final @NonNull String key, final @NonNull Locale locale) { return GlobalTranslator.get().translate(key, locale); } }; public static @NonNull ITextComponent apply(final ITextComponent input, final Locale locale) { if (input instanceof AdventureTextComponent) { return ((AdventureTextComponent) input).rendered(locale); } else { return NativeComponentRenderer.get().render(input.copy(), locale); } } /** * Gets the default translatable component renderer. * * @return a translatable component renderer * @see TranslationRegistry */ public static @NonNull NativeComponentRenderer<Locale> get() { return NativeComponentRenderer.INSTANCE; } /** * Gets a message format from a key and context. * * @param key a translation key * @param context a context * @return a message format or {@code null} to skip translation */ protected abstract @Nullable MessageFormat translate(final @NonNull String key, final @NonNull C context); public ITextComponent render(@NonNull IFormattableTextComponent component, final @NonNull C context) { if (component instanceof TranslationTextComponent) { component = this.renderTranslatable((TranslationTextComponent) component, context); } else { this.renderSiblings(component, context); } final net.minecraft.util.text.event.HoverEvent hover = component.getStyle().getHoverEvent(); if (hover != null) { component.setStyle(component.getStyle().withHoverEvent(this.renderHoverEvent(hover, context))); } return component; } private HoverEvent renderHoverEvent(final HoverEvent input, final @NonNull C context) { final HoverEvent.Action<?> action = input.getAction(); if (action == HoverEvent.Action.SHOW_TEXT) { final ITextComponent original = input.getValue(HoverEvent.Action.SHOW_TEXT); return new HoverEvent(HoverEvent.Action.SHOW_TEXT, this.render(original.copy(), context)); } else if (action == HoverEvent.Action.SHOW_ENTITY) { final HoverEvent.EntityHover data = input.getValue(HoverEvent.Action.SHOW_ENTITY); if (data.name != null) { final ITextComponent rendered = this.render(data.name.copy(), context); return new HoverEvent(HoverEvent.Action.SHOW_ENTITY, new HoverEvent.EntityHover(data.type, data.id, rendered)); } } return input; } protected @NonNull IFormattableTextComponent renderTranslatable(final @NonNull TranslationTextComponent component, final @NonNull C context) { final /* @Nullable */ MessageFormat format = this.translate(component.getKey(), context); if (format == null) { // we don't have a translation for this component, but the arguments or children // of this component might need additional rendering final Object[] args = component.getArgs(); if (args.length > 0) { for (int i = 0, size = args.length; i < size; i++) { if (args[i] instanceof ITextComponent) { args[i] = this.render(((ITextComponent) args[i]).copy(), context); } } } this.renderSiblings(component, context); return component; } final Object[] args = component.getArgs(); final StringTextComponent result; // no arguments makes this render very simple if(args.length == 0) { result = new StringTextComponent(format.format(null, new StringBuffer(), null).toString()); } else { result = new StringTextComponent(""); final Object[] nulls = new Object[args.length]; final StringBuffer sb = format.format(nulls, new StringBuffer(), null); final AttributedCharacterIterator it = format.formatToCharacterIterator(nulls); while (it.getIndex() < it.getEndIndex()) { final int end = it.getRunLimit(); final Integer index = (Integer) it.getAttribute(MessageFormat.Field.ARGUMENT); if (index != null && args[index] instanceof ITextComponent) { result.append(this.render(((ITextComponent) args[index]).copy(), context)); } else { result.append(new StringTextComponent(sb.substring(it.getIndex(), end))); } it.setIndex(end); } } result.setStyle(component.getStyle()); this.renderSiblings(component, context, (idx, rendered) -> result.append(rendered)); return result; } private void renderSiblings(final ITextComponent component, final C context) { this.renderSiblings(component, context, component.getSiblings()::set); } private void renderSiblings(final ITextComponent component, final C context, final SiblingConsumer consumer) { final List<ITextComponent> siblings = component.getSiblings(); for (int i = 0; i < siblings.size(); i++) { final ITextComponent original = siblings.get(i); final ITextComponent rendered = this.render(original.copy(), context); consumer.accept(i, rendered); } } @FunctionalInterface interface SiblingConsumer { // Receives every sibling void accept(final int idx, final ITextComponent rendered); } }
42.973404
146
0.676198
230c819dd8b20b1667b1bfedff088b4300a57377
2,940
import com.sun.mail.util.MailSSLSocketFactory; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; /** * @author ShmeBluk * @version 1.0 * @ClassName: SimpleMailSend * @Desc: 简单邮件发送实现 * @package PACKAGE_NAME * @project File_and_Mail * @date 2020/7/18 19:25 */ public class SimpleMailSend { public static void main(String[] args) { Transport transport = null; try { InputStream is = new FileInputStream("MailTransport\\src\\mailInfo.properties"); Properties props = new Properties(); props.load(is); MailSSLSocketFactory mailSSLSocket = new MailSSLSocketFactory(); mailSSLSocket.setTrustAllHosts(true); props.put("mail.smtp.ssl.socketFactory", mailSSLSocket); String host = props.getProperty("mail.host"); String user = props.getProperty("user"); String password = props.getProperty("password"); String receiver = props.getProperty("receiver"); //1.创建整个程序所需的环境信息的Session对象 PasswordAuthentication passwordAuthentication = new PasswordAuthentication(user, password); Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return passwordAuthentication; } }; Session session = Session.getDefaultInstance(props, authenticator); session.setDebug(true);//开启session的debug模式 //2.获取Transport对象 transport = session.getTransport(); //3.连接邮件服务器 transport.connect(host, user, password); //4.创建简单邮件(文本邮件) MimeMessage message = new MimeMessage(session); //创建session对象 InternetAddress senderAddress = new InternetAddress(user);//发件人(需开启smtp服务) InternetAddress receiverAddress = new InternetAddress(receiver);//收件人 message.setFrom(senderAddress);//设置发件人 message.setRecipient(Message.RecipientType.TO, receiverAddress);//设置收件人类型和收件人 message.setSubject("SimpleTextMail");//设置主题 //两个方法不能同时存在,后面的会覆盖前面的邮件内容 // message.setText("第一段<br>第二段<br>第三段<br>", "UTF-8");//设置发送内容(普通文本内容) message.setContent("<h1>一级标题</h1><hr><h2>二级标题</h2>", "text/html;charset=UTF-8");//设置发送内容(HTML格式) //5.发送邮件 transport.sendMessage(message, message.getAllRecipients()); } catch (Exception e) { e.printStackTrace(); } finally { //6.关闭资源 try { if (transport != null) transport.close(); } catch (MessagingException e) { e.printStackTrace(); } } } }
35.853659
108
0.613946
9be6700598b8bf3b0e6a593c57254d9da21bf019
457
package de.ropemc.api.wrapper.net.minecraft.client.gui; import de.ropemc.api.wrapper.WrappedClass; @WrappedClass("net.minecraft.client.gui.GuiGameOver") public interface GuiGameOver { void actionPerformed(GuiButton var0); void confirmClicked(boolean var0, int var1); boolean doesGuiPauseGame(); void drawScreen(int var0, int var1, float var2); void initGui(); void keyTyped(char var0, int var1); void updateScreen(); }
19.869565
55
0.730853
215af54355d6f6ad53900f8375e09184da5c1bd3
1,758
package name.jacktang.projecteuler.util; import java.util.TreeMap; public class MathUtil { public static boolean isPrime(long num) { if (num < 2) { return false; } for (int factor = 2; factor < num; factor++) { if (num % factor == 0) { return false; } } return true; } public static boolean[] generatePrimes(int limit) { boolean[] numbers = new boolean[limit]; for (int i = 1; i < limit; i++) { numbers[i] = true; } int i = 1; while (i + 1 <= Math.sqrt(limit)) { for (int multiple = 2; (i + 1) * multiple <= limit; multiple++) { numbers[(i + 1) * multiple - 1] = false; } i++; while (!numbers[i]) { i++; } } return numbers; } public static boolean isPalindrome(int num) { String numString = String.valueOf(num); for (int i = 0; i < numString.length() / 2 + 1; i++) { if (numString.charAt(i) != numString.charAt(numString.length() - i - 1)) { return false; } } return true; } public static TreeMap<Long, Integer> getPrimeFactors(long num) { TreeMap<Long, Integer> factors = new TreeMap<>(); while (num % 2 == 0) { factors.put(2L, factors.containsKey(2L) ? factors.get(2L) + 1 : 1); num /= 2; } for (int i = 3; i <= Math.sqrt(num); i += 2) { while (num % i == 0) { factors.put((long) i, factors.containsKey((long) i) ? factors.get((long) i) + 1 : 1); num /= i; } } if (num > 2) { factors.put(num, 1); } return factors; } public static long isPowerNumber(long num, long maxBase) { for (long base = 2; base <= maxBase; base++) { long devision = num; while (devision != 1) { if (devision % base != 0) { break; } devision /= base; } if (devision == 1) { return base; } } return 0; } }
21.703704
89
0.567122
bef404109c17d843b85c6645652dfca7906e2758
212
package alektas.pocketbasket.domain.entities; public interface BasketItemModel extends ItemModel { String getKey(); void setKey(String key); boolean isMarked(); void setMarked(boolean marked); }
23.555556
52
0.745283
20dc82b3c53df41a8a328c1483d3d3d711133b1c
7,179
package cookbuddy; import java.io.IOException; import java.nio.file.Path; import java.util.Optional; import java.util.logging.Logger; import cookbuddy.commons.core.Config; import cookbuddy.commons.core.LogsCenter; import cookbuddy.commons.core.Version; import cookbuddy.commons.exceptions.DataConversionException; import cookbuddy.commons.util.ConfigUtil; import cookbuddy.commons.util.StringUtil; import cookbuddy.logic.Logic; import cookbuddy.logic.LogicManager; import cookbuddy.model.Model; import cookbuddy.model.ModelManager; import cookbuddy.model.ReadOnlyRecipeBook; import cookbuddy.model.ReadOnlyUserPrefs; import cookbuddy.model.RecipeBook; import cookbuddy.model.UserPrefs; import cookbuddy.model.util.SampleDataUtil; import cookbuddy.storage.JsonRecipeBookStorage; import cookbuddy.storage.JsonUserPrefsStorage; import cookbuddy.storage.RecipeBookStorage; import cookbuddy.storage.Storage; import cookbuddy.storage.StorageManager; import cookbuddy.storage.UserPrefsStorage; import cookbuddy.ui.Ui; import cookbuddy.ui.UiManager; import javafx.application.Application; import javafx.stage.Stage; /** * Runs the application. */ public class MainApp extends Application { public static final Version VERSION = new Version(0, 6, 0, true); private static final Logger logger = LogsCenter.getLogger(MainApp.class); protected Ui ui; protected Logic logic; protected Storage storage; protected Model model; protected Config config; @Override public void init() throws Exception { logger.info("=============================[ Initializing CookBuddy ]==========================="); super.init(); AppParameters appParameters = AppParameters.parse(getParameters()); config = initConfig(appParameters.getConfigPath()); UserPrefsStorage userPrefsStorage = new JsonUserPrefsStorage(config.getUserPrefsFilePath()); UserPrefs userPrefs = initPrefs(userPrefsStorage); RecipeBookStorage recipeBookStorage = new JsonRecipeBookStorage(userPrefs.getDataFilePath(), userPrefs.getImagesPath()); storage = new StorageManager(recipeBookStorage, userPrefsStorage); initLogging(config); model = initModelManager(storage, userPrefs); logic = new LogicManager(model, storage); ui = new UiManager(logic); } /** * Returns a {@code ModelManager} with the data from {@code storage}'s recipe * book and {@code userPrefs}. <br> * The data from the sample recipe book will be used instead if * {@code storage}'s recipe book is not found, or an empty recipe book will be * used instead if errors occur when reading {@code storage}'s recipe book. */ private Model initModelManager(Storage storage, ReadOnlyUserPrefs userPrefs) { Optional<ReadOnlyRecipeBook> recipeBookOptional; ReadOnlyRecipeBook initialData; try { recipeBookOptional = storage.readRecipeBook(); if (!recipeBookOptional.isPresent()) { logger.info("Data file not found. Populating RecipeBook with sample recipes."); } initialData = new RecipeBook(); initialData = recipeBookOptional.orElseGet(SampleDataUtil::getSampleRecipeBook); } catch (DataConversionException e) { logger.warning("Data file not in the correct format. Will be starting with an empty RecipeBook"); initialData = new RecipeBook(); } catch (IOException e) { logger.warning("Problem while reading from the file. Will be starting with an empty RecipeBook"); initialData = new RecipeBook(); } return new ModelManager(initialData, userPrefs); } private void initLogging(Config config) { LogsCenter.init(config); } /** * Returns a {@code Config} using the file at {@code configFilePath}. <br> * The default file path {@code Config#DEFAULT_CONFIG_FILE} will be used instead * if {@code configFilePath} is null. */ protected Config initConfig(Path configFilePath) { Config initializedConfig; Path configFilePathUsed; configFilePathUsed = Config.DEFAULT_CONFIG_FILE; if (configFilePath != null) { logger.info("Custom Config file specified " + configFilePath); configFilePathUsed = configFilePath; } logger.info("Using config file : " + configFilePathUsed); try { Optional<Config> configOptional = ConfigUtil.readConfig(configFilePathUsed); initializedConfig = configOptional.orElse(new Config()); } catch (DataConversionException e) { logger.warning("Config file at " + configFilePathUsed + " is not in the correct format. " + "Using default config properties"); initializedConfig = new Config(); } // Update config file in case it was missing to begin with or there are // new/unused fields try { ConfigUtil.saveConfig(initializedConfig, configFilePathUsed); } catch (IOException e) { logger.warning("Failed to save config file : " + StringUtil.getDetails(e)); } return initializedConfig; } /** * Returns a {@code UserPrefs} using the file at {@code storage}'s user prefs * file path, or a new {@code UserPrefs} with default configuration if errors * occur when reading from the file. */ protected UserPrefs initPrefs(UserPrefsStorage storage) { Path prefsFilePath = storage.getUserPrefsFilePath(); logger.info("Using prefs file : " + prefsFilePath); UserPrefs initializedPrefs; try { Optional<UserPrefs> prefsOptional = storage.readUserPrefs(); initializedPrefs = prefsOptional.orElse(new UserPrefs()); } catch (DataConversionException e) { logger.warning("UserPrefs file at " + prefsFilePath + " is not in the correct format. " + "Using default user prefs"); initializedPrefs = new UserPrefs(); } catch (IOException e) { logger.warning("Problem while reading from the file. Will be starting with an empty RecipeBook"); initializedPrefs = new UserPrefs(); } // Update prefs file in case it was missing to begin with or there are // new/unused fields try { storage.saveUserPrefs(initializedPrefs); } catch (IOException e) { logger.warning("Failed to save config file : " + StringUtil.getDetails(e)); } return initializedPrefs; } @Override public void start(Stage primaryStage) { logger.info("Starting CookBuddy " + MainApp.VERSION); ui.start(primaryStage); } @Override public void stop() { logger.info("============================ [ Stopping CookBuddy ] ============================="); try { storage.saveUserPrefs(model.getUserPrefs()); } catch (IOException e) { logger.severe("Failed to save preferences " + StringUtil.getDetails(e)); } } }
37.784211
109
0.663602
b874af2b6863859f38ce760f233fd91600ad2387
1,386
package com.mingrisoft.anxingdemo3.UI.activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import com.mingrisoft.anxingdemo3.R; import com.mingrisoft.anxingdemo3.UI.util.PlayVoice; /** * Created by 11455 on 2018/6/9. */ public class Activity_two_level_function_voice extends AppCompatActivity implements View.OnClickListener{ @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); supportRequestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.two_level_function_voice); View view = this.findViewById(R.id.voice_btn); view.setOnClickListener(this); view = this.findViewById(R.id.voice_btn2); view.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.voice_btn:{ //直接创建,不需要设置setDataSource //mMediaPlayer= MediaPlayer.create(this, R.raw.audio); //mMediaPlayer.start(); PlayVoice.playVoice(this); break; } case R.id.voice_btn2:{ PlayVoice.stopVoice(); finish(); } } } }
25.666667
105
0.645743
f2202ef2a022bce5d915296b7c5f039a006b4d20
1,622
/* * This file is generated by jOOQ. */ package com.oneops.crawler.jooq.cms.routines; import com.oneops.crawler.jooq.cms.Kloopzcm; import javax.annotation.Generated; import org.jooq.Parameter; import org.jooq.impl.AbstractRoutine; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.10.0" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class NsCreateNamespace extends AbstractRoutine<java.lang.Void> { private static final long serialVersionUID = 95560614; /** * The parameter <code>kloopzcm.ns_create_namespace.p_ns_path</code>. */ public static final Parameter<String> P_NS_PATH = createParameter("p_ns_path", org.jooq.impl.SQLDataType.VARCHAR, false, false); /** * The parameter <code>kloopzcm.ns_create_namespace.out_ns_id</code>. */ public static final Parameter<Long> OUT_NS_ID = createParameter("out_ns_id", org.jooq.impl.SQLDataType.BIGINT, false, false); /** * Create a new routine call instance */ public NsCreateNamespace() { super("ns_create_namespace", Kloopzcm.KLOOPZCM); addInParameter(P_NS_PATH); addOutParameter(OUT_NS_ID); } /** * Set the <code>p_ns_path</code> parameter IN value to the routine */ public void setPNsPath(String value) { setValue(P_NS_PATH, value); } /** * Get the <code>out_ns_id</code> parameter OUT value from the routine */ public Long getOutNsId() { return get(OUT_NS_ID); } }
25.34375
132
0.667694
bad39acf48d28f1dc71045c1b818e59e39ad786e
4,082
package com.twitter.elephantbird.pig.util; import java.io.IOException; import java.util.Map; import java.math.BigDecimal; import java.math.BigInteger; import com.google.common.base.Preconditions; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.io.Writable; import org.apache.pig.LoadStoreCaster; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.Tuple; import org.joda.time.DateTime; /** * Base LoadStoreCaster implementation which simplifies specification of conversion from Pig types * to Writable type. * * @author Andy Schlaikjer */ public abstract class WritableStoreCaster<W extends Writable> extends WritableLoadCaster<W> implements LoadStoreCaster { private final DataOutputBuffer buf = new DataOutputBuffer(); public WritableStoreCaster(W writable) { super(writable); } public WritableStoreCaster() { } private byte[] write(Writable writable) throws IOException { Preconditions.checkNotNull(writable); buf.reset(); writable.write(buf); return buf.getData(); } @Override public byte[] toBytes(DataByteArray value) throws IOException { return write(toWritable(value)); } @Override public byte[] toBytes(String value) throws IOException { return write(toWritable(value)); } @Override public byte[] toBytes(Boolean value) throws IOException { return write(toWritable(value)); } @Override public byte[] toBytes(Integer value) throws IOException { return write(toWritable(value)); } @Override public byte[] toBytes(Long value) throws IOException { return write(toWritable(value)); } @Override public byte[] toBytes(Float value) throws IOException { return write(toWritable(value)); } @Override public byte[] toBytes(Double value) throws IOException { return write(toWritable(value)); } @Override public byte[] toBytes(Map<String, Object> value) throws IOException { return write(toWritable(value)); } @Override public byte[] toBytes(Tuple value) throws IOException { return write(toWritable(value)); } @Override public byte[] toBytes(DateTime value) throws IOException { return write(toWritable(value)); } @Override public byte[] toBytes(DataBag value) throws IOException { return write(toWritable(value)); } @Override public byte[] toBytes(BigDecimal value) throws IOException { return write(toWritable(value)); } @Override public byte[] toBytes(BigInteger value) throws IOException { return write(toWritable(value)); } protected W toWritable(DataByteArray value) throws IOException { throw new UnsupportedOperationException(); } protected W toWritable(String value) throws IOException { throw new UnsupportedOperationException(); } protected W toWritable(Boolean value) throws IOException { throw new UnsupportedOperationException(); } protected W toWritable(Integer value) throws IOException { throw new UnsupportedOperationException(); } protected W toWritable(Long value) throws IOException { throw new UnsupportedOperationException(); } protected W toWritable(Float value) throws IOException { throw new UnsupportedOperationException(); } protected W toWritable(Double value) throws IOException { throw new UnsupportedOperationException(); } protected W toWritable(Map<String, Object> value) throws IOException { throw new UnsupportedOperationException(); } protected W toWritable(Tuple value) throws IOException { throw new UnsupportedOperationException(); } protected W toWritable(DataBag value) throws IOException { throw new UnsupportedOperationException(); } protected W toWritable(DateTime value) throws IOException { throw new UnsupportedOperationException(); } protected W toWritable(BigDecimal value) throws IOException { throw new UnsupportedOperationException(); } protected W toWritable(BigInteger value) throws IOException { throw new UnsupportedOperationException(); } }
25.672956
98
0.742528
4d5fa1086f953cc7a87c052e4fe277d4b5ee81ed
4,433
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.firebase.inappmessaging.model; import androidx.annotation.Nullable; import java.util.Map; /** Encapsulates a Firebase In App Message. */ public abstract class InAppMessage { @Deprecated Text title; @Deprecated Text body; @Deprecated String imageUrl; @Deprecated ImageData imageData; @Deprecated Button actionButton; @Deprecated String backgroundHexColor; @Deprecated String campaignId; @Deprecated String campaignName; @Deprecated Boolean isTestMessage; MessageType messageType; CampaignMetadata campaignMetadata; @Nullable private Map<String, String> data; /** @hide */ @Deprecated public InAppMessage( Text title, Text body, String imageUrl, ImageData imageData, Button actionButton, Action action, String backgroundHexColor, String campaignId, String campaignName, Boolean isTestMessage, MessageType messageType, Map<String, String> data) { this.title = title; this.body = body; this.imageUrl = imageUrl; this.imageData = imageData; this.actionButton = actionButton; this.backgroundHexColor = backgroundHexColor; this.campaignId = campaignId; this.campaignName = campaignName; this.isTestMessage = isTestMessage; this.messageType = messageType; this.campaignMetadata = new CampaignMetadata(campaignId, campaignName, isTestMessage); this.data = data; } /** @hide */ public InAppMessage( CampaignMetadata campaignMetadata, MessageType messageType, Map<String, String> data) { this.campaignMetadata = campaignMetadata; this.messageType = messageType; this.data = data; } /** @deprecated Use the message specific methods instead. */ @Nullable @Deprecated public Text getTitle() { return title; } /** @deprecated Use the message specific methods (see {@link CardMessage}) instead. */ @Nullable @Deprecated public Text getBody() { return body; } /** @deprecated Use the message specific methods (see {@link CardMessage}) instead. */ @Nullable @Deprecated public String getImageUrl() { return imageUrl; } /** @deprecated Use the message specific methods (see {@link CardMessage}) instead. */ @Nullable @Deprecated public ImageData getImageData() { return imageData; } /** @deprecated Use the message specific methods (see {@link CardMessage}) */ @Nullable @Deprecated public Button getActionButton() { if (getAction() != null) { return getAction().getButton(); } return actionButton; } /** @deprecated Use the message specific methods (see {@link CardMessage}) instead. */ @Deprecated @Nullable public abstract Action getAction(); /** @deprecated Use the message specific methods (see {@link CardMessage}) instead. */ @Nullable @Deprecated public String getBackgroundHexColor() { return backgroundHexColor; } /** @deprecated Use getCampaignMetadata().getCampaignId() instead. */ @Nullable @Deprecated public String getCampaignId() { return campaignMetadata.getCampaignId(); } /** @deprecated Use getCampaignMetadata().getCampaignName() instead. */ @Nullable @Deprecated public String getCampaignName() { return campaignMetadata.getCampaignName(); } /** @deprecated Use getCampaignMetadata().getIsTestMessage() instead. */ @Nullable @Deprecated public Boolean getIsTestMessage() { return campaignMetadata.getIsTestMessage(); } /** Gets the {@link MessageType} of the message */ @Nullable public MessageType getMessageType() { return messageType; } /** Gets the {@link CampaignMetadata} of the message */ @Nullable public CampaignMetadata getCampaignMetadata() { return campaignMetadata; } @Nullable public Map<String, String> getData() { return data; } }
27.70625
93
0.709452
daf2e8e31cf5d342e355f1a1cc6b9ef71bce28c2
3,340
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package co.edu.uniandes.csw.carrosUsados.persistence; import co.edu.uniandes.csw.carrosUsados.entities.PuntoVentaEntity; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; /** * Clase que maneja la persistencia para PuntoVenta Se conecta a través Entity. * Manager de javax.persistance con la base de datos SQL. * @author Daniella Arteaga */ @Stateless public class PuntoVentaPersistence { private static final Logger LOGGER = Logger.getLogger(PuntoVentaPersistence.class.getName()); /** * */ @PersistenceContext(unitName = "CarTeamPU") protected EntityManager em; /** * Método para persisitir la entidad en la base de datos. * * @param puntoEntity objeto punto que se creará en la base de datos * @return devuelve la entidad creada con un id dado por la base de datos. */ public PuntoVentaEntity create(PuntoVentaEntity puntoEntity) { LOGGER.log(Level.INFO, "Creando un nuevo punto de venta."); em.persist(puntoEntity); LOGGER.log(Level.INFO, "Punto de venta creado"); return puntoEntity; } /** * Devuelve todas los puntos de venta de la base de datos. * * @return una lista con todas los puntos que encuentre en la base de * datos, */ public List<PuntoVentaEntity> findAll() { LOGGER.log(Level.INFO, "Consultando todos los puntos de venta"); TypedQuery q = em.createQuery("select u from PuntoVentaEntity u", PuntoVentaEntity.class); return q.getResultList(); } /** * Busca si hay algun punto con el id que se envía de argumento * * @param puntoId Id: id correspondiente al punto buscada. * @return un punto de venta. */ public PuntoVentaEntity find(Long puntoId) { LOGGER.log(Level.INFO, "Consultando el punto de venta con id={0}", puntoId); return em.find(PuntoVentaEntity.class, puntoId); } /** * Actualiza un punto de venta. * * @param puntoEntity Entity: el punto que viene con los nuevos cambios. * Por ejemplo el nombre pudo cambiar. En ese caso, se haria uso del método * update. * @return un punto con los cambios aplicados. */ public PuntoVentaEntity update(PuntoVentaEntity puntoEntity) { LOGGER.log(Level.INFO, "Actualizando el punto de venta con id={0}", puntoEntity.getId()); return em.merge(puntoEntity); } /** * * Borra un punto de la base de datos recibiendo como argumento el id * del punto. * * @param puntoId: id correspondiente al punto a borrar. */ public void delete(Long puntoId) { LOGGER.log(Level.INFO, "Borrando el punto de venta con id={0}", puntoId); PuntoVentaEntity puntoEntity = em.find(PuntoVentaEntity.class, puntoId); em.remove(puntoEntity); } }
33.4
99
0.654192
b54331fa4ca014de7b78644750b51167325fc79d
7,695
package org.stepic.droid.ui.dialogs; import android.annotation.SuppressLint; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.design.widget.TextInputLayout; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import org.jetbrains.annotations.NotNull; import org.stepic.droid.R; import org.stepic.droid.base.App; import org.stepic.droid.util.ProgressHelper; import org.stepic.droid.web.Api; import javax.inject.Inject; import butterknife.BindString; import butterknife.ButterKnife; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class RemindPasswordDialogFragment extends DialogFragment { private static final String ERROR_TEXT_KEY = "Error_Text_Key"; @Inject Api api; public static RemindPasswordDialogFragment newInstance() { return new RemindPasswordDialogFragment(); } private TextInputLayout emailTextWrapper; private LoadingProgressDialog progressLogin; private View rootView; @BindString(R.string.email_wrong) String emailWrong; @NotNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { App.Companion.component().inject(this); @SuppressLint("InflateParams") //it is dialog and it shoud not have any parent View v = ((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.view_remind_password, null, false); emailTextWrapper = ButterKnife.findById(v, R.id.emailViewWrapper); rootView = ButterKnife.findById(v, R.id.root_view_dialog); rootView.requestFocus(); progressLogin = new LoadingProgressDialog(getContext()); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.remind_password) .setView(v) .setPositiveButton(R.string.send, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .setNegativeButton(R.string.cancel, null); final AlertDialog alertDialog = builder.create(); alertDialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { Button b = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sendEmail(alertDialog); } }); } }); if (emailTextWrapper.getEditText() != null) { emailTextWrapper.getEditText().setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_SEND) { sendEmail(alertDialog); handled = true; } return handled; } }); emailTextWrapper.getEditText().setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { hideError(emailTextWrapper); } } }); } ButterKnife.bind(this, alertDialog); if (savedInstanceState != null) { String errorText = savedInstanceState.getString(ERROR_TEXT_KEY); if (errorText != null) { showError(emailTextWrapper, errorText); } } return alertDialog; } private void sendEmail(final AlertDialog alertDialog) { ProgressHelper.activate(progressLogin); safetyHideKeypad(emailTextWrapper.getEditText()); String email; try { email = emailTextWrapper.getEditText().getText().toString().trim(); } catch (NullPointerException e) { ProgressHelper.dismiss(progressLogin); return; } if (!email.isEmpty()) { api.remindPassword(email).enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { ProgressHelper.dismiss(progressLogin); okhttp3.Response rawResponse = response.raw(); if (rawResponse.priorResponse() != null && rawResponse.priorResponse().code() == 302) { alertDialog.dismiss(); Toast.makeText(getContext(), R.string.email_sent, Toast.LENGTH_SHORT).show(); } else if (response.code() == 200) { if (rootView != null) rootView.requestFocus(); showError(emailTextWrapper, emailWrong); } else { final Context context = getContext(); if (context != null) { Toast.makeText(context, R.string.connectionProblems, Toast.LENGTH_SHORT).show(); } } } @Override public void onFailure(Call<Void> call, Throwable t) { ProgressHelper.dismiss(progressLogin); final Context context = getContext(); if (context != null) { Toast.makeText(context, R.string.connectionProblems, Toast.LENGTH_SHORT).show(); } } }); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (emailTextWrapper != null && emailTextWrapper.getError() != null) outState.putString(ERROR_TEXT_KEY, emailTextWrapper.getError().toString()); } @Override public void onDestroyView() { if (emailTextWrapper != null && emailTextWrapper.getEditText() != null) { emailTextWrapper.getEditText().setOnFocusChangeListener(null); emailTextWrapper.getEditText().setOnEditorActionListener(null); } super.onDestroyView(); } private void hideError(TextInputLayout textInputLayout) { if (textInputLayout != null) { textInputLayout.setError(""); textInputLayout.setErrorEnabled(false); } } private void showError(TextInputLayout textInputLayout, String errorText) { if (textInputLayout != null) { textInputLayout.setErrorEnabled(true); textInputLayout.setError(errorText); } } private void safetyHideKeypad(TextView view) { if (view != null) { InputMethodManager imm = (InputMethodManager) App.Companion.getAppContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } } }
36.469194
151
0.608837
36964eaf474d915687ec040a12cd364d661b393c
1,221
package com.profitera.services.system.mail; import java.io.IOException; import java.util.Map; import javax.mail.MessagingException; import com.profitera.dataaccess.AbortTransactionException; import com.profitera.email.IEmailProvider; import com.profitera.server.ServiceEngine; import com.profitera.services.system.SystemService; import com.profitera.services.system.mail.impl.MailSender; public class MailService extends SystemService implements IEmailProvider { private static final String errorMsg = "Exception while sending email"; public boolean sendEmail(final Map<String, Object> emailDetails, final boolean failOnError) throws AbortTransactionException { AbortTransactionException ate = null; boolean mailSent = false; try { // call method to compose and actually sent the mail new MailSender().composeEmail(emailDetails, ServiceEngine.getConfig(false)); } catch (IOException ex) { ate = new AbortTransactionException(errorMsg, ex); } catch (MessagingException ex) { ate = new AbortTransactionException(errorMsg, ex); } if (ate == null) { mailSent = true; } if (!mailSent && failOnError) { throw ate; } return mailSent; } }
33.916667
128
0.747748
6cf2f62c761efa0b930d0099e0d682de1ba2b9a0
2,737
package slimeknights.tmechworks; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.config.ModConfig; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent; import net.minecraftforge.fml.event.lifecycle.InterModProcessEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import slimeknights.tmechworks.client.ClientProxy; import slimeknights.tmechworks.common.CommonProxy; import slimeknights.tmechworks.common.MechworksContent; import slimeknights.tmechworks.common.config.MechworksConfig; import slimeknights.tmechworks.common.entities.MechworksFakePlayer; import slimeknights.tmechworks.common.network.PacketHandler; import slimeknights.tmechworks.common.worldgen.MechworksWorld; @Mod(TMechworks.modId) public class TMechworks { public static final String modId = "tmechworks"; public static final String modName = "Tinkers' Mechworks"; public static final Logger log = LogManager.getLogger(modId); public static TMechworks instance; public static CommonProxy proxy = DistExecutor.safeRunForDist(()-> ClientProxy::new, ()-> CommonProxy::new); public static MechworksContent content; public TMechworks() { instance = this; ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, MechworksConfig.COMMON_SPEC); IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); bus.addListener(this::preInit); bus.addListener(this::init); bus.addListener(this::postInit); bus.addListener(this::setupClient); MinecraftForge.EVENT_BUS.addListener(MechworksFakePlayer::onWorldUnload); content = new MechworksContent(); content.initRegisters(); bus.register(content); MinecraftForge.EVENT_BUS.register(new MechworksWorld()); } private void preInit(final FMLCommonSetupEvent event) { proxy.preInit(); content.preInit(event); PacketHandler.register(); } private void init(final InterModEnqueueEvent event) { proxy.init(); content.init(event); } private void postInit(final InterModProcessEvent event) { proxy.postInit(); content.postInit(event); } private void setupClient(final FMLClientSetupEvent event) { proxy.setupClient(); } }
35.089744
112
0.761418
92035bfac81dafa6a704ef719364880d2dadca66
1,656
/** * junixsocket * * Copyright 2009-2020 Christian Kohlschütter * * 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.newsclub.net.unix.rmi; import java.io.Closeable; import java.io.IOException; import java.rmi.Remote; /** * A resource that can be exposed remotely, and closed locally as well as remotely. * * @author Christian Kohlschütter */ public interface RemoteCloseable<T> extends Remote, Closeable { /** * Returns the resource (or the Remote instance of it). * * If the returned resource is {@link Closeable}, then closing via {@code get().close()}} will * affect the client-side (local), but not necessarily the server-side as well (the exact behavior * depends on the resource). * * @return The wrapped resource. * @throws IOException if there was a problem. */ T get() throws IOException; /** * Closes the resource on the server-side (i.e., where it was created), and — as long as the * wrapped resource returned by {@link #get()} supports it — locally as well. * * @throws IOException if there was a problem. */ @Override void close() throws IOException; }
32.470588
100
0.708333
6bf754c9edd61036e92c9a978096ad9737563df7
1,977
package LianFragmentPac; import android.content.Context; import android.support.annotation.NonNull; import android.text.Layout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AbsListView; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.Filterable; import android.widget.TextView; import com.example.a123.tongxunlu.R; import com.hp.hpl.sparta.Text; import java.util.ArrayList; import java.util.List; /** * Created by 123 on 2016/12/22. */ public class LianAdapter extends ArrayAdapter<LianXiRen> implements Filterable{ public LianAdapter(Context context, int resource, List<LianXiRen> objects) { super(context, resource, objects); } @NonNull @Override public View getView(int position, View convertView, ViewGroup parent) { LianXiRen mLianXiRen=getItem(position); String str=mLianXiRen.getFirstName(); String str1=mLianXiRen.getName(); if(str.equals("")){ convertView= LayoutInflater.from(getContext()).inflate(R.layout.tab02_title,null); if(position!=getCount()-1){ LianXiRen mLianXiRen1=getItem(position+1); if (mLianXiRen1.getFirstName().equals("")){ AbsListView.LayoutParams param = new AbsListView.LayoutParams( 0,1); convertView.setLayoutParams(param); } }if(position==getCount()-1){ AbsListView.LayoutParams param = new AbsListView.LayoutParams( 0,1); convertView.setLayoutParams(param); } }else { convertView = LayoutInflater.from(getContext()).inflate(R.layout.tab02_item, null); } TextView mTextView2=(TextView)convertView.findViewById(R.id.mTextView); mTextView2.setText(str1); return convertView; } }
30.890625
95
0.681841
594c81e071f1ed9222f0d95d13b4a64851f15f01
867
package com.iluwatar.cqrsasync.command; import java.math.BigDecimal; import java.util.concurrent.CompletableFuture; public interface CommandService { CompletableFuture<Boolean> authorCreated(final String username, final String name, final String email); CompletableFuture<Boolean> bookAddedToAuthor(final String title, final BigDecimal price, final String username); CompletableFuture<Boolean> authorNameUpdated(final String username, final String name); CompletableFuture<Boolean> authorUsernameUpdated(final String oldUsername, final String newUsername); CompletableFuture<Boolean> authorEmailUpdated(final String username, final String email); CompletableFuture<Boolean> bookTitleUpdated(final String oldTitle, final String newTitle); CompletableFuture<Boolean> bookPriceUpdated(final String title, final BigDecimal price); }
37.695652
116
0.814302
40501d6173bafecb6d33f1758d223c2e65f68ce1
2,240
/* * Copyright 2014-2016 Intel Corporation * * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/org/documents/epl-v10.php * * 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.moe.natjdemo.moe.test.util; import android.test.InstrumentationTestCase; import ios.coregraphics.struct.CGRect; import org.junit.Assert; public abstract class MOETest extends InstrumentationTestCase { protected static final void assertArrayEquals(boolean[] expecteds, boolean[] actuals) { Assert.assertEquals("arrays don't have the same length", expecteds.length, actuals.length); for (int idx = 0; idx < expecteds.length; ++idx) { Assert.assertEquals("values compare failed", expecteds[idx], actuals[idx]); } } protected static final void assertArrayEquals(CGRect[] expecteds, CGRect[] actuals) { Assert.assertEquals("arrays don't have the same length", expecteds.length, actuals.length); for (int idx = 0; idx < expecteds.length; ++idx) { assertEquals("values compare failed", expecteds[idx], actuals[idx]); } } protected static final void assertArrayEquals(Object[] expecteds, Object[] actuals) { Assert.assertArrayEquals(expecteds, actuals); } protected static void assertEquals(CGRect expected, CGRect actual) { assertEquals(null, expected, actual); } protected static void assertEquals(String message, CGRect expected, CGRect actual) { Assert.assertEquals("CGRect.o.x compare failed", expected.origin().x(), actual.origin().x(), 0.0f); Assert.assertEquals("CGRect.o.y compare failed", expected.origin().y(), actual.origin().y(), 0.0f); Assert.assertEquals("CGRect.s.w compare failed", expected.size().width(), actual.size().width(), 0.0f); Assert.assertEquals("CGRect.s.h compare failed", expected.size().height(), actual.size().height(), 0.0f); } }
39.298246
107
0.739732
2f71953e4cd5475680566423ab3b0b79d9f9fc79
1,182
package thirdparty.apache.commons; import org.apache.commons.lang3.builder.ToStringBuilder; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * * @since 2017-07-27 * @author fixalot */ public class ToStringBuilderTest { // @SuppressWarnings("unused") private static final Logger logger = LoggerFactory.getLogger(ToStringBuilderTest.class); @Test public void printToStringResult() { PlainObject po = new PlainObject(); logger.debug(ToStringBuilder.reflectionToString(po)); po.setStringField("야"); po.setIntField(65536); logger.debug(ToStringBuilder.reflectionToString(po)); try { logger.debug(ToStringBuilder.reflectionToString(null)); // 에러남 } catch (Exception e) { // do nothing } } @SuppressWarnings("unused") private class PlainObject { private String stringField; private Integer intField; public String getStringField() { return stringField; } public void setStringField(String stringField) { this.stringField = stringField; } public Integer getIntField() { return intField; } public void setIntField(Integer intField) { this.intField = intField; } } }
21.888889
89
0.734349
c7fe28a8194f1c3387bf197a54e2abd4ce1b5952
1,431
package inheritance; import java.util.HashSet; import java.util.Set; public class Place implements ReviewAble { String name; int price; //0-4, $-$$$$ Set<Review> reviews = new HashSet<>(); public Place(String name, int price) { this.name = name; this.price = price; validatePrice(); } public Place(String name, String price) { this.name = name; this.price = price.length(); validatePrice(); } private void validatePrice() { if (this.price > 4) this.price = 4; if (this.price < 1) this.price = 1; } public String getPrice() { StringBuilder price = new StringBuilder(); int i = 0; while (i < this.price) { price.append("$"); i++; } return price.toString(); } @Override public float getRating() { if (this.reviews.size() == 0) return 0; return (float) this.reviews.stream() .mapToDouble(review -> review.rating)//get only ratings .sum() / this.reviews.size(); } @Override public String toString() { return String.format("name: %s, stars: %.1f, price: %s(%d)", this.name, getRating(), this.getPrice(), this.price); } @Override public void addReview(Review review) { if (review.place != this) return; this.reviews.add(review); } }
24.672414
71
0.54717
04d9e2f6d0b3a97223a841ed05e6e121d839e18c
703
package com.fbd.core.common.quartz.util; public class StringUtil { /** * Case insensitive && string trimmed match * * @param string1 * @param string2 * @return true if strings seem to have */ public static boolean isSameTextValue(String string1, String string2) { if (string1 == null || string2 == null) { if (string1 == null && string2 == null) return true; else return false; } if (string1.trim().equalsIgnoreCase(string2.trim())) { return true; } return false; } public static boolean isEmpty(String s) { boolean flg = true; if (s != null && s.trim().length() > 0) { return false; } return flg; } }
18.5
73
0.59744
2f7d70f4fdfee520dbcb1a5d66337125bf42f234
4,840
// Copyright (C) 2015 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.httpd.plugins; import static javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED; import com.google.gerrit.extensions.registration.RegistrationHandle; import com.google.gerrit.httpd.resources.Resource; import com.google.gerrit.server.config.GerritServerConfig; import com.google.gerrit.server.plugins.Plugin; import com.google.gerrit.server.plugins.ReloadPluginListener; import com.google.gerrit.server.plugins.StartPluginListener; import com.google.gwtexpui.server.CacheHeaders; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.servlet.GuiceFilter; import org.eclipse.jgit.lib.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import javax.servlet.FilterChain; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Singleton public class LfsPluginServlet extends HttpServlet implements StartPluginListener, ReloadPluginListener { private static final long serialVersionUID = 1L; private static final Logger log = LoggerFactory.getLogger(LfsPluginServlet.class); public static final String URL_REGEX = "^(?:/a)?(?:/p/|/)(.+)(?:/info/lfs/objects/batch)$"; private List<Plugin> pending = new ArrayList<>(); private final String pluginName; private final FilterChain chain; private AtomicReference<GuiceFilter> filter; @Inject LfsPluginServlet(@GerritServerConfig Config cfg) { this.pluginName = cfg.getString("lfs", null, "plugin"); this.chain = new FilterChain() { @Override public void doFilter(ServletRequest req, ServletResponse res) throws IOException { Resource.NOT_FOUND.send( (HttpServletRequest) req, (HttpServletResponse) res); } }; this.filter = new AtomicReference<>(); } @Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { if (filter.get() == null) { CacheHeaders.setNotCacheable(res); res.sendError(SC_NOT_IMPLEMENTED); return; } filter.get().doFilter(req, res, chain); } @Override public synchronized void init(ServletConfig config) throws ServletException { super.init(config); for (Plugin plugin : pending) { install(plugin); } pending = null; } @Override public synchronized void onStartPlugin(Plugin plugin) { if (pending != null) { pending.add(plugin); } else { install(plugin); } } @Override public void onReloadPlugin(Plugin oldPlugin, Plugin newPlugin) { install(newPlugin); } private void install(Plugin plugin) { if (!plugin.getName().equals(pluginName)) { return; } final GuiceFilter guiceFilter = load(plugin); plugin.add(new RegistrationHandle() { @Override public void remove() { filter.compareAndSet(guiceFilter, null); } }); filter.set(guiceFilter); } private GuiceFilter load(Plugin plugin) { if (plugin.getHttpInjector() != null) { final String name = plugin.getName(); final GuiceFilter guiceFilter; try { guiceFilter = plugin.getHttpInjector().getInstance(GuiceFilter.class); } catch (RuntimeException e) { log.warn(String.format("Plugin %s cannot load GuiceFilter", name), e); return null; } try { ServletContext ctx = PluginServletContext.create(plugin, "/"); guiceFilter.init(new WrappedFilterConfig(ctx)); } catch (ServletException e) { log.warn(String.format("Plugin %s failed to initialize HTTP", name), e); return null; } plugin.add(new RegistrationHandle() { @Override public void remove() { guiceFilter.destroy(); } }); return guiceFilter; } return null; } }
30.632911
80
0.71095
007cff16bd506af24542f7f32bf1725734e2ca60
773
package com.example.yuanyuanlai.drivenoworry.Lock; import android.app.Service; import android.content.Intent; import android.content.IntentFilter; import android.os.IBinder; public class LockService extends Service { private LockScreenReceiver lockScreenReceiver; @Override public void onCreate() { lockScreenReceiver = new LockScreenReceiver(); IntentFilter mScreenOffFilte = new IntentFilter(); mScreenOffFilte.addAction(Intent.ACTION_SCREEN_OFF); registerReceiver(lockScreenReceiver,mScreenOffFilte); } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(lockScreenReceiver); } }
23.424242
61
0.717982
fe8e6f76f1a7824e3e7a0436a0f45bc6b25cbfa5
1,246
package com.tazine.jvm.exception; import java.lang.reflect.Field; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * DirectMemoryMonitor * * @author frank * @date 2019/1/22 */ public class DirectMemoryMonitor { private static final int _1M = 1024 * 1024; public static void main(String[] args) { while (true){ try { TimeUnit.SECONDS.sleep(1); report(); } catch (InterruptedException e) { e.printStackTrace(); } } } private static void report(){ try { Class c = Class.forName("java.nio.Bits"); // 总内存大小 Field field1 = c.getDeclaredField("maxMemory"); field1.setAccessible(true); // 剩余内存大小 Field field2 = c.getDeclaredField("reservedMemory"); field2.setAccessible(true); synchronized (c) { Long max = (Long) field1.get(null); AtomicLong reserve = (AtomicLong) field2.get(null); System.out.println(max/_1M + " " + reserve.get()/_1M); } } catch (Exception e) { e.printStackTrace(); } } }
26.510638
70
0.540931
58b98eed513967da450252c5ef816fd11052b386
3,394
package com.example.yiyoudoctor.mvp.model; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.util.Log; import com.example.yiyoudoctor.Base.App; import com.example.yiyoudoctor.Base.DemoContext; import com.example.yiyoudoctor.mvp.contract.LoginContract; import com.example.yiyoudoctor.util.my.NetUtils; import org.json.JSONException; import org.json.JSONObject; import io.rong.imkit.RongIM; import io.rong.imlib.RongIMClient; /** * Created by 夏夜晚凤 on 2017/4/21. */ public class LoginModel implements LoginContract.Model { String token; onConnectListener onConnectListener; public LoginModel(LoginContract.Model.onConnectListener onConnectListener) { this.onConnectListener = onConnectListener; } @Override /** * 获得token */ public void getToken() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String result = NetUtils.sendGetRequest("token"); return result; } @Override protected void onPostExecute(String result) { try { if (result != null) { JSONObject object = new JSONObject(result); JSONObject jobj = object.getJSONObject("result"); if (object.getInt("code") == 200) { token = jobj.getString("token"); connect(token); SharedPreferences.Editor edit = DemoContext.getInstance().getSharedPreferences().edit(); edit.putString("DEMO_TOKEN", token); edit.apply(); } } } catch (JSONException e) { e.printStackTrace(); } } }.execute(); } public void connect(final String token) { if (onConnectListener.ifApp()) { /** * IMKit SDK调用第二步,建立与服务器的连接 */ RongIM.connect("VqGgB3fFDbso3VxrfOeuSc92zQ3Ar7D+FvdaUdbFdKChHmQx/kgPxw1xg++ZCCnIZKK6aMdPkquoCasGlAV3fA==", new RongIMClient.ConnectCallback() { /** * Token 错误,在线上环境下主要是因为 Token 已经过期,您需要向 App Server 重新请求一个新的 Token */ @Override public void onTokenIncorrect() { Log.e("LoginActivity", "--onTokenIncorrect"); } /** * 连接融云成功 * @param userid 当前 token */ @Override public void onSuccess(String userid) { Log.e("LoginActivity", "--onSuccess" + userid); onConnectListener.onSuccess(); } /** * 连接融云失败 * @param errorCode 错误码,可到官网 查看错误码对应的注释 * http://www.rongcloud.cn/docs/android.html#常见错误码 */ @Override public void onError(RongIMClient.ErrorCode errorCode) { onConnectListener.onError(); Log.e("LoginActivity", "--onError" + errorCode); } }); } } }
28.521008
155
0.52033