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
ce2328560e2c021f8291d35fbf1aa77dbf9cc83c
245
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class Npe { void bar() { final @Nullable Object o = foo(); o.hashCode(); // NPE } @Nullable Object foo() { return null; } }
17.5
42
0.636735
c20e22742ea8a41a3a1382bf83e5ebb4fb803dff
999
package com.github.jayield.rapper.unitofwork; import com.github.jayield.rapper.DomainObject; import java.util.Queue; public class CreateHelper extends AbstractCommitHelper { public CreateHelper(UnitOfWork unit, Queue<DomainObject> list) { super(unit, list); } @Override public Object identityMapUpdateNext() { if (objectIterator == null) objectIterator = list.iterator(); if (objectIterator.hasNext()) { DomainObject object = objectIterator.next(); unit.validate(object.getIdentityKey(), object); return true; } return null; } @Override public Object rollbackNext() { if (objectIterator == null) objectIterator = list.iterator(); if (objectIterator.hasNext()) { DomainObject domainObject = objectIterator.next(); unit.invalidate(domainObject.getClass(), domainObject.getIdentityKey()); return true; } return null; } }
29.382353
84
0.641642
3cfe1f613c5de442342b1bd8bf89378ee2f8c39d
890
import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Movie implements Serializable { private static final long serialVersionUID = 1L; String movieImdbLink = ""; String movieTitle = ""; String titleYear = ""; String imdbScore = ""; String directorName = ""; String actor1Name = ""; String actor2Name = ""; String actor3Name = ""; String duration = ""; String budget = ""; String contentRating = ""; List<String> genres = new ArrayList<>(); String movieFacebookLikes = ""; String directorFacebookLikes = ""; String actor1FacebookLikes = ""; String actor2FacebookLikes = ""; String actor3FacebookLikes = ""; String castTotalFacebookLikes = ""; String facenumberInPoster = ""; String gross = ""; String posterLink = ""; @Override public String toString() { return this.movieTitle + " (" + this.movieImdbLink + ")"; } }
24.054054
59
0.693258
f7b34a42d68a798314c994e229519f8d6678c098
1,590
/* * 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 control; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.logging.Level; import java.util.logging.Logger; public class telaEstoque { private String nome; private String valor; public String getQuantidade() { return quantidade; } public void setQuantidade(String quantidade) { this.quantidade = quantidade; } private String quantidade; public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getValor() { return valor; } public void setValor(String valor) { this.valor = valor; } public String salvar(){ try { FileWriter fw = new FileWriter("estoque.txt",true); PrintWriter pw = new PrintWriter(fw); //escrever conteudo no arquivo e pular linha pw.println("Nome: "+nome+"Valor: "+valor); //pw.println("Valor: "+valor); //pw.println("Quantidade: "+quantidade); pw.flush();// enviar os dados no momento pw.close();// fechar o pw fw.close(); } catch (IOException ex) { Logger.getLogger(telaArtista.class.getName()).log(Level.SEVERE, null, ex); } return "Salvo com sucesso"; } }
25.645161
93
0.595597
1e5175d5c9118d225e8a3c2dbfb53a9877f09c64
526
package lab8; import java.io.*; public class CopyDataThread extends Thread { public CopyDataThread(FileWriter f1, File f2) throws IOException, InterruptedException { FileReader fr=new FileReader("f1"); int x=fr.read( ); FileWriter f = new FileWriter(f2); int i = 0; while( x!=-1) { f.write((char)x); i++; if(i%10 == 0) { System.out.println("10 characters are copied"); sleep(500); } x=fr.read(); } } }
21.916667
92
0.534221
a9f1e95aa3fd95be7406fd9aa7472c6c1cc14981
11,347
/* * (c) Tyler Hostager, 2018. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.*; /** * ViewController object acts as a delegate between the model and view objects * * @author Tyler Hostager * @version 1.0.0 * @since 2/18/18 */ public class ViewController implements ActionListener, ISharedApplicationObjects { private T3ALauncherModel model; private MainGUI view; private String previousCmd; private JRadioButton previousBtn, currentBtn; private boolean isDebug; private boolean hasSeenResPrompt; public static ViewController CURRENT_VC; public static MainGUI CURRENT_UI; public static T3ALauncherModel CURRENT_MODEL; //region - CONSTRUCTORS /** * Default constructor * * Only use this if you need static access to something or aboslutely must create a * new empty instance of a controller. Otherwise, eternal sadness and other bad things * will occur. */ public ViewController() { /* Do nothing... woohoo! */ } /** * Constructs view controller using custom debug settings * * @param isDebug */ public ViewController(boolean isDebug) { this.isDebug = isDebug; } /** * * @param model * @param view */ public ViewController(@NotNull T3ALauncherModel model, @NotNull MainGUI view) { this.model = model; this.view = view; ViewController.CURRENT_UI = this.view; ViewController.CURRENT_VC = this; ViewController.CURRENT_MODEL = this.model; } /** * * @param isDebug * @param model * @param view */ public ViewController(boolean isDebug, @NotNull T3ALauncherModel model, @NotNull MainGUI view) { this.isDebug = isDebug; this.model = model; this.view = view; this.previousCmd = "BFME1"; this.previousBtn = view.getB1Btn(); this.currentBtn = view.getB1Btn(); ViewController.CURRENT_MODEL = this.model; ViewController.CURRENT_VC = this; ViewController.CURRENT_UI = this.view; initUI(); addActionListeners(); } //endregion /** * */ public void initUI() { initUI(true); } /** * * @param isDebug */ public void initUI(boolean isDebug) { ViewController.CURRENT_VC = this; this.isDebug = isDebug; try { view.initUI(); Runnable prompt = this::promptResolutionDetectionDialog; Thread promptThread = new Thread(prompt); promptThread.start(); while (true) { if (!promptThread.isAlive()) { view.launchMainWindow(); break; } } } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private void addActionListeners() { view.getB1Btn().addActionListener(this); view.getB2Btn().addActionListener(this); view.getRotwkBtn().addActionListener(this); view.getResChooser().addActionListener(this); } public boolean isDebug() { return isDebug; } public void setDebug(boolean debug) { isDebug = debug; } public T3ALauncherModel getModel() { return model; } /** */ public void setModel(T3ALauncherModel model) { this.model = model; } public MainGUI getView() { return view; } /** */ public void setView(MainGUI view) { this.view = view; } /** */ private void promptResolutionDetectionDialog() { try { Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); Double x = dimension.getWidth(); Double y = dimension.getHeight(); Integer xInt = Math.round(x.intValue()); Integer yInt = Math.round(y.intValue()); if (!hasSeenResPrompt) { Runnable dialogTask = () -> JOptionPane.showMessageDialog( new JFrame() { @Override public int getDefaultCloseOperation() { view.repaint(); return DISPOSE_ON_CLOSE; } }, "RESOLUTION AUTO-DETECTION:\n\nDetected Resolution: \"" .concat(String.valueOf(xInt)) .concat("x") .concat(String.valueOf(yInt)) .concat("\"\nSetting value as default...") ); hasSeenResPrompt = true; Thread dThread = new Thread(dialogTask); dThread.start(); } Runnable detectResolution; if (view != null && view.getResChooser() != null && view.getResChooser().getItemCount() > 0) { detectResolution = () -> { if (view.getResChooser().getItemCount() > 0) { for (int i = 0; i < view.getResChooser().getItemCount() - 1; i++) { if (((String) view.getResChooser().getItemAt(i)).substring(0, 2).contains(x.toString().substring(0, 2))) { view.getResChooser().setSelectedItem(view.getResChooser().getItemAt(i)); view.getResChooser().setSelectedIndex(i); } } } }; detectResolution.run(); view.repaint(); } else { view.initUI(); promptResolutionDetectionDialog(); } } catch (Exception e) { System.err.println(e.getMessage()); System.out.println(); e.printStackTrace(); } } /** * * @param e */ @Override public void actionPerformed(ActionEvent e) { try { if (e.getSource() instanceof JComponent) { JComponent component = (JComponent) e.getSource(); if (component instanceof JRadioButton) { JRadioButton btn = (JRadioButton) component; JRadioButton otherBtn = previousBtn == null ? view.getB1Btn() : previousBtn; currentBtn = btn; if (!btn.getActionCommand().equals(previousCmd) && !btn.getActionCommand().equals(model.getSelectedGame().getName())) { String btmTxt = "Lord of the Rings - The Battle for Middle-Earth"; view.getLotrTitleTxt1().setText(btmTxt); if (!currentBtn.isSelected()) { currentBtn.setSelected(true); model.setSelectedGame( currentBtn.getActionCommand().equals("BFME2") ? Game.BFME2 : ( currentBtn.getActionCommand().equals("BFME1") ? Game.BFME1 : Game.ROTWK ) ); } String selectedGame = model.getSelectedGame().getName(); String newTxt = btmTxt.concat( selectedGame.contains("ROTWK") ? " Rise of the Witch King" : ( selectedGame.contains("2") ? " II" : "" ) ); view.getLotrTitleTxt1().setText(newTxt); } else { if (!btn.isSelected()) { if (btn.getActionCommand().equals(view.getB1Btn().getActionCommand())) { view.getB2Btn().setSelected(false); view.getRotwkBtn().setSelected(false); } else if (btn.getActionCommand().equals(view.getB2Btn().getActionCommand())) { view.getB1Btn().setSelected(false); view.getRotwkBtn().setSelected(false); } else if (btn.getActionCommand().equals(view.getRotwkBtn().getActionCommand())) { view.getB1Btn().setSelected(false); view.getB2Btn().setSelected(false); } btn.setSelected(true); } } String cmd1 = otherBtn.getActionCommand(); String cmd2 = btn.getActionCommand(); view.getBkgdImgPanel().chgImgSelectionsForActionCommands(cmd1, cmd2); previousBtn = btn; currentBtn = null; } else if (component instanceof JComboBox) { String parsedResolution = ((String)((JComboBox) component).getSelectedItem()); parsedResolution = parsedResolution == null ? "" : parsedResolution; String xRes, yRes; String t2[] = parsedResolution.split("x"); xRes = t2[0]; yRes = t2[1]; Integer xVal = null; Integer yVal = null; ResObject resolution = null; try { xVal = Integer.parseInt(xRes); yVal = Integer.parseInt(yRes); } catch (Exception ex) { JOptionPane.showMessageDialog(view, ex.getMessage()); } if (xRes != null && yRes != null) { resolution = new ResObject(xVal, yVal); } } } } catch (Exception ex) { System.out.println("\n\nERROR: " + ex.getMessage()); JOptionPane.showMessageDialog(view.getContentPane(), ex.getMessage()); } if (e.getSource() instanceof JRadioButton) { previousCmd = e.getActionCommand(); } } }
36.252396
139
0.525778
ad7ea36ee1404c4d56036c7a1c557d732576da65
585
package edu.pse.beast.highlevel; /** * The ResultInterface provides the necessary methods to present the result of a * check. * @author Jonas */ public interface ResultInterface { /** * * @return if the result is in a state where it can be presented */ boolean readyToPresent(); /** * Presents the result of the check. * Every class that extends this class has to implement it for itself. * @param presenter the presentable where it is supposed to be presented on */ void presentTo(ResultPresenterElement presenter); }
26.590909
80
0.673504
2f86b46c57faf20247d32655edbe6fa5899b7ea1
1,193
package tokyo.peya.plugins.peyangplayerreporter.util; import tokyo.peya.lib.SQLModifier; import tokyo.peya.plugins.peyangplayerreporter.Variables; import java.sql.Connection; import java.util.Date; import java.util.UUID; public class ChatLogger { public static void onChat(UUID senderUUID, String content) { try(Connection connection = Variables.chatLog.getConnection()) { SQLModifier.insert(connection, "CHAT_LOG", senderUUID.toString(), new Date().getTime(), content ); } catch (Exception e) { e.printStackTrace(); } } public static void onPrivateMessage(UUID senderUUID, UUID recipientUUID, String content) { try(Connection connection = Variables.chatLog.getConnection()) { SQLModifier.insert(connection, "PRIV_MSG_LOG", senderUUID.toString(), recipientUUID.toString(), new Date().getTime(), content ); } catch (Exception e) { e.printStackTrace(); } } }
26.511111
92
0.562448
4e1fe50e33f74c029b2e43452d015c19abee7648
1,094
package com.hjqjl.whlibrary.utils; import android.annotation.SuppressLint; import android.content.Context; import android.text.TextUtils; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.hjqjl.whlibrary.R; public class ToastUtil { private static Toast toast; public static void showC(Context context, String text) { if (TextUtils.isEmpty(text)) { return; } if (toast == null) { toast = new Toast(context); } else { toast.cancel(); toast = new Toast(context); } LayoutInflater inflater = LayoutInflater.from(context); @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.custom_toast_layout, null); TextView textView1 = view.findViewById(R.id.tv_toast); textView1.setText(text); toast.setView(view); toast.setGravity(Gravity.CENTER, 0, 0); toast.setDuration(Toast.LENGTH_SHORT); toast.show(); } }
29.567568
104
0.664534
821bbbae443b826d30315d4d7f6d915a59cf2118
1,532
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * 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.teiid.translator.marshallers; import java.io.IOException; import org.infinispan.protostream.MessageMarshaller; public class G3Marshaller implements MessageMarshaller<G3> { @Override public String getTypeName() { return "pm1.G3"; } @Override public Class<G3> getJavaClass() { return G3.class; } @Override public G3 readFrom(ProtoStreamReader reader) throws IOException { int e1 = reader.readInt("e1"); String e2 = reader.readString("e2"); G3 g3 = new G3(); g3.setE1(e1); g3.setE2(e2); return g3; } @Override public void writeTo(ProtoStreamWriter writer, G3 g3) throws IOException { writer.writeInt("e1", g3.getE1()); writer.writeString("e2", g3.getE2()); } }
29.461538
77
0.686684
911829856ad16da0bab59b736327458bc0d302a3
4,193
package it.jira.permission; import com.atlassian.jira.config.properties.APKeys; import com.atlassian.plugin.connect.modules.beans.ProjectPermissionCategory; import com.atlassian.plugin.connect.modules.beans.ProjectPermissionModuleBean; import com.atlassian.plugin.connect.modules.beans.nested.I18nProperty; import com.atlassian.plugin.connect.modules.beans.nested.SingleConditionBean; import com.atlassian.plugin.connect.modules.util.ModuleKeyUtils; import com.atlassian.plugin.connect.test.common.servlet.ConnectRunner; import com.atlassian.plugin.connect.test.common.util.AddonTestUtils; import it.jira.JiraTestBase; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.util.Map; import static it.jira.permission.PermissionJsonBean.PermissionType.PROJECT; import static it.jira.permission.PermissionJsonBeanMatcher.isPermission; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; public class TestProjectPermission extends JiraTestBase { private static final String pluginKey = AddonTestUtils.randomAddonKey(); private static final String permissionKey = "plugged-project-permission"; private static final String fullPermissionKey = ModuleKeyUtils.addonAndModuleKey(pluginKey, permissionKey); private static final String permissionName = "Custom connect project permission"; private static final String description = "Custom connect global permission"; private static final ProjectPermissionCategory permissionCategory = ProjectPermissionCategory.ISSUES; private static final String projectKey = "TEST"; private static MyPermissionRestClient myPermissionRestClient; private static ConnectRunner remotePlugin; @BeforeClass public static void startConnectAddon() throws Exception { myPermissionRestClient = new MyPermissionRestClient(product); remotePlugin = new ConnectRunner(product.environmentData().getBaseUrl().toString(), pluginKey) .setAuthenticationToNone() .addModule( "jiraProjectPermissions", ProjectPermissionModuleBean.newProjectPermissionModuleBean() .withKey(permissionKey) .withName(new I18nProperty(permissionName, null)) .withDescription(new I18nProperty(description, null)) .withCategory(permissionCategory) .withConditions(SingleConditionBean.newSingleConditionBean() .withCondition("voting_enabled") .build()) .build() ) .start(); } @AfterClass public static void stopConnectAddon() throws Exception { if (remotePlugin != null) { remotePlugin.stopAndUninstall(); } } @Before public void setup() { product.backdoor().project().addProject("Test project", projectKey, "admin"); } @After public void tearDown() { product.backdoor().project().deleteProject(projectKey); } @Test public void pluggableProjectPermissionShouldDisplayOnTheProjectPermission() throws Exception { Map<String, PermissionJsonBean> myPermissions = myPermissionRestClient.getMyPermissions(); PermissionJsonBean permission = myPermissions.get(fullPermissionKey); assertThat(permission, isPermission(fullPermissionKey, PROJECT, permissionName, description)); } @Test public void pluggableProjectPermissionShouldNotDisplayIfConditionsAreNotFulfilled() throws Exception { product.backdoor().applicationProperties().setOption(APKeys.JIRA_OPTION_VOTING, false); Map<String, PermissionJsonBean> myPermissions = myPermissionRestClient.getMyPermissions(); PermissionJsonBean permission = myPermissions.get(fullPermissionKey); assertThat(permission, nullValue()); product.backdoor().applicationProperties().setOption(APKeys.JIRA_OPTION_VOTING, true); } }
44.606383
111
0.714524
ad8be487b45903d7cf1e50e32a90d6bd457e9f6f
1,291
/** * Copyright 2012 XnnYygn * * 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.hako.dao.db.vendor; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; /** * An adapter of {@link DataSource} to {@link DbVendor}. * * @author xnnyygn * @version %I%, %G% * @since 1.0.0 * @see DataSource#getConnection() */ public class DataSourceAdapter extends SingleDbVendor { private final DataSource source; /** * Create * * @param source */ public DataSourceAdapter(DataSource source) { super(); this.source = source; } public Connection connect() throws ConnectException { try { return source.getConnection(); } catch (SQLException e) { throw new ConnectException(e); } } }
23.907407
80
0.695585
85292e6c54aa229ad3d70b6fe599211e70bc90a6
827
package top.niunaijun.obfuscator; import com.googlecode.dex2jar.ir.stmt.LabelStmt; import com.googlecode.dex2jar.ir.stmt.Stmt; import com.googlecode.dex2jar.ir.stmt.Stmts; import org.objectweb.asm.Label; import java.util.ArrayList; import java.util.List; public class LBlock { private LabelStmt labelStmt; private List<Stmt> stmts = new ArrayList<>(); public LBlock() { this.labelStmt = Stmts.nLabel(); this.labelStmt.tag = new Label(); } public LBlock(LabelStmt labelStmt, List<Stmt> stmts) { this.labelStmt = labelStmt; this.stmts = stmts; } public LabelStmt getLabelStmt() { return labelStmt; } public void setLabelStmt(LabelStmt labelStmt) { this.labelStmt = labelStmt; } public List<Stmt> getStmts() { return stmts; } public void setStmts(List<Stmt> stmts) { this.stmts = stmts; } }
20.170732
55
0.73156
3d3eb7dff0fdf2c0194b6aafd8343fe6935a51fa
2,342
package org.jenkinsci.plugins.webhookstep; import hudson.FilePath; import hudson.model.Result; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; import org.jenkinsci.plugins.workflow.test.steps.SemaphoreStep; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.RestartableJenkinsRule; import java.io.File; import java.net.URL; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class WaitForWebhookRestartTest { @Rule public RestartableJenkinsRule rr = new RestartableJenkinsRule(); @Test public void testWaitHook() throws Exception { URL url = this.getClass().getResource("/simple.json"); FilePath contentFilePath = new FilePath(new File(url.getFile())); String content = contentFilePath.readToString(); rr.then(rr -> { WorkflowJob p = rr.jenkins.createProject(WorkflowJob.class, "prj"); p.setDefinition(new CpsFlowDefinition( "node {\n" + " def hook = registerWebhook(token: \"test-token\")\n" + " echo \"token=${hook.token}\"\n" + " semaphore 'started'\n" + " def data = waitForWebhook(hook)\n" + " echo \"${data}\"" + "}", true)); WorkflowRun b = p.scheduleBuild2(0).getStartCondition().get(); SemaphoreStep.waitForStart("started/1", b); assertTrue(JenkinsRule.getLog(b), b.isBuilding()); }); rr.then(rr -> { WorkflowJob job = rr.jenkins.getItemByFullName("prj", WorkflowJob.class); assertNotNull(job); WorkflowRun run = job.getBuildByNumber(1); assertNotNull(run); SemaphoreStep.success("started/1", null); rr.postJSON("webhook-step/test-token", content); rr.waitForCompletion(run); rr.assertBuildStatus(Result.SUCCESS, run); rr.assertLogContains("token=test-token", run); rr.assertLogContains("\"action\":\"done\"", run); }); } }
35.484848
85
0.611016
927ab94d43c46fa65c818f869c746a24c8775e88
4,530
package gui_elements.combo_boxes; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import game_object.PropertyNotFoundException; import gui_elements.panes.CustomFunctionNamesPane; import gui_elements.panes.CustomFunctionsPane; import gui_elements.panes.MainPane; import interactions.CustomComponentParameterFormat; import interactions.CustomFunction; import interactions.InteractionManager; import javafx.event.ActionEvent; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; public class CustomFunctionTypeComboBox extends MainComboBox { private static final String FILENAME = "custom_function_type_cb.properties"; private static final String CUSTOM_FUNCTIONS_FILENAME = "data/CustomFunctions.properties"; private static final String BLANK = ""; private static final String COLON = ":"; private static final String CATCH_IO_EXCEPTION_STRING = "Cannot get all custom functions!"; private static final String FINALLY_IO_EXCEPTION_STRING = "Cannot close custom functions file!"; private Map<String, String> custom_function_map; private InteractionManager interaction_manager; private CustomFunctionNamesPane custom_function_names_pane; private CustomFunctionsPane custom_functions_pane; private CustomFunction custom_function; private int interaction_id; public CustomFunctionTypeComboBox(InteractionManager interaction_manager, int interaction_id, MainPane custom_function_names_pane, MainPane custom_functions_pane, CustomFunction custom_function) { super(FILENAME); this.interaction_manager = interaction_manager; this.interaction_id = interaction_id; this.custom_function_names_pane = (CustomFunctionNamesPane) custom_function_names_pane; this.custom_functions_pane = (CustomFunctionsPane) custom_functions_pane; this.custom_function = custom_function; custom_function_map = new HashMap<String, String>(); chooseElements(); } private void chooseElements() { getCustomFunctions(); getComboBox().setOnAction((ActionEvent ev) -> { String type = getComboBox().getSelectionModel().getSelectedItem(); custom_function = interaction_manager.getInteraction(interaction_id).generateCustomFunction(type); CustomComponentParameterFormat format = custom_function.getParameterFormat(); createInformationAlert(custom_function, format); List<String> parameterList = format.getParameterList(); custom_function_names_pane.getPane().getChildren().clear(); custom_functions_pane.getPane().getChildren().clear(); for(int i = 0; i < parameterList.size(); i++) { String parameter = parameterList.get(i); custom_function_names_pane.addCustomFunctionNameLabel(parameter + COLON); try { String value = format.getParameterValue(parameter); custom_functions_pane.addCustomFunctionTextField(value); } catch (PropertyNotFoundException e) { custom_functions_pane.addCustomFunctionTextField(BLANK); } } }); } private void getCustomFunctions() { Properties properties = new Properties(); InputStream input = null; try { input = new FileInputStream(CUSTOM_FUNCTIONS_FILENAME); properties.load(input); for(Object key : properties.keySet()) { String custom_function_string = (String) key; getComboBox().getItems().add(custom_function_string); custom_function_map.put(custom_function_string, properties.getProperty(custom_function_string)); } } catch (IOException ex) { logError(ex, Level.SEVERE, CATCH_IO_EXCEPTION_STRING); } finally { if (input != null) { try { input.close(); } catch (IOException e) { logError(e, Level.SEVERE, FINALLY_IO_EXCEPTION_STRING); } } } } private void logError(Exception e, Level level, String error) { Logger logger = Logger.getAnonymousLogger(); Exception ex = new Exception(e); logger.log(level, error, ex); } public CustomFunction getCurrentSelectedCustomFunction() { return custom_function; } private void createInformationAlert(CustomFunction custom_function, CustomComponentParameterFormat format) { Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle(custom_function.getName()); alert.setHeaderText(null); alert.setContentText(format.getHelpText()); alert.showAndWait(); } }
39.051724
109
0.772406
ac5fb97887c93859afd9471f2525ea7a4d6232c0
7,593
/* * Copyright 2013-2020 consulo.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.navigationToolbar; import com.intellij.ide.structureView.StructureViewBuilder; import com.intellij.ide.structureView.StructureViewModel; import com.intellij.ide.structureView.StructureViewTreeElement; import com.intellij.ide.structureView.TreeBasedStructureViewBuilder; import com.intellij.ide.structureView.impl.common.PsiTreeElementBase; import com.intellij.ide.ui.UISettings; import com.intellij.ide.util.treeView.smartTree.NodeProvider; import com.intellij.ide.util.treeView.smartTree.TreeElement; import com.intellij.lang.Language; import com.intellij.lang.LanguageStructureViewBuilder; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; import consulo.annotation.access.RequiredReadAction; import consulo.util.lang.Comparing; import consulo.util.lang.ObjectUtil; import consulo.util.lang.ref.SoftReference; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * from kotlin */ public abstract class StructureAwareNavBarModelExtension extends AbstractNavBarModelExtension { @Nullable private SoftReference<PsiFile> currentFile; @Nullable private SoftReference<StructureViewModel> currentFileStructure; private long currentFileModCount = -1; @Nonnull protected abstract Language getLanguage(); @Nonnull protected List<NodeProvider<?>> getApplicableNodeProviders() { return Collections.emptyList(); } protected boolean acceptParentFromModel(PsiElement psiElement) { return true; } @Override @RequiredReadAction public PsiElement getLeafElement(@Nonnull DataContext dataContext) { if (UISettings.getInstance().getShowMembersInNavigationBar()) { PsiFile psiFile = dataContext.getData(CommonDataKeys.PSI_FILE); Editor editor = dataContext.getData(CommonDataKeys.EDITOR); if (psiFile == null || editor == null) return null; PsiElement psiElement = psiFile.findElementAt(editor.getCaretModel().getOffset()); if (psiElement != null && psiElement.getLanguage() == getLanguage()) { StructureViewModel model = buildStructureViewModel(psiFile, editor); if (model != null) { Object currentEditorElement = model.getCurrentEditorElement(); if (currentEditorElement instanceof PsiElement) { return ((PsiElement)currentEditorElement).getOriginalElement(); } } } } return null; } @Override @RequiredReadAction public boolean processChildren(Object object, Object rootElement, Processor<Object> processor) { if (UISettings.getInstance().getShowMembersInNavigationBar()) { if (object instanceof PsiElement) { if (((PsiElement)object).getLanguage() == getLanguage()) { StructureViewModel model = buildStructureViewModel(((PsiElement)object).getContainingFile(), null); if (model != null) { return processStructureViewChildren(model.getRoot(), object, processor); } } } } return super.processChildren(object, rootElement, processor); } @Nullable @Override @RequiredReadAction public PsiElement getParent(@Nonnull PsiElement psiElement) { if (psiElement.getLanguage() == getLanguage()) { PsiFile containingFile = psiElement.getContainingFile(); if (containingFile == null) { return null; } StructureViewModel model = buildStructureViewModel(containingFile, null); if (model != null) { PsiElement parentInModel = findParentInModel(model.getRoot(), psiElement); if(acceptParentFromModel(parentInModel)) { return parentInModel; } } } return super.getParent(psiElement); } @Override public boolean normalizeChildren() { return false; } @Nullable @RequiredReadAction private PsiElement findParentInModel(StructureViewTreeElement root, PsiElement psiElement) { for (TreeElement child : childrenFromNodeAndProviders(root)) { if(child instanceof StructureViewTreeElement) { if(Comparing.equal(((StructureViewTreeElement)child).getValue(), psiElement)) { return ObjectUtil.tryCast(root.getValue(), PsiElement.class); } PsiElement target = findParentInModel((StructureViewTreeElement)child, psiElement); if(target != null) { return target; } } } return null; } @RequiredReadAction private boolean processStructureViewChildren(StructureViewTreeElement parent, Object object, Processor<Object> processor) { List<TreeElement> children = childrenFromNodeAndProviders(parent); boolean result = true; if (Comparing.equal(parent.getValue(), object)) { for (TreeElement child : children) { if (child instanceof StructureViewTreeElement) { if (!processor.process(((StructureViewTreeElement)child).getValue())) { result = false; } } } } else { for (TreeElement child : children) { if (child instanceof StructureViewTreeElement) { if (!processStructureViewChildren((StructureViewTreeElement)child, object, processor)) { result = false; } } } } return result; } @RequiredReadAction private List<TreeElement> childrenFromNodeAndProviders(StructureViewTreeElement parent) { List<TreeElement> children; if (parent instanceof PsiTreeElementBase) { children = ((PsiTreeElementBase)parent).getChildrenWithoutCustomRegions(); } else { children = Arrays.asList(parent.getChildren()); } List<TreeElement> fromProviders = getApplicableNodeProviders().stream().flatMap(nodeProvider -> nodeProvider.provideNodes(parent).stream()).collect(Collectors.toList()); return ContainerUtil.concat(children, fromProviders); } @Nullable private StructureViewModel buildStructureViewModel(PsiFile file, @Nullable Editor editor) { if (Comparing.equal(SoftReference.deref(currentFile), file) && currentFileModCount == file.getModificationStamp()) { StructureViewModel model = SoftReference.deref(currentFileStructure); if (model != null) { return model; } } StructureViewBuilder builder = LanguageStructureViewBuilder.INSTANCE.getStructureViewBuilder(file); if (builder instanceof TreeBasedStructureViewBuilder) { StructureViewModel model = ((TreeBasedStructureViewBuilder)builder).createStructureViewModel(editor); currentFile = new SoftReference<>(file); currentFileStructure = new SoftReference<>(model); currentFileModCount = file.getModificationStamp(); return model; } return null; } }
35.647887
173
0.727512
aa09de2a6f52fe6291e87e3e01ac2d587b7b0585
1,816
/* * (c) Copyright 2015 Micro Focus or one of its affiliates. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. * * The only warranties for products and services of Micro Focus and its affiliates * and licensors ("Micro Focus") are as may be set forth in the express warranty * statements accompanying such products and services. Nothing herein should be * construed as constituting an additional warranty. Micro Focus shall not be * liable for technical or editorial errors or omissions contained herein. The * information contained herein is subject to change without notice. */ package com.hp.autonomy.searchcomponents.idol.answer.requests; import com.hp.autonomy.searchcomponents.core.requests.RequestObjectTest; import com.hp.autonomy.searchcomponents.idol.answer.ask.AskAnswerServerRequest; import com.hp.autonomy.searchcomponents.idol.answer.ask.AskAnswerServerRequestBuilder; import com.hp.autonomy.types.requests.idol.actions.answer.params.AskSortParam; import java.io.IOException; public class AskAnswerServerRequestTest extends RequestObjectTest<AskAnswerServerRequest, AskAnswerServerRequestBuilder> { @Override protected String json() throws IOException { return "{\"text\": \"GPU\", \"sort\": \"SYSTEM\", \"systemName\": \"answerbank0\", \"maxResults\": 5, \"minScore\": 0}"; } @Override protected AskAnswerServerRequest constructObject() { return AskAnswerServerRequestImpl.builder() .text("GPU") .sort(AskSortParam.SYSTEM) .systemName("answerbank0") .maxResults(5) .minScore(0d) .build(); } @Override protected String toStringContent() { return "text"; } }
39.478261
128
0.715859
b05246a4bb7dce578b50976fa64c139e9eec9ac9
1,122
package org.mockserver.client.serialization.model; import org.junit.Test; import org.mockserver.model.Body; import org.mockserver.model.RegexBody; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.mockserver.model.RegexBody.regex; /** * @author jamesdbloom */ public class RegexBodyDTOTest { @Test public void shouldReturnValuesSetInConstructor() { // when RegexBodyDTO regexBody = new RegexBodyDTO(new RegexBody("some_body")); // then assertThat(regexBody.getRegex(), is("some_body")); assertThat(regexBody.getType(), is(Body.Type.REGEX)); } @Test public void shouldBuildCorrectObject() { // when RegexBody regexBody = new RegexBodyDTO(new RegexBody("some_body")).buildObject(); // then assertThat(regexBody.getValue(), is("some_body")); assertThat(regexBody.getType(), is(Body.Type.REGEX)); } @Test public void shouldReturnCorrectObjectFromStaticBuilder() { assertThat(regex("some_body"), is(new RegexBody("some_body"))); } }
27.365854
89
0.688948
597b61bb1b3a9326e86a100d4ee1615d540a4a74
254
package com.qintess.clinicaVeterinaria.repositorios; import org.springframework.data.repository.CrudRepository; import com.qintess.clinicaVeterinaria.entidades.Especie; public interface EspecieRepositorio extends CrudRepository<Especie, Integer> { }
25.4
78
0.854331
7daf72092c11da2a158e4eaec5aa9228dfb9e575
1,060
package com.snc.zero.handler; import android.annotation.SuppressLint; import android.os.Handler; import android.os.Looper; import android.os.Message; /** * Handler * * @author [email protected] * @since 2018 */ public class EventHandler { @SuppressLint("HandlerLeak") private final Handler mHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { if (null != msg) { if (msg.obj instanceof Runnable) { ((Runnable) msg.obj).run(); } } super.handleMessage(msg); } }; public void postDelayed(Runnable runnable, long delayMillis) { mHandler.removeCallbacks(runnable); mHandler.postDelayed(runnable, delayMillis); } /* public void post(Runnable runnable) { mHandler.removeCallbacks(runnable); mHandler.post(runnable); } public void removeCallbacks(Runnable runnable) { mHandler.removeCallbacks(runnable); } */ }
23.043478
74
0.616038
03f12de3d34480ea0bc5e42ab8e5506c344f8c69
7,433
package visualization_msgs.msg.dds; import us.ihmc.communication.packets.Packet; import us.ihmc.euclid.interfaces.Settable; import us.ihmc.euclid.interfaces.EpsilonComparable; import java.util.function.Supplier; import us.ihmc.pubsub.TopicDataType; /** * MenuEntry message. * * Each InteractiveMarker message has an array of MenuEntry messages. * A collection of MenuEntries together describe a * menu/submenu/subsubmenu/etc tree, though they are stored in a flat * array. The tree structure is represented by giving each menu entry * an ID number and a "parent_id" field. Top-level entries are the * ones with parent_id = 0. Menu entries are ordered within their * level the same way they are ordered in the containing array. Parent * entries must appear before their children. * * Example: * - id = 3 * parent_id = 0 * title = "fun" * - id = 2 * parent_id = 0 * title = "robot" * - id = 4 * parent_id = 2 * title = "pr2" * - id = 5 * parent_id = 2 * title = "turtle" * * Gives a menu tree like this: * - fun * - robot * - pr2 * - turtle */ public class MenuEntry extends Packet<MenuEntry> implements Settable<MenuEntry>, EpsilonComparable<MenuEntry> { /** * Command_type stores the type of response desired when this menu * entry is clicked. * FEEDBACK: send an InteractiveMarkerFeedback message with menu_entry_id set to this entry's id. * ROSRUN: execute "rosrun" with arguments given in the command field (above). * ROSLAUNCH: execute "roslaunch" with arguments given in the command field (above). */ public static final byte FEEDBACK = (byte) 0; public static final byte ROSRUN = (byte) 1; public static final byte ROSLAUNCH = (byte) 2; /** * ID is a number for each menu entry. Must be unique within the * control, and should never be 0. */ public long id_; /** * ID of the parent of this menu entry, if it is a submenu. If this * menu entry is a top-level entry, set parent_id to 0. */ public long parent_id_; /** * menu / entry title */ public java.lang.StringBuilder title_; /** * Arguments to command indicated by command_type (below) */ public java.lang.StringBuilder command_; public byte command_type_; public MenuEntry() { title_ = new java.lang.StringBuilder(255); command_ = new java.lang.StringBuilder(255); } public MenuEntry(MenuEntry other) { this(); set(other); } public void set(MenuEntry other) { id_ = other.id_; parent_id_ = other.parent_id_; title_.setLength(0); title_.append(other.title_); command_.setLength(0); command_.append(other.command_); command_type_ = other.command_type_; } /** * ID is a number for each menu entry. Must be unique within the * control, and should never be 0. */ public void setId(long id) { id_ = id; } /** * ID is a number for each menu entry. Must be unique within the * control, and should never be 0. */ public long getId() { return id_; } /** * ID of the parent of this menu entry, if it is a submenu. If this * menu entry is a top-level entry, set parent_id to 0. */ public void setParentId(long parent_id) { parent_id_ = parent_id; } /** * ID of the parent of this menu entry, if it is a submenu. If this * menu entry is a top-level entry, set parent_id to 0. */ public long getParentId() { return parent_id_; } /** * menu / entry title */ public void setTitle(java.lang.String title) { title_.setLength(0); title_.append(title); } /** * menu / entry title */ public java.lang.String getTitleAsString() { return getTitle().toString(); } /** * menu / entry title */ public java.lang.StringBuilder getTitle() { return title_; } /** * Arguments to command indicated by command_type (below) */ public void setCommand(java.lang.String command) { command_.setLength(0); command_.append(command); } /** * Arguments to command indicated by command_type (below) */ public java.lang.String getCommandAsString() { return getCommand().toString(); } /** * Arguments to command indicated by command_type (below) */ public java.lang.StringBuilder getCommand() { return command_; } public void setCommandType(byte command_type) { command_type_ = command_type; } public byte getCommandType() { return command_type_; } public static Supplier<MenuEntryPubSubType> getPubSubType() { return MenuEntryPubSubType::new; } @Override public Supplier<TopicDataType> getPubSubTypePacket() { return MenuEntryPubSubType::new; } @Override public boolean epsilonEquals(MenuEntry other, double epsilon) { if(other == null) return false; if(other == this) return true; if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.id_, other.id_, epsilon)) return false; if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.parent_id_, other.parent_id_, epsilon)) return false; if (!us.ihmc.idl.IDLTools.epsilonEqualsStringBuilder(this.title_, other.title_, epsilon)) return false; if (!us.ihmc.idl.IDLTools.epsilonEqualsStringBuilder(this.command_, other.command_, epsilon)) return false; if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.command_type_, other.command_type_, epsilon)) return false; return true; } @Override public boolean equals(Object other) { if(other == null) return false; if(other == this) return true; if(!(other instanceof MenuEntry)) return false; MenuEntry otherMyClass = (MenuEntry) other; if(this.id_ != otherMyClass.id_) return false; if(this.parent_id_ != otherMyClass.parent_id_) return false; if (!us.ihmc.idl.IDLTools.equals(this.title_, otherMyClass.title_)) return false; if (!us.ihmc.idl.IDLTools.equals(this.command_, otherMyClass.command_)) return false; if(this.command_type_ != otherMyClass.command_type_) return false; return true; } @Override public java.lang.String toString() { StringBuilder builder = new StringBuilder(); builder.append("MenuEntry {"); builder.append("id="); builder.append(this.id_); builder.append(", "); builder.append("parent_id="); builder.append(this.parent_id_); builder.append(", "); builder.append("title="); builder.append(this.title_); builder.append(", "); builder.append("command="); builder.append(this.command_); builder.append(", "); builder.append("command_type="); builder.append(this.command_type_); builder.append("}"); return builder.toString(); } }
27.838951
119
0.609713
bff6d62e811b221ce78136225778fe3ceaeac00b
1,555
public class Person { // Instance variables: every person has a first name and last name private String firstName; private String lastName; // Constructor: creates a Person with the given first name and last name public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } // Default Constructor: creates a generic person public Person() { this.firstName = "John"; this.lastName = "Smith"; } // doSomething(): an example of a non-static method for the Person class. // This method just prints out a message saying something a // normal person might say public void doSomething() { System.out.println("I'm watching Netflix"); } // toString(): retuns a String representation of a Person (their full name) public String toString() { String str = firstName + " " + lastName; return str; } // getters: return the values of the instance variables public String getFirstName() { return this.firstName; } public String getLastName() { return this.lastName; } // setters: changes the value of the instance variables public void setFirstName(String firstName) { if (firstName.trim().length() != 0) { this.firstName = firstName; } } public void setLastName(String lastName) { if (lastName.trim().length() != 0) { this.lastName = lastName; } } }
29.903846
79
0.613505
620eed0f8375a621d63f353c9ea5bfd0563e7992
745
package leetcode300; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; /** * @date 2021/12/17 */ public class N386 { public List<Integer> lexicalOrder(int n) { List<Integer> res = new ArrayList<>(); dfs(0, 1, n, res); return res; } // todo zsx private void dfs(int num, int start, int n, List<Integer> res) { if (num > n) { return; } for (int i = start; i < 10; i++) { int number = i + num; if (number <= n) { res.add(number); dfs(number * 10, 0, n, res); } } } @Test void t() { System.out.println(lexicalOrder(25)); } }
17.738095
68
0.484564
2ae668db19f604d2235c136ef2fb07f03ae0822f
1,108
package org.danekja.discussment.core.dao; import org.danekja.discussment.core.domain.Category; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; class CategoryDaoIT extends GenericDaoIT<Long, Category> { protected final CategoryDao categoryDao; @Autowired public CategoryDaoIT(CategoryDao dao) { super(dao); this.categoryDao = dao; } @Override protected Category newTestInstance() { return new Category("CategoryDaoITInstance"); } @Override protected Long getTestIdForSearch() { return -1L; } @Override protected Long getTestIdForSearch_notFound() { return -666L; } @Override protected Long getTestIdForRemove() { return -2L; } @Override protected String getSearchResultTestValue(Category item) { return item.getName(); } @Test void getCategories() { List<Category> found = categoryDao.getCategories(); internalTestSearchResults(TestData.TEST_CATEGORIES, found); } }
22.612245
67
0.681408
ea5ca233c09f442d06b12d74a54aedfb9781d3b6
1,281
import com.geekcattle.Application; import com.geekcattle.service.console.LogService; import junit.framework.TestCase; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; /** * author geekcattle * date 2016/10/21 0021 下午 16:54 */ @RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持! @SpringBootTest(classes = Application.class) @WebAppConfiguration // 由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。 public class TestApp extends TestCase { @Autowired JedisPool jedisPool; @Autowired RedisTemplate<String, String> redisTemplate; @Test public void testRedis(){ redisTemplate.opsForValue().set("geekcattle","df1111111111111"); Jedis jedis = jedisPool.getResource(); jedis.setex("geek", 1000, "cattle"); System.out.println(redisTemplate.opsForValue().get("geekcattle")); } }
32.846154
93
0.779859
ca61a2cdb06cf497d50e75a29d11154eb300ed37
712
package com.daimabaike.springboot.mybatis.sys.mapper; import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import com.daimabaike.springboot.mybatis.core.mapper.BaseMapper; import com.daimabaike.springboot.mybatis.sys.entity.User; @Mapper public interface UserMapper extends BaseMapper<User> { // @Override @Select("select * from user where id=#{id}") User get(User userDto); @Select("select sleep(#{time}) as 'time' from dual") int find(int time); // for update 没有索引的字段,会全表锁住。如果不了解细节,慎用。建议查询条件是唯一键字段(含主键)才使用 @Override @Select("select * from user where name=#{name} for update") List<User> query(User dto) ; }
26.37037
65
0.728933
77aef902f8008539f47b3ea211885609b5f9de2d
269
package Modelo; import Auxiliar.Posicao; // Classe auxiliar para instanciar uma esteira com direcao para esquerda public class EsteiraEsquerda extends Esteira { public EsteiraEsquerda(Posicao umaPosicao) { super(3, "esteiraLeft.png", umaPosicao); } }
24.454545
72
0.750929
f1381f4c26fc7b5dd3ed1a975345871a41271fac
790
public class Node implements Comparable<Node> { Node next; Integer value; /* this is a very straight forward class, simply makes a node to store data in */ public Node(Integer value1) { next = null; value = value1; } public Node(Integer value1, Node next1) { next = next1; value = value1; } public Integer getVal() { return value; } public void setVal(Integer value1) { value = value1; } public Node getNext() { return next; } public void setNext(Node next1) { next = next1; } @Override public int compareTo(Node that) { return ((Integer)value).compareTo((Integer)that.value); } }
16.808511
68
0.534177
c360c62bcd09c0521b86ae5e0a7901ee51795dac
1,445
package com.example.android.miwok; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ListView; import java.util.ArrayList; import java.util.List; public class ColorsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_colors); List<Word> colors= new ArrayList<>(); colors.add(new Word("Red","weṭeṭṭi",R.drawable.color_red,R.raw.color_red)); colors.add(new Word("Green","chokokki",R.drawable.color_green,R.raw.color_green)); colors.add(new Word("Brown","ṭakaakki",R.drawable.color_brown,R.raw.color_brown)); colors.add(new Word("Gray","ṭopoppi",R.drawable.color_gray,R.raw.color_gray)); colors.add(new Word("Black","kululli",R.drawable.color_black,R.raw.color_black)); colors.add(new Word("White","kelelli",R.drawable.color_white,R.raw.color_white)); colors.add(new Word("Dusty Yellow","ṭopiisә",R.drawable.color_dusty_yellow,R.raw.color_dusty_yellow)); colors.add(new Word("Mustard Yellow","chiwiiṭә",R.drawable.color_mustard_yellow,R.raw.color_mustard_yellow)); WordAdapter adapter= new WordAdapter(this,colors, R.color.category_colors); ListView colorsListView= (ListView) findViewById(R.id.colorsListView); colorsListView.setAdapter(adapter); } }
42.5
117
0.728028
8c963504c5d14bfab9a42d8a596a9674b3eb0a4a
1,324
package keyboardwarrior; import java.util.HashMap; public final class ShortcutMap { private static ShortcutMap instance = null; public HashMap<String, String> shortcut_map; private ShortcutMap() { shortcut_map = SerFileReader.serFileIn(shortcut_map, SerFileDir.SF1); } /** * * @return */ public static ShortcutMap getInstance() { if (instance == null) { instance = new ShortcutMap(); } return instance; } /** * * @param key * @param value */ public void put(String key, String value) { shortcut_map.put(key, value); } /** * * @return */ public HashMap<String, String> getShortcutMap() { return shortcut_map; } /** * * @param shortcut_Key */ public void setShortcutMap(HashMap<String, String> shortcut_Key) { shortcut_map = shortcut_Key; } public void printToConsole() { shortcut_map.entrySet().forEach(entry -> { System.out.println(entry.getKey() + " " + entry.getValue()); }); } public void updateShortcutSerFile() { ShortcutMap shortcut_map = ShortcutMap.getInstance(); SerFileWriter.serFileOut(shortcut_map.getShortcutMap(), SerFileDir.SF1); } }
21.354839
80
0.586858
7e5f3d2f4e7e2d8fb25d49fa4db91ed78faadbf0
728
package com.example; import java.util.concurrent.atomic.AtomicInteger; public class ProcessMemoryModel { public static void main(String[] args) throws InterruptedException { MyTask task= new MyTask(); Thread t1= new Thread(task); Thread t2= new Thread(task); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(task.getData()); } } class MyTask implements Runnable { private AtomicInteger data= new AtomicInteger(0); @Override public void run() { for (int i=0;i<1_000_000;++i){ this.data.incrementAndGet(); // critical section } } public int getData() { return data.get(); } }
22.75
72
0.598901
86b57749bf97b8bafed2dffbe2ba84ee9bc29096
2,146
package com.diguits.domainmodeldefinition.serialization.mappers; import com.diguits.domainmodeldefinition.definitions.RelationshipPartDef; import com.diguits.domainmodeldefinition.definitions.ValueObjectDef; import com.diguits.domainmodeldefinition.serialization.dtomodel.RelationshipPartDefDTO; import com.diguits.common.mapping.MappingContext; import com.diguits.common.mapping.IMapperProvider; public class RelationshipPartDefToRelationshipPartDefDTOMapper extends BaseDefToBaseDefDTOMapper<RelationshipPartDef, RelationshipPartDefDTO> { RelationOverrideDefToRelationOverrideDefDTOMapper relationOverrideDefToRelationOverrideDefDTOMapper; ColumnDefToColumnDefDTOMapper columnDefToColumnDefDTOMapper; FilterDefToFilterDefDTOMapper filterDefToFilterDefDTOMapper; public RelationshipPartDefToRelationshipPartDefDTOMapper(IMapperProvider mapperProvider) { super(mapperProvider); } public void map(RelationshipPartDef source, RelationshipPartDefDTO target, MappingContext context) { if(source==null || target == null) return; if(source.getDomainObject() !=null){ target.setDomainObjectId(source.getDomainObject().getId()); if(source.getDomainObject() instanceof ValueObjectDef) target.setDomainObjectIsValueObject(true); else target.setDomainObjectIsValueObject(false); } if(source.getOwner()!=null) target.setOwnerId(source.getOwner().getId()); if(source.getField()!=null) target.setFieldId(source.getField().getId()); target.setRelationType(source.getRelationType()); if(source.getToRelationshipPart()!=null) target.setToRelationshipPartId(source.getToRelationshipPart().getId()); super.map(source, target, context); } public void mapBack(RelationshipPartDefDTO source, RelationshipPartDef target, MappingContext context) { if(source == null || target == null) return; target.setRelationType(source.getRelationType()); super.mapBack(source, target, context); } @Override protected Class<RelationshipPartDefDTO> getToClass() { return RelationshipPartDefDTO.class; } @Override protected Class<RelationshipPartDef> getFromClass() { return RelationshipPartDef.class; } }
39.018182
143
0.819199
3c431a6d8fd099af2b020bfddce4cf17d21671ee
1,570
package com.teambition.talk.entity; import org.parceler.Parcel; /** * Created by wlanjie on 15/9/14. */ @Parcel(Parcel.Serialization.BEAN) public class UserVoip { private String _id; private String user; private String voipAccount; private String voipPwd; private String subToken; private String subAccountSid; private String _userId; private String id; public String get_id() { return _id; } public void set_id(String _id) { this._id = _id; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getVoipAccount() { return voipAccount; } public void setVoipAccount(String voipAccount) { this.voipAccount = voipAccount; } public String getVoipPwd() { return voipPwd; } public void setVoipPwd(String voipPwd) { this.voipPwd = voipPwd; } public String getSubToken() { return subToken; } public void setSubToken(String subToken) { this.subToken = subToken; } public String getSubAccountSid() { return subAccountSid; } public void setSubAccountSid(String subAccountSid) { this.subAccountSid = subAccountSid; } public String get_userId() { return _userId; } public void set_userId(String _userId) { this._userId = _userId; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
18.915663
56
0.61465
6539ba4e815711bcb11a0cc3a2beec14b530f654
664
package solution; import java.util.List; public abstract class Replyer { public String company; public int bonusPoints; public List<String> skills; int id; public Replyer(int id, String company, int bonusPoints, List<String> skills) { this.id = id; this.skills = skills; this.company = company; this.bonusPoints = bonusPoints; } @Override public int hashCode() { return id; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Replyer replyer = (Replyer) o; return id == replyer.id; } }
17.025641
80
0.620482
b15ab428ba73f739561bdff7fcb9ffb00aad4a97
145
package com.gorden5566.aop.simple.service; /** * @author gorden5566 * @date 2019-03-18 */ public interface TestService { void test(); }
13.181818
42
0.675862
6f70f51673d98d28bd30c7a307206f20a1ba7698
1,829
package info.seleniumcucumber; //import com.epam.reportportal.testng.ReportPortalTestNGListener; import org.testng.annotations.*; import io.cucumber.testng.AbstractTestNGCucumberTests; import io.cucumber.testng.CucumberOptions; @CucumberOptions( plugin = { "pretty" // ,"com.aventstack.extentreports.cucumber.adapter.ExtentCucumberAdapter:" ,"com.epam.reportportal.cucumber.ScenarioReporter" // ,"com.epam.reportportal.cucumber.StepReporter" // ,"com.epam.reportportal.cucumber.ScenarioReporter" }, glue = {"info.seleniumcucumber.steps"}, // glue = {"src/test/java/info/seleniumcucumber/steps/"}, // features = {"classpath:features/"} // features = {"classpath:features/my_first.feature"} features = { // "src/test/resources/features/Purchase.feature", // "src/test/resources/features/Purchase2.feature", // "src/test/resources/features/registeruser.feature", // "src/test/resources/features/login.feature", // "src/test/resources/features/testDB.feature", // "src/test/resources/features/ExecuteAutomationDevTools.feature", "src/test/resources/features/weather-intercept.feature", "src/test/resources/features/saucedemo-login.feature", // "src/test/resources/features/my_first.feature" }, monochrome = true // tags = {}, ) //@Listeners({ReportPortalTestNGListener.class}) public class RunnerTestNG extends AbstractTestNGCucumberTests { @Override @DataProvider(parallel = true) public Object[][] scenarios() { return super.scenarios(); } // @BeforeSuite // public void beforeSuiteActivities() { // // // } // // @AfterSuite // public void afterActivities() { // // } }
33.254545
79
0.655549
d7b31ce79d0102aa1bda12ab9de7866a81f487e3
716
package me.kevinwalker.ui.controller; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.image.ImageView; import me.kevinwalker.main.ImageResourc; import java.net.URL; import java.util.ResourceBundle; public class PopupController implements Initializable { public static PopupController instance; public Label message; public Button cancel; public ImageView error; @Override public void initialize(URL location, ResourceBundle resources) { instance = this; if (ImageResourc.error != null) error.setImage(ImageResourc.error); else error.setImage(ImageResourc.loading); } }
25.571429
68
0.744413
557ba8c18fdd6970f26a9ebcebcc24faacef5447
249
/**上午10:02:36 * @author zhangyh2 * VitamioListener.java * TODO */ package io.vov.vitamio; /** @author zhangyh2 * VitamioListener * 上午10:02:36 * TODO 这里面进行设置一些动作接口。方便主项目进行调取 */ public interface VitamioListener { public void startTime(); }
14.647059
34
0.706827
d7e1427e2498a0c51e081b1b0b4ae2deb699c154
2,665
package me.lefted.leashes.mixins; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityType; import net.minecraft.entity.ai.goal.Goal; import net.minecraft.entity.mob.MobEntity; import net.minecraft.entity.mob.PathAwareEntity; import net.minecraft.entity.passive.TameableEntity; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; @Mixin(PathAwareEntity.class) @Environment(EnvType.SERVER) public abstract class PathAwareEntityMixin extends MobEntity { protected PathAwareEntityMixin(EntityType<? extends MobEntity> entityType, World world) { super(entityType, world); } @Overwrite public void updateLeash() { sandbox(); } private void sandbox() { super.updateLeash(); Entity entity = this.getHoldingEntity(); if (entity != null && entity.world == this.world) { this.setPositionTarget(entity.getBlockPos(), 5); float f = this.distanceTo(entity); if (((Object) this) instanceof TameableEntity && ((TameableEntity) (Object) this).isInSittingPose()) { if (f > 50.0f) { this.detachLeash(true, true); } return; } this.updateForLeashLength(f); if (f > 50.0f) { this.detachLeash(true, true); this.goalSelector.disableControl(Goal.Control.MOVE); } else if (f > 6.0f) { double d = (entity.getX() - this.getX()) / (double) f; double e = (entity.getY() - this.getY()) / (double) f; double g = (entity.getZ() - this.getZ()) / (double) f; this.setVelocity(this.getVelocity().add(Math.copySign(d * d * 0.4, d), Math.copySign(e * e * 0.4, e), Math.copySign(g * g * 0.4, g))); } else { this.goalSelector.enableControl(Goal.Control.MOVE); float d = 2.0f; Vec3d vec3d = new Vec3d(entity.getX() - this.getX(), entity.getY() - this.getY(), entity.getZ() - this.getZ()).normalize() .multiply(Math.max(f - 2.0f, 0.0f)); this.getNavigation().startMovingTo(this.getX() + vec3d.x, this.getY() + vec3d.y, this.getZ() + vec3d.z, this.getRunFromLeashSpeed()); } } } @Shadow protected abstract void updateForLeashLength(float leashLength); @Shadow protected abstract double getRunFromLeashSpeed(); }
39.191176
150
0.616886
ade0b9255c53c1990c7c2a4cb977d7db34a97c21
682
package pta; import config.SootConfig; import soot.PackManager; import soot.Scene; import soot.Transform; /** * @program: MySootScript * @description: * @author: 0range * @create: 2021-06-17 17:21 **/ public class Starter { public static final String className = "pta.ptademo.Hello"; public static void main(String[] args) { SootConfig.setupSoot(className); String sootClassPath = Scene.v().getSootClassPath(); // 打印soot的classpath System.out.println("sootClassPath = " + sootClassPath); PackManager.v().getPack("wjtp").add(new Transform("wjtp.MyPTA",new MyPTATransformer())); PackManager.v().runPacks(); } }
21.3125
96
0.667155
2e70feda00c35b78112d39306f472836ba7a8e71
2,140
/* */ package org.apache.pdfbox.contentstream.operator.color; /* */ /* */ import java.io.IOException; /* */ import java.util.List; /* */ import org.apache.pdfbox.contentstream.operator.MissingOperandException; /* */ import org.apache.pdfbox.contentstream.operator.Operator; /* */ import org.apache.pdfbox.contentstream.operator.OperatorProcessor; /* */ import org.apache.pdfbox.cos.COSArray; /* */ import org.apache.pdfbox.cos.COSBase; /* */ import org.apache.pdfbox.cos.COSNumber; /* */ import org.apache.pdfbox.pdmodel.graphics.color.PDColor; /* */ import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public abstract class SetColor /* */ extends OperatorProcessor /* */ { /* */ public void process(Operator operator, List<COSBase> arguments) throws IOException { /* 42 */ PDColorSpace colorSpace = getColorSpace(); /* 43 */ if (!(colorSpace instanceof org.apache.pdfbox.pdmodel.graphics.color.PDPattern)) { /* */ /* 45 */ if (arguments.size() < colorSpace.getNumberOfComponents()) /* */ { /* 47 */ throw new MissingOperandException(operator, arguments); /* */ } /* 49 */ if (!checkArrayTypesClass(arguments, COSNumber.class)) { /* */ return; /* */ } /* */ } /* */ /* 54 */ COSArray array = new COSArray(); /* 55 */ array.addAll(arguments); /* 56 */ setColor(new PDColor(array, colorSpace)); /* */ } /* */ /* */ protected abstract PDColor getColor(); /* */ /* */ protected abstract void setColor(PDColor paramPDColor); /* */ /* */ protected abstract PDColorSpace getColorSpace(); /* */ } /* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/pdfbox/contentstream/operator/color/SetColor.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
30.571429
114
0.543925
a93f072c915350db662c008437247939cc95b5cd
291
package com.gl.roadaccidents.repository; import com.gl.roadaccidents.model.WeatherCondition; import org.springframework.data.jpa.repository.JpaRepository; /** * Created by gavin on 16-5-22. */ public interface WeatherConditionRepository extends JpaRepository<WeatherCondition, Long> { }
26.454545
91
0.810997
7661a41bdaced4c45092af16b168f9681e1bd180
1,288
package uk.gov.hmcts.reform.em.hrs.service; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import uk.gov.hmcts.reform.em.hrs.domain.HearingRecordingSegment; import uk.gov.hmcts.reform.em.hrs.repository.HearingRecordingSegmentRepository; import java.util.Collections; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static uk.gov.hmcts.reform.em.hrs.componenttests.TestUtil.RANDOM_UUID; @ExtendWith(MockitoExtension.class) class SegmentServiceImplTest { @Mock private HearingRecordingSegmentRepository segmentRepository; @InjectMocks private SegmentServiceImpl underTest; @Test void testFindByRecordingId() { doReturn(Collections.emptyList()).when(segmentRepository).findByHearingRecordingId(RANDOM_UUID); final List<HearingRecordingSegment> segments = underTest.findByRecordingId(RANDOM_UUID); assertThat(segments).isEmpty(); verify(segmentRepository, times(1)).findByHearingRecordingId(RANDOM_UUID); } }
33.025641
104
0.799689
742e95cac53bfe3046378c38d654cee9ffb93940
2,690
package ru.fizteh.fivt.students.SibgatullinDamir.Shell; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; /** * Created by Lenovo on 01.10.2014. */ public class RmCommand implements Commands { void removeNonrecursive(String path) throws MyException { try { Path newPath = Shell.currentPath.resolve(path).toRealPath(); if (Files.isDirectory(newPath)) { throw new MyException("rm: cannot remove '" + path + "': No such file or directory"); } else { Files.delete(newPath); } } catch (IOException e) { throw new MyException("rm: " + path + ": the file does not exist"); } } void removeRecursive(String path) throws MyException { try { Path newPath = Shell.currentPath.resolve(path).toRealPath(); if (Files.isDirectory(newPath)) { removeRecursiveFinal(newPath); } else { Files.delete(newPath); } } catch (IOException e) { throw new MyException("rm: cannot remove " + path + ": No such file or directory"); } } void removeRecursiveFinal(Path path) throws MyException { if (!Files.exists(path)) { throw new MyException("rm: cannot remove '" + path.toString() + "': No such file or directory"); } File dir = new File(path.toString()); File[] files = dir.listFiles(); for (File file : files) { if (file.isFile()) { try { Files.delete(path); } catch (IOException e) { throw new MyException("I/O error occurs while removing " + file.toPath().toString()); } } else { removeRecursiveFinal(file.toPath()); } } try { Files.delete(path); } catch (IOException ex) { throw new MyException("I/O error occurs while removing " + path.toString()); } } public void execute(String[] args) throws MyException { if (args.length < 2) { throw new MyException("rm: not enough arguments"); } if (args.length > 3) { throw new MyException("rm: too many arguments"); } if (args[1].equals("-r") && args.length == 3) { removeRecursive(args[2]); } else if (args.length == 2) { removeNonrecursive(args[1]); } else { throw new MyException("rm: invalid arguments"); } } public String getName() { return "rm"; } }
32.02381
108
0.533829
bef5e38c7a24ebd891e9062ba91f91fe11208fad
23,181
package edu.purdue.cuttlefish.crypto; import edu.purdue.cuttlefish.utils.ArrayUtils; import edu.purdue.cuttlefish.utils.EncodeUtils; import edu.purdue.cuttlefish.utils.FileUtils; import javax.crypto.*; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class SWP extends CryptoScheme { private static final String DEFAULT_KEY_PATH = "/tmp/swp.sk"; // SWP encryption constructions mode. dup indicates duplicate words can exist. no dup indicates // duplicate words are removed before encrypting. rand indicates words are permuted before // encrypting and no rand means the order of the words is preserved. The default is dup and no // rand which does not remove any words or change their order. enum ConstructionMode { DUP_AND_NO_RAND, DUP_AND_RAND, NO_DUP_AND_NO_RAND, NO_DUP_AND_RAND } // split sentences into words based on this delimiter private static final String DELIMITER = " "; private static final int BITLENGTH = 128; private static final int BLOCK_BYTES = BITLENGTH / Byte.SIZE; private static final double LOAD_FACTOR = 0.8; private static final int LEFT = ((int) (LOAD_FACTOR * BLOCK_BYTES)); private static final int RIGHT = BLOCK_BYTES - LEFT; private static final String AES_ALGORITHM = "AES/ECB/PKCS5Padding"; SecretKey key = (SecretKey) this.privateKey; private Cipher aesCipherEncrypt; private Cipher aesCipherDecrypt; private final ConstructionMode constructionMode; public boolean duplicateWords; public boolean randomWordOrder; public SWP() { this(DEFAULT_KEY_PATH); } public SWP(String privateKeyPath) { this(privateKeyPath, ConstructionMode.DUP_AND_NO_RAND); } public SWP(String privateKeyPath, ConstructionMode constructionMode) { super(privateKeyPath); this.constructionMode = constructionMode; this.duplicateWords = this.constructionMode == ConstructionMode.DUP_AND_NO_RAND || this.constructionMode == ConstructionMode.DUP_AND_RAND; this.randomWordOrder = this.constructionMode == ConstructionMode.DUP_AND_RAND || this.constructionMode == ConstructionMode.NO_DUP_AND_RAND; // initialize aes encryption and decryption ciphers try { this.aesCipherEncrypt = Cipher.getInstance(AES_ALGORITHM, "SunJCE"); this.aesCipherEncrypt.init(Cipher.ENCRYPT_MODE, this.key); this.aesCipherDecrypt = Cipher.getInstance(AES_ALGORITHM, "SunJCE"); this.aesCipherDecrypt.init(Cipher.DECRYPT_MODE, this.key); } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | InvalidKeyException e) { throw new RuntimeException("Unable to initialize AES cipher"); } } @Override public void keyGen() { KeyGenerator kgen = null; try { kgen = KeyGenerator.getInstance("AES"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } // set the size of the key. kgen.init(BITLENGTH); SecretKey skeySpec = kgen.generateKey(); // save key to file FileUtils.saveObjectToFile(skeySpec, privateKeyPath); } /** * Returns BLOCK_BYTES length byte array of random bytes based on the given record id */ public byte[] getRandomStreamOfBytes(long recordId) { byte[] recordIdBytes = ByteBuffer.allocate(BLOCK_BYTES).putLong(recordId).array(); byte[] nonce = ArrayUtils.xor(this.key.getEncoded(), recordIdBytes); Cipher streamCipher; try { streamCipher = Cipher.getInstance("AES/CTR/NoPadding"); streamCipher.init(Cipher.ENCRYPT_MODE, this.key, new IvParameterSpec(nonce)); } catch (Exception e) { throw new RuntimeException("Unable to initialize stream cipher"); } byte[] randBytes = null; try { // Plain text is 0 always we don't really care randBytes = streamCipher.doFinal(ByteBuffer.allocate(BLOCK_BYTES).putInt(0).array()); } catch (IllegalBlockSizeException | BadPaddingException e) { e.printStackTrace(); } return randBytes; } /** * Given a key and a seed, return a pseudo-random string based on the aes block * * @param key * @param data * @return */ private byte[] PRF(byte[] key, byte[] data) { if (key == null) throw new RuntimeException("Key is empty cannot proceed"); if (key.length > BLOCK_BYTES) throw new RuntimeException("Key Size > 16 bytes" + key.length); byte[] fullKey = new byte[BLOCK_BYTES]; System.arraycopy(key, 0, fullKey, 0, key.length); if (key.length < BLOCK_BYTES) for (int i = key.length; i < BLOCK_BYTES; i++) fullKey[i] = 0; byte[] f; try { SecretKeySpec keySpec = new SecretKeySpec(fullKey, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE"); cipher.init(Cipher.ENCRYPT_MODE, keySpec); f = cipher.doFinal(data); } catch (Exception e) { throw new RuntimeException("Invalid Parameters" + e.getMessage()); } return f; } /** * Encrypt a string (sentence) word by word. * * @param sentence the plaintext string * @return the encrypted string */ public String encrypt(String sentence) { // split sentences into words. each word is encrypted individually String[] words = sentence.split(DELIMITER, -1); List<String> wordsToEncrypt = new ArrayList<>(); for (String word : words) { // empty string indicates consecutive delimiters. We want to preserve these. if (word.equals("")) { wordsToEncrypt.add(word); continue; } // if the construction does not allow duplicate words, don't add the same word twice if (!duplicateWords && wordsToEncrypt.contains(word)) continue; wordsToEncrypt.add(word); } // if the order of the words is not important, permute the order of the words if (this.randomWordOrder) Collections.shuffle(wordsToEncrypt, RNG); String ctxt = ""; int recordId = 0; for (int wordIndex = 0; wordIndex < wordsToEncrypt.size(); wordIndex++) { String word = wordsToEncrypt.get(wordIndex); // if this is an empty word, add a delimiter to keep the ciphertext correct. // E.g., "_word1" or "word1__word2" where _ represents the delimiter will lead to empty words. if (word.equals("")) { if (wordIndex < wordsToEncrypt.size() - 1) ctxt += DELIMITER; continue; } while (word.length() > 0) { int limit = Math.min(word.length(), BLOCK_BYTES - 1); String wordPart = word.substring(0, limit); word = word.substring(limit); byte[] wordBA; wordBA = wordPart.getBytes(StandardCharsets.UTF_8); if (wordBA.length >= BLOCK_BYTES) throw new RuntimeException("Word too big to encryptWord: " + word); byte[] encryptedWord = encryptWord(wordBA, recordId++); ctxt += EncodeUtils.base64Encode(encryptedWord); if (word.length() > 0) ctxt += DELIMITER; } if (wordIndex < wordsToEncrypt.size() - 1) ctxt += DELIMITER; } return ctxt; } /** * Encrypt a single word. */ public byte[] encryptWord(byte[] word, long recordId) { if (word == null) return new byte[0]; if (word.length >= BLOCK_BYTES) throw new RuntimeException("word too big to encryptWord"); // Generate Stream Cipher Bytes byte[] streamCipherBytes = getRandomStreamOfBytes(recordId); byte[] blockCipherBytes = encryptToken(word); // Split the cipher Bytes into {left, Right} byte[] blockCipherBytesLeft = Arrays.copyOfRange(blockCipherBytes, 0, LEFT); byte[] streamCipherBytesLeft = Arrays.copyOfRange(streamCipherBytes, 0, LEFT); byte[] F_S_temp = PRF(blockCipherBytesLeft, streamCipherBytesLeft); byte[] searchLayerBytesRight; if (RIGHT == 0) // No false positives but additional storage searchLayerBytesRight = Arrays.copyOfRange(F_S_temp, 0, BLOCK_BYTES); else // Expect false positives while searching searchLayerBytesRight = Arrays.copyOfRange(F_S_temp, 0, RIGHT); byte[] searchLayerBytes = new byte[streamCipherBytesLeft.length + searchLayerBytesRight.length]; System.arraycopy(streamCipherBytesLeft, 0, searchLayerBytes, 0, LEFT); System.arraycopy(searchLayerBytesRight, 0, searchLayerBytes, LEFT, searchLayerBytesRight.length); return ArrayUtils.xor(blockCipherBytes, searchLayerBytes); } /** * Decrypt a given encrypted string (sentence) word by word. * * @param ciphertext the encrypted sentence to decrypt * @return */ public String decrypt(String ciphertext) { if (ciphertext == null || ciphertext.isEmpty()) return ciphertext; // split sentences into words. each word is encrypted individually String[] words = ciphertext.split(DELIMITER, -1); String ptxt = ""; for (int i = 0; i < words.length; i++) { String word = words[i]; String p = null; if (word.equals("")) { if (i < words.length - 1) ptxt += DELIMITER; continue; } else { byte[] wordBA = EncodeUtils.base64Decode(word); p = new String(decryptWord(wordBA, i), StandardCharsets.UTF_8); } ptxt += p; if (i < words.length - 1) ptxt += DELIMITER; } return ptxt; } /** * Decrypt a given word */ public byte[] decryptWord(byte[] cipherBytes, long recordID) { if (cipherBytes == null || cipherBytes.length == 0) return new byte[0]; // Generate a Stream Cipher byte[] streamCipherBytes = getRandomStreamOfBytes(recordID); byte[] streamCipherBytesLeft = Arrays.copyOfRange(streamCipherBytes, 0, LEFT); // Split the cipher Bytes into {left, Right} byte[] cipherBytesLeft = Arrays.copyOfRange(cipherBytes, 0, LEFT); byte[] cipherBytesRight = Arrays.copyOfRange(cipherBytes, LEFT, cipherBytes.length); // Peel off the left bytes of search layer from cipherText to get left bytes of Block Cipher byte[] blockCipherBytesLeft = ArrayUtils.xor(cipherBytesLeft, streamCipherBytesLeft); if (blockCipherBytesLeft.length == BLOCK_BYTES) return decryptToken(blockCipherBytesLeft); else { // compute the right bytes of search layer byte[] tmpBytes = PRF(blockCipherBytesLeft, streamCipherBytesLeft); byte[] tmpBytesRight = Arrays.copyOfRange(tmpBytes, 0, RIGHT); byte[] blockCipherBytesRight = ArrayUtils.xor(cipherBytesRight, tmpBytesRight); byte[] blockLayerBytes = new byte[BLOCK_BYTES]; System.arraycopy(blockCipherBytesLeft, 0, blockLayerBytes, 0, LEFT); System.arraycopy(blockCipherBytesRight, 0, blockLayerBytes, LEFT, RIGHT); return decryptToken(blockLayerBytes); } } /** * Encrypt a regular expression. * * @param regex the plaintext regular expression to encrypt * @return the encrypted regular expression */ public String encryptRegex(String regex) { String encRegex = ""; while (!regex.equals("")) { RegexOp ro = new RegexOp(regex); // get the next token. String token; if (ro.operator == null) { token = regex; regex = ""; } else { token = regex.substring(0, ro.position); regex = regex.substring(ro.position + ro.operator.length()); } // add the encrypted token if (!token.equals("")) encRegex += encryptToken(token); // add the same operator to the encrypted regex. if (ro.operator != null) encRegex += ro.operator; } return encRegex; } /** * Encrypts a token of a regular expression, e.g., in regex "cat|dog|mouse" the tokens are * "cat", "dog", "mouse" * * @param token the plaintext token as a string to encrypt * @return */ public String encryptToken(String token) { String encToken = ""; while (token.length() > 0) { int limit = Math.min(token.length(), BLOCK_BYTES - 1); String plaintextPart = token.substring(0, limit); token = token.substring(limit); byte[] plainBytes; plainBytes = plaintextPart.getBytes(StandardCharsets.UTF_8); if (plainBytes.length >= BLOCK_BYTES) throw new RuntimeException("Word too big to encryptWord: " + token); if (!encToken.equals("")) encToken += " "; encToken += EncodeUtils.base64Encode(encryptToken(plainBytes)); } return encToken; } /** * Encrypts a token of a regular expression, e.g., in regex "cat|dog|mouse" the tokens are * "cat", "dog", "mouse" * * @param token the plaintext token as a byte array to encrypt */ private byte[] encryptToken(byte[] token) { if (token.length >= BLOCK_BYTES) throw new RuntimeException("token too big to encrypt"); byte[] ctxt = null; try { ctxt = aesCipherEncrypt.doFinal(token); } catch (IllegalBlockSizeException | BadPaddingException e) { e.printStackTrace(); } return ctxt; } /** * Decrypts a given encrypted token * * @param ctxtToken the encryped token to decrypt */ private byte[] decryptToken(byte[] ctxtToken) { byte[] ptxt = null; try { ptxt = aesCipherDecrypt.doFinal(ctxtToken); } catch (IllegalBlockSizeException | BadPaddingException e) { e.printStackTrace(); } return ptxt; } private static byte[][] ciphertextToBytes(String ciphertext) { // convert ciphertext to array of words as byte arrays. String[] words = ciphertext.split(DELIMITER, -1); List<byte[]> wordsList = new ArrayList<>(); for (String word : words) if (word.equals("")) wordsList.add(null); else wordsList.add(EncodeUtils.base64Decode(word)); byte[][] wordsBA = new byte[wordsList.size()][]; for (int i = 0; i < wordsList.size(); i++) wordsBA[i] = wordsList.get(i); return wordsBA; } public boolean startsWith(String ciphertext, String token) { return this.match(ciphertext, token + ".*"); } public boolean endsWith(String ciphertext, String token) { return this.match(ciphertext, ".*" + token); } /** * <pre> * Support for any combination of the 3 operands " ", ".*", "|" * * a) " "(single space): acts as a word separator. * b) ".*": indicates 1st word followed by 2nd word not necessarily directly e.g x.*y * c) "|": indicates either or e.g x|y * * </pre> * * @param ciphertext * @return */ public boolean match(String ciphertext, String regex) { // the array holding the encrypted words after the given ciphertext is split on the set // DELIMITER. byte[][] wordsBA = ciphertextToBytes(ciphertext); char[] charPositions = new char[wordsBA.length]; String newRegex = ""; char currentCharacter = 'a'; while (!regex.equals("")) { RegexOp ro = new RegexOp(regex); // get the next token. String token = ""; if (ro.operator == null) { token = regex; regex = ""; } else { token = regex.substring(0, ro.position); regex = regex.substring(ro.position + ro.operator.length()); } if (!token.equals("")) { // replace token with next character String regexToken = "" + currentCharacter; // find which words match this token List<Integer> tokenLocations = matchPositions(wordsBA, EncodeUtils.base64Decode(token)); // fill the character array with the character that replaced the word. for (int location : tokenLocations) { // if a character already exists in a location, it means the same token was met // before and a character was assigned to it. Use that same character to replace // the token, instead of the next available character. if (charPositions[location] != '\u0000') regexToken = "" + charPositions[location]; else charPositions[location] = currentCharacter; } // add the character that replaces the token to the new regex. newRegex += regexToken; // advance the character. currentCharacter += 1; } // add the same operator to the new regex. if (ro.operator != null) newRegex += ro.operator; } String newString = ""; for (int i = 0; i < wordsBA.length; i++) { // a word can be null e.g when double delimiter is in the original ciphertext. if (wordsBA[i] == null) { if (i < charPositions.length - 1) newString += " "; continue; } // if the character in the same position of the word is not null, replace the word with // the character in the new string. Otherwise replace it with the string XX which // essentially acts as a non-match. if (charPositions[i] != '\u0000') newString += charPositions[i]; else newString += "XX"; // separate words. if (i < charPositions.length - 1) newString += DELIMITER; } return newString.matches(newRegex); } private List<Integer> matchPositions(byte[][] words, byte[] tokenBytes) { List<Integer> locations = new ArrayList<Integer>(); for (int i = 0; i < words.length; i++) if (words[i] != null && matchWord(words[i], tokenBytes)) locations.add(i); return locations; } public List<Integer> matchPositions(String ciphertext, String token) { byte[] tokenBytes = EncodeUtils.base64Decode(token); // convert ciphertext to array of words as byte arrays. byte[][] wordsBA = ciphertextToBytes(ciphertext); return matchPositions(wordsBA, tokenBytes); } public int matchCount(String ciphertext, String token) { byte[] tokenBytes = EncodeUtils.base64Decode(token); int count = 0; byte[][] wordsBA = ciphertextToBytes(ciphertext); for (byte[] word : wordsBA) if (word != null && matchWord(word, tokenBytes)) count++; return count; } public boolean matchExists(String ciphertext, String token) { byte[] tokenBytes = EncodeUtils.base64Decode(token); byte[][] wordsBA = ciphertextToBytes(ciphertext); for (byte[] word : wordsBA) if (word != null && matchWord(word, tokenBytes)) return true; return false; } private boolean matchWord(byte[] cipherBytes, byte[] tokenBytes) { if (cipherBytes == null || tokenBytes == null) return false; // Peel off the search layer bytes of given layer byte[] searchBytes = ArrayUtils.xor(tokenBytes, cipherBytes); byte[] searchBytesLeft = Arrays.copyOfRange(searchBytes, 0, LEFT); byte[] searchBytesRight = Arrays.copyOfRange(searchBytes, LEFT, cipherBytes.length); // Split the tokenBytes into {left, Right} of Left bytes and Right bytes byte[] tokenBytesLeft = Arrays.copyOfRange(tokenBytes, 0, LEFT); // Verify search layer byte[] tmpBytes = PRF(tokenBytesLeft, searchBytesLeft); byte[] tmpBytesRight; if (RIGHT == 0) tmpBytesRight = Arrays.copyOfRange(tmpBytes, 0, BLOCK_BYTES); else tmpBytesRight = Arrays.copyOfRange(tmpBytes, 0, RIGHT); return Arrays.equals(searchBytesRight, tmpBytesRight); } public static class RegexOp { private static final String ANY = ".*"; private static final String OR = "|"; private static final String SPACE = DELIMITER; public String operator = null; public int position = -1; /** * Given a regular expression string, find the first instance of an operator and keep track * of its kind and position. If no operator is found, set position to -1 and kind to null * * @param regex */ public RegexOp(String regex) { int p = regex.indexOf(ANY); if (p > -1 && (position == -1 || p < position)) { operator = ANY; position = p; } p = regex.indexOf(OR); if (p > -1 && (position == -1 || p < position)) { operator = OR; position = p; } p = regex.indexOf(SPACE); if (p > -1 && (position == -1 || p < position)) { operator = SPACE; position = p; } } } public static void main(String[] args) { SWP s = new SWP(); String ctxt = s.encrypt("5"); String encRegex = s.encryptRegex("5"); // String encRegex = s.encryptRegex("TN|AL|SD"); System.out.println(s.match(ctxt, encRegex)); System.out.println("ctxt= " + ctxt); System.out.println("regex= " + encRegex); System.out.println(s.decrypt(ctxt)); } }
34.444279
106
0.587766
9a6941a56c97f6fc0669ba9739400c49710cccad
1,036
package stellarapi.impl.celestial; import stellarapi.api.lib.math.SpCoord; import stellarapi.api.optics.Wavelength; import stellarapi.api.view.IAtmosphereEffect; /** * Default implementation of sky. */ public class DefaultSkyVanilla implements IAtmosphereEffect { @Override public void applyAtmRefraction(SpCoord pos) { return; } @Override public void disapplyAtmRefraction(SpCoord pos) { return; } @Override public float calculateAirmass(SpCoord pos) { return 0.0f; } @Override public float getExtinctionRate(Wavelength wavelength) { return 0.0f; } @Override public double getSeeing(Wavelength wl) { return 0.0f; } @Override public float getAbsorptionFactor(float partialTicks) { return 0.0f; } @Override public float getDispersionFactor(Wavelength wavelength, float partialTicks) { return 1.0f; } @Override public float getLightPollutionFactor(Wavelength wavelength, float partialTicks) { return 0.0f; } @Override public float minimumSkyRenderBrightness() { return 0.2f; } }
17.862069
82
0.757722
923de92eb30b6405ab93580f668d6686b5b957c5
795
package org.apsarasmc.spigot.command; import net.kyori.adventure.audience.MessageType; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.bungeecord.BungeeComponentSerializer; import org.apsarasmc.spigot.util.TextComponentUtil; import org.bukkit.command.CommandSender; import javax.annotation.Nonnull; public class SpigotSender implements org.apsarasmc.apsaras.command.CommandSender { private final CommandSender sender; public SpigotSender(CommandSender sender){ this.sender = sender; } @Override public void sendMessage(@Nonnull Identity source, @Nonnull Component message, @Nonnull MessageType type) { sender.spigot().sendMessage(source.uuid(), TextComponentUtil.toBukkit(message)); } }
34.565217
108
0.811321
813046695716f338ec412153766ed0f9789cd7c7
195
package Factory_File; public class ConcreteCreator extends AbstractCreator { @Override IFile getRecord(String fileName) { return new GenericFile(fileName); } }
19.5
55
0.671795
a4f71ab11fd4bc7e1b7d98104ad3ddd9379a5b7f
2,786
package org.ningning.codefu.crossword_gen; import static com.google.common.base.Preconditions.checkArgument; public class Util { public static void printAWord(String word, char mode, int beginRow, int beginCol, Board board) { checkArgument(word.length() <= board.getLongestSide(), "The word's length %d exceeds longest side of the board %d", word.length(), board.getLongestSide()); // initialize the empty board char[][] boardView = initBoardView(board); switch (mode) { case 'h': setAWordInARow(word, beginRow, beginCol, boardView); break; case 'v': setAWordInACol(word, beginRow, beginCol, boardView); break; default: break; } // print the board printBoard(boardView); } private static char[][] initBoardView(Board board) { int viewRows = board.getRows() * 2 + 1; int viewCols = board.getCols() * 2 + 1; char[][] boardView = new char[viewRows][viewCols]; for (int row = 0; row < viewRows; row++) { for (int col = 0; col < viewCols; col++) { if (row % 2 == 0) { // even rows, are grid lines boardView[row][col] = '-'; } else { if (col % 2 == 0) { // even cols, are grid lines boardView[row][col] = '|'; } else { boardView[row][col] = ' '; } } } } return boardView; } private static void setAWordInARow( String word, int row, int beginCol, char[][] boardView) { int rowInView = row * 2 - 1; int beginColInView = beginCol * 2 - 1; for (int i = 0; i < word.length(); i++) { int colInView = beginColInView + i * 2; boardView[rowInView][colInView] = word.charAt(i); } } private static void setAWordInACol( String word, int beginRow, int col, char[][] boardView) { int colInView = col * 2 - 1; int beginRowInView = beginRow * 2 - 1; for (int i = 0; i < word.length(); i++) { int rowInView = beginRowInView + i * 2; boardView[rowInView][colInView] = word.charAt(i); } } private static void printBoard(char[][] boardView) { for (int row = 0; row < boardView.length; row++) { for (int col = 0; col < boardView[row].length; col++) { System.out.print(boardView[row][col]); } System.out.println(); } } }
30.955556
76
0.488873
d581a991a58e0820cd3c370d63d7237e8f84c738
3,329
/* * 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 helpers; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Breaze */ public class PortScanner { private final DatagramSocket socket; public PortScanner() throws SocketException { this.socket = new DatagramSocket(); } public void send(String msg, String server, int port) throws UnknownHostException, IOException { InetAddress host = InetAddress.getByName(server); byte[] buffer = msg.getBytes(); DatagramPacket request = new DatagramPacket(buffer, buffer.length, host, port); this.socket.send(request); } public ArrayList<ArrayList> scanPort(){ PropertiesManager pm = new PropertiesManager(); String portRange[] = pm.getPortRange(); String onNetwork[] = pm.getOnNetwork(); ArrayList<String> neighbours = new ArrayList(); ArrayList<String> names = new ArrayList(); ArrayList<Integer> ports = new ArrayList(); int startPort = Integer.parseInt(portRange[0]); int finalPort = Integer.parseInt(portRange[1]); System.out.println("Scanning ports..."); for(String server : onNetwork) { for(int i = startPort; i <= finalPort; i++){ try { this.socket.setSoTimeout(1000); this.send("running", server, i); String response = this.getResponse(); response = response.replace("\u0000", ""); // removes NUL chars response = response.replace("\\u0000", ""); // removes backslash+u0000 String data[] = response.split(":"); System.out.println(response); String name = data[0]; String port = data[1]; names.add(name); neighbours.add(server); ports.add(Integer.parseInt(port)); System.out.println(server+" is reachable in port: "+i); } catch (IOException ex) { System.out.println(server+" is not reachable in port: "+i); //System.out.println("Error: "+ ex.getMessage()); } } } ArrayList<ArrayList> neighboursInfo = new ArrayList<ArrayList>(); neighboursInfo.add(neighbours); neighboursInfo.add(ports); neighboursInfo.add(names); return neighboursInfo; } public String getResponse() throws IOException { byte[] buffer = new byte[30]; DatagramPacket request = new DatagramPacket(buffer, buffer.length); this.socket.receive(request); //System.out.println(new String(request.getData())); return new String(request.getData()); } }
35.042105
98
0.58486
fb9af0f8e4d58bcb73b0c59b5f74d1772abc2849
2,591
/* * */ package components; import java.util.Arrays; import java.util.List; import junit.framework.Assert; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import categories.IntegrationTest; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; /** * Class for testing heater and pump pin functionality. */ @RunWith(Parameterized.class) public class GPIOTest { /** * Runs ten times with no real "values". * * @return List of times */ @Parameterized.Parameters public static List<Object[]> data() { return Arrays.asList(new Object[10][0]); } /** The pin which is used for enabling and disabling of the heater. */ private static GpioPinDigitalOutput heaterPin; /** The pin which is used for enabling and disabling of the pump. */ private static GpioPinDigitalOutput pumpPin; /** The controller which gives the possibility to receive heater and pump pins. */ private static GpioController gpio; /** * Parameterless constructor needed as test will start multiple times. */ public GPIOTest() {} /** * stop all GPIO activity/threads by shutting down the GPIO controller (this method will * forcefully shutdown all GPIO monitoring threads and scheduled tasks). */ @AfterClass public static void after() { heaterPin.high(); pumpPin.high(); gpio.shutdown(); } /** * provision gpio pin #01 as an output pin and turn on. */ @BeforeClass public static void init() { gpio = GpioFactory.getInstance(); heaterPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_03, "heating", PinState.HIGH); pumpPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04, "pump", PinState.HIGH); } /** * Smoke test that switches GPIO pins on and off. * * @throws InterruptedException if thread.sleep can't be executed */ @Category(IntegrationTest.class) @Test public void testGpio() throws InterruptedException { heaterPin.low(); pumpPin.low(); Thread.sleep(1000); Assert.assertEquals(PinState.LOW, heaterPin.getState()); Assert.assertEquals(PinState.LOW, pumpPin.getState()); heaterPin.high(); pumpPin.high(); Thread.sleep(1000); Assert.assertEquals(PinState.HIGH, heaterPin.getState()); Assert.assertEquals(PinState.HIGH, pumpPin.getState()); } }
25.91
91
0.716712
d683bdd0e11e61aba5e2a1c6d7683a4b354966fc
3,828
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.search.documents.implementation.converters; import com.azure.core.util.logging.ClientLogger; import com.azure.core.util.serializer.ObjectSerializer; import com.azure.core.util.serializer.SerializerEncoding; import com.azure.search.documents.models.IndexAction; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.util.Map; import static com.azure.search.documents.implementation.util.Utility.getDefaultSerializerAdapter; /** * A converter between {@link com.azure.search.documents.implementation.models.IndexAction} and {@link IndexAction}. */ public final class IndexActionConverter { private static final ClientLogger LOGGER = new ClientLogger(IndexActionConverter.class); /** * Maps from {@link com.azure.search.documents.implementation.models.IndexAction} to {@link IndexAction}. */ public static <T> IndexAction<T> map(com.azure.search.documents.implementation.models.IndexAction obj) { if (obj == null) { return null; } IndexAction<T> indexAction = new IndexAction<>(); indexAction.setActionType(obj.getActionType()); if (obj.getAdditionalProperties() != null) { Map<String, Object> properties = obj.getAdditionalProperties(); IndexActionHelper.setProperties(indexAction, properties); } return indexAction; } /** * Maps from {@link IndexAction} to {@link com.azure.search.documents.implementation.models.IndexAction}. */ public static <T> com.azure.search.documents.implementation.models.IndexAction map(IndexAction<T> obj, ObjectSerializer serializer) { if (obj == null) { return null; } com.azure.search.documents.implementation.models.IndexAction indexAction = new com.azure.search.documents.implementation.models.IndexAction().setActionType(obj.getActionType()); // Attempt to get the document as the Map<String, Object> properties. Object document = IndexActionHelper.getProperties(obj); if (document == null) { // If ths document wasn't a Map type, get the generic document type. document = obj.getDocument(); } // Convert the document to the JSON string representation. String documentJson; if (serializer == null) { // A custom ObjectSerializer isn't being used, fallback to default JacksonAdapter. try { documentJson = getDefaultSerializerAdapter().serialize(document, SerializerEncoding.JSON); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } else { // A custom ObjectSerializer is being used, use it. documentJson = new String(serializer.serializeToBytes(document), StandardCharsets.UTF_8); } if (documentJson != null) { boolean startsWithCurlyBrace = documentJson.startsWith("{"); boolean endsWithCurlyBrace = documentJson.endsWith("}"); if (startsWithCurlyBrace && endsWithCurlyBrace) { indexAction.setRawDocument(documentJson.substring(1, documentJson.length() - 1)); } else if (startsWithCurlyBrace) { indexAction.setRawDocument(documentJson.substring(1)); } else if (endsWithCurlyBrace) { indexAction.setRawDocument(documentJson.substring(0, documentJson.length() - 1)); } else { indexAction.setRawDocument(documentJson); } } return indexAction; } private IndexActionConverter() { } }
39.875
116
0.670063
398c99560e2b7c9cf153b76e90ac1b97431d0bb6
525
package com.libbytian.pan.system.exception; import lombok.Data; import lombok.EqualsAndHashCode; /** * Created with IntelliJ IDEA. * Description: * @author QiSun */ @EqualsAndHashCode(callSuper = true) @Data public class ImageCodeException extends RuntimeException{ protected final String message; public ImageCodeException(String message) { this.message = message; } public ImageCodeException(String message, Throwable e){ super(message, e); this.message = message; } }
19.444444
59
0.710476
41160dce4fe8053d0b672ef1f7077d4a89868f55
4,000
package wy.addons.zcgl.cpn_room.model; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.enums.IdType; import java.util.Date; /** * 房间Model * * @author wyframe * @Date 2018-01-03 15:02:19 */ public class Xgt_cpn_room { private static final long serialVersionUID = 1L; @TableId(value="room_id", type= IdType.AUTO) private Integer room_id; private String room_nm; private String room_yt; private String room_adrs; private Double room_adrs_x; private Double room_adrs_y; private String romm_photo_url; private String romm_photo_url6; private String romm_photo_url5; private String romm_photo_url4; private String romm_photo_url3; private String romm_photo_url2; private Integer par_room_id; private Integer cpn_branch_id; private Date cre_dt; private Integer st_id; private String oper_user; public Integer getRoom_id() { return room_id; } public void setRoom_id(Integer room_id) { this.room_id = room_id; } public String getRoom_nm() { return room_nm; } public void setRoom_nm(String room_nm) { this.room_nm = room_nm; } public String getRoom_yt() { return room_yt; } public void setRoom_yt(String room_yt) { this.room_yt = room_yt; } public String getRoom_adrs() { return room_adrs; } public void setRoom_adrs(String room_adrs) { this.room_adrs = room_adrs; } public Double getRoom_adrs_x() { return room_adrs_x; } public void setRoom_adrs_x(Double room_adrs_x) { this.room_adrs_x = room_adrs_x; } public Double getRoom_adrs_y() { return room_adrs_y; } public void setRoom_adrs_y(Double room_adrs_y) { this.room_adrs_y = room_adrs_y; } public String getRomm_photo_url() { return romm_photo_url; } public void setRomm_photo_url(String romm_photo_url) { this.romm_photo_url = romm_photo_url; } public String getRomm_photo_url6() { return romm_photo_url6; } public void setRomm_photo_url6(String romm_photo_url6) { this.romm_photo_url6 = romm_photo_url6; } public String getRomm_photo_url5() { return romm_photo_url5; } public void setRomm_photo_url5(String romm_photo_url5) { this.romm_photo_url5 = romm_photo_url5; } public String getRomm_photo_url4() { return romm_photo_url4; } public void setRomm_photo_url4(String romm_photo_url4) { this.romm_photo_url4 = romm_photo_url4; } public String getRomm_photo_url3() { return romm_photo_url3; } public void setRomm_photo_url3(String romm_photo_url3) { this.romm_photo_url3 = romm_photo_url3; } public String getRomm_photo_url2() { return romm_photo_url2; } public void setRomm_photo_url2(String romm_photo_url2) { this.romm_photo_url2 = romm_photo_url2; } public Integer getPar_room_id() { return par_room_id; } public void setPar_room_id(Integer par_room_id) { this.par_room_id = par_room_id; } public Integer getCpn_branch_id() { return cpn_branch_id; } public void setCpn_branch_id(Integer cpn_branch_id) { this.cpn_branch_id = cpn_branch_id; } public Date getCre_dt() { return cre_dt; } public void setCre_dt(Date cre_dt) { this.cre_dt = cre_dt; } public Integer getSt_id() { return st_id; } public void setSt_id(Integer st_id) { this.st_id = st_id; } public String getOper_user() { return oper_user; } public void setOper_user(String oper_user) { this.oper_user = oper_user; } @Override public String toString() { return "Xgt_cpn_room [room_id=" + room_id + ", room_nm=" + room_nm + ", room_yt=" + room_yt + ", room_adrs=" + room_adrs + ", room_adrs_x=" + room_adrs_x + ", room_adrs_y=" + room_adrs_y + ", romm_photo_url=" + romm_photo_url + ", romm_photo_url6=" + romm_photo_url6 + ", romm_photo_url5=" + romm_photo_url5 + ", romm_photo_url4=" + romm_photo_url4 + ", romm_photo_url3=" + romm_photo_url3 + ", romm_photo_url2=" + romm_photo_url2 + ", par_room_id=" + par_room_id + ", cpn_branch_id=" + cpn_branch_id + ", cre_dt=" + cre_dt + ", st_id=" + st_id + ", oper_user=" + oper_user + "]"; } }
23.529412
110
0.73875
a116b6ea3bfe6bd7352441eee7ec4bbcdd948b99
2,971
package dev.satyrn.wolfarmor.common.network.packets; import dev.satyrn.wolfarmor.common.network.MessageBase; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.io.IOException; public class UpdatePotionEffectMessage extends MessageBase.ClientMessageBase<UpdatePotionEffectMessage> { private int entityId; private byte effectId; private byte amplifier; private int duration; private byte flags; public UpdatePotionEffectMessage() {} public UpdatePotionEffectMessage(int entityId, PotionEffect potionEffect) { this.entityId = entityId; this.effectId = (byte)(Potion.getIdFromPotion(potionEffect.getPotion()) & 0xff); this.amplifier = (byte)(potionEffect.getAmplifier() & 0xFF); this.duration = Math.min(Short.MAX_VALUE, potionEffect.getDuration()); this.flags = 0; if (potionEffect.getIsAmbient()) { this.flags |= 0b01; } if (potionEffect.doesShowParticles()) { this.flags |= 0b10; } } @Override protected void read(PacketBuffer buffer) throws IOException { this.entityId = buffer.readVarInt(); this.effectId = buffer.readByte(); this.amplifier = buffer.readByte(); this.duration = buffer.readVarInt(); this.flags = buffer.readByte(); } @Override protected void write(PacketBuffer buffer) throws IOException { buffer.writeVarInt(this.entityId); buffer.writeByte(this.effectId); buffer.writeByte(this.amplifier); buffer.writeVarInt(this.duration); buffer.writeByte(this.flags); } @SideOnly(Side.CLIENT) public boolean doesShowParticles() { return (this.flags & 0b10) == 0b10; } @SideOnly(Side.CLIENT) public boolean getIsAmbient() { return (this.flags & 0b01) == 0b01; } @SideOnly(Side.CLIENT) public boolean isMaxDuration() { return this.duration == Short.MAX_VALUE; } @Override protected IMessage process(EntityPlayer player, Side side) { Entity entity = player.getEntityWorld().getEntityByID(this.entityId); if (entity instanceof EntityLivingBase) { Potion potion = Potion.getPotionById(this.effectId & 0xFF); if (potion != null) { PotionEffect potioneffect = new PotionEffect(potion, this.duration, this.amplifier, this.getIsAmbient(), this.doesShowParticles()); potioneffect.setPotionDurationMax(this.isMaxDuration()); ((EntityLivingBase) entity).addPotionEffect(potioneffect); } } return null; } }
37.607595
147
0.692696
e5dfc96426de447d920b1053f9dc6d28490b8e03
336
package spins.promela.compiler.ltsmin.matrix; import spins.promela.compiler.expression.Expression; /** * * @author FIB */ public interface LTSminGuardContainer extends Iterable<LTSminGuardBase> { abstract public void addGuard(LTSminGuardBase guard); abstract public void addGuard(Expression guard); abstract int guardCount(); }
24
73
0.794643
2c17761fc4792ab39b734a990ce13c875e84fb93
2,004
package cc.mrbird.febs.yb.dao; import cc.mrbird.febs.yb.entity.YbReconsiderVerifyView; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.ibatis.annotations.Param; import java.util.List; /** * <p> * VIEW Mapper 接口 * </p> * * @author viki * @since 2020-07-30 */ public interface YbReconsiderVerifyViewMapper extends BaseMapper<YbReconsiderVerifyView> { void updateYbReconsiderVerifyView(YbReconsiderVerifyView ybReconsiderVerifyView); IPage<YbReconsiderVerifyView> findYbReconsiderVerifyView(Page page, @Param("ybReconsiderVerifyView") YbReconsiderVerifyView ybReconsiderVerifyView); int findReconsiderVerifyApplyDateCount(@Param("ybReconsiderVerifyView") YbReconsiderVerifyView ybReconsiderVerifyView); IPage<YbReconsiderVerifyView> findReconsiderVerifyViewNull(Page page, @Param("ybReconsiderVerifyView") YbReconsiderVerifyView ybReconsiderVerifyView, @Param("searchType") String[] searchType); int findReconsiderVerifyCountNull(@Param("ybReconsiderVerifyView") YbReconsiderVerifyView ybReconsiderVerifyView, @Param("searchType") String[] searchType); // IPage<YbReconsiderVerifyView> findReconsiderVerifyView(Page page, @Param("ybReconsiderVerifyView") YbReconsiderVerifyView ybReconsiderVerifyView, @Param("searchType") String[] searchType); // int findReconsiderVerifyCount(@Param("ybReconsiderVerifyView") YbReconsiderVerifyView ybReconsiderVerifyView, @Param("searchType") String[] searchType); IPage<YbReconsiderVerifyView> findReconsiderVerifyView(Page page, @Param("ybReconsiderVerifyView") YbReconsiderVerifyView ybReconsiderVerifyView); int findReconsiderVerifyCount(@Param("ybReconsiderVerifyView") YbReconsiderVerifyView ybReconsiderVerifyView); List<YbReconsiderVerifyView> findReconsiderVerifyViewList(@Param("ybReconsiderVerifyView") YbReconsiderVerifyView ybReconsiderVerifyView); }
45.545455
196
0.826846
ca826ccfd0bdb02c50a89a06f0c6ee509b9248f4
2,259
package com.xiaoke1256.bizliconchain.common.service; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Timestamp; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.xiaoke1256.bizliconchain.common.bo.EthTrasLog; import com.xiaoke1256.bizliconchain.common.bo.EthTrasLogSearchCondition; import com.xiaoke1256.bizliconchain.common.dao.EthTrasLogMapper; @Service @Transactional public class EthTrasLogService { /** * 本系统自定义的STATUS(S:成功;C:已提交;E:错误) */ public static final String STATUS_SUCCESS = "S"; public static final String STATUS_COMMITED = "C"; public static final String STATUS_ERROR = "E"; @Autowired private EthTrasLogMapper ethTrasLogMapper; @Transactional(readOnly=true) public EthTrasLog getEthTrasLog(Integer logId) { return ethTrasLogMapper.getEthTrasLog(logId); } public void saveLog(EthTrasLog log) { ethTrasLogMapper.saveLog(log); } public EthTrasLog saveLog(String nonce,String contractAddress,String method,String bizKey,String trasHash,BigInteger gasPrice) { EthTrasLog log = new EthTrasLog(); log.setNonce(nonce); log.setContractAddress(contractAddress); log.setMethod(method); log.setBizKey(bizKey); log.setTrasHash(trasHash); log.setStatus(STATUS_COMMITED); log.setGasPrice(gasPrice); Timestamp now = new Timestamp(System.currentTimeMillis()); log.setInsertTime(now); log.setUpdateTime(now); ethTrasLogMapper.saveLog(log); return log; } public void updateLog(EthTrasLog log) { log.setUpdateTime(new Timestamp(System.currentTimeMillis())); ethTrasLogMapper.updateLog(log); } @Transactional(readOnly=true) public List<EthTrasLog> searchLog(EthTrasLogSearchCondition condition){ return ethTrasLogMapper.searchLog(condition); } public void modifyError(EthTrasLog log,String errMsg) { log.setStatus(STATUS_ERROR); log.setErrMsg(errMsg); log.setFinishTime(new Timestamp(System.currentTimeMillis())); log.setUpdateTime(new Timestamp(System.currentTimeMillis())); ethTrasLogMapper.updateLog(log); } }
31.375
130
0.764498
5ae5fe015e495f0b2310be43dec04f5ce127caf8
1,485
package io.redskap.swagger.brake.core.util; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; public class PathNormalizerTest { @Test(expected = IllegalArgumentException.class) public void testNormalizePathSlashesThrowsExceptionWhenNullGiven() { // given // when PathNormalizer.normalizePathSlashes(null); // then exception thrown } @Test(expected = IllegalArgumentException.class) public void testNormalizePathSlashesThrowsExceptionWhenBlankGiven() { // given // when PathNormalizer.normalizePathSlashes(" "); // then exception thrown } @Test public void testNormalizePathSlashesAddsNecessaryLeadingSlashesIfMissing() { // given // when String result = PathNormalizer.normalizePathSlashes("test/path"); // then assertThat(result).isEqualTo("/test/path"); } @Test public void testNormalizePathSlashesRemovesUnnecessaryTrailingSlashesIfAny() { // given // when String result = PathNormalizer.normalizePathSlashes("/test/path/"); // then assertThat(result).isEqualTo("/test/path"); } @Test public void testNormalizePathSlashesRemovesAndAddsSlashesWhereNeeded() { // given // when String result = PathNormalizer.normalizePathSlashes("test/path/"); // then assertThat(result).isEqualTo("/test/path"); } }
29.117647
82
0.664646
40d5e0c20b16676c6852cbc5b83e7ecba355fd2e
833
package rs.ac.uns.pmf.footballteamfinder.framework.networkmodel.team; import com.google.gson.annotations.SerializedName; public class VenueNetworkEntity { @SerializedName("image") private String image; @SerializedName("address") private String address; @SerializedName("surface") private String surface; @SerializedName("city") private String city; @SerializedName("name") private String name; @SerializedName("id") private int id; @SerializedName("capacity") private int capacity; public String getImage(){ return image; } public String getAddress(){ return address; } public String getSurface(){ return surface; } public String getCity(){ return city; } public String getName(){ return name; } public int getId(){ return id; } public int getCapacity(){ return capacity; } }
15.145455
69
0.726291
fb96372152e5cae107108658a21bc5517aaaa32e
13,050
package rocks.metaldetector.service.summary; import org.assertj.core.api.WithAssertions; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import rocks.metaldetector.butler.facade.ReleaseService; import rocks.metaldetector.support.DetectorSort; import rocks.metaldetector.support.Page; import rocks.metaldetector.support.PageRequest; import rocks.metaldetector.support.Pagination; import rocks.metaldetector.support.TimeRange; import rocks.metaldetector.testutil.DtoFactory.ArtistDtoFactory; import rocks.metaldetector.testutil.DtoFactory.ReleaseDtoFactory; import java.time.LocalDate; import java.util.Collections; import java.util.List; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static rocks.metaldetector.service.summary.SummaryServiceImpl.RESULT_LIMIT; import static rocks.metaldetector.service.summary.SummaryServiceImpl.TIME_RANGE_MONTHS; import static rocks.metaldetector.support.DetectorSort.Direction.ASC; import static rocks.metaldetector.support.DetectorSort.Direction.DESC; @ExtendWith(MockitoExtension.class) class ReleaseCollectorTest implements WithAssertions { @Mock private ReleaseService releaseService; @InjectMocks private ReleaseCollector underTest; @AfterEach void tearDown() { reset(releaseService); } @Test @DisplayName("collecting upcoming releases does not call releaseService when no artists are given") void test_upcoming_releases_does_not_call_release_service() { // when underTest.collectUpcomingReleases(Collections.emptyList()); // then verifyNoInteractions(releaseService); } @Test @DisplayName("collecting upcoming releases calls releaseService with followed artists' names") void test_upcoming_releases_calls_release_service_with_artist_names() { // given var expectedArtistNames = List.of("A"); var artists = List.of(ArtistDtoFactory.withName("A")); doReturn(new Page<>(Collections.emptyList(), new Pagination())).when(releaseService).findReleases(any(), any(), any(), any()); // when underTest.collectUpcomingReleases(artists); // then verify(releaseService).findReleases(eq(expectedArtistNames), any(), any(), any()); } @Test @DisplayName("collecting upcoming releases calls releaseService with correct time range") void test_upcoming_releases_calls_release_service_with_time_range() { // given var tomorrow = LocalDate.now().plusDays(1); var expectedTimeRange = new TimeRange(tomorrow, tomorrow.plusMonths(TIME_RANGE_MONTHS)); var artists = List.of(ArtistDtoFactory.withName("A")); doReturn(new Page<>(Collections.emptyList(), new Pagination())).when(releaseService).findReleases(any(), any(), any(), any()); // when underTest.collectUpcomingReleases(artists); // then verify(releaseService).findReleases(any(), eq(expectedTimeRange), any(), any()); } @Test @DisplayName("collecting upcoming releases calls releaseService without query") void test_upcoming_releases_calls_release_service_without_query() { // given var artists = List.of(ArtistDtoFactory.withName("A")); doReturn(new Page<>(Collections.emptyList(), new Pagination())).when(releaseService).findReleases(any(), any(), any(), any()); // when underTest.collectUpcomingReleases(artists); // then verify(releaseService).findReleases(any(), any(), eq(null), any()); } @Test @DisplayName("collecting upcoming releases calls releaseService with correct page request and sorting") void test_upcoming_releases_calls_release_service_with_page_request() { // given var sorting = new DetectorSort("releaseDate", ASC); var expectedPageRequest = new PageRequest(1, RESULT_LIMIT, sorting); var artists = List.of(ArtistDtoFactory.withName("A")); doReturn(new Page<>(Collections.emptyList(), new Pagination())).when(releaseService).findReleases(any(), any(), any(), any()); // when underTest.collectUpcomingReleases(artists); // then verify(releaseService).findReleases(any(), any(), any(), eq(expectedPageRequest)); } @Test @DisplayName("collecting upcoming releases returns list of releases") void test_upcoming_returns_releases() { // given var artists = List.of(ArtistDtoFactory.withName("A")); var releases = List.of(ReleaseDtoFactory.createDefault(), ReleaseDtoFactory.createDefault()); doReturn(new Page<>(releases, new Pagination())).when(releaseService).findReleases(any(), any(), any(), any()); // when var result = underTest.collectUpcomingReleases(artists); // then assertThat(result).isEqualTo(releases); } @Test @DisplayName("collecting recent releases does not call releaseService when no artists are given") void test_recent_releases_does_not_call_release_service() { // when underTest.collectRecentReleases(Collections.emptyList()); // then verifyNoInteractions(releaseService); } @Test @DisplayName("collecting recent releases calls releaseService with followed artists' names") void test_recent_releases_calls_release_service_with_artist_names() { // given var expectedArtistNames = List.of("A"); var artists = List.of(ArtistDtoFactory.withName("A")); doReturn(new Page<>(Collections.emptyList(), new Pagination())).when(releaseService).findReleases(any(), any(), any(), any()); // when underTest.collectRecentReleases(artists); // then verify(releaseService).findReleases(eq(expectedArtistNames), any(), any(), any()); } @Test @DisplayName("collecting recent releases calls releaseService with correct time range") void test_recent_releases_calls_release_service_with_time_range() { // given var now = LocalDate.now(); var expectedTimeRange = new TimeRange(now.minusMonths(TIME_RANGE_MONTHS), now); var artists = List.of(ArtistDtoFactory.withName("A")); doReturn(new Page<>(Collections.emptyList(), new Pagination())).when(releaseService).findReleases(any(), any(), any(), any()); // when underTest.collectRecentReleases(artists); // then verify(releaseService).findReleases(any(), eq(expectedTimeRange), any(), any()); } @Test @DisplayName("collecting recent releases calls releaseService without query") void test_recent_releases_calls_release_service_without_query() { // given var artists = List.of(ArtistDtoFactory.withName("A")); doReturn(new Page<>(Collections.emptyList(), new Pagination())).when(releaseService).findReleases(any(), any(), any(), any()); // when underTest.collectRecentReleases(artists); // then verify(releaseService).findReleases(any(), any(), eq(null), any()); } @Test @DisplayName("collecting recent releases calls releaseService with correct page request and sorting") void test_recent_releases_calls_release_service_with_page_request() { // given var expectedSorting = new DetectorSort("releaseDate", DESC); var expectedPageRequest = new PageRequest(1, RESULT_LIMIT, expectedSorting); var artists = List.of(ArtistDtoFactory.withName("A")); doReturn(new Page<>(Collections.emptyList(), new Pagination())).when(releaseService).findReleases(any(), any(), any(), any()); // when underTest.collectRecentReleases(artists); // then verify(releaseService).findReleases(any(), any(), any(), eq(expectedPageRequest)); } @Test @DisplayName("collecting top releases does not call releaseService when no artists are given") void test_top_releases_does_not_call_release_service() { // when underTest.collectTopReleases(new TimeRange(), Collections.emptyList(), 10); // then verifyNoInteractions(releaseService); } @Test @DisplayName("collecting top releases calls releaseService with top followed artists' names") void test_top_releases_calls_release_service_with_top_artist_names() { // given var expectedArtistNames = List.of("A"); var artists = List.of(ArtistDtoFactory.withName("A")); doReturn(new Page<>(Collections.emptyList(), new Pagination())).when(releaseService).findReleases(any(), any(), any(), any()); // when underTest.collectTopReleases(new TimeRange(), artists, 10); // then verify(releaseService).findReleases(eq(expectedArtistNames), any(), any(), any()); } @Test @DisplayName("collecting top releases calls releaseService with given time range") void test_top_releases_calls_release_service_with_time_range() { // given var now = LocalDate.now(); var timeRange = new TimeRange(now, now.plusDays(666)); var artists = List.of(ArtistDtoFactory.withName("A")); doReturn(new Page<>(Collections.emptyList(), new Pagination())).when(releaseService).findReleases(any(), any(), any(), any()); // when underTest.collectTopReleases(timeRange, artists, 10); // then verify(releaseService).findReleases(any(), eq(timeRange), any(), any()); } @Test @DisplayName("collecting top releases calls releaseService without query") void test_top_releases_calls_release_service_without_query() { // given var artists = List.of(ArtistDtoFactory.withName("A")); doReturn(new Page<>(Collections.emptyList(), new Pagination())).when(releaseService).findReleases(any(), any(), any(), any()); // when underTest.collectTopReleases(new TimeRange(), artists, 10); // then verify(releaseService).findReleases(any(), any(), eq(null), any()); } @Test @DisplayName("collecting top releases calls releaseService with correct page request and sorting") void test_top_releases_calls_release_service_with_page_request() { // given var sorting = new DetectorSort("artist", ASC); var expectedPageRequest = new PageRequest(1, RESULT_LIMIT, sorting); var artists = List.of(ArtistDtoFactory.withName("A")); doReturn(new Page<>(Collections.emptyList(), new Pagination())).when(releaseService).findReleases(any(), any(), any(), any()); // when underTest.collectTopReleases(new TimeRange(), artists, 10); // then verify(releaseService).findReleases(any(), any(), any(), eq(expectedPageRequest)); } @Test @DisplayName("collecting top releases fetches releases with most followers first") void test_top_releases_most_followed() { // given var artist1 = ArtistDtoFactory.withName("a"); var artist2 = ArtistDtoFactory.withName("b"); artist1.setFollower(5); artist2.setFollower(10); var release1 = ReleaseDtoFactory.withArtistName(artist1.getArtistName()); var release2 = ReleaseDtoFactory.withArtistName(artist2.getArtistName()); var artists = List.of(artist1, artist2); doReturn(new Page<>(List.of(release2, release1), new Pagination())).when(releaseService).findReleases(any(), any(), any(), any()); // when var result = underTest.collectTopReleases(new TimeRange(), artists, 1); // then assertThat(result).containsExactly(release2); } @Test @DisplayName("collecting top releases sorts by release date") void test_top_releases_sorted() { // given var artist1 = ArtistDtoFactory.withName("a"); var artist2 = ArtistDtoFactory.withName("b"); var release1 = ReleaseDtoFactory.withArtistName(artist1.getArtistName()); var release2 = ReleaseDtoFactory.withArtistName(artist2.getArtistName()); release2.setReleaseDate(LocalDate.now().minusDays(10)); var artists = List.of(artist1, artist2); doReturn(new Page<>(List.of(release2, release1), new Pagination())).when(releaseService).findReleases(any(), any(), any(), any()); // when var result = underTest.collectTopReleases(new TimeRange(), artists, 10); // then assertThat(result).hasSize(2); assertThat(result.get(0)).isEqualTo(release2); assertThat(result.get(1)).isEqualTo(release1); } @Test @DisplayName("collecting top releases limits to given value") void test_top_releases_limited() { // given var maxReleases = 1; var artist1 = ArtistDtoFactory.withName("a"); var artist2 = ArtistDtoFactory.withName("b"); artist1.setFollower(2); artist2.setFollower(1); var release1 = ReleaseDtoFactory.withArtistName(artist1.getArtistName()); var release2 = ReleaseDtoFactory.withArtistName(artist2.getArtistName()); var artists = List.of(artist1, artist2); doReturn(new Page<>(List.of(release2, release1), new Pagination())).when(releaseService).findReleases(any(), any(), any(), any()); // when var result = underTest.collectTopReleases(new TimeRange(), artists, maxReleases); // then assertThat(result).hasSize(maxReleases); assertThat(result).containsExactly(release1); } }
38.382353
134
0.73387
e5d25506b07429736f99dd693c9a5ea14d989405
6,459
/** * * Copyright (c) Microsoft and contributors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * */ // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. package com.microsoft.azure.management.dns.models; import java.util.ArrayList; /** * Represents the properties of the records in the RecordSet. */ public class RecordSetProperties { private ArrayList<AaaaRecord> aaaaRecords; /** * Optional. Gets or sets the list of AAAA records in the RecordSet. * @return The AaaaRecords value. */ public ArrayList<AaaaRecord> getAaaaRecords() { return this.aaaaRecords; } /** * Optional. Gets or sets the list of AAAA records in the RecordSet. * @param aaaaRecordsValue The AaaaRecords value. */ public void setAaaaRecords(final ArrayList<AaaaRecord> aaaaRecordsValue) { this.aaaaRecords = aaaaRecordsValue; } private ArrayList<ARecord> aRecords; /** * Optional. Gets or sets the list of A records in the RecordSet. * @return The ARecords value. */ public ArrayList<ARecord> getARecords() { return this.aRecords; } /** * Optional. Gets or sets the list of A records in the RecordSet. * @param aRecordsValue The ARecords value. */ public void setARecords(final ArrayList<ARecord> aRecordsValue) { this.aRecords = aRecordsValue; } private CnameRecord cnameRecord; /** * Optional. Gets or sets the CNAME record in the RecordSet. * @return The CnameRecord value. */ public CnameRecord getCnameRecord() { return this.cnameRecord; } /** * Optional. Gets or sets the CNAME record in the RecordSet. * @param cnameRecordValue The CnameRecord value. */ public void setCnameRecord(final CnameRecord cnameRecordValue) { this.cnameRecord = cnameRecordValue; } private ArrayList<MxRecord> mxRecords; /** * Optional. Gets or sets the list of MX records in the RecordSet. * @return The MxRecords value. */ public ArrayList<MxRecord> getMxRecords() { return this.mxRecords; } /** * Optional. Gets or sets the list of MX records in the RecordSet. * @param mxRecordsValue The MxRecords value. */ public void setMxRecords(final ArrayList<MxRecord> mxRecordsValue) { this.mxRecords = mxRecordsValue; } private ArrayList<NsRecord> nsRecords; /** * Optional. Gets or sets the list of NS records in the RecordSet. * @return The NsRecords value. */ public ArrayList<NsRecord> getNsRecords() { return this.nsRecords; } /** * Optional. Gets or sets the list of NS records in the RecordSet. * @param nsRecordsValue The NsRecords value. */ public void setNsRecords(final ArrayList<NsRecord> nsRecordsValue) { this.nsRecords = nsRecordsValue; } private ArrayList<PtrRecord> ptrRecords; /** * Optional. Gets or sets the list of PTR records in the RecordSet. * @return The PtrRecords value. */ public ArrayList<PtrRecord> getPtrRecords() { return this.ptrRecords; } /** * Optional. Gets or sets the list of PTR records in the RecordSet. * @param ptrRecordsValue The PtrRecords value. */ public void setPtrRecords(final ArrayList<PtrRecord> ptrRecordsValue) { this.ptrRecords = ptrRecordsValue; } private SoaRecord soaRecord; /** * Optional. Gets or sets the SOA record in the RecordSet. * @return The SoaRecord value. */ public SoaRecord getSoaRecord() { return this.soaRecord; } /** * Optional. Gets or sets the SOA record in the RecordSet. * @param soaRecordValue The SoaRecord value. */ public void setSoaRecord(final SoaRecord soaRecordValue) { this.soaRecord = soaRecordValue; } private ArrayList<SrvRecord> srvRecords; /** * Optional. Gets or sets the list of SRV records in the RecordSet. * @return The SrvRecords value. */ public ArrayList<SrvRecord> getSrvRecords() { return this.srvRecords; } /** * Optional. Gets or sets the list of SRV records in the RecordSet. * @param srvRecordsValue The SrvRecords value. */ public void setSrvRecords(final ArrayList<SrvRecord> srvRecordsValue) { this.srvRecords = srvRecordsValue; } private long ttl; /** * Required. Gets or sets the TTL of the records in the RecordSet. * @return The Ttl value. */ public long getTtl() { return this.ttl; } /** * Required. Gets or sets the TTL of the records in the RecordSet. * @param ttlValue The Ttl value. */ public void setTtl(final long ttlValue) { this.ttl = ttlValue; } private ArrayList<TxtRecord> txtRecords; /** * Optional. Gets or sets the list of TXT records in the RecordSet. * @return The TxtRecords value. */ public ArrayList<TxtRecord> getTxtRecords() { return this.txtRecords; } /** * Optional. Gets or sets the list of TXT records in the RecordSet. * @param txtRecordsValue The TxtRecords value. */ public void setTxtRecords(final ArrayList<TxtRecord> txtRecordsValue) { this.txtRecords = txtRecordsValue; } /** * Initializes a new instance of the RecordSetProperties class. * */ public RecordSetProperties() { } /** * Initializes a new instance of the RecordSetProperties class with required * arguments. * * @param ttl Gets or sets the TTL of the records in the RecordSet. */ public RecordSetProperties(long ttl) { this(); this.setTtl(ttl); } }
28.082609
79
0.65041
286aa02f0f38b031362d220912aede3a13c0a198
2,202
package de.uniwue.informatik.praline.pseudocircuitplans.properties; import de.uniwue.informatik.praline.datastructure.graphs.Graph; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; /** * Object for gathering {@link PropertyValue}s for one graph */ public class PropertySheet { private Graph graph; private LinkedHashMap<String, PropertyValue> allValues = new LinkedHashMap<>(); public PropertySheet(Graph graph) { this.graph = graph; } /** * * @param propertyValue * @param <E> * @return * false if the value was not added because there is already a value of this property (remove it first from * this sheet!) * or true if the value was added */ public <E> boolean addValue(PropertyValue<E> propertyValue) { String propertyName = propertyValue.getProperty().getPropertyName(); if (allValues.containsKey(propertyName)) { return false; } allValues.put(propertyName, propertyValue); return true; } public <E> PropertyValue<E> removeValue(PropertyValue<E> propertyValue) { String propertyName = propertyValue.getProperty().getPropertyName(); if (!allValues.containsKey(propertyName)) { return null; } return allValues.remove(propertyName); } public Collection<PropertyValue> getAllValues() { return new ArrayList<>(allValues.values()); } public void removeAllValues() { allValues.clear(); } public <E> E getPropertyValue(String propertyName) { return (E) allValues.get(propertyName).getValue(); } public <E> E getPropertyValue(Property<E> property) { return (E) allValues.get(property.getPropertyName()).getValue(); } public <N extends Number & Comparable> NumberDistribution<N> getPropertyValue(NumberDistributionProperty<N> property) { return (NumberDistribution<N>) allValues.get(property.getPropertyName()).getValue(); } public Graph getGraph() { return graph; } }
30.164384
116
0.638056
75d7e020450cf445119af784b313dd27cf877840
1,280
/* * 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 io.github.faimoh.todowebapp.actions; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * * @author Faisal Ahmed Pasha Mohammed https://github.com/faimoh */ public class Utilities { public static String parseRequestParameterWithDefault(String parameter, String def) { if(parameter == null || parameter.isBlank() || parameter.isEmpty()) { return def; }else { return parameter; } } public static int parseWithDefault(String s, int def) { try { return Integer.parseInt(s); } catch (NumberFormatException e) { return def; } } public static Timestamp parseDateAndTime(String strDate, String strTime) { try { Date dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(strDate+" "+strTime); return new Timestamp(dateTime.getTime()); } catch (ParseException pe) { return null; } } }
30.47619
99
0.617969
5f3b3e4a9dd405f572803527d8b523f0a22bc8ec
4,648
package cn.org.rapid_framework.generator.ext.ant; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Arrays; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; import cn.org.rapid_framework.generator.GeneratorFacade; import cn.org.rapid_framework.generator.GeneratorProperties; import cn.org.rapid_framework.generator.ext.tableconfig.builder.TableConfigXmlBuilder; import cn.org.rapid_framework.generator.ext.tableconfig.model.TableConfigSet; import cn.org.rapid_framework.generator.util.SystemHelper; public abstract class BaseGeneratorTask extends Task{ protected Path classpath; protected String shareInput; //共享模板目录,可以使用classpath:前缀 protected String input; //模板输入目录,可以使用classpath:前缀 protected String output; //模板输出目录,可以使用classpath:前缀 private boolean openOutputDir = false; private String _package; public static Properties toProperties(Hashtable properties) { Properties props = new Properties(); props.putAll(properties); return props; } private void error(Exception e) { StringWriter out = new StringWriter(); e.printStackTrace(new PrintWriter(out)); log(out.toString(),Project.MSG_ERR); } protected GeneratorFacade createGeneratorFacade(String input,String output) { if(input == null) throw new IllegalArgumentException("input must be not null"); if(output == null) throw new IllegalArgumentException("output must be not null"); GeneratorProperties.setProperties(new Properties()); Properties properties = toProperties(getProject().getProperties()); properties.setProperty("basedir", getProject().getBaseDir().getAbsolutePath()); GeneratorProperties.setProperties(properties); GeneratorFacade gf = new GeneratorFacade(); gf.getGenerator().addTemplateRootDir(input); if(shareInput != null) { gf.getGenerator().addTemplateRootDir(shareInput); } gf.getGenerator().setOutRootDir(output); return gf; } public String getShareInput() { return shareInput; } public void setShareInput(String shareInput) { this.shareInput = shareInput; } public void setInput(String input) { this.input = input; } public void setOutput(String output) { this.output = output; } public void setOpenOutputDir(boolean openOutputDir) { this.openOutputDir = openOutputDir; } public String getPackage() { return _package; } public void setPackage(String _package) { this._package = _package; } public void setClasspathRef(Reference r){ this.classpath = new Path(getProject()); this.classpath.setRefid(r); } @Override final public void execute() throws BuildException { super.execute(); setContextClassLoader(); try { executeInternal(); }catch(Exception e) { error(e); throw new BuildException(e); } } protected void executeInternal() throws Exception { freemarker.log.Logger.selectLoggerLibrary(freemarker.log.Logger.LIBRARY_NONE); executeBefore(); GeneratorFacade facade = createGeneratorFacade(input,output); List<Map> maps = getGeneratorContexts(); if(maps == null) return; for(Map map : maps) { facade.generateByMap(map); } if(openOutputDir && SystemHelper.isWindowsOS) { Runtime.getRuntime().exec("cmd.exe /c start "+output); } } private void setContextClassLoader() { if(classpath == null) { String cp = ((AntClassLoader) getClass().getClassLoader()).getClasspath(); classpath = new Path(getProject(),cp); } AntClassLoader classloader = new AntClassLoader(getProject(),classpath,true); Thread.currentThread().setContextClassLoader(classloader); } protected void executeBefore() throws Exception { } protected abstract List<Map> getGeneratorContexts() throws Exception; }
32.503497
90
0.652324
792133ee5ae5e03ef9cc05038d4cbca5aae785c9
1,246
package ampcontrol.model.training.model.validation.listen; import org.nd4j.evaluation.classification.Evaluation; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.function.Consumer; /** * Check point for {@link Evaluation Evaluations}. Stores the result in a text file. */ public class EvalCheckPoint implements Consumer<Evaluation> { private final String fileName; private final String modelName; private final TextWriter.Factory writerFactory; /** * Constructor * @param fileName name of the file to write evaluation to * @param modelName Name of the model */ public EvalCheckPoint(String fileName, String modelName, TextWriter.Factory writerFactory) { this.fileName = fileName; this.modelName = modelName; this.writerFactory = writerFactory; } @Override public void accept(Evaluation eval) { try { Path path = Paths.get(fileName); TextWriter writer = writerFactory.create(path); writer.write(modelName + "\n"); writer.write(eval.stats()); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
28.318182
96
0.666132
08c104a72268e2329d76a3a55cba7b3257f1ce4f
742
package ru.job4j.bomberman.threads; import ru.job4j.bomberman.Board; import ru.job4j.bomberman.Cell; import ru.job4j.bomberman.units.Unit; /** * @author shaplov * @since 24.05.2019 */ public abstract class Job implements Runnable { protected final Unit unit; protected final Board board; public Job(Board board, Unit unit) { this.board = board; this.unit = unit; } protected boolean tryMove(int deltaX, int deltaY) throws InterruptedException { Cell dest = new Cell(unit.getCell().getRow() + deltaX, unit.getCell().getCol() + deltaY); boolean result = board.move(unit.getCell(), dest); if (result) { unit.setCell(dest); } return result; } }
23.935484
97
0.645553
25c0a110cc1528443512a08d8bd9f885d7f25d23
553
package q11291; public class StaticFieldDemo { public static void main(String[] args) { A.aStaticField = 5; A a1 = new A(3); A a2 = new A(4); System.out.println("a1 = " + a1); System.out.println("a2 = " + a2); System.out.println("A.aStaticField = " + A.aStaticField); } } class A { public static int aStaticField; private int instanceField; public A(int instanceField) { this.instanceField = instanceField; } public String toString() { return "A [instanceField = " + instanceField + ", aStaticField = " + aStaticField + "]"; } }
25.136364
90
0.663653
6af12a548bff1651ab195cd31b01513851da0371
1,562
package com.augur.tacacs; /** * Used in authorization REQUEST and RESPONSE packets. * * @author [email protected] * Copyright 2016 Augur Systems, Inc. All rights reserved. */ public class Argument { final String attribute; final String value; final boolean isOptional; /** * Create an attribute-value pair, also called a argument. * * @param attribute The non-null String attribute name * @param value The possibly null String value * @param isOptional A boolean flag indicating the value is optional */ public Argument(String attribute, String value, boolean isOptional) { this.attribute = attribute; this.value = value; this.isOptional = isOptional; } /** * Parses an argument read from a packet. * @param arg The non-null, non-empty String representation of an attribute-value pair. */ public Argument(String arg) { String[] args = arg.split("[=*]", 2); this.attribute=args[0]; if (args.length==2) { this.value=args[1]; } else { this.value = null; } isOptional = (arg.length() > attribute.length()) && // there is another character after the attribute name (arg.charAt(attribute.length()) == '*'); } /** @return The argument's String attribute name. */ public String getAttribute() { return attribute; } /** @return The argument's String value; possibly null. */ public String getValue() { return value; } public boolean isOptional() { return isOptional; } @Override public String toString() { return attribute+(isOptional?"*":"=")+(value==null?"":value); } }
22.637681
108
0.683739
215f1f2199efca54011d76a6373737ecc0642cc4
886
package DP_entity_linking.geneticAlgorithm.similarity; import DP_entity_linking.geneticAlgorithm.GenSequence; import DP_entity_linking.geneticAlgorithm.Interval; import org.apache.lucene.search.similarities.LMJelinekMercerSimilarity; import org.apache.lucene.search.similarities.Similarity; import java.util.Random; /** * Created by miroslav.kudlac on 11/22/2015. */ public class LmJelink implements GenSequence<Similarity> { private Interval value; public LmJelink() { this.value = new Interval(0.000001f, 0.0001f, 100); this.value.setUsek(100); } @Override public void mutate(Random rnd) { value.mutate(rnd); } @Override public void create(Random rnd) { this.value.create(rnd); } @Override public Similarity get() { return new LMJelinekMercerSimilarity( value.getCurrentPosition() ); } }
25.314286
75
0.716704
754a24475cccfebd43e4f28593222e805537d1ba
4,917
package br.com.gbvbahia.maker.works; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import junit.framework.TestCase; import org.apache.commons.logging.Log; import org.junit.Before; import org.junit.Test; import br.com.gbvbahia.entities.EntityPatternTest; import br.com.gbvbahia.entities.EntitySetComplexTest; import br.com.gbvbahia.entities.EntitySetTest; import br.com.gbvbahia.maker.MakeEntity; import br.com.gbvbahia.maker.factories.Factory; import br.com.gbvbahia.maker.factories.types.works.MakeSet; import br.com.gbvbahia.maker.log.LogInfo; /** * @since v.1 01/05/2012 * @author Guilherme */ public class MakeSetTest extends TestCase { private static Log logger = LogInfo.getLog("Test :: MakeSetTest"); private Pattern pattern; private Validator validator; public MakeSetTest() { super("MakeSetTest"); } @Before @Override public void setUp() { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); this.validator = factory.getValidator(); this.pattern = Pattern.compile(MakeSet.KEY_PROPERTY); } @Test public void testRegexSet() throws Exception { logger.debug("String - GetRegexSet"); Matcher matcher = this.pattern.matcher("isSet{br.com.compre}[1,1]"); boolean test = matcher.find(); assertTrue("Primeiro: deveria ser true.", test); matcher = this.pattern.matcher("isSet{br.com.compre}[0,10]"); boolean test2 = matcher.find(); assertTrue("Segundo: deveria ser true.", test2); matcher = this.pattern.matcher("isSet{br.com.gbvbahia.entityes.EntityPatternTest}[999,10000]"); boolean test3 = matcher.find(); assertTrue("Terceiro: deveria ser true.", test3); matcher = this.pattern.matcher("isSet{}[9,10]"); boolean testfalse1 = matcher.find(); assertFalse("TesteFalse1: deveria ser false.", testfalse1); matcher = this.pattern.matcher("isSet{}"); boolean testfalse2 = matcher.find(); assertFalse("TesteFalse2: deveria ser false.", testfalse2); matcher = this.pattern.matcher("isSet{br. com.compre}[1,3]"); boolean testfalse25 = matcher.find(); assertFalse("TesteFalse2_5: deveria ser false.", testfalse25); matcher = this.pattern.matcher("isSet{br.com.compre}9,9"); boolean testfalse3 = matcher.find(); assertFalse("TesteFalse3: deveria ser false.", testfalse3); matcher = this.pattern.matcher("isSet{br.com.compre}[a9,23]"); boolean testfalse4 = matcher.find(); assertFalse("TesteFalse4: deveria ser false.", testfalse4); matcher = this.pattern.matcher("isSet[br.com.compre][1,a2]"); boolean testfalse5 = matcher.find(); assertFalse("TesteFalse5: deveria ser false.", testfalse5); matcher = this.pattern.matcher("isSet{br.com.compre}[999]"); boolean testfalse6 = matcher.find(); assertFalse("TesteFalse6: deveria ser false.", testfalse6); matcher = this.pattern.matcher("isSet{br.com.compre}[9, 9]"); boolean testfalse7 = matcher.find(); assertFalse("TesteFalse7: deveria ser false.", testfalse7); matcher = this.pattern.matcher("isSet{br.com.compre} [9,9]"); boolean testfalse8 = matcher.find(); assertFalse("TesteFalse8: deveria ser false.", testfalse8); } @Test public void testPopularSet() throws Exception { logger.debug("String - GetPopularSet"); Factory.loadSetup("make.xml"); EntitySetTest test = MakeEntity.make(EntitySetTest.class, "testSet1"); logger.debug(test); assertNotNull("Test 1: test não pode ser nulo.", test); assertNotNull("Test 1: Set de test não pode ser nula.", test.getSetPattern()); assertTrue("Test 1: Set de test não pode ser menor que 3.", test.getSetPattern().size() >= 3); assertTrue("Test 1: Set de test não pode ser maior que 5.", test.getSetPattern().size() <= 5); for (EntityPatternTest entity : test.getSetPattern()) { this.validarJsr303(entity); } assertNotNull("Test 2: SetComplex de test não pode ser nula.", test.getSetComplex()); assertTrue("Test 2: SetComplex de test não pode ser menor que 15.", test.getSetComplex().size() >= 15); assertTrue("Test 2: SetComplex de test não pode ser maior que 25.", test.getSetComplex().size() <= 25); for (EntitySetComplexTest entity : test.getSetComplex()) { this.validarJsr303(entity); } } private void validarJsr303(Object test) { Set<ConstraintViolation<Object>> erros = this.validator.validate(test); for (ConstraintViolation<Object> erro : erros) { logger.error(erro.getMessage()); } assertTrue("Erros de validação encontrados", erros.isEmpty()); } }
37.534351
100
0.690665
ef3374b6b521a446dbd5c3e002270770b3ff41d5
8,511
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.base.CaseFormat.LOWER_CAMEL; import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION; import static com.google.errorprone.fixes.SuggestedFixes.addModifiers; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.annotationsAmong; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import static javax.lang.model.element.ElementKind.FIELD; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.STATIC; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.Immutable; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions; import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions.ConstantExpression; import com.google.errorprone.bugpatterns.threadsafety.ConstantExpressions.ConstantExpressionVisitor; import com.google.errorprone.bugpatterns.threadsafety.ThreadSafety; import com.google.errorprone.bugpatterns.threadsafety.WellKnownMutability; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.suppliers.Supplier; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.util.Name; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Pattern; import java.util.stream.Stream; import javax.lang.model.element.NestingKind; /** Finds fields which can be safely made static. */ @BugPattern( name = "FieldCanBeStatic", summary = "A final field initialized at compile-time with an instance of an immutable type can be" + " static.", severity = SUGGESTION) public final class FieldCanBeStatic extends BugChecker implements VariableTreeMatcher { private static final Supplier<ImmutableSet<Name>> EXEMPTING_VARIABLE_ANNOTATIONS = VisitorState.memoize( s -> Stream.of("com.google.inject.testing.fieldbinder.Bind") .map(s::getName) .collect(toImmutableSet())); private final WellKnownMutability wellKnownMutability; private final ConstantExpressions constantExpressions; public FieldCanBeStatic(ErrorProneFlags flags) { this.wellKnownMutability = WellKnownMutability.fromFlags(flags); this.constantExpressions = ConstantExpressions.fromFlags(flags); } @Override public Description matchVariable(VariableTree tree, VisitorState state) { VarSymbol symbol = getSymbol(tree); if (symbol == null || !symbol.isPrivate() || !tree.getModifiers().getFlags().contains(FINAL) || symbol.isStatic() || !symbol.getKind().equals(FIELD) || (symbol.flags() & RECORD_FLAG) == RECORD_FLAG) { return NO_MATCH; } ClassSymbol enclClass = symbol.owner.enclClass(); if (enclClass == null) { return NO_MATCH; } if (!enclClass.getNestingKind().equals(NestingKind.TOP_LEVEL) && !enclClass.isStatic() && symbol.getConstantValue() == null) { // JLS 8.1.3: inner classes cannot declare static members, unless the member is a constant // variable return NO_MATCH; } if (!isTypeKnownImmutable(getType(tree), state)) { return NO_MATCH; } if (tree.getInitializer() == null || !isPure(tree.getInitializer(), state)) { return NO_MATCH; } if (!annotationsAmong(symbol, EXEMPTING_VARIABLE_ANNOTATIONS.get(state), state).isEmpty()) { return NO_MATCH; } SuggestedFix fix = SuggestedFix.builder() .merge(renameVariable(tree, state)) .merge(addModifiers(tree, state, STATIC).orElse(SuggestedFix.emptyFix())) .build(); return describeMatch(tree, fix); } private static final long RECORD_FLAG = 1L << 61; /** * Renames the variable, clobbering any qualifying (like {@code this.}). This is a tad unsafe, but * we need to somehow remove any qualification with an instance. */ private SuggestedFix renameVariable(VariableTree variableTree, VisitorState state) { String name = variableTree.getName().toString(); if (!LOWER_CAMEL_PATTERN.matcher(name).matches()) { return SuggestedFix.emptyFix(); } String replacement = LOWER_CAMEL.to(UPPER_UNDERSCORE, variableTree.getName().toString()); int typeEndPos = state.getEndPosition(variableTree.getType()); int searchOffset = typeEndPos - ((JCTree) variableTree).getStartPosition(); int pos = ((JCTree) variableTree).getStartPosition() + state.getSourceForNode(variableTree).indexOf(name, searchOffset); SuggestedFix.Builder fix = SuggestedFix.builder().replace(pos, pos + name.length(), replacement); VarSymbol sym = getSymbol(variableTree); new TreeScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree tree, Void unused) { handle(tree); return super.visitIdentifier(tree, null); } @Override public Void visitMemberSelect(MemberSelectTree tree, Void unused) { handle(tree); return super.visitMemberSelect(tree, null); } private void handle(Tree tree) { if (sym.equals(getSymbol(tree))) { fix.replace(tree, replacement); } } }.scan(state.getPath().getCompilationUnit(), null); return fix.build(); } private static final Pattern LOWER_CAMEL_PATTERN = Pattern.compile("[a-z][a-zA-Z0-9]+"); /** * Tries to establish whether an expression is pure. For example, literals and invocations of * known-pure functions are pure. */ private boolean isPure(ExpressionTree initializer, VisitorState state) { return constantExpressions .constantExpression(initializer, state) .map(FieldCanBeStatic::isStatic) .orElse(false); } private static boolean isStatic(ConstantExpression expression) { AtomicBoolean staticable = new AtomicBoolean(true); expression.accept( new ConstantExpressionVisitor() { @Override public void visitIdentifier(Symbol identifier) { if (!(identifier instanceof ClassSymbol) && !identifier.isStatic()) { staticable.set(false); } } }); return staticable.get(); } private boolean isTypeKnownImmutable(Type type, VisitorState state) { ThreadSafety threadSafety = ThreadSafety.builder() .setPurpose(ThreadSafety.Purpose.FOR_IMMUTABLE_CHECKER) .knownTypes(wellKnownMutability) .acceptedAnnotations( ImmutableSet.of(Immutable.class.getName(), AutoValue.class.getName())) .markerAnnotations(ImmutableSet.of()) .build(state); return !threadSafety .isThreadSafeType( /* allowContainerTypeParameters= */ true, threadSafety.threadSafeTypeParametersInScope(type.tsym), type) .isPresent(); } }
39.957746
100
0.720949
d9bae7cf012492fb230c67a2e54da34fba0993ed
645
package com.skytala.eCommerce.domain.product.relations.product.event.promoCodeEmail; import java.util.List; import com.skytala.eCommerce.framework.pubsub.Event; import com.skytala.eCommerce.domain.product.relations.product.model.promoCodeEmail.ProductPromoCodeEmail; public class ProductPromoCodeEmailFound implements Event{ private List<ProductPromoCodeEmail> productPromoCodeEmails; public ProductPromoCodeEmailFound(List<ProductPromoCodeEmail> productPromoCodeEmails) { this.productPromoCodeEmails = productPromoCodeEmails; } public List<ProductPromoCodeEmail> getProductPromoCodeEmails() { return productPromoCodeEmails; } }
30.714286
105
0.849612
230bef8aec7192b8afd2b602bace8fb79b833ae5
964
package org.yamikaze.unit.test.mock.proxy; /** * @author qinluo * @version 1.0.0 * @date 2019-11-12 10:22 */ public class ProxyWrapper { private Class<?> mockType; private Object mockObject; public ProxyWrapper(Class<?> mockType, Object mockObject) { this.mockType = mockType; this.mockObject = mockObject; } public Class<?> getMockType() { return mockType; } public void setMockType(Class<?> mockType) { this.mockType = mockType; } public Object getMockObject() { return mockObject; } public void setMockObject(Object mockObject) { this.mockObject = mockObject; } @Override public int hashCode() { return mockType.hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof ProxyWrapper) { return mockType.equals(((ProxyWrapper) obj).mockType); } return false; } }
19.673469
66
0.609959
8ad52f4b9f3542c2210fb21797922c2a3416d659
145
public class SynonymGame { public static void main(String[] args) { Synonym synonym = new Synonym(); synonym.play(); } }
20.714286
44
0.6
9433f85011eb528b5485a454c0ae9ed5f9acc34f
39,769
/* * * This file is generated under this project, "DocVersionManager". * * Date : 2014. 11. 21. 오후 5:28:28 * * Author: Park_Jun_Hong_(fafanmama_at_naver_com) * */ package open.commons.tool.dvm.ui; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.codehaus.jettison.json.JSONException; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.StatusLineManager; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.jface.window.ApplicationWindow; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.DropTargetAdapter; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.wb.swt.SWTResourceManager; import open.commons.Result; import open.commons.tool.dvm.Metadata; import open.commons.tool.dvm.json.DocConfig; import open.commons.tool.dvm.json.DvmConfig; import open.commons.tool.dvm.json.ProjectConfig; import open.commons.tool.dvm.widget.DocConfigInputDlg; import open.commons.tool.dvm.widget.DocConfigView; import open.commons.tool.dvm.widget.ProjectConfigView; import open.commons.tool.dvm.widget.StringInputDlg; import open.commons.tool.dvm.widget.UpdateLogDigalog; import open.commons.utils.ArrayUtils; import open.commons.utils.FileUtils; import open.commons.utils.IOUtils; public class DocVersionManagerMainUI extends ApplicationWindow implements IDocConfigChangeListener, IProjectConfigChangeListener { private static UpdateLogDigalog logDlg; private Tree treeProjectNavigator; private TreeViewer treeViewer; private Group grpConfigFile; private Combo cbxConfigFile; private Composite cpProjectNavigation; private Composite cpNaviMenus; private ToolBar tbTree; private ToolBar tbConfig; private ToolItem tltmNewProject; private ToolItem tltmNewDoc; private ToolBar tbConfigFile; private ToolItem tltmOpenConfigFile; private ToolItem tltmLoadConfigFile; private Shell mainShell; private ToolItem tltmSeparator; private ToolItem tltmSaveFile; private String resourceFile; private SashForm sashForm; private ScrolledComposite scDetailedView; private Label lblLogo; private DvmConfig dvmConfig = new DvmConfig(); /** * {@link DocConfig} or {@link ProjectConfig} */ private Object currentDetailedItem; /** * Create the application window. */ public DocVersionManagerMainUI() { super(null); createActions(); addToolBar(SWT.FLAT | SWT.WRAP); addMenuBar(); addStatusLine(); init(); logDlg = new UpdateLogDigalog(new Shell(Display.getCurrent())); logDlg.ready(); } private void addConfigFileList(String filepath) { if (!new File(filepath).exists()) { return; } String curfile = cbxConfigFile.getText(); String[] files = cbxConfigFile.getItems(); if (!ArrayUtils.contains(files, filepath)) { files = ArrayUtils.prepend(files, filepath); } cbxConfigFile.setItems(files); cbxConfigFile.setText(curfile); } private void addProjectConfig(ProjectConfig config) { this.dvmConfig.addProjectConfig(config); } @Override public void change(ProjectConfig newValue, ProjectConfig oldValue) { try { if (oldValue != null) { this.dvmConfig.removeProjectConfig(oldValue.getProject()); } if (newValue != null) { this.dvmConfig.addProjectConfig(newValue); updateCurrentDetailedView(newValue.getProject(), newValue); } } catch (Exception e) { } } @Override public void change(String project, DocConfig newValue, DocConfig oldValue) { this.dvmConfig.addApplication(newValue.getExeCmd(), newValue.getFileExt().split("[|]")); updateCurrentDetailedView(project, newValue); } private void clearDetailedView() { Control latestDocConfig = scDetailedView.getContent(); if (latestDocConfig != null) { latestDocConfig.dispose(); } } private void clearProjectConfig() { this.dvmConfig.clearProjectConfigs(); } /** * Configure the shell. * * @param newShell */ @Override protected void configureShell(Shell newShell) { newShell.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { if (logDlg != null) { Shell shell = logDlg.getShell(); if (shell != null) { shell.dispose(); } } } }); newShell.setImage(SWTResourceManager.getImage(DocVersionManagerMainUI.class, "/images/osa_user_blue_tester.png")); super.configureShell(newShell); newShell.setText(Metadata.product() + " " + Metadata.version() + " - " + Metadata.update() + " (" + Metadata.author() + " | " + Metadata.email() + ")"); this.mainShell = newShell; } /** * Create the actions. */ private void createActions() { } /** * Create contents of the application window. * * @param parent */ @Override protected Control createContents(Composite parent) { Composite container = new Composite(parent, SWT.NONE); container.setLayout(new GridLayout(1, false)); this.grpConfigFile = new Group(container, SWT.NONE); this.grpConfigFile.setLayout(new GridLayout(4, false)); this.grpConfigFile.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblNewLabel = new Label(this.grpConfigFile, SWT.NONE); lblNewLabel.setText("Config File: "); lblNewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); this.cbxConfigFile = new Combo(this.grpConfigFile, SWT.BORDER);// | SWT.WRAP | SWT.MULTI); this.cbxConfigFile.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { File file = new File(cbxConfigFile.getText()); if (tltmLoadConfigFile != null && !tltmLoadConfigFile.isDisposed()) { tltmLoadConfigFile.setEnabled(file.exists()); } } }); int dropTargetOperations = DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_DEFAULT; DropTarget dropTarget = new DropTarget(this.cbxConfigFile, dropTargetOperations); final TextTransfer textTransfer = TextTransfer.getInstance(); final FileTransfer fileTransfer = FileTransfer.getInstance(); dropTarget.setTransfer(new Transfer[] { textTransfer, fileTransfer }); dropTarget.addDropListener(new DropTargetAdapter() { @Override public void drop(DropTargetEvent event) { if (!fileTransfer.isSupportedType(event.currentDataType) // || event.data == null) { return; } String filepath = null; filepath = event.data.getClass().isArray() ? ((Object[]) event.data)[0].toString() : event.data.toString(); if (new File(filepath).isFile()) { cbxConfigFile.setText(filepath); addConfigFileList(filepath); } else { MessageDialog.openWarning(mainShell, "설정 파일 선택", "파일만 선택할 수 있습니다."); } } }); this.cbxConfigFile.setFont(SWTResourceManager.getFont("Courier New", 10, SWT.ITALIC)); this.cbxConfigFile.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1)); this.tbConfigFile = new ToolBar(this.grpConfigFile, SWT.FLAT | SWT.RIGHT); this.tltmOpenConfigFile = new ToolItem(this.tbConfigFile, SWT.NONE); this.tltmOpenConfigFile.setImage(SWTResourceManager.getImage(DocVersionManagerMainUI.class, "/images/directory_24x24.png")); this.tltmOpenConfigFile.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { FileDialog dlg = new FileDialog(getShell(), SWT.NONE); String filepath = dlg.open(); if (filepath == null) { return; } cbxConfigFile.setText(filepath); addConfigFileList(filepath); } }); this.tltmLoadConfigFile = new ToolItem(this.tbConfigFile, SWT.NONE); this.tltmLoadConfigFile.setEnabled(new File(cbxConfigFile.getText()).isFile()); this.tltmLoadConfigFile.setImage(SWTResourceManager.getImage(DocVersionManagerMainUI.class, "/images/project_configs.png")); this.tltmLoadConfigFile.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { try { File resourceFile = new File(cbxConfigFile.getText().trim()); if (!resourceFile.exists()) { MessageDialog.openInformation(mainShell, "No File", "선택된 파일이 없습니다."); return; } byte[] bytes = IOUtils.readFully(new FileInputStream(resourceFile)); String jsonStr = new String(bytes, "UTF-8"); clearProjectConfig(); dvmConfig = new DvmConfig(); dvmConfig.mature(jsonStr); setProjectConfig(treeViewer); updateResourceFile(resourceFile.getAbsolutePath()); createDetailedLogo(); } catch (Exception ex) { MessageDialog.openWarning(mainShell, "데이터 선택 오류", "선택한 파일에 포함된 데이터가 JSON 형식이 아니거나 다른 이유로 로딩 중 오류가 발생했습니다."); updateResourceFile(null); ex.printStackTrace(); } } }); new Label(this.grpConfigFile, SWT.NONE); sashForm = new SashForm(container, SWT.SMOOTH); sashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); createProjectNavigation(sashForm); this.scDetailedView = new ScrolledComposite(this.sashForm, SWT.H_SCROLL | SWT.V_SCROLL); this.scDetailedView.setExpandHorizontal(true); this.scDetailedView.setExpandVertical(true); this.sashForm.setWeights(new int[] { 298, 1029 }); createDetailedLogo(); return container; } private void createDetailedLogo() { this.lblLogo = new Label(this.scDetailedView, SWT.CENTER); this.lblLogo.setImage(SWTResourceManager.getImage(DocVersionManagerMainUI.class, "/images/ic_action_dock.png")); this.scDetailedView.setContent(this.lblLogo); this.scDetailedView.setMinSize(this.lblLogo.computeSize(SWT.DEFAULT, SWT.DEFAULT)); } /** * Create the menu manager. * * @return the menu manager */ @Override protected MenuManager createMenuManager() { MenuManager menuManager = new MenuManager("menu"); return menuManager; } private void createNewDocConfig(String projectName) { DocConfigInputDlg dlg = new DocConfigInputDlg(mainShell, projectName, this.dvmConfig.getProjectNames(), this.dvmConfig.getApps()); if (dlg.open() != Dialog.OK) { return; } String project = dlg.getProject(); if (project.isEmpty()) { MessageDialog.openInformation(mainShell, "데이타 누락", "프로젝트 이름을 꼭~ 입력하시기 바랍니다."); } DocConfig docConfig = dlg.getDocConfig(); ProjectConfig projectConfig = this.dvmConfig.getProjectConfig(project); if (projectConfig == null) { projectConfig = new ProjectConfig(); projectConfig.setProject(project); this.dvmConfig.addProjectConfig(projectConfig); } if (!projectConfig.contains(docConfig.getDocKind())) { this.dvmConfig.addDocConfig(project, docConfig); } treeViewer.refresh(); // detailed view 정보 갱신 if (currentDetailedItem != null && ProjectConfig.class.isAssignableFrom(currentDetailedItem.getClass())) { String currentProject = ((ProjectConfig) currentDetailedItem).getProject(); if (project.equals(currentProject)) { setDetailedView(projectConfig); } } } private void createProjectNavigation(SashForm sashForm) { this.cpProjectNavigation = new Composite(sashForm, SWT.NONE); GridLayout gl_cpProjectNavigation = new GridLayout(1, false); gl_cpProjectNavigation.marginWidth = 0; gl_cpProjectNavigation.marginHeight = 0; this.cpProjectNavigation.setLayout(gl_cpProjectNavigation); this.cpNaviMenus = new Composite(this.cpProjectNavigation, SWT.BORDER); GridLayout gl_cpNaviMenus = new GridLayout(2, false); gl_cpNaviMenus.marginWidth = 0; gl_cpNaviMenus.marginHeight = 0; gl_cpNaviMenus.verticalSpacing = 0; this.cpNaviMenus.setLayout(gl_cpNaviMenus); this.cpNaviMenus.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1)); this.tbTree = new ToolBar(this.cpNaviMenus, SWT.RIGHT); this.tbTree.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); ToolItem tltmExpandAll = new ToolItem(this.tbTree, SWT.NONE); tltmExpandAll.setToolTipText("Expand All."); tltmExpandAll.setImage(SWTResourceManager.getImage(DocVersionManagerMainUI.class, "/images/expandall.gif")); tltmExpandAll.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { super.widgetSelected(e); Event event = new Event(); event.display = getShell().getDisplay(); event.doit = true; event.widget = treeProjectNavigator; for (TreeItem item : treeProjectNavigator.getItems()) { event.item = item; treeProjectNavigator.notifyListeners(SWT.Expand, event); item.setExpanded(true); } } }); ToolItem tltmCollapseAll = new ToolItem(this.tbTree, SWT.NONE); tltmCollapseAll.setToolTipText("Collapse All."); tltmCollapseAll.setImage(SWTResourceManager.getImage(DocVersionManagerMainUI.class, "/images/collapseall.gif")); tltmCollapseAll.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (TreeItem item : treeProjectNavigator.getItems()) { item.setExpanded(false); } } }); this.tbConfig = new ToolBar(this.cpNaviMenus, SWT.FLAT | SWT.RIGHT); new ToolItem(this.tbConfig, SWT.SEPARATOR); ToolItem tltmNewDvm = new ToolItem(this.tbConfig, SWT.NONE); tltmNewDvm.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { StringInputDlg dlg = new StringInputDlg(getShell(), ""); dlg.setDlgTitle("프로젝트 이름"); dlg.setDlgMessage("프로젝트 이름을 입력하세요."); if (dlg.open() != Dialog.OK) { return; } String newPrjName = dlg.getString(); if (newPrjName.isEmpty()) { MessageDialog.openWarning(getShell(), "데이터 누락", "프로젝트 이름이 누락 되었습니다."); return; } clearProjectConfig(); ProjectConfig newProject = new ProjectConfig(); newProject.setProject(newPrjName); addProjectConfig(newProject); createDetailedLogo(); treeViewer.refresh(); } }); tltmNewDvm.setToolTipText("Create a new DVM"); tltmNewDvm.setImage(SWTResourceManager.getImage(DocVersionManagerMainUI.class, "/images/ic_action_copy.png")); new ToolItem(this.tbConfig, SWT.SEPARATOR); this.tltmNewProject = new ToolItem(this.tbConfig, SWT.NONE); this.tltmNewProject.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { StringInputDlg dlg = new StringInputDlg(getShell(), ""); dlg.setDlgTitle("프로젝트 이름"); dlg.setDlgMessage("프로젝트 이름을 입력하세요."); if (dlg.open() != Dialog.OK) { return; } String newPrjName = dlg.getString(); if (newPrjName.isEmpty() || !dvmConfig.isNewProject(newPrjName)) { MessageDialog.openWarning(getShell(), "데이터 중복", "동일한 이름의 프로젝트가 존재합니다."); return; } ProjectConfig newProject = new ProjectConfig(); newProject.setProject(newPrjName); addProjectConfig(newProject); treeViewer.refresh(); } }); this.tltmNewProject.setToolTipText("Add a new Project Config."); this.tltmNewProject.setImage(SWTResourceManager.getImage(DocVersionManagerMainUI.class, "/images/add_project.png")); this.tltmNewDoc = new ToolItem(this.tbConfig, SWT.NONE); this.tltmNewDoc.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { createNewDocConfig(null); } }); this.tltmNewDoc.setImage(SWTResourceManager.getImage(DocVersionManagerMainUI.class, "/images/osa_server_file_24x24.png")); this.tltmNewDoc.setToolTipText("Add a new Doc Config."); this.tltmSeparator = new ToolItem(this.tbConfig, SWT.SEPARATOR); this.tltmSeparator.setText("New Item"); this.tltmSaveFile = new ToolItem(this.tbConfig, SWT.NONE); this.tltmSaveFile.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (!dvmConfig.hasProject()) { MessageDialog.openInformation(mainShell, "No Projects", "저장할 프로젝트 정보가 없습니다."); return; } try { // Map<String, ProjectConfig> configs = (Map<String, ProjectConfig>) treeViewer.getInput(); // Result<File> result = saveProject(JSONArrayFactory.toJSONArray(configs.values(), // ProjectConfig.class).toString(2), resourceFile); Result<File> result = saveProject(dvmConfig.toJSONString(2), resourceFile); if (result.getResult()) { resourceFile = result.getData().getAbsolutePath(); cbxConfigFile.setText(resourceFile); addConfigFileList(resourceFile); MessageDialog.openInformation(mainShell, "작업 완료", "성공적으로 파일을 저장하였습니다."); } else { if (result.getMessage() != null) { MessageDialog.openInformation(mainShell, "파일 저장 실패", result.getMessage()); } } } catch (JSONException e1) { MessageDialog.openInformation(mainShell, "작업 완료", "성공적으로 파일을 저장하였습니다."); } } }); this.tltmSaveFile.setImage(SWTResourceManager.getImage(DocVersionManagerMainUI.class, "/images/ic_action_save.png")); this.tltmSaveFile.setToolTipText("Save Configurations."); treeViewer = new TreeViewer(this.cpProjectNavigation, SWT.BORDER); this.treeViewer.setComparator(new Sorter()); this.treeProjectNavigator = treeViewer.getTree(); this.treeProjectNavigator.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); this.treeProjectNavigator.addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent e) { TreeItem item = treeProjectNavigator.getItem(new Point(e.x, e.y)); if (item == null) { return; } Object data = item.getData(); if (data == null) { return; } Class<?> dataClass = data.getClass(); if (ProjectConfig.class.isAssignableFrom(dataClass)) { Event event = new Event(); event.item = item; event.display = getShell().getDisplay(); event.doit = true; event.widget = treeProjectNavigator; treeProjectNavigator.notifyListeners(SWT.Expand, event); item.setExpanded(!item.getExpanded()); } else if (DocConfig.class.isAssignableFrom(dataClass)) { } } @Override public void mouseDown(MouseEvent e) { Object obj = e.getSource(); if (obj == null || !Tree.class.isAssignableFrom(obj.getClass())) { return; } Tree tree = (Tree) obj; final TreeItem item = tree.getItem(new Point(e.x, e.y)); if (item == null) { return; } final Object data = item.getData(); if (data == null) { return; } switch (e.button) { case 1: // Left Button if (ProjectConfig.class.isAssignableFrom(data.getClass())) { clearDetailedView(); setDetailedView((ProjectConfig) data); } else if (DocConfig.class.isAssignableFrom(data.getClass())) { clearDetailedView(); setDetailedView(((ProjectConfig) item.getParentItem().getData()).getProject(), (DocConfig) data); } scDetailedView.setMinSize(400, 300); break; case 3: // Right button final Menu popmenu = new Menu((Control) e.getSource()); MenuItem deleteItem = new MenuItem(popmenu, SWT.NONE); deleteItem.setText("&Delete"); deleteItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (MessageDialog.openConfirm(mainShell, "설정 삭제", "선택하신 설정을 삭제하시겠습니까?")) { if (ProjectConfig.class.isAssignableFrom(data.getClass())) { deleteConfig(((ProjectConfig) data).getProject(), null); } else if (DocConfig.class.isAssignableFrom(data.getClass())) { deleteConfig(((ProjectConfig) item.getParentItem().getData()).getProject(), ((DocConfig) data).getDocKind()); } if (itsMe(data)) { clearDetailedView(); createDetailedLogo(); } } popmenu.dispose(); } }); MenuItem newDocConfigItem = new MenuItem(popmenu, SWT.NONE); newDocConfigItem.setText("&New Doc Config"); newDocConfigItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // (start) [BUG-FIX]: 신규 문서 추가시 현재 프로젝트 이름 설정 / Park_Jun_Hong_(fafanmama_at_naver_com): // 2019. 12. 15. 오후 6:43:18 String project = null; if (ProjectConfig.class.isAssignableFrom(data.getClass())) { project = ((ProjectConfig) data).getProject(); } else if (DocConfig.class.isAssignableFrom(data.getClass())) { project = ((ProjectConfig) item.getParentItem().getData()).getProject(); } // (end): 2019. 12. 15. 오후 6:43:18 createNewDocConfig(project); popmenu.dispose(); } }); if (ProjectConfig.class.isAssignableFrom(data.getClass())) { MenuItem saveProjectStandalone = new MenuItem(popmenu, SWT.NONE); saveProjectStandalone.setText("&Save Project"); saveProjectStandalone.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { List<ProjectConfig> config = new ArrayList<>(); config.add((ProjectConfig) data); try { // Result<File> result = saveProject(JSONArrayFactory.toJSONArray(config, // ProjectConfig.class).toString(2), null); Result<File> result = saveProject(dvmConfig.toJSONString(2), null); if (result.getResult()) { // (start) [BUG-FIX]: 파일 저장 취소에 따른 메시지 추가 / // Park_Jun_Hong_(fafanmama_at_naver_com): 2019. 12. 15. 오후 6:47:01 if (result.getData() != null) { MessageDialog.openInformation(mainShell, "작업 완료", "성공적으로 파일을 저장하였습니다."); } else { MessageDialog.openInformation(mainShell, "작업 완료", "파일을 저장하지 않았습니다."); } // (end): 2019. 12. 15. 오후 6:47:01 } else { MessageDialog.openInformation(mainShell, "파일 저장 실패", result.getMessage()); } } catch (JSONException e1) { e1.printStackTrace(); } popmenu.dispose(); } }); } popmenu.setVisible(true); break; } } }); this.treeViewer.setContentProvider(new TreeContentProvider()); this.treeViewer.setLabelProvider(new ViewerLabelProvider()); this.treeViewer.setInput(this.dvmConfig.getProjectConfigs()); } /** * Create the status line manager. * * @return the status line manager */ @Override protected StatusLineManager createStatusLineManager() { StatusLineManager statusLineManager = new StatusLineManager(); return statusLineManager; } /** * Create the toolbar manager. * * @return the toolbar manager */ @Override protected ToolBarManager createToolBarManager(int style) { ToolBarManager toolBarManager = new ToolBarManager(style); return toolBarManager; } private void deleteConfig(String project, String docKind) { if (project != null && docKind != null) { ProjectConfig projectConfig = this.dvmConfig.getProjectConfig(project); if (projectConfig == null) { return; } projectConfig.removeDocConfig(docKind); } else if (project != null) { this.dvmConfig.removeProjectConfig(project); } treeViewer.refresh(); } /** * Return the initial size of the window. */ @Override protected Point getInitialSize() { return new Point(1356, 918); } private void init() { // create file } private boolean itsMe(Object item) { if (currentDetailedItem != null) { return currentDetailedItem.equals(item); } return false; } /** * * @param data * 저장할 데이터 문자열. JSON 포맷 * @param latestFilename * 기본 파일명 * * @since 2014. 12. 2. */ private Result<File> saveProject(String data, String latestFilename) { Result<File> result = new Result<>(); File file = null; FileDialog dlg = new FileDialog(mainShell, SWT.SAVE); dlg.setFilterExtensions(new String[] { "*.dvm" }); if (latestFilename != null) { dlg.setFileName(FileUtils.getFileName(latestFilename)); } String filepath = dlg.open(); if (filepath == null) { // (start) [BUG-FIX]: 파일 저장 취소에 따른 메시지 추가 / Park_Jun_Hong_(fafanmama_at_naver_com): 2019. 12. 15. 오후 6:47:13 result.andTrue().setMessage("파일을 저장하지 않았습니다."); // (end): 2019. 12. 15. 오후 6:47:13 return result; } file = new File(filepath); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e1) { result.setMessage("파일 생성시 에러가 발생하였습니다"); return result; } } else { try { IOUtils.transfer(new FileInputStream(file), new FileOutputStream(new File(file.getAbsolutePath() + ".bak")), "UTF-8"); } catch (Exception ignored) { ignored.printStackTrace(); } } BufferedWriter writer = null; BufferedReader reader = null; try { reader = new BufferedReader(new StringReader(data)); String readline = null; writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF-8")); while ((readline = reader.readLine()) != null) { writer.write(readline); writer.newLine(); } writer.flush(); result.andTrue().setData(file); } catch (Exception e1) { result.setMessage(e1.getLocalizedMessage()); } finally { IOUtils.close(reader, writer); } return result; } private void setDetailedView(ProjectConfig projectConfig) { ProjectConfigView projectConfigView = new ProjectConfigView(scDetailedView, SWT.NONE); projectConfigView.setProjectConfig(projectConfig); projectConfigView.addProjectConfigChangeListener(DocVersionManagerMainUI.this); scDetailedView.setContent(projectConfigView); updateCurrentDetailedItem(projectConfig); } private void setDetailedView(String project, DocConfig docConfig) { DocConfigView docConfigView = new DocConfigView(scDetailedView, SWT.NONE, this.dvmConfig.getApps()); docConfigView.setConfig(project, docConfig); docConfigView.addDocConfigChangeListener(DocVersionManagerMainUI.this); scDetailedView.setContent(docConfigView); updateCurrentDetailedItem(docConfig); } private void setProjectConfig(TreeViewer viewer) { viewer.setInput(this.dvmConfig.getProjectConfigs()); } private void updateCurrentDetailedItem(Object item) { this.currentDetailedItem = item; } private void updateCurrentDetailedView(String project, Object data) { if (data == null) { } else if (ProjectConfig.class.isAssignableFrom(data.getClass())) { clearDetailedView(); ProjectConfigView projectConfigView = new ProjectConfigView(scDetailedView, SWT.NONE); projectConfigView.setProjectConfig((ProjectConfig) data); projectConfigView.addProjectConfigChangeListener(DocVersionManagerMainUI.this); scDetailedView.setContent(projectConfigView); updateCurrentDetailedItem(data); } else if (DocConfig.class.isAssignableFrom(data.getClass())) { clearDetailedView(); DocConfigView docConfigView = new DocConfigView(scDetailedView, SWT.NONE, this.dvmConfig.getApps()); docConfigView.setConfig(project, (DocConfig) data); docConfigView.addDocConfigChangeListener(DocVersionManagerMainUI.this); scDetailedView.setContent(docConfigView); updateCurrentDetailedItem(data); } treeViewer.refresh(); } private void updateResourceFile(String filename) { this.resourceFile = filename; } public static UpdateLogDigalog getLogView() { return logDlg; } /** * Launch the application. * * @param args */ public static void main(String args[]) { try { DocVersionManagerMainUI window = new DocVersionManagerMainUI(); window.setBlockOnOpen(true); window.open(); Display.getCurrent().dispose(); } catch (Exception e) { e.printStackTrace(); } } // private static class Sorter extends ViewerSorter { private static class Sorter extends ViewerComparator { public int compare(Viewer viewer, Object e1, Object e2) { if (ProjectConfig.class.isAssignableFrom(e1.getClass()) // && ProjectConfig.class.isAssignableFrom(e2.getClass())) { String project1 = ((ProjectConfig) e1).getProject(); String project2 = ((ProjectConfig) e2).getProject(); int orderP1 = project1.charAt(0); int orderP2 = project2.charAt(0); int c = orderP1 - orderP2; if (c != 0) { return c; } String yearP1 = null; String yearP2 = null; switch (orderP1) { case '0': return project1.compareTo(project2); case '[': project1 = project1.substring(9); project2 = project2.substring(9); default: // 년도별로는 내림차순 yearP1 = project1.substring(0, 4); yearP2 = project2.substring(0, 4); c = yearP1.compareTo(yearP2); if (c != 0) { return project2.compareTo(project1); } else { return project1.compareTo(project2); } } } else { return 0; } } } private static class TreeContentProvider implements ITreeContentProvider { public void dispose() { } @SuppressWarnings("unchecked") public Object[] getChildren(Object parentElement) { Class<?> parentClass = parentElement.getClass(); if (Map.class.isAssignableFrom(parentClass)) { return ((Map<String, ProjectConfig>) parentElement).values().toArray(); } else if (ProjectConfig.class.isAssignableFrom(parentClass)) { return ((ProjectConfig) parentElement).getDocConfigs().toArray(); } else { return new Object[0]; } } public Object[] getElements(Object inputElement) { return getChildren(inputElement); } public Object getParent(Object element) { return null; } public boolean hasChildren(Object element) { return getChildren(element).length > 0; } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } } private static class ViewerLabelProvider extends LabelProvider { public Image getImage(Object element) { Class<?> elemClass = element.getClass(); if (ProjectConfig.class.isAssignableFrom(elemClass)) { return SWTResourceManager.getImage(DocVersionManagerMainUI.class, "/images/project.png"); } else if (DocConfig.class.isAssignableFrom(elemClass)) { return SWTResourceManager.getImage(DocVersionManagerMainUI.class, "/images/doc.png"); } else { return null; } } public String getText(Object element) { Class<?> elemClass = element.getClass(); if (ProjectConfig.class.isAssignableFrom(elemClass)) { return ((ProjectConfig) element).getProject(); } else if (DocConfig.class.isAssignableFrom(elemClass)) { return ((DocConfig) element).getDocKind(); } else { return null; } } } }
37.27179
160
0.576504
5fc2b0a11b6896f66ca923c4f04744d20ce49215
6,864
package br.com.orange.mercadolivre.Usuario; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.util.Assert; import org.springframework.web.util.NestedServletException; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @SpringBootTest @AutoConfigureMockMvc public class UsuarioTest { @Autowired private MockMvc mockMvc; @PersistenceContext private EntityManager manager; @Autowired private UsuarioRepository repository; @Transactional private void populaBanco(){ Usuario usuario = new Usuario("[email protected]","123456"); manager.persist(usuario); } String usuarioRequest = "{\n" + " \"email\" : \"[email protected]\",\n" + " \"senha\" : \"123456\"\n" + "}"; @Test @WithMockUser @DisplayName("Deveria lidar com o sucesso no cadastro de usuário") public void criaUsuarioTeste() throws Exception{ /* * Nesse desafio seguiremos a risca todas as especificações * retornaremos apenas o status code 200 e não mais um objeto! */ mockMvc.perform(MockMvcRequestBuilders.post("/mercadolivre/usuarios") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(this.usuarioRequest) ).andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()); } @Test @WithMockUser @DisplayName("Deveria lidar com o email duplicado no banco de dados") @Transactional public void emailDuplicadoTeste() throws Exception{ String request = "{\n" + " \"email\" : \"[email protected]\",\n" + " \"senha\" : \"123456\"\n" + "}"; mockMvc.perform(MockMvcRequestBuilders.post("/mercadolivre/usuarios") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(request) ).andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()); mockMvc.perform(MockMvcRequestBuilders.post("/mercadolivre/usuarios") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(request) ).andExpect(MockMvcResultMatchers.status().isBadRequest()) .andDo(MockMvcResultHandlers.print()); } @Test @WithMockUser public void emailVazioTeste() throws Exception{ String usuarioNullouVazio = "{\n" + " \"email\" : \"\",\n" + " \"senha\" : \"123456\"\n" + "}"; mockMvc.perform(MockMvcRequestBuilders.post("/mercadolivre/usuarios") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(usuarioNullouVazio) ).andExpect(MockMvcResultMatchers.status().isBadRequest()) .andExpect(jsonPath("$[0].field").isString()) .andExpect(jsonPath("$[0].status").isNumber()) .andExpect(jsonPath("$[0].error").value("O campo email não pode estar vazio")) .andDo(MockMvcResultHandlers.print()); } @Test @WithMockUser @DisplayName("Deveria lidar com login (email) com formato inválido") public void emailFormatoInvalidoTeste() throws Exception{ String emailMalFormatado = "{\n" + " \"email\" : \"qualquer.comemail\",\n" + " \"senha\" : \"123456\"\n" + "}"; mockMvc.perform(MockMvcRequestBuilders.post("/mercadolivre/usuarios") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(emailMalFormatado) ).andExpect(MockMvcResultMatchers.status().isBadRequest()) .andExpect(jsonPath("$[0].field").isString()) .andExpect(jsonPath("$[0].status").isNumber()) .andExpect(jsonPath("$[0].error").value("O campo email deve ter um formato válido")) .andDo(MockMvcResultHandlers.print()); } @Test @WithMockUser @DisplayName("Deveria lidar com a senha branca ou nula") public void senhaBrancaOuNulaTeste() throws Exception{ String senhaBrancaOuNula = "{\n" + " \"email\" : \"[email protected]\",\n" + " \"senha\" : \"\"\n" + "}"; mockMvc.perform(MockMvcRequestBuilders.post("/mercadolivre/usuarios") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(senhaBrancaOuNula) ).andExpect(MockMvcResultMatchers.status().isBadRequest()) .andExpect(jsonPath("$[0].field").isString()) .andExpect(jsonPath("$[0].status").isNumber()) .andDo(MockMvcResultHandlers.print()); } @Test @DisplayName("Deveria lidar com uma senha com o tamanho menor que 6 caracteres") @WithMockUser public void senhaSemTamanhoMinimo() throws Exception{ String senhaMenor = "{\n" + " \"email\" : \"[email protected]\",\n" + " \"senha\" : \"12345\"\n" + "}"; mockMvc.perform(MockMvcRequestBuilders.post("/mercadolivre/usuarios") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(senhaMenor) ).andExpect(MockMvcResultMatchers.status().isBadRequest()) .andExpect(jsonPath("$[0].field").isString()) .andExpect(jsonPath("$[0].status").isNumber()) .andExpect(jsonPath("$[0].error").value("O campo senha deve ter no mínimo 6 caracteres")) .andDo(MockMvcResultHandlers.print()); } }
38.133333
105
0.618444
53e36c18c2092eeb2d22f987d43383d18d2639d9
1,266
package utils.dto; import utils.entity.Error; import utils.entity.Errors; import java.util.ArrayList; import java.util.List; /** * Created by Pavel Dudin * on 04.10.2017 * [email protected] */ public class ErrorsDto { private List<ErrorDto> errors; public ErrorsDto() { errors = new ArrayList<>(); } public List<ErrorDto> getErrors() { return errors; } public ErrorsDto addError(ErrorDto error) { this.errors.add(error); return this; } public static ErrorsDto create(String message) { ErrorsDto errors = new ErrorsDto(); errors.addError(new ErrorDto("_error", message)); return errors; } public static ErrorsDto instanceOf(Errors e) { ErrorsDto errors = new ErrorsDto(); for (Error error : e.getErrors()) { errors.addError(ErrorDto.instanceOf(error)); } return errors; } public static ErrorsDto instanceOf(Throwable th) { ErrorsDto errors = new ErrorsDto(); errors.addError(new ErrorDto("_error", th.getMessage())); return errors; } @Override public String toString() { return "ErrorsDto{" + "errors=" + errors + '}'; } }
21.827586
65
0.600316
1fb839f4d3801493e3800d0b17646866f5f7aba2
2,416
package ca.on.oicr.gsi.shesmu.compiler; import static ca.on.oicr.gsi.shesmu.compiler.TypeUtils.TO_ASM; import ca.on.oicr.gsi.shesmu.plugin.types.Imyhat; import java.util.Iterator; import java.util.Set; import java.util.function.Consumer; import org.objectweb.asm.Type; import org.objectweb.asm.commons.GeneratorAdapter; import org.objectweb.asm.commons.Method; public final class LetArgumentNodeUnivalued extends LetArgumentNodeBaseExpression { private static final Type A_ITERATOR_TYPE = Type.getType(Iterator.class); private static final Type A_OBJECT_TYPE = Type.getType(Object.class); private static final Type A_SET_TYPE = Type.getType(Set.class); private static final Method METHOD_ITERATOR__NEXT = new Method("next", A_OBJECT_TYPE, new Type[] {}); private static final Method METHOD_SET__ITERATOR = new Method("iterator", A_ITERATOR_TYPE, new Type[] {}); private static final Method METHOD_SET__SIZE = new Method("size", Type.INT_TYPE, new Type[] {}); public LetArgumentNodeUnivalued(DestructuredArgumentNode name, ExpressionNode expression) { super(name, expression); } @Override public boolean filters() { return true; } @Override public Consumer<Renderer> render(LetBuilder let, Imyhat type, Consumer<Renderer> loadLocal) { let.checkAndSkip( (r, happyPath) -> { loadLocal.accept(r); r.methodGen().invokeInterface(A_SET_TYPE, METHOD_SET__SIZE); r.methodGen().push(1); r.methodGen().ifICmp(GeneratorAdapter.EQ, happyPath); }); return r -> { loadLocal.accept(r); r.methodGen().invokeInterface(A_SET_TYPE, METHOD_SET__ITERATOR); r.methodGen().invokeInterface(A_ITERATOR_TYPE, METHOD_ITERATOR__NEXT); r.methodGen().unbox(((Imyhat.ListImyhat) type).inner().apply(TO_ASM)); }; } @Override public boolean typeCheck( int line, int column, Imyhat type, DestructuredArgumentNode name, Consumer<String> errorHandler) { if (type == Imyhat.EMPTY) { errorHandler.accept(String.format("%d:%d: Row will always be dropped.", line, column)); return false; } if (type instanceof Imyhat.ListImyhat) { return name.typeCheck(((Imyhat.ListImyhat) type).inner(), errorHandler); } errorHandler.accept( String.format("%d:%d: Expected list but got %s.", line, column, type.name())); return false; } }
35.529412
98
0.70654
e30c177864d771c37a0b0e231bc87bad0b852770
1,433
package com.intellij.tasks.actions; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.ui.Messages; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.net.MalformedURLException; import java.net.URL; /** * @author Mikhail Golubev */ public class DeadlockWithCertificateDialogAction extends AnAction { public static final String SELF_SIGNED_SERVER_URL = "https://self-signed.certificates-tests.labs.intellij.net"; @Override public void actionPerformed(@NotNull final AnActionEvent e) { ApplicationManager.getApplication().invokeLater(() -> { URL location = null; try { location = new URL(SELF_SIGNED_SERVER_URL); } catch (MalformedURLException ignored) { } // EDT will not be released for dialog until message dialog is shown. Meanwhile downloading of image by // ImageFetcher thread, started by MediaTracker, won't stop until certificate is accepted by user. Messages.showMessageDialog(e.getProject(), "This dialog may not be shown due to deadlock caused by MediaTracker and CertificateManager. " + "Fortunately it didn't happen." , "Deadlocking Dialog", new ImageIcon(location)); }); } }
39.805556
129
0.704815
82a5162eb3e14b48bf15a7f83c522c6c78603e09
2,384
package net.commotionwireless.olsrinfo.datatypes; import java.util.Collection; /** * A network interface from the list of interfaces that <tt>olsrd</tt> is aware * of at runtime. * * Written as part of the Commotion Wireless project * * @author Hans-Christoph Steiner <[email protected]> * @see <a * href="https://code.commotionwireless.net/projects/commotion/wiki/OLSR_Configuration_and_Management">OLSR * Configuration and Management</a> */ public class Interface { public String name; public String nameFromKernel; public int interfaceMode; public boolean emulatedHostClientInterface; public boolean sendTcImmediately; public int fishEyeTtlIndex; public int olsrForwardingTimeout; public int olsrMessageSequenceNumber; public Collection<LinkQualityMultiplier> linkQualityMultipliers; public int olsrInterfaceMetric; public int helloEmissionInterval; public int helloValidityTime; public int tcValidityTime; public int midValidityTime; public int hnaValidityTime; public String state; public int olsrMTU; public boolean wireless; public String ipv4Address; public String netmask; public String broadcast; public String ipv6Address; public String multicast; public boolean icmpRedirect; public boolean spoofFilter; public String kernelModule; public int addressLength; public int carrier; public int dormant; public String features; public String flags; public int linkMode; public String macAddress; public int ethernetMTU; public String operationalState; public int txQueueLength; public int collisions; public int multicastPackets; public int rxBytes; public int rxCompressed; public int rxCrcErrors; public int rxDropped; public int rxErrors; public int rxFifoErrors; public int rxFrameErrors; public int rxLengthErrors; public int rxMissedErrors; public int rxOverErrors; public int rxPackets; public int txAbortedErrors; public int txBytes; public int txCarrierErrors; public int txCompressed; public int txDropped; public int txErrors; public int txFifoErrors; public int txHeartbeatErrors; public int txPackets; public int txWindowErrors; public int beaconing; public int encryptionKey; public int fragmentationThreshold; public int signalLevel; public int linkQuality; public int misc; public int noiseLevel; public int nwid; public int wirelessRetries; public String wirelessStatus; }
27.402299
112
0.799916
714eb57a3afa0d918b47914ab72b33db5cc696ee
734
package io.github.jupiterio.necessaries; import net.fabricmc.api.ModInitializer; import io.github.jupiterio.necessaries.claim.ClaimManager; import io.github.jupiterio.necessaries.tp.TeleportCommands; import io.github.jupiterio.necessaries.portal.PortalManager; public class NecessariesMod implements ModInitializer { @Override public void onInitialize() { // This code runs as soon as Minecraft is in a mod-load-ready state. // However, some things (like resources) may still be uninitialized. // Proceed with mild caution. System.out.println("Initializing Necessaries"); ClaimManager.initialize(); TeleportCommands.initialize(); PortalManager.initialize(); } }
33.363636
76
0.735695
00c8775a20d7ceb3a7d1f68c4fd42bd4db8de539
7,713
/* * 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.openmeetings.db.dao.server; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceException; import javax.persistence.TypedQuery; import org.apache.openmeetings.db.dao.IDataProviderDao; import org.apache.openmeetings.db.dao.user.AdminUserDao; import org.apache.openmeetings.db.entity.server.LdapConfig; import org.apache.openmeetings.util.DaoHelper; import org.apache.openmeetings.util.OpenmeetingsVariables; import org.red5.logging.Red5LoggerFactory; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; /** * Insert/Update/Delete {@link LdapConfig} * * * @author swagner * */ @Transactional public class LdapConfigDao implements IDataProviderDao<LdapConfig> { private static final Logger log = Red5LoggerFactory.getLogger( LdapConfigDao.class, OpenmeetingsVariables.webAppRootKey); public final static String[] searchFields = {"name", "configFileName", "domain", "comment"}; @PersistenceContext private EntityManager em; @Autowired private AdminUserDao usersDao; public Long addLdapConfig(String name, Boolean addDomainToUserName, String configFileName, String domain, Long insertedby, Boolean isActive) { try { LdapConfig ldapConfig = new LdapConfig(); ldapConfig.setAddDomainToUserName(addDomainToUserName); ldapConfig.setConfigFileName(configFileName); ldapConfig.setDeleted(false); ldapConfig.setDomain(domain); ldapConfig.setIsActive(isActive); ldapConfig.setName(name); ldapConfig.setInserted(new Date()); if (insertedby != null) { log.debug("addLdapConfig :1: " + usersDao.get(insertedby)); ldapConfig.setInsertedby(usersDao.get(insertedby)); } log.debug("addLdapConfig :2: " + insertedby); ldapConfig = em.merge(ldapConfig); Long ldapConfigId = ldapConfig.getLdapConfigId(); if (ldapConfigId > 0) { return ldapConfigId; } else { throw new Exception("Could not store SOAPLogin"); } } catch (Exception ex2) { log.error("[addLdapConfig]: ", ex2); } return null; } public Long addLdapConfigByObject(LdapConfig ldapConfig) { try { ldapConfig.setDeleted(false); ldapConfig.setInserted(new Date()); ldapConfig = em.merge(ldapConfig); Long ldapConfigId = ldapConfig.getLdapConfigId(); if (ldapConfigId > 0) { return ldapConfigId; } else { throw new Exception("Could not store SOAPLogin"); } } catch (Exception ex2) { log.error("[addLdapConfig]: ", ex2); } return null; } public Long updateLdapConfig(Long ldapConfigId, String name, Boolean addDomainToUserName, String configFileName, String domain, Long updatedby, Boolean isActive) { try { LdapConfig ldapConfig = this.get(ldapConfigId); if (ldapConfig == null) { return -1L; } ldapConfig.setAddDomainToUserName(addDomainToUserName); ldapConfig.setConfigFileName(configFileName); ldapConfig.setDeleted(false); ldapConfig.setDomain(domain); ldapConfig.setIsActive(isActive); ldapConfig.setName(name); ldapConfig.setUpdated(new Date()); if (updatedby != null) { log.debug("updateLdapConfig :1: " + usersDao.get(updatedby)); ldapConfig.setUpdatedby(usersDao.get(updatedby)); } log.debug("updateLdapConfig :2: " + updatedby); ldapConfig = em.merge(ldapConfig); ldapConfigId = ldapConfig.getLdapConfigId(); return ldapConfigId; } catch (Exception ex2) { log.error("[updateLdapConfig]: ", ex2); } return -1L; } public LdapConfig get(long ldapConfigId) { try { String hql = "select c from LdapConfig c " + "WHERE c.ldapConfigId = :ldapConfigId " + "AND c.deleted = :deleted"; TypedQuery<LdapConfig> query = em .createQuery(hql, LdapConfig.class); query.setParameter("ldapConfigId", ldapConfigId); query.setParameter("deleted", false); LdapConfig ldapConfig = null; try { ldapConfig = query.getSingleResult(); } catch (NoResultException ex) { } return ldapConfig; } catch (Exception ex2) { log.error("[get]: ", ex2); } return null; } public List<LdapConfig> getActiveLdapConfigs() { log.debug("getActiveLdapConfigs"); // get all users TypedQuery<LdapConfig> query = em.createNamedQuery("getActiveLdapConfigs", LdapConfig.class); query.setParameter("isActive", true); return query.getResultList(); } public List<LdapConfig> getLdapConfigs() { //Add localhost Domain LdapConfig ldapConfig = new LdapConfig(); ldapConfig.setName("local DB [internal]"); ldapConfig.setLdapConfigId(-1); List<LdapConfig> result = new ArrayList<LdapConfig>(); result.add(ldapConfig); result.addAll(getActiveLdapConfigs()); return result; } public List<LdapConfig> get(int start, int count) { TypedQuery<LdapConfig> q = em.createNamedQuery("getNondeletedLdapConfigs", LdapConfig.class); q.setFirstResult(start); q.setMaxResults(count); return q.getResultList(); } public List<LdapConfig> get(String search, int start, int count, String sort) { TypedQuery<LdapConfig> q = em.createQuery(DaoHelper.getSearchQuery("LdapConfig", "lc", search, true, false, sort, searchFields), LdapConfig.class); q.setFirstResult(start); q.setMaxResults(count); return q.getResultList(); } public long count() { try { TypedQuery<Long> query = em .createQuery( "select count(c.ldapConfigId) from LdapConfig c where c.deleted = false", Long.class); List<Long> ll = query.getResultList(); log.debug("selectMaxFromLdapConfig" + ll.get(0)); return ll.get(0); } catch (Exception ex2) { log.error("[selectMaxFromLdapConfig] ", ex2); } return 0L; } public long count(String search) { TypedQuery<Long> q = em.createQuery(DaoHelper.getSearchQuery("LdapConfig", "lc", search, true, true, null, searchFields), Long.class); return q.getSingleResult(); } public LdapConfig update(LdapConfig entity, Long userId) { try { if (entity.getLdapConfigId() <= 0) { entity.setInserted(new Date()); if (userId != null) { entity.setInsertedby(usersDao.get(userId)); } entity.setDeleted(false); em.persist(entity); } else { entity.setUpdated(new Date()); if (userId != null) { entity.setUpdatedby(usersDao.get(userId)); } entity.setDeleted(false); em.merge(entity); } } catch (PersistenceException ex) { log.error("[update LdapConfig]", ex); } return entity; } public void delete(LdapConfig entity, Long userId) { if (entity.getLdapConfigId() >= 0) { entity.setUpdated(new Date()); if (userId != null) { entity.setUpdatedby(usersDao.get(userId)); } entity.setDeleted(true); em.merge(entity); } } }
28.566667
149
0.719046
a6a1ee6a21f8b5140e6592dac3b9eae5a9365774
5,845
/* * 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 javax.faces.component; import static org.easymock.EasyMock.expect; import static org.testng.Assert.*; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.el.ELContext; import javax.el.ELException; import javax.el.ValueExpression; import javax.faces.FacesException; import javax.faces.context.FacesContext; import javax.faces.el.ValueBinding; import org.easymock.EasyMock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Test for {@link UIComponent#getValueExpression(String)}. and * {@link UIComponent#setValueExpression(String, javax.el.ValueExpression)}. */ public class UIComponentValueExpressionTest extends UIComponentTestBase { private UIComponent _testimpl; private ValueExpression _expression; private ELContext _elContext; @Override @BeforeMethod(alwaysRun = true) protected void setUp() throws Exception { super.setUp(); Collection<Method> mockedMethods = new ArrayList<Method>(); Class<UIComponent> clazz = UIComponent.class; mockedMethods.add(clazz.getDeclaredMethod("getAttributes", (Class<?>[])null)); mockedMethods.add(clazz.getDeclaredMethod("getFacesContext", (Class<?>[])null)); mockedMethods.add(clazz.getDeclaredMethod("getValueBinding", new Class[] { String.class })); _testimpl = _mocksControl.createMock(clazz, mockedMethods.toArray(new Method[mockedMethods.size()])); _expression = _mocksControl.createMock(ValueExpression.class); _elContext = _mocksControl.createMock(ELContext.class); _mocksControl.checkOrder(true); } @Test(expectedExceptions = { NullPointerException.class }) public void testValueExpressionArgumentNPE() throws Exception { _testimpl.setValueExpression(null, _expression); } @Test(expectedExceptions = { IllegalArgumentException.class }) public void testValueExpressionArgumentId() throws Exception { _testimpl.setValueExpression("id", _expression); } @Test(expectedExceptions = { IllegalArgumentException.class }) public void testValueExpressionArgumentsParent() throws Exception { _testimpl.setValueExpression("parent", _expression); } @Test public void testValueExpression() throws Exception { expect(_expression.isLiteralText()).andReturn(false); _mocksControl.replay(); _testimpl.setValueExpression("xxx", _expression); _mocksControl.verify(); assertEquals(_expression, _testimpl.getValueExpression("xxx")); _testimpl.setValueExpression("xxx", null); _mocksControl.verify(); assertNull(_testimpl.getValueExpression("xxx")); assertNull(_testimpl.bindings); } @Test(expectedExceptions = { FacesException.class }) public void testValueExpressionWithExceptionOnGetValue() throws Exception { expect(_expression.isLiteralText()).andReturn(true); expect(_testimpl.getFacesContext()).andReturn(_facesContext); expect(_facesContext.getELContext()).andReturn(_elContext); expect(_expression.getValue(EasyMock.eq(_elContext))).andThrow(new ELException()); Map<String, Object> map = new HashMap<String, Object>(); expect(_testimpl.getAttributes()).andReturn(map); _mocksControl.replay(); _testimpl.setValueExpression("xxx", _expression); } @Test public void testValueExpressionWithLiteralText() throws Exception { expect(_expression.isLiteralText()).andReturn(true); expect(_testimpl.getFacesContext()).andReturn(_facesContext); expect(_facesContext.getELContext()).andReturn(_elContext); expect(_expression.getValue(EasyMock.eq(_elContext))).andReturn("abc"); Map<String, Object> map = new HashMap<String, Object>(); expect(_testimpl.getAttributes()).andReturn(map); _mocksControl.replay(); _testimpl.setValueExpression("xxx", _expression); assertEquals("abc", map.get("xxx")); _mocksControl.verify(); assertNull(_testimpl.getValueExpression("xxx")); } @Test public void testValueExpressionWithValueBindingFallback() throws Exception { ValueBinding valueBinding = _mocksControl.createMock(ValueBinding.class); expect(_testimpl.getValueBinding("xxx")).andReturn(valueBinding); _mocksControl.replay(); ValueExpression valueExpression = _testimpl.getValueExpression("xxx"); _mocksControl.verify(); assertTrue(valueExpression instanceof _ValueBindingToValueExpression); _mocksControl.reset(); expect(_elContext.getContext(EasyMock.eq(FacesContext.class))).andReturn(_facesContext); expect(valueBinding.getValue(EasyMock.eq(_facesContext))).andReturn("value"); _mocksControl.replay(); assertEquals("value", valueExpression.getValue(_elContext)); _mocksControl.verify(); } }
40.034247
109
0.723867
f652ab634544a3e3def5d6cfb8134b3d062b3b2d
799
package com.example.mybrower; import android.os.Bundle; import android.os.PersistableBundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.example.adapter.TestAdapter; import com.example.bean.UserInfoBean; import java.util.ArrayList; import java.util.List; public class Test extends AppCompatActivity { private String[] strings=new String[10]; private List<UserInfoBean> userInfoBeans=new ArrayList<>(); private TestAdapter testAdapter; @Override public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) { super.onCreate(savedInstanceState, persistentState); testAdapter=new TestAdapter(strings); testAdapter=new TestAdapter(userInfoBeans); } }
27.551724
108
0.777222
e34676c6564e763965f5cb93888455c3f3df2ccf
278
package com.holtak.holidays4j.exception; public class Holiday4jException extends Exception { public Holiday4jException(String message) { super(message); } public Holiday4jException(String message, Throwable cause) { super(message, cause); } }
21.384615
64
0.708633
8dafac62480157f26283b36c4754b0a0509856bc
2,700
/** * * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by * the European Commission - subsequent versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * <p> * http://ec.europa.eu/idabc/eupl * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. * <p> * Date: 23-08-2016 * Author(s): Sjoerd Boerhout * <p> */ package nl.dictu.prova.plugins.input.msexcel; import nl.dictu.prova.TestRunner; import nl.dictu.prova.framework.TestCase; import nl.dictu.prova.framework.TestSuite; import nl.dictu.prova.plugins.input.InputPlugin; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * * @author Sjoerd Boerhout */ public class MsExcel implements InputPlugin { private final static Logger LOGGER = LogManager.getLogger(MsExcel.class. getName()); @Override public void init(TestRunner tr) throws Exception { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public String setTestRoot(String string, String string1) throws IllegalArgumentException { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public String setTestCaseFilter(String[] strings) throws NullPointerException { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public TestSuite setUp(TestSuite ts) throws NullPointerException { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public TestCase loadTestCase(TestCase tc) throws NullPointerException { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void shutDown() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public String getName() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
30.681818
131
0.74
e669e0db03591366216e71fc24e624b2de3e5869
921
package array; /** * https://oj.leetcode.com/problems/search-insert-position/ * Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. * You may assume no duplicates in the array. * Here are few examples. * <pre> * [1,3,5,6], 5 → 2 * [1,3,5,6], 2 → 1 * [1,3,5,6], 7 → 4 * [1,3,5,6], 0 → 0 * </pre> */ public class SearchInsertPosition { public int searchInsert(int[] A, int target) { int l = A == null ? 0 : A.length; if (l == 0) return 0; int low = 0, high = l - 1; while (low <= high) { int mid = low + (high - low) / 2; if (A[mid] == target) return mid; if (target > A[mid]) { low = mid + 1; } else if (target < A[mid]) { high = mid - 1; } } return low; } }
28.78125
157
0.508143
9f3b40ea81a4018a5b93bcf3265ef5f7da296be2
997
package ru.job4j.tracker; import java.util.List; import java.util.Scanner; /** * Class ConsoleInput. * * @author Ayder Khayredinov ([email protected]). * @version 1. * @since 3.01.2019. */ public class ConsoleInput implements Input { /** * Поле создаем экземпляр сканера. */ private Scanner scanner = new Scanner(System.in); /** * Переопределяем метод ask. */ public String ask(String questions) { System.out.println(questions); return scanner.nextLine(); } /** * Перегружаем метод ask. */ @Override public int ask(String question, List<Integer> range) { int key = Integer.valueOf(this.ask(question)); boolean exist = false; for (int value : range) { if (value == key) { exist = true; break; } } if (!exist) { throw new MenuOutExceptoin("Out of menu range"); } return key; } }
21.212766
60
0.553661
bf4b4e388f0f58bf41994cd369d091b90e232a47
2,888
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.manifmerger; import static com.android.manifmerger.ManifestModel.NodeTypes; import com.android.annotations.NonNull; import com.android.annotations.Nullable; import com.android.ide.common.blame.SourceFile; import com.android.ide.common.blame.SourcePosition; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import org.w3c.dom.Element; /** * An xml element that does not belong to a {@link com.android.manifmerger.XmlDocument} */ public class OrphanXmlElement extends XmlNode { @NonNull private final Element mXml; @NonNull private final NodeTypes mType; public OrphanXmlElement(@NonNull Element xml, @NonNull DocumentModel<NodeTypes> model) { mXml = Preconditions.checkNotNull(xml); String elementName = mXml.getNodeName(); // if there's a namespace prefix, just strip it. The DocumentModel does not look at // namespaces right now. mType = model.fromXmlSimpleName(elementName.substring(elementName.indexOf(':') + 1)); } /** * Returns true if this xml element's {@link NodeTypes} is * the passed one. */ public boolean isA(NodeTypes type) { return this.mType == type; } @NonNull @Override public Element getXml() { return mXml; } @NonNull @Override public NodeKey getId() { return new NodeKey(Strings.isNullOrEmpty(getKey()) ? getName().toString() : getName().toString() + "#" + getKey()); } @NonNull @Override public NodeName getName() { return XmlNode.unwrapName(mXml); } /** * Returns this xml element {@link NodeTypes} */ @NonNull public NodeTypes getType() { return mType; } /** * Returns the unique key for this xml element within the xml file or null if there can be only * one element of this type. */ @Nullable public String getKey() { return mType.getNodeKeyResolver().getKey(mXml); } @NonNull @Override public SourcePosition getPosition() { return SourcePosition.UNKNOWN; } @Override @NonNull public SourceFile getSourceFile() { return SourceFile.UNKNOWN; } }
26.990654
99
0.67036
9276479b75e8ee34d156aeac0408d5b0241c9220
1,186
/* * Copyright (C) 2015 fuwjax.org ([email protected]) * * 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.fuwjax.oss.util.io; import java.util.PrimitiveIterator; public class StringIntReader implements IntReader.Safe { private final PrimitiveIterator.OfInt iter; private final CharSequence chars; private int count; public StringIntReader(final CharSequence chars) { this.chars = chars; iter = chars.codePoints().iterator(); } @Override public int read() { if(iter.hasNext()) { count++; return iter.nextInt(); } return -1; } @Override public String toString() { return chars.subSequence(count, chars.length()).toString(); } }
26.954545
75
0.725126
87d5e652b8088650170091797ee40e2a9d0dfef1
638
/* * 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 codegenius; /** * * @author codegeni.us */ public class EagerInitialization { // define private instance. private static final EagerInitialization instance = new EagerInitialization(); //Restrict to create new instance. private EagerInitialization() { } // use only created instance via public method. public static EagerInitialization getInstance() { return instance; } }
24.538462
83
0.680251
0035e42185ec4889110047a2097dd9a36764ed6b
1,700
package com.yhy.common.beans.net.model.tm; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; /** * Created with Android Studio. * Title:ItemParamForOrderContext * Description: * Copyright:Copyright (c) 2016 * Company:quanyan * Author:鲍杰 * Date:2016-12-21 * Time:15:08 * Version 1.1.0 */ public class ItemParamForOrderContext implements Serializable { private static final long serialVersionUID = -1663364665258285310L; /** * 商品id 必填 */ public long itemId; /** * 商品购买数量 必填 */ public long buyAmount; /** * 反序列化函数,用于从json字符串反序列化本类型实例 */ public static ItemParamForOrderContext deserialize(String json) throws JSONException { if (json != null && !json.isEmpty()) { return deserialize(new JSONObject(json)); } return null; } /** * 反序列化函数,用于从json节点对象反序列化本类型实例 */ public static ItemParamForOrderContext deserialize(JSONObject json) throws JSONException { if (json != null && json != JSONObject.NULL && json.length() > 0) { ItemParamForOrderContext result = new ItemParamForOrderContext(); // 商品id 必填 result.itemId = json.optLong("itemId"); // 商品购买数量 必填 result.buyAmount = json.optLong("buyAmount"); return result; } return null; } /* * 序列化函数,用于从对象生成数据字典 */ public JSONObject serialize() throws JSONException { JSONObject json = new JSONObject(); // 商品id 必填 json.put("itemId", this.itemId); // 商品购买数量 必填 json.put("buyAmount", this.buyAmount); return json; } }
22.368421
94
0.612353
7e107cc22b5cbe916a349592c369c8b48b868051
1,024
package guerbai.f851_900; import java.util.HashMap; import java.util.Map; public class LemonadeChange { private static boolean lemonadeChange(int[] bills) { Map<Integer, Integer> m = new HashMap<>(); m.put(5, 0); m.put(10, 0); for (int bill: bills) { if (bill == 5) { m.put(5, m.get(5)+1); } else if (bill == 10) { if (m.get(5) == 0) { return false; } m.put(5, m.get(5)-1); m.put(10, m.get(10)+1); } else { if (m.get(10) > 0) { if (m.get(5) == 0) { return false; } m.put(10, m.get(10)-1); m.put(5, m.get(5)-1); } else if (m.get(5) < 3) { return false; } else { m.put(5, m.get(5)-3); } } } return true; } }
27.675676
56
0.351563
93e9e73c0c9f2e41525af67057b67cf457d8f1bc
565
class MultipleInheritance { interface A { int X = 1; String FOO = "foo"; } interface B extends A { int X = 2; String FOO = "foo"; } interface C extends A, B { int Y = C.<error descr="Reference to 'X' is ambiguous, both 'A.X' and 'B.X' match">X</error>; String BAR = C.<error descr="Reference to 'FOO' is ambiguous, both 'A.FOO' and 'B.FOO' match">FOO</error>.substring(1); } } class Shadowing { interface A { int X = 1; } interface B extends A { int X = 2; } interface C extends B { int Y = C.X; } }
18.225806
123
0.573451
79e81187e675474eaf9041ae77c8e6402fd3dc95
10,158
/* * (C) Copyright 2015-2018 Nuxeo (http://nuxeo.com/) and others. * * 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. * * Contributors: * Nuxeo */ package org.nuxeo.ecm.blob.azure; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeFalse; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.security.InvalidKeyException; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.nuxeo.common.utils.RFC2231; import org.nuxeo.ecm.blob.AbstractCloudBinaryManager; import org.nuxeo.ecm.blob.AbstractTestCloudBinaryManager; import org.nuxeo.ecm.core.api.Blob; import org.nuxeo.ecm.core.api.Blobs; import org.nuxeo.ecm.core.blob.BlobInfo; import org.nuxeo.ecm.core.blob.ManagedBlob; import org.nuxeo.ecm.core.blob.SimpleManagedBlob; import org.nuxeo.ecm.core.blob.binary.Binary; import org.nuxeo.ecm.core.io.download.DownloadHelper; import org.nuxeo.runtime.api.Framework; import org.nuxeo.runtime.test.runner.Features; import org.nuxeo.runtime.test.runner.FeaturesRunner; import org.nuxeo.runtime.test.runner.RuntimeFeature; import com.microsoft.azure.storage.Constants; import com.microsoft.azure.storage.StorageCredentialsSharedAccessSignature; import com.microsoft.azure.storage.StorageException; import com.microsoft.azure.storage.blob.CloudBlobContainer; import com.microsoft.azure.storage.blob.CloudBlockBlob; import com.microsoft.azure.storage.blob.SharedAccessBlobHeaders; import com.microsoft.azure.storage.blob.SharedAccessBlobPolicy; import com.microsoft.azure.storage.core.StreamMd5AndLength; import com.microsoft.azure.storage.core.Utility; /** * WARNING: You must pass those variables to your test configuration: * <p> * * <pre> * -Dnuxeo.storage.azure.account.name: Azure account name * -Dnuxeo.storage.azure.account.key: Azure account key * -Dnuxeo.storage.azure.container: A test container name * </pre> * * @author <a href="mailto:[email protected]">Arnaud Kervern</a> */ @RunWith(FeaturesRunner.class) @Features(RuntimeFeature.class) public class TestAzureBinaryManager extends AbstractTestCloudBinaryManager<AzureBinaryManager> { protected final static List<String> PARAMETERS = Arrays.asList(AzureBinaryManager.ACCOUNT_KEY_PROPERTY, AzureBinaryManager.ACCOUNT_NAME_PROPERTY, AzureBinaryManager.CONTAINER_PROPERTY); protected static Map<String, String> properties = new HashMap<>(); protected static final String PREFIX = "testfolder/"; @BeforeClass public static void initialize() { AbstractCloudBinaryManager bm = new AzureBinaryManager(); PARAMETERS.forEach(s -> { properties.put(s, Framework.getProperty(bm.getSystemPropertyName(s))); }); // Ensure mandatory parameters are set PARAMETERS.forEach(s -> { assumeFalse(isBlank(properties.get(s))); }); properties.put("prefix", PREFIX); } @AfterClass public static void afterClass() { // Cleanup keys Properties props = Framework.getProperties(); PARAMETERS.forEach(props::remove); } @Override protected AzureBinaryManager getBinaryManager() throws IOException { AzureBinaryManager binaryManager = new AzureBinaryManager(); binaryManager.initialize("azuretest", properties); return binaryManager; } @Override protected Set<String> listObjects() { Set<String> digests = new HashSet<>(); binaryManager.container.listBlobs(PREFIX, false).forEach(lb -> { try { if (lb instanceof CloudBlockBlob) { // ignore subdirectories String name = ((CloudBlockBlob) lb).getName(); String digest = name.substring(PREFIX.length()); digests.add(digest); } } catch (URISyntaxException e) { // Do nothing. } }); return digests; } protected Set<String> listAllObjects() { Set<String> names = new HashSet<>(); binaryManager.container.listBlobs("", true).forEach(lb -> { try { String name = ((CloudBlockBlob) lb).getName(); names.add(name); } catch (URISyntaxException e) { // Do nothing. } }); return names; } @Test public void testSigning() throws IOException, URISyntaxException, StorageException, InvalidKeyException { CloudBlobContainer container = binaryManager.container; Binary binary = binaryManager.getBinary(Blobs.createBlob(CONTENT)); assertNotNull(binary); CloudBlockBlob blockBlobReference = container.getBlockBlobReference(CONTENT_MD5); SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy(); policy.setPermissionsFromString("r"); // rscd content-dispositoon // rsct content-type Instant endDateTime = LocalDateTime.now().plusHours(1).atZone(ZoneId.systemDefault()).toInstant(); policy.setSharedAccessExpiryTime(Date.from(endDateTime)); SharedAccessBlobHeaders headers = new SharedAccessBlobHeaders(); headers.setContentDisposition("attachment; filename=\"blabla.txt\""); headers.setContentType("text/plain"); String something = blockBlobReference.generateSharedAccessSignature(policy, headers, null); System.out.println(something); CloudBlockBlob blob = new CloudBlockBlob(blockBlobReference.getUri(), new StorageCredentialsSharedAccessSignature(something)); System.out.println(blob.getQualifiedUri()); } protected String getContentTypeHeader(Blob blob) { String contentType = blob.getMimeType(); String encoding = blob.getEncoding(); if (contentType != null && !StringUtils.isBlank(encoding)) { int i = contentType.indexOf(';'); if (i >= 0) { contentType = contentType.substring(0, i); } contentType += "; charset=" + encoding; } return contentType; } protected String getContentDispositionHeader(Blob blob, HttpServletRequest servletRequest) { if (servletRequest == null) { return RFC2231.encodeContentDisposition(blob.getFilename(), false, null); } else { return DownloadHelper.getRFC2231ContentDisposition(servletRequest, blob.getFilename()); } } @Test public void ensureDigestDecode() throws IOException, StorageException { Blob blob = Blobs.createBlob(CONTENT2); String contentMd5; try (InputStream is = blob.getStream()) { StreamMd5AndLength md5 = Utility.analyzeStream(is, blob.getLength(), 2 * Constants.MB, true, true); contentMd5 = md5.getMd5(); } assertTrue(AzureFileStorage.isBlobDigestCorrect(CONTENT2_MD5, contentMd5)); } @Override @Test public void testBinaryManagerGC() throws Exception { if (binaryManager.prefix.isEmpty()) { // no additional test if no bucket name prefix super.testBinaryManagerGC(); return; } // create a md5-looking extra file at the root String name1 = "12345678901234567890123456789012"; try (InputStream in = new ByteArrayInputStream(new byte[] { '0' })) { CloudBlockBlob blob = binaryManager.container.getBlockBlobReference(name1); blob.upload(in, 1); } // create a md5-looking extra file in a "subdirectory" of the prefix String name2 = binaryManager.prefix + "subfolder/12345678901234567890123456789999"; try (InputStream in = new ByteArrayInputStream(new byte[] { '0' })) { CloudBlockBlob blob = binaryManager.container.getBlockBlobReference(name2); blob.upload(in, 1); } // check that the files are here assertEquals(new HashSet<>(Arrays.asList(name1, name2)), listAllObjects()); // run base test with the prefix super.testBinaryManagerGC(); // check that the extra files are still here Set<String> res = listAllObjects(); assertTrue(res.contains(name1)); assertTrue(res.contains(name2)); } @Test public void testRemoteURI() throws Exception { Blob blob = Blobs.createBlob(CONTENT); Binary binary = binaryManager.getBinary(blob); BlobInfo blobInfo = new BlobInfo(); blobInfo.digest = binary.getDigest(); blobInfo.length = Long.valueOf(blob.getLength()); blobInfo.filename = "caf\u00e9 corner.txt"; blobInfo.mimeType = "text/plain"; ManagedBlob mb = new SimpleManagedBlob(blobInfo ); URI uri = binaryManager.getRemoteUri(binary.getDigest(), mb, null); String string = uri.toASCIIString(); // %-escaped version assertTrue(string, string.contains("filename*%3DUTF-8%27%27caf%C3%A9%20corner.txt")); } }
37.483395
111
0.687537
c5884260c4a68eeaad0ea5b7125a52d10a3cc1b5
4,094
/* * Copyright 2014-2018 Rudy De Busscher (https://www.atbash.be) * * 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 be.atbash.ee.security.octopus.interceptor; import be.atbash.ee.security.octopus.context.internal.OctopusInvocationContext; import org.apache.deltaspike.security.api.authorization.AccessDecisionState; import org.apache.deltaspike.security.api.authorization.SecurityViolation; import org.apache.deltaspike.security.spi.authorization.EditableAccessDecisionVoterContext; import java.security.InvalidParameterException; import java.util.*; /** * Implementation of {@link EditableAccessDecisionVoterContext} with the {@link OctopusInvocationContext} interface or for a specific method. */ public class CustomAccessDecisionVoterContext implements EditableAccessDecisionVoterContext { private AccessDecisionState state = AccessDecisionState.INITIAL; // FIXME Update this state depending on the stage private List<SecurityViolation> securityViolations; private Map<String, Object> metaData = new HashMap<>(); private OctopusInvocationContext context; public CustomAccessDecisionVoterContext(OctopusInvocationContext context) { this.context = context; } /** * {@inheritDoc} */ @Override public AccessDecisionState getState() { return state; } /** * {@inheritDoc} */ @Override public List<SecurityViolation> getViolations() { if (securityViolations == null) { return Collections.emptyList(); } return Collections.unmodifiableList(securityViolations); } /** * {@inheritDoc} */ @Override public <T> T getSource() { return (T) context; } /** * {@inheritDoc} */ @Override public void setSource(Object source) { if (!(source instanceof OctopusInvocationContext)) { throw new InvalidParameterException("Only OctopusInvocationContext supported"); } this.context = (OctopusInvocationContext) source; } /** * {@inheritDoc} */ @Override public Map<String, Object> getMetaData() { return Collections.unmodifiableMap(metaData); } /** * {@inheritDoc} */ @Override public <T> T getMetaDataFor(String key, Class<T> targetType) { return (T) metaData.get(key); } /** * {@inheritDoc} */ @Override public void addMetaData(String key, Object metaData) { //TODO specify nested security calls this.metaData.put(key, metaData); } /** * {@inheritDoc} */ @Override public void setState(AccessDecisionState accessDecisionVoterState) { if (AccessDecisionState.VOTE_IN_PROGRESS.equals(accessDecisionVoterState)) { securityViolations = new ArrayList<>(); //lazy init } state = accessDecisionVoterState; if (AccessDecisionState.INITIAL.equals(accessDecisionVoterState) || AccessDecisionState.VOTE_IN_PROGRESS.equals(accessDecisionVoterState)) { return; } //meta-data is only needed until the end of a voting process metaData.clear(); } /** * {@inheritDoc} */ @Override public void addViolation(SecurityViolation securityViolation) { if (securityViolations == null) { throw new IllegalStateException( AccessDecisionState.VOTE_IN_PROGRESS.name() + " is required for adding security-violations"); } securityViolations.add(securityViolation); } }
30.781955
141
0.676844
1cc6edfc87e442f71dac8501feb3756497559d6e
1,639
package com.dyh.string; import java.util.ArrayList; import java.util.List; import java.util.Stack; /** * Remove All Adjacent Duplicates In String:给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。 * 在 S 上反复执行重复项删除操作,直到无法继续删除。 * 在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。 * input: "abbaca" * output: "ca" * @author dyh * */ public class RemoveAllAdjacentDuplicatesInString { public static String removeDuplicates(String S) { int flag = 0; StringBuilder sb = new StringBuilder(); while(flag != -1) { flag = isDuplicates(S); for(int i = 0; i < S.length(); i++) { if(i != flag) { sb.append(S.charAt(i)); }else { i++; } } S = sb.toString(); sb.delete(0, sb.length()); } return S; } public static String removeDuplicates2(String S) { char[] chars = S.toCharArray(); Stack<Character> stack = new Stack<>(); for(int i = 0; i < S.length(); i++) { if(stack.isEmpty() || chars[i] != stack.peek()) { stack.push(chars[i]); }else { stack.pop(); } } StringBuilder sBuilder = new StringBuilder(); for(Character c: stack) { sBuilder.append(c); } return sBuilder.toString(); } public static int isDuplicates(String s) { int index = -1; for(int i = 0; i < s.length(); i++) { if(i == s.length() - 1) { break; } if(s.charAt(i) == s.charAt(i+1)) { index = i; break; } } return index; } public static void main(String[] args) { // TODO Auto-generated method stub String string = "abbaca"; System.out.println(removeDuplicates(string)); } }
21.012821
88
0.578401
c82f2bdd523fc5bb048288497a279e751e06b33f
10,299
/* * @(#)CharcoalEffect.java * * Copyright (c) 2009 by Jeremy Wood. * All rights reserved. * * The copyright of this software is owned by Jeremy Wood. * You may not use, copy or modify this software, except in * accordance with the license agreement you entered into with * Jeremy Wood. For details see accompanying license terms. * * This software is probably, but not necessarily, discussed here: * http://javagraphics.blogspot.com/ * * And the latest version should be available here: * https://javagraphics.dev.java.net/ */ package com.bric.awt; import com.bric.geom.GeneralPathWriter; import com.bric.geom.MeasuredShape; import com.bric.geom.PathWriter; import java.awt.Shape; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.util.Random; /** * This applies a charcoal effect to a shape. * <p/> * This basically takes a shape and applies several "cracks" of varying * depth at a fixed angle. * <p/> * (The implementation is pretty simple, and there are a few interesting * code snippets commented out that change how this renders.) * * @version 1.1 */ public class CharcoalEffect { public final PathWriter writer; public final int seed; public final float size; public final float angle; public final float maxDepth; /** * Creates a new <code>CharcoalEffect</code>. * * @param dest the destination to write the new shape to. * @param size the size of the cracks. This is float from [0,1], where * "0" means "no crack depth" and "1" means "high depth". The depth is * always relative to the <i>possible</i> depth. * @param angle the angle of the cracks. * @param randomSeed the random seed. */ public CharcoalEffect(PathWriter dest, float size, float angle, int randomSeed) { this(dest, size, angle, randomSeed, Float.MAX_VALUE); } /** * Creates a new <code>CharcoalEffect</code>. * * @param dest the destination to write the new shape to. * @param size the size of the cracks. This is float from [0,1], where * "0" means "no crack depth" and "1" means "high depth". The depth is * always relative to the <i>possible</i> depth. * @param angle the angle of the cracks. * @param randomSeed the random seed. * @param maxDepth this is the maximum crack depth. If this is zero, then no * cracks will be added. If this is 5, then cracks will be at most 5 pixels. * If you aren't sure what to make this value, use <code>Float.MAX_VALUE</code>. */ public CharcoalEffect(PathWriter dest, float size, float angle, int randomSeed, float maxDepth) { if (size < 0 || size > 1) throw new IllegalArgumentException("size (" + size + ") must be between 0 and 1."); writer = dest; seed = randomSeed; this.size = size; this.angle = angle; this.maxDepth = maxDepth; } /** * Applies the <code>CharcoalEffect</code> to a shape. * * @param shape the shape to apply the effect to. * @param size the size of the cracks. This is float from [0,1], where * "0" means "no crack depth" and "1" means "high depth". The depth is * always relative to the <i>possible</i> depth. * @param angle the angle of the cracks. * @param randomSeed the random seed. * @param maxDepth this is the maximum crack depth. If this is zero, then no * cracks will be added. If this is 5, then cracks will be at most 5 pixels. * If you aren't sure what to make this value, use <code>Float.MAX_VALUE</code>. * @return a new filtered path. */ public static GeneralPath filter(Shape shape, float size, float angle, int randomSeed, float maxDepth) { GeneralPath path = new GeneralPath(); GeneralPathWriter writer = new GeneralPathWriter(path); CharcoalEffect effect = new CharcoalEffect(writer, size, angle, randomSeed, maxDepth); effect.write(shape); return path; } /** * Applies the <code>CharcoalEffect</code> to a shape. * * @param shape the shape to apply the effect to. * @param size the size of the cracks. This is float from [0,1], where * "0" means "no crack depth" and "1" means "high depth". The depth is * always relative to the <i>possible</i> depth. * @param angle the angle of the cracks. * @param randomSeed the random seed. * @return a new filtered path. */ public static GeneralPath filter(Shape shape, float size, float angle, int randomSeed) { return filter(shape, size, angle, randomSeed, Float.MAX_VALUE); } /** * Applies this effect to the shape provided. * * @param shape the shape to write. */ public void write(Shape s) { Random random = new Random(seed); Point2D center = new Point2D.Float(); Point2D rightSide = new Point2D.Float(); MeasuredShape[] m = MeasuredShape.getSubpaths(s, .05f); subpathIterator: for (int a = 0; a < m.length; a++) { float orig = m[a].getOriginalDistance(); float total = m[a].getDistance(); float distance = 0; float pendingGap = 0; writer.moveTo(m[a].getMoveToX(), m[a].getMoveToY()); while (distance < orig) { pendingGap += (.05f + .95f * random.nextFloat()) * 20 * (.05f + .95f * (1 - .9f * size)); if (distance + pendingGap >= orig) { //we're overflowing: float remaining = orig - distance; if (remaining > 2) { m[a].writeShape(distance / total, remaining / total, writer, false); } else { writer.closePath(); } continue subpathIterator; } else if (distance + pendingGap < orig) { //see if we can add a crack here: m[a].getPoint(distance + pendingGap, center); /** Don't add a crack if this point is completely inside the guiding shape. * And don't trust shape.contains(x,y,width,height). Although that is in * theory what we want, it doesn't always return correct results! * This test isn't quite the same, but gets us what we need. And accurately: */ boolean addCrack = !(s.contains(center.getX() - .5, center.getY() - .5) && s.contains(center.getX() + .5, center.getY() - .5) && s.contains(center.getX() - .5, center.getY() + .5) && s.contains(center.getX() + .5, center.getY() + .5)); if (addCrack) { for (int mult = -1; mult <= 1; mult += 2) { //try both the clockwise and the counterclockwise side float width = .05f; //yes, you can also try this: //float angle = m[a].getTangentSlope(distance+pendingGap); //or //float angle = m[a].getTangentSlope(distance+pendingGap)-(float)Math.PI/4; while (s.contains(center.getX() + width * Math.cos(angle + mult * Math.PI / 2), center.getY() + width * Math.sin(angle + mult * Math.PI / 2)) && width < maxDepth) { width++; } //or to make something spikey, try: //if(guide.contains(center.getX()+.1*Math.cos(angle-mult*Math.PI/2), // center.getY()+.1*Math.sin(angle-mult*Math.PI/2))) { // width = random.nextFloat()*8+1; //} if (width > 1) { //width will be > 1 when we're on the correct side AND we have //a fleshy material to cut into float crackWidth, depth; //now define a constant to multiply the depth of the crack by //when width is 5, multiply by 1. when width is 15, multiply by .5 float k = -.05f * width + 1.25f; if (k > 1) k = 1; //cap at these values if (k < .4f) k = .4f; depth = width * k * (.5f + .5f * size) * (.25f + .75f * random.nextFloat()); crackWidth = depth * depth / 150; if (crackWidth < 1f) crackWidth = 1f; if (crackWidth > 2) crackWidth = 2; if (distance + pendingGap - crackWidth / 2 > 0 && distance + pendingGap + crackWidth / 2 < orig) { m[a].getPoint(distance + pendingGap + crackWidth / 2, rightSide); m[a].writeShape(distance / total, (pendingGap - crackWidth / 2) / total, writer, false); writer.lineTo( (float) (center.getX() + depth * Math.cos(angle + mult * Math.PI / 2)), (float) (center.getY() + depth * Math.sin(angle + mult * Math.PI / 2)) ); writer.lineTo((float) rightSide.getX(), (float) rightSide.getY()); distance += pendingGap + crackWidth / 2; pendingGap = 0; } break; } } } } } writer.closePath(); } } }
46.183857
130
0.514904
7f60d5fcafda2f77107184f75213c44a11eca520
1,056
package com.cadnunsdev.direccionescongespanhol; import com.google.android.gms.maps.model.LatLng; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; /** * Created by Tiago Silva on 17/01/2017. */ public class GeoCodeJsonService { String urlService = "https://maps.googleapis.com/maps/api/geocode/json?address="; // public static LatLng getByAdress(String adress){ // DefaultHttpClient defaultClient = new JsonObjectRequest; // // Setup the get request // HttpGet httpGetRequest = new HttpGet("http://example.json"); // // // Execute the request in the client // HttpResponse httpResponse = defaultClient.execute(httpGetRequest); // // Grab the response // BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); // String json = reader.readLine(); // // // Instantiate a JSON object from the request response // JSONObject jsonObject = new JSONObject(json); // // } }
32
124
0.696023