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
c9380415a612ee8b50a2994714151b7d2aa301ac
2,111
/* Copyright (c) 2020 - for information on the respective copyright owner see the NOTICE file and/or the repository at https://github.com/hyperledger-labs/business-partner-agent 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.hyperledger.oa.impl.web; import io.micronaut.context.annotation.Requires; import io.micronaut.context.annotation.Value; import io.micronaut.context.env.Environment; import io.micronaut.scheduling.annotation.Async; import lombok.extern.slf4j.Slf4j; import org.hyperledger.aries.AriesClient; import org.hyperledger.oa.config.runtime.RequiresWeb; import org.hyperledger.oa.impl.activity.VPManager; import javax.inject.Inject; import javax.inject.Singleton; import java.time.Duration; @Slf4j @Singleton @RequiresWeb @Requires(notEnv = { Environment.TEST }) public class WebStartupTasks { @Inject private VPManager vpMgmt; @Inject private WebDidDocManager dicDocMgmt; @Inject private AriesClient ac; @Value("${oagent.host}") private String host; @Async public void onServiceStartedEvent() { log.debug("Running web mode startup tasks..."); vpMgmt.getVerifiablePresentation().ifPresentOrElse(vp -> { log.info("VP already exists, skipping: {}", host); }, () -> { ac.statusWaitUntilReady(Duration.ofSeconds(60)); log.info("Creating default did document for host: {}", host); dicDocMgmt.createIfNeeded(host); log.info("Creating default public profile for host: {}", host); vpMgmt.recreateVerifiablePresentation(); }); } }
32.476923
75
0.722406
7df1acab65afe1422d28f7ae6a5845d3cb80c12b
2,779
package slimeknights.tconstruct.tools.common; import java.util.Set; import javax.annotation.Nonnull; import com.google.common.collect.ImmutableSet; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.util.NonNullList; import net.minecraft.world.World; import net.minecraftforge.registries.IForgeRegistryEntry.Impl; import slimeknights.tconstruct.library.Util; import slimeknights.tconstruct.library.tinkering.TinkersItem; import slimeknights.tconstruct.tools.TinkerTools; public class RepairRecipe extends Impl<IRecipe> implements IRecipe { public RepairRecipe() { this.setRegistryName(Util.getResource("repair")); } private static final Set<Item> repairItems = ImmutableSet.of(TinkerTools.sharpeningKit); @Override public boolean matches(@Nonnull InventoryCrafting inv, @Nonnull World worldIn) { return !getRepairedTool(inv, true).isEmpty(); } @Nonnull @Override public ItemStack getCraftingResult(@Nonnull InventoryCrafting inv) { return getRepairedTool(inv, true); } @Nonnull private ItemStack getRepairedTool(@Nonnull InventoryCrafting inv, boolean simulate) { ItemStack tool = null; NonNullList<ItemStack> input = NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); for(int i = 0; i < inv.getSizeInventory(); i++) { ItemStack slot = inv.getStackInSlot(i); // empty slot if(slot.isEmpty()) { continue; } slot = slot.copy(); slot.setCount(1); Item item = slot.getItem(); // is it the tool? if(item instanceof TinkersItem) { // stop if we already have a tool, 2 tools present if(tool != null) { return ItemStack.EMPTY; } tool = slot; } // otherwise.. input material else if(repairItems.contains(item)) { input.set(i, slot); } // invalid item else { return ItemStack.EMPTY; } } // no tool found? if(tool == null) { return ItemStack.EMPTY; } if(simulate) { input = Util.deepCopyFixedNonNullList(input); } // do the repairing, also checks for valid input return ((TinkersItem) tool.getItem()).repair(tool.copy(), input); } @Nonnull @Override public ItemStack getRecipeOutput() { return ItemStack.EMPTY; } @Override public NonNullList<ItemStack> getRemainingItems(@Nonnull InventoryCrafting inv) { return NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); } @Override public boolean canFit(int width, int height) { return width >= 3 && height >= 3; } @Override public boolean isHidden() { return true; } }
25.495413
97
0.689097
684132939a4f74b5e0237f7c9ffeec41e2c4738d
1,180
/* * Copyright (c) 2020 Dario Lucia (https://www.dariolucia.eu) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.dariolucia.reatmetric.api.common; /** * This enumeration specifies the two possible retrieval directions in a retrieval request: from the time/data item reference to the future, * or to the past. */ public enum RetrievalDirection { /** * Retrieve data item from the reference to the future: data items are returned in ascending generation time order */ TO_FUTURE, /** * Retrieve data item from the reference to the past: data items are returned in descending generation time order */ TO_PAST }
34.705882
140
0.722881
c4e262980bd4058380d7cff18638dc36a34000ef
389
package com.feedbactory.client.ui.feedback.personal; final class NoCriteriaSubmissionScaleRenderer extends PersonalFeedbackSubmissionScaleRenderer { final int[] emptyControlGap = new int[] {0}; @Override final String getSubmissionColumnHeader() { return ""; } @Override final int[] getSubmissionScaleControlGaps() { return emptyControlGap; } }
17.681818
93
0.719794
0d534afd130761614498123d2fbc517c10708c40
1,528
package com.symphony.bdk.workflow.engine.executor.group; import com.symphony.bdk.ext.group.gen.api.model.GroupList; import com.symphony.bdk.ext.group.gen.api.model.SortOrder; import com.symphony.bdk.ext.group.gen.api.model.Status; import com.symphony.bdk.workflow.engine.executor.ActivityExecutor; import com.symphony.bdk.workflow.engine.executor.ActivityExecutorContext; import com.symphony.bdk.workflow.swadl.v1.activity.group.GetGroups; import lombok.extern.slf4j.Slf4j; @Slf4j public class GetGroupsExecutor implements ActivityExecutor<GetGroups> { private static final String OUTPUTS_GROUP_KEY = "groups"; @Override public void execute(ActivityExecutorContext<GetGroups> execution) { log.debug("Getting groups"); Status status = toStatus(execution.getActivity().getStatus()); Integer limit = execution.getActivity().getLimit(); SortOrder sort = toSortOrder(execution.getActivity().getSortOrder()); String before = execution.getActivity().getBefore(); String after = execution.getActivity().getAfter(); GroupList groups = execution.bdk().groups().listGroups(status, before, after, limit, sort); execution.setOutputVariable(OUTPUTS_GROUP_KEY, groups); } private Status toStatus(String status) { if (status == null) { return null; } else { return Status.fromValue(status); } } private SortOrder toSortOrder(String sortOrder) { if (sortOrder == null) { return null; } else { return SortOrder.fromValue(sortOrder); } } }
31.183673
95
0.740838
9fb7f3e0280d3a456022458242c65f9c7c122651
937
package com.example.restservice; import java.util.Date; import lombok.Data; /** * This class is the model for Partidak. * * @author kalboetxeaga.ager * */ @Data public class Partida { private String puntuazioa; private String kills; private String time; private String date; private Employee employee; public Partida() { } public String getPuntuazioa() { return puntuazioa; } public void setPuntuazioa(String puntuazioa) { this.puntuazioa = puntuazioa; } public String getKills() { return kills; } public void setKills(String kills) { this.kills = kills; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public Employee getEmployee() { return employee; } public void setEmployee(Employee employee) { this.employee = employee; } }
17.036364
47
0.701174
6df58c01b11981211763948bab71ee1fd9689e18
669
package fr.adrienbrault.idea.symfony2plugin.templating.variable.resolver; import fr.adrienbrault.idea.symfony2plugin.templating.variable.TwigTypeContainer; import fr.adrienbrault.idea.symfony2plugin.templating.variable.dict.PsiVariable; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.List; /** * @author Daniel Espendiller <[email protected]> */ public interface TwigTypeResolver { void resolve(Collection<TwigTypeContainer> targets, @Nullable Collection<TwigTypeContainer> previousElement, String typeName, Collection<List<TwigTypeContainer>> previousElements, @Nullable Collection<PsiVariable> psiVariables); }
41.8125
232
0.835575
e82e870ca3eac4a7d25a10103dd32417173bab89
2,441
package com.aljazkajtna.kamino.ui.residents; import android.database.DataSetObserver; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.aljazkajtna.kamino.R; import com.aljazkajtna.kamino.data.pojo.Resident; import java.util.List; public class ResidentsListAdapter extends BaseAdapter { private static final String Tag = "ResidentsListAdapter"; private final Fragment fragment; private final List<Resident> residentList; public ResidentsListAdapter(Fragment fragment, List<Resident> residentList) { this.fragment = fragment; this.residentList = residentList; } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int i) { return false; } @Override public void registerDataSetObserver(DataSetObserver dataSetObserver) { } @Override public void unregisterDataSetObserver(DataSetObserver dataSetObserver) { } @Override public int getCount() { return residentList.size(); } @Override public Object getItem(int i) { return residentList.get(i); } @Override public long getItemId(int i) { return 0; } @Override public boolean hasStableIds() { return false; } @Override public View getView(int i, View view, ViewGroup viewGroup) { Resident data = (Resident) getItem(i); View elementView = (View) view; if (elementView == null) { final LayoutInflater inflater = LayoutInflater.from(fragment.getContext()); elementView = inflater.inflate(R.layout.resident_list_element, null); } TextView name = elementView.findViewById(R.id.residentName); name.setText(data.getName()); elementView.setOnClickListener(view1 -> { ((ResidentsFragment) fragment).openResident(data); }); return elementView; } @Override public int getItemViewType(int i) { return 0; } @Override public int getViewTypeCount() { return 1; } @Override public boolean isEmpty() { return false; } }
23.699029
88
0.636624
4e7616ad49029e11b07e8f41703e1bf3a6fd9879
10,913
//name: date: import java.util.*; //for the queue interface public class TreeLab { public static TreeNode root = null; public static String s = "XCOMPUTERSCIENCE"; //public static String s = "XSingaporeAmericanSchool"; //public static String s = "XAComputerScienceTreeHasItsRootAtTheTop"; public static void main(String[] args) { root = buildTree( root, s ); System.out.print( display(root, 0) ); System.out.print("\nPreorder: " + preorderTraverse(root)); System.out.print("\nInorder: " + inorderTraverse(root)); System.out.print("\nPostorder: " + postorderTraverse(root)); System.out.println("\n\nNodes = " + countNodes(root)); System.out.println("Leaves = " + countLeaves(root)); System.out.println("Grandparents = " + countGrands(root)); System.out.println("Only childs = " + countOnlys(root)); System.out.println("\nHeight of tree = " + height(root)); System.out.println("Width = " + width(root)); System.out.println("Min = " + min(root)); System.out.println("Max = " + max(root)); System.out.println("\nBy Level: "); System.out.println(displayLevelOrder(root)); } public static TreeNode buildTree(TreeNode root, String s) { root = new TreeNode("" + s.charAt(1), null, null); for(int pos = 2; pos < s.length(); pos++) insert(root, "" + s.charAt(pos), pos, (int)(1 + Math.log(pos) / Math.log(2))); insert(root, "A", 17, 5); insert(root, "B", 18, 5); insert(root, "C", 37, 6); //B's right child return root; } public static void insert(TreeNode t, String s, int pos, int level) { TreeNode p = t; for(int k = level - 2; k > 0; k--) if((pos & (1 << k)) == 0) p = p.getLeft(); else p = p.getRight(); if((pos & 1) == 0) p.setLeft(new TreeNode(s, null, null)); else p.setRight(new TreeNode(s, null, null)); } private static String display(TreeNode t, int level) { String toRet = ""; if(t == null) return ""; toRet += display(t.getRight(), level + 1); //recurse right for(int k = 0; k < level; k++) toRet += "\t"; toRet += t.getValue() + "\n"; toRet += display(t.getLeft(), level + 1); //recurse left return toRet; } public static String preorderTraverse(TreeNode t) { String toReturn = ""; if(t == null) return ""; toReturn += t.getValue() + " "; //preorder visit toReturn += preorderTraverse(t.getLeft()); //recurse left toReturn += preorderTraverse(t.getRight()); //recurse right return toReturn; } public static String inorderTraverse(TreeNode t) { String toReturn = ""; if(t == null) return ""; toReturn += inorderTraverse(t.getLeft()); toReturn += t.getValue() + " "; toReturn += inorderTraverse(t.getRight()); return toReturn; } public static String postorderTraverse(TreeNode t) { String toReturn = ""; if(t == null) return ""; toReturn += postorderTraverse(t.getLeft()); toReturn += postorderTraverse(t.getRight()); toReturn += t.getValue() + " "; return toReturn; } public static int countNodes(TreeNode t) { if(t==null) return 0; else if(t.getLeft()==null&&t.getRight()==null) return 1; else if(t.getLeft()==null) return 1+countNodes(t.getRight()); else if(t.getRight()==null) return 1+countNodes(t.getLeft()); else return 1+countNodes(t.getLeft())+countNodes(t.getRight()); } public static int countLeaves(TreeNode t) { if(t==null) return 0; else if(t.getLeft()==null&&t.getRight()==null) return 1; else if(t.getLeft()==null) return countLeaves(t.getRight()); else if(t.getRight()==null) return countLeaves(t.getLeft()); else return countLeaves(t.getLeft())+countLeaves(t.getRight()); } public static int countGrands(TreeNode t) { if(t==null) return 0; else if(height(t)>=2) return 1+countGrands(t.getLeft())+countGrands(t.getRight()); else return 0; } public static int countOnlys(TreeNode t) { if(t==null) return 0; else if(t.getRight()!=null&&t.getLeft()!=null) return countOnlys(t.getRight())+countOnlys(t.getLeft()); else if(t.getRight()!=null||t.getLeft()!=null) { if(t.getLeft()==null) return 1+countOnlys(t.getRight()); else return 1+countOnlys(t.getLeft()); } else return 0; } public static int height(TreeNode t) { if(t==null) return 0; else if(t.getRight()==null && t.getLeft()==null) return 0; else if(t.getRight()==null) return 1+height(t.getLeft()); else if(t.getLeft()==null) return 1+height(t.getRight()); else return 1+Math.max(height(t.getRight()),height(t.getLeft())); } /* "width" is the longest path from leaf to leaf */ public static int width(TreeNode t) { if(t==null) return 0; if(t.getRight()==null && t.getLeft()==null) return 1; else if(t.getRight()==null) { int t1=height(t); int tL=1+width(t.getLeft()); if(t1>tL) return t1; else return tL; } else if(t.getLeft()==null) { int t1=height(t); int tR=1+width(t.getRight()); if(t1>tR) return t1; else return tR; } else { int t1=height(t.getLeft())+height(t.getRight())+1; int tR=1+width(t.getRight()); int tL=1+width(t.getLeft()); if(t1>tR) { if(t1>tL) return t1; else return tR; } else { if(tR>tL) return tR; else return tL; } } } @SuppressWarnings("unchecked")//this removes the warning about needing to cast public static Object min(TreeNode t) { if(t==null) return null; if(t.getRight()==null && t.getLeft()==null) return (String)t.getValue(); else if(t.getRight()==null) { String t1=(String)t.getValue(); String tL=(String)min(t.getLeft()); if(t1.compareTo(tL)<0) return t1; else return tL; } else if(t.getLeft()==null) { String t1=(String)t.getValue(); String tR=(String)min(t.getRight()); if(t1.compareTo(tR)<0) return t1; else return tR; } else { String t1=(String)t.getValue(); String tR=(String)min(t.getRight()); String tL=(String)min(t.getLeft()); if(t1.compareTo(tR)<0) { if(t1.compareTo(tL)<0) return t1; else return tR; } else { if(tR.compareTo(tL)<0) return tR; else return tL; } } } @SuppressWarnings("unchecked")//this removes the warning about needing to cast public static Object max(TreeNode t) { if(t==null) return null; if(t.getRight()==null && t.getLeft()==null) return (String)t.getValue(); else if(t.getRight()==null) { String t1=(String)t.getValue(); String tL=(String)max(t.getLeft()); if(t1.compareTo(tL)>0) return t1; else return tL; } else if(t.getLeft()==null) { String t1=(String)t.getValue(); String tR=(String)max(t.getRight()); if(t1.compareTo(tR)>0) return t1; else return tR; } else { String t1=(String)t.getValue(); String tR=(String)max(t.getRight()); String tL=(String)max(t.getLeft()); if(t1.compareTo(tR)>0) { if(t1.compareTo(tL)>0) return t1; else return tR; } else { if(tR.compareTo(tL)>0) return tR; else return tL; } } } /* this method is not recursive. Use a local queue to store the children of the current node.*/ public static String displayLevelOrder(TreeNode t) { Queue <TreeNode> k= new LinkedList<>(); String toReturn = ""; if(t == null) return toReturn; else k.add(t); while(!k.isEmpty()) { if(k.peek().getLeft() != null) k.add(k.peek().getLeft()); if(k.peek().getRight() != null) k.add(k.peek().getRight()); toReturn += k.poll().getValue(); } return toReturn; } } /*************************************************** ----jGRASP exec: java Lab01 E E C M N T E C I U C O S C B P A R Preorder: C O P R A S B C U C I M T E N E C E Inorder: R A P B C S O C U I C E T N M C E E Postorder: A R C B S P C I U O E N T C E E M C Nodes = 18 Leaves = 8 Grandparents = 5 Only childs = 3 Height of tree = 5 Width = 8 Min = A Max = U By Level: COMPUTERSCIENCEABC *******************************************************/ /* TreeNode class for the AP Exams */ class TreeNode { private Object value; private TreeNode left, right; public TreeNode(Object initValue) { value = initValue; left = null; right = null; } public TreeNode(Object initValue, TreeNode initLeft, TreeNode initRight) { value = initValue; left = initLeft; right = initRight; } public Object getValue() { return value; } public TreeNode getLeft() { return left; } public TreeNode getRight() { return right; } public void setValue(Object theNewValue) { value = theNewValue; } public void setLeft(TreeNode theNewLeft) { left = theNewLeft; } public void setRight(TreeNode theNewRight) { right = theNewRight; } }
24.97254
81
0.491249
6f4af005f35a84f7cc28b8cfbf8874515cba022a
17,131
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ package integration.forms; import com.sun.star.beans.PropertyState; import com.sun.star.beans.PropertyValue; import com.sun.star.beans.XPropertySet; import com.sun.star.container.XChild; import com.sun.star.container.XIndexContainer; import com.sun.star.container.XNameContainer; import com.sun.star.document.MacroExecMode; import com.sun.star.drawing.XDrawPage; import com.sun.star.drawing.XDrawPageSupplier; import com.sun.star.drawing.XDrawPages; import com.sun.star.drawing.XDrawPagesSupplier; import com.sun.star.form.XFormsSupplier; import com.sun.star.frame.XComponentLoader; import com.sun.star.frame.XController; import com.sun.star.frame.XFrame; import com.sun.star.frame.XModel; import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.lang.XServiceInfo; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; import com.sun.star.util.XModifiable; /**************************************************************************/ /**************************************************************************/ /** provides a small wrapper around a document */ public class DocumentHelper { private XMultiServiceFactory m_orb; private XComponent m_documentComponent; /* ================================================================== */ /* ------------------------------------------------------------------ */ public DocumentHelper( XMultiServiceFactory orb, XComponent document ) { m_orb = orb; m_documentComponent = document; } /* ------------------------------------------------------------------ */ protected static XComponent implLoadAsComponent( XMultiServiceFactory orb, String documentOrFactoryURL ) throws com.sun.star.uno.Exception { return implLoadAsComponent( orb, documentOrFactoryURL, new PropertyValue[0] ); } /* ------------------------------------------------------------------ */ protected static XComponent implLoadAsComponent( XMultiServiceFactory orb, String documentOrFactoryURL, final PropertyValue[] i_args ) throws com.sun.star.uno.Exception { XComponentLoader aLoader = (XComponentLoader)UnoRuntime.queryInterface( XComponentLoader.class, orb.createInstance( "com.sun.star.frame.Desktop" ) ); XComponent document = dbfTools.queryComponent( aLoader.loadComponentFromURL( documentOrFactoryURL, "_blank", 0, i_args ) ); return document; } /* ------------------------------------------------------------------ */ private static DocumentHelper implLoadDocument( XMultiServiceFactory orb, String documentOrFactoryURL ) throws com.sun.star.uno.Exception { return implLoadDocument( orb, documentOrFactoryURL, new PropertyValue[0] ); } /* ------------------------------------------------------------------ */ private static DocumentHelper implLoadDocument( XMultiServiceFactory orb, String documentOrFactoryURL, final PropertyValue[] i_args ) throws com.sun.star.uno.Exception { XComponent document = implLoadAsComponent( orb, documentOrFactoryURL, i_args ); XServiceInfo xSI = (XServiceInfo)UnoRuntime.queryInterface( XServiceInfo.class, document ); if ( xSI.supportsService( "com.sun.star.sheet.SpreadsheetDocument" ) ) return new SpreadsheetDocument( orb, document ); return new DocumentHelper( orb, document ); } /* ------------------------------------------------------------------ */ public static DocumentHelper loadDocument( XMultiServiceFactory orb, String documentURL ) throws com.sun.star.uno.Exception { return implLoadDocument( orb, documentURL ); } /* ------------------------------------------------------------------ */ public static DocumentHelper blankTextDocument( XMultiServiceFactory orb ) throws com.sun.star.uno.Exception { return blankDocument( orb, DocumentType.WRITER ); } /* ------------------------------------------------------------------ */ public static DocumentHelper blankXMLForm( XMultiServiceFactory orb ) throws com.sun.star.uno.Exception { return blankDocument( orb, DocumentType.XMLFORM ); } /* ------------------------------------------------------------------ */ public static DocumentHelper blankDocument( XMultiServiceFactory orb, DocumentType eType ) throws com.sun.star.uno.Exception { final PropertyValue[] args = new PropertyValue[] { new PropertyValue( "MacroExecutionMode", -1, MacroExecMode.ALWAYS_EXECUTE, PropertyState.DIRECT_VALUE ) }; return implLoadDocument( orb, getDocumentFactoryURL( eType ), args ); } /* ================================================================== */ /* ------------------------------------------------------------------ */ public XComponent getDocument( ) { return m_documentComponent; } /* ------------------------------------------------------------------ */ public boolean isModified() { XModifiable modify = (XModifiable)query( XModifiable.class ); return modify.isModified(); } /* ------------------------------------------------------------------ */ public Object query( Class aInterfaceClass ) { return UnoRuntime.queryInterface( aInterfaceClass, m_documentComponent ); } /* ------------------------------------------------------------------ */ public XMultiServiceFactory getOrb( ) { return m_orb; } /* ------------------------------------------------------------------ */ /** retrieves the current view of the document @return the view component, queried for the interface described by aInterfaceClass */ public DocumentViewHelper getCurrentView( ) { // get the model interface for the document XModel xDocModel = (XModel)UnoRuntime.queryInterface(XModel.class, m_documentComponent ); // get the current controller for the document - as a controller is tied to a view, // this gives us the currently active view for the document. XController xController = xDocModel.getCurrentController(); if ( classify() == DocumentType.CALC ) return new SpreadsheetView( m_orb, this, xController ); return new DocumentViewHelper( m_orb, this, xController ); } /* ------------------------------------------------------------------ */ /** reloads the document * * The reload is done by dispatching the respective URL at a frame of the document. * As a consequence, if you have references to a view of the document, or any interface * of the document, they will become invalid. * The Model instance itself, at which you called reload, will still be valid, it will * automatically update its internal state after the reload. * * Another consequence is that if the document does not have a view at all, it cannot * be reloaded. */ public void reload() throws Exception { DocumentViewHelper view = getCurrentView(); XFrame frame = view.getController().getFrame(); XModel oldModel = frame.getController().getModel(); getCurrentView().dispatch( ".uno:Reload" ); m_documentComponent = (XComponent)UnoRuntime.queryInterface( XComponent.class, frame.getController().getModel() ); XModel newModel = getCurrentView().getController().getModel(); if ( UnoRuntime.areSame( oldModel, newModel ) ) throw new java.lang.IllegalStateException( "reload failed" ); } /* ------------------------------------------------------------------ */ /** creates a new form which is a child of the given form components container @param xParentContainer The parent container for the new form @param sInitialName The initial name of the form. May be null, in this case the default (which is an implementation detail) applies. */ protected XIndexContainer createSubForm( XIndexContainer xParentContainer, String sInitialName ) throws com.sun.star.uno.Exception { // create a new form Object xNewForm = m_orb.createInstance( "com.sun.star.form.component.DataForm" ); // insert xParentContainer.insertByIndex( xParentContainer.getCount(), xNewForm ); // set the name if necessary if ( null != sInitialName ) { XPropertySet xFormProps = dbfTools.queryPropertySet( xNewForm ); xFormProps.setPropertyValue( "Name", sInitialName ); } // outta here return (XIndexContainer)UnoRuntime.queryInterface( XIndexContainer.class, xNewForm ); } /* ------------------------------------------------------------------ */ /** creates a new form which is a child of the given form components container @param aParentContainer The parent container for the new form @param sInitialName The initial name of the form. May be null, in this case the default (which is an implementation detail) applies. */ public XIndexContainer createSubForm( Object aParentContainer, String sInitialName ) throws com.sun.star.uno.Exception { XIndexContainer xParentContainer = (XIndexContainer)UnoRuntime.queryInterface( XIndexContainer.class, aParentContainer ); return createSubForm( xParentContainer, sInitialName ); } /* ------------------------------------------------------------------ */ /** creates a form which is a sibling of the given form @param aForm A sinbling of the to be created form. @param sInitialName The initial name of the form. May be null, in this case the default (which is an implementation detail) applies. */ public XIndexContainer createSiblingForm( Object aForm, String sInitialName ) throws com.sun.star.uno.Exception { // get the parent XIndexContainer xContainer = (XIndexContainer)dbfTools.getParent( aForm, XIndexContainer.class ); // append a new form to this parent container return createSubForm( xContainer, sInitialName ); } /* ------------------------------------------------------------------ */ /** retrieves the document model which a given form component belongs to */ static public DocumentHelper getDocumentForComponent( Object aFormComponent, XMultiServiceFactory orb ) { XChild xChild = (XChild)UnoRuntime.queryInterface( XChild.class, aFormComponent ); XModel xModel = null; while ( ( null != xChild ) && ( null == xModel ) ) { XInterface xParent = (XInterface)xChild.getParent(); xModel = (XModel)UnoRuntime.queryInterface( XModel.class, xParent ); xChild = (XChild)UnoRuntime.queryInterface( XChild.class, xParent ); } return new DocumentHelper( orb, xModel ); } /* ------------------------------------------------------------------ */ /** returns a URL which can be used to create a document of a certain type */ public static String getDocumentFactoryURL( DocumentType eType ) { if ( eType == DocumentType.WRITER ) return "private:factory/swriter"; if ( eType == DocumentType.CALC ) return "private:factory/scalc"; if ( eType == DocumentType.DRAWING ) return "private:factory/sdraw"; if ( eType == DocumentType.XMLFORM ) return "private:factory/swriter?slot=21053"; return "private:factory/swriter"; } /* ------------------------------------------------------------------ */ /** classifies a document */ public DocumentType classify( ) { XServiceInfo xSI = (XServiceInfo)UnoRuntime.queryInterface( XServiceInfo.class, m_documentComponent ); if ( xSI.supportsService( "com.sun.star.text.TextDocument" ) ) return DocumentType.WRITER; else if ( xSI.supportsService( "com.sun.star.sheet.SpreadsheetDocument" ) ) return DocumentType.CALC; else if ( xSI.supportsService( "com.sun.star.drawing.DrawingDocument" ) ) return DocumentType.DRAWING; return DocumentType.UNKNOWN; } /* ------------------------------------------------------------------ */ /** retrieves a com.sun.star.drawing.DrawPage of the document, denoted by index * @param index * the index of the draw page * @throws * com.sun.star.lang.IndexOutOfBoundsException * com.sun.star.lang.WrappedTargetException */ protected XDrawPage getDrawPage( int index ) throws com.sun.star.lang.IndexOutOfBoundsException, com.sun.star.lang.WrappedTargetException { XDrawPagesSupplier xSuppPages = (XDrawPagesSupplier)UnoRuntime.queryInterface( XDrawPagesSupplier.class, getDocument() ); XDrawPages xPages = xSuppPages.getDrawPages(); return (XDrawPage)UnoRuntime.queryInterface( XDrawPage.class, xPages.getByIndex( index ) ); } /* ------------------------------------------------------------------ */ /** retrieves the <type scope="com.sun.star.drawing">DrawPage</type> of the document */ protected XDrawPage getMainDrawPage( ) throws com.sun.star.uno.Exception { XDrawPage xReturn; // in case of a Writer document, this is rather easy: simply ask the XDrawPageSupplier XDrawPageSupplier xSuppPage = (XDrawPageSupplier)UnoRuntime.queryInterface( XDrawPageSupplier.class, getDocument() ); if ( null != xSuppPage ) xReturn = xSuppPage.getDrawPage(); else { // the model itself is no draw page supplier - okay, it may be a Writer or Calc document // (or any other multi-page document) XDrawPagesSupplier xSuppPages = (XDrawPagesSupplier)UnoRuntime.queryInterface( XDrawPagesSupplier.class, getDocument() ); XDrawPages xPages = xSuppPages.getDrawPages(); xReturn = (XDrawPage)UnoRuntime.queryInterface( XDrawPage.class, xPages.getByIndex( 0 ) ); // Note that this is no really error-proof code: If the document model does not support the // XDrawPagesSupplier interface, or if the pages collection returned is empty, this will break. } return xReturn; } /* ------------------------------------------------------------------ */ /** retrieves the root of the hierarchy of form components */ protected XNameContainer getFormComponentTreeRoot( ) throws com.sun.star.uno.Exception { XFormsSupplier xSuppForms = (XFormsSupplier)UnoRuntime.queryInterface( XFormsSupplier.class, getMainDrawPage( ) ); XNameContainer xFormsCollection = null; if ( null != xSuppForms ) { xFormsCollection = xSuppForms.getForms(); } return xFormsCollection; } /* ------------------------------------------------------------------ */ /** creates a component at the service factory provided by the document */ public XInterface createInstance( String serviceSpecifier ) throws com.sun.star.uno.Exception { XMultiServiceFactory xORB = (XMultiServiceFactory)UnoRuntime.queryInterface( XMultiServiceFactory.class, m_documentComponent ); return (XInterface)xORB.createInstance( serviceSpecifier ); } /* ------------------------------------------------------------------ */ /** creates a component at the service factory provided by the document */ public XInterface createInstanceWithArguments( String serviceSpecifier, Object[] arguments ) throws com.sun.star.uno.Exception { XMultiServiceFactory xORB = (XMultiServiceFactory)UnoRuntime.queryInterface( XMultiServiceFactory.class, m_documentComponent ); return (XInterface) xORB.createInstanceWithArguments( serviceSpecifier, arguments ); } };
42.720698
172
0.592318
705b2b7bda699c130f6464789fdcdb27a58bb989
347
package edp.vap.dao; import edp.vap.model.OperaLog; public interface OperaLogMapper { int deleteByPrimaryKey(Long id); int insert(OperaLog record); int insertSelective(OperaLog record); OperaLog selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(OperaLog record); int updateByPrimaryKey(OperaLog record); }
20.411765
53
0.757925
1bf8d0f7d6151922ee237f8c54f2c1f308b92da1
1,189
package org.iotp.analytics.ruleengine.plugins.msg; import java.util.Optional; import org.iotp.analytics.ruleengine.api.device.ToDeviceActorNotificationMsg; import org.iotp.analytics.ruleengine.common.msg.cluster.ServerAddress; import org.iotp.infomgt.data.id.DeviceId; import org.iotp.infomgt.data.id.PluginId; import org.iotp.infomgt.data.id.TenantId; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.ToString; /** */ @ToString @RequiredArgsConstructor public class ToDeviceRpcRequestPluginMsg implements ToDeviceActorNotificationMsg { private final ServerAddress serverAddress; @Getter private final PluginId pluginId; @Getter private final TenantId pluginTenantId; @Getter private final ToDeviceRpcRequest msg; public ToDeviceRpcRequestPluginMsg(PluginId pluginId, TenantId pluginTenantId, ToDeviceRpcRequest msg) { this(null, pluginId, pluginTenantId, msg); } public Optional<ServerAddress> getServerAddress() { return Optional.ofNullable(serverAddress); } @Override public DeviceId getDeviceId() { return msg.getDeviceId(); } @Override public TenantId getTenantId() { return msg.getTenantId(); } }
25.297872
106
0.789739
3430f313c35cf93836cf3be6aeb011fcddee2577
11,002
package net.minecraft.world.phys.shapes; import com.google.common.collect.Lists; import com.google.common.math.DoubleMath; import it.unimi.dsi.fastutil.doubles.DoubleList; import java.util.List; import java.util.Optional; import javax.annotation.Nullable; import net.minecraft.Util; import net.minecraft.core.AxisCycle; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.util.Mth; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; public abstract class VoxelShape { protected final DiscreteVoxelShape shape; @Nullable private VoxelShape[] faces; VoxelShape(DiscreteVoxelShape pShape) { this.shape = pShape; } public double min(Direction.Axis pAxis) { int i = this.shape.firstFull(pAxis); return i >= this.shape.getSize(pAxis) ? Double.POSITIVE_INFINITY : this.get(pAxis, i); } public double max(Direction.Axis pAxis) { int i = this.shape.lastFull(pAxis); return i <= 0 ? Double.NEGATIVE_INFINITY : this.get(pAxis, i); } public AABB bounds() { if (this.isEmpty()) { throw (UnsupportedOperationException)Util.pauseInIde(new UnsupportedOperationException("No bounds for empty shape.")); } else { return new AABB(this.min(Direction.Axis.X), this.min(Direction.Axis.Y), this.min(Direction.Axis.Z), this.max(Direction.Axis.X), this.max(Direction.Axis.Y), this.max(Direction.Axis.Z)); } } protected double get(Direction.Axis pAxis, int pIndex) { return this.getCoords(pAxis).getDouble(pIndex); } protected abstract DoubleList getCoords(Direction.Axis pAxis); public boolean isEmpty() { return this.shape.isEmpty(); } public VoxelShape move(double pXOffset, double pYOffset, double pZOffset) { return (VoxelShape)(this.isEmpty() ? Shapes.empty() : new ArrayVoxelShape(this.shape, (DoubleList)(new OffsetDoubleList(this.getCoords(Direction.Axis.X), pXOffset)), (DoubleList)(new OffsetDoubleList(this.getCoords(Direction.Axis.Y), pYOffset)), (DoubleList)(new OffsetDoubleList(this.getCoords(Direction.Axis.Z), pZOffset)))); } public VoxelShape optimize() { VoxelShape[] avoxelshape = new VoxelShape[]{Shapes.empty()}; this.forAllBoxes((p_83275_, p_83276_, p_83277_, p_83278_, p_83279_, p_83280_) -> { avoxelshape[0] = Shapes.joinUnoptimized(avoxelshape[0], Shapes.box(p_83275_, p_83276_, p_83277_, p_83278_, p_83279_, p_83280_), BooleanOp.OR); }); return avoxelshape[0]; } public void forAllEdges(Shapes.DoubleLineConsumer pAction) { this.shape.forAllEdges((p_83228_, p_83229_, p_83230_, p_83231_, p_83232_, p_83233_) -> { pAction.consume(this.get(Direction.Axis.X, p_83228_), this.get(Direction.Axis.Y, p_83229_), this.get(Direction.Axis.Z, p_83230_), this.get(Direction.Axis.X, p_83231_), this.get(Direction.Axis.Y, p_83232_), this.get(Direction.Axis.Z, p_83233_)); }, true); } public void forAllBoxes(Shapes.DoubleLineConsumer pAction) { DoubleList doublelist = this.getCoords(Direction.Axis.X); DoubleList doublelist1 = this.getCoords(Direction.Axis.Y); DoubleList doublelist2 = this.getCoords(Direction.Axis.Z); this.shape.forAllBoxes((p_83239_, p_83240_, p_83241_, p_83242_, p_83243_, p_83244_) -> { pAction.consume(doublelist.getDouble(p_83239_), doublelist1.getDouble(p_83240_), doublelist2.getDouble(p_83241_), doublelist.getDouble(p_83242_), doublelist1.getDouble(p_83243_), doublelist2.getDouble(p_83244_)); }, true); } public List<AABB> toAabbs() { List<AABB> list = Lists.newArrayList(); this.forAllBoxes((p_83267_, p_83268_, p_83269_, p_83270_, p_83271_, p_83272_) -> { list.add(new AABB(p_83267_, p_83268_, p_83269_, p_83270_, p_83271_, p_83272_)); }); return list; } public double min(Direction.Axis pAxis, double pPrimaryPosition, double pSecondaryPosition) { Direction.Axis direction$axis = AxisCycle.FORWARD.cycle(pAxis); Direction.Axis direction$axis1 = AxisCycle.BACKWARD.cycle(pAxis); int i = this.findIndex(direction$axis, pPrimaryPosition); int j = this.findIndex(direction$axis1, pSecondaryPosition); int k = this.shape.firstFull(pAxis, i, j); return k >= this.shape.getSize(pAxis) ? Double.POSITIVE_INFINITY : this.get(pAxis, k); } public double max(Direction.Axis pAxis, double pPrimaryPosition, double pSecondaryPosition) { Direction.Axis direction$axis = AxisCycle.FORWARD.cycle(pAxis); Direction.Axis direction$axis1 = AxisCycle.BACKWARD.cycle(pAxis); int i = this.findIndex(direction$axis, pPrimaryPosition); int j = this.findIndex(direction$axis1, pSecondaryPosition); int k = this.shape.lastFull(pAxis, i, j); return k <= 0 ? Double.NEGATIVE_INFINITY : this.get(pAxis, k); } protected int findIndex(Direction.Axis pAxis, double pPosition) { return Mth.binarySearch(0, this.shape.getSize(pAxis) + 1, (p_166066_) -> { return pPosition < this.get(pAxis, p_166066_); }) - 1; } @Nullable public BlockHitResult clip(Vec3 pStartVec, Vec3 pEndVec, BlockPos pPos) { if (this.isEmpty()) { return null; } else { Vec3 vec3 = pEndVec.subtract(pStartVec); if (vec3.lengthSqr() < 1.0E-7D) { return null; } else { Vec3 vec31 = pStartVec.add(vec3.scale(0.001D)); return this.shape.isFullWide(this.findIndex(Direction.Axis.X, vec31.x - (double)pPos.getX()), this.findIndex(Direction.Axis.Y, vec31.y - (double)pPos.getY()), this.findIndex(Direction.Axis.Z, vec31.z - (double)pPos.getZ())) ? new BlockHitResult(vec31, Direction.getNearest(vec3.x, vec3.y, vec3.z).getOpposite(), pPos, true) : AABB.clip(this.toAabbs(), pStartVec, pEndVec, pPos); } } } public Optional<Vec3> closestPointTo(Vec3 pPoint) { if (this.isEmpty()) { return Optional.empty(); } else { Vec3[] avec3 = new Vec3[1]; this.forAllBoxes((p_166072_, p_166073_, p_166074_, p_166075_, p_166076_, p_166077_) -> { double d0 = Mth.clamp(pPoint.x(), p_166072_, p_166075_); double d1 = Mth.clamp(pPoint.y(), p_166073_, p_166076_); double d2 = Mth.clamp(pPoint.z(), p_166074_, p_166077_); if (avec3[0] == null || pPoint.distanceToSqr(d0, d1, d2) < pPoint.distanceToSqr(avec3[0])) { avec3[0] = new Vec3(d0, d1, d2); } }); return Optional.of(avec3[0]); } } /** * Projects" this shape onto the given side. For each box in the shape, if it does not touch the given side, it is * eliminated. Otherwise, the box is extended in the given axis to cover the entire range [0, 1]. */ public VoxelShape getFaceShape(Direction pSide) { if (!this.isEmpty() && this != Shapes.block()) { if (this.faces != null) { VoxelShape voxelshape = this.faces[pSide.ordinal()]; if (voxelshape != null) { return voxelshape; } } else { this.faces = new VoxelShape[6]; } VoxelShape voxelshape1 = this.calculateFace(pSide); this.faces[pSide.ordinal()] = voxelshape1; return voxelshape1; } else { return this; } } private VoxelShape calculateFace(Direction pSide) { Direction.Axis direction$axis = pSide.getAxis(); DoubleList doublelist = this.getCoords(direction$axis); if (doublelist.size() == 2 && DoubleMath.fuzzyEquals(doublelist.getDouble(0), 0.0D, 1.0E-7D) && DoubleMath.fuzzyEquals(doublelist.getDouble(1), 1.0D, 1.0E-7D)) { return this; } else { Direction.AxisDirection direction$axisdirection = pSide.getAxisDirection(); int i = this.findIndex(direction$axis, direction$axisdirection == Direction.AxisDirection.POSITIVE ? 0.9999999D : 1.0E-7D); return new SliceShape(this, direction$axis, i); } } public double collide(Direction.Axis pMovementAxis, AABB pCollisionBox, double pDesiredOffset) { return this.collideX(AxisCycle.between(pMovementAxis, Direction.Axis.X), pCollisionBox, pDesiredOffset); } protected double collideX(AxisCycle pMovementAxis, AABB pCollisionBox, double pDesiredOffset) { if (this.isEmpty()) { return pDesiredOffset; } else if (Math.abs(pDesiredOffset) < 1.0E-7D) { return 0.0D; } else { AxisCycle axiscycle = pMovementAxis.inverse(); Direction.Axis direction$axis = axiscycle.cycle(Direction.Axis.X); Direction.Axis direction$axis1 = axiscycle.cycle(Direction.Axis.Y); Direction.Axis direction$axis2 = axiscycle.cycle(Direction.Axis.Z); double d0 = pCollisionBox.max(direction$axis); double d1 = pCollisionBox.min(direction$axis); int i = this.findIndex(direction$axis, d1 + 1.0E-7D); int j = this.findIndex(direction$axis, d0 - 1.0E-7D); int k = Math.max(0, this.findIndex(direction$axis1, pCollisionBox.min(direction$axis1) + 1.0E-7D)); int l = Math.min(this.shape.getSize(direction$axis1), this.findIndex(direction$axis1, pCollisionBox.max(direction$axis1) - 1.0E-7D) + 1); int i1 = Math.max(0, this.findIndex(direction$axis2, pCollisionBox.min(direction$axis2) + 1.0E-7D)); int j1 = Math.min(this.shape.getSize(direction$axis2), this.findIndex(direction$axis2, pCollisionBox.max(direction$axis2) - 1.0E-7D) + 1); int k1 = this.shape.getSize(direction$axis); if (pDesiredOffset > 0.0D) { for(int l1 = j + 1; l1 < k1; ++l1) { for(int i2 = k; i2 < l; ++i2) { for(int j2 = i1; j2 < j1; ++j2) { if (this.shape.isFullWide(axiscycle, l1, i2, j2)) { double d2 = this.get(direction$axis, l1) - d0; if (d2 >= -1.0E-7D) { pDesiredOffset = Math.min(pDesiredOffset, d2); } return pDesiredOffset; } } } } } else if (pDesiredOffset < 0.0D) { for(int k2 = i - 1; k2 >= 0; --k2) { for(int l2 = k; l2 < l; ++l2) { for(int i3 = i1; i3 < j1; ++i3) { if (this.shape.isFullWide(axiscycle, k2, l2, i3)) { double d3 = this.get(direction$axis, k2 + 1) - d1; if (d3 <= 1.0E-7D) { pDesiredOffset = Math.max(pDesiredOffset, d3); } return pDesiredOffset; } } } } } return pDesiredOffset; } } public String toString() { return this.isEmpty() ? "EMPTY" : "VoxelShape[" + this.bounds() + "]"; } }
45.090164
390
0.636157
5fac88bdf42451eba755fa201c420d96dde1d576
5,453
// Copyright 2022 The Nomulus Authors. 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 google.registry.tools.javascrap; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Sets.difference; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import google.registry.keyring.api.Keyring; import google.registry.model.annotations.DeleteAfterMigration; import google.registry.rde.Ghostryde; import google.registry.tools.Command; import google.registry.tools.params.PathParameter; import google.registry.xjc.XjcXmlTransformer; import google.registry.xjc.rde.XjcRdeDeposit; import google.registry.xjc.rdedomain.XjcRdeDomain; import google.registry.xjc.rderegistrar.XjcRdeRegistrar; import google.registry.xml.XmlException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.inject.Inject; import javax.inject.Provider; import javax.xml.bind.JAXBElement; /** * Command to view and schema validate an XML RDE escrow deposit. * * <p>Note that this command only makes sure that both deposits contain the same registrars and * domains, regardless of the order. To verify that they are indeed equivalent one still needs to * verify internal consistency within each deposit (i.e. to check that all hosts and contacts * referenced by domains are included in the deposit) by calling {@code * google.registry.tools.ValidateEscrowDepositCommand}. */ @DeleteAfterMigration @Parameters(separators = " =", commandDescription = "Compare two XML escrow deposits.") public final class CompareEscrowDepositsCommand implements Command { @Parameter( description = "Two XML escrow deposit files. Each may be a plain XML or an XML GhostRyDE file.", validateWith = PathParameter.InputFile.class) private List<Path> inputs; @Inject Provider<Keyring> keyring; private XjcRdeDeposit getDeposit(Path input) throws IOException, XmlException { InputStream fileStream = Files.newInputStream(input); InputStream inputStream = fileStream; if (input.toString().endsWith(".ghostryde")) { inputStream = Ghostryde.decoder(fileStream, keyring.get().getRdeStagingDecryptionKey()); } return XjcXmlTransformer.unmarshal(XjcRdeDeposit.class, inputStream); } @Override public void run() throws Exception { checkArgument( inputs.size() == 2, "Must supply 2 files to compare, but %s was/were supplied.", inputs.size()); XjcRdeDeposit deposit1 = getDeposit(inputs.get(0)); XjcRdeDeposit deposit2 = getDeposit(inputs.get(1)); compareXmlDeposits(deposit1, deposit2); } private static void process(XjcRdeDeposit deposit, Set<String> domains, Set<String> registrars) { for (JAXBElement<?> item : deposit.getContents().getContents()) { if (XjcRdeDomain.class.isAssignableFrom(item.getDeclaredType())) { XjcRdeDomain domain = (XjcRdeDomain) item.getValue(); domains.add(checkNotNull(domain.getName())); } else if (XjcRdeRegistrar.class.isAssignableFrom(item.getDeclaredType())) { XjcRdeRegistrar registrar = (XjcRdeRegistrar) item.getValue(); registrars.add(checkNotNull(registrar.getId())); } } } private static boolean printUniqueElements( Set<String> set1, Set<String> set2, String element, String deposit) { ImmutableList<String> uniqueElements = ImmutableList.copyOf(difference(set1, set2)); if (!uniqueElements.isEmpty()) { System.out.printf( "%s only in %s:\n%s\n", element, deposit, Joiner.on("\n").join(uniqueElements)); return false; } return true; } private static void compareXmlDeposits(XjcRdeDeposit deposit1, XjcRdeDeposit deposit2) { Set<String> domains1 = new HashSet<>(); Set<String> domains2 = new HashSet<>(); Set<String> registrars1 = new HashSet<>(); Set<String> registrars2 = new HashSet<>(); process(deposit1, domains1, registrars1); process(deposit2, domains2, registrars2); boolean good = true; good &= printUniqueElements(domains1, domains2, "domains", "deposit1"); good &= printUniqueElements(domains2, domains1, "domains", "deposit2"); good &= printUniqueElements(registrars1, registrars2, "registrars", "deposit1"); good &= printUniqueElements(registrars2, registrars1, "registrars", "deposit2"); if (good) { System.out.println( "The two deposits contain the same domains and registrars. " + "You still need to run validate_escrow_deposit to check reference consistency."); } else { System.out.println("The two deposits differ."); } } }
41.625954
99
0.739226
68bf4392d361f8c71c88ee2b3ee142a71248f778
1,265
package com.xiaobei.spring.demo.bean.lifecycle.domain; import org.springframework.beans.factory.DisposableBean; import javax.annotation.PreDestroy; /** * @author <a href="https://github.com/xiaobei-ihmhny">xiaobei-ihmhny</a> * @date 2020/8/12 20:32 */ public class DestructionDomain implements DisposableBean { private Long id; private String name; public Long getId() { return id; } public DestructionDomain setId(Long id) { this.id = id; return this; } public String getName() { return name; } public DestructionDomain setName(String name) { this.name = name; return this; } @Override public String toString() { return "DestructionDomain{" + "id=" + id + ", name='" + name + '\'' + '}'; } @PreDestroy public void preDestroy() { this.name = "16-1"; System.out.println(this); } /** * Bean的销毁回调 * @throws Exception */ @Override public void destroy() throws Exception { this.name = "16-2"; System.out.println(this); } public void initDestroy() { this.name = "16-3"; System.out.println(this); } }
19.765625
73
0.563636
5e0923b7bb3ca6844badf05ce2ef148ee54657b9
1,365
package org.onap.usecaseui.server.service.lcm.domain.aai.bean; /** * Copyright (C) 2020 Huawei, Inc. and others. 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. */ import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class RelationshipDataTest { @Before public void before() throws Exception { } @After public void after() throws Exception { } @Test public void relationshipdatatest() throws Exception { RelationshipData relationshipData = new RelationshipData(); relationshipData.setRelationshipKey("123"); relationshipData.setRelationshipValue("123"); Assert.assertEquals(relationshipData.getRelationshipKey(),"123"); Assert.assertEquals(relationshipData.getRelationshipValue(),"123"); } }
29.673913
75
0.721612
88b4bf6aa97981a6bf79362c64640a7fc5c21b4c
381
package com.dsm.nms.domain.image.exception; import com.dsm.nms.global.error.ErrorCode; import com.dsm.nms.global.error.exception.NmsException; public class ImageNotFoundException extends NmsException { public static NmsException EXCEPTION = new ImageNotFoundException(); private ImageNotFoundException() { super(ErrorCode.IMAGE_NOT_FOUND); } }
23.8125
58
0.750656
c109a21f777f078a756cad448b37a9527bb40ac8
3,978
package com.vladmihalcea.book.hpjp.hibernate.bootstrap; import com.vladmihalcea.book.hpjp.util.DataSourceProxyType; import com.vladmihalcea.book.hpjp.util.PersistenceUnitInfoImpl; import com.vladmihalcea.book.hpjp.util.providers.DataSourceProvider; import com.vladmihalcea.book.hpjp.util.providers.Database; import com.vladmihalcea.book.hpjp.util.providers.MySQLDataSourceProvider; import com.zaxxer.hikari.HikariDataSource; import org.hibernate.SessionFactory; import org.hibernate.cfg.AvailableSettings; import org.hibernate.integrator.spi.Integrator; import org.hibernate.jpa.HibernatePersistenceProvider; import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor; import org.hibernate.jpa.boot.spi.IntegratorProvider; import org.junit.After; import org.junit.Before; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManagerFactory; import javax.persistence.spi.PersistenceUnitInfo; import javax.sql.DataSource; import java.io.Closeable; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; /** * @author Vlad Mihalcea */ public abstract class AbstractJPAProgrammaticBootstrapTest { protected final Logger LOGGER = LoggerFactory.getLogger(getClass()); private EntityManagerFactory emf; public EntityManagerFactory entityManagerFactory() { return emf; } @Before public void init() { PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName()); Map<String, Object> configuration = new HashMap<>(); Integrator integrator = integrator(); if (integrator != null) { configuration.put("hibernate.integrator_provider", (IntegratorProvider) () -> Collections.singletonList(integrator)); } emf = new HibernatePersistenceProvider().createContainerEntityManagerFactory( persistenceUnitInfo, configuration ); } @After public void destroy() { emf.close(); } protected PersistenceUnitInfoImpl persistenceUnitInfo(String name) { PersistenceUnitInfoImpl persistenceUnitInfo = new PersistenceUnitInfoImpl( name, entityClassNames(), properties() ); String[] resources = resources(); if (resources != null) { persistenceUnitInfo.getMappingFileNames().addAll(Arrays.asList(resources)); } return persistenceUnitInfo; } protected abstract Class<?>[] entities(); protected String[] resources() { return null; } protected List<String> entityClassNames() { return Arrays.asList(entities()).stream().map(Class::getName).collect(Collectors.toList()); } protected Properties properties() { Properties properties = new Properties(); properties.put("hibernate.dialect", dataSourceProvider().hibernateDialect()); properties.put("hibernate.hbm2ddl.auto", "create-drop"); DataSource dataSource = newDataSource(); if (dataSource != null) { properties.put("hibernate.connection.datasource", dataSource); } properties.put("hibernate.generate_statistics", Boolean.TRUE.toString()); return properties; } protected DataSource newDataSource() { return proxyDataSource() ? dataSourceProxyType().dataSource(dataSourceProvider().dataSource()) : dataSourceProvider().dataSource(); } protected DataSourceProxyType dataSourceProxyType() { return DataSourceProxyType.DATA_SOURCE_PROXY; } protected boolean proxyDataSource() { return true; } protected DataSourceProvider dataSourceProvider() { return database().dataSourceProvider(); } protected Database database() { return Database.HSQLDB; } protected Integrator integrator() { return null; } }
31.571429
129
0.713424
af33e7dcb9e87a2a71e692b6cf82646506a52f7f
1,994
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.glassfish.eecommon.api; import java.io.IOException; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileSystem; import org.openide.filesystems.FileUtil; /** * Class that allows proper creation of an XML file via FileSystem.AtomicAction. * Otherwise, there is a risk that the wrong data loader will catch the file * after it's created, but before the DOCTYPE or schema header is written. * * @author Peter Williams */ public class XmlFileCreator implements FileSystem.AtomicAction { private final FileObject source; private final FileObject destFolder; private final String name; private final String ext; private FileObject result; public XmlFileCreator(final FileObject source, final FileObject destFolder, final String name, final String ext) { this.source = source; this.destFolder = destFolder; this.name = name; this.ext = ext; this.result = null; } public void run() throws IOException { result = FileUtil.copyFile(source, destFolder, name, ext); } public FileObject getResult() { return result; } }
33.79661
80
0.727182
f8e8296ab8074b0a927262d0156d8e5ce0113095
4,444
package com.egoveris.ffdd.render.zk.form; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zul.Hbox; import org.zkoss.zul.Row; import com.egoveris.ffdd.model.model.VisibilidadComponenteDTO; import com.egoveris.ffdd.render.model.InputComponent; import com.egoveris.ffdd.render.zk.comp.ext.ComplexComponenLayout; import com.egoveris.ffdd.render.zk.constr.DynamicConstraint.ConstraintMember; import com.egoveris.ffdd.render.zk.util.ComponentUtils; public class VisibilityListener implements EventListener { private ConditionImpl condition; private Set<Component> listModifyVis; boolean estadoDefault = true; private VisibilidadComponenteDTO visibilidadComponenteDTO; public VisibilityListener(Component rootComp, VisibilidadComponenteDTO restriccionDTO) { this(rootComp, restriccionDTO, null); } public VisibilityListener(Component rootComp, VisibilidadComponenteDTO visibilidadComponenteDTO, String sufijoRepetitivo) { this.visibilidadComponenteDTO = visibilidadComponenteDTO; listModifyVis = obtenerComponentes(rootComp, visibilidadComponenteDTO.getComponentesOcultos(), sufijoRepetitivo); condition = new ConditionImpl(visibilidadComponenteDTO.getCondiciones(), rootComp, sufijoRepetitivo); } public void addListenerToParticipants() { for (Component part : condition.getParticipantsComps()) { ComponentUtils.addEventListener(part, this); } } public void triggerToParticipants() { for (Component part : condition.getParticipantsComps()) { ComponentUtils.dispararValidacion(part); } } private Set<Component> obtenerComponentes(Component rootComp, List<String> valores, String sufijoRepetitivo) { listModifyVis = new HashSet<Component>(); for (String nombreComp : valores) { listModifyVis.add(ComponentUtils.findComponent(rootComp, nombreComp, sufijoRepetitivo)); } return listModifyVis; } @Override public void onEvent(Event event) throws Exception { boolean cond = condition.validar(); if (cond == estadoDefault) { invertirVisibilidad(); estadoDefault = !estadoDefault; } } private void invertirVisibilidad() { for (Component component : listModifyVis) { component.setVisible(!component.isVisible()); component.invalidate(); // row if(component instanceof Row) { ((ComplexComponenLayout) component .getChildren().get(0).getChildren() .get(0)).setVisible(component.isVisible()); // if(!component.isVisible()) { cleanInputElement(component .getChildren().get(0).getChildren() .get(0), component.isVisible()); // } } if(component instanceof InputComponent) { if(!component.isVisible()) { ((InputComponent) component).setRawValue(null); } // Textbox component.getParent().setVisible(component.isVisible()); // fuerza las validaciones reValidate((InputComponent) component); // Label Component row = component.getParent().getParent(); //TODO condicionar solo cuando sean componentes complejos for (Component componenteRow : row.getChildren()) { if (componenteRow instanceof Hbox) { if(!componenteRow.getNextSibling().isVisible() && !component.isVisible()){ componenteRow.setVisible(false); }else{ componenteRow.setVisible(true); } } } } } } /** * limpia todos los elementos de los input complejos * @param visible * @param complexComponenLayout */ private void cleanInputElement(Component component, boolean visible) { if(component instanceof InputComponent) { component.setVisible(visible); if (!visible) { ((InputComponent) component).setRawValue(null); } } for(Component child : component.getChildren()) { cleanInputElement(child, visible); } } @SuppressWarnings("rawtypes") private void reValidate(InputComponent component) { Iterator iterator = component.getListenerIterator(ComponentUtils.eventForComp(component)); while (iterator.hasNext()) { Object object = (Object) iterator.next(); if (object instanceof ConstraintMember) { ((ConstraintMember) object).reValidate(); } } } public VisibilidadComponenteDTO getVisibilidadComponenteDTO() { return visibilidadComponenteDTO; } }
28.305732
124
0.732448
b815dc97b4c3a479eef96bf0df7a48da730b0764
2,959
/* * Copyright (C) 2016 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.android.dialer.spam; import com.android.dialer.logging.ContactLookupResult; import com.android.dialer.logging.ContactSource; import com.android.dialer.logging.ReportingLocation; /** Default implementation of SpamBindings. */ public class SpamBindingsStub implements SpamBindings { @Override public boolean isSpamEnabled() { return false; } @Override public boolean isSpamNotificationEnabled() { return false; } @Override public boolean isDialogEnabledForSpamNotification() { return false; } @Override public boolean isDialogReportSpamCheckedByDefault() { return false; } @Override public int percentOfSpamNotificationsToShow() { return 0; } @Override public int percentOfNonSpamNotificationsToShow() { return 0; } @Override public void checkSpamStatus(String number, String countryIso, Listener listener) { listener.onComplete(false); } @Override public void checkUserMarkedNonSpamStatus(String number, String countryIso, Listener listener) { listener.onComplete(false); } @Override public void checkUserMarkedSpamStatus(String number, String countryIso, Listener listener) { listener.onComplete(false); } @Override public void checkGlobalSpamListStatus(String number, String countryIso, Listener listener) { listener.onComplete(false); } @Override public boolean checkSpamStatusSynchronous(String number, String countryIso) { return false; } @Override public void reportSpamFromAfterCallNotification( String number, String countryIso, int callType, ReportingLocation.Type from, ContactLookupResult.Type contactLookupResultType) {} @Override public void reportSpamFromCallHistory( String number, String countryIso, int callType, ReportingLocation.Type from, ContactSource.Type contactSourceType) {} @Override public void reportNotSpamFromAfterCallNotification( String number, String countryIso, int callType, ReportingLocation.Type from, ContactLookupResult.Type contactLookupResultType) {} @Override public void reportNotSpamFromCallHistory( String number, String countryIso, int callType, ReportingLocation.Type from, ContactSource.Type contactSourceType) {} }
26.185841
97
0.738763
ac774236a0a65b55139e135cce61950ca8f506d3
1,045
package com.vcg.config; import javax.sql.DataSource; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.TransactionManagementConfigurer; import com.alibaba.druid.pool.DruidDataSource; @Configuration @EnableTransactionManagement public class JdbcConfig implements TransactionManagementConfigurer { @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource dataSource() { return new DruidDataSource(); } @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return new DataSourceTransactionManager(dataSource()); } }
29.027778
83
0.810526
b0d23ce2aa8527bfb43eafec957933ad17c9671c
3,387
package pl.dreamlab.persistentcollectionsbenchmark.list.plan; import cyclops.data.Seq; import io.vavr.collection.Vector; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.organicdesign.fp.collections.PersistentVector; import org.pcollections.ConsPStack; import java.util.ArrayList; import java.util.LinkedList; import static java.util.stream.IntStream.range; @State(Scope.Benchmark) public class ListsInitializingExecutionPlan extends BaseListExecutionPlan { public BaseListExecutionPlan basePlan; @Setup(Level.Invocation) public void setUp(BaseListExecutionPlan plan) { this.basePlan = plan; switch (plan.listCollection) { case JAVA: initJavaLinkedList(plan); break; case JAVA_ARRAY_LIST: initJavaArrayList(plan); break; case VAVR: initVavrList(plan); break; case VAVR_VECTOR: initVavrVector(plan); break; case PCOLLECTIONS: initPcollections(plan); break; case PAGURO: initPaguro(plan); break; case BIFURCAN: initBifurcan(plan); break; case CYCLOPS: initCyclops(plan); break; } } private void initJavaArrayList(BaseListExecutionPlan plan) { plan.javaArrayList = new ArrayList<>(); range(0, plan.numberOfOperations).forEach(i -> plan.javaArrayList.add(plan.random.nextInt())); } private void initVavrVector(BaseListExecutionPlan plan) { plan.vavrVector = Vector.empty(); range(0, plan.numberOfOperations).forEach(i -> plan.vavrVector = plan.vavrVector.append(plan.random.nextInt())); } private void initJavaLinkedList(BaseListExecutionPlan plan) { plan.javaList = new LinkedList<>(); range(0, plan.numberOfOperations).forEach(i -> plan.javaList.add(plan.random.nextInt())); } private void initVavrList(BaseListExecutionPlan plan) { plan.vavrList = io.vavr.collection.List.of(); range(0, plan.numberOfOperations).forEach(i -> plan.vavrList = plan.vavrList.append(plan.random.nextInt())); } private void initPaguro(BaseListExecutionPlan plan) { plan.paguroList = PersistentVector.empty(); range(0, plan.numberOfOperations).forEach(i -> plan.paguroList = plan.paguroList.append(plan.random.nextInt())); } private void initPcollections(BaseListExecutionPlan plan) { plan.pcollectionsList = ConsPStack.empty(); range(0, plan.numberOfOperations).forEach(i -> plan.pcollectionsList = plan.pcollectionsList.plus(plan.random.nextInt())); } private void initBifurcan(BaseListExecutionPlan plan) { plan.bifucanList = io.lacuna.bifurcan.List.of(); range(0, plan.numberOfOperations).forEach(i -> plan.bifucanList = plan.bifucanList.addLast(plan.random.nextInt())); } private void initCyclops(BaseListExecutionPlan plan) { plan.cyclopsList = Seq.empty(); range(0, plan.numberOfOperations).forEach(i -> plan.cyclopsList = plan.cyclopsList.plus(plan.random.nextInt())); } }
35.652632
130
0.658105
c2404f4a639c7666f0064de6b23f81a6856bd6c1
1,999
package com.tm.kafka.connect.rest.interpolator.source; import com.tm.kafka.connect.rest.interpolator.InterpolationContext; import org.junit.Before; import org.junit.Test; import java.net.URL; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; public class PropertyInterpolationSourceTest { PropertyInterpolationSource subject; @Before public void setUp() { subject = new PropertyInterpolationSource(); } @Test public void shouldReturnPropertyTypeWhenRequesting() { assertEquals(InterpolationSourceType.property, subject.getType()); } @Test public void shouldReturnSystemPropertyWhenRequested() { String property = System.getProperties().propertyNames().nextElement().toString(); String value = subject.getValue("system:" + property, mock(InterpolationContext.class)); assertEquals(System.getProperty(property), value); } @Test public void shouldReturnClasspathPropertyWhenRequested() { String value = subject.getValue("test.properties:property.foo", mock(InterpolationContext.class)); assertEquals("bar", value); } @Test public void shouldReturnFilePropertyWhenRequested() { URL url = ClassLoader.getSystemResource("test.properties"); String value = subject.getValue(url.getFile() + ":property.foo", mock(InterpolationContext.class)); assertEquals("bar", value); } @Test public void shouldReturnNullWhenNoPropertyFound() { String value = subject.getValue("test.properties:does.not.exist", mock(InterpolationContext.class)); assertEquals(null, value); } @Test public void shouldReturnNullWhenNoPropertiesFileFound() { String value = subject.getValue("no-such-file.properties:property.foo", mock(InterpolationContext.class)); assertEquals(null, value); } @Test public void shouldReturnNullWhenPropertyDefinedIncorrectly() { String value = subject.getValue("some-property", mock(InterpolationContext.class)); assertEquals(null, value); } }
30.753846
110
0.757379
c2c1c32222c3a025ce41609e9d6748fb3cb4a892
15,587
package rsc.publisher; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.*; import org.junit.*; import org.reactivestreams.Publisher; import rsc.processor.UnicastProcessor; import rsc.test.TestSubscriber; import rsc.util.*; public class PublisherZipTest { @Test public void constructors() { ConstructorTestBuilder ctb = new ConstructorTestBuilder(PublisherZip.class); ctb.addRef("sources", new Publisher[0]); ctb.addRef("p1", Px.never()); ctb.addRef("p2", Px.never()); ctb.addRef("sourcesIterable", Collections.emptyList()); ctb.addRef("queueSupplier", (Supplier<Queue<Object>>)() -> new ConcurrentLinkedQueue<>()); ctb.addInt("prefetch", 1, Integer.MAX_VALUE); ctb.addRef("zipper", (Function<Object[], Object>)v -> v); ctb.addRef("zipper2", (BiFunction<Object, Object, Object>)(v1, v2) -> v1); ctb.test(); } @Test public void sameLength() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source = Px.fromIterable(Arrays.asList(1, 2)); source.zipWith(source, (a, b) -> a + b).subscribe(ts); ts.assertValues(2, 4) .assertNoError() .assertComplete(); } @Test public void sameLengthOptimized() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source = Px.range(1, 2); source.zipWith(source, (a, b) -> a + b).subscribe(ts); ts.assertValues(2, 4) .assertNoError() .assertComplete(); } @Test public void sameLengthBackpressured() { TestSubscriber<Integer> ts = new TestSubscriber<>(0); Px<Integer> source = Px.fromIterable(Arrays.asList(1, 2)); source.zipWith(source, (a, b) -> a + b).subscribe(ts); ts.assertNoValues() .assertNoError() .assertNotComplete(); ts.request(1); ts.assertValue(2) .assertNoError() .assertNotComplete(); ts.request(2); ts.assertValues(2, 4) .assertNoError() .assertComplete(); } @Test public void sameLengthOptimizedBackpressured() { TestSubscriber<Integer> ts = new TestSubscriber<>(0); Px<Integer> source = Px.range(1, 2); source.zipWith(source, (a, b) -> a + b).subscribe(ts); ts.assertNoValues() .assertNoError() .assertNotComplete(); ts.request(1); ts.assertValue(2) .assertNoError() .assertNotComplete(); ts.request(2); ts.assertValues(2, 4) .assertNoError() .assertComplete(); } @Test public void differentLength() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source1 = Px.fromIterable(Arrays.asList(1, 2)); Px<Integer> source2 = Px.fromIterable(Arrays.asList(1, 2, 3)); source1.zipWith(source2, (a, b) -> a + b).subscribe(ts); ts.assertValues(2, 4) .assertNoError() .assertComplete(); } @Test public void differentLengthOpt() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source1 = Px.range(1, 2); Px<Integer> source2 = Px.range(1, 3); source1.zipWith(source2, (a, b) -> a + b).subscribe(ts); ts.assertValues(2, 4) .assertNoError() .assertComplete(); } @Test public void emptyNonEmpty() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source1 = Px.fromIterable(Collections.emptyList()); Px<Integer> source2 = Px.fromIterable(Arrays.asList(1, 2, 3)); source1.zipWith(source2, (a, b) -> a + b).subscribe(ts); ts.assertNoValues() .assertNoError() .assertComplete(); } @Test public void nonEmptyAndEmpty() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source1 = Px.fromIterable(Arrays.asList(1, 2, 3)); Px<Integer> source2 = Px.fromIterable(Collections.emptyList()); source1.zipWith(source2, (a, b) -> a + b).subscribe(ts); ts.assertNoValues() .assertNoError() .assertComplete(); } @Test public void scalarNonScalar() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source1 = Px.just(1); Px<Integer> source2 = Px.fromIterable(Arrays.asList(1, 2, 3)); source1.zipWith(source2, (a, b) -> a + b).subscribe(ts); ts.assertValues(2) .assertNoError() .assertComplete(); } @Test public void scalarNonScalarBackpressured() { TestSubscriber<Integer> ts = new TestSubscriber<>(0); Px<Integer> source1 = Px.just(1); Px<Integer> source2 = Px.fromIterable(Arrays.asList(1, 2, 3)); source1.zipWith(source2, (a, b) -> a + b).subscribe(ts); ts.assertNoValues() .assertNoError() .assertNotComplete(); ts.request(1); ts.assertValues(2) .assertNoError() .assertComplete(); } @Test public void scalarNonScalarOpt() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source1 = Px.just(1); Px<Integer> source2 = Px.range(1, 3); source1.zipWith(source2, (a, b) -> a + b).subscribe(ts); ts.assertValues(2) .assertNoError() .assertComplete(); } @Test public void scalarScalar() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source1 = Px.just(1); Px<Integer> source2 = Px.just(1); source1.zipWith(source2, (a, b) -> a + b).subscribe(ts); ts.assertValues(2) .assertNoError() .assertComplete(); } @Test public void emptyScalar() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source1 = Px.empty(); Px<Integer> source2 = Px.just(1); source1.zipWith(source2, (a, b) -> a + b).subscribe(ts); ts.assertNoValues() .assertNoError() .assertComplete(); } @Test public void sameLengthIterable() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source = Px.fromIterable(Arrays.asList(1, 2)); Px.zipIterable(Arrays.asList(source, source), a -> (Integer)a[0] + (Integer)a[1]).subscribe(ts); ts.assertValues(2, 4) .assertNoError() .assertComplete(); } @Test public void sameLengthOptimizedIterable() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source = Px.range(1, 2); Px.zipIterable(Arrays.asList(source, source), a -> (Integer)a[0] + (Integer)a[1]).subscribe(ts); ts.assertValues(2, 4) .assertNoError() .assertComplete(); } @Test public void sameLengthBackpressuredIterable() { TestSubscriber<Integer> ts = new TestSubscriber<>(0); Px<Integer> source = Px.fromIterable(Arrays.asList(1, 2)); Px.zipIterable(Arrays.asList(source, source), a -> (Integer)a[0] + (Integer)a[1]).subscribe(ts); ts.assertNoValues() .assertNoError() .assertNotComplete(); ts.request(1); ts.assertValue(2) .assertNoError() .assertNotComplete(); ts.request(2); ts.assertValues(2, 4) .assertNoError() .assertComplete(); } @Test public void sameLengthOptimizedBackpressuredIterable() { TestSubscriber<Integer> ts = new TestSubscriber<>(0); Px<Integer> source = Px.range(1, 2); Px.zipIterable(Arrays.asList(source, source), a -> (Integer)a[0] + (Integer)a[1]).subscribe(ts); ts.assertNoValues() .assertNoError() .assertNotComplete(); ts.request(1); ts.assertValue(2) .assertNoError() .assertNotComplete(); ts.request(2); ts.assertValues(2, 4) .assertNoError() .assertComplete(); } @Test public void differentLengthIterable() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source1 = Px.fromIterable(Arrays.asList(1, 2)); Px<Integer> source2 = Px.fromIterable(Arrays.asList(1, 2, 3)); Px.zipIterable(Arrays.asList(source1, source2), a -> (Integer)a[0] + (Integer)a[1]).subscribe(ts); ts.assertValues(2, 4) .assertNoError() .assertComplete(); } @Test public void differentLengthOptIterable() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source1 = Px.range(1, 2); Px<Integer> source2 = Px.range(1, 3); Px.zipIterable(Arrays.asList(source1, source2), a -> (Integer)a[0] + (Integer)a[1]).subscribe(ts); ts.assertValues(2, 4) .assertNoError() .assertComplete(); } @Test public void emptyNonEmptyIterable() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source1 = Px.fromIterable(Collections.emptyList()); Px<Integer> source2 = Px.fromIterable(Arrays.asList(1, 2, 3)); Px.zipIterable(Arrays.asList(source1, source2), a -> (Integer)a[0] + (Integer)a[1]).subscribe(ts); ts.assertNoValues() .assertNoError() .assertComplete(); } @Test public void nonEmptyAndEmptyIterable() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source1 = Px.fromIterable(Arrays.asList(1, 2, 3)); Px<Integer> source2 = Px.fromIterable(Collections.emptyList()); Px.zipIterable(Arrays.asList(source1, source2), a -> (Integer)a[0] + (Integer)a[1]).subscribe(ts); ts.assertNoValues() .assertNoError() .assertComplete(); } @Test public void scalarNonScalarIterable() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source1 = Px.just(1); Px<Integer> source2 = Px.fromIterable(Arrays.asList(1, 2, 3)); Px.zipIterable(Arrays.asList(source1, source2), a -> (Integer)a[0] + (Integer)a[1]).subscribe(ts); ts.assertValues(2) .assertNoError() .assertComplete(); } @Test public void scalarNonScalarBackpressuredIterable() { TestSubscriber<Integer> ts = new TestSubscriber<>(0); Px<Integer> source1 = Px.just(1); Px<Integer> source2 = Px.fromIterable(Arrays.asList(1, 2, 3)); Px.zipIterable(Arrays.asList(source1, source2), a -> (Integer)a[0] + (Integer)a[1]).subscribe(ts); ts.assertNoValues() .assertNoError() .assertNotComplete(); ts.request(1); ts.assertValues(2) .assertNoError() .assertComplete(); } @Test public void scalarNonScalarOptIterable() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source1 = Px.just(1); Px<Integer> source2 = Px.range(1, 3); Px.zipIterable(Arrays.asList(source1, source2), a -> (Integer)a[0] + (Integer)a[1]).subscribe(ts); ts.assertValues(2) .assertNoError() .assertComplete(); } @Test public void scalarScalarIterable() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source1 = Px.just(1); Px<Integer> source2 = Px.just(1); Px.zipIterable(Arrays.asList(source1, source2), a -> (Integer)a[0] + (Integer)a[1]).subscribe(ts); ts.assertValues(2) .assertNoError() .assertComplete(); } @Test public void emptyScalarITerable() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px<Integer> source1 = Px.empty(); Px<Integer> source2 = Px.just(1); Px.zipIterable(Arrays.asList(source1, source2), a -> (Integer)a[0] + (Integer)a[1]).subscribe(ts); ts.assertNoValues() .assertNoError() .assertComplete(); } @Test public void syncFusionMapToNull() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px.range(1, 10) .<Integer, Integer>zipWith(Px.range(1, 2).map(v -> v == 2 ? null : v), (a, b) -> a + b).subscribe(ts); ts.assertValue(2) .assertError(NullPointerException.class) .assertNotComplete(); } @Test public void syncFusionMapToNullFilter() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Px.range(1, 10) .<Integer, Integer>zipWith(Px.range(1, 2).map(v -> v == 2 ? null : v).filter(v -> true), (a, b) -> a + b).subscribe(ts); ts.assertValue(2) .assertError(NullPointerException.class) .assertNotComplete(); } @Test public void asyncFusionMapToNull() { TestSubscriber<Integer> ts = new TestSubscriber<>(); UnicastProcessor<Integer> up = new UnicastProcessor<>(new SpscArrayQueue<>(2)); up.onNext(1); up.onNext(2); up.onComplete(); Px.range(1, 10) .<Integer, Integer>zipWith(up.map(v -> v == 2 ? null : v), (a, b) -> a + b).subscribe(ts); ts.assertValue(2) .assertError(NullPointerException.class) .assertNotComplete(); } @Test public void asyncFusionMapToNullFilter() { TestSubscriber<Integer> ts = new TestSubscriber<>(); UnicastProcessor<Integer> up = new UnicastProcessor<>(new SpscArrayQueue<>(2)); up.onNext(1); up.onNext(2); up.onComplete(); Px.range(1, 10) .<Integer, Integer>zipWith(up.map(v -> v == 2 ? null : v).filter(v -> true), (a, b) -> a + b).subscribe(ts); ts.assertValue(2) .assertError(NullPointerException.class) .assertNotComplete(); } @Test public void isEmptyFalseButPollFilters() { TestSubscriber<Object[]> ts = new TestSubscriber<>(0); Px<Integer> source = Px.fromArray(1, 2, 3).filter(v -> v == 2); Px.zip(a -> a, 1, source, source).subscribe(ts); ts.request(1); ts.assertValueCount(1) .assertNoError() .assertComplete(); Assert.assertArrayEquals(new Object[] { 2, 2 }, ts.values().get(0)); } @Test public void zipWithNoStackoverflow() { int n = 5000; TestSubscriber<Integer> ts = new TestSubscriber<>(); BiFunction<Integer, Integer, Integer> f = (a, b) -> a + b; Px<Integer> source = Px.just(1); Px<Integer> result = source; for (int i = 0; i < n; i++) { result = result.zipWith(source, f); } result.subscribe(ts); ts.assertValue(n + 1) .assertNoError() .assertComplete(); } }
29.134579
128
0.554693
020ec07a483445fae3554ec745b7fb7521379e6e
1,930
package com.disconf.web.service.impl; import com.disconf.core.common.model.Response; import com.disconf.web.common.SearchResult; import com.disconf.web.entity.ConfigEntityHistory; import com.disconf.web.mapper.ConfigEntityHistoryMapper; import com.disconf.web.search.AppSearch; import com.disconf.web.service.IAppService; import com.disconf.web.service.IConfigHistoryService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author lzj * @date 2018/1/5 */ @Service public class ConfigHistoryServiceImpl implements IConfigHistoryService { private static final Logger logger = LoggerFactory.getLogger(ConfigHistoryServiceImpl.class); @Autowired private ConfigEntityHistoryMapper configHistoryMapper; @Override public List<ConfigEntityHistory> selectAll() { return configHistoryMapper.selectAll(); } @Override public Response insert(ConfigEntityHistory configEntityHistory) { configHistoryMapper.insert(configEntityHistory); return Response.success(); } @Override public Response delete(Long id) { configHistoryMapper.delete(id); return Response.success(); } @Override public SearchResult<ConfigEntityHistory> selectByParam(ConfigEntityHistory ConfigEntityHistory) { List<ConfigEntityHistory> rows = configHistoryMapper.selectByParam(ConfigEntityHistory); int total = configHistoryMapper.selectCountByParam(ConfigEntityHistory); return new SearchResult<>(total, rows); } @Override public ConfigEntityHistory selectById(Long id) { return configHistoryMapper.selectById(id); } @Override public Response update(ConfigEntityHistory app) { configHistoryMapper.update(app); return Response.success(); } }
30.15625
101
0.755959
8a0bce1efb6aa1cf0ca41e49d8b029ae1ea38aa6
309
package de.baltic_online.base.sql; public class SimpleQuery extends AbstractQuery { public SimpleQuery(TableCache cache) { super( cache ); } public SimpleQuery(TableCache cache,TableAttribute[] ta) { super( cache, ta ); } public boolean find(Object toFind) { return true; } }
15.45
58
0.686084
fd4b5e7811104765609c4f95779721ffb22eea35
3,195
package org.goodiemania.melinoe.framework.drivers.web; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.time.Duration; import java.util.Objects; import java.util.Optional; import java.util.UUID; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.goodiemania.melinoe.framework.api.exceptions.MelinoeException; import org.goodiemania.melinoe.framework.api.web.WebDriver; import org.goodiemania.melinoe.framework.config.Configuration; import org.goodiemania.melinoe.framework.drivers.web.browsers.DriverChooser; import org.goodiemania.melinoe.framework.drivers.web.browsers.FirefoxHeadless; import org.goodiemania.melinoe.framework.session.InternalSession; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.ui.WebDriverWait; public class RawWebDriver { private static final String RELOAD_FLAG_VALUE = "reloadFlag"; private final InternalSession internalSession; private RemoteWebDriver remoteWebDriver; private ScreenshotTaker screenshotTaker; private WebDriverWait webDriverWait; private LocalStorage localStorage; private final WebDriverImpl webDriver; private String reloadFlag = RELOAD_FLAG_VALUE; public RawWebDriver(final InternalSession internalSession) { this.internalSession = internalSession; this.webDriver = new WebDriverImpl(internalSession); } public RemoteWebDriver getRemoteWebDriver() { if (remoteWebDriver == null) { generate(); } return remoteWebDriver; } public WebDriver getWebDriver() { return webDriver; } public ScreenshotTaker getScreenshotTaker() { return screenshotTaker; } public WebDriverWait getWebDriverWait() { return webDriverWait; } public boolean hasPageBeenChecked() { if (remoteWebDriver == null) { generate(); } return StringUtils.equals(localStorage.get(reloadFlag), RELOAD_FLAG_VALUE); } public void markPageChecked() { if (remoteWebDriver == null) { generate(); } reloadFlag = UUID.randomUUID().toString(); localStorage.put(reloadFlag, RELOAD_FLAG_VALUE); } private void generate() { final String browserChoice = Configuration.BROWSER.get(); this.remoteWebDriver = DriverChooser.chooseDriver(browserChoice) .apply(Configuration.BROWSER_EXE_LOCATION.get()); this.remoteWebDriver.manage().window().maximize(); screenshotTaker = new ScreenshotTaker(internalSession); webDriverWait = new WebDriverWait(remoteWebDriver, Duration.ofSeconds(60)); localStorage = new LocalStorage(this); internalSession.getMetaSession().addDriver(webDriver); } public void close() { if (remoteWebDriver != null) { if (!hasPageBeenChecked()) { remoteWebDriver.quit(); throw new MelinoeException("You must check your page before you close the Web Driver"); } remoteWebDriver.quit(); remoteWebDriver = null; } } }
31.019417
103
0.703912
4a4c1a60e35a9b3698c1de588b620074af32c51d
325
package com.akexorcist.knoxactivator.event; /** * Created by Akexorcist on 4/21/2016 AD. */ public class LicenseActivationFailedEvent { int errorType; public LicenseActivationFailedEvent(int errorType) { this.errorType = errorType; } public int getErrorType() { return errorType; } }
19.117647
56
0.686154
5aedc8d5c514656095e31fe7bcb116b0511dccf0
7,418
package com.paragon464.gameserver.model.content; import com.paragon464.gameserver.model.entity.mob.player.Player; import com.paragon464.gameserver.model.entity.mob.player.container.impl.BankTransfer; public class BankPins { static final String[] MESSAGES = {"Now click the SECOND digit.", "Time for the THIRD digit.", "Finally, the FOURTH digit.", "Finally, the FOURTH digit."}; private static final int ENTER_PIN_INTERFACE = 13; private static final int PIN_SETTINGS_INTERFACE = 14; public boolean enteredPin = false; private Player player; private int nextIndex = 0; private boolean changingPin, changingPinCheck; private int[] attemptedPin = new int[4]; private int[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; public BankPins(Player player) { this.player = player; } public void open() { openPinSettings(); } private void openPinSettings() { player.getFrames().sendInterfaceVisibility(14, 220, false); player.getFrames().sendComponentPosition(14, 225, 3000, 3000);//yes, I really want to do that. player.getFrames().sendComponentPosition(14, 230, 3000, 3000);//No, forget I asked. player.getFrames().sendComponentPosition(14, 220, 3000, 3000);//Big black square with red bars player.getFrames().sendComponentPosition(14, 133, 3000, 3000);//delete your pin player.getFrames().sendComponentPosition(14, 132, 3000, 3000);//change your pin player.getFrames().sendComponentPosition(14, 134, 3000, 3000);//change your recov delay - top player.getFrames().sendComponentPosition(14, 135, 3000, 3000);//Cancel the pin that's pending player.getInterfaceSettings().openInterface(PIN_SETTINGS_INTERFACE); } public void handle(int interfaceId, int buttonId) { switch (interfaceId) { case PIN_SETTINGS_INTERFACE: switch (buttonId) { case 130:// Set a pin changingPin = true; openEnterPin(); break; } break; case ENTER_PIN_INTERFACE: if (buttonId >= 100 && buttonId <= 110) { int index = buttonId - 100; if (index == 0 && buttonId == 109) { index = 9; } int number = numbers[index]; if (nextIndex < 3) { int child = 140 + nextIndex; player.getFrames().modifyText("*", 13, child); nextIndex++; attemptedPin[nextIndex] = number; String type = nextIndex == 1 ? "2nd" : nextIndex == 2 ? "3rd" : nextIndex == 3 ? "4th" : ""; player.getFrames().modifyText("Click the " + type + " digit...", 13, 151); } else { nextIndex = 0; if (changingPin && !changingPinCheck) { if (player.getAttributes().getInt("bank_pin_hash") == -1) {//player has no pin. changingPinCheck = true; player.getFrames().sendMessage("Please set your new PIN."); openEnterPin(); return; } boolean match = true; for (int i = 0; i < attemptedPin.length; i++) { int pin = getPinForIndex(i); if (attemptedPin[i] != pin) { match = false; break; } } if (!match) { player.getFrames().sendMessage("The pin you entered was incorrect."); player.getInterfaceSettings().closeInterfaces(false); return; } else { changingPinCheck = true; player.getFrames().sendMessage("Please set your new PIN."); openEnterPin(); } return; } if (player.getAttributes().getInt("bank_pin_hash") == -1 || (changingPin && changingPinCheck)) {//we set a new pin player.getAttributes().set("bank_pin_hash", attemptedPin[0] + (attemptedPin[1] << 8) + (attemptedPin[2] << 16) + (attemptedPin[3] << 24)); enteredPin = true; changingPinCheck = false; changingPin = false; player.getFrames().sendMessage("Your pin is now set."); player.getVariables().setTransferContainer(new BankTransfer(player)); } else {//we confirm with current pin boolean match = true; for (int i = 0; i < attemptedPin.length; i++) { int pin = getPinForIndex(i); if (attemptedPin[i] != pin) { match = false; break; } } if (!match) { player.getFrames().sendMessage("The pin you entered was incorrect."); player.getInterfaceSettings().closeInterfaces(false); return; } else { enteredPin = true; player.getFrames().sendMessage("You successfully entered your bank pin."); player.getVariables().setTransferContainer(new BankTransfer(player)); } } } } else if (buttonId == 149) { player.getInterfaceSettings().closeInterfaces(false); } break; } } public void openEnterPin() { player.getInterfaceSettings().openInterface(ENTER_PIN_INTERFACE); player.getFrames().modifyText("Click the 1st digit...", 13, 151); player.getFrames().modifyText("", 13, 150); for (int i = 0; i < 3; i++) { player.getFrames().modifyText("?", 13, 140 + i); } scramble(); } public int getPinForIndex(int index) { int packed = player.getAttributes().getInt("bank_pin_hash"); int pin = -1; switch (index) { case 0: pin = packed & 0xff; break; case 1: pin = packed >> 8 & 0xff; break; case 2: pin = packed >> 16 & 0xff; break; case 3: pin = packed >> 24 & 0xff; break; } return pin; } public void scramble() { for (int i = 0; i < 10; i++) { numbers[i] = i; player.getFrames().modifyText("" + i, 13, 110 + i); } } }
46.074534
166
0.460097
6725de935cc2f374a011aa262d80ecb3ed97e442
1,662
package com.mapswithme.maps.search; import android.view.View; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import com.mapswithme.maps.R; import com.mapswithme.util.UiUtils; public class SearchFilterController { @NonNull private final View mFrame; @NonNull private final TextView mShowOnMap; @NonNull private final View mDivider; @Nullable private final FilterListener mFilterListener; interface FilterListener { void onShowOnMapClick(); } public SearchFilterController(@NonNull View frame, @Nullable FilterListener listener, @StringRes int populateButtonText) { mFrame = frame; mFilterListener = listener; mShowOnMap = mFrame.findViewById(R.id.show_on_map); mShowOnMap.setText(populateButtonText); mDivider = mFrame.findViewById(R.id.divider); initListeners(); } public void show(boolean show) { UiUtils.showIf(show, mFrame); showPopulateButton(true); } void showPopulateButton(boolean show) { UiUtils.showIf(show, mShowOnMap); } void showDivider(boolean show) { UiUtils.showIf(show, mDivider); } private void initListeners() { mShowOnMap.setOnClickListener(v -> { if (mFilterListener != null) mFilterListener.onShowOnMapClick(); }); } public static class DefaultFilterListener implements FilterListener { @Override public void onShowOnMapClick() { } } }
22.16
87
0.659446
3bccf7eaff50b439f0a04c94dd1ff5e29d8d916e
2,050
/* * Copyright 2018 Nextworks s.r.l. * * 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 it.nextworks.nfvmano.libs.ifa.catalogues.interfaces.messages; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonInclude; import it.nextworks.nfvmano.libs.ifa.common.InterfaceMessage; import it.nextworks.nfvmano.libs.ifa.common.exceptions.MalformattedElementException; import it.nextworks.nfvmano.libs.ifa.descriptors.nsd.Nsd; /** * Request to on-board an NSD in the NFVO. * * REF IFA 013 v2.3.1 - 7.2.2 * * @author nextworks * */ public class OnboardNsdRequest implements InterfaceMessage { private Nsd nsd; @JsonInclude(JsonInclude.Include.NON_EMPTY) private Map<String, String> userDefinedData = new HashMap<>(); public OnboardNsdRequest() { // TODO Auto-generated constructor stub } /** * constructor * * @param nsd NSD to be on-boarded. * @param userDefinedData User defined data for the NSD. */ public OnboardNsdRequest(Nsd nsd, Map<String, String> userDefinedData) { this.nsd = nsd; if (userDefinedData != null) this.userDefinedData = userDefinedData; } /** * @return the nsd */ public Nsd getNsd() { return nsd; } /** * @return the userDefinedData */ public Map<String, String> getUserDefinedData() { return userDefinedData; } @Override public void isValid() throws MalformattedElementException { if (nsd == null) { throw new MalformattedElementException("On board NSD request without NSD"); } else nsd.isValid(); } }
24.698795
84
0.730244
0d2c9d4fdacf55cf86f8c2eb52d9065beaa7ca13
1,113
package cucumber.runner; import cucumber.runtime.Backend; import cucumber.runtime.Glue; import cucumber.runtime.RuntimeOptions; import cucumber.runtime.snippets.FunctionNameGenerator; import gherkin.pickles.PickleStep; import java.util.Collections; import java.util.List; import static java.util.Collections.emptyList; public class TestRunnerSupplier implements Backend, RunnerSupplier { private final EventBus bus; private final RuntimeOptions runtimeOptions; protected TestRunnerSupplier(EventBus bus, RuntimeOptions runtimeOptions) { this.bus = bus; this.runtimeOptions = runtimeOptions; } @Override public void loadGlue(Glue glue, List<String> gluePaths) { } @Override public void buildWorld() { } @Override public void disposeWorld() { } @Override public List<String> getSnippet(PickleStep step, String keyword, FunctionNameGenerator functionNameGenerator) { return emptyList(); } @Override public Runner get() { return new Runner(bus, Collections.singleton(this), runtimeOptions); } }
22.714286
114
0.728661
8c2b71b647f114025e645950855db6935ae21900
115
package io.github.educontessi.domain.service.validator; public interface Validator { public void validate(); }
14.375
55
0.782609
781553c8c31086caeadada4574a36de825a68eec
3,793
package us.codecraft.webmagic.proxy; import lombok.extern.slf4j.Slf4j; import us.codecraft.webmagic.Task; import java.util.Comparator; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicReference; /** * @author yaoqiang * 可刷新的代理提供商抽象实现 */ @Slf4j public abstract class AbstractRefreshableProxyProvider implements RefreshableProxyProvider { private final AtomicReference<FutureTask<Proxy>> usedProxyCache = new AtomicReference<>(); private final PriorityBlockingQueue<ExpirableProxy> ipQueue = new PriorityBlockingQueue<>(1000, Comparator.comparing(ExpirableProxy::getExpireTime)); protected void doPut(ExpirableProxy expirableProxy) { ipQueue.put(expirableProxy); } protected int hostSize() { return ipQueue.size(); } @Override public void refreshProxy(Task task, Proxy proxy) { if (proxy != null) { FutureTask<Proxy> proxyFutureTask = usedProxyCache.get(); Proxy currentProxy = getCurrentProxy(task); // 如果在出错到这里的过程中,usedProxyCache被更新过,proxy 就不可能相等,如果依然相等,说明没有更新过 // 可能没有使用代理的情况 if (proxy.equals(currentProxy)) { // 如果此时依然没有更新过,就设置为空 usedProxyCache.compareAndSet(proxyFutureTask, null); } } } @Override public Proxy getCurrentProxy(Task task) { FutureTask<Proxy> cache = usedProxyCache.get(); Proxy currentProxy = null; try { if (cache != null) currentProxy = cache.get(5, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); log.error(e.getMessage(), e); Thread.currentThread().interrupt(); } catch (ExecutionException e) { e.printStackTrace(); log.error(e.getCause().getMessage(), e); } catch (TimeoutException e) { log.error(e.getMessage(), e); e.printStackTrace(); } return currentProxy; } private FutureTask<Proxy> buildCacheTask() { return new FutureTask<>(this::doGet); } /** * 特别注意,防止活锁,集cache中总是抛出异常,那么将无限循环,无限报错 * * @param task 下载任务 * @return 返回代理 */ @Override public Proxy getProxy(Task task) { while (!Thread.currentThread().isInterrupted()) { FutureTask<Proxy> cache = usedProxyCache.get(); if (cache == null) { FutureTask<Proxy> futureTask = buildCacheTask(); if (usedProxyCache.compareAndSet(null, futureTask)) { cache = futureTask; futureTask.run(); } else { // 交换失败,需要更新到最新数据 cache = usedProxyCache.get(); } } try { if (cache != null) { ExpirableProxy proxy = (ExpirableProxy) cache.get(5, TimeUnit.SECONDS); if (!proxy.isExpire()) return proxy; } usedProxyCache.compareAndSet(cache, null); } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.error(e.getMessage(), e); usedProxyCache.compareAndSet(cache, null); } catch (ExecutionException e) { log.error(e.getMessage(), e); usedProxyCache.compareAndSet(cache, null); } catch (TimeoutException e) { log.error(e.getMessage(), e); } } return null; } private Proxy doGet() throws InterruptedException { ExpirableProxy proxy; do { proxy = ipQueue.take(); } while (proxy.isExpire()); return proxy; } }
30.58871
153
0.568679
b14bc922eb63daeec9debd6569c41db2ebcd7d82
4,131
package com.example.pickyourcollege; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class CollegeActivity extends AppCompatActivity { private Button btnCancel; private Button btnSave; private EditText txtName; private EditText txtMajor; private EditText txtLocation; private EditText txtRank; private EditText txtLivingCost; private EditText txtTuition; private EditText txtScholarship; private EditText txtDistance; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_college); Intent intent = getIntent(); int intCollegeIdx = intent.getIntExtra("intCollegeIdx", 0); // bind views btnCancel = (Button) findViewById(R.id.btnCancel); btnSave = (Button) findViewById(R.id.btnSave); txtName = (EditText) findViewById(R.id.txtName); txtMajor = (EditText) findViewById(R.id.txtMajor); txtLocation = (EditText) findViewById(R.id.txtLocation); txtRank = (EditText) findViewById(R.id.txtRank); txtLivingCost = (EditText) findViewById(R.id.txtLivingCost); txtTuition = (EditText) findViewById(R.id.txtTuition); txtScholarship = (EditText) findViewById(R.id.txtScholarship); txtDistance = (EditText) findViewById(R.id.txtDistance); // set up buttons btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(CollegeActivity.this, MainActivity.class)); } }); btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (intCollegeIdx >= 0 && intCollegeIdx < MainActivity.intMaxNumOfOffers) { // 0~ for offers, save info MainActivity.colleges[intCollegeIdx].name = txtName.getText().toString(); MainActivity.colleges[intCollegeIdx].major = txtMajor.getText().toString(); MainActivity.colleges[intCollegeIdx].location = txtLocation.getText().toString(); MainActivity.colleges[intCollegeIdx].rank = Integer.parseInt(txtRank.getText().toString()); MainActivity.colleges[intCollegeIdx].livingCost = Integer.parseInt(txtLivingCost.getText().toString()); MainActivity.colleges[intCollegeIdx].tuition = Integer.parseInt(txtTuition.getText().toString()); MainActivity.colleges[intCollegeIdx].scholarship = Integer.parseInt(txtScholarship.getText().toString()); MainActivity.colleges[intCollegeIdx].distance = Integer.parseInt(txtDistance.getText().toString()); MainActivity.colleges[intCollegeIdx].computeScore(MainActivity.weights); // update the score of this college } startActivity(new Intent(CollegeActivity.this, MainActivity.class)); } }); // display current info of this college if (intCollegeIdx >= 0 && intCollegeIdx < MainActivity.intMaxNumOfOffers) { // 0~ for offers txtName.setText(MainActivity.colleges[intCollegeIdx].name); txtMajor.setText(MainActivity.colleges[intCollegeIdx].major); txtLocation.setText(MainActivity.colleges[intCollegeIdx].location); txtRank.setText(String.valueOf(MainActivity.colleges[intCollegeIdx].rank)); txtLivingCost.setText(String.valueOf(MainActivity.colleges[intCollegeIdx].livingCost)); txtTuition.setText(String.valueOf(MainActivity.colleges[intCollegeIdx].tuition)); txtScholarship.setText(String.valueOf(MainActivity.colleges[intCollegeIdx].scholarship)); txtDistance.setText(String.valueOf(MainActivity.colleges[intCollegeIdx].distance)); } } }
47.482759
128
0.671992
319941da8c2d27ef52bf2edca40570a969df3de2
2,321
package org.ovirt.engine.api.restapi.types.externalhostproviders; import static org.ovirt.engine.api.restapi.utils.HexUtils.string2hex; import java.util.Date; import org.ovirt.engine.api.model.KatelloErratum; import org.ovirt.engine.api.restapi.types.AbstractInvertibleMappingTest; import org.ovirt.engine.api.restapi.types.DateMapper; import org.ovirt.engine.core.common.businessentities.Erratum; import org.ovirt.engine.core.common.businessentities.Erratum.ErrataSeverity; import org.ovirt.engine.core.common.businessentities.Erratum.ErrataType; public class ErratumMapperTest extends AbstractInvertibleMappingTest<KatelloErratum, Erratum, Erratum> { private static final Date DATE = new Date(); public ErratumMapperTest() { super(KatelloErratum.class, Erratum.class, Erratum.class); } @Override protected void verify(KatelloErratum model, KatelloErratum transform) { assertEquals(model.getId(), transform.getId()); assertEquals(model.getName(), transform.getName()); assertEquals(model.getTitle(), transform.getTitle()); assertEquals(model.getSummary(), transform.getSummary()); assertEquals(model.getSolution(), transform.getSolution()); assertEquals(model.getDescription(), transform.getDescription()); assertEquals(model.getIssued(), transform.getIssued()); assertEquals(model.getSeverity(), transform.getSeverity()); assertEquals(model.getType(), transform.getType()); assertNotNull(model.getPackages()); assertNotNull(transform.getPackages()); assertEquals(model.getPackages().getPackages().size(), transform.getPackages().getPackages().size()); for (int i = 0; i < model.getPackages().getPackages().size(); i++) { assertEquals(model.getPackages().getPackages().get(i).getName(), transform.getPackages().getPackages().get(i).getName()); } } protected KatelloErratum postPopulate(KatelloErratum model) { model.setName(model.getId()); model.setId(string2hex(model.getId())); model.setIssued(DateMapper.map(DATE, null)); model.setSeverity(ErrataSeverity.MODERATE.getDescription()); model.setType(ErrataType.ENHANCEMENT.getDescription()); return super.postPopulate(model); } }
45.509804
109
0.720379
ee264a2fe28a36a61b06ba3d1de896ba00084811
368
public class Size extends Place{ private int width; public Size(){ super("default size",34); } public void setwidth(int newwidth){ this.width=newwidth; } public int getwidth(){ return width; } public String toString(){ String out = super.toString(); out += "-->Size"; return out; } }
20.444444
39
0.548913
e3fb621b22c4c9f8d86b04f7e0139650462f5fa9
2,339
/* * Copyright 2014 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.gradle.nativebinaries.toolchain.internal.gcc; import org.gradle.api.Action; import org.gradle.api.internal.DefaultNamedDomainObjectSet; import org.gradle.internal.reflect.Instantiator; import org.gradle.nativebinaries.toolchain.TargetedPlatformToolChain; import org.gradle.nativebinaries.toolchain.GccCommandLineToolConfiguration; import org.gradle.nativebinaries.toolchain.internal.tools.*; import java.util.List; import java.util.Map; public class DefaultGccPlatformToolChain<T extends GccCommandLineToolConfiguration> extends DefaultNamedDomainObjectSet<T> implements TargetedPlatformToolChain<T> { private final String name; private final String displayName; public DefaultGccPlatformToolChain(Class<? extends T> type, Map<String, T> asMap, Instantiator instantiator, String name, String displayName) { super(type, instantiator); this.name = name; this.displayName = displayName; for (T tool : asMap.values()) { add(newConfiguredGccTool(tool)); } } private T newConfiguredGccTool(T defaultTool) { GccCommandLineToolConfigurationInternal gccToolInternal = (GccCommandLineToolConfigurationInternal) defaultTool; DefaultGccCommandLineToolConfiguration platformTool = getInstantiator().newInstance(DefaultGccCommandLineToolConfiguration.class, defaultTool.getName(), gccToolInternal.getToolType(), defaultTool.getExecutable()); Action<List<String>> argAction = gccToolInternal.getArgAction(); platformTool.withArguments(argAction); return (T) platformTool; } public String getDisplayName() { return displayName; } public String getName() { return name; } }
41.767857
221
0.756734
75077f1ffbbef6d93469a6fdc908ba6cc6258091
1,372
package com.github.freshchen.keeping.prototype; import java.util.ArrayList; /** * @program: fresh-design-pattern * @Date: 2019/5/18 23:21 * @Author: Ling Chen * @Description: 通过序列号实现深复制 * GirlFriendShallow{name='San Kong', hobbies=[food, make up], secrets=Secret{heigth='170', weight='50'}} * GirlFriendShallow{name='San Kong', hobbies=[food, make up], secrets=Secret{heigth='170', weight='50'}} * GirlFriend object same ? false * GirlFriend's Secretobject same ? false */ public class GirlFriendDeepTest { public static void main(String[] args) throws Exception { GirlFriendDeep girlFriendDeep = new GirlFriendDeep(); Secret secret = new Secret(); secret.setHeigth("170"); secret.setWeight("50"); girlFriendDeep.setName("San Kong"); girlFriendDeep.setHobbies(new ArrayList<String>() {{ add("food"); add("make up"); }}); girlFriendDeep.setSecrets(secret); GirlFriendDeep girlFriendDeep1 = girlFriendDeep.deepclone(); System.out.println(girlFriendDeep.toString()); System.out.println(girlFriendDeep1.toString()); System.out.println("GirlFriend object same ? " + (girlFriendDeep == girlFriendDeep1)); System.out.println("GirlFriend's Secretobject same ? " + (girlFriendDeep.getSecrets() == girlFriendDeep1.getSecrets())); } }
39.2
128
0.672741
22e80e5a6427f8457f887c3fb389a2baac985170
7,687
package fr.tse.lt2c.satin.matrix.extraction.ibr; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.log4j.Level; import org.apache.log4j.Logger; import fr.tse.lt2c.satin.matrix.beans.BinaryMatrix; import fr.tse.lt2c.satin.matrix.beans.DecompositionResult; import fr.tse.lt2c.satin.matrix.beans.SortableRectangle; import fr.tse.lt2c.satin.matrix.extraction.behaviors.RectangleExtractor; /** * Linear time implementation of IBR * * @author Julien Subercaze * */ public class IBRLinearWithLogger implements RectangleExtractor { Logger logger = Logger.getLogger("IBRLinear"); public final static Level DEBUG_LEVEL = Level.OFF; BinaryMatrix binaryMatrix = null; int MIN_AREA; /** * Intervals are encoded as triple : x_start,x_end,height */ int[] intervals1; int[] intervals2; List<SortableRectangle> rectangles; int intervalIndex = 0; private int maxInterval; private boolean extendCurrent; private int previousIntervalInList; private int newIntervalInList; private int startX; private int[] intervalsPrevious; private int[] intervalsNew; private int[] buffer; private int xmin; private int xmax; private boolean inInterval; public IBRLinearWithLogger(BinaryMatrix matrix) { this.binaryMatrix = matrix; } @Override public DecompositionResult extractDisjointRectangles() { long t1 = System.nanoTime(); rectangles = new ArrayList<>(); // First line boolean[][] mat = this.binaryMatrix.matrix; inInterval = false; intervals1 = new int[binaryMatrix.getCol() / 2 * 3]; intervals2 = new int[binaryMatrix.getCol() / 2 * 3]; for (int i = 0; i < binaryMatrix.getCol(); i++) { if (mat[0][i]) { if (!inInterval) { // Create new interval intervals1[intervalIndex * 3] = i; inInterval = true; } } else { if (inInterval) { inInterval = false; intervals1[intervalIndex * 3 + 1] = i; intervals1[intervalIndex * 3 + 2] = 1; intervalIndex++; } } } if (logger.isDebugEnabled()) { logger.debug("First Line"); logger.debug("Intervals " + Arrays.toString(intervals1)); } // Steady maxInterval = intervalIndex; inInterval = false; extendCurrent = false; // Index in list of previous intervals previousIntervalInList = 0; // New list newIntervalInList = 0; // Start of current interval startX = 0; intervalsPrevious = intervals1; intervalsNew = intervals2; for (int j = 1; j < binaryMatrix.getRow(); j++) { if (logger.isDebugEnabled()) { logger.debug("Line " + j); } previousIntervalInList = 0; newIntervalInList = 0; xmin = intervalsPrevious[0]; xmax = intervalsPrevious[1]; for (int i = 0; i < binaryMatrix.getCol(); i++) { if (logger.isDebugEnabled()) { logger.debug("(" + j + "," + i + ")"); } if (mat[j][i]) { if (i != binaryMatrix.getCol() - 1) { if (!inInterval) { inInterval = true; startX = i; // Start a new interval, checks if matches with // previous if (i == xmin) { extendCurrent = true; } else if (xmin < i && previousIntervalInList < maxInterval - 1) { // Move to the index to match current X while (xmin < i && previousIntervalInList < maxInterval) { previousIntervalInList++; xmin = intervalsPrevious[previousIntervalInList * 3]; //Add the previous as rectangle logger.debug("there"); } // Once at the end xmax = intervalsPrevious[previousIntervalInList * 3 + 1]; // Check again if (i == xmin) { extendCurrent = true; } }else{ //Add the previous rectangle if any if(maxInterval!=0){ rectangles .add(new SortableRectangle( intervalsPrevious[previousIntervalInList * 3], binaryMatrix.getRow() - intervalsPrevious[previousIntervalInList * 3 + 2], intervalsPrevious[previousIntervalInList * 3 + 1] - intervalsPrevious[previousIntervalInList * 3], intervalsPrevious[previousIntervalInList * 3 + 2])); } } } /** * We could check here in an {else},if it grows larger * than previous line interval here, however it would * lead to unnecessary comparisons, we rather check at * the end */ } else { logger.debug("Check EOL interval"); checkInterval(i, j,true); } } else { // Did it grew larger than the max of previous interval // ? checkInterval(i, j,false); } }// Switch maxInterval = newIntervalInList; buffer = intervalsPrevious; intervalsPrevious = intervalsNew; Arrays.fill(buffer, 0); intervalsNew = buffer; if (logger.isDebugEnabled()) { logger.debug("Rectangles " + rectangles); logger.debug("Intervals " + Arrays.toString(intervalsPrevious)); } } // Add the list of new rectangles for (int i = 0; i < maxInterval; i++) { rectangles .add(new SortableRectangle( intervalsPrevious[previousIntervalInList * 3], binaryMatrix.getRow() - intervalsPrevious[previousIntervalInList * 3 + 2], intervalsPrevious[previousIntervalInList * 3 + 1] - intervalsPrevious[previousIntervalInList * 3], intervalsPrevious[previousIntervalInList * 3 + 2])); } return new DecompositionResult(System.nanoTime() - t1, rectangles, -1); } private void checkInterval(int i, int j,boolean eol) { if (inInterval) { if (extendCurrent) { if (i+(eol?1:0) != xmax) { // Add the previous rectangle to the list of // rectangle SortableRectangle rect = new SortableRectangle( intervalsPrevious[previousIntervalInList * 3], j - intervalsPrevious[previousIntervalInList * 3 + 2], intervalsPrevious[previousIntervalInList * 3 + 1] - intervalsPrevious[previousIntervalInList * 3] +(eol?1:0), intervalsPrevious[previousIntervalInList * 3 + 2]); if (rect.getArea() != 0) rectangles.add(rect); // Create new interval intervalsNew[newIntervalInList * 3] = startX; intervalsNew[newIntervalInList * 3 + 1] = i; intervalsNew[newIntervalInList * 3 + 2] = 1; // Move newIntervalInList++; previousIntervalInList++; if (logger.isDebugEnabled()) { logger.debug("i!=xmax"); logger.debug("rectangles " + rectangles); logger.debug("intervals new " + Arrays.toString(intervalsNew)); } } else { // Add the previous internal to the new one, // with increased height intervalsNew[newIntervalInList * 3] = intervalsPrevious[previousIntervalInList * 3]; intervalsNew[newIntervalInList * 3 + 1] = intervalsPrevious[previousIntervalInList * 3 + 1]; intervalsNew[newIntervalInList * 3 + 2] = intervalsPrevious[previousIntervalInList * 3 + 2] + 1; // Move indexs newIntervalInList++; previousIntervalInList++; if (logger.isDebugEnabled()) { logger.debug("Extended previous rectangle"); logger.debug("intervals new " + Arrays.toString(intervalsNew)); } } } else { // Add new interval to the party intervalsNew[newIntervalInList * 3] = startX; intervalsNew[newIntervalInList * 3 + 1] = i+(eol?1:0); intervalsNew[newIntervalInList * 3 + 2] = 1; // Move newIntervalInList++; previousIntervalInList++; if (logger.isDebugEnabled()) { logger.debug("Added new interval"); logger.debug("intervals new " + Arrays.toString(intervalsNew)); } } extendCurrent = false; inInterval = false; } } }
29.339695
101
0.642513
75787af833026d86857091a27eb0c0d0d35a6444
2,111
package solveur; import instance.Instance; import instance.model.Demande; import instance.reseau.Client; import io.InstanceReader; import io.SolutionWriter; import io.exception.ReaderException; import solution.Solution; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; public class Triviale implements Solveur{ @Override public String getNom() { return "Triviale"; } @Override public Solution solve(Instance instance) { Solution solution = new Solution(instance); for(Map.Entry<Integer,Client> entry : instance.getClients().entrySet()){ for (Demande demande : entry.getValue().getDemandes()){ solution.addDemandNewTourneeTruck(demande); solution.addDemandTourneeTech(demande); } } return solution; } public static void main(String[] args) { InstanceReader reader; try { //reader = new InstanceReader("exemple/testInstance.txt"); //reader = new InstanceReader("instances/ORTEC-early-easy/VSC2019_ORTEC_early_09_easy.txt"); reader = new InstanceReader("instances/ORTEC-early/VSC2019_ORTEC_early_05.txt"); Instance instance = reader.readInstance(); Triviale triviale = new Triviale(); System.out.println(triviale.getNom()); Solution solution = triviale.solve(instance); System.out.println(solution.toString()); if(solution.check()) System.out.println("Solution OK"); else System.out.println("Solution NOK"); SolutionWriter io = new SolutionWriter(solution, triviale.getNom()); io.writeSolution(); } catch (ReaderException ex) { Logger.getLogger(Instance.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }
34.048387
104
0.653719
ef3607fea04d97960ff4d423a40c7684f2f0a661
2,238
/* * Copyright (c) $today.year.devonline.academy * * 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 academy.devonline.javamm.compiler.component.impl; import java.util.List; import static java.util.Objects.requireNonNull; import academy.devonline.javamm.code.fragment.ByteCode; import academy.devonline.javamm.code.fragment.SourceCode; import academy.devonline.javamm.code.fragment.SourceLine; import academy.devonline.javamm.code.fragment.operation.Block; import academy.devonline.javamm.compiler.Compiler; import academy.devonline.javamm.compiler.JavammSyntaxError; import academy.devonline.javamm.compiler.component.BlockOperationReader; import academy.devonline.javamm.compiler.component.SourceLineReader; /** * @author devonline * @link http://devonline.academy/javamm */ public class CompilerImpl implements Compiler { private final SourceLineReader sourceLineReader; private final BlockOperationReader blockOperationReader; public CompilerImpl(final SourceLineReader sourceLineReader, final BlockOperationReader blockOperationReader) { this.sourceLineReader = requireNonNull(sourceLineReader); this.blockOperationReader = requireNonNull(blockOperationReader); } @Override public ByteCode compile(final SourceCode... sourceCodes) throws JavammSyntaxError { // временная реализация - считываем только первый sourceCodes final List<SourceLine> sourceLines = sourceLineReader.read(sourceCodes[0]); final Block block = blockOperationReader.read(SourceLine.EMPTY_SOURCE_LINE, sourceLines.listIterator()); // т.к. ByteCode - функц. интерфейс, то возвращаем при помощи лямды return () -> block; } }
39.964286
112
0.766756
43e4dd0b5b109c9bc349cb6c967520c63c27f5fa
11,568
// Generate glue code import java.io.*; import java.util.*; class typeinfo { String scm_name; String java_name; String java_inp_type[]; typeinfo(String sname, String jname, String jit[]) { scm_name = sname; java_name = jname; java_inp_type = jit; } void write(PrintStream out) { int mode; out.println("//Autogenerated by typeinfo on " + new Date()); out.println("class scm" + java_name + " extends Procedure implements Obj"); out.println("{"); out.println(" Obj apply(Cell args, Env f)\n throws Exception\n {"); out.println(" Cell t = args;"); out.println(" Obj tmp;"); for (int i=0; i<java_inp_type.length; i++) { out.println(" if (t == null) { throw new SchemeError(\"" + scm_name + " expects " + java_inp_type.length + " arguments\"); }"); out.println(" tmp = (t.car!=null)?t.car.eval(f):null; t = t.cdr;"); if (java_inp_type[i].equals("String")) { mode = 0; } else if ((java_inp_type[i].equals("short")) || (java_inp_type[i].equals("int")) || (java_inp_type[i].equals("long"))) { mode = 1; } else if ((java_inp_type[i].equals("float")) || (java_inp_type[i].equals("double"))) { mode = 3; } else { mode = 2; } switch(mode) { case 0: // String out.println (" if ((tmp != null) && !(tmp instanceof Selfrep))" + " { throw new SchemeError(\"" + scm_name + " expects a String for arg #" + (i+1) + "\"); }"); out.println (" String arg" + i + " = (tmp!=null)?((Selfrep)tmp).val:null;"); break; case 1: // number case 3: out.println (" if (!(tmp instanceof Selfrep))" + " { throw new SchemeError(\"" + scm_name + " expects a number for arg #" + (i+1) + "\"); }"); if (mode == 1) { out.println (" "+java_inp_type[i]+" arg" + i + " = (" + java_inp_type[i] + ")(Math.round(((Selfrep)tmp).num));"); } else { out.println (" "+java_inp_type[i]+" arg" + i + " = (" + java_inp_type[i] + ")(((Selfrep)tmp).num);"); } break; default: // primnode out.println (" if ((tmp != null) && !(tmp instanceof primnode))" + " { throw new SchemeError(\"" + scm_name + " expects a " + java_inp_type[i] + " for arg #" + (i+1) + "\"); }"); out.println (" if ((tmp != null) && !((((primnode)tmp).val) instanceof " + java_inp_type[i] + ")) { throw new SchemeError(\"" + scm_name + " expects a " + java_inp_type[i] + " for arg #" + (i+1) + "\"); }"); out.println (" "+java_inp_type[i]+" arg" + i + " = (tmp != null)?(" + java_inp_type[i] + ")(((primnode)tmp).val):null;"); break; } } // Now create the new object out.print(" return new primnode(new " + java_name + "("); if (java_inp_type.length != 0) out.print("arg0"); for (int i=1; i<java_inp_type.length; i++) { out.print(", arg" + i); } out.println("));\n }"); out.println(" public String toString()"); out.println(" { return (\"<#" + scm_name + "#>\"); }"); out.println("}"); } } class procinfo // Create simple procedures // automatically { String java_name; String scm_name; String java_inp_type[]; procinfo(String sname, String jname, String jit[]) { java_name = jname; scm_name = sname; java_inp_type = jit; } void write(PrintStream out) { int mode; out.println("//Autogenerated by procinfo on " + new Date()); out.println ("class scm" + java_name + " extends Procedure implements Obj\n{"); out.println (" Obj apply(Cell args, Env f)\n throws Exception\n {\n"); out.println (" Cell t = args;"); out.println (" Obj tmp;"); for (int i=0; i<java_inp_type.length; i++) { out.println (" if (t == null) { throw new SchemeError(\"" + scm_name + " expects " + java_inp_type.length + " arguments\"); }"); out.println (" tmp = (t.car!=null)?t.car.eval(f):null; t = t.cdr;"); if (java_inp_type[i].equals("String")) { mode = 0; } else if ((java_inp_type[i].equals("short")) || (java_inp_type[i].equals("int")) || (java_inp_type[i].equals("float")) || (java_inp_type[i].equals("double")) || (java_inp_type[i].equals("long"))) { mode = 1; } else { mode = 2; } switch(mode) { case 0: // String out.println (" if ((tmp != null) && !(tmp instanceof Selfrep))" + " { throw new SchemeError(\"" + scm_name + " expects a String for arg #" + (i+1) + "\"); }"); out.println (" String arg" + i + " = (tmp!=null)?((Selfrep)tmp).val:null;"); break; case 1: // number out.println (" if (!(tmp instanceof Selfrep))" + " { throw new SchemeError(\"" + scm_name + " expects a number for arg #" + (i+1) + "\"); }"); out.println (" "+java_inp_type[i]+" arg" + i + " = (" + java_inp_type[i] + ")(((Selfrep)tmp).num);"); break; default: // primnode out.println (" if ((tmp != null) && !(tmp instanceof primnode))" + " { throw new SchemeError(\"" + scm_name + " expects a " + java_inp_type[i] + " for arg #" + (i+1) + "\"); }"); out.println (" if ((tmp != null) && !((((primnode)tmp).val) instanceof " + java_inp_type[i] + ")) { throw new SchemeError(\"" + scm_name + " expects a " + java_inp_type[i] + " for arg #" + (i+1) + "\"); }"); out.println (" "+java_inp_type[i]+" arg" + i + " = (tmp != null)?(" + java_inp_type[i] + ")(((primnode)tmp).val):null;"); break; } } // now call the method out.print(" arg0." + java_name + "(arg1"); for (int i=2; i<java_inp_type.length; i++) { out.print(", arg" + i); } out.println(");\n return null;\n }"); out.println(" public String toString()"); out.println(" { return (\"<#" + scm_name + "#>\"); }"); out.println("}"); } } class autogen implements jas.RuntimeConstants { static String procs[][] = { // Manipulate class env {"ClassEnv", "CP"}, {"jas-class-addcpe", "addCPItem"}, {"ClassEnv", "Var"}, {"jas-class-addfield", "addField"}, {"ClassEnv", "CP"}, {"jas-class-addinterface", "addInterface"}, {"ClassEnv", "CP"}, {"jas-class-setclass", "setClass"}, {"ClassEnv", "CP"}, {"jas-class-setsuperclass", "setSuperClass"}, {"ClassEnv", "short", "String", "String", "CodeAttr", "ExceptAttr"}, {"jas-class-addmethod", "addMethod"}, {"ClassEnv", "short"}, {"jas-class-setaccess", "setClassAccess"}, {"ClassEnv", "String"}, {"jas-class-setsource", "setSource"}, {"ClassEnv", "scmOutputStream"}, {"jas-class-write", "write"}, // Add things to exceptions {"ExceptAttr", "CP"}, {"jas-exception-add", "addException"}, // Manipulate code attrs {"CodeAttr", "Insn"}, {"jas-code-addinsn", "addInsn"}, {"CodeAttr", "short"}, {"jas-code-stack-size", "setStackSize"}, {"CodeAttr", "short"}, {"jas-code-var-size", "setVarSize"}, {"CodeAttr", "Catchtable"}, {"jas-set-catchtable", "setCatchtable"}, // add things to catchtables {"Catchtable", "CatchEntry"}, {"jas-add-catch-entry", "addEntry"}, }; static String types[][] = { {"String"}, {"make-ascii-cpe", "AsciiCP"}, {"String"}, {"make-class-cpe", "ClassCP"}, {"String", "String"}, {"make-name-type-cpe", "NameTypeCP"}, {"String", "String", "String"}, {"make-field-cpe", "FieldCP"}, {"String", "String", "String"}, {"make-interface-cpe", "InterfaceCP"}, {"String", "String", "String"}, {"make-method-cpe", "MethodCP"}, {"int"}, {"make-integer-cpe", "IntegerCP"}, {"float"}, {"make-float-cpe", "FloatCP"}, {"long"}, {"make-long-cpe", "LongCP"}, {"double"}, {"make-double-cpe", "DoubleCP"}, {"String"}, {"make-string-cpe", "StringCP"}, {"short", "CP", "CP", "ConstAttr"}, {"make-field", "Var"}, {"CP"}, {"make-const", "ConstAttr"}, {"String"}, {"make-outputstream", "scmOutputStream"}, {"String"}, {"make-label", "Label"}, {}, {"make-class-env", "ClassEnv"}, {}, {"make-code", "CodeAttr"}, {}, {"make-exception", "ExceptAttr"}, {}, {"make-catchtable", "Catchtable"}, {"Label", "Label", "Label", "CP"}, {"make-catch-entry", "CatchEntry"}, {"int", "int"}, {"iinc", "IincInsn"}, {"CP", "int"}, {"multianewarray", "MultiarrayInsn"}, {"CP", "int"}, {"invokeinterface", "InvokeinterfaceInsn"}, }; public static void main(String argv[]) throws IOException { PrintStream initer = new PrintStream(new FileOutputStream("AutoInit.java")); initer.println("package scm;\n\nimport jas.*;"); initer.println("class AutoInit\n{\n static void fillit(Env e)\n {"); // Generate types in the system. PrintStream doit = new PrintStream(new FileOutputStream("AutoTypes.java")); doit.println("package scm;\n\nimport jas.*;"); for (int x = 0; x<types.length; x += 2) { typeinfo tp = new typeinfo(types[x+1][0], types[x+1][1], types[x]); tp.write(doit); initer.println("e.definevar(Symbol.intern(\"" + types[x+1][0] + "\"), new scm" + types[x+1][1] + "());"); } // Add some simple procedures doit = new PrintStream(new FileOutputStream("AutoProcs.java")); doit.println("package scm;\n\nimport jas.*;"); for (int x = 0; x<procs.length; x += 2) { procinfo p = new procinfo(procs[x+1][0], procs[x+1][1], procs[x]); initer.println("e.definevar(Symbol.intern(\"" + procs[x+1][0] + "\"), new scm" + procs[x+1][1] + "());"); p.write(doit); } initer.println(" }\n}"); } }
38.431894
90
0.453665
f896851a2e7d270935826540913222747838b761
3,809
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.bian.dto.CRCustomerCampaignSpecificationRetrieveInputModelCustomerCampaignSpecificationInstanceAnalysis; import org.bian.dto.CRCustomerCampaignSpecificationRetrieveInputModelCustomerCampaignSpecificationInstanceReportRecord; import javax.validation.Valid; /** * CRCustomerCampaignSpecificationRetrieveInputModel */ public class CRCustomerCampaignSpecificationRetrieveInputModel { private Object customerCampaignSpecificationRetrieveActionTaskRecord = null; private String customerCampaignSpecificationRetrieveActionRequest = null; private CRCustomerCampaignSpecificationRetrieveInputModelCustomerCampaignSpecificationInstanceReportRecord customerCampaignSpecificationInstanceReportRecord = null; private CRCustomerCampaignSpecificationRetrieveInputModelCustomerCampaignSpecificationInstanceAnalysis customerCampaignSpecificationInstanceAnalysis = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The retrieve service call consolidated processing record * @return customerCampaignSpecificationRetrieveActionTaskRecord **/ public Object getCustomerCampaignSpecificationRetrieveActionTaskRecord() { return customerCampaignSpecificationRetrieveActionTaskRecord; } public void setCustomerCampaignSpecificationRetrieveActionTaskRecord(Object customerCampaignSpecificationRetrieveActionTaskRecord) { this.customerCampaignSpecificationRetrieveActionTaskRecord = customerCampaignSpecificationRetrieveActionTaskRecord; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Details of the retrieve action service request (lists requested reports) * @return customerCampaignSpecificationRetrieveActionRequest **/ public String getCustomerCampaignSpecificationRetrieveActionRequest() { return customerCampaignSpecificationRetrieveActionRequest; } public void setCustomerCampaignSpecificationRetrieveActionRequest(String customerCampaignSpecificationRetrieveActionRequest) { this.customerCampaignSpecificationRetrieveActionRequest = customerCampaignSpecificationRetrieveActionRequest; } /** * Get customerCampaignSpecificationInstanceReportRecord * @return customerCampaignSpecificationInstanceReportRecord **/ public CRCustomerCampaignSpecificationRetrieveInputModelCustomerCampaignSpecificationInstanceReportRecord getCustomerCampaignSpecificationInstanceReportRecord() { return customerCampaignSpecificationInstanceReportRecord; } public void setCustomerCampaignSpecificationInstanceReportRecord(CRCustomerCampaignSpecificationRetrieveInputModelCustomerCampaignSpecificationInstanceReportRecord customerCampaignSpecificationInstanceReportRecord) { this.customerCampaignSpecificationInstanceReportRecord = customerCampaignSpecificationInstanceReportRecord; } /** * Get customerCampaignSpecificationInstanceAnalysis * @return customerCampaignSpecificationInstanceAnalysis **/ public CRCustomerCampaignSpecificationRetrieveInputModelCustomerCampaignSpecificationInstanceAnalysis getCustomerCampaignSpecificationInstanceAnalysis() { return customerCampaignSpecificationInstanceAnalysis; } public void setCustomerCampaignSpecificationInstanceAnalysis(CRCustomerCampaignSpecificationRetrieveInputModelCustomerCampaignSpecificationInstanceAnalysis customerCampaignSpecificationInstanceAnalysis) { this.customerCampaignSpecificationInstanceAnalysis = customerCampaignSpecificationInstanceAnalysis; } }
45.891566
218
0.873195
80758bf7fd5454f5491d1f97adfcdd6217f5fd56
3,366
package de.ahus1.example.jdbi; import de.ahus1.example.jdbi._10_CrudJbdiSelectAllTest.Sighting; import de.ahus1.example.jdbi._10_CrudJbdiSelectAllTest.SightingResultMapper; import org.assertj.core.api.Assertions; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.BindBean; import org.skife.jdbi.v2.sqlobject.GetGeneratedKeys; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; /** * @author Alexander Schwartz 2016 */ public class _30_CrudJbdiInsertWithSequence extends _00_AbstractJdbiBaseTest { @Before public void shouldSetupSequence() { dbi = new DBI("jdbc:oracle:thin:@localhost:1521:XE", "test", "test"); dbi.withHandle(handle -> { handle.execute("CREATE SEQUENCE seq INCREMENT BY 1 START WITH 100"); return null; }); } @After public void tearDownSequence() throws Exception { dbi.withHandle(handle -> { handle.execute("DROP SEQUENCE seq"); return null; }); } /** * Oracle needs to be queried by index and not id (like * {@link org.skife.jdbi.v2.sqlobject.FigureItOutResultSetMapper} does). */ public static class OracleGeneratedKeyMapper implements ResultSetMapper<Long> { @Override public Long map(int index, ResultSet r, StatementContext ctx) throws SQLException { return r.getLong(1); } } public interface SightingRepsitory extends _20_CrudJbdiSelectSingleTest.SightingRepsitory { @SqlUpdate("INSERT INTO sighting (id, name) values (:s.id, :s.name)") void createNewSightingWithKnownId(@BindBean("s") Sighting sighting); @SqlUpdate("INSERT INTO sighting (id, name) VALUES (seq.nextval, :s.name)") @GetGeneratedKeys(columnName = "id", value = OracleGeneratedKeyMapper.class) int createNewSightingAutogeneratedId(@BindBean("s") Sighting sighting); } @Test public void shouldInsertWithKnownId() { dbi.registerMapper(new SightingResultMapper()); SightingRepsitory sightingRepsitory = dbi.onDemand(SightingRepsitory.class); sightingRepsitory.createNewSightingWithKnownId(Sighting.builder() .id(2).name("Enterprise") .build()); List<Sighting> sightings = sightingRepsitory.findByName("Enterprise"); Assertions.assertThat(sightings) .containsExactly(Sighting.builder() .id(2).name("Enterprise") .build()); } @Test public void shouldInsertWithAutogeneratedId() { dbi.registerMapper(new SightingResultMapper()); SightingRepsitory sightingRepsitory = dbi.onDemand(SightingRepsitory.class); int id = sightingRepsitory.createNewSightingAutogeneratedId(Sighting.builder() .name("Enterprise") .build()); List<Sighting> sightings = sightingRepsitory.findByName("Enterprise"); Assertions.assertThat(sightings) .containsExactly(Sighting.builder() .id(id).name("Enterprise") .build()); } }
36.989011
95
0.671123
092718f38bddf0db0d3a1a7b11255e98db646c54
1,122
package com.example.BookTradingClub.presentation.controller; import com.example.BookTradingClub.presentation.dto.UserBookDto; import com.example.BookTradingClub.service.BookService; import com.example.BookTradingClub.service.domain.UserBook; import org.modelmapper.ModelMapper; import org.modelmapper.TypeToken; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.lang.reflect.Type; import java.util.List; @RestController @RequestMapping(path= "/user-books") public class UserBooksController { @Autowired private BookService bookService; @Autowired private ModelMapper mapper; @RequestMapping(method = RequestMethod.GET) List<UserBookDto> getExistingUserBooks(){ List<UserBook> books = bookService.usersBooks(); Type userBookModelListType = new TypeToken<List<UserBookDto>>(){}.getType(); return mapper.map(books, userBookModelListType); } }
29.526316
84
0.78877
53023d47c10fdafe3a04ccab0954df65e4c8df4f
290
package de.rieckpil.learning.highperformancejpa.entity; import lombok.Data; import javax.persistence.Entity; import javax.persistence.Table; import java.time.Instant; @Data @Entity @Table(name= "announcement") public class Announcement extends Topic { private Instant validUntil; }
18.125
55
0.796552
8b8ea6802dee2c16ccbc18fb8964fa06dadd449e
7,966
/* * Copyright 2015-2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hawkular.rest; import static javax.ws.rs.core.Response.Status.CREATED; import java.io.IOException; import java.io.InputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.util.ArrayList; import java.util.List; import java.util.Spliterator; import java.util.stream.StreamSupport; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import org.hawkular.inventory.api.paging.Page; import org.hawkular.inventory.api.paging.PageContext; import org.hawkular.rest.json.Link; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SequenceWriter; /** * @author Lukas Krejci * @author Heiko W. Rupp * @since 0.0.1 */ final class ResponseUtil { /** * This method exists solely to concentrate usage of {@link javax.ws.rs.core.Response#created(java.net.URI)} into * one place until <a href="https://issues.jboss.org/browse/RESTEASY-1162">this JIRA</a> is resolved somehow. * * @param info the UriInfo instance of the current request * @param id the ID of a newly created entity under the base * @return the response builder with status 201 and location set to the entity with the provided id. */ public static Response.ResponseBuilder created(UriInfo info, String id) { return Response.status(CREATED).location(info.getRequestUriBuilder().segment(id).build()); } /** * Similar to {@link #created(UriInfo, String)} but used when more than 1 entity is created during the request. * <p/> * The provided list of ids is converted to URIs (by merely appending the ids using the * {@link UriBuilder#segment(String...)} method) and put in the response as its entity. * * @param info uri info to help with converting ids to URIs * @param ids the list of ids of the entities * @return the response builder with status 201 and entity set */ public static Response.ResponseBuilder created(UriInfo info, Spliterator<String> ids) { return Response.status(CREATED) .entity(StreamSupport.stream(ids, false).map( (id) -> info.getRequestUriBuilder().segment(id).build())); } public static <T> Response.ResponseBuilder pagedResponse(Response.ResponseBuilder response, UriInfo uriInfo, ObjectMapper mapper, Page<T> page) { InputStream data = null; try { //extract the data out of the page data = pageToStream(page, mapper, () -> { // the page iterator should be depleted by this time so the total size should be correctly set response.type(MediaType.APPLICATION_OCTET_STREAM_TYPE); createPagingHeader(response, uriInfo, page); }); } catch (IOException e) { } response.entity(data); return response; } public static <T> Response.ResponseBuilder pagedResponse(Response.ResponseBuilder response, UriInfo uriInfo, Page<T> page, Object data) { response.entity(data); createPagingHeader(response, uriInfo, page); return response; } private static <T> InputStream pageToStream(Page<T> page, ObjectMapper mapper, Runnable callback) throws IOException { final PipedOutputStream outs = new PipedOutputStream(); final PipedInputStream ins = new PipedInputStream() { @Override public void close() throws IOException { outs.close(); super.close(); } }; outs.connect(ins); mapper.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET); PageToStreamThreadPool.getInstance().submit(() -> { try (Page<T> closeablePage = page; PipedOutputStream out = outs; SequenceWriter sequenceWriter = mapper.writer().writeValuesAsArray(out)) { for (T element : closeablePage) { sequenceWriter.write(element); sequenceWriter.flush(); } } catch (IOException e) { throw new IllegalStateException("Unable to convert page to input stream.", e); } finally { callback.run(); } }); return ins; } /** * Create the paging headers for collections and attach them to the passed builder. Those are represented as * <i>Link:</i> http headers that carry the URL for the pages and the respective relation. * <br/>In addition a <i>X-Total-Count</i> header is created that contains the whole collection size. * * @param builder The ResponseBuilder that receives the headers * @param uriInfo The uriInfo of the incoming request to build the urls * @param resultList The collection with its paging information */ public static void createPagingHeader(final Response.ResponseBuilder builder, final UriInfo uriInfo, final Page<?> resultList) { UriBuilder uriBuilder; PageContext pc = resultList.getPageContext(); int page = pc.getPageNumber(); List<Link> links = new ArrayList<>(); if (pc.isLimited() && resultList.getTotalSize() > (pc.getPageNumber() + 1) * pc.getPageSize()) { int nextPage = page + 1; uriBuilder = uriInfo.getRequestUriBuilder(); // adds ?q, ?per_page, ?page, etc. if needed uriBuilder.replaceQueryParam("page", nextPage); links.add(new Link("next", uriBuilder.build().toString())); } if (page > 0) { int prevPage = page - 1; uriBuilder = uriInfo.getRequestUriBuilder(); // adds ?q, ?per_page, ?page, etc. if needed uriBuilder.replaceQueryParam("page", prevPage); links.add(new Link("prev", uriBuilder.build().toString())); } // A link to the last page if (pc.isLimited()) { long lastPage = resultList.getTotalSize() / pc.getPageSize(); if (resultList.getTotalSize() % pc.getPageSize() == 0) { lastPage -= 1; } uriBuilder = uriInfo.getRequestUriBuilder(); // adds ?q, ?per_page, ?page, etc. if needed uriBuilder.replaceQueryParam("page", lastPage); links.add(new Link("last", uriBuilder.build().toString())); } // A link to the current page uriBuilder = uriInfo.getRequestUriBuilder(); // adds ?q, ?per_page, ?page, etc. if needed StringBuilder linkHeader = new StringBuilder(new Link("current", uriBuilder.build().toString()) .rfc5988String()); //followed by the rest of the link defined above links.forEach((l) -> linkHeader.append(", ").append(l.rfc5988String())); //add that all as a single Link header to the response builder.header("Link", linkHeader.toString()); // Create a total size header builder.header("X-Total-Count", resultList.getTotalSize()); } }
41.489583
117
0.638212
d7854ab6ec2fad333c6e17c99a0f864565d8897c
989
package nv.visualFX.cloth.libs; /** * Callback interface to manage the DirectX context/device used for compute<p></p> * Created by mazhen'gui on 2017/9/12. */ public interface DxContextManagerCallback { /** * Acquire the D3D context for the current thread * * Acquisitions are allowed to be recursive within a single thread. * You can acquire the context multiple times so long as you release * it the same count. */ void acquireContext(); /** * Release the D3D context from the current thread */ void releaseContext(); /** * Return if exposed buffers (only cloth particles at the moment) * are created with D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX. * * The user is responsible to query and acquire the mutex of all * corresponding buffers. * todo: We should acquire the mutex locally if we continue to * allow resource sharing across devices. */ boolean synchronizeResources(); }
29.088235
82
0.680485
3fdafe33b520ca6fe3febd0d33e9c709dc904333
526
package cn.rui97.ruigou.mapper; import cn.rui97.ruigou.domain.Brand; import cn.rui97.ruigou.query.BrandQuery; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.baomidou.mybatisplus.plugins.Page; import java.util.List; /** * <p> * 品牌信息 Mapper 接口 * </p> * * @author lurui * @since 2019-01-13 */ public interface BrandMapper extends BaseMapper<Brand> { /** * 查询分页数据 * @param page * @param query * @return */ List<Brand> selectPageList(Page<Brand> page, BrandQuery query); }
19.481481
67
0.68251
0fe0e83cfbd64f083b93f343471d9165a582fc4c
2,161
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.schema.access; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Constants related to Protocol Versions for Hortonworks Schema Registry. */ public class HortonworksProtocolVersions { /** * The minimum valid protocol version. */ public static final int MIN_VERSION = 1; /** * The maximum valid protocol version. */ public static final int MAX_VERSION = 3; /** * Map from protocol version to the required schema fields for the given version. */ private static final Map<Integer, Set<SchemaField>> REQUIRED_SCHEMA_FIELDS_BY_PROTOCOL; static { final Map<Integer,Set<SchemaField>> requiredFieldsByProtocol = new HashMap<>(); requiredFieldsByProtocol.put(1, EnumSet.of(SchemaField.SCHEMA_IDENTIFIER, SchemaField.SCHEMA_VERSION)); requiredFieldsByProtocol.put(2, EnumSet.of(SchemaField.SCHEMA_VERSION_ID)); requiredFieldsByProtocol.put(3, EnumSet.of(SchemaField.SCHEMA_VERSION_ID)); REQUIRED_SCHEMA_FIELDS_BY_PROTOCOL = Collections.unmodifiableMap(requiredFieldsByProtocol); } public static Set<SchemaField> getRequiredSchemaFields(final Integer protocolVersion) { return REQUIRED_SCHEMA_FIELDS_BY_PROTOCOL.get(protocolVersion); } }
37.912281
111
0.745951
9806384a8dd453d030f761d05e15cfafa94b92d6
798
package org.tiankafei.jdbc.mybatis.dao; import org.apache.ibatis.session.SqlSessionFactory; import org.tiankafei.jdbc.dao.ICommonDAO; /** * @author 甜咖啡 */ public interface ICommonMyBatisDAO extends ICommonDAO { /** * 获取mybatis的session会话工厂类 * * @return mybatis的session会话工厂类 */ public SqlSessionFactory getSqlSessionFactory(); /** * 打开mybatis的session会话 * * @param autoCommit 是否自动提交事物 */ public void openSession(boolean autoCommit); /** * 关闭sqlSession */ public void transactionClose(); /** * 获取查询结果 * * @param type mapper * @return 查询结果 */ public Object getMapper(Class<?> type); /** * 添加映射类 * * @param type 映射类 */ public void addMapper(Class<?> type); }
17.347826
55
0.609023
d6a6cfd108da70e24106e69598aa6568196de28f
545
package javauygulamaları; public class polindrome22 { public static int dizi(String[] A){ int enUzun = A[0].length(); int indis=0; for (int i = 0; i < A.length; i++) { if (enUzun< A[i].length()) { enUzun= A[i].length(); indis = i+1; } } return indis; } public static void main(String[] args) { String[] A = {"Ali" , "Emre" , "Berat" , "Mehmet" , "Fatih", "Emirhan"}; System.out.println("En uzun : " + dizi(A)); } }
18.793103
80
0.47156
0ee01285ffa9b4734a5378e33de39e3ad364a22b
6,539
package org.embulk.input.jdbc.getter; import java.lang.reflect.Field; import java.sql.Types; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.embulk.config.ConfigException; import org.embulk.config.ConfigSource; import org.embulk.config.Task; import org.embulk.input.jdbc.AbstractJdbcInputPlugin.PluginTask; import org.embulk.input.jdbc.JdbcColumn; import org.embulk.input.jdbc.JdbcColumnOption; import org.embulk.input.jdbc.JdbcInputConnection; import org.embulk.spi.Exec; import org.embulk.spi.PageBuilder; import org.embulk.spi.type.TimestampType; import org.embulk.spi.type.Type; import org.embulk.util.timestamp.TimestampFormatter; import static java.util.Locale.ENGLISH; public class ColumnGetterFactory { protected final PageBuilder to; private final String defaultTimeZone; private final Map<Integer, String> jdbcTypes = getAllJDBCTypes(); public ColumnGetterFactory(PageBuilder to, String defaultTimeZone) { this.to = to; this.defaultTimeZone = defaultTimeZone; } public ColumnGetter newColumnGetter(JdbcInputConnection con, PluginTask task, JdbcColumn column, JdbcColumnOption option) { return newColumnGetter(con, task, column, option, option.getValueType()); } private ColumnGetter newColumnGetter(JdbcInputConnection con, PluginTask task, JdbcColumn column, JdbcColumnOption option, String valueType) { Type toType = getToType(option); switch(valueType) { case "coalesce": // resolve actual valueType using sqlTypeToValueType() method and retry. return newColumnGetter(con, task, column, option, sqlTypeToValueType(column, column.getSqlType())); case "long": return new LongColumnGetter(to, toType); case "float": return new FloatColumnGetter(to, toType); case "double": return new DoubleColumnGetter(to, toType); case "boolean": return new BooleanColumnGetter(to, toType); case "string": return new StringColumnGetter(to, toType); case "json": return new JsonColumnGetter(to, toType); case "date": return new DateColumnGetter(to, toType, newTimestampFormatter(option, DateColumnGetter.DEFAULT_FORMAT)); case "time": return new TimeColumnGetter(to, toType, newTimestampFormatter(option, DateColumnGetter.DEFAULT_FORMAT)); case "timestamp": return new TimestampColumnGetter(to, toType, newTimestampFormatter(option, DateColumnGetter.DEFAULT_FORMAT)); case "decimal": return new BigDecimalColumnGetter(to, toType); default: throw new ConfigException(String.format(ENGLISH, "Unknown value_type '%s' for column '%s'", option.getValueType(), column.getName())); } } protected Map<Integer,String> getAllJDBCTypes() { Map<Integer,String> map = new HashMap<Integer, String>(); for(Field f: Types.class.getFields()){ try { map.put((Integer) f.get(null), f.getName()); } catch(IllegalAccessException iea){ } } return map; } public String getJdbcType(int sqlType) { return jdbcTypes.get(sqlType); } protected String sqlTypeToValueType(JdbcColumn column, int sqlType) { switch(sqlType) { // getLong case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: case Types.BIGINT: return "long"; // getFloat case Types.FLOAT: case Types.REAL: return "float"; // getDouble case Types.DOUBLE: return "double"; // getBool case Types.BOOLEAN: case Types.BIT: // JDBC BIT is boolean, unlike SQL-92 return "boolean"; // getString, Clob case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: case Types.CLOB: case Types.NCHAR: case Types.NVARCHAR: case Types.LONGNVARCHAR: return "string"; // TODO //// getBytes Blob //case Types.BINARY: //case Types.VARBINARY: //case Types.LONGVARBINARY: //case Types.BLOB: // return new BytesColumnGetter(); // getDate case Types.DATE: return "date"; // getTime case Types.TIME: return "time"; // getTimestamp case Types.TIMESTAMP: return "timestamp"; // TODO //// Null //case Types.NULL: // return new NullColumnGetter(); // getBigDecimal case Types.NUMERIC: case Types.DECIMAL: return "decimal"; // others case Types.ARRAY: // array case Types.STRUCT: // map case Types.REF: case Types.DATALINK: case Types.SQLXML: // XML case Types.ROWID: case Types.DISTINCT: case Types.JAVA_OBJECT: case Types.OTHER: default: throw unsupportedOperationException(column); } } protected Type getToType(JdbcColumnOption option) { if (!option.getType().isPresent()) { return null; } Type toType = option.getType().get(); if (toType instanceof TimestampType && option.getTimestampFormat().isPresent()) { toType = ((TimestampType)toType).withFormat(option.getTimestampFormat().get()); } return toType; } private TimestampFormatter newTimestampFormatter(JdbcColumnOption option, String defaultTimestampFormat) { final String format = option.getTimestampFormat().orElse(defaultTimestampFormat); final String timezone = option.getTimeZone().orElse(this.defaultTimeZone); return TimestampFormatter.builder(format, true).setDefaultZoneFromString(timezone).build(); } private static UnsupportedOperationException unsupportedOperationException(JdbcColumn column) { throw new UnsupportedOperationException( String.format(ENGLISH, "Unsupported type %s (sqlType=%d) of '%s' column. Please add '%s: {value_type: string}' to 'column_options: {...}' option to convert the values to strings, or exclude the column from 'select:' option", column.getTypeName(), column.getSqlType(), column.getName(), column.getName())); } }
33.192893
221
0.632971
ae166217a31f9567e33b4b38432ff594b2e0070d
2,016
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package uk.co.objectconnexions.expressiveobjects.applib.query; import java.io.Serializable; import uk.co.objectconnexions.expressiveobjects.applib.DomainObjectContainer; import uk.co.objectconnexions.expressiveobjects.applib.filter.Filter; /** * For use by repository implementations, representing the values of a query. * * <p> * The implementations of these objects are be provided by the underlying * persistor/object store; consult its documentation. * * <p> * <b>Note:</b> that not every object store will necessarily support this * interface. In particular, the in-memory object store does not. For this, you * can use the {@link Filter} interface to similar effect, for example in * {@link DomainObjectContainer#allMatches(Class, Filter)}). Note that the * filtering is done within the {@link DomainObjectContainer} rather than being * pushed back to the object store. */ public interface Query<T> extends Serializable { /** * The {@link Class} of the objects returned by this query. */ public Class<T> getResultType(); /** * A human-readable representation of this query and its values. */ public String getDescription(); }
37.333333
79
0.737103
d4ad7e2ad57ce3d773d53bd3a1d405ad0e43fd02
1,070
/* This file is licensed to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.xmlunit.diff; /** * Decides whether the difference engine should stop the whole * comparison process because of the current difference. */ public interface ComparisonController { /** * May instruct the difference engine to stop the whole comparison process. * * @param difference the Difference that is responsible for * stopping the comparison process * @return whether to stop the comparison process */ boolean stopDiffing(Difference difference); }
35.666667
79
0.745794
229a8288b2deabd1c12266e8f5e1d7b6cc2fa46c
3,707
package interactivespaces.service.image.depth.internal.openni2.libraries; import interactivespaces.service.image.depth.internal.openni2.libraries.OpenNI2Library.OniSensorType; import org.bridj.IntValuedEnum; import org.bridj.Pointer; import org.bridj.StructObject; import org.bridj.ann.CLong; import org.bridj.ann.Field; import org.bridj.ann.Library; /** * <i>native declaration : OniCTypes.h</i><br> * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> or <a href="http://bridj.googlecode.com/">BridJ</a> . */ @Library("OpenNI2") public class OniFrame extends StructObject { @Field(0) public int dataSize() { return this.io.getIntField(this, 0); } @Field(0) public OniFrame dataSize(int dataSize) { this.io.setIntField(this, 0, dataSize); return this; } /** C type : void* */ @Field(1) public Pointer<? > data() { return this.io.getPointerField(this, 1); } /** C type : void* */ @Field(1) public OniFrame data(Pointer<? > data) { this.io.setPointerField(this, 1, data); return this; } /** C type : OniSensorType */ @Field(2) public IntValuedEnum<OniSensorType > sensorType() { return this.io.getEnumField(this, 2); } /** C type : OniSensorType */ @Field(2) public OniFrame sensorType(IntValuedEnum<OniSensorType > sensorType) { this.io.setEnumField(this, 2, sensorType); return this; } @CLong @Field(3) public long timestamp() { return this.io.getCLongField(this, 3); } @CLong @Field(3) public OniFrame timestamp(long timestamp) { this.io.setCLongField(this, 3, timestamp); return this; } @Field(4) public int frameIndex() { return this.io.getIntField(this, 4); } @Field(4) public OniFrame frameIndex(int frameIndex) { this.io.setIntField(this, 4, frameIndex); return this; } @Field(5) public int width() { return this.io.getIntField(this, 5); } @Field(5) public OniFrame width(int width) { this.io.setIntField(this, 5, width); return this; } @Field(6) public int height() { return this.io.getIntField(this, 6); } @Field(6) public OniFrame height(int height) { this.io.setIntField(this, 6, height); return this; } /** C type : OniVideoMode */ @Field(7) public OniVideoMode videoMode() { return this.io.getNativeObjectField(this, 7); } /** C type : OniVideoMode */ @Field(7) public OniFrame videoMode(OniVideoMode videoMode) { this.io.setNativeObjectField(this, 7, videoMode); return this; } /** C type : OniBool */ @Field(8) public int croppingEnabled() { return this.io.getIntField(this, 8); } /** C type : OniBool */ @Field(8) public OniFrame croppingEnabled(int croppingEnabled) { this.io.setIntField(this, 8, croppingEnabled); return this; } @Field(9) public int cropOriginX() { return this.io.getIntField(this, 9); } @Field(9) public OniFrame cropOriginX(int cropOriginX) { this.io.setIntField(this, 9, cropOriginX); return this; } @Field(10) public int cropOriginY() { return this.io.getIntField(this, 10); } @Field(10) public OniFrame cropOriginY(int cropOriginY) { this.io.setIntField(this, 10, cropOriginY); return this; } @Field(11) public int stride() { return this.io.getIntField(this, 11); } @Field(11) public OniFrame stride(int stride) { this.io.setIntField(this, 11, stride); return this; } public OniFrame() { super(); } public OniFrame(Pointer pointer) { super(pointer); } }
26.105634
183
0.694902
d59c3262d6127f8ed096de262223b7d473975370
594
package playground; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.logging.Logger; import static org.junit.jupiter.api.Assertions.assertTrue; class AppTest { private static final Logger LOG = Logger.getLogger(AppTest.class.getName()); @BeforeEach void setUp() { LOG.info("Before running test..."); } @AfterEach void tearDown() { LOG.info("After running test..."); } @Test void test() { LOG.info("Running test..."); assertTrue(true, () -> "Blah Blah Blah..."); } }
19.16129
78
0.681818
d7255bbabe19cb0d65d67119cf4a94d60e20ac70
1,553
/* * Copyright (C) 2007 The Guava 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.google.common.collect; import com.google.common.base.Function; import com.google.common.testing.ForwardingWrapperTester; import junit.framework.TestCase; import java.util.ListIterator; /** * Tests for {@code ForwardingListIterator}. * * @author Robert Konigsberg */ public class ForwardingListIteratorTest extends TestCase { @SuppressWarnings("rawtypes") public void testForwarding() { new ForwardingWrapperTester() .testForwarding( ListIterator.class, new Function<ListIterator, ListIterator>() { @Override public ListIterator apply(ListIterator delegate) { return wrap(delegate); } }); } private static <T> ListIterator<T> wrap(final ListIterator<T> delegate) { return new ForwardingListIterator<T>() { @Override protected ListIterator<T> delegate() { return delegate; } }; } }
28.759259
75
0.688989
0ac3381508529733229cfe4e2e52905048ad23da
2,938
/* * The MIT License (MIT) * * Copyright (c) 2013-2014 Jeff Nelson, Cinchapi Software Collective * * 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.cinchapi.concourse; import javax.annotation.concurrent.Immutable; import com.google.common.collect.ComparisonChain; /** * A {@link Tag} is a wrapper around {@link String} that represents the * string value in key in record and distinguishes from simple String values. A * Tag does not get full-text indexed. * * @author knd */ @Immutable public final class Tag implements Comparable<Tag> { /** * Return a Tag that embeds {@code value}. * * @param value * @return the Tag */ public static Tag create(String value) { return new Tag(value); } /** * The String representation for the value in key in record * that this Tag embeds. */ private final String value; /** * Construct a new instance. * * @param value */ private Tag(String value) { this.value = value; } @Override public int compareTo(Tag other) { return ComparisonChain.start().compare(toString(), other.toString()) .result(); } /** * Return {@code true} if {@code other} of type String or * Tag equals this Tag. * * @param other * @return {@code true} if {@code other} equals this tag */ @Override public boolean equals(Object other) { boolean isEqual = false; if(other instanceof Tag) { isEqual = compareTo((Tag) other) == 0; } else if(other instanceof String) { isEqual = value.equals(other.toString()); } return isEqual; } /** * Return the String value that this Tag embeds. * * @return the value */ @Override public String toString() { return value; } }
29.089109
80
0.653846
e0e6582010b32bde8db218daf169fe699deb9569
7,449
package org.firstinspires.ftc.teamcode.opmodes.GenericTest; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.teamcode.Lib.FTCLib.DcMotor8863; /** * This OpMode tests a DC motor and is meant to test the functionality of the DcMotor8863 class. * It also demonstrates the various methods available to control motor movement. Examples for each * of the major methods are given. Read the comments to understand the example. */ @TeleOp(name = "Test DcMotor8863 Ramp", group = "Test") //@Disabled public class TestDCMotor8863PowerRamp extends LinearOpMode { //************************************************************** // You need these variables inside this block // declare the motor DcMotor8863 motor; // for setting up a ramp up from 0 to the desired power double initialPower = 0; double finalPower = 1.0; double rampTime = 1000; //************************************************************** int feedback = 0; double powerToRunAt = 0.8; // % of full speed int value = 0; private ElapsedTime runningTimer; private double lastTime = 0; private String mode; @Override public void runOpMode() { runningTimer = new ElapsedTime(0); //************************************************************** // You need the initializations inside this block // Instantiate and initialize motors motor = new DcMotor8863(RobotConfigMappingForGenericTest.getleftMotorName(), hardwareMap); // set the type of motor you are controlling motor.setMotorType(DcMotor8863.MotorType.ANDYMARK_40); // for each revolution of the motor, it moves something. How far does it move it? In this case // I'm just testing the motor so it moves 360 degress per revolution. But it could be a drive // train that moves 10 cm per revolution. Look at what is attached and how far it moves per // revolution. motor.setMovementPerRev(360); // When the motor finishes its movement, how close to the goal does it need to be in order // to call it done? 5 encoder ticks? 1 encoder tick? motor.setTargetEncoderTolerance(5); // When the motor finishes its movement is the motor able to spin freely (FLOAT) or does it // actively resist being moved and hold its position (HOLD)? motor.setFinishBehavior(DcMotor8863.FinishBehavior.FLOAT); // Motor power can range from -1.0 to +1.0. The minimum motor power for the motor. Any power // below this will be automatically set to this number. motor.setMinMotorPower(-1); // The maximum motor power that will be sent to the motor. Any motor power above this will be // autimatically trimmed back to this number. motor.setMaxMotorPower(1); // The direction the motor moves when it is sent a positive power. Can be FORWARD or // BACKWARD. motor.setDirection(DcMotor.Direction.FORWARD); // If you want the motor to slowly ramp up to speed setup a power ramp. If you don't // just comment out this line. These parameters set the slope of a line that motor power // cannot go above during the ramp up time. Y axis = power, X axis = time motor.setupPowerRamp(initialPower, finalPower, rampTime); //************************************************************** // test internal routines from DcMotor8863 //value = motor.getEncoderCountForDegrees(-400); //telemetry.addData("Encoder count for degrees = ", "%d", value); // Wait for the start button telemetry.addData(">", "Press Start to run Motor."); telemetry.update(); waitForStart(); runningTimer.reset(); // Next I will demonstrate / test the ability of a motor to change its speed not is a sudden // change but by a gradual ramp of the power. // Start the motor running in constant power mode (no PID). Then perform a series of // gradual power changes. boolean powerRampRan1x = false; boolean powerRampRan2x = false; boolean powerRampRan3x = false; boolean powerRampRan4x = false; // Set the motor to spin freely when power is removed motor.setAfterCompletionToFloat(); motor.setupPowerRamp(0, 1.0, 4000); // Start the motor. Since a power ramp has been setup, the motor start out with a ramp up of // power. motor.runAtConstantPower(powerToRunAt); mode = "0 -> 0.8"; // You need to run this loop in order to use the power ramp. while (opModeIsActive() && !motor.isMotorStateComplete()) { motor.update(); // change motor direction if (runningTimer.milliseconds() > 6000 && !powerRampRan1x) { // start a power ramp. Power will gradually change from running forward to // running backward over 2 seconds motor.setupAndStartPowerRamp(1.0, -.8, 4000); mode = "1.0 -> -0.8"; powerRampRan1x = true; } // After 9 seconds slow the motor down gradually if (runningTimer.milliseconds() > 12000 && !powerRampRan2x) { // start a power ramp. Power will gradually reduce to 30 % motor.setupAndStartPowerRamp(-.8, -.3, 4000); mode = "-0.8 -> -0.3"; powerRampRan2x = true; } // After 13 seconds speed the motor up if (runningTimer.milliseconds() > 18000 && !powerRampRan3x) { // start a power ramp. Power will gradually increase to 100 % motor.setupAndStartPowerRamp(-.3, -1.0, 4000); mode = "-0.3 -> -1.0"; powerRampRan3x = true; } // Stop the motor after 17 seconds by gradually bringing it to a stop if (runningTimer.milliseconds() > 24000 && !powerRampRan4x) { motor.setupAndStartPowerRamp(-1.0, 0, 4000); powerRampRan4x = true; mode = "-1.0 -> 0.0"; } // Shutdown the motor if (runningTimer.milliseconds() > 30000) { motor.shutDown(); break; } // display some information on the driver phone telemetry.addData(">", mode); telemetry.addData("Motor Speed = ", "%5.2f", motor.getCurrentPower()); telemetry.addData("feedback = ", "%5.2f", motor.getPositionInTermsOfAttachment()); telemetry.addData("Encoder Count = ", "%5d", motor.getCurrentPosition()); telemetry.addData("Elapsed time = ", "%5.0f", runningTimer.milliseconds()); telemetry.addData(">", "Press Stop to end test."); telemetry.update(); } telemetry.addData(">", "Movement tests complete"); telemetry.addData(">", "Press Stop to end test."); telemetry.update(); while (opModeIsActive()) { idle(); } // Turn off motor, let it float and signal done; motor.setMotorToFloat(); telemetry.addData(">", "Done"); telemetry.update(); } }
42.084746
102
0.600752
28822034c871a2423806a053341b221575450295
2,359
package com.data.tructure.array; /** * 二分查找 * * @author cuishifeng * @Title: BinarySearch * @ProjectName com.dataStructure.array * @date 2018-09-07 */ public class BinarySearch { private long[] array; private int nElems; public BinarySearch(int maxIndex) { array = new long[maxIndex]; nElems = 0; } /** * 无序插入 */ public void insert(long value) { array[nElems] = value; nElems++; } /** * 有序插入 - 从小到达排序 */ public void orderInsert(long value) { int j; for (j = 0; j < nElems; j++) { if (array[j] > value) { break; } } for (int i = nElems; i > j; i--) { array[i] = array[i - 1]; } array[j] = value; nElems++; } /** * 插入 - 从大到小排序 */ public void orderBigInsert(long value) { int j; for (j = 0; j < nElems; j++) { if (array[j] < value) { break; } } for (int i = nElems; i > j; i--) { array[i] = array[i - 1]; } array[j] = value; nElems++; } /** * 二分查找 */ public int find(long searchKey) { int lowerBound = 0; int upperBound = nElems - 1; int currentBound; int findCount = 0; while (true) { findCount++; System.out.println("第 " + findCount + " 次寻找"); currentBound = (upperBound + lowerBound) / 2; if (array[currentBound] == searchKey) { return currentBound; } else if (lowerBound > upperBound) { return nElems; } else { if (array[currentBound] < searchKey) { lowerBound = currentBound + 1; } else { upperBound = currentBound - 1; } } } } public void dispalay() { for (long a : array) { System.out.println(a); } } public static void main(String[] args) { BinarySearch binarySearch = new BinarySearch(100); for (long i = 0; i < 100; i++) { binarySearch.insert(i); } int index = binarySearch.find(1); System.out.println("二分查找获取的数组下标: " + index); } }
21.842593
58
0.449767
534544c1f56c09c12e51d65d093f8316d734647d
5,369
/** HistoryManager.java * @author Sunita Sarawagi * @since 1.1 * @version 1.3 */ package iitb.CRF; import iitb.Utils.Counters; import java.io.Serializable; class EdgeGenerator implements Serializable { /** * */ private static final long serialVersionUID = -4872905008657745029L; int offset; int numOrigY; int histsize; EdgeGenerator(int histsize, int numOrigY) { offset = 1; for (int i = 0; i < histsize-1; i++) offset *= numOrigY; this.numOrigY = numOrigY; this.histsize = histsize; } int first(int destY) { return destY/numOrigY; } int next(int destY, int currentSrcY) { return currentSrcY + offset; } int firstY(int pos) { return 0; } int nextY(int currentY, int pos) { if ((pos >= histsize-1) || (currentY < numOrigY-1)) return currentY+1; if (currentY >= Math.pow(numOrigY,(pos+1))) return numOrigY*offset; return currentY+1; } }; class HistoryManager implements Serializable { /** * */ private static final long serialVersionUID = 2916617303265831850L; int histsize; int numOrigY; int numY; HistoryManager(int histsize, int num) { this.histsize = histsize; numOrigY = num; this.numY = num; for (int i = 0; i < histsize-1; numY *= num, i++); }; FeatureGenerator getFeatureGen(FeatureGenerator fgen) { if (histsize == 1) return fgen; return new FeatureGeneratorWithHistory(fgen); }; DataIter mapTrainData(DataIter trainData) { if (histsize == 1) return trainData; return new DataIterHistory(trainData); }; void set_y(DataSequence data, int i, int label) { if (histsize > 1) data.set_y(i,label%numOrigY); } int getOrigY(int label){ return label%numOrigY; } EdgeGenerator getEdgeGenerator() { return new EdgeGenerator(histsize,numOrigY); } class FeatureHist implements Feature { Feature orig; Counters ctr; FeatureHist() {} FeatureHist(int histsize, int numOrigY) { ctr = new Counters(histsize+1, numOrigY); } void init(Feature f) { orig = f; ctr.clear(); ctr.fix(0,orig.y()); ctr.fix(histsize,0); if (orig.yprev() != -1) { ctr.fix(1,orig.yprev()); } /* if (pos == 0) { for (int i = 1; i < histsize; i++) ctr.fix(i,0); } */ if (orig.yprevArray() != null) { for (int i = 0; i < orig.yprevArray().length; i++) { if (orig.yprevArray()[i] != -1) ctr.fix(i+1, orig.yprevArray()[i]); } } } boolean advance() { return ctr.advance(); } public int index() {return orig.index();} public int y() {return ctr.value(histsize-1,0);} public int yprev() { if ((orig.yprevArray() == null) || (orig.yprevArray()[histsize-1] == -1)) return -1; return ctr.value(histsize,1); } public int[] yprevArray() {return null;} public float value() {return orig.value();} String type() {return "H ";} void print() {System.out.println(type() + index() + " " + y() + " " + yprev() + " " + value());} }; class FeatureGeneratorWithHistory implements FeatureGenerator { /** * */ private static final long serialVersionUID = 8104535757570574219L; FeatureGenerator fgen; FeatureHist currentFeature, histFeature; boolean allDone; iitb.Model.FeatureImpl feature = new iitb.Model.FeatureImpl(); FeatureGeneratorWithHistory(FeatureGenerator fgen) { this.fgen = fgen; histFeature = new FeatureHist(histsize,numOrigY); } public int numFeatures() {return fgen.numFeatures();} // + numY*numOrigY;} public void startScanFeaturesAt(DataSequence data, int pos) { fgen.startScanFeaturesAt(data,pos); allDone = false; if (fgen.hasNext()) { currentFeature = histFeature; currentFeature.init(fgen.next()); } else allDone = true; } public boolean hasNext() {return !allDone;} public Feature next() { feature.copy(currentFeature); //currentFeature.print(); boolean nextY = currentFeature.advance(); if (!nextY) { if (fgen.hasNext()) currentFeature.init(fgen.next()); //else if (currentFeature != edgeFeatures) // currentFeature = edgeFeatures; else allDone = true; } return feature; } /* (non-Javadoc) * @see iitb.CRF.FeatureGenerator#featureName(int) */ public String featureName(int featureIndex) { return fgen.featureName(featureIndex); } }; class DataSequenceHist implements DataSequence { /** * */ private static final long serialVersionUID = 1280727093574327309L; Counters cntr; transient DataSequence orig; DataSequenceHist() {cntr = new Counters(histsize,numOrigY);} void init(DataSequence orig) { this.orig = orig; } public int length() {return orig.length();} public int y(int i) { cntr.clear(); for(int k = histsize-1; k >= 0; k--) if (i-k >= 0) cntr.fix(k,orig.y(i-k)); else cntr.fix(k,0); return cntr.value(); } public Object x(int i) {return orig.x(i);} public void set_y(int i, int label) {} }; class DataIterHistory implements DataIter { DataIter orig; DataSequenceHist dataSeq; DataIterHistory(DataIter orig) { this.orig = orig; dataSeq = new DataSequenceHist(); } public void startScan() {orig.startScan();} public boolean hasNext() {return orig.hasNext();} public DataSequence next() {dataSeq.init(orig.next()); return dataSeq;} }; };
26.448276
97
0.64295
8e33d1185249d4742ce9da3af63386828094c241
1,381
package com.xjbg.sso.server.authencation; /** * @author kesc * @since 2019/5/18 */ public interface AuthenticationInfo { /** * Returns all principals associated with the corresponding Subject. Each principal is an identifying piece of * information useful to the application such as a username, or user id, a given name, etc - anything useful * to the application to identify the current <code>Subject</code>. * <p/> * The returned principals should <em>not</em> contain any credentials used to verify principals, such * as passwords, private keys, etc. Those should be instead returned by {@link #getCredentials() getCredentials()}. * * @return all principals associated with the corresponding Subject. */ Principal getPrincipals(); /** * Returns the credentials associated with the corresponding Subject. A credential verifies one or more of the * {@link #getPrincipals() principals} associated with the Subject, such as a password or private key. Credentials * are used by Shiro particularly during the authentication process to ensure that submitted credentials * during a login attempt match exactly the credentials here in the <code>AuthenticationInfo</code> instance. * * @return the credentials associated with the corresponding Subject. */ Object getCredentials(); }
46.033333
120
0.721217
a1d6edacf1bf50e7fd35ffbf4d2db1d4675b3e91
684
package awesome.data.structure.algorithm.sort.practice; /** * 冒泡排序 * * @author: Andy * @time: 2019/6/30 13:13 * @since */ public class BubbleSort extends Sort{ /** * 冒泡排序 * * @param a 要排序的数组 * @param n 要排序的数组长度 */ public static void sort(int[] a, int n){ for(int i = n - 1; n > 0; n--){ for(int j = 0; j < i; j++){ if(a[j] > a[j + 1]){ swap(a, j, j + 1); } } } } public static void main(String[] args) { int[] a = {1,5,3,2,1,4}; sort(a, a.length); for(int e : a){ System.out.println(e); } } }
18.486486
55
0.419591
1dbb3a6284259a1c6d22c728e99b2729f6db93da
4,904
package com.kieserjw; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; public class InputandAnalysis { private String inputFilename; private ArrayList<String> stringList; private ArrayList<Double> numberList; private double sumNumbers; private double mean; private double median; // create a dummy instance public InputandAnalysis() { this(null); } // create an instance with an input file name // go through and input file and analyse for strings and numbers public InputandAnalysis(String inputFilename) { this.inputFilename = inputFilename; this.stringList = new ArrayList<String>(); this.numberList = new ArrayList<Double>(); this.sumNumbers = 0; this.mean = 0; this.median = 0; this.inputFile(); this.analyseNumbers(); this.analyseStrings(); } // read the file name specified into the array lists public void inputFile() { BufferedReader br = null; FileReader fr = null; try { fr = new FileReader(inputFilename); br = new BufferedReader(fr); String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { try { double d = Double.parseDouble(sCurrentLine); this.numberList.add(d); } catch (NumberFormatException ex) { this.stringList.add(sCurrentLine); } } } catch (IOException e) { e.printStackTrace(); // error handling } finally { try { if (br != null) br.close(); if (fr != null) fr.close(); } catch (IOException ex) { ex.printStackTrace(); } } } // calculate median, sum, and mean public void analyseNumbers() { if (this.numberList.size() > 0) { Collections.sort(this.numberList); int middle = numberList.size() / 2; if (numberList.size() % 2 == 1) { this.median = numberList.get(middle); } else { this.median = (numberList.get(middle) + numberList.get(middle - 1)) / 2.0; } for (int i = 0; i < numberList.size(); i++) { this.sumNumbers = numberList.get(i) + this.sumNumbers; } this.mean = this.sumNumbers / this.numberList.size(); } } // sort strings in reverse order public void analyseStrings() { Collections.sort(this.stringList, Collections.reverseOrder(String.CASE_INSENSITIVE_ORDER)); } // print out the required information public String toString() { String resultString = ""; if (this.numberList.size() > 0) { resultString += "Sum: " + Utilities.printDecimal(this.getTotal()) + System.lineSeparator(); resultString += "Mean: " + Utilities.printDecimal(this.getMean()) + System.lineSeparator(); resultString += "Median: " + Utilities.printDecimal(this.getMedian()) + System.lineSeparator(); resultString += "Percentage of values that are numbers: " + Utilities.printDecimal(this.getPercentageNumbers() * 100) + "%" + System.lineSeparator(); } if (this.stringList.size() > 0) { resultString += "reverse alphabetical distinct list of strings found in the file with number of times that string appeared: "; for (int i = 0; i < this.stringList.size(); i++) { String temp = this.stringList.get(i); if (i == 0 || !temp.equals(this.stringList.get(i - 1))) { resultString += System.lineSeparator() + temp + ": " + Collections.frequency(this.stringList, temp); } } } return resultString; } public double getMean() { return this.mean; } public double getMedian() { return this.median; } public double getTotal() { return this.sumNumbers; } public int getCountOfNumbers() { return this.numberList.size(); } public boolean contains(String src) { return this.stringList.contains(src); } public double getPercentageNumbers() { return this.numberList.size() / (double) (this.stringList.size() + this.numberList.size()); } public ArrayList<String> getStringList() { return this.stringList; } public ArrayList<Double> getNumberList() { return this.numberList; } }
32.052288
139
0.549347
00b980fc07f82858891509e71751fca6c375dbfc
3,317
package test; import com.kenshine.cglib.demo02.TestClass; import com.kenshine.cglib.demo03.SampleClass; import net.sf.cglib.proxy.*; import org.junit.Assert; import org.junit.Test; import java.lang.reflect.Method; /** * @author :kenshine * @date :Created in 2021/12/30 22:03 * @description:測試 * @modified By: * @version: $ */ public class EnhancerTest { /** * 1.FixedValue * 对所有拦截的方法返回相同的值 */ @Test public void test01_FixedValue(){ Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(SampleClass.class); enhancer.setCallback(new FixedValue() { @Override public Object loadObject() throws Exception { return "Hello cglib"; } }); //enhancer.create 创建增强代理对象 SampleClass proxy = (SampleClass) enhancer.create(); System.out.println(proxy.test(null)); //拦截test,输出Hello cglib System.out.println(proxy.toString()); System.out.println(proxy.getClass()); // 返回的值为 hello cglib // 会出现ClassCastException System.out.println(proxy.hashCode()); } /** * 2. invocationHandler * 在代理类实例上调用其代理接口中声明的方法时,最终都会由InvocationHandler的invoke方法执行 */ @Test public void test02_invocationHandler(){ Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(SampleClass.class); enhancer.setCallback(new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //getDeclaringClass 获取声明方法的类 if(method.getDeclaringClass() != Object.class && method.getReturnType() == String.class){ return "hello cglib"; }else{ throw new RuntimeException("Do not know what to do"); } } }); SampleClass proxy = (SampleClass) enhancer.create(); Assert.assertEquals("hello cglib", proxy.test(null)); Assert.assertNotEquals("Hello cglib", proxy.toString()); } /** * 3.CallbackFilter */ @Test public void test03_CallbackFilter(){ Enhancer enhancer = new Enhancer(); //CallbackHelper CallbackHelper callbackHelper = new CallbackHelper(SampleClass.class, new Class[0]) { @Override protected Object getCallback(Method method) { //满足条件则代理 if(method.getDeclaringClass() != Object.class && method.getReturnType() == String.class){ return new FixedValue() { @Override public Object loadObject() throws Exception { return "Hello cglib"; } }; }else{ return NoOp.INSTANCE; } } }; enhancer.setSuperclass(SampleClass.class); enhancer.setCallbackFilter(callbackHelper); enhancer.setCallbacks(callbackHelper.getCallbacks()); SampleClass proxy = (SampleClass) enhancer.create(); Assert.assertEquals("Hello cglib", proxy.test(null)); Assert.assertNotEquals("Hello cglib",proxy.toString()); System.out.println(proxy.hashCode()); } }
32.519608
105
0.583358
296b77e9fdf666bd495bf05a34ee562d2b4e5754
4,268
/* * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.core.client.config; import static java.util.stream.Collectors.toMap; import static org.assertj.core.api.Assertions.assertThat; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Map; import java.util.Optional; import org.junit.Test; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; /** * Validate the functionality of the Client*Configuration classes */ public class ConfigurationBuilderTest { @Test public void overrideConfigurationClassHasExpectedMethods() throws Exception { assertConfigurationClassIsValid(ClientOverrideConfiguration.class); } private void assertConfigurationClassIsValid(Class<?> configurationClass) throws Exception { // Builders should be instantiable from the configuration class Method createBuilderMethod = configurationClass.getMethod("builder"); Object builder = createBuilderMethod.invoke(null); // Builders should implement the configuration class's builder interface Class<?> builderInterface = Class.forName(configurationClass.getName() + "$Builder"); assertThat(builder).isInstanceOf(builderInterface); Class<?> builderClass = builder.getClass(); Method[] builderMethods = builderClass.getDeclaredMethods(); // Builder's build methods should return the configuration object Optional<Method> buildMethod = Arrays.stream(builderMethods).filter(m -> m.getName().equals("build")).findFirst(); assertThat(buildMethod).isPresent(); Object builtObject = buildMethod.get().invoke(builder); assertThat(builtObject).isInstanceOf(configurationClass); // Analyze the builder for compliance with the bean specification BeanInfo builderBeanInfo = Introspector.getBeanInfo(builderClass); Map<String, PropertyDescriptor> builderProperties = Arrays.stream(builderBeanInfo.getPropertyDescriptors()) .collect(toMap(PropertyDescriptor::getName, p -> p)); // Validate method names for (Field field : configurationClass.getFields()) { // Ignore generated fields (eg. by Jacoco) if (field.isSynthetic()) { continue; } String builderPropertyName = builderClass.getSimpleName() + "'s " + field.getName() + " property"; PropertyDescriptor builderProperty = builderProperties.get(field.getName()); // Builders should have a bean-style write method for each field assertThat(builderProperty).as(builderPropertyName).isNotNull(); assertThat(builderProperty.getReadMethod()).as(builderPropertyName + "'s read method").isNull(); assertThat(builderProperty.getWriteMethod()).as(builderPropertyName + "'s write method").isNotNull(); // Builders should have a fluent write method for each field Arrays.stream(builderMethods) .filter(builderMethod -> matchesSignature(field.getName(), builderProperty, builderMethod)) .findAny() .orElseThrow(() -> new AssertionError(builderClass + " can't write " + field.getName())); } } private boolean matchesSignature(String methodName, PropertyDescriptor property, Method builderMethod) { return builderMethod.getName().equals(methodName) && builderMethod.getParameters().length == 1 && builderMethod.getParameters()[0].getType().equals(property.getPropertyType()); } }
45.404255
122
0.709231
5a3e462eccb8e32c71cde8f51ade662b472a2f16
7,545
// ParameterBasePanel.java package mit.cadlab.dome3.gui.objectmodel.modelobject.parameter; import mit.cadlab.dome3.gui.objectmodel.DomeObjectGui; import mit.cadlab.dome3.gui.objectmodel.dataobject.DocumentationBasePanel; import mit.cadlab.dome3.objectmodel.DomeObject; import mit.cadlab.dome3.objectmodel.modelobject.parameter.Parameter; import mit.cadlab.dome3.swing.DComboBox; import mit.cadlab.dome3.swing.DTextField; import mit.cadlab.dome3.swing.LayeredCenterLayout; import mit.cadlab.dome3.swing.Templates; import java.awt.GridBagConstraints; import java.awt.Insets; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.ComboBoxModel; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLayeredPane; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public abstract class ParameterBasePanel extends JLayeredPane implements DomeObjectGui { protected static GridBagConstraints gbc; // used as abbreviation for GridBagConstraints class protected PropertyChangeListener propertyListener; protected DTextField nameField; protected DComboBox dataTypeComboBox; protected DataObjectCards valuePanel; protected DocumentationBasePanel docPanel; protected JTabbedPane contentTabs; protected JCheckBox constantCheckBox; protected Parameter dataModel; public ParameterBasePanel(Parameter param) { if (param == null) throw new IllegalArgumentException("Parameter gui - null Parameter"); dataModel = param; propertyListener = getPropertyListener(); dataModel.addPropertyChangeListener(propertyListener); createComponents(); layoutComponents(); configureComponents(); } protected PropertyChangeListener getPropertyListener() { return new GenericParameterPropertyChangeListener(); } protected void createComponents() { nameField = Templates.makeDTextField(dataModel.getName()); dataTypeComboBox = Templates.makeDComboBox(makeDataTypeComboBoxModel()); contentTabs = Templates.makeTabbedPane(); contentTabs.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { repaint(); } }); constantCheckBox = Templates.makeCheckBox("constant:", dataModel.isConstant(), true); } protected abstract ComboBoxModel makeDataTypeComboBoxModel(); protected void layoutComponents() { setLayout(new LayeredCenterLayout()); add(makeConstantPanel()); add(makeMainPanel()); } protected void configureComponents() { } // to be overridden by subclasses public JPanel makeConstantPanel() { JPanel p = new JPanel(); p.setOpaque(false); JPanel filler1 = new JPanel(); filler1.setOpaque(false); JComponent[] comps = {filler1, constantCheckBox}; // gridx, gridy, gridwidth, gridheight, weightx, weighty, anchor, fill, insets(t,l,b,r), ipadx, ipady GridBagConstraints[] gbcs = { new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, gbc.CENTER, gbc.BOTH, new Insets(0, 0, 0, 0), 0, 0), // center filler new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, gbc.EAST, gbc.NONE, new Insets(0, 0, 0, 8), 0, -2), // constant check box }; Templates.layoutGridBagB(p, comps, gbcs); return p; } public JPanel makeMainPanel() { JPanel p = new JPanel(); JComponent[] comps = {Templates.makeLabel("name:"), nameField, dataTypeComboBox, contentTabs}; // gridx, gridy, gridwidth, gridheight, weightx, weighty, anchor, fill, insets(t,l,b,r), ipadx, ipady GridBagConstraints[] gbcs = { new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, gbc.WEST, gbc.NONE, new Insets(0, 0, 0, 0), 0, 0), // name label new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, gbc.WEST, gbc.HORIZONTAL, new Insets(0, 5, 0, 5), 0, 0), // name field new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, gbc.EAST, gbc.NONE, new Insets(0, 0, 0, 0), 0, 0), // data type chooser new GridBagConstraints(0, 1, 3, 1, 1.0, 1.0, gbc.NORTHWEST, gbc.BOTH, new Insets(5, 0, 0, 0), 0, 0), // tabbed pane }; Templates.layoutGridBagB(p, comps, gbcs); return p; } // connect to data model public void setModel(Parameter model) { if (model == null) throw new IllegalArgumentException("Parameter gui - null Parameter"); if (dataModel != null) { dataModel.removePropertyChangeListener(propertyListener); } dataModel = model; dataModel.addPropertyChangeListener(propertyListener); getModelData(); } protected void getModelData() { setName(dataModel.getName()); nameField.setCurrent(); setDataTypeSelection(); setConstant(dataModel.isConstant()); docPanel.setModel(dataModel.getDocumentation()); } protected void setModelData() { // when does this get used? setModelName(); //setModelDataTypeSelection(); // doesn't make sense setModelConstant(); } protected void setModelName() { dataModel.setName(nameField.getText()); } protected void setModelDataTypeSelection(Parameter.DataTypeSelection dtSel) { dataModel.setDataTypeSelection(dtSel); } protected void setModelCurrentType() { dataModel.setCurrentType((String) dataTypeComboBox.getSelectedItem()); } public void setModelConstant() { dataModel.setConstant(constantCheckBox.isSelected()); } // Parameter javabean support public void setName(String value) { nameField.setText(value); } protected void setDataTypeSelection() { dataTypeComboBox.setModel(makeDataTypeComboBoxModel()); valuePanel.setDataObjects(dataModel.getDataObjects(), dataModel.getCurrentType()); } public void setCurrentType(String value) { dataTypeComboBox.setSelectedItem(value); //?? //valuePanel.showType(value); // assume it works //dataTypeComboBox.setBackground(currentBgColor); } public void setConstant(boolean constant) { constantCheckBox.setSelected(constant); } //protected void showCurrentValue() { //valuePanel.showType((String)dataTypeComboBox.getSelectedItem()); //} class GenericParameterPropertyChangeListener implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent e) { String property = e.getPropertyName(); Object newValue = e.getNewValue(); if (property.equals(Parameter.NAME)) { setName((String) newValue); nameField.setCurrent(); } else if (property.equals(Parameter.DATATYPESELECTION)) { setDataTypeSelection(); } else if (property.equals(Parameter.CURRENT_TYPE)) { dataTypeComboBox.setSelectedObject(newValue); } else if (property.equals(Parameter.CONSTANT)) { setConstant(((Boolean) newValue).booleanValue()); } } } // DomeObjectGui interface public DomeObject getDomeObject() { return dataModel; } public String getTitlePrefix() { return "Parameter: "; } public String getTitle() { return getTitlePrefix() + getDomeObject().getName(); } public Object getGuiObject() { return dataModel; } public void close() { // get data? // sangmok: memory problem fix. valuePanel is DataObjectCards instance which contains DataObjectPanel instances. // releaseDataObjectReferenceOfDataObjectPanel() method of DataObjectCards releases references to data object. valuePanel.releaseDataObjectReferenceOfDataObjectPanel(); } }
30.546559
122
0.714115
f811d161a2f664fd92049cc2aa210be46e7a5e35
342
package util; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Test; /** * Created by ZhouYing. * www.zhouying.xyz */ public class LogTest { static Logger logger = LogManager.getLogger(); @Test public void test() { logger.error("blabla -> {}", "332211"); } }
17.1
50
0.660819
a64db470beb3fff421e2c31299dfbdd592d47b61
2,450
package user; import java.util.HashMap; import java.util.Map; import lida.Lida; import spark.Request; import spark.Response; public class UserController { public static String login(Request req, Response res) { // Obtain request parameters String email = req.queryParams("login-email"); String password = req.queryParams("login-password"); // Use DAO to get data from DB User user = UserDAO.findUserByEmailAndPassword(email, password); // Create HashMap for template Map<String, Object> map = new HashMap<String, Object>(); if (user != null) { // Authenticated // Create Session req.session().attribute("userId", user.getId().toString()); // Redirect to Dashboard res.redirect("/sec/dashboard"); return null; } else { // Bad Credentials // Render Template map.put("error", "Bad Credentials"); return Lida.render(map, "home.mustache"); } } public static String register(Request req, Response res) { // Obtain request parameters String firstName = req.queryParams("register-firstname"); String lastName = req.queryParams("register-lastname"); String email = req.queryParams("register-email"); String password = req.queryParams("register-password"); // Create HashMap for template Map<String, Object> map = new HashMap<String, Object>(); // Use DAO to get data from DB User existingUser = UserDAO.findUserByEmail(email); if (existingUser != null) { // existing // Render Template map.put("error", "User already created"); return Lida.render(map, "home.mustache"); } // Use DAO to insert data into DB User user = UserDAO.createUser(firstName, lastName, email, password); // Create Session req.session().attribute("userId", user.getId().toString()); // Redirect to Dashboard res.redirect("/sec/dashboard"); return null; } public static String loginAndRegisterScreen() { Map<String, Object> map = new HashMap<String, Object>(); return Lida.render(map, "home.mustache"); } public static String logout(Request req, Response res) { req.session().removeAttribute("userId"); res.redirect("/"); return null; } public static void isAuthenticated(Request req, Response res) { // isAuthenticated String userId = req.session().attribute("userId"); if (userId == null) { res.redirect("/"); } } }
25
71
0.659592
e3a3e7d7ac9c9d8a7e8c1a9df8f95b738616c1cf
548
package cn.yjxxclub.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; /** * Author: Starry.Teng * Email: [email protected] * Date: 17-9-12 * Time: 下午12:59 * Describe: Application */ @SpringBootApplication //@EnableScheduling//通过@EnableScheduling注解开启对计划任务的支持 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
26.095238
68
0.773723
a4566c900492ab3aed5d0de29d9eb14b453b7690
15,045
/*- * Copyright (C) 2013-2014 The JBromo Authors. * * 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.jbromo.dao.jpa.query.jpql.from; import org.jbromo.common.BooleanUtil; import org.jbromo.sample.server.model.src.User; import org.junit.Assert; import org.junit.Test; /** * JUnit JpqlFromBuilder class. * @author qjafcunuas */ public class JpqlFromBuilderTest { /** * Define the beginning of the from query. */ private static final String ROOT_FROM_QUERY = "from " + User.class.getName() + " o "; /** * Define the root alias. */ private static final String ROOT_ALIAS = "o"; /** * Validate from builder. * @param from the from builder to validate. * @param fromQuery the waited from query */ private void validate(final JpqlFromBuilder from, final String fromQuery) { Assert.assertEquals(from.toString(), fromQuery); final StringBuilder builder = new StringBuilder("select o "); from.build(builder); Assert.assertEquals(builder.toString(), "select o " + fromQuery); } /** * Return a new instance of from query. * @return the new instance. */ private JpqlFromBuilder newInstance() { return new JpqlFromBuilder(User.class); } /** * Test constructor. */ @Test public void constructor() { final JpqlFromBuilder from = newInstance(); validate(from, ROOT_FROM_QUERY); } /** * Test getRootAlias method. */ @Test public void getRootAlias() { Assert.assertNotNull(new JpqlFromBuilder(User.class).getRootAlias()); Assert.assertEquals(new JpqlFromBuilder(User.class).getRootAlias(), ROOT_ALIAS); } /** * Test join method. */ @Test public void join() { String query = ROOT_FROM_QUERY; String alias; int aliasId = 1; final JpqlFromBuilder from = newInstance(); for (final Boolean newAlias : BooleanUtil.ALL) { aliasId = 1; // alias o1 alias = from.join(from.getRootAlias(), "manyToOneGroup", newAlias); query += "inner join o.manyToOneGroup "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.manyToOneGroup"); } validate(from, query); // alias o2 alias = from.join(from.getRootAlias(), "oneToOneGroup", newAlias); query += "inner join o.oneToOneGroup "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.oneToOneGroup"); } validate(from, query); // alias o3 alias = from.join(from.getRootAlias(), "manyToManyGroups", newAlias); query += "inner join o.manyToManyGroups "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.manyToManyGroups"); } validate(from, query); // alias o4 alias = from.join(from.getRootAlias(), "surnames", newAlias); query += "inner join o.surnames "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.surnames"); } validate(from, query); } } /** * Test joinFetch method. */ @Test public void joinFetch() { String query = ROOT_FROM_QUERY; String alias; int aliasId = 1; final JpqlFromBuilder from = newInstance(); for (final Boolean newAlias : BooleanUtil.ALL) { aliasId = 1; // alias o1 alias = from.joinFetch(from.getRootAlias(), "manyToOneGroup", newAlias); query += "inner join fetch o.manyToOneGroup "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.manyToOneGroup"); } validate(from, query); // alias o2 alias = from.joinFetch(from.getRootAlias(), "oneToOneGroup", newAlias); query += "inner join fetch o.oneToOneGroup "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.oneToOneGroup"); } validate(from, query); // alias o3 alias = from.joinFetch(from.getRootAlias(), "manyToManyGroups", newAlias); query += "inner join fetch o.manyToManyGroups "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.manyToManyGroups"); } validate(from, query); // alias o4 alias = from.joinFetch(from.getRootAlias(), "surnames", newAlias); query += "inner join fetch o.surnames "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.surnames"); } validate(from, query); } } /** * Test rightJoin method. */ @Test public void rightJoin() { String query = ROOT_FROM_QUERY; String alias; int aliasId = 1; final JpqlFromBuilder from = newInstance(); for (final Boolean newAlias : BooleanUtil.ALL) { aliasId = 1; // alias o1 alias = from.rightJoin(from.getRootAlias(), "manyToOneGroup", newAlias); query += "right join o.manyToOneGroup "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.manyToOneGroup"); } validate(from, query); // alias o2 alias = from.rightJoin(from.getRootAlias(), "oneToOneGroup", newAlias); query += "right join o.oneToOneGroup "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.oneToOneGroup"); } validate(from, query); // alias o3 alias = from.rightJoin(from.getRootAlias(), "manyToManyGroups", newAlias); query += "right join o.manyToManyGroups "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.manyToManyGroups"); } validate(from, query); // alias o4 alias = from.rightJoin(from.getRootAlias(), "surnames", newAlias); query += "right join o.surnames "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.surnames"); } validate(from, query); } } /** * Test rightJoinFetch method. */ @Test public void rightJoinFetch() { String query = ROOT_FROM_QUERY; String alias; int aliasId = 1; final JpqlFromBuilder from = newInstance(); for (final Boolean newAlias : BooleanUtil.ALL) { aliasId = 1; // alias o1 alias = from.rightJoinFetch(from.getRootAlias(), "manyToOneGroup", newAlias); query += "right join fetch o.manyToOneGroup "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.manyToOneGroup"); } validate(from, query); // alias o2 alias = from.rightJoinFetch(from.getRootAlias(), "oneToOneGroup", newAlias); query += "right join fetch o.oneToOneGroup "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.oneToOneGroup"); } validate(from, query); // alias o3 alias = from.rightJoinFetch(from.getRootAlias(), "manyToManyGroups", newAlias); query += "right join fetch o.manyToManyGroups "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.manyToManyGroups"); } validate(from, query); // alias o4 alias = from.rightJoinFetch(from.getRootAlias(), "surnames", newAlias); query += "right join fetch o.surnames "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.surnames"); } validate(from, query); } } /** * Test leftJoin method. */ @Test public void leftJoin() { String query = ROOT_FROM_QUERY; String alias; int aliasId = 1; final JpqlFromBuilder from = newInstance(); for (final Boolean newAlias : BooleanUtil.ALL) { aliasId = 1; // alias o1 alias = from.leftJoin(from.getRootAlias(), "manyToOneGroup", newAlias); query += "left join o.manyToOneGroup "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.manyToOneGroup"); } validate(from, query); // alias o2 alias = from.leftJoin(from.getRootAlias(), "oneToOneGroup", newAlias); query += "left join o.oneToOneGroup "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.oneToOneGroup"); } validate(from, query); // alias o3 alias = from.leftJoin(from.getRootAlias(), "manyToManyGroups", newAlias); query += "left join o.manyToManyGroups "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.manyToManyGroups"); } validate(from, query); // alias o4 alias = from.leftJoin(from.getRootAlias(), "surnames", newAlias); query += "left join o.surnames "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.surnames"); } validate(from, query); } } /** * Test leftJoinFetch method. */ @Test public void leftJoinFetch() { String query = ROOT_FROM_QUERY; String alias; int aliasId = 1; final JpqlFromBuilder from = newInstance(); for (final Boolean newAlias : BooleanUtil.ALL) { aliasId = 1; // alias o1 alias = from.leftJoinFetch(from.getRootAlias(), "manyToOneGroup", newAlias); query += "left join fetch o.manyToOneGroup "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.manyToOneGroup"); } validate(from, query); // alias o2 alias = from.leftJoinFetch(from.getRootAlias(), "oneToOneGroup", newAlias); query += "left join fetch o.oneToOneGroup "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.oneToOneGroup"); } validate(from, query); // alias o3 alias = from.leftJoinFetch(from.getRootAlias(), "manyToManyGroups", newAlias); query += "left join fetch o.manyToManyGroups "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.manyToManyGroups"); } validate(from, query); // alias o4 alias = from.leftJoinFetch(from.getRootAlias(), "surnames", newAlias); query += "left join fetch o.surnames "; if (newAlias) { Assert.assertEquals(alias, ROOT_ALIAS + aliasId++); query += alias + " "; } else { Assert.assertEquals(alias, "o.surnames"); } validate(from, query); } } }
34.427918
91
0.529944
980d5a1f34dabf2750e5aca2429cb40c1704cee8
890
package ui.ex1.screen.facets.lookupscreenfacet; import io.jmix.ui.component.TextField; import io.jmix.ui.screen.Install; import io.jmix.ui.screen.Screen; import io.jmix.ui.screen.UiController; import io.jmix.ui.screen.UiDescriptor; import org.springframework.beans.factory.annotation.Autowired; import ui.ex1.entity.Customer; import java.util.Collection; @UiController("sample_LookupScreenFacetScreen") @UiDescriptor("lookup-screen-facet-screen.xml") public class LookupScreenFacetScreen extends Screen { // tag::select-handler[] @Autowired private TextField<String> userField; @Install(to = "lookupScreen", subject = "selectHandler") private void lookupScreenSelectHandler(Collection<Customer> collection) { if (!collection.isEmpty()) { userField.setValue(collection.iterator().next().getEmail()); } } // end::select-handler[] }
31.785714
77
0.746067
3d69b6b1b8a8faf412c5f0e49df4cf88ea8dd788
3,248
/* * Copyright 2017 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.springframework.cloud.stream.binder.kinesis.properties; import org.springframework.boot.context.properties.ConfigurationProperties; /** * * @author Peter Oates * @author Artem Bilan * @author Jacob Severson * */ @ConfigurationProperties(prefix = "spring.cloud.stream.kinesis.binder") public class KinesisBinderConfigurationProperties { private String[] headers = new String[] {}; private int describeStreamBackoff = 1000; private int describeStreamRetries = 50; private boolean autoAddShards = false; private int minShardCount = 1; private Checkpoint checkpoint = new Checkpoint(); public String[] getHeaders() { return this.headers; } public void setHeaders(String... headers) { this.headers = headers; } public int getDescribeStreamBackoff() { return this.describeStreamBackoff; } public void setDescribeStreamBackoff(int describeStreamBackoff) { this.describeStreamBackoff = describeStreamBackoff; } public int getDescribeStreamRetries() { return this.describeStreamRetries; } public void setDescribeStreamRetries(int describeStreamRetries) { this.describeStreamRetries = describeStreamRetries; } public boolean isAutoAddShards() { return this.autoAddShards; } public void setAutoAddShards(boolean autoAddShards) { this.autoAddShards = autoAddShards; } public int getMinShardCount() { return this.minShardCount; } public void setMinShardCount(int minShardCount) { this.minShardCount = minShardCount; } public Checkpoint getCheckpoint() { return this.checkpoint; } public void setCheckpoint(Checkpoint checkpoint) { this.checkpoint = checkpoint; } public static class Checkpoint { private String table = "checkpoint"; private long readCapacity = 1L; private long writeCapacity = 1L; private int createDelay = 1; private int createRetries = 25; public String getTable() { return this.table; } public void setTable(String table) { this.table = table; } public long getReadCapacity() { return this.readCapacity; } public void setReadCapacity(long readCapacity) { this.readCapacity = readCapacity; } public long getWriteCapacity() { return this.writeCapacity; } public void setWriteCapacity(long writeCapacity) { this.writeCapacity = writeCapacity; } public int getCreateDelay() { return this.createDelay; } public void setCreateDelay(int createDelay) { this.createDelay = createDelay; } public int getCreateRetries() { return this.createRetries; } public void setCreateRetries(int createRetries) { this.createRetries = createRetries; } } }
22.246575
75
0.744458
9b7e5b7e7c92999f9133e6986c51f43c431b20e2
858
package com.hjay.tmall.Entity.Implement; /* CREATE TABLE productimage ( id int(11) NOT NULL AUTO_INCREMENT, pid int(11) DEFAULT NULL, type varchar(255) DEFAULT NULL, PRIMARY KEY (id), CONSTRAINT fk_productimage_product FOREIGN KEY (pid) REFERENCES product (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; */ import com.hjay.tmall.Entity.Bean; public class ProductImage extends Bean { private int id; private Product product; private String type; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } }
20.428571
78
0.645688
305cfe024f87e1b6717112b0fb63b1f592f0ea03
800
/** * Copyright (C) 2016 EDIT * European Distributed Institute of Taxonomy * http://www.e-taxonomy.eu * * The contents of this file are subject to the Mozilla Public License Version 1.1 * See LICENSE.TXT at the top of this package for the full license terms. */ package org.cybertaxonomy.utis.store; import java.net.URI; import java.util.Date; import java.util.List; import org.cybertaxonomy.utis.checklist.DRFChecklistException; /** * @author a.kohlbecker * @date Nov 9, 2016 * */ public interface ResourceProvider { /** * @param lastUpdated The date time when the data store was last updated with the resources from the provider * * @return * @throws DRFChecklistException */ public List<URI> getResources(Date lastUpdated) throws DRFChecklistException; }
24.242424
113
0.72875
61fa44d70d96057b239a4e4040dcd0d199b0fef1
2,146
/* * This is the MIT license, see also http://www.opensource.org/licenses/mit-license.html * * Copyright (c) 2001 Brian Pitcher * * 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. */ // $Header: /home/andrew/Projects/penguincoder/cvs/WebLech/weblech/spider/URLToDownload.java,v 1.1 2004/03/07 20:51:05 mercury Exp $ package weblech.spider; import java.net.URL; public class URLToDownload implements java.io.Serializable { private final URL url; private final URL referer; private final int depth; public URLToDownload(URL url, int depth) { this(url, null, depth); } public URLToDownload(URL url, URL referer, int depth) { this.url = url; this.referer = referer; this.depth = depth; } public URL getURL() { return url; } public URL getReferer() { return referer; } public int getDepth() { return depth; } public String toString() { return url + ", referer " + referer + ", depth " + depth; } }
31.101449
133
0.671948
b9c00cf42222adf0645598f76ce7ea2330f1a227
2,996
package com.lanking.uxb.service.adminSecurity.api.impl; import java.util.Collection; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.google.common.collect.Lists; import com.lanking.cloud.component.db.support.hibernate.Repo; import com.lanking.cloud.domain.support.common.auth.ConsoleMenuEntity; import com.lanking.cloud.sdk.bean.Status; import com.lanking.cloud.sdk.data.Params; import com.lanking.cloud.sdk.util.CollectionUtils; import com.lanking.uxb.service.adminSecurity.api.ConsoleMenuService; import com.lanking.uxb.service.adminSecurity.form.ConsoleMenuForm; /** * @author xinyu.zhou * @since V2.1 */ @Service @Transactional(readOnly = true) public class ConsoleMenuServiceImpl implements ConsoleMenuService { @Autowired @Qualifier("ConsoleMenuEntityRepo") private Repo<ConsoleMenuEntity, Long> repo; @Override @Transactional(readOnly = false) public ConsoleMenuEntity save(ConsoleMenuForm form) { ConsoleMenuEntity consoleMenuEntity = null; if (form.getId() == null) { consoleMenuEntity = new ConsoleMenuEntity(); consoleMenuEntity.setpId(form.getpId()); consoleMenuEntity.setStatus(Status.ENABLED); consoleMenuEntity.setSystemId(form.getSystemId()); consoleMenuEntity.setCreateAt(new Date()); } else { consoleMenuEntity = repo.get(form.getId()); consoleMenuEntity.setUpdateAt(new Date()); } consoleMenuEntity.setName(form.getName()); consoleMenuEntity.setUrl(form.getUrl()); return repo.save(consoleMenuEntity); } @Override @Transactional(readOnly = false) public ConsoleMenuEntity update(ConsoleMenuForm form) { ConsoleMenuEntity consoleMenuEntity = repo.get(form.getId()); consoleMenuEntity.setName(form.getName()); consoleMenuEntity.setUpdateAt(new Date()); consoleMenuEntity.setUrl(form.getUrl()); return repo.save(consoleMenuEntity); } @Override @Transactional(readOnly = false) public void delete(Long id) { ConsoleMenuEntity consoleMenuEntity = repo.get(id); consoleMenuEntity.setStatus(Status.DELETED); } @Override public List<ConsoleMenuEntity> getBySystem(Long systemId, Status status) { if (systemId == null) { return Lists.newArrayList(); } Params params = Params.param("systemId", systemId); if (status != null) { params.put("status", status.getValue()); } return repo.find("$getBySystem", params).list(); } @Override public List<ConsoleMenuEntity> findByUser(Long systemId, Long userId) { return repo.find("$getByUser", Params.param("userId", userId).put("systemId", systemId)).list(); } @Override @Transactional public void updateStatus(Collection<Long> ids, Status status) { if (CollectionUtils.isNotEmpty(ids)) { repo.execute("$updateStatus", Params.param("ids", ids).put("status", status.getValue())); } } }
32.215054
98
0.76769
3de69598a4af18f03626a25f71c862807dd045e2
1,206
package com.raj.moh.sanju.vines.singlevideoinforesponse; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.raj.moh.sanju.vines.pojo.channellistresponse.Thumbnails; public class Snippet { @SerializedName("publishedAt") @Expose private String publishedAt; @SerializedName("title") @Expose private String title; @SerializedName("description") @Expose private String description; @SerializedName("thumbnails") @Expose private Thumbnails thumbnails; public Thumbnails getThumbnails() { return thumbnails; } public void setThumbnails(Thumbnails thumbnails) { this.thumbnails = thumbnails; } public String getPublishedAt() { return publishedAt; } public void setPublishedAt(String publishedAt) { this.publishedAt = publishedAt; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
22.754717
67
0.680763
ef5e024bc60f38aa340a207a6d76b5baa89c5833
296
package com.deyatech.admin.mapper; import com.deyatech.admin.entity.MetadataCategory; import com.deyatech.common.base.BaseMapper; /** * <p> * 元数据分类 Mapper 接口 * </p> * * @Author lee. * @since 2019-08-07 */ public interface MetadataCategoryMapper extends BaseMapper<MetadataCategory> { }
17.411765
78
0.733108
99a580ae401de9211488a50c35ef7296012be5d0
823
package gov.noaa.models.gridpoints; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.google.gson.GsonBuilder; import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import gov.noaa.Feature; @EqualsAndHashCode(callSuper = true) @NoArgsConstructor @Data @JsonIgnoreProperties(ignoreUnknown = true) public class Forecast extends Feature { private List<String> context; private GridpointsProperties properties; public void setGeometry(org.geojson.Polygon geometry) { this.geometry = geometry; } public String toJson(boolean pretty){ GsonBuilder gsonbuilder = new GsonBuilder(); if(pretty) gsonbuilder.setPrettyPrinting(); return gsonbuilder.serializeSpecialFloatingPointValues().create().toJson(this); } }
25.71875
91
0.784933
08f8ed8d1a588b18d19beece0e7d1a92d32ae0f1
1,250
package edu.stanford.math.plex4.test_utility; import cern.colt.Timer; /** * This class contains static methods for measuring time intervals. It is exists * for convenience purposes so that one doesn't have to instantiate an object whenever * one wishes to measure a time interval. * * @author Andrew Tausz * */ public class Timing { private static Timer timer; private static void initialize() { timer = new Timer(); } public static void restart() { if (timer == null) { initialize(); } timer.reset(); timer.start(); } public static void stop() { if (timer == null) { initialize(); } timer.stop(); } public static void reset() { if (timer == null) { initialize(); } timer.reset(); } public static float seconds() { if (timer == null) { initialize(); } return timer.seconds(); } public static void stopAndDisplay() { if (timer == null) { initialize(); } timer.stop(); System.out.println("Elapsed time (s): " + timer.seconds()); timer.reset(); } public static void stopAndDisplay(String label) { if (timer == null) { initialize(); } timer.stop(); System.out.println("Elapsed time (s) for " + label + ": " + timer.seconds()); timer.reset(); } }
18.382353
86
0.6312
1f6e6dd5907c70b1eeb21006bc4d43079a6d78b9
5,514
/** */ package src.main.gov.va.vha09.grecc.raptat.gg.oneoffs.io; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import src.main.gov.va.vha09.grecc.raptat.gg.datastructures.annotationcomponents.AnnotatedPhrase; import src.main.gov.va.vha09.grecc.raptat.gg.datastructures.annotationcomponents.AnnotationGroup; import src.main.gov.va.vha09.grecc.raptat.gg.datastructures.annotationcomponents.ConceptRelation; import src.main.gov.va.vha09.grecc.raptat.gg.datastructures.annotationcomponents.RaptatAttribute; import src.main.gov.va.vha09.grecc.raptat.gg.textanalysis.RaptatDocument; /** @author Glenn Gobbel */ public class SQLAnnotationRetriever { /* Class used to build AnnotatedPhrase object from fields in SQL database */ private class AnnotatedPhraseFields { private final String mentionID; private final String startOffset; private final String endOffset; private final String phraseText; private final List<ConceptRelation> conceptRelations; private final List<RaptatAttribute> attributes; /** * @param mentionID * @param startOffset * @param endOffset * @param phraseText * @param conceptRelations * @param attributes */ public AnnotatedPhraseFields(String mentionID, String startOffset, String endOffset, String phraseText, List<ConceptRelation> conceptRelations, List<RaptatAttribute> attributes) { super(); this.mentionID = mentionID; this.startOffset = startOffset; this.endOffset = endOffset; this.phraseText = phraseText; this.conceptRelations = conceptRelations; this.attributes = attributes; } } /* Class used to build ConceptRelation object from fields */ private class ConceptRelationFields { private final String conceptRelationID; private final String conceptRelationName; private final List<String> idsOfRelatedAnnotations; /** * @param conceptRelationID * @param conceptRelationName * @param idsOfRelatedAnnotations */ public ConceptRelationFields(String conceptRelationID, String conceptRelationName, List<String> idsOfRelatedAnnotations) { super(); this.conceptRelationID = conceptRelationID; this.conceptRelationName = conceptRelationName; this.idsOfRelatedAnnotations = idsOfRelatedAnnotations; } } /* Class used to build RaptatAttribute object from fields */ private class RaptatAttributeFields { private final String id; private final String typeName; private final List<String> values; /** * @param id * @param typeName * @param values */ public RaptatAttributeFields(String id, String typeName, List<String> values) { super(); this.id = id; this.typeName = typeName; this.values = values; } } /* Class used to build RaptatDocument object from fields in SQL database */ private class RaptatDocumentFields { private final String textSource; private RaptatDocumentFields(String textSource) { this.textSource = textSource; } private RaptatDocument getRaptatDocumentFromFields() { RaptatDocument document = new RaptatDocument(); document.setTextSourcePath(this.textSource); return document; } } /* * General, unspecified object for storing the information used to connect to a database */ private SQLAnnotationWriter.DbConnectionObject databaseConnectionInformation; /** */ public SQLAnnotationRetriever() {} /* * The databaseConnectionInformation is a placeholder used to represent all the needed information * to connect to the database for retrieving annotations */ public SQLAnnotationRetriever( SQLAnnotationWriter.DbConnectionObject databaseConnectionInformation) { this.databaseConnectionInformation = databaseConnectionInformation; } /* * Implement this method to set up a connection to the database and make sure it is valid. If so, * return true. If not, return false; */ public boolean connectToDatabase() { boolean validConnection = false; return validConnection; } public Set<AnnotationGroup> getNextAnnotationGroupBatch() { /* Set the number of groups you want to return as a set */ int returnSetSize = 100; Set<AnnotationGroup> groupsToReturn = new HashSet<>(returnSetSize); for (int groupIndex = 0; groupIndex < returnSetSize; groupIndex++) { AnnotationGroup annotationGroup = getNextAnnotationGroup(); groupsToReturn.add(annotationGroup); } return groupsToReturn; } /** * May 29, 2018 * * @return */ private String getDocumentTextSource() { String textSource = "Name of document that was annotated"; return textSource; } /** * May 29, 2018 * * @return */ private AnnotationGroup getNextAnnotationGroup() { String textSource = getDocumentTextSource(); RaptatDocument document = new RaptatDocument(); document.setTextSourcePath(textSource); List<AnnotatedPhrase> annotatedPhrases = getNextAnnotationGroupPhrases(); return null; } /** * May 29, 2018 * * @return */ private List<AnnotatedPhrase> getNextAnnotationGroupPhrases() { List<AnnotatedPhrase> annotatedPhrases = new ArrayList<>(); return annotatedPhrases; } /** * May 29, 2018 * * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }
27.708543
100
0.714908
6c9bfb4b6c725af9b12aea2e2c2820dd257c5b6e
2,959
package com.twu.biblioteca; import com.twu.biblioteca.exceptions.BookNonexistentException; import com.twu.biblioteca.exceptions.BookUnavailableException; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; public class LibraryTest { @Before public void resetLibrary() { Library.reset(); } //TODO looks like an assertion is missing @Test public void libraryCanAddBooks() { Book newBook = new Book(); Library.addBook(newBook); } @Test public void libraryCanBeReset() { addTestBooks(); Library.reset(); assertThat(Library.getBookList().size(), is(0)); } @Test public void libraryCanReturnListOfBooks() { Book book1 = new Book(); book1.setAuthor("Pablo"); book1.setTitle("Book 1"); book1.setYear(2018); Book book2 = new Book(); book1.setAuthor("Mengmeng"); book1.setTitle("Book 2"); book1.setYear(2018); Library.addBook(book1); Library.addBook(book2); ArrayList<Book> expected = new ArrayList<>(); expected.add(book1); expected.add(book2); List<Book> books = Library.getBookList(); assertThat(books, is(expected)); } @Test public void libraryCanLoanOutAvailableBook() throws BookUnavailableException, BookNonexistentException { Book book1 = new Book(); book1.setAuthor("Pablo"); book1.setTitle("Book 1"); book1.setYear(2018); Library.addBook(book1); Book loanedBook = Library.loanBook(0); assertThat(loanedBook, is(book1)); assertThat(loanedBook.isAvailable(), is(false)); } @Test(expected = BookUnavailableException.class) public void libraryCannotLoanOutUnavailableBook() throws BookNonexistentException, BookUnavailableException { Book book1 = new Book(); book1.setAuthor("Pablo"); book1.setTitle("Book 1"); book1.setYear(2018); book1.setAvailable(false); Library.addBook(book1); Library.loanBook(0); } @Test(expected = BookNonexistentException.class) public void libraryCannotLoanOutNonexistentBook() throws BookNonexistentException, BookUnavailableException { Library.loanBook(0); } static void addTestBooks() { Book book0 = new Book(); book0.setAuthor("Roy"); book0.setTitle("Book 0"); book0.setYear(2004); Library.addBook(book0); Book book1 = new Book(); book1.setAuthor("Paul"); book1.setTitle("Book 1"); book1.setYear(2018); Library.addBook(book1); Book book2 = new Book(); book2.setAuthor("Mengmeng"); book2.setTitle("Book 2"); book2.setYear(2018); Library.addBook(book2); } }
27.398148
113
0.634336
e0f9e348b1b9cd83f60535f64a6207974fc0f4cf
2,684
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.drill.exec.planner.common; import java.util.BitSet; import java.util.List; import org.apache.drill.exec.planner.cost.DrillCostBase.DrillCostFactory; import org.apache.calcite.plan.RelOptPlanner; import org.apache.calcite.rel.core.Aggregate; import org.apache.calcite.rel.core.AggregateCall; import org.apache.calcite.rel.InvalidRelException; import org.apache.calcite.rel.RelNode; import org.apache.calcite.util.ImmutableBitSet; import org.apache.calcite.plan.RelOptCluster; import org.apache.calcite.plan.RelOptCost; import org.apache.calcite.plan.RelTraitSet; /** * Base class for logical and physical Aggregations implemented in Drill */ public abstract class DrillAggregateRelBase extends Aggregate implements DrillRelNode { public DrillAggregateRelBase(RelOptCluster cluster, RelTraitSet traits, RelNode child, boolean indicator, ImmutableBitSet groupSet, List<ImmutableBitSet> groupSets, List<AggregateCall> aggCalls) throws InvalidRelException { super(cluster, traits, child, indicator, groupSet, groupSets, aggCalls); } @Override public RelOptCost computeSelfCost(RelOptPlanner planner) { for (AggregateCall aggCall : getAggCallList()) { String name = aggCall.getAggregation().getName(); // For avg, stddev_pop, stddev_samp, var_pop and var_samp, the ReduceAggregatesRule is supposed // to convert them to use sum and count. Here, we make the cost of the original functions high // enough such that the planner does not choose them and instead chooses the rewritten functions. if (name.equals("AVG") || name.equals("STDDEV_POP") || name.equals("STDDEV_SAMP") || name.equals("VAR_POP") || name.equals("VAR_SAMP")) { return ((DrillCostFactory)planner.getCostFactory()).makeHugeCost(); } } return ((DrillCostFactory)planner.getCostFactory()).makeTinyCost(); } }
44
123
0.762668
b2ea13dda8ae0eb3fca3e346736828cbf126a1dc
2,334
package com.qvalent.quickstreamapi.model.response; import com.qvalent.quickstreamapi.model.common.Status; public class Customer { private final String customerId; private final String customerName; private final String supplierBusinessCode; private final String customerNumber; private final Status status; private final String phoneNumber; private final String emailAddress; private final NotificationMedium preferredNotificationMedium; private final Address address; private final Links links; public Customer() { customerId = null; customerName = null; supplierBusinessCode = null; customerNumber = null; status = null; phoneNumber = null; emailAddress = null; preferredNotificationMedium = null; address = null; links = null; } public String getCustomerId() { return customerId; } public String getCustomerName() { return customerName; } public String getSupplierBusinessCode() { return supplierBusinessCode; } public String getCustomerNumber() { return customerNumber; } public Status getStatus() { return status; } public String getPhoneNumber() { return phoneNumber; } public String getEmailAddress() { return emailAddress; } public NotificationMedium getPreferredNotificationMedium() { return preferredNotificationMedium; } public Address getAddress() { return address; } public Links getLinks() { return links; } @Override public String toString() { return "Customer [customerId=" + customerId + ", customerName=" + customerName + ", supplierBusinessCode=" + supplierBusinessCode + ", customerNumber=" + customerNumber + ", status=" + status + ", phoneNumber=" + phoneNumber + ", emailAddress=" + emailAddress + ", preferredNotificationMedium=" + preferredNotificationMedium + ", address=" + address + ", links=" + links + "]"; } }
24.3125
81
0.584404
7e0b743d40c9105db4ae7cacac63c755c1bf283a
9,389
/* * Class: RandomStreamWithCache * Description: random stream whose uniforms are cached for more efficiency * Environment: Java * Software: SSJ * Copyright (C) 2001 Pierre L'Ecuyer and Universite de Montreal * Organization: DIRO, Universite de Montreal * @author * @since * * * 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 umontreal.ssj.rng; import cern.colt.list.DoubleArrayList; /** * This class represents a random stream whose uniforms are cached for more * efficiency when using common random numbers. An object from this class is * constructed with a reference to a @ref RandomStream instance used to get * the random numbers. These numbers are stored in an internal array to be * retrieved later. The dimension of the array increases as the values are * generated. If the #nextDouble method is called after the object is reset, * it gives back the cached values instead of computing new ones. If the * cache is exhausted before the stream is reset, new values are computed, * and added to the cache. * * Such caching allows for a better performance with common random numbers, * when generating uniforms is time-consuming. It can also help with * restoring the simulation to a certain state without setting * stream-specific seeds. However, using such caching may lead to memory * problems if a large quantity of random numbers are needed. * * <div class="SSJ-bigskip"></div> */ public class RandomStreamWithCache implements RandomStream { private RandomStream stream; private DoubleArrayList values; private int index = 0; private boolean caching = true; /** * Constructs a new cached random stream with internal stream `stream`. * @param stream the random stream whose uniforms are cached. * @exception NullPointerException if `stream` is `null`. */ public RandomStreamWithCache (RandomStream stream) { if (stream == null) throw new NullPointerException ("The given random stream cannot be null"); this.stream = stream; values = new DoubleArrayList(); } /** * Constructs a new cached random stream with internal stream `stream`. * The `initialCapacity` parameter is used to set the initial capacity * of the internal array which can grow as needed; it does not limit * the total size of the cache. * @param stream the random stream whose values are cached. * @param initialCapacity the initial capacity of the cache. * @exception NullPointerException if `stream` is `null`. */ public RandomStreamWithCache (RandomStream stream, int initialCapacity) { if (stream == null) throw new NullPointerException ("The given random stream cannot be null"); this.stream = stream; values = new DoubleArrayList (initialCapacity); } /** * Determines if the random stream is caching values, default being * `true`. When caching is turned OFF, the #nextDouble method simply * calls the corresponding method on the internal random stream, * without storing the generated uniforms. * @return the caching indicator. */ public boolean isCaching() { return caching; } /** * Sets the caching indicator to `caching`. If caching is turned OFF, * this method calls #clearCache to clear the cached values. * @param caching the new value of the caching indicator. */ public void setCaching (boolean caching) { if (this.caching && !caching) clearCache(); this.caching = caching; } /** * Returns a reference to the random stream whose values are cached. * @return a reference to the random stream whose values are cached. */ public RandomStream getCachedStream() { return stream; } /** * Sets the random stream whose values are cached to `stream`. If the * stream is changed, the #clearCache method is called to clear the * cache. * @param stream the new random stream whose values will be * cached. * @exception NullPointerException if `stream` is `null`. */ public void setCachedStream (RandomStream stream) { if (stream == null) throw new NullPointerException ("The given random stream cannot be null"); if (stream == this.stream) return; this.stream = stream; clearCache(); } /** * Clears the cached values for this random stream. Any subsequent call * will then obtain new values from the internal stream. */ public void clearCache() { //values.clear(); // Keep the array previously returned by getCachedValues // intact to allow caching values for several // replications. values = new DoubleArrayList(); index = 0; } /** * Resets this random stream to recover values from the cache. * Subsequent calls to #nextDouble will return the cached uniforms * until all the values are returned. When the array of cached values * is exhausted, the internal random stream is used to generate new * values which are added to the internal array as well. This method is * equivalent to calling #setCacheIndex(int). */ public void initCache() { index = 0; } /** * Returns the total number of values cached by this random stream. * @return the total number of cached values. */ public int getNumCachedValues() { return values.size(); } /** * Return the index of the next cached value that will be returned by * the stream. If the cache is exhausted, the returned value * corresponds to the value returned by #getNumCachedValues, and a * subsequent call to #nextDouble will generate a new variate rather * than reading a previous one from the cache. If caching is disabled, * this always returns 0. * @return the index of the next cached value. */ public int getCacheIndex() { return index; } /** * Sets the index, in the cache, of the next value returned by * #nextDouble. If `newIndex` is 0, this is equivalent to calling * #initCache. If `newIndex` is #getNumCachedValues, subsequent calls * to #nextDouble will add new values to the cache. * @param newIndex the new index. * @exception IllegalArgumentException if `newIndex` is negative or * greater than or equal to the cache size. */ public void setCacheIndex (int newIndex) { if (newIndex < 0 || newIndex > values.size()) throw new IllegalArgumentException ("newIndex must not be negative or greater than the cache size"); index = newIndex; } /** * Returns an array list containing the values cached by this random * stream. * @return the array of cached values. */ public DoubleArrayList getCachedValues() { return values; } /** * Sets the array list containing the cached values to `values`. This * resets the cache index to the size of the given array. * @param values the array list of cached values. * @exception NullPointerException if `values` is `null`. */ public void setCachedValues (DoubleArrayList values) { if (values == null) throw new NullPointerException(); this.values = values; index = values.size(); } public void resetStartStream () { stream.resetStartStream(); } public void resetStartSubstream () { stream.resetStartSubstream(); } public void resetNextSubstream () { stream.resetNextSubstream(); } public double nextDouble () { if (!caching) return stream.nextDouble(); else if (index >= values.size()) { double v = stream.nextDouble(); values.add (v); ++index; return v; } else return values.getQuick (index++); } public void nextArrayOfDouble (double[] u, int start, int n) { if (!caching) { stream.nextArrayOfDouble (u, start, n); return; } int remainingValues = values.size() - index; if (remainingValues < 0) remainingValues = 0; int ncpy = Math.min (n, remainingValues); if (ncpy > 0) { System.arraycopy (values.elements(), index, u, start, ncpy); index += ncpy; } int ngen = n - ncpy; if (ngen > 0) { stream.nextArrayOfDouble (u, start + ncpy, ngen); for (int i = ncpy; i < n; i++) { values.add (u[start + i]); ++index; } } } public int nextInt (int i, int j) { return i + (int) (nextDouble () * (j - i + 1)); } public void nextArrayOfInt (int i, int j, int[] u, int start, int n) { for (int x = start; x < start + n; x++) u[x] = nextInt (i, j); } }
34.391941
77
0.653637
a53858265d62fe7aff6ba9be29a1b5c5cb45f506
2,243
// // Ce fichier a été généré par l'implémentation de référence JavaTM Architecture for XML Binding (JAXB), v2.2.8-b130911.1802 // Voir <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Toute modification apportée à ce fichier sera perdue lors de la recompilation du schéma source. // Généré le : 2016.08.05 à 03:51:24 AM CEST // package uk.co.bbc.rd.bmx; import java.math.BigInteger; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; /** * <p> * Classe Java pour array_type complex type. * <p> * Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe. * * <pre> * &lt;complexType name="array_type"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="size" use="required" type="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "array_type") @XmlSeeAlso({ FilesType.class, LogMessagesType.class, UserCommentsType.class, AttributesType.class, LocatorsType.class, SegmentationType.class, VbiManifestType.class, DigibetaDropoutsType.class, AncManifestType.class, MaterialPackagesType.class, FileSourcePackagesType.class, TimecodeBreaksType.class, VtrErrorsType.class, TrackPackagesType.class, PhysicalSourcePackagesType.class, PseFailuresType.class, TracksType.class, IdentificationsType.class }) public class ArrayType { @XmlAttribute(name = "size", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger size; /** * Obtient la valeur de la propriété size. * @return * possible object is * {@link BigInteger } */ public BigInteger getSize() { return size; } /** * Définit la valeur de la propriété size. * @param value * allowed object is * {@link BigInteger } */ public void setSize(BigInteger value) { this.size = value; } }
33.984848
194
0.730272
19dc22804bc4554c623a0fdf25b42b12c6f91ecb
1,270
/* * File name: ArrayEval.java * * Programmer : Jake Botka * * Date: Aug 17, 2020 * */ package main.org.botka.utility.api.data.structures.arrays; /** * Utility class for array evaluations * * @author Jake Botka * */ public class ArrayEval { /** * * @param arr * @return */ public static double mean(double[] arr) { double answer = Double.NaN; if (arr != null) { double sum = 0.0; for (double d : arr) { sum += d; } answer = sum / (double) arr.length; } return answer; } /** * * @param arr * @return */ public static double min(double[] arr) { double min = Double.MIN_VALUE; return min; } /** * * @param arr * @return */ public static double max(double[] arr) { double max = Double.MAX_VALUE; return max; } /** * * @param arr * @param value * @return */ public boolean hasValue(Object[] arr, Object value) { if (arr != null && value != null) for (int i =0; i < arr.length; i++) if (arr[i].equals(value)) return true; return false; } /** * * @param arr * @return */ public static boolean hasNull(Object[] arr) { if (arr != null) for (int i = 0; i < arr.length; i++) { if (arr[i] == null) return true; } return false; } }
14.767442
58
0.558268
0c53936137796c065d1f031d2de0c9bd79bbb18b
7,413
package org.gearvrf.animation.keyframe; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import org.gearvrf.GVRBone; import org.gearvrf.GVRComponent; import org.gearvrf.GVRContext; import org.gearvrf.GVRMesh; import org.gearvrf.GVRRenderData; import org.gearvrf.GVRSceneObject; import org.gearvrf.utility.Log; import org.joml.Matrix4f; /** * Controls skeletal animation (skinning). */ public class GVRSkinningController extends GVRAnimationController { private static final String TAG = GVRSkinningController.class.getSimpleName(); protected GVRContext gvrContext; protected GVRSceneObject sceneRoot; protected SceneAnimNode animRoot; protected Map<String, SceneAnimNode> nodeByName; protected Map<GVRSceneObject, List<GVRBone>> boneMap; protected class SceneAnimNode { GVRSceneObject sceneObject; SceneAnimNode parent; List<SceneAnimNode> children; Matrix4f localTransform; Matrix4f globalTransform; int channelId; boolean noname; SceneAnimNode(GVRSceneObject sceneObject, SceneAnimNode parent) { this.sceneObject = sceneObject; this.parent = parent; children = new ArrayList<SceneAnimNode>(); localTransform = new Matrix4f(); globalTransform = new Matrix4f(); channelId = -1; noname = sceneObject.getName().equals(""); } } /** * Constructs the skeleton for a list of {@link GVRSceneObject}. * * @param sceneRoot The scene root. * @param animation The animation object. */ public GVRSkinningController(GVRSceneObject sceneRoot, GVRKeyFrameAnimation animation) { super(animation); this.sceneRoot = sceneRoot; nodeByName = new TreeMap<String, SceneAnimNode>(); boneMap = new HashMap<GVRSceneObject, List<GVRBone>>(); animRoot = createAnimationTree(sceneRoot, null); pruneTree(animRoot); MeshVisitor visitor = new MeshVisitor(); sceneRoot.forAllComponents(visitor, GVRRenderData.getComponentType()); } protected SceneAnimNode createAnimationTree(GVRSceneObject node, SceneAnimNode parent) { GVRSceneObject root = node; if (node.getName().equals("") && (node.getChildrenCount() == 1)) { GVRSceneObject child = node.getChildByIndex(0); if (child != null) { node.setName(child.getName()); child.setName(child.getName() + "-2"); root = child; } } SceneAnimNode internalNode = new SceneAnimNode(node, parent); // Find channel Id if (animation != null) { internalNode.channelId = animation.findChannel(node.getName()); } // Bind-pose local transform internalNode.localTransform.set(node.getTransform().getLocalModelMatrix4f()); internalNode.globalTransform.set(internalNode.localTransform); // Global transform if (parent != null) { parent.globalTransform.mul(internalNode.globalTransform, internalNode.globalTransform); } nodeByName.put(node.getName(), internalNode); for (GVRSceneObject child : root.getChildren()) { SceneAnimNode animChild = createAnimationTree(child, internalNode); internalNode.children.add(animChild); } return internalNode; } private class MeshVisitor implements GVRSceneObject.ComponentVisitor { public boolean visit(GVRComponent c) { GVRRenderData rd = (GVRRenderData) c; GVRMesh mesh = rd.getMesh(); if (mesh != null) { setupBone(rd.getOwnerObject()); } return true; } } protected void setupBone(GVRSceneObject node) { GVRMesh mesh; if (node.getRenderData() != null && (mesh = node.getRenderData().getMesh()) != null) { Log.v(TAG, "setupBone checking mesh with %d vertices", mesh.getVertexBuffer().getVertexCount()); for (GVRBone bone : mesh.getBones()) { bone.setSceneObject(node); GVRSceneObject skeletalNode = sceneRoot.getSceneObjectByName(bone.getName()); if (skeletalNode == null) { Log.w(TAG, "what? cannot find the skeletal node for bone: %s", bone.toString()); continue; } // Create look-up table for bones List<GVRBone> boneList = boneMap.get(skeletalNode); if (boneList == null) { boneList = new ArrayList<GVRBone>(); boneMap.put(skeletalNode, boneList); } boneList.add(bone); } } } /** * Update bone transforms for the specified tick. */ @Override protected void animateImpl(float animationTick) { Matrix4f[] animationTransform = animation.getTransforms(animationTick); updateTransforms(animRoot, new Matrix4f(), animationTransform); for (Entry<GVRSceneObject, List<GVRBone>> ent : boneMap.entrySet()) { // Transform all bone splits (a bone can be split into multiple instances if they influence // different meshes) SceneAnimNode node = nodeByName.get(ent.getKey().getName()); if (node == null) { return; } for (GVRBone bone : ent.getValue()) { updateBoneMatrices(bone, node); } } } protected void updateTransforms(SceneAnimNode node, Matrix4f parentTransform, Matrix4f[] animationTransform) { if (node.channelId != -1) { node.localTransform.set(animationTransform[node.channelId]); } else { // Default local transform node.localTransform.set(node.sceneObject.getTransform().getLocalModelMatrix4f()); } parentTransform.mul(node.localTransform, node.globalTransform); for (SceneAnimNode child : node.children) { updateTransforms(child, node.globalTransform, animationTransform); } } protected void updateBoneMatrices(GVRBone bone, SceneAnimNode node) { Matrix4f finalMatrix = new Matrix4f().set(bone.getOffsetMatrix()); node.globalTransform.mul(finalMatrix, finalMatrix); Matrix4f globalInverse = new Matrix4f().set(bone.getSceneObject().getTransform().getModelMatrix4f()).invert(); globalInverse.mul(finalMatrix, finalMatrix); bone.setFinalTransformMatrix(finalMatrix); } /* Returns true if the subtree should be kept */ protected boolean pruneTree(SceneAnimNode node) { boolean keep = node.channelId != -1; if (keep) { return keep; } Iterator<SceneAnimNode> iter = node.children.iterator(); while (iter.hasNext()) { SceneAnimNode child = iter.next(); boolean keepChild = pruneTree(child); keep |= keepChild; if (!keepChild) { iter.remove(); } } return keep; } }
33.849315
118
0.612573
e6c4929e1941f87f0dba372cbd6010f39415679a
10,209
/* * Copyright (C) 1999-2011 University of Connecticut Health Center * * Licensed under the MIT License (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.opensource.org/licenses/mit-license.php */ package cbit.vcell.units; import java.io.Serializable; import java.util.HashMap; import org.vcell.util.Matchable; import cbit.vcell.matrix.RationalExp; import cbit.vcell.matrix.RationalNumber; import cbit.vcell.parser.ExpressionException; import cbit.vcell.parser.ExpressionUtils; import cbit.vcell.parser.RationalExpUtils; import cbit.vcell.units.parser.UnitSymbol; public class VCUnitDefinition implements Matchable, Serializable{ private InternalUnitDefinition fieldUnitDefinition = null; private VCUnitSystem fieldVCUnitSystem = null; private UnitSymbol fieldUnitSymbol = null; // // each unit should be a singleton within the unit system it came from // because they are singletons, it is ok for each unit to cache it's own derived units locally (for divide, mult, power). // private transient HashMap<VCUnitDefinition, VCUnitDefinition> divideByMap = null; private transient HashMap<VCUnitDefinition, VCUnitDefinition> multiplyByMap = null; private transient HashMap<ucar.units_vcell.RationalNumber, VCUnitDefinition> powerMap = null; VCUnitDefinition(InternalUnitDefinition unitDefinition, VCUnitSystem vcUnitSystem, UnitSymbol unitsymbol) { super(); this.fieldUnitDefinition = unitDefinition; this.fieldVCUnitSystem = vcUnitSystem; this.fieldUnitSymbol = unitsymbol; } public String getSymbol() { return fieldUnitSymbol.getUnitSymbol(); } public String getSymbolUnicode() { return fieldUnitSymbol.getUnitSymbolUnicode(); } public String getSymbolHtml() { return fieldUnitSymbol.getUnitSymbolHtml(); } public VCUnitDefinition getInverse() { double newNumericScale = 1.0/fieldUnitSymbol.getNumericScale(); return getUnit(newNumericScale,getSymbolRationalExpWithoutNumericScale(this.fieldUnitSymbol).inverse()); } public VCUnitDefinition divideBy(VCUnitDefinition childUnit) { VCUnitDefinition ratioUnit = null; if (divideByMap != null){ ratioUnit = divideByMap.get(childUnit); if (ratioUnit != null){ return ratioUnit; } }else{ divideByMap = new HashMap<VCUnitDefinition, VCUnitDefinition>(); } double newNumericScale = fieldUnitSymbol.getNumericScale()/childUnit.fieldUnitSymbol.getNumericScale(); RationalExp thisNonnumericUnit = getSymbolRationalExpWithoutNumericScale(this.fieldUnitSymbol); RationalExp otherNonnumericUnit = getSymbolRationalExpWithoutNumericScale(childUnit.fieldUnitSymbol); ratioUnit = getUnit(newNumericScale, thisNonnumericUnit.div(otherNonnumericUnit)); divideByMap.put(childUnit,ratioUnit); return ratioUnit; } public boolean isTBD() { return fieldUnitDefinition.isTBD(); } private static RationalExp getSymbolRationalExpWithoutNumericScale(UnitSymbol unitSymbol) { String unitString = unitSymbol.getUnitSymbolAsInfixWithoutFloatScale(); RationalExp rationalExp; try { rationalExp = RationalExpUtils.getRationalExp(new cbit.vcell.parser.Expression(unitString)); } catch (ExpressionException e) { e.printStackTrace(); throw new RuntimeException("unit exception "+e.getMessage()); } return rationalExp; } private VCUnitDefinition getUnit(double numericScale, RationalExp rationalExp){ if (numericScale==1.0){ UnitSymbol unitSymbol = new UnitSymbol(rationalExp.infixString()); return fieldVCUnitSystem.getInstance(unitSymbol.getUnitSymbol()); }else{ UnitSymbol unitSymbol = new UnitSymbol(rationalExp.infixString()); return fieldVCUnitSystem.getInstance(numericScale + " " + unitSymbol.getUnitSymbol()); } } public VCUnitDefinition raiseTo(ucar.units_vcell.RationalNumber rationalNumber) { VCUnitDefinition powerUnit = null; if (powerMap != null){ powerUnit = powerMap.get(rationalNumber); if (powerUnit != null){ return powerUnit; } }else{ powerMap = new HashMap<ucar.units_vcell.RationalNumber, VCUnitDefinition>(); } RationalExp origRationalExpWithoutNumericScale = getSymbolRationalExpWithoutNumericScale(fieldUnitSymbol); RationalExp rationalExpWithoutNumericScale = origRationalExpWithoutNumericScale; // // if a negative exponent, take reciprocal of the base and transform to a positive exponent // if (rationalNumber.doubleValue()<0){ rationalExpWithoutNumericScale = rationalExpWithoutNumericScale.inverse(); rationalNumber = rationalNumber.minus(); } // // if the exponent is integer valued, raise power by repeated multiplication // if (rationalNumber.intValue()==rationalNumber.doubleValue()){ for (int i=1;i<Math.abs(rationalNumber.intValue());i++){ rationalExpWithoutNumericScale = rationalExpWithoutNumericScale.mult(origRationalExpWithoutNumericScale); } double newNumericScale = Math.pow(fieldUnitSymbol.getNumericScale(),rationalNumber.doubleValue()); powerUnit = getUnit(newNumericScale, rationalExpWithoutNumericScale); powerMap.put(rationalNumber, powerUnit); return powerUnit; }else{ throw new RuntimeException("raiseTo( non-integer ) not yet supported"); } } public VCUnitDefinition multiplyBy(VCUnitDefinition unit) { VCUnitDefinition productUnit = null; if (multiplyByMap != null){ productUnit = multiplyByMap.get(unit); if (productUnit != null){ return productUnit; } }else{ multiplyByMap = new HashMap<VCUnitDefinition, VCUnitDefinition>(); } double newNumericScale = fieldUnitSymbol.getNumericScale() * unit.fieldUnitSymbol.getNumericScale(); productUnit = getUnit(newNumericScale, getSymbolRationalExpWithoutNumericScale(this.fieldUnitSymbol).mult(getSymbolRationalExpWithoutNumericScale(unit.fieldUnitSymbol))); multiplyByMap.put(unit, productUnit); return productUnit; } public boolean compareEqual(Matchable matchable) { if (this == matchable){ return true; } if ( !(matchable instanceof VCUnitDefinition) ) { return false; } VCUnitDefinition matchableUnitDefn = (VCUnitDefinition)matchable; if (!this.fieldUnitDefinition.compareEqual(matchableUnitDefn.fieldUnitDefinition)) { return false; } if (!fieldUnitSymbol.getUnitSymbol().equals(matchableUnitDefn.fieldUnitSymbol.getUnitSymbol())) { return false; } return true; } public boolean isCompatible(VCUnitDefinition targetUnit) { return fieldUnitDefinition.isCompatible(targetUnit.fieldUnitDefinition); } public double convertTo(double conversionFactor, VCUnitDefinition targetUnit) { return fieldUnitDefinition.convertTo(conversionFactor, targetUnit.fieldUnitDefinition); } public ucar.units_vcell.Unit getUcarUnit() { return fieldUnitDefinition.getUcarUnit(); } public String toString(){ return getSymbol(); } public boolean isEquivalent(VCUnitDefinition otherUnit) { return this.fieldUnitDefinition.compareEqual(otherUnit.fieldUnitDefinition); } public RationalNumber getDimensionlessScale() { // System.err.println("VCUnitDefinition.getDimensionlessScale(): this unit = "+getSymbol()); VCUnitDefinition dimensionless = fieldVCUnitSystem.getInstance_DIMENSIONLESS(); if (isEquivalent(dimensionless)){ RationalNumber rationalConversionScale = new RationalNumber(1); // System.err.println("VCUnitDefinition.getDimensionlessScale(): conversion scale = "+rationalConversionScale.toString()); return rationalConversionScale; } if (isCompatible(dimensionless)){ double conversionScale = dimensionless.convertTo(1.0, this); RationalNumber rationalConversionScale = RationalNumber.getApproximateFraction(conversionScale); // System.err.println("VCUnitDefinition.getDimensionlessScale(): conversion scale = "+rationalConversionScale.toString()); return rationalConversionScale; } // System.err.println("VCUnitDefinition.getDimensionlessScale(): not compatable with dimensionless"); // // this is not strictly a dimensionless since we do not automatically convert between molecules and moles) // so have to explicitly look for such cases. // final VCUnitDefinition molecules_per_uM_um3 = fieldVCUnitSystem.getInstance("molecules.uM-1.um-3"); final RationalNumber value_molecules_per_uM_um3 = new RationalNumber(new Double(ExpressionUtils.value_molecules_per_uM_um3_NUMERATOR).longValue(),1000000); RationalNumber tempValue = value_molecules_per_uM_um3; VCUnitDefinition tempUnit = molecules_per_uM_um3; for (int i=0;i<10;i++){ // System.err.println("VCUnitDefinition.getDimensionlessScale(): mult unit = "+this.multiplyBy(tempUnit).getSymbol()); if (this.multiplyBy(tempUnit).isCompatible(dimensionless)){ double conversionScale = dimensionless.convertTo(1.0, this.multiplyBy(tempUnit)); RationalNumber rationalConversionScale = RationalNumber.getApproximateFraction(conversionScale).div(tempValue); // System.err.println("VCUnitDefinition.getDimensionlessScale(): mult unit = "+this.multiplyBy(tempUnit).getSymbol()+" worked, conversion scale = "+rationalConversionScale.toString()); return rationalConversionScale; } // System.err.println("VCUnitDefinition.getDimensionlessScale(): div unit = "+this.divideBy(tempUnit).getSymbol()); if (this.divideBy(tempUnit).isCompatible(dimensionless)){ double conversionScale = dimensionless.convertTo(1.0, this.divideBy(tempUnit)); RationalNumber rationalConversionScale = RationalNumber.getApproximateFraction(conversionScale).mult(tempValue); // System.err.println("VCUnitDefinition.getDimensionlessScale(): div unit = "+this.divideBy(tempUnit).getSymbol()+" worked, conversion scale = "+rationalConversionScale.toString()); return rationalConversionScale; } tempValue = tempValue.mult(value_molecules_per_uM_um3); tempUnit = tempUnit.multiplyBy(molecules_per_uM_um3); } throw new RuntimeException("unit "+getSymbol()+" is not dimensionless, cannot be a unit conversion factor"); } }
42.012346
188
0.765011
d4f43fbcd6ce7fd084fc00bee1d914634297d7f0
582
package io.mzlnk.springframework.multitenant.oauth2.resourceserver.resolver.token; import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver; import org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver; import javax.servlet.http.HttpServletRequest; public class DefaultTokenResolver implements TokenResolver { private final BearerTokenResolver resolver = new DefaultBearerTokenResolver(); @Override public String resolve(HttpServletRequest httpRequest) { return resolver.resolve(httpRequest); } }
32.333333
90
0.821306
8f805a03dfedc3221b846db247f93eca3a3a7fd4
710
/** * * @author gurnoor */ package nl.esciencecenter.qtm.utils; public class NumberFormat { private String number; private String format; private float value; public NumberFormat(String num, String form) { this.number = num.replace(" ", ""); this.format = form; try { value = Float.parseFloat(num); } catch (Exception ex) { value = 0; } } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public float getValue() { return value; } public void setValue(float value) { this.value = value; } }
16.511628
47
0.666197
3fee4c5749969b43980e58267b942b8d29da3e59
8,023
package br.com.mvbos.fillit; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.support.annotation.NonNull; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import android.util.Log; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Date; import br.com.mvbos.fillit.data.FillItContract; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { private Context appContext; @Test public void useAppContext() throws Exception { appContext = InstrumentationRegistry.getTargetContext(); long mGasStation = 1; long mVehicle = 1; long mFuel = 1; long mDate = new Date().getTime(); double mPrice = 3.75; int mLiters = 5; double mLat = 513; double mLng = 513; long mDataSync = new Date().getTime(); Uri uri = testInsert(mGasStation, mVehicle, mFuel, mDate, mPrice, mLiters, mLat, mLng, mDataSync); assertNotEquals(uri, null); Log.e("br.com.mvbos.fillit", "URI " + uri); testQuery(mGasStation, mVehicle, mFuel, mDate, mPrice, mLiters, mLat, mLng, mDataSync); int ru = testUpdate(mGasStation, mVehicle, mFuel, mDate, mPrice, mLiters, mLat, mLng, mDataSync); assertEquals(ru, 1); int rd = testDelete(); assertEquals(rd, 1); assertEquals("br.com.mvbos.fillit", appContext.getPackageName()); } private int testDelete() { String mSelectionClause = FillItContract.FillEntry._ID + "= ?"; String[] mSelectionArgs = {"1"}; int mRowsDeleted; mRowsDeleted = getContentResolver().delete( FillItContract.FillEntry.CONTENT_URI, mSelectionClause, mSelectionArgs ); return mRowsDeleted; } @NonNull private int testUpdate(float mGasstation, float mVeichle, float mFuel, float mDate, double mPrice, int mLiters, double mLat, double mLng, float mDataSync) { ContentValues mUpdateValues = new ContentValues(); mUpdateValues.put(FillItContract.FillEntry.COLUMN_NAME_GASSTATION, mGasstation); mUpdateValues.put(FillItContract.FillEntry.COLUMN_NAME_VEHICLE, mVeichle); mUpdateValues.put(FillItContract.FillEntry.COLUMN_NAME_FUEL, mFuel); mUpdateValues.put(FillItContract.FillEntry.COLUMN_NAME_DATE, mDate); mUpdateValues.put(FillItContract.FillEntry.COLUMN_NAME_PRICE, mPrice); mUpdateValues.put(FillItContract.FillEntry.COLUMN_NAME_LITERS, mLiters); mUpdateValues.put(FillItContract.FillEntry.COLUMN_NAME_LAT, mLat); mUpdateValues.put(FillItContract.FillEntry.COLUMN_NAME_LNG, mLng); mUpdateValues.put(FillItContract.FillEntry.COLUMN_NAME_DATASYNC, mDataSync); int mRowsUpdated; String[] mSelectionArgs = {"1"}; String mSelectionClause = FillItContract.FillEntry._ID + " = ?"; mRowsUpdated = getContentResolver().update( FillItContract.FillEntry.CONTENT_URI, mUpdateValues, mSelectionClause, mSelectionArgs ); return mRowsUpdated; } private Uri testInsert(float mGasstation, float mVeichle, float mFuel, float mDate, double mPrice, int mLiters, double mLat, double mLng, float mDataSync) { Uri mFillUri; ContentValues mFillValues = new ContentValues(); mFillValues.put(FillItContract.FillEntry.COLUMN_NAME_GASSTATION, mGasstation); mFillValues.put(FillItContract.FillEntry.COLUMN_NAME_VEHICLE, mVeichle); mFillValues.put(FillItContract.FillEntry.COLUMN_NAME_FUEL, mFuel); mFillValues.put(FillItContract.FillEntry.COLUMN_NAME_DATE, mDate); mFillValues.put(FillItContract.FillEntry.COLUMN_NAME_PRICE, mPrice); mFillValues.put(FillItContract.FillEntry.COLUMN_NAME_LITERS, mLiters); mFillValues.put(FillItContract.FillEntry.COLUMN_NAME_LAT, mLat); mFillValues.put(FillItContract.FillEntry.COLUMN_NAME_LNG, mLng); mFillValues.put(FillItContract.FillEntry.COLUMN_NAME_DATASYNC, mDataSync); mFillUri = getContentResolver().insert(FillItContract.FillEntry.CONTENT_URI, mFillValues); return mFillUri; } @NonNull private void testQuery(float mGasstation, float mVeichle, float mFuel, float mDate, double mPrice, int mLiters, double mLat, double mLng, float mDataSync) { Cursor mCursor; String mSortOrder = null; String[] mProjection = { FillItContract.FillEntry._ID, FillItContract.FillEntry.COLUMN_NAME_GASSTATION, FillItContract.FillEntry.COLUMN_NAME_VEHICLE, FillItContract.FillEntry.COLUMN_NAME_FUEL, FillItContract.FillEntry.COLUMN_NAME_DATE, FillItContract.FillEntry.COLUMN_NAME_PRICE, FillItContract.FillEntry.COLUMN_NAME_LITERS, FillItContract.FillEntry.COLUMN_NAME_LAT, FillItContract.FillEntry.COLUMN_NAME_LNG, FillItContract.FillEntry.COLUMN_NAME_DATASYNC }; String mSelectionClause = ""; //FillItContract.FillEntry._ID + " = ?" String[] mSelectionArgs = {}; mCursor = getContentResolver().query( FillItContract.FillEntry.CONTENT_URI, mProjection, mSelectionClause, mSelectionArgs, mSortOrder); if (mCursor != null) { int gasstationIndex = mCursor.getColumnIndex(FillItContract.FillEntry.COLUMN_NAME_GASSTATION); int veichleIndex = mCursor.getColumnIndex(FillItContract.FillEntry.COLUMN_NAME_VEHICLE); int fuelIndex = mCursor.getColumnIndex(FillItContract.FillEntry.COLUMN_NAME_FUEL); int dateIndex = mCursor.getColumnIndex(FillItContract.FillEntry.COLUMN_NAME_DATE); int priceIndex = mCursor.getColumnIndex(FillItContract.FillEntry.COLUMN_NAME_PRICE); int litersIndex = mCursor.getColumnIndex(FillItContract.FillEntry.COLUMN_NAME_LITERS); int latIndex = mCursor.getColumnIndex(FillItContract.FillEntry.COLUMN_NAME_LAT); int lngIndex = mCursor.getColumnIndex(FillItContract.FillEntry.COLUMN_NAME_LNG); int dataSyncIndex = mCursor.getColumnIndex(FillItContract.FillEntry.COLUMN_NAME_DATASYNC); while (mCursor.moveToNext()) { long gasstation = mCursor.getLong(gasstationIndex); long vehicle = mCursor.getLong(veichleIndex); float fuel = mCursor.getLong(fuelIndex); long date = mCursor.getLong(dateIndex); double price = mCursor.getDouble(priceIndex); int liters = mCursor.getInt(litersIndex); double lat = mCursor.getDouble(latIndex); double lng = mCursor.getDouble(lngIndex); long dataSync = mCursor.getLong(dataSyncIndex); assertEquals(mGasstation, gasstation, 0.002); assertEquals(mVeichle, vehicle, 0.002); assertEquals(mFuel, fuel, 0.002); assertEquals(mDate, date, 0.002); assertEquals(mPrice, price, 0.002); assertEquals(mLiters, liters, 0.002); assertEquals(mLat, lat, 0.002); assertEquals(mLng, lng, 0.002); assertEquals(mDataSync, dataSync, 0.002); } mCursor.close(); } else { } } public ContentResolver getContentResolver() { return appContext.getContentResolver(); } }
40.520202
160
0.67319
9e5a372685c147124e58a9e9f5491e953219e65f
5,318
package me.zohar.runscore.dictconfig.service; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.validation.constraints.NotBlank; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.alicp.jetcache.anno.Cached; import cn.hutool.core.util.StrUtil; import me.zohar.runscore.common.exception.BizError; import me.zohar.runscore.common.exception.BizException; import me.zohar.runscore.common.valid.ParamValid; import me.zohar.runscore.common.vo.PageResult; import me.zohar.runscore.dictconfig.domain.DictItem; import me.zohar.runscore.dictconfig.domain.DictType; import me.zohar.runscore.dictconfig.param.AddOrUpdateDictTypeParam; import me.zohar.runscore.dictconfig.param.DictDataParam; import me.zohar.runscore.dictconfig.param.DictTypeQueryCondParam; import me.zohar.runscore.dictconfig.param.UpdateDictDataParam; import me.zohar.runscore.dictconfig.repo.DictItemRepo; import me.zohar.runscore.dictconfig.repo.DictTypeRepo; import me.zohar.runscore.dictconfig.vo.DictItemVO; import me.zohar.runscore.dictconfig.vo.DictTypeVO; @Service public class DictService { @Autowired private DictItemRepo dictItemRepo; @Autowired private DictTypeRepo dictTypeRepo; @ParamValid @Transactional public void updateDictData(UpdateDictDataParam param) { Set<String> dictItemCodeSet = new HashSet<String>(); for (DictDataParam dictDataParam : param.getDictDatas()) { if (!dictItemCodeSet.add(dictDataParam.getDictItemCode())) { throw new BizException(BizError.字典项code不能重复); } } DictType dictType = dictTypeRepo.getOne(param.getDictTypeId()); dictItemRepo.deleteAll(dictType.getDictItems()); double orderNo = 1; for (DictDataParam dictDataParam : param.getDictDatas()) { DictItem dictItem = dictDataParam.convertToPo(); dictItem.setDictTypeId(dictType.getId()); dictItem.setOrderNo(orderNo); dictItemRepo.save(dictItem); orderNo++; } } @ParamValid @Transactional public void delDictTypeById(@NotBlank String id) { DictType dictType = dictTypeRepo.getOne(id); dictItemRepo.deleteAll(dictType.getDictItems()); dictTypeRepo.delete(dictType); } @ParamValid @Transactional(readOnly = true) public DictTypeVO findDictTypeById(@NotBlank String id) { return DictTypeVO.convertFor(dictTypeRepo.getOne(id)); } @ParamValid @Transactional public void addOrUpdateDictType(AddOrUpdateDictTypeParam param) { // 新增 if (StrUtil.isBlank(param.getId())) { DictType dictType = param.convertToPo(); dictTypeRepo.save(dictType); } // 修改 else { DictType dictType = dictTypeRepo.getOne(param.getId()); BeanUtils.copyProperties(param, dictType); dictTypeRepo.save(dictType); } } @Transactional(readOnly = true) public PageResult<DictTypeVO> findDictTypeByPage(DictTypeQueryCondParam param) { Specification<DictType> spec = new Specification<DictType>() { /** * */ private static final long serialVersionUID = 1L; public Predicate toPredicate(Root<DictType> root, CriteriaQuery<?> query, CriteriaBuilder builder) { List<Predicate> predicates = new ArrayList<Predicate>(); if (StrUtil.isNotBlank(param.getDictTypeCode())) { predicates.add(builder.like(root.get("dictTypeCode"), "%" + param.getDictTypeCode() + "%")); } if (StrUtil.isNotBlank(param.getDictTypeName())) { predicates.add(builder.like(root.get("dictTypeName"), "%" + param.getDictTypeName() + "%")); } return predicates.size() > 0 ? builder.and(predicates.toArray(new Predicate[predicates.size()])) : null; } }; Page<DictType> result = dictTypeRepo.findAll(spec, PageRequest.of(param.getPageNum() - 1, param.getPageSize(), Sort.by(Sort.Order.desc("dictTypeCode")))); PageResult<DictTypeVO> pageResult = new PageResult<>(DictTypeVO.convertFor(result.getContent()), param.getPageNum(), param.getPageSize(), result.getTotalElements()); return pageResult; } @Cached(name = "dictItem_", key = "#dictTypeCode + '_' + #dictItemCode", expire = 3600) @Transactional(readOnly = true) public DictItemVO findDictItemByDictTypeCodeAndDictItemCode(String dictTypeCode, String dictItemCode) { return DictItemVO .convertFor(dictItemRepo.findByDictTypeDictTypeCodeAndDictItemCode(dictTypeCode, dictItemCode)); } @Cached(name = "dictItems_", key = "#dictTypeCode", expire = 3600) @Transactional(readOnly = true) public List<DictItemVO> findDictItemByDictTypeCode(String dictTypeCode) { return DictItemVO.convertFor(dictItemRepo.findByDictTypeDictTypeCodeOrderByOrderNo(dictTypeCode)); } @Transactional(readOnly = true) public List<DictItemVO> findDictItemByDictTypeId(String dictTypeId) { return DictItemVO.convertFor(dictItemRepo.findByDictTypeIdOrderByOrderNo(dictTypeId)); } }
35.691275
108
0.778112
54d7c71762e8011284409192627ca2d37b132aed
4,818
/* * Copyright 2018 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.workbench.screens.scenariosimulation.client.handlers; import java.util.Arrays; import java.util.List; import com.ait.lienzo.client.core.shape.Viewport; import com.ait.lienzo.client.core.types.Point2D; import com.google.gwt.event.dom.client.ContextMenuEvent; import org.drools.workbench.screens.scenariosimulation.client.AbstractScenarioSimulationTest; import org.drools.workbench.screens.scenariosimulation.client.widgets.ScenarioGridCell; import org.junit.Before; import org.mockito.AdditionalMatchers; import org.mockito.Mock; import org.uberfire.ext.wires.core.grids.client.model.GridColumn; import org.uberfire.ext.wires.core.grids.client.widget.grid.renderers.grids.GridRenderer; import org.uberfire.ext.wires.core.grids.client.widget.grid.renderers.grids.impl.BaseGridRendererHelper; import static org.drools.workbench.screens.scenariosimulation.client.TestProperties.CLICK_POINT_X; import static org.drools.workbench.screens.scenariosimulation.client.TestProperties.GRID_WIDTH; import static org.drools.workbench.screens.scenariosimulation.client.TestProperties.HEADER_HEIGHT; import static org.drools.workbench.screens.scenariosimulation.client.TestProperties.HEADER_ROW_HEIGHT; import static org.drools.workbench.screens.scenariosimulation.client.TestProperties.OFFSET_X; import static org.drools.workbench.screens.scenariosimulation.client.TestProperties.UI_COLUMN_INDEX; import static org.drools.workbench.screens.scenariosimulation.client.TestProperties.UI_ROW_INDEX; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; public abstract class AbstractScenarioSimulationGridHandlerTest extends AbstractScenarioSimulationTest { @Mock protected Point2D point2DMock; @Mock protected Viewport viewportMock; @Mock protected ScenarioGridCell scenarioGridCellMock; @Mock protected ContextMenuEvent contextMenuEventMock; protected List<GridColumn<?>> columnsMock; @Mock protected BaseGridRendererHelper scenarioGridRendererHelperMock; @Mock private BaseGridRendererHelper.RenderingInformation scenarioRenderingInformationMock; @Mock private GridRenderer scenarioGridRendererMock; @Mock private BaseGridRendererHelper.RenderingBlockInformation floatingBlockInformationMock; @Before public void setUp() { super.setup(); doReturn(scenarioGridCellMock).when(scenarioGridModelMock).getCell(UI_ROW_INDEX, UI_COLUMN_INDEX); when(scenarioGridPanelMock.getScenarioGrid()).thenReturn(scenarioGridMock); when(scenarioGridMock.getWidth()).thenReturn(GRID_WIDTH); when(scenarioGridMock.getModel()).thenReturn(scenarioGridModelMock); when(scenarioGridMock.getRenderer()).thenReturn(scenarioGridRendererMock); when(scenarioGridMock.getRendererHelper()).thenReturn(scenarioGridRendererHelperMock); when(scenarioGridMock.getViewport()).thenReturn(viewportMock); when(scenarioGridMock.getComputedLocation()).thenReturn(new Point2D(0.0, 0.0)); when(scenarioGridRendererMock.getHeaderHeight()).thenReturn(HEADER_HEIGHT); when(scenarioGridRendererMock.getHeaderRowHeight()).thenReturn(HEADER_ROW_HEIGHT); when(scenarioGridRendererHelperMock.getRenderingInformation()).thenReturn(scenarioRenderingInformationMock); // mock single column in grid when(scenarioGridModelMock.getHeaderRowCount()).thenReturn(1); columnsMock = Arrays.asList(gridColumnMock, gridColumnMock); when(scenarioGridModelMock.getColumns()).thenReturn(columnsMock); when(scenarioGridModelMock.getColumnCount()).thenReturn(2); // mock that column to index 0 BaseGridRendererHelper.ColumnInformation columnInformation = new BaseGridRendererHelper.ColumnInformation(gridColumnMock, UI_COLUMN_INDEX, OFFSET_X); when(scenarioGridRendererHelperMock.getColumnInformation(AdditionalMatchers.or(eq(0.0), eq(CLICK_POINT_X)))) .thenReturn(columnInformation); when(scenarioRenderingInformationMock.getFloatingBlockInformation()).thenReturn(floatingBlockInformationMock); } }
47.70297
118
0.795558
6c965bc1dd40e79dd80c7c87488a6fb15fb8367a
36,034
package com.github.jarvisframework.tool.core.io; import com.github.jarvisframework.tool.core.convert.Convert; import com.github.jarvisframework.tool.core.exception.UtilException; import com.github.jarvisframework.tool.core.lang.Assert; import com.github.jarvisframework.tool.core.text.StringBuilder; import com.github.jarvisframework.tool.core.util.CharsetUtils; import com.github.jarvisframework.tool.core.util.HexUtils; import com.github.jarvisframework.tool.core.util.StringUtils; import java.io.*; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.Charset; import java.util.Collection; import java.util.Objects; import java.util.zip.CRC32; import java.util.zip.CheckedInputStream; import java.util.zip.Checksum; /** * IO工具类<br> * IO工具类只是辅助流的读写,并不负责关闭流。原因是流可能被多次读写,读写关闭后容易造成问题。 * * @author Doug Wang * @since 1.0, 2020-07-10 19:51:13 */ public class IOUtils { /** * 默认缓存大小 8192 */ public static final int DEFAULT_BUFFER_SIZE = 2 << 12; /** * 默认中等缓存大小 16384 */ public static final int DEFAULT_MIDDLE_BUFFER_SIZE = 2 << 13; /** * 默认大缓存大小 32768 */ public static final int DEFAULT_LARGE_BUFFER_SIZE = 2 << 14; /** * 数据流末尾 */ public static final int EOF = -1; // -------------------------------------------------------------------------------------- Copy start /** * 将Reader中的内容复制到Writer中 使用默认缓存大小,拷贝后不关闭Reader * * @param reader Reader * @param writer Writer * @return 拷贝的字节数 * @throws IORuntimeException IO异常 */ public static long copy(Reader reader, Writer writer) throws IORuntimeException { return copy(reader, writer, DEFAULT_BUFFER_SIZE); } /** * 将Reader中的内容复制到Writer中,拷贝后不关闭Reader * * @param reader Reader * @param writer Writer * @param bufferSize 缓存大小 * @return 传输的byte数 * @throws IORuntimeException IO异常 */ public static long copy(Reader reader, Writer writer, int bufferSize) throws IORuntimeException { return copy(reader, writer, bufferSize, null); } /** * 将Reader中的内容复制到Writer中,拷贝后不关闭Reader * * @param reader Reader * @param writer Writer * @param bufferSize 缓存大小 * @param streamProgress 进度处理器 * @return 传输的byte数 * @throws IORuntimeException IO异常 */ public static long copy(Reader reader, Writer writer, int bufferSize, StreamProgress streamProgress) throws IORuntimeException { char[] buffer = new char[bufferSize]; long size = 0; int readSize; if (null != streamProgress) { streamProgress.start(); } try { while ((readSize = reader.read(buffer, 0, bufferSize)) != EOF) { writer.write(buffer, 0, readSize); size += readSize; writer.flush(); if (null != streamProgress) { streamProgress.progress(size); } } } catch (Exception e) { throw new IORuntimeException(e); } if (null != streamProgress) { streamProgress.finish(); } return size; } /** * 拷贝流,使用默认Buffer大小,拷贝后不关闭流 * * @param in 输入流 * @param out 输出流 * @return 传输的byte数 * @throws IORuntimeException IO异常 */ public static long copy(InputStream in, OutputStream out) throws IORuntimeException { return copy(in, out, DEFAULT_BUFFER_SIZE); } /** * 拷贝流,拷贝后不关闭流 * * @param in 输入流 * @param out 输出流 * @param bufferSize 缓存大小 * @return 传输的byte数 * @throws IORuntimeException IO异常 */ public static long copy(InputStream in, OutputStream out, int bufferSize) throws IORuntimeException { return copy(in, out, bufferSize, null); } /** * 拷贝流,拷贝后不关闭流 * * @param in 输入流 * @param out 输出流 * @param bufferSize 缓存大小 * @param streamProgress 进度条 * @return 传输的byte数 * @throws IORuntimeException IO异常 */ public static long copy(InputStream in, OutputStream out, int bufferSize, StreamProgress streamProgress) throws IORuntimeException { Assert.notNull(in, "InputStream is null !"); Assert.notNull(out, "OutputStream is null !"); if (bufferSize <= 0) { bufferSize = DEFAULT_BUFFER_SIZE; } byte[] buffer = new byte[bufferSize]; if (null != streamProgress) { streamProgress.start(); } long size = 0; try { for (int readSize; (readSize = in.read(buffer)) != EOF; ) { out.write(buffer, 0, readSize); size += readSize; out.flush(); if (null != streamProgress) { streamProgress.progress(size); } } } catch (IOException e) { throw new IORuntimeException(e); } if (null != streamProgress) { streamProgress.finish(); } return size; } /** * 拷贝流 thanks to: https://github.com/venusdrogon/feilong-io/blob/master/src/main/java/com/feilong/io/IOWriterUtil.java<br> * 本方法不会关闭流 * * @param in 输入流 * @param out 输出流 * @param bufferSize 缓存大小 * @param streamProgress 进度条 * @return 传输的byte数 * @throws IORuntimeException IO异常 */ public static long copyByNIO(InputStream in, OutputStream out, int bufferSize, StreamProgress streamProgress) throws IORuntimeException { return copy(Channels.newChannel(in), Channels.newChannel(out), bufferSize, streamProgress); } /** * 拷贝文件流,使用NIO * * @param in 输入 * @param out 输出 * @return 拷贝的字节数 * @throws IORuntimeException IO异常 */ public static long copy(FileInputStream in, FileOutputStream out) throws IORuntimeException { Assert.notNull(in, "FileInputStream is null!"); Assert.notNull(out, "FileOutputStream is null!"); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = in.getChannel(); outChannel = out.getChannel(); return inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw new IORuntimeException(e); } finally { closeQuietly(outChannel); closeQuietly(inChannel); } } /** * 拷贝流,使用NIO,不会关闭流 * * @param in {@link ReadableByteChannel} * @param out {@link WritableByteChannel} * @return 拷贝的字节数 * @throws IORuntimeException IO异常 * @since 4.5.0 */ public static long copy(ReadableByteChannel in, WritableByteChannel out) throws IORuntimeException { return copy(in, out, DEFAULT_BUFFER_SIZE); } /** * 拷贝流,使用NIO,不会关闭流 * * @param in {@link ReadableByteChannel} * @param out {@link WritableByteChannel} * @param bufferSize 缓冲大小,如果小于等于0,使用默认 * @return 拷贝的字节数 * @throws IORuntimeException IO异常 * @since 4.5.0 */ public static long copy(ReadableByteChannel in, WritableByteChannel out, int bufferSize) throws IORuntimeException { return copy(in, out, bufferSize, null); } /** * 拷贝流,使用NIO,不会关闭流 * * @param in {@link ReadableByteChannel} * @param out {@link WritableByteChannel} * @param bufferSize 缓冲大小,如果小于等于0,使用默认 * @param streamProgress {@link StreamProgress}进度处理器 * @return 拷贝的字节数 * @throws IORuntimeException IO异常 */ public static long copy(ReadableByteChannel in, WritableByteChannel out, int bufferSize, StreamProgress streamProgress) throws IORuntimeException { Assert.notNull(in, "InputStream is null !"); Assert.notNull(out, "OutputStream is null !"); ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize <= 0 ? DEFAULT_BUFFER_SIZE : bufferSize); long size = 0; if (null != streamProgress) { streamProgress.start(); } try { while (in.read(byteBuffer) != EOF) { byteBuffer.flip();// 写转读 size += out.write(byteBuffer); byteBuffer.clear(); if (null != streamProgress) { streamProgress.progress(size); } } } catch (IOException e) { throw new IORuntimeException(e); } if (null != streamProgress) { streamProgress.finish(); } return size; } // -------------------------------------------------------------------------------------- Copy end // -------------------------------------------------------------------------------------- getReader and getWriter start /** * 获得一个文件读取器,默认使用UTF-8编码 * * @param in 输入流 * @return BufferedReader对象 * @since 5.1.6 */ public static BufferedReader getUtf8Reader(InputStream in) { return getReader(in, CharsetUtils.CHARSET_UTF_8); } /** * 获得一个文件读取器 * * @param in 输入流 * @param charsetName 字符集名称 * @return BufferedReader对象 */ public static BufferedReader getReader(InputStream in, String charsetName) { return getReader(in, Charset.forName(charsetName)); } /** * 获得一个Reader * * @param in 输入流 * @param charset 字符集 * @return BufferedReader对象 */ public static BufferedReader getReader(InputStream in, Charset charset) { if (null == in) { return null; } InputStreamReader reader; if (null == charset) { reader = new InputStreamReader(in); } else { reader = new InputStreamReader(in, charset); } return new BufferedReader(reader); } /** * 获得{@link BufferedReader}<br> * 如果是{@link BufferedReader}强转返回,否则新建。如果提供的Reader为null返回null * * @param reader 普通Reader,如果为null返回null * @return {@link BufferedReader} or null * @since 3.0.9 */ public static BufferedReader getReader(Reader reader) { if (null == reader) { return null; } return (reader instanceof BufferedReader) ? (BufferedReader) reader : new BufferedReader(reader); } /** * 获得{@link PushbackReader}<br> * 如果是{@link PushbackReader}强转返回,否则新建 * * @param reader 普通Reader * @param pushBackSize 推后的byte数 * @return {@link PushbackReader} * @since 3.1.0 */ public static PushbackReader getPushBackReader(Reader reader, int pushBackSize) { return (reader instanceof PushbackReader) ? (PushbackReader) reader : new PushbackReader(reader, pushBackSize); } /** * 获得一个Writer,默认编码UTF-8 * * @param out 输入流 * @return OutputStreamWriter对象 * @since 5.1.6 */ public static OutputStreamWriter getUtf8Writer(OutputStream out) { return getWriter(out, CharsetUtils.CHARSET_UTF_8); } /** * 获得一个Writer * * @param out 输入流 * @param charsetName 字符集 * @return OutputStreamWriter对象 */ public static OutputStreamWriter getWriter(OutputStream out, String charsetName) { return getWriter(out, Charset.forName(charsetName)); } /** * 获得一个Writer * * @param out 输入流 * @param charset 字符集 * @return OutputStreamWriter对象 */ public static OutputStreamWriter getWriter(OutputStream out, Charset charset) { if (null == out) { return null; } if (null == charset) { return new OutputStreamWriter(out); } else { return new OutputStreamWriter(out, charset); } } // -------------------------------------------------------------------------------------- getReader and getWriter end // -------------------------------------------------------------------------------------- read start /** * 从流中读取内容 * * @param in 输入流 * @param charsetName 字符集 * @return 内容 * @throws IORuntimeException IO异常 */ public static String read(InputStream in, String charsetName) throws IORuntimeException { FastByteArrayOutputStream out = read(in); return StringUtils.isBlank(charsetName) ? out.toString() : out.toString(charsetName); } /** * 从流中读取内容,读取完毕后并不关闭流 * * @param in 输入流,读取完毕后并不关闭流 * @param charset 字符集 * @return 内容 * @throws IORuntimeException IO异常 */ public static String read(InputStream in, Charset charset) throws IORuntimeException { FastByteArrayOutputStream out = read(in); return null == charset ? out.toString() : out.toString(charset); } /** * 从流中读取内容,读取完毕后并不关闭流 * * @param channel 可读通道,读取完毕后并不关闭通道 * @param charset 字符集 * @return 内容 * @throws IORuntimeException IO异常 * @since 4.5.0 */ public static String read(ReadableByteChannel channel, Charset charset) throws IORuntimeException { FastByteArrayOutputStream out = read(channel); return null == charset ? out.toString() : out.toString(charset); } /** * 从流中读取内容,读到输出流中,读取完毕后并不关闭流 * * @param in 输入流 * @return 输出流 * @throws IORuntimeException IO异常 */ public static FastByteArrayOutputStream read(InputStream in) throws IORuntimeException { final FastByteArrayOutputStream out = new FastByteArrayOutputStream(); copy(in, out); return out; } /** * 从流中读取内容,读到输出流中 * * @param channel 可读通道,读取完毕后并不关闭通道 * @return 输出流 * @throws IORuntimeException IO异常 */ public static FastByteArrayOutputStream read(ReadableByteChannel channel) throws IORuntimeException { final FastByteArrayOutputStream out = new FastByteArrayOutputStream(); copy(channel, Channels.newChannel(out)); return out; } /** * 从Reader中读取String,读取完毕后并不关闭Reader * * @param reader Reader * @return String * @throws IORuntimeException IO异常 */ public static String read(Reader reader) throws IORuntimeException { final StringBuilder builder = StringUtils.builder(); final CharBuffer buffer = CharBuffer.allocate(DEFAULT_BUFFER_SIZE); try { while (-1 != reader.read(buffer)) { builder.append(buffer.flip().toString()); } } catch (IOException e) { throw new IORuntimeException(e); } return builder.toString(); } /** * 从FileChannel中读取UTF-8编码内容 * * @param fileChannel 文件管道 * @return 内容 * @throws IORuntimeException IO异常 */ public static String readUtf8(FileChannel fileChannel) throws IORuntimeException { return read(fileChannel, CharsetUtils.CHARSET_UTF_8); } /** * 从FileChannel中读取内容,读取完毕后并不关闭Channel * * @param fileChannel 文件管道 * @param charsetName 字符集 * @return 内容 * @throws IORuntimeException IO异常 */ public static String read(FileChannel fileChannel, String charsetName) throws IORuntimeException { return read(fileChannel, CharsetUtils.charset(charsetName)); } /** * 从FileChannel中读取内容 * * @param fileChannel 文件管道 * @param charset 字符集 * @return 内容 * @throws IORuntimeException IO异常 */ public static String read(FileChannel fileChannel, Charset charset) throws IORuntimeException { MappedByteBuffer buffer; try { buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size()).load(); } catch (IOException e) { throw new IORuntimeException(e); } return StringUtils.str(buffer, charset); } /** * 从流中读取bytes,读取完毕后关闭流 * * @param in {@link InputStream} * @return bytes * @throws IORuntimeException IO异常 */ public static byte[] readBytes(InputStream in) throws IORuntimeException { return readBytes(in, true); } /** * 从流中读取bytes * * @param in {@link InputStream} * @param isCloseStream 是否关闭输入流 * @return bytes * @throws IORuntimeException IO异常 * @since 5.0.4 */ public static byte[] readBytes(InputStream in, boolean isCloseStream) throws IORuntimeException { final FastByteArrayOutputStream out = new FastByteArrayOutputStream(); copy(in, out); if (isCloseStream) { closeQuietly(in); } return out.toByteArray(); } /** * 读取指定长度的byte数组,不关闭流 * * @param in {@link InputStream},为null返回null * @param length 长度,小于等于0返回空byte数组 * @return bytes * @throws IORuntimeException IO异常 */ public static byte[] readBytes(InputStream in, int length) throws IORuntimeException { if (null == in) { return null; } if (length <= 0) { return new byte[0]; } byte[] b = new byte[length]; int readLength; try { readLength = in.read(b); } catch (IOException e) { throw new IORuntimeException(e); } if (readLength > 0 && readLength < length) { byte[] b2 = new byte[readLength]; System.arraycopy(b, 0, b2, 0, readLength); return b2; } else { return b; } } /** * 读取16进制字符串 * * @param in {@link InputStream} * @param length 长度 * @param toLowerCase true 传换成小写格式 , false 传换成大写格式 * @return 16进制字符串 * @throws IORuntimeException IO异常 */ public static String readHex(InputStream in, int length, boolean toLowerCase) throws IORuntimeException { return HexUtils.encodeHexStr(readBytes(in, length), toLowerCase); } /** * 从流中读取前28个byte并转换为16进制,字母部分使用大写 * * @param in {@link InputStream} * @return 16进制字符串 * @throws IORuntimeException IO异常 */ public static String readHex28Upper(InputStream in) throws IORuntimeException { return readHex(in, 28, false); } /** * 从流中读取前28个byte并转换为16进制,字母部分使用小写 * * @param in {@link InputStream} * @return 16进制字符串 * @throws IORuntimeException IO异常 */ public static String readHex28Lower(InputStream in) throws IORuntimeException { return readHex(in, 28, true); } /** * 从流中读取对象,即对象的反序列化 * * <p> * 注意!!! 此方法不会检查反序列化安全,可能存在反序列化漏洞风险!!! * </p> * * @param <T> 读取对象的类型 * @param in 输入流 * @return 输出流 * @throws IORuntimeException IO异常 * @throws UtilException ClassNotFoundException包装 */ public static <T> T readObj(InputStream in) throws IORuntimeException, UtilException { return readObj(in, null); } /** * 从流中读取对象,即对象的反序列化,读取后不关闭流 * * <p> * 注意!!! 此方法不会检查反序列化安全,可能存在反序列化漏洞风险!!! * </p> * * @param <T> 读取对象的类型 * @param in 输入流 * @param clazz 读取对象类型 * @return 输出流 * @throws IORuntimeException IO异常 * @throws UtilException ClassNotFoundException包装 */ public static <T> T readObj(InputStream in, Class<T> clazz) throws IORuntimeException, UtilException { try { return readObj((in instanceof ValidateObjectInputStream) ? (ValidateObjectInputStream) in : new ValidateObjectInputStream(in), clazz); } catch (IOException e) { throw new IORuntimeException(e); } } /** * 从流中读取对象,即对象的反序列化,读取后不关闭流 * * <p> * 此方法使用了{@link ValidateObjectInputStream}中的黑白名单方式过滤类,用于避免反序列化漏洞<br> * 通过构造{@link ValidateObjectInputStream},调用{@link ValidateObjectInputStream#accept(Class[])} * 或者{@link ValidateObjectInputStream#refuse(Class[])}方法添加可以被序列化的类或者禁止序列化的类。 * </p> * * @param <T> 读取对象的类型 * @param in 输入流,使用{@link ValidateObjectInputStream}中的黑白名单方式过滤类,用于避免反序列化漏洞 * @param clazz 读取对象类型 * @return 输出流 * @throws IORuntimeException IO异常 * @throws UtilException ClassNotFoundException包装 */ public static <T> T readObj(ValidateObjectInputStream in, Class<T> clazz) throws IORuntimeException, UtilException { if (in == null) { throw new IllegalArgumentException("The InputStream must not be null"); } try { //noinspection unchecked return (T) in.readObject(); } catch (IOException e) { throw new IORuntimeException(e); } catch (ClassNotFoundException e) { throw new UtilException(e); } } /** * 从流中读取内容,使用UTF-8编码 * * @param <T> 集合类型 * @param in 输入流 * @param collection 返回集合 * @return 内容 * @throws IORuntimeException IO异常 */ public static <T extends Collection<String>> T readUtf8Lines(InputStream in, T collection) throws IORuntimeException { return readLines(in, CharsetUtils.CHARSET_UTF_8, collection); } /** * 从流中读取内容 * * @param <T> 集合类型 * @param in 输入流 * @param charsetName 字符集 * @param collection 返回集合 * @return 内容 * @throws IORuntimeException IO异常 */ public static <T extends Collection<String>> T readLines(InputStream in, String charsetName, T collection) throws IORuntimeException { return readLines(in, CharsetUtils.charset(charsetName), collection); } /** * 从流中读取内容 * * @param <T> 集合类型 * @param in 输入流 * @param charset 字符集 * @param collection 返回集合 * @return 内容 * @throws IORuntimeException IO异常 */ public static <T extends Collection<String>> T readLines(InputStream in, Charset charset, T collection) throws IORuntimeException { return readLines(getReader(in, charset), collection); } /** * 从Reader中读取内容 * * @param <T> 集合类型 * @param reader {@link Reader} * @param collection 返回集合 * @return 内容 * @throws IORuntimeException IO异常 */ public static <T extends Collection<String>> T readLines(Reader reader, final T collection) throws IORuntimeException { readLines(reader, (LineHandler) collection::add); return collection; } /** * 按行读取UTF-8编码数据,针对每行的数据做处理 * * @param in {@link InputStream} * @param lineHandler 行处理接口,实现handle方法用于编辑一行的数据后入到指定地方 * @throws IORuntimeException IO异常 * @since 3.1.1 */ public static void readUtf8Lines(InputStream in, LineHandler lineHandler) throws IORuntimeException { readLines(in, CharsetUtils.CHARSET_UTF_8, lineHandler); } /** * 按行读取数据,针对每行的数据做处理 * * @param in {@link InputStream} * @param charset {@link Charset}编码 * @param lineHandler 行处理接口,实现handle方法用于编辑一行的数据后入到指定地方 * @throws IORuntimeException IO异常 * @since 3.0.9 */ public static void readLines(InputStream in, Charset charset, LineHandler lineHandler) throws IORuntimeException { readLines(getReader(in, charset), lineHandler); } /** * 按行读取数据,针对每行的数据做处理<br> * {@link Reader}自带编码定义,因此读取数据的编码跟随其编码。 * * @param reader {@link Reader} * @param lineHandler 行处理接口,实现handle方法用于编辑一行的数据后入到指定地方 * @throws IORuntimeException IO异常 */ public static void readLines(Reader reader, LineHandler lineHandler) throws IORuntimeException { Assert.notNull(reader); Assert.notNull(lineHandler); // 从返回的内容中读取所需内容 final BufferedReader bReader = getReader(reader); String line; try { while ((line = bReader.readLine()) != null) { lineHandler.handle(line); } } catch (IOException e) { throw new IORuntimeException(e); } } // -------------------------------------------------------------------------------------- read end /** * String 转为流 * * @param content 内容 * @param charsetName 编码 * @return 字节流 */ public static ByteArrayInputStream toStream(String content, String charsetName) { return toStream(content, CharsetUtils.charset(charsetName)); } /** * String 转为流 * * @param content 内容 * @param charset 编码 * @return 字节流 */ public static ByteArrayInputStream toStream(String content, Charset charset) { if (content == null) { return null; } return toStream(StringUtils.bytes(content, charset)); } /** * String 转为UTF-8编码的字节流流 * * @param content 内容 * @return 字节流 * @since 4.5.1 */ public static ByteArrayInputStream toUtf8Stream(String content) { return toStream(content, CharsetUtils.CHARSET_UTF_8); } /** * 文件转为流 * * @param file 文件 * @return {@link FileInputStream} */ public static FileInputStream toStream(File file) { try { return new FileInputStream(file); } catch (FileNotFoundException e) { throw new IORuntimeException(e); } } /** * String 转为流 * * @param content 内容bytes * @return 字节流 * @since 4.1.8 */ public static ByteArrayInputStream toStream(byte[] content) { if (content == null) { return null; } return new ByteArrayInputStream(content); } /** * 转换为{@link BufferedInputStream} * * @param in {@link InputStream} * @return {@link BufferedInputStream} * @since 4.0.10 */ public static BufferedInputStream toBuffered(InputStream in) { return (in instanceof BufferedInputStream) ? (BufferedInputStream) in : new BufferedInputStream(in); } /** * 转换为{@link BufferedOutputStream} * * @param out {@link OutputStream} * @return {@link BufferedOutputStream} * @since 4.0.10 */ public static BufferedOutputStream toBuffered(OutputStream out) { return (out instanceof BufferedOutputStream) ? (BufferedOutputStream) out : new BufferedOutputStream(out); } /** * 将{@link InputStream}转换为支持mark标记的流<br> * 若原流支持mark标记,则返回原流,否则使用{@link BufferedInputStream} 包装之 * * @param in 流 * @return {@link InputStream} * @since 4.0.9 */ public static InputStream toMarkSupportStream(InputStream in) { if (null == in) { return null; } if (false == in.markSupported()) { return new BufferedInputStream(in); } return in; } /** * 转换为{@link PushbackInputStream}<br> * 如果传入的输入流已经是{@link PushbackInputStream},强转返回,否则新建一个 * * @param in {@link InputStream} * @param pushBackSize 推后的byte数 * @return {@link PushbackInputStream} * @since 3.1.0 */ public static PushbackInputStream toPushbackStream(InputStream in, int pushBackSize) { return (in instanceof PushbackInputStream) ? (PushbackInputStream) in : new PushbackInputStream(in, pushBackSize); } /** * 将byte[]写到流中 * * @param out 输出流 * @param isCloseOut 写入完毕是否关闭输出流 * @param content 写入的内容 * @throws IORuntimeException IO异常 */ public static void write(OutputStream out, boolean isCloseOut, byte[] content) throws IORuntimeException { try { out.write(content); } catch (IOException e) { throw new IORuntimeException(e); } finally { if (isCloseOut) { closeQuietly(out); } } } /** * 将多部分内容写到流中,自动转换为UTF-8字符串 * * @param out 输出流 * @param isCloseOut 写入完毕是否关闭输出流 * @param contents 写入的内容,调用toString()方法,不包括不会自动换行 * @throws IORuntimeException IO异常 * @since 3.1.1 */ public static void writeUtf8(OutputStream out, boolean isCloseOut, Object... contents) throws IORuntimeException { write(out, CharsetUtils.CHARSET_UTF_8, isCloseOut, contents); } /** * 将多部分内容写到流中,自动转换为字符串 * * @param out 输出流 * @param charsetName 写出的内容的字符集 * @param isCloseOut 写入完毕是否关闭输出流 * @param contents 写入的内容,调用toString()方法,不包括不会自动换行 * @throws IORuntimeException IO异常 */ public static void write(OutputStream out, String charsetName, boolean isCloseOut, Object... contents) throws IORuntimeException { write(out, CharsetUtils.charset(charsetName), isCloseOut, contents); } /** * 将多部分内容写到流中,自动转换为字符串 * * @param out 输出流 * @param charset 写出的内容的字符集 * @param isCloseOut 写入完毕是否关闭输出流 * @param contents 写入的内容,调用toString()方法,不包括不会自动换行 * @throws IORuntimeException IO异常 * @since 3.0.9 */ public static void write(OutputStream out, Charset charset, boolean isCloseOut, Object... contents) throws IORuntimeException { OutputStreamWriter osw = null; try { osw = getWriter(out, charset); for (Object content : contents) { if (content != null) { osw.write(Convert.toString(content, StringUtils.EMPTY)); } } osw.flush(); } catch (IOException e) { throw new IORuntimeException(e); } finally { if (isCloseOut) { closeQuietly(osw); } } } /** * 将多部分内容写到流中 * * @param out 输出流 * @param isCloseOut 写入完毕是否关闭输出流 * @param obj 写入的对象内容 * @throws IORuntimeException IO异常 * @since 5.3.3 */ public static void writeObj(OutputStream out, boolean isCloseOut, Serializable obj) throws IORuntimeException { writeObjects(out, isCloseOut, obj); } /** * 将多部分内容写到流中 * * @param out 输出流 * @param isCloseOut 写入完毕是否关闭输出流 * @param contents 写入的内容 * @throws IORuntimeException IO异常 */ public static void writeObjects(OutputStream out, boolean isCloseOut, Serializable... contents) throws IORuntimeException { ObjectOutputStream osw = null; try { osw = out instanceof ObjectOutputStream ? (ObjectOutputStream) out : new ObjectOutputStream(out); for (Object content : contents) { if (content != null) { osw.writeObject(content); osw.flush(); } } } catch (IOException e) { throw new IORuntimeException(e); } finally { if (isCloseOut) { closeQuietly(osw); } } } /** * 从缓存中刷出数据 * * @param flushable {@link Flushable} * @since 4.2.2 */ public static void flush(Flushable flushable) { if (null != flushable) { try { flushable.flush(); } catch (Exception e) { // 静默刷出 } } } /** * 关闭<br> * 关闭失败不会抛出异常 * * @param closeable 被关闭的对象 */ public static void closeQuietly(Closeable closeable) { if (null != closeable) { try { closeable.close(); } catch (Exception e) { // 静默关闭 } } } /** * 关闭<br> * 关闭失败不会抛出异常 * * @param closeable 被关闭的对象 */ public static void closeQuietly(AutoCloseable closeable) { if (null != closeable) { try { closeable.close(); } catch (Exception e) { // 静默关闭 } } } /** * 尝试关闭指定对象<br> * 判断对象如果实现了{@link AutoCloseable},则调用之 * * @param obj 可关闭对象 * @since 4.3.2 */ public static void closeIfPosible(Object obj) { if (obj instanceof AutoCloseable) { closeQuietly((AutoCloseable) obj); } } /** * 对比两个流内容是否相同<br> * 内部会转换流为 {@link BufferedInputStream} * * @param input1 第一个流 * @param input2 第二个流 * @return 两个流的内容一致返回true,否则false * @throws IORuntimeException IO异常 * @since 4.0.6 */ public static boolean contentEquals(InputStream input1, InputStream input2) throws IORuntimeException { if (false == (input1 instanceof BufferedInputStream)) { input1 = new BufferedInputStream(input1); } if (false == (input2 instanceof BufferedInputStream)) { input2 = new BufferedInputStream(input2); } try { int ch = input1.read(); while (EOF != ch) { int ch2 = input2.read(); if (ch != ch2) { return false; } ch = input1.read(); } int ch2 = input2.read(); return ch2 == EOF; } catch (IOException e) { throw new IORuntimeException(e); } } /** * 对比两个Reader的内容是否一致<br> * 内部会转换流为 {@link BufferedInputStream} * * @param input1 第一个reader * @param input2 第二个reader * @return 两个流的内容一致返回true,否则false * @throws IORuntimeException IO异常 * @since 4.0.6 */ public static boolean contentEquals(Reader input1, Reader input2) throws IORuntimeException { input1 = getReader(input1); input2 = getReader(input2); try { int ch = input1.read(); while (EOF != ch) { int ch2 = input2.read(); if (ch != ch2) { return false; } ch = input1.read(); } int ch2 = input2.read(); return ch2 == EOF; } catch (IOException e) { throw new IORuntimeException(e); } } /** * 对比两个流内容是否相同,忽略EOL字符<br> * 内部会转换流为 {@link BufferedInputStream} * * @param input1 第一个流 * @param input2 第二个流 * @return 两个流的内容一致返回true,否则false * @throws IORuntimeException IO异常 * @since 4.0.6 */ public static boolean contentEqualsIgnoreEOL(Reader input1, Reader input2) throws IORuntimeException { final BufferedReader br1 = getReader(input1); final BufferedReader br2 = getReader(input2); try { String line1 = br1.readLine(); String line2 = br2.readLine(); while (line1 != null && line1.equals(line2)) { line1 = br1.readLine(); line2 = br2.readLine(); } return Objects.equals(line1, line2); } catch (IOException e) { throw new IORuntimeException(e); } } /** * 计算流CRC32校验码,计算后关闭流 * * @param in 文件,不能为目录 * @return CRC32值 * @throws IORuntimeException IO异常 * @since 4.0.6 */ public static long checksumCRC32(InputStream in) throws IORuntimeException { return checksum(in, new CRC32()).getValue(); } /** * 计算流的校验码,计算后关闭流 * * @param in 流 * @param checksum {@link Checksum} * @return Checksum * @throws IORuntimeException IO异常 * @since 4.0.10 */ public static Checksum checksum(InputStream in, Checksum checksum) throws IORuntimeException { Assert.notNull(in, "InputStream is null !"); if (null == checksum) { checksum = new CRC32(); } try { in = new CheckedInputStream(in, checksum); IOUtils.copy(in, new NullOutputStream()); } finally { IOUtils.closeQuietly(in); } return checksum; } }
29.367563
151
0.576039
fe39f902b58e54e055360071747502d94522573d
15,627
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.rest; import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.Version; import org.elasticsearch.common.xcontent.ParsedMediaType; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.hamcrest.ElasticsearchMatchers; import org.hamcrest.Matcher; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; public class RestCompatibleVersionHelperTests extends ESTestCase { int CURRENT_VERSION = Version.CURRENT.major; int PREVIOUS_VERSION = Version.CURRENT.major - 1; int OBSOLETE_VERSION = Version.CURRENT.major - 2; public void testAcceptAndContentTypeCombinations() { assertThat(requestWith(acceptHeader(PREVIOUS_VERSION), contentTypeHeader(PREVIOUS_VERSION), bodyPresent()), isCompatible()); assertThat(requestWith(acceptHeader(PREVIOUS_VERSION), contentTypeHeader(PREVIOUS_VERSION), bodyNotPresent()), isCompatible()); ElasticsearchStatusException e = expectThrows( ElasticsearchStatusException.class, () -> requestWith(acceptHeader(PREVIOUS_VERSION), contentTypeHeader(CURRENT_VERSION), bodyPresent()) ); assertThat( e.getMessage(), equalTo( "A compatible version is required on both Content-Type and Accept headers " + "if either one has requested a compatible version and the compatible versions must match. " + "Accept=" + acceptHeader(PREVIOUS_VERSION) + ", Content-Type=" + contentTypeHeader(CURRENT_VERSION) ) ); // no body - content-type is ignored assertThat(requestWith(acceptHeader(PREVIOUS_VERSION), contentTypeHeader(CURRENT_VERSION), bodyNotPresent()), isCompatible()); // no body - content-type is ignored assertThat(requestWith(acceptHeader(CURRENT_VERSION), contentTypeHeader(PREVIOUS_VERSION), bodyNotPresent()), not(isCompatible())); e = expectThrows( ElasticsearchStatusException.class, () -> requestWith(acceptHeader(CURRENT_VERSION), contentTypeHeader(PREVIOUS_VERSION), bodyPresent()) ); assertThat( e.getMessage(), equalTo( "A compatible version is required on both Content-Type and Accept headers " + "if either one has requested a compatible version and the compatible versions must match. " + "Accept=" + acceptHeader(CURRENT_VERSION) + ", Content-Type=" + contentTypeHeader(PREVIOUS_VERSION) ) ); assertThat(requestWith(acceptHeader(CURRENT_VERSION), contentTypeHeader(CURRENT_VERSION), bodyPresent()), not(isCompatible())); assertThat(requestWith(acceptHeader(CURRENT_VERSION), contentTypeHeader(CURRENT_VERSION), bodyNotPresent()), not(isCompatible())); // tests when body present and one of the headers missing - versioning is required on both when body is present e = expectThrows( ElasticsearchStatusException.class, () -> requestWith(acceptHeader(PREVIOUS_VERSION), contentTypeHeader(null), bodyPresent()) ); assertThat( e.getMessage(), equalTo( "A compatible version is required on both Content-Type and Accept headers " + "if either one has requested a compatible version and the compatible versions must match. " + "Accept=" + acceptHeader(PREVIOUS_VERSION) + ", Content-Type=" + contentTypeHeader(null) ) ); e = expectThrows( ElasticsearchStatusException.class, () -> requestWith(acceptHeader(CURRENT_VERSION), contentTypeHeader(null), bodyPresent()) ); assertThat( e.getMessage(), equalTo( "A compatible version is required on both Content-Type and Accept headers " + "if either one has requested a compatible version. " + "Accept=" + acceptHeader(CURRENT_VERSION) + ", Content-Type=" + contentTypeHeader(null) ) ); e = expectThrows( ElasticsearchStatusException.class, () -> requestWith(acceptHeader(null), contentTypeHeader(CURRENT_VERSION), bodyPresent()) ); assertThat( e.getMessage(), equalTo( "A compatible version is required on both Content-Type and Accept headers " + "if either one has requested a compatible version. " + "Accept=" + acceptHeader(null) + ", Content-Type=" + contentTypeHeader(CURRENT_VERSION) ) ); e = expectThrows( ElasticsearchStatusException.class, () -> requestWith(acceptHeader(null), contentTypeHeader(PREVIOUS_VERSION), bodyPresent()) ); assertThat( e.getMessage(), equalTo( "A compatible version is required on both Content-Type and Accept headers " + "if either one has requested a compatible version and the compatible versions must match. " + "Accept=" + acceptHeader(null) + ", Content-Type=" + contentTypeHeader(PREVIOUS_VERSION) ) ); // tests when body NOT present and one of the headers missing assertThat(requestWith(acceptHeader(PREVIOUS_VERSION), contentTypeHeader(null), bodyNotPresent()), isCompatible()); assertThat(requestWith(acceptHeader(CURRENT_VERSION), contentTypeHeader(null), bodyNotPresent()), not(isCompatible())); // body not present - accept header is missing - it will default to Current version. Version on content type is ignored assertThat(requestWith(acceptHeader(null), contentTypeHeader(PREVIOUS_VERSION), bodyNotPresent()), not(isCompatible())); assertThat(requestWith(acceptHeader(null), contentTypeHeader(CURRENT_VERSION), bodyNotPresent()), not(isCompatible())); assertThat(requestWith(acceptHeader(null), contentTypeHeader(null), bodyNotPresent()), not(isCompatible())); // Accept header = application/json means current version. If body is provided then accept and content-Type should be the same assertThat(requestWith(acceptHeader("application/json"), contentTypeHeader(null), bodyNotPresent()), not(isCompatible())); assertThat( requestWith(acceptHeader("application/json"), contentTypeHeader("application/json"), bodyPresent()), not(isCompatible()) ); assertThat(requestWith(acceptHeader(null), contentTypeHeader("application/json"), bodyPresent()), not(isCompatible())); } public void testObsoleteVersion() { ElasticsearchStatusException e = expectThrows( ElasticsearchStatusException.class, () -> requestWith(acceptHeader(OBSOLETE_VERSION), contentTypeHeader(OBSOLETE_VERSION), bodyPresent()) ); assertThat( e.getMessage(), equalTo( "Accept version must be either version " + CURRENT_VERSION + " or " + PREVIOUS_VERSION + ", but found " + OBSOLETE_VERSION + ". " + "Accept=" + acceptHeader(OBSOLETE_VERSION) ) ); e = expectThrows( ElasticsearchStatusException.class, () -> requestWith(acceptHeader(OBSOLETE_VERSION), contentTypeHeader(null), bodyNotPresent()) ); assertThat( e.getMessage(), equalTo( "Accept version must be either version " + CURRENT_VERSION + " or " + PREVIOUS_VERSION + ", but found " + OBSOLETE_VERSION + ". " + "Accept=" + acceptHeader(OBSOLETE_VERSION) ) ); e = expectThrows( ElasticsearchStatusException.class, () -> requestWith(acceptHeader(PREVIOUS_VERSION), contentTypeHeader(OBSOLETE_VERSION), bodyPresent()) ); assertThat( e.getMessage(), equalTo( "Content-Type version must be either version " + CURRENT_VERSION + " or " + PREVIOUS_VERSION + ", but found " + OBSOLETE_VERSION + ". " + "Content-Type=" + contentTypeHeader(OBSOLETE_VERSION) ) ); } public void testMediaTypeCombinations() { // body not present - ignore content-type assertThat(requestWith(acceptHeader(null), contentTypeHeader(PREVIOUS_VERSION), bodyNotPresent()), not(isCompatible())); assertThat(requestWith(acceptHeader(null), contentTypeHeader("application/json"), bodyNotPresent()), not(isCompatible())); assertThat(requestWith(acceptHeader("*/*"), contentTypeHeader("application/json"), bodyNotPresent()), not(isCompatible())); // this is for instance used by SQL assertThat( requestWith(acceptHeader("application/json"), contentTypeHeader("application/cbor"), bodyPresent()), not(isCompatible()) ); assertThat( requestWith( acceptHeader("application/vnd.elasticsearch+json;compatible-with=7"), contentTypeHeader("application/vnd.elasticsearch+cbor;compatible-with=7"), bodyPresent() ), isCompatible() ); // different versions on different media types expectThrows( ElasticsearchStatusException.class, () -> requestWith( acceptHeader("application/vnd.elasticsearch+json;compatible-with=7"), contentTypeHeader("application/vnd.elasticsearch+cbor;compatible-with=8"), bodyPresent() ) ); } public void testTextMediaTypes() { assertThat( requestWith(acceptHeader("text/tab-separated-values"), contentTypeHeader("application/json"), bodyNotPresent()), not(isCompatible()) ); assertThat(requestWith(acceptHeader("text/plain"), contentTypeHeader("application/json"), bodyNotPresent()), not(isCompatible())); assertThat(requestWith(acceptHeader("text/csv"), contentTypeHeader("application/json"), bodyNotPresent()), not(isCompatible())); // versioned assertThat( requestWith( acceptHeader("text/vnd.elasticsearch+tab-separated-values;compatible-with=7"), contentTypeHeader(7), bodyNotPresent() ), isCompatible() ); assertThat( requestWith(acceptHeader("text/vnd.elasticsearch+plain;compatible-with=7"), contentTypeHeader(7), bodyNotPresent()), isCompatible() ); assertThat( requestWith(acceptHeader("text/vnd.elasticsearch+csv;compatible-with=7"), contentTypeHeader(7), bodyNotPresent()), isCompatible() ); } public void testVersionParsing() { byte version = randomNonNegativeByte(); assertThat( RestCompatibleVersionHelper.parseVersion( ParsedMediaType.parseMediaType("application/vnd.elasticsearch+json;compatible-with=" + version) ), equalTo(version) ); assertThat( RestCompatibleVersionHelper.parseVersion( ParsedMediaType.parseMediaType("application/vnd.elasticsearch+cbor;compatible-with=" + version) ), equalTo(version) ); assertThat( RestCompatibleVersionHelper.parseVersion( ParsedMediaType.parseMediaType("application/vnd.elasticsearch+smile;compatible-with=" + version) ), equalTo(version) ); assertThat( RestCompatibleVersionHelper.parseVersion( ParsedMediaType.parseMediaType("application/vnd.elasticsearch+x-ndjson;compatible-with=" + version) ), equalTo(version) ); assertThat(RestCompatibleVersionHelper.parseVersion(ParsedMediaType.parseMediaType("application/json")), nullValue()); assertThat( RestCompatibleVersionHelper.parseVersion( ParsedMediaType.parseMediaType("APPLICATION/VND.ELASTICSEARCH+JSON;COMPATIBLE-WITH=" + version) ), equalTo(version) ); assertThat(RestCompatibleVersionHelper.parseVersion(ParsedMediaType.parseMediaType("APPLICATION/JSON")), nullValue()); assertThat(RestCompatibleVersionHelper.parseVersion(ParsedMediaType.parseMediaType("application/json; sth=123")), is(nullValue())); } private Matcher<Version> isCompatible() { return requestHasVersion(PREVIOUS_VERSION); } private Matcher<Version> requestHasVersion(int version) { return ElasticsearchMatchers.HasPropertyLambdaMatcher.hasProperty(v -> (int) v.major, equalTo(version)); } private String bodyNotPresent() { return ""; } private String bodyPresent() { return "some body"; } private String contentTypeHeader(int version) { return mediaType(String.valueOf(version)); } private String acceptHeader(int version) { return mediaType(String.valueOf(version)); } private String acceptHeader(String value) { return value; } private String contentTypeHeader(String value) { return value; } private String mediaType(String version) { if (version != null) { return "application/vnd.elasticsearch+json;compatible-with=" + version; } return null; } private Version requestWith(String accept, String contentType, String body) { ParsedMediaType parsedAccept = ParsedMediaType.parseMediaType(accept); ParsedMediaType parsedContentType = ParsedMediaType.parseMediaType(contentType); return RestCompatibleVersionHelper.getCompatibleVersion(parsedAccept, parsedContentType, body.isEmpty() == false); } }
40.908377
139
0.617521