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
7d3910ddb2ea292b59cd76d0572f7fd2e8802f80
1,846
/** * Filename: TVGuideListAdapter.java * Author: Peter Piech * Date: 3/15/2013 * Description: TVGuideListAdapter class draws the ListView * from the TVGuideFragment class. */ package edu.rpi.rpimobile; import java.util.List; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import edu.rpi.rpimobile.model.TVChannel; public class TVGuideListAdapter extends BaseAdapter { private Context context; private List<TVChannel> channels; private LayoutInflater inflater; public TVGuideListAdapter(Context context_, List<TVChannel> channels_) { this.context = context_; this.channels = channels_; } @Override public int getCount() { return channels.size(); } @Override public Object getItem(int index) { return channels.get(index); } @Override public long getItemId(int index) { return index; } @Override public View getView(final int index, View convertView, ViewGroup parent) { inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View itemView = inflater.inflate(R.layout.tvguide_list_item, parent, false); TextView tvNetworkName = (TextView) itemView.findViewById(R.id.networkName); TextView tvChannelNum = (TextView) itemView.findViewById(R.id.channelNumber); tvNetworkName.setText(channels.get(index).getNetworkName()); tvChannelNum.setText(channels.get(index).getNumber()); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(channels.get(index).getNetworkURL()))); } }); return itemView; } }
23.666667
106
0.752438
177befd36b7455ac10111efc41a8ae5e26d9a7d8
277
package org.bf2.cos.catalog.camel.maven.connector.validator; import org.bf2.cos.catalog.camel.maven.connector.support.Connector; import com.fasterxml.jackson.databind.node.ObjectNode; public interface Validator { void validate(Connector connector, ObjectNode schema); }
27.7
67
0.812274
bbbb113a004554dac17b2bf5ce157e742838d454
8,877
/* * 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.river.jeri.internal.runtime; import org.apache.river.jeri.internal.runtime.ObjectTable.NoSuchObject; import org.apache.river.logging.Levels; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.OutputStream; import java.lang.reflect.Method; import java.rmi.server.ExportException; import java.rmi.server.Unreferenced; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import net.jini.core.constraint.InvocationConstraints; import net.jini.export.ServerContext; import net.jini.id.Uuid; import net.jini.id.UuidFactory; import net.jini.io.MarshalInputStream; import net.jini.io.UnsupportedConstraintException; import net.jini.jeri.BasicInvocationDispatcher; import net.jini.jeri.InboundRequest; import net.jini.jeri.InvocationDispatcher; import net.jini.jeri.RequestDispatcher; import net.jini.jeri.ServerCapabilities; /** * * @author peter */ public class DgcRequestDispatcher implements RequestDispatcher { private static final Logger logger = Logger.getLogger("net.jini.jeri.BasicJeriExporter"); private static final Collection<Method> dgcDispatcherMethods = new ArrayList<Method>(2); static { Method[] methods = DgcServer.class.getMethods(); for (int i = 0; i < methods.length; i++) { final Method m = methods[i]; AccessController.doPrivileged(new PrivilegedAction() { public Object run() { m.setAccessible(true); return null; } }); dgcDispatcherMethods.add(m); } } private static final ServerCapabilities dgcServerCapabilities = new ServerCapabilities() { public InvocationConstraints checkConstraints( InvocationConstraints constraints) throws UnsupportedConstraintException { assert constraints.equals(InvocationConstraints.EMPTY); return InvocationConstraints.EMPTY; } }; private final Unreferenced unrefCallback; private final ObjectTable table; private final ConcurrentMap<Uuid,Target> idTable = new ConcurrentHashMap<Uuid,Target>(); private final AtomicInteger dgcEnabledCount = new AtomicInteger(); // guarded by idTable lock private final InvocationDispatcher dgcDispatcher; private final DgcServer dgcServer; DgcRequestDispatcher(Unreferenced unrefCallback, ObjectTable table ) { this.unrefCallback = unrefCallback; this.table = table; try { dgcDispatcher = new BasicInvocationDispatcher( dgcDispatcherMethods, dgcServerCapabilities, null, null, this.getClass().getClassLoader()) { protected ObjectInputStream createMarshalInputStream( Object impl, InboundRequest request, boolean integrity, Collection context) throws IOException { ClassLoader loader = getClassLoader(); return new MarshalInputStream( request.getRequestInputStream(), loader, integrity, loader, Collections.unmodifiableCollection(context)); // useStreamCodebases() not invoked } }; } catch (ExportException e) { throw new AssertionError(); } this.dgcServer = table.getDgcServer(this); } boolean forTable(ObjectTable table) { return this.table == table; } boolean isReferenced() { return !idTable.isEmpty(); } Target get(Uuid id) { return idTable.get(id); } void put(Target target) throws ExportException { Uuid id = target.getObjectIdentifier(); if (id.equals(Jeri.DGC_ID)) { throw new ExportException( "object identifier reserved for DGC"); } Target exists = idTable.putIfAbsent(id, target); if (exists != null){ throw new ExportException( "object identifier already in use"); } if (target.getEnableDGC()) { dgcEnabledCount.incrementAndGet(); } } void remove(Target target, boolean gc) { Uuid id = target.getObjectIdentifier(); boolean removed = idTable.remove(id, target); if (target.getEnableDGC() && removed) { int count = dgcEnabledCount.decrementAndGet(); assert count >= 0; } if (gc && idTable.isEmpty()) { /* * We have to be careful to make this callback without holding * the lock for idTable, because the callback implementation * will likely be code that calls this object's isReferenced * method in its own synchronized block. * * This also means it is possible (although unlikely) for the * idtable to become non empty before making this call. */ unrefCallback.unreferenced(); } } private boolean hasDgcEnabledTargets() { return dgcEnabledCount.get() > 0; } public void dispatch(InboundRequest request) { try { InputStream in = request.getRequestInputStream(); Uuid id = UuidFactory.read(in); Target target = null; if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "id={0}", id); } try { /* * The DGC object identifier is hardwired here, * rather than install it in idTable; this * eliminates the need to worry about not counting * the DGC server as an exported object in the * table, and it doesn't need all of the machinery * that Target provides. */ if (id.equals(Jeri.DGC_ID)) { dispatchDgcRequest(request); return; } target = get(id); if (target == null) { logger.log(Level.FINEST, "id not in table"); throw new NoSuchObject(); } target.dispatch(request); } catch (NoSuchObject e) { in.close(); OutputStream out = request.getResponseOutputStream(); out.write(Jeri.NO_SUCH_OBJECT); out.close(); if (logger.isLoggable(Levels.FAILED)) { logger.log(Levels.FAILED, "no such object: {0}", id); } } } catch (IOException e) { request.abort(); if (logger.isLoggable(Levels.FAILED)) { logger.log(Levels.FAILED, "I/O exception dispatching request", e); } } } private void dispatchDgcRequest(final InboundRequest request) throws IOException, NoSuchObject { if (!hasDgcEnabledTargets()) { logger.log(Level.FINEST, "no DGC-enabled targets"); throw new NoSuchObject(); } OutputStream out = request.getResponseOutputStream(); out.write(Jeri.OBJECT_HERE); final Collection context = new ArrayList(5); request.populateContext(context); ServerContext.doWithServerContext(new Runnable() { public void run() { dgcDispatcher.dispatch(dgcServer, request, context); } }, Collections.unmodifiableCollection(context)); } }
35.086957
98
0.613946
6534ad5219396035faf2025e454109ec0595289e
1,835
package com.liangwenchao.android.utils.bitmap; import android.content.Context; import android.graphics.Bitmap; import android.os.Environment; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.util.UUID; /** * Created by LiangWenchao on 2016/8/5. */ public class BitmapUtils { /** * 压缩图片并保存 * @param bitmap 原图片 * @param format 压缩格式 * @param quality 压缩质量 * @param destFile 压缩后的文件 * @return 压缩后的路径 */ public static String save(Bitmap bitmap, Bitmap.CompressFormat format, int quality, File destFile){ try { FileOutputStream out = new FileOutputStream(destFile); if(bitmap.compress(format,quality,out)){ out.flush(); out.close(); } if(bitmap!=null &&!bitmap.isRecycled()){ bitmap.recycle(); } return destFile.getAbsolutePath(); } catch (Exception e){ e.printStackTrace(); } return null; } /** * 压缩图片并保存 * @param bitmap 原图片 * @param format 压缩格式 * @param quailty 压缩质量 * @param context 上下文 * @return 压缩后的路径 */ public static String save(Bitmap bitmap, Bitmap.CompressFormat format, int quailty, Context context){ if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ Toast.makeText(context,"请插入SD卡",Toast.LENGTH_SHORT).show(); return null; } File destDir = new File(Environment.getExternalStorageDirectory() + "/" + context.getPackageName() + "/image/"); if(!destDir.exists()){ destDir.mkdirs(); } File destFile = new File(destDir, UUID.randomUUID().toString()); return save(bitmap,format,quailty,destFile); } }
28.671875
120
0.60545
1f8138c2ca007c4e3488025f0e18ab1f3b707c4a
1,721
package leetcode.medium; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** @author : Gaurav Kaushik https://leetcode.com/kaushikgaurav08/ https://www.linkedin.com/in/gvk28/ https://github.com/gauravkaushik ======================================================================== https://leetcode.com/problems/permutations-ii/ ======================================================================== Given a collection of numbers that might contain duplicates, return all possible unique permutations. Example: Input: [1,1,2] Output: [ [1,1,2], [1,2,1], [2,1,1] ] */ public class PermutationsII { public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> res = new ArrayList<>(); boolean[] visited = new boolean[nums.length]; List<Integer> temp = new ArrayList<>(); Arrays.sort(nums); dfs(nums, visited, temp, res); return res; } private void dfs(int[] nums, boolean[] visited, List<Integer> temp, List<List<Integer>> res) { if(temp.size() == nums.length) { res.add(new ArrayList<>(temp)); return; } long prev = Long.MIN_VALUE; for(int i=0; i<nums.length; i++) { if(prev!=nums[i] && visited[i] == false) { visited[i] = true; temp.add(nums[i]); dfs(nums, visited, temp, res); temp.remove(temp.size()-1); visited[i] = false; prev = (long)nums[i]; } } } }
24.585714
101
0.471238
59b7f11fdc4448f7a36ece106e7a1c3401c383a9
3,867
import java.rmi.Naming; import javax.swing.JOptionPane; public class Client { static String state = null; static Bank selected = null; static int key = -1; public static void main(String[] args) { try { // Requisita todos os Bancos com qual existe o "convênio" Bank bank1 = (Bank) Naming.lookup("//127.0.0.1:1099/BancoService"); Bank bank2 = (Bank) Naming.lookup("//127.0.0.1:1099/BancoService2"); Bank bank3 = (Bank) Naming.lookup("//127.0.0.1:1099/BancoService3"); String nomeBanco = ""; // Irá Executar o Programa em Loop inicio: while (true) { // Irá Exibir a Caixa de Dialogo até o momento em que o numero do cartão estiver // correto boolean existe = false; while (!existe) { // REcebe o numero do cartão String n = JOptionPane.showInputDialog("Número do Cartão: "); // Faz a pesquisa em todos os bancos para ver a existência do usuario if (bank1.getAccount(n) != -1) { state = n; selected = bank1; existe = true; nomeBanco = bank1.getName(); } else if (bank2.getAccount(n) != -1) { state = n; selected = bank2; existe = true; nomeBanco = bank2.getName(); } else if (bank3.getAccount(n) != -1) { state = n; selected = bank3; existe = true; nomeBanco = bank3.getName(); } } // Enquanto a Operação não for finalizada irá aparecer as opções operacoes: while (key != 4) { // Caso nada seja selecionado, ou seja, janela for fechada, o programa encerra if (selected != null) { // lista de Opções Object[] options = { "Deposito", "Saque", "Extrato", "Transferência", "Encerrar Operação" }; // Recebe a opção selecionada int menu = JOptionPane.showOptionDialog(null, "Qual operação você deseja Realizar ?", "Bem Vindo ao " + nomeBanco, JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); // Realiza a operação de acordo com a opção selecionada switch (menu) { // Deposito case 0: { String valor = JOptionPane.showInputDialog("Valor: "); String senha = JOptionPane.showInputDialog("Senha: "); selected.makeDeposit(state, senha, Double.valueOf(valor)); break; } // Saque case 1: { String valor = JOptionPane.showInputDialog("Valor: "); String senha = JOptionPane.showInputDialog("Senha: "); selected.makeWithdraw(state, senha, Double.valueOf(valor)); break; } // Extrato case 2: { selected.getSale(state); break; } // Trasferência case 3: { String valor = JOptionPane.showInputDialog("Valor: "); String conta = JOptionPane.showInputDialog("Conta à receber: "); String senha = JOptionPane.showInputDialog("Senha: "); selected.makeTransfer(state, conta, senha, Double.valueOf(valor)); break; } // Encerrar Operação case 4: { state = null; selected = null; break operacoes; } default: { break inicio; } } } else { // Encerra o Programa JOptionPane.showMessageDialog(null, "Inserir o cartão corretamente!", "", JOptionPane.ERROR_MESSAGE); break inicio; } } } } catch (Exception e) { e.printStackTrace(); } } }
33.051282
116
0.528575
aa0c4f7b3838de57d49ff6d098805bc5b16d8c58
1,578
/* * Copyright (c) 2015 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.spotify.heroic.aggregation; import lombok.Data; import java.util.Optional; import java.util.concurrent.TimeUnit; @Data public class Options implements Aggregation { public static final String NAME = "opts"; public static final long DEFAULT_SIZE = TimeUnit.MILLISECONDS.convert(60, TimeUnit.MINUTES); private final Optional<SamplingQuery> sampling; private final Optional<Aggregation> aggregation; @Override public AggregationInstance apply(final AggregationContext context) { return aggregation .orElse(Empty.INSTANCE) .apply(context.withOptions(sampling.flatMap(SamplingQuery::getSize), sampling.flatMap(SamplingQuery::getExtent))); } }
34.304348
96
0.739544
4bb312ef58101b802bd5feff45938f6196141752
1,725
/*! (c) Copyright 2015 - 2018 Micro Focus or one of 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 // // Apache License 2.0 - Apache Software Foundation // www.apache.org // Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION ... // // 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.hpe.leanft.selenium; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ByTextTest { private By.ByText _byStrategyUnderTest; @Before public void setUp() { _byStrategyUnderTest = (By.ByText) By.visibleText("some string"); } @Test(expected = IllegalArgumentException.class) public void constructor_ShouldThrowExceptionInCaseConstructedWithNull() { _byStrategyUnderTest = (By.ByText) By.visibleText(null, By.FLAGS.CASE_INSENSITIVE); } @Test(expected = IllegalArgumentException.class) public void constructor_ShouldThrowExceptionInCaseConstructedWithEmpty() { _byStrategyUnderTest = (By.ByText) By.visibleText("", By.FLAGS.CASE_INSENSITIVE); } @Test public void toString_ShouldReturnText() { _byStrategyUnderTest.toString(); assertEquals("By.visibleText: \"some string\"", _byStrategyUnderTest.toString()); } }
34.5
122
0.764058
abbd5e35cddeb24f985cbb07513d45120b69b759
2,101
/* Ball.java created on Dec, 19, 2016 * * Copyright (c) <2016> Pin-Ying Tu <dbi1463@gmail.com> * * This file is part of MVCExample under the MIT license. * * 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 tw.funymph.example.mvc.model; /** * This class represents a rolled out lottery ball. * * @author Pin-Ying Tu * @version 1.0 * @since 1.0 */ public class Ball { private int number; private boolean special; /** * Construct a ball with its number and whether the number * is special or not. * * @param ballNumber the ball number * @param specialBall true if the number is special */ Ball(int ballNumber, boolean specialBall) { number = ballNumber; special = specialBall; } /** * Get whether the ball number is special or not. * * @return true if the ball number is special */ public boolean isSpecial() { return special; } /** * Get the ball number. * * @return the ball number */ public int getNumber() { return number; } }
30.449275
81
0.693003
a03b1086709f7077892e500d540d177de68f3add
12,545
/* ============================================================================= * * COPYRIGHT 2010 BBN Technologies Corp. * 1300 North 17th Street, Suite 600 * Arlington, VA 22209 * (703) 284-1200 * * This program is the subject of intellectual property rights * licensed from BBN Technologies * * This legend must continue to appear in the source code * despite modifications or enhancements by any party. * * * ============================================================================== */ package com.bbn.c2s2.pint.client.ui; import java.awt.Dimension; import java.sql.Date; import java.util.ArrayList; import java.util.List; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.AbstractTableModel; import com.bbn.c2s2.pint.rdf.RDFHelper; import com.bbn.c2s2.util.Constants; import com.bbn.c2s2.util.ObservationLoader; import com.hp.hpl.jena.rdf.model.Model; import edu.jhuapl.c2s2.processfinderenterprisebus.DetectedProcess; import edu.jhuapl.c2s2.processfinderenterprisebus.ObservationToActivityMapping; public class ResultsPanel extends JPanel { private static final long serialVersionUID = 1115124904413317852L; private DefaultListModel _resListModel; private Model _rnrm; private ObservationIndex _obsIndex; private MappingTableModel _tblMappingModel; // components private JTextField _tfScore; private JTextField _tfMaxDistance; private JTextField _tfEarliest; private JTextField _tfLatest; private JTextField _tfMaxTimespan; public ResultsPanel() { super(); initializeComponents(); } public void setObservationIndex(ObservationIndex obsIndex) { _obsIndex = obsIndex; _tblMappingModel.setObservationIndex(obsIndex); } public void setModel(Model rnrm) { _rnrm = rnrm; // update the results table _tblMappingModel.setModel(rnrm); // update each of the DPListItems List<DPListItem> items = new ArrayList<DPListItem>(_resListModel.size()); for (int i = 0; i < _resListModel.size(); i++) { items.add((DPListItem) _resListModel.get(i)); } _resListModel.clear(); for (DPListItem item : items) { item.setModel(rnrm); _resListModel.addElement(item); } } public void clearResults() { // clear mapping table _tblMappingModel.setDetectedProcess(null); // clear list of results _resListModel.clear(); // clear eval score _tfScore.setText(""); _tfEarliest.setText(""); _tfLatest.setText(""); _tfMaxDistance.setText(""); _tfMaxTimespan.setText(""); } private void initializeComponents() { setBorder(BorderFactory.createTitledBorder("Results")); setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); // #### Result list add(createResultListPanel()); // #### DetectedProcess add(createDetectedProcessPanel()); } private JPanel createResultListPanel() { JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.LINE_AXIS)); // _resListModel = new ResultsListModel(rnrm); _resListModel = new DefaultListModel(); JList list = new JList(_resListModel); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent lse) { if (!lse.getValueIsAdjusting()) { JList src = (JList) lse.getSource(); if (null != src) { DPListItem item = (DPListItem) (src.getSelectedValue()); if (null != item) { setSelectedProcess(item.getDetectedProcess()); } } } } }); JScrollPane scroll = new JScrollPane(list); scroll.setMinimumSize(new Dimension(150, 200)); scroll.setPreferredSize(new Dimension(150, 200)); scroll.setMaximumSize(new Dimension(150, Integer.MAX_VALUE)); p.add(scroll); return p; } private String secondsToDateString(double seconds) { String rv = ""; Date d = new Date((long) seconds * 1000); rv = Constants.DATE_FORMAT_SHORT.format(d); return rv; } private String secondsToElapsedTime(double seconds) { int hours = (int) Math.floor(seconds / 3600); double rem = seconds - (hours * 3600); int minutes = (int) Math.floor(rem / 60); rem = rem - (minutes * 60); return String.format("%1$2d:%2$2d:%3$2.0f", hours, minutes, rem); } private void setSelectedProcess(DetectedProcess proc) { // update evaluation score _tfScore.setText(String.format("%1$1.4f", proc.getScore())); _tfEarliest.setText(secondsToDateString(proc .getEarliestObservationTimeStamp())); _tfLatest.setText(secondsToDateString(proc .getLatestObservationTimeStamp())); _tfMaxDistance.setText(String.format("%1$1.4f", proc .getDetectedProcessMaximumDistanceInMeters())); _tfMaxTimespan.setText(secondsToElapsedTime(proc .getDetectedProcessTimeSpanInSeconds())); // TODO: update result properties // update mappings table _tblMappingModel.setDetectedProcess(proc); } private JPanel createDetectedProcessPanel() { JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS)); p.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // #### score and properties - top row JPanel pScoreProps = new JPanel(); pScoreProps.setLayout(new BoxLayout(pScoreProps, BoxLayout.LINE_AXIS)); pScoreProps.setAlignmentY(TOP_ALIGNMENT); // Score field JPanel pField = new JPanel(); pField.setAlignmentY(TOP_ALIGNMENT); pField.setLayout(new BoxLayout(pField, BoxLayout.LINE_AXIS)); JLabel lField = new JLabel("Evalution Score:"); _tfScore = new JTextField(8); Dimension d = new Dimension(50, 20); _tfScore.setPreferredSize(d); _tfScore.setMaximumSize(d); _tfScore.setMinimumSize(d); _tfScore.setEditable(false); pField.add(lField); pField.add(Box.createRigidArea(new Dimension(10, 0))); pField.add(_tfScore); pScoreProps.add(pField); pScoreProps.add(Box.createRigidArea(new Dimension(10, 0))); // Max Distance field pField = new JPanel(); pField.setAlignmentY(TOP_ALIGNMENT); pField.setLayout(new BoxLayout(pField, BoxLayout.LINE_AXIS)); lField = new JLabel("Max Distance (m):"); _tfMaxDistance = new JTextField(8); d = new Dimension(70, 20); _tfMaxDistance.setPreferredSize(d); _tfMaxDistance.setMaximumSize(d); _tfMaxDistance.setMinimumSize(d); _tfMaxDistance.setEditable(false); pField.add(lField); pField.add(Box.createRigidArea(new Dimension(10, 0))); pField.add(_tfMaxDistance); pScoreProps.add(pField); pScoreProps.add(Box.createRigidArea(new Dimension(10, 0))); // Max Time field pField = new JPanel(); pField.setAlignmentY(TOP_ALIGNMENT); pField.setLayout(new BoxLayout(pField, BoxLayout.LINE_AXIS)); lField = new JLabel("Max Timespan (s):"); _tfMaxTimespan = new JTextField(12); d = new Dimension(80, 20); _tfMaxTimespan.setPreferredSize(d); _tfMaxTimespan.setMaximumSize(d); _tfMaxTimespan.setMinimumSize(d); _tfMaxTimespan.setEditable(false); pField.add(lField); pField.add(Box.createRigidArea(new Dimension(10, 0))); pField.add(_tfMaxTimespan); pScoreProps.add(pField); pScoreProps.add(Box.createHorizontalGlue()); p.add(pScoreProps); p.add(Box.createRigidArea(new Dimension(0, 5))); // #### score and properties - 2nd row pScoreProps = new JPanel(); pScoreProps.setLayout(new BoxLayout(pScoreProps, BoxLayout.LINE_AXIS)); pScoreProps.setAlignmentY(TOP_ALIGNMENT); // Earliest time field pField = new JPanel(); pField.setAlignmentY(TOP_ALIGNMENT); pField.setLayout(new BoxLayout(pField, BoxLayout.LINE_AXIS)); lField = new JLabel("Earliest Time (s):"); _tfEarliest = new JTextField(16); d = new Dimension(100, 20); _tfEarliest.setPreferredSize(d); _tfEarliest.setMaximumSize(d); _tfEarliest.setMinimumSize(d); _tfEarliest.setEditable(false); pField.add(lField); pField.add(Box.createRigidArea(new Dimension(10, 0))); pField.add(_tfEarliest); pScoreProps.add(pField); pScoreProps.add(Box.createRigidArea(new Dimension(10, 0))); // Latest time field pField = new JPanel(); pField.setAlignmentY(TOP_ALIGNMENT); pField.setLayout(new BoxLayout(pField, BoxLayout.LINE_AXIS)); lField = new JLabel("Latest Time (s):"); _tfLatest = new JTextField(16); d = new Dimension(100, 20); _tfLatest.setPreferredSize(d); _tfLatest.setMaximumSize(d); _tfLatest.setMinimumSize(d); _tfLatest.setEditable(false); pField.add(lField); pField.add(Box.createRigidArea(new Dimension(10, 0))); pField.add(_tfLatest); pScoreProps.add(pField); pScoreProps.add(Box.createHorizontalGlue()); p.add(pScoreProps); // #### mapping table JPanel pBindings = new JPanel(); pBindings.setLayout(new BoxLayout(pBindings, BoxLayout.LINE_AXIS)); _tblMappingModel = new MappingTableModel(null, _obsIndex, _rnrm); JTable mapTable = new JTable(_tblMappingModel); JScrollPane scroll = new JScrollPane(mapTable); scroll.setPreferredSize(new Dimension(-1, 200)); scroll.setMinimumSize(scroll.getPreferredSize()); pBindings.add(scroll); pBindings.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); p.add(pBindings); return p; } public void setResults(List<DetectedProcess> processes) { _resListModel.clear(); for (DetectedProcess proc : processes) { DPListItem item = new DPListItem(proc, _rnrm); _resListModel.addElement(item); } } @Override public Dimension getMinimumSize() { return new Dimension(500, 400); } @Override public Dimension getPreferredSize() { return new Dimension(500, 400); } class DPListItem { private DetectedProcess _dp; private Model _rnrm; DPListItem(DetectedProcess proc) { this(proc, null); } DPListItem(DetectedProcess proc, Model rnrm) { _dp = proc; _rnrm = rnrm; } @Override public String toString() { String rv = _dp.getProcessIdUri(); if (null != _rnrm) { rv = RDFHelper.getLabel(_rnrm, rv); } return rv; } public DetectedProcess getDetectedProcess() { return _dp; } public void setModel(Model rnrm) { _rnrm = rnrm; } } class MappingTableModel extends AbstractTableModel { private static final long serialVersionUID = 7160317490178615265L; final String[] _colNames = { "Activity", "Observation", "Time", "Latitude", "Longitude" }; private DetectedProcess _dp; private Model _rnrm; private ObservationIndex _obsIndex; MappingTableModel(DetectedProcess dp, ObservationIndex obsIndex, Model rnrm) { _dp = dp; _rnrm = rnrm; _obsIndex = obsIndex; } public void setObservationIndex(ObservationIndex obsIndex) { _obsIndex = obsIndex; } public void setModel(Model rnrm) { _rnrm = rnrm; fireTableDataChanged(); } public void setDetectedProcess(DetectedProcess dp) { _dp = dp; fireTableDataChanged(); } @Override public String getColumnName(int column) { return _colNames[column]; } @Override public int getColumnCount() { return _colNames.length; } @Override public int getRowCount() { int rv = 0; if (null != _dp) { return _dp.getDetectedActivities().size(); } return rv; } @Override public Object getValueAt(int row, int col) { // TODO: handle case where the _obsIndex is empty because a new // empty set of results has been added Object rv = null; ObservationToActivityMapping binding = _dp.getDetectedActivities() .get(row); boolean unbound = (null == binding.getObservationUri()); switch (col) { case 0: rv = RDFHelper.getLabel(_rnrm, binding.getActivityUri()); break; case 1: rv = (unbound) ? " ---UNBOUND--- " : ObservationLoader .getLabel(binding.getObservationUri()); break; case 2: rv = (unbound) ? " ----- " : _obsIndex.getObservation( binding.getObservationUri()).getObservationTime() .toXMLFormat(); break; case 3: rv = (unbound) ? " ----- " : _obsIndex.getObservation( binding.getObservationUri()).getLocation() .getLatitude(); break; case 4: rv = (unbound) ? " ----- " : _obsIndex.getObservation( binding.getObservationUri()).getLocation() .getLongitude(); break; default: rv = "UNKNOWN COLUMN"; } return rv; } } }
29.039352
81
0.706018
3fee3300bd8be2277c2a4ef114becc8e46e3513c
391
package com.github.forax.vmboiler.sample.script; import java.util.Objects; public class Binding { private Type type; public Binding(Type type) { this.type = Objects.requireNonNull(type); } public Type type() { return type; } public void type(Type type) { this.type = type; } @Override public String toString() { return "binding(" + type + ')'; } }
16.291667
48
0.644501
266c5845cf2fb49fbad3d6376b9dd519e2f72195
3,286
/* PLEASE DO NOT EDIT THIS FILE */ package cool; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.BaseErrorListener; import org.antlr.v4.runtime.Recognizer; import org.antlr.v4.runtime.RecognitionException; public class LexerTest { static String[] TOKENS = {"ERROR", "TYPEID", "OBJECTID", "BOOL_CONST", "INT_CONST", "STR_CONST", "'('", "')'", "':'", "'@'", "';'", "','", "'+'", "'-'", "'*'", "'/'", "'~'", "'<'", "'='", "'{'", "'}'", "'.'", "DARROW", "LE", "ASSIGN", "CLASS", "ELSE", "FI", "IF", "IN", "INHERITS", "LET", "LOOP", "POOL", "THEN", "WHILE", "CASE", "ESAC", "OF", "NEW", "ISVOID", "NOT" }; static int VALUED_INDEX_LIMIT = 6; static int EOF_TYPEID = -1; public static void main(String args[]) { if(args.length < 1) { System.err.println("No files given"); System.exit(1); } for(String filename : args) printTokenStream(filename); } static String escapeSpecialCharacters(String text) { return text .replaceAll("\\\\", "\\\\\\\\") .replaceAll("\n", "\\\\n") .replaceAll("\t", "\\\\t") .replaceAll("\b", "\\\\b") .replaceAll("\f", "\\\\f") .replaceAll("\"", "\\\\\"") .replaceAll("\r", "\\\\015") .replaceAll("\033","\\\\033") .replaceAll("\001","\\\\001") .replaceAll("\002","\\\\002") .replaceAll("\003","\\\\003") .replaceAll("\004","\\\\004") .replaceAll("\022","\\\\022") .replaceAll("\013","\\\\013") .replaceAll("\000", "\\\\000") ; } static void printTokenStream(String filename) { //create input stream ANTLRInputStream inStream = null; try { inStream = new ANTLRInputStream(new FileInputStream(filename)); } catch(IOException e) { System.err.println("Cannot read input file."); System.exit(1); } CoolLexer lexer = new CoolLexer(inStream); //Call Lexer API for token stream CommonTokenStream tokens = new CommonTokenStream(lexer); tokens.fill(); //printing the name of the file String name = filename.substring(filename.lastIndexOf('/') + 1); System.out.println("#name \"" + name + "\""); final int BOOL_CONST_INDEX = Arrays.asList(TOKENS).indexOf("BOOL_CONST"); final int STR_CONST_INDEX = Arrays.asList(TOKENS).indexOf("STR_CONST"); final int ERROR_INDEX = Arrays.asList(TOKENS).indexOf("ERROR"); //Print tokens int typeid; for(Token t: tokens.getTokens()) { typeid = t.getType(); if(typeid > TOKENS.length){ System.out.println("Invalid Token generated - Token id : "+typeid+" for text \""+t.getText()+"\""); continue; } if(typeid != EOF_TYPEID) { String output = String.format("#%d %s", t.getLine(), TOKENS[typeid - 1]); if(typeid <= VALUED_INDEX_LIMIT) { if(typeid - 1 == BOOL_CONST_INDEX) output += " " + t.getText().toLowerCase(); else if(typeid - 1 == STR_CONST_INDEX) output += " \"" + escapeSpecialCharacters(t.getText()) + "\""; else if(typeid - 1 == ERROR_INDEX) output += " \"" + escapeSpecialCharacters(t.getText()) + "\""; else output += " " + t.getText(); } System.out.println(output); } } } }
28.573913
367
0.599817
dc5b562a87925a06a943d0e09fb2bb1abd225811
7,510
/** * 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.mahout.clustering.meanshift; import java.util.Collection; import java.util.List; import com.google.common.collect.Lists; import org.apache.hadoop.conf.Configuration; import org.apache.mahout.clustering.kernel.IKernelProfile; import org.apache.mahout.common.ClassUtils; import org.apache.mahout.common.distance.DistanceMeasure; import org.apache.mahout.math.Vector; public class MeanShiftCanopyClusterer { private final double convergenceDelta; // the T1 distance threshold private final double t1; // the T2 distance threshold private final double t2; // the distance measure private final DistanceMeasure measure; private final IKernelProfile kernelProfile; // if true accumulate clusters during merge so clusters can be produced later private final boolean runClustering; public MeanShiftCanopyClusterer(Configuration configuration) { measure = ClassUtils.instantiateAs(configuration.get(MeanShiftCanopyConfigKeys.DISTANCE_MEASURE_KEY), DistanceMeasure.class); measure.configure(configuration); runClustering = configuration.getBoolean(MeanShiftCanopyConfigKeys.CLUSTER_POINTS_KEY, true); kernelProfile = ClassUtils.instantiateAs(configuration.get(MeanShiftCanopyConfigKeys.KERNEL_PROFILE_KEY), IKernelProfile.class); // nextCanopyId = 0; // never read? t1 = Double .parseDouble(configuration.get(MeanShiftCanopyConfigKeys.T1_KEY)); t2 = Double .parseDouble(configuration.get(MeanShiftCanopyConfigKeys.T2_KEY)); convergenceDelta = Double.parseDouble(configuration .get(MeanShiftCanopyConfigKeys.CLUSTER_CONVERGENCE_KEY)); } public MeanShiftCanopyClusterer(DistanceMeasure aMeasure, IKernelProfile aKernelProfileDerivative, double aT1, double aT2, double aDelta, boolean runClustering) { // nextCanopyId = 100; // so canopyIds will sort properly // never read? measure = aMeasure; t1 = aT1; t2 = aT2; convergenceDelta = aDelta; kernelProfile = aKernelProfileDerivative; this.runClustering = runClustering; } public double getT1() { return t1; } public double getT2() { return t2; } /** * Merge the given canopy into the canopies list. If it touches any existing * canopy (norm<T1) then add the center of each to the other. If it covers any * other canopies (norm<T2), then merge the given canopy with the closest * covering canopy. If the given canopy does not cover any other canopies, add * it to the canopies list. * * @param aCanopy * a MeanShiftCanopy to be merged * @param canopies * the List<Canopy> to be appended */ public void mergeCanopy(MeanShiftCanopy aCanopy, Collection<MeanShiftCanopy> canopies) { MeanShiftCanopy closestCoveringCanopy = null; double closestNorm = Double.MAX_VALUE; for (MeanShiftCanopy canopy : canopies) { double norm = measure.distance(canopy.getCenter(), aCanopy.getCenter()); double weight = kernelProfile.calculateDerivativeValue(norm, t1); if (weight > 0.0) { aCanopy.touch(canopy, weight); } if (norm < t2 && (closestCoveringCanopy == null || norm < closestNorm)) { closestNorm = norm; closestCoveringCanopy = canopy; } } if (closestCoveringCanopy == null) { canopies.add(aCanopy); } else { closestCoveringCanopy.merge(aCanopy, runClustering); } } /** * Shift the center to the new centroid of the cluster * * @param canopy * the canopy to shift. * @return if the cluster is converged */ public boolean shiftToMean(MeanShiftCanopy canopy) { canopy.observe(canopy.getCenter(), canopy.getMass()); canopy.computeConvergence(measure, convergenceDelta); canopy.computeParameters(); return canopy.isConverged(); } /** * Return if the point is covered by this canopy * * @param canopy * a canopy. * @param point * a Vector point * @return if the point is covered */ boolean covers(MeanShiftCanopy canopy, Vector point) { return measure.distance(canopy.getCenter(), point) < t1; } /** * Return if the point is closely covered by the canopy * * @param canopy * a canopy. * @param point * a Vector point * @return if the point is covered */ public boolean closelyBound(MeanShiftCanopy canopy, Vector point) { return measure.distance(canopy.getCenter(), point) < t2; } /** * This is the reference mean-shift implementation. Given its inputs it * iterates over the points and clusters until their centers converge or until * the maximum number of iterations is exceeded. * * @param points * the input List<Vector> of points * @param measure * the DistanceMeasure to use * @param numIter * the maximum number of iterations */ public static List<MeanShiftCanopy> clusterPoints(Iterable<Vector> points, DistanceMeasure measure, IKernelProfile aKernelProfileDerivative, double convergenceThreshold, double t1, double t2, int numIter) { MeanShiftCanopyClusterer clusterer = new MeanShiftCanopyClusterer(measure, aKernelProfileDerivative, t1, t2, convergenceThreshold, true); int nextCanopyId = 0; List<MeanShiftCanopy> canopies = Lists.newArrayList(); for (Vector point : points) { clusterer.mergeCanopy( new MeanShiftCanopy(point, nextCanopyId++, measure), canopies); } List<MeanShiftCanopy> newCanopies = canopies; boolean[] converged = { false }; for (int iter = 0; !converged[0] && iter < numIter; iter++) { newCanopies = clusterer.iterate(newCanopies, converged); } return newCanopies; } protected List<MeanShiftCanopy> iterate(Iterable<MeanShiftCanopy> canopies, boolean[] converged) { converged[0] = true; List<MeanShiftCanopy> migratedCanopies = Lists.newArrayList(); for (MeanShiftCanopy canopy : canopies) { converged[0] = shiftToMean(canopy) && converged[0]; mergeCanopy(canopy, migratedCanopies); } return migratedCanopies; } protected static MeanShiftCanopy findCoveringCanopy(MeanShiftCanopy canopy, Iterable<MeanShiftCanopy> clusters) { // canopies use canopyIds assigned when input vectors are processed as // vectorIds too int vectorId = canopy.getId(); for (MeanShiftCanopy msc : clusters) { for (int containedId : msc.getBoundPoints().toList()) { if (vectorId == containedId) { return msc; } } } return null; } }
34.608295
109
0.696538
005a10c2167916e5607005a7fcbc0c7f252ef7d8
443
package com.linkedin.samples.pf.dao; import com.linkedin.samples.pf.dto.Customer; import com.linkedin.samples.pf.dto.Order; import java.io.Serializable; import java.util.Collection; /** * * @author SIGINT-X */ public interface OrderDAO<M> extends Serializable { M getOrders(); M getOrders(Customer customer); M getOrders(String customerId); <T> T getOrder(long orderId); <O> O saveOrder(Order order); }
17.038462
51
0.697517
5c63e49d2b981a52efc7617d79d843fedd30ece8
9,261
package services; import java.sql.Connection; import java.sql.SQLException; import org.bson.Document; import org.json.JSONException; import org.json.JSONObject; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import db.Database; import tools.CommentTools; import tools.ErrorJSON; import tools.ErrorTools; import tools.TwistTools; import tools.SessionTools; import tools.UserTools; public class CommentS { public static JSONObject addComment(String key_session,String id_message, String comment) { if(key_session==null || comment==null || id_message==null ) return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_MISSING_PARAMETERS,ErrorTools.CODE_MISSING_PARAMETERS); Connection connection=null; try { //connect to mysql connection = Database.getMySQLConnection(); if(!SessionTools.isConnectedByKey(key_session,connection)) return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_USER_NOT_CONNECTED, ErrorTools.CODE_USER_NOT_CONNECTED); if(SessionTools.hasExceededTimeOut(key_session, connection)) { SessionTools.removeSession(key_session,connection); return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_USER_DISCONNECTED_AUTOMATICALLY, ErrorTools.CODE_USER_DISCONNECTED_AUTOMATICALLY); } //ajout de 30min dans session_fin SessionTools.updateTimeOut(key_session, connection); String id_user = SessionTools.getIdUser(key_session, connection); String login = UserTools.getLogin(id_user, connection); MongoDatabase mongoDatabase=Database.getMongoDBConnection(); MongoCollection<Document> commentCollection = mongoDatabase.getCollection("message"); if(!TwistTools.twistExists(id_message,commentCollection)) return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_TWIST_DOES_NOT_EXIST, ErrorTools.CODE_TWIST_DOES_NOT_EXIST); String firstname = UserTools.getFirstName(id_user, connection); String familyname = UserTools.getFamilyName(id_user, connection); CommentTools.addComment(id_message,firstname, familyname, comment,id_user,login,commentCollection); } catch(JSONException e) { return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_ERROR_JSON, ErrorTools.CODE_ERROR_JSON); }catch(SQLException e) { return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_ERROR_SQL, ErrorTools.CODE_ERROR_SQL); }finally { if(connection!=null) try { connection.close(); } catch (SQLException e) { return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_ERROR_SQL, ErrorTools.CODE_ERROR_SQL); } } return ErrorJSON.serviceAccepted("You have successfully added your comment"); } public static JSONObject removeComment(String key_session,String id_message, String id_comment) { if(key_session==null || id_comment==null || id_message==null ) return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_MISSING_PARAMETERS,ErrorTools.CODE_MISSING_PARAMETERS); Connection connection=null; try { //connect to mysql connection = Database.getMySQLConnection(); if(!SessionTools.isConnectedByKey(key_session,connection)) return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_USER_NOT_CONNECTED,ErrorTools.CODE_USER_NOT_CONNECTED); if(SessionTools.hasExceededTimeOut(key_session, connection)) { SessionTools.removeSession(key_session,connection); return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_USER_DISCONNECTED_AUTOMATICALLY, ErrorTools.CODE_USER_DISCONNECTED_AUTOMATICALLY); } //ajout de 30min dans session_fin SessionTools.updateTimeOut(key_session, connection); MongoDatabase mongoDatabase=Database.getMongoDBConnection(); MongoCollection<Document> commentCollection = mongoDatabase.getCollection("message"); if(!TwistTools.twistExists(id_message,commentCollection)) return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_TWIST_DOES_NOT_EXIST, ErrorTools.CODE_TWIST_DOES_NOT_EXIST); if(!CommentTools.commentExists(id_message, id_comment,commentCollection)) return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_COMMENT_DOES_NOT_EXIST, ErrorTools.CODE_COMMENT_DOES_NOT_EXIST); String id_user = SessionTools.getIdUser(key_session, connection); if(!CommentTools.checkAuthor(id_user,id_message, id_comment, commentCollection)) { return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_NOT_AUTHOR,ErrorTools.CODE_NOT_AUTHOR); } CommentTools.removeComment(id_message,id_comment,commentCollection); return ErrorJSON.serviceAccepted("You have successfully removed a comment"); }catch(SQLException e) { return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_ERROR_SQL, ErrorTools.CODE_ERROR_SQL); }catch(JSONException e) { return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_ERROR_JSON, ErrorTools.CODE_ERROR_JSON); }finally { if(connection!=null) try { connection.close(); } catch (SQLException e) { return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_ERROR_SQL, ErrorTools.CODE_ERROR_SQL); } } } public static JSONObject listComment(String key_session, String id_message) { if(key_session==null || id_message==null ) return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_MISSING_PARAMETERS,ErrorTools.CODE_MISSING_PARAMETERS); Connection connection=null; try { //connect to mysql connection = Database.getMySQLConnection(); if(!SessionTools.isConnectedByKey(key_session,connection)) return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_USER_NOT_CONNECTED,ErrorTools.CODE_USER_NOT_CONNECTED); if(SessionTools.hasExceededTimeOut(key_session, connection)) { SessionTools.removeSession(key_session,connection); return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_USER_DISCONNECTED_AUTOMATICALLY, ErrorTools.CODE_USER_DISCONNECTED_AUTOMATICALLY); } //ajout de 30min dans session_fin SessionTools.updateTimeOut(key_session, connection); MongoDatabase mongoDatabase=Database.getMongoDBConnection(); MongoCollection<Document> commentCollection = mongoDatabase.getCollection("message"); if(!TwistTools.twistExists(id_message,commentCollection)) return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_TWIST_DOES_NOT_EXIST, ErrorTools.CODE_TWIST_DOES_NOT_EXIST); //connect to mongodb return CommentTools.listComment(id_message,commentCollection); }catch(JSONException e) { return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_ERROR_JSON, ErrorTools.CODE_ERROR_JSON); }catch(SQLException e) { return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_ERROR_SQL, ErrorTools.CODE_ERROR_SQL); }finally { if(connection!=null) try { connection.close(); } catch (SQLException e) { return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_ERROR_SQL, ErrorTools.CODE_ERROR_SQL); } } } public static JSONObject EditComment(String key_session, String id_message, String id_comment, String comment) { if(key_session==null || comment==null || id_message==null || id_comment==null) return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_MISSING_PARAMETERS,ErrorTools.CODE_MISSING_PARAMETERS); Connection connection=null; try { //connect to mysql connection = Database.getMySQLConnection(); if(!SessionTools.isConnectedByKey(key_session,connection)) return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_USER_NOT_CONNECTED, ErrorTools.CODE_USER_NOT_CONNECTED); if(SessionTools.hasExceededTimeOut(key_session, connection)) { SessionTools.removeSession(key_session,connection); return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_USER_DISCONNECTED_AUTOMATICALLY, ErrorTools.CODE_USER_DISCONNECTED_AUTOMATICALLY); } //ajout de 30min dans session_fin SessionTools.updateTimeOut(key_session, connection); String id_user = SessionTools.getIdUser(key_session, connection); String login = UserTools.getLogin(id_user, connection); MongoDatabase mongoDatabase=Database.getMongoDBConnection(); MongoCollection<Document> commentCollection = mongoDatabase.getCollection("message"); if(!TwistTools.twistExists(id_message,commentCollection)) return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_TWIST_DOES_NOT_EXIST, ErrorTools.CODE_TWIST_DOES_NOT_EXIST); if(!CommentTools.commentExists(id_message,id_comment,commentCollection)) return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_COMMENT_DOES_NOT_EXIST, ErrorTools.CODE_MAIL_DOES_NOT_EXIST); if(!CommentTools.checkAuthor(id_user,id_message, id_comment, commentCollection)) { return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_NOT_AUTHOR,ErrorTools.CODE_NOT_AUTHOR); } CommentTools.editComment(id_message,id_comment,comment,commentCollection); } catch(JSONException e) { return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_ERROR_JSON, ErrorTools.CODE_ERROR_JSON); }catch(SQLException e) { return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_ERROR_SQL, ErrorTools.CODE_ERROR_SQL); }finally { if(connection!=null) try { connection.close(); } catch (SQLException e) { return ErrorJSON.serviceRefused(ErrorTools.MESSAGE_ERROR_SQL, ErrorTools.CODE_ERROR_SQL); } } return ErrorJSON.serviceAccepted("You have successfully edited your comment"); } }
38.111111
137
0.788036
5517624b0cb49937d26aa81d99c776bdb2cf56d9
4,623
package com.haxademic.demo.draw.shapes; import java.util.ArrayList; import com.haxademic.core.app.P; import com.haxademic.core.app.PAppletHax; import com.haxademic.core.app.config.AppSettings; import com.haxademic.core.app.config.Config; import com.haxademic.core.debug.DebugView; import com.haxademic.core.draw.context.OpenGLUtil; import com.haxademic.core.draw.context.PG; import com.haxademic.core.draw.filters.pshader.CubicLensDistortionFilter; import com.haxademic.core.draw.filters.pshader.DitherFilter; import com.haxademic.core.draw.filters.pshader.GrainFilter; import com.haxademic.core.draw.filters.pshader.RadialFlareFilter; import com.haxademic.core.draw.filters.pshader.SaturationFilter; import com.haxademic.core.draw.filters.pshader.VignetteFilter; import com.haxademic.core.draw.image.ImageUtil; import com.haxademic.core.draw.shapes.PShapeUtil; import com.haxademic.core.draw.shapes.Shapes; import com.haxademic.core.file.FileUtil; import com.haxademic.core.render.FrameLoop; import com.haxademic.core.ui.UI; import processing.core.PGraphics; import processing.core.PImage; import processing.core.PShape; import processing.opengl.PGraphicsOpenGL; import processing.opengl.PShader; public class Demo_Shapes_createTorusMatcap extends PAppletHax { public static void main(String args[]) { arguments = args; PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); } int FRAMES = 60 * 10; protected PShape shape; protected float torusRadius; protected PShader matCapShader; protected ArrayList<PImage> matCapImages; protected String MATCAP_IMG_INDEX = "MATCAP_IMG_INDEX"; protected PGraphics scaleDown; protected void config() { Config.setAppSize(1024, 1024); Config.setProperty(AppSettings.LOOP_FRAMES, FRAMES); Config.setProperty(AppSettings.RENDERING_MOVIE, false); Config.setProperty(AppSettings.RENDERING_MOVIE_START_FRAME, 1 + FRAMES); Config.setProperty(AppSettings.RENDERING_MOVIE_STOP_FRAME, 1 + FRAMES * 2); } protected void firstFrame() { // build texture scaleDown = PG.newPG(p.width / 6, p.height / 6, false, false); ((PGraphicsOpenGL)scaleDown).textureSampling(2); // create torus w/quads torusRadius = p.width * 2; shape = Shapes.createTorus(torusRadius, torusRadius/20, 60, 18, null); // get triangulaed version if desired shape = shape.getTessellation(); // rotate up front for ease of later fancy rotation PShapeUtil.meshRotateOnAxis(shape, P.HALF_PI, P.X); // matcap shader & textures matCapImages = FileUtil.loadImagesFromDir(FileUtil.getPath("haxademic/images/matcap/"), "png,jpg"); matCapShader = p.loadShader( FileUtil.getPath("haxademic/shaders/lights/matcap/matcap-frag.glsl"), FileUtil.getPath("haxademic/shaders/lights/matcap/matcap-vert.glsl") ); UI.addSlider(MATCAP_IMG_INDEX, 25, 0, matCapImages.size() - 1, 1, false); } protected void drawApp() { background(0); PG.setCenterScreen(p.g); // fancier rotating rotation float curRads = -1f * FrameLoop.progressRads(); p.translate(torusRadius * P.cos(curRads), torusRadius * P.sin(curRads), torusRadius/2); // p.rotateX(-curRads); p.rotateZ(curRads); p.rotateY(-curRads); // draw torus // matcap shader p.noLights(); matCapShader.set("range", 0.97f); matCapShader.set("matcap", matCapImages.get(UI.valueInt(MATCAP_IMG_INDEX))); p.shader(matCapShader); // draw mesh w/matcap p.shape(shape); p.resetShader(); // draw extra mesh wireframe p.noFill(); p.stroke(255, 20); p.strokeWeight(2); // PShapeUtil.drawTriangles(p.g, shape, null, 1); // copy to small ImageUtil.copyImage(p.get(), scaleDown); DebugView.setTexture("scaleDown", scaleDown); // postprocessing VignetteFilter.instance(p).setDarkness(0.5f); VignetteFilter.instance(p).setSpread(0.2f); // VignetteFilter.instance(p).applyTo(p.g); CubicLensDistortionFilter.instance(p).setAmplitude(-1f); // CubicLensDistortionFilter.instance(p).applyTo(p.g); SaturationFilter.instance(p).setSaturation(1.4f); SaturationFilter.instance(p).applyTo(scaleDown); GrainFilter.instance(p).setTime(p.frameCount * 0.02f); GrainFilter.instance(p).setCrossfade(0.05f); // GrainFilter.instance(p).applyTo(scaleDown); RadialFlareFilter.instance(p).setImageBrightness(12f); RadialFlareFilter.instance(p).setFlareBrightness(2f); RadialFlareFilter.instance(p).applyTo(scaleDown); DitherFilter.instance(P.p).setDitherMode8x8(); DitherFilter.instance(P.p).applyTo(scaleDown); // draw scaled back up ImageUtil.copyImage(scaleDown, p.g); p.image(scaleDown, 0, 0, p.width, p.height); } }
33.258993
136
0.758382
f6601abf5b92880054b932e04f3462a9deb004ea
910
package com.github.jstN0body.adventofcode.java.day12; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class PassagePathing { public static void main(String[] args) { List<String> caves = new ArrayList<>(); for (String s : args) { String[] ar = s.split("-"); caves.addAll(Arrays.asList(ar)); } for (String s : caves) { new Cave(s, Character.isUpperCase(s.charAt(0)) ? CaveType.LARGE : CaveType.SMALL); } for (String s : args) { String[] ar = s.split("-"); Cave.ALL_CAVES.get(ar[0]).destinations.add(Cave.ALL_CAVES.get(ar[1])); Cave.ALL_CAVES.get(ar[1]).destinations.add(Cave.ALL_CAVES.get(ar[0])); } Cave start = Cave.ALL_CAVES.get("start"); Cave end = Cave.ALL_CAVES.get("end"); new Pathfinder(start, end); } }
32.5
94
0.582418
36f2260fdce2e084771df836b682fe38b1f0eca4
1,391
// Copyright 2000-2021 Nokia // // Licensed under the Apache License 2.0 // SPDX-License-Identifier: Apache-2.0 // package com.nextenso.radius.agent.impl; import com.nextenso.proxylet.radius.RadiusAttribute; import com.nextenso.proxylet.radius.acct.DisconnectUtils; /** * The Disconnect Request (RFC 5176). */ public class DisconnectRequest extends AccountingRequestFacade { public DisconnectRequest(int identifier, boolean instanciateResp) { super(identifier, false); if (instanciateResp) { setResponse(new DisconnectResponse(this)); } } /** * @see com.nextenso.radius.agent.impl.AccountingRequestFacade#getDefaultPort() */ @Override public int getDefaultPort() { return DisconnectUtils.DISCONNECT_PORT; } /** * @see com.nextenso.radius.agent.impl.AccountingRequestFacade#isValid() */ @Override public String isValid() { String res = validateAttributes(); return res; } /** * @see com.nextenso.radius.agent.impl.AccountingRequestFacade#isValidAttribute(com.nextenso.proxylet.radius.RadiusAttribute) */ @Override public boolean isValidAttribute(RadiusAttribute attribute) { boolean res = DisconnectUtils.isValidAttribute(getCode(), attribute); return res; } /** * @see com.nextenso.radius.agent.impl.AccountingRequestFacade#getMessageType() */ @Override protected String getMessageType() { return "Disconnect Request"; } }
23.183333
126
0.74982
292ffc9a55a0af72614b0f87c449c6bbc373ebc3
12,527
/* * 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.solr.handler; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.util.ContentStream; import org.apache.solr.common.util.ContentStreamBase; import org.apache.solr.request.LocalSolrQueryRequest; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class TestCSVLoader extends SolrTestCaseJ4 { @BeforeClass public static void beforeClass() throws Exception { System.setProperty("enable.update.log", "false"); // schema12 doesn't support _version_ initCore("solrconfig.xml","schema12.xml"); } String filename; File file; @Override @Before public void setUp() throws Exception { // if you override setUp or tearDown, you better call // the super classes version super.setUp(); File tempDir = createTempDir("TestCSVLoader").toFile(); file = new File(tempDir, "solr_tmp.csv"); filename = file.getPath(); cleanup(); } @Override @After public void tearDown() throws Exception { // if you override setUp or tearDown, you better call // the super classes version super.tearDown(); if (null != file) { Files.delete(file.toPath()); file = null; } } void makeFile(String contents) { try (Writer out = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8)) { out.write(contents); } catch (Exception e) { throw new RuntimeException(e); } } void cleanup() { assertU(delQ("*:*")); assertU(commit()); } void loadLocal(String... args) throws Exception { LocalSolrQueryRequest req = (LocalSolrQueryRequest)req(args); // TODO: stop using locally defined streams once stream.file and // stream.body work everywhere List<ContentStream> cs = new ArrayList<>(1); ContentStreamBase f = new ContentStreamBase.FileStream(new File(filename)); f.setContentType("text/csv"); cs.add(f); req.setContentStreams(cs); h.query("/update",req); } @Test public void testCSVLoad() throws Exception { makeFile("id\n100\n101\n102"); loadLocal(); // check default commit of false assertQ(req("id:[100 TO 110]"),"//*[@numFound='0']"); assertU(commit()); assertQ(req("id:[100 TO 110]"),"//*[@numFound='3']"); } @Test public void testCSVRowId() throws Exception { makeFile("id\n100\n101\n102"); loadLocal("rowid", "rowid_i");//add a special field // check default commit of false assertU(commit()); assertQ(req("rowid_i:1"),"//*[@numFound='1']"); assertQ(req("rowid_i:2"),"//*[@numFound='1']"); assertQ(req("rowid_i:100"),"//*[@numFound='0']"); makeFile("id\n200\n201\n202"); loadLocal("rowid", "rowid_i", "rowidOffset", "100");//add a special field // check default commit of false assertU(commit()); assertQ(req("rowid_i:101"),"//*[@numFound='1']"); assertQ(req("rowid_i:102"),"//*[@numFound='1']"); assertQ(req("rowid_i:10000"),"//*[@numFound='0']"); } @Test public void testCommitFalse() throws Exception { makeFile("id\n100\n101\n102"); loadLocal("commit","false"); assertQ(req("id:[100 TO 110]"),"//*[@numFound='0']"); assertU(commit()); assertQ(req("id:[100 TO 110]"),"//*[@numFound='3']"); } @Test public void testCommitTrue() throws Exception { makeFile("id\n100\n101\n102"); loadLocal("commit","true"); assertQ(req("id:[100 TO 110]"),"//*[@numFound='3']"); } @Test public void testLiteral() throws Exception { makeFile("id\n100"); loadLocal("commit","true", "literal.name","LITERAL_VALUE"); assertQ(req("*:*"),"//doc/str[@name='name'][.='LITERAL_VALUE']"); } @Test public void testCSV() throws Exception { lrf.args.put(CommonParams.VERSION,"2.2"); makeFile("id,str_s\n100,\"quoted\"\n101,\n102,\"\"\n103,"); loadLocal("commit","true"); assertQ(req("id:[100 TO 110]"),"//*[@numFound='4']"); assertQ(req("id:100"),"//arr[@name='str_s']/str[.='quoted']"); assertQ(req("id:101"),"count(//str[@name='str_s'])=0"); // 102 is a quoted zero length field ,"", as opposed to ,, // but we can't distinguish this case (and it's debateable // if we should). Does CSV have a way to specify missing // from zero-length? assertQ(req("id:102"),"count(//str[@name='str_s'])=0"); assertQ(req("id:103"),"count(//str[@name='str_s'])=0"); // test overwrite by default loadLocal("commit","true"); assertQ(req("id:[100 TO 110]"),"//*[@numFound='4']"); // test explicitly adding header=true (the default) loadLocal("commit","true","header","true"); assertQ(req("id:[100 TO 110]"),"//*[@numFound='4']"); // test no overwrites loadLocal("commit","true", "overwrite","false"); assertQ(req("id:[100 TO 110]"),"//*[@numFound='8']"); // test overwrite loadLocal("commit","true"); assertQ(req("id:[100 TO 110]"),"//*[@numFound='4']"); // test global value mapping loadLocal("commit","true", "map","quoted:QUOTED"); assertQ(req("id:[100 TO 110]"),"//*[@numFound='4']"); assertQ(req("id:100"),"//arr[@name='str_s']/str[.='QUOTED']"); assertQ(req("id:101"),"count(//str[@name='str_s'])=0"); assertQ(req("id:102"),"count(//str[@name='str_s'])=0"); assertQ(req("id:103"),"count(//str[@name='str_s'])=0"); // test value mapping to empty (remove) loadLocal("commit","true", "map","quoted:"); assertQ(req("id:[100 TO 110]"),"//*[@numFound='4']"); assertQ(req("id:100"),"count(//str[@name='str_s'])=0"); // test value mapping from empty loadLocal("commit","true", "map",":EMPTY"); assertQ(req("id:[100 TO 110]"),"//*[@numFound='4']"); assertQ(req("id:100"),"//arr[@name='str_s']/str[.='quoted']"); assertQ(req("id:101"),"//arr[@name='str_s']/str[.='EMPTY']"); assertQ(req("id:102"),"//arr[@name='str_s']/str[.='EMPTY']"); assertQ(req("id:103"),"//arr[@name='str_s']/str[.='EMPTY']"); // test multiple map rules loadLocal("commit","true", "map",":EMPTY", "map","quoted:QUOTED"); assertQ(req("id:[100 TO 110]"),"//*[@numFound='4']"); assertQ(req("id:100"),"//arr[@name='str_s']/str[.='QUOTED']"); assertQ(req("id:101"),"//arr[@name='str_s']/str[.='EMPTY']"); assertQ(req("id:102"),"//arr[@name='str_s']/str[.='EMPTY']"); assertQ(req("id:103"),"//arr[@name='str_s']/str[.='EMPTY']"); // test indexing empty fields loadLocal("commit","true", "f.str_s.keepEmpty","true"); assertQ(req("id:[100 TO 110]"),"//*[@numFound='4']"); assertQ(req("id:100"),"//arr[@name='str_s']/str[.='quoted']"); assertQ(req("id:101"),"//arr[@name='str_s']/str[.='']"); assertQ(req("id:102"),"//arr[@name='str_s']/str[.='']"); assertQ(req("id:103"),"//arr[@name='str_s']/str[.='']"); // test overriding the name of fields loadLocal("commit","true", "fieldnames","id,my_s", "header","true", "f.my_s.map",":EMPTY"); assertQ(req("id:[100 TO 110]"),"//*[@numFound='4']"); assertQ(req("id:100"),"//arr[@name='my_s']/str[.='quoted']"); assertQ(req("id:101"),"count(//arr[@name='str_s']/str)=0"); assertQ(req("id:102"),"count(//arr[@name='str_s']/str)=0"); assertQ(req("id:103"),"count(//arr[@name='str_s']/str)=0"); assertQ(req("id:101"),"//arr[@name='my_s']/str[.='EMPTY']"); assertQ(req("id:102"),"//arr[@name='my_s']/str[.='EMPTY']"); assertQ(req("id:103"),"//arr[@name='my_s']/str[.='EMPTY']"); // test that header in file was skipped assertQ(req("id:id"),"//*[@numFound='0']"); // test skipping a field via the "skip" parameter loadLocal("commit","true","keepEmpty","true","skip","str_s"); assertQ(req("id:[100 TO 110]"),"//*[@numFound='4']"); assertQ(req("id:[100 TO 110]"),"count(//str[@name='str_s']/str)=0"); // test skipping a field by specifying an empty name loadLocal("commit","true","keepEmpty","true","fieldnames","id,"); assertQ(req("id:[100 TO 110]"),"//*[@numFound='4']"); assertQ(req("id:[100 TO 110]"),"count(//str[@name='str_s']/str)=0"); // test loading file as if it didn't have a header loadLocal("commit","true", "fieldnames","id,my_s", "header","false"); assertQ(req("id:id"),"//*[@numFound='1']"); assertQ(req("id:100"),"//arr[@name='my_s']/str[.='quoted']"); // test skipLines loadLocal("commit","true", "fieldnames","id,my_s", "header","false", "skipLines","1"); assertQ(req("id:id"),"//*[@numFound='1']"); assertQ(req("id:100"),"//arr[@name='my_s']/str[.='quoted']"); // test multi-valued fields via field splitting w/ mapping of subvalues makeFile("id,str_s\n" +"100,\"quoted\"\n" +"101,\"a,b,c\"\n" +"102,\"a,,b\"\n" +"103,\n"); loadLocal("commit","true", "f.str_s.map",":EMPTY", "f.str_s.split","true"); assertQ(req("id:[100 TO 110]"),"//*[@numFound='4']"); assertQ(req("id:100"),"//arr[@name='str_s']/str[.='quoted']"); assertQ(req("id:101"),"//arr[@name='str_s']/str[1][.='a']"); assertQ(req("id:101"),"//arr[@name='str_s']/str[2][.='b']"); assertQ(req("id:101"),"//arr[@name='str_s']/str[3][.='c']"); assertQ(req("id:102"),"//arr[@name='str_s']/str[2][.='EMPTY']"); assertQ(req("id:103"),"//arr[@name='str_s']/str[.='EMPTY']"); // test alternate values for delimiters makeFile("id|str_s\n" +"100|^quoted^\n" +"101|a;'b';c\n" +"102|a;;b\n" +"103|\n" +"104|a\\\\b\n" // no backslash escaping should be done by default ); loadLocal("commit","true", "separator","|", "encapsulator","^", "f.str_s.map",":EMPTY", "f.str_s.split","true", "f.str_s.separator",";", "f.str_s.encapsulator","'" ); assertQ(req("id:[100 TO 110]"),"//*[@numFound='5']"); assertQ(req("id:100"),"//arr[@name='str_s']/str[.='quoted']"); assertQ(req("id:101"),"//arr[@name='str_s']/str[1][.='a']"); assertQ(req("id:101"),"//arr[@name='str_s']/str[2][.='b']"); assertQ(req("id:101"),"//arr[@name='str_s']/str[3][.='c']"); assertQ(req("id:102"),"//arr[@name='str_s']/str[2][.='EMPTY']"); assertQ(req("id:103"),"//arr[@name='str_s']/str[.='EMPTY']"); assertQ(req("id:104"),"//arr[@name='str_s']/str[.='a\\\\b']"); // test no escaping + double encapsulator escaping by default makeFile("id,str_s\n" +"100,\"quoted \"\" \\ string\"\n" +"101,unquoted \"\" \\ string\n" // double encap shouldn't be an escape outside encap +"102,end quote \\\n" ); loadLocal("commit","true" ); assertQ(req("id:100"),"//arr[@name='str_s']/str[.='quoted \" \\ string']"); assertQ(req("id:101"),"//arr[@name='str_s']/str[.='unquoted \"\" \\ string']"); assertQ(req("id:102"),"//arr[@name='str_s']/str[.='end quote \\']"); // setting an escape should disable encapsulator makeFile("id,str_s\n" +"100,\"quoted \"\" \\\" \\\\ string\"\n" // quotes should be part of value +"101,unquoted \"\" \\\" \\, \\\\ string\n" ); loadLocal("commit","true" ,"escape","\\" ); assertQ(req("id:100"),"//arr[@name='str_s']/str[.='\"quoted \"\" \" \\ string\"']"); assertQ(req("id:101"),"//arr[@name='str_s']/str[.='unquoted \"\" \" , \\ string']"); } }
37.618619
103
0.586014
ee1bcd2fc5a0a0e071a6254bfe8632520d483ce5
3,878
package jetbrains.mps.lang.actions.testLanguage.constraints; /*Generated by MPS */ import jetbrains.mps.smodel.runtime.base.BaseConstraintsDescriptor; import jetbrains.mps.smodel.runtime.ConstraintFunction; import jetbrains.mps.smodel.runtime.ConstraintContext_CanBeParent; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import jetbrains.mps.smodel.runtime.CheckingNodeContext; import org.jetbrains.mps.openapi.model.SNode; import org.jetbrains.mps.openapi.language.SAbstractConcept; import org.jetbrains.mps.openapi.language.SContainmentLink; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SConceptOperations; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations; import jetbrains.mps.smodel.SNodePointer; import org.jetbrains.mps.openapi.language.SConcept; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; public class ActionTestSidetransformTestContainer_Constraints extends BaseConstraintsDescriptor { public ActionTestSidetransformTestContainer_Constraints() { super(CONCEPTS.ActionTestSidetransformTestContainer$fB); } @Override protected ConstraintFunction<ConstraintContext_CanBeParent, Boolean> calculateCanBeParentConstraint() { return new ConstraintFunction<ConstraintContext_CanBeParent, Boolean>() { @NotNull public Boolean invoke(@NotNull ConstraintContext_CanBeParent context, @Nullable CheckingNodeContext checkingNodeContext) { boolean result = staticCanBeAParent(context.getNode(), context.getChildNode(), context.getChildConcept(), context.getLink()); if (!(result) && checkingNodeContext != null) { checkingNodeContext.setBreakingNode(canBeParentBreakingPoint); } return result; } }; } private static boolean staticCanBeAParent(SNode node, SNode childNode, SAbstractConcept childConcept, SContainmentLink link) { if (childConcept == CONCEPTS.ActionTestSidetransformChild1$gm && link == LINKS.abstractChildConstrained$oWFz) { return false; } if (SConceptOperations.isSubConceptOf(SNodeOperations.asSConcept(childConcept), CONCEPTS.ActionTestSidetransformAnotherChildCommonSuperConcept$yl) && link == LINKS.anotherAbstractChildConstrained$P5uT) { return false; } return true; } private static final SNodePointer canBeParentBreakingPoint = new SNodePointer("r:51315b9d-b515-42e5-b0a0-21c0544c81b4(jetbrains.mps.lang.actions.testLanguage.constraints)", "1227128029536583770"); private static final class CONCEPTS { /*package*/ static final SConcept ActionTestSidetransformTestContainer$fB = MetaAdapterFactory.getConcept(0x737ed1fffa634ebcL, 0xa834435499b23c64L, 0x179f28a7ade381e5L, "jetbrains.mps.lang.actions.testLanguage.structure.ActionTestSidetransformTestContainer"); /*package*/ static final SConcept ActionTestSidetransformChild1$gm = MetaAdapterFactory.getConcept(0x737ed1fffa634ebcL, 0xa834435499b23c64L, 0x44969b12b8c94c1bL, "jetbrains.mps.lang.actions.testLanguage.structure.ActionTestSidetransformChild1"); /*package*/ static final SConcept ActionTestSidetransformAnotherChildCommonSuperConcept$yl = MetaAdapterFactory.getConcept(0x737ed1fffa634ebcL, 0xa834435499b23c64L, 0x2c35cefefcaa0dd0L, "jetbrains.mps.lang.actions.testLanguage.structure.ActionTestSidetransformAnotherChildCommonSuperConcept"); } private static final class LINKS { /*package*/ static final SContainmentLink abstractChildConstrained$oWFz = MetaAdapterFactory.getContainmentLink(0x737ed1fffa634ebcL, 0xa834435499b23c64L, 0x179f28a7ade381e5L, 0x44969b12b8d87e51L, "abstractChildConstrained"); /*package*/ static final SContainmentLink anotherAbstractChildConstrained$P5uT = MetaAdapterFactory.getContainmentLink(0x737ed1fffa634ebcL, 0xa834435499b23c64L, 0x179f28a7ade381e5L, 0x2c35cefefca5514fL, "anotherAbstractChildConstrained"); } }
61.555556
297
0.825168
c3a59191674cd91f731f317fdb13df1f36766d90
1,631
package frc.robot.commands; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.Constants; import frc.robot.subsystems.drivetrainsub; //commented out lines are for distance-based autonomous (using encoders) //current lines are for time-based autonomous public class autoDrive extends CommandBase{ private final drivetrainsub m_Drive; //private final double distance; private double startTime; private double duration; public autoDrive (drivetrainsub subsystem, double duration){ m_Drive = subsystem; //this.distance = distance; this.duration = duration*1000; } // only goes once at beginning when command is called @Override public void initialize(){ //m_Drive.resetEncoder(); startTime = System.currentTimeMillis(); } // keeps repeating until the command ends @Override public void execute(){ //m_Drive.autoDrive(distance); m_Drive.tankdrive(Constants.autodriveleft, Constants.autodriveright); addRequirements(m_Drive); } //only goes once at end when command is finishing @Override public void end(boolean inerrupted){ m_Drive.tankdrive(0, 0); } //condition for the command to end on its own @Override public boolean isFinished(){ /*if (m_Drive.getDistance()<distance) { return false; } else { return true; } */ if (System.currentTimeMillis()-startTime<duration){ return false; } else { return true; } } }
22.342466
77
0.637032
5d013a83f12060a7b71cd6daacb1b14811b17a71
225
package com.demofamilies.app.base; import android.support.v7.app.AppCompatActivity; /** * author: xujiaji * created on: 2018/5/18 10:30 * description: */ public abstract class BaseActivity extends AppCompatActivity { }
17.307692
60
0.755556
aa84945e2cd50da8988697178b5525924e1adc02
8,791
package com.service.impl; import java.sql.Timestamp; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.dao.StayRegisterDao; import com.page.Page; import com.pojo.StayRegisterPo; @Transactional @Service(value="stayRegisterService") public class StayRegisterService implements com.service.StayRegisterService { @Autowired private StayRegisterDao stayRegisterDao; @Override public int insertAll(StayRegisterPo stayRegisterPo) { return stayRegisterDao.insertAll(stayRegisterPo); } @Override public Page<StayRegisterPo> pageFuzzyselectOne(int receiveTargeTypeID, int isBillID,String roomNumber,Page<StayRegisterPo> vo) { int start=0; if (vo.getCurrentPage()>1) { start=(vo.getCurrentPage()-1)*vo.getPageSize(); } List<StayRegisterPo> list=stayRegisterDao.pageFuzzyselectOne(receiveTargeTypeID, isBillID, roomNumber,start, vo.getPageSize()); vo.setResult(list); int count=stayRegisterDao.countFuzzyselectOne(receiveTargeTypeID, isBillID,roomNumber); vo.setTotal(count); return vo; } @Override public StayRegisterPo selectById(Integer id) { return this.stayRegisterDao.selectById(id); } @Override public int insertStayregisterdetails(int stayRegisterID, int passengerID) { return stayRegisterDao.insertStayregisterdetails(stayRegisterID, passengerID); } @Override public int insertDeposit(StayRegisterPo stayRegisterPo) { return stayRegisterDao.insertDeposit(stayRegisterPo); } @Override public List<StayRegisterPo> selectDepositById(int id) { return stayRegisterDao.selectDepositById(id); } @Override public int insertConsumptiondetails(StayRegisterPo stayRegisterPo) { return stayRegisterDao.insertConsumptiondetails(stayRegisterPo); } @Override public Page<StayRegisterPo> pageConsumption(int consumptionStayRegisterID,Page<StayRegisterPo> vo) { int start=0; if (vo.getCurrentPage()>1) { start=(vo.getCurrentPage()-1)*vo.getPageSize(); } List<StayRegisterPo> list=stayRegisterDao.pageConsumption(consumptionStayRegisterID, start, vo.getPageSize()); vo.setResult(list); int count=stayRegisterDao.countConsumption(consumptionStayRegisterID); vo.setTotal(count); return vo; } @Override public int deleteConsumption(Integer id) { return stayRegisterDao.deleteConsumption(id); } @Override public int updateSumConst(int id, Double sumConst) { return stayRegisterDao.updateSumConst(id, sumConst); } @Override public List<StayRegisterPo> selectMoney(int id) { return stayRegisterDao.selectMoney(id); } @Override public List<StayRegisterPo> selectChangRoom(int id) { return stayRegisterDao.selectChangRoom(id); } @Override public List<StayRegisterPo> selectAll() { return stayRegisterDao.selectAll(); } @Override public int updateRemind(int id, int remind) { return stayRegisterDao.updateRemind(id, remind); } @Override public int updateChangRoom(StayRegisterPo stayRegisterPo) { return stayRegisterDao.updateChangRoom(stayRegisterPo); } @Override public int pay(int id, String remarks, Timestamp payTime, int payWay) { return stayRegisterDao.pay(id, remarks, payTime, payWay); } @Override public Page<StayRegisterPo> pageFuzzyselectTwo(int receiveTargetID, int isBillID, String roomNumber, Page<StayRegisterPo> vo) { int start=0; if (vo.getCurrentPage()>1) { start=(vo.getCurrentPage()-1)*vo.getPageSize(); } List<StayRegisterPo> list=stayRegisterDao.pageFuzzyselectTwo(receiveTargetID, isBillID, roomNumber,start, vo.getPageSize()); vo.setResult(list); int count=stayRegisterDao.countFuzzyselectTwo(receiveTargetID, isBillID, roomNumber); vo.setTotal(count); return vo; } @Override public List<StayRegisterPo> selectFormTeamId(int receiveTargetID, int isBillID) { return this.stayRegisterDao.selectFormTeamId(receiveTargetID, isBillID); } @Override public List<StayRegisterPo> selectTeamDeposit(int receiveTargetID) { return this.stayRegisterDao.selectTeamDeposit(receiveTargetID); } @Override public List<StayRegisterPo> selectTeamConsumption(int receiveTargetID) { return this.stayRegisterDao.selectTeamConsumption(receiveTargetID); } @Override public List<StayRegisterPo> ajaxSelectTeamRoom(int receiveTargetID, String roomNumber) { return this.stayRegisterDao.ajaxSelectTeamRoom(receiveTargetID, roomNumber); } @Override public List<StayRegisterPo> ajaxSelectTeamFormTime(int receiveTargetID, Timestamp min, Timestamp max) { return this.stayRegisterDao.ajaxSelectTeamFormTime(receiveTargetID, min, max); } @Override public List<StayRegisterPo> ajaxSelectTeamDeposit(int receiveTargetID, Timestamp min, Timestamp max) { return this.stayRegisterDao.ajaxSelectTeamDeposit(receiveTargetID, min, max); } @Override public List<StayRegisterPo> ajaxSelectTeamConsumption(int receiveTargetID, Timestamp min, Timestamp max) { return this.stayRegisterDao.ajaxSelectTeamConsumption(receiveTargetID, min, max); } @Override public List<StayRegisterPo> selectDepositJinJianBan(int id) { return this.stayRegisterDao.selectDepositJinJianBan(id); } @Override public List<StayRegisterPo> selectConsumptionJinJianBan(int id) { return this.stayRegisterDao.selectConsumptionJinJianBan(id); } @Override public StayRegisterPo selectInformationXiangQingBan(int id) { return this.stayRegisterDao.selectInformationXiangQingBan(id); } @Override public int changOverTeam(int id, int receiveTargetID) { return this.stayRegisterDao.changOverTeam(id, receiveTargetID); } @Override public List<StayRegisterPo> selectFormTeamIdTwo(int isBillID) { return this.stayRegisterDao.selectFormTeamIdTwo(isBillID); } @Override public Page<StayRegisterPo> pageFuzzyselectThree(int isBillID, String roomNumber, Page<StayRegisterPo> vo) { int start=0; if (vo.getCurrentPage()>1) { start=(vo.getCurrentPage()-1)*vo.getPageSize(); } List<StayRegisterPo> list=stayRegisterDao.pageFuzzyselectThree(isBillID, roomNumber,start, vo.getPageSize()); vo.setResult(list); int count=stayRegisterDao.countFuzzyselectThree(isBillID, roomNumber); vo.setTotal(count); return vo; } @Override public List<StayRegisterPo> selectShuJuTongJi(Timestamp min, Timestamp max) { return this.stayRegisterDao.selectShuJuTongJi(min, max); } /*-------------------------------------FinancialStatistics--------------------------------------------------------*/ @Override public Page<StayRegisterPo> pageFuzzyselectFour(Page<StayRegisterPo> vo) { int start=0; if (vo.getCurrentPage()>1) { start=(vo.getCurrentPage()-1)*vo.getPageSize(); } List<StayRegisterPo> list=stayRegisterDao.pageFuzzyselectFour(start, vo.getPageSize()); vo.setResult(list); int count=stayRegisterDao.countFuzzyselectFour(); vo.setTotal(count); return vo; } @Override public Page<StayRegisterPo> pageFuzzyselectFive(Timestamp min, Timestamp max, Page<StayRegisterPo> vo) { int start=0; if (vo.getCurrentPage()>1) { start=(vo.getCurrentPage()-1)*vo.getPageSize(); } List<StayRegisterPo> list=stayRegisterDao.pageFuzzyselectFive(min, max,start, vo.getPageSize()); vo.setResult(list); int count=stayRegisterDao.countFuzzyselectFive(min, max); vo.setTotal(count); return vo; } @Override public List<StayRegisterPo> selectPayJingJianBanNot() { return this.stayRegisterDao.selectPayJingJianBanNot(); } @Override public List<StayRegisterPo> selectPayStayNumberNot() { return this.stayRegisterDao.selectPayStayNumberNot(); } @Override public List<StayRegisterPo> selectPayXiaoFeiNot() { return this.stayRegisterDao.selectPayXiaoFeiNot(); } @Override public List<StayRegisterPo> selectPayJingJianBan(Timestamp min, Timestamp max) { return this.stayRegisterDao.selectPayJingJianBan(min, max); } @Override public List<StayRegisterPo> selectPayStayNumber(Timestamp min, Timestamp max) { return this.stayRegisterDao.selectPayStayNumber(min, max); } @Override public List<StayRegisterPo> selectPayXiaoFei(Timestamp min, Timestamp max) { return this.stayRegisterDao.selectPayXiaoFei(min, max); } @Override public List<StayRegisterPo> selectAllInformation(int id) { return this.stayRegisterDao.selectAllInformation(id); } @Override public List<StayRegisterPo> selectXiaoFeiMingXi(int id) { return this.stayRegisterDao.selectXiaoFeiMingXi(id); } @Override public int updateStayRegisterPredetermineID(Integer predetermineID, Integer id) { return this.stayRegisterDao.updateStayRegisterPredetermineID(predetermineID, id); } @Override public StayRegisterPo selectSumconst(int id) { return this.stayRegisterDao.selectSumconst(id); } }
27.996815
129
0.77568
31d6a0fcdc6d44e400c595687d9f77edf4458511
2,196
package jef.common; import jef.common.Configuration.ConfigItem; import jef.common.log.LogUtil; import jef.tools.StringUtils; /** * 所有配置类的基类 * @author Administrator * */ public abstract class Cfg { static class Config implements ConfigItem{ String key; public Config(String key){ this.key=key; } @Override public String toString() { return key; } public String name() { return key; } } /** * 返回一个指定键值的ConfigItem * @param key * @return */ public static ConfigItem valueOf(String key){ return new Config(key); } /** * 得到布尔值 * @param itemkey * @param defaultValue * @return */ public boolean getBoolean(ConfigItem itemkey, boolean defaultValue) { String s = get(itemkey); return StringUtils.toBoolean(s, defaultValue); } /** * 得到double值 * @param itemkey * @param defaultValue * @return */ public double getDouble(ConfigItem itemkey, double defaultValue) { String s = get(itemkey); try { double n = Double.parseDouble(s); return n; } catch (Exception e) { LogUtil.warn("the jef config ["+itemkey+"] has invalid value:"+ s); return defaultValue; } } /** * 得到int值 * @param itemkey * @param defaultValue * @return */ public int getInt(ConfigItem itemkey, int defaultValue) { String s = get(itemkey); try { int n = Integer.parseInt(s); return n; } catch (Exception e) { LogUtil.warn("the jef config ["+itemkey+"] has invalid value:"+ s); return defaultValue; } } /** * 得到String,如果没有返回"" * @param itemkey * @return */ public String get(ConfigItem itemkey) { String key; if(itemkey instanceof Enum){ key=((Enum<?>) itemkey).name(); key = StringUtils.replaceChars(key, "_$", ".-").toLowerCase(); }else{ key=itemkey.toString(); } return get(key, ""); } public String get(ConfigItem itemkey, String defaultValue) { String key = getKey(itemkey); return get(key,defaultValue); } static public String getKey(ConfigItem itemkey){ return StringUtils.replaceChars(itemkey.toString(), "_$", ".-").toLowerCase(); } /** * * @param key * @param string * @return */ protected abstract String get(String key, String string); }
19.263158
80
0.653461
40fba157552366f0d5f194f626e5fe13a9b6681b
2,209
package edu.rice.cs.hpcviewer.ui.handlers; import java.util.List; import javax.inject.Named; import org.eclipse.e4.core.di.annotations.Execute; import org.eclipse.e4.ui.di.AboutToShow; import org.eclipse.e4.ui.model.application.MApplication; import org.eclipse.e4.ui.model.application.ui.basic.MWindow; import org.eclipse.e4.ui.model.application.ui.menu.MDirectMenuItem; import org.eclipse.e4.ui.model.application.ui.menu.MMenuElement; import org.eclipse.e4.ui.services.IServiceConstants; import org.eclipse.e4.ui.workbench.modeling.EModelService; import org.eclipse.e4.ui.workbench.modeling.EPartService; import org.eclipse.swt.widgets.Shell; import edu.rice.cs.hpcbase.map.UserInputHistory; import edu.rice.cs.hpcviewer.ui.addon.DatabaseCollection; public abstract class RecentDatabase { public static final String HISTORY_DATABASE_RECENT = "recent"; public static final int HISTORY_MAX = 10; private static final String ID_DATA_ECP = "viewer/recent"; @AboutToShow public void aboutToShow( List<MMenuElement> items, DatabaseCollection database, EModelService modelService, MWindow window ) { UserInputHistory history = new UserInputHistory(HISTORY_DATABASE_RECENT, HISTORY_MAX); if (history.getHistory().size() == 0) return; for(String db: history.getHistory()) { MDirectMenuItem menu = modelService.createModelElement(MDirectMenuItem.class); menu.setElementId(db); menu.setLabel(db); menu.setContributionURI(getURI()); menu.getTransientData().put(ID_DATA_ECP, db); items.add(menu); } } @Execute public void execute(@Named(IServiceConstants.ACTIVE_SHELL) Shell shell, MApplication application, MWindow window, MDirectMenuItem menu, EModelService modelService, EPartService partService) { String db = (String) menu.getTransientData().get(ID_DATA_ECP); execute(application, window, modelService, partService, shell, db); } protected abstract String getURI(); protected abstract void execute(MApplication application, MWindow window, EModelService modelService, EPartService partService, Shell shell, String database); }
30.680556
88
0.749208
4ddb29a7f0fe1a7518cac2cd19c85d05658b1243
115
class C { /** * Some method. * * @param value some (&copy;) param. */ abstract void m(int value); }
14.375
38
0.521739
764d3eed3e1ddee68439bd8c79193e98f2c6f5b2
3,457
/* * Copyright 2013, 2014 Megion Research & Development GmbH * * 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. */ /** * modified by swapnibble from plactal.io * This code was extracted from the Java cryptography library from * www.bouncycastle.org. The code has been formatted to comply with the rest of * the formatting in this library. */ package com.metallicus.protonsdk.eosio.commander.ec; import java.math.BigInteger; /** * An elliptic curve */ public class EcCurve { private EcFieldElement _a; private EcFieldElement _b; private BigInteger _q; private EcPoint _infinity; public EcCurve(BigInteger q, BigInteger a, BigInteger b) { this._q = q; this._a = fromBigInteger(a); this._b = fromBigInteger(b); this._infinity = new EcPoint(this, null, null); } public EcFieldElement getA() { return _a; } public EcFieldElement getB() { return _b; } public BigInteger getQ() { return _q; } public EcPoint getInfinity() { return _infinity; } public int getFieldSize() { return _q.bitLength(); } public EcFieldElement fromBigInteger(BigInteger x) { return new EcFieldElement(this._q, x); } public EcPoint decodePoint(byte[] encodedPoint) { EcPoint p = null; // Switch on encoding type switch (encodedPoint[0]) { case 0x00: p = getInfinity(); break; case 0x02: case 0x03: int ytilde = encodedPoint[0] & 1; byte[] i = new byte[encodedPoint.length - 1]; System.arraycopy(encodedPoint, 1, i, 0, i.length); EcFieldElement x = new EcFieldElement(this._q, new BigInteger(1, i)); EcFieldElement alpha = x.multiply(x.square().add(_a)).add(_b); EcFieldElement beta = alpha.sqrt(); if (beta == null) { throw new RuntimeException("Invalid compression"); } int bit0 = (beta.toBigInteger().testBit(0) ? 1 : 0); if (bit0 == ytilde) { p = new EcPoint(this, x, beta, true); } else { p = new EcPoint(this, x, new EcFieldElement(this._q, _q.subtract(beta.toBigInteger())), true); } break; case 0x04: case 0x06: case 0x07: byte[] xEnc = new byte[(encodedPoint.length - 1) / 2]; byte[] yEnc = new byte[(encodedPoint.length - 1) / 2]; System.arraycopy(encodedPoint, 1, xEnc, 0, xEnc.length); System.arraycopy(encodedPoint, xEnc.length + 1, yEnc, 0, yEnc.length); p = new EcPoint(this, new EcFieldElement(this._q, new BigInteger(1, xEnc)), new EcFieldElement(this._q, new BigInteger(1, yEnc))); break; default: throw new RuntimeException("Invalid encoding 0x" + Integer.toString(encodedPoint[0], 16)); } return p; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof EcCurve)) { return false; } EcCurve other = (EcCurve) obj; return this._q.equals(other._q) && _a.equals(other._a) && _b.equals(other._b); } @Override public int hashCode() { return _a.hashCode() ^ _b.hashCode() ^ _q.hashCode(); } }
27.007813
107
0.680069
d709834be8a73ea581d7081af0340a99c3bf4c62
1,014
package com.logginghub.logging.filters; import com.logginghub.logging.LogEvent; import com.logginghub.utils.filter.Filter; /** * A Filter<LogEvent> that passes events whose message matches exactly the string passed in at * construction time. * * @author James */ public class MessageIsFilter implements Filter<LogEvent> { private String value; private boolean ignoreCase = true; public MessageIsFilter(String value) { setMessageString(value); } public boolean passes(LogEvent event) { String message = event.getMessage(); boolean passes; if (ignoreCase) { passes = message.toLowerCase().equals(value); } else { passes = message.equals(value); } return passes; } public void setMessageString(String text) { if (ignoreCase) { value = text.toLowerCase(); } else { value = text; } } }
23.045455
95
0.588757
e3d3dc522f16119aa73588447180e4a2c8bdca0a
865
package no.nav.repository.pensjon.common.cache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.sf.ehcache.CacheException; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; public class LoggingElementPutCacheEventListener extends DefaultCacheEventListener { private final Logger logger = LoggerFactory.getLogger(LoggingElementPutCacheEventListener.class); @Override public void notifyElementPut(Ehcache cache, Element element) throws CacheException { if (!logger.isTraceEnabled() || cache == null || element == null) { return; } logger.trace("Caching object: {} in cache: {} with key: {}", element.getObjectValue(), cache.getName(), element.getObjectKey()); } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
30.892857
136
0.721387
e2c942168e14c8e1f4621ebec2cb6b25e63afe3d
443
package project.marketbot.models.pojo; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import project.marketbot.models.db.CompanyIndicators; /** * Retrieved from MarketWatch */ @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class MarketWatchResponse { private String industry; private String sector; private CompanyIndicators companyIndicators; }
19.26087
53
0.805869
6513fc3e361824b81ed5158fbf2436675ab14cb4
1,132
/* * Copyright 2015 Matthew Aguirre * * 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.l2fprod.common.swing; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.Window; /** * UIUtilities. <br> * */ public final class UIUtilities { private UIUtilities() { } public static void centerOnScreen(Window window) { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension size = window.getSize(); window.setLocation( (screenSize.width - size.width) / 2, (screenSize.height - size.height) / 2); } }
28.3
75
0.691696
279a46ea8f2f36d62d7cb85711bfccf1a0be8940
371
package activitystreamer.commands.processors.impl; import activitystreamer.command.Command; import activitystreamer.commands.processors.CommandProcessor; public class AbstractCommandProcessor<T extends Command> implements CommandProcessor<T> { @Override public void processCommand(T command) { } protected void doProcessCommand(T command) { } }
20.611111
89
0.784367
6cbde884ce72e2c346eef61a3d7e2ae1f512b2a1
1,596
/** * Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io) * * 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 teetime.stage; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.List; import org.junit.Test; import teetime.framework.test.StageTester; public class MD5StageTest { @Test public void test() { MD5Stage md5Stage = new MD5Stage(); final String[] inputValues = new String[] { "test", "a", "123", "b", "foo" }; final String[] hashes = new String[] { "098f6bcd4621d373cade4e832627b4f6", "0cc175b9c0f1b6a831c399e269772661", "202cb962ac59075b964b07152d234b70", "92eb5ffee6ae2fec3ad71c777531578f", "acbd18db4cc2f85cedef654fccc4a4d8" }; final List<String> results = new ArrayList<String>(); StageTester.test(md5Stage).and() .send(inputValues).to(md5Stage.getInputPort()).and() .receive(results).from(md5Stage.getOutputPort()).start(); assertThat(results, contains(hashes)); } }
33.25
96
0.743734
e749a14994348d58e60fd452e28a860444d9d289
1,690
package io.shiftleft.overflowdb.util; import org.apache.tinkerpop.gremlin.process.traversal.util.FastNoSuchElementException; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Subclass-safe variant of MultiIterator */ public final class MultiIterator2<T> implements Iterator<T>, Serializable { private final List<Iterator<? extends T>> iterators = new ArrayList<>(); private int current = 0; public void addIterator(final Iterator<? extends T> iterator) { this.iterators.add(iterator); } @Override public boolean hasNext() { if (this.current >= this.iterators.size()) return false; Iterator currentIterator = this.iterators.get(this.current); while (true) { if (currentIterator.hasNext()) { return true; } else { this.current++; if (this.current >= iterators.size()) break; currentIterator = iterators.get(this.current); } } return false; } @Override public void remove() { this.iterators.get(this.current).remove(); } @Override public T next() { if (this.iterators.isEmpty()) throw FastNoSuchElementException.instance(); Iterator<? extends T> currentIterator = iterators.get(this.current); while (true) { if (currentIterator.hasNext()) { return currentIterator.next(); } else { this.current++; if (this.current >= iterators.size()) break; currentIterator = iterators.get(current); } } throw FastNoSuchElementException.instance(); } public void clear() { this.iterators.clear(); this.current = 0; } }
23.802817
86
0.65503
5817067afcebd61455ff5f90613520c3010956ca
1,633
package io.github.muxiaobai.common.ConvertUtil; import java.io.*; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; public class DuplicateFile { private void load(Set set, String path){ BufferedReader reader= new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream(path))); try{ for(String line = reader.readLine(); line != null; line = reader.readLine()){ set.add(line); } reader.close(); }catch(IOException e){ } } public static void main(String[] args) { Set set = new TreeSet(); DuplicateFile stop = new DuplicateFile(); stop.load(set,"/word/stop_words.txt"); System.out.println(set.size()); stop.writeToTxt(set); } public void writeToTxt(Set set){ Iterator iterator = set.iterator(); File file = new File("./stop_words.txt"); FileWriter fw = null; BufferedWriter writer = null; try { fw = new FileWriter(file); writer = new BufferedWriter(fw); while(iterator.hasNext()){ writer.write(iterator.next().toString()); writer.newLine();//换行 } writer.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); }finally{ try { writer.close(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
28.649123
116
0.540723
fd40bb26326601e271ac4a57a7a0e2a48b12be28
2,453
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.irobot.a; import java.util.Locale; // Referenced classes of package com.irobot.a: // g, d class g$25 implements j.a { public void a(j.b b) { g g1 = a; // 0 0:aload_0 // 1 1:getfield #16 <Field g a> // 2 4:astore_3 d d1 = null; // 3 5:aconst_null // 4 6:astore_2 g1.y = null; // 5 7:aload_3 // 6 8:aconst_null // 7 9:putfield #25 <Field j g.y> if(b != j.b.XFER_OK) //* 8 12:aload_1 //* 9 13:getstatic #31 <Field j$b j$b.XFER_OK> //* 10 16:if_acmpeq 51 { b = ((j.b) (String.format(Locale.US, "Firmware Update Failed: %s", new Object[] { b.toString() }))); // 11 19:getstatic #37 <Field Locale Locale.US> // 12 22:ldc1 #39 <String "Firmware Update Failed: %s"> // 13 24:iconst_1 // 14 25:anewarray Object[] // 15 28:dup // 16 29:iconst_0 // 17 30:aload_1 // 18 31:invokevirtual #43 <Method String j$b.toString()> // 19 34:aastore // 20 35:invokestatic #49 <Method String String.format(Locale, String, Object[])> // 21 38:astore_1 d1 = new d(d.a.ALOperationFailedError, ((String) (b))); // 22 39:new #51 <Class d> // 23 42:dup // 24 43:getstatic #57 <Field d$a d$a.ALOperationFailedError> // 25 46:aload_1 // 26 47:invokespecial #60 <Method void d(d$a, String)> // 27 50:astore_2 } ((g.d)a.a).d(a, d1); // 28 51:aload_0 // 29 52:getfield #16 <Field g a> // 30 55:getfield #63 <Field g$f g.a> // 31 58:checkcast #65 <Class g$d> // 32 61:aload_0 // 33 62:getfield #16 <Field g a> // 34 65:aload_2 // 35 66:invokeinterface #69 <Method void g$d.d(g, d)> // 36 71:return } final g a; g$25(g g1) { a = g1; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #16 <Field g a> super(); // 3 5:aload_0 // 4 6:invokespecial #19 <Method void Object()> // 5 9:return } }
29.914634
90
0.483082
dc449fb16a406855ff03e054aeda972a2530a5cd
1,550
/* * Copyright (C) 2016 The Dagger 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 dagger.grpc.functional.server; import dagger.grpc.server.InProcessServerModule; import java.io.IOException; import org.junit.rules.ExternalResource; final class CoffeeServerResource extends ExternalResource { private final String name; private final CoffeeServer<?> coffeeServer; CoffeeServerResource(String name, CoffeeServer.Builder<?> coffeeServerBuilder) { this.name = name; this.coffeeServer = coffeeServerBuilder.inProcessServerModule(InProcessServerModule.serverNamed(name)).build(); } public String name() { return name; } public int methodCount(String methodName) { return coffeeServer.countingInterceptor().countCalls(methodName); } @Override protected void before() throws IOException, InterruptedException { coffeeServer.start(); } @Override protected void after() { coffeeServer.shutdown(); } @Override public String toString() { return name; } }
27.678571
99
0.743226
cde87b4b1c1c5f705f989e30e1bc4dc635c8e693
3,708
import java.util.*; import org.junit.Test; import static org.junit.Assert.*; // LC1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/ // // Given an array of integers nums and a positive integer k, find whether it's possible to divide // this array into sets of k consecutive numbers. // Return True if it is possible. Otherwise, return False. // // Constraints: // 1 <= k <= nums.length <= 10^5 // 1 <= nums[i] <= 10^9 public class DivideArrayInSetsOfKConsecutiveNumbers { // SortedMap // time complexity: O(N*log(N)), space complexity: O(N) // 117 ms(66.05%), 50.6 MB(61.23%) for 47 tests public boolean isPossibleDivide(int[] nums, int k) { if (nums.length % k != 0) { return false; } TreeMap<Integer, Integer> freq = new TreeMap<>(); for (int num : nums) { freq.put(num, freq.getOrDefault(num, 0) + 1); } while (!freq.isEmpty()) { var entry = freq.pollFirstEntry(); int num = entry.getKey(); int count = entry.getValue(); for (int a = num + 1; a < num + k; a++) { int cnt = freq.getOrDefault(a, 0); if (cnt < count) { return false; } if (cnt == count) { freq.remove(a); } else { freq.put(a, cnt - count); } } } return true; } // SortedMap // time complexity: O(N*log(N)), space complexity: O(N) // 146 ms(49.24%), 49.4 MB(69.61%) for 47 tests public boolean isPossibleDivide2(int[] nums, int k) { TreeMap<Integer, Integer> freq = new TreeMap<>(); for (int num : nums) { freq.put(num, freq.getOrDefault(num, 0) + 1); } for (int num : freq.keySet()) { int count = freq.get(num); if (count == 0) { continue; } for (int i = k - 1; i >= 0; i--) { int diff = freq.getOrDefault(num + i, 0) - count; if (diff < 0) { return false; } freq.put(num + i, diff); } } return true; } // Hash Table + Heap // time complexity: O(N*log(N)), space complexity: O(N) // 63 ms(81.03%), 48.2 MB(87.82%) for 47 tests public boolean isPossibleDivide3(int[] nums, int k) { Map<Integer, Integer> freq = new HashMap<>(); PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int num : nums) { freq.put(num, freq.getOrDefault(num, 0) + 1); } pq.addAll(freq.keySet()); while (!pq.isEmpty()) { int cur = pq.poll(); int count = freq.get(cur); if (count == 0) { continue; } for (int i = 0; i < k; i++) { int diff = freq.getOrDefault(cur + i, 0) - count; if (diff < 0) { return false; } freq.put(cur + i, diff); } } return true; } private void test(int[] nums, int k, boolean expected) { assertEquals(expected, isPossibleDivide(nums, k)); assertEquals(expected, isPossibleDivide2(nums, k)); assertEquals(expected, isPossibleDivide3(nums, k)); } @Test public void test() { test(new int[] {1, 2, 3, 3, 4, 4, 5, 6}, 4, true); test(new int[] {3, 2, 1, 2, 3, 4, 3, 4, 5, 9, 10, 11}, 3, true); test(new int[] {3, 3, 2, 2, 1, 1}, 3, true); test(new int[] {1, 2, 3, 4}, 3, false); } public static void main(String[] args) { String clazz = new Object() { }.getClass().getEnclosingClass().getSimpleName(); org.junit.runner.JUnitCore.main(clazz); } }
33.405405
97
0.514293
fd436f0c1339f661556037866c01658a4b3d1cc5
69
package test; public final class Simple { public Simple() { } }
11.5
27
0.652174
14337aa692c6bfc99ef63bf3300e73112bd5218b
6,283
package com.echecs.api.web.controller; import com.echecs.api.model.*; import com.echecs.api.shared.MovementPieces; import com.echecs.api.shared.SequenceGeneratorService; import com.echecs.api.Repository.SessionRepo; import org.bson.json.JsonObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; import java.util.List; import java.util.Optional; @CrossOrigin(origins = "*") @RestController public class SessionController { @Autowired private SessionRepo sessionRepo; @Autowired private ChessController chessController; //@Autowired //private ChessRepo chessRepo; @Autowired private SequenceGeneratorService sequenceGeneratorService; /** * @return ResponseEntity<?> */ @RequestMapping(value = "/Sessions", method = RequestMethod.GET) public ResponseEntity<?> listSessions() { HttpHeaders headers = new HttpHeaders(); ServletUriComponentsBuilder location = ServletUriComponentsBuilder .fromCurrentRequest(); headers.setLocation(URI.create(location.toUriString())); return ResponseEntity.status(HttpStatus.ACCEPTED).headers(headers).body(sessionRepo.findAll()); } /** * @param id * @return Optional<Session> */ @GetMapping(value = "/Sessions/{id}") public Optional<Session> sessionById(@PathVariable int id) { return sessionRepo.findById(id); } /** * @param session * @return ResponseEntity<?> */ @PostMapping(value = "/Sessions") public ResponseEntity<?> saveSession(@RequestBody Session session) { //System.out.println(session); if (session== null) { return ResponseEntity.noContent().build(); } //si il existe deja un user avec le meme email, deja inscrit if(sessionRepo.findById((session.getIdSession())).isPresent()) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("une session est déja existante avec cet id"); } /* incrementer idChess créer un chess */ /*si le playerBlack et le playerWhite n'ont pas déjà une session existante , créer une nouvelle session sinon en créer reprendredre la session en incrémentant le idChess*/ boolean new_players=true; int idChess; Session exist_session=new Session(); Session sessionAdded=new Session(); //faire un filtre, existe t'il une session déjà par les deux players, si oui la récupérer List<Session> listSession= sessionRepo.findAll(); for (Session value : listSession) { if (((session.getIdBlackPlayer() == value.getIdBlackPlayer()) & (session.getIdWhitePlayer() == value.getIdWhitePlayer())) || ((session.getIdBlackPlayer() == value.getIdWhitePlayer()) & (session.getIdWhitePlayer() == value.getIdBlackPlayer()))) { new_players = false; exist_session = value; } } if(new_players){ //dans ce cas c'est le premier chess pour les deux players, donc nouvelle session Chess chess = new Chess(State.NEW); //appel controleur pour incrément id et save chess chessController.saveChess(chess); /* enregistrer la nouvelle session et récupérer le résultat du save */ //incrémenter l'id de la session, car c'est une nouvelle session.setIdSession(sequenceGeneratorService.generateSequence(Session.SEQUENCE_NAME)); //modifier la liste_chess (vide à l'inistialisation) de la session en ajoutant le nouveau chess session.getListIdChess().add(chess.getIdChess()); System.out.println("je crée une nouvelle session id : " +session.getIdSession()); // save la nouvelle session sessionAdded = sessionRepo.save(session); }else{ Chess chess = new Chess(State.NEW); //appel controleur pour incément id et save chess chessController.saveChess(chess); //ajouter l'id du nouvel chess à la liste de chess de la session idChess = chess.getIdChess(); exist_session.getListIdChess().add(idChess); sessionAdded=sessionRepo.save(exist_session); } /* creation de l'uri a retourner en cas de succes du save */ URI location = ServletUriComponentsBuilder .fromCurrentRequest() .path("/{id}") .buildAndExpand(sessionAdded.getIdSession()) .toUri(); return ResponseEntity.created(location).build(); } /** * @param idSession * @param idChess * @param idPlayer * @param from * @param to * @return ResponseEntity<?> */ @PostMapping(value="Sessions/{idSession}/{idChess}/move") public ResponseEntity<?> movePiece(@PathVariable int idSession,@PathVariable int idChess,@RequestParam Optional<Integer> idPlayer,@RequestParam Optional<String> from,@RequestParam Optional<String> to) { Session session= sessionById(idSession).get(); JsonObject response; if(session.getListIdChess().contains(idChess) && ((session.getIdWhitePlayer()==idPlayer.get())||(session.getIdBlackPlayer()==idPlayer.get()))){ Chess chess = chessController.chessById(idChess).get(); // System.out.println(chess.getSquares().get(from.get()).getPiece().getFamily()); response = MovementPieces.movePiece(from.get(),to.get(),chess,idPlayer.get(),session); // save a new chess after modif chessController.updateChess(chess); }else{ return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("le chess n'appartient pas à cette session ou le player ne joue pas dans cette session"); } return ResponseEntity.status(HttpStatus.ACCEPTED).body(response.toString()); } }
34.333333
257
0.652714
47fa11e2682f763bfa46634afbe0801384736268
1,538
/** * Licensed to the Austrian Association for Software Tool Integration (AASTI) * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. The AASTI 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.openengsb.ui.admin.organizeGlobalsPage; /** * Helper class for the easy maintaining of the globals in the tree of the OrganizeGlobalsPage */ public class Global { private String name; private String classname; public Global(String name, String classname) { this.setName(name); this.setClassname(classname); } public String toString() { return name; } public void setClassname(String classname) { this.classname = classname; } public String getClassname() { return classname; } public void setName(String name) { this.name = name; } public String getName() { return name; } }
29.576923
94
0.704161
f93e1664c4b79f1eafcd9d6658bb6cdd85eaad27
579
package uk.gov.register.util; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; public class ToArrayConverter extends JsonSerializer<Object> { public ToArrayConverter() { super(); } @Override public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartArray(1); gen.writeString(value.toString()); gen.writeEndArray(); } }
27.571429
111
0.74266
34a7056e519ed02ea1d98dbdca3c79bcdd28db1b
1,312
import dagger.MyApplicationLoader; import org.junit.Test; import play.Application; import play.ApplicationLoader; import play.Environment; import play.mvc.Http; import play.mvc.Result; import play.test.Helpers; import play.test.WithApplication; import java.util.Arrays; import java.util.List; import java.util.TimeZone; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static play.test.Helpers.*; public class IntegrationTest extends WithApplication { @Override protected Application provideApplication() { return new MyApplicationLoader().load(ApplicationLoader.create(Environment.simple())); } @Test public void testIndex() { Http.RequestBuilder request = Helpers.fakeRequest(); request.uri(controllers.routes.TimeController.index().url()); // passing app in explicitly here is key since route() overloads without it use the deprecated // static Application references Result result = route(app, request); assertEquals(result.status(), OK); String content = contentAsString(result); List<String> timezones = Arrays.asList(TimeZone.getAvailableIDs()); for (String timezone : timezones) { assertTrue(content.contains(timezone)); } } }
30.511628
102
0.722561
7d646d5295b60e8cf0047df615de292eae419d2c
248
package kr.webgori.lolien.discord.bot.dto.league; import java.time.LocalDateTime; import lombok.Builder; import lombok.Data; @Builder @Data public class LeagueDto { private int idx; private String title; private LocalDateTime createdDate; }
19.076923
49
0.790323
35b6414565b910432c65e05eb5aa0118d10dcbeb
958
package org.jetbrains.jps.builders.java; import org.jetbrains.jps.ExtensionsSupport; import java.io.File; import java.io.IOException; import java.util.Collection; /** * @author Eugene Zhuravlev */ public abstract class JavaSourceTransformer { public static abstract class TransformError extends IOException { protected TransformError(String message) { super(message); } protected TransformError(String message, Throwable cause) { super(message, cause); } protected TransformError(Throwable cause) { super(cause); } } public abstract CharSequence transform(File sourceFile, CharSequence content) throws TransformError; private static final ExtensionsSupport<JavaSourceTransformer> ourExtSupport = new ExtensionsSupport<JavaSourceTransformer>(JavaSourceTransformer.class); public static Collection<JavaSourceTransformer> getTransformers() { return ourExtSupport.getExtensions(); } }
25.891892
154
0.76096
c39eb939094ded2520afb4ac19c44c88c3b7b39d
277
package com.randomappsinc.simpleflashcards.quiz.constants; import androidx.annotation.IntDef; @IntDef({ QuestionType.MULTIPLE_CHOICE, QuestionType.FREE_FORM_INPUT }) public @interface QuestionType { int MULTIPLE_CHOICE = 0; int FREE_FORM_INPUT = 1; }
21.307692
58
0.747292
6ed8fb186e71e48ea3ad55aec6166da5f5439707
87
package edu.tum.cs.i1.pse; public class House extends AbstractCompositeComponent { }
17.4
55
0.793103
b9ea02dbad56d5264cd107d761370e841ebbaac0
10,842
package io.github.syncmc.murdersleuth.listeners; import java.util.Map.Entry; import java.util.UUID; import io.github.syncmc.murdersleuth.enums.GameString; import io.github.syncmc.murdersleuth.enums.PlayerRole; import io.github.syncmc.murdersleuth.events.GamePlayerEvent.MurdererAcquiredBowEvent; import io.github.syncmc.murdersleuth.events.GamePlayerEvent.MurdererKilledEvent; import io.github.syncmc.murdersleuth.events.GamePlayerEvent.NewDetectiveDetectedEvent; import io.github.syncmc.murdersleuth.events.GamePlayerEvent.NewMurdererDetectedEvent; import io.github.syncmc.murdersleuth.events.GamePlayerEvent.NonMurdererAcquiredBowEvent; import io.github.syncmc.murdersleuth.events.GamePlayerEvent.NonMurdererKilledEvent; import io.github.syncmc.murdersleuth.events.GamePlayerEvent.DetectiveKilledEvent; import io.github.syncmc.murdersleuth.util.GameHelper; import io.github.syncmc.murdersleuth.util.PlayerData; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.AbstractClientPlayer; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.init.MobEffects; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.potion.PotionEffect; import net.minecraft.util.math.BlockPos; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent.ClientTickEvent; import net.minecraftforge.fml.common.gameevent.TickEvent.Phase; public class ClientTickListener { @SubscribeEvent public void onClientTick(final ClientTickEvent event) { if (event.phase == Phase.END && (GameHelper.getInstance().localWorld = Minecraft.getMinecraft().world) != null && (GameHelper.getInstance().localPlayer = Minecraft.getMinecraft().player) != null) { for (EntityPlayer player : GameHelper.getInstance().localWorld.playerEntities) { if (player instanceof AbstractClientPlayer) { AbstractClientPlayer clientPlayer = (AbstractClientPlayer) player; UUID clientPlayerUUID = GameHelper.getUUID(clientPlayer); PlayerData clientPlayerData = GameHelper.getInstance().getPlayerData(clientPlayerUUID); PlayerRole clientPlayerRole = clientPlayerData.getPlayerRole(); BlockPos clientPlayerPos = clientPlayer.getPosition(); if (clientPlayerRole == PlayerRole.NONE) { clientPlayerData = new PlayerData(clientPlayer.getName(), PlayerRole.UNKNOWN, false, clientPlayerPos); clientPlayerRole = clientPlayerData.getPlayerRole(); GameHelper.getInstance().setPlayerData(clientPlayerUUID, clientPlayerData); } if (!clientPlayerData.getLastPos().equals(clientPlayerPos)) { clientPlayerPos = clientPlayer.getPosition(); clientPlayerData.setLastPos(clientPlayerPos); GameHelper.getInstance().setPlayerData(clientPlayerUUID, clientPlayerData); } if (clientPlayerRole == PlayerRole.UNKNOWN || clientPlayerRole == PlayerRole.INNOCENT || (clientPlayerRole == PlayerRole.MURDERER && !clientPlayerData.hasBow())) { UUID murdererUUID = GameHelper.getInstance().getMurdererUUID(); ItemStack itemStack = GameHelper.getHeldItemStack(clientPlayer); Item item = itemStack.getItem(); if (clientPlayerRole == PlayerRole.UNKNOWN && murdererUUID == null && item == Items.IRON_SWORD && itemStack.getDisplayName() .equals(GameString.KNIFE_NAME.getGameText().getStrippedFormattedText()) && GameHelper.getLore(itemStack).equals(GameHelper.getInstance().knifeLore)) { MinecraftForge.EVENT_BUS .post(new NewMurdererDetectedEvent(clientPlayerUUID, clientPlayerData)); } else if (item == Items.BOW && itemStack.getDisplayName() .equals(GameString.BOW_NAME.getGameText().getStrippedFormattedText())) { if ((clientPlayerRole == PlayerRole.UNKNOWN || clientPlayerRole == PlayerRole.INNOCENT) && GameHelper.getInstance().getDetectiveUUID() != clientPlayerUUID && GameHelper.getLore(itemStack).equals(GameHelper.getInstance().detBowLore)) { MinecraftForge.EVENT_BUS .post(new NewDetectiveDetectedEvent(clientPlayerUUID, clientPlayerData)); } else if (GameHelper.getLore(itemStack).equals(GameHelper.getInstance().innoBowLore)) { if ((clientPlayerRole == PlayerRole.UNKNOWN || clientPlayerRole == PlayerRole.INNOCENT) && !clientPlayerData.hasBow()) { MinecraftForge.EVENT_BUS .post(new NonMurdererAcquiredBowEvent(clientPlayerUUID, clientPlayerData)); } else if (clientPlayerRole == PlayerRole.MURDERER) { MinecraftForge.EVENT_BUS .post(new MurdererAcquiredBowEvent(clientPlayerUUID, clientPlayerData)); } } } if (clientPlayerRole == PlayerRole.UNKNOWN && murdererUUID != null) { clientPlayerData.setPlayerRole(PlayerRole.INNOCENT); GameHelper.getInstance().setPlayerData(clientPlayerUUID, clientPlayerData); } } } } for (Entry<UUID, PlayerData> entry : GameHelper.getInstance().getTrackedPlayerData().entrySet()) { UUID playerUUID = entry.getKey(); PlayerData playerData = entry.getValue(); if (playerData.getPlayerRole() != PlayerRole.DEAD) { EntityPlayer foundPlayer = GameHelper.getInstance().localWorld.getPlayerEntityByUUID(playerUUID); BlockPos playerPos = playerData.getLastPos(); int playerX = playerPos.getX(); int playerY = playerPos.getY(); int playerZ = playerPos.getZ(); if (foundPlayer == null) { if (GameHelper.getInstance().localPlayer.isInRangeToRender3d(playerX, playerY, playerZ)) { switch (playerData.getPlayerRole()) { case UNKNOWN: case INNOCENT: MinecraftForge.EVENT_BUS.post(new NonMurdererKilledEvent(playerUUID, playerData)); break; case DETECTIVE: MinecraftForge.EVENT_BUS.post(new DetectiveKilledEvent(playerUUID, playerData)); break; case MURDERER: MinecraftForge.EVENT_BUS.post(new MurdererKilledEvent(playerUUID, playerData)); break; default: break; } } } else if (foundPlayer.isInvisible()) { boolean hasInvisibilityPotionEffect = false; for (PotionEffect potionEffect : foundPlayer.getActivePotionEffects()) { if (!hasInvisibilityPotionEffect && potionEffect.getPotion() == MobEffects.INVISIBILITY && potionEffect.getDuration() > GameHelper.MAX_INVISIBILITY_TICKS) { hasInvisibilityPotionEffect = true; switch (playerData.getPlayerRole()) { case UNKNOWN: case INNOCENT: MinecraftForge.EVENT_BUS.post(new NonMurdererKilledEvent(playerUUID, playerData)); break; case DETECTIVE: MinecraftForge.EVENT_BUS.post(new DetectiveKilledEvent(playerUUID, playerData)); break; case MURDERER: MinecraftForge.EVENT_BUS.post(new MurdererKilledEvent(playerUUID, playerData)); break; default: break; } break; } } if (!hasInvisibilityPotionEffect) { switch (playerData.getPlayerRole()) { case UNKNOWN: case INNOCENT: MinecraftForge.EVENT_BUS.post(new NonMurdererKilledEvent(playerUUID, playerData)); break; case DETECTIVE: MinecraftForge.EVENT_BUS.post(new DetectiveKilledEvent(playerUUID, playerData)); break; case MURDERER: MinecraftForge.EVENT_BUS.post(new MurdererKilledEvent(playerUUID, playerData)); break; default: break; } } } } } } } }
53.408867
119
0.513374
f454283a4681b27f930fb1b4dd621b116d1867d6
1,592
/** * Copyright (C) 2002 Mike Hummel (mh@mhus.de) * * 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.summerclouds.common.crypt.crypt; import org.summerclouds.common.core.tool.MMath; /** * add for encode and sub for decode current block value. * * @author mikehummel */ public class CipherBlockAdd implements CipherBlock { private byte[] block; private int pos; public CipherBlockAdd(byte[] block) { this.block = block; } public CipherBlockAdd(int size) { block = new byte[size]; } public byte[] getBlock() { return block; } public int getSize() { return block.length; } @Override public void reset() { pos = 0; } @Override public byte encode(byte in) { in = MMath.addRotate(in, block[pos]); next(); return in; } @Override public byte decode(byte in) { in = MMath.subRotate(in, block[pos]); next(); return in; } private void next() { pos = (pos + 1) % block.length; } }
23.072464
75
0.631281
f71f6ab158cce25bbf9b4c01240bf00a6fb793dc
1,122
package me.panavtec.cleancontacts.di; import android.app.Application; import com.squareup.picasso.Picasso; import dagger.Module; import dagger.Provides; import javax.inject.Singleton; import me.panavtec.cleancontacts.di.qualifiers.UiThread; import me.panavtec.cleancontacts.presentation.CleanContactsViewInjector; import me.panavtec.cleancontacts.presentation.ViewInjectorImp; import me.panavtec.cleancontacts.ui.imageloader.ImageLoader; import me.panavtec.cleancontacts.ui.imageloader.PicassoImageLoader; import me.panavtec.threaddecoratedview.views.ThreadSpec; @Module( complete = false, library = true) public class UiModule { @Provides @Singleton Picasso providePicasso(Application app) { return Picasso.with(app); } @Provides @Singleton ImageLoader provideImageLoader(Picasso picasso) { return new PicassoImageLoader(picasso); } @Provides @Singleton CleanContactsViewInjector provideViewInjector(ViewInjectorImp imp) { return imp; } @Provides @Singleton ViewInjectorImp provieViewInjectorImp(@UiThread ThreadSpec threadSpec) { return new ViewInjectorImp(threadSpec); } }
32.057143
95
0.807487
ee50c4d6e77a798909560280c09d95eb9c700e28
10,578
package com.chen.data; import android.util.Log; import android.widget.Button; import android.widget.Toast; import com.chen.activity.BaseActivity; import com.chen.activity.R; import com.chen.handle.HttpUtil; import com.chen.handle.Util; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class ClassSign { public static class StudentSign{ private String name; private boolean signed; private StudentSign(String name,boolean signed){ this.name=name; this.signed=signed; } public String getName() { return name; } private boolean isSigned() { return signed; } } public static final String TAG="ClassSign";//用于生成日志的tag public static final int NOT_SIGNED=1;//状态:未签到 public static final int SIGNED=2;//状态:签到成功 public static final int FAILED=3;//状态:签到失败 private static ClassSign now_sign=null;//当前的签到 private static boolean allow_activity_update=true;//是否允许对应的活动更新当前签到 private String place;//签到地点 private String initiator;//发起人 private double[] center;//签到中心(用于核验用户是否签到成功) 第一个是纬度,第二个是经度 private int distance;//允许的最大签到距离半径 private MyDate deadline;//签到的截止时间 private int status;//签到状态 private int id;//签到在服务器sql中的id private List<StudentSign> studentSigns;//签到人员列表 private ClassSign(String place,String initiator,double[] center,int distance,MyDate deadline,int id,List<StudentSign> signs){ this.place=place; this.initiator=initiator; this.center=center; this.distance=distance; this.deadline=deadline; this.status=NOT_SIGNED; this.id=id; this.studentSigns=signs; } public String getPlace() { return place; } public String getInitiator() { return initiator; } public double[] getCenter() { return center; } public int getDistance() { return distance; } public MyDate getDeadline() { return deadline; } public int getStatus() { return status; } public int getId() { return id; } public void setStatus(int status) { this.status = status; } public static boolean isAllow_activity_update() { return allow_activity_update; } public static void setAllow_activity_update(boolean allow_activity_update) { ClassSign.allow_activity_update = allow_activity_update; } public static ClassSign getNow_sign() { return now_sign; } //从服务器查询对应于当前用户的签到 public static void searchClassSign(final BaseActivity activity){ List<HttpUtil.Arg> args=new ArrayList<>(); args.add(new HttpUtil.Arg("type","check_sign_events")); args.add(new HttpUtil.Arg("number",User.getNowUser().getNumber())); HttpUtil.sendGetHttpRequest(args, new Callback() { @Override public void onFailure(Call call, IOException e) { Util.displayError(activity,e,"查询签到失败",TAG,true); } @Override public void onResponse(Call call, Response response) throws IOException { try { JSONObject object=new JSONObject(URLDecoder.decode(response.body().string(),"utf-8")); if(object.getString("status").equals("ok")){ int id=Integer.parseInt(object.getString("id")); findSign(id,activity); }else{ now_sign=null; Util.recreateActivity(activity); } }catch (JSONException e){ Util.displayError(activity,e,"查询签到失败",TAG,true); } } }); } //根据id从服务器获取签到 private static void findSign(int id,final BaseActivity activity){ List<HttpUtil.Arg> args=new ArrayList<>(); args.add(new HttpUtil.Arg("type","check_sign")); args.add(new HttpUtil.Arg("id_list",""+id)); HttpUtil.sendPostHttpRequest(args, new Callback() { @Override public void onFailure(Call call, IOException e) { Util.displayError(activity,e,"寻找签到时出错",TAG,true); } @Override public void onResponse(Call call, Response response) throws IOException { try { JSONArray array=new JSONArray(URLDecoder.decode(response.body().string(),"utf-8")); JSONObject object=array.getJSONObject(0); String status=object.getString("status"); if(status.equals("ok")){ JSONArray msg=array.getJSONArray(1); JSONObject sign=msg.getJSONObject(0); int n=msg.length(); String place=sign.getString("place"); String initiator=sign.getString("initiator"); String center_w=sign.getString("center_w"); String center_j=sign.getString("center_j"); String distance=sign.getString("distance"); String deadline=sign.getString("deadline"); String sign_id=null; List<StudentSign> studentSigns=new ArrayList<>(); for(int i=1;i<n;i++){ JSONObject student=msg.getJSONObject(i); if(sign_id==null){ sign_id=student.getString("sign_id"); } String name=student.getString("name"); String sign_status=student.getString("sign_status"); studentSigns.add(new StudentSign(name,sign_status.equals("3"))); } double[] center=new double[2]; center[0]=Double.parseDouble(center_w); center[1]=Double.parseDouble(center_j); now_sign=new ClassSign(place,initiator,center,Integer.parseInt(distance),MyDate.parseMyDate(deadline),Integer.parseInt(sign_id),studentSigns); Util.recreateActivity(activity); }else { activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity,"找不到对应的签到",Toast.LENGTH_SHORT).show(); Log.e(TAG, "找不到对应的签到"); } }); } }catch (JSONException e){ Util.displayError(activity,e,"寻找签到时出错",TAG,true); } } }); } public void sign(final int distance,boolean succeed, final Button sign_btn, final BaseActivity activity){ sign_btn.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.btn_grey)); sign_btn.setEnabled(false); sign_btn.setText("请稍候"); if(succeed){ this.status=ClassSign.SIGNED; }else { this.status=ClassSign.FAILED; } List<HttpUtil.Arg> args=new ArrayList<>(); args.add(new HttpUtil.Arg("type","execute_sign")); args.add(new HttpUtil.Arg("number",User.getNowUser().getNumber())); args.add(new HttpUtil.Arg("sign_status",succeed ? "3":"2")); HttpUtil.sendGetHttpRequest(args, new Callback() { @Override public void onFailure(Call call, IOException e) { Util.displayError(activity,e,"签到时发生错误",TAG,true); displayError(activity,sign_btn); } @Override public void onResponse(Call call, Response response){ try{ String status=new JSONObject(URLDecoder.decode(response.body().string(),"utf-8")).getString("status"); if(status.equals("ok")){ activity.runOnUiThread(new Runnable() { @Override public void run() { sign_btn.setEnabled(false); sign_btn.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.btn_green)); sign_btn.setText("签到成功"); Toast.makeText(activity,"签到成功 距离为"+distance+"米",Toast.LENGTH_SHORT).show(); } }); }else { activity.runOnUiThread(new Runnable() { @Override public void run() { sign_btn.setEnabled(false); sign_btn.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.btn_red)); sign_btn.setText("签到失败"); Toast.makeText(activity,"签到失败 距离为"+distance+"米",Toast.LENGTH_SHORT).show(); } }); } }catch (Exception e){ Util.displayError(activity,e,"签到时发生错误",TAG,true); displayError(activity,sign_btn); } } }); } //签到时发生错误时的提示 private static void displayError(BaseActivity activity,final Button sign_btn){ try{ activity.runOnUiThread(new Runnable() { @Override public void run() { sign_btn.setText("错误"); } }); }catch (Exception e1){ e1.printStackTrace(); } } public List<ClassSign.StudentSign> getSignedStudents(){ List<StudentSign> signs=new ArrayList<>(); for(StudentSign s:studentSigns){ if(s.isSigned()){ signs.add(s); } } return signs; } public List<ClassSign.StudentSign> getUnsignedStudents(){ List<StudentSign> signs=new ArrayList<>(); for(StudentSign s:studentSigns){ if(!s.isSigned()){ signs.add(s); } } return signs; } }
38.326087
166
0.54065
29df529816ae5b9db4450d77849883878a2b1712
2,481
package net.jadfreex.pv.logic; import java.util.HashMap; import java.util.Map; import net.jadfreex.pv.model.Articulo; import net.jadfreex.pv.model.Contenedor; /** * * @author 170828 Grupo Salinas */ public abstract class ContenedorLogic<T extends Contenedor> { abstract T newInstance(); public T newInstance(Class<? extends Contenedor> clazz) { try { T container = (T)clazz.newInstance(); container.setSize(0); container.setArticulos(new HashMap<Integer, Articulo>()); return container; } catch (Exception e) { return null; } } public Contenedor addArticle(Contenedor container, Integer index, Articulo article) { if(null != container && null != article && null != container.getArticulos()) { Map<Integer, Articulo> articles = container.getArticulos(); container.setSize(container.getSize() + article.getQuantity()); articles.put(index, article); } return container; } public Contenedor removeArticle(Contenedor container, Integer index, Articulo article) { if(null != container && null != container.getArticulos()) { Map<Integer, Articulo> articles = container.getArticulos(); Articulo aux = articles.get(index); container.setSize(container.getSize() - aux.getQuantity()); articles.remove(index); } return container; } public Contenedor removeArticles(Contenedor container, Integer index) { if(null != container && null != container.getArticulos()) { Map<Integer, Articulo> articles = container.getArticulos(); container.setSize(0); articles.clear(); } return container; } public Articulo getArticle(Contenedor container, Integer index) { if(null != container && null != container.getArticulos()) { Map<Integer, Articulo> articles = container.getArticulos(); Articulo article = articles.get(index); return article; } return null; } public Map<Integer, Articulo> getArticles(Contenedor container) { if(null != container && null != container.getArticulos()) { Map<Integer, Articulo> articles = container.getArticulos(); return articles; } return null; } }
33.986301
93
0.598146
11c1f0a8752fd4e462dbaba326ae8d422448b454
1,907
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.mdrsolutions.web; import com.mdrsolutions.web.mp3.MP3ReadDirectory; import com.mdrsolutions.web.mp3.model.MP3Tag; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.codehaus.jackson.map.ObjectMapper; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.AbstractHandler; import org.springframework.context.ApplicationContext; /** * * @author michael */ public class Mp3TagService extends AbstractHandler { public static void main(String[] args) throws Exception { Server server = new Server(8080); server.setHandler(new Mp3TagService()); server.start(); server.join(); } public void handle(String string, Request rqst, HttpServletRequest hsr, HttpServletResponse hsr1) throws IOException, ServletException { hsr1.setContentType("application/json; charset=UTF-8"); hsr1.setStatus(HttpServletResponse.SC_OK); rqst.setHandled(true); String location = rqst.getParameter("loc"); ApplicationContext ac = ApplicationContextUtils.getApplicationContext(); MP3ReadDirectory readDirectory = (MP3ReadDirectory) ac.getBean("mp3ReadDirectory"); if (null != location) { List<MP3Tag> readMP3Directory = readDirectory.readMP3Directory(location); ObjectMapper mapper = new ObjectMapper(); hsr1.getWriter().println(mapper.writeValueAsString(readMP3Directory)); } else { hsr1.getWriter().println(""); } } private boolean validateRequestParam(String requestParam) { boolean flag = true; return flag; } }
34.053571
140
0.718406
c823dd4a2ea6bf1ecda22de1219d23b88f01b14f
446
package com.bulain.sort; public class BubbleSort implements Sort { public void sort(int[] params) { int temp; for (int i = params.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (params[j] > params[j + 1]) { temp = params[j]; params[j] = params[j + 1]; params[j + 1] = temp; } } } } }
24.777778
53
0.390135
9d0cd20658029af27b98b038ff4b19956633eaf5
6,045
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.usergrid.persistence.collection.mvcc.stage.write; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.apache.usergrid.persistence.collection.EntityCollectionManager; import org.apache.usergrid.persistence.collection.EntityCollectionManagerFactory; import org.apache.usergrid.persistence.collection.exception.WriteUniqueVerifyException; import org.apache.usergrid.persistence.collection.guice.TestCollectionModule; import org.apache.usergrid.persistence.collection.mvcc.stage.TestEntityGenerator; import org.apache.usergrid.persistence.collection.serialization.SerializationFig; import org.apache.usergrid.persistence.core.guice.MigrationManagerRule; import org.apache.usergrid.persistence.core.scope.ApplicationScope; import org.apache.usergrid.persistence.core.scope.ApplicationScopeImpl; import org.apache.usergrid.persistence.core.test.ITRunner; import org.apache.usergrid.persistence.core.test.UseModules; import org.apache.usergrid.persistence.model.entity.Entity; import org.apache.usergrid.persistence.model.entity.Id; import org.apache.usergrid.persistence.model.entity.SimpleId; import org.apache.usergrid.persistence.model.field.IntegerField; import org.apache.usergrid.persistence.model.field.StringField; import com.google.inject.Inject; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; /** * Simple integration test of uniqueness verification. */ @RunWith( ITRunner.class ) @UseModules( TestCollectionModule.class ) public class WriteUniqueVerifyIT { @Inject SerializationFig serializationFig; @Inject @Rule public MigrationManagerRule migrationManagerRule; @Inject public EntityCollectionManagerFactory cmf; @Test public void testConflict() { final Id appId = new SimpleId("testConflict"); final ApplicationScope scope = new ApplicationScopeImpl( appId ); final EntityCollectionManager entityManager = cmf.createCollectionManager( scope ); final Entity entity = TestEntityGenerator.generateEntity(); entity.setField(new StringField("name", "Aston Martin Vanquish", true)); entity.setField(new StringField("identifier", "v12", true)); entity.setField(new IntegerField("top_speed_mph", 200)); entityManager.write( entity ).toBlocking().last(); Entity entityFetched = entityManager.load( entity.getId() ).toBlocking().last(); entityFetched.setField( new StringField("foo", "bar")); // wait for temporary unique value records to time out try { Thread.sleep(serializationFig.getTimeout() * 1100); } catch (InterruptedException ignored) { } // another enity that tries to use two unique values already taken by first final Entity entity2 = TestEntityGenerator.generateEntity(); entity2.setField(new StringField("name", "Aston Martin Vanquish", true)); entity2.setField(new StringField("identifier", "v12", true)); entity2.setField(new IntegerField("top_speed_mph", 120)); try { entityManager.write( entity2 ).toBlocking().last(); fail("Write should have thrown an exception"); } catch ( Exception ex ) { WriteUniqueVerifyException e = (WriteUniqueVerifyException)ex; // verify two unique value violations assertEquals( 2, e.getVioliations().size() ); } // ensure we can update original entity without error entity.setField( new IntegerField("top_speed_mph", 190) ); entityManager.write( entity ); } @Test public void testNoConflict1() { final Id appId = new SimpleId("testNoConflict"); final ApplicationScope scope = new ApplicationScopeImpl( appId); final EntityCollectionManager entityManager = cmf.createCollectionManager( scope ); final Entity entity = TestEntityGenerator.generateEntity(); entity.setField(new StringField("name", "Porsche 911 GT3", true)); entity.setField(new StringField("identifier", "911gt3", true)); entity.setField(new IntegerField("top_speed_mph", 194)); entityManager.write( entity ).toBlocking().last(); Entity entityFetched = entityManager.load( entity.getId() ).toBlocking().last(); entityFetched.setField( new StringField("foo", "baz")); entityManager.write( entityFetched ).toBlocking().last(); } @Test public void testNoConflict2() { final Id appId = new SimpleId("testNoConflict"); final ApplicationScope scope = new ApplicationScopeImpl( appId ); final EntityCollectionManager entityManager = cmf.createCollectionManager( scope ); final Entity entity = TestEntityGenerator.generateEntity(); entity.setField(new StringField("name", "Alfa Romeo 8C Competizione", true)); entity.setField(new StringField("identifier", "ar8c", true)); entity.setField(new IntegerField("top_speed_mph", 182)); entityManager.write( entity ).toBlocking().last(); entity.setField( new StringField("foo", "bar")); entityManager.write( entity ).toBlocking().last(); } }
41.40411
91
0.726882
24e35b465dc7412280d3935d794e14017a80b592
1,411
// ============================================================================ // // Copyright (C) 2006-2018 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.repository.model.migration; import java.util.Date; import java.util.GregorianCalendar; import org.talend.core.model.migration.AbstractItemMigrationTask; import org.talend.core.model.properties.Item; /** * Migration task added only to avoid people to import jobs with additionalField in a version who doesn't contain the * additionalField.<br> * If any job is imported in an old version, there will be an exception because additionalField is not existing in the * old emf model. */ public class AddAdditionalFieldMigrationTask extends AbstractItemMigrationTask { public Date getOrder() { GregorianCalendar gc = new GregorianCalendar(2012, 6, 25, 14, 0, 0); return gc.getTime(); } @Override public ExecutionResult execute(Item item) { return ExecutionResult.NOTHING_TO_DO; } }
35.275
119
0.64068
7ed5af52c24b51e799407be30f2934fb6783d1c2
1,206
package org.clafer.ir; import org.clafer.common.Check; import org.clafer.domain.Domain; /** * Returns array[index]. * * @author jimmy */ public class IrSetElement extends IrAbstractSet { private final IrSetArrayExpr array; private final IrIntExpr index; IrSetElement(IrSetArrayExpr array, IrIntExpr index, Domain env, Domain ker, Domain card) { super(env, ker, card); this.array = Check.notNull(array); this.index = Check.notNull(index); } public IrSetArrayExpr getArray() { return array; } public IrIntExpr getIndex() { return index; } @Override public <A, B> B accept(IrSetExprVisitor<A, B> visitor, A a) { return visitor.visit(this, a); } @Override public boolean equals(Object obj) { if (obj instanceof IrSetElement) { IrSetElement other = (IrSetElement) obj; return array.equals(other.array) && index.equals(other.index); } return false; } @Override public int hashCode() { return array.hashCode() ^ index.hashCode(); } @Override public String toString() { return array + "[" + index + "]"; } }
22.333333
94
0.613599
df179079a3f5f1402c8c75f12ebfb7243c98c9ac
3,120
// // Copyright (c) 2008-2011, Kenneth Bell // // 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 DiscUtils.Net.Dns; import java.time.Instant; /** * Base class for all resource records (DNS RRs). */ public class ResourceRecord { public ResourceRecord(String name, RecordType type, RecordClass rClass, long expiry) { _name = name; _recordType = type; _class = rClass; _expiry = expiry; } /** * Gets the class of record. */ private RecordClass _class; public RecordClass getClass_() { return _class; } /** * Gets the expiry time of the record. */ private long _expiry; public long getExpiry() { return _expiry; } /** * Gets the name of the resource (domain). */ private String _name; public String getName() { return _name; } /** * Gets the type of record. */ private RecordType _recordType; public RecordType getRecordType() { return _recordType; } public static ResourceRecord readFrom(PacketReader reader) { String name = reader.readName(); RecordType type = RecordType.valueOf(reader.readUShort()); RecordClass rClass = RecordClass.valueOf(reader.readUShort()); long expiry = Instant.now().plusSeconds(reader.readInt()).toEpochMilli(); switch (type) { case Pointer: return new PointerRecord(name, type, rClass, expiry, reader); case CanonicalName: return new CanonicalNameRecord(name, type, rClass, expiry, reader); case Address: return new IP4AddressRecord(name, type, rClass, expiry, reader); case Text: return new TextRecord(name, type, rClass, expiry, reader); case Service: return new ServiceRecord(name, type, rClass, expiry, reader); default: int len = reader.readUShort(); reader.setPosition(reader.getPosition() + len); return new ResourceRecord(name, type, rClass, expiry); } } }
30.291262
90
0.661218
c37190aff690988555240af97d190853fab17ebd
3,423
/* * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must 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 com.oracle.truffle.api.instrumentation; import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; /** * Event node factories are factories of event nodes for a {@link EventContext program location}. * The factory might be invoked multiple times for one and the same source location but the location * does never change for a particular returned event node. * * <p> * For example it makes sense to register a performance counter on {@link #create(EventContext) } * and increment the counter in the {@link ExecutionEventNode} implementation. The counter can be * stored as a {@link CompilationFinal compilation final}, so no peak performance overhead persists * for looking up the counter on the fast path. * </p> * * @since 0.12 */ public interface ExecutionEventNodeFactory { /** * Returns a new instance of {@link ExecutionEventNode} for this particular source location. * This method might be invoked multiple times for one particular source location * {@link EventContext context}. The implementation must ensure that this is handled * accordingly. * * @param context the current context where this event node should get created. * @return a new event node instance, or <code>null</code> for no event node at the location * @since 0.12 */ ExecutionEventNode create(EventContext context); }
46.256757
100
0.748758
40f17ae565b4a882a171cc2530b0e8833497c000
2,015
package org.venity.jphp.ext.android.android.classes; import com.gluonhq.charm.glisten.control.AppBar; import com.gluonhq.charm.glisten.visual.MaterialDesignIcon; import javafx.scene.Node; import org.venity.jphp.ext.android.AndroidExtension; import org.venity.jphp.ext.android.fx.classes.UXControl; import org.venity.jphp.ext.android.fx.classes.UXList; import php.runtime.annotation.Reflection; import php.runtime.env.Environment; import php.runtime.reflection.ClassEntity; @Reflection.Name("UXAppBar") @Reflection.Namespace(AndroidExtension.NS_ANDROID) public class UXAppBar extends UXControl<AppBar> { public UXAppBar(Environment env, AppBar wrappedObject) { super(env, wrappedObject); } public UXAppBar(Environment env, ClassEntity clazz) { super(env, clazz); } @Reflection.Signature public void __construct(){ __wrappedObject = new AppBar(); } @Reflection.Signature public void clear(){ getWrappedObject().clear(); } @Reflection.Getter public double getSpacing(){ return getWrappedObject().getSpacing(); } @Reflection.Setter public void setSpacing(double s){ getWrappedObject().setSpacing(s); } @Reflection.Getter public double getProgress(){ return getWrappedObject().getProgress(); } @Reflection.Setter public void setProgress(double p){ getWrappedObject().setProgress(p); } @Reflection.Getter public Node getNavIcon(){ return getWrappedObject().getNavIcon(); } @Reflection.Getter public UXList<Node> getItems(){ return new UXList<Node>(__env__, getWrappedObject().getActionItems()); } @Reflection.Setter public void setNavIcon(Node N){ getWrappedObject().setNavIcon(N); } @Reflection.Getter public Node getTitle(){ return getWrappedObject().getTitle(); } @Reflection.Setter public void setTitle(Node N){ getWrappedObject().setTitle(N); } }
24.573171
78
0.691315
2a24881f67fa90426db1691b6aa6bcb40ab50c1c
11,983
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.policy; import android.test.ActivityInstrumentationTestCase2; import android.test.UiThreadTest; import android.test.suitebuilder.annotation.SmallTest; import android.view.ActionMode; import android.view.ActionMode.Callback; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.SearchEvent; import android.view.View; import android.view.Window; import android.view.WindowManager.LayoutParams; import android.view.accessibility.AccessibilityEvent; import java.util.List; /** * Tests {@link PhoneWindow}'s {@link ActionMode} related methods. */ @SmallTest public final class PhoneWindowActionModeTest extends ActivityInstrumentationTestCase2<PhoneWindowActionModeTestActivity> { private PhoneWindow mPhoneWindow; private MockWindowCallback mWindowCallback; private MockActionModeCallback mActionModeCallback; public PhoneWindowActionModeTest() { super(PhoneWindowActionModeTestActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); mPhoneWindow = (PhoneWindow) getActivity().getWindow(); mWindowCallback = new MockWindowCallback(); mPhoneWindow.setCallback(mWindowCallback); mActionModeCallback = new MockActionModeCallback(); } public void testStartActionModeWithCallback() { mWindowCallback.mShouldReturnOwnActionMode = true; ActionMode mode = mPhoneWindow.getDecorView().startActionMode( mActionModeCallback, ActionMode.TYPE_FLOATING); assertEquals(mWindowCallback.mLastCreatedActionMode, mode); } public void testStartActionModePrimaryFinishesPreviousMode() { // Use custom callback to control the provided ActionMode. mWindowCallback.mShouldReturnOwnActionMode = true; ActionMode mode1 = mPhoneWindow.getDecorView().startActionMode( mActionModeCallback, ActionMode.TYPE_PRIMARY); ActionMode mode2 = mPhoneWindow.getDecorView().startActionMode( mActionModeCallback, ActionMode.TYPE_PRIMARY); assertTrue(mode1 instanceof MockActionMode); assertTrue(((MockActionMode) mode1).mIsFinished); assertNotNull(mode2); } public void testStartActionModeFloatingFinishesPreviousMode() { // Use custom callback to control the provided ActionMode. mWindowCallback.mShouldReturnOwnActionMode = true; ActionMode mode1 = mPhoneWindow.getDecorView().startActionMode( mActionModeCallback, ActionMode.TYPE_FLOATING); ActionMode mode2 = mPhoneWindow.getDecorView().startActionMode( mActionModeCallback, ActionMode.TYPE_FLOATING); assertTrue(mode1 instanceof MockActionMode); assertTrue(((MockActionMode) mode1).mIsFinished); assertNotNull(mode2); } public void testStartActionModePreservesPreviousModeOfDifferentType1() { // Use custom callback to control the provided ActionMode. mWindowCallback.mShouldReturnOwnActionMode = true; ActionMode mode1 = mPhoneWindow.getDecorView().startActionMode( mActionModeCallback, ActionMode.TYPE_FLOATING); ActionMode mode2 = mPhoneWindow.getDecorView().startActionMode( mActionModeCallback, ActionMode.TYPE_PRIMARY); assertTrue(mode1 instanceof MockActionMode); assertFalse(((MockActionMode) mode1).mIsFinished); assertNotNull(mode2); } public void testStartActionModePreservesPreviousModeOfDifferentType2() { // Use custom callback to control the provided ActionMode. mWindowCallback.mShouldReturnOwnActionMode = true; ActionMode mode1 = mPhoneWindow.getDecorView().startActionMode( mActionModeCallback, ActionMode.TYPE_PRIMARY); ActionMode mode2 = mPhoneWindow.getDecorView().startActionMode( mActionModeCallback, ActionMode.TYPE_FLOATING); assertTrue(mode1 instanceof MockActionMode); assertFalse(((MockActionMode) mode1).mIsFinished); assertNotNull(mode2); } public void testWindowCallbackModesLifecycleIsNotHandled() { mWindowCallback.mShouldReturnOwnActionMode = true; ActionMode mode = mPhoneWindow.getDecorView().startActionMode( mActionModeCallback, ActionMode.TYPE_PRIMARY); assertNotNull(mode); assertEquals(mWindowCallback.mLastCreatedActionMode, mode); assertFalse(mActionModeCallback.mIsCreateActionModeCalled); assertTrue(mWindowCallback.mIsActionModeStarted); } @UiThreadTest public void testCreatedPrimaryModeLifecycleIsHandled() { mWindowCallback.mShouldReturnOwnActionMode = false; ActionMode mode = mPhoneWindow.getDecorView().startActionMode( mActionModeCallback, ActionMode.TYPE_PRIMARY); assertNotNull(mode); assertEquals(ActionMode.TYPE_PRIMARY, mode.getType()); assertTrue(mActionModeCallback.mIsCreateActionModeCalled); assertTrue(mWindowCallback.mIsActionModeStarted); } @UiThreadTest public void testCreatedFloatingModeLifecycleIsHandled() { mWindowCallback.mShouldReturnOwnActionMode = false; ActionMode mode = mPhoneWindow.getDecorView().startActionMode( mActionModeCallback, ActionMode.TYPE_FLOATING); assertNotNull(mode); assertEquals(ActionMode.TYPE_FLOATING, mode.getType()); assertTrue(mActionModeCallback.mIsCreateActionModeCalled); assertTrue(mWindowCallback.mIsActionModeStarted); } @UiThreadTest public void testCreatedModeIsNotStartedIfCreateReturnsFalse() { mWindowCallback.mShouldReturnOwnActionMode = false; mActionModeCallback.mShouldCreateActionMode = false; ActionMode mode = mPhoneWindow.getDecorView().startActionMode( mActionModeCallback, ActionMode.TYPE_FLOATING); assertTrue(mActionModeCallback.mIsCreateActionModeCalled); assertFalse(mWindowCallback.mIsActionModeStarted); assertNull(mode); } private static final class MockWindowCallback implements Window.Callback { private boolean mShouldReturnOwnActionMode = false; private MockActionMode mLastCreatedActionMode; private boolean mIsActionModeStarted = false; @Override public boolean dispatchKeyEvent(KeyEvent event) { return false; } @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) { return false; } @Override public boolean dispatchTouchEvent(MotionEvent event) { return false; } @Override public boolean dispatchTrackballEvent(MotionEvent event) { return false; } @Override public boolean dispatchGenericMotionEvent(MotionEvent event) { return false; } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { return false; } @Override public View onCreatePanelView(int featureId) { return null; } @Override public boolean onCreatePanelMenu(int featureId, Menu menu) { return false; } @Override public boolean onPreparePanel(int featureId, View view, Menu menu) { return false; } @Override public boolean onMenuOpened(int featureId, Menu menu) { return false; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { return false; } @Override public void onWindowAttributesChanged(LayoutParams attrs) {} @Override public void onContentChanged() {} @Override public void onWindowFocusChanged(boolean hasFocus) {} @Override public void onAttachedToWindow() {} @Override public void onDetachedFromWindow() {} @Override public void onPanelClosed(int featureId, Menu menu) {} @Override public boolean onSearchRequested() { return false; } @Override public boolean onSearchRequested(SearchEvent searchEvent) { return false; } @Override public ActionMode onWindowStartingActionMode(Callback callback) { if (mShouldReturnOwnActionMode) { MockActionMode mode = new MockActionMode(); mLastCreatedActionMode = mode; return mode; } return null; } @Override public ActionMode onWindowStartingActionMode(Callback callback, int type) { if (mShouldReturnOwnActionMode) { MockActionMode mode = new MockActionMode(); mode.mActionModeType = type; mLastCreatedActionMode = mode; return mode; } return null; } @Override public void onActionModeStarted(ActionMode mode) { mIsActionModeStarted = true; } @Override public void onActionModeFinished(ActionMode mode) {} } private static final class MockActionModeCallback implements ActionMode.Callback { private boolean mShouldCreateActionMode = true; private boolean mIsCreateActionModeCalled = false; @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return true; } @Override public void onDestroyActionMode(ActionMode mode) {} @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { mIsCreateActionModeCalled = true; return mShouldCreateActionMode; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return false; } } private static final class MockActionMode extends ActionMode { private int mActionModeType = ActionMode.TYPE_PRIMARY; private boolean mIsFinished = false; @Override public int getType() { return mActionModeType; } @Override public void setTitle(CharSequence title) {} @Override public void setTitle(int resId) {} @Override public void setSubtitle(CharSequence subtitle) {} @Override public void setSubtitle(int resId) {} @Override public void setCustomView(View view) {} @Override public void invalidate() {} @Override public void finish() { mIsFinished = true; } @Override public Menu getMenu() { return null; } @Override public CharSequence getTitle() { return null; } @Override public CharSequence getSubtitle() { return null; } @Override public View getCustomView() { return null; } @Override public MenuInflater getMenuInflater() { return null; } } }
31.785146
86
0.669365
90d773eb14c7724ffc4056a1885578d59ee0391c
1,104
package org.aikodi.jlo.model.expression; import org.aikodi.chameleon.core.element.ElementImpl; import org.aikodi.chameleon.core.lookup.LocalLookupContext; import org.aikodi.chameleon.core.lookup.LookupException; import org.aikodi.chameleon.core.reference.CrossReferenceTarget; import org.aikodi.chameleon.core.validation.Valid; import org.aikodi.chameleon.core.validation.Verification; import org.aikodi.chameleon.oo.type.Type; public abstract class AbstractTarget extends ElementImpl implements CrossReferenceTarget { public AbstractTarget() { super(); } public abstract Type getTargetDeclaration(); public LocalLookupContext<?> targetContext() throws LookupException { return getTargetDeclaration().targetContext(); } /** * A super target is always valid. If invocations on a super target must always resolve to an effective declaration, * as is the case in Java, then the language must add that rule. For mixins, for example, that must only be the case for * an actual combination of mixins. */ @Override public Verification verifySelf() { return Valid.create(); } }
32.470588
121
0.787138
600d92109482cbda8df3aaac9f435510f5a1a9be
5,274
/* * Copyright 2006-2009, 2017, 2020 United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The NASA World Wind Java (WWJ) platform is 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. * * NASA World Wind Java (WWJ) also contains the following 3rd party Open Source * software: * * Jackson Parser – Licensed under Apache 2.0 * GDAL – Licensed under MIT * JOGL – Licensed under Berkeley Software Distribution (BSD) * Gluegen – Licensed under Berkeley Software Distribution (BSD) * * A complete listing of 3rd Party software notices and licenses included in * NASA World Wind Java (WWJ) can be found in the WorldWindJava-v2.2 3rd-party * notices and licenses PDF found in code directory. */ package gov.nasa.worldwindx.examples; import gov.nasa.worldwind.WorldWind; import gov.nasa.worldwind.avlist.AVKey; import gov.nasa.worldwind.geom.Position; import gov.nasa.worldwind.layers.RenderableLayer; import gov.nasa.worldwind.render.*; import gov.nasa.worldwind.util.*; import java.awt.*; import java.util.ArrayList; /** * @author tag * @version $Id: PathsOnDateline.java 2189 2014-07-30 19:25:51Z tgaskins $ */ public class PathsOnDateline extends ApplicationTemplate { public static class AppFrame extends ApplicationTemplate.AppFrame { public AppFrame() { super(true, true, false); RenderableLayer layer = new RenderableLayer(); // Create and set an attribute bundle. ShapeAttributes attrs = new BasicShapeAttributes(); attrs.setOutlineMaterial(new Material(WWUtil.makeRandomColor(null))); attrs.setOutlineWidth(2d); ArrayList<Position> pathPositions = new ArrayList<Position>(); pathPositions.add(Position.fromDegrees(28, 170, 1e4)); pathPositions.add(Position.fromDegrees(35, -179, 1e4)); pathPositions.add(Position.fromDegrees(38, 180, 1e4)); pathPositions.add(Position.fromDegrees(35, -170, 1e4)); pathPositions.add(Position.fromDegrees(30, -170, 1e4)); pathPositions.add(Position.fromDegrees(32, -180, 1e4)); pathPositions.add(Position.fromDegrees(30, 170, 1e4)); Path path = new Path(pathPositions); path.setAttributes(attrs); BasicShapeAttributes highlightAttrs = new BasicShapeAttributes(attrs); highlightAttrs.setOutlineMaterial(Material.WHITE); path.setHighlightAttributes(highlightAttrs); path.setVisible(true); path.setAltitudeMode(WorldWind.RELATIVE_TO_GROUND); path.setPathType(AVKey.GREAT_CIRCLE); path.setShowPositions(true); path.setShowPositionsThreshold(1e12); // Configure the path to draw its outline and position points in the colors below. We use three colors that // are evenly distributed along the path's length and gradually increasing in opacity. Position colors may // be assigned in any manner the application chooses. This example illustrates only one way of assigning // color to each path position. Color[] colors = { new Color(1f, 0f, 0f, 0.4f), new Color(0f, 1f, 0f, 0.6f), new Color(0f, 0f, 1f, 1.0f), }; path.setPositionColors(new ExamplePositionColors(colors, pathPositions.size())); layer.addRenderable(path); insertBeforeCompass(getWwd(), layer); this.getWwd().addSelectListener(new BasicDragger((this.getWwd()))); } } /** * Example implementation of {@link gov.nasa.worldwind.render.Path.PositionColors} that evenly distributes the * specified colors along a path with the specified length. For example, if the Colors array contains red, green, * blue (in that order) and the pathLength is 6, this assigns the following colors to each path ordinal: 0:red, * 1:red, 2:green, 3:green, 4:blue, 5:blue. */ public static class ExamplePositionColors implements Path.PositionColors { protected Color[] colors; protected int pathLength; public ExamplePositionColors(Color[] colors, int pathLength) { this.colors = colors; this.pathLength = pathLength; } public Color getColor(Position position, int ordinal) { int index = colors.length * ordinal / this.pathLength; return this.colors[index]; } } public static void main(String[] args) { ApplicationTemplate.start("Paths on Dateline", AppFrame.class); } }
41.203125
119
0.669132
88af8ca7ce08cad690138ebf0c52588b9abcbb2a
3,007
/* */ package org.springframework.instrument.classloading.weblogic; /* */ /* */ import java.lang.instrument.ClassFileTransformer; /* */ import java.lang.instrument.IllegalClassFormatException; /* */ import java.lang.reflect.InvocationHandler; /* */ import java.lang.reflect.Method; /* */ import java.util.Hashtable; /* */ import org.springframework.lang.Nullable; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ class WebLogicClassPreProcessorAdapter /* */ implements InvocationHandler /* */ { /* */ private final ClassFileTransformer transformer; /* */ private final ClassLoader loader; /* */ /* */ public WebLogicClassPreProcessorAdapter(ClassFileTransformer transformer, ClassLoader loader) { /* 49 */ this.transformer = transformer; /* 50 */ this.loader = loader; /* */ } /* */ /* */ /* */ /* */ @Nullable /* */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { /* 57 */ String name = method.getName(); /* 58 */ if ("equals".equals(name)) { /* 59 */ return Boolean.valueOf((proxy == args[0])); /* */ } /* 61 */ if ("hashCode".equals(name)) { /* 62 */ return Integer.valueOf(hashCode()); /* */ } /* 64 */ if ("toString".equals(name)) { /* 65 */ return toString(); /* */ } /* 67 */ if ("initialize".equals(name)) { /* 68 */ initialize((Hashtable<?, ?>)args[0]); /* 69 */ return null; /* */ } /* 71 */ if ("preProcess".equals(name)) { /* 72 */ return preProcess((String)args[0], (byte[])args[1]); /* */ } /* */ /* 75 */ throw new IllegalArgumentException("Unknown method: " + method); /* */ } /* */ /* */ /* */ public void initialize(Hashtable<?, ?> params) {} /* */ /* */ /* */ public byte[] preProcess(String className, byte[] classBytes) { /* */ try { /* 84 */ byte[] result = this.transformer.transform(this.loader, className, null, null, classBytes); /* 85 */ return (result != null) ? result : classBytes; /* */ } /* 87 */ catch (IllegalClassFormatException ex) { /* 88 */ throw new IllegalStateException("Cannot transform due to illegal class format", ex); /* */ } /* */ } /* */ /* */ /* */ public String toString() { /* 94 */ return getClass().getName() + " for transformer: " + this.transformer; /* */ } /* */ } /* Location: /home/kali/ctf/htb/fatty-10.10.10.174/ftp/fatty-client.jar!/org/springframework/instrument/classloading/weblogic/WebLogicClassPreProcessorAdapter.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
29.480392
177
0.502162
2fc80ef648e6b77960492edbe100c063f65d0a3d
928
package ru.arsmagna; import org.jetbrains.annotations.*; import java.util.ArrayList; import java.util.Collection; /** * Секция INI-файла. */ public final class IniSection { /** * Имя секции. */ public String name; /** * Строки. */ public Collection<IniLine> lines; //========================================================================= /** * Конструктор по умолчанию. */ public IniSection() { lines = new ArrayList<>(); } /** * Конструктор. * @param name Имя секции. */ public IniSection ( String name ) { this.name = name; lines = new ArrayList<>(); } //========================================================================= @NotNull @Override @Contract(pure = true) public String toString() { return "[" + name + "]"; } }
16.571429
79
0.422414
73454f31d34a7b8ac63328502699c5d1e2e02f62
1,180
package org.gecko.config; import org.gecko.core.gen.converter.DataTypeConverter; import org.gecko.core.gen.converter.WidgetTypeConverter; import org.gecko.core.gen.parser.BeetlParser; import org.gecko.core.gen.parser.FreeMarkerParser; import org.gecko.core.gen.parser.Parser; import org.gecko.core.gen.parser.ParserComposite; import org.gecko.core.metadata.MetaDataService; import org.gecko.core.metadata.MetaDataServiceImpl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author: dengzhi * @date: 2018/5/28 */ @Configuration public class CodeConfig { @Bean public MetaDataService metaDataService() { return new MetaDataServiceImpl(); } @Bean public DataTypeConverter dataTypeConverter() { return new DataTypeConverter(); } @Bean public WidgetTypeConverter WidgetTypeConverter() { return new WidgetTypeConverter(); } @Bean public Parser parser() { ParserComposite parser = new ParserComposite(); parser.addParser(new BeetlParser()); parser.addParser(new FreeMarkerParser()); return parser; } }
26.818182
60
0.733898
e80fea920fd9391e466c60774ec61f45a21c0e72
2,456
package com.insulin.shared.constants; /** * Large class of constants used for email, starting from the configuration to the actual message passed * to the user. */ public final class EmailConstants { public static final String SIMPLE_MAIL_TRANSFER_PROTOCOL = "smtps"; public static final String FROM_EMAIL = "support@insulin.com"; public static final String CC_EMAIL = ""; public static final String EMAIL_SUBJECT = "Insulin Sensitivity - Welcome abroad!"; public static final String DELETE_SUBJECT = "Insulin Sensitivity - We are sorry"; public static final String RESET_SUBJECT = "Insulin Sensitivity - Forgot your password?"; public static final String GMAIL_SMTP_SERVER = "smtp.gmail.com"; public static final String SMTP_HOST = "mail.smtp.host"; public static final String SMTP_AUTH = "mail.smtp.auth"; public static final String SMTP_PORT = "mail.smtp.port"; public static final int DEFAULT_PORT = 465; public static final String SMTP_STARTTLS_ENABLE = "mail.smtp.starttls.enable"; public static final String SMTP_STARTTLS_REQUIRED = "mail.smtp.starttls.required"; public static final String REGISTER_TEXT_MESSAGE = "Hello Mr./Mrs. %s,\n\nWe are pleased to announce you that your account was created with " + "success. In order to use your account, login using the credentials inserted to the register form. We hope that our application " + "will be useful for you and your healthy.\n\nWe thank you for your trust,\nInsulin Sensitivity Team"; public static final String DELETE_TEXT_MESSAGE = "Dear Mr./Mrs. %s, \n\nWe are sorry that you choose to leave us, no matter what the reason is. " + "We hope that someday you will come back, we are welcoming you anytime with our arms open. Until then, best of luck and thank you for all your " + "support.\n\nWe thank you for your trust,\nInsulin Sensitivity Team"; public static final String RESET_PASSWORD_MESSAGE = "Dear Mr/Mrs,\n\nYou requested a link to reset your password. " + "Click here: http://localhost:4200/resetPassword/%s in order to change your password. " + "Please pay attention that the link is available only three hours! " + "You will be prompted to a form where you can insert your newly password.\nIf you did not request to change your password, please ignore the link from above.\n\n" + "Insulin Sensitivity team."; }
68.222222
174
0.724756
a509c934b76e8649a255365241eced6df7dca8e5
2,583
package factory; import factory.validator.TransactionValidator; import factory.validator.ValidationResult; import fileio.repository.BanknoteRepository; import fileio.repository.CoinRepository; import fileio.repository.DatabaseResult; import model.Currency; import model.Transaction; import state.*; import state.TransactionType; public class TransactionFactory { /** * The function creates transaction object according to given params * * @param transactionId * @param pair = trade pair like BTC-USD * @param coinQuantity = coin order quantity like 1 BTC * @param coinOrderValue = coin order value like 35000 to buy/sell coin * @param transactionType = approved or pending transaction * @return Transaction object */ public Transaction createTransaction(String transactionId, String pair, String coinQuantity, String coinOrderValue, String transactionType) { String[] pairNames = pair.split("-"); // split currency names ( example BTC-USD -> BTC USD ) // Validate currencies' name ValidationResult pairResult = TransactionValidator.validatePair(pairNames[0], pairNames[1]); // Validate coin order quantity and coin order value ValidationResult quantityResult = TransactionValidator.validateQuantites(coinQuantity, coinOrderValue); // Validate type ValidationResult typeResult = TransactionValidator.validateType(transactionType); boolean isValidated = pairResult.isValid && quantityResult.isValid && typeResult.isValid; // If params include invalid param, return null if (!isValidated) { return null; } // Validate id is unique or not ValidationResult idResult = TransactionValidator.validateTransactionId(transactionId); String id = transactionId; // If id is not unique, get the new unique id if (!idResult.isValid) id = idResult.messages; // Get the coin object from coin repository ( like BTC object ) DatabaseResult gottenCoin = (new CoinRepository()).getById(pairNames[0]); // Get the banknote object from banknote repository ( like USD object ) DatabaseResult gottenBanknote = (new BanknoteRepository()).getById(pairNames[1]); // Create state for transaction type State state = new Pending(); if (transactionType.equals("Approved")) { state = new Approved(); } TransactionType type = new TransactionType(state); // Create transaction Transaction transaction = new Transaction(id, (Currency) gottenCoin.getObject(), (Currency) gottenBanknote.getObject(), type, Double.valueOf(coinQuantity), Double.valueOf(coinOrderValue)); return transaction; } }
34.44
116
0.75842
ab404b0bcfe42cd6437ccb11d64ac70f4a1e6e05
2,105
package com.bazl.dna.database.compare.constants; import com.bazl.dna.common.PublicConstants; public class QuickCompareConstants extends PublicConstants { /** * 查询数不能大于线程数 */ public static final int COMPARE_PAGE_SIZE = 10; /** * 队列类型 */ public static final String QUEUE_TYPE = "quickCompareDirect"; /** * 队列名称 */ public static final String QUEUE_NAME = "quickCompareQueue"; /** * 队列标识 */ public static final String QUEUE_KEY = "quickCompareKey"; /** * 快速比对 str */ public static final String QUEUE_TYPE_QUICK_STR = QUEUE_TYPE + "QueueStr"; public static final String QUEUE_NAME_QUICK_STR = QUEUE_NAME + "Str"; public static final String QUEUE_KEY_QUICK_STR_COMPARE = QUEUE_NAME + "StrCompare"; /** * 快速比对 ystr */ public static final String QUEUE_TYPE_QUICK_YSTR = QUEUE_TYPE + "QueueYstr"; public static final String QUEUE_NAME_QUICK_YSTR = QUEUE_NAME + "Ystr"; public static final String QUEUE_KEY_QUICK_YSTR_COMPARE = QUEUE_NAME + "YstrCompare"; /** * 快速比对 mix */ public static final String QUEUE_TYPE_QUICK_MIX = QUEUE_TYPE + "QueueMix"; public static final String QUEUE_NAME_QUICK_MIX = QUEUE_NAME + "Mix"; public static final String QUEUE_KEY_QUICK_MIX_COMPARE = QUEUE_NAME + "MixCompare"; /** * 快速比对 relative three conjoined */ public static final String QUEUE_TYPE_QUICK_RELATIVE_THREE_CONJOINED = QUEUE_TYPE + "QueueThreeConjoined"; public static final String QUEUE_NAME_QUICK_RELATIVE_THREE_CONJOINED = QUEUE_NAME + "RelativeThreeConjoined"; public static final String QUEUE_KEY_QUICK_RELATIVE_THREE_CONJOINED_COMPARE = QUEUE_NAME + "ThreeConjoinedCompare"; /** * 快速比对 relative single conjoined */ public static final String QUEUE_TYPE_QUICK_RELATIVE_SINGLE_CONJOINED = QUEUE_TYPE + "QueueSingleConjoined"; public static final String QUEUE_NAME_QUICK_RELATIVE_SINGLE_CONJOINED = QUEUE_NAME + "RelativeSingleConjoined"; public static final String QUEUE_KEY_QUICK_RELATIVE_SINGLE_CONJOINED_COMPARE = QUEUE_NAME + "SingleConjoinedCompare"; /** * Constructor */ private QuickCompareConstants() { super(); } }
30.507246
118
0.767221
d6940bd3f68e8d24ef95b9c72da19ad9aba9a762
3,544
/** * Copyright (c) 2014, 2015 ControlsFX * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of ControlsFX, any associated website, nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CONTROLSFX BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.controlsfx.samples.propertysheet; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; public class Address { private String addressLine; private String suburb; private final StringProperty state = new SimpleStringProperty(); private final StringProperty postcode = new SimpleStringProperty(); public Address() { } /** * @return the addressLine */ public String getAddressLine() { return addressLine; } /** * @param addressLine the addressLine to set */ public void setAddressLine(String addressLine) { this.addressLine = addressLine; } /** * @return the suburb */ public String getSuburb() { return suburb; } /** * @param suburb the suburb to set */ public void setSuburb(String suburb) { this.suburb = suburb; } /** * @return the state */ public String getState() { return state.get(); } /** * @param state the state to set */ public void setState(String state) { this.state.set(state); } /** * @return Property that contains the state. */ public StringProperty stateProperty() { return state; } /** * @return the postcode */ public String getPostcode() { return postcode.get(); } /** * @param postcode the postcode to set */ public void setPostcode(String postcode) { this.postcode.set(postcode); } /** * @return Property that contains the postcode. */ public StringProperty postcodeProperty() { return postcode; } @Override public String toString() { return addressLine + " " + suburb + " " + state.get() + " " + postcode.get(); } }
30.033898
86
0.646727
47d5045fc71a5b3ad92c8faacaf354550b485ae7
1,615
package sg.ncl.service.experiment.validation; import io.jsonwebtoken.Claims; import lombok.extern.slf4j.Slf4j; import sg.ncl.common.authentication.Role; import sg.ncl.common.exception.base.ForbiddenException; import sg.ncl.common.jwt.JwtToken; import sg.ncl.service.realization.domain.Realization; import java.util.EnumSet; import java.util.List; import java.util.stream.Collectors; /** * @author Te Ye * @version 1.0 */ @Slf4j public class Validator { private Validator() { } public static void checkPermissions(final Realization realization, final boolean isOwner, final Claims claims) { if (!(claims.get(JwtToken.KEY) instanceof List<?>)) { log.warn("Bad claims type found: {}", claims); throw new ForbiddenException(); } log.info("Id of requester from web: {}", claims.getSubject()); log.info("Role of requester from web: {}", claims.get(JwtToken.KEY)); String contextUserId = claims.getSubject(); EnumSet<Role> roles = ((List<String>) claims.get(JwtToken.KEY)).stream().filter(Role::contains).map(Role::valueOf).collect(Collectors.toCollection(() -> EnumSet.noneOf(Role.class))); log.info("Context user id: {}, Context role: {}", contextUserId, roles); // FIXME too strict, we might want users on the same team to remove them also if (!roles.contains(Role.ADMIN) && !isOwner && !contextUserId.equals(realization.getUserId())) { log.warn("Access denied for delete experiment: /{}/ ", realization.getExperimentId()); throw new ForbiddenException(); } } }
35.888889
190
0.679257
975448796be790ca2edc6af270223f99f336798e
2,481
/*- * #%L * PhantomJS Maven Core * %% * Copyright (C) 2013 - 2017 Kyle Lieber * %% * 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. * #L% */ package com.github.klieber.phantomjs.archive; import com.github.klieber.phantomjs.archive.mapping.ArchiveFormat; public class TemplatedArchive extends AbstractArchive { private final ArchiveFormat archiveFormat; private final String version; public TemplatedArchive(ArchiveFormat archiveFormat, String version) { this.archiveFormat = archiveFormat; this.version = version; } @Override public String getBaseUrl() { return applyTemplate(this.archiveFormat.getBaseUrlTemplate()); } @Override public String getExtension() { return this.archiveFormat.getExtension(); } @Override public String getArchiveName() { return applyTemplate(this.archiveFormat.getFileTemplate()); } @Override public String getPathToExecutable() { return applyTemplate(this.archiveFormat.getExecutableTemplate()); } @Override public String getVersion() { return version; } @Override public String getClassifier() { return this.archiveFormat.getClassifier(); } private String applyTemplate(String template) { return template .replaceAll("\\{version}", this.version) .replaceAll("\\{classifier}", this.archiveFormat.getClassifier()) .replaceAll("\\{extension}", this.archiveFormat.getExtension()); } }
31.807692
80
0.731963
a46e64d903c1884e3a5788802ade9d524438bd57
2,034
package jetbrains.mps.lang.context.defs.behavior; /*Generated by MPS */ import jetbrains.mps.core.aspects.behaviour.BaseBehaviorAspectDescriptor; import jetbrains.mps.core.aspects.behaviour.api.BHDescriptor; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.NotNull; import org.jetbrains.mps.openapi.language.SAbstractConcept; import jetbrains.mps.lang.smodel.ConceptSwitchIndex; import jetbrains.mps.lang.smodel.ConceptSwitchIndexBuilder; import jetbrains.mps.smodel.adapter.ids.MetaIdFactory; public final class BehaviorAspectDescriptor extends BaseBehaviorAspectDescriptor { private final BHDescriptor myNativeTypedNodeDef__BehaviorDescriptor = new NativeTypedNodeDef__BehaviorDescriptor(); private final BHDescriptor myNativeTypedConceptDef__BehaviorDescriptor = new NativeTypedConceptDef__BehaviorDescriptor(); private final BHDescriptor myTypedNativeDef__BehaviorDescriptor = new TypedNativeDef__BehaviorDescriptor(); private final BHDescriptor myTypedDef__BehaviorDescriptor = new TypedDef__BehaviorDescriptor(); public BehaviorAspectDescriptor() { } @Nullable public BHDescriptor getDescriptor(@NotNull SAbstractConcept concept) { SAbstractConcept cncpt = concept; switch (conceptIndex.index(cncpt)) { case 0: return myNativeTypedConceptDef__BehaviorDescriptor; case 1: return myNativeTypedNodeDef__BehaviorDescriptor; case 2: return myTypedDef__BehaviorDescriptor; case 3: return myTypedNativeDef__BehaviorDescriptor; default: } return null; } private static final ConceptSwitchIndex conceptIndex = new ConceptSwitchIndexBuilder().put(MetaIdFactory.conceptId(0xea3159bff48e4720L, 0xbde286dba75f0d34L, 0x26084ede749bc5f2L), MetaIdFactory.conceptId(0xea3159bff48e4720L, 0xbde286dba75f0d34L, 0x46263286da99051L), MetaIdFactory.conceptId(0xea3159bff48e4720L, 0xbde286dba75f0d34L, 0x653030359368062cL), MetaIdFactory.conceptId(0xea3159bff48e4720L, 0xbde286dba75f0d34L, 0x4bf59690bc00f6b1L)).seal(); }
49.609756
451
0.826942
f898a9075314ef4b433eae8dd35cb1bd27290715
231
package ro.msg.internship.timesheet.repository; import org.springframework.data.jpa.repository.JpaRepository; import ro.msg.internship.timesheet.model.Psp; public interface PspRepository extends JpaRepository<Psp, Integer> { }
23.1
68
0.82684
d22e01685df008565b5bbd42135f9886eb0bc5c0
2,367
package fr.openwide.core.wicket.more.link.descriptor.builder.state.terminal; import org.apache.wicket.Page; import org.apache.wicket.model.IModel; import org.apache.wicket.request.resource.ResourceReference; /** * A state where the build can be terminated, returning the result of the build. */ public interface ILateTargetDefinitionTerminalState<TPageResult, TResourceResult, TImageResourceResult> { /** * @param pageClass The class of the page that the resulting link should point to. * @return The resulting link descriptor or link descriptor mapper for this builder, pointing to the given page. */ TPageResult page(Class<? extends Page> pageClass); /** * @param resourceReference The reference to the resource that the resulting link should point to. * @return The resulting link descriptor or link descriptor mapper for this builder, pointing to the given resource. */ TResourceResult resource(ResourceReference resourceReference); /** * @param resourceReference The reference to the resource that the resulting link should point to. * @return The resulting link descriptor or link descriptor mapper for this builder, pointing to the given resource. */ TImageResourceResult imageResource(ResourceReference resourceReference); /** * @param pageClassModel A model for the class of the page that the resulting link should point to. * @return The resulting link descriptor or link descriptor mapper for this builder, pointing to whatever page * is returned by the given model. */ TPageResult page(IModel<? extends Class<? extends Page>> pageClassModel); /** * @param resourceReferenceModel A model for the reference to the resource that the resulting link should point to. * @return The resulting link descriptor or link descriptor mapper for this builder, pointing to whatever resource * reference is returned by the given model. */ TResourceResult resource(IModel<? extends ResourceReference> resourceReferenceModel); /** * @param resourceReferenceModel A model for the reference to the resource that the resulting link should point to. * @return The resulting link descriptor or link descriptor mapper for this builder, pointing to whatever resource * reference is returned by the given model. */ TImageResourceResult imageResource(IModel<? extends ResourceReference> resourceReferenceModel); }
45.519231
117
0.782847
22c9a0ebed31119abf8297dd24f0cac712be78db
1,211
package com.nextbreakpoint.blueprint.designs.controllers; import com.nextbreakpoint.blueprint.common.core.Controller; import com.nextbreakpoint.blueprint.common.core.Json; import com.nextbreakpoint.blueprint.common.events.DesignDocumentUpdateCompleted; import com.nextbreakpoint.blueprint.designs.model.DesignChangedNotification; import io.vertx.rxjava.core.Vertx; import rx.Single; import java.util.Objects; public class DesignDocumentUpdateCompletedController implements Controller<DesignDocumentUpdateCompleted, Void> { private final Vertx vertx; private final String address; public DesignDocumentUpdateCompletedController(Vertx vertx, String address) { this.vertx = Objects.requireNonNull(vertx); this.address = Objects.requireNonNull(address); } @Override public Single<Void> onNext(DesignDocumentUpdateCompleted event) { DesignChangedNotification notification = DesignChangedNotification.builder() .withKey(event.getDesignId().toString()) .withRevision(event.getRevision()) .build(); vertx.eventBus().publish(address, Json.encodeValue(notification)); return Single.just(null); } }
36.69697
113
0.757225
ce401c97760d6ff5fde568f280748c1655925fc8
7,208
package org.jboss.resteasy.cdi; import org.jboss.resteasy.cdi.i18n.LogMessages; import org.jboss.resteasy.cdi.i18n.Messages; import org.jboss.resteasy.util.GetRestful; import javax.decorator.Decorator; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; import javax.enterprise.event.Observes; import javax.enterprise.inject.spi.AnnotatedType; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.BeforeBeanDiscovery; import javax.enterprise.inject.spi.Extension; import javax.enterprise.inject.spi.InjectionTarget; import javax.enterprise.inject.spi.ProcessAnnotatedType; import javax.enterprise.inject.spi.ProcessInjectionTarget; import javax.enterprise.inject.spi.ProcessSessionBean; import javax.enterprise.util.AnnotationLiteral; import javax.ws.rs.core.Application; import javax.ws.rs.ext.Provider; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; /** * This Extension handles default scopes for discovered JAX-RS components. It * also observes ProcessInjectionTarget event and wraps InjectionTargets * representing JAX-RS components within JaxrsInjectionTarget. Furthermore, it * builds the sessionBeanInterface map which maps Session Bean classes to a * local interface. This map is used in CdiInjectorFactory during lookup of * Sesion Bean JAX-RS components. * * @author Jozef Hartinger */ public class ResteasyCdiExtension implements Extension { private BeanManager beanManager; private static final String JAVAX_EJB_STATELESS = "javax.ejb.Stateless"; private static final String JAVAX_EJB_SINGLETON = "javax.ejb.Singleton"; // Scope literals public static final Annotation requestScopedLiteral = new AnnotationLiteral<RequestScoped>() { private static final long serialVersionUID = 3381824686081435817L; }; public static final Annotation applicationScopedLiteral = new AnnotationLiteral<ApplicationScoped>() { private static final long serialVersionUID = -8211157243671012820L; }; private Map<Class<?>, Type> sessionBeanInterface = new HashMap<Class<?>, Type>(); /** * Obtain BeanManager reference for future use. */ public void observeBeforeBeanDiscovery(@Observes BeforeBeanDiscovery event, BeanManager beanManager) { this.beanManager = beanManager; } /** * Set a default scope for each CDI bean which is a JAX-RS Resource, Provider * or Application subclass. */ public <T> void observeResources(@Observes ProcessAnnotatedType<T> event, BeanManager beanManager) { if (this.beanManager == null) { // this may happen if Solder Config receives BBD first this.beanManager = beanManager; } AnnotatedType<T> type = event.getAnnotatedType(); if (!type.getJavaClass().isInterface()) { for (Annotation annotation : type.getAnnotations()) { Class<?> annotationType = annotation.annotationType(); if (annotationType.getName().equals(JAVAX_EJB_STATELESS) || annotationType.getName().equals(JAVAX_EJB_SINGLETON)) { LogMessages.LOGGER.debug(Messages.MESSAGES.beanIsSLSBOrSingleton(type.getJavaClass())); return; // Do not modify scopes of SLSBs and Singletons } } if (type.isAnnotationPresent(Provider.class)) { LogMessages.LOGGER.debug(Messages.MESSAGES.discoveredCDIBeanJaxRsProvider(type.getJavaClass().getCanonicalName())); event.setAnnotatedType(wrapAnnotatedType(type, applicationScopedLiteral)); } else if (GetRestful.isRootResource(type.getJavaClass()) && !type.isAnnotationPresent(Decorator.class)) { LogMessages.LOGGER.debug(Messages.MESSAGES.discoveredCDIBeanJaxRsResource(type.getJavaClass().getCanonicalName())); event.setAnnotatedType(wrapAnnotatedType(type, requestScopedLiteral)); } else if (Application.class.isAssignableFrom(type.getJavaClass())) { LogMessages.LOGGER.debug(Messages.MESSAGES.discoveredCDIBeanApplication(type.getJavaClass().getCanonicalName())); event.setAnnotatedType(wrapAnnotatedType(type, applicationScopedLiteral)); } } } protected <T> AnnotatedType<T> wrapAnnotatedType(AnnotatedType<T> type, Annotation scope) { if (Utils.isScopeDefined(type.getJavaClass(), beanManager)) { LogMessages.LOGGER.debug(Messages.MESSAGES.beanHasScopeDefined(type.getJavaClass())); return type; // leave it as it is } else { LogMessages.LOGGER.debug(Messages.MESSAGES.beanDoesNotHaveScopeDefined(type.getJavaClass(), scope)); return new JaxrsAnnotatedType<T>(type, scope); } } /** * Wrap InjectionTarget of JAX-RS components within JaxrsInjectionTarget * which takes care of JAX-RS property injection. */ public <T> void observeInjectionTarget(@Observes ProcessInjectionTarget<T> event) { if (event.getAnnotatedType() == null) { // check for resin's bug http://bugs.caucho.com/view.php?id=3967 LogMessages.LOGGER.warn(Messages.MESSAGES.annotatedTypeNull()); return; } if (Utils.isJaxrsComponent(event.getAnnotatedType().getJavaClass())) { event.setInjectionTarget(wrapInjectionTarget(event)); } } protected <T> InjectionTarget<T> wrapInjectionTarget(ProcessInjectionTarget<T> event) { return new JaxrsInjectionTarget<T>(event.getInjectionTarget(), event.getAnnotatedType().getJavaClass()); } /** * Observes ProcessSessionBean events and creates a (Bean class -> Local * interface) map for Session beans with local interfaces. This map is * necessary since RESTEasy identifies a bean class as JAX-RS components * while CDI requires a local interface to be used for lookup. */ public <T> void observeSessionBeans(@Observes ProcessSessionBean<T> event) { Bean<Object> sessionBean = event.getBean(); if (Utils.isJaxrsComponent(sessionBean.getBeanClass())) { addSessionBeanInterface(sessionBean); } } private void addSessionBeanInterface(Bean<?> bean) { for (Type type : bean.getTypes()) { if ((type instanceof Class<?>) && ((Class<?>) type).isInterface()) { Class<?> clazz = (Class<?>) type; if (Utils.isJaxrsAnnotatedClass(clazz)) { sessionBeanInterface.put(bean.getBeanClass(), type); LogMessages.LOGGER.debug(Messages.MESSAGES.typeWillBeUsedForLookup(type, bean.getBeanClass())); return; } } } LogMessages.LOGGER.debug(Messages.MESSAGES.noLookupInterface(bean.getBeanClass())); } public Map<Class<?>, Type> getSessionBeanInterface() { return sessionBeanInterface; } }
39.604396
128
0.688957
5ba9a3e3f7a77d7fc0fc4c6dd1a0212e319725e2
1,159
package cn.smile.smilemall.ware.service; import cn.smile.common.utils.PageUtils; import cn.smile.smilemall.ware.entity.WareSkuEntity; import cn.smile.smilemall.ware.vo.SkuHasStockVo; import cn.smile.smilemall.ware.vo.WareSkuLockVo; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; import java.util.Map; /** * 商品库存 * * @author smile * @email 1367159064@qq.com * @date 2021-01-06 23:35:52 */ public interface WareSkuService extends IService<WareSkuEntity> { /** * <p>通用查询</p> * @author Smile * @date 2021/2/15/015 * @param params 1 * @return cn.smile.common.utils.PageUtils */ PageUtils queryPage(Map<String, Object> params); /** * <p>添加库存</p> * @author Smile * @date 2021/2/15/015 * @param skuId 1 * @param wareId 2 * @param skuNum 3 * @return boolean */ boolean addStock(Long skuId, Long wareId, Integer skuNum); /** * <p>判断是否有库存</p> * @author Smile * @date 2021/2/15/015 * @param ids 1 * @return List<SkuHasStockVo> */ List<SkuHasStockVo> getSkuHasStock(List<Long> ids); Boolean orderLockStock(WareSkuLockVo wareSkuLockVo); }
21.462963
65
0.679034
c4cb61af9098501950b29fa8b8565933f57a7cf9
9,503
package com.gmail.a93ak.andrei19.threads.MyAsync; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import android.app.Activity; import android.os.Handler; import android.os.Message; import android.os.Process; import android.support.annotation.NonNull; import static com.gmail.a93ak.andrei19.threads.MyAsync.MyAsyncTask.Status.RUNNING; public abstract class MyAsyncTask<Params, Progress, Result> { private Activity activity; // ссылка на наше activity private static final String LOG_TAG = "AsyncTask"; private static final int CORE_POOL_SIZE = 10; // пул потоков private static final int MAXIMUM_POOL_SIZE = 128; // максимальный пул потоков private static final int KEEP_ALIVE = 1; // время на сокращение очереди, после освобождения старым потоком // фабрика потоков создающая потоки с именами "AsynckTask #N" для THREAD_POOL_EXECUTOR private static final ThreadFactory sThreadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); // потокобезопасный Integer public Thread newThread(@NonNull Runnable r) { return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); } }; // попытка извлечь из пустой очереди заблокирует вызывающий поток до тех пор пока не появится элемент // попытка записать в полную очередь также заблокиру вызывающтй поток // очередь потоков для THREAD_POOL_EXECUTOR private static final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<>(10); // executor, который будет выполнять наш код private static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); private static final int MESSAGE_POST_RESULT = 1; private static final int MESSAGE_POST_PROGRESS = 2; // наш handler, который постит сообщения об окончании задачи, или промежуточном результате private static final InternalHandler sHandler = new InternalHandler(); // наш executor, только volatile и он static private static volatile Executor sDefaultExecutor = THREAD_POOL_EXECUTOR; // абстрактный callable c параметрами внутри, возвращать должен результат работы private final WorkerRunnable<Params, Result> mWorker; // отменяемая задача, на вход примет mWorker. резульат операции получется методом get private final FutureTask<Result> mFuture; // сначала статус "не начато" private volatile Status mStatus = Status.PENDING; public Status getmStatus() { return mStatus; } // флаг вызова задачи private final AtomicBoolean mTaskInvoked = new AtomicBoolean(); // статус задачи, каждое состяние может быть установлено однажды public enum Status { PENDING, //ещё не начато RUNNING, //выполняется FINISHED, //завершено } public MyAsyncTask() { // теперь наш worker будет выполнять то что в doInBackGround и давать результат mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { mTaskInvoked.set(true); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); return postResult(doInBackground(mParams)); } }; // а через него получим результат mFuture = new FutureTask<Result>(mWorker) { @Override protected void done() { try { final Result result = get(); // возможно это мы получаем результат если что-то пошло не так? postResultIfNotInvoked(result); } catch (InterruptedException e) { android.util.Log.w(LOG_TAG, e); } catch (ExecutionException e) { throw new RuntimeException("An error occured while executing", e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } catch (Throwable t) { throw new RuntimeException("An error occured while executing ", t); } } }; } // постим резульат если не вызван? private void postResultIfNotInvoked(Result result) { final boolean wasTaskInvoked = mTaskInvoked.get(); if (!wasTaskInvoked) { postResult(result); } } // метод, дающий нам результат asyncTask private Result postResult(Result result) { Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(this, result)); message.sendToTarget(); return result; } protected abstract Result doInBackground(Params... params); protected void onPreExecute() { } protected void onPostExecute(Result result) { } protected void onProgressUpdate(Progress... values) {} protected void onCancelled(Result result) { onCancelled(); } protected void onCancelled() {} public final boolean isCancelled() { return mFuture.isCancelled(); } public final boolean cancel(boolean mayInterruptIfRunning) { return mFuture.cancel(mayInterruptIfRunning); } public final Result get() throws InterruptedException, ExecutionException { return mFuture.get(); } // ожидать результа иначе таймаут public final Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return mFuture.get(timeout, unit); } public Activity getActivity() { return activity; } public void setActivity(Activity activity) { this.activity = activity; } // основной метод, через него выполняем задачу public final MyAsyncTask<Params, Progress, Result> execute(Params... params) { if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING: throw new IllegalStateException("Cannot execute task:" + " the task is already running."); case FINISHED: throw new IllegalStateException("Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)"); } } return this; } // этот метод может быть вызван из doInBackGround, каждый раз когда этот метод будет вызван // выполнится onPrgressUpdate с помощью Handlera (он отправит соответствующий msg) protected final void publishProgress(Progress... values) { if (!isCancelled()) { sHandler.obtainMessage(MESSAGE_POST_PROGRESS, new AsyncTaskResult<Progress>(this, values)).sendToTarget(); } } // если задача была прервана, то соответсвующий метод, иначе onPostExecute private void finish(Result result) { if (isCancelled()) { onCancelled(result); } else { onPostExecute(result); } mStatus = Status.FINISHED; } // handler для обработки и отправки сообщений, он вызывает finish при завершении, и он же вызывает // onProgressUpdate, в роли объекта передачи либо результат выполнения, либо промежуточные результаты private static class InternalHandler extends Handler { @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) @Override public void handleMessage(Message msg) { AsyncTaskResult result = (AsyncTaskResult) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: // если задача завершена // то вызываем метод финиш с результатом result.mTask.finish(result.mData[0]); break; case MESSAGE_POST_PROGRESS: // если задача выдаёт прогресс // то вызываем метод OnProgressUpdate Integer a = (Integer) result.mData[0]; result.mTask.onProgressUpdate(result.mData); break; } } } // наш Callable в котором надо реализовать call и который имеет ссылку на параметры, наш callable // будет работать с параметрами и давать результат и в нём выполняется mFutureTask private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> { Params[] mParams; } // класс результата выполнения задачи или промежуточного результата private static class AsyncTaskResult<Data> { final MyAsyncTask mTask; final Data[] mData; AsyncTaskResult(MyAsyncTask task, Data... data) { mTask = task; mData = data; } } }
36.833333
177
0.651163
cf95c008cbc42897ed3dca5e57d44fdf68dab1ee
335
package com.dn.andrewphan.bixolonprinter; /** * Package: com.dn.andrewphan.bixolonprinter * Created by andrew.phan * on 5/24/18 10:01 AM */ import com.bixolon.printer.BixolonPrinter; public class BixolonPrinterManager { public class OutValue{ public int intValue; } static BixolonPrinter mBixolonPrinter; }
18.611111
44
0.728358
1a4ee9047d8fdd562447c3248e12802b2afa996e
3,660
/* This file is part of the iText (R) project. Copyright (c) 1998-2020 iText Group NV Authors: iText Software. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation with the addition of the following permission added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program; if not, see http://www.gnu.org/licenses or write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA, 02110-1301 USA, or download the license from the following URL: http://itextpdf.com/terms-of-use/ The interactive user interfaces in modified source and object code versions of this program must display Appropriate Legal Notices, as required under Section 5 of the GNU Affero General Public License. In accordance with Section 7(b) of the GNU Affero General Public License, a covered work must retain the producer line in every PDF that is created or manipulated using iText. You can be released from the requirements of the license by purchasing a commercial license. Buying such a license is mandatory as soon as you develop commercial activities involving the iText software without disclosing the source code of your own applications. These activities include: offering paid services to customers as an ASP, serving PDFs on the fly in a web application, shipping iText with a closed source product. For more information, please contact iText Software Corp. at this address: sales@itextpdf.com */ package com.itextpdf.svg.renderers.path; import com.itextpdf.kernel.geom.Point; import com.itextpdf.kernel.pdf.canvas.PdfCanvas; /** * Interface for IPathShape, which draws the Path-data's d element instructions. */ public interface IPathShape { /** * Draws this instruction to a canvas object. * * @param canvas to which this instruction is drawn */ void draw(PdfCanvas canvas); /** * This method sets the coordinates for the path painting operator and does internal * preprocessing, if necessary * @param inputCoordinates an array containing point values for path coordinates * @param startPoint the ending point of the previous operator, or, in broader terms, * the point that the coordinates should be absolutized against, for relative operators */ void setCoordinates(String[] inputCoordinates, Point startPoint); /** * Gets the ending point on the canvas after the path shape has been drawn * via the {@link IPathShape#draw(PdfCanvas)} method, in SVG space coordinates. * * @return The {@link Point} representing the final point in the drawn path. * If the point does not exist or does not change {@code null} may be returned. */ Point getEndingPoint(); /** * Returns true when this shape is a relative operator. False if it is an absolute operator. * * @return true if relative, false if absolute */ boolean isRelative(); }
43.058824
109
0.725683
4d78e120199e12078c54219de468ecb78e7a8636
8,334
/* * Copyright (c) 2008-2019 Haulmont. * * 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.haulmont.addon.restapi.api.auth; import com.google.common.base.Preconditions; import com.haulmont.addon.restapi.api.config.RestApiConfig; import com.haulmont.cuba.core.global.ClientType; import com.haulmont.cuba.core.global.Configuration; import com.haulmont.cuba.core.global.GlobalConfig; import com.haulmont.cuba.core.sys.SecurityContext; import com.haulmont.cuba.security.auth.AuthenticationService; import com.haulmont.cuba.security.auth.TrustedClientCredentials; import com.haulmont.cuba.security.global.LoginException; import com.haulmont.addon.restapi.exception.RestApiAccessDeniedException; import com.haulmont.cuba.security.global.UserSession; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpHeaders; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.*; import org.springframework.security.oauth2.provider.token.AbstractTokenGranter; import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import java.util.*; import static com.haulmont.cuba.core.sys.AppContext.withSecurityContext; import static com.haulmont.addon.restapi.api.auth.CubaTokenEnhancer.EXTENDED_DETAILS_ATTRIBUTE_PREFIX; public class ExternalOAuthTokenGranter extends AbstractTokenGranter implements OAuthTokenIssuer { protected static final String USERNAME_DETAILS_ATTRIBUTE = "username"; protected static final String GRANT_TYPE_DETAILS_ATTRIBUTE = "grant_type"; protected static final String GRANT_TYPE = "external"; private static final Logger log = LoggerFactory.getLogger(ExternalOAuthTokenGranter.class); protected ClientDetailsService clientDetailsService; protected OAuth2RequestFactory requestFactory; @Inject protected Configuration configuration; @Inject protected AuthenticationService authenticationService; protected ExternalOAuthTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) { super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE); this.clientDetailsService = clientDetailsService; this.requestFactory = requestFactory; } @Override public OAuth2AccessTokenResult issueToken(OAuth2AccessTokenRequest tokenRequest) { RestApiConfig config = configuration.getConfig(RestApiConfig.class); String login = tokenRequest.getLogin(); Locale locale = tokenRequest.getLocale(); Map<String, String> parameters = new HashMap<>(); parameters.put("username", login); parameters.put("client_id", config.getRestClientId()); parameters.put("scope", "rest-api"); parameters.put("grant", GRANT_TYPE); UserSession session; try { TrustedClientCredentials credentials = new TrustedClientCredentials(login, config.getTrustedClientPassword(), locale); credentials.setClientType(ClientType.REST_API); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (attributes != null) { HttpServletRequest request = attributes.getRequest(); credentials.setIpAddress(request.getRemoteAddr()); credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT))); } else { credentials.setClientInfo(makeClientInfo("")); } credentials.setParams(tokenRequest.getLoginParams()); session = authenticationService.login(credentials).getSession(); } catch (RestApiAccessDeniedException ex) { log.info("User is not allowed to use the REST API {}", login); throw new BadCredentialsException("User is not allowed to use the REST API"); } catch (LoginException e) { log.info("Unable to issue token for REST API: {}", login); throw new BadCredentialsException("Bad credentials"); } parameters.put(CubaUserAuthenticationProvider.SESSION_ID_DETAILS_ATTRIBUTE, session.getId().toString()); for (Map.Entry<String, String> tokenParam : tokenRequest.getTokenDetails().entrySet()) { parameters.put(EXTENDED_DETAILS_ATTRIBUTE_PREFIX + tokenParam.getKey(), tokenParam.getValue()); } // issue token using obtained Session, it is required for DB operations inside of persistent token store OAuth2AccessToken accessToken = withSecurityContext(new SecurityContext(session), () -> { ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(config.getRestClientId()); TokenRequest tr = getRequestFactory().createTokenRequest(parameters, authenticatedClient); return grant(GRANT_TYPE, tr); }); return new OAuth2AccessTokenResult(session, accessToken); } @Override public OAuth2AccessTokenResult issueToken(String login, Locale locale, Map<String, Object> loginParams) { OAuth2AccessTokenRequest tokenRequest = new OAuth2AccessTokenRequest(); tokenRequest.setLogin(login); tokenRequest.setLocale(locale); tokenRequest.setLoginParams(loginParams); return issueToken(tokenRequest); } @Override protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { String externalPrincipal = tokenRequest.getRequestParameters().get("username"); String sessionId = tokenRequest.getRequestParameters().get(CubaUserAuthenticationProvider.SESSION_ID_DETAILS_ATTRIBUTE); Preconditions.checkState(externalPrincipal != null); Preconditions.checkState(sessionId != null); OAuth2Request storedOAuth2Request = requestFactory.createOAuth2Request(client, tokenRequest); ExternalAuthenticationToken authentication = new ExternalAuthenticationToken(externalPrincipal, getRoleUserAuthorities(tokenRequest)); @SuppressWarnings("unchecked") Map<String, String> details = (Map<String, String>) authentication.getDetails(); if (details == null) { details = new HashMap<>(); } details.put(CubaUserAuthenticationProvider.SESSION_ID_DETAILS_ATTRIBUTE, sessionId); details.put(USERNAME_DETAILS_ATTRIBUTE, externalPrincipal); details.put(GRANT_TYPE_DETAILS_ATTRIBUTE, GRANT_TYPE); authentication.setDetails(details); return new OAuth2Authentication(storedOAuth2Request, authentication); } protected List<GrantedAuthority> getRoleUserAuthorities(TokenRequest tokenRequest) { return new ArrayList<>(); } protected String makeClientInfo(String userAgent) { GlobalConfig globalConfig = configuration.getConfig(GlobalConfig.class); //noinspection UnnecessaryLocalVariable String serverInfo = String.format("REST API (%s:%s/%s) %s", globalConfig.getWebHostName(), globalConfig.getWebPort(), globalConfig.getWebContextName(), StringUtils.trimToEmpty(userAgent)); return serverInfo; } }
46.558659
130
0.736741
65ae144f6d529c38f04c15588504cee23d7a2d9e
6,765
package model.suffixtreebased.suffixtrees; import model.genomes.WordArray; /** * Represents a Generalized Trie - each edge has only 1 char * A string inserted to the Trie is the concatenation of labels from the root to a node with a key of that string */ public class Trie { /** * The root of the suffix tree */ public final PatternNode root; private boolean debug; private TreeType type; private int lastKey; public Trie(TreeType type){ root = new PatternNode(type); debug = false; this.type = type; lastKey = 0; } public PatternNode getRoot(){ return root; } public void put(WordArray str, String key, int UNK_CHAR_INDEX){ PatternNode lastNode = put(str, root, false, UNK_CHAR_INDEX); if (lastNode != null && type == TreeType.STATIC){ lastNode.setKey(key); } } public PatternNode putWithSuffix(WordArray str, int UNK_CHAR_INDEX){ return putWithSuffix(str, root, false, UNK_CHAR_INDEX); } public PatternNode addNode(int ch, PatternNode srcNode){ PatternNode target_node = srcNode.getTargetNode(ch); if (target_node == null){ target_node = new PatternNode(type); srcNode.addTargetNode(ch, target_node); } return target_node; } public PatternNode put(WordArray str, PatternNode srcNode, boolean includeUnknownChar, int UNK_CHAR_INDEX) { PatternNode currNode = null; if (str.getLength() > 0) { currNode = srcNode; for (int i = 0; i < str.getLength(); i++) { int strChar = str.getLetter(i); if (includeUnknownChar || (!includeUnknownChar && strChar != UNK_CHAR_INDEX)) { currNode = addNode(strChar, currNode); } } } return currNode; } public PatternNode putWithSuffix(WordArray str, PatternNode srcNode, boolean includeUnknownChar, int UNK_CHAR_INDEX){ PatternNode currNode = null; if (str.getLength() > 0) { currNode = srcNode; for (int i = 0; i < str.getLength(); i++) { int strChar = str.getLetter(i); if (includeUnknownChar || (!includeUnknownChar && strChar != UNK_CHAR_INDEX )) { currNode = addNode(strChar, currNode); if (currNode.getPatternKey() == null) { currNode.setKey(Integer.toString(++lastKey)); } } } } if (str.getLength() > 1) { //putWithSuffix the suffix of str str = new WordArray(str); str.addToStartIndex(1); putWithSuffix(str, root, includeUnknownChar, UNK_CHAR_INDEX); } return currNode; } /** * Adds str to the Trie under the given key. * * @param str the string added to the tree * @param key the key of that string * @throws IllegalStateException if an invalid index is passed as input */ public PatternNode put(WordArray str, String key, PatternNode extendedStrNode) throws IllegalStateException { if (str.getLength() > 0) { PatternNode currNode = root; int index = 0; //as long as the infix of str is in the tree, go on for (int i = 0; i < str.getLength(); i++) { int letter = str.getLetter(i); PatternNode target_node = currNode.getTargetNode(letter); //there is no outgoing edge with letter if (target_node == null) { break; } currNode = target_node; if (currNode.getPatternKey() == null){ currNode.setKey(Integer.toString(++lastKey)); } //advance the node if (extendedStrNode != null) { extendedStrNode = extendedStrNode.getTargetNode(letter); extendedStrNode.setSuffix(currNode); } index++; } //insert to the tree the rest of str for (int i = index; i < str.getLength(); i++) { int letter = str.getLetter(i); PatternNode nextNode = new PatternNode(type); currNode.addTargetNode(letter, nextNode); currNode = nextNode; if (currNode.getPatternKey() == null){ currNode.setKey(Integer.toString(++lastKey)); } if (extendedStrNode != null) { extendedStrNode = extendedStrNode.getTargetNode(letter); extendedStrNode.setSuffix(currNode); } } if (extendedStrNode == null && type == TreeType.STATIC) { currNode.setKey(key); } //continue recursively adding all suffixes //if (type.equals("enumeration")) { if (index != str.getLength()) { //putWithSuffix the suffix of str extendedStrNode = root.getTargetNode(str.getLetter(0)); extendedStrNode.setSuffix(root); str = new WordArray(str); str.addToStartIndex(1); put(str, key, extendedStrNode); } //} return currNode; } return null; } public Pair<PatternNode, Integer> search(WordArray str){ return search(str, root); } /** * Returns the deepest node of which the concatenation of labels to this node is an infix of str (str[0:index]) * @param str * @return */ public Pair<PatternNode, Integer> search(WordArray str, PatternNode src_node){ PatternNode curr_node = src_node; int index = 0; for (int i = 0; i < str.getLength(); i++) { int str_char = str.getLetter(i); PatternNode target_node = curr_node.getTargetNode(str_char); if (target_node == null){ break; } curr_node = target_node; index++; } return new Pair<>(curr_node, index); } /** * A private class used to return a tuples of two elements */ public class Pair<A, B> { private final A first; private final B second; public Pair(A first, B second) { this.first = first; this.second = second; } public A getFirst() { return first; } public B getSecond() { return second; } } public TreeType getType(){ return type; } }
30.890411
121
0.539394
94fc515d3895cfe443401a1e9a41550efc889004
8,058
/* * Copyright 2016-2021 Micro Focus or one of 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 com.hpe.caf.worker.document.tasks; import com.hpe.caf.api.worker.TaskStatus; import com.hpe.caf.api.worker.WorkerResponse; import com.hpe.caf.api.worker.WorkerTaskData; import com.hpe.caf.worker.document.DocumentWorkerChange; import com.hpe.caf.worker.document.DocumentWorkerChangeLogEntry; import com.hpe.caf.worker.document.DocumentWorkerConstants; import com.hpe.caf.worker.document.DocumentWorkerDocumentTask; import com.hpe.caf.worker.document.DocumentWorkerScript; import com.hpe.caf.worker.document.changelog.ChangeLogFunctions; import com.hpe.caf.worker.document.changelog.MutableDocument; import com.hpe.caf.worker.document.config.DocumentWorkerConfiguration; import com.hpe.caf.worker.document.exceptions.InvalidChangeLogException; import com.hpe.caf.worker.document.exceptions.InvalidScriptException; import com.hpe.caf.worker.document.impl.ApplicationImpl; import com.hpe.caf.worker.document.impl.ScriptImpl; import com.hpe.caf.worker.document.output.ChangeLogBuilder; import com.hpe.caf.worker.document.util.DocumentFunctions; import com.hpe.caf.worker.document.util.ListFunctions; import com.hpe.caf.worker.document.util.MapFunctions; import com.hpe.caf.worker.document.views.ReadOnlyDocument; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import javax.annotation.Nonnull; public final class DocumentTask extends AbstractTask { private final DocumentWorkerDocumentTask documentTask; @Nonnull public static DocumentTask create( final ApplicationImpl application, final WorkerTaskData workerTask, final DocumentWorkerDocumentTask documentTask ) throws InvalidChangeLogException, InvalidScriptException { Objects.requireNonNull(documentTask); return new DocumentTask(application, workerTask, documentTask); } private DocumentTask( final ApplicationImpl application, final WorkerTaskData workerTask, final DocumentWorkerDocumentTask documentTask ) throws InvalidChangeLogException, InvalidScriptException { super(application, workerTask, createEffectiveDocument(documentTask), documentTask.customData, documentTask.scripts); this.documentTask = documentTask; } @Nonnull private static ReadOnlyDocument createEffectiveDocument(final DocumentWorkerDocumentTask documentTask) throws InvalidChangeLogException { Objects.requireNonNull(documentTask); final ReadOnlyDocument baseDocument = ReadOnlyDocument.create(documentTask.document); final MutableDocument effectiveDocument = new MutableDocument(baseDocument); effectiveDocument.applyChangeLog(documentTask.changeLog); return ReadOnlyDocument.create(effectiveDocument); } @Nonnull @Override protected WorkerResponse createWorkerResponseImpl() { // Build up the changes to add to the change log final ChangeLogBuilder changeLogBuilder = new ChangeLogBuilder(); document.recordChanges(changeLogBuilder); final List<DocumentWorkerChange> changes = changeLogBuilder.getChanges(); // Check if any of the changes include any new failures final boolean hasFailures = ChangeLogFunctions.hasFailures(changes); // Select the output queue final String outputQueue = response.getOutputQueue(hasFailures); // If there have been failures, then check if the framework is configured to return a RESULT_EXCEPTION rather than simply adding // them to the change log if (hasFailures && application.getConfiguration().getEnableExceptionOnFailure()) { final String failures = DocumentFunctions.documentNodes(document) .flatMap(d -> d.getFailures().stream()) .map(f -> f.getFailureId() + ": " + f.getFailureMessage()) .collect(Collectors.joining("\n")); return new WorkerResponse(outputQueue, TaskStatus.RESULT_EXCEPTION, failures.getBytes(StandardCharsets.UTF_8), "DocumentWorkerException", 1, null); } // Create a new change log entry final DocumentWorkerChangeLogEntry changeLogEntry = new DocumentWorkerChangeLogEntry(); changeLogEntry.name = getChangeLogEntryName(); changeLogEntry.changes = changes.isEmpty() ? null : changes; // Put together the complete change log final ArrayList<DocumentWorkerChangeLogEntry> changeLog = ListFunctions.copy(documentTask.changeLog, 1); changeLog.add(changeLogEntry); // Get the installed scripts to include them in the response final List<DocumentWorkerScript> installedScripts = scripts.streamImpls() .filter(ScriptImpl::shouldIncludeInResponse) .map(ScriptImpl::toDocumentWorkerScript) .collect(Collectors.toList()); // Construct the DocumentWorkerDocumentTask object final DocumentWorkerDocumentTask documentWorkerResult = new DocumentWorkerDocumentTask(); documentWorkerResult.document = documentTask.document; documentWorkerResult.changeLog = changeLog; documentWorkerResult.customData = MapFunctions.emptyToNull(response.getCustomData().asMap()); documentWorkerResult.scripts = ListFunctions.emptyToNull(installedScripts); // Serialise the result object final byte[] data = application.serialiseResult(documentWorkerResult); // If the response message includes any scripts then it is in the v2 message format // If any of the scripts have an engine specified then it is in the v3 message format final int resultMessageVersion; if (documentWorkerResult.scripts == null) { resultMessageVersion = 1; } else if (documentWorkerResult.scripts.stream().map(script -> script.engine).allMatch(Objects::isNull)) { resultMessageVersion = 2; } else { resultMessageVersion = 3; } // Create the WorkerResponse object return new WorkerResponse(outputQueue, TaskStatus.RESULT_SUCCESS, data, DocumentWorkerConstants.DOCUMENT_TASK_NAME, resultMessageVersion, null); } @Nonnull @Override protected WorkerResponse handleGeneralFailureImpl(final Throwable failure) { document.getFailures().add(failure.getClass().getName(), failure.getLocalizedMessage(), failure); // Create a RESULT_SUCCESS for the document // (RESULT_SUCCESS is used even if there are failures, as the failures are successfully returned) return this.createWorkerResponse(); } @Nonnull private String getChangeLogEntryName() { final DocumentWorkerConfiguration config = application.getConfiguration(); final String changeLogEntryName = config.getWorkerName() + ":" + config.getWorkerVersion(); return changeLogEntryName; } }
42.410526
136
0.696327
407f2cfccc82f20a46277815bc5dbc27df3fc848
7,017
package com.cognizant.databaseActivity; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Scanner; public class EmployeeDAOImp1 implements EmployeeDAO { Scanner sc = new Scanner(System.in); Connection conn = getConnection(); PreparedStatement ps1 = null; PreparedStatement ps2 = null; PreparedStatement ps3 = null; PreparedStatement ps4 = null; @Override public boolean saveEmployee(Employee employee) { List<Employee> employees = new ArrayList<Employee>(); String insert_query = "insert into employee values(?,?,?,?,?,?,?)"; try { ps1 = conn.prepareStatement(insert_query); ps1.setInt(1, employee.getId()); ps1.setString(2, employee.getName()); ps1.setString(3, employee.getAddress()); ps1.setString(4, employee.getDesignation()); ps1.setInt(5, employee.getAge()); ps1.setDouble(6, employee.getSalary()); ps1.setInt(7, employee.getPhone()); int insert_result = ps1.executeUpdate(); if (insert_result > 0) { System.out.println("Data inserted succesfully"); } else { System.out.println("Something went wrong in insertion"); } } catch (SQLException e) { e.printStackTrace(); } return false; } @Override public boolean updateEmployee(int emp_id) { Employee em = new Employee(); List<Employee> employees = new ArrayList<Employee>(); String update_name = "update employee set name = ? where id = ?"; String update_city = "update employee set address = ? where id = ?"; String update_age = "update employee set ge = ? where id = ?"; String update_phone = "update employee set phone = ? where id = ?"; try { ps1 = conn.prepareStatement(update_name); ps2 = conn.prepareStatement(update_city); ps3 = conn.prepareStatement(update_age); ps4 = conn.prepareStatement(update_phone); System.out.println("\nDo you want to update name ? press 1 for yes/ press 2 for no : "); int choice1 = sc.nextInt(); sc.nextLine(); if (choice1 == 1) { System.out.println("\nEnter new name : "); String new_name = sc.nextLine(); ps1.setString(1, new_name); ps1.setInt(2, emp_id); int update_result = ps1.executeUpdate(); if (update_result > 0) { System.out.println("Name updated succesfully"); } else { System.out.println("Something went wrong in name updation"); } // em.setName(new_name); // System.out.println("\nName updated succesfully..."); } System.out.println("\nDo you want to update city ? press 1 for yes/ press 2 for no : "); int choice2 = sc.nextInt(); sc.nextLine(); if (choice2 == 1) { System.out.println("\nEnter new city : "); String new_city = sc.next(); ps2.setString(1, new_city); ps2.setInt(2, emp_id); int update_result = ps2.executeUpdate(); if (update_result > 0) { System.out.println("City updated succesfully"); } else { System.out.println("Something went wrong in city updation"); } // System.out.println("\nCity updated succesfully..."); } System.out.println("\nDo you want to update age ? press 1 for yes/ press 2 for no : "); int choice3 = sc.nextInt(); sc.nextLine(); if (choice3 == 1) { System.out.println("\nEnter new age : "); int new_age = sc.nextInt(); ps3.setInt(1, new_age); ps3.setInt(2, emp_id); int update_result = ps1.executeUpdate(); if (update_result > 0) { System.out.println("Age updated succesfully"); } else { System.out.println("Something went wrong in age updation"); } // System.out.println("\nAge updated succesfully..."); } System.out.println("\nDo you want to update mobile number ? press 1 for yes/ press 2 for no : "); int choice4 = sc.nextInt(); sc.nextLine(); if (choice4 == 1) { System.out.println("\nEnter new city : "); int new_number = sc.nextInt(); ps4.setInt(1, new_number); ps4.setInt(2, emp_id); int update_result = ps1.executeUpdate(); if (update_result > 0) { System.out.println("Phone Number updated succesfully"); } else { System.out.println("Something went wrong in number updation"); } // System.out.println("\nMobile number updated succesfully..."); } } catch (SQLException e) { e.printStackTrace(); } return false; } @Override public boolean deleteEmployee(int emp_id2) { List<Employee> employees = new ArrayList<Employee>(); String delete_query = "delete from employee where id = ?"; try { ps1 = conn.prepareStatement(delete_query); ps1.setInt(1, emp_id2); int delete_result = ps1.executeUpdate(); if (delete_result > 0) { System.out.println("Data deleted succesfully"); } else { System.out.println("Something went wrong in deletion"); } } catch (SQLException e) { e.printStackTrace(); } return false; } @Override public Employee getEmployeeById(int id) { String select_query = "select * from employee where id = ?"; try { ps1 = conn.prepareStatement(select_query); ps1.setInt(1, id); ResultSet rs = ps1.executeQuery(); Employee emp = null; while (rs.next()) { emp = new Employee(); emp.setId(rs.getInt("id")); emp.setName(rs.getString("name")); emp.setAddress(rs.getString("address")); emp.setDesignation(rs.getString("designation")); emp.setAge(rs.getInt("age")); emp.setSalary(rs.getInt("salary")); emp.setPhone(rs.getInt("phone")); } return emp; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override public List<Employee> getAllEmployees() { List<Employee> employees = new ArrayList<Employee>(); String select_query = "select * from employee"; try { ps1 = conn.prepareStatement(select_query); ResultSet rs = ps1.executeQuery(); while (rs.next()) { Employee emp = new Employee(); emp.setId(rs.getInt("id")); emp.setName(rs.getString("name")); emp.setAddress(rs.getString("address")); emp.setDesignation(rs.getString("designation")); emp.setAge(rs.getInt("age")); emp.setSalary(rs.getInt("salary")); emp.setPhone(rs.getInt("phone")); employees.add(emp); } return employees; } catch (SQLException e) { e.printStackTrace(); } return null; } private Connection getConnection() { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/ctspune"; conn = DriverManager.getConnection(url, "root", "root"); return conn; } catch (Exception e) { return null; } } }
32.943662
101
0.647998
a172d6dd0e6bed9d9b67e51e7bdfe45863b22f4d
789
package ru.job4j; import net.jcip.annotations.ThreadSafe; import java.util.concurrent.atomic.AtomicReference; /** * The {@code CASCount} is atomic non-blocking counter. * * @author Merkurev Sergei (merkurevsergei@yandex.ru) * @version 0.1 * @since 0.1 */ @ThreadSafe public class CASCount { private final AtomicReference<Integer> count; public CASCount() { count = new AtomicReference<>(); count.set(0); } /** * increment count. */ public void increment() { while (true) { int value = count.get(); if (count.compareAndSet(value, value + 1)) { break; } } } /** * @return count value. */ public int get() { return count.get(); } }
18.785714
56
0.560203
f9f22258716b8927deec6340321ced2f7bad87e0
3,345
/* * Copyright (c) 2013 Yolodata, LLC, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yolodata.tbana.cascading.splunk; import cascading.flow.FlowProcess; import cascading.tap.Tap; import cascading.tap.hadoop.io.HadoopTupleEntrySchemeIterator; import cascading.tuple.TupleEntryCollector; import cascading.tuple.TupleEntryIterator; import com.yolodata.tbana.hadoop.mapred.splunk.SplunkConf; import org.apache.commons.lang.NotImplementedException; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.RecordReader; import java.io.IOException; import java.util.Properties; import java.util.UUID; public class SplunkTap extends Tap<JobConf, RecordReader, OutputCollector> { private final String id = UUID.randomUUID().toString(); private final Properties splunkLogin; private String confKey; public SplunkTap(Properties splunkLogin, SplunkScheme inputScheme) { super(inputScheme); this.splunkLogin = splunkLogin; } @Override public String getIdentifier() { return id; } @Override public void sourceConfInit(FlowProcess<JobConf> process, JobConf conf) { setConfKey(conf, SplunkConf.SPLUNK_HOST); setConfKey(conf, SplunkConf.SPLUNK_USERNAME); setConfKey(conf, SplunkConf.SPLUNK_PASSWORD); setConfKey(conf, SplunkConf.SPLUNK_PORT); SplunkConf splunkConf = new SplunkConf(conf); splunkConf.validateLoginConfiguration(); super.sourceConfInit(process, conf); } @Override public TupleEntryIterator openForRead(FlowProcess<JobConf> flowProcess, RecordReader recordReader) throws IOException { return new HadoopTupleEntrySchemeIterator( flowProcess, this, recordReader ); } @Override public TupleEntryCollector openForWrite(FlowProcess<JobConf> flowProcess, OutputCollector outputCollector) throws IOException { throw new NotImplementedException("Write to Splunk not implemented"); } @Override public boolean createResource(JobConf conf) throws IOException { // Assume Splunk resource exists. return true; } @Override public boolean deleteResource(JobConf conf) throws IOException { // Delete nothing. return true; } @Override public boolean resourceExists(JobConf conf) throws IOException { return true; } @Override public long getModifiedTime(JobConf conf) throws IOException { // TODO: Not sure what to return here, last modified event? return System.currentTimeMillis(); } public void setConfKey(JobConf conf, String key) { String value = splunkLogin.getProperty(key, null); if(value != null) conf.set(key, value); } }
32.794118
131
0.727952
cfe12eea3f5206de6d74a26960465759f999ccf6
261
package net.datafaker.service; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class FakerIDNTest { @Test void toASCIINoError() { assertThat(FakerIDN.toASCII("hello")).isEqualTo("hello"); } }
18.642857
65
0.712644
dcca8ae18eda02ad3fee1ed56589fccb33503cc1
1,162
import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import javax.imageio.ImageIO; public class BmpToFile { public static void main(String[] args) { BufferedImage img = null; try { img = ImageIO.read(new File("src/resources/yoda-80.bmp")); int w = img.getWidth(); int h = img.getHeight(); int[][] arr = new int[w][h]; Raster raster = img.getData(); PrintWriter writer = new PrintWriter("src/resources/yoda-80.txt", "UTF-8"); if (w <= h) { writer.println(w); } else { writer.println(h); } String s = ""; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { arr[x][y] = raster.getSample(x, y, 0); if (arr[x][y] == 0) { // open, write the coordinates to file writer.println((y + 1) + " " + (x + 1)); } s += arr[x][y]; } System.out.println(s); s = ""; } writer.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } }
23.714286
81
0.517212
6eda24f6d53c9a8cc9247e775f1c750251df60b0
790
package de.dseelp.database.api.storage; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; /** * @author DSeeLP * @since 0.1-ALPHA */ @AllArgsConstructor @NoArgsConstructor public class StringStorage implements StorageObject { private String s; @Override public Object get() { return s; } @Override public void set(Object s) { this.s = (String) s; } @Override public void load(String var1) { this.s = var1; } @Override public boolean compare(StorageObject storageObject) { if (storageObject instanceof StringStorage) { return get().equals(storageObject.get()); } return false; } @Override public String getAsString() { return s; } }
18.809524
57
0.626582
81779d1bd82076a6362eaff4b381a23a62ed4f60
5,501
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cdancy.etcd.rest.features; import javax.inject.Named; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.jclouds.rest.annotations.Fallback; import org.jclouds.rest.annotations.FormParams; import org.jclouds.rest.annotations.QueryParams; import org.jclouds.rest.annotations.RequestFilters; import com.cdancy.etcd.rest.domain.keys.Key; import com.cdancy.etcd.rest.fallbacks.EtcdFallbacks.KeyOnAlreadyExists; import com.cdancy.etcd.rest.fallbacks.EtcdFallbacks.KeyOnCompareFailed; import com.cdancy.etcd.rest.fallbacks.EtcdFallbacks.KeyOnNonFound; import com.cdancy.etcd.rest.filters.EtcdAuthentication; @RequestFilters(EtcdAuthentication.class) @Consumes(MediaType.APPLICATION_JSON) @Path("/{jclouds.api-version}/keys") public interface KeysApi { @Named("keys:create") @PUT @Path("/{key}") Key createKey(@PathParam("key") String key, @FormParam("value") String value); @Named("keys:create-with-options") @PUT @Path("/{key}") Key createKey(@PathParam("key") String key, @FormParam("value") String value, @FormParam("ttl") int seconds); @Named("keys:create-in-order") @POST @Path("/{key}") Key createInOrderKey(@PathParam("key") String key, @FormParam("value") String value); @Named("keys:create-in-order-with-options") @POST @Path("/{key}") Key createInOrderKey(@PathParam("key") String key, @FormParam("value") String value, @FormParam("ttl") int seconds); @Named("keys:list-in-order") @GET @QueryParams(keys = { "recursive", "sorted" }, values = { "true", "true" }) @Path("/{key}") @Fallback(KeyOnNonFound.class) Key listInOrderKey(@PathParam("key") String key); @Named("keys:get") @GET @Path("/{key}") @Fallback(KeyOnNonFound.class) Key getKey(@PathParam("key") String key); @Named("keys:delete") @DELETE @Path("/{key}") @Fallback(KeyOnNonFound.class) Key deleteKey(@PathParam("key") String key); @Named("keys:wait") @GET @Path("/{key}") @QueryParams(keys = { "wait" }, values = { "true" }) @Fallback(KeyOnNonFound.class) Key waitKey(@PathParam("key") String key); @Named("keys:wait-with-options") @GET @Path("/{key}") @QueryParams(keys = { "wait" }, values = { "true" }) @Fallback(KeyOnNonFound.class) Key waitKey(@PathParam("key") String key, @QueryParam("waitIndex") int waitIndex); @Named("keys:compare-and-delete-value") @DELETE @Path("/{key}") @Fallback(KeyOnCompareFailed.class) Key compareAndDeleteKey(@PathParam("key") String key, @QueryParam("prevValue") String prevValue); @Named("keys:compare-and-delete-index") @DELETE @Path("/{key}") @Fallback(KeyOnCompareFailed.class) Key compareAndDeleteKey(@PathParam("key") String key, @QueryParam("prevIndex") int prevIndex); @Named("keys:compare-and-swap-value") @PUT @Path("/{key}") @Fallback(KeyOnCompareFailed.class) Key compareAndSwapKeyValue(@PathParam("key") String key, @QueryParam("prevValue") String prevValue, @FormParam("value") String value); @Named("keys:compare-and-swap-index") @PUT @Path("/{key}") @Fallback(KeyOnCompareFailed.class) Key compareAndSwapKeyIndex(@PathParam("key") String key, @QueryParam("prevIndex") int prevIndex, @FormParam("value") String value); @Named("keys:compare-and-swap-exist") @PUT @Path("/{key}") @Fallback(KeyOnCompareFailed.class) Key compareAndSwapKeyExist(@PathParam("key") String key, @QueryParam("prevExist") boolean prevExist, @FormParam("value") String value); @Named("keys:dir-create") @PUT @FormParams(keys = { "dir" }, values = { "true" }) @Path("/{dir}") @Fallback(KeyOnAlreadyExists.class) Key createDir(@PathParam("dir") String dir); @Named("keys:dir-create-with-options") @PUT @FormParams(keys = { "dir" }, values = { "true" }) @Path("/{dir}") @Fallback(KeyOnAlreadyExists.class) Key createDir(@PathParam("dir") String dir, @FormParam("ttl") int seconds); @Named("keys:dir-list") @GET @Path("/{dir}/") @Fallback(KeyOnNonFound.class) Key listDir(@PathParam("dir") String dir, @QueryParam("recursive") boolean recursive); @Named("keys:dir-delete") @DELETE @Path("/{dir}/") @QueryParams(keys = { "recursive" }, values = { "true" }) @Fallback(KeyOnNonFound.class) Key deleteDir(@PathParam("dir") String dir); }
34.167702
120
0.682603
1f678bc020e74aee8ae7f3c9bd3cde7244f2bfc6
2,734
package seedu.address.storage; import static seedu.address.commons.util.CollectionUtil.requireAllNonNull; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.file.Path; import java.util.Map; import java.util.Optional; import java.util.logging.Logger; import seedu.address.commons.core.LogsCenter; import seedu.address.commons.util.FileUtil; import seedu.address.model.AddressBook; import seedu.address.model.ReadOnlyAddressBook; public class SerializableAddressBookStorage implements AddressBookStorage { private static final Logger logger = LogsCenter.getLogger(SerializableAddressBookStorage.class); private Path filePath; public SerializableAddressBookStorage(Path filePath) { this.filePath = filePath; } @Override public Path getAddressBookFilePath() { return filePath; } @Override public Optional<ReadOnlyAddressBook> readAddressBook() { return readAddressBook(filePath); } @Override public Optional<ReadOnlyAddressBook> readAddressBook(Path filePath) { requireAllNonNull(filePath); try { ObjectInputStream objectInputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(filePath.toString()))); Map<String, Object> storageMap = (Map<String, Object>) objectInputStream.readObject(); objectInputStream.close(); return Optional.of(new AddressBook(storageMap)); } catch (Exception e) { return Optional.empty(); } } @Override public void saveAddressBook(ReadOnlyAddressBook addressBook) throws IOException { saveAddressBook(addressBook, filePath); } @Override public void saveAddressBook(ReadOnlyAddressBook addressBook, Path filePath) throws IOException { requireAllNonNull(addressBook, filePath); FileUtil.createIfMissing(filePath); File file = new File(filePath.toString()); File parentFile = file.getParentFile(); if (parentFile != null) { //noinspection ResultOfMethodCallIgnored file.getParentFile().mkdirs(); } //noinspection ResultOfMethodCallIgnored file.createNewFile(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file, false))); objectOutputStream.writeObject(addressBook.generateStorageMap()); objectOutputStream.flush(); objectOutputStream.close(); } }
33.753086
105
0.721287
3dc45e5c5078aa4bb189562a09b65a76a532c7fe
4,257
/* * Copyright 2017 Tran Le Duy * * 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.duy.calculator.userinterface; import android.content.Context; import android.content.SharedPreferences; import android.content.res.AssetManager; import android.graphics.Typeface; import android.preference.PreferenceManager; import com.duy.calculator.R; /** * Font Manager * Created by Duy on 23-Jan-17. */ public final class FontManager { /** * it can be null object, make private */ private static Typeface typeface = null; public static Typeface loadTypefaceFromAsset(Context context) { if (typeface != null) return typeface; String path = "fonts/"; SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); String font = sharedPreferences.getString(context.getString(R.string.key_pref_font), context.getString(R.string.font_light)); if (font.equals(context.getString(R.string.font_black))) { path = path + "Roboto-Black.ttf"; } else if (font.equals(context.getString(R.string.font_light))) { path = path + "Roboto-Light.ttf"; } else if (font.equals(context.getString(R.string.font_bold))) { path = path + "Roboto-Bold.ttf"; } else if (font.equals(context.getString(R.string.font_italic))) { path = path + "Roboto-Italic.ttf"; } else if (font.equals(context.getString(R.string.font_thin))) { path = path + "Roboto-Thin.ttf"; } AssetManager assetManager = context.getAssets(); typeface = Typeface.createFromAsset(assetManager, path); return typeface; } public String getFont(Context context) { String path = "fonts/"; SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); String font = sharedPreferences.getString(context.getString(R.string.key_pref_font), context.getString(R.string.font_light)); if (font.equals(context.getString(R.string.font_black))) { return path + "Roboto-Black.ttf"; } else if (font.equals(context.getString(R.string.font_light))) { return path + "Roboto-Light.ttf"; } else if (font.equals(context.getString(R.string.font_bold))) { return path + "Roboto-Bold.ttf"; } else if (font.equals(context.getString(R.string.font_italic))) { return path + "Roboto-Italic.ttf"; } else if (font.equals(context.getString(R.string.font_thin))) { return path + "Roboto-Thin.ttf"; } return path + "Roboto-Light.ttf"; } public Typeface getTypeFace(Context context) { String path = "fonts/"; SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); String font = sharedPreferences.getString(context.getString(R.string.key_pref_font), context.getString(R.string.font_light)); if (font.equals(context.getString(R.string.font_black))) { path = path + "Roboto-Black.ttf"; } else if (font.equals(context.getString(R.string.font_light))) { path = path + "Roboto-Light.ttf"; } else if (font.equals(context.getString(R.string.font_bold))) { path = path + "Roboto-Bold.ttf"; } else if (font.equals(context.getString(R.string.font_italic))) { path = path + "Roboto-Italic.ttf"; } else if (font.equals(context.getString(R.string.font_thin))) { path = path + "Roboto-Thin.ttf"; } AssetManager assetManager = context.getAssets(); return Typeface.createFromAsset(assetManager, path); } }
41.735294
101
0.662908
567ecebdcf455dc1143d7a94afb690eb1c7f0177
578
package realm.service; public enum RegisterExceptionEnum{ UNKOWN_ERROR(-1, "未知错误,注册失败"), SUCCESS(0, "注册成功"), Mail_Register_Exception(1, "mail注册失败"), Phone_Register_Exception(2, "phone注册失败"), VerificationCode_Expired(3,"验证码失效") ; private Integer code; private String msg; private RegisterExceptionEnum(Integer code,String msg) { this.msg = msg; this.code = code; } public String getMsg() { return msg; } public Integer getCode() { return code; } }
20.642857
61
0.588235
714361474742451e770700f91ebf88baf6caea3d
2,358
package com.mdimension.jchronic.repeaters; import java.util.Calendar; import com.mdimension.jchronic.tags.Pointer; import com.mdimension.jchronic.tags.Pointer.PointerType; import com.mdimension.jchronic.utils.Span; import com.mdimension.jchronic.utils.Time; public class RepeaterMinute extends RepeaterUnit { public static final int MINUTE_SECONDS = 60; private Calendar _currentMinuteStart; @Override protected Span _nextSpan(PointerType pointer) { if (_currentMinuteStart == null) { if (pointer == PointerType.FUTURE) { _currentMinuteStart = Time.cloneAndAdd(Time.ymdhm(getNow()), Calendar.MINUTE, 1); } else if (pointer == PointerType.PAST) { _currentMinuteStart = Time.cloneAndAdd(Time.ymdhm(getNow()), Calendar.MINUTE, -1); } else { throw new IllegalArgumentException("Unable to handle pointer " + pointer + "."); } } else { int direction = (pointer == Pointer.PointerType.FUTURE) ? 1 : -1; _currentMinuteStart.add(Calendar.MINUTE, direction); } return new Span(_currentMinuteStart, Calendar.SECOND, RepeaterMinute.MINUTE_SECONDS); } @Override protected Span _thisSpan(PointerType pointer) { Calendar minuteBegin; Calendar minuteEnd; if (pointer == Pointer.PointerType.FUTURE) { minuteBegin = getNow(); minuteEnd = Time.ymdhm(getNow()); } else if (pointer == Pointer.PointerType.PAST) { minuteBegin = Time.ymdhm(getNow()); minuteEnd = getNow(); } else if (pointer == Pointer.PointerType.NONE) { minuteBegin = Time.ymdhm(getNow()); minuteEnd = Time.cloneAndAdd(Time.ymdhm(getNow()), Calendar.SECOND, RepeaterMinute.MINUTE_SECONDS); } else { throw new IllegalArgumentException("Unable to handle pointer " + pointer + "."); } return new Span(minuteBegin, minuteEnd); } @Override public Span getOffset(Span span, int amount, Pointer.PointerType pointer) { int direction = (pointer == Pointer.PointerType.FUTURE) ? 1 : -1; // WARN: Does not use Calendar return span.add(direction * amount * RepeaterMinute.MINUTE_SECONDS); } @Override public int getWidth() { // WARN: Does not use Calendar return RepeaterMinute.MINUTE_SECONDS; } @Override public String toString() { return super.toString() + "-minute"; } }
31.026316
105
0.686175
3f534b332577e8e6a6448eb0ad644a427adc0f27
549
package com.ctsi.hook; import com.ctsi.hook.waiqin.WaiqinHook; import com.ctsi.hook.weixin.WxapkgHook; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; /** * Created by wanglin on 2018/5/14. */ public class XposedInit implements IXposedHookLoadPackage { @Override public void handleLoadPackage(LoadPackageParam loadPackageParam) throws Throwable { WaiqinHook.hook(loadPackageParam);//外勤助手 WxapkgHook.hook(loadPackageParam);//微信小程序 } }
24.954545
87
0.772313
30df93f92fdb744bcd68a77682dc7fbcd92f10fa
7,471
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.event.entity; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.event.Cancellable; import org.spongepowered.api.event.cause.entity.health.HealthModifier; import org.spongepowered.api.event.cause.entity.health.source.HealingSource; import org.spongepowered.api.event.impl.AbstractHealEntityEvent; import org.spongepowered.api.eventgencore.annotation.ImplementedBy; import org.spongepowered.api.eventgencore.annotation.PropertySettings; import org.spongepowered.api.util.Tuple; import java.util.List; import java.util.Map; import java.util.function.Function; /** * An event where an {@link Entity} is "healed". This can usually mean that * after a certain amount of "heal amount" the entity is destroyed. Similar to * the {@link DamageEntityEvent}, this event uses various modifiers */ @ImplementedBy(AbstractHealEntityEvent.class) public interface HealEntityEvent extends TargetEntityEvent, Cancellable { /** * Gets the original amount to "heal" the targeted {@link Entity}. * * @return The original heal amount */ double getOriginalHealAmount(); /** * Gets the original "final" amount of healing after all original * {@link HealthModifier}s are applied to {@link #getOriginalHealAmount()} ()}. * The "final" heal amount is considered the amount gained by the * {@link Entity}, if health is tracked. * * @return The final amount of healing to originally deal */ @PropertySettings(requiredParameter = false, generateMethods = false) double getOriginalFinalHealAmount(); /** * Gets an {@link Map} of all original {@link HealthModifier}s * and their associated "modified" heal amount. Note that ordering is not * retained. * * @return An immutable map of the original modified heal amounts */ @PropertySettings(requiredParameter = false, generateMethods = false) Map<HealthModifier, Double> getOriginalHealingAmounts(); /** * Gets the final heal amount that will be applied to the entity. The * final heal amount is the end result of the {@link #getBaseHealAmount()} * being applied in {@link Function#apply(Object)} available from all * the {@link Tuple}s of {@link HealthModifier} to {@link Function} in * {@link #getOriginalFunctions()}. * * @return The final heal amount to deal */ @PropertySettings(requiredParameter = false, generateMethods = false) double getFinalHealAmount(); /** * Gets the original healing amount for the provided * {@link HealthModifier}. If the provided {@link HealthModifier} was not * included in {@link #getOriginalHealingAmounts()}, an * {@link IllegalArgumentException} is thrown. * * @param healthModifier The original healing modifier * @return The original healing change */ double getOriginalHealingModifierAmount(HealthModifier healthModifier); /** * Gets the original {@link List} of {@link HealthModifier} to * {@link Function} that was originally passed into the event. * * @return The list of heal amount modifier functions */ List<Tuple<HealthModifier, Function<? super Double, Double>>> getOriginalFunctions(); /** * Gets the "base" healing amount to apply to the targeted {@link Entity}. * The "base" heal amount is the original value before passing along the chain * of {@link Function}s for all known {@link HealthModifier}s. * * @return The base heal amount */ @PropertySettings(requiredParameter = false, generateMethods = false) double getBaseHealAmount(); /** * Sets the "base" healing amount to apply to the targeted {@link Entity}. * The "base" heal amount is the original value passed along the chain of * {@link Function}s for all known {@link HealthModifier}s. * * @param healAmount The base heal amount */ void setBaseHealAmount(double healAmount); /** * Checks whether the provided {@link HealthModifier} is applicable to the * current available {@link HealthModifier}s. * * @param healthModifier The health modifier to check * @return True if the health modifier is relevant to this event */ boolean isModifierApplicable(HealthModifier healthModifier); /** * Gets the heal amount for the provided {@link HealthModifier}. Providing that * {@link #isModifierApplicable(HealthModifier)} returns <code>true</code>, * the cached "heal amount" for the {@link HealthModifier} is returned. * * @param healthModifier The heal amount modifier to get the heal amount for * @return The modifier */ double getHealAmount(HealthModifier healthModifier); /** * ns the provided {@link Function} to be used for the given * {@link HealthModifier}. If the {@link HealthModifier} is already * included in {@link #getModifiers()}, the {@link Function} replaces * the existing function. If there is no {@link Tuple} for the * {@link HealthModifier}, a new one is created and added to the end * of the list of {@link Function}s to be applied to the * {@link #getBaseHealAmount()}. * * <p>If needing to create a custom {@link HealthModifier} is required, * usage of the * {@link org.spongepowered.api.event.cause.entity.health.HealthModifier.Builder} * is recommended.</p> * * @param healthModifier The heal amount modifier * @param function The function to map to the modifier */ void setHealAmount(HealthModifier healthModifier, Function<? super Double, Double> function); /** * Gets a list of simple {@link Tuple}s of {@link HealthModifier} keyed to * their representative {@link Function}s. All {@link HealthModifier}s are * applicable to the entity based on the {@link HealingSource} and any * possible invulnerabilities due to the {@link HealingSource}. * * @return A list of heal amount modifiers to functions */ @PropertySettings(requiredParameter = false, generateMethods = false) List<Tuple<HealthModifier, Function<? super Double, Double>>> getModifiers(); }
42.448864
97
0.709142
583de5d8adf3da1cca0ca5d5aeb75aee3c6ea446
184
package mytest.lookup; /*** * * @author Jshu * @since 2021/3/10 21:13 */ public class Teacher extends User{ public void showMe(){ System.out.println("i am teacher"); } }
13.142857
39
0.630435
09998c16f15f4b00a56d9a905261976fa75ea6ff
6,197
/* * Decompiled with CFR 0_79. * * Could not load the following classes: * android.util.SparseArray */ package org.anddev.andengine.entity.layer.tiled.tmx; import android.util.SparseArray; import java.util.ArrayList; import org.anddev.andengine.entity.layer.tiled.tmx.TMXLayer; import org.anddev.andengine.entity.layer.tiled.tmx.TMXObjectGroup; import org.anddev.andengine.entity.layer.tiled.tmx.TMXProperties; import org.anddev.andengine.entity.layer.tiled.tmx.TMXTileProperty; import org.anddev.andengine.entity.layer.tiled.tmx.TMXTileSet; import org.anddev.andengine.entity.layer.tiled.tmx.TMXTiledMapProperty; import org.anddev.andengine.entity.layer.tiled.tmx.util.constants.TMXConstants; import org.anddev.andengine.opengl.buffer.BufferObject; import org.anddev.andengine.opengl.buffer.BufferObjectManager; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.vertex.RectangleVertexBuffer; import org.anddev.andengine.util.SAXUtils; import org.xml.sax.Attributes; public class TMXTiledMap implements TMXConstants { private final SparseArray<TMXProperties<TMXTileProperty>> mGlobalTileIDToTMXTilePropertiesCache = new SparseArray(); private final SparseArray<TextureRegion> mGlobalTileIDToTextureRegionCache = new SparseArray(); private final String mOrientation; private final RectangleVertexBuffer mSharedVertexBuffer; private final ArrayList<TMXLayer> mTMXLayers = new ArrayList<TMXLayer>(); private final ArrayList<TMXObjectGroup> mTMXObjectGroups = new ArrayList<TMXObjectGroup>(); private final ArrayList<TMXTileSet> mTMXTileSets = new ArrayList<TMXTileSet>(); private final TMXProperties<TMXTiledMapProperty> mTMXTiledMapProperties = new TMXProperties(); private final int mTileColumns; private final int mTileHeight; private final int mTileWidth; private final int mTilesRows; TMXTiledMap(Attributes attributes) { this.mOrientation = attributes.getValue("", "orientation"); if (!this.mOrientation.equals("orthogonal")) { throw new IllegalArgumentException("orientation: '" + this.mOrientation + "' is not supported."); } this.mTileColumns = SAXUtils.getIntAttributeOrThrow(attributes, "width"); this.mTilesRows = SAXUtils.getIntAttributeOrThrow(attributes, "height"); this.mTileWidth = SAXUtils.getIntAttributeOrThrow(attributes, "tilewidth"); this.mTileHeight = SAXUtils.getIntAttributeOrThrow(attributes, "tileheight"); this.mSharedVertexBuffer = new RectangleVertexBuffer(35044); BufferObjectManager.getActiveInstance().loadBufferObject(this.mSharedVertexBuffer); this.mSharedVertexBuffer.update(this.mTileWidth, this.mTileHeight); } void addTMXLayer(TMXLayer tMXLayer) { this.mTMXLayers.add(tMXLayer); } void addTMXObjectGroup(TMXObjectGroup tMXObjectGroup) { this.mTMXObjectGroups.add(tMXObjectGroup); } void addTMXTileSet(TMXTileSet tMXTileSet) { this.mTMXTileSets.add(tMXTileSet); } public void addTMXTiledMapProperty(TMXTiledMapProperty tMXTiledMapProperty) { this.mTMXTiledMapProperties.add((Object)tMXTiledMapProperty); } @Deprecated public final int getHeight() { return this.mTilesRows; } public final String getOrientation() { return this.mOrientation; } public RectangleVertexBuffer getSharedVertexBuffer() { return this.mSharedVertexBuffer; } public ArrayList<TMXLayer> getTMXLayers() { return this.mTMXLayers; } public ArrayList<TMXObjectGroup> getTMXObjectGroups() { return this.mTMXObjectGroups; } public TMXProperties<TMXTileProperty> getTMXTileProperties(int n) { TMXProperties tMXProperties = (TMXProperties)this.mGlobalTileIDToTMXTilePropertiesCache.get(n); if (tMXProperties != null) { return tMXProperties; } ArrayList<TMXTileSet> arrayList = this.mTMXTileSets; int n2 = -1 + arrayList.size(); do { TMXTileSet tMXTileSet; if (n2 < 0) { throw new IllegalArgumentException("No TMXTileProperties found for pGlobalTileID=" + n); } if (n >= (tMXTileSet = arrayList.get(n2)).getFirstGlobalTileID()) { return tMXTileSet.getTMXTilePropertiesFromGlobalTileID(n); } --n2; } while (true); } public TMXProperties<TMXTileProperty> getTMXTilePropertiesByGlobalTileID(int n) { return (TMXProperties)this.mGlobalTileIDToTMXTilePropertiesCache.get(n); } public ArrayList<TMXTileSet> getTMXTileSets() { return this.mTMXTileSets; } public TMXProperties<TMXTiledMapProperty> getTMXTiledMapProperties() { return this.mTMXTiledMapProperties; } public TextureRegion getTextureRegionFromGlobalTileID(int n) { SparseArray<TextureRegion> sparseArray = this.mGlobalTileIDToTextureRegionCache; TextureRegion textureRegion = (TextureRegion)sparseArray.get(n); if (textureRegion != null) { return textureRegion; } ArrayList<TMXTileSet> arrayList = this.mTMXTileSets; int n2 = -1 + arrayList.size(); do { TMXTileSet tMXTileSet; if (n2 < 0) { throw new IllegalArgumentException("No TextureRegion found for pGlobalTileID=" + n); } if (n >= (tMXTileSet = arrayList.get(n2)).getFirstGlobalTileID()) { TextureRegion textureRegion2 = tMXTileSet.getTextureRegionFromGlobalTileID(n); sparseArray.put(n, (Object)textureRegion2); return textureRegion2; } --n2; } while (true); } public final int getTileColumns() { return this.mTileColumns; } public final int getTileHeight() { return this.mTileHeight; } public final int getTileRows() { return this.mTilesRows; } public final int getTileWidth() { return this.mTileWidth; } @Deprecated public final int getWidth() { return this.mTileColumns; } }
37.331325
120
0.703082
2f6fe3e187e742478b0c2991642864dca934dc19
432
package net.mgsx.game.examples.platformer.tasks; import net.mgsx.game.examples.platformer.inputs.PlayerController; import net.mgsx.game.plugins.btree.annotations.TaskAlias; @TaskAlias("onGround") public class OnGroundCondition extends ConditionTask { @Override public boolean match() { PlayerController player = PlayerController.components.get(getEntity()); if(player == null) return false; return player.onGround; } }
24
73
0.789352