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
ea06bf27a5f9b2f59d60ff8016af73bf00fc7801
1,152
package ru.job4j.set; import ru.job4j.list.SimpleList; import java.util.*; /** * Class SimpleSet класс реализует множество на массиве * * @author Konstantin Inozemcev (9715791@gmail.com) * @version $Id$ * @since 0.1 */ public class SimpleSet<T> { /** * Ссылка на контейнер */ private SimpleList simpleList; /** * Конструктор - создание нового объекта */ public SimpleSet() { simpleList = new SimpleList(); } /** * Метод добавляет элемент в множество * @param e элемент */ public void add(T e) { if (!contains(e)) { simpleList.add(e); } } /** * Метод проверяет , содержит множество элемент e * @param e элемента * @return true если содержит, false нет. */ public boolean contains(T e) { return simpleList.contains(e); } /** * Метод возвращает итеретор * @return итератор . */ public Iterator<T> iterator() { return simpleList.iterator(); } public static void main(String[] args) { SimpleSet set = new SimpleSet(); set.add(1); } }
18.580645
57
0.568576
77c0abd8f29449c5988155fbbc9cc09844ee85ee
244
package ru.domclick.cockpit.plugin.log.mapper.util; import lombok.AllArgsConstructor; import lombok.Data; import org.elasticsearch.search.SearchHit; @Data @AllArgsConstructor public final class SearchHitWrapper { private SearchHit hit; }
20.333333
51
0.815574
b3465bb238cabab29432803be101484ba0f4bed5
2,909
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * jkl */ package com.microsoft.azure.management.apimanagement.v2018_06_01_preview.implementation; import com.microsoft.azure.arm.model.implementation.WrapperImpl; import com.microsoft.azure.management.apimanagement.v2018_06_01_preview.Notifications; import rx.functions.Func1; import rx.Observable; import com.microsoft.azure.Page; import com.microsoft.azure.management.apimanagement.v2018_06_01_preview.NotificationContract; import com.microsoft.azure.management.apimanagement.v2018_06_01_preview.NotificationName; class NotificationsImpl extends WrapperImpl<NotificationsInner> implements Notifications { private final ApiManagementManager manager; NotificationsImpl(ApiManagementManager manager) { super(manager.inner().notifications()); this.manager = manager; } public ApiManagementManager manager() { return this.manager; } @Override public NotificationContractImpl define(String name) { return wrapModel(name); } private NotificationContractImpl wrapModel(NotificationContractInner inner) { return new NotificationContractImpl(inner, manager()); } private NotificationContractImpl wrapModel(String name) { return new NotificationContractImpl(name, this.manager()); } @Override public Observable<NotificationContract> listByServiceAsync(final String resourceGroupName, final String serviceName) { NotificationsInner client = this.inner(); return client.listByServiceAsync(resourceGroupName, serviceName) .flatMapIterable(new Func1<Page<NotificationContractInner>, Iterable<NotificationContractInner>>() { @Override public Iterable<NotificationContractInner> call(Page<NotificationContractInner> page) { return page.items(); } }) .map(new Func1<NotificationContractInner, NotificationContract>() { @Override public NotificationContract call(NotificationContractInner inner) { return new NotificationContractImpl(inner, manager()); } }); } @Override public Observable<NotificationContract> getAsync(String resourceGroupName, String serviceName, NotificationName notificationName) { NotificationsInner client = this.inner(); return client.getAsync(resourceGroupName, serviceName, notificationName) .map(new Func1<NotificationContractInner, NotificationContract>() { @Override public NotificationContract call(NotificationContractInner inner) { return new NotificationContractImpl(inner, manager()); } }); } }
38.276316
135
0.726366
8105ceeac2c625ac23ec66a89c527cd63cc85398
6,280
/******************************************************************************* * Caleydo - Visualization for Molecular Biology - http://caleydo.org * Copyright (c) The Caleydo Team. All rights reserved. * Licensed under the new BSD license, available at http://caleydo.org/license ******************************************************************************/ package org.caleydo.vis.lineup.ui.mapping; import static org.caleydo.core.event.EventPublisher.trigger; import java.io.StringWriter; import java.util.Objects; import javax.script.Bindings; import javax.script.Compilable; import javax.script.CompiledScript; import javax.script.ScriptEngine; import javax.script.ScriptException; import org.caleydo.vis.lineup.internal.event.CodeUpdateEvent; import org.caleydo.vis.lineup.model.mapping.ScriptedMappingFunction; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * @author Samuel Gratzl * */ public class JSEditorDialog extends TitleAreaDialog { private static final String DEFAULT_MESSAGE = "that maps the input value in the variable named: \"value\" to a 0..1 range\n" + "where \"value_min\" and \"value_max\" are the current or defined minimal/maximal input values"; private final Object receiver; private final ScriptEngine engine; private ScriptedMappingFunction model; private Text codeUI; private Text testUI; private Text testOutputUI; private CompiledScript script; private StringWriter w = new StringWriter(); public JSEditorDialog(Shell parentShell, Object receiver, ScriptedMappingFunction model) { super(parentShell); setBlockOnOpen(false); this.receiver = receiver; this.engine = ScriptedMappingFunction.createEngine(); this.engine.getContext().setWriter(w); this.model = model; } @Override public void create() { super.create(); getShell().setText("Edit JavaScript Mapping Function"); setTitle("Edit JavaScript Mapping Function"); // Set the message setMessage(DEFAULT_MESSAGE, IMessageProvider.INFORMATION); } @Override protected Control createDialogArea(Composite parent) { parent = (Composite) super.createDialogArea(parent); Group group = new Group(parent, SWT.SHADOW_ETCHED_IN); final GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); gd.minimumHeight = gd.heightHint = 250; group.setLayoutData(gd); group.setLayout(new GridLayout(1, true)); group.setText("Code"); codeUI = new Text(group, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); codeUI.setLayoutData(gd); codeUI.setText(model.toJavaScript()); group = new Group(parent, SWT.SHADOW_ETCHED_IN); group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); group.setText("Test"); group.setLayout(new GridLayout(2, false)); Label l = new Label(group, SWT.None); l.setText("Input: "); l.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, true)); testUI = new Text(group, SWT.BORDER); testUI.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); testUI.setText("0.25"); l = new Label(group, SWT.None); l.setText("Output: "); l.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, true)); testOutputUI = new Text(group, SWT.BORDER | SWT.READ_ONLY); testOutputUI.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); return parent; } @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, 5, "Test", false); createButton(parent, IDialogConstants.RETRY_ID, "Apply", false); super.createButtonsForButtonBar(parent); } @Override protected void buttonPressed(int buttonId) { if (buttonId == IDialogConstants.RETRY_ID) applyPressed(); else if (buttonId == 5) testPressed(); super.buttonPressed(buttonId); } private void testPressed() { try { double f = Double.parseDouble(testUI.getText()); if (!verifyCode()) return; w.getBuffer().setLength(0); // reset Bindings b = engine.createBindings(); b.put("v", f); model.addBindings(b); final Object r = script.eval(b); String output = Objects.toString(r); testOutputUI.setText(output); String extra = w.toString(); if (extra.length() > 0) setMessage(extra, IMessageProvider.WARNING); else setMessage(DEFAULT_MESSAGE, IMessageProvider.INFORMATION); } catch(NumberFormatException e) { testOutputUI.setText("Invalid input: " + e.getMessage()); } catch (ScriptException e) { testOutputUI.setText("Error: " + e.getMessage()); } } private boolean verifyCode() { String fullCode = ScriptedMappingFunction.fullCode(codeUI.getText()); Compilable c = (Compilable) engine; try { this.script = c.compile(fullCode); // dummy test Bindings b = engine.createBindings(); b.put("v", 0.5); model.addBindings(b); Object r = script.eval(b); if (!(r instanceof Number)) { setErrorMessage("function must return a float value"); return false; } setErrorMessage(null); return true; } catch (ScriptException e) { setErrorMessage(String.format("Invalid code:\nRow %d Column %d: %s", e.getLineNumber(), e.getColumnNumber(), e.getMessage())); } return false; } private void applyPressed() { if (!verifyCode()) return; trigger(new CodeUpdateEvent(codeUI.getText()).to(receiver)); } @Override protected void okPressed() { if (!verifyCode()) return; trigger(new CodeUpdateEvent(codeUI.getText()).to(receiver)); super.okPressed(); } public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setLayout(new GridLayout(1, false)); ScriptedMappingFunction model = new ScriptedMappingFunction(0, 1); new JSEditorDialog(shell, null, model).open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } }
31.878173
125
0.712102
fc35a3f26083362f704ba4de9596c0f0957077f5
3,799
package weixin.guanjia.base.controller; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.google.gson.Gson; import weixin.util.DataDictionaryUtil.MaterialStatus; import weixin.util.DataDictionaryUtil.MaterialType; import weixin.util.DataDictionaryUtil.UrlType; @Controller @RequestMapping("/dataDict") @SuppressWarnings("all") public class DataDictController { @RequestMapping(params = "urlType") public void urlType(HttpServletRequest request, HttpServletResponse response) throws IOException { // 调用后台的查询所有商户的信息的接口方法 // 输出到页面 response.setContentType("application/json;charset=utf-8"); PrintWriter out = response.getWriter(); Gson gson = new Gson(); List urlType = new ArrayList<>(); UrlType[] types = UrlType.values(); for (UrlType t : types) { Map<String, String> m = new HashMap<String, String>(); m.put("code", t.getCode()); m.put("name", t.getName()); urlType.add(m); } String json = gson.toJson(urlType); out.write(json); } @RequestMapping(params = "materialType") public void materialType(HttpServletRequest request, HttpServletResponse response) throws IOException { // 调用后台的查询所有商户的信息的接口方法 // 输出到页面 response.setContentType("application/json;charset=utf-8"); PrintWriter out = response.getWriter(); Gson gson = new Gson(); List typeList = new ArrayList<>(); MaterialType[] types = MaterialType.values(); for (MaterialType t : types) { Map<String, String> m = new HashMap<String, String>(); m.put("code", t.getCode()); m.put("name", t.getName()); typeList.add(m); } String json = gson.toJson(typeList); out.write(json); } @RequestMapping(params = "status") public void status(HttpServletRequest request, HttpServletResponse response) throws IOException { // 调用后台的查询所有商户的信息的接口方法 // 输出到页面 response.setContentType("application/json;charset=utf-8"); PrintWriter out = response.getWriter(); Gson gson = new Gson(); List typeList = new ArrayList<>(); MaterialStatus[] types = MaterialStatus.values(); for (MaterialStatus t : types) { Map<String, String> m = new HashMap<String, String>(); m.put("code", t.getCode()); m.put("name", t.getName()); typeList.add(m); } String json = gson.toJson(typeList); out.write(json); } @RequestMapping(params = "auditStatus") public void auditStatus(HttpServletRequest request, HttpServletResponse response) throws IOException { // 调用后台的查询所有商户的信息的接口方法 // 输出到页面 response.setContentType("application/json;charset=utf-8"); PrintWriter out = response.getWriter(); Gson gson = new Gson(); List typeList = new ArrayList<>(); Map<String, String> m = new HashMap<String, String>(); m.put("code", MaterialStatus.audit_fail.getCode()); m.put("name", MaterialStatus.audit_fail.getName()); typeList.add(m); m = new HashMap<String, String>(); m.put("code", MaterialStatus.audit_pass.getCode()); m.put("name", MaterialStatus.audit_pass.getName()); typeList.add(m); String json = gson.toJson(typeList); out.write(json); } }
34.225225
107
0.635957
4e9afa96081a94fbfe4c90082c6ba615fe4b60bb
1,695
package com.appsculture.jp.flashcardapp.activities; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.appsculture.jp.flashcardapp.R; import com.appsculture.jp.flashcardapp.fragments.ListViewFragment; import javax.inject.Inject; import dagger.android.AndroidInjection; import dagger.android.AndroidInjector; import dagger.android.DispatchingAndroidInjector; import dagger.android.support.HasSupportFragmentInjector; public class CreateListActivity extends AppCompatActivity implements HasSupportFragmentInjector { private static final String LIST_ID_VALUE = "1"; @Inject DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_list); this.configureDagger(); this.showFragment(savedInstanceState); } private void showFragment(Bundle savedInstanceState) { ListViewFragment fragment = new ListViewFragment(); Bundle bundle = new Bundle(); bundle.putString(ListViewFragment.LIST_ID_KEY, LIST_ID_VALUE); fragment.setArguments(bundle); getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, fragment, null) .commit(); } private void configureDagger() { AndroidInjection.inject(this); } @Override public DispatchingAndroidInjector<Fragment> supportFragmentInjector() { return dispatchingAndroidInjector; } }
28.25
95
0.746313
d7c6a16e26f73913128f13f6c5dfb768efa5c95f
3,800
package seedu.address.logic.commands; //import static org.junit.Assert.assertEquals; import static seedu.address.logic.commands.Command.MESSAGE_LOGIN; import static seedu.address.logic.commands.CommandTestUtil.assertCommandFailure; //import static seedu.address.logic.commands.ViewLoanListCommand.MESSAGE_EMPTY; //import static seedu.address.testutil.StatusFeatureTestObjects.getExpectedUpdatedArduinoItem; //import static seedu.address.testutil.StatusFeatureTestObjects.getExpectedViewLoanListMessageOutput; //import static seedu.address.testutil.StatusFeatureTestObjects.getLoanListTestFile; import static seedu.address.testutil.StatusFeatureTestObjects.getLoanerDescription; import static seedu.address.testutil.StatusFeatureTestObjects.getStockList; import static seedu.address.testutil.StatusFeatureTestObjects.getTestIndex; import static seedu.address.testutil.TypicalAccounts.getTypicalAccountList; //import javax.xml.bind.JAXBException; import org.junit.Test; import seedu.address.logic.CommandHistory; //import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.UserPrefs; //import seedu.address.model.account.Username; //import seedu.address.model.item.Item; //@@author ChewKinWhye public class LoanListCommandsTest { private Model model = new ModelManager(getStockList(), new UserPrefs(), getTypicalAccountList()); private CommandHistory commandHistory = new CommandHistory(); private LoanListCommand loanListCommand = new LoanListCommand(getLoanerDescription()); private ViewLoanListCommand viewLoanListCommand = new ViewLoanListCommand(); private DeleteLoanListCommand deleteLoanListCommand = new DeleteLoanListCommand(getTestIndex()); @Test public void executeViewLoanListCommandWithoutLogin() { assertCommandFailure(viewLoanListCommand, model, commandHistory, MESSAGE_LOGIN); } @Test public void executeDeleteLoanListCommandWithoutLogin() { assertCommandFailure(deleteLoanListCommand, model, commandHistory, MESSAGE_LOGIN); } @Test public void executeLoanListCommandWithoutLogin() { assertCommandFailure(loanListCommand, model, commandHistory, MESSAGE_LOGIN); } /*@Test public void executeLoanListAndViewLoanListAndDeleteLoanList() { Username admin = new Username("admin"); model.setLoggedInUser(admin); try { loanListCommand.updateLoanList(getLoanListTestFile(), getLoanerDescription()); } catch (JAXBException e) { throw new AssertionError("The loan list test file is vaild"); } try { loanListCommand.updateStatus(model, commandHistory); } catch (CommandException e) { throw new AssertionError("The updated status is valid"); } Item actualUpdatedArduinoItem = model.getFilteredItemList().get(0); assertEquals(actualUpdatedArduinoItem, getExpectedUpdatedArduinoItem()); try { String actualViewLoanListMessageOutput = viewLoanListCommand.getMessageOutput(getLoanListTestFile()); assertEquals(actualViewLoanListMessageOutput, getExpectedViewLoanListMessageOutput()); } catch (CommandException e) { throw new AssertionError("Loan list file is not empty"); } try { deleteLoanListCommand.deleteLoanList(model, commandHistory, getLoanListTestFile()); } catch (Exception e) { throw new AssertionError("The loan list entry should be deleted"); } try { viewLoanListCommand.getMessageOutput(getLoanListTestFile()); } catch (CommandException e) { assertEquals(e.getMessage(), MESSAGE_EMPTY); } }*/ }
44.705882
113
0.753684
f527716ec2986c209f2a120724e118e69513ce38
1,268
package jordan.bettercraft.init.mobs.entitys; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.ai.EntityAIAttackMelee; import net.minecraft.util.EnumHand; public class EntityAIMummyAttack extends BetterEntityAIAttackMelee { private final EntityMummy mummy; private int raiseArmTicks; public EntityAIMummyAttack(EntityMummy mummyIn, double speedIn, boolean longMemoryIn) { super(mummyIn, speedIn, longMemoryIn); this.mummy = mummyIn; } /** * Execute a one shot task or start executing a continuous task */ public void startExecuting() { super.startExecuting(); this.raiseArmTicks = 0; } /** * Resets the task */ public void resetTask() { super.resetTask(); this.mummy.setArmsRaised(false); } /** * Updates the task */ public void updateTask() { super.updateTask(); ++this.raiseArmTicks; if (this.raiseArmTicks >= 5 && this.attackTick < 10) { this.mummy.setArmsRaised(true); } else { this.mummy.setArmsRaised(false); } } }
21.133333
90
0.577287
b38af319f3af420d29263c6fc5f22c6cb548a27b
1,186
package com.sequenceiq.cloudbreak.service.secret.model; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.sequenceiq.cloudbreak.service.secret.doc.SecretResponseModelDescription; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel @JsonInclude(Include.NON_NULL) public class SecretResponse implements Serializable { @ApiModelProperty(SecretResponseModelDescription.ENGINE_PATH) private String enginePath; @ApiModelProperty(SecretResponseModelDescription.SECRET_PATH) private String secretPath; public SecretResponse() { } public SecretResponse(String enginePath, String secretPath) { this.enginePath = enginePath; this.secretPath = secretPath; } public String getEnginePath() { return enginePath; } public void setEnginePath(String enginePath) { this.enginePath = enginePath; } public String getSecretPath() { return secretPath; } public void setSecretPath(String secretPath) { this.secretPath = secretPath; } }
25.782609
83
0.751265
b9b60e4e8d4830df00a0e80b16e33e4fe584ffac
469
package com.lernoscio.rover.environment; /** * Location is an interface for 3-dimensional areas that have * a name, an understanding of boundaries and can be directional. * In a Location you can turn and move. */ public interface Location { public String toString(); public String getName(); public boolean isWithin(final Coordinates coordinates); public boolean isFacing(final Coordinates position, final Direction direction); }
26.055556
83
0.727079
c407a794475f663c872fe251622945dba2d1dbd7
4,479
// Data SQLCommand is a light JDBC wrapper. // Copyright (C) 2012-2015 Adrián Romero Corchado. // // This file is part of Data SQLCommand // // 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.adr.datasql.meta; import com.adr.datasql.data.MetaData; import com.adr.datasql.orm.RecordArray; import com.adr.datasql.orm.RecordParameters; import com.adr.datasql.orm.RecordResults; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; /** * * @author adrian */ public class View implements SourceListFactory { protected String name = null; protected final List<Field> fields = new ArrayList<>(); public View() { } public View(String name, Field... fields) { this.name = name; this.fields.addAll(Arrays.asList(fields)); } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Field> getFields() { return fields; } @Override public String toString() { return "View {name: " + Objects.toString(getName()) + ", fields: " + Objects.toString(getFields()) + "}"; } private MetaData[] projection = null; @Override public MetaData[] defProjection() { if (projection == null) { List<MetaData> l = fields.stream().filter(f -> f.isLoad()).map(f -> new MetaData(f.getName(), f.getKind())).collect(Collectors.toList()); projection = l.toArray(new MetaData[l.size()]); } return projection; } private MetaData[] keys = null; @Override public MetaData[] defProjectionKeys() { if (keys == null) { List<MetaData> l = fields.stream().filter(f -> f.isKey()).map(f -> new MetaData(f.getName(), f.getKind())).collect(Collectors.toList()); keys = l.toArray(new MetaData[l.size()]); } return keys; } @Override public <R, F> SourceList<R, F> createSourceList(RecordResults<R> record, RecordParameters<F> filter) { return new EntitySourceList(this, record, filter); } private static class EntitySourceList<R, F> implements SourceList<R, F> { private final View view; private final RecordResults<R> record; private final RecordParameters<F> filter; private MetaData[] criteria; private StatementOrder[] order; public EntitySourceList(View view, RecordResults<R> record, RecordParameters<F> filter) { this.view = view; this.record = record; this.filter = filter; this.criteria = null; this.order = null; } @Override public void setCriteria(MetaData[] criteria) { this.criteria = criteria; } @Override public void setOrder(StatementOrder[] order) { this.order = order; } @Override public StatementQuery<R, F> getStatementList() { CommandEntityList command = new CommandEntityList(view.getName(), MetaData.getNames(view.defProjection()), MetaData.getNames(criteria), order); return new BasicStatementQuery<R, F>(command).setResults(record.createResults(view.defProjection())).setParameters(filter.createParams(criteria)); } @Override public StatementFind<R, Object[]> getStatementFind() { CommandEntityGet command = new CommandEntityGet(view.getName(), MetaData.getNames(view.defProjectionKeys()), MetaData.getNames(view.defProjection())); return new BasicStatementFind<R, Object[]>(command).setResults(record.createResults(view.defProjection())).setParameters(new RecordArray().createParams(view.defProjectionKeys())); } } }
34.72093
191
0.628489
bf7d99b9705ee82556f4d51bd2a1122912945694
3,618
package com.arctos6135.robotpathfinder.core; import java.util.Objects; /** * Represents a point that the robot must pass through in a path or trajectory. * <p> * A waypoint consists of an X value, Y value, and heading (direction the robot * is travelling in). Used to construct paths and trajectories. Waypoints are * immutable. * </p> * <p> * The angle used for heading is in <em>radians</em>, following the unit circle. * Thus, 0 represents right, &pi;/2 represents up, and so on. * </p> * <p> * Note that it does not matter what specific unit is used for distance; * however, the unit must match with the units in the {@link RobotSpecs} object * used to construct the trajectory. For example, if the unit for max velocity * in the {@link RobotSpecs} object was m/s, the unit used for distance must be * m. * </p> * * @author Tyler Tian * @since 3.0.0 */ public class Waypoint { protected double x; protected double y; protected double heading; protected double velocity = Double.NaN; @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Waypoint)) { return false; } Waypoint waypoint = (Waypoint) o; return x == waypoint.x && y == waypoint.y && heading == waypoint.heading && velocity == waypoint.velocity; } @Override public int hashCode() { return Objects.hash(x, y, heading, velocity); } @Override public String toString() { return "{" + " x='" + getX() + "'" + ", y='" + getY() + "'" + ", heading='" + getHeading() + "'" + ", velocity='" + getVelocity() + "'" + "}"; } /** * Creates a new {@link Waypoint} with all fields set to 0. The velocity is * unconstrained. */ public Waypoint() { } /** * Creates a new {@link Waypoint} with the specified parameters. The velocity is * unconstrained. * * @param x The x coordinate of the waypoint * @param y The y coordinate of the waypoint * @param heading The heading of the robot at the waypoint, in radians */ public Waypoint(double x, double y, double heading) { this.x = x; this.y = y; this.heading = heading; } /** * Creates a new {@link Waypoint} with the specified parameters. * * @param x The x coordinate of the waypoint * @param y The y coordinate of the waypoint * @param heading The heading of the robot at the waypoint, in radians * @param velocity the velocity of the robot at the waypoint */ public Waypoint(double x, double y, double heading, double velocity) { this.x = x; this.y = y; this.heading = heading; this.velocity = velocity; } /** * Retrieves the x coordinate of this waypoint. * * @return The x coordinate */ public double getX() { return x; } /** * Retrieves the y coordinate of this waypoint. * * @return The y coordinate */ public double getY() { return y; } /** * Retrieves the heading of this waypoint. * * @return The heading */ public double getHeading() { return heading; } /** * Retrieves the velocity of the robot at this waypoint. * <p> * By default, this value is set to {@code NaN} to signify that the velocity is * unconstrained. * </p> * * @return The velocity */ public double getVelocity() { return velocity; } }
27.409091
114
0.587617
9cd14a1e37e8c94f4ebbbec8855060c09980f310
1,606
package misrraimsp.tinymarket.util.config; import misrraimsp.tinymarket.util.converter.StringToCategoryConverter; import misrraimsp.tinymarket.util.converter.StringToPriceIntervalConverter; import misrraimsp.tinymarket.util.converter.StringToStatusPedidoConverter; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.format.FormatterRegistry; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Bean public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:messages"); messageSource.setDefaultEncoding("UTF-8"); return messageSource; } @Override public LocalValidatorFactoryBean getValidator() { LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean(); bean.setValidationMessageSource(messageSource()); return bean; } @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(new StringToCategoryConverter()); registry.addConverter(new StringToPriceIntervalConverter()); registry.addConverter(new StringToStatusPedidoConverter()); } }
40.15
106
0.804483
74d569010c800bf3ea771a482b42c006bbe538b5
1,589
package com.it.api.model; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import javax.persistence.*; import java.util.Set; @Entity @Data @Table(name = "Room") public class Room { @Id @Column(name = "room_number", nullable = false) private long roomNumber; @Column(name = "height", nullable = false) private float height; @Column(name = "width", nullable = false) private float width; @Column(name = "max_occupation", nullable = false) private int maxOccupation; @Column(name = "floor", nullable = false) private int floor; @Column(name = "access_level", nullable = false) private int accessLevel; @ManyToOne @JoinColumn(name = "dept_id", nullable = false) private Department dept; @OneToMany(mappedBy = "room", cascade = CascadeType.ALL, orphanRemoval = true) @JsonIgnore @ToString.Exclude @EqualsAndHashCode.Exclude private Set<Booking> bookings; @OneToMany(mappedBy = "room", cascade = CascadeType.ALL, orphanRemoval = true) @JsonIgnore @EqualsAndHashCode.Exclude private Set<AccessLog> accesses; public Room() { } public Room(long roomNumber, float height, float width, int maxOccupation, int floor, Department dept, int accessLevel) { this.roomNumber = roomNumber; this.height = height; this.width = width; this.maxOccupation = maxOccupation; this.floor = floor; this.dept = dept; this.accessLevel = accessLevel; } }
25.222222
125
0.676526
53e190811423d565354aafa1acf6b067e3a21b5a
1,106
package io.github.factoryfx.javafx.editor.attribute.visualisation; import io.github.factoryfx.factory.attribute.primitive.ShortAttribute; import io.github.factoryfx.javafx.editor.attribute.ValidationDecoration; import io.github.factoryfx.javafx.editor.attribute.ValueAttributeVisualisation; import io.github.factoryfx.javafx.util.TypedTextFieldHelper; import javafx.scene.Node; import javafx.scene.control.TextField; import javafx.util.converter.ShortStringConverter; public class ShortAttributeVisualisation extends ValueAttributeVisualisation<Short, ShortAttribute> { public ShortAttributeVisualisation(ShortAttribute shortAttribute, ValidationDecoration validationDecoration) { super(shortAttribute,validationDecoration); } @Override public Node createValueVisualisation() { TextField textField = new TextField(); TypedTextFieldHelper.setupShortTextField(textField); textField.textProperty().bindBidirectional(observableAttributeValue, new ShortStringConverter()); textField.disableProperty().bind(readOnly); return textField; } }
42.538462
114
0.808318
1442eb0edc05772a20000906ab0171796f77a62a
1,941
/* * Copyright © 2021 <a href="mailto:zhang.h.n@foxmail.com">Zhang.H.N</a>. * * Licensed under the Apache License, Version 2.0 (thie "License"); * You may not use this file except in compliance with the license. * You may obtain a copy of the License at * * http://wwww.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 govering permissions and * limitations under the License. */ package org.gcszhn.system.security; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import org.gcszhn.system.config.JSONConfig; /** * SHA单向加密算法 * @author Zhang.H.N * @version 1.0 */ public class ShaEncrypt { /** * SHA-256的加盐加密算法 * @param message UTF-8编码的明文 * @param salt UTF-8编码的Base64字符串盐 * @return UTF-8编码的Base64密文 */ public static String encrypt(String message, String salt) { byte[] saltArray = Base64.getDecoder().decode(salt.getBytes(JSONConfig.DEFAULT_CHARSET)); byte[] messArray = message.getBytes(JSONConfig.DEFAULT_CHARSET); byte[] mixsArray = new byte[Math.max(saltArray.length, messArray.length)]; for (int i = 0; i < mixsArray.length; i++) { byte s = i < saltArray.length?saltArray[i]:0; byte m = i < messArray.length?messArray[i]:0; mixsArray[i] = (byte)((s + m)/2); } try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(mixsArray); return new String(Base64.getEncoder().encode(md.digest()), JSONConfig.DEFAULT_CHARSET); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } return null; } }
36.622642
99
0.665636
05dd30076e0a9d946ba8ca6c6a06d98df172d174
465
package com.otherhshe.niceread.utils; import android.support.design.widget.Snackbar; import android.view.View; /** * Author: Othershe * Time: 2016/8/16 17:01 */ public class SnackBarUtil { public static void show(View rootView, int textId) { Snackbar.make(rootView, textId, Snackbar.LENGTH_SHORT).show(); } public static void show(View rootView, String text) { Snackbar.make(rootView, text, Snackbar.LENGTH_SHORT).show(); } }
23.25
70
0.701075
44b43e4c1bbc0fa208203e87cf4b2fa5b924da30
466
package com.gupao.decorator.menuaccess; /** * @ProjectName: DesignPattern * @ClassName: BaseMenu * @Description: TODO(一句话描述该类的功能) * @Author: tangqi * @Date: 2020/5/12 10:35 上午 * @Version v1.0 */ public class BaseMenu extends Menu{ @Override public Boolean getVisiable() { return true; } @Override public Boolean getLogin() { return false; } @Override public String getName() { return "首页"; } }
16.068966
39
0.613734
2b3d09d3f9b647ac1485472db2af2c3a3bd01194
5,068
/** * */ package org.jpwned.core; import com.google.gson.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.*; import org.jpwned.model.Breach; import org.jpwned.model.Paste; import org.jpwned.utils.Constants; import org.jpwned.utils.QueryCollector; /** * This class uses <a href="https://haveibeenpwned.com/">https://haveibeenpwned.com</a> APIs * * @author Dariush Moshiri * * @see <a href="https://haveibeenpwned.com/API/v2">API info</a> * * @see <a href="https://haveibeenpwned.com/API/v2#ResponseCodes">Request errors</a> * * */ public class JPwned { private Gson gson; private String userAgent; /** * @param userAgent this request header must be set otherwise any call will result in an HTTP 403 response */ public JPwned(String userAgent) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateDeserializer()); gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeDeserializer()); this.gson = gsonBuilder.create(); if(userAgent == null || userAgent.isEmpty()) throw new IllegalArgumentException("User-Agent must not be empty or null"); this.userAgent = userAgent; } /** * * @param account email that has to be checked * @return the list of breaches for the <code>account</code> * @throws IOException if there is a problem with the request */ public List<Breach> getAllBreachesForAccount(String account) throws IOException { String url = Constants.HOST + Constants.BREACHED_ACCOUNT + "/" + URLEncoder.encode(account, "UTF-8"); return Arrays.asList(gson.fromJson(getReaderFromConnection(url), Breach[].class)); } /** * * @param account email that has to be checked * @param domain get only the breaches for this <code>domain</code> * @return the list of breaches of the <code>domain</code> for the <code>account</code> * @throws IOException if there is a problem with the request */ public List<Breach> getAllBreachesForAccount(String account, String domain) throws IOException { Map<String, String> params = new HashMap<String, String>(); params.put("domain", domain); String url = Constants.HOST + Constants.BREACHED_ACCOUNT + "/" + URLEncoder.encode(account, "UTF-8") + generateRequestParams(params); return Arrays.asList(gson.fromJson(getReaderFromConnection(url), Breach[].class)); } /** * @return all the breaches in the system * @throws IOException if there is a problem with the request */ public List<Breach> getAllBreachedSites() throws IOException { String url = Constants.HOST + Constants.BREACHED_SITES; return Arrays.asList(gson.fromJson(getReaderFromConnection(url), Breach[].class)); } /** * @param domain get only the breaches for this <code>domain</code> * @return all the breaches of the <code>domain</code> * @throws IOException if there is a problem with the request */ public List<Breach> getAllBreachedSites(String domain) throws IOException { Map<String, String> params = new HashMap<String, String>(); params.put("domain", domain); String url = Constants.HOST + Constants.BREACHED_SITES + generateRequestParams(params); return Arrays.asList(gson.fromJson(getReaderFromConnection(url), Breach[].class)); } /** * @param name title of the breach * @return the breach with <code>name</code> as its title * @throws IOException if there is a problem with the request */ public Breach getBreach(String name) throws IOException { String url = Constants.HOST + Constants.BREACH + "/" + name; return gson.fromJson(getReaderFromConnection(url), Breach.class); } /** * A "data class" is an attribute of a record compromised in a breach. * @return all the data classes saved in the system ordered alphabetically * @throws IOException */ public List<String> getAllDataClasses() throws IOException { String url = Constants.HOST + Constants.DATA_CLASSES; return Arrays.asList(gson.fromJson(getReaderFromConnection(url), String[].class)); } /** * @param account email address to be searched for * @return the list of pastes associated with <code>account</code> * @throws IOException */ public List<Paste> getAllPastesForAccount(String account) throws IOException { String url = Constants.HOST + Constants.PASTES_ACCOUNT + "/" + URLEncoder.encode(account, "UTF-8"); return Arrays.asList(gson.fromJson(getReaderFromConnection(url), Paste[].class)); } private String generateRequestParams(Map<String, String> params) { return params.entrySet().stream().collect(new QueryCollector()); } private Reader getReaderFromConnection(String url) throws IOException { URLConnection connection = new URL(url).openConnection(); connection.setRequestProperty("User-Agent", userAgent); return new BufferedReader(new InputStreamReader(connection.getInputStream())); } }
35.690141
135
0.73678
aa31ea0cfbd1981ce5b5c6662efef655bf552ebf
2,899
/* * 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.flink.streaming.tests; import org.apache.flink.api.connector.sink2.Sink; import org.apache.flink.connector.elasticsearch.sink.Elasticsearch7SinkBuilder; import org.apache.flink.connector.testframe.external.ExternalSystemDataReader; import org.apache.flink.connector.testframe.external.sink.TestingSinkSettings; import org.apache.http.HttpHost; import java.net.URL; import java.util.List; class Elasticsearch7SinkExternalContext extends ElasticsearchSinkExternalContextBase { /** * Instantiates a new Elasticsearch 7 sink context base. * * @param addressExternal The address to access Elasticsearch from the host machine (outside of * the containerized environment). * @param addressInternal The address to access Elasticsearch from Flink. When running in a * containerized environment, should correspond to the network alias that resolves within * the environment's network together with the exposed port. * @param connectorJarPaths The connector jar paths. */ Elasticsearch7SinkExternalContext( String addressExternal, String addressInternal, List<URL> connectorJarPaths) { super(addressInternal, connectorJarPaths, new Elasticsearch7Client(addressExternal)); } @Override public Sink<KeyValue<Integer, String>> createSink(TestingSinkSettings sinkSettings) { client.createIndexIfDoesNotExist(indexName, 1, 0); return new Elasticsearch7SinkBuilder<KeyValue<Integer, String>>() .setHosts(HttpHost.create(this.addressInternal)) .setEmitter(new ElasticsearchTestEmitter(new UpdateRequest7Factory(indexName))) .setBulkFlushMaxActions(BULK_BUFFER) .build(); } @Override public ExternalSystemDataReader<KeyValue<Integer, String>> createSinkDataReader( TestingSinkSettings sinkSettings) { return new ElasticsearchDataReader(client, indexName, PAGE_LENGTH); } @Override public String toString() { return "Elasticsearch 7 sink context."; } }
42.014493
99
0.74198
1ea924f233986d705ee972fbaa6f21aadf3734db
252
import java.util.Scanner; public class CalculateExpression { public static void main(String[] args) { double val = ((30 + 21) * 0.5 * (35 - 12 - 0.5)); double result = Math.pow(val, 2); System.out.println(result); } }
22.909091
57
0.583333
fc183d233e42e5a48cef630be8e2a02e8b75be7a
415
package functional.com.trailblazers.freewheelers.helpers; import org.openqa.selenium.By; public class OrderTable { public static By selectFor(String item) { return By.xpath("//tbody/tr/td[2][text() = '" + item + "']/parent::*/td[4]/select"); } public static By saveButtonFor(String item) { return By.xpath("//tbody/tr/td[2][text() = '" + item + "']/parent::*/td[6]/button"); } }
27.666667
92
0.624096
010c9b74ddff3d23709bdeb9d56662131acab528
5,600
/* * Copyright 2008-2019 Async-IO.org * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.atmosphere.interceptor; import org.atmosphere.cpr.Action; import org.atmosphere.cpr.AsyncIOInterceptorAdapter; import org.atmosphere.cpr.AsyncIOWriter; import org.atmosphere.cpr.AtmosphereInterceptorAdapter; import org.atmosphere.cpr.AtmosphereInterceptorWriter; import org.atmosphere.cpr.AtmosphereRequest; import org.atmosphere.cpr.AtmosphereResource; import org.atmosphere.cpr.AtmosphereResource.TRANSPORT; import org.atmosphere.cpr.AtmosphereResourceEvent; import org.atmosphere.cpr.AtmosphereResourceEventListenerAdapter; import org.atmosphere.cpr.AtmosphereResponse; import org.atmosphere.cpr.FrameworkConfig; import org.atmosphere.cpr.HeaderConfig; import org.atmosphere.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import static org.atmosphere.cpr.FrameworkConfig.INJECTED_ATMOSPHERE_RESOURCE; /** * Padding interceptor for Browser that needs whitespace when streaming is used. * * @author Jeanfrancois Arcand */ public class PaddingAtmosphereInterceptor extends AtmosphereInterceptorAdapter { private static final Logger logger = LoggerFactory.getLogger(PaddingAtmosphereInterceptor.class); private final byte[] padding; private final String paddingText; public PaddingAtmosphereInterceptor(){ paddingText = confPadding(2048); padding = paddingText.getBytes(); } public PaddingAtmosphereInterceptor(int size){ paddingText = confPadding(size); padding = paddingText.getBytes(); } protected final static String confPadding(int size) { StringBuilder whitespace = new StringBuilder(); for (int i = 0; i < size; i++) { whitespace.append(" "); } whitespace.append("\n"); return whitespace.toString(); } private void writePadding(AtmosphereResponse response) { AtmosphereRequest request = response.request(); if (request != null && request.getAttribute("paddingWritten") != null) return; if (response.resource() != null && response.resource().transport().equals(TRANSPORT.STREAMING)) { request.setAttribute(FrameworkConfig.TRANSPORT_IN_USE, HeaderConfig.STREAMING_TRANSPORT); response.setContentType("text/plain"); } response.write(padding, true); try { response.flushBuffer(); } catch (IOException e) { logger.trace("", e); } } @Override public Action inspect(final AtmosphereResource r) { if (Utils.webSocketMessage(r)) return Action.CONTINUE; final AtmosphereResponse response = r.getResponse(); final AtmosphereRequest request = r.getRequest(); String uuid = request.getHeader(HeaderConfig.X_ATMOSPHERE_TRACKING_ID); boolean padding = r.transport().equals(TRANSPORT.STREAMING) || r.transport().equals(TRANSPORT.LONG_POLLING); if (uuid != null && !uuid.equals("0") && r.transport().equals(TRANSPORT.WEBSOCKET) && request.getAttribute(INJECTED_ATMOSPHERE_RESOURCE) != null) { padding = true; } if (padding) { r.addEventListener(new ForcePreSuspend(response)); super.inspect(r); AsyncIOWriter writer = response.getAsyncIOWriter(); if (AtmosphereInterceptorWriter.class.isAssignableFrom(writer.getClass())) { AtmosphereInterceptorWriter.class.cast(writer).interceptor(new AsyncIOInterceptorAdapter() { private void padding() { if (!r.isSuspended()) { writePadding(response); request.setAttribute("paddingWritten", "true"); } } @Override public void prePayload(AtmosphereResponse response, byte[] data, int offset, int length) { padding(); } @Override public void postPayload(AtmosphereResponse response, byte[] data, int offset, int length) { } }); } else { logger.warn("Unable to apply {}. Your AsyncIOWriter must implement {}", getClass().getName(), AtmosphereInterceptorWriter.class.getName()); } } return Action.CONTINUE; } @Override public String toString() { return "Browser Padding Interceptor Support"; } public final class ForcePreSuspend extends AtmosphereResourceEventListenerAdapter implements AllowInterceptor { private final AtmosphereResponse response; public ForcePreSuspend(AtmosphereResponse response) { this.response = response; } @Override public void onPreSuspend(AtmosphereResourceEvent event) { writePadding(response); event.getResource().removeEventListener(this); } } }
36.129032
155
0.661607
c062393d8dcf71c5e3d531502b817cc0b00f64e8
3,635
package com.techelevator.dao; import static org.junit.Assert.assertEquals; import javax.sql.DataSource; import org.junit.Before; import org.junit.Test; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; import com.techelevator.model.Review; public class ReviewJdbcDAOTest extends DAOIntegrationTest { private JdbcTemplate template; private ReviewJdbcDAO reviewDao; private static int REVIEW_ID_BREWERY; private static int TARGET_ID_BREW; private static int REVIEW_ID_BEER; private static int TARGET_ID_BEER; private static int USER_ID; @Before public void setup() { DataSource dataSource = this.getDataSource(); template = new JdbcTemplate(dataSource); reviewDao = new ReviewJdbcDAO(template); Review testRev = new Review(); REVIEW_ID_BREWERY = 2; TARGET_ID_BREW = 100; REVIEW_ID_BEER = 1; TARGET_ID_BEER = 1000; USER_ID = 3; // insert a dummy brewery String createTestBrewery = "INSERT INTO breweries(id, name) VALUES(100,'TEST')"; template.update(createTestBrewery); // insert a dummy beer to dummy brewery String addAbeer = "INSERT INTO beers(id, name, brewery_id, beer_type) VALUES(1000, 'Greatest Beer', 100, 131)"; template.update(addAbeer); //insert dummy review String sqlInsertDummyBrewery = "INSERT INTO REVIEWS(review_type, target_id, user_id, review_title," + "review_body, review_caps) VALUES(?, ?, ?, ?, ?, ?)"; template.update(sqlInsertDummyBrewery, REVIEW_ID_BREWERY, TARGET_ID_BREW, USER_ID, "WOW", "IT IS A GREAT BREWERY", 5); String sqlInsertDummyBeer = "INSERT INTO REVIEWS(review_type, target_id, user_id, review_title," + "review_body, review_caps) VALUES(?, ?, ?, ?, ?, ?)"; template.update(sqlInsertDummyBeer, REVIEW_ID_BEER, TARGET_ID_BEER, USER_ID, "WOW", "GREAT TASTE", 5); } @Test public void getAllReviewsByTargetIdTestBreweryReview() { String sqlGetCount = "SELECT COUNT(*) FROM reviews JOIN users ON reviews.user_id = users.user_id" + " WHERE target_id = ?"; SqlRowSet result = template.queryForRowSet(sqlGetCount, TARGET_ID_BREW); result.next(); assertEquals(result.getInt(1), reviewDao.getAllReviewsByTargetId(TARGET_ID_BREW).size()); assertEquals(TARGET_ID_BREW, reviewDao.getAllReviewsByTargetId(TARGET_ID_BREW).get(0).getTargetId()); assertEquals("WOW", reviewDao.getAllReviewsByTargetId(TARGET_ID_BREW).get(0).getReviewTitle()); assertEquals("IT IS A GREAT BREWERY", reviewDao.getAllReviewsByTargetId(TARGET_ID_BREW).get(0).getReviewBody()); } @Test public void getAllReviewsByTargetIdTestBeerReview() { String sqlGetCount = "SELECT COUNT(*) FROM reviews JOIN users ON reviews.user_id = users.user_id" + " WHERE target_id = ?"; SqlRowSet result = template.queryForRowSet(sqlGetCount, TARGET_ID_BEER); result.next(); assertEquals(result.getInt(1), reviewDao.getAllReviewsByTargetId(TARGET_ID_BEER).size()); assertEquals(TARGET_ID_BEER, reviewDao.getAllReviewsByTargetId(TARGET_ID_BEER).get(0).getTargetId()); assertEquals("WOW", reviewDao.getAllReviewsByTargetId(TARGET_ID_BEER).get(0).getReviewTitle()); assertEquals("GREAT TASTE", reviewDao.getAllReviewsByTargetId(TARGET_ID_BEER).get(0).getReviewBody()); } @Test public void getAllReviewsByUserId() { String sqlCount = "SELECT COUNT(*) FROM reviews JOIN users ON users.user_id = reviews.user_id WHERE user_id = ?"; SqlRowSet result = template.queryForRowSet(sqlCount, USER_ID); result.next(); System.out.println(reviewDao.getAllReviewsByUserId(USER_ID).size()); //assertEquals(result.getInt(1), reviewDao.getAllReviewsByUserId(USER_ID).size()); } }
41.781609
115
0.763961
42e72529bfe6ff2ae47f3674f3b75680b6e28fa9
1,180
package com.jeecg.qywx.api.message.vo; public class News { private String touser;//成员ID列表(消息接收者,多个接收者用‘|’分隔,最多支持1000个)。特殊情况:指定为@all,则向关注该企业应用的全部成员发送 private String toparty;//部门ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参 private String totag;// 标签ID列表,多个接收者用‘|’分隔。当touser为@all时忽略本参数 private String msgtype;//消息类型,此时固定为:voice (不支持主页型应用) private int agentid;//企业应用的id,整型。可在应用的设置页面查看 private NewsEntity news;//信息实体 public String getTouser() { return touser; } public void setTouser(String touser) { this.touser = touser; } public String getToparty() { return toparty; } public void setToparty(String toparty) { this.toparty = toparty; } public String getTotag() { return totag; } public void setTotag(String totag) { this.totag = totag; } public String getMsgtype() { return msgtype; } public void setMsgtype(String msgtype) { this.msgtype = msgtype; } public int getAgentid() { return agentid; } public void setAgentid(int agentid) { this.agentid = agentid; } public NewsEntity getNews() { return news; } public void setNews(NewsEntity news) { this.news = news; } }
24.081633
94
0.688136
0bc92a7cfeb8e09d2ce7b5bae044ea1873a06a46
1,722
package net.ijiangtao.tech.demo.i18n.interceptor; import lombok.extern.slf4j.Slf4j; import net.ijiangtao.tech.demo.i18n.util.LanguageUtil; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.support.RequestContextUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Locale; @Slf4j public class LanguageInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("preHandle:请求前调用"); //请求头 当前语言 // Accept-Language: zh-CN // Accept-Language: en-US LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request); Locale local= localeResolver.resolveLocale(request); log.info("local={} , localDisplayName={}",local.toString(),local.getDisplayName()); LanguageUtil.setCurrentLang(local.toString()); log.info("LanguageUtil.getCurrentLang() = {}",LanguageUtil.getCurrentLang()); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { log.info("postHandle:请求后调用"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { log.info("afterCompletion:请求调用完成后回调方法,即在视图渲染完成后回调"); } }
35.142857
119
0.735192
ae88ea270ef98e328fe85c06cb9dd9560ee951e0
8,970
/** * 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.azkfw.gui.dialog; import java.awt.Component; import java.awt.Container; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.border.BevelBorder; import javax.swing.border.SoftBevelBorder; /** * このクラスは、設定ダイアログ画面を実装する為の基底クラスです。 * * @since 1.0.0 * @version 1.0.0 2014/10/06 * @author Kawakicchi */ public abstract class ConfigurationDialog<DATA> extends JDialog { /** serialVersionUID */ private static final long serialVersionUID = 4046832570158320828L; private static final int DEFAULT_BUTTON_MARGIN = 6; private static final int DEFAULT_BORDER_SIZE = 3; private static final int DEFAULT_BUTTON_WIDTH = 120; private static final int DEFAULT_BUTTON_HEIGHT = 24; /** data object */ private DATA data; /** listener */ private List<ConfigurationDialogListener> listeners; // Component /** client panel */ private JPanel pnlClient; /** border */ private JPanel pnlBorder; /** OK button */ private JButton btnOk; /** Cancel button */ private JButton btnCancel; /** Option button list */ private List<JButton> optionButtonList; /** * コンストラクタ * * @param aData Data */ public ConfigurationDialog(final DATA aData) { super(); init(aData); } /** * コンストラクタ * * @param aFrame Frame * @param aData Data */ public ConfigurationDialog(final Frame aFrame, final DATA aData) { super(aFrame); init(aData); } /** * コンストラクタ * * @param aDialog Dialog * @param aData Data */ public ConfigurationDialog(final Dialog aDialog, final DATA aData) { super(aDialog); init(aData); } /** * コンストラクタ * * @param aFrame Frame * @param aModal Modal * @param aData Data */ public ConfigurationDialog(final Frame aFrame, final boolean aModal, final DATA aData) { super(aFrame, aModal); init(aData); } /** * コンストラクタ * * @param aDialog Dialog * @param aModal Modal * @param aData Data */ public ConfigurationDialog(final Dialog aDialog, final boolean aModal, final DATA aData) { super(aDialog, aModal); init(aData); } private void init(final DATA aData) { setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); setLayout(null); setMinimumSize(new Dimension(480, 120)); data = aData; listeners = new ArrayList<ConfigurationDialogListener>(); optionButtonList = new ArrayList<JButton>(); Container container = getContentPane(); pnlClient = new JPanel(); pnlClient.setLayout(null); container.add(pnlClient); pnlBorder = new JPanel(); pnlBorder.setBorder(new SoftBevelBorder(BevelBorder.RAISED)); container.add(pnlBorder); btnOk = new JButton("OK"); btnOk.setSize(DEFAULT_BUTTON_WIDTH, DEFAULT_BUTTON_HEIGHT); container.add(btnOk); btnCancel = new JButton("キャンセル"); btnCancel.setSize(DEFAULT_BUTTON_WIDTH, DEFAULT_BUTTON_HEIGHT); container.add(btnCancel); btnOk.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { doClickButtonOk(); } }); btnCancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { doClickButtonCancel(); } }); addComponentListener(new ComponentAdapter() { @Override public void componentResized(final ComponentEvent event) { doResizeDialog(); } }); addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent event) { doClickButtonCancel(); } @Override public void windowOpened(final WindowEvent event) { setSize(getPreferredSize()); } }); } public Dimension getPreferredSize() { return new Dimension(getWidth(), getHeight()); } @Override public final Component add(final Component comp) { return pnlClient.add(comp); } @Override public final int getComponentCount() { return pnlClient.getComponentCount(); } @Override public final Component getComponent(final int index) { return pnlClient.getComponent(index); } protected final JPanel getClientPanel() { return pnlClient; } public final void addOptionButton(final JButton aButton) { if (0 >= aButton.getWidth()) { aButton.setSize(DEFAULT_BUTTON_WIDTH, DEFAULT_BUTTON_HEIGHT); } optionButtonList.add(aButton); getContentPane().add(aButton); doResizeDialog(); } /** * コンテナの中心に移動する。 * * @param aParent 親コンテナ */ public final void setLocationMiddle(final Container aParent) { int x = (aParent.getWidth() - getWidth()) / 2; int y = (aParent.getHeight() - getHeight()) / 2; setLocation(aParent.getX() + x, aParent.getY() + y); } /** * 設定ダイアログへリスナーを登録する。 * * @param listener リスナー */ public final void addConfigurationDialogListener(final ConfigurationDialogListener listener) { synchronized (listeners) { listeners.add(listener); } } /** * 設定ダイアログからリスナーを削除する。 * * @param listener */ public final void removeConfigurationDialogListener(final ConfigurationDialogListener listener) { synchronized (listeners) { listeners.remove(listener); } } /** * クライアントサイズを設定する。 * <p> * クライアントサイズを元にダイアログサイズを設定する。 * </p> * * @param aWidth 横幅 * @param aHeight 縦幅 */ public final void setClientPanelSize(final int aWidth, final int aHeight) { Insets insets = getClientInsets(); setSize(aWidth + (insets.left + insets.left), aHeight + (insets.top + insets.bottom)); } /** * データを取得する。 * * @return データ */ public final DATA getData() { return data; } /** * バリデーション処理。 * * @return <code>true</code>で成功 */ protected abstract boolean isValidate(); /** * OKボタンが押下された時の処理。 * * @return <code>false</code>で処理を中断 */ protected abstract boolean doClickOK(final DATA aData); /** * Cancelボタンが押下された時の処理。 * * @return <code>false</code>で処理を中断 */ protected abstract boolean doClickCancel(); private void doClickButtonOk() { if (isValidate()) { if (doClickOK(data)) { ConfigurationDialogEvent event = new ConfigurationDialogEvent(this); synchronized (listeners) { for (ConfigurationDialogListener listener : listeners) { try { listener.configurationDialogOk(event, data); } catch (Exception ex) { ex.printStackTrace(); } } } setVisible(false); dispose(); } } } private void doClickButtonCancel() { if (doClickCancel()) { ConfigurationDialogEvent event = new ConfigurationDialogEvent(this); synchronized (listeners) { for (ConfigurationDialogListener listener : listeners) { try { listener.configurationDialogCancel(event, data); } catch (Exception ex) { ex.printStackTrace(); } } } setVisible(false); dispose(); } } public Insets getClientInsets() { Insets insets = super.getInsets(); return new Insets(insets.top, insets.left, insets.bottom + (DEFAULT_BUTTON_MARGIN + DEFAULT_BUTTON_HEIGHT + DEFAULT_BUTTON_MARGIN + DEFAULT_BORDER_SIZE), insets.right); } private void doResizeDialog() { Insets insets = getInsets(); int width = getWidth() - (insets.left + insets.right); int height = getHeight() - (insets.top + insets.bottom); pnlClient.setBounds(0, 0, width, height - (DEFAULT_BUTTON_MARGIN + DEFAULT_BUTTON_HEIGHT + DEFAULT_BUTTON_MARGIN + DEFAULT_BORDER_SIZE)); pnlBorder.setBounds(-2, height - (DEFAULT_BUTTON_MARGIN + DEFAULT_BUTTON_HEIGHT + DEFAULT_BUTTON_MARGIN + DEFAULT_BORDER_SIZE), width + 4, DEFAULT_BORDER_SIZE); int x = DEFAULT_BUTTON_MARGIN; int y = height - (DEFAULT_BUTTON_HEIGHT + DEFAULT_BUTTON_MARGIN); for (JButton button : optionButtonList) { button.setLocation(x, y); x += button.getWidth() + DEFAULT_BUTTON_MARGIN; } btnOk.setLocation(width - (DEFAULT_BUTTON_WIDTH + DEFAULT_BUTTON_MARGIN) * 2, y); btnCancel.setLocation(width - (DEFAULT_BUTTON_WIDTH + DEFAULT_BUTTON_MARGIN) * 1, y); } }
24.847645
140
0.710591
09b126ea4c158d5cced3d8858c18d162c9772bfd
1,166
/* * Copyright 2014,2015 agwlvssainokuni * * 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 cherry.goods.crypto; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import org.apache.commons.lang3.RandomUtils; import org.junit.Test; public class NullCryptoTest { @Test public void testEncodeDecode() { NullCrypto crypto = new NullCrypto(); for (int i = 0; i < 100; i++) { byte[] plain = RandomUtils.nextBytes(1024); byte[] enc = crypto.encrypt(plain); assertThat(enc, is(plain)); byte[] dec = crypto.decrypt(enc); assertThat(dec, is(enc)); } } }
29.15
76
0.697256
c7c84eed4152c6564f042e0869a1204ae64015c2
325
package CodingBat; public class tripleUp { public static void main(String[] args) { } public static boolean tripleUp(int[] nums) { for (int i = 1; i < nums.length - 1; i++) { if (nums[i - 1] + 1 == nums[i] && nums[i] + 1 == nums[i + 1]) return true; } return false; } }
21.666667
86
0.513846
4789d1be00cb748915858c9dfea3d404cc26c41d
1,583
/* * Copyright 2003 - 2016 The eFaps Team * * 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.efaps.esjp.common.history; import org.efaps.admin.datamodel.Type; import org.efaps.admin.event.Parameter; import org.efaps.admin.program.esjp.EFapsApplication; import org.efaps.admin.program.esjp.EFapsUUID; import org.efaps.esjp.ci.CICommon; import org.efaps.esjp.common.history.xml.AbstractHistoryLog; import org.efaps.esjp.common.history.xml.CreateAttributeSetLog; /** * TODO comment! * * @author The eFaps Team */ @EFapsUUID("12ba6b00-99fd-45b8-9de5-9c7a4f2ed256") @EFapsApplication("eFaps-Kernel") public abstract class InsertAttributeSetHistoryTrigger_Base extends AbstractAttributeSetHistoryTrigger { /** * {@inheritDoc} */ @Override protected Type getHistoryType() { return CICommon.HistoryAttributeSetCreate.getType(); } /** * {@inheritDoc} */ @Override protected AbstractHistoryLog getLogObject(final Parameter _parameter) { return new CreateAttributeSetLog(); } }
27.77193
75
0.731522
9979b3083cc4b3d1888c0f537a55b515f0794bb1
1,209
package xyz.moonrabbit.gradlepleaseconsole.parser; import org.json.JSONArray; import org.json.JSONObject; public class GradlePleaseSearchParser extends AbstractParser { private final static String PREFIX = "searchCallback("; private final static String SUFFIX = ")"; @Override protected String getUrl(String search) { return "http://gradleplease.appspot.com/search?q=" + search; } @Override protected void processInternal(String content) { content = content.trim(); if (!content.startsWith(PREFIX) || !content.endsWith(SUFFIX)) { System.err.println("Something wrong. Wrong response"); System.exit(1); } String jsonContent = content.substring("searchCallback(".length(), content.length() - SUFFIX.length()); JSONObject json = new JSONObject(jsonContent); if (json.optBoolean("error")) { System.err.println("Nothing found :-("); System.exit(1); } JSONArray array = json.getJSONObject("response").getJSONArray("docs"); json = array.getJSONObject(0); System.out.println(json.getString("id") + ":" + json.getString("latestVersion")); } }
32.675676
111
0.64847
50913e67693205da51fc4e7c25a773e0e891a1f1
650
package GUI; import Utils.XCommand; import javax.swing.JButton; import javax.swing.JPanel; public class WidthPanel extends JPanel { public WidthPanel(XCommand cmd) { setLayout(null); JButton btnSmall = new JButton("Small"); JButton btnMedium = new JButton("Medium"); JButton btnLarge = new JButton("Large"); btnSmall.setBounds(10, 0, 100, 30); btnMedium.setBounds(10, 40, 100, 30); btnLarge.setBounds(10, 80, 100, 30); btnSmall.addActionListener(cmd.actionWidth); btnMedium.addActionListener(cmd.actionWidth); btnLarge.addActionListener(cmd.actionWidth); add(btnSmall); add(btnMedium); add(btnLarge); } }
20.3125
47
0.723077
ea0977702b6d4ec5c60a113f5a30c4e2e9d91458
1,113
package ru.stqa.pft.addressbook.tests; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.ContactData; import java.util.List; /** * Created by user on 3/24/2017. */ public class ContactDeletionTests extends TestBase { @BeforeMethod public void ensurePreconditions() { app.goTo().homePage(); if (app.contact().list().size() == 0) { app.goTo().addContactPage(); app.contact().create(new ContactData().withFirstName("John").withLastName("Doe").withAddress("Green Street, LA, 30495") .withPhone("1-208-555-1212").withEmail("johndoe@soup.com").withGroup("g2name"), true); } } @Test//(enabled = false) public void testContactDeletion() { List<ContactData> before = app.contact().list(); int index = before.size() - 1; app.contact().delete(index); app.goTo().homePage(); List<ContactData> after = app.contact().list(); Assert.assertEquals(after.size(), before.size() - 1); before.remove(index); Assert.assertEquals(before, after); } }
27.146341
125
0.67655
ac5f3a7b90c60045dc8821df08cea45afc5e61fe
3,257
/** * Copyright © 2015 Mercateo AG (http://www.mercateo.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mercateo.common.rest.schemagen.types; import static java.util.Objects.requireNonNull; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import com.mercateo.common.rest.schemagen.JsonHyperSchema; import com.mercateo.common.rest.schemagen.ListSlicer; import com.mercateo.common.rest.schemagen.PaginationLinkBuilder; import com.mercateo.common.rest.schemagen.PaginationLinkBuilder.PaginationLinkCreator; import javax.ws.rs.core.Link; public class PaginatedResponseBuilder<ElementIn, ElementOut> extends ResponseBuilderAbstract<PaginatedResponseBuilder<ElementIn, ElementOut>, ElementIn, ElementOut, PaginatedResponse<ElementOut>> { private PaginationLinkCreator paginationLinkCreator; private PaginatedList<ElementIn> paginatedList; /** * @deprecated please use {@link PaginatedResponse#builder()} instead */ @Deprecated public PaginatedResponseBuilder() { } @Override public PaginatedResponse<ElementOut> build() { requireNonNull(paginatedList); requireNonNull(elementMapper); requireNonNull(containerLinks); requireNonNull(paginationLinkCreator); PaginatedList<ObjectWithSchema<ElementOut>> mappedList = new PaginatedList<>( paginatedList.total, paginatedList.offset, paginatedList.limit, paginatedList.members.stream().map(elementMapper).collect(Collectors.toList())); final List<Link> containerLinks = new ArrayList<>(this.containerLinks); containerLinks.addAll(PaginationLinkBuilder.of(paginatedList.total, paginatedList.offset, paginatedList.limit).generateLinks(paginationLinkCreator)); JsonHyperSchema schema = JsonHyperSchema.from(containerLinks); return PaginatedResponse.create(mappedList.members, mappedList.total, mappedList.offset, mappedList.limit, schema); } public PaginatedResponseBuilder<ElementIn, ElementOut> withPaginationLinkCreator( PaginationLinkCreator paginationLinkCreator) { this.paginationLinkCreator = requireNonNull(paginationLinkCreator); return this; } public PaginatedResponseBuilder<ElementIn, ElementOut> withList(List<ElementIn> list, Integer offset, Integer limit) { paginatedList = ListSlicer.withDefaultInterval().create(offset, limit).createSliceOf(list); return this; } public PaginatedResponseBuilder<ElementIn, ElementOut> withList( PaginatedList<ElementIn> paginatedList) { this.paginatedList = paginatedList; return this; } }
38.77381
136
0.741787
1549015aa0e06f9eb7870f0a1ebbdc3b5384ab59
186
// PR#130 public aspect NoReturnTypeInDesignator { static after(): this(Point) && call(!static *(..)) { System.out.println( "after" ); } } class Point {}
14.307692
57
0.548387
79a7b56930091705f8c8193cfb320a7068694c8f
2,419
package com.LYH.algorithm; import java.util.Map; public class mazeDemo { public static void main(String[] args) { // 创建二维数组 int[][] map=new int[8][7]; // 初始化 for (int i = 0; i < 8; i++) { map[i][0]=1; map[i][6]=1; if (i<7){ map[0][i]=1; map[7][i]=1; } } map[5][5]=1; map[5][1]=1; Maze maze=new Maze(); // 展示初始地图 maze.showArray(map); // 设置起点 maze.setWay(map,1,1); // 展示找到结果后的地图 maze.showArray(map); } } class Maze{ // 整体思路:设置起始点,在起始点的基础上进行加减,以此来当做点的前后左右移动 // 走过的点用2标记,未走过的用0标记,死点(无法向0点移动的点)用3标记 // 其实整体来看,递归也是一种循环,一直循环同一个方法体 // 这里一直递归,每次移动都调用一下方法体本身,即递归一次 // 假设一个方向撞墙,则在此点的基础上进行其他方向的移动 // 若此点无法移动,为死点,则返回上一个点,在上一个点的基础上再进行移动 public boolean setWay(int[][] map,int i,int j){ if (map[4][5]==2){ // 每次递归,则判断是否到终点,终点为map[6][1],若到终点,则返回true,若不为终点,则进入下面的else中,进行移动寻找终点 System.out.println("已找到出口"); return true; }else { if (map[i][j]==0){ //判断当前点能否移动 map[i][j]=2; //当前点可以移动则向当前点移动,并标记此点为2 if (setWay(map,i+1,j)){ //向下移动,并进入下一次递归,若下一次依旧可以向下移动,则再进入下一次递归,若不能,则返回flase,即结束下一次的递归,并返回此次递归,并结束此次的if,进入下一个if // 若终点就在下面,则一直向下移动,到达终点的那次递归,进行上面的map[][]==2的if判断结果为true,则此处进入if结构体,则引链式反应,一直返回true,直到方法结束 return true; }else if (setWay(map,i,j+1)){ // 进入此次if,即向右移动依然和上面的一样的流程 return true; }else if (setWay(map,i-1,j)){ // 向上移动 return true; }else if (setWay(map,i,j-1)){ // 向左移动 return true; }else { // 若此点无法向标记为0的点移动,则标记此点为3 map[i][j]=3; return false; } }else { //不能则直接返回flase,返回上一个点 return false; } } } public void showArray(int [][] map){ // 遍历二维数组 for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[i].length; j++) { System.out.print(map[i][j]+" "); } System.out.println(); } } }
29.864198
110
0.440265
9d54fa6f6a192fc25be47f2582fe411f5bad6a26
567
package com.wust.iot.service; import com.wust.iot.model.ProjectIndustry; import org.springframework.stereotype.Service; import java.util.List; @Service public interface ProjectIndustryService { /** * 查找一条项目行业 * @param id * @return */ ProjectIndustry findOneProjectIndustry(Integer id); /** * 查找全部的项目行业 * @return */ List<ProjectIndustry> findProjectIndustryList(); /** * 新增一条项目行业 * @param projectIndustry * @return */ int insertOneProjectIndustry(ProjectIndustry projectIndustry); }
18.290323
66
0.666667
c7b616cd63a16c9a3a267abc81bb48e9273ecd5c
573
package com.searchservice.app.domain.port.api; import org.springframework.http.ResponseEntity; import com.searchservice.app.domain.dto.throttler.ThrottlerResponse; public interface InputDocumentServicePort { ThrottlerResponse addDocuments(boolean isNRT,String collectionName, String payload); ResponseEntity<ThrottlerResponse> performDocumentInjection(boolean isNrt, String tableName, String payload, ThrottlerResponse documentInjectionThrottlerResponse); ResponseEntity<ThrottlerResponse> documentInjectWithInvalidTableName(int tenantId, String tableName); }
35.8125
108
0.856894
0964ab2e3d7a1bee68d52c06d999ebd01f38ff97
1,102
package zone.fothu.pets.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.transaction.annotation.Transactional; import zone.fothu.pets.model.Image; public interface ImageRepository extends JpaRepository<Image, Integer> { @Modifying @Transactional @Query(nativeQuery = true, value = "INSERT INTO pets.images VALUES (DEFAULT, ?1)") void saveNewImage(String imageURL); @Query(nativeQuery = true, value = "SELECT MAX(id) FROM pets.images") int findLatestImageId(); @Query(nativeQuery = true, value = "SELECT * FROM pets.images WHERE id = ?1") Image findImageById(int imageId); @Query(nativeQuery = true, value = "SELECT * FROM pets.images WHERE image_url = ?1") Image findImageByURL(String imageURL); @Modifying @Transactional @Query(nativeQuery = true, value = "UPDATE pets.pets SET image_id = ?2 WHERE id = ?1") void setPetImage(int petId, int imageId); }
34.4375
90
0.724138
c7d3f7c8a45e5b07072b14d33a8826d2ec535081
1,018
package kin.backupandrestore.utils; import android.content.Context; import android.content.pm.ApplicationInfo; import android.view.View; import androidx.constraintlayout.widget.Group; public class ViewUtils { public static void registerToGroupOnClickListener(Group group, View root, View.OnClickListener listener) { int refIds[] = group.getReferencedIds(); for (int id : refIds) { root.findViewById(id).setOnClickListener(listener); } } public static void setGroupEnable(Group group, View root, boolean enable) { int refIds[] = group.getReferencedIds(); for (int id : refIds) { root.findViewById(id).setEnabled(enable); } } public static String getApplicationName(Context context) { ApplicationInfo applicationInfo = context.getApplicationInfo(); int stringId = applicationInfo.labelRes; return stringId == 0 ? applicationInfo.nonLocalizedLabel.toString() : context.getString(stringId); } }
31.8125
110
0.700393
87cf2b53573c53a047850b460b808e6768d324d5
1,480
package com.jtbdevelopment.games.security.spring.redirects; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; /** * Date: 6/2/15 Time: 3:32 PM */ public class MobileAwareFailureAuthenticationHandler extends SimpleUrlAuthenticationFailureHandler { protected static final Logger logger = LoggerFactory .getLogger(MobileAwareFailureAuthenticationHandler.class); private final MobileAppChecker checker; public MobileAwareFailureAuthenticationHandler(final MobileAppChecker checker) { this.checker = checker; } @Override public void onAuthenticationFailure(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException exception) throws IOException, ServletException { if (checker.isMobileRequest(request)) { logger.debug("Mobile flag, no failure url set, sending 401 Unauthorized error"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed: " + exception.getMessage()); } else { super.onAuthenticationFailure(request, response, exception); } } }
37
100
0.763514
82e6579ef9c153a78c53ff0e1235aed4edcaa5f9
1,391
package com.mengyunzhi.synthetical.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.math.BigDecimal; /** * 定价规则 */ @Entity public class Price { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; // 主键 private BigDecimal price; // 单位里程价格 private Float minKilometres; // 最低公里数 private Float maxKilometres; // 最高公里数 public Price() { } public Price(BigDecimal price, Float minKilometres, Float maxKilometres) { this.price = price; this.minKilometres = minKilometres; this.maxKilometres = maxKilometres; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public Float getMinKilometres() { return minKilometres; } public void setMinKilometres(Float minKilometres) { this.minKilometres = minKilometres; } public Float getMaxKilometres() { return maxKilometres; } public void setMaxKilometres(Float maxKilometres) { this.maxKilometres = maxKilometres; } }
21.075758
78
0.630482
bd2c93c815f0ef74ac8dde27c71bce260243f4b5
1,197
package org.batfish.vendor.check_point_management; import static com.google.common.base.MoreObjects.toStringHelper; import java.util.Map; import javax.annotation.Nonnull; import org.batfish.vendor.VendorSupplementalInformation; /** Configuration encompassing settings for all CheckPoint management servers in a snapshot. */ public final class CheckpointManagementConfiguration implements VendorSupplementalInformation { public CheckpointManagementConfiguration(Map<String, ManagementServer> servers) { _servers = servers; } public @Nonnull Map<String, ManagementServer> getServers() { return _servers; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof CheckpointManagementConfiguration)) { return false; } CheckpointManagementConfiguration that = (CheckpointManagementConfiguration) o; return _servers.equals(that._servers); } @Override public int hashCode() { return _servers.hashCode(); } @Override public String toString() { return toStringHelper(this).add("_servers", _servers).toString(); } private final @Nonnull Map<String, ManagementServer> _servers; }
27.204545
95
0.751044
e46311e25c9d517bd52ead2a9c80bbebb15ed153
8,221
package com.jeesuite.common.util; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import com.jeesuite.common.ThreadLocalContext; import com.jeesuite.common.WebConstants; import com.jeesuite.common.http.HttpMethod; import com.jeesuite.common.json.JsonUtils; public class WebUtils { private static final String POINT = "."; private static final String XML_HTTP_REQUEST = "XMLHttpRequest"; private static final String MULTIPART = "multipart/"; private static List<String> doubleDomainSuffixs = Arrays.asList(".com.cn",".org.cn",".net.cn"); //内网解析域名 private static List<String> internalDomains = ResourceUtils.getList("internal.dns.domains"); public static boolean isAjax(HttpServletRequest request){ return (request.getHeader(WebConstants.HEADER_REQUESTED_WITH) != null && XML_HTTP_REQUEST.equalsIgnoreCase(request.getHeader(WebConstants.HEADER_REQUESTED_WITH).toString())) ; } public static void responseOutJson(HttpServletResponse response,String json) { //将实体对象转换为JSON Object转换 response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); PrintWriter out = null; try { out = response.getWriter(); out.append(json); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } } } public static void responseOutHtml(HttpServletResponse response,String html) { //将实体对象转换为JSON Object转换 response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=utf-8"); PrintWriter out = null; try { out = response.getWriter(); out.append(html); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } } } public static void responseOutJsonp(HttpServletResponse response,String callbackFunName,Object jsonObject) { //将实体对象转换为JSON Object转换 response.setCharacterEncoding("UTF-8"); response.setContentType("text/plain; charset=utf-8"); PrintWriter out = null; String json = (jsonObject instanceof String) ? jsonObject.toString() : JsonUtils.toJson(jsonObject); String content = callbackFunName + "("+json+")"; try { out = response.getWriter(); out.append(content); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } } } /** * 获取根域名 * @param request * @return */ public static String getRootDomain(HttpServletRequest request) { String host = request.getHeader(WebConstants.HEADER_FORWARDED_HOST); if(StringUtils.isBlank(host))host = request.getServerName(); return parseHostRootDomain(host); } public static String getRootDomain(String url) { String host = getDomain(url); return parseHostRootDomain(host); } private static String parseHostRootDomain(String host){ if(IpUtils.isIp(host) || IpUtils.LOCAL_HOST.equals(host)){ return host; } String[] segs = StringUtils.split(host, POINT); int len = segs.length; if(doubleDomainSuffixs.stream().anyMatch(e -> host.endsWith(e))){ return segs[len - 3] + POINT + segs[len - 2] + POINT + segs[len - 1]; } return segs[len - 2] + POINT + segs[len - 1]; } public static String getDomain(String url) { String[] urlSegs = StringUtils.split(url,"/"); return urlSegs[1]; } public static String getBaseUrl(String url) { String[] segs = StringUtils.split(url,"/"); return segs[0] + "//" + segs[1]; } public static String getBaseUrl(HttpServletRequest request){ return getBaseUrl(request, true); } /** * 获取baseurl<br> * nginx转发需设置 proxy_set_header X-Forwarded-Proto $scheme; * @param request * @param withContextPath * @return */ public static String getBaseUrl(HttpServletRequest request,boolean withContextPath){ String baseUrl = null; String schame = request.getHeader(WebConstants.HEADER_FORWARDED_PROTO); String host = request.getHeader(WebConstants.HEADER_FORWARDED_HOST); String prefix = request.getHeader(WebConstants.HEADER_FORWARDED_PRIFIX); if(StringUtils.isBlank(host)){ String[] segs = StringUtils.split(request.getRequestURL().toString(),"/"); baseUrl = segs[0] + "//" + segs[1]; }else{ if(StringUtils.isBlank(schame)){ String port = request.getHeader(WebConstants.HEADER_FORWARDED_PORT); schame = "443".equals(port) ? "https://" : "http://"; }else{ if(schame.contains(",")){ schame = StringUtils.split(schame, ",")[0]; } schame = schame + "://"; } if(host.contains(",")){ host = StringUtils.split(host, ",")[0]; } baseUrl = schame + host + StringUtils.trimToEmpty(prefix); } if(withContextPath && StringUtils.isNotBlank(request.getContextPath())){ baseUrl = baseUrl + request.getContextPath(); } return baseUrl; } public static Map<String, String> getCustomHeaders(){ Map<String, String> headers = new HashMap<>(); HttpServletRequest request = ThreadLocalContext.get(ThreadLocalContext.REQUEST_KEY); if(request == null)return headers; Enumeration<String> headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()){ String headerName = headerNames.nextElement().toLowerCase(); if(headerName.startsWith(WebConstants.HEADER_PREFIX)){ String headerValue = request.getHeader(headerName); if(headerValue != null)headers.put(headerName, headerValue); } } return headers; } public static final boolean isMultipartContent(HttpServletRequest request) { if (!HttpMethod.POST.name().equalsIgnoreCase(request.getMethod())) { return false; } String contentType = request.getContentType(); if (contentType == null) { return false; } contentType = contentType.toLowerCase(Locale.ENGLISH); if (contentType.startsWith(MULTIPART) || "application/octet-stream".equals(contentType)) { return true; } return false; } /** * 是否内网调用 * @param request * @return */ public static boolean isInternalRequest(HttpServletRequest request){ // String headerValue = request.getHeader(WebConstants.HEADER_INTERNAL_REQUEST); if(StringUtils.isNotBlank(headerValue)){ try { TokenGenerator.validate(headerValue, true); } catch (Exception e) { headerValue = null; } } if(headerValue != null && Boolean.parseBoolean(headerValue)){ return true; } //从网关转发 headerValue = request.getHeader(WebConstants.HEADER_GATEWAY_TOKEN); if(StringUtils.isNotBlank(headerValue)){ try { TokenGenerator.validate(headerValue, true); } catch (Exception e) { headerValue = null; } } if(StringUtils.isNotBlank(headerValue)){ return false; } String clientIp = request.getHeader(WebConstants.HEADER_REAL_IP); if(clientIp == null)clientIp = IpUtils.getIpAddr(request); if(IpUtils.isInnerIp(clientIp)) { return true; } boolean isInner = IpUtils.isInnerIp(request.getServerName()); if(!isInner && !internalDomains.isEmpty()){ isInner = internalDomains.stream().anyMatch(domain -> request.getServerName().endsWith(domain)); } return isInner; } public static void printRequest(HttpServletRequest request) { System.out.println("============Request start=============="); System.out.println("uri:" + request.getRequestURI()); System.out.println("method:" + request.getMethod()); Enumeration<String> headerNames = request.getHeaderNames(); String headerName; while(headerNames.hasMoreElements()) { headerName = headerNames.nextElement(); System.out.println(String.format("Header %s = %s", headerName,request.getHeader(headerName))); } System.out.println("============Request end=============="); } }
30.790262
112
0.679358
e5fa37e701a83f4102ba277baa6dd3b5e8fecd39
914
package approdictio.dict; /** * <p> * is the exception thrown if a file read does contain format errors. * </p> */ public class FileFormatException extends Exception { private final int lineNo; private final String msg; private String filename = "stream without name"; public FileFormatException(String msg, int lineNo, Throwable e) { this.msg = msg; this.lineNo = lineNo; if (e!=null) { initCause(e); } } public FileFormatException(String msg, int lineNo) { this(msg, lineNo, null); } public void setFilename(String filename) { this.filename = filename; } /** * <p>the number of the line with the error</p> * @return the error line number */ public int getLineNo() { return lineNo; } public String getFilename() { return filename; } @Override public String getMessage() { return String.format("%s(%s): %s", filename, lineNo, msg); } }
25.388889
69
0.66302
5e2dd9dc0bf8c6f785aa9622c8503e6ad6923c5e
109
package net.redbear.module.communicate; /** * Created by Dong on 16/1/28. */ public class DuoVersion { }
12.111111
39
0.688073
3e0a227525dc60fb39d82502bca5295b641b671a
4,816
package nl.m4jit.tradetoday.presentation.transactions; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.JOptionPane; import javax.swing.JTextField; import nl.m4jit.framework.ValidationException; import nl.m4jit.framework.presentation.swing.abstractdialogs.RecordDialog; import nl.m4jit.tradetoday.dataaccess.members.MemberGateway; import nl.m4jit.tradetoday.dataaccess.members.MemberTable; import nl.m4jit.tradetoday.dataaccess.transactions.TransactionGateway; import nl.m4jit.tradetoday.domainlogic.Application; import nl.m4jit.tradetoday.domainlogic.members.MemberModule; import nl.m4jit.tradetoday.domainlogic.transactions.TransactionModule; public class ServiceTransactionIFrame extends RecordDialog<TransactionGateway>{ private MemberGateway fromMember, toMember; public ServiceTransactionIFrame(){ super(new String[]{"25dlu", "75dlu"}, 5); addLabel("Afnemer:"); addTextField("fromnumber", 1); JTextField fromNameField = addTextField("fromname", 1); fromNameField.setEditable(false); fromNameField.addFocusListener(this); addLabel("Datum:"); addFormattedTextField("date", new SimpleDateFormat("d-M-yyyy"), 2); addLabel("Dienst:"); addTextField("service", 2); addLabel("Aanbieder:"); addTextField("tonumber", 1); JTextField toNameField = addTextField("toname", 1); toNameField.setEditable(false); toNameField.addFocusListener(this); addLabel("Punten:"); addTextField("points", 1); setUI(); } @Override public String getScreenTitle(boolean isNew) { return "Dienstverling invoeren"; } @Override public String getNotificationMessge(boolean isNew) { return "Dienstverling ingevoerd"; } @Override public Object getValue(String name) { if (name.equals("date")) { return Application.getInstance().getDefaultDate(); } else { return ""; } } @Override public void focusGainedEvent(String name) { if (name.equals("fromname")) { int number = Integer.parseInt(getTextValue("fromnumber")); MemberGateway tempMember = MemberTable.getInstance().retreive(number); if (tempMember == null) { setFocusOnComponent("fromnumber"); JOptionPane.showMessageDialog(this, "Lid niet gevonden"); } else if (tempMember.getDeregistrationdate() == null) { fromMember = tempMember; setTextValue("fromname", MemberModule.getFullname(fromMember)); setFocusOnComponent("date"); } else { setFocusOnComponent("fromnumber"); JOptionPane.showMessageDialog(this, "Lid is uitgeschreven"); } } else if (name.equals("toname")) { int number = Integer.parseInt(getTextValue("tonumber")); MemberGateway tempMember = MemberTable.getInstance().retreive(number); if (tempMember == null) { setFocusOnComponent("tonumber"); JOptionPane.showMessageDialog(this, "Lid niet gevonden"); } else if (tempMember.getDeregistrationdate() == null) { toMember = tempMember; setTextValue("toname", MemberModule.getFullname(toMember)); setFocusOnComponent("points"); } else { setFocusOnComponent("tonumber"); JOptionPane.showMessageDialog(this, "Lid is uitgeschreven"); } } } @Override protected TransactionGateway create() { String service = "Dienst: " + getTextValue("service"); Date date = (Date) getFormattedTextFieldValue("date"); int points = Integer.parseInt(getTextValue("points")); try{ return TransactionModule.getInstance().makeSimpleTransaction(fromMember, toMember, points, "S", service, date); }catch(ValidationException ex){ String message = ex.getMessage(); if(message.equals("no client")){ giveMessageAndSetFocus("Geen afnemer opgegeven", "fromnumber"); }else if(message.equals("no description")){ giveMessageAndSetFocus("Geen omschrijving opgegeven", "service"); }else if(message.equals("no provider")){ giveMessageAndSetFocus("Geen aanbieder opgegeven", "tonumber"); } return null; } } @Override protected void update() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
31.272727
135
0.627907
3248f26c0a2380b5d9fe816e37babbd3e0684f39
3,378
package fr.univnantes.termsuite.eval.bilangaligner; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Stream; import org.assertj.core.util.Lists; import fr.univnantes.termsuite.eval.TermSuiteEvals; import fr.univnantes.termsuite.eval.model.Corpus; import fr.univnantes.termsuite.eval.model.LangPair; import fr.univnantes.termsuite.eval.resources.Tsv3ColFile; import fr.univnantes.termsuite.model.Lang; public class AlignmentEvalService { public Tsv3ColFile getRefFile(AlignmentEvalRun run) { return new Tsv3ColFile(getRefFilePath(run.getCorpus(), run.getLangPair())); } private Path getRefFilePath(Corpus corpus, LangPair pair) { return Paths.get("src", "eval", "resources", "refs", corpus.getFullName(), String.format("%s-%s-%s.tsv", corpus.getShortName(), pair.getSource().getCode(), pair.getTarget().getCode()) ); } public boolean hasRef(Corpus corpus, LangPair pair) { return getRefFilePath(corpus, pair).toFile().exists(); } public boolean hasAnyRefForLangPair(LangPair pair) { for(Corpus corpus:Corpus.values()) if(hasRef(corpus, pair)) return true; return false; } public Stream<LangPair> langPairs() { List<LangPair> pairs = Lists.newArrayList(); for(Lang source:Lang.values()) { for(Lang target:Lang.values()) { LangPair pair = new LangPair(source, target); if(hasAnyRefForLangPair(pair)) pairs.add(pair); } } return pairs.stream(); } public Path getLangPairPath(LangPair langPair) { Path path = TermSuiteEvals.getAlignmentDirectory().resolve(langPair.toString()); path.toFile().mkdirs(); return path; } public Path getEvaluatedMethodPath(LangPair langPair, EvaluatedMethod evaluatedMethod) { Path path = getLangPairPath(langPair).resolve(evaluatedMethod.toString()); path.toFile().mkdirs(); return path; } public void saveRunTrace(AlignmentEvalRun run) throws IOException { try(Writer writer = new FileWriter(getRunTracePath(run).toFile())) { writer.write(AlignmentRecord.toOneLineHeaders()); writer.write('\n'); run.getTrace().tries().forEach(e -> { try { writer.write(e.toOneLineString()); writer.write('\n'); } catch (IOException e1) { throw new RuntimeException(e1); } }); } } public Path getRunTracePath(AlignmentEvalRun run) { return getEvaluatedMethodPath(run.getLangPair(), run.getEvaluatedMethod()).resolve( String.format("%s-%s", run.getCorpus(), run.getTerminoConfig())); } public Writer getResultWriter(LangPair langPair, EvaluatedMethod evaluatedMethod) throws IOException { Path resultPath = getEvaluatedMethodPath(langPair, evaluatedMethod).resolve("results.txt"); FileWriter writer = new FileWriter(resultPath.toFile()); writer.write(String.format("%s\t%s\t%s\t%s\t%s%n", "run", "pr", "tot", "suc", "ign" )); return writer; } public void writeResultLine(Writer resultWriter, AlignmentEvalRun run) throws IOException { RunTrace trace = run.getTrace(); resultWriter.write(String.format("%s\t%.2f\t%d\t%d\t%d%n", run.getName(), trace.getPrecision(), trace.validResults().count(), trace.successResults().count(), trace.invalidResults().count() )); resultWriter.flush(); } }
28.627119
103
0.712848
64be949334f583aa5bca96063f9b9effd6e20be3
3,755
/* * JBoss, Home of Professional Open Source * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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.hibernate.validator.ap.checks; import java.util.Set; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; /** * <p> * Implementations represent checks, which determine whether a given constraint * annotation is allowed at a given element. * </p> * <p> * Implementations should be derived from {@link AbstractConstraintCheck} in * order to implement only those check methods applicable for the element kinds * supported by the check. * </p> * * @author Gunnar Morling */ public interface ConstraintCheck { /** * Checks, whether the given annotation is allowed at the given field. * * @param element An annotated field. * @param annotation An annotation at that field. * * @return A set with errors, that describe, why the given annotation is * not allowed at the given element. In case no errors occur (the * given annotation is allowed at the given element), an empty set * must be returned. */ Set<ConstraintCheckError> checkField(VariableElement element, AnnotationMirror annotation); /** * Checks, whether the given annotation is allowed at the given method. * * @param element An annotated method. * @param annotation An annotation at that method. * * @return A set with errors, that describe, why the given annotation is * not allowed at the given element. In case no errors occur (the * given annotation is allowed at the given element), an empty set * must be returned. */ Set<ConstraintCheckError> checkMethod(ExecutableElement element, AnnotationMirror annotation); /** * Checks, whether the given annotation is allowed at the given annotation * type declaration. * * @param element An annotated annotation type declaration. * @param annotation An annotation at that annotation type. * * @return A set with errors, that describe, why the given annotation is * not allowed at the given element. In case no errors occur (the * given annotation is allowed at the given element), an empty set * must be returned. */ Set<ConstraintCheckError> checkAnnotationType(TypeElement element, AnnotationMirror annotation); /** * Checks, whether the given annotation is allowed at the given type * declaration (class, interface, enum). * * @param element An annotated type declaration. * @param annotation An annotation at that type. * * @return A set with errors, that describe, why the given annotation is * not allowed at the given element. In case no errors occur (the * given annotation is allowed at the given element), an empty set * must be returned. */ Set<ConstraintCheckError> checkNonAnnotationType(TypeElement element, AnnotationMirror annotation); }
37.929293
79
0.720373
0f52a1349ec684cbea681acc5d348abf2c1061b6
2,054
package fr.xebia.streams.java.transform; import org.bytedeco.javacpp.opencv_core; import org.bytedeco.javacv.Frame; import org.bytedeco.javacv.OpenCVFrameConverter; import java.util.function.Supplier; public class MediaConversion { public static opencv_core.Mat toMat(Frame frame){ OpenCVFrameConverter.ToMat toMat = new OpenCVFrameConverter.ToMat(); return toMat.convert(frame); } public static Frame toFrame(opencv_core.Mat mat){ OpenCVFrameConverter.ToMat toMat = new OpenCVFrameConverter.ToMat(); return toMat.convert(mat); } public static opencv_core.IplImage matToIplImage(opencv_core.Mat mat){ OpenCVFrameConverter.ToIplImage toIplImage = new OpenCVFrameConverter.ToIplImage(); return toIplImage.convert(toFrame(mat)); } public static Frame iplImageToFrame(opencv_core.IplImage iplImage){ OpenCVFrameConverter.ToIplImage toIplImage = new OpenCVFrameConverter.ToIplImage(); return toIplImage.convert(iplImage); } public static opencv_core.Mat iplImageToMat(opencv_core.IplImage image){ return toMat(iplImageToFrame(image)); } //(iplImageToFrame _ andThen frameToMat)(image)*/ /* private val frameToMatConverter = ThreadLocal.withInitial(new Supplier[OpenCVFrameConverter.ToMat] { def get(): OpenCVFrameConverter.ToMat = new OpenCVFrameConverter.ToMat }) private val bytesToMatConverter = ThreadLocal.withInitial(new Supplier[OpenCVFrameConverter.ToIplImage] { def get(): OpenCVFrameConverter.ToIplImage = new OpenCVFrameConverter.ToIplImage }) def frameToMat(frame: Frame): Mat = frameToMatConverter.get().convert(frame) def matToFrame(mat: Mat): Frame = frameToMatConverter.get().convert(mat) def matToIplImage(mat: Mat): IplImage = bytesToMatConverter.get().convert(matToFrame(mat)) def iplImageToFrame(image: IplImage): Frame = bytesToMatConverter.get().convert(image) def iplImageToMat(image: IplImage): Mat = (iplImageToFrame _ andThen frameToMat)(image)*/ }
38.037037
109
0.747322
229fc29826d8ed479325f0cccd4e967b00ab11c7
1,748
package com.xyoye.dandanplay.bean; import android.support.annotation.NonNull; import java.io.Serializable; /** * Created by xyoye on 2018/11/19. */ public class LanDeviceBean implements Comparable<LanDeviceBean>,Serializable{ private String ip; private String deviceName; private String domain; private String account; private String password; private boolean anonymous; public LanDeviceBean() { } public LanDeviceBean(String ip, String deviceName) { this.ip = ip; this.deviceName = deviceName; } public LanDeviceBean(String account, String password, boolean anonymous){ this.account = account; this.password = password; this.anonymous = anonymous; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getDeviceName() { return deviceName; } public void setDeviceName(String deviceName) { this.deviceName = deviceName; } public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isAnonymous() { return anonymous; } public void setAnonymous(boolean anonymous) { this.anonymous = anonymous; } @Override public int compareTo(@NonNull LanDeviceBean o) { return ip.compareTo(o.ip); } }
20.325581
77
0.631579
aba624e79eca23b1bf35bc532a32d1514ee2a28b
5,957
/* * Copyright (C) 2017 Synacts GmbH, Switzerland (info@synacts.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.digitalid.utility.functional.failable; import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.digitalid.utility.annotations.generics.Specifiable; import net.digitalid.utility.annotations.generics.Unspecifiable; import net.digitalid.utility.annotations.method.Pure; import net.digitalid.utility.annotations.ownership.Captured; import net.digitalid.utility.functional.interfaces.BinaryOperator; import net.digitalid.utility.functional.interfaces.Consumer; import net.digitalid.utility.validation.annotations.type.Functional; import net.digitalid.utility.validation.annotations.type.Immutable; /** * This functional interface models a failable binary operator that maps two objects of type {@code TYPE} to another object of type {@code TYPE}. */ @Immutable @Functional public interface FailableBinaryOperator<@Specifiable TYPE, @Unspecifiable EXCEPTION extends Exception> extends FailableBinaryFunction<TYPE, TYPE, TYPE, EXCEPTION> { /* -------------------------------------------------- Suppression -------------------------------------------------- */ @Pure @Override public default @Nonnull BinaryOperator<TYPE> suppressExceptions(@Captured @Nonnull Consumer<@Nonnull ? super Exception> handler, @Captured TYPE defaultOutput) { return (input0, input1) -> { try { return evaluate(input0, input1); } catch (@Nonnull Exception exception) { handler.consume(exception); return defaultOutput; } }; } @Pure @Override public default @Nonnull BinaryOperator<@Nullable TYPE> suppressExceptions(@Captured @Nonnull Consumer<@Nonnull ? super Exception> handler) { return suppressExceptions(handler, null); } @Pure @Override public default @Nonnull BinaryOperator<TYPE> suppressExceptions(@Captured TYPE defaultOutput) { return suppressExceptions(Consumer.DO_NOTHING, defaultOutput); } @Pure @Override public default @Nonnull BinaryOperator<@Nullable TYPE> suppressExceptions() { return suppressExceptions(Consumer.DO_NOTHING, null); } /* -------------------------------------------------- Composition -------------------------------------------------- */ /** * Returns the composition of the given operators with a flexible exception type. */ @Pure public static <@Specifiable TYPE, @Unspecifiable EXCEPTION extends Exception> @Nonnull FailableBinaryOperator<TYPE, EXCEPTION> compose(@Nonnull FailableBinaryOperator<TYPE, ? extends EXCEPTION> binaryOperator, @Nonnull FailableUnaryOperator<TYPE, ? extends EXCEPTION> unaryOperator) { return (input0, input1) -> unaryOperator.evaluate(binaryOperator.evaluate(input0, input1)); } /** * Returns the composition of this operator followed by the given operator. * Unfortunately, it is not possible to make the exception type flexible. * * @see #compose(net.digitalid.utility.functional.failable.FailableBinaryOperator, net.digitalid.utility.functional.failable.FailableUnaryOperator) */ @Pure public default @Nonnull FailableBinaryOperator<TYPE, EXCEPTION> before(@Nonnull FailableUnaryOperator<TYPE, ? extends EXCEPTION> operator) { return (input0, input1) -> operator.evaluate(evaluate(input0, input1)); } /** * Returns the composition of the given operators with a flexible exception type. */ @Pure public static <@Specifiable TYPE, @Unspecifiable EXCEPTION extends Exception> @Nonnull FailableBinaryOperator<TYPE, EXCEPTION> compose(@Nonnull FailableUnaryOperator<TYPE, ? extends EXCEPTION> unaryOperator0, @Nonnull FailableUnaryOperator<TYPE, ? extends EXCEPTION> unaryOperator1, @Nonnull FailableBinaryOperator<TYPE, ? extends EXCEPTION> binaryOperator) { return (input0, input1) -> binaryOperator.evaluate(unaryOperator0.evaluate(input0), unaryOperator1.evaluate(input1)); } /** * Returns the composition of the given operators followed by this operator. * Unfortunately, it is not possible to make the exception type flexible. * * @see #compose(net.digitalid.utility.functional.failable.FailableUnaryOperator, net.digitalid.utility.functional.failable.FailableUnaryOperator, net.digitalid.utility.functional.failable.FailableBinaryOperator) */ @Pure public default @Nonnull FailableBinaryOperator<TYPE, EXCEPTION> after(@Nonnull FailableUnaryOperator<TYPE, ? extends EXCEPTION> operator0, @Nonnull FailableUnaryOperator<TYPE, ? extends EXCEPTION> operator1) { return (input0, input1) -> evaluate(operator0.evaluate(input0), operator1.evaluate(input1)); } /* -------------------------------------------------- Null Handling -------------------------------------------------- */ @Pure @Override public default @Nonnull FailableBinaryOperator<@Nullable TYPE, EXCEPTION> replaceNull(@Captured TYPE defaultOutput) { return (input0, input1) -> input0 != null && input1 != null ? evaluate(input0, input1) : defaultOutput; } @Pure @Override public default @Nonnull FailableBinaryOperator<@Nullable TYPE, EXCEPTION> propagateNull() { return replaceNull(null); } }
47.656
363
0.692463
804d3972f651c0a208f6ed668909f361ea8ce8dd
1,021
package sune.ssp.util; public class TypeUtils { public static Class<?>[] recognizeClasses(Object... arguments) { int length = arguments.length; Class<?>[] classes = new Class<?>[length]; for(int i = 0; i < length; ++i) { Object argument; if((argument = arguments[i]) == null) { classes[i] = Object.class; continue; } Class<?> clazz = argument.getClass(); classes[i] = toPrimitive(clazz); } return classes; } public static Class<?> toPrimitive(Class<?> clazz) { if(clazz == Boolean.class) return boolean.class; if(clazz == Character.class) return char.class; if(clazz == Byte.class) return byte.class; if(clazz == Short.class) return short.class; if(clazz == Integer.class) return int.class; if(clazz == Long.class) return long.class; if(clazz == Float.class) return float.class; if(clazz == Double.class) return double.class; if(clazz == Void.class) return void.class; return clazz; } }
31.90625
65
0.616063
42caecb207ccfaaa2b43d0e7892012ae6b05b2ed
846
package org.vertexium.inmemory; import org.vertexium.util.ConvertingIterable; import java.util.Map; public class InMemoryEdgeTable extends InMemoryTable<InMemoryEdge> { public InMemoryEdgeTable(Map<String, InMemoryTableElement<InMemoryEdge>> rows) { super(rows); } public InMemoryEdgeTable() { } @Override protected InMemoryTableElement<InMemoryEdge> createInMemoryTableElement(String id) { return new InMemoryTableEdge(id); } public Iterable<InMemoryTableEdge> getAllTableElements() { return new ConvertingIterable<InMemoryTableElement<InMemoryEdge>, InMemoryTableEdge>(super.getRowValues()) { @Override protected InMemoryTableEdge convert(InMemoryTableElement<InMemoryEdge> o) { return (InMemoryTableEdge) o; } }; } }
29.172414
116
0.704492
1ca05e750ee510e12f018f4e4adc670d0e7feb29
2,329
package com.sequenceiq.cloudbreak.service.hostgroup; import static com.sequenceiq.cloudbreak.exception.NotFoundException.notFound; import java.util.Optional; import java.util.Set; import javax.inject.Inject; import org.springframework.stereotype.Service; import com.sequenceiq.cloudbreak.common.type.HostMetadataState; import com.sequenceiq.cloudbreak.domain.stack.cluster.host.HostGroup; import com.sequenceiq.cloudbreak.domain.stack.cluster.host.HostMetadata; import com.sequenceiq.cloudbreak.repository.HostGroupRepository; import com.sequenceiq.cloudbreak.service.hostmetadata.HostMetadataService; @Service public class HostGroupService { @Inject private HostGroupRepository hostGroupRepository; @Inject private HostMetadataService hostMetadataService; public Set<HostGroup> getByCluster(Long clusterId) { return hostGroupRepository.findHostGroupsInCluster(clusterId); } public Optional<HostGroup> findHostGroupInClusterByName(Long clusterId, String hostGroupName) { return hostGroupRepository.findHostGroupInClusterByName(clusterId, hostGroupName); } public HostGroup save(HostGroup hostGroup) { return hostGroupRepository.save(hostGroup); } public Set<HostMetadata> findEmptyHostMetadataInHostGroup(Long hostGroupId) { return hostMetadataService.findEmptyHostsInHostGroup(hostGroupId); } public Optional<HostGroup> getByClusterIdAndInstanceGroupName(Long clusterId, String instanceGroupName) { return hostGroupRepository.findHostGroupsByInstanceGroupName(clusterId, instanceGroupName); } public void updateHostMetaDataStatus(Long id, HostMetadataState status) { HostMetadata hostMetadata = hostMetadataService.findById(id) .orElseThrow(notFound("HostMetadata", id)); hostMetadata.setHostMetadataState(status); hostMetadataService.save(hostMetadata); } public Set<HostGroup> findHostGroupsInCluster(Long clusterId) { return hostGroupRepository.findHostGroupsInCluster(clusterId); } public void deleteAll(Iterable<HostGroup> hostGroups) { hostGroupRepository.deleteAll(hostGroups); } public Set<HostGroup> findAllHostGroupsByRecipe(Long recipeId) { return hostGroupRepository.findAllHostGroupsByRecipe(recipeId); } }
35.830769
109
0.784457
31e03abd402d2f2f35c82c3ac1daefa97c4024fc
2,523
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.openanalytics_open.model.v20180619; import com.aliyuncs.AcsResponse; import com.aliyuncs.openanalytics_open.transform.v20180619.GetDLAServiceStatusResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class GetDLAServiceStatusResponse extends AcsResponse { private String requestId; private String regionId; private UserDLAServiceStatus userDLAServiceStatus; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getRegionId() { return this.regionId; } public void setRegionId(String regionId) { this.regionId = regionId; } public UserDLAServiceStatus getUserDLAServiceStatus() { return this.userDLAServiceStatus; } public void setUserDLAServiceStatus(UserDLAServiceStatus userDLAServiceStatus) { this.userDLAServiceStatus = userDLAServiceStatus; } public static class UserDLAServiceStatus { private Boolean isServiceReady; private Boolean isOSSOpen; private Boolean isDLAAccountReady; public Boolean getIsServiceReady() { return this.isServiceReady; } public void setIsServiceReady(Boolean isServiceReady) { this.isServiceReady = isServiceReady; } public Boolean getIsOSSOpen() { return this.isOSSOpen; } public void setIsOSSOpen(Boolean isOSSOpen) { this.isOSSOpen = isOSSOpen; } public Boolean getIsDLAAccountReady() { return this.isDLAAccountReady; } public void setIsDLAAccountReady(Boolean isDLAAccountReady) { this.isDLAAccountReady = isDLAAccountReady; } } @Override public GetDLAServiceStatusResponse getInstance(UnmarshallerContext context) { return GetDLAServiceStatusResponseUnmarshaller.unmarshall(this, context); } @Override public boolean checkShowJsonItemName() { return false; } }
25.23
99
0.753072
b4f32ad57a12b6a85a7b50a9dae15dc5749aa1b8
975
package net.liaocy.smartcar; import android.app.Application; import net.liaocy.smartcar.biz.BizSensor; import net.liaocy.smartcar.biz.BizSpeaker; public class AppContext extends Application { private static AppContext instance; private BizSpeaker bizSpeaker; private BizSensor bizSensor; public BizSpeaker getBizSpeaker() { return this.bizSpeaker; } public BizSensor getBizSensor() { return this.bizSensor; } public static AppContext getInstance() { return instance; } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); instance = this; //init and start bizSpeaker bizSpeaker = new BizSpeaker(this); //init and start bizSpeaker -- end //init and start sensor monitors this.bizSensor = new BizSensor(this); this.bizSensor.start(); //init and start sensor monitors -- end } }
22.159091
47
0.65641
ecc765ec9cd0c7f263eb2fe2b55262cb6f68daf7
3,856
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sling.auth.core.impl; import static org.apache.sling.auth.core.impl.FailureCodesMapper.getFailureReason; import javax.jcr.SimpleCredentials; import javax.security.auth.login.AccountLockedException; import javax.security.auth.login.AccountNotFoundException; import javax.security.auth.login.CredentialExpiredException; import org.apache.sling.api.resource.LoginException; import org.apache.sling.auth.core.spi.AuthenticationHandler.FAILURE_REASON_CODES; import org.apache.sling.auth.core.spi.AuthenticationInfo; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Test; public class FailureCodesMapperTest { private final AuthenticationInfo dummyAuthInfo = new AuthenticationInfo("dummy"); @Test public void unknown() { MatcherAssert.assertThat( getFailureReason(dummyAuthInfo, new RuntimeException()), CoreMatchers.equalTo(FAILURE_REASON_CODES.UNKNOWN)); } @Test public void loginExceptionWithNoCause() { MatcherAssert.assertThat( getFailureReason(dummyAuthInfo, new LoginException("Something went wrong")), CoreMatchers.equalTo(FAILURE_REASON_CODES.INVALID_LOGIN)); } @Test public void passwordExpired() { MatcherAssert.assertThat( getFailureReason(dummyAuthInfo, new LoginException(new CredentialExpiredException())), CoreMatchers.equalTo(FAILURE_REASON_CODES.PASSWORD_EXPIRED)); } @Test public void accountLocked() { MatcherAssert.assertThat( getFailureReason(dummyAuthInfo, new LoginException(new AccountLockedException())), CoreMatchers.equalTo(FAILURE_REASON_CODES.ACCOUNT_LOCKED)); } @Test public void accountNotFound() { MatcherAssert.assertThat( getFailureReason(dummyAuthInfo, new LoginException(new AccountNotFoundException())), CoreMatchers.equalTo(FAILURE_REASON_CODES.ACCOUNT_NOT_FOUND)); } @Test public void expiredToken() { MatcherAssert.assertThat( getFailureReason(dummyAuthInfo, new LoginException(new TokenCredentialsExpiredException())), CoreMatchers.equalTo(FAILURE_REASON_CODES.EXPIRED_TOKEN)); } @Test public void passwordExpiredAndNewPasswordInHistory() { AuthenticationInfo info = new AuthenticationInfo("dummy"); SimpleCredentials credentials = new SimpleCredentials("ignored", "ignored".toCharArray()); credentials.setAttribute("PasswordHistoryException", new Object()); // value is not checked info.put("user.jcr.credentials", credentials); MatcherAssert.assertThat( getFailureReason(info, new LoginException(new CredentialExpiredException())), CoreMatchers.equalTo(FAILURE_REASON_CODES.PASSWORD_EXPIRED_AND_NEW_PASSWORD_IN_HISTORY)); } // doubles for an Oak class static class TokenCredentialsExpiredException extends Exception { private static final long serialVersionUID = 1L; } }
37.803922
104
0.739627
53a2b064e82edb9ddf5c6e546c85b25cb3d508e1
397
import java.lang.reflect.Modifier; import static org.junit.Assert.*; import org.junit.Test; /** * The test class CheckersTests. * * @author (your name) * @version (a version number or a date) */ public class CheckersTests { CheckerBoard buildInitial() { return new CheckerBoard(); } @Test(timeout=1000) public void testConstructor() { buildIntial(); } }
17.26087
52
0.654912
cbc146b4ffd3e31077e488bb4de025fe6c71415f
3,842
import org.junit.*; import static org.junit.Assert.*; public class YatzyTest { public Yatzy yatzy; @Test public void chance_scores_sum_of_all_dice() { int expected = 15; int actual = Yatzy.initGamePlayer(1,2,3,4,5).chance(); assertEquals(expected, actual); assertEquals(16, Yatzy.initGamePlayer(3,3,4,5,1).chance()); } @Test public void yatzy_scores_50() { int expected = 50; int actual = Yatzy.initGamePlayer(4,4,4,4,4).yatzy(); assertEquals(expected, actual); assertEquals(50, Yatzy.initGamePlayer(6,6,6,6,6).yatzy()); assertEquals(0, Yatzy.initGamePlayer(6,6,6,6,3).yatzy()); } @Test public void test_1s() { assertEquals(Yatzy.initGamePlayer(1,2,3,4,5).ones(), 1); assertEquals(Yatzy.initGamePlayer(1,2,1,4,5).ones(), 2); assertEquals(Yatzy.initGamePlayer(6,2,2,4,5).ones(), 0); assertEquals(Yatzy.initGamePlayer(1,2,1,1,1).ones(), 4); } @Test public void test_2s() { assertEquals(4, Yatzy.initGamePlayer(1,2,3,2,6).twos()); assertEquals(10, Yatzy.initGamePlayer(2,2,2,2,2).twos()); } @Test public void test_threes() { assertEquals(6, Yatzy.initGamePlayer(1,2,3,2,3).threes()); assertEquals(12, Yatzy.initGamePlayer(2,3,3,3,3).threes()); } @Test public void fours_test() { assertEquals(12, Yatzy.initGamePlayer(4,4,4,5,5).fours()); assertEquals(8, Yatzy.initGamePlayer(4,4,5,5,5).fours()); assertEquals(4, Yatzy.initGamePlayer(4,5,5,5,5).fours()); } @Test public void fives() { assertEquals(10, Yatzy.initGamePlayer(4,4,4,5,5).fives()); assertEquals(15, Yatzy.initGamePlayer(4,4,5,5,5).fives()); assertEquals(20, Yatzy.initGamePlayer(4,5,5,5,5).fives()); } @Test public void sixes_test() { assertEquals(0, Yatzy.initGamePlayer(4,4,4,5,5).sixes()); assertEquals(6, Yatzy.initGamePlayer(4,4,6,5,5).sixes()); assertEquals(18, Yatzy.initGamePlayer(6,5,6,6,5).sixes()); } @Test public void one_pair() { assertEquals(6, Yatzy.initGamePlayer(3,4,3,5,6).score_pair()); assertEquals(10, Yatzy.initGamePlayer(5,3,3,3,5).score_pair()); assertEquals(12, Yatzy.initGamePlayer(5,3,6,6,5).score_pair()); } @Test public void two_Pair() { assertEquals(16, Yatzy.initGamePlayer(3,3,5,4,5).two_pair()); assertEquals(16, Yatzy.initGamePlayer(3,3,5,5,5).two_pair()); } @Test public void three_of_a_kind() { assertEquals(9, Yatzy.initGamePlayer(3,3,3,4,5).three_of_a_kind()); assertEquals(15, Yatzy.initGamePlayer(5,3,5,4,5).three_of_a_kind()); assertEquals(9, Yatzy.initGamePlayer(3,3,3,3,5).three_of_a_kind()); assertEquals(9, Yatzy.initGamePlayer(3,3,3,3,3).three_of_a_kind()); } @Test public void four_of_a_knd() { assertEquals(12, Yatzy.initGamePlayer(3,3,3,3,5).four_of_a_kind()); assertEquals(20, Yatzy.initGamePlayer(5,5,5,4,5).four_of_a_kind()); } @Test public void smallStraight() { assertEquals(15, Yatzy.initGamePlayer(1,2,3,4,5).smallStraight()); assertEquals(15, Yatzy.initGamePlayer(2,3,4,5,1).smallStraight()); assertEquals(0, Yatzy.initGamePlayer(1,2,2,4,5).smallStraight()); } @Test public void largeStraight() { assertEquals(20, Yatzy.initGamePlayer(6,2,3,4,5).largeStraight()); assertEquals(20, Yatzy.initGamePlayer(2,3,4,5,6).largeStraight()); assertEquals(0, Yatzy.initGamePlayer(1,2,2,4,5).largeStraight()); } @Test public void fullHouse() { assertEquals(18, Yatzy.initGamePlayer(6,2,2,2,6).fullHouse()); assertEquals(0, Yatzy.initGamePlayer(2,3,4,5,6).fullHouse()); } }
32.559322
76
0.625976
280d7bcce4c5b88e86b99569b885c97d943e738f
403
package uk.ac.nottingham.chen_chen.fractalviewer; /** * Mode class, similar to enumerate indicating the finger motion direction * @Author: Chen Chen * First Android project created on April 2016 for Web Based Computing (H63JAV), University of Nottingham */ public class Mode { public static final int NOTHING = 0; public static final int DRAG = 1; public static final int PINCH = 2; }
28.785714
105
0.736973
e8054a1d8a9ffdf663bc39366a8631ba1f448d1c
1,016
package com.coderZsq.dao; import com.alibaba.druid.pool.DruidDataSourceFactory; import com.coderZsq.bean.Customer; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; import java.util.List; import java.util.Properties; // druid // spring jdbc public class CustomerDao { private static JdbcTemplate tpl; static { try { // 获取连接池 Properties properties = new Properties(); properties.load(CustomerDao.class.getClassLoader().getResourceAsStream("druid.properties")); DataSource ds = DruidDataSourceFactory.createDataSource(properties); // 创建tpl tpl = new JdbcTemplate(ds); } catch (Exception e) { e.printStackTrace(); } } public List<Customer> list() { String sql = "SELECT id, name, age, height FROM customer"; return tpl.query(sql, new BeanPropertyRowMapper<>(Customer.class)); } }
29.028571
104
0.673228
899179bcd393054890270540d52f7110356aabf3
1,724
/* * Scala compiler interface * * Copyright Lightbend, Inc. and Mark Harrah * * Licensed under Apache License 2.0 * (http://www.apache.org/licenses/LICENSE-2.0). * * See the NOTICE file distributed with this work for * additional information regarding copyright ownership. */ package scala.tools.sci.compile; import java.nio.file.Path; import java.io.Serializable; import java.util.Optional; /** * Define an abstract interface that represents the output of the compilation. * * <p>Inheritors are {@link SingleOutput} with a global output directory and {@link MultipleOutput} * that specifies the output directory per source file. * * <p>These two subclasses exist to satisfy the Scala compiler which accepts both single and * multiple targets. These targets may depend on the sources to be compiled. * * <p>Note that Javac does not support multiple output and any attempt to use it will result in a * runtime exception. * * <p>This class is used both as an input to the compiler and as an output of the * scala.tools.sci.compile.CompileAnalysis. */ public interface Output extends Serializable { /** * Returns the multiple outputs passed or to be passed to the Scala compiler. If single output * directory is used or Javac will consume this setting, it returns {@link * java.util.Optional#EMPTY}. * * @see scala.tools.sci.compile.MultipleOutput */ public Optional<OutputGroup[]> getMultipleOutput(); /** * Returns the single output passed or to be passed to the Scala or Java compiler. If multiple * outputs are used, it returns {@link java.util.Optional#EMPTY}. * * @see scala.tools.sci.compile.SingleOutput */ public Optional<Path> getSingleOutput(); }
33.153846
99
0.735499
20a458a7cf8ee288175ed4f14b2c88d5e27d50e4
1,268
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.runtime.components.json; import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.impl.DefaultComponent; import java.util.Map; /** * Used to marshal and unmarshal to/from JSON using the jackson library */ public class JsonComponent extends DefaultComponent { public JsonComponent() { } public JsonComponent(CamelContext context) { super(context); } @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { return new JsonEndpoint(uri, this); } }
30.190476
118
0.730284
fcc9fc32a191c62b6d2c8909e89e968bd4cf27c8
22,084
/** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.regionserver; import static org.apache.hadoop.hbase.HBaseTestingUtility.START_KEY; import static org.apache.hadoop.hbase.HBaseTestingUtility.START_KEY_BYTES; import static org.apache.hadoop.hbase.HBaseTestingUtility.fam1; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.ChoreService; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HBaseTestCase; import org.apache.hadoop.hbase.HBaseTestCase.HRegionIncommon; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.testclassification.MediumTests; import org.apache.hadoop.hbase.testclassification.RegionServerTests; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Durability; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.io.hfile.HFileScanner; import org.apache.hadoop.hbase.regionserver.compactions.CompactionContext; import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequest; import org.apache.hadoop.hbase.regionserver.compactions.DefaultCompactor; import org.apache.hadoop.hbase.regionserver.compactions.NoLimitCompactionThroughputController; import org.apache.hadoop.hbase.regionserver.compactions.CompactionThroughputController; import org.apache.hadoop.hbase.regionserver.compactions.CompactionThroughputControllerFactory; import org.apache.hadoop.hbase.wal.WAL; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.Pair; import org.apache.hadoop.hbase.util.Threads; import org.junit.After; import org.junit.Assume; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TestName; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; /** * Test compaction framework and common functions */ @Category({RegionServerTests.class, MediumTests.class}) public class TestCompaction { @Rule public TestName name = new TestName(); private static final Log LOG = LogFactory.getLog(TestCompaction.class.getName()); private static final HBaseTestingUtility UTIL = HBaseTestingUtility.createLocalHTU(); protected Configuration conf = UTIL.getConfiguration(); private HRegion r = null; private HTableDescriptor htd = null; private static final byte [] COLUMN_FAMILY = fam1; private final byte [] STARTROW = Bytes.toBytes(START_KEY); private static final byte [] COLUMN_FAMILY_TEXT = COLUMN_FAMILY; private int compactionThreshold; private byte[] secondRowBytes, thirdRowBytes; private static final long MAX_FILES_TO_COMPACT = 10; /** constructor */ public TestCompaction() { super(); // Set cache flush size to 1MB conf.setInt(HConstants.HREGION_MEMSTORE_FLUSH_SIZE, 1024 * 1024); conf.setInt("hbase.hregion.memstore.block.multiplier", 100); conf.set(CompactionThroughputControllerFactory.HBASE_THROUGHPUT_CONTROLLER_KEY, NoLimitCompactionThroughputController.class.getName()); compactionThreshold = conf.getInt("hbase.hstore.compactionThreshold", 3); secondRowBytes = START_KEY_BYTES.clone(); // Increment the least significant character so we get to next row. secondRowBytes[START_KEY_BYTES.length - 1]++; thirdRowBytes = START_KEY_BYTES.clone(); thirdRowBytes[START_KEY_BYTES.length - 1] += 2; } @Before public void setUp() throws Exception { this.htd = UTIL.createTableDescriptor(name.getMethodName()); this.r = UTIL.createLocalHRegion(htd, null, null); } @After public void tearDown() throws Exception { WAL wal = r.getWAL(); this.r.close(); wal.close(); } /** * Verify that you can stop a long-running compaction * (used during RS shutdown) * @throws Exception */ @Test public void testInterruptCompaction() throws Exception { assertEquals(0, count()); // lower the polling interval for this test int origWI = HStore.closeCheckInterval; HStore.closeCheckInterval = 10*1000; // 10 KB try { // Create a couple store files w/ 15KB (over 10KB interval) int jmax = (int) Math.ceil(15.0/compactionThreshold); byte [] pad = new byte[1000]; // 1 KB chunk for (int i = 0; i < compactionThreshold; i++) { HRegionIncommon loader = new HRegionIncommon(r); Put p = new Put(Bytes.add(STARTROW, Bytes.toBytes(i))); p.setDurability(Durability.SKIP_WAL); for (int j = 0; j < jmax; j++) { p.add(COLUMN_FAMILY, Bytes.toBytes(j), pad); } HBaseTestCase.addContent(loader, Bytes.toString(COLUMN_FAMILY)); loader.put(p); loader.flushcache(); } HRegion spyR = spy(r); doAnswer(new Answer() { public Object answer(InvocationOnMock invocation) throws Throwable { r.writestate.writesEnabled = false; return invocation.callRealMethod(); } }).when(spyR).doRegionCompactionPrep(); // force a minor compaction, but not before requesting a stop spyR.compactStores(); // ensure that the compaction stopped, all old files are intact, Store s = r.stores.get(COLUMN_FAMILY); assertEquals(compactionThreshold, s.getStorefilesCount()); assertTrue(s.getStorefilesSize() > 15*1000); // and no new store files persisted past compactStores() FileStatus[] ls = r.getFilesystem().listStatus(r.getRegionFileSystem().getTempDir()); assertEquals(0, ls.length); } finally { // don't mess up future tests r.writestate.writesEnabled = true; HStore.closeCheckInterval = origWI; // Delete all Store information once done using for (int i = 0; i < compactionThreshold; i++) { Delete delete = new Delete(Bytes.add(STARTROW, Bytes.toBytes(i))); byte [][] famAndQf = {COLUMN_FAMILY, null}; delete.deleteFamily(famAndQf[0]); r.delete(delete); } r.flush(true); // Multiple versions allowed for an entry, so the delete isn't enough // Lower TTL and expire to ensure that all our entries have been wiped final int ttl = 1000; for (Store hstore: this.r.stores.values()) { HStore store = (HStore)hstore; ScanInfo old = store.getScanInfo(); ScanInfo si = new ScanInfo(old.getFamily(), old.getMinVersions(), old.getMaxVersions(), ttl, old.getKeepDeletedCells(), 0, old.getComparator()); store.setScanInfo(si); } Thread.sleep(ttl); r.compact(true); assertEquals(0, count()); } } private int count() throws IOException { int count = 0; for (StoreFile f: this.r.stores. get(COLUMN_FAMILY_TEXT).getStorefiles()) { HFileScanner scanner = f.getReader().getScanner(false, false); if (!scanner.seekTo()) { continue; } do { count++; } while(scanner.next()); } return count; } private void createStoreFile(final HRegion region) throws IOException { createStoreFile(region, Bytes.toString(COLUMN_FAMILY)); } private void createStoreFile(final HRegion region, String family) throws IOException { HRegionIncommon loader = new HRegionIncommon(region); HBaseTestCase.addContent(loader, family); loader.flushcache(); } @Test public void testCompactionWithCorruptResult() throws Exception { int nfiles = 10; for (int i = 0; i < nfiles; i++) { createStoreFile(r); } HStore store = (HStore) r.getStore(COLUMN_FAMILY); Collection<StoreFile> storeFiles = store.getStorefiles(); DefaultCompactor tool = (DefaultCompactor)store.storeEngine.getCompactor(); tool.compactForTesting(storeFiles, false); // Now lets corrupt the compacted file. FileSystem fs = store.getFileSystem(); // default compaction policy created one and only one new compacted file Path dstPath = store.getRegionFileSystem().createTempName(); FSDataOutputStream stream = fs.create(dstPath, null, true, 512, (short)3, (long)1024, null); stream.writeChars("CORRUPT FILE!!!!"); stream.close(); Path origPath = store.getRegionFileSystem().commitStoreFile( Bytes.toString(COLUMN_FAMILY), dstPath); try { ((HStore)store).moveFileIntoPlace(origPath); } catch (Exception e) { // The complete compaction should fail and the corrupt file should remain // in the 'tmp' directory; assert (fs.exists(origPath)); assert (!fs.exists(dstPath)); System.out.println("testCompactionWithCorruptResult Passed"); return; } fail("testCompactionWithCorruptResult failed since no exception was" + "thrown while completing a corrupt file"); } /** * Create a custom compaction request and be sure that we can track it through the queue, knowing * when the compaction is completed. */ @Test public void testTrackingCompactionRequest() throws Exception { // setup a compact/split thread on a mock server HRegionServer mockServer = Mockito.mock(HRegionServer.class); Mockito.when(mockServer.getConfiguration()).thenReturn(r.getBaseConf()); CompactSplitThread thread = new CompactSplitThread(mockServer); Mockito.when(mockServer.getCompactSplitThread()).thenReturn(thread); // setup a region/store with some files Store store = r.getStore(COLUMN_FAMILY); createStoreFile(r); for (int i = 0; i < MAX_FILES_TO_COMPACT + 1; i++) { createStoreFile(r); } CountDownLatch latch = new CountDownLatch(1); TrackableCompactionRequest request = new TrackableCompactionRequest(latch); thread.requestCompaction(r, store, "test custom comapction", Store.PRIORITY_USER, request); // wait for the latch to complete. latch.await(); thread.interruptIfNecessary(); } /** * HBASE-7947: Regression test to ensure adding to the correct list in the * {@link CompactSplitThread} * @throws Exception on failure */ @Test public void testMultipleCustomCompactionRequests() throws Exception { // setup a compact/split thread on a mock server HRegionServer mockServer = Mockito.mock(HRegionServer.class); Mockito.when(mockServer.getConfiguration()).thenReturn(r.getBaseConf()); CompactSplitThread thread = new CompactSplitThread(mockServer); Mockito.when(mockServer.getCompactSplitThread()).thenReturn(thread); // setup a region/store with some files int numStores = r.getStores().size(); List<Pair<CompactionRequest, Store>> requests = new ArrayList<Pair<CompactionRequest, Store>>(numStores); CountDownLatch latch = new CountDownLatch(numStores); // create some store files and setup requests for each store on which we want to do a // compaction for (Store store : r.getStores()) { createStoreFile(r, store.getColumnFamilyName()); createStoreFile(r, store.getColumnFamilyName()); createStoreFile(r, store.getColumnFamilyName()); requests .add(new Pair<CompactionRequest, Store>(new TrackableCompactionRequest(latch), store)); } thread.requestCompaction(r, "test mulitple custom comapctions", Store.PRIORITY_USER, Collections.unmodifiableList(requests)); // wait for the latch to complete. latch.await(); thread.interruptIfNecessary(); } private class StoreMockMaker extends StatefulStoreMockMaker { public ArrayList<StoreFile> compacting = new ArrayList<StoreFile>(); public ArrayList<StoreFile> notCompacting = new ArrayList<StoreFile>(); private ArrayList<Integer> results; public StoreMockMaker(ArrayList<Integer> results) { this.results = results; } public class TestCompactionContext extends CompactionContext { private List<StoreFile> selectedFiles; public TestCompactionContext(List<StoreFile> selectedFiles) { super(); this.selectedFiles = selectedFiles; } @Override public List<StoreFile> preSelect(List<StoreFile> filesCompacting) { return new ArrayList<StoreFile>(); } @Override public boolean select(List<StoreFile> filesCompacting, boolean isUserCompaction, boolean mayUseOffPeak, boolean forceMajor) throws IOException { this.request = new CompactionRequest(selectedFiles); this.request.setPriority(getPriority()); return true; } @Override public List<Path> compact(CompactionThroughputController throughputController) throws IOException { finishCompaction(this.selectedFiles); return new ArrayList<Path>(); } } @Override public synchronized CompactionContext selectCompaction() { CompactionContext ctx = new TestCompactionContext(new ArrayList<StoreFile>(notCompacting)); compacting.addAll(notCompacting); notCompacting.clear(); try { ctx.select(null, false, false, false); } catch (IOException ex) { fail("Shouldn't happen"); } return ctx; } @Override public synchronized void cancelCompaction(Object object) { TestCompactionContext ctx = (TestCompactionContext)object; compacting.removeAll(ctx.selectedFiles); notCompacting.addAll(ctx.selectedFiles); } public synchronized void finishCompaction(List<StoreFile> sfs) { if (sfs.isEmpty()) return; synchronized (results) { results.add(sfs.size()); } compacting.removeAll(sfs); } @Override public int getPriority() { return 7 - compacting.size() - notCompacting.size(); } } public class BlockingStoreMockMaker extends StatefulStoreMockMaker { BlockingCompactionContext blocked = null; public class BlockingCompactionContext extends CompactionContext { public volatile boolean isInCompact = false; public void unblock() { synchronized (this) { this.notifyAll(); } } @Override public List<Path> compact(CompactionThroughputController throughputController) throws IOException { try { isInCompact = true; synchronized (this) { this.wait(); } } catch (InterruptedException e) { Assume.assumeNoException(e); } return new ArrayList<Path>(); } @Override public List<StoreFile> preSelect(List<StoreFile> filesCompacting) { return new ArrayList<StoreFile>(); } @Override public boolean select(List<StoreFile> f, boolean i, boolean m, boolean e) throws IOException { this.request = new CompactionRequest(new ArrayList<StoreFile>()); return true; } } @Override public CompactionContext selectCompaction() { this.blocked = new BlockingCompactionContext(); try { this.blocked.select(null, false, false, false); } catch (IOException ex) { fail("Shouldn't happen"); } return this.blocked; } @Override public void cancelCompaction(Object object) {} public int getPriority() { return Integer.MIN_VALUE; // some invalid value, see createStoreMock } public BlockingCompactionContext waitForBlocking() { while (this.blocked == null || !this.blocked.isInCompact) { Threads.sleepWithoutInterrupt(50); } BlockingCompactionContext ctx = this.blocked; this.blocked = null; return ctx; } @Override public Store createStoreMock(String name) throws Exception { return createStoreMock(Integer.MIN_VALUE, name); } public Store createStoreMock(int priority, String name) throws Exception { // Override the mock to always return the specified priority. Store s = super.createStoreMock(name); when(s.getCompactPriority()).thenReturn(priority); return s; } } /** Test compaction priority management and multiple compactions per store (HBASE-8665). */ @Test public void testCompactionQueuePriorities() throws Exception { // Setup a compact/split thread on a mock server. final Configuration conf = HBaseConfiguration.create(); HRegionServer mockServer = mock(HRegionServer.class); when(mockServer.isStopped()).thenReturn(false); when(mockServer.getConfiguration()).thenReturn(conf); when(mockServer.getChoreService()).thenReturn(new ChoreService("test")); CompactSplitThread cst = new CompactSplitThread(mockServer); when(mockServer.getCompactSplitThread()).thenReturn(cst); //prevent large compaction thread pool stealing job from small compaction queue. cst.shutdownLongCompactions(); // Set up the region mock that redirects compactions. HRegion r = mock(HRegion.class); when( r.compact(any(CompactionContext.class), any(Store.class), any(CompactionThroughputController.class))).then(new Answer<Boolean>() { public Boolean answer(InvocationOnMock invocation) throws Throwable { invocation.getArgumentAt(0, CompactionContext.class).compact( invocation.getArgumentAt(2, CompactionThroughputController.class)); return true; } }); // Set up store mocks for 2 "real" stores and the one we use for blocking CST. ArrayList<Integer> results = new ArrayList<Integer>(); StoreMockMaker sm = new StoreMockMaker(results), sm2 = new StoreMockMaker(results); Store store = sm.createStoreMock("store1"), store2 = sm2.createStoreMock("store2"); BlockingStoreMockMaker blocker = new BlockingStoreMockMaker(); // First, block the compaction thread so that we could muck with queue. cst.requestSystemCompaction(r, blocker.createStoreMock(1, "b-pri1"), "b-pri1"); BlockingStoreMockMaker.BlockingCompactionContext currentBlock = blocker.waitForBlocking(); // Add 4 files to store1, 3 to store2, and queue compactions; pri 3 and 4 respectively. for (int i = 0; i < 4; ++i) { sm.notCompacting.add(createFile()); } cst.requestSystemCompaction(r, store, "s1-pri3"); for (int i = 0; i < 3; ++i) { sm2.notCompacting.add(createFile()); } cst.requestSystemCompaction(r, store2, "s2-pri4"); // Now add 2 more files to store1 and queue compaction - pri 1. for (int i = 0; i < 2; ++i) { sm.notCompacting.add(createFile()); } cst.requestSystemCompaction(r, store, "s1-pri1"); // Finally add blocking compaction with priority 2. cst.requestSystemCompaction(r, blocker.createStoreMock(2, "b-pri2"), "b-pri2"); // Unblock the blocking compaction; we should run pri1 and become block again in pri2. currentBlock.unblock(); currentBlock = blocker.waitForBlocking(); // Pri1 should have "compacted" all 6 files. assertEquals(1, results.size()); assertEquals(6, results.get(0).intValue()); // Add 2 files to store 1 (it has 2 files now). for (int i = 0; i < 2; ++i) { sm.notCompacting.add(createFile()); } // Now we have pri4 for store 2 in queue, and pri3 for store1; store1's current priority // is 5, however, so it must not preempt store 2. Add blocking compaction at the end. cst.requestSystemCompaction(r, blocker.createStoreMock(7, "b-pri7"), "b-pri7"); currentBlock.unblock(); currentBlock = blocker.waitForBlocking(); assertEquals(3, results.size()); assertEquals(3, results.get(1).intValue()); // 3 files should go before 2 files. assertEquals(2, results.get(2).intValue()); currentBlock.unblock(); cst.interruptIfNecessary(); } private static StoreFile createFile() throws Exception { StoreFile sf = mock(StoreFile.class); when(sf.getPath()).thenReturn(new Path("file")); StoreFile.Reader r = mock(StoreFile.Reader.class); when(r.length()).thenReturn(10L); when(sf.getReader()).thenReturn(r); return sf; } /** * Simple {@link CompactionRequest} on which you can wait until the requested compaction finishes. */ public static class TrackableCompactionRequest extends CompactionRequest { private CountDownLatch done; /** * Constructor for a custom compaction. Uses the setXXX methods to update the state of the * compaction before being used. */ public TrackableCompactionRequest(CountDownLatch finished) { super(); this.done = finished; } @Override public void afterExecute() { super.afterExecute(); this.done.countDown(); } } }
37.304054
100
0.705126
ffb1bd54ff8c0f487100c63013e8c6e0e9022491
3,824
package org.elixir_lang.annotator; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiRecursiveElementVisitor; import com.intellij.psi.impl.source.tree.LeafPsiElement; import org.elixir_lang.ElixirSyntaxHighlighter; import org.elixir_lang.psi.ElixirKeywordKey; import org.jetbrains.annotations.NotNull; /** * Annotates {@link org.elixir_lang.psi.EscapeSequence} as {@link ElixirSyntaxHighlighter#VALID_ESCAPE_SEQUENCE} */ public class EscapeSequence implements Annotator, DumbAware { /* * Public Instance Methods */ /** * Annotates the specified PSI element. * It is guaranteed to be executed in non-reentrant fashion. * I.e there will be no call of this method for this instance before previous call get completed. * Multiple instances of the annotator might exist simultaneously, though. * * @param element to annotate. * @param holder the container which receives annotations created by the plugin. */ @Override public void annotate(@NotNull final PsiElement element, @NotNull final AnnotationHolder holder) { element.accept( new PsiRecursiveElementVisitor() { /* * Public Instance Methods */ @Override public void visitElement(PsiElement element) { if (element instanceof org.elixir_lang.psi.EscapeSequence) { visitEscapeSequence((org.elixir_lang.psi.EscapeSequence) element); } } /* * Private Instance Methods */ private void visitEscapeSequence(org.elixir_lang.psi.EscapeSequence escapeSequence) { PsiElement parent = escapeSequence.getParent(); // parent can highlight itself if (!(parent instanceof org.elixir_lang.psi.EscapeSequence)) { highlight(escapeSequence, holder, ElixirSyntaxHighlighter.VALID_ESCAPE_SEQUENCE); } } } ); } /* * Private Instance Methods */ private void highlight(@NotNull final PsiElement element, @NotNull AnnotationHolder annotationHolder, @NotNull final TextAttributesKey textAttributesKey) { highlight(element.getTextRange(), annotationHolder, textAttributesKey); } /** * Highlights `textRange` with the given `textAttributesKey`. * * @param textRange textRange in the document to highlight * @param annotationHolder the container which receives annotations created by the plugin. * @param textAttributesKey text attributes to apply to the `node`. */ private void highlight(@NotNull final TextRange textRange, @NotNull AnnotationHolder annotationHolder, @NotNull final TextAttributesKey textAttributesKey) { annotationHolder.createInfoAnnotation(textRange, null) .setEnforcedTextAttributes(TextAttributes.ERASE_MARKER); annotationHolder.createInfoAnnotation(textRange, null) .setEnforcedTextAttributes( EditorColorsManager.getInstance().getGlobalScheme().getAttributes(textAttributesKey) ); } }
41.11828
112
0.647228
d880976718d5e1d6aebf8dcb592be369df6734ce
4,284
package LuckyDip; import java.util.ArrayList; import java.util.List; import me.lewys.com.Hub; import me.lewys.particles.ParticleEffect; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import dexoria.core.DexCore; public class luckydip implements Listener{ LuckyDipManager ldm = new LuckyDipManager(); Location playerLocation; Player player; Location cauldron; Location cauldron_top; Location cauldron_inside; boolean canmove = true; int lava_task; int runnableTask; int totalitems = 0; List<PossibleItems> got = new ArrayList<>(); List<Entity> bats = new ArrayList<>(); List<Entity> items = new ArrayList<>(); public luckydip(Location playerLoc, Player p) { playerLocation = playerLoc; player = p; } @SuppressWarnings("deprecation") public void doLuckyDip(){ startLava(); player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 1000000,10)); if(player.getLocation().add(2,0,0).getBlock().getType() == Material.AIR){ cauldron = player.getLocation().add(2,0,0).getBlock().getLocation(); player.teleport(new Location(player.getLocation().getWorld(), cauldron.getX() -2, player.getLocation().getY(), player.getLocation().getZ(), -90, player.getLocation().getPitch())); }else if(player.getLocation().subtract(2,0,0).getBlock().getType() == Material.AIR){ cauldron = player.getLocation().subtract(2,0,0).getBlock().getLocation(); player.teleport(new Location(player.getLocation().getWorld(), cauldron.getX() + 2, player.getLocation().getY(), player.getLocation().getZ(), 90, player.getLocation().getPitch())); }else if(player.getLocation().add(0,0,2).getBlock().getType() == Material.AIR){ cauldron = player.getLocation().add(0,0,2).getBlock().getLocation(); player.teleport(new Location(player.getLocation().getWorld(), player.getLocation().getX(), player.getLocation().getY(), cauldron.getZ() - 2, 0, player.getLocation().getPitch())); }else if(player.getLocation().subtract(0,0,2).getBlock().getType() == Material.AIR){ cauldron = player.getLocation().subtract(0,0,2).getBlock().getLocation(); player.teleport(new Location(player.getLocation().getWorld(), player.getLocation().getX(), player.getLocation().getY(), cauldron.getZ() + 2, 180, player.getLocation().getPitch())); }else{ return; } if(cauldron.getBlock().getType() != Material.AIR) return; cauldron_top = cauldron.add(0.5,1,0.5); cauldron_inside = cauldron_top.subtract(0,0.2,0); ldm.addActivePlayer(player.getName(), this); cauldron.getBlock().setType(Material.CAULDRON); canmove = false; runnableTask = Bukkit.getScheduler().scheduleAsyncRepeatingTask(Hub.instance, new Runnable(){ @Override public void run() { if(totalitems == 3){ stopLava(); } if(totalitems == 4){ end(); } totalitems++; } }, 20 * 4, 20 * 4); } @SuppressWarnings("deprecation") public void startLava(){ lava_task = Bukkit.getScheduler().scheduleAsyncRepeatingTask(Hub.instance, new Runnable(){ @Override public void run() { ParticleEffect.LAVA.display(cauldron_inside, 0.1f, 0f, 0.1f, 0.2f, 2); } }, 5, 5); } public void stopLava(){ Bukkit.getScheduler().cancelTask(lava_task); } public void end(){ Bukkit.getScheduler().cancelTask(runnableTask); /*/ * Clear memory */ cauldron.getBlock().setType(Material.AIR); player.removePotionEffect(PotionEffectType.SPEED); player = null; cauldron = null; cauldron_top = null; cauldron_inside = null; playerLocation = null; canmove = true; } public void doRandomItemPopOut() { Location loc = null; } public void doubleGameCurrency(String UUID){ DexCore.getCurrencySystem().addGC(UUID, DexCore.getCurrencySystem().getGC(UUID) * 2); } public void doubleCosmeticCurrency(String UUID){ DexCore.getCurrencySystem().addCC(UUID, DexCore.getCurrencySystem().getCC(UUID) * 2); } public boolean hasBeenPicked(PossibleItems item){ return got.contains(item); } }
28.370861
183
0.702381
7cc8620ebd66bb09e91a04711926bd4e7eb7b0cc
7,219
/* * XML Type: DeletedMetadataCollection * Namespace: http://schemas.microsoft.com/xrm/2011/Metadata/Query * Java type: com.microsoft.schemas.xrm._2011.metadata.query.DeletedMetadataCollection * * Automatically generated - do not modify. */ package com.microsoft.schemas.xrm._2011.metadata.query.impl; /** * An XML DeletedMetadataCollection(@http://schemas.microsoft.com/xrm/2011/Metadata/Query). * * This is a complex type. */ public class DeletedMetadataCollectionImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements com.microsoft.schemas.xrm._2011.metadata.query.DeletedMetadataCollection { private static final long serialVersionUID = 1L; public DeletedMetadataCollectionImpl(org.apache.xmlbeans.SchemaType sType) { super(sType); } private static final javax.xml.namespace.QName KEYVALUEPAIROFDELETEDMETADATAFILTERSARRAYOFGUIDPLUVPKTF$0 = new javax.xml.namespace.QName("http://schemas.microsoft.com/xrm/2011/Metadata/Query", "KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUv_PKtF"); /** * Gets array of all "KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUv_PKtF" elements */ public org.datacontract.schemas._2004._07.system_collections_generic.KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF[] getKeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtFArray() { synchronized (monitor()) { check_orphaned(); java.util.List targetList = new java.util.ArrayList(); get_store().find_all_element_users(KEYVALUEPAIROFDELETEDMETADATAFILTERSARRAYOFGUIDPLUVPKTF$0, targetList); org.datacontract.schemas._2004._07.system_collections_generic.KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF[] result = new org.datacontract.schemas._2004._07.system_collections_generic.KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF[targetList.size()]; targetList.toArray(result); return result; } } /** * Gets ith "KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUv_PKtF" element */ public org.datacontract.schemas._2004._07.system_collections_generic.KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF getKeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtFArray(int i) { synchronized (monitor()) { check_orphaned(); org.datacontract.schemas._2004._07.system_collections_generic.KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF target = null; target = (org.datacontract.schemas._2004._07.system_collections_generic.KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF)get_store().find_element_user(KEYVALUEPAIROFDELETEDMETADATAFILTERSARRAYOFGUIDPLUVPKTF$0, i); if (target == null) { throw new IndexOutOfBoundsException(); } return target; } } /** * Returns number of "KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUv_PKtF" element */ public int sizeOfKeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtFArray() { synchronized (monitor()) { check_orphaned(); return get_store().count_elements(KEYVALUEPAIROFDELETEDMETADATAFILTERSARRAYOFGUIDPLUVPKTF$0); } } /** * Sets array of all "KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUv_PKtF" element WARNING: This method is not atomicaly synchronized. */ public void setKeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtFArray(org.datacontract.schemas._2004._07.system_collections_generic.KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF[] keyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtFArray) { check_orphaned(); arraySetterHelper(keyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtFArray, KEYVALUEPAIROFDELETEDMETADATAFILTERSARRAYOFGUIDPLUVPKTF$0); } /** * Sets ith "KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUv_PKtF" element */ public void setKeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtFArray(int i, org.datacontract.schemas._2004._07.system_collections_generic.KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF keyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF) { synchronized (monitor()) { check_orphaned(); org.datacontract.schemas._2004._07.system_collections_generic.KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF target = null; target = (org.datacontract.schemas._2004._07.system_collections_generic.KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF)get_store().find_element_user(KEYVALUEPAIROFDELETEDMETADATAFILTERSARRAYOFGUIDPLUVPKTF$0, i); if (target == null) { throw new IndexOutOfBoundsException(); } target.set(keyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF); } } /** * Inserts and returns a new empty value (as xml) as the ith "KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUv_PKtF" element */ public org.datacontract.schemas._2004._07.system_collections_generic.KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF insertNewKeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF(int i) { synchronized (monitor()) { check_orphaned(); org.datacontract.schemas._2004._07.system_collections_generic.KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF target = null; target = (org.datacontract.schemas._2004._07.system_collections_generic.KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF)get_store().insert_element_user(KEYVALUEPAIROFDELETEDMETADATAFILTERSARRAYOFGUIDPLUVPKTF$0, i); return target; } } /** * Appends and returns a new empty value (as xml) as the last "KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUv_PKtF" element */ public org.datacontract.schemas._2004._07.system_collections_generic.KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF addNewKeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF() { synchronized (monitor()) { check_orphaned(); org.datacontract.schemas._2004._07.system_collections_generic.KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF target = null; target = (org.datacontract.schemas._2004._07.system_collections_generic.KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF)get_store().add_element_user(KEYVALUEPAIROFDELETEDMETADATAFILTERSARRAYOFGUIDPLUVPKTF$0); return target; } } /** * Removes the ith "KeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUv_PKtF" element */ public void removeKeyValuePairOfDeletedMetadataFiltersArrayOfguidPlUvPKtF(int i) { synchronized (monitor()) { check_orphaned(); get_store().remove_element(KEYVALUEPAIROFDELETEDMETADATAFILTERSARRAYOFGUIDPLUVPKTF$0, i); } } }
51.564286
283
0.740546
44bcda3a5619d40e00e59fdd4b2db1e633f128c4
3,232
package deformablemesh.geometry; /** * * An ordered collection of 3 nodes that will be used for calculating geometric properties. * The winding of the triangle should be such that CCW points outwards from the volume * contained within. * * User: msmith * Date: 7/2/13 * Time: 7:56 AM * To change this template use File | Settings | File Templates. */ public class Triangle3D { final Node3D A,B,C; public double area; public double[] normal; public double[] center; public Triangle3D(Node3D a, Node3D b, Node3D c){ A = a; B = b; C = c; normal = new double[3]; center = new double[3]; } //cacluates the area the normal and the center. final static double one_third = 1.0/3.0; public void update(){ //calculate area double[] a = A.getCoordinates(); double[] b = B.getCoordinates(); double[] c = C.getCoordinates(); double[] ab = new double[3]; double[] ac = new double[3]; for(int i = 0; i<3; i++){ ab[i] = b[i] - a[i]; ac[i] = c[i] - a[i]; } normal[0] = (ab[1]*ac[2] - ab[2]*ac[1]); normal[1] = (ab[2]*ac[0] - ab[0]*ac[2]); normal[2] = (ab[0]*ac[1] - ab[1]*ac[0]); area = 0.5*Math.sqrt(normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2]); if(area>0){ for(int i = 0; i<3; i++){ normal[i] = normal[i]/area; center[i] = (a[i] + b[i] + c[i])*one_third; } } } public int[] getIndices(){ return new int[]{A.index, B.index, C.index}; } public boolean hasNode(Node3D other){ return A==other||B==other||C==other; } public double[] getNormal() { return normal; } @Override public int hashCode(){ return A.index + B.index + C.index; } @Override public boolean equals(Object o){ if(o==null) return false; if(o instanceof Triangle3D ){ //check for cyclic equality. Triangle3D ot = (Triangle3D)o; if(A.index==ot.A.index){ return B.index==ot.B.index&&C.index==ot.C.index; } else if(A.index==ot.B.index){ return B.index==ot.C.index&&C.index==ot.A.index; } else if(A.index==ot.C.index){ return B.index==ot.A.index&&C.index==ot.B.index; } } return false; } public boolean hasConnection(Connection3D con){ return hasNode(con.A)&&hasNode(con.B); } public void getIndices(int[] indexes) { indexes[0] = A.index; indexes[1] = B.index; indexes[2] = C.index; } public double[] getCoordinates(int dex){ switch(dex%3){ case 0: return A.getCoordinates(); case 1: return B.getCoordinates(); case 2: return C.getCoordinates(); } throw new RuntimeException("Negative node value is not valid! " + dex); } public boolean containsNode(Node3D node) { return (A.index==node.index) || (B.index==node.index) || (C.index==node.index); } }
25.25
94
0.524134
86015384345d520debcae24663768f9593658e27
674
package com.bank.bpm.partners.workers.onboarding.order; import br.com.six2six.fixturefactory.Fixture; import br.com.six2six.fixturefactory.Rule; import br.com.six2six.fixturefactory.loader.TemplateLoader; import java.util.stream.IntStream; public class ProductRequestTemplate implements TemplateLoader { public static final String BASIC = "BASIC"; @Override public void load() { Fixture.of(ProductRequest.class).addTemplate(BASIC, new Rule() {{ add("sku", uniqueRandom(IntStream.range(1, 100).mapToObj(item -> String.format("SKU-%d", item)).toArray())); add("amount", random(Integer.class, range(0, 500))); add("dispatchable", Boolean.TRUE); }}); } }
29.304348
111
0.746291
7de4aea30df55dd2202e31946813c8b27f63bea4
824
package netty_examples; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.TooLongFrameException; import java.util.List; public class FrameChunkDecoder extends ByteToMessageDecoder { private final int maxFrameSize; public FrameChunkDecoder(int maxFrameSize) { this.maxFrameSize = maxFrameSize; } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> list) throws Exception { int readableBytes = byteBuf.readableBytes(); if(readableBytes > maxFrameSize) { byteBuf.clear(); throw new TooLongFrameException(); } ByteBuf buf = byteBuf.readBytes(readableBytes); list.add(buf); } }
27.466667
107
0.718447
8a6e973402cb119f8d5e960d5b6b3fcc9e299e52
2,228
package jpuppeteer.cdp.client.entity.css; /** * Properties of a web font: https://www.w3.org/TR/2008/REC-CSS2-20080411/fonts.html#font-descriptions and additional information such as platformFontFamily and fontVariationAxes. * experimental */ public class FontFace { /** * The font-family. */ public final String fontFamily; /** * The font-style. */ public final String fontStyle; /** * The font-variant. */ public final String fontVariant; /** * The font-weight. */ public final String fontWeight; /** * The font-stretch. */ public final String fontStretch; /** * The unicode-range. */ public final String unicodeRange; /** * The src. */ public final String src; /** * The resolved platform font family */ public final String platformFontFamily; /** * Available variation settings (a.k.a. "axes"). */ public final java.util.List<jpuppeteer.cdp.client.entity.css.FontVariationAxis> fontVariationAxes; public FontFace(String fontFamily, String fontStyle, String fontVariant, String fontWeight, String fontStretch, String unicodeRange, String src, String platformFontFamily, java.util.List<jpuppeteer.cdp.client.entity.css.FontVariationAxis> fontVariationAxes) { this.fontFamily = fontFamily; this.fontStyle = fontStyle; this.fontVariant = fontVariant; this.fontWeight = fontWeight; this.fontStretch = fontStretch; this.unicodeRange = unicodeRange; this.src = src; this.platformFontFamily = platformFontFamily; this.fontVariationAxes = fontVariationAxes; } public FontFace(String fontFamily, String fontStyle, String fontVariant, String fontWeight, String fontStretch, String unicodeRange, String src, String platformFontFamily) { this.fontFamily = fontFamily; this.fontStyle = fontStyle; this.fontVariant = fontVariant; this.fontWeight = fontWeight; this.fontStretch = fontStretch; this.unicodeRange = unicodeRange; this.src = src; this.platformFontFamily = platformFontFamily; this.fontVariationAxes = null; } }
28.564103
263
0.671454
4055d4fb0c244cbeaea80c5a968600b2519312eb
7,102
package org.wcdevs.blog.cdk; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awscdk.RemovalPolicy; import software.amazon.awscdk.services.ecr.Repository; import software.amazon.awscdk.services.ecr.TagMutability; import software.amazon.awscdk.services.iam.Grant; import software.constructs.Construct; import java.security.SecureRandom; import java.util.Random; import java.util.UUID; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.params.provider.Arguments.arguments; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; class DockerRepositoryTest { private final Random random = new SecureRandom(); private Repository.Builder builderMock; private Repository repositoryMock; @BeforeEach void setUp() { repositoryMock = mock(Repository.class); when(repositoryMock.grantPullPush(any())).thenReturn(mock(Grant.class)); builderMock = mock(Repository.Builder.class); when(builderMock.imageTagMutability(any())).thenReturn(builderMock); when(builderMock.repositoryName(any())).thenReturn(builderMock); when(builderMock.removalPolicy(any())).thenReturn(builderMock); when(builderMock.lifecycleRules(any())).thenReturn(builderMock); when(builderMock.build()).thenReturn(repositoryMock); } static Stream<Arguments> newInstanceParameters() { return Stream.of(arguments(RemovalPolicy.RETAIN, TagMutability.IMMUTABLE), arguments(RemovalPolicy.RETAIN, TagMutability.MUTABLE), arguments(RemovalPolicy.DESTROY, TagMutability.IMMUTABLE), arguments(RemovalPolicy.DESTROY, TagMutability.MUTABLE)); } @ParameterizedTest @MethodSource("newInstanceParameters") void newInstanceWithParameters(RemovalPolicy removalPolicy, TagMutability tagMutable) { StaticallyMockedCdk.executeTest(() -> { try (var mockedBuilder = mockStatic(Repository.Builder.class)) { mockedBuilder.when(() -> Repository.Builder.create(any(), any())).thenReturn(builderMock); var inParams = mock(DockerRepository.InputParameters.class); when(inParams.removalPolicy()).thenReturn(removalPolicy); when(inParams.isRetainRegistryOnDelete()).thenReturn(removalPolicy == RemovalPolicy.RETAIN); when(inParams.tagMutability()).thenReturn(tagMutable); when(inParams.isInmutableTags()).thenReturn(tagMutable == TagMutability.IMMUTABLE); var actual = DockerRepository.newInstance(mock(Construct.class), randomString(), inParams); assertNotNull(actual); } }); } @Test void newInputParameters() { var repositoryName = randomString(); var accountId = randomString(); var actual = DockerRepository.newInputParameters(repositoryName, accountId); assertNotNull(actual); assertEquals(repositoryName, actual.getRepositoryName()); assertEquals(accountId, actual.getAccountId()); assertEquals(DockerRepository.InputParameters.DEFAULT_MAX_IMAGE_COUNT, actual.getMaxImageCount()); assertEquals(DockerRepository.InputParameters.DEFAULT_RETAIN_POLICY, actual.isRetainRegistryOnDelete()); assertEquals(DockerRepository.InputParameters.DEFAULT_INMUTABLE_TAGS, actual.isInmutableTags()); assertEquals(TagMutability.IMMUTABLE, actual.tagMutability()); assertEquals(RemovalPolicy.RETAIN, actual.removalPolicy()); } @Test void newInputParametersFromBuilder() { var random = new SecureRandom(); var repoName = randomString(); var accountId = randomString(); var maxImageCount = random.nextInt(); var inmutableTags = random.nextBoolean(); var retainRegistryOnDelete = random.nextBoolean(); var actual = DockerRepository.InputParameters.builder() .repositoryName(repoName) .accountId(accountId) .maxImageCount(maxImageCount) .inmutableTags(inmutableTags) .retainRegistryOnDelete(retainRegistryOnDelete) .build(); assertNotNull(actual); assertEquals(repoName, actual.getRepositoryName()); assertEquals(accountId, actual.getAccountId()); assertEquals(maxImageCount, actual.getMaxImageCount()); assertEquals(inmutableTags, actual.isInmutableTags()); assertEquals(retainRegistryOnDelete, actual.isRetainRegistryOnDelete()); } private String randomString() { return UUID.randomUUID().toString(); } @Test void getEcRepository() { StaticallyMockedCdk.executeTest(() -> { try (var mockedBuilder = mockStatic(Repository.Builder.class)) { mockedBuilder.when(() -> Repository.Builder.create(any(), any())).thenReturn(builderMock); var actual = DockerRepository.newInstance(mock(Construct.class), randomString(), mock(DockerRepository.InputParameters.class)); assertEquals(repositoryMock, actual.getEcRepository()); } }); } @Test void allArgsConstructorRetainImageInmutableTags() { testAllArgsConstructor(random.nextInt(), true, RemovalPolicy.RETAIN, true, TagMutability.IMMUTABLE); } @Test void allArgsConstructorDestroyImageMutableTags() { testAllArgsConstructor(random.nextInt(), false, RemovalPolicy.DESTROY, false, TagMutability.MUTABLE); } void testAllArgsConstructor(int expectedMaxImageCount, boolean expectedRetainRegistry, RemovalPolicy expectedRemovalPolicy, boolean expectedInmutableTags, TagMutability expectedTagMutability) { var repoName = randomString(); var accountId = randomString(); var actual = new DockerRepository.InputParameters(repoName, accountId, expectedMaxImageCount, expectedRetainRegistry, expectedInmutableTags); assertNotNull(actual); assertEquals(repoName, actual.getRepositoryName()); assertEquals(accountId, actual.getAccountId()); assertEquals(expectedMaxImageCount, actual.getMaxImageCount()); assertEquals(expectedRetainRegistry, actual.isRetainRegistryOnDelete()); assertEquals(expectedInmutableTags, actual.isInmutableTags()); assertEquals(expectedTagMutability, actual.tagMutability()); assertEquals(expectedRemovalPolicy, actual.removalPolicy()); } }
43.304878
100
0.694875
8a690af52de52a89af2e02828f91ece01e5d6631
1,016
package com.huanmedia.videochat.mvp.model.video; import android.content.Context; import com.huanmedia.videochat.mvp.base.BaseMVPModel; import com.huanmedia.videochat.mvp.base.DataCallBack; import com.huanmedia.videochat.mvp.entity.request.ShortVideoPraiseRequest; import com.huanmedia.videochat.repository.base.HttpResponseHandler; import com.huanmedia.videochat.repository.net.MHttpManagerFactory; public class ShortVideoPraiseModelImpl extends BaseMVPModel implements IShortVideoPraiseModel { @Override public void shortVideoPraise(Context context, ShortVideoPraiseRequest params, DataCallBack callBack) { MHttpManagerFactory.getMainManager().shortVideoPraise(context, params, new HttpResponseHandler() { @Override public void onSuccess(Object result) { callBack.getDataSuccess(result); } @Override public void onError(String message) { callBack.getDataFail(message); } }); } }
37.62963
106
0.732283
ad27df5cc774900d582b55e212738d319f98931d
463
package com.jeffbrower.http; public class ErrorResponseException extends RuntimeException { private static final long serialVersionUID = 1L; public final Status status; public ErrorResponseException(final Status status, final String message) { super(message); this.status = status; } public ErrorResponseException(final Status status, final String message, final Throwable cause) { super(message, cause); this.status = status; } }
25.722222
99
0.75378
f3f93c0e97338d5816fca2ef59bfa47c70d930e2
2,726
/* * 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 net.groboclown.p4plugin.ui.config; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import net.groboclown.p4plugin.components.UserProjectPreferences; import net.groboclown.p4plugin.ui.WrapperPanel; import org.jetbrains.annotations.NotNull; import javax.swing.*; public class P4ConfigurationProjectPanel implements Disposable { private static final Logger LOG = Logger.getInstance(P4ConfigurationProjectPanel.class); private final Project project; private UserPreferencesPanel myMainPanel; private WrapperPanel wrappedPanel; private volatile boolean isInitialized = false; P4ConfigurationProjectPanel(@NotNull Project project) { this.project = project; } synchronized boolean isModified(@NotNull UserProjectPreferences preferences) { return isInitialized && myMainPanel.isModified(preferences); } synchronized void saveSettings(@NotNull UserProjectPreferences preferences) { if (!isInitialized) { // nothing to do return; } myMainPanel.saveSettingsToConfig(preferences); } synchronized void loadSettings(@NotNull UserProjectPreferences preferences) { if (!isInitialized) { getPanel(preferences); return; } LOG.debug("Loading settings into the main panel"); myMainPanel.loadSettingsIntoGUI(preferences); } synchronized JPanel getPanel(@NotNull UserProjectPreferences preferences) { if (!isInitialized) { LOG.debug("Creating settings panel"); myMainPanel = new UserPreferencesPanel(); isInitialized = true; wrappedPanel = new WrapperPanel(myMainPanel.getRootPanel()); } loadSettings(preferences); return wrappedPanel; } public synchronized void dispose() { // TODO is there a dispose to call on this panel? //if (myMainPanel != null) { // Disposer.dispose(myMainPanel); //} myMainPanel = null; wrappedPanel = null; isInitialized = false; } }
34.075
92
0.70066
79df879179e6906f0c26cb2f9a334b8d515d72b1
2,512
package org.dstadler.commons.collections; import java.util.Iterator; import java.util.List; import java.util.function.Consumer; import java.util.function.Function; /** * An {@link java.util.List} which wraps another list and provides a read-only view * of a specific property of the type of object contained in the original list. * * Any method which would modify the underlying list throws an {@link UnsupportedOperationException}. * * The implementation uses an accessor function to extract a property from the underlying list, e.g. it can * be constructed as follows: * * List&lt;String&gt; list = new ObjectAccessorList&lt;&gt;(originalList, MyObject::getStringProperty()); * * Some reading methods also throw UnsupportedOperationException, mostly they cannot be implemented * without an "inverse" operation from R to E. * * Currently at least get(), size(), isEmpty(), iterator() and forEach() can be expected to work. * * Changes to the underlying list should usually have the expected effect on this implementation. * * Reading fom the the underlying list in multiple threads should work, modifying the underlying * list in multiple threads concurrently is not supported. * * @param <E> The type of objects stored in the underlying list * @param <R> The type of object this list provides by reading it from the * underlying list via the provided accessor function */ public class ObjectAccessorList<R, E> extends UnsupportedList<R> { private final List<E> original; private final Function<E, R> accessor; public ObjectAccessorList(List<E> original, Function<E, R> accessor) { this.original = original; this.accessor = accessor; } @Override public R get(int index) { return accessor.apply(original.get(index)); } @Override public int size() { return original.size(); } @Override public boolean isEmpty() { return original.isEmpty(); } @Override public Iterator<R> iterator() { return new Iterator<R>() { private final Iterator<E> it = original.iterator(); @Override public boolean hasNext() { return it.hasNext(); } @Override public R next() { return accessor.apply(it.next()); } }; } @Override public void forEach(Consumer<? super R> action) { original.forEach(e -> action.accept(accessor.apply(e))); } }
31.797468
107
0.669984
8d71e770285bfa39d5fefc89fab1bb4ed323a318
7,052
package utilities; import java.io.InputStream; import java.io.StringBufferInputStream; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import org.junit.After; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class SaveManagerTest extends JsonTest { /* Paths for our use */ final Path TEST_DIRECTORY = Paths.get("src", "test", "resources", "testData"); final Path FAKE_GRAPH = Paths.get(TEST_DIRECTORY.toString(), "fakeGraph"); final Path FAKE_GRAPH_BACKUP = null; // to make sure no one tries to use it in a test final Path EMPTY_FILE = Paths.get(TEST_DIRECTORY.toString(), "emptyFile"); final Path EMPTY_FILE_TEMP = Paths.get(TEST_DIRECTORY.toString(), "emptyFile" + SaveManager.TEMP_EXTENSION); final Path CREATION_FILE = Paths.get(TEST_DIRECTORY.toString(), "noFile"); final String FAKE_GRAPH_DATA_NODE1 = "{\"id\": \"n0\",\"label\": \"Fake Project main feature\",\"actionType\" : \"feature\",\"x\": 0,\"y\": 0,\"size\": 2}"; final String FAKE_GRAPH_DATA_EDGE1 = "{\"id\": \"e0\",\"source\": \"n0\",\"target\": \"n1\"}"; /* Data that can be used for tests */ final String SIMPLE_DATA = "[" + SIMPLE_OBJECT + "]"; final String SIMPLE_DATA_REPLACEMENT = "[" + SIMPLE_OBJECT2 + "]"; final String SIMPLE_DATA_INSERT = "[" + SIMPLE_OBJECT + "," + SIMPLE_OBJECT3 + "]"; final String COMPLEX_DATA = "{ \"data\":" + SIMPLE_DATA + "}"; final String COMPLEX_DATA_INSERT = "{ \"data\":" + SIMPLE_DATA_INSERT + "}"; private SaveManager manager; @Before public void setUp() throws Exception { SaveManager.setFilePermissionsForEveryone(TEST_DIRECTORY); SaveManager.setFilePermissionsForEveryone(EMPTY_FILE); Files.createFile(EMPTY_FILE); // moves the backup to ensure that the fake graph is always the same final Path FAKE_GRAPH_BACKUP = Paths.get(TEST_DIRECTORY.toString(), "fakeGraphBackup"); Files.move(FAKE_GRAPH_BACKUP, FAKE_GRAPH_BACKUP, StandardCopyOption.REPLACE_EXISTING); manager = new SaveManager(); } @After public void tearDown() throws Exception { Files.deleteIfExists(EMPTY_FILE); Files.deleteIfExists(EMPTY_FILE_TEMP); try { Files.deleteIfExists(CREATION_FILE); } catch (Exception e) { e.printStackTrace(); } } @Test(expected = NoSuchFileException.class) public void testLoadDataCreationFile() throws Exception { // should make the entire file contain the data manager.loadObjects(new ArrayList<String>(), CREATION_FILE); } @Test public void testLoadData() throws Exception { String expected = "[" + FAKE_GRAPH_DATA_NODE1 + "," + FAKE_GRAPH_DATA_EDGE1 + "]"; ArrayList<String> str = new ArrayList<String>(); str.add("n0"); str.add("e0"); // should make the entire file contain the data StringBuffer buffer = manager.loadObjects(str, FAKE_GRAPH); jsonEquals(expected, buffer.toString()); } @Test public void testCreateTemporyPath() { Path p = SaveManager.createTemporyPath(EMPTY_FILE); assertEquals(EMPTY_FILE_TEMP, p); } @Test public void testReplaceEmptyFile() throws Exception { // sanity check assertTrue(Files.exists(EMPTY_FILE)); assertTrue(!Files.exists(EMPTY_FILE_TEMP)); // NOTE: I am calling this method with the reverse inputs // EMPTY_FILE is the temp file in this case assertTrue(SaveManager.replaceRealWithTemp(EMPTY_FILE, EMPTY_FILE_TEMP)); assertTrue(!Files.exists(EMPTY_FILE)); assertTrue(Files.exists(EMPTY_FILE_TEMP)); } @Test public void testReplaceEmptyToCreationFile() throws Exception { // sanity check assertTrue(Files.exists(EMPTY_FILE)); assertTrue(!Files.exists(CREATION_FILE)); // NOTE: I am calling this method with the reverse inputs // EMPTY_FILE is the temp file in this case assertTrue(SaveManager.replaceRealWithTemp(EMPTY_FILE, CREATION_FILE)); assertTrue(!Files.exists(EMPTY_FILE)); assertTrue(Files.exists(CREATION_FILE)); } @Test public void testEmptyFile() throws Exception { assertTrue(SaveManager.isFileEmpty(EMPTY_FILE)); } @Test public void testNotEmptyFile() throws Exception { assertFalse(SaveManager.isFileEmpty(FAKE_GRAPH)); } @Test(expected = SaveException.class) public void testSaveDataExceptsIfNotArray() throws Exception { InputStream stream = new StringBufferInputStream(SIMPLE_REPLACEMENT); // should make the entire file contain the data manager.saveData(stream, EMPTY_FILE, null); } @Test(expected = SaveException.class) public void testSaveDataExceptsIfNotJsonObject() throws Exception { InputStream stream = new StringBufferInputStream("This is not a json object \""); // should make the entire file contain the data manager.saveData(stream, EMPTY_FILE, null); } @Test public void testSaveDataEmptyFile() throws Exception { final InputStream stream = new StringBufferInputStream(SIMPLE_DATA); // should make the entire file contain the data manager.saveData(stream, EMPTY_FILE, null); compareFileData(SIMPLE_DATA, EMPTY_FILE); } /** * The same manager should create the file if it does not exist * @throws Exception */ @Test public void testSaveDataCreationFile() throws Exception { final InputStream stream = new StringBufferInputStream(SIMPLE_DATA); // should make the entire file contain the data manager.saveData(stream, CREATION_FILE, null); compareFileData(SIMPLE_DATA, CREATION_FILE); } /** * Writes out the data to a file. * * Then inserts new data into the file * @throws Exception */ @Test public void testSaveDataFileInsert() throws Exception { InputStream stream = new StringBufferInputStream(SIMPLE_DATA); // should make the entire file contain the data manager.saveData(stream, CREATION_FILE, null); stream = new StringBufferInputStream("[" + SIMPLE_OBJECT3 + "]"); Map<String, String> values = new HashMap<String, String>(); values.put("insert", null); manager.saveData(stream, CREATION_FILE, values); compareFileData(SIMPLE_DATA_INSERT, CREATION_FILE); } /** * The same manager should create the file if it does not exist * @throws Exception */ @Test public void testSaveDataFileComplexInsert() throws Exception { InputStream stream = new StringBufferInputStream(COMPLEX_DATA); Map<String, String> values = new HashMap<String, String>(); values.put("object", null); // should make the entire file contain the data manager.saveData(stream, CREATION_FILE, values); stream = new StringBufferInputStream("[" + SIMPLE_OBJECT3 + "]"); values = new HashMap<String, String>(); values.put("insert", null); values.put("2", "data"); manager.saveData(stream, CREATION_FILE, values); compareFileData(COMPLEX_DATA_INSERT, CREATION_FILE); } public static void compareFileData(String expected, Path result) throws Exception { Scanner s = new Scanner(result).useDelimiter("\\A"); String file = s.next(); jsonEquals(expected, file); } }
31.765766
157
0.740216
3c37eea94c7ba70e703457874da2dbc42d979417
5,676
package com.revcontent.rcnativeandroidsdk.banner; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.constraintlayout.widget.ConstraintLayout; import com.revcontent.rcnativeandroidsdk.R; import com.revcontent.rcnativeandroidsdk.connectivity.ConnectionMonitor; class RCSliderBannerLayout extends ConstraintLayout { protected final int BANNER_LOAD_DELAY = 2000; private RCBannerWebView webView; private BannerSize bannerSize = BannerSize.W320XH50; private boolean isBannerLoaded = false; @Nullable private BannerEventListener eventListener = null; public RCSliderBannerLayout(@NonNull Context context) { this(context, null, 0, 0); } public RCSliderBannerLayout(@NonNull Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0, 0); } public RCSliderBannerLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr, 0); } public RCSliderBannerLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } boolean getIsBannerLoaded() { return isBannerLoaded; } void loadBanner(int widgetID, BannerSize size) { if (webView != null) { //prepare layout container bannerSize = size; requestLayout(); //load banner webView.setWidgetId(String.valueOf(widgetID)); webView.setBannerSize(size); webView.loadWidget(); } } void addEventListener(BannerEventListener eventListener) { this.eventListener = eventListener; } void removeEventListener() { this.eventListener = null; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); updateWebViewSize(bannerSize); } private void updateWebViewSize(BannerSize size) { ViewGroup.LayoutParams lp = webView.getLayoutParams(); int initHeight = lp.height; int initWidth = lp.width; int maxHeight = getMeasuredHeight() - getContext().getResources().getDimensionPixelSize(R.dimen.button_size); int maxWidth = getMeasuredWidth(); double contentHeight = size.height; double contentWidth = size.width; double scale = 100; if (size.height > maxHeight || size.width > maxWidth){ double widthRatio = maxWidth * 100d / size.width; double heightRatio = maxHeight * 100d / size.height; scale = Math.min(widthRatio, heightRatio); contentHeight = (int)(contentHeight * (int)scale / 100d); contentWidth = (int)(contentWidth * (int)scale / 100d); } webView.setInitialScale((int)scale); if (initHeight != contentHeight || initWidth != contentWidth){ lp.height = (int) (contentHeight); lp.width = (int) (contentWidth); webView.setLayoutParams(lp); requestLayout(); } } @Override protected void onFinishInflate() { super.onFinishInflate(); webView = findViewById(R.id.banner_web_view); ImageView closeView = findViewById(R.id.banner_close); closeView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (eventListener != null) { eventListener.onClosed(); } } }); initWebView(); } private void initWebView() { webView.setInitialScale(100); webView.setVerticalScrollBarEnabled(false); webView.setHorizontalScrollBarEnabled(false); // disable scroll on touch webView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return (event.getAction() == MotionEvent.ACTION_MOVE); } }); webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) { if (eventListener != null) eventListener.onLinkTap(); view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); return true; } else { return false; } } @Override public void onPageFinished(final WebView view, String url) { if (eventListener != null) view.postDelayed(new Runnable() { @Override public void run() { ConnectionMonitor monitor = new ConnectionMonitor(getContext()); if (monitor.isNetworkAvailable()){ isBannerLoaded = true; eventListener.onLoaded(); } } }, BANNER_LOAD_DELAY); } }); } }
33.192982
124
0.611698
8c54513c4703924dd7f635e7e45ad88575910e35
2,774
package info.seleniumcucumber.utils.dataproviders; import java.io.FileInputStream; import java.io.FileOutputStream; import info.seleniumcucumber.utils.BaseTest; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import info.seleniumcucumber.testDataTypes.Customer; public class ExcelDataReader implements BaseTest { private static XSSFSheet ExcelWSheet; private static XSSFWorkbook ExcelWBook; private static XSSFCell Cell; private static XSSFRow Row; static Customer customer; private static final String customerFilePath = configFileReader.getTestDataResourcePath() + "TestData.xlsx"; private static final String sheetName = "LoginPage"; //This method is set to the file path and to open the excel file, pass excel path and //sheet name as arguments to this method public void setExcelFile() throws Exception{ try { // Open the excel file FileInputStream excelFile = new FileInputStream(customerFilePath); //Access the required test data sheet ExcelWBook = new XSSFWorkbook(excelFile); ExcelWSheet = ExcelWBook.getSheet(sheetName); } catch (Exception e) { throw(e); } } //This method is to read the test data from the excel cell, //in this we are passing parametres as Row num and Col num public Customer getExcelData(int rowNum) { try { FileInputStream excelFile = new FileInputStream(customerFilePath); //Access the required test data sheet ExcelWBook = new XSSFWorkbook(excelFile); ExcelWSheet = ExcelWBook.getSheet(sheetName); XSSFRow row = ExcelWSheet.getRow(rowNum); //Cell = ExcelWSheet.getRow(rowNum).getCell(colNum); //String cellData = Cell.getStringCellValue(); customer = new Customer(); customer.setUserName(row.getCell(1).getStringCellValue()); customer.setPassword(row.getCell(2).getStringCellValue()); return customer; } catch (Exception e) { return customer; } } //This method is to write in the excel cell, row num and col num are the parameters public static void setCellData(String result, int rowNum, int colNum) throws Exception{ try{ Row = ExcelWSheet.getRow(rowNum); // Cell = Row.getCell(colNum, Row.RETURN_BLANK_AS_NULL); if (Cell == null) { Cell = Row.createCell(colNum); Cell.setCellValue(result); } else { Cell.setCellValue(result); } // Constant variables Test Data path and Test Data file name FileOutputStream fileOut = new FileOutputStream(customerFilePath); ExcelWBook.write(fileOut); fileOut.flush(); fileOut.close(); }catch(Exception e){ throw (e); } } }
22.737705
109
0.725306
c66372b66b76b3692054ec3a840c4fbaeadf9c1e
3,566
package org.ihtsdo.otf.rest.client.terminologyserver.pojo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.ihtsdo.otf.utils.SnomedIdentifierUtils; @JsonPropertyOrder({"id", "effectiveTime", "released", "releasedEffectiveTime", "active", "moduleId", "refsetId", "referencedComponentId", "additionalFields"}) @JsonIgnoreProperties(ignoreUnknown = true) public class RefsetMemberPojo implements SnomedComponent { private String id; private boolean released; private String effectiveTime; private boolean active; private String moduleId; private String releasedEffectiveTime; private String referencedComponentId; private String refsetId; private AdditionalFieldsPojo additionalFields; public RefsetMemberPojo() {} @Override public String getId() { return id; } @Override public String getConceptId() { return SnomedIdentifierUtils.isValidConceptIdFormat(referencedComponentId) ? referencedComponentId : null; } public void setId(String id) { this.id = id; } public String getEffectiveTime() { return effectiveTime; } public void setReleasedEffectiveTime(String releasedEffectiveTime) { this.releasedEffectiveTime = releasedEffectiveTime; } public String getreleasedEffectiveTime() { return releasedEffectiveTime; } public void setReferencedComponentId(String referencedComponentId) { this.referencedComponentId = referencedComponentId; } public RefsetMemberPojo withReferencedComponentId(String referencedComponentId) { this.referencedComponentId = referencedComponentId; return this; } public String getRefsetId() { return refsetId; } public void setRefsetId(String refsetId) { this.refsetId = refsetId; } public RefsetMemberPojo withRefsetId(String refsetId) { this.refsetId = refsetId; return this; } public AdditionalFieldsPojo getAdditionalFields() { if (this.additionalFields == null) { this.additionalFields = new AdditionalFieldsPojo(); } return additionalFields; } public void setAdditionalFields(AdditionalFieldsPojo additionalFields) { this.additionalFields = additionalFields; } public String getReferencedComponentId() { return referencedComponentId; } public void setEffectiveTime(String effectiveTime) { this.effectiveTime = effectiveTime; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public RefsetMemberPojo withActive(boolean active) { setActive(active); return this; } public String getModuleId() { return moduleId; } public void setModuleId(String moduleId) { this.moduleId = moduleId; } public RefsetMemberPojo withModuleId(String moduleId) { this.moduleId = moduleId; return this; } public boolean getReleased() { return released; } public void setReleased(boolean released) { this.released = released; } public String getMemberId() { return id; } public void setMemberId(String id) { this.id = id; } @Override public String toString() { return id + ":" + refsetId + " " + referencedComponentId + " -> " + additionalFields.toString(); } public String toStringFull() { return "RefsetPojo [id=" + id + ", released=" + released + ", effectiveTime=" + effectiveTime + ", active=" + active + ", moduleId=" + moduleId + ", releasedEffectiveTime=" + releasedEffectiveTime + ", referencedComponentId=" + referencedComponentId + ", refsetId=" + refsetId + ", additionalFields=" + additionalFields + "]"; } }
23.006452
159
0.750421
c69993481693d41ee44663d196c2d8d31b190dd9
8,767
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package moeaframework.moead; import com.mathworks.toolbox.javabuilder.MWException; import emo.Individual; import emo.OptimizationProblem; import emo.OptimizationUtilities; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import kkt.KKT_Calculator; import optimization.TestScript_EMO2017; import optimization.TestScript_IEEE_TEVC_DC_NSGA3; import org.moeaframework.Executor; import org.moeaframework.algorithm.MOEAD; import org.moeaframework.core.NondominatedPopulation; import org.moeaframework.core.Solution; import org.moeaframework.core.TerminationCondition; import org.moeaframework.core.variable.RealVariable; import parsing.IndividualEvaluator; import reference_directions.ReferenceDirection; import utils.InputOutput; /** * * @author Haitham */ public class ReportingExecutor extends Executor { private OptimizationProblem problem; private IndividualEvaluator evaluator; private KKT_Calculator kktCalculator; public ReportingExecutor( OptimizationProblem problem, IndividualEvaluator evaluator, KKT_Calculator kktCalculator, List<ReferenceDirection> referenceDirectionsList) { this.problem = problem; this.evaluator = evaluator; this.kktCalculator = kktCalculator; } @Override protected void preRunLogic(int run) { super.preRunLogic(run); // Create run directory File runOutputDir = TestScript_EMO2017.getRunOutputDir(TestScript_EMO2017.getEngineOutputDir(problem, "moead"), run - 1); runOutputDir.mkdirs(); } @Override protected void postGenerationLogic(int run, int gen) { //System.out.println("G = " + gen + ", FE = " + currentAlgorithm.getNumberOfEvaluations()); try { super.postGenerationLogic(run, gen); // Convert solutions to individuals (MOEA Framework to EvoMO) Individual[] allIndividuals; if (currentAlgorithm instanceof MOEAD) { allIndividuals = new Individual[moeadPopulation.size()]; for (int i = 0; i < moeadPopulation.size(); i++) { double[] solReal = new double[moeadPopulation.get(i).getSolution().getNumberOfVariables()]; for (int j = 0; j < solReal.length; j++) { solReal[j] = ((RealVariable) moeadPopulation.get(i).getSolution().getVariable(j)).getValue(); } // Notice that we are creating a redundant individual here // just for logging purposes. This increase the number of // function evalutaions unjustifiably. If you need the // actual number of function evaluations used by the // algorithm use currentAlgorithm.getNumberOfEvaluations(), // i.e. use the one calculated by MOEA Framework not the one // calculated using our IndividualEvaluator. allIndividuals[i] = new Individual(problem, evaluator, solReal); } dumpOutputFiles(allIndividuals, run, gen); } // else { // allIndividuals = new Individual[currentAlgorithm.getResult().size()]; // for (int i = 0; i < currentAlgorithm.getResult().size(); i++) { // double[] solReal = new double[currentAlgorithm.getResult().get(i).getNumberOfVariables()]; // for (int j = 0; j < solReal.length; j++) { // solReal[j] = ((RealVariable) currentAlgorithm.getResult().get(i).getVariable(j)).getValue(); // } // // Notice that we are creating a redundant individual here // // just for logging purposes. This increase the number of // // function evalutaions unjustifiably. If you need the // // actual number of function evaluations used by the // // algorithm use currentAlgorithm.getNumberOfEvaluations(), // // i.e. use the one calculated by MOEA Framework not the one // // calculated using our IndividualEvaluator. // allIndividuals[i] = new Individual(problem, evaluator, solReal); // } // dumpOutputFiles(allIndividuals, run, gen); // } } catch (FileNotFoundException ex) { Logger.getLogger(ReportingExecutor.class.getName()).log(Level.SEVERE, null, ex); System.out.println(ex.toString()); System.exit(-1); } catch (IOException ex) { Logger.getLogger(ReportingExecutor.class.getName()).log(Level.SEVERE, null, ex); System.out.println(ex.toString()); System.exit(-1); } catch (MWException ex) { Logger.getLogger(ReportingExecutor.class.getName()).log(Level.SEVERE, null, ex); System.out.println(ex.toString()); System.exit(-1); } } private void dumpOutputFiles(Individual[] allIndividuals, int run, int gen) throws IOException, MWException, FileNotFoundException { // Extract non-dominated solutions only. Individual[] nonDominatedIndividuals = OptimizationUtilities.getNonDominatedIndividuals(allIndividuals, 0.0); // Create the hash map to be returned HashMap<String, StringBuilder> dumpMap = new HashMap<>(); // Dump output files File runOutputDir = TestScript_IEEE_TEVC_DC_NSGA3.getRunOutputDir(TestScript_IEEE_TEVC_DC_NSGA3.getEngineOutputDir( problem, "moead"), run - 1); StringBuilder varSpaceSb = InputOutput.collectRealDecisionSpace(problem, nonDominatedIndividuals); StringBuilder objSpaceSb = InputOutput.collectObjectiveSpace(problem, nonDominatedIndividuals); // Var. Space dumpMap.put("var.dat", varSpaceSb); // Obj. Space dumpMap.put("obj.dat", objSpaceSb); // Generations Count dumpMap.put("gen_count", new StringBuilder(String.valueOf(gen - 1))); // Meta Data // double[] hvIdealPoint = evaluator.getIdealPoint(); double[] hvRefPoint = evaluator.getReferencePoint(); for (int i = 0; i < hvRefPoint.length; i++) { hvRefPoint[i] *= 1.01; } StringBuilder metaDataSb = InputOutput.collectMetaData( allIndividuals, evaluator.getIdealPoint(), hvRefPoint, currentAlgorithm.getNumberOfEvaluations(), 0, // Zero numerical function evaluations 0.0); dumpMap.put("meta.txt", metaDataSb); // KKTPM metrics if (kktCalculator != null) { StringBuilder kktpmSb = InputOutput.collectKKTPM( kktCalculator, nonDominatedIndividuals, OptimizationUtilities.pullPointBack(evaluator.getIdealPoint(), 0.01)); dumpMap.put("kkt.dat", kktpmSb); } // Matlab Plotting Scripts (for 2 & 3 objectives) StringBuilder sb = null; if (problem.objectives.length == 2) { sb = InputOutput.createMatlabScript2D(OptimizationUtilities.getNonDominatedIndividuals(nonDominatedIndividuals, 0.0)); } else if (problem.objectives.length == 3) { sb = InputOutput.createMatlabScript3D(OptimizationUtilities.getNonDominatedIndividuals(nonDominatedIndividuals, 0.0)); } if (sb != null) { dumpMap.put("matlab.m", sb); } // Write all to files InputOutput.dumpAll(runOutputDir, dumpMap); } /** * @return the problem */ public OptimizationProblem getProblem() { return problem; } /** * @param problem the problem to set */ public void setProblem(OptimizationProblem problem) { this.problem = problem; } /** * @return the evaluator */ public IndividualEvaluator getEvaluator() { return evaluator; } /** * @param evaluator the evaluator to set */ public void setEvaluator(IndividualEvaluator evaluator) { this.evaluator = evaluator; } }
44.055276
137
0.613551
721ab479f892dcd7b775aecba8ed71c0d1d8632c
1,330
package water.util; import java.util.HashSet; import java.util.Set; import water.api.DocGen.FieldDoc; import water.api.ParamImportance; /** A helper class proving queries over Iced objects parameters. */ public class ParamUtils { /** * Names of the model parameters which will always be shown in a short description of * the model (e.g., for a tree model it would include ntrees and depth). */ public static Set<String> getCriticalParamNames(FieldDoc[] doc) { return getParamNames(doc, ParamImportance.CRITICAL); } /** * Names of the model parameters which will also be shown in a longer description of * the model (e.g., learning rate). */ public static Set<String> getSecondaryParamNames(FieldDoc[] doc) { return getParamNames(doc, ParamImportance.SECONDARY); } /** * Names of the model parameters which will be shown only in an expert view of * the model (e.g., for Deep Learning it would include initial_weight_scale). */ public static Set<String> getExpertParamNames(FieldDoc[] doc) { return getParamNames(doc, ParamImportance.EXPERT); } public static Set<String> getParamNames(FieldDoc[] doc, ParamImportance filter) { HashSet<String> r = new HashSet<String>(); for (FieldDoc d : doc) if (d.importance()==filter) r.add(d.name()); return r; } }
31.666667
87
0.713534
a5b718fa6f2e946b2e4dc6d71cdc05393e332815
1,904
package tck; import org.extra.mutiny.MethodWithCompletable; import org.extra.mutiny.MethodWithMaybeString; import org.extra.mutiny.MethodWithSingleString; import io.vertx.test.core.VertxTestBase; import org.junit.Test; import java.util.concurrent.CompletionStage; public class AsyncResultAdapterTest extends VertxTestBase { @Test public void testSingleReportingSubscribeUncheckedException() { RuntimeException cause = new RuntimeException(); MethodWithSingleString meth = new MethodWithSingleString(handler -> { throw cause; }); CompletionStage<String> single = meth.doSomethingWithResult().subscribeAsCompletionStage(); single.whenComplete((result, err) -> { assertNull(result); assertNotNull(err); testComplete(); }); await(); } @Test public void testMaybeReportingSubscribeUncheckedException() { RuntimeException cause = new RuntimeException(); MethodWithMaybeString meth = new MethodWithMaybeString(handler -> { throw cause; }); CompletionStage<String> single = meth.doSomethingWithMaybeResult().subscribeAsCompletionStage(); single.whenComplete((result, err) -> { assertNull(result); assertNotNull(err); testComplete(); }); await(); } @Test public void testCompletableReportingSubscribeUncheckedException() { RuntimeException cause = new RuntimeException(); MethodWithCompletable meth = new MethodWithCompletable(handler -> { throw cause; }); CompletionStage<Void> single = meth.doSomethingWithResult().subscribeAsCompletionStage(); single.whenComplete((result, err) -> { assertNull(result); assertNotNull(err); testComplete(); }); await(); } }
32.827586
104
0.654937
437c68c3ab62105fe79b7d16ba88b752bfe21fc1
14,989
/* MasterMaze: An RPG Copyright (C) 2011-2012 Eric Ahnell Any questions should be directed to the author via email at: products@puttysoftware.com */ package com.puttysoftware.mastermaze.battle.map; import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.WindowConstants; import com.puttysoftware.commondialogs.CommonDialogs; import com.puttysoftware.images.BufferedImageIcon; import com.puttysoftware.mastermaze.DrawGrid; import com.puttysoftware.mastermaze.MasterMaze; import com.puttysoftware.mastermaze.battle.GenericBattle; import com.puttysoftware.mastermaze.maze.generic.MazeObject; import com.puttysoftware.mastermaze.maze.objects.Darkness; import com.puttysoftware.mastermaze.maze.objects.EmptyVoid; import com.puttysoftware.mastermaze.prefs.PreferencesManager; import com.puttysoftware.mastermaze.resourcemanagers.ImageTransformer; import com.puttysoftware.mastermaze.resourcemanagers.LogoManager; import com.puttysoftware.mastermaze.resourcemanagers.MusicManager; import com.puttysoftware.mastermaze.resourcemanagers.ObjectImageManager; import com.puttysoftware.platform.Platform; class MapBattleGUI { // Fields private JFrame battleFrame; private MapBattleDraw battlePane; private JLabel messageLabel; private final MapBattleViewingWindowManager vwMgr; private final MapBattleStats bs; private final MapBattleEffects be; private DrawGrid drawGrid; boolean eventHandlersOn; // Constructors MapBattleGUI() { this.vwMgr = new MapBattleViewingWindowManager(); this.bs = new MapBattleStats(); this.be = new MapBattleEffects(); this.setUpGUI(); this.eventHandlersOn = true; } // Methods JFrame getOutputFrame() { return this.battleFrame; } MapBattleViewingWindowManager getViewManager() { return this.vwMgr; } void clearStatusMessage() { this.messageLabel.setText(" "); } void setStatusMessage(final String msg) { if (!msg.isEmpty() && !msg.matches("\\s+")) { this.messageLabel.setText(msg); } } void showBattle() { MasterMaze.getApplication().getMenuManager().setBattleMenus(); if (PreferencesManager .getMusicEnabled(PreferencesManager.MUSIC_BATTLE)) { MusicManager.stopMusic(); MusicManager.playMusic("battle"); } this.battleFrame.setVisible(true); this.battleFrame.setJMenuBar( MasterMaze.getApplication().getMenuManager().getMainMenuBar()); } void hideBattle() { if (MusicManager.isMusicPlaying()) { MusicManager.stopMusic(); } if (this.battleFrame != null) { this.battleFrame.setVisible(false); } } void redrawBattle(final MapBattleDefinitions bd) { // Draw the battle, if it is visible if (this.battleFrame.isVisible()) { int x, y; int xFix, yFix; final int xView = this.vwMgr.getViewingWindowLocationX(); final int yView = this.vwMgr.getViewingWindowLocationY(); final int xlView = this.vwMgr.getLowerRightViewingWindowLocationX(); final int ylView = this.vwMgr.getLowerRightViewingWindowLocationY(); for (x = xView; x <= xlView; x++) { for (y = yView; y <= ylView; y++) { xFix = x - xView; yFix = y - yView; try { final BufferedImageIcon icon1 = bd.getBattleMaze() .getBattleGround(y, x).battleRenderHook(); final BufferedImageIcon icon2 = bd.getBattleMaze() .getBattleCell(y, x).battleRenderHook(); this.drawGrid.setImageCell(ImageTransformer .getCompositeImage(icon1, icon2), xFix, yFix); } catch (final ArrayIndexOutOfBoundsException ae) { final EmptyVoid ev = new EmptyVoid(); this.drawGrid.setImageCell(ev.battleRenderHook(), xFix, yFix); } catch (final NullPointerException np) { final EmptyVoid ev = new EmptyVoid(); this.drawGrid.setImageCell(ev.battleRenderHook(), xFix, yFix); } } } this.battlePane.repaint(); this.battleFrame.pack(); } } void redrawOneBattleSquare(final MapBattleDefinitions bd, final int x, final int y, final MazeObject obj3) { // Draw the battle, if it is visible if (this.battleFrame.isVisible()) { try { int xFix, yFix; final int xView = this.vwMgr.getViewingWindowLocationX(); final int yView = this.vwMgr.getViewingWindowLocationY(); xFix = y - xView; yFix = x - yView; final BufferedImageIcon icon1 = bd.getBattleMaze() .getBattleGround(x, y).battleRenderHook(); final BufferedImageIcon icon2 = bd.getBattleMaze() .getBattleCell(x, y).battleRenderHook(); final BufferedImageIcon icon3 = obj3.battleRenderHook(); this.drawGrid.setImageCell(ImageTransformer .getVirtualCompositeImage(icon1, icon2, icon3), xFix, yFix); this.battlePane.repaint(); } catch (final ArrayIndexOutOfBoundsException ae) { // Do nothing } catch (final NullPointerException np) { // Do nothing } this.battleFrame.pack(); } } void updateStatsAndEffects(final MapBattleDefinitions bd) { this.bs.updateStats(bd.getActiveCharacter()); this.be.updateEffects(bd.getActiveCharacter()); } private void setUpGUI() { final EventHandler handler = new EventHandler(); final Container borderPane = new Container(); borderPane.setLayout(new BorderLayout()); this.messageLabel = new JLabel(" "); this.messageLabel.setOpaque(true); if (MasterMaze.inDebugMode()) { this.battleFrame = new JFrame("Battle (DEBUG)"); } else { this.battleFrame = new JFrame("Battle"); } this.battleFrame.setContentPane(borderPane); Platform.hookFrameIcon(this.battleFrame, LogoManager.getIconLogo()); this.battleFrame .setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); this.battleFrame.setResizable(false); this.drawGrid = new DrawGrid( MapBattleViewingWindowManager.getViewingWindowSize()); for (int x = 0; x < MapBattleViewingWindowManager .getViewingWindowSize(); x++) { for (int y = 0; y < MapBattleViewingWindowManager .getViewingWindowSize(); y++) { final MazeObject dark = new Darkness().gameRenderHook(y, x, 0); this.drawGrid.setImageCell(ObjectImageManager.getImage( dark.getName(), dark.getGameBaseID(), dark.getGameTemplateColor(), dark.getGameAttributeID(), dark.getGameAttributeTemplateColor()), x, y); } } this.battlePane = new MapBattleDraw(this.drawGrid); borderPane.add(this.battlePane, BorderLayout.CENTER); borderPane.add(this.messageLabel, BorderLayout.NORTH); borderPane.add(this.bs.getStatsPane(), BorderLayout.EAST); borderPane.add(this.be.getEffectsPane(), BorderLayout.SOUTH); this.battleFrame.addKeyListener(handler); } void turnEventHandlersOff() { this.eventHandlersOn = false; } void turnEventHandlersOn() { this.eventHandlersOn = true; } boolean areEventHandlersOn() { return this.eventHandlersOn; } private class EventHandler implements KeyListener { public EventHandler() { // Do nothing } @Override public void keyPressed(final KeyEvent e) { if (!PreferencesManager.oneMove()) { if (e.isShiftDown()) { this.handleArrows(e); } else { this.handleMovement(e); } } } @Override public void keyReleased(final KeyEvent e) { if (PreferencesManager.oneMove()) { if (e.isShiftDown()) { this.handleArrows(e); } else { this.handleMovement(e); } } } @Override public void keyTyped(final KeyEvent e) { // Do nothing } private void handleMovement(final KeyEvent e) { try { if (System.getProperty("os.name") .equalsIgnoreCase("Mac OS X")) { if (e.isMetaDown()) { return; } } else { if (e.isControlDown()) { return; } } final GenericBattle bl = MasterMaze.getApplication() .getBattle(); final MapBattleGUI bg = MapBattleGUI.this; if (bg.eventHandlersOn) { final int keyCode = e.getKeyCode(); switch (keyCode) { case KeyEvent.VK_NUMPAD4: case KeyEvent.VK_LEFT: case KeyEvent.VK_A: bl.updatePosition(-1, 0); break; case KeyEvent.VK_NUMPAD2: case KeyEvent.VK_DOWN: case KeyEvent.VK_X: bl.updatePosition(0, 1); break; case KeyEvent.VK_NUMPAD6: case KeyEvent.VK_RIGHT: case KeyEvent.VK_D: bl.updatePosition(1, 0); break; case KeyEvent.VK_NUMPAD8: case KeyEvent.VK_UP: case KeyEvent.VK_W: bl.updatePosition(0, -1); break; case KeyEvent.VK_NUMPAD7: case KeyEvent.VK_Q: bl.updatePosition(-1, -1); break; case KeyEvent.VK_NUMPAD9: case KeyEvent.VK_E: bl.updatePosition(1, -1); break; case KeyEvent.VK_NUMPAD3: case KeyEvent.VK_C: bl.updatePosition(1, 1); break; case KeyEvent.VK_NUMPAD1: case KeyEvent.VK_Z: bl.updatePosition(-1, 1); break; case KeyEvent.VK_NUMPAD5: case KeyEvent.VK_S: // Confirm before attacking self final int res = CommonDialogs.showConfirmDialog( "Are you sure you want to attack yourself?", "Battle"); if (res == JOptionPane.YES_OPTION) { bl.updatePosition(0, 0); } break; default: break; } } } catch (final Exception ex) { MasterMaze.getErrorLogger().logError(ex); } } private void handleArrows(final KeyEvent e) { try { if (System.getProperty("os.name") .equalsIgnoreCase("Mac OS X")) { if (e.isMetaDown()) { return; } } else { if (e.isControlDown()) { return; } } final GenericBattle bl = MasterMaze.getApplication() .getBattle(); final MapBattleGUI bg = MapBattleGUI.this; if (bg.eventHandlersOn) { final int keyCode = e.getKeyCode(); switch (keyCode) { case KeyEvent.VK_NUMPAD4: case KeyEvent.VK_LEFT: case KeyEvent.VK_A: bl.fireArrow(-1, 0); break; case KeyEvent.VK_NUMPAD2: case KeyEvent.VK_DOWN: case KeyEvent.VK_X: bl.fireArrow(0, 1); break; case KeyEvent.VK_NUMPAD6: case KeyEvent.VK_RIGHT: case KeyEvent.VK_D: bl.fireArrow(1, 0); break; case KeyEvent.VK_NUMPAD8: case KeyEvent.VK_UP: case KeyEvent.VK_W: bl.fireArrow(0, -1); break; case KeyEvent.VK_NUMPAD7: case KeyEvent.VK_Q: bl.fireArrow(-1, -1); break; case KeyEvent.VK_NUMPAD9: case KeyEvent.VK_E: bl.fireArrow(1, -1); break; case KeyEvent.VK_NUMPAD3: case KeyEvent.VK_C: bl.fireArrow(1, 1); break; case KeyEvent.VK_NUMPAD1: case KeyEvent.VK_Z: bl.fireArrow(-1, 1); break; case KeyEvent.VK_NUMPAD5: case KeyEvent.VK_S: // Confirm before attacking self final int res = CommonDialogs.showConfirmDialog( "Are you sure you want to attack yourself?", "Battle"); if (res == JOptionPane.YES_OPTION) { bl.fireArrow(0, 0); } break; default: break; } } } catch (final Exception ex) { MasterMaze.getErrorLogger().logError(ex); } } } }
38.433333
87
0.507706
45f6b4b5f420d49f4b17d95f2a5a084bb54b90f3
9,204
package TestScript.B2C; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.TimeUnit; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.ui.Select; import org.testng.Assert; import org.testng.ITestContext; import org.testng.annotations.Test; import CommonFunction.Common; import CommonFunction.HMCCommon; import Pages.HMCPage; import TestData.PropsUtils; import TestScript.SuperTestClass; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SHOP34Test extends SuperTestClass { public HMCPage hmcPage; private String siteType = "B2C"; private String mt1 = "22TP2TXX13Y20LD"; private String mt2 = "22TP2TXX13Y20LE"; private String mt3 = "22TP2TXX13Y20LF"; private String mt = "22TP2TXX13Y20LD,22TP2TXX13Y20LE,22TP2TXX13Y20LF"; private String optionID = "4X90L66916"; private String store = "usweb"; private String b2bUnit = ""; private String columnTitle = "store,unit,machineType,optionPartNum,optionDesc,optionType,baseWarrantyKey,supportOS,templateName,groupName,assignedStatus,validateRuleStatus"; public SHOP34Test(String store) { this.Store = store; this.testName = "SHOPE-34"; } @Test(priority = 0, enabled = true, alwaysRun = true, groups = { "shopgroup", "productbuilder", "p2", "b2c" }) public void SHOP34(ITestContext ctx) { try { this.prepareTest(); String filePath = "D:\\SHOP34\\"; deleteFile(filePath); changeChromeDefDownFolder(filePath); hmcPage = new HMCPage(driver); // B2C String catalog = "masterMultiCountryProductCatalog-Online"; downloadPBValidateCSV(catalog, siteType, mt, optionID, store, b2bUnit); ArrayList<String> hmcData = convertHmcValue(); for (String text : hmcData) System.out.println(text); Common.sleep(6000); String downloadFile = filePath + "ProductBuilderValidateResult.csv"; File file = new File(downloadFile); Assert.assertTrue(file.exists()); ArrayList<String> csvData = convertCSV(downloadFile); for (String text : csvData) System.out.println(text); Assert.assertEquals(hmcData, csvData); driver.switchTo().defaultContent(); hmcPage.hmcHome_hmcSignOut.click(); // OUTLET siteType = "OUTLET"; store = "outletus"; deleteFile(filePath); downloadPBValidateCSV(catalog, siteType, mt, optionID, store, b2bUnit); hmcData = convertHmcValue(); for (String text : hmcData) System.out.println(text); Common.sleep(6000); downloadFile = filePath + "ProductBuilderValidateResult.csv"; file = new File(downloadFile); Assert.assertTrue(file.exists()); csvData = convertCSV(downloadFile); for (String text : csvData) System.out.println(text); Assert.assertEquals(hmcData, csvData); driver.switchTo().defaultContent(); hmcPage.hmcHome_hmcSignOut.click(); // B2B siteType = "B2B"; mt1 = "22TP2TT570020HA"; mt2 = "22TP2TXX12Y20JE"; mt3 = "22TP2TXX15G20HQ"; mt = "22TP2TT570020HA,22TP2TXX12Y20JE,22TP2TXX15G20HQ"; optionID = "4X30H56867"; b2bUnit = "1213577815"; store = "usle"; deleteFile(filePath); downloadPBValidateCSV(catalog, siteType, mt, optionID, store, b2bUnit); hmcData = convertHmcValue(); for (String text : hmcData) System.out.println(text); Common.sleep(6000); downloadFile = filePath + "ProductBuilderValidateResult.csv"; file = new File(downloadFile); Assert.assertTrue(file.exists()); csvData = convertCSV(downloadFile); for (String text : csvData) System.out.println(text); Assert.assertEquals(hmcData, csvData); driver.switchTo().defaultContent(); hmcPage.hmcHome_hmcSignOut.click(); deleteFile(filePath); } catch (Throwable e) { handleThrowable(e, ctx); } } private ArrayList<String> convertHmcValue() { ArrayList<String> hmcData = new ArrayList<String>(); int lineTotal = hmcPage.PBValidate_storeColumn.size(); for (int i = 0; i < lineTotal; i++) { if (i != 0) { Assert.assertEquals(hmcPage.PBValidate_storeColumn.get(i).getText(), store); String mtText = hmcPage.PBValidate_machineTypeColumn.get(i).getText().trim(); Assert.assertTrue(mtText.equals(mt1) || mtText.equals(mt2) || mtText.equals(mt3), "mtText: " + mtText + " is not in " + mt); Assert.assertEquals(hmcPage.PBValidate_optionPartNumColumn.get(i).getText().trim(), optionID); if(siteType.equals("B2B")) { Assert.assertEquals(hmcPage.PBValidate_unitColumn.get(i).getText().trim(), b2bUnit); } } String temp = getValue(hmcPage.PBValidate_storeColumn.get(i).getText(), i) + ","; temp = temp + getValue(hmcPage.PBValidate_unitColumn.get(i).getText(), i) + ","; temp = temp + getValue(hmcPage.PBValidate_machineTypeColumn.get(i).getText(), i) + ","; temp = temp + getValue(hmcPage.PBValidate_optionPartNumColumn.get(i).getText(), i) + ","; temp = temp + getValue(hmcPage.PBValidate_optionDescColumn.get(i).getText(), i) + ","; temp = temp + getValue(hmcPage.PBValidate_optionTypeColumn.get(i).getText(), i) + ","; temp = temp + getValue(hmcPage.PBValidate_baseWarrantyKeyColumn.get(i).getText(), i) + ","; temp = temp + getValue(hmcPage.PBValidate_supportOSColumn.get(i).getText(), i) + ","; temp = temp + getValue(hmcPage.PBValidate_templateNameColumn.get(i).getText(), i) + ","; temp = temp + getValue(hmcPage.PBValidate_groupNameColumn.get(i).getText(), i) + ","; temp = temp + getValue(hmcPage.PBValidate_assignedStatusColumn.get(i).getText(), i) + ","; temp = temp + getValue(hmcPage.PBValidate_validateRuleStatusColumn.get(i).getText(), i); hmcData.add(temp); if (i == 0) Assert.assertEquals(temp, columnTitle); } return hmcData; } private String getValue(String text, int i) { if (text.equals("N/A")) text = ""; else if (i == 0) { Pattern p = Pattern.compile("\\s*"); Matcher m = p.matcher(text); text = m.replaceAll(""); } else { Pattern p = Pattern.compile("\\n*"); Matcher m = p.matcher(text); text = m.replaceAll(""); } return text; } private void deleteFile(String filePath) { File file = new File(filePath); if (!file.exists() && !file.isDirectory()) { file.mkdirs(); } if (file.exists()) { File[] files = file.listFiles(); for (File file1 : files) { file1.delete(); } } } private void changeChromeDefDownFolder(String downloadFilepath) throws IOException { driver.close(); HashMap<String, Object> chromePrefs = new HashMap<String, Object>(); chromePrefs.put("profile.default_content_settings.popups", 0); chromePrefs.put("download.default_directory", downloadFilepath); ChromeOptions options = new ChromeOptions(); options.setExperimentalOption("prefs", chromePrefs); DesiredCapabilities cap = DesiredCapabilities.chrome(); cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); cap.setCapability(ChromeOptions.CAPABILITY, options); driver = new ChromeDriver(cap); driver.manage().timeouts().pageLoadTimeout(PropsUtils.getDefaultTimeout(), TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(PropsUtils.getDefaultTimeout(), TimeUnit.SECONDS); driver.manage().window().maximize(); driver.manage().deleteAllCookies(); } private void downloadPBValidateCSV(String catalog, String siteType, String mt, String optioinID, String store, String b2bUnit) throws InterruptedException { driver.get(testData.HMC.getHomePageUrl()); HMCCommon.Login(hmcPage, testData); hmcPage.Home_Nemo.click(); hmcPage.Nemo_productBuilder.click(); hmcPage.productBuilder_productBuilderValidate.click(); driver.switchTo().frame(hmcPage.PBValidate_iframe); Select catalogSel = new Select(hmcPage.PBValidate_catalogVersion); catalogSel.selectByVisibleText(catalog); Select siteTypeSel = new Select(hmcPage.PBValidate_siteType); siteTypeSel.selectByVisibleText(siteType); hmcPage.PBValidate_machineTypes.clear(); hmcPage.PBValidate_machineTypes.sendKeys(mt); if (optioinID != "") hmcPage.PBValidate_optionCode.sendKeys(optioinID); hmcPage.PBValidate_store.sendKeys(store); if (b2bUnit != "") hmcPage.PBValidate_b2bunit.sendKeys(b2bUnit); hmcPage.PBValidate_validateButton.click(); Common.sleep(12000); hmcPage.PBValidate_downloadButton.click(); } private ArrayList<String> convertCSV(String csvFile) { BufferedReader br = null; String line = ""; ArrayList<String> data = new ArrayList<String>(); try { br = new BufferedReader(new FileReader(csvFile)); String temp = ""; while ((line = br.readLine()) != null) { // System.out.println(line); if (line.contains("store,unit,machineType")) data.add(line); else if (!line.startsWith("\",")) temp = temp + line; else { data.add(temp.replaceAll("\"", "")); temp = ""; } } br.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return data; } }
33.469091
174
0.717188
d7860e8b6c5fa9dc5a13d9d9478eab53b4dd2a42
166
package com.ae.gestion.facture.virement.web.request; import lombok.Data; @Data public class VirmentRequest { private Long idFacture; private Double prix; }
16.6
52
0.759036
206b52bfaa9d0df74c8064934eafe9ab5afa20d6
10,086
package jp.co.tis.s2n.javaConverter.convert; import java.io.File; import java.io.IOException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathExpressionException; import org.apache.commons.lang3.StringUtils; import org.xml.sax.SAXException; import jp.co.tis.s2n.converterCommon.log.LogUtils; import jp.co.tis.s2n.converterCommon.struts.analyzer.ClassPathConvertUtil; import jp.co.tis.s2n.converterCommon.struts.analyzer.NablarchRoutingFileGenerator; import jp.co.tis.s2n.converterCommon.struts.analyzer.StrutsAnalyzeResult; import jp.co.tis.s2n.converterCommon.struts.analyzer.output.Route; import jp.co.tis.s2n.javaConverter.convert.logic.ConvertFactory; import jp.co.tis.s2n.javaConverter.convert.logic.ConvertX; import jp.co.tis.s2n.javaConverter.convert.profile.S2nProfile; import jp.co.tis.s2n.javaConverter.convert.sqlfile.SqlFileConverter; import jp.co.tis.s2n.javaConverter.convert.statistics.ActionStatistics; import jp.co.tis.s2n.javaConverter.convert.statistics.AnnotationStatistics; import jp.co.tis.s2n.javaConverter.convert.statistics.OtherStatistics; import jp.co.tis.s2n.javaConverter.convert.statistics.S2JDBCStatistics; import jp.co.tis.s2n.javaConverter.convert.statistics.SQLResultStatistics; import jp.co.tis.s2n.javaConverter.keyword.JavaKeyword; import jp.co.tis.s2n.javaConverter.node.AnnotationNodeUtil; import jp.co.tis.s2n.javaConverter.node.Node; import jp.co.tis.s2n.javaConverter.node.NodeUtil; import jp.co.tis.s2n.javaConverter.parser.JavaParser; /** * S2N JavaConverterの主処理。 * * @author Fumihiko Yamamoto * */ public class ConvertStruts2Nablarch extends AbstractJavaParser implements JavaKeyword { private StrutsAnalyzeResult[] strutsAnalyzeResultList; private Map<String, Route> allRoutes; //プロファイル private S2nProfile activeProfile; private static String sp = System.getProperty("file.separator"); /** * JavaConverterの主処理。 * @param args 引数 * @throws Exception 例外 */ public static void main(String[] args) throws Exception { LogUtils.init(); // パラメータ必須チェック if (args.length < 1) { System.err.print("usage:java -jar javaconverter.jar [設定ファイル]" ); System.exit(-1); } //設定ファイルを読み取り String profileName = args[0]; // 設定ファイル存在チェック if (!new File(profileName).exists()) { System.err.print(profileName + " - エラー:設定ファイルが見つかりません。"); System.exit(-1); } S2nProfile activeProfile = new S2nProfile(profileName); //パッケージマッピングファイル String mappingFileName = null; if (args.length > 1) { mappingFileName = args[1]; // マッピングファイル存在チェック if (!new File(mappingFileName).exists()) { System.err.print(mappingFileName + " - エラー:パッケージマッピングファイルが見つかりません。"); System.exit(-1); } else if (!"csv".equals(mappingFileName.substring(mappingFileName.lastIndexOf('.') + 1))) { System.err.print(mappingFileName + " - エラー:パッケージマッピングファイルをCSVフォーマットにしてください。"); System.exit(-1); } } ClassPathConvertUtil.loadMappingFile(mappingFileName); /**StrutsにおけるFormのBaseクラス、置換前、置換後map*/ ClassPathConvertUtil.loadBaseClassnameConvertMap("BaseClassnameConvertMap.csv"); /**StrutsにおけるServlet関連クラス、置換前、置換後map*/ ClassPathConvertUtil.loadServletClassnameConvertMap("ServletClassnameConvertMap.csv"); String projectPath = activeProfile.getProjectPath(); ConvertStruts2Nablarch parserJava = new ConvertStruts2Nablarch(); parserJava.setActiveProfile(activeProfile); parserJava.setInPath(projectPath + "java" + sp + "from"); parserJava.setOutPath(projectPath + "java" + sp + "to"); parserJava.setTmpPath(projectPath + "java" + sp + "tmp"); parserJava.setCodeName(activeProfile.getFileEncoding()); parserJava.setStrutsAnalyzeResultList(activeProfile.getStrutsAnalyzeResultList()); parserJava.createRoutes(projectPath); parserJava.execute(); //テストアプリにも直接デプロイ if (!StringUtils.isEmpty(activeProfile.getTestDeployPath())) { parserJava.setOutPath(activeProfile.getTestDeployPath()); parserJava.execute(); } if (activeProfile.getSavePathForRoutexml() != null) { NablarchRoutingFileGenerator.saveRoutingFile(parserJava.allRoutes, new File(activeProfile.getSavePathForRoutexml()), activeProfile.getConvertMode()); } SqlFileConverter sqlFileConv = new SqlFileConverter(); sqlFileConv.setInPath(projectPath + "sql" + sp + "from"); sqlFileConv.setOutPath(projectPath + "sql" + sp + "to"); sqlFileConv.setTmpPath(projectPath + "sql" + sp + "tmp"); sqlFileConv.setCodeName(activeProfile.getFileEncoding()); sqlFileConv.setActiveProfile(activeProfile); sqlFileConv.execute(); AnnotationStatistics.getInstance().exportData(); S2JDBCStatistics.getInstance().exportData(); ActionStatistics.getInstance().exportData(); OtherStatistics.getInstance().exportData(); SQLResultStatistics.exportData(); } /** * プロファイルを設定する。 * @param activeProfile プロファイル */ public void setActiveProfile(S2nProfile activeProfile) { this.activeProfile = activeProfile; } /** * Strutsの設定ファイルからRoutes.xmlを構築する。 * @param projectPath プロジェクトパス * @throws XPathExpressionException 例外 * @throws SAXException 例外 * @throws IOException 例外 * @throws ParserConfigurationException 例外 */ protected void createRoutes(String projectPath) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException { Map<String, Route> routes = new LinkedHashMap<>(); this.allRoutes = routes; if (getStrutsAnalyzeResultList() == null) { return; } //Routeに書き出すために合成 for (StrutsAnalyzeResult cResult : this.getStrutsAnalyzeResultList()) { Map<String, Route> cRoutes = cResult.getRoutes(); for (Route val : cRoutes.values()) { routes.put(val.getPath(), val); } } } protected void executeFile(String inFilePath, String outPath, String fileName){ println("<<File:" + inFilePath); String inputPath = new File(inFilePath).getParent(); Node topNode = JavaParser.parse(inputPath, fileName, this.codeName); modify(inFilePath, fileName, topNode); postProc(outPath, fileName, topNode, activeProfile); } protected void modify(String inFilePath, String fileName, Node topNode) { String className = "jp.co.tis.s2n.javaConverter.convert.logic.Convert"; if (fileName.endsWith("Form.java")) { className += "Form"; } else if (fileName.endsWith("Action.java")) { className += "Action"; } else if (fileName.endsWith("Logic.java")) { className += "Logic"; } else if (fileName.endsWith("Service.java")) { className += "Service"; } else if (fileName.endsWith("Dto.java")) { className += "Dto"; } else { //ファイルの中身を見て判別する String fileType = determine(topNode); className += fileType; } if (className != null) { ConvertX conv = ConvertFactory.getInstance(className, fileName); try { ClassPathConvertUtil.getInstance().resetMap(); conv.setActiveProfile(this.activeProfile); conv.initVelocityEngine(); conv.setStrutsAnalyzeResult(this.getStrutsAnalyzeResultList()); conv.setAllRoutes(this.allRoutes); conv.makeAnnotationLog(topNode); conv.convertProc(fileName, topNode); } catch (Exception ex) { LogUtils.warn(fileName, className, "例外が発生しました。", ex); ex.printStackTrace(); } } } /** * ファイルの中身を見て種類の判別を実施する。 * @param topNode トップノード * @return ファイルの種別 */ private String determine(Node topNode) { List<Node> annotationNodes = NodeUtil.findAllNode(topNode, "@Generated"); if(annotationNodes == null || annotationNodes.size() == 0) { List<Node> annotationNodesEntity = NodeUtil.findAllNode(topNode, "@Entity"); if(annotationNodesEntity != null && annotationNodesEntity.size() > 0) { return "Entity"; } } for (Node annotationNode : annotationNodes) { AnnotationNodeUtil anode = new AnnotationNodeUtil(annotationNode); String value = anode.getStringValueWithoutQuote("value"); if ((value != null) && (value.contains("S2JDBC-Gen"))) { if (value.contains("EntityModelFactoryImpl")) { //エンティティで確定 return "Entity"; } else if (value.contains("ServiceModelFactoryImpl")) { //サービスで確定だがServlce専用処理はないのでOthersで返す return "Others"; } } } return "Others"; } /** * Strutsの分析結果を取得する。 * @return Strutsの分析結果 */ public StrutsAnalyzeResult[] getStrutsAnalyzeResultList() { return strutsAnalyzeResultList; } /** * Strutsの分析結果を設定する。 * @param strutsAnalyzeResultList Strutsの分析結果 */ public void setStrutsAnalyzeResultList(StrutsAnalyzeResult[] strutsAnalyzeResultList) { this.strutsAnalyzeResultList = strutsAnalyzeResultList; } }
37.080882
105
0.634245
252725658ab5096ded59aedde8fa90c68728824a
5,486
/** * Copyright 2008-2017 Qualogy Solutions B.V. * * 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.qualogy.qafe.bind.presentation.component; import java.util.List; /** * @author rjankie */ public class DataGrid extends EditableComponent implements HasComponents { private static final long serialVersionUID = 3607530581878883535L; private Integer maxRows; private Integer pageSize; private Integer currentPage; private Integer minRows; private Boolean delete = Boolean.FALSE; private Boolean add = Boolean.FALSE; private Boolean pageScroll = Boolean.FALSE; private Boolean export = Boolean.FALSE; private String exportFormats = "excel,pdf,csv,xml"; private Boolean importEnabled = Boolean.FALSE; private String importAction = "set"; private List<DataGridColumn> columns; private OverFlowPanel overflow; private DatagridControlBar controlbar; private Boolean multipleSelect; private String rowColors; private Boolean selectFirstRow; private Boolean save; private Boolean cancel; private Boolean refresh; private String overflowGroup; public String getExportFormats() { return exportFormats; } public void setExportFormats(String exportFormats) { this.exportFormats = exportFormats; } public Boolean getImportEnabled() { return importEnabled; } public void setImportEnabled(Boolean importEnabled) { this.importEnabled = importEnabled; } public String getImportAction() { return importAction; } public void setImportAction(String importAction) { this.importAction = importAction; } public DatagridControlBar getControlbar() { return controlbar; } public void setControlbar(DatagridControlBar controlbar) { this.controlbar = controlbar; } public List<DataGridColumn> getColumns() { return columns; } public void setColumns(List<DataGridColumn> columns) { this.columns = columns; } /** * @deprecated */ @Deprecated public Integer getMaxRows() { return maxRows; } /** * @deprecated */ @Deprecated public void setMaxRows(Integer maxRows) { this.maxRows = maxRows; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public Integer getCurrentPage() { return currentPage; } public void setCurrentPage(Integer currentPage) { this.currentPage = currentPage; } public Boolean getDelete() { return delete; } public void setDelete(Boolean delete) { this.delete = delete; } public Boolean getAdd() { return add; } public void setAdd(Boolean add) { this.add = add; } public Integer getMinRows() { return minRows; } public void setMinRows(Integer minRows) { this.minRows = minRows; } public Boolean getExport() { return export; } public void setExport(Boolean export) { this.export = export; } public OverFlowPanel getOverflow() { return overflow; } public void setOverflow(OverFlowPanel overflow) { this.overflow = overflow; } public boolean hasOverflow() { return (overflow != null); } public boolean hasColumns() { return (columns != null); } @Override public List<? extends Component> getComponents() { return columns; } public Boolean getMultipleSelect() { return multipleSelect; } public void setMultipleSelect(Boolean multipleSelect) { this.multipleSelect = multipleSelect; } public String getRowColors() { return rowColors; } public void setRowColors(String rowColors) { this.rowColors = rowColors; } public Boolean getPageScroll() { return pageScroll; } public void setPageScroll(Boolean pageScroll) { this.pageScroll = pageScroll; } public Boolean getSelectFirstRow() { return selectFirstRow; } public void setSelectFirstRow(Boolean selectFirstRow) { this.selectFirstRow = selectFirstRow; } public Boolean getSave() { return save; } public void setSave(Boolean save) { this.save = save; } public Boolean getCancel() { return cancel; } public void setCancel(Boolean cancel) { this.cancel = cancel; } public Boolean getRefresh() { return refresh; } public void setRefresh(Boolean refresh) { this.refresh = refresh; } public String getOverflowGroup() { return overflowGroup; } public void setOverflowGroup(String overflowGroup) { this.overflowGroup = overflowGroup; } }
20.938931
75
0.648742
b9da75fb5b5f175c4243a9b393d7f6b6f29f85b7
340
package com.brianway.learning.spring.aop.aspectj.anno; public class ForumService { @NeedTest(value = true) public void deleteForum(int forumId) { System.out.println("删除论坛模块:" + forumId); } @NeedTest(value = false) public void deleteTopic(int topicId) { System.out.println("删除论坛主题:" + topicId); } }
24.285714
54
0.658824
d5457c903cf1bfa620b04cddaac6220322cd2529
231
package com.haulmont.sample.petclinic.service; public interface VisitTestDataCreationService { String NAME = "petclinic_VisitTestDataCreationService"; void createVisits(); boolean necessaryToCreateVisitTestData(); }
23.1
59
0.796537
a70c960f9620c9a6a3377a62bc5f91dc31ffa86d
1,739
package org.anddev.andengine.util; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import org.anddev.andengine.util.constants.Constants; public class SimplePreferences implements Constants { private static SharedPreferences.Editor EDITORINSTANCE; private static SharedPreferences INSTANCE; private static final String PREFERENCES_NAME = null; public static int getAccessCount(Context paramContext, String paramString) { return getInstance(paramContext).getInt(paramString, 0); } public static SharedPreferences.Editor getEditorInstance(Context paramContext) { if (EDITORINSTANCE == null) { EDITORINSTANCE = getInstance(paramContext).edit(); } return EDITORINSTANCE; } public static SharedPreferences getInstance(Context paramContext) { if (INSTANCE == null) { INSTANCE = paramContext.getSharedPreferences(PREFERENCES_NAME, 0); } return INSTANCE; } public static int incrementAccessCount(Context paramContext, String paramString) { return incrementAccessCount(paramContext, paramString, 1); } public static int incrementAccessCount(Context paramContext, String paramString, int paramInt) { SharedPreferences localSharedPreferences = getInstance(paramContext); int i = paramInt + localSharedPreferences.getInt(paramString, 0); localSharedPreferences.edit().putInt(paramString, i).commit(); return i; } } /* Location: C:\Users\Rodelle\Desktop\Attacknid\Tools\Attacknids-dex2jar.jar * Qualified Name: org.anddev.andengine.util.SimplePreferences * JD-Core Version: 0.7.0.1 */
32.203704
97
0.732605
d72cfb3f7c5619fc29f016f1e61ccd4192d049ec
4,220
package de.kontextwork.poc.spring.blaze.fullapp.rolemembership; import com.blazebit.persistence.view.EntityViewManager; import com.blazebit.persistence.view.EntityViewSetting; import de.kontextwork.poc.spring.blaze.core.PageableEntityViewRepository; import de.kontextwork.poc.spring.blaze.core.RegularEntityViewRepository; import de.kontextwork.poc.spring.blaze.fullapp.realm.RealmService; import de.kontextwork.poc.spring.blaze.fullapp.realm.model.jpa.Realm; import de.kontextwork.poc.spring.blaze.fullapp.realm.model.view.RealmIdView; import de.kontextwork.poc.spring.blaze.fullapp.role.RoleService; import de.kontextwork.poc.spring.blaze.fullapp.role.model.jpa.RealmRole; import de.kontextwork.poc.spring.blaze.fullapp.role.model.view.RoleIdView; import de.kontextwork.poc.spring.blaze.fullapp.rolemembership.model.view.RealmRoleMembershipCreateView; import de.kontextwork.poc.spring.blaze.fullapp.rolemembership.model.view.RealmRoleMembershipIdView; import de.kontextwork.poc.spring.blaze.fullapp.subject.SubjectService; import de.kontextwork.poc.spring.blaze.fullapp.subject.model.view.SubjectIdView; import de.kontextwork.poc.spring.blaze.fullapp.subject.user.model.jpa.User; import de.kontextwork.poc.spring.configuration.BlazePersistenceConfiguration; import de.kontextwork.poc.spring.configuration.JpaBlazeConfiguration; import java.util.Set; import org.junit.jupiter.api.Test; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.jdbc.AutoConfigureDataJdbc; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.context.annotation.Import; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.jdbc.Sql.ExecutionPhase; import static org.assertj.core.api.Assertions.assertThat; @Import({ SubjectService.class, RealmService.class, RoleService.class, RealmRoleMembershipService.class, JpaBlazeConfiguration.class, BlazePersistenceConfiguration.class, PageableEntityViewRepository.class, RegularEntityViewRepository.class, ModelMapper.class }) @AutoConfigureDataJdbc @DataJpaTest(properties = {"blazepersistance.enabled=true"}) class RealmRoleMembershipServiceTest { @Autowired EntityViewManager entityViewManager; @Autowired private SubjectService subjectService; @Autowired private RealmService realmService; @Autowired private RoleService roleService; @Autowired private RealmRoleMembershipService realmRoleMembershipService; @Test @Sql( statements = "alter table subject_user modify uid bigint auto_increment;", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD ) void createMembership() { User user = subjectService.create(new User("John", "Doe")); Realm realm = realmService.create(new Realm("Random")); RealmRole role = roleService.create(new RealmRole("SOME_ROLE", Set.of())); final SubjectIdView subjectIdView = subjectService.getOneAsIdView(user.getId()).orElseThrow(); final RealmIdView realmIdView = realmService.getOneAsIdView(realm.getId()).orElseThrow(); final RoleIdView roleIdView = roleService.getOneAsIdView(role.getId()).orElseThrow(); RealmRoleMembershipCreateView createView = entityViewManager.create(RealmRoleMembershipCreateView.class); createView.setRealm(realmIdView); createView.setRole(roleIdView); createView.setSubject(subjectIdView); realmRoleMembershipService.create(createView); assertThat( realmRoleMembershipService.findAll(EntityViewSetting.create(RealmRoleMembershipIdView.class)).size() ).isNotZero(); } @Test @Sql( statements = "alter table subject_user modify uid bigint auto_increment;", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD ) void assign() { User user = subjectService.create(new User("John", "Doe")); Realm realm = realmService.create(new Realm("Random")); RealmRole role = roleService.create(new RealmRole("SOME_ROLE", Set.of())); realmRoleMembershipService.assign(realm, role, user); assertThat( realmRoleMembershipService.findAll(EntityViewSetting.create(RealmRoleMembershipIdView.class)).size() ).isNotZero(); } }
43.505155
131
0.811611
ac02e5b2b18a51757c8c60a625cc0f937a10c849
9,361
package com.antest1.gotobrowser.Browser; import android.media.MediaPlayer; import android.os.Handler; import com.antest1.gotobrowser.Helpers.KcUtils; import com.antest1.gotobrowser.Helpers.MediaPlayerPool; import com.antest1.gotobrowser.Subtitle.KcSubtitleUtils; import com.crashlytics.android.Crashlytics; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; public class BrowserSoundPlayer { public final static String PLAYER_ALL = "all"; public final static String PLAYER_BGM = "bgm"; public final static String PLAYER_SE = "se"; public final static String PLAYER_VOICE = "voice"; public final static int AUDIO_POOL_LIMIT = 25; private static boolean isMuteMode = false; private Handler handler; private Map<String, MediaPlayerPool> players = new HashMap<>(); private Map<String, Float> volumes = new HashMap<>(); private float currentBgmVolume; public static boolean ismute() { return isMuteMode; } public static void setmute(boolean value) { isMuteMode = value; } public static void mute() { setmute(true); } public static void unmute() { setmute(false); } public BrowserSoundPlayer(Handler subtitle_handler) { players.put(PLAYER_BGM, new MediaPlayerPool(1)); players.put(PLAYER_SE, new MediaPlayerPool(AUDIO_POOL_LIMIT)); players.put(PLAYER_VOICE, new MediaPlayerPool(1)); volumes.put(PLAYER_BGM, 1.0f); volumes.put(PLAYER_SE, 0.7f); volumes.put(PLAYER_VOICE, 0.8f); handler = subtitle_handler; } public boolean shouldAudioLoop(String url) { return url.contains("resources/bgm") && !url.contains("fanfare"); } public void setVolume(String player_set, float value) { if (PLAYER_ALL.equals(player_set)) { for (String key: volumes.keySet()) { volumes.put(key, value); if (isMuteMode) players.get(key).setVolumeAll(0.0f, 0.0f); else players.get(key).setVolumeAll(value, value); } } else { String[] player_list = player_set.split(","); for (String key: player_list) { if (volumes.containsKey(key)) { volumes.put(key, value); if (isMuteMode) players.get(key).setVolumeAll(0.0f, 0.0f); else players.get(key).setVolumeAll(value, value); } } } } public void setMuteAll(boolean is_mute) { setmute(is_mute); for (String key: volumes.keySet()) { float volume = is_mute ? 0.0f : volumes.get(key); players.get(key).setVolumeAll(volume, volume); } } public void setStreamsLimit(String player_set, int value) { try { if (PLAYER_ALL.equals(player_set)) { for (String key: players.keySet()) { players.get(key).setStreamsLimit(value); } } else { String[] player_list = player_set.split(","); for (String key: player_list) { if (players.containsKey(key)) players.get(key).setStreamsLimit(value); } } } catch (NullPointerException e) { KcUtils.reportException(e); } } private boolean set(MediaPlayer player, File file, float volume) { if (isMuteMode) volume = 0.0f; try { String path = file.getAbsolutePath(); player.setVolume(volume, volume); player.setLooping(shouldAudioLoop(path)); player.setDataSource(path); player.prepare(); return true; } catch (IOException e) { KcUtils.reportException(e); return false; } } public void setNextPlay(String player_id, File file, ResourceProcess.SubtitleRunnable sr) { MediaPlayerPool player = players.get(player_id); player.setOnAllCompletedListener((pool, lastPlayer) -> { play(player_id, file); handler.post(sr); player.setOnAllCompletedListener(null); }); } public void play(String player_id, File file) { MediaPlayerPool player = players.get(player_id); float volume = ismute() ? 0.0f : volumes.get(player_id); if (player != null) { MediaPlayer audio = new MediaPlayer(); boolean result = set(audio, file, volume); if (result) { player.addToPool(audio); audio.start(); } } } public void pause(String player_set) { String[] player_list = player_set.split(","); for (String key: player_list) { if (players.containsKey(key)) { players.get(key).pauseAll(); } } } public void stop(String player_set) { String[] player_list = player_set.split(","); for (String key: player_list) { if (players.containsKey(key)) { players.get(key).stopAll(); } } } public void startAll() { for (String key: players.keySet()) { MediaPlayerPool player = players.get(key); if (!player.isAnyPlaying()) { players.get(key).startAll(); } } } public void pauseAll() { for (String key: players.keySet()) { MediaPlayerPool player = players.get(key); if (player.isAnyPlaying()) { players.get(key).pauseAll(); } } } public void stopAll() { for (String key: players.keySet()) { players.get(key).stopAll(); } } public void releaseAll() { for (String key: players.keySet()) { players.get(key).release(); } } public void stopSound(String url, boolean isOnPractice, int currentMapId, int currentBattleBgmId) { String[] STOP_FLAG = { "battle_result/battle_result_main.json", "battle/battle_main.json", "/kcs2/resources/se/217.mp3" }; for (String pattern: STOP_FLAG) { if (url.contains(pattern)) { boolean fadeout_flag = true; boolean shutter_call = url.contains("/se/217.mp3"); if (shutter_call) { if (isOnPractice) { isOnPractice = false; continue; } JsonObject bgmData = KcSubtitleUtils.getMapBgmGraph(currentMapId); if (bgmData != null) { JsonArray normal_bgm = bgmData.getAsJsonArray("api_map_bgm"); boolean normal_diff = normal_bgm.get(0).getAsInt() != normal_bgm.get(1).getAsInt(); boolean normal_flag = currentBattleBgmId == normal_bgm.get(0).getAsInt() && normal_diff; JsonArray boss_bgm = bgmData.getAsJsonArray("api_boss_bgm"); boolean boss_diff = boss_bgm.get(0).getAsInt() != boss_bgm.get(1).getAsInt(); boolean boss_flag = currentBattleBgmId == boss_bgm.get(0).getAsInt() && boss_diff; fadeout_flag = normal_flag || boss_flag; } } if (fadeout_flag) { fadeBgmOut(); break; } } } String[] STOP_V_FLAG = { "api_req_map", "api_get_member/slot_item" }; for (String pattern: STOP_V_FLAG) { if (url.contains(pattern)) { stop(PLAYER_VOICE); } } } public void fadeBgmOut() { if (isMuteMode) return; final int FADE_DURATION = 720; final int FADE_INTERVAL = 80; final float MAX_VOLUME = volumes.get(PLAYER_BGM); MediaPlayerPool bgm_player = players.get(PLAYER_BGM); int numberOfSteps = FADE_DURATION / FADE_INTERVAL; final float deltaVolume = MAX_VOLUME / (float) numberOfSteps; currentBgmVolume = MAX_VOLUME; final Timer timer = new Timer(true); TimerTask timerTask = new TimerTask() { @Override public void run() { try { if (isMuteMode) currentBgmVolume = 0.0f; bgm_player.setVolumeAll(currentBgmVolume, currentBgmVolume); currentBgmVolume -= deltaVolume; if(currentBgmVolume < 0.0f){ stop(PLAYER_BGM); timer.cancel(); timer.purge(); bgm_player.setVolumeAll(MAX_VOLUME, MAX_VOLUME); } } catch (IllegalStateException e) { stop(PLAYER_BGM); timer.cancel(); timer.purge(); bgm_player.setVolumeAll(MAX_VOLUME, MAX_VOLUME); Crashlytics.logException(e); } } }; timer.schedule(timerTask, 0, FADE_INTERVAL); } }
34.799257
112
0.552826
23a16a6959309fabf287af08382447d53a3713be
1,617
package com.ggg.et3.domain; import java.util.ArrayList; import java.util.List; import com.ggg.et3.jpa.entity.Category; import com.ggg.et3.jpa.entity.CategoryTag; import com.ggg.et3.jpa.service.CategoryService; import com.ggg.et3.jpa.service.CategoryTagService; /** * This class holds a list of CategoryTags which holds a list of tags per Category * Used in display tags view * @author gg2712 * */ public class CategoryTagsSet { private List<CategoryTags> ctList; public CategoryTagsSet() { super(); ctList = new ArrayList<CategoryTags>(); CategoryService cs = CategoryService.getInstance(); List<Category> catList = cs.find(); CategoryTagService cts = CategoryTagService.getInstance(); for (Category cat : catList) { List<CategoryTag> ctagList = cts.findByCategory(cat); if (ctagList.size() > 0) { CategoryTags categoryTags = new CategoryTags(cat.getName()); for (CategoryTag ctag : ctagList) { categoryTags.add(new Tag(ctag.getId(), ctag.getTag(), ctag.getCategory().getName())); } add(categoryTags); } } } private void add(CategoryTags tags) { ctList.add(tags); } public List<CategoryTags> getCategoryTagsList() { return ctList; } public static void main(String[] args) { CategoryTagsSet cts = new CategoryTagsSet(); List<CategoryTags> ctagsList = cts.getCategoryTagsList(); for(CategoryTags ctags : ctagsList) { List<Tag> tagList = ctags.getTags(); System.out.println("***" + ctags.getCategory()); for(Tag tag : tagList) { System.out.println(tag); } } } }
21.851351
90
0.681509
ef2eb68d77718f63f552eeff560f079d8e1a1a43
2,647
/* * JMAB - Java Macroeconomic Agent Based Modeling Toolkit * Copyright (C) 2013 Alessandro Caiani and Antoine Godin * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * 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 General Public License for more details. */ package benchmark.population; import java.util.List; import benchmark.StaticValues; import jmab.agents.MacroAgent; import jmab.events.MacroTicEvent; import jmab.population.AbstractPopulationHandler; import jmab.population.PopulationHandler; import net.sourceforge.jabm.Population; import net.sourceforge.jabm.agent.Agent; /** * @author Alessandro Caiani and Antoine Godin * */ public class NoEntryPopulationHandler extends AbstractPopulationHandler implements PopulationHandler { /* (non-Javadoc) * @see jmab.population.PopulationHandler#initialiseAgent(net.sourceforge.jabm.agent.Agent, net.sourceforge.jabm.agent.Agent) */ @Override public void initialiseAgent(Agent newAgent, Agent oldAgent) { // TODO Auto-generated method stub //For the moment, not sure we need this method } /* (non-Javadoc) * @see jmab.population.AbstractPopulationHandler#handleAgent(net.sourceforge.jabm.agent.Agent, int, java.util.List, int) */ @Override protected void handleAgent(Agent agent, int id, List<Agent> agents, int populationId) { // TODO Auto-generated method stub //For the moment, not sure we need this method } /* (non-Javadoc) * @see jmab.population.AbstractPopulationHandler#onTicArrived(jmab.events.MacroTicEvent) */ @Override protected void onTicArrived(MacroTicEvent event) { switch(event.getTic()){ case StaticValues.TIC_POPULATIONHANDLER: updatePopulations(); break; } } /** * */ private void updatePopulations() { removeDeadAgents(); } /** * */ private void removeDeadAgents() { List<Population> populations= population.getPopulations(); for (Population population:populations){ List<Agent> populationAgents= population.getAgentList().getAgents(); for (int i=0;i<populationAgents.size();i++){ MacroAgent agent=(MacroAgent)populationAgents.get(i); if (agent.isDead()){ populationAgents.remove(i); } } } } }
28.462366
127
0.717794
78f5d40d4c2da5b4d24630300912c420b527f41d
370
package com.kintone.client.model.record; import lombok.Value; /** A value object for a Text field. */ @Value public class SingleLineTextFieldValue implements FieldValue { /** The value of the Text field. */ private final String value; /** {@inheritDoc} */ @Override public FieldType getType() { return FieldType.SINGLE_LINE_TEXT; } }
20.555556
61
0.681081
7d5763dbaf315577bcc1d2636c6dbfce666e71c2
2,440
package ru.apetrov; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; import ru.apetrov.models.*; public class HorseTest{ @Test public void whenMoveHorseUpLeft1(){ ChessBoard board = new ChessBoard(); Horse horse = new Horse(new Position(4, 4)); board.addFigure(horse); Position position = new Position(3, 2); board.move(horse, position); assertThat(horse.getPosition(), is(position)); } @Test public void whenMoveHorseUpLeft2(){ ChessBoard board = new ChessBoard(); Horse horse = new Horse(new Position(4, 4)); board.addFigure(horse); Position position = new Position(2, 3); board.move(horse, position); assertThat(horse.getPosition(), is(position)); } @Test public void whenMoveHorseUpRight1(){ ChessBoard board = new ChessBoard(); Horse horse = new Horse(new Position(4, 4)); board.addFigure(horse); Position position = new Position(5, 2); board.move(horse, position); assertThat(horse.getPosition(), is(position)); } @Test public void whenMoveHorseUpRight2(){ ChessBoard board = new ChessBoard(); Horse horse = new Horse(new Position(4, 4)); board.addFigure(horse); Position position = new Position(6, 3); board.move(horse, position); assertThat(horse.getPosition(), is(position)); } @Test public void whenMoveHorseDownLeft1(){ ChessBoard board = new ChessBoard(); Horse horse = new Horse(new Position(4, 4)); board.addFigure(horse); Position position = new Position(3, 6); board.move(horse, position); assertThat(horse.getPosition(), is(position)); } @Test public void whenMoveHorseDownLeft2(){ ChessBoard board = new ChessBoard(); Horse horse = new Horse(new Position(4, 4)); board.addFigure(horse); Position position = new Position(2, 5); board.move(horse, position); assertThat(horse.getPosition(), is(position)); } @Test public void whenMoveHorseDownRight1(){ ChessBoard board = new ChessBoard(); Horse horse = new Horse(new Position(4, 4)); board.addFigure(horse); Position position = new Position(5, 6); board.move(horse, position); assertThat(horse.getPosition(), is(position)); } @Test public void whenMoveHorseDownRight2(){ ChessBoard board = new ChessBoard(); Horse horse = new Horse(new Position(4, 4)); board.addFigure(horse); Position position = new Position(6, 5); board.move(horse, position); assertThat(horse.getPosition(), is(position)); } }
27.111111
48
0.711475
bbdade000af825e6d03ab0941c583a0737aa2296
452
package io.redspark.ireadme.init; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; @Configuration @PropertySource(value = "classpath:config/${spring.profiles.active}.properties", ignoreResourceNotFound = true) @Import({ AppDataSource.class, AppPersistenceConfig.class , AppSecurityConfig.class}) public class AppConfig {}
41.090909
111
0.836283
f0b4e8cd170ac0a677964b517d8dc151e3a6ba5d
1,508
package com.ragemachine.moon.api.mixin.mixins; import com.ragemachine.moon.MoonHack; import com.ragemachine.moon.impl.client.modules.render.EnchantColor; import net.minecraft.client.renderer.RenderItem; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumHand; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyArg; @Mixin({ RenderItem.class }) public class MixinRenderItem { @Shadow private void renderModel(final IBakedModel model, final int color, final ItemStack stack) { } @ModifyArg(method = { "renderEffect" }, at = @At(value = "INVOKE", target = "net/minecraft/client/renderer/RenderItem.renderModel(Lnet/minecraft/client/renderer/block/model/IBakedModel;I)V"), index = 1) private int renderEffect(final int oldValue) { return MoonHack.getModuleManager.getModule(EnchantColor.class).isEnabled() ? EnchantColor.getColor(1L, 1.0f).getRGB() : oldValue; } private boolean isHandGood(final EnumHand activeHand, final boolean leftHandedRenderHand) { switch (activeHand) { case MAIN_HAND: { return leftHandedRenderHand; } case OFF_HAND: { return !leftHandedRenderHand; } default: { return false; } } } }
35.069767
206
0.700265