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
52031a7af6cc3ef4540df807361aff150b0a26d6
1,948
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.core.archive; import java.io.File; import java.io.IOException; import org.eclipse.birt.core.archive.compound.ArchiveReader; /** * file based archive reader. * It reads multiple streams from a single physical file. the file * is created by FileArchiveWriter. */ public class FileArchiveReader extends ArchiveReader { /** * @param fileName - * the absolute name of the file archive */ public FileArchiveReader( String fileName ) throws IOException { super( fileName ); } /** * Explode the existing compound file archive to a folder that contains * corresponding files in it. NOTE: The original file archive will NOT be * deleted. However, if the specified folder archive exists already, its old * content will be totally erased first. * * @param folderArchiveName - * the name of the folder archive. * @throws IOException */ public void expandFileArchive( String folderArchiveName ) throws IOException { File folder = new File( folderArchiveName ); folderArchiveName = folder.getCanonicalPath( ); ArchiveUtil.deleteAllFiles( folder ); // Clean up the folder if it // exists. folder.mkdirs( ); // Create archive folder FolderArchiveWriter writer = new FolderArchiveWriter( folderArchiveName ); try { writer.initialize( ); ArchiveUtil.copy( this, writer ); } finally { writer.finish( ); } } }
29.074627
81
0.662218
1c445e3336d7551b040ada824a8ac99cbe45a4e5
4,069
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.util; import java.io.*; import java.util.Calendar; import javax.servlet.*; public class ServletUtil { /** * Initial HTML header */ public static PrintWriter initHTML(ServletResponse response, String title ) throws IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>\n" + "<link rel='stylesheet' type='text/css' href='/static/hadoop.css'>\n" + "<title>" + title + "</title>\n" + "<body>\n" + "<h1>" + title + "</h1>\n"); return out; } /** * Get a parameter from a ServletRequest. * Return null if the parameter contains only white spaces. */ public static String getParameter(ServletRequest request, String name) { String s = request.getParameter(name); if (s == null) { return null; } s = s.trim(); return s.length() == 0? null: s; } public static final String HTML_TAIL = "<hr />\n" + "This release is based on the <a href='https://github.com/facebook/hadoop-20'>Facebook Distribution of Hadoop</a>, " + "powering the largest Hadoop clusters in the Universe!\n" + "</body></html>"; /** * HTML footer to be added in the jsps. * @return the HTML footer. */ public static String htmlFooter() { return HTML_TAIL; } /** * Generate the percentage graph and returns HTML representation string * of the same. * * @param perc The percentage value for which graph is to be generated * @param width The width of the display table * @return HTML String representation of the percentage graph * @throws IOException */ public static String percentageGraph(int perc, int width) throws IOException { assert perc >= 0; assert perc <= 100; StringBuilder builder = new StringBuilder(); builder.append("<table border=\"1px\" width=\""); builder.append(width); builder.append("px\"><tr>"); if(perc > 0) { builder.append("<td cellspacing=\"0\" class=\"perc_filled\" width=\""); builder.append(perc); builder.append("%\"></td>"); }if(perc < 100) { builder.append("<td cellspacing=\"0\" class=\"perc_nonfilled\" width=\""); builder.append(100 - perc); builder.append("%\"></td>"); } builder.append("</tr></table>"); return builder.toString(); } /** * Generate the percentage graph and returns HTML representation string * of the same. * @param perc The percentage value for which graph is to be generated * @param width The width of the display table * @return HTML String representation of the percentage graph * @throws IOException */ public static String percentageGraph(float perc, int width) throws IOException { return percentageGraph((int)perc, width); } /** * @return a long value as passed in the given parameter, throwing * an exception if it is not present or if it is not a valid number. */ public static long parseLongParam(ServletRequest request, String param) throws IOException { String paramStr = request.getParameter(param); if (paramStr == null) { throw new IOException("Invalid request has no " + param + " parameter"); } return Long.valueOf(paramStr); } }
33.908333
122
0.669452
f694199e569d028ec5404e7fefe37764874b8005
16,685
/* ************************************************************************* * The contents of this file are subject to the Openbravo Public License * Version 1.1 (the "License"), being the Mozilla Public License * Version 1.1 with a permitted attribution clause; you may not use this * file except in compliance with the License. You may obtain a copy of * the License at http://www.openbravo.com/legal/license.html * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * The Original Code is Openbravo ERP. * The Initial Developer of the Original Code is Openbravo SLU * All portions are Copyright (C) 2001-2017 Openbravo SLU * All Rights Reserved. * Contributor(s): ______________________________________. ************************************************************************ */ package org.openbravo.translate; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import javax.servlet.ServletException; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.apache.xerces.parsers.SAXParser; import org.openbravo.database.CPStandAlone; import org.openbravo.database.SessionInfo; import org.openbravo.exception.NoConnectionAvailableException; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; /** * Looks for translatable elements in html, fo, srpt and jrxml files inserting them in * ad_textinterfaces table. * * @author Fernando Iriazabal **/ public class Translate extends DefaultHandler { private static CPStandAlone pool; private static final Pattern LETTER_PATTERN = Pattern.compile("[a-zA-Z]"); private static final List<String> translatableExtensions = Arrays.asList("html", "fo", "srpt", "jrxml"); private static final Logger log = Logger.getLogger(Translate.class); private XMLReader parser; private String extension; private String actualTag; private String actualFile; private String actualPrefix; private StringBuilder translationText; private int count = 0; private String moduleLang = ""; private String moduleID = ""; private Path moduleBasePath; private Connection conn; private boolean canTranslateModule = true; private static Map<String, List<TranslateData>> allLabels; private static HashSet<String> modsInDev = new HashSet<>(); private static void init(String xmlPoolFile) { pool = new CPStandAlone(xmlPoolFile); } private Translate() { } /** * @param _fileTermination * File extension to filter. */ public Translate(String _fileTermination) throws ServletException { extension = _fileTermination; boolean isHtml = extension.toLowerCase().endsWith("html"); if (isHtml) parser = new org.cyberneko.html.parsers.SAXParser(); else parser = new SAXParser(); parser.setEntityResolver(new LocalEntityResolver()); parser.setContentHandler(this); } /** * Command Line method. * * @param argv * List of arguments. There is 2 call ways, with 2 arguments; the first one is the * attribute to indicate if the AD_TEXTINTERFACES must be cleaned ("clean") and the * second one is the Openbravo.properties path. The other way is with more arguments, * where: 0- Openbravo.properties path. 1- Path where are the files to translate. */ public static void main(String argv[]) throws Exception { PropertyConfigurator.configure("log4j.lcf"); if (argv.length != 2) { log.error("Usage: Translate Openbravo.properties [clean|remove|sourceDir]"); log.error("Received: " + Arrays.asList(argv)); return; } init(argv[0]); Translate translate; switch (argv[1]) { case "clean": log.debug("clean AD_TEXTINTERFACES"); translate = new Translate(); translate.clean(); return; case "remove": log.debug("remove AD_TEXTINTERFACES"); translate = new Translate(); translate.remove(); return; } Path obPath = Paths.get(argv[1]).normalize(); TranslateData[] mods = TranslateData.getModulesInDevelopment(pool); for (TranslateData mod : mods) { modsInDev.add(mod.id); } for (TranslateData mod : mods) { Path path; if ("0".equals(mod.id)) { path = obPath.resolve("src"); } else { path = obPath.resolve(Paths.get("modules", mod.javapackage, "src")); if (!Files.exists(path)) { continue; } } log.info("Looking for translatable elements in " + mod.javapackage + " (" + mod.name + ")"); for (String extension : translatableExtensions) { translate = new Translate(extension); translate.moduleLang = mod.lang; translate.moduleID = mod.id; translate.moduleBasePath = path; translate.execute(); if (translate.count > 0) { log.info(" parsed " + translate.count + " " + extension + " files"); } if (!translate.canTranslateModule) { break; } } } if (mods.length == 0) { log.info("No modules in development to look for translatable elements."); } destroy(); } /** * Executes the clean of the AD_TEXTINTERFACES table. */ private void clean() { try { TranslateData.clean(pool); } catch (final Exception e) { log.error("clean error", e); } } private void remove() { try { int n = TranslateData.remove(pool); if (n > 0) { log.info("Removed " + n + " unused elements"); } } catch (final Exception e) { log.error("remove error", e); } } /** Looks for translatable elements for a given module and extension */ private void execute() throws IOException { final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:.*\\." + extension); Files.walkFileTree(moduleBasePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (matcher.matches(file)) { if (!canTranslateModule()) { log.error(" Module is not set as translatable or has not defined language, but has translatable elements"); log.error(" No translations will be inserted. Set the module as 'is translation requiered' and select a language"); log.error(" then execute translation again."); canTranslateModule = false; return FileVisitResult.TERMINATE; } parseFile(file); } return FileVisitResult.CONTINUE; } }); if (conn != null) { try { pool.releaseCommitConnection(conn); } catch (SQLException e) { log.error("Error commiting changes to database", e); } } } private boolean canTranslateModule() { return !(moduleLang == null || moduleLang.equals("")); } /** * Parse each file searching the text to translate. * * @param fileParsing * File to parse. */ private void parseFile(Path fileParsing) { actualFile = "/" + moduleBasePath.relativize(fileParsing).toString().replace("\\", "/"); log.debug("File: " + actualFile); try (InputStream in = Files.newInputStream(fileParsing); InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) { parser.parse(new InputSource(reader)); count++; } catch (final Exception e) { log.error("file: " + actualFile, e); } } /** * Parse each attribute of each element in the file. This method decides which ones must been * translated. * * @param amap * Attributes of the element. */ private void parseAttributes(Attributes amap) { String type = ""; String value = ""; for (int i = 0; i < amap.getLength(); i++) { String strAux = amap.getValue(i); if (amap.getQName(i).equalsIgnoreCase("type")) { type = strAux; } else if (amap.getQName(i).equalsIgnoreCase("value")) { value = strAux; } else if (amap.getQName(i).equalsIgnoreCase("onMouseOver")) { if (strAux.toLowerCase().startsWith("window.status='")) { int j = strAux.lastIndexOf("';"); int aux = j; while ((j != -1) && (aux = strAux.lastIndexOf("';", j - 1)) != -1) { j = aux; } translate(strAux.substring(15, j)); } } else if (amap.getQName(i).equalsIgnoreCase("alt")) { translate(strAux); } else if (amap.getQName(i).equalsIgnoreCase("title")) { translate(strAux); } } if (value != null && !value.equals("") && type.equalsIgnoreCase("button")) { translate(value); } } /** * The start of the document to translate. */ @Override public void startDocument() { } /** * The prefix mapping for the file. */ @Override public void startPrefixMapping(String prefix, String uri) { actualPrefix = " xmlns:" + prefix + "=\"" + uri + "\""; } /** * Method to know if a specific element in the file is parseable or not. * * @param tagname * Name of the element. * @return True if the element is parseable, false if not. */ private boolean isParseable(String tagname) { if (tagname.equalsIgnoreCase("script")) return false; else if (extension.equalsIgnoreCase("jrxml") && !tagname.equalsIgnoreCase("text") && !tagname.equalsIgnoreCase("textFieldExpression")) { return false; } return true; } /** * Start of an element of the file. When the parser finds a new element in the file, it calls to * this method. */ @Override public void startElement(String uri, String name, String qName, Attributes amap) { log.debug("startElement element name=" + qName + " actualtag" + actualTag + " trlTxt" + translationText); if (actualTag != null && isParseable(actualTag) && translationText != null) { translate(translationText.toString()); } translationText = null; parseAttributes(amap); if (actualPrefix != null && !actualPrefix.equals("")) { actualPrefix = ""; } actualTag = name.trim().toUpperCase(); } /** * End of an element of the file. When the parser finds the end of an element in the file, it * calls to this method. */ @Override public void endElement(String uri, String name, String qName) { log.debug("endElement : " + qName); if (isParseable(actualTag) && translationText != null) { translate(translationText.toString()); } translationText = null; actualTag = ""; } /** * This method is called by the parser when it finds any content between the start and end * element's tags. */ @Override public void characters(char[] ch, int start, int length) { final String chars = new String(ch, start, length); log.debug("characters: " + chars); if (translationText == null) translationText = new StringBuilder(); translationText.append(chars); } /** * This method is the one in charge of the translation of the found text. * * @param txt * String with the text to translate. */ private void translate(String txt) { translate(txt, false); } /** * This method is the one in charge of the translation of the found text. * * @param input * String with the text to translate. * @param isPartial * Indicates if the text passed is partial text or the complete one found in the element * content. */ private void translate(String input, boolean isPartial) { String txt = input.replace("\r", "").replace("\n", " ").replaceAll(" ( )+", " ").trim(); if (!isPartial && actualTag.equalsIgnoreCase("textFieldExpression")) { int pos = txt.indexOf("\""); while (pos != -1) { txt = txt.substring(pos + 1); pos = txt.indexOf("\""); if (pos != -1) { translate(txt.substring(0, pos), true); txt = txt.substring(pos + 1); } else break; pos = txt.indexOf("\""); } return; } boolean translatableTxt = !(txt.equals("") || txt.toLowerCase().startsWith("xx") || isNumeric(txt)); if (!translatableTxt) { return; } log.debug("Checking [" + txt + "] from file" + actualFile + " - language: " + moduleLang); TranslateData t = getLabel(txt); if (t != null) { if ("N".equals(t.tr) && t.module.equals(moduleID) && t.id != null) { try { TranslateData.update(getConnection(), pool, t.id); t.tr = "Y"; } catch (ServletException e) { log.error("Could not set label as used [" + txt + "]"); } } } else { createLabel(txt); } } /** Returns a suitable text interface element for the given txt or null if there is none. */ private TranslateData getLabel(String txt) { if (allLabels == null) { // lazy initialization: in case none of the modules in development has elements to translate // it won't be initialized initializeAllLabels(); } List<TranslateData> labels = allLabels.get(txt); if (labels == null) { return null; } TranslateData selected = null; for (TranslateData label : labels) { if (!moduleLang.equals(label.lang)) { continue; } if (actualFile.equals(label.filename)) { return label; } else if (label.filename == null || "".equals(label.filename)) { selected = label; } } return selected; } /** * Loads in memory all text interfaces. Typically this is faster than querying them each time a * translatable element is found in a file by reducing significantly the number of queries. */ private void initializeAllLabels() { TranslateData[] all; try { all = TranslateData.getTextInterfaces(pool); } catch (ServletException e) { throw new RuntimeException("Error loading text interfaces from DB", e); } allLabels = new HashMap<>(all.length); String currentTxt = null; List<TranslateData> currentList = null; for (TranslateData label : all) { if (!label.text.equals(currentTxt)) { currentTxt = label.text; currentList = new ArrayList<>(); allLabels.put(currentTxt, currentList); } currentList.add(label); } } private void createLabel(String txt) { try { TranslateData.insert(getConnection(), pool, txt, actualFile, moduleID); log.info(" New label found [" + txt + "] in " + actualFile); } catch (ServletException e) { log.error(" Could not insert label [" + txt + "]", e); } List<TranslateData> labelsForTxt = allLabels.get(txt); if (labelsForTxt == null) { labelsForTxt = new ArrayList<>(); allLabels.put(txt, labelsForTxt); } TranslateData newElement = new TranslateData(); newElement.text = txt; newElement.filename = actualFile; newElement.lang = moduleLang; labelsForTxt.add(newElement); } private Connection getConnection() { if (conn == null) { try { conn = pool.getTransactionConnection(); } catch (NoConnectionAvailableException | SQLException e) { throw new RuntimeException("Could not get a DB connection", e); } } return conn; } /** * To know if a text is numeric or not. * * @param ini * String with the text. * @return True if has no letter in the text or false if has any letter. */ private static boolean isNumeric(String ini) { return !LETTER_PATTERN.matcher(ini).find(); } /** Closes database connection. */ private static void destroy() { // remove cached connection from thread local SessionInfo.init(); pool.destroy(); } }
31.362782
128
0.630986
a915564a5ad1ea4e2223a48933c934d0614a730c
1,468
package uil2012.district1.part2; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class Bus { private static Scanner in; public static void main(String[] args) throws FileNotFoundException { in = new Scanner(new File("data/uil2012/bus.dat")); int buses = in.nextInt(); in.nextLine(); for (int i = 0; i < buses; i++) { String[] bus = in.nextLine().split(" "); int[] busNums = new int[bus.length]; for (int j = 0; j < bus.length; j++) { busNums[j] = Integer.parseInt(bus[j]); } ArrayList<Integer> list = new ArrayList<Integer>(); list.add(busNums[0]); for (int k = 1; k < busNums.length-1; k += 2) { int sum = list.get(k/2) + busNums[k] + busNums[k + 1]; list.add(sum); } int smol = list.get(0); // no 'a's allowed for(int x : list) { if(x < smol) { smol = x; } } for(int c = 0; c < list.size(); c++) { if(list.get(c) == smol) { char pos = (char)('A' + c); System.out.print(pos); System.out.print(" "); } } System.out.println(smol); } } }
32.622222
74
0.444823
638141c8123ad79f7de22115abc2aacd0c7b1d55
912
package org.beigesoft.uml.service.persist.xmllight; import java.util.List; import org.beigesoft.pojo.HasNameEditable; import org.beigesoft.uml.pojo.UseCaseExtended; public class SaxUseCaseExtendedFiller<P extends UseCaseExtended> extends SaxUseCaseFiller<P> { public SaxUseCaseExtendedFiller(String namePersistable, List<String> pathCurrent) { super(namePersistable, pathCurrent); } @Override public boolean fillModel(String elementName, String elementValue) { if(isConsumableForElement(elementName)) { if(super.fillModel(elementName, elementValue)) {//shape's width height, adjust min size isRectangle return true; } if(SrvSaveXmlUseCaseExtended.NAMEXML_EXTENTIONPOINT.equals(elementName)) { HasNameEditable extPoint = new HasNameEditable(elementValue); getModel().getExtentionPoints().add(extPoint); } } return false; } }
32.571429
106
0.746711
83db61b27521e2afee52f5db1ee6d90e4e771224
159
package gg.projecteden.nexus.features.discord.commands.justice.deactivate; public class UnFreezeDiscordCommand extends _PunishmentDeactivateDiscordCommand {}
39.75
82
0.880503
24cbbd38c77875d5a9416b7e66787f6adc3d191f
248
package com.jees.core.database.dao; import com.jees.core.database.support.AbsRedisDao; import lombok.extern.log4j.Log4j2; import org.springframework.stereotype.Service; @Log4j2 @Service public class RedisDao<ID, T> extends AbsRedisDao<ID, T> { }
22.545455
57
0.798387
21bc0a7742f13b24803c7b9dbb23adaf9b5b68e5
2,877
//package com.dxn; // //import java.util.Collections; // //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.boot.CommandLineRunner; //import org.springframework.security.crypto.password.PasswordEncoder; //import org.springframework.stereotype.Component; // //import com.dxn.model.Course; //import com.dxn.model.Role; //import com.dxn.model.RoleName; //import com.dxn.model.Topic; //import com.dxn.model.User; //import com.dxn.repository.CourseRepository; //import com.dxn.repository.RoleRepository; //import com.dxn.repository.TopicRepository; //import com.dxn.repository.UserRepository; // //@Component //public class DbInitializer implements CommandLineRunner { // // @Autowired // private CourseRepository courseRepository; // // @Autowired // private RoleRepository roleRepository; // // @Autowired // private TopicRepository topicRepository; // // @Autowired // private UserRepository userRepository; // // @Autowired // private PasswordEncoder passwordEncoder; // // @Override // public void run(String... args) throws Exception { // this.roleRepository.deleteAll(); // this.userRepository.deleteAll(); // this.topicRepository.deleteAll(); // this.courseRepository.deleteAll(); // // Role adminRole = roleRepository.save(new Role(RoleName.ROLE_ADMIN)); // Role userRole = roleRepository.save(new Role(RoleName.ROLE_USER)); // // String password = passwordEncoder.encode("password"); // // userRepository.save(new User("admin", password, Collections.singleton(adminRole))); // userRepository.save(new User("user", password, Collections.singleton(userRole))); // // Topic programming = topicRepository.save(new Topic("Programming", "Programming Description")); // Topic english = topicRepository.save(new Topic("English", "English Description")); // Topic math = topicRepository.save(new Topic("Math", "Math Description")); // Topic science = topicRepository.save(new Topic("Science", "Science Description")); // // courseRepository.save(new Course("Java", "Java Description", programming)); // courseRepository.save(new Course("C++", "C++ Description", programming)); // courseRepository.save(new Course("Literature", "Literature Description", english)); // courseRepository.save(new Course("Shakespeare", "Shakespeare Description", english)); // courseRepository.save(new Course("Calculus I", "Calculus I Description", math)); // courseRepository.save(new Course("Calculus II", "Cal II Description", math)); // courseRepository.save(new Course("Cal III", "Cal III Description", math)); // courseRepository.save(new Course("Physics", "Physics Description", science)); // courseRepository.save(new Course("Chem", "Chem Description", science)); // courseRepository.save(new Course("Bio", "Bio Description", science)); // // System.out.println("-- Database has been initialized"); // } //}
39.958333
98
0.738964
2f075dcadff35f52cf31ecf2095db80ebe759745
6,086
package de.main; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import de.model.Apdex; import de.model.Bucket; import de.model.Sample; import de.model.SampleError; /** * Calculates the Apdex Value according to the formula: * APDEX = (SATISFIED + 0,5 * TOLERATED) / TOTAL SAMPLES * * It also provides an option to divide the tolerated-frustrated * interval into more buckets as improvement to gain a more granular value. * @author Michael Wurst */ public class APDEXCalculator { private int frustratedValueF; private int toleratedValueT; private int bucketCountofInterval_T_F = 1; public APDEXCalculator() { } public APDEXCalculator(int toleratedValueT) { this.toleratedValueT = toleratedValueT; frustratedValueF = 4 * toleratedValueT; } public APDEXCalculator(int toleratedValueT, int frustradedValueF) { this.toleratedValueT = toleratedValueT; this.frustratedValueF = frustradedValueF; } /** * Calculates the Apdex according to the specified settings and returns * the results in an new object. * @param sampleList * @return Apdex Object */ public Apdex calculate(List<Sample> sampleList) { Apdex apdex = new Apdex(); int totalSamplesCount = sampleList.size(); int satisfiedCount = 0; int toleratedCount = 0; int frustradedCount = 0; int totalErrorCount = 0; Map<String, SampleError> errorMap = new HashMap<>(); if (bucketCountofInterval_T_F == 1) { for (Sample temp : sampleList) { if(temp.getErrorCount() == 1){ totalErrorCount++; SampleError error = new SampleError(); if(errorMap.containsKey(temp.getResponseCode())){ error = errorMap.get(temp.getResponseCode()); int count = error.getErrorCount() + 1; error.setErrorCount(count); errorMap.put(temp.getResponseCode(), error); } else { error.setErrorCode(temp.getResponseCode()); error.setErrorMsg(temp.getResponseMessage()); error.setErrorCount(temp.getErrorCount()); errorMap.put(temp.getResponseCode(), error); } } int elapsedTime = temp.getElapsedTime(); if (elapsedTime < toleratedValueT) { satisfiedCount++; } else { if (elapsedTime < frustratedValueF) { toleratedCount++; } else { frustradedCount++; } } } // calculate APDEX value double roundApdex = (double)(satisfiedCount + toleratedCount / 2) / totalSamplesCount; apdex.setApdexValue((double)Math.round(roundApdex * 10000) /10000); } else { int[] tolBuckets = new int[bucketCountofInterval_T_F]; int intervallT_F = frustratedValueF - toleratedValueT; double bucketSize = intervallT_F / bucketCountofInterval_T_F; for (Sample temp : sampleList) { int elapsedTime = temp.getElapsedTime(); if(temp.getErrorCount() == 1){ totalErrorCount++; SampleError error = new SampleError(); if(errorMap.containsKey(temp.getResponseCode())){ error = errorMap.get(temp.getResponseCode()); int count = error.getErrorCount() + 1; error.setErrorCount(count); errorMap.put(temp.getResponseCode(), error); } else { error.setErrorCode(temp.getResponseCode()); error.setErrorMsg(temp.getResponseMessage()); error.setErrorCount(temp.getErrorCount()); errorMap.put(temp.getResponseCode(), error); } } if (elapsedTime < toleratedValueT) { satisfiedCount++; } else { if (elapsedTime < frustratedValueF) { toleratedCount++; // Tolerated Buckets with sample counts double i = bucketSize; int bucketNumber = 0; // find the right bucket while(i <= intervallT_F && elapsedTime < frustratedValueF){ if(elapsedTime < (toleratedValueT+i)){ if(bucketNumber < bucketCountofInterval_T_F){ tolBuckets[bucketNumber] = tolBuckets[bucketNumber] + 1; break; } else { // if you've reached the upper limit, add to last possible bucket tolBuckets[bucketCountofInterval_T_F-1] += 1; break; } } i = i + bucketSize; bucketNumber++; } } else { frustradedCount++; } } } double toleratedValue = 0; int weight = 0; List<Bucket> bucketList = new ArrayList<>(); double minValue = toleratedValueT; double maxValue = 0; // bucketCountofInterval_T_F + 1, because 'Satisfied bucket' is has a the most weight with 0 for (int i = 0; i < tolBuckets.length; i++) { maxValue = minValue + bucketSize; Bucket bucket = new Bucket(); bucket.setBucketNumber(i+1); bucket.setTotalSamples(tolBuckets[i]); bucket.setBucketSize(bucketSize); bucket.setMinValue(minValue); bucket.setMaxValue(maxValue); bucketList.add(bucket); toleratedValue = toleratedValue + ((tolBuckets.length - weight) * tolBuckets[i]) / (bucketCountofInterval_T_F + 1); weight++; minValue = maxValue; } apdex.setToleratedBucketsCount(bucketCountofInterval_T_F); double roundApdex = (double)(satisfiedCount + toleratedValue)/totalSamplesCount; apdex.setApdexValue((double)Math.round(roundApdex * 10000) /10000); apdex.setToleratedBuckets(bucketList); } apdex.setFrustradedCount(frustradedCount); apdex.setSatisfiedCount(satisfiedCount); apdex.setToleratedCount(toleratedCount); apdex.setTotalSamplesCount(totalSamplesCount); apdex.setTotalErrorCount(totalErrorCount); apdex.setOccurredErrors(errorMap); return apdex; } public int getBucketCountofInterval_T_F() { return bucketCountofInterval_T_F; } public void setBucketCountofInterval_T_F(int bucketCountofInterval_T_F) { this.bucketCountofInterval_T_F = bucketCountofInterval_T_F; } public int getFrustradedValueF() { return frustratedValueF; } public void setFrustradedValueF(int frustradedValueF) { this.frustratedValueF = frustradedValueF; } public int getToleratedValueT() { return toleratedValueT; } public void setToleratedValueT(int toleratedValueT) { this.toleratedValueT = toleratedValueT; } }
30.582915
96
0.694052
724177818fb0d1f255c2bb1817993e8cddfb9d80
934
/* * Lu.java * <p> * (C) 2019 by Damir Cavar * * NLP-Lab code base. */ package org.nlplab.jsonnlp; import com.fasterxml.jackson.annotation.JsonProperty; public class Lu { @JsonProperty("name") private String name; @JsonProperty("definition") private String definition; @JsonProperty("pos") private String pos; @JsonProperty("name") public String getName() { return name; } @JsonProperty("name") public void setName(String name) { this.name = name; } @JsonProperty("pos") public String getPos() { return pos; } @JsonProperty("pos") public void setPos(String pos) { this.pos = pos; } @JsonProperty("definition") public String getDefinition() { return definition; } @JsonProperty("definition") public void setDefinition(String definition) { this.definition = definition; } }
17.296296
53
0.610278
f25030c0fbabdf88555a2d79d2d944725eee40e9
867
package com.android.billingclient.api; import android.content.Context; import android.content.IntentFilter; /* access modifiers changed from: package-private */ public final class d0 { private final Context a; /* renamed from: b reason: collision with root package name */ private final c0 f2722b; d0(Context context, j jVar) { this.a = context; this.f2722b = new c0(this, jVar, null); } /* access modifiers changed from: package-private */ public final j a() { return c0.a(this.f2722b); } /* access modifiers changed from: package-private */ public final void b() { this.f2722b.a(this.a); } /* access modifiers changed from: package-private */ public final void c() { this.f2722b.a(this.a, new IntentFilter("com.android.vending.billing.PURCHASES_UPDATED")); } }
26.272727
97
0.655133
78998963af475b887e770e81f1a44aaebf95fde8
386
package com.learn.springboot.extension; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component @Slf4j public class MyCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { log.info("CommandLineRunner is running"); } }
24.125
63
0.777202
b2f2084b153bc0a5d63ab616b17da0fa273b51dd
4,439
package seedu.address.logic.commands.storage; import static org.junit.jupiter.api.Assertions.assertEquals; import static seedu.address.testutil.TypicalModulesInfo.getTypicalModulesInfo; import static seedu.address.testutil.TypicalStudyPlans.getTypicalModulePlanner; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import seedu.address.logic.commands.CommandResult; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.UserPrefs; import seedu.address.model.semester.Semester; import seedu.address.model.semester.SemesterName; import seedu.address.model.semester.UniqueSemesterList; import seedu.address.model.studyplan.StudyPlan; import seedu.address.testutil.StudyPlanBuilder; /** * Contains integration tests (interaction with the Model) for {@code DeleteSemesterCommand}. */ public class DeleteSemesterCommandTest { private Model model; @BeforeEach public void setUp() { model = new ModelManager(getTypicalModulePlanner(), new UserPrefs(), getTypicalModulesInfo()); UniqueSemesterList semesters = new UniqueSemesterList(); semesters.add(new Semester(SemesterName.Y1S1)); semesters.add(new Semester(SemesterName.Y1ST1)); StudyPlan studyPlan = new StudyPlanBuilder().withSemesters(semesters).build(); model.addStudyPlan(studyPlan); model.activateStudyPlan(studyPlan.getIndex()); model.addModule("CS1101S", SemesterName.Y1S1); } @Test public void execute_deleteMainstreamSemester_success() throws CommandException { // a mainstream semester is a non-special term or non-Year 5 SemesterName semesterName = SemesterName.Y1S1; Model expectedModel = generateExpectedModel(semesterName); expectedModel.deleteAllModulesInSemester(semesterName); DeleteSemesterCommand command = new DeleteSemesterCommand(semesterName); CommandResult expectedResult = new CommandResult(String.format(DeleteSemesterCommand.MESSAGE_DELETE_MAINSTREAM_SEMESTER_SUCCESS, semesterName)); CommandResult actualResult = command.execute(model); // check command result assertEquals(expectedResult, actualResult); // check semesters UniqueSemesterList expectedSemesters = expectedModel.getActiveStudyPlan().getSemesters(); UniqueSemesterList actualSemesters = model.getActiveStudyPlan().getSemesters(); assertEquals(expectedSemesters, actualSemesters); } @Test public void execute_deleteNonMainstreamSemester_success() throws CommandException { // a non-mainstream semester is a special term or a Year 5 semester SemesterName specialSemesterName = SemesterName.Y1ST1; Model expectedModel = generateExpectedModel(specialSemesterName); expectedModel.deleteSemester(specialSemesterName); DeleteSemesterCommand command = new DeleteSemesterCommand(specialSemesterName); CommandResult expectedResult = new CommandResult(String.format(DeleteSemesterCommand.MESSAGE_DELETE_SPECIAL_SEMESTER_SUCCESS, specialSemesterName)); CommandResult actualResult = command.execute(model); // check command result assertEquals(expectedResult, actualResult); // check semesters UniqueSemesterList expectedSemesters = expectedModel.getActiveStudyPlan().getSemesters(); UniqueSemesterList actualSemesters = model.getActiveStudyPlan().getSemesters(); assertEquals(expectedSemesters, actualSemesters); } /** * Generates an expected model for testing, given a semester name. * @param semesterName can be mainstream or non-mainstream * @return expected model which will be used for testing */ private Model generateExpectedModel(SemesterName semesterName) { Model expectedModel = new ModelManager(getTypicalModulePlanner(), new UserPrefs(), getTypicalModulesInfo()); UniqueSemesterList semesters = new UniqueSemesterList(); semesters.add(new Semester(semesterName)); StudyPlan studyPlan = new StudyPlanBuilder().withSemesters(semesters).build(); expectedModel.addStudyPlan(studyPlan); expectedModel.activateStudyPlan(studyPlan.getIndex()); return expectedModel; } }
44.39
116
0.747466
29361c14448d1bfc459d97400af837348a72b937
2,108
package ProblemDomain; import java.io.Serializable; import java.math.BigInteger; import java.security.SecureRandom; import java.time.LocalDate; import java.util.Random; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import DataAccessObjects.TokenDAO; @XmlRootElement(name = "token") @Entity(name = "token") public class Token implements Serializable { private static final long serialVersionUID = 1L; @Id // signifies the primary key @Column(name = "token_id", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO) private long tokenID; @Column(name = "token", nullable = false, length = 40) private String token; @Column(name = "expire_date") private LocalDate expireDate; @ManyToOne(optional = false) @JoinColumn(name = "eventPlanner_id", referencedColumnName = "eventPlanner_id") private EventPlanner planner; public Token() { }; public Token(EventPlanner planner) { setEventPlanner(planner); Random random = new SecureRandom(); String token = new BigInteger(130, random).toString(32); setToken(token); setExpireDate(LocalDate.now()); } public long getTokenID() { return this.tokenID; } public void setTokenID(long tokenID) { this.tokenID = tokenID; } public String getToken() { return this.token; } @XmlElement public void setToken(String token) { this.token = token; } public LocalDate getExpireDate() { return this.expireDate; } @XmlElement public void setExpireDate(LocalDate expireDate) { this.expireDate = expireDate; } public EventPlanner getEventPlanner() { return this.planner; } @XmlElement public void setEventPlanner(EventPlanner planner) { this.planner = planner; } public Boolean validate() { return LocalDate.now().equals(getExpireDate()); } public void save() { TokenDAO.saveToken(this); } }
22.425532
80
0.755693
69c7f5f1d3ed49322d34b845ea653034d01fff00
3,633
package co.dporn.gmd.client.views; import java.math.BigDecimal; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; import co.dporn.gmd.client.presenters.ContentPresenter; import co.dporn.gmd.client.presenters.ContentPresenter.VideoCardView; import gwt.material.design.client.ui.MaterialCard; import gwt.material.design.client.ui.MaterialLabel; import gwt.material.design.client.ui.MaterialVideo; import gwt.material.design.client.ui.animate.MaterialAnimation; import gwt.material.design.client.ui.animate.Transition; public class VideoCardUi extends Composite implements VideoCardView, CanBeDeleted { @UiField VoteBarUI voteBarUi; @UiField protected MaterialVideo videoEmbedUrl; @UiField protected MaterialLabel authorName; @UiField protected MaterialLabel authorBlurb; @UiField protected MaterialCard card; @UiField protected DpornLink viewLink; @UiField protected DpornLink viewChannel; private int showDelay; private static VideoCardUiUiBinder uiBinder = GWT.create(VideoCardUiUiBinder.class); interface VideoCardUiUiBinder extends UiBinder<Widget, VideoCardUi> { } public VideoCardUi() { initWidget(uiBinder.createAndBindUi(this)); } @Override protected void onLoad() { super.onLoad(); MaterialAnimation animation = new MaterialAnimation(); animation.setTransition(Transition.ZOOMIN); animation.setDelay(0); animation.setDuration(250 + showDelay); animation.animate(card); } @Override public void setImageUrl(String url) { // do nothing } @Override public void setAvatarUrl(String url) { // avatarImage.setUrl(url); } @Override public void setDisplayName(String name) { authorName.setText(name); } @Override public void setTitle(String blurb) { authorBlurb.setText(blurb); } @Override public void setShowDelay(int showDelay) { this.showDelay = showDelay; } @Override public void bindPresenter(ContentPresenter presenter) { // TODO Auto-generated method stub } @Override public void unbindPresenter() { // TODO Auto-generated method stub } @Override public void setVideoEmbedUrl(String url) { videoEmbedUrl.setUrl(url); } @Override public void setViewLink(String linkUrl) { viewLink.setHref(linkUrl); } @Override public void setChannelLink(String linkUrl) { viewChannel.setHref(linkUrl); } @Override public void setChannelLinkVisible(boolean visible) { viewChannel.setVisible(visible); } @Override public void setViewLinkVisible(boolean visible) { viewLink.setVisible(visible); } @Override public void setDeleted(boolean deleted) { if (deleted) { MaterialAnimation animation = new MaterialAnimation(); animation.setTransition(Transition.ZOOMOUT); animation.setDelay(250); animation.setDuration(250 + showDelay); animation.animate(card); animation.animate(() -> removeFromParent()); } } @Override public void setEarnings(BigDecimal earnings) { voteBarUi.setEarnings(earnings); } @Override public void setNetVoteCount(long netVoteCount) { voteBarUi.setNetVoteCount(netVoteCount); } @Override public void setVotedValue(int amount) { voteBarUi.setVotedValue(amount); } @Override public HandlerRegistration setUpvoteHandler(ClickHandler handler) { return voteBarUi.setUpvoteHandler(handler); } @Override public int getVotedValue() { return voteBarUi.getVotedValue(); } }
22.849057
85
0.774291
22a737335ac591d3b186fb59b26d5c8cd8bfd148
1,489
package uk.ac.ox.well.cortexjdk.utils.alignment.pairwise; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.reference.FastaSequenceFile; import htsjdk.samtools.reference.ReferenceSequence; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by kiran on 29/09/2017. */ public class TestBwaAligner { @Test public void testAlignment() { String ref = "testdata/two_short_contigs.fa"; Map<String, String> expectedAlignments = new HashMap<>(); expectedAlignments.put("TTCTGTATCGTATGCTCTGAATAAAAATCGTGGCCCTATTTCGTATAGT", "unknown\t0\t1\t0\t60\t49M\t*\t0\t0\tTTCTGTATCGTATGCTCTGAATAAAAATCGTGGCCCTATTTCGTATAGT\t*\tNM:i:0"); expectedAlignments.put("GGGCCGCGCCTATTATGGGCTTCTCTCTGAGTACTGGTCATGTAGTTGCTGTAGTCGTAGTGTCGTGGCCCCCCAGT", "unknown\t0\t2\t0\t60\t77M\t*\t0\t0\tGGGCCGCGCCTATTATGGGCTTCTCTCTGAGTACTGGTCATGTAGTTGCTGTAGTCGTAGTGTCGTGGCCCCCCAGT\t*\tNM:i:0"); BwaAligner ba = new BwaAligner(ref); FastaSequenceFile fa = new FastaSequenceFile(new File(ref), true); ReferenceSequence rseq; while ((rseq = fa.nextSequence()) != null) { List<SAMRecord> alignments = ba.align(rseq.getBaseString()); for (SAMRecord sr : alignments) { Assert.assertEquals(expectedAlignments.get(sr.getReadString()), sr.getSAMString().trim()); } } ba.close(); } }
37.225
240
0.719275
362a2390565df5153444aa9fd2b3afb5c5932c14
921
package com.jpeony.sunflower.remoting; import com.jpeony.sunflower.remoting.exception.RemotingConnectException; import com.jpeony.sunflower.remoting.exception.RemotingSendRequestException; import com.jpeony.sunflower.remoting.exception.RemotingTimeoutException; import com.jpeony.sunflower.remoting.exception.RemotingTooMuchRequestException; import com.jpeony.sunflower.remoting.protocol.RemotingCommand; /** * @author yihonglei */ public interface RemotingClient extends RemotingService { /** * @param addr Request ip and port * @param request Request object * @param timeoutMillis Message sending timeout */ void invokeOneway(final String addr, final RemotingCommand request, final long timeoutMillis) throws InterruptedException, RemotingConnectException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException; }
41.863636
99
0.789359
c74d58ac2bdc0bd443ee9c5edcd7895c0c8e3435
11,377
/** * 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.fineract.portfolio.collateralmanagement.api; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.parameters.RequestBody; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import java.util.Collection; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriInfo; import org.apache.fineract.commands.domain.CommandWrapper; import org.apache.fineract.commands.service.CommandWrapperBuilder; import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService; import org.apache.fineract.infrastructure.codes.service.CodeValueReadPlatformService; import org.apache.fineract.infrastructure.core.api.ApiRequestParameterHelper; import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext; import org.apache.fineract.organisation.monetary.data.CurrencyData; import org.apache.fineract.organisation.monetary.service.CurrencyReadPlatformService; import org.apache.fineract.portfolio.collateralmanagement.data.CollateralManagementData; import org.apache.fineract.portfolio.collateralmanagement.service.ClientCollateralManagementReadPlatformService; import org.apache.fineract.portfolio.collateralmanagement.service.CollateralManagementReadPlatformService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Path("/collateral-management") @Component @Scope("singleton") @Tag(name = "Collateral Management", description = "Collateral Management is for managing collateral operations") public class CollateralManagementApiResource { private final DefaultToApiJsonSerializer<CollateralManagementData> apiJsonSerializerService; private final DefaultToApiJsonSerializer<CurrencyData> apiJsonSerializerServiceForCurrency; private final ApiRequestParameterHelper apiRequestParameterHelper; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; private final PlatformSecurityContext context; private final CodeValueReadPlatformService codeValueReadPlatformService; private final CollateralManagementReadPlatformService collateralManagementReadPlatformService; private final String collateralReadPermission = "COLLATERAL_PRODUCT"; private final ClientCollateralManagementReadPlatformService clientCollateralManagementReadPlatformService; private final CurrencyReadPlatformService currencyReadPlatformService; @Autowired public CollateralManagementApiResource(final DefaultToApiJsonSerializer<CollateralManagementData> apiJsonSerializerService, final ApiRequestParameterHelper apiRequestParameterHelper, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, final PlatformSecurityContext context, final CodeValueReadPlatformService codeValueReadPlatformService, final CollateralManagementReadPlatformService collateralManagementReadPlatformService, final ClientCollateralManagementReadPlatformService clientCollateralManagementReadPlatformService, final CurrencyReadPlatformService currencyReadPlatformService, final DefaultToApiJsonSerializer<CurrencyData> apiJsonSerializerServiceForCurrency) { this.apiJsonSerializerService = apiJsonSerializerService; this.apiRequestParameterHelper = apiRequestParameterHelper; this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; this.context = context; this.codeValueReadPlatformService = codeValueReadPlatformService; this.collateralManagementReadPlatformService = collateralManagementReadPlatformService; this.clientCollateralManagementReadPlatformService = clientCollateralManagementReadPlatformService; this.currencyReadPlatformService = currencyReadPlatformService; this.apiJsonSerializerServiceForCurrency = apiJsonSerializerServiceForCurrency; } @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Operation(summary = "Create a new collateral", description = "Collateral Creation") @RequestBody(required = true, content = @Content(schema = @Schema(implementation = CollateralManagementApiResourceSwagger.PostCollateralManagementProductRequest.class))) @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = CollateralManagementApiResourceSwagger.PostCollateralManagementProductResponse.class))) }) public String createCollateral(@Parameter(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandWrapper = new CommandWrapperBuilder().createCollateral().withJson(apiRequestBodyAsJson).build(); final CommandProcessingResult commandProcessingResult = this.commandsSourceWritePlatformService.logCommandSource(commandWrapper); return this.apiJsonSerializerService.serialize(commandProcessingResult); } @GET @Path("{collateralId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Operation(summary = "Get Collateral", description = "Fetch Collateral") @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = CollateralManagementApiResourceSwagger.GetCollateralManagementsResponse.class))) }) public String getCollateral(@PathParam("collateralId") @Parameter(description = "collateralId") final Long collateralId, @Context final UriInfo uriInfo) { this.context.authenticatedUser() .validateHasReadPermission(CollateralManagementJsonInputParams.COLLATERAL_PRODUCT_READ_PERMISSION.getValue()); final CollateralManagementData collateralManagementData = this.collateralManagementReadPlatformService .getCollateralProduct(collateralId); return this.apiJsonSerializerService.serialize(collateralManagementData); } @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Operation(summary = "Get All Collaterals", description = "Fetch all Collateral Products") @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = CollateralManagementApiResourceSwagger.GetCollateralManagementsResponse.class)))) }) public String getAllCollaterals(@Context final UriInfo uriInfo) { this.context.authenticatedUser() .validateHasReadPermission(CollateralManagementJsonInputParams.COLLATERAL_PRODUCT_READ_PERMISSION.getValue()); Collection<CollateralManagementData> collateralManagementDataList = this.collateralManagementReadPlatformService .getAllCollateralProducts(); return this.apiJsonSerializerService.serialize(collateralManagementDataList); } @GET @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Operation(summary = "Get Collateral Template", description = "Get Collateral Template") @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = CollateralManagementApiResourceSwagger.GetCollateralProductTemplate.class)))) }) public String getCollateralTemplate(@Context final UriInfo uriInfo) { Collection<CurrencyData> currencyDataCollection = this.currencyReadPlatformService.retrieveAllPlatformCurrencies(); return this.apiJsonSerializerServiceForCurrency.serialize(currencyDataCollection); } @PUT @Path("{collateralId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Operation(summary = "Update Collateral", description = "Update Collateral") @RequestBody(required = true, content = @Content(schema = @Schema(implementation = CollateralManagementApiResourceSwagger.PutCollateralProductRequest.class))) @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = CollateralManagementApiResourceSwagger.PutCollateralProductResponse.class))) }) public String updateCollateral(@PathParam("collateralId") @Parameter(description = "collateralId") final Long collateralId, @Parameter(hidden = true) final String jsonBody) { final CommandWrapper commandWrapper = new CommandWrapperBuilder().updateCollateralProduct(collateralId).withJson(jsonBody).build(); final CommandProcessingResult commandProcessingResult = this.commandsSourceWritePlatformService.logCommandSource(commandWrapper); return this.apiJsonSerializerService.serialize(commandProcessingResult); } @DELETE @Path("{collateralId}") @Produces({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON }) @Operation(summary = "Delete a Collateral", description = "Delete Collateral") @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = CollateralManagementApiResourceSwagger.DeleteCollateralProductResponse.class))) }) public String deleteCollateral(@PathParam("collateralId") @Parameter(description = "collateralId") final Long collateralId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteCollateralProduct(collateralId).build(); final CommandProcessingResult commandProcessingResult = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.apiJsonSerializerService.serialize(commandProcessingResult); } }
60.195767
225
0.795201
6947c0d98f86d5580e196c4225a36db363da40b6
182
package com.jota.patterns.factory; import com.jota.patterns.model.Triangle; public interface TriangleFactoryMethod { Triangle createTriangle(int sideA, int sideB, int sideC); }
20.222222
59
0.796703
4b5d0d609450706a41297cc25894be49bef42dcf
250
package edu.iit.hawk.atolentino.request_information_processing.boundaries; public abstract class RequestInformation { public abstract boolean isNill(); public Integer getAid() { return null; } public Integer getRid() { return null; } }
17.857143
74
0.756
021a3776e81db5cc85ce27b04c7b48d62d27b22a
8,407
package com.antbrains.wordseg; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import com.antbrains.crf.BESB1B2MTagConvertor; import com.antbrains.crf.CrfModel; import com.antbrains.crf.SgdCrf; import com.antbrains.crf.TagConvertor; import com.antbrains.crf.hadoop.FileTools; import com.antbrains.wordseg.Token.Type; import com.antbrains.wordseg.luceneanalyzer.CharTermAttribute; import com.antbrains.wordseg.luceneanalyzer.OffsetAttribute; import com.antbrains.wordseg.luceneanalyzer.StandardTokenizer; import com.antbrains.wordseg.luceneanalyzer.TypeAttribute; import com.antbrains.wordseg.luceneanalyzer.Version; public class ChineseSegmenter { private ChineseSegmenter(){ try{ InputStream is = ChineseSegmenter.class.getResourceAsStream("/crf.model"); if(is==null) throw new RuntimeException("can't find /crf.model"); model=SgdCrf.loadModel(is); is.close(); is = ChineseSegmenter.class.getResourceAsStream("/segdict.txt"); List<String> words=FileTools.read2List(is, "UTF8"); this.mmseg=new MMSeg(words); this.rmmseg=new RMMSeg(words); }catch(Exception e){ } } private static ChineseSegmenter instance; static{ instance=new ChineseSegmenter(); } public static ChineseSegmenter getInstance(){ return instance; } public MMSeg getMmseg() { return mmseg; } public RMMSeg getRmmseg() { return rmmseg; } private MMSeg mmseg; private RMMSeg rmmseg; private TagConvertor tc = new BESB1B2MTagConvertor(); private CrfModel model; public CrfModel getModel() { return model; } public List<List<Token>> processByLuceneAnalyzer(String sen) { List<List<Token>> result = new ArrayList<List<Token>>(); StandardTokenizer tokenizer = new StandardTokenizer(Version.LUCENE_29, new StringReader(sen)); CharTermAttribute termAtt = (CharTermAttribute) tokenizer.addAttribute(CharTermAttribute.class); OffsetAttribute offsetAtt = (OffsetAttribute) tokenizer.addAttribute(OffsetAttribute.class); TypeAttribute typeAtt = (TypeAttribute) tokenizer.addAttribute(TypeAttribute.class); List<Token> subSen = new ArrayList<Token>(); try { int lastPos = 0; boolean lastIsCn = false; while (tokenizer.incrementToken()) { int start = offsetAtt.startOffset(); int end = offsetAtt.endOffset(); if (lastPos < start) {// 被StandardAnalyzer扔掉的都认为是标点,不用参与分词 for (int i = lastPos; i < start; i++) { if (subSen.size() > 0) { result.add(subSen); } subSen = new ArrayList<Token>(); subSen.add(new Token(null, sen, i, i + 1, Type.PUNCT)); } lastIsCn = false; } lastPos = end; String wordType = typeAtt.type(); Token token = new Token(sen, start, end); if (wordType.equals("<IDEOGRAPHIC>")) {// 汉字 token.setType(Type.CWORD); if (!lastIsCn) { if (subSen.size() > 0) { result.add(subSen); subSen = new ArrayList<Token>(); } lastIsCn = true; } } else { lastIsCn = false; if (subSen.size() > 0) { result.add(subSen); } subSen = new ArrayList<Token>(); if (wordType.equals("<ALPHANUM>")) { token.setType(Type.ALPHA); } else if (wordType.equals("<NUM>")) { token.setType(Type.NUMBER); } } subSen.add(token); } if (subSen.size() > 0) { result.add(subSen); } } catch (IOException e) { e.printStackTrace(); } return result; } public List<Token> seg(String sen) { List<Token> result = new ArrayList<Token>(); // 先用StandardAnalyzer处理一遍 List<List<Token>> subSens = this.processByLuceneAnalyzer(sen); for (List<Token> subSen : subSens) { if (subSen.size() < 2) { result.addAll(subSen); } else { for (Token tk : this.segmentSentence(subSen)) { result.add(tk); } } } return result; } private String tokens2String(List<Token> tokens) { StringBuilder sb = new StringBuilder(); for (Token tk : tokens) { sb.append(tk.getNormalizedText()); } return sb.toString(); } private boolean isEqual(List<Token> tks1, List<Token> tks2) { if (tks1.size() != tks2.size()) return false; for (int i = 0; i < tks1.size(); i++) { if (tks1.get(i).getLength() != tks2.get(i).getLength()) { return false; } } return true; } private List<int[]> compareResult(List<Token> tks1, List<Token> tks2) { List<int[]> result = new ArrayList<int[]>(); int i = 0; int j = 0; int pos1 = 0; int pos2 = 0; int lastAlignPos = 0; int lastAlignI = 0; int lastAlignJ = 0; while (true) { if (i >= tks1.size() || j >= tks2.size()) break; Token tk1 = tks1.get(i); Token tk2 = tks2.get(j); if (tk1.getLength() == tk2.getLength()) { i++; pos1 += tk1.getLength(); j++; pos2 += tk2.getLength(); continue; } // 出现没对齐的情况 lastAlignI = i; lastAlignJ = j; lastAlignPos = pos1; // i++; pos1 += tk1.getLength(); // j++; pos2 += tk2.getLength(); while (pos1 != pos2) { if (pos1 < pos2) { i++; // if(i==tks1.size()) break L; pos1 += tks1.get(i).getLength(); } else { j++; // if(j==tks2.size()) break L; pos2 += tks2.get(j).getLength(); } } if (pos1 != pos2) break; // 再次对齐 result.add(new int[] { lastAlignPos, pos1, lastAlignI, lastAlignJ, i, j }); i++; j++; } if (i < tks1.size() || j < tks2.size()) { System.err.println("Unexpected here "); for (Token tk : tks1) { System.out.print(tk.getOrigText() + " "); } System.out.println(); for (Token tk : tks2) { System.out.print(tk.getOrigText() + " "); } System.out.println(); } return result; } private List<Token> segmentSentence(List<Token> tokens) { // 首先用MMSeg和RMMSeg分词,如果不一致,就用CRFs消歧 String s = this.tokens2String(tokens); List<Token> tks1 = this.mmseg.seg(s); List<Token> tks2 = this.rmmseg.seg(s); if (this.isEqual(tks1, tks2)) { return tks1; } List<int[]> diff = this.compareResult(tks1, tks2); List<Token> result = new ArrayList<Token>(); int lastPos = 0; for (int[] arr : diff) { for (int i = lastPos; i < arr[2]; i++) { result.add(tks1.get(i)); } boolean hasLeftContext = arr[2] > 0; boolean hasRightContext = arr[4] < tks1.size() - 2; if (hasLeftContext) { if (tks1.get(arr[2] - 1).getLength() != tks2.get(arr[3] - 1).getLength()) { hasLeftContext = false; } } if (hasRightContext) { if (tks1.get(arr[4] + 2).getLength() != tks2.get(arr[5] + 2).getLength()) { hasRightContext = false; } } int start1 = hasLeftContext ? arr[2] - 1 : arr[2]; int end1 = hasRightContext ? arr[4] + 2 : arr[4] + 1; // 如果上文有歧义,暂时不考虑上下文,主要原因是实现起来有些繁琐,而且上下文影响不是很大 // 比如:一千 年 来人 类 历史 // 一 千年 来 人类 历史 // 当考虑 “来人类” 的时候 ,左边的上下文是不确定的 int start2 = hasLeftContext ? arr[3] - 1 : arr[3]; int end2 = hasRightContext ? arr[5] + 2 : arr[5] + 1; List<Token> subList1 = tks1.subList(start1, end1); List<Token> subList2 = tks2.subList(start2, end2); double score1 = SgdCrf.getScore(this.token2Array(subList1), tc, model); double score2 = SgdCrf.getScore(this.token2Array(subList2), tc, model); if (score1 >= score2) { result.addAll(tks1.subList(arr[2], arr[4] + 1)); } else { result.addAll(tks2.subList(arr[3], arr[5] + 1)); } lastPos = arr[4] + 1; } for (int i = lastPos; i < tks1.size(); i++) { result.add(tks1.get(i)); } return result; } private String[] token2Array(List<Token> tokens){ String[] result=new String[tokens.size()]; int i=0; for(Token token:tokens){ result[i++]=token.getOrigText(); } return result; } }
28.117057
100
0.579874
747aa535a96ce5d74318d925fbaa845aedf92c9a
1,172
package com.ruoyi.ee.service; import java.util.List; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.ee.domain.WfHoliday; /** * 假期申请Service接口 * * @author hui * @date 2021-03-26 */ public interface IWfHolidayService { /** * 查询假期申请 * * @param wfHolidayId 假期申请ID * @return 假期申请 */ public WfHoliday selectWfHolidayById(Long wfHolidayId); /** * 查询假期申请列表 * * @param wfHoliday 假期申请 * @return 假期申请集合 */ public List<WfHoliday> selectWfHolidayList(WfHoliday wfHoliday); /** * 新增假期申请 * * @param wfHoliday 假期申请 * @return 结果 */ public int insertWfHoliday(WfHoliday wfHoliday); /** * 修改假期申请 * * @param wfHoliday 假期申请 * @return 结果 */ public int updateWfHoliday(WfHoliday wfHoliday); /** * 批量删除假期申请 * * @param ids 需要删除的数据ID * @return 结果 */ public int deleteWfHolidayByIds(String ids); /** * 删除假期申请信息 * * @param wfHolidayId 假期申请ID * @return 结果 */ public int deleteWfHolidayById(Long wfHolidayId); public AjaxResult cancelApply(Long wfHolidayId); }
17.757576
68
0.598976
72393f4f8ca18c91d9b4626cc7108c48f1f39bde
1,371
package io.github.ThatRobin.ccpacks.Mixins; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.resource.*; import net.minecraft.server.MinecraftServer; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.io.File; import java.util.Set; @Mixin(value = MinecraftServer.class, priority = 1001) // after Fabric public class MinecraftServerMixin { private static final ResourcePackSource RESOURCE_PACK_SOURCE = ResourcePackSource.nameAndSource("pack.source.ccpacks"); @Inject(method = "loadDataPacks", at = @At(value = "HEAD")) private static void loadDataPacks(ResourcePackManager resourcePackManager, DataPackSettings dataPackSettings, boolean safeMode, CallbackInfoReturnable<DataPackSettings> cir) { File DATAPACKS_PATH = FabricLoader.getInstance().getGameDirectory().toPath().resolve("mods").toFile(); Set<ResourcePackProvider> pack = ((AccessorMixin)resourcePackManager).getProviders(); pack.add( new FileResourcePackProvider( DATAPACKS_PATH, RESOURCE_PACK_SOURCE ) ); ((AccessorMixin) resourcePackManager).setProviders(pack); } }
40.323529
179
0.738147
52de873ef27fda8fa75ef2466857e73a769f0de5
572
public class Student extends Person { private double gpa; public Student(String name, String address, double gpa) { //super(); // This will call the no argument constructor from parent class. Java will do it for you super(name, address); this.gpa = gpa; } public Student(String name) { //Using this to call an overloading constructor this(name, "12", 4.0); } public double getGpa() { return gpa; } public void setGpa(double gpa) { this.gpa = gpa; } @Override public String toString() { return super.toString() + "\nGPA: " + gpa; } }
19.066667
101
0.667832
afc6f0f8c89cfbac097b35dc3298b0a467bbb382
4,108
/* * 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.commons.math3.analysis.differentiation; import org.apache.commons.math3.analysis.MultivariateMatrixFunction; import gov.nasa.jpf.annotation.Conditional; import static br.ufmg.labsoft.mutvariants.schematalib.SchemataLibMethods.*; /** * Class representing the Jacobian of a multivariate vector function. * <p> * The rows iterate on the model functions while the columns iterate on the parameters; thus, * the numbers of rows is equal to the dimension of the underlying function vector * value and the number of columns is equal to the number of free parameters of * the underlying function. * </p> * @since 3.1 */ public class JacobianFunction implements MultivariateMatrixFunction { @Conditional public static boolean _mut96997 = false, _mut96998 = false, _mut96999 = false, _mut97000 = false, _mut97001 = false, _mut97002 = false, _mut97003 = false, _mut97004 = false, _mut97005 = false, _mut97006 = false, _mut97007 = false, _mut97008 = false, _mut97009 = false, _mut97010 = false, _mut97011 = false; /** * Underlying vector-valued function. */ private final MultivariateDifferentiableVectorFunction f; /** * Simple constructor. * @param f underlying vector-valued function */ public JacobianFunction(final MultivariateDifferentiableVectorFunction f) { this.f = f; } /** * {@inheritDoc} */ public double[][] value(double[] point) { br.ufmg.labsoft.mutvariants.schematalib.SchemataLibMethods.listener.listen("org.apache.commons.math3.analysis.differentiation.JacobianFunction.value_43"); // set up parameters final DerivativeStructure[] dsX = new DerivativeStructure[point.length]; for (int i = 0; ROR_less(i, point.length, "org.apache.commons.math3.analysis.differentiation.JacobianFunction.value_43", _mut96997, _mut96998, _mut96999, _mut97000, _mut97001); ++i) { br.ufmg.labsoft.mutvariants.schematalib.SchemataLibMethods.listener.listen("org.apache.commons.math3.analysis.differentiation.JacobianFunction.value_43"); dsX[i] = new DerivativeStructure(point.length, 1, i, point[i]); } // compute the derivatives final DerivativeStructure[] dsY = f.value(dsX); // extract the Jacobian final double[][] y = new double[dsY.length][point.length]; final int[] orders = new int[point.length]; for (int i = 0; ROR_less(i, dsY.length, "org.apache.commons.math3.analysis.differentiation.JacobianFunction.value_43", _mut97007, _mut97008, _mut97009, _mut97010, _mut97011); ++i) { br.ufmg.labsoft.mutvariants.schematalib.SchemataLibMethods.listener.listen("org.apache.commons.math3.analysis.differentiation.JacobianFunction.value_43"); for (int j = 0; ROR_less(j, point.length, "org.apache.commons.math3.analysis.differentiation.JacobianFunction.value_43", _mut97002, _mut97003, _mut97004, _mut97005, _mut97006); ++j) { br.ufmg.labsoft.mutvariants.schematalib.SchemataLibMethods.listener.listen("org.apache.commons.math3.analysis.differentiation.JacobianFunction.value_43"); orders[j] = 1; y[i][j] = dsY[i].getPartialDerivative(orders); orders[j] = 0; } } return y; } }
52
310
0.717624
e94218b2761fcf9779cb6874b996992d176eda97
3,040
package net.renfei.service; import com.jblur.acme_client.CommandExecutor; import com.jblur.acme_client.Parameters; import net.renfei.base.BaseService; import net.renfei.config.RenFeiConfig; import org.springframework.stereotype.Service; /** * <p>Title: LetsEncryptService</p> * <p>Description: </p> * * @author RenFei(i @ renfei.net) * @date : 2021-02-11 16:31 */ @Service public class LetsEncryptService extends BaseService { private final RenFeiConfig renFeiConfig; public LetsEncryptService(RenFeiConfig renFeiConfig) { this.renFeiConfig = renFeiConfig; } /** * 注册CA用户帐户 */ public void register() { Parameters parameters = new Parameters(); parameters.setCommand("register"); parameters.setAccountKey(renFeiConfig.getLetsEncrypt().getDirPath() + "/account.key"); parameters.setWithAgreementUpdate(true); parameters.setEmail(renFeiConfig.getLetsEncrypt().getEmail()); new CommandExecutor(parameters).execute(); } /** * 请求证书订单并下载DNS01验证文件 * * @param csrFileName CSR证书请求文件名称 */ public void orderCertificate(String csrFileName) { Parameters parameters = new Parameters(); parameters.setCommand("order-certificate"); parameters.setAccountKey(renFeiConfig.getLetsEncrypt().getDirPath() + "/account.key"); parameters.setWorkDir(renFeiConfig.getLetsEncrypt().getDirPath() + "/workdir/"); parameters.setCsr(renFeiConfig.getLetsEncrypt().getDirPath() + "/" + csrFileName); parameters.setChallengeType("DNS01"); parameters.setDnsDigestDir(renFeiConfig.getLetsEncrypt().getDirPath() + "/digests/"); new CommandExecutor(parameters).execute(); } /** * 验证域名记录(DNS01) * * @param csrFileName CSR证书请求文件名称 */ public void verifyDomains(String csrFileName) { Parameters parameters = new Parameters(); parameters.setCommand("verify-domains"); parameters.setAccountKey(renFeiConfig.getLetsEncrypt().getDirPath() + "/account.key"); parameters.setWorkDir(renFeiConfig.getLetsEncrypt().getDirPath() + "/workdir/"); parameters.setCsr(renFeiConfig.getLetsEncrypt().getDirPath() + "/" + csrFileName); parameters.setChallengeType("DNS01"); new CommandExecutor(parameters).execute(); } /** * 生成证书并下载 cert.pem,chain.pem和fullchain.pem * * @param csrFileName CSR证书请求文件名称 */ public void generateCertificate(String csrFileName) { Parameters parameters = new Parameters(); parameters.setCommand("generate-certificate"); parameters.setAccountKey(renFeiConfig.getLetsEncrypt().getDirPath() + "/account.key"); parameters.setWorkDir(renFeiConfig.getLetsEncrypt().getDirPath() + "/workdir/"); parameters.setCsr(renFeiConfig.getLetsEncrypt().getDirPath() + "/" + csrFileName); parameters.setCertDir(renFeiConfig.getLetsEncrypt().getDirPath() + "/certdir/"); new CommandExecutor(parameters).execute(); } }
37.073171
94
0.686513
74d904bd2cb6d7034173479c05cf694f90147572
1,628
package me.dwliu.framework.core.tool.convert; import org.springframework.boot.convert.ApplicationConversionService; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.lang.Nullable; import org.springframework.util.StringValueResolver; /** * 类型 转换 服务,添加了 IEnum 转换 * * @author L.cm */ public class MicaConversionService extends ApplicationConversionService { @Nullable private static volatile MicaConversionService SHARED_INSTANCE; public MicaConversionService() { this(null); } public MicaConversionService(@Nullable StringValueResolver embeddedValueResolver) { super(embeddedValueResolver); super.addConverter(new EnumToStringConverter()); super.addConverter(new StringToEnumConverter()); } /** * Return a shared default application {@code ConversionService} instance, lazily * building it once needed. * <p> * Note: This method actually returns an {@link MicaConversionService} * instance. However, the {@code ConversionService} signature has been preserved for * binary compatibility. * @return the shared {@code MicaConversionService} instance (never{@code null}) */ public static GenericConversionService getInstance() { MicaConversionService sharedInstance = MicaConversionService.SHARED_INSTANCE; if (sharedInstance == null) { synchronized (MicaConversionService.class) { sharedInstance = MicaConversionService.SHARED_INSTANCE; if (sharedInstance == null) { sharedInstance = new MicaConversionService(); MicaConversionService.SHARED_INSTANCE = sharedInstance; } } } return sharedInstance; } }
31.921569
85
0.779484
ef077ce3c91fdbf83a3e78424479c6543ee6134e
2,191
package com.xpto.impl.toggleRouter; import com.xpto.impl.Feature; import org.junit.Test; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; public class FeatureConfigurationTest { private static FeatureConfiguration featureConfiguration; @Test public void shouldBeEnabledWhenNoServiceIsSetAndFeatureIsEnabled() { Feature feature = new Feature("1", "isButtonBlue", "1", "", true, true); featureConfiguration = new FeatureConfiguration(Optional.empty(), feature); assertThat(featureConfiguration.isEnabled()).isTrue(); } @Test public void shouldBeDisabledWhenNoServiceIsSetAndFeatureIsDisabled() { Feature feature = new Feature("1", "isButtonBlue", "1", "", true, false); featureConfiguration = new FeatureConfiguration(Optional.empty(), feature); assertThat(featureConfiguration.isEnabled()).isFalse(); } @Test public void shouldBeEnabledWhenServiceHasPermission() { Feature feature = new Feature("1", "isButtonGreen", "1", "abc", true, true); featureConfiguration = new FeatureConfiguration(Optional.of("abc"), feature); assertThat(featureConfiguration.isEnabled()).isTrue(); } @Test public void shouldBeDisableWhenServiceHasNoPermission() { Feature feature = new Feature("1", "isButtonGreen", "1", "abc", true, true); featureConfiguration = new FeatureConfiguration(Optional.of("trump"), feature); assertThat(featureConfiguration.isEnabled()).isFalse(); } @Test public void shouldBeDisabledServicesDontMatchFeatureEnabled(){ Feature feature = new Feature("1", "isButtonRed", "1", "abc", false, true); featureConfiguration = new FeatureConfiguration(Optional.of("trump"), feature); assertThat(featureConfiguration.isEnabled()).isFalse(); } @Test public void shouldBeEnabledServicesDontMatchFeatureDisabled(){ Feature feature = new Feature("1", "isButtonRed", "1", "abc", false, false); featureConfiguration = new FeatureConfiguration(Optional.of("trump"), feature); assertThat(featureConfiguration.isEnabled()).isTrue(); } }
38.438596
87
0.704701
c39d4b09e94f6bc3c2129e39fbd9fb53998c7bcc
1,483
public class Data { public Data(LaunchType launchType) { this.launchType = launchType; params.setBasic(DataSet.getBasic()); if(launchType == LaunchType.CONST){ setData(); } } LaunchType launchType; Params params = new Params(); public void setData(Double r) { params.setKQF(DataSet.getParams(launchType, r)); } public void setData() { setData(null); } public static class Params{ public Params(){ } public Params(double k, double q, double f){ this.k = k; this.q = q; this.f = f; } public Params(int Rl, int Rr, double vi1, double vi2, double ksi2){ this.Rl = Rl; this.Rr = Rr; this.vi1 = vi1; this.vi2 = vi2; this.ksi2 = ksi2; } public Params(Params other){ setBasic(other); } int Rl, Rr; double k, q, f; double vi1, vi2, ksi2; private void setBasic(Params other) { this.Rl = other.Rl; this.Rr = other.Rr; this.vi1 = other.vi1; this.vi2 = other.vi2; this.ksi2 = other.ksi2; } private void setKQF(Params other) { this.k = other.k; this.q = other.q; this.f = other.f; } public int getSize() { return (Rr - Rl); } } }
21.185714
75
0.476062
e75d68d86884f18783e4d58d8fb924b6126c2622
2,152
package com.victorbg.racofib.domain.schedule; import com.victorbg.racofib.data.database.AppDatabase; import com.victorbg.racofib.domain.UseCase; import com.victorbg.racofib.data.model.subject.SubjectSchedule; import com.victorbg.racofib.data.repository.AppExecutors; import com.victorbg.racofib.data.repository.base.Resource; import com.victorbg.racofib.utils.Utils; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import androidx.lifecycle.LiveData; import androidx.lifecycle.MediatorLiveData; import io.reactivex.Single; @Singleton public class LoadScheduleUseCase extends UseCase<Void, LiveData<Resource<List<SubjectSchedule>>>> { private final AppDatabase appDatabase; @Inject public LoadScheduleUseCase(AppExecutors appExecutors, AppDatabase appDatabase) { super(appExecutors); this.appDatabase = appDatabase; } /** * For every emission of subjects returns the schedule associated. It is util when the colors of * the subjects changes this also emits a new schedule with the correct colors. * * <p> * * @return */ @Override public LiveData<Resource<List<SubjectSchedule>>> execute() { MediatorLiveData<Resource<List<SubjectSchedule>>> result = new MediatorLiveData<>(); result.setValue(Resource.loading(null)); executeSingleAction( () -> appDatabase .subjectsDao() .getSubjects() .flatMap( subjects -> appDatabase .subjectScheduleDao() .getSchedule() .flatMap( schedule -> { Utils.assignColorsSchedule(subjects, schedule); return Single.just(schedule); })), data -> appExecutors.executeOnMainThread(() -> result.setValue(Resource.success(data))), error -> appExecutors.executeOnMainThread( () -> result.setValue(Resource.error(error.getMessage())))); return result; } }
32.606061
99
0.635223
22fbec79f1f1d7d2ef12aae3db963ac5aad05fcc
2,329
/* * Copyright 2014 - 2017 Cognizant Technology Solutions * * 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.cognizant.cognizantits.ide.main.dashboard.server; import com.cognizant.cognizantits.ide.main.mainui.AppMainFrame; import java.awt.Desktop; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; /** * * */ public class DashBoardManager { public DashBoardServer server; AppMainFrame sMainFrame; public DashBoardManager(AppMainFrame sMainFrame) { this.sMainFrame = sMainFrame; } public DashBoardServer server() { if (server == null || !server.isAlive()) { server = new DashBoardServer(); server.prepare(); server.start(); } return server; } public void stopServer() { if (server != null && server.isAlive()) { server.stopServer(); } } public void onProjectChanged() { try { DashBoardData.setProjLocation(sMainFrame.getProject().getLocation()); HarCompareHandler.init(); } catch (Exception ex) { Logger.getLogger(DashBoardManager.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } } public void openHarComapareInBrowser() { String add = server().url() + "/dashboard/harCompare/home.html"; if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { try { Desktop.getDesktop().browse(new URL(add).toURI()); } catch (URISyntaxException | IOException ex) { Logger.getLogger(DashBoardManager.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } } } }
31.053333
106
0.654787
491dd41e38afad6724eaec0626fdd45b0a1dc7b1
2,124
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 3.0.11 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package com.badlogic.gdx.physics.bullet.collision; import com.badlogic.gdx.physics.bullet.BulletBase; import com.badlogic.gdx.physics.bullet.linearmath.*; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Matrix3; import com.badlogic.gdx.math.Matrix4; public class btTetrahedronShapeEx extends btBU_Simplex1to4 { private long swigCPtr; protected btTetrahedronShapeEx(final String className, long cPtr, boolean cMemoryOwn) { super(className, CollisionJNI.btTetrahedronShapeEx_SWIGUpcast(cPtr), cMemoryOwn); swigCPtr = cPtr; } /** Construct a new btTetrahedronShapeEx, normally you should not need this constructor it's intended for low-level usage. */ public btTetrahedronShapeEx(long cPtr, boolean cMemoryOwn) { this("btTetrahedronShapeEx", cPtr, cMemoryOwn); construct(); } @Override protected void reset(long cPtr, boolean cMemoryOwn) { if (!destroyed) destroy(); super.reset(CollisionJNI.btTetrahedronShapeEx_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn); } public static long getCPtr(btTetrahedronShapeEx obj) { return (obj == null) ? 0 : obj.swigCPtr; } @Override protected void finalize() throws Throwable { if (!destroyed) destroy(); super.finalize(); } @Override protected synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; CollisionJNI.delete_btTetrahedronShapeEx(swigCPtr); } swigCPtr = 0; } super.delete(); } public btTetrahedronShapeEx() { this(CollisionJNI.new_btTetrahedronShapeEx(), true); } public void setVertices(Vector3 v0, Vector3 v1, Vector3 v2, Vector3 v3) { CollisionJNI.btTetrahedronShapeEx_setVertices(swigCPtr, this, v0, v1, v2, v3); } }
30.342857
126
0.687853
8f10cce24037cf8b5b9ece7cf184f5cde71be5ae
1,015
package com.kk.inject.testsdk.internal; import com.kk.inject.Inject; import com.kk.inject.NotNull; import com.kk.inject.testsdk.GreetingManager; import com.kk.inject.testsdk.User; /** * User implementation. */ public class UserImpl implements User { /** * The clue between the greeting and the user name. */ @NotNull private static final String CLUE = ", I am "; /** * The injected greeting manager. */ @NotNull @Inject private GreetingManager mGreetingManager; /** * The usr name passed to the constructor. */ @NotNull private String mUserName; /** * Constructs the user with the specified user name. * * @param userName * The user name for the user. */ public UserImpl(@NotNull final String userName) { mUserName = userName; } /** * {@inheritDoc} */ @Override @NotNull public String introduce() { return mGreetingManager.getGreeting() + CLUE + mUserName; } }
21.595745
65
0.627586
c32a34d4508d8388526509205ba874243fcf7823
1,111
package io.prime.web.thumbnailator.core.test.util; import static org.assertj.core.api.Assertions.assertThat; import java.util.regex.Pattern; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.prime.web.thumbnailator.core.generator.ImageIdGenerator; import io.prime.web.thumbnailator.core.generator.ImageIdGeneratorWithUUID; public class UUIDImageIdGeneratorTest { private final ImageIdGenerator generator = new ImageIdGeneratorWithUUID(); private final Logger logger = LoggerFactory.getLogger( this.getClass() ); @Test public void test() { final String filename = "sample.jpg"; final String imageId = generator.generate( "sample.jpg" ); logger.info( "ImageId: " + imageId ); assertThat( imageId ).isNotNull() .isNotEmpty() .matches( Pattern.compile( "^(?!/).*", Pattern.DOTALL | Pattern.CASE_INSENSITIVE ) ) .doesNotContain( "//" ) .endsWith( filename ); } }
32.676471
114
0.630063
3ea3fc820959e41e98928959315c01533f0e9cc9
3,006
package app.coronawarn.server.services.distribution.dgc.structure; import app.coronawarn.server.common.protocols.internal.dgc.ValueSets; import app.coronawarn.server.common.shared.collection.ImmutableStack; import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider; import app.coronawarn.server.services.distribution.assembly.structure.archive.ArchiveOnDisk; import app.coronawarn.server.services.distribution.assembly.structure.archive.decorator.signing.DistributionArchiveSigningDecorator; import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk; import app.coronawarn.server.services.distribution.assembly.structure.file.FileOnDisk; import app.coronawarn.server.services.distribution.config.DistributionServiceConfig; import app.coronawarn.server.services.distribution.config.DistributionServiceConfig.DigitalGreenCertificate; import java.util.Arrays; import java.util.Optional; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DigitalCertificatesDirectory extends IndexDirectoryOnDisk<String> { private static final Logger logger = LoggerFactory.getLogger(DigitalCertificatesDirectory.class); public static final String EXPORT_BINARY_FILENAME = "export.bin"; private final DistributionServiceConfig distributionServiceConfig; private final DigitalGreenCertificate dgcConfig; private final CryptoProvider cryptoProvider; private ValueSets valueSets; /** * Constructs a {@link IndexDirectoryOnDisk} instance that represents a directory, for a digital green certificates * and writes valuesets to all supported countries by the dgc. */ public DigitalCertificatesDirectory(DistributionServiceConfig distributionServiceConfig, DigitalGreenCertificate dgcConfig, CryptoProvider cryptoProvider) { super(dgcConfig.getDgcDirectory(), ignoredValue -> Arrays.stream(dgcConfig.getSupportedLanguages()) .map(String::toLowerCase) .collect(Collectors.toSet()), Object::toString); this.distributionServiceConfig = distributionServiceConfig; this.dgcConfig = dgcConfig; this.cryptoProvider = cryptoProvider; } @Override public void prepare(ImmutableStack<Object> indices) { if (valueSets != null) { this.addWritableToAll(lang -> { ArchiveOnDisk archiveToPublish = new ArchiveOnDisk(dgcConfig.getValuesetsFileName()); archiveToPublish.addWritable(new FileOnDisk(EXPORT_BINARY_FILENAME, valueSets.toByteArray())); logger.info("Writing digital green certificate value sets to {}/{}/{}.", dgcConfig.getDgcDirectory(), lang.peek(), archiveToPublish.getName()); return Optional.of(new DistributionArchiveSigningDecorator( archiveToPublish, cryptoProvider, distributionServiceConfig)); }); } super.prepare(indices); } public void addValueSetsToAll(ValueSets valueSets) { this.valueSets = valueSets; } }
44.865672
132
0.792748
e79ef21899f49ce031405edc235f1d027b30e250
17,395
package com.xceptance.xlt.nocoding.command.action.request; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.openqa.selenium.InvalidArgumentException; import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; import com.gargoylesoftware.htmlunit.HttpMethod; import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebResponse; import com.gargoylesoftware.htmlunit.util.NameValuePair; import com.gargoylesoftware.htmlunit.util.UrlUtils; import com.xceptance.xlt.engine.XltWebClient; import com.xceptance.xlt.nocoding.command.action.AbstractActionSubItem; import com.xceptance.xlt.nocoding.util.Constants; import com.xceptance.xlt.nocoding.util.RecentKeyTreeMap; import com.xceptance.xlt.nocoding.util.context.Context; import com.xceptance.xlt.nocoding.util.resolver.VariableResolver; import com.xceptance.xlt.nocoding.util.storage.DataStorage; /** * Describes a HTTP Request, that gets transformed to a {@link WebRequest} and then sent via the {@link XltWebClient}. * * @author ckeiner */ public class Request extends AbstractActionSubItem { /** * The URL as String */ private String url; /** * The HttpMethod for the WebRequest. Defaults to "GET" */ private String httpMethod; /** * Sets the WebRequest as Xhr request. Defaults to "false" */ private String xhr; /** * Defines if the parameters are encoded. Defaults to "false" */ private String encodeParameters; /** * The list of the parameters */ private List<NameValuePair> parameters; /** * The list of cookies */ private Map<String, String> cookies; /** * A map that defines the headers */ private Map<String, String> headers; /** * The body of the {@link WebRequest} */ private String body; /** * Defines if the body is encoded. Defaults to "false" */ private String encodeBody; /** * Creates an instance of {@link Request}, that sets {@link #url} to null. */ public Request() { this(null); } /** * Creates an instance of {@link Request}, that sets {@link #url}. * * @param url * The URL as {@link String}. */ public Request(final String url) { this.url = url; parameters = new ArrayList<>(); cookies = new LinkedHashMap<>(); headers = new RecentKeyTreeMap(); } public String getUrl() { return url; } public void setUrl(final String url) { this.url = url; } public String getHttpMethod() { return httpMethod; } public void setHttpMethod(final String httpMethod) { this.httpMethod = httpMethod; } public String getXhr() { return xhr; } public void setXhr(final String xhr) { this.xhr = xhr; } public String getEncodeParameters() { return encodeParameters; } public void setEncodeParameters(final String encodeParameters) { this.encodeParameters = encodeParameters; } public List<NameValuePair> getParameters() { return parameters; } public void setParameters(final List<NameValuePair> parameters) { this.parameters = parameters; } public Map<String, String> getCookies() { return cookies; } public void setCookies(final Map<String, String> cookies) { this.cookies = cookies; } public Map<String, String> getHeaders() { return headers; } /** * Create a {@link RecentKeyTreeMap} out of the specified map, so headers are always treated case insensitive. * * @param headers * The map with the headers */ public void setHeaders(final Map<String, String> headers) { if (headers != null && !headers.isEmpty()) { this.headers = new RecentKeyTreeMap(); this.headers.putAll(headers); } } public String getBody() { return body; } public void setBody(final String body) { this.body = body; } public String getEncodeBody() { return encodeBody; } public void setEncodeBody(final String encodeBody) { this.encodeBody = encodeBody; } /** * Fills in the default values for all unspecified attributes.<br> * Note, that default headers and cookies are already set at the WebClient.. * * @param context * The {@link Context} with the {@link DataStorage} */ public void fillDefaultData(final Context<?> context) { // Set default URL if it isn't specified if (getUrl() == null || getUrl().isEmpty()) { setUrl(context.getDefaultItems().get(Constants.URL)); } // Set default HttpMethod if it isn't specified if (getHttpMethod() == null) { setHttpMethod(context.getDefaultItems().get(Constants.METHOD)); } // Set default Xhr if it isn't specified if (getXhr() == null) { setXhr(context.getDefaultItems().get(Constants.XHR)); } // Set default encodeParameters if it isn't specified if (getEncodeParameters() == null) { setEncodeParameters(context.getDefaultItems().get(Constants.ENCODEPARAMETERS)); } /* * Set default parameters */ if (context.getDefaultParameters() != null && !context.getDefaultParameters().getItems().isEmpty()) { // Get default parameters final List<NameValuePair> defaultParameters = context.getDefaultParameters().getItems(); // Overwrite the default values with the current ones or add the current ones if (getParameters() != null) { for (final NameValuePair defaultParameter : defaultParameters) { if (!getParameters().contains(defaultParameter)) { getParameters().add(defaultParameter); } } } } // Set default body if it isn't specified if (getBody() == null) { setBody(context.getDefaultItems().get(Constants.BODY)); } // Set default encodeBody if it isn't specified if (getEncodeBody() == null) { setEncodeBody(context.getDefaultItems().get(Constants.ENCODEBODY)); } } /** * Tries to resolve all variables of non-null attributes * * @param context * The {@link Context} with the {@link VariableResolver} * @throws InvalidArgumentException */ void resolveValues(final Context<?> context) throws InvalidArgumentException { String resolvedValue; // Resolve Url resolvedValue = context.resolveString(getUrl()); setUrl(resolvedValue); // Resolve Httpmethod resolvedValue = context.resolveString(getHttpMethod()); setHttpMethod(resolvedValue); // Resolve Xhr if it isn't null if (getXhr() != null) { resolvedValue = context.resolveString(getXhr()); setXhr(resolvedValue); } // Resolve encodeParameters if it isn't null if (getEncodeParameters() != null) { resolvedValue = context.resolveString(getEncodeParameters()); setEncodeParameters(resolvedValue); } // Resolve each parameter in parameters if is neither null nor empty if (getParameters() != null && !getParameters().isEmpty()) { final List<NameValuePair> resolvedParameters = new ArrayList<>(); String resolvedParameterName, resolvedParameterValue; // Iterate over the list for (final NameValuePair parameter : parameters) { // Resolve the name of the parameter resolvedParameterName = context.resolveString(parameter.getName()); // Resolve the value of the parameter resolvedParameterValue = context.resolveString(parameter.getValue()); // Add the resolved name and resolved value to the new parameter list resolvedParameters.add(new NameValuePair(resolvedParameterName, resolvedParameterValue)); } // Reassign the parameter list to the resolved parameter list setParameters(resolvedParameters); } // Resolve each header in headers if is neither null nor empty if (getHeaders() != null && !getHeaders().isEmpty()) { // Create a new map final Map<String, String> resolvedHeaders = new HashMap<>(); // And insert the resolved key and value of the old map into the new one getHeaders().forEach((final String key, final String value) -> { resolvedHeaders.put(context.resolveString(key), context.resolveString(value)); }); // Reassign the header to its resolved values setHeaders(resolvedHeaders); } // Resolve encodeBody if it isn't null if (getEncodeBody() != null) { resolvedValue = context.resolveString(getEncodeBody()); setEncodeBody(resolvedValue); } // Resolve Body if it isn't null if (getBody() != null) { resolvedValue = context.resolveString(getBody()); setBody(resolvedValue); } } /** * Builds the {@link WebRequest} with the given {@link Context} and sends the <code>WebRequest</code>. Finally, it * stores the corresponding {@link WebResponse} with {@link Context#setWebResponse(WebResponse)}. * * @param context * The {@link Context} with the {@link DataStorage}, {@link VariableResolver} and {@link XltWebClient} * @throws IOException * if building of sending the <code>WebRequest</code> fails * @throws FailingHttpStatusCodeException */ @Override public void execute(final Context<?> context) throws FailingHttpStatusCodeException, IOException { // Fill in the default data if the attribute is not specified fillDefaultData(context); // Then resolve all variables resolveValues(context); // Throw an error if the url is null or empty if (url == null || url.isEmpty()) { throw new InvalidArgumentException("Url is empty. Please set a default url or specify a url."); } // Build the WebRequest final WebRequest webRequest = buildWebRequest(context); // Check that the webRequest isn't null if (webRequest != null) { // Load the webResponse context.loadWebResponse(webRequest); } } /** * Sets the cookies at the web client * * @param context * The current {@link Context} * @throws MalformedURLException * If {@link #url} of this request cannot be transformed to a URL */ private void setCookiesAtWebClient(final Context<?> context) throws MalformedURLException { if (getCookies() != null && !getCookies().isEmpty()) { final URL url = new URL(getUrl()); cookies.forEach((key, value) -> { context.getWebClient().addCookie(key + "=" + value, url, this); }); } } /** * Builds the {@link WebRequest} that is specified by this object * * @param context * The current {@link Context} * @return The <code>WebRequest</code> that is specified by this object * @throws MalformedURLException * @throws UnsupportedEncodingException */ WebRequest buildWebRequest(final Context<?> context) throws MalformedURLException, UnsupportedEncodingException { // Create a URL object final URL url = new URL(this.url); // Create a WebRequest final WebRequest webRequest = new WebRequest(url, HttpMethod.valueOf(getHttpMethod())); // Set headers if they aren't null or empty if (getHeaders() != null || !getHeaders().isEmpty()) { final RecentKeyTreeMap headerExchange = new RecentKeyTreeMap(); headerExchange.putAll(webRequest.getAdditionalHeaders()); headerExchange.putAll(headers); webRequest.setAdditionalHeaders(headerExchange); } // Set Xhr if it is specified and can be converted to a boolean if (getXhr() != null && Boolean.valueOf(getXhr())) { webRequest.setXHR(); // Set XHR headers webRequest.getAdditionalHeaders().put("X-Requested-With", "XMLHttpRequest"); // If there was a previous WebResponse, set the Url als Referer if (context.getWebResponse() != null) { // Get the url of the old webResponse webRequest.getAdditionalHeaders().put("Referer", context.getWebResponse().getWebRequest().getUrl().toString()); } } // Set parameters if they aren't null or empty if (getParameters() != null && !getParameters().isEmpty()) { // Decode parameters if they are specified and set to "true" if (getEncodeParameters() != null && !Boolean.valueOf(getEncodeParameters())) { decodeParameters(); } handleParameters(webRequest, parameters); } // Set Body if specified and no parameters are set if (getBody() != null && !getBody().isEmpty() && (getParameters() == null || getParameters().isEmpty())) { // Decode Body if they are specified and set to "true" if (getEncodeBody() != null && !Boolean.valueOf(getEncodeBody())) { decodeBody(); } webRequest.setRequestBody(body); } // Sets the cookies at the web client setCookiesAtWebClient(context); // Return the webRequest return webRequest; } /** * Decodes the body. * * @throws UnsupportedEncodingException */ private void decodeBody() throws UnsupportedEncodingException { setBody(URLDecoder.decode(getBody(), "UTF-8")); } /** * Decodes each parameter in {@link #parameters}. * * @throws UnsupportedEncodingException */ private void decodeParameters() throws UnsupportedEncodingException { final List<NameValuePair> decodedParameters = new ArrayList<>(); for (final NameValuePair parameter : getParameters()) { final String decodedName = parameter.getName() != null ? URLDecoder.decode(parameter.getName(), "UTF-8") : null; final String decodedValue = parameter.getValue() != null ? URLDecoder.decode(parameter.getValue(), "UTF-8") : null; final NameValuePair decodedParameter = new NameValuePair(decodedName, decodedValue); decodedParameters.add(decodedParameter); } setParameters(decodedParameters); } /** * Provides the url and method used */ public String toSimpleDebugString() { final String output = "Request-URL: " + url + " with Method." + httpMethod; return output; } private void handleParameters(final WebRequest webRequest, final List<NameValuePair> parameters) throws MalformedURLException { final HttpMethod method = webRequest.getHttpMethod(); if (parameters != null && !parameters.isEmpty()) { // POST as well as PUT and PATCH if (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PATCH)) { webRequest.setRequestParameters(parameters); } else { final URL url = buildNewUrl(webRequest.getUrl(), parameters); webRequest.setUrl(url); } } } private static URL buildNewUrl(final URL url, final List<NameValuePair> parameters) throws MalformedURLException { URL newUrl = url; if (parameters != null && !parameters.isEmpty()) { final String query = url.getQuery(); String parameterToQuery = ""; // Add query and "&" to the url if (query != null) { parameterToQuery += query + "&"; } for (final NameValuePair parameter : parameters) { parameterToQuery += parameter.getName() + "=" + parameter.getValue() + "&"; } parameterToQuery = parameterToQuery.substring(0, parameterToQuery.lastIndexOf("&")); newUrl = UrlUtils.getUrlWithNewQuery(url, parameterToQuery); } return newUrl; } }
31.229803
129
0.599598
9b06abccbfbe0e931799c2413a3bb6fc6778edf2
2,773
import java.io.File; import java.io.IOException; import java.util.Comparator; import net.runelite.mapping.Export; import net.runelite.mapping.Implements; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("n") @Implements("GrandExchangeOfferUnitPriceComparator") final class GrandExchangeOfferUnitPriceComparator implements Comparator { @ObfuscatedName("pa") @ObfuscatedSignature( signature = "Ljz;" ) @Export("clanChat") static ClanChat clanChat; @ObfuscatedName("sb") @ObfuscatedSignature( signature = "Lln;" ) @Export("worldMap") static WorldMap worldMap; @ObfuscatedName("h") @ObfuscatedGetter( intValue = -135135315 ) static int field75; @ObfuscatedName("c") @ObfuscatedSignature( signature = "(Lv;Lv;I)I", garbageValue = "-1189972175" ) @Export("compare_bridged") int compare_bridged(GrandExchangeEvent var1, GrandExchangeEvent var2) { return var1.grandExchangeOffer.unitPrice < var2.grandExchangeOffer.unitPrice ? -1 : (var2.grandExchangeOffer.unitPrice == var1.grandExchangeOffer.unitPrice ? 0 : 1); } public int compare(Object var1, Object var2) { return this.compare_bridged((GrandExchangeEvent)var1, (GrandExchangeEvent)var2); } public boolean equals(Object var1) { return super.equals(var1); } @ObfuscatedName("c") @ObfuscatedSignature( signature = "(B)[Lgn;", garbageValue = "-20" ) public static class185[] method116() { return new class185[]{class185.field2298, class185.field2300, class185.field2297, class185.field2299, class185.field2304, class185.field2296, class185.field2302, class185.field2301, class185.field2303, class185.field2305}; } @ObfuscatedName("g") @ObfuscatedSignature( signature = "(Ljava/lang/String;Ljava/lang/String;ZB)Lmr;", garbageValue = "48" ) @Export("getPreferencesFile") public static AccessFile getPreferencesFile(String var0, String var1, boolean var2) { File var3 = new File(InvDefinition.cacheDir, "preferences" + var0 + ".dat"); if (var3.exists()) { try { AccessFile var10 = new AccessFile(var3, "rw", 10000L); return var10; } catch (IOException var9) { } } String var4 = ""; if (ViewportMouse.cacheGamebuild == 33) { var4 = "_rc"; } else if (ViewportMouse.cacheGamebuild == 34) { var4 = "_wip"; } File var5 = new File(Message.userHomeDirectory, "jagex_" + var1 + "_preferences" + var0 + var4 + ".dat"); AccessFile var6; if (!var2 && var5.exists()) { try { var6 = new AccessFile(var5, "rw", 10000L); return var6; } catch (IOException var8) { } } try { var6 = new AccessFile(var3, "rw", 10000L); return var6; } catch (IOException var7) { throw new RuntimeException(); } } }
28.010101
224
0.719077
39fbcc47c65b2fd94937241a89bd85bb707a40de
96
class A { } class B extends A { void m() { Class<? extends A> c = getClass();<caret> } }
13.714286
45
0.541667
8f751f38b801dfaef9effab56bef3b69b28d8379
5,580
/* * Copyright 2011 - 2013 NTB University of Applied Sciences in Technology * Buchs, Switzerland, http://www.ntb.ch/inf * * 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.deepjava.classItems; import java.io.PrintStream; public class InterfaceList { private static PrintStream vrb = Item.vrb; private static final byte listCapacityAddOn = 8; private Class[] interfaces; // interfaces public int length; public boolean done; public InterfaceList() { interfaces = new Class[listCapacityAddOn]; done = true; } public void clear() { for (int n = interfaces.length-1; n >= 0; n--) interfaces[n] = null; length = 0; done = true; } public Class getFront() { assert length > 0; return interfaces[0]; } public Class getTail() { assert length > 0; return interfaces[length-1]; } /** * get interface at specified position: position == 0: front item, position == length-1: tail item. * @param position item position in list: 0 <= position < length * @return interface at the specified position or null if position out of range */ public Class getInterfaceAt(int position) { if (position < 0 || position >= length) return null; else return interfaces[position]; } /** * @param interf * @return */ public int getIndexOf(Class interf) { int n = length-1; while (n >= 0 && interfaces[n] != interf) n--; return n; } /** * @param interfaceId * @return the position(index) of interfaceId if found, else -1 */ public int getIndexWithThisId(int interfaceId) { int n = length-1; while (n >= 0 && interfaces[n].index < interfaceId) n--; if (n >= 0 && interfaces[n].index != interfaceId) n = -1; return n; } void updateBaseIndex(int interfaceId, int baseIndex) { assert false; } /** * append interface sorted according to the extension level of their referencing classes (descending ext. level) */ void appendSorted(Class interf) { int pos = getIndexWithThisId(interf.index); // select interface with the same identifier if (pos >= 0) { // replace it, if the new interface with same id is an extension of the selected one if (interfaces[pos].methTabLength < interf.methTabLength) interfaces[pos] = interf; } else // append the new interface append(interf); } /** * append interface if field index is not present in the list */ void appendCallId(Class interf) { int n = length-1; while (n >= 0 && interfaces[n].index != interf.index) n--; if (n < 0) append(interf); } /** * append interface if field chkId is not present in the list */ void appendChkId(Class interf) { int n = length-1; while (n >= 0 && interfaces[n].chkId != interf.chkId) n--; if (n < 0) append(interf); } /** * sort interfaces according to their ident(index) in descending way */ void append(Class interf) { if (length >= interfaces.length) { Class[] newInterfaces = new Class[length + listCapacityAddOn]; System.arraycopy(interfaces, 0, newInterfaces, 0, interfaces.length); interfaces = newInterfaces; } interfaces[length] = interf; length++; } /** * sort interfaces according to their id (index) in descending way */ void sortId() { for (int left = 0; left < length-1; left++) { for (int right = left+1; right < length; right++) { if (interfaces[left].index < interfaces[right].index) { Class h = interfaces[left]; interfaces[left] = interfaces[right]; interfaces[right] = h; } } } } /** * sort interfaces according to their type check identifier in descending way */ void sortChkId() { for (int left = 0; left < length-1; left++) { for (int right = left+1; right < length; right++) { if (interfaces[left].chkId < interfaces[right].chkId) { Class h = interfaces[left]; interfaces[left] = interfaces[right]; interfaces[right] = h; } } } } //--- debug utilities public void print(){ vrb.printf("interface list: (length=%1$d, done=%2$b)\n", length, done); for( int n = 0; n < length; n++){ Class interf = interfaces[n]; vrb.printf("\tname=%1$s, id=%2$d, #meths=%3$d\n", interf.name, interf.index, interf.methTabLength ); } vrb.println(); } // public static void insertAndPrint(InterfaceList ia, int interfaceId, int nofInterfaceMethods ){ // vrb.printf("\nupdate( %1$d, %2$d)\n", interfaceId, nofInterfaceMethods ); // ia.update( interfaceId, nofInterfaceMethods ); // ia.print( ); // } // // public static void main(String[] args) { // InterfaceList ia = new InterfaceList(5); // insertAndPrint( ia, 2, 12 ); // insertAndPrint( ia, 3, 13 ); // insertAndPrint( ia, 1, 11 ); // // insertAndPrint( ia, 3, 3 ); // insertAndPrint( ia, 3, 33 ); // // insertAndPrint( ia, 2, 2 ); // insertAndPrint( ia, 2, 22 ); // // insertAndPrint( ia, 1, 1 ); // insertAndPrint( ia, 1, 11 ); // insertAndPrint( ia, 1, 111 ); // } }
28.911917
114
0.63638
aba4fda69814c677ce5fe909d43ba52ae075879b
2,669
/* * Copyright 2006-2021 WebPKI.org (http://webpki.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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.webpki.crypto; import java.security.Provider; import java.security.Security; import java.util.logging.Level; import java.util.logging.Logger; /** * Bouncycastle loader */ public class CustomCryptoProvider { private static Logger logger = Logger.getLogger(CustomCryptoProvider.class.getCanonicalName()); private CustomCryptoProvider() {} // No instantiation private static boolean loadBouncyCastle(boolean insertFirst, boolean require) { //#if BOUNCYCASTLE boolean loaded = false; try { Provider bc = (Provider) Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider").getDeclaredConstructor().newInstance(); if (Security.getProvider(bc.getName()) == null) { try { if (insertFirst) { Security.insertProviderAt(bc, 1); logger.info("BouncyCastle successfully inserted at position #1"); } else { Security.addProvider(bc); logger.info("BouncyCastle successfully added to the list of providers"); } } catch (Exception e) { logger.log(Level.SEVERE, "BouncyCastle didn't load"); throw new RuntimeException(e); } } else { logger.info("BouncyCastle was already loaded"); } loaded = true; } catch (Exception e) { if (require) { logger.log(Level.SEVERE, "BouncyCastle was not found"); throw new RuntimeException(e); } logger.info("BouncyCastle was not found, continue anyway"); } return loaded; //#else return false; //#endif } public static boolean conditionalLoad(boolean insertFirst) { return loadBouncyCastle(insertFirst, false); } public static void forcedLoad(boolean insertFirst) { loadBouncyCastle(insertFirst, true); } }
34.662338
144
0.618209
27753c7619e3aa5a49ac8c20c9c780bd9259846c
2,429
/* * Copyright 2019, Perfect Sense, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gyro.plugin.ssh; import java.util.List; import com.psddev.dari.util.ObjectUtils; import gyro.core.GyroCore; import gyro.core.GyroInstance; import gyro.core.command.VersionCommand; import picocli.CommandLine.Command; @Command(name = "list", header = "List instances found in provided config file.", synopsisHeading = "%n", parameterListHeading = "%nParameters:%n", optionListHeading = "%nOptions:%n", usageHelpWidth = 100, mixinStandardHelpOptions = true, versionProvider = VersionCommand.class ) public class ListCommand extends AbstractInstanceCommand { private static final Table LIST_TABLE = new Table() .addColumn("Instance ID", 20) .addColumn("State", 12) .addColumn("Launch Date", 30) .addColumn("Hostname", 65); @Override public void doExecute(List<GyroInstance> instances) { LIST_TABLE.writeHeader(GyroCore.ui()); for (GyroInstance instance : instances) { LIST_TABLE.writeRow( GyroCore.ui(), instance.getGyroInstanceId(), instance.getGyroInstanceState(), instance.getGyroInstanceLaunchDate(), getHostname(instance) ); } LIST_TABLE.writeFooter(GyroCore.ui()); } public String getHostname(GyroInstance instance) { if (!ObjectUtils.isBlank(instance.getGyroInstanceHostname())) { return instance.getGyroInstanceHostname(); } if (!ObjectUtils.isBlank(instance.getGyroInstancePublicIpAddress())) { return instance.getGyroInstancePublicIpAddress(); } if (!ObjectUtils.isBlank(instance.getGyroInstancePrivateIpAddress())) { return instance.getGyroInstancePrivateIpAddress(); } return ""; } }
31.141026
79
0.672705
d3d504665261c32af7fd681443892324e2128463
1,901
/* * Copyright 2020 The 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.yanncebron.m68kplugin.parser; import com.intellij.testFramework.TestDataPath; @TestDataPath("$PROJECT_ROOT/testData/parser/bitInstructions") public class BitInstructionsParsingTest extends M68kParsingTestCase { public BitInstructionsParsingTest() { super("bitInstructions"); } public void testBchgInstructionImmDrd() throws Exception { doCodeTest(" bchg #1,d0"); } public void testBchgInstructionDataSizeImmDrd() throws Exception { doCodeTest(" bchg.b #1,d0"); } public void testBchgInstructionDrdDrd() throws Exception { doCodeTest(" bchg d0,d1"); } public void testBchgInstructionMissingSource() throws Exception { doCodeTest(" bchg "); } public void testBchgInstructionMissingDestination() throws Exception { doCodeTest(" bchg d0,"); } public void testBclrInstructionDrdDrd() throws Exception { doCodeTest(" bclr.l d1,d2"); } public void testBsetInstructionDrdDrd() throws Exception { doCodeTest(" bset.b d1,d2"); } public void testBtstInstructionDrdDrd() throws Exception { doCodeTest(" btst d1,d2"); } public void testBtstInstructionDrdPcd() throws Exception { doCodeTest(" btst d1,42(pc)"); } public void testBtstInstructionImmPci() throws Exception { doCodeTest(" btst #1,42(pc,d0)"); } }
27.955882
75
0.732246
e5efca9ca75589c3975980d10c4d704d6e6265bb
65
package com.cooey.common.vo; public class CaretakerSettings { }
13
32
0.784615
7c039d96246b9ca3be368116714b94d2451682e1
3,736
package com.dante.minimization; import com.dante.coverage.CovUnit; import com.dante.coverage.CoverageReport; import com.dante.tedd.graph.GraphNode; import com.dante.tedd.graph.utils.ComparatorNodesIncreasing; import com.dante.utils.SetsUtils; import org.apache.log4j.Logger; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; public class TestSelector { private final static Logger logger = Logger.getLogger(TestSelector.class.getName()); public List<GraphNode<String>> greedySelectingTestCases(CoverageReport coverageReport) { List<GraphNode<String>> greedySelectedTestCases = new LinkedList<>(); Map<GraphNode<String>, Set<CovUnit>> mapTestCovUnits = coverageReport.getMapTestCovUnits(); Set<CovUnit> allCovUnits = new HashSet<>(); List<GraphNode<String>> originalTestSuite = new LinkedList<>(mapTestCovUnits.keySet()); originalTestSuite.sort(new ComparatorNodesIncreasing<>()); GraphNode<String> testWithMaxCov = null; int maxCov = -1; for (GraphNode<String> testCase : originalTestSuite) { Set<CovUnit> unitsCoveredByTestCase = mapTestCovUnits.get(testCase); allCovUnits.addAll(unitsCoveredByTestCase); if(unitsCoveredByTestCase.size() > maxCov) { maxCov = unitsCoveredByTestCase.size(); testWithMaxCov = testCase; } } logger.info("Test with max cov: " + testWithMaxCov + ", cov: " + maxCov); Set<CovUnit> incrementalCovUnits = new HashSet<>(mapTestCovUnits.get(testWithMaxCov)); greedySelectedTestCases.add(testWithMaxCov); originalTestSuite.remove(testWithMaxCov); logger.info("All cov units: " + allCovUnits.size()); while(!originalTestSuite.isEmpty() && !incrementalCovUnits.containsAll(allCovUnits)) { GraphNode<String> testToAdd = null; int maxCovDifference = -1; for (GraphNode<String> testCase : originalTestSuite) { Set<CovUnit> unitsCoveredByTestCase = mapTestCovUnits.get(testCase); int difference = SetsUtils.setsDifference(unitsCoveredByTestCase, incrementalCovUnits).size(); if(difference > maxCovDifference) { maxCovDifference = difference; testToAdd = testCase; } } logger.info("Test to add: " + testToAdd + ", max cov diff: " + maxCovDifference); incrementalCovUnits.addAll(mapTestCovUnits.get(testToAdd)); logger.info("Incremental cov units: " + incrementalCovUnits.size()); greedySelectedTestCases.add(testToAdd); originalTestSuite.remove(testToAdd); } return greedySelectedTestCases; } public List<GraphNode<String>> selectTestCases(CoverageReport coverageReport) { List<GraphNode<String>> selectedTestCases = new LinkedList<>(); Map<GraphNode<String>, Set<CovUnit>> mapTestCovUnits = coverageReport.getMapTestCovUnits(); Set<CovUnit> allCovUnits = new HashSet<>(); List<GraphNode<String>> originalTestSuite = new LinkedList<>(mapTestCovUnits.keySet()); originalTestSuite.sort(new ComparatorNodesIncreasing<>()); for (GraphNode<String> testCase : originalTestSuite) { logger.info("Test case: " + testCase); Set<CovUnit> unitsCoveredByTestCase = mapTestCovUnits.get(testCase); if(!allCovUnits.containsAll(unitsCoveredByTestCase)) { selectedTestCases.add(testCase); allCovUnits.addAll(unitsCoveredByTestCase); } } return selectedTestCases; } }
47.291139
110
0.671574
8957259270e173b18e77df1b0f27ad646c6dec83
3,496
package carsales.servlets; import carsales.LogicLayer; import carsales.dao.*; import carsales.models.*; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class AddCarServlet extends HttpServlet { private final LogicLayer logic = LogicLayer.getInstance(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setAttribute("brands", logic.findAllBrands()); req.setAttribute("types", logic.findAllBodyType()); req.setAttribute("user", req.getSession().getAttribute("user")); req.getRequestDispatcher("/WEB-INF/car_sales/addcar.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletContext servletContext = this.getServletConfig().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); ServletFileUpload upload = new ServletFileUpload(factory); Map<String, String> fields = new HashMap<>(); fields.put("year", null); fields.put("color", null); fields.put("models", null); fields.put("body_type", null); fields.put("picturePath", null); try { @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(req); if (formItems != null && formItems.size() > 0) { for (FileItem item : formItems) { if (item.isFormField()) { String fieldName = item.getFieldName(); if (fields.containsKey(fieldName)) { fields.put(fieldName, item.getString()); } } else { File fileDir = new File(getServletContext().getRealPath("")); if (!fileDir.exists()) { fileDir.mkdirs(); } File filePath = new File(fileDir + File.separator + "car_sales_views" + File.separator + item.getName()); System.out.println(filePath); item.write(filePath); fields.put("picturePath", "http://localhost:8080/hibernate/car_sales_views/" + item.getName()); } } } if (logic.addCar(req, fields)) { req.getRequestDispatcher("/WEB-INF/car_sales/addcar.jsp").forward(req, resp); } else { resp.sendRedirect(String.format("%s/car_sales_views/cars.html", req.getContextPath())); } } catch (Exception ex) { ex.printStackTrace(); } } }
42.634146
129
0.630149
a3def73350252605c0e31e48676ade2aac0d5444
4,619
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.terminal.arrangement; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.components.StoragePathMacros; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.ToolWindow; import com.intellij.terminal.JBTerminalWidget; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentManager; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.terminal.ShellTerminalWidget; import org.jetbrains.plugins.terminal.TerminalTabState; import org.jetbrains.plugins.terminal.TerminalView; import java.nio.file.Path; import java.util.List; @State(name = "TerminalArrangementManager", storages = @Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)) public class TerminalArrangementManager implements PersistentStateComponent<TerminalArrangementState> { private final TerminalWorkingDirectoryManager myWorkingDirectoryManager; private final Project myProject; private ToolWindow myTerminalToolWindow; private TerminalArrangementState myState; public TerminalArrangementManager(@NotNull Project project) { myProject = project; myWorkingDirectoryManager = new TerminalWorkingDirectoryManager(); } public void setToolWindow(@NotNull ToolWindow terminalToolWindow) { myTerminalToolWindow = terminalToolWindow; myWorkingDirectoryManager.init(terminalToolWindow); } @Nullable @Override public TerminalArrangementState getState() { if (!isAvailable() || myTerminalToolWindow == null) { // do not save state, reuse previously stored state return null; } TerminalArrangementState state = calcArrangementState(myTerminalToolWindow); TerminalCommandHistoryManager.getInstance().retainCommandHistoryFiles(getCommandHistoryFileNames(state), myProject); return state; } @Override public void loadState(@NotNull TerminalArrangementState state) { if (isAvailable()) { myState = state; } } @NotNull private static List<String> getCommandHistoryFileNames(@NotNull TerminalArrangementState state) { return ContainerUtil.mapNotNull(state.myTabStates, tabState -> tabState.myCommandHistoryFileName); } @Nullable public TerminalArrangementState getArrangementState() { return myState; } @NotNull private TerminalArrangementState calcArrangementState(@NotNull ToolWindow terminalToolWindow) { TerminalArrangementState arrangementState = new TerminalArrangementState(); ContentManager contentManager = terminalToolWindow.getContentManager(); for (Content content : contentManager.getContents()) { JBTerminalWidget terminalWidget = TerminalView.getWidgetByContent(content); if (terminalWidget == null) continue; TerminalTabState tabState = new TerminalTabState(); tabState.myTabName = content.getTabName(); tabState.myWorkingDirectory = myWorkingDirectoryManager.getWorkingDirectory(content); tabState.myCommandHistoryFileName = TerminalCommandHistoryManager.getFilename( ShellTerminalWidget.getCommandHistoryFilePath(terminalWidget) ); arrangementState.myTabStates.add(tabState); } Content selectedContent = contentManager.getSelectedContent(); arrangementState.mySelectedTabIndex = selectedContent == null ? -1 : contentManager.getIndexOfContent(selectedContent); return arrangementState; } public void assignCommandHistoryFile(@NotNull JBTerminalWidget terminalWidget, @Nullable TerminalTabState tabState) { if (isAvailable() && terminalWidget instanceof ShellTerminalWidget) { Path historyFile = TerminalCommandHistoryManager.getInstance().getOrCreateCommandHistoryFile( tabState != null ? tabState.myCommandHistoryFileName : null, myProject ); String historyFilePath = historyFile != null ? historyFile.toAbsolutePath().toString() : null; ((ShellTerminalWidget)terminalWidget).setCommandHistoryFilePath(historyFilePath); } } public static @NotNull TerminalArrangementManager getInstance(@NotNull Project project) { return project.getService(TerminalArrangementManager.class); } static boolean isAvailable() { return Registry.is("terminal.persistent.tabs"); } }
41.990909
140
0.792379
93a1d21640eb392c483ccda5527d97baa54c1fec
6,401
/* * Copyright 2016 kohii * * 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.smoothcsv.swing.gridsheet; import com.smoothcsv.commons.constants.Orientation; import com.smoothcsv.swing.gridsheet.model.GridSheetSelectionModel; /** * @author kohii */ public class CellIterator { private final GridSheetPane grid; private final boolean inSelection; private final boolean wrap; private final boolean reverse; private final Orientation orientation; private int minRow; private int maxRow; private int minColumn; private int maxColumn; private int startRow; private int startColumn; private boolean turned; private int row; private int column; public CellIterator(GridSheetPane grid, boolean inSelection, boolean wrap, boolean reverse, Orientation orientation, boolean startsFromFirst) { this.grid = grid; this.inSelection = inSelection; this.wrap = wrap; this.reverse = reverse; this.orientation = orientation; GridSheetSelectionModel selectionModel = grid.getSelectionModel(); if (inSelection) { minRow = selectionModel.getMinRowSelectionIndex(); maxRow = selectionModel.getMaxRowSelectionIndex(); minColumn = selectionModel.getMinColumnSelectionIndex(); maxColumn = selectionModel.getMaxColumnSelectionIndex(); } else { minRow = 0; maxRow = grid.getRowCount() - 1; minColumn = 0; maxColumn = grid.getColumnCount() - 1; } if (minRow == maxRow && minColumn == maxColumn) { turned = true; } if (startsFromFirst) { if (reverse) { this.startRow = maxRow; this.startColumn = maxColumn; } else { this.startRow = minRow; this.startColumn = minColumn; } if (inSelection) { if (orientation == Orientation.HORIZONTAL) { while (!isCellSelected(startRow, startColumn)) { startRow += reverse ? -1 : 1; } } else { while (!isCellSelected(startRow, startColumn)) { startColumn += reverse ? -1 : 1; } } } } else { this.startRow = selectionModel.getRowAnchorIndex(); this.startColumn = selectionModel.getColumnAnchorIndex(); } this.row = startRow; this.column = startColumn; if (orientation == Orientation.VERTICAL) { int tmp; tmp = this.row; this.row = this.column; this.column = tmp; tmp = this.startRow; this.startRow = this.startColumn; this.startColumn = tmp; tmp = this.minRow; this.minRow = this.minColumn; this.minColumn = tmp; tmp = this.maxRow; this.maxRow = this.maxColumn; this.maxColumn = tmp; } } public boolean next() { if (!inSelection) { if (!reverse) { if (column == maxColumn) { if (row == maxRow) { if (!wrap) { return false; } else { if (turned) { return false; } turned = true; row = minRow; } } else { row++; } column = minColumn; } else { column++; } } else { if (column == minColumn) { if (row == minRow) { if (!wrap) { return false; } else { if (turned) { return false; } turned = true; row = maxRow; } } else { row--; } column = maxColumn; } else { column--; } } } else { // In selection if (!reverse) { for (int j = column + 1; j <= maxColumn; j++) { if (isCellSelected(row, j)) { column = j; return true; } } for (int i = row + 1; i <= maxRow; i++) { for (int j = minColumn; j <= maxColumn; j++) { if (isCellSelected(i, j)) { row = i; column = j; return true; } } } if (turned || !wrap) { return false; } turned = true; row = minRow; for (int j = minColumn; j <= maxColumn; j++) { if (isCellSelected(row, j)) { column = j; break; } } } else { for (int j = column - 1; minColumn <= j; j--) { if (isCellSelected(row, j)) { column = j; return true; } } for (int i = row - 1; minRow <= i; i--) { for (int j = maxColumn; minColumn <= j; j--) { if (isCellSelected(i, j)) { row = i; column = j; return true; } } } if (turned || !wrap) { return false; } turned = true; row = maxRow; for (int j = maxColumn; minColumn <= j; j--) { if (isCellSelected(row, j)) { column = j; break; } } } } if (turned && ((!reverse & startRow <= row && startColumn <= column) || (reverse & row <= startRow && column <= startColumn))) { return false; } return true; } private boolean isCellSelected(int row, int column) { int r, c; if (orientation == Orientation.VERTICAL) { c = row; r = column; } else { r = row; c = column; } return grid.getSelectionModel().isCellSelected(r, c); } public int getRow() { return orientation == Orientation.VERTICAL ? column : row; } /** * @return the column */ public int getColumn() { return orientation == Orientation.VERTICAL ? row : column; } @Override public String toString() { return getRow() + "," + getColumn(); } }
25.810484
125
0.528355
09d721a77e2fc99dc957ad2862ccf1bf49ec5d25
5,175
/** * This file is part of HTTP Client library. * Copyright (C) 2014 Noor Dawod. All rights reserved. * https://github.com/noordawod/http-client * * Released under the MIT license * http://en.wikipedia.org/wiki/MIT_License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.fine47.http; import com.fine47.http.request.AbstractRequest; import com.fine47.cache.CacheInterface; import com.fine47.http.response.AbstractResponse; import com.fine47.http.response.BinaryResponse; import java.util.concurrent.ExecutorService; /** * A handy download manager which uses a simple caching interface to store, * fetch and delete Internet resources of type {@link E}. * * @param <E> type of resources which the download manager handles * @see <a href="https://github.com/noordawod/android-cache">Android Cache</a> */ public class DownloadManager<E> { /** * The HTTP Client instance associated with this download manager. */ public final ActivityHttpClient client; /** * The Caching instance associated with this download manager. */ public final CacheInterface<String, E> cache; DownloadManager(ActivityHttpClient client, CacheInterface<String, E> cache) { this.client = client; this.cache = cache; } /** * This will cause the download manager to shutdown and run a garbage- * collection on the cache engine. The process, by the way, will be dispatched * to the thread pool and should, thus, produce no noticeable slowdown. */ public void shutdown() { final ExecutorService threadPool = client.getThreadPool(); if(null != threadPool) { threadPool.execute(new Runnable() { @Override public void run() { cache.runGc(); } }); } } /** * Dispatch a request to download a resource from the Internet. All downloads * use GET method. * * @param <M> meta-data type which could be accompanying this request * @param request generic request to dispatch * @param response generic handler to handle the result */ public <M>void dispatch( final AbstractRequest<M> request, final AbstractResponse<E, M> response ) { // Try to get a cached entry first for this URL. final E cacheEntry = cache.get(request.url); // If there's no cached entry... if(null == cacheEntry) { getImpl(request, response); } else { // Cached entry is available, let's call the response handler on a // thread pool, as is expected. final ExecutorService threadPool = client.getThreadPool(); if(null == threadPool) { // No thread pool configured, so call the handler directly. response.onSuccess(cacheEntry, request); } else { // Execute the handler on a separate thread. threadPool.execute(new Runnable() { @Override public void run() { response.onSuccess(cacheEntry, request); } }); } } } protected <M>void getImpl( final AbstractRequest<M> request, final AbstractResponse<E, M> response ) { // Dispatch a request to download this URL. client.getImpl( request, new BinaryResponseWrapper(request, new BinaryResponse<M>() { @Override public boolean isAlive() { return response.isAlive(); } @Override public void onSuccess( byte[] bytes, AbstractRequest<M> req ) { E cacheEntry = cache.store(request.url, bytes); if(null == cacheEntry) { // Cache entry not saved, call failure handler. onFailure( null, null, new RuntimeException("Unable to store bytes into cache.") ); } else { // Cache entry has been saved, call success handler. response.onSuccess(cacheEntry, request); } } @Override public void onFailure( byte[] bytes, AbstractRequest<M> req, Throwable error ) { response.onFailure(null, request, error); } }) ); } }
31.944444
80
0.657391
82ba1cb8633c208ed139ae570f32be3e14b6b32f
3,866
package br.com.ufg.listaplic.template; import br.com.six2six.fixturefactory.Fixture; import br.com.six2six.fixturefactory.Rule; import br.com.six2six.fixturefactory.loader.TemplateLoader; import br.com.ufg.listaplic.dto.listelab.ListIntegrationDTO; import br.com.ufg.listaplic.dto.listelab.QuestoesIntegrationDTO; import java.util.Collections; import java.util.UUID; public class ListIntegrationDTOTemplate implements TemplateLoader { private static final String ID = "id"; private static final String TITULO = "titulo"; private static final String USUARIO = "usuario"; private static final String NIVEL_DIFICULDADE = "nivelDeDificuldade"; private static final String PRONTA_PARA_APLICACAO = "prontaParaAplicacao"; private static final String QUESTOES_DISCURSIVA = "questoesDiscursiva"; private static final String QUESTOES_MULTIPLA_ESCOLHA = "questoesMultiplaEscolha"; private static final String QUESTOES_ASSOCIACAO_DE_COLUNAS = "questoesAssociacaoDeColunas"; private static final String QUESTOES_VERDADEIRO_OU_FALSO = "questoesVerdadeiroOuFalso"; public enum TYPES { LIST_WITH_ONE_QUESTION, LIST_WITH_TWO_QUESTION, LIST_WITH_FOUR_QUESTION } @Override public void load() { buildListWithOneQuestionTemplate(); buildListWithTwoQuestionTemplate(); buildListWithFourQuestionTemplate(); } private void buildListWithOneQuestionTemplate() { Fixture.of(ListIntegrationDTO.class).addTemplate(TYPES.LIST_WITH_ONE_QUESTION.name(), new Rule() {{ add(ID, UUID.randomUUID()); add(TITULO, "Lista de Teste"); add(USUARIO, "professor@ufg.br"); add(PRONTA_PARA_APLICACAO, true); add(QUESTOES_DISCURSIVA, has(1).of(QuestoesIntegrationDTO.class, QuestoesIntegrationDTOTemplate.TYPES.DISCURSIVE.name())); add(QUESTOES_MULTIPLA_ESCOLHA, Collections.emptyList()); add(QUESTOES_ASSOCIACAO_DE_COLUNAS, Collections.emptyList()); add(QUESTOES_VERDADEIRO_OU_FALSO, Collections.emptyList()); }}); } private void buildListWithTwoQuestionTemplate() { Fixture.of(ListIntegrationDTO.class).addTemplate(TYPES.LIST_WITH_TWO_QUESTION.name(), new Rule() {{ add(ID, UUID.randomUUID()); add(TITULO, "Lista de Teste"); add(USUARIO, "professor@ufg.br"); add(PRONTA_PARA_APLICACAO, true); add(QUESTOES_DISCURSIVA, has(1).of(QuestoesIntegrationDTO.class, QuestoesIntegrationDTOTemplate.TYPES.DISCURSIVE.name())); add(QUESTOES_MULTIPLA_ESCOLHA, has(1).of(QuestoesIntegrationDTO.class, QuestoesIntegrationDTOTemplate.TYPES.MULTIPLE_CHOICE.name())); add(QUESTOES_ASSOCIACAO_DE_COLUNAS, Collections.emptyList()); add(QUESTOES_VERDADEIRO_OU_FALSO, Collections.emptyList()); }}); } private void buildListWithFourQuestionTemplate() { Fixture.of(ListIntegrationDTO.class).addTemplate(TYPES.LIST_WITH_FOUR_QUESTION.name(), new Rule() {{ add(ID, UUID.randomUUID()); add(TITULO, "Lista de Teste"); add(USUARIO, "professor@ufg.br"); add(PRONTA_PARA_APLICACAO, true); add(QUESTOES_DISCURSIVA, has(1).of(QuestoesIntegrationDTO.class, QuestoesIntegrationDTOTemplate.TYPES.DISCURSIVE.name())); add(QUESTOES_MULTIPLA_ESCOLHA, has(1).of(QuestoesIntegrationDTO.class, QuestoesIntegrationDTOTemplate.TYPES.MULTIPLE_CHOICE.name())); add(QUESTOES_ASSOCIACAO_DE_COLUNAS, has(1).of(QuestoesIntegrationDTO.class, QuestoesIntegrationDTOTemplate.TYPES.COLUMN_BINDING.name())); add(QUESTOES_VERDADEIRO_OU_FALSO, has(1).of(QuestoesIntegrationDTO.class, QuestoesIntegrationDTOTemplate.TYPES.TRUE_OR_FALSE.name())); add(NIVEL_DIFICULDADE, 1); }}); } }
49.564103
149
0.722193
e780c20b7940683970fc3e87e2f63f23f7fe47ce
1,679
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos.Rpc.proto package POGOProtos.Rpc; public interface GymBadgeStatsOrBuilder extends // @@protoc_insertion_point(interface_extends:POGOProtos.Rpc.GymBadgeStats) com.google.protobuf.MessageOrBuilder { /** * <code>uint64 total_time_defended_ms = 1;</code> * @return The totalTimeDefendedMs. */ long getTotalTimeDefendedMs(); /** * <code>uint32 num_battles_won = 2;</code> * @return The numBattlesWon. */ int getNumBattlesWon(); /** * <code>uint32 num_berries_fed = 3;</code> * @return The numBerriesFed. */ int getNumBerriesFed(); /** * <code>uint32 num_deploys = 4;</code> * @return The numDeploys. */ int getNumDeploys(); /** * <code>uint32 num_battles_lost = 5;</code> * @return The numBattlesLost. */ int getNumBattlesLost(); /** * <code>repeated .POGOProtos.Rpc.GymBattleProto gym_battles = 15;</code> */ java.util.List<POGOProtos.Rpc.GymBattleProto> getGymBattlesList(); /** * <code>repeated .POGOProtos.Rpc.GymBattleProto gym_battles = 15;</code> */ POGOProtos.Rpc.GymBattleProto getGymBattles(int index); /** * <code>repeated .POGOProtos.Rpc.GymBattleProto gym_battles = 15;</code> */ int getGymBattlesCount(); /** * <code>repeated .POGOProtos.Rpc.GymBattleProto gym_battles = 15;</code> */ java.util.List<? extends POGOProtos.Rpc.GymBattleProtoOrBuilder> getGymBattlesOrBuilderList(); /** * <code>repeated .POGOProtos.Rpc.GymBattleProto gym_battles = 15;</code> */ POGOProtos.Rpc.GymBattleProtoOrBuilder getGymBattlesOrBuilder( int index); }
26.234375
79
0.685527
36394622ede50caf1c64b842ef0bdc9756360331
470
package io.quarkus.reactive.db2.client.deployment; import io.quarkus.builder.item.SimpleBuildItem; import io.quarkus.runtime.RuntimeValue; import io.vertx.db2client.DB2Pool; public final class DB2PoolBuildItem extends SimpleBuildItem { private final RuntimeValue<DB2Pool> db2Pool; public DB2PoolBuildItem(RuntimeValue<DB2Pool> db2Pool) { this.db2Pool = db2Pool; } public RuntimeValue<DB2Pool> getDB2Pool() { return db2Pool; } }
23.5
61
0.751064
010e41170b7338af303c19373428f4d52961a436
6,598
/* * Copyright 2019-2021 The kafkaproxy developers (see CONTRIBUTORS) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.dajudge.kafkaproxy.roundtrip.cluster.container; import com.dajudge.kafkaproxy.roundtrip.cluster.KafkaWaitStrategy; import com.dajudge.kafkaproxy.roundtrip.comm.CommunicationSetup; import com.dajudge.kafkaproxy.roundtrip.comm.ServerSecurity; import com.github.dockerjava.api.command.InspectContainerResponse; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; import org.testcontainers.containers.output.Slf4jLogConsumer; import org.testcontainers.images.builder.Transferable; import org.testcontainers.utility.MountableFile; import java.time.Duration; import java.util.HashMap; import java.util.Map; import static com.dajudge.kafkaproxy.roundtrip.cluster.container.Version.CP_VERSION; import static com.dajudge.kafkaproxy.roundtrip.util.Util.indent; import static com.dajudge.kafkaproxy.roundtrip.util.Util.safeToString; import static java.lang.String.join; import static java.lang.String.valueOf; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.stream.Collectors.joining; import static org.testcontainers.images.PullPolicy.alwaysPull; import static org.testcontainers.utility.MountableFile.forClasspathResource; public class KafkaContainer extends GenericContainer<KafkaContainer> { private static final Logger LOG = LoggerFactory.getLogger(KafkaContainer.class); private static final int KAFKA_CLIENT_PORT = 9092; private static final int KAFKA_BROKER_PORT = 9093; private static final String ENTRYPOINT_PATH = "/customEntrypoint.sh"; private final String internalHostname; private final ServerSecurity serverSecurity; public KafkaContainer( final ZookeeperContainer zookeeper, final int brokerId, final Network network, final CommunicationSetup communicationSetup ) { super("confluentinc/cp-kafka:" + CP_VERSION); this.internalHostname = "broker" + brokerId; serverSecurity = communicationSetup.getServerSecurity("CN=localhost"); this.withNetwork(network) .withImagePullPolicy(alwaysPull()) .withNetworkAliases(internalHostname) .withCreateContainerCmdModifier(mod -> { mod.withUser("root"); }) .withEnv("KAFKA_ZOOKEEPER_CONNECT", zookeeper.getEndpoint()) .withEnv("CONFLUENT_SUPPORT_METRICS_ENABLE", "0") .withEnv("KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR", "1") .withEnv("KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS", "0") .withEnv("KAFKA_OFFSETS_TOPIC_NUM_PARTITIONS", "1") .withEnv("KAFKA_BROKER_ID", valueOf(brokerId)) .withEnv("KAFKA_NUM_PARTITIONS", "10") .withEnv("KAFKA_LISTENERS", join(",", "CLIENT://:" + KAFKA_CLIENT_PORT, "BROKER://:" + KAFKA_BROKER_PORT )) .withEnv("KAFKA_LISTENER_SECURITY_PROTOCOL_MAP", join(",", "CLIENT:" + serverSecurity.getClientProtocol(), "BROKER:PLAINTEXT" )) .withEnv("KAFKA_INTER_BROKER_LISTENER_NAME", "BROKER") .withEnv("KAFKA_SSL_TRUSTSTORE_LOCATION", serverSecurity.getTrustStoreLocation()) .withEnv("KAFKA_SSL_TRUSTSTORE_PASSWORD", safeToString(serverSecurity.getTrustStorePassword())) .withEnv("KAFKA_SSL_TRUSTSTORE_TYPE", serverSecurity.getTrustStoreType()) .withEnv("KAFKA_SSL_KEYSTORE_LOCATION", serverSecurity.getKeyStoreLocation()) .withEnv("KAFKA_SSL_KEYSTORE_PASSWORD", safeToString(serverSecurity.getKeyStorePassword())) .withEnv("KAFKA_SSL_KEYSTORE_TYPE", serverSecurity.getKeyStoreType()) .withEnv("KAFKA_SSL_KEY_PASSWORD", safeToString(serverSecurity.getKeyPassword())) .withEnv("KAFKA_SSL_CLIENT_AUTH", serverSecurity.getClientAuth()) .withExposedPorts(KAFKA_CLIENT_PORT) .withCopyFileToContainer(entrypointScript(), ENTRYPOINT_PATH) .withCommand("sh", ENTRYPOINT_PATH) .waitingFor(new KafkaWaitStrategy( KAFKA_CLIENT_PORT, communicationSetup.getClientSecurity() )) .withStartupTimeout(Duration.ofSeconds(300)) .withLogConsumer(new Slf4jLogConsumer(LOG)); } @NotNull private MountableFile entrypointScript() { return forClasspathResource("customEntrypoint.sh", 777); } @Override protected void containerIsStarting(final InspectContainerResponse containerInfo) { final String configFile = configFile(); LOG.info("Uploading keystores to container..."); serverSecurity.uploadKeyStores(this::copyFileToContainer); LOG.info("Writing config to container:\n{}", indent(4, configFile)); copyFileToContainer(Transferable.of(configFile.getBytes(UTF_8)), "/tmp/config.env"); } private String configFile() { final Map<String, String> config = new HashMap<String, String>() {{ put("KAFKA_ADVERTISED_LISTENERS", join(",", "CLIENT://localhost:" + getMappedPort(KAFKA_CLIENT_PORT), "BROKER://" + internalHostname + ":" + KAFKA_BROKER_PORT )); }}; return config.entrySet().stream() .map((e) -> e.getKey() + "=" + e.getValue()) .collect(joining("\n")); } public String getClientEndpoint() { return "localhost:" + getMappedPort(KAFKA_CLIENT_PORT); } @Override public boolean equals(final Object o) { return super.equals(o); } @Override public int hashCode() { return super.hashCode(); } }
45.503448
111
0.679903
859b7329386acf81fae5fc0a829d7445ad4fe5a0
263
package cardealer.repositories; import cardealer.entities.Part; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface PartRepository extends JpaRepository<Part, Integer> { }
26.3
70
0.847909
ff19e837c03ffdc6d47031244a8720a3face58e3
8,029
package org.apache.lucene.index; /* * 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. */ import java.io.File; import java.io.IOException; import java.util.*; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.DocumentStoredFieldVisitor; import org.apache.lucene.document.DoubleField; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType.NumericType; import org.apache.lucene.document.FieldType; import org.apache.lucene.document.FloatField; import org.apache.lucene.document.IntField; import org.apache.lucene.document.LongField; import org.apache.lucene.document.StoredField; import org.apache.lucene.document.StringField; import org.apache.lucene.index.FieldInfo.IndexOptions; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.search.FieldCache; import org.apache.lucene.store.BaseDirectory; import org.apache.lucene.store.BufferedIndexInput; import org.apache.lucene.store.Directory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util._TestUtil; import org.junit.AfterClass; import org.junit.BeforeClass; public class TestFieldsReader extends LuceneTestCase { private static Directory dir; private static Document testDoc; private static FieldInfos.Builder fieldInfos = null; @BeforeClass public static void beforeClass() throws Exception { testDoc = new Document(); fieldInfos = new FieldInfos.Builder(); DocHelper.setupDoc(testDoc); for (IndexableField field : testDoc) { fieldInfos.addOrUpdate(field.name(), field.fieldType()); } dir = newDirectory(); IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy()); conf.getMergePolicy().setNoCFSRatio(0.0); IndexWriter writer = new IndexWriter(dir, conf); writer.addDocument(testDoc); writer.close(); FaultyIndexInput.doFail = false; } @AfterClass public static void afterClass() throws Exception { dir.close(); dir = null; fieldInfos = null; testDoc = null; } public void test() throws IOException { assertTrue(dir != null); assertTrue(fieldInfos != null); IndexReader reader = DirectoryReader.open(dir); Document doc = reader.document(0); assertTrue(doc != null); assertTrue(doc.getField(DocHelper.TEXT_FIELD_1_KEY) != null); Field field = (Field) doc.getField(DocHelper.TEXT_FIELD_2_KEY); assertTrue(field != null); assertTrue(field.fieldType().storeTermVectors()); assertFalse(field.fieldType().omitNorms()); assertTrue(field.fieldType().indexOptions() == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); field = (Field) doc.getField(DocHelper.TEXT_FIELD_3_KEY); assertTrue(field != null); assertFalse(field.fieldType().storeTermVectors()); assertTrue(field.fieldType().omitNorms()); assertTrue(field.fieldType().indexOptions() == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); field = (Field) doc.getField(DocHelper.NO_TF_KEY); assertTrue(field != null); assertFalse(field.fieldType().storeTermVectors()); assertFalse(field.fieldType().omitNorms()); assertTrue(field.fieldType().indexOptions() == IndexOptions.DOCS_ONLY); DocumentStoredFieldVisitor visitor = new DocumentStoredFieldVisitor(DocHelper.TEXT_FIELD_3_KEY); reader.document(0, visitor); final List<IndexableField> fields = visitor.getDocument().getFields(); assertEquals(1, fields.size()); assertEquals(DocHelper.TEXT_FIELD_3_KEY, fields.get(0).name()); reader.close(); } public static class FaultyFSDirectory extends BaseDirectory { Directory fsDir; public FaultyFSDirectory(File dir) { fsDir = newFSDirectory(dir); lockFactory = fsDir.getLockFactory(); } @Override public IndexInput openInput(String name, IOContext context) throws IOException { return new FaultyIndexInput(fsDir.openInput(name, context)); } @Override public String[] listAll() throws IOException { return fsDir.listAll(); } @Override public boolean fileExists(String name) throws IOException { return fsDir.fileExists(name); } @Override public void deleteFile(String name) throws IOException { fsDir.deleteFile(name); } @Override public long fileLength(String name) throws IOException { return fsDir.fileLength(name); } @Override public IndexOutput createOutput(String name, IOContext context) throws IOException { return fsDir.createOutput(name, context); } @Override public void sync(Collection<String> names) throws IOException { fsDir.sync(names); } @Override public void close() throws IOException { fsDir.close(); } } private static class FaultyIndexInput extends BufferedIndexInput { IndexInput delegate; static boolean doFail; int count; private FaultyIndexInput(IndexInput delegate) { super("FaultyIndexInput(" + delegate + ")", BufferedIndexInput.BUFFER_SIZE); this.delegate = delegate; } private void simOutage() throws IOException { if (doFail && count++ % 2 == 1) { throw new IOException("Simulated network outage"); } } @Override public void readInternal(byte[] b, int offset, int length) throws IOException { simOutage(); delegate.seek(getFilePointer()); delegate.readBytes(b, offset, length); } @Override public void seekInternal(long pos) throws IOException { } @Override public long length() { return delegate.length(); } @Override public void close() throws IOException { delegate.close(); } @Override public FaultyIndexInput clone() { FaultyIndexInput i = new FaultyIndexInput(delegate.clone()); // seek the clone to our current position try { i.seek(getFilePointer()); } catch (IOException e) { throw new RuntimeException(); } return i; } } // LUCENE-1262 public void testExceptions() throws Throwable { File indexDir = _TestUtil.getTempDir("testfieldswriterexceptions"); try { Directory dir = new FaultyFSDirectory(indexDir); IndexWriterConfig iwc = newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer(random())).setOpenMode(OpenMode.CREATE); IndexWriter writer = new IndexWriter(dir, iwc); for(int i=0;i<2;i++) writer.addDocument(testDoc); writer.forceMerge(1); writer.close(); IndexReader reader = DirectoryReader.open(dir); FaultyIndexInput.doFail = true; boolean exc = false; for(int i=0;i<2;i++) { try { reader.document(i); } catch (IOException ioe) { // expected exc = true; } try { reader.document(i); } catch (IOException ioe) { // expected exc = true; } } assertTrue(exc); reader.close(); dir.close(); } finally { _TestUtil.rmDir(indexDir); } } }
32.905738
136
0.702952
c1907ac99e3d5b67b52cf3d0582f6a7f0bea2f3b
2,609
package com.twitter.aurora.scheduler.thrift.aop; import com.google.common.collect.ImmutableSet; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.matcher.Matchers; import org.junit.Before; import org.junit.Test; import com.twitter.aurora.gen.APIVersion; import com.twitter.aurora.gen.AuroraAdmin; import com.twitter.aurora.gen.GetJobsResult; import com.twitter.aurora.gen.JobConfiguration; import com.twitter.aurora.gen.Response; import com.twitter.aurora.gen.Result; import com.twitter.aurora.scheduler.thrift.auth.DecoratedThrift; import com.twitter.common.testing.easymock.EasyMockTest; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static com.twitter.aurora.gen.ResponseCode.OK; public class APIVersionInterceptorTest extends EasyMockTest { private static final String ROLE = "bob"; private AuroraAdmin.Iface realThrift; private AuroraAdmin.Iface decoratedThrift; private APIVersionInterceptor interceptor; @Before public void setUp() { interceptor = new APIVersionInterceptor(); realThrift = createMock(AuroraAdmin.Iface.class); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { MockDecoratedThrift.bindForwardedMock(binder(), realThrift); AopModule.bindThriftDecorator( binder(), Matchers.annotatedWith(DecoratedThrift.class), interceptor); } }); decoratedThrift = injector.getInstance(AuroraAdmin.Iface.class); } @Test public void testVersionIsSet() throws Exception { Response response = new Response().setResponseCode(OK) .setResult(Result.getJobsResult(new GetJobsResult() .setConfigs(ImmutableSet.<JobConfiguration>of()))); expect(realThrift.getJobs(ROLE)).andReturn(response); control.replay(); assertNotNull(decoratedThrift.getJobs(ROLE).version); } @Test public void testExistingVersion() throws Exception { Response response = new Response().setResponseCode(OK) .setResult(Result.getJobsResult(new GetJobsResult() .setConfigs(ImmutableSet.<JobConfiguration>of()))) .setVersion(new APIVersion().setMajor(1)); expect(realThrift.getJobs(ROLE)).andReturn(response); control.replay(); Response decoratedResponse = decoratedThrift.getJobs(ROLE); assertNotNull(decoratedResponse.version); assertEquals(decoratedResponse.version.getMajor(), 1); } }
32.209877
68
0.753162
41b17acd8be6fd0cd82b557fc04005ebbce115b3
1,926
/* * Copyright (C) 2022 Objectos Software LTDA. * * 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 objectos.lang; import static org.testng.Assert.assertEquals; import org.testng.annotations.Test; public class Event3Test { final Note3<Void, Void, Void> TRACE = Note3.trace(); final Note3<Void, Void, Void> DEBUG = Note3.debug(); final Note3<Void, Void, Void> INFO = Note3.info(); final Note3<Void, Void, Void> WARN = Note3.warn(); final Note3<Void, Void, Void> ERROR = Note3.error(); @Test public void key() { assertEquals(TRACE.key(), "Event3Test.java:24"); assertEquals(DEBUG.key(), "Event3Test.java:26"); assertEquals(INFO.key(), "Event3Test.java:28"); assertEquals(WARN.key(), "Event3Test.java:30"); assertEquals(ERROR.key(), "Event3Test.java:32"); } @Test public void level() { assertEquals(TRACE.level(), Level.TRACE); assertEquals(DEBUG.level(), Level.DEBUG); assertEquals(INFO.level(), Level.INFO); assertEquals(WARN.level(), Level.WARN); assertEquals(ERROR.level(), Level.ERROR); } @Test public void source() { assertEquals(TRACE.source(), "objectos.lang.Event3Test"); assertEquals(DEBUG.source(), "objectos.lang.Event3Test"); assertEquals(INFO.source(), "objectos.lang.Event3Test"); assertEquals(WARN.source(), "objectos.lang.Event3Test"); assertEquals(ERROR.source(), "objectos.lang.Event3Test"); } }
31.57377
75
0.702492
e45cc962afb8635a6f9c2e5be50c764b1559ed86
9,377
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.vanilla.mixin.network; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.network.play.INetHandlerPlayServer; import net.minecraft.network.play.client.C07PacketPlayerDigging; import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement; import net.minecraft.network.play.server.S23PacketBlockChange; import net.minecraft.server.MinecraftServer; import net.minecraft.server.management.ServerConfigurationManager; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IChatComponent; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.WorldServer; import org.spongepowered.api.entity.EntityInteractionTypes; import org.spongepowered.api.entity.player.Player; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.entity.player.PlayerChatEvent; import org.spongepowered.api.event.entity.player.PlayerQuitEvent; import org.spongepowered.api.text.Texts; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.common.Sponge; import org.spongepowered.common.registry.SpongeGameRegistry; import org.spongepowered.common.text.SpongeTexts; import org.spongepowered.common.util.VecHelper; import org.spongepowered.vanilla.util.EntityUtils; @Mixin(NetHandlerPlayServer.class) public abstract class MixinNetHandlerPlayServer implements INetHandlerPlayServer { @Shadow private EntityPlayerMP playerEntity; @Shadow private MinecraftServer serverController; boolean isRightClickAirCancelled; @Redirect(method = "processChatMessage", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/management/ServerConfigurationManager;sendChatMsgImpl(Lnet/minecraft/util/IChatComponent;Z)V")) public void onProcessChatMessage(ServerConfigurationManager this$0, IChatComponent component, boolean isChat) { final PlayerChatEvent event = SpongeEventFactory.createPlayerChat(Sponge.getGame(), (Player) this.playerEntity, SpongeTexts.toText(component), Texts.of((String) ((ChatComponentTranslation) component).getFormatArgs()[1]), ((Player) this.playerEntity).getMessageSink()); if (!Sponge.getGame().getEventManager().post(event)) { event.getSink().sendMessage(event.getNewMessage()); } } @Redirect(method = "onDisconnect", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/management/ServerConfigurationManager;sendChatMsg(Lnet/minecraft/util/IChatComponent;)V")) public void onDisconnectHandler(ServerConfigurationManager this$0, IChatComponent component) { final PlayerQuitEvent event = SpongeEventFactory.createPlayerQuit(Sponge.getGame(), (Player) this.playerEntity, SpongeTexts.toText (component), ((Player) this.playerEntity).getMessageSink()); Sponge.getGame().getEventManager().post(event); event.getSink().sendMessage(event.getNewMessage()); } @Inject(method = "processPlayerDigging", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;isBlockProtected" + "(Lnet/minecraft/world/World;Lnet/minecraft/util/BlockPos;Lnet/minecraft/entity/player/EntityPlayer;)Z"), cancellable = true) public void injectProcessPlayerDigging(C07PacketPlayerDigging packetIn, CallbackInfo ci) { // We'll handle all the logic here ci.cancel(); final WorldServer worldserver = this.serverController.worldServerForDimension(this.playerEntity.dimension); //TODO Quote gabizou: Calculate the clicked location on the server. Hmmm, sounds fun...come back and do later -_-. boolean cancelled = Sponge.getGame().getEventManager().post(SpongeEventFactory.createPlayerInteractBlock(Sponge.getGame(), new Cause(null, this.playerEntity, null), (Player) this.playerEntity, new Location((World) worldserver, VecHelper.toVector(packetIn.getPosition())), SpongeGameRegistry.directionMap.inverse().get(packetIn.getFacing()), EntityInteractionTypes.ATTACK, null)); boolean revert = cancelled; if (!cancelled) { if (!this.serverController.isBlockProtected(worldserver, packetIn.getPosition(), this.playerEntity) && worldserver.getWorldBorder() .contains(packetIn.getPosition())) { this.playerEntity.theItemInWorldManager.onBlockClicked(packetIn.getPosition(), packetIn.getFacing()); } else { revert = true; } } if (revert) { this.playerEntity.playerNetServerHandler.sendPacket(new S23PacketBlockChange(worldserver, packetIn.getPosition())); } } /** * Invoke before {@code packetIn.getPlacedBlockDirection() == 255} (line 576 in source) to reset "isRightClickAirCancelled" flag. * @param packetIn Injected packet param * @param ci Info to provide mixin on how to handle the callback */ @Inject(method = "processPlayerBlockPlacement", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/play/client/C08PacketPlayerBlockPlacement;getPlacedBlockDirection()I", ordinal = 1)) public void injectBeforeBlockDirectionCheck(C08PacketPlayerBlockPlacement packetIn, CallbackInfo ci) { this.isRightClickAirCancelled = false; } /** * Invoke after {@code packetIn.getPlacedBlockDirection() == 255} (line 576 in source) to fire {@link org.spongepowered.api.event.entity * .player.PlayerInteractEvent} on right click with air with item in-hand. * @param packetIn Injected packet param * @param ci Info to provide mixin on how to handle the callback */ @Inject(method = "processPlayerBlockPlacement", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/play/client/C08PacketPlayerBlockPlacement;getPlacedBlockDirection()I", ordinal = 1, shift = At.Shift.BY, by = 3)) public void injectBeforeItemStackCheck(C08PacketPlayerBlockPlacement packetIn, CallbackInfo ci) { final MovingObjectPosition objectPosition = EntityUtils.rayTraceFromEntity(this.playerEntity, 4, 1); if (objectPosition != null && objectPosition.entityHit == null) { this.isRightClickAirCancelled = Sponge.getGame().getEventManager().post(SpongeEventFactory.createPlayerInteract(Sponge.getGame(), (Player) this.playerEntity, EntityInteractionTypes.USE, null)); } } /** * Invoke before {@code itemstack == null} (line 578 in source) to stop the logic for using an item if {@link org.spongepowered.api.event * .entity.player.PlayerInteractEvent} was cancelled. * @param packetIn Injected packet param * @param ci Info to provide mixin on how to handle the callback */ @Inject(method = "processPlayerBlockPlacement", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/management/ItemInWorldManager;tryUseItem(Lnet/minecraft/entity/player/EntityPlayer;" + "Lnet/minecraft/world/World;Lnet/minecraft/item/ItemStack;)Z", ordinal = 0), cancellable = true) public void injectAfterItemStackCheck(C08PacketPlayerBlockPlacement packetIn, CallbackInfo ci) { // Handle interact logic ci.cancel(); if (!this.isRightClickAirCancelled) { this.playerEntity.theItemInWorldManager .tryUseItem(this.playerEntity, this.serverController.worldServerForDimension(this.playerEntity.dimension), this.playerEntity.inventory.getCurrentItem()); } } }
56.830303
147
0.73339
7353f0f24ec2f43ffa17df9098af2b78f04c644c
157
package dev.kosztadani.examples.mock.api; public interface Sensor { /** * @return The temperature, in degrees Celsius. */ int sense(); }
15.7
51
0.636943
5f675ad4a4c9014e2cb90b035353d824d0a98aed
808
package br.com.zupacademy.vinicius.mercadolivre.produto.pergunta_usuario_produto; import br.com.zupacademy.vinicius.mercadolivre.produto.Produto; import br.com.zupacademy.vinicius.mercadolivre.produto.ProdutoRepository; import br.com.zupacademy.vinicius.mercadolivre.usuario.Usuario; import javax.validation.constraints.NotBlank; import java.util.Optional; public class PerguntaForm { @NotBlank private String titulo; public Pergunta toModel(Long id, ProdutoRepository repository, Usuario usuario) { Optional<Produto> produto = repository.findById(id); if (produto.isEmpty()) throw new IllegalArgumentException("Não existe um produto com o id "+id+"."); return new Pergunta(this.titulo, usuario); } public String getTitulo() { return titulo; } }
32.32
108
0.756188
08f10b1dc5799deebc47496b0ff6d93f432fc173
1,877
package mage.cards.v; import java.util.UUID; import mage.MageInt; import mage.abilities.common.EntersBattlefieldAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.condition.common.KickedCondition; import mage.abilities.effects.common.combat.CantAttackUnlessDefenderControllsPermanent; import mage.abilities.effects.common.counter.AddCountersSourceEffect; import mage.abilities.keyword.KickerAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Zone; import mage.counters.CounterType; import mage.filter.common.FilterLandPermanent; /** * * @author LoneFox */ public final class VodalianSerpent extends CardImpl { public VodalianSerpent(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{3}{U}"); this.subtype.add(SubType.SERPENT); this.power = new MageInt(2); this.toughness = new MageInt(2); // Kicker {2} this.addAbility(new KickerAbility("{2}")); // Vodalian Serpent can't attack unless defending player controls an Island. this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new CantAttackUnlessDefenderControllsPermanent(new FilterLandPermanent(SubType.ISLAND, "an Island")))); // If Vodalian Serpent was kicked, it enters the battlefield with four +1/+1 counters on it. this.addAbility(new EntersBattlefieldAbility(new AddCountersSourceEffect(CounterType.P1P1.createInstance(4)), KickedCondition.instance, "If {this} was kicked, it enters the battlefield with four +1/+1 counters on it.", "")); } public VodalianSerpent(final VodalianSerpent card) { super(card); } @Override public VodalianSerpent copy() { return new VodalianSerpent(this); } }
36.803922
169
0.746937
606f81fb88f0424c7f259104dff08075ed5a9977
4,542
import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.Image; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.IOException; import javax.swing.JLabel; import java.awt.Dimension; import java.awt.Font; import javax.swing.SwingConstants; public class frmAbout extends JFrame { private static final long serialVersionUID = 7816880762813642189L; private JPanel contentPane; public frmAbout() { setIconImage(Toolkit.getDefaultToolkit().getImage(frmAbout.class.getResource("/resources/graphics/AppIcon.png"))); setResizable(false); setTitle("About BDU"); addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent windowEvent) { // Open main menu Main.window_manager.OpenWindow(0); } }); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setPreferredSize(new Dimension(684, 322)); setContentPane(contentPane); contentPane.setLayout(null); // Pack and center the JFrame pack(); setLocationRelativeTo(null); // LABELS // lblBrainwaveDetectionUtility JLabel lblBrainwaveDetectionUtility = new JLabel("<html><body style=\"text-align: left; text-justify: inter-word;\">Brainwave Detection Utility (BDU) is designed to work with the \"Star Wars The Force Trainer II\" headset. Other NeuroSky products should work but are untested.<br/><br/>This program uses jSerialComm, a platform-independent serial port access for Java. You can learn more about it here: https://fazecast.github.io/jSerialComm/.<br/><br/>This program also uses XChart, a light-weight and convenient library for plotting data. You can learn more about it here: https://knowm.org/open-source/xchart/.<br/><br/>BDU is licensed to you under the Apache 2.0 License. See https://www.apache.org/licenses/LICENSE-2.0.txt for more information.</body></html>"); lblBrainwaveDetectionUtility.setHorizontalAlignment(SwingConstants.LEFT); lblBrainwaveDetectionUtility.setVerticalAlignment(SwingConstants.TOP); lblBrainwaveDetectionUtility.setBounds(224, 103, 450, 229); contentPane.add(lblBrainwaveDetectionUtility); // lblHeading JLabel lblHeading = new JLabel("Brainwave Detection Utility"); lblHeading.setHorizontalAlignment(SwingConstants.CENTER); lblHeading.setFont(new Font("Lucida Grande", Font.PLAIN, 35)); lblHeading.setBounds(218, 6, 456, 48); contentPane.add(lblHeading); // lblVersion JLabel lblVersion = new JLabel("Version 2.0"); lblVersion.setFont(new Font("Lucida Grande", Font.PLAIN, 20)); lblVersion.setBounds(224, 46, 143, 25); contentPane.add(lblVersion); // lblAuthor JLabel lblAuthor = new JLabel("By KernelGhost"); lblAuthor.setFont(new Font("Lucida Grande", Font.PLAIN, 15)); lblAuthor.setBounds(224, 66, 143, 25); contentPane.add(lblAuthor); // IMAGES // AppIcon try { JLabel lblIcon = new JLabel(""); lblIcon.setBounds(12, 55, 200, 200); BufferedImage imgIcon; imgIcon = ImageIO.read(getClass().getResource("/resources/graphics/AppIcon.png")); Image imgIconScaled = imgIcon.getScaledInstance(lblIcon.getWidth(), lblIcon.getHeight(), Image.SCALE_SMOOTH); ImageIcon icoIcon = new ImageIcon(imgIconScaled); lblIcon.setIcon(icoIcon); contentPane.add(lblIcon); } catch (IOException e1) {} // XChart try { JLabel lblXChart = new JLabel(""); lblXChart.setToolTipText("XChart"); lblXChart.setBounds(400, 47, 44, 44); BufferedImage imgIcon; imgIcon = ImageIO.read(getClass().getResource("/resources/graphics/XChart.png")); Image imgIconScaled = imgIcon.getScaledInstance(lblXChart.getWidth(), lblXChart.getHeight(), Image.SCALE_SMOOTH); ImageIcon icoIcon = new ImageIcon(imgIconScaled); lblXChart.setIcon(icoIcon); contentPane.add(lblXChart); } catch (IOException e1) {} // JSerialComm try { JLabel lblJSerialComm = new JLabel(""); lblJSerialComm.setToolTipText("jSerialComm"); lblJSerialComm.setBounds(340, 47, 51, 44); BufferedImage imgIcon; imgIcon = ImageIO.read(getClass().getResource("/resources/graphics/JSerialComm.png")); Image imgIconScaled = imgIcon.getScaledInstance(lblJSerialComm.getWidth(), lblJSerialComm.getHeight(), Image.SCALE_SMOOTH); ImageIcon icoIcon = new ImageIcon(imgIconScaled); lblJSerialComm.setIcon(icoIcon); contentPane.add(lblJSerialComm); } catch (IOException e1) {} } }
41.669725
769
0.747908
6ded1cb8c23e709eadab42bf0d72a1d65688bd9e
10,241
package visnode.challenge; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; import visnode.application.ExceptionHandler; import visnode.application.Messages; import visnode.commons.ImageScale; import visnode.commons.swing.WindowFactory; import visnode.gui.IconFactory; import visnode.gui.ListItemComponent; import visnode.gui.ScrollFactory; import visnode.gui.UIHelper; import visnode.repository.GroupRepository; import visnode.repository.RepositoryException; import visnode.repository.UserRepository; import visnode.user.User; /** * The challenge user panel */ public class MissionUserPanel extends JPanel { /** Thumbnail size */ private static final int THUMBNAIL_SIZE = 64; /** Group */ private JComboBox<Group> groups; /** Button filter */ private JButton buttonFilter; /** Button update */ private JButton buttonUpdate; /** Button new group */ private JButton buttonNewGroup; /** Items list */ private JPanel items; /** Container */ private JPanel container; /** Users */ private List<User> users; /** * Creates a new mission list panel */ private MissionUserPanel() { super(); loadUsers(); initGui(); initEvents(); } /** * Shows the dialog */ public static void showDialog() { Messages.get().message("user").subscribe((msg) -> { WindowFactory.modal().title(msg).create((container) -> { container.setBorder(null); container.add(new MissionUserPanel()); }).setVisible(true); }); } /** * Initializes the interface */ private void initGui() { setLayout(new BorderLayout()); setPreferredSize(new Dimension(800, 500)); add(buildGroup(), BorderLayout.NORTH); add(buildList()); add(buildButtons(), BorderLayout.SOUTH); loadGroups(); loadUsersList(); } /** * Load users */ private void loadUsers() { this.users = new ArrayList<>(); try { this.users = UserRepository.get().getAll(); } catch (RepositoryException ex) { ExceptionHandler.get().handle(ex); } } /** * Load groups */ private void loadGroups() { Object selected = groups.getSelectedItem(); groups.removeAllItems(); groups.addItem(new Group("All")); try { GroupRepository.get().getAll().forEach((it) -> { groups.addItem(it); }); if (selected == null) { groups.setSelectedIndex(0); } else { groups.setSelectedItem(selected); } } catch (RepositoryException ex) { ExceptionHandler.get().handle(ex); } } /** * Load user list */ private void loadUsersList() { if (items != null) { container.remove(items); } container.add(buildListComponent()); container.revalidate(); repaint(); } /** * Initializes the events */ private void initEvents() { buttonNewGroup.addActionListener((evt) -> { GroupFormPanel.showDialog(); loadGroups(); }); buttonUpdate.addActionListener((evt) -> { Group group = (Group) groups.getSelectedItem(); if (group == null || group.getId() == 0) { JOptionPane.showMessageDialog(null, "No group selected"); return; } GroupFormPanel.showDialog(group); loadUsersList(); }); buttonFilter.addActionListener((evt) -> { loadUsersList(); }); } /** * Builds the group box * * @return JComponent */ private JComponent buildGroup() { // Builds the label JLabel label = new JLabel(); Messages.get().message("challenge.group").subscribe((msg) -> { label.setText(msg); }).dispose(); // Build de group combo-box groups = new JComboBox(); // Action filter buttonFilter = new JButton(IconFactory.get().create("fa:search")); // Action update buttonUpdate = new JButton(IconFactory.get().create("fa:pencil")); // Action new group buttonNewGroup = new JButton(); Messages.get().message("challenge.newGroup").subscribe((msg) -> { buttonNewGroup.setText(msg); buttonNewGroup.setIcon(IconFactory.get().create("fa:plus")); }); // Builds the box JPanel panel = new JPanel(); panel.setLayout(new FlowLayout(FlowLayout.LEFT)); panel.add(label); panel.add(groups); panel.add(buttonFilter); panel.add(buttonUpdate); panel.add(buttonNewGroup); return panel; } /** * Build the buttons * * @return JComponent */ private JComponent buildButtons() { JButton button = new JButton(); Messages.get().message("next").subscribe((msg) -> { button.setText(msg); button.setIcon(IconFactory.get().create("fa:check")); }); button.addActionListener((evt) -> { SwingUtilities.getWindowAncestor(MissionUserPanel.this).dispose(); }); JComponent panel = new JPanel(); panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); panel.setLayout(new BorderLayout()); panel.add(button, BorderLayout.EAST); return panel; } /** * Creates the mission list * * @return JComponent */ private JComponent buildList() { container = new JPanel(); container.setLayout(new BorderLayout()); JScrollPane scrollPane = ScrollFactory.pane(container).create(); scrollPane.setBorder(null); return scrollPane; } /** * Returns the list component * * @return JComponent */ private JComponent buildListComponent() { JPanel list = new JPanel(); list.setLayout(new GridLayout(0, 1)); List<User> userList = users; Group group = (Group) groups.getSelectedItem(); if (group != null && group.getId() > 0) { userList = users.stream().filter((user) -> { return group.getUsers().stream() .filter((it) -> it.getUser().getId() == user.getId()) .findFirst().isPresent(); }).collect(Collectors.toList()); } userList.forEach((user) -> { list.add(buildListItem(user)); }); items = new JPanel(); items.setLayout(new BorderLayout()); items.add(list, BorderLayout.NORTH); return items; } /** * Creates the user list item * * @return JComponent */ private JComponent buildListItem(User user) { // Solve challenge JButton solve = new JButton(); Messages.get().message("challenge").subscribe((msg) -> { solve.setIcon(IconFactory.get().create("fa:filter")); solve.setText(msg); }); solve.addActionListener((ev) -> { SwingUtilities.getWindowAncestor(MissionUserPanel.this).dispose(); MissionUserChallengePanel.showDialog(user); }); // Conquests challenge JButton conquest = new JButton(); Messages.get().message("challenge.conquest").subscribe((msg) -> { conquest.setIcon(IconFactory.get().create("fa:dollar")); conquest.setText(msg); }); conquest.addActionListener((ev) -> { ChallengeConquestPanel.showDialog(user); }); // Buttons GridLayout buttonsActionsLayout = new GridLayout(2, 1); buttonsActionsLayout.setVgap(5); JPanel buttonsActions = new JPanel(); buttonsActions.setLayout(buttonsActionsLayout); buttonsActions.add(solve); buttonsActions.add(conquest); JPanel buttonsPanel = new JPanel(); buttonsPanel.setLayout(new BorderLayout()); buttonsPanel.add(buttonsActions, BorderLayout.NORTH); buttonsPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 5)); // Image BufferedImage image = ImageScale.scale(user.getImageBuffered(), THUMBNAIL_SIZE); JLabel icon = new JLabel(new ImageIcon(image)); icon.setBorder(BorderFactory.createLineBorder(UIHelper.getColor("Node.border"))); JPanel imagePanel = new JPanel(); imagePanel.add(icon); // Name JLabel name = new JLabel(); name.setText(user.getName()); name.setFont(new Font("Segoe UI", Font.BOLD, 18)); // Xp JLabel xp = new JLabel(String.format("%s xp", user.getXp())); xp.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); // Header JPanel header = new JPanel(); header.setLayout(new FlowLayout()); header.add(name); // Container JPanel container = new JPanel(); container.setLayout(new GridLayout(2, 1)); container.add(header); container.add(xp); // Builds the component JPanel component = new JPanel(); component.setLayout(new FlowLayout()); component.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); component.add(imagePanel); component.add(container); component.add(container); ListItemComponent itemComponent = new ListItemComponent(); itemComponent.add(component, BorderLayout.WEST); itemComponent.add(buttonsPanel, BorderLayout.EAST); return itemComponent; } }
31.41411
89
0.593301
1dfc36a98cf071bd3a77aaa0392ee98ff4da16ed
6,796
/* Copyright (C) GridGain Systems. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* _________ _____ __________________ _____ * __ ____/___________(_)______ /__ ____/______ ____(_)_______ * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \ * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / / * \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/ */ package org.gridgain.grid.ggfs; import org.apache.hadoop.conf.*; import org.apache.hadoop.fs.*; import org.gridgain.grid.*; import org.gridgain.grid.cache.*; import org.gridgain.grid.kernal.ggfs.hadoop.*; import org.gridgain.grid.spi.communication.tcp.*; import org.gridgain.grid.spi.discovery.tcp.*; import org.gridgain.grid.spi.discovery.tcp.ipfinder.*; import org.gridgain.grid.spi.discovery.tcp.ipfinder.vm.*; import org.gridgain.grid.util.typedef.*; import org.gridgain.grid.util.typedef.internal.*; import org.gridgain.grid.util.ipc.shmem.*; import org.gridgain.testframework.junits.common.*; import java.lang.reflect.*; import java.net.*; import java.util.*; import java.util.concurrent.atomic.*; import static org.gridgain.grid.events.GridEventType.*; import static org.gridgain.grid.cache.GridCacheAtomicityMode.*; import static org.gridgain.grid.cache.GridCacheMode.*; /** * IPC cache test. */ public class GridGgfsHadoopFileSystemLightIpcCacheSelfTest extends GridCommonAbstractTest { /** IP finder. */ private static final GridTcpDiscoveryIpFinder IP_FINDER = new GridTcpDiscoveryVmIpFinder(true); /** Path to test hadoop configuration. */ private static final String HADOOP_FS_CFG = "modules/core/src/test/config/hadoop/core-site.xml"; /** Group size. */ public static final int GRP_SIZE = 128; /** Started grid counter. */ private static int cnt; /** {@inheritDoc} */ @Override protected GridConfiguration getConfiguration(String gridName) throws Exception { GridConfiguration cfg = super.getConfiguration(gridName); GridTcpDiscoverySpi discoSpi = new GridTcpDiscoverySpi(); discoSpi.setIpFinder(IP_FINDER); cfg.setDiscoverySpi(discoSpi); GridGgfsConfiguration ggfsCfg = new GridGgfsConfiguration(); ggfsCfg.setDataCacheName("partitioned"); ggfsCfg.setMetaCacheName("replicated"); ggfsCfg.setName("ggfs"); ggfsCfg.setManagementPort(GridGgfsConfiguration.DFLT_MGMT_PORT + cnt); ggfsCfg.setIpcEndpointConfiguration("{type:'shmem', port:" + (GridIpcSharedMemoryServerEndpoint .DFLT_IPC_PORT + cnt) + "}"); ggfsCfg.setBlockSize(512 * 1024); // Together with group blocks mapper will yield 64M per node groups. cfg.setGgfsConfiguration(ggfsCfg); cfg.setCacheConfiguration(cacheConfiguration()); cfg.setIncludeEventTypes(EVT_TASK_FAILED, EVT_TASK_FINISHED, EVT_JOB_MAPPED); GridTcpCommunicationSpi commSpi = new GridTcpCommunicationSpi(); commSpi.setSharedMemoryPort(-1); cfg.setCommunicationSpi(commSpi); cnt++; return cfg; } /** * Gets cache configuration. * * @return Cache configuration. */ private GridCacheConfiguration[] cacheConfiguration() { GridCacheConfiguration cacheCfg = defaultCacheConfiguration(); cacheCfg.setName("partitioned"); cacheCfg.setCacheMode(PARTITIONED); cacheCfg.setDistributionMode(GridCacheDistributionMode.PARTITIONED_ONLY); cacheCfg.setWriteSynchronizationMode(GridCacheWriteSynchronizationMode.FULL_SYNC); cacheCfg.setAffinityMapper(new GridGgfsGroupDataBlocksKeyMapper(GRP_SIZE)); cacheCfg.setBackups(0); cacheCfg.setQueryIndexEnabled(false); cacheCfg.setAtomicityMode(TRANSACTIONAL); GridCacheConfiguration metaCacheCfg = defaultCacheConfiguration(); metaCacheCfg.setName("replicated"); metaCacheCfg.setCacheMode(REPLICATED); metaCacheCfg.setWriteSynchronizationMode(GridCacheWriteSynchronizationMode.FULL_SYNC); metaCacheCfg.setQueryIndexEnabled(false); metaCacheCfg.setAtomicityMode(TRANSACTIONAL); return new GridCacheConfiguration[] {metaCacheCfg, cacheCfg}; } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { startGrids(4); } /** {@inheritDoc} */ @Override protected void afterTestsStopped() throws Exception { G.stopAll(true); } /** * Test how IPC cache map works. * * @throws Exception If failed. */ public void testIpcCache() throws Exception { Field cacheField = GridGgfsHadoopIpcIo.class.getDeclaredField("ipcCache"); cacheField.setAccessible(true); Field activeCntField = GridGgfsHadoopIpcIo.class.getDeclaredField("activeCnt"); activeCntField.setAccessible(true); Map<String, GridGgfsHadoopIpcIo> cache = (Map<String, GridGgfsHadoopIpcIo>)cacheField.get(null); Configuration cfg = new Configuration(); cfg.addResource(U.resolveGridGainUrl(HADOOP_FS_CFG)); cfg.setBoolean("fs.ggfs.impl.disable.cache", true); String endpoint = "shmem:10500"; // Ensure that existing IO is reused. FileSystem fs1 = FileSystem.get(new URI("ggfs://" + endpoint + '/'), cfg); assertEquals(1, cache.size()); GridGgfsHadoopIpcIo io = cache.get(endpoint); assertEquals(1, ((AtomicInteger)activeCntField.get(io)).get()); // Ensure that when IO is used by multiple file systems and one of them is closed, IO is not stopped. FileSystem fs2 = FileSystem.get(new URI("ggfs://" + endpoint + "/abc"), cfg); assertEquals(1, cache.size()); assertEquals(2, ((AtomicInteger)activeCntField.get(io)).get()); fs2.close(); assertEquals(1, cache.size()); assertEquals(1, ((AtomicInteger)activeCntField.get(io)).get()); Field stopField = GridGgfsHadoopIpcIo.class.getDeclaredField("stopping"); stopField.setAccessible(true); assert !(Boolean)stopField.get(io); // Ensure that IO is stopped when nobody else is need it. fs1.close(); assert cache.isEmpty(); assert (Boolean)stopField.get(io); } }
34.323232
110
0.690259
a9ca157ea8dfe75b1a9835611cf0dcb095d2560e
1,414
package org.silentsoft.badge4j.badge; public class FlatSquareBadge extends Badge { public FlatSquareBadge(String label, String message, String color, String labelColor, String[] links, String logo, int logoWidth) { super(label, message, color, labelColor, links, logo, logoWidth); } @Override protected int getHeight() { return 20; } @Override protected int getVerticalMargin() { return 0; } @Override protected boolean hasShadow() { return false; } @Override public String render() { StringBuilder builder = new StringBuilder(); builder.append("<g shape-rendering=\"crispEdges\">"); builder.append(String.format("<rect width=\"%s\" height=\"%d\" fill=\"%s\"/>", toString(getLeftWidth()), getHeight(), labelColor)); builder.append(String.format("<rect x=\"%s\" width=\"%s\" height=\"%d\" fill=\"%s\"/>", toString(getLeftWidth()), toString(getRightWidth()), getHeight(), color)); builder.append("</g>"); builder.append(String.format("<g fill=\"#fff\" text-anchor=\"middle\" font-family=\"%s\" text-rendering=\"geometricPrecision\" font-size=\"110\">", getFontFamily())); builder.append(renderLogo()); builder.append(renderLabel()); builder.append(renderMessage()); builder.append("</g>"); return renderBadge(builder.toString()); } }
36.25641
174
0.628006
01a03121bb77d184f3002d019edaa7e581966528
2,971
/* * 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.ignite.internal.performancestatistics.util; import java.io.PrintStream; import com.fasterxml.jackson.core.io.CharTypes; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; /** */ public class Utils { /** Json mapper. */ public static final ObjectMapper MAPPER = new ObjectMapper(); /** */ private final static char[] HC = "0123456789ABCDEF".toCharArray(); /** Creates empty object for given value if absent. */ public static ObjectNode createObjectIfAbsent(String val, ObjectNode json) { ObjectNode node = (ObjectNode)json.get(val); if (node == null) { node = MAPPER.createObjectNode(); json.set(val, node); } return node; } /** Creates empty array for given value if absent. */ public static ArrayNode createArrayIfAbsent(String val, ObjectNode json) { ArrayNode node = (ArrayNode)json.get(val); if (node == null) { node = MAPPER.createArrayNode(); json.set(val, node); } return node; } /** * Prints JSON-escaped string to the stream. * * @param ps Print stream to write to. * @param str String to print. * @see CharTypes#appendQuoted(StringBuilder, String) */ public static void printEscaped(PrintStream ps, String str) { int[] escCodes = CharTypes.get7BitOutputEscapes(); int escLen = escCodes.length; for (int i = 0, len = str.length(); i < len; ++i) { char c = str.charAt(i); if (c >= escLen || escCodes[c] == 0) { ps.print(c); continue; } ps.print('\\'); int escCode = escCodes[c]; if (escCode < 0) { ps.print('u'); ps.print('0'); ps.print('0'); int val = c; ps.print(HC[val >> 4]); ps.print(HC[val & 0xF]); } else ps.print((char)escCode); } } }
29.71
80
0.609222
14a5341ca3d028da0dc0ace3f4ca26ed6ef60535
389
package cn.edu.hust.util; import java.math.BigDecimal; /** * 数字格工具类 * @author Administrator * */ public class NumberUtils { /** * 格式化小数 * @param num 数字 * @param scale 四舍五入的位数 * @return 格式化小数 */ public static double formatDouble(double num, int scale) { BigDecimal bd = new BigDecimal(num); return bd.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } }
16.208333
68
0.678663
d46538fbbcbdb444f31712cdcf81bfc94f9761f7
3,157
/* * Copyright (C) 2012-2021, TomTom (http://tomtom.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tomtom.speedtools.services.push; import com.tomtom.speedtools.services.push.domain.Notification; import com.tomtom.speedtools.services.push.domain.NotificationChannelType; import com.tomtom.speedtools.services.push.domain.PushToken; import javax.annotation.Nonnull; import java.util.Set; /** * Implementation of this interface can push notifications to an underlying push service. */ public interface PushNotificationProvider { /** * Method pushes {@link Notification} to given channel id. * * @param notification The {@link Notification} to push. * @param pushToken The {@link PushToken} to push to. * @return The {@link PushToken} the provider is using for the registration. This could have been updated. * @throws PushConnectionException Thrown in case a connection could not me made to push service. * @throws InvalidPushTokenException Thrown in case the provider has marked the {@link PushToken} invalid. This * {@link PushToken} should not be used anymore. */ PushToken push(@Nonnull Notification notification, @Nonnull final PushToken pushToken) throws PushConnectionException, InvalidPushTokenException; /** * Method returns supported {@link NotificationChannelType}. * * @return The {@link NotificationChannelType} that this instance supports. */ @Nonnull NotificationChannelType getSupportedNotificationChannelType(); /** * This method returns push channel IDs that have been used earlier, but which are considered to be no longer valid, * according to the push notification provider. This will happen when a customer removes an application from its * device for instance. References can safely be removed. * * @return A set of obsolete push channels or empty. */ @Nonnull Set<PushToken> getObsoletePushTokens(); /** * Some providers are not able to fetch obsolete tokens from the underlying push service. This methods returns true * for implementations that do support this and false otherwise. * * @return True for implementations that support fetching of obsolete tokens and false otherwise. */ boolean canGetObsoletePushTokens(); /** * Some providers may be disabled at startup. this method returns true in case the provider instance is enabled, * false otherwise. * * @return True in case the provider instance is enabled, false otherwise. */ boolean isEnabled(); }
41
149
0.721254
a30d467dee130b5feb5a9b2790a6880ab89efec5
770
package blog.system.server.config; import org.springframework.boot.web.server.ErrorPage; import org.springframework.boot.web.server.ErrorPageRegistrar; import org.springframework.boot.web.server.ErrorPageRegistry; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; @Configuration public class ErrorCodeConfig implements ErrorPageRegistrar { @Override public void registerErrorPages(ErrorPageRegistry registry) { registry.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, "/403") , new ErrorPage(HttpStatus.NOT_FOUND, "/404") , new ErrorPage(HttpStatus.GATEWAY_TIMEOUT, "/504") , new ErrorPage(HttpStatus.HTTP_VERSION_NOT_SUPPORTED, "/505")); } }
40.526316
80
0.758442
74943010ace05701cd03129618417519889d7bee
1,484
package com.github.bjuvensjo.rsimulator.core; import com.google.inject.ImplementedBy; import java.nio.file.Path; import java.util.Optional; import java.util.Properties; /** * SimulatorResponse is returned by {@link Simulator}. * * @author Magnus Bjuvensjö */ @ImplementedBy(SimulatorResponseImpl.class) public interface SimulatorResponse { /** * Returns the properties of a specific test data request and response pair. If the name of the test data request * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported * properties, see *PropertiesInterceptor classes. * * @return the properties of a specific test data request and response pair */ Optional<Properties> getProperties(); /** * Sets the specified properties. * * @param properties the properties to set */ void setProperties(Optional<Properties> properties); /** * Returns the test data response. * * @return the test data response */ String getResponse(); /** * Sets the specified response. * * @param response the response to set */ void setResponse(String response); /** * Returns the matching request path. * * @return the matching request path */ Path getMatchingRequest(); /** * Sets the specified path. * * @param path the path to set */ void setMatchingRequest(Path path); }
24.327869
117
0.665094
3520c3925e13f6a236b0df153a89483e66501f7c
1,641
/* * Copyright 2014 The gRPC 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 io.grpc.internal; import io.grpc.Attributes; import io.grpc.Metadata; /** * A observer of a server-side transport for stream creation events. Notifications must occur from * the transport thread. */ public interface ServerTransportListener { /** * Called when a new stream was created by the remote client. * * @param stream the newly created stream. * @param method the fully qualified method name being called on the server. * @param headers containing metadata for the call. */ void streamCreated(ServerStream stream, String method, Metadata headers); /** * The transport has finished all handshakes and is ready to process streams. * * @param attributes transport attributes * @return the effective transport attributes that is used as the basis of call attributes */ Attributes transportReady(Attributes attributes); /** * The transport completed shutting down. All resources have been released. */ void transportTerminated(); }
33.489796
98
0.719074
b5f7d302c686df29d8288935a6d8b552405fb2ed
2,373
package ru.netradar.util; import java.util.ArrayList; import java.util.Collection; public class EnumUtils { /** * Создаёт строку, содержащую строковое представление объектов. * Если коллекция равна null или пустая - возвращается пустая строка. * Пример результата (для коллекции чисел [2, 5, 7, 10], разделитель: [, ]): "2, 5, 7, 10". * * @param objectCollection коллекция объектов * @param comma строка разделилтель, между строковыми представлениями объектов * @return строка, содержащаю порядковые номера элементов перечеслений, переданных в коллекции */ public static String objectCollectionToCommaString(final Collection<?> objectCollection, final String comma) { if (objectCollection == null) { return ""; } if (objectCollection.size() == 0) { return ""; } if (comma == null) { throw new IllegalArgumentException("Parameter comma cannot be null"); } final StringBuilder stringBuilder = new StringBuilder(); for (Object obj : objectCollection) { if (stringBuilder.length() != 0) { stringBuilder.append(comma); } stringBuilder.append(obj); } return stringBuilder.toString(); } /** * Создаёт строку, содержащую порядковые номера элементов перечеслений, переданных в коллекции. * Если коллекция равна null или пустая - возвращается пустая строка. * Пример результата: "2, 5, 7, 10". * * @param enumCollection коллекция перечислений * @param comma строка разделитель, между порядковыми номерами элементов перечислений * @return строка, содержащаю порядковые номера элементов перечеслений, переданных в коллекции */ public static String enumCollectionToOrdinalString(final Collection<? extends Enumeration<?>> enumCollection, final String comma) { if (enumCollection == null) { return ""; } final Collection<Integer> ordinalCollection = new ArrayList<Integer>(); for (Enumeration e : enumCollection) { ordinalCollection.add(e.getOrdinal()); } return objectCollectionToCommaString(ordinalCollection, comma); } private EnumUtils() { } }
34.897059
114
0.630847
bc30b2b5a6befceb92d8154ce5e6457c47f94cce
2,155
package nablarch.core.util.map; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.ReentrantLock; /** * 与えられたMapに対する自動排他制御を実装するラッパークラス。 * アクセサを使用した時点で排他ロックを自動的に取得する。 * @param <K> キーの型 * @param <V> 値の型 * * @author Iwauo Tajima <iwauo@tis.co.jp> */ public class ExclusiveAccessMap<K, V> extends LockableMap<K, V> { /** * コンストラクタ。 * @param baseMap ラップ対象のMap */ public ExclusiveAccessMap(Map<K, V> baseMap) { super(baseMap); } /** * コンストラクタ * @param baseMap ラップ対象のMap * @param lock ロックオブジェクト */ public ExclusiveAccessMap(Map<K, V> baseMap, ReentrantLock lock) { super(baseMap, lock); } /** {@inheritDoc} */ public void clear() { lock(); super.clear(); } /** {@inheritDoc} */ public boolean containsKey(Object key) { lock(); return super.containsKey(key); } /** {@inheritDoc} */ public boolean containsValue(Object value) { lock(); return super.containsValue(value); } /** {@inheritDoc} */ public Set<java.util.Map.Entry<K, V>> entrySet() { lock(); return super.entrySet(); } /** {@inheritDoc} */ public V get(Object key) { lock(); return super.get(key); } /** {@inheritDoc} */ public boolean isEmpty() { lock(); return super.isEmpty(); } /** {@inheritDoc} */ public Set<K> keySet() { lock(); return super.keySet(); } /** {@inheritDoc} */ public V put(K key, V value) { lock(); return super.put(key, value); } /** {@inheritDoc} */ public void putAll(Map<? extends K, ? extends V> m) { lock(); super.putAll(m); } /** {@inheritDoc} */ public V remove(Object key) { lock(); return super.remove(key); } /** {@inheritDoc} */ public int size() { lock(); return super.size(); } /** {@inheritDoc} */ public Collection<V> values() { lock(); return super.values(); } }
20.330189
70
0.533643
20097a95eeb9575a36bf3d41bd780b96fec16151
231
package io.sim.demo.x7.repository; import io.xream.sqli.api.ResultMapRepository; import org.springframework.stereotype.Repository; /** * @Author Sim */ @Repository public interface OmsRepository extends ResultMapRepository { }
19.25
60
0.796537
ab56d9439e44c648acd4f73b17f9306719d1351b
4,287
// Fig. 7.12: DeckOfCards.java // DeckOfCards class represents a deck of playing cards. import java.security.SecureRandom; public class DeckOfCards { // random number generator private static final SecureRandom randomNumbers = new SecureRandom(); private static final int NUMBER_OF_CARDS = 52; // constant # of Cards //I added this private static final int CARDS_IN_HAND = 5; // Constant 5 card hand private Card[] deck = new Card[NUMBER_OF_CARDS]; // Card references private int currentCard = 0; // index of next Card to be dealt (0-51) // constructor fills deck of Cards public DeckOfCards() { String[] faces = {"Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}; String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"}; // populate deck with Card objects for (int count = 0; count < deck.length; count++) { deck[count] = new Card(faces[count % 13], suits[count / 13]); } } // shuffle deck of Cards with one-pass algorithm public void shuffle() { // next call to method dealCard should start at deck[0] again currentCard = 0; // for each Card, pick another random Card (0-51) and swap them for (int first = 0; first < deck.length; first++) { // select a random number between 0 and 51 int second = randomNumbers.nextInt(NUMBER_OF_CARDS); // swap current Card with randomly selected Card Card temp = deck[first]; deck[first] = deck[second]; deck[second] = temp; } } // deal one Card public Card dealCard() { // determine whether Cards remain to be dealt if (currentCard < deck.length) { return deck[currentCard++]; // return current Card in array } else { return null; // return null to indicate that all Cards were dealt } } // My added Code is below here public int getHandSize() { int handSize = CARDS_IN_HAND; return handSize; } public void handCheck() { if (checkPair() == true) { System.out.println("There is a pair"); } else if (checkPair() == false) { System.out.println("No Pairs"); } if (checkTwoPair()== true) { System.out.println("There are two pairs"); } else if (checkTwoPair() == false){ System.out.println("There is not two pairs"); } if (checkThreeOfKind()== true) { System.out.println("There is a three of a kind"); } else if (checkThreeOfKind() == false){ System.out.println("There is no three of a kind"); } if (checkFourOfKind()== true) { System.out.println("There is a four of a kind"); } else if (checkFourOfKind() == false){ System.out.println("There is no four of a kind"); } } public Boolean checkPair(){ for (int i = 0; i < CARDS_IN_HAND; i++) { for (int j = i+1; j < CARDS_IN_HAND; j++) { if (deck[i].getFace().equals(deck[j].getFace())) { return true; } } } return false; } public Boolean checkTwoPair(){ int numberOfPairs = 0; for (int i = 0; i < CARDS_IN_HAND; i++) { for (int j = i + 1; j < CARDS_IN_HAND; j++) { if (deck[i].getFace() == deck[j].getFace()) { numberOfPairs++; } } } if (numberOfPairs >= 2) { return true; } return false; } public Boolean checkThreeOfKind() { int matchCount = 0; for (int i = 0; i < CARDS_IN_HAND; i++) { for (int j = i + 1; j < CARDS_IN_HAND; j++) { if (deck[i].getFace() == deck[j].getFace()) { matchCount++; } } } if (matchCount >= 3) { return true; } return false; } public Boolean checkFourOfKind() { int quadCount = 0; for (int i = 0; i < CARDS_IN_HAND; i++) { for (int j = i + 1; j < CARDS_IN_HAND; j++) { if (deck[i].getFace() == deck[j].getFace()) { quadCount++; } } } if (quadCount >= 4) { return true; } return false; } }
27.305732
74
0.544903
37ef3fd60f9ddc072fc5330e39274c7ea87fa391
2,349
/* * Copyright (C) 2022-2022 Huawei Technologies Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.huawei.dynamic.config.source; import com.huawei.dynamic.config.DynamicConfiguration; import com.huawei.dynamic.config.sources.MockEnvironment; import com.huawei.dynamic.config.sources.TestConfigSources; import com.huaweicloud.sermant.core.plugin.config.PluginConfigManager; import com.huaweicloud.sermant.core.service.dynamicconfig.common.DynamicConfigEvent; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.springframework.core.env.PropertySource; /** * 配置源测试 * * @author zhouss * @since 2022-04-16 */ public class SpringPropertyLocatorTest { private static final String KEY = "test"; private static final String CONTENT = "test: 1"; @Before public void before() { final DynamicConfigEvent event = Mockito.mock(DynamicConfigEvent.class); Mockito.when(event.getKey()).thenReturn(KEY); Mockito.when(event.getContent()).thenReturn(CONTENT); final DynamicConfiguration configuration = Mockito.mock(DynamicConfiguration.class); Mockito.when(configuration.getFirstRefreshDelayMs()).thenReturn(0L); Mockito.mockStatic(PluginConfigManager.class) .when(() -> PluginConfigManager.getPluginConfig(DynamicConfiguration.class)) .thenReturn(configuration); } @Test public void locate() { final SpringPropertyLocator springPropertyLocator = new SpringPropertyLocator(); final PropertySource<?> locate = springPropertyLocator.locate(new MockEnvironment()); Assert.assertEquals(locate.getName(), "Sermant-Dynamic-Config"); Assert.assertEquals(locate.getProperty(KEY), TestConfigSources.ORDER); } }
37.285714
93
0.744146
733dbb84f29dad86d281f4093b6ef42bda91109c
1,823
// Template Source: BaseEntityCollectionPage.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests; import com.microsoft.graph.models.UsedInsight; import com.microsoft.graph.requests.UsedInsightCollectionRequestBuilder; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.requests.UsedInsightCollectionResponse; import com.microsoft.graph.http.BaseCollectionPage; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Used Insight Collection Page. */ public class UsedInsightCollectionPage extends BaseCollectionPage<UsedInsight, UsedInsightCollectionRequestBuilder> { /** * A collection page for UsedInsight * * @param response the serialized UsedInsightCollectionResponse from the service * @param builder the request builder for the next collection page */ public UsedInsightCollectionPage(@Nonnull final UsedInsightCollectionResponse response, @Nonnull final UsedInsightCollectionRequestBuilder builder) { super(response, builder); } /** * Creates the collection page for UsedInsight * * @param pageContents the contents of this page * @param nextRequestBuilder the request builder for the next page */ public UsedInsightCollectionPage(@Nonnull final java.util.List<UsedInsight> pageContents, @Nullable final UsedInsightCollectionRequestBuilder nextRequestBuilder) { super(pageContents, nextRequestBuilder); } }
44.463415
167
0.704882
2296a58191e51f9475f9b68558022a824be2c195
2,440
import fi.helsinki.cs.tmc.edutestutils.MockStdio; import fi.helsinki.cs.tmc.edutestutils.Points; import org.junit.*; import static org.junit.Assert.*; @Points("53") public class FirstPartTest { @Rule public MockStdio io = new MockStdio(); @Test public void noExceptions() throws Exception { io.setSysIn("pekka\n3\n"); try { FirstPart.main(new String[0]); } catch (Exception e) { String v = "press button \"show backtrace\" and you find the cause of the problem by scrollong down to the " + "\"Caused by\""; throw new Exception("With input \"Pekka 2\" " + v, e); } } public String sanitize(String s) { return s.replaceAll("\r\n", "\n").replaceAll("\r", "\n").replaceAll("\n", " ").replaceAll(" ", " ").replaceAll(" ", ""); } @Test public void test1() { io.setSysIn("Java\n3\n"); FirstPart.main(new String[0]); String out = io.getSysOut().replaceAll(" ", ""); assertTrue("your program should print \"Result: \"", out.contains("Result:")); assertTrue("With input Java 3 your program should print \"Result: Jav\"", out.contains("Result:Jav")); assertFalse("With input Java 3 your program should print \"Result: Jav\"", out.contains("Result:Java")); } @Test public void test2() { io.setSysIn("Programming\n7\n"); FirstPart.main(new String[0]); String out = io.getSysOut().replaceAll(" ", ""); assertTrue("your program should print \"Result: \"", out.contains("Result:")); assertTrue("With input Programming 7 your program should print \"Result: Program\"", out.contains("Result:Program")); assertFalse("With input Programming 7 your program should print \"Result: Program\"", out.contains("Result:Programm")); } @Test public void test3() { io.setSysIn("Web-designer\n10\n"); FirstPart.main(new String[0]); String out = io.getSysOut().replaceAll(" ", ""); assertTrue("your program should print \"Result: \"", out.contains("Result:")); assertTrue("With input Web-designer 10 your program should print \"Result: Web-design\"", out.contains("Result:Web-design")); assertFalse("With input Web-designer 10 your program should print \"Result: Web-design\"", out.contains("Result:Web-designe")); } }
35.882353
135
0.603279
d297f3603ff389c92d6ca1800d402aee3e478f3c
375
package net.wohlfart.mercury.model; public class HasRevision<T> { private Revision revision; private T entity; public HasRevision(Revision revision, T entity) { this.revision = revision; this.entity = entity; } public Revision getRevision() { return revision; } public T getEntity() { return entity; } }
16.304348
53
0.621333
1005861539bc9b0de5d30bbc724a0109e7f0bf5f
5,448
package com.company; import java.util.LinkedList; import java.util.ListIterator; import java.util.Scanner; public class Main { private static final LinkedList<Song> playlist = new LinkedList<>(); private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) { /* Create a program that implements a playlist for songs. Create a Song class having title and duration of song There will be an Album class containing an inner class called SongList. The inner SongList class will use an ArrayList and will provide a method to add a song. Songs from different albums can be added to the Playlist. Once the songs have been added to the playlist, create a menu of options to: Quit, Skip Forward to the next song, Skip backward to the previous song, Replay the current song, List the songs in the playlist, and additionally, remove a song from the playlist. A song must exist in the album before it can be added to the playlist inner class SongList will also provide findSong() method which will be used by containing Album class to add Songs to the PlayList. */ Album album1 = new Album("Favourites"); album1.addSong("Kuch Kuch Hota hai", 5); album1.addSong("Ye kaali kaali aankhe", 4); album1.addSong("I am a disco dancer", 6); album1.addSong("Jaa Chudail", 5); album1.addSong("Bole Chudiya", 5); album1.addToPlaylist(playlist); printPlayList(); playlistOperations(); } private static void playlistOperations() { boolean quit = false; boolean forward = true; ListIterator<Song> i = playlist.listIterator(); if (playlist.isEmpty()) { System.out.println("No songs in the playlist"); return; } else { printOptions(); System.out.printf("Now playing %1$s\n", i.next()); } while (!quit) { int option = scanner.nextInt(); scanner.nextLine(); switch (option) { case 0: System.out.println("Bye Bye!"); quit = true; break; case 1: if (!forward) { if (i.hasNext()) { i.next(); } forward = true; } if (i.hasNext()) { System.out.printf("Now playing %1$s\n", i.next()); } else { System.out.println("End of playlist reached!"); forward = false; } break; case 2: if (forward) { if (i.hasPrevious()) { i.previous(); } forward = false; } if (i.hasPrevious()) { System.out.printf("Now playing %1$s\n", i.previous()); } else { System.out.println("Start of the playlist reached!"); forward = true; } break; case 3: if (forward) { if (i.hasPrevious()) { System.out.printf("Now playing %1$s\n", i.previous()); forward = false; } else { System.out.println("Start of the playlist reached"); } } else { if (i.hasNext()) { System.out.printf("Now playing %1$s\n", i.next()); forward = true; } else { System.out.println("End of the playlist reached"); } } break; case 4: printPlayList(); break; case 6: if(playlist.size() >0) { i.remove(); if(i.hasNext()) { System.out.println("Now playing " + i.next()); } else if(i.hasPrevious()) { System.out.println("Now playing " + i.previous()); } } break; default: printOptions(); break; } } } private static void printOptions() { System.out.println("Available actions:"); System.out.println("0 - to quit\n" + "1 - to play next song\n" + "2 - to play previous song\n" + "3 - to replay the current song\n" + "4 - list songs in the playlist\n" + "5 - print available options.\n" + "6 - delete current song from playlist"); } private static void printPlayList() { System.out.println("Songs currently in the Playlist:"); for (Song song : playlist) { System.out.println("\t" + song); } System.out.println(); } }
34.481013
116
0.451175
94ad2c23973827caeaa07abf717274ef882dcdad
48
package org.ko.problems; public class P738 { }
9.6
24
0.729167
c6ac03be2ea38284a17e635ad899155d4becda16
5,360
/* * 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 timeseriesweka.filters.shapelet_transforms.search_functions; import java.util.ArrayList; import java.util.Random; import weka.core.Instance; import timeseriesweka.filters.shapelet_transforms.Shapelet; /** * * @author raj09hxu */ public class LocalSearch extends RandomTimedSearch{ int maxIterations; protected LocalSearch(ShapeletSearchOptions ops) { super(ops); maxIterations = ops.getMaxIterations(); } @Override public ArrayList<Shapelet> SearchForShapeletsInSeries(Instance timeSeries, ProcessCandidate checkCandidate){ ArrayList<Shapelet> seriesShapelets = new ArrayList<>(); double[] series = timeSeries.toDoubleArray(); int numLengths = maxShapeletLength - minShapeletLength /*+ 1*/; //want max value to be inclusive. visited = new boolean[numLengths][]; //maxIterations is the same as K. for(int currentIterations = 0; currentIterations < maxIterations; currentIterations++){ int lengthIndex = random.nextInt(numLengths); int length = lengthIndex + minShapeletLength; //offset the index by the min value. int maxPositions = series.length - length ; int start = random.nextInt(maxPositions); // can only have valid start positions based on the length. //we haven't constructed the memory for this length yet. initVisitedMemory(series, length); if(!visited[lengthIndex][start]){ Shapelet shape = evaluateShapelet(series, start, length, checkCandidate); //if the shapelet is null, it means it was poor quality. so we've abandoned this branch. if(shape != null) seriesShapelets.add(shape); } } return seriesShapelets; } private static final int START_DEC = 0, START_INC = 1, LENGTH_DEC = 2, LENGTH_INC = 3; private Shapelet evaluateShapelet(double[] series, int start, int length, ProcessCandidate checkCandidate) { //we've not eval'd this shapelet; consider and put in list. Shapelet shapelet = visitCandidate(series, start, length, checkCandidate); if(shapelet == null) return shapelet; Shapelet[] shapelets; int index; Shapelet bsf_shapelet = shapelet; do{ //need to reset directions after each loop. shapelets = new Shapelet[4]; //calculate the best four directions. int startDec = start - 1; int startInc = start + 1; int lengthDec = length - 1; int lengthInc = length + 1; //as long as our start position doesn't go below 0. if(startDec >= 0){ shapelets[START_DEC] = visitCandidate(series, startDec, length, checkCandidate); } //our start position won't make us over flow on length. the start position is in the last pos. if(startInc < series.length - length){ shapelets[START_INC] = visitCandidate(series, startInc, length, checkCandidate); } //don't want to be shorter than the min length && does our length reduction invalidate our start pos? if(lengthDec > minShapeletLength && start < series.length - lengthDec){ shapelets[LENGTH_DEC] = visitCandidate(series, start, lengthDec, checkCandidate); } //dont want to be longer than the max length && does our start position invalidate our new length. if(lengthInc < maxShapeletLength && start < series.length - lengthInc){ shapelets[LENGTH_INC] = visitCandidate(series, start, lengthInc, checkCandidate); } //find the best shaplet direction and record which the best direction is. if it's -1 we don't want to move. //we only want to move when the shapelet is better, or equal but longer. index = -1; for(int i=0; i < shapelets.length; i++){ Shapelet shape = shapelets[i]; //if we're greater than the quality value then we want it, or if we're the same as the quality value but we are increasing length. if(shape != null && ((shape.qualityValue > bsf_shapelet.qualityValue) || (shape.qualityValue == bsf_shapelet.qualityValue && i == LENGTH_INC))){ index = i; bsf_shapelet = shape; } } //find the direction thats best, if it's same as current but longer keep searching, if it's shorter and same stop, if it's start = bsf_shapelet.startPos; length = bsf_shapelet.length; }while(index != -1); //no directions are better. return bsf_shapelet; } }
40
147
0.585075
40813c7b23d914fe6335c1931fb7a0a0ab352ba8
745
package ladysnake.permafrozen.mixin; import ladysnake.permafrozen.client.melonslisestuff.extension.IExtendedCompiledChunk; import org.lwjgl.system.MemoryUtil; import org.spongepowered.asm.mixin.Mixin; import net.minecraft.client.render.chunk.ChunkBuilder; import org.spongepowered.asm.mixin.Unique; @Mixin(ChunkBuilder.ChunkData.class) public class ChunkDataMixin implements IExtendedCompiledChunk { @Unique private long skylightBufferPtr = MemoryUtil.nmemAlloc(16 * 4 * 16); @Override public long getSkylightBuffer() { return this.skylightBufferPtr; } @Override public void freeSkylightBuffer() { MemoryUtil.nmemFree(this.skylightBufferPtr); this.skylightBufferPtr = 0L; } }
26.607143
85
0.757047
dbe98814d84496a47233c9d55dcc732361beb729
652
package com.fjx.mg.me.safe_center.check.identity_mobile; import com.library.common.base.BasePresenter; import com.library.common.base.BaseView; import java.util.Map; public interface IdentityMobileAuthContract { interface View extends BaseView { void checkSuccess(); void showTimeCount(String s); } abstract class Presenter extends BasePresenter<IdentityMobileAuthContract.View> { Presenter(IdentityMobileAuthContract.View view) { super(view); } abstract void check(Map<String, Object> map); abstract void sendSmsCode(); abstract void releaseTimer(); } }
20.375
85
0.694785
05fff5a7390818a733985b3a78288db923573593
936
package com.shetouane.armitage.structures; public class SidebarItem { public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public void setHeader(boolean value) { this.isHeader = value; } public boolean isHeader() { return isHeader; } public void showCount(boolean count) { this.showCount = count; } public boolean showCount() { return showCount; } public void setClickable(boolean clickable) { this.clickable = clickable; } public boolean getClickable() { return clickable; } public int getImage() { return image; } public void setImage(int image) { this.image = image; } private String title; private int count = 0; private boolean isHeader = false; private int image; private boolean showCount = true, clickable = true; }
15.864407
52
0.698718
f90efb2d00e413f8f7367f4032123f15ee14f7eb
8,847
package com.kongling.bourse.data.kline.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.google.common.collect.Maps; import com.kongling.bourse.data.kline.entity.PO.GoodsKlineMinute5Info; import com.kongling.bourse.data.kline.entity.PO.GoodsKlineMinuteInfo; import com.kongling.bourse.data.kline.entity.PO.GoodsOrghisInfo; import com.kongling.bourse.data.kline.entity.VO.KlineQueryVo; import com.kongling.bourse.data.kline.mapper.GoodsKlineMinute5InfoMapper; import com.kongling.bourse.data.kline.service.IGoodsKlineMinute15InfoService; import com.kongling.bourse.data.kline.service.IGoodsKlineMinute5InfoService; import com.util.DateUtil; import com.util.DealDateUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.exception.ExceptionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.task.TaskExecutor; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.Date; import java.util.List; import java.util.Map; /** * <p> * 商品5分钟分时信息 服务实现类 * </p> * * @author kongling * @since 2019-05-27 */ @Service @Slf4j public class GoodsKlineMinute5InfoServiceImpl extends ServiceImpl<GoodsKlineMinute5InfoMapper, GoodsKlineMinute5Info> implements IGoodsKlineMinute5InfoService { private static Map<String, GoodsKlineMinute5Info> goodsKlineMinute5InfoHashMap = Maps.newHashMap(); @Autowired TaskExecutor taskExecutor; @Autowired private IGoodsKlineMinute15InfoService goodsKlineMinute15InfoService; @Override public List<Object> listHistoryByVo(KlineQueryVo vo) { List<GoodsKlineMinute5Info> list = baseMapper.selectList(new QueryWrapper<GoodsKlineMinute5Info>() .eq("code",vo.getStockCode()) .between( vo.getStartDate()!=null && vo.getEndDate()!=null, "date",vo.getStartDate(),vo.getEndDate()) .orderByDesc("date")); return (List<Object>)(Object)list; } @Override public void toCompoundData5Minute(GoodsOrghisInfo stockOrghisInfo) { String stockCode =stockOrghisInfo.getCode(); try { //原始时间 Date iniDate = stockOrghisInfo.getDateTime(); /******* 五分钟数据*********************/ Date fiveDateStart = DateUtil.dateMinuteStart(iniDate, 5); BigDecimal newPrice = new BigDecimal(stockOrghisInfo.getOpen()); GoodsKlineMinute5Info goods5= goodsKlineMinute5InfoHashMap.get(stockCode); if(goods5==null || goods5.getDate().before(fiveDateStart)){ goods5 = baseMapper.selectOne(new QueryWrapper<GoodsKlineMinute5Info>() .eq("code",stockCode) .eq("date",fiveDateStart)); } if (goods5 != null && goods5.getDate().compareTo(fiveDateStart)==0) { final GoodsKlineMinute5Info goods5s=goods5; taskExecutor.execute(()->{ if (newPrice.compareTo(goods5s.getHigh()) > 0) { goods5s.setHigh(newPrice); } if (newPrice.compareTo(goods5s.getLow()) < 0) { goods5s.setLow(newPrice); } goods5s.setClosePrice(newPrice); goodsKlineMinute5InfoHashMap.put(stockCode,goods5s); baseMapper.update(null,new UpdateWrapper<GoodsKlineMinute5Info>() .setSql("volume=volume+"+stockOrghisInfo.getVolume()) .set("highest_price",goods5s.getHigh()) .set("lowest_price",goods5s.getLow()) .set("closing_price",goods5s.getClosePrice()) .eq("id",goods5s.getId())); }); } else if(goods5==null || goods5.getDate().before(fiveDateStart)){ GoodsKlineMinute5Info fiveMinuteDataSynthesis = new GoodsKlineMinute5Info(); fiveMinuteDataSynthesis.setLow(newPrice); fiveMinuteDataSynthesis.setHigh(newPrice); fiveMinuteDataSynthesis.setOpenPrice(newPrice); fiveMinuteDataSynthesis.setClosePrice(newPrice); fiveMinuteDataSynthesis.setCode(stockOrghisInfo.getCode()); if(goods5!=null){ fiveMinuteDataSynthesis.setPrevClose(goods5.getClosePrice().stripTrailingZeros().toPlainString()); } fiveMinuteDataSynthesis.setDate(fiveDateStart); Date nowDate = DealDateUtil.getNowDate(); fiveMinuteDataSynthesis.setTimestamp(nowDate); fiveMinuteDataSynthesis.setCreateTime(nowDate); fiveMinuteDataSynthesis.setDateYmd(DealDateUtil.getYearMonthDay(DealDateUtil.dateToLocalDateTime(iniDate)).toDate()); baseMapper.insert(fiveMinuteDataSynthesis); goodsKlineMinute5InfoHashMap.put(stockCode,goods5); } }catch (Exception e){ log.error("合成5分钟数据失败:\n"+ ExceptionUtils.getFullStackTrace(e)); } } @Override public void toCompoundData5MinuteByMinute(GoodsKlineMinuteInfo goodss) { String stockCode =goodss.getCode(); try { //原始时间 Date iniDate = goodss.getDate(); /******* 五分钟数据*********************/ Date fiveDateStart = DateUtil.dateMinuteStart(iniDate, 5); GoodsKlineMinute5Info goods5= goodsKlineMinute5InfoHashMap.get(stockCode); if(goods5==null || goods5.getDate().before(fiveDateStart)){ goods5 = baseMapper.selectOne(new QueryWrapper<GoodsKlineMinute5Info>() .eq("code",stockCode) .eq("date",fiveDateStart)); } if (goods5 != null && goods5.getDate().compareTo(fiveDateStart)==0) { if (goodss.getHigh().compareTo(goods5.getHigh()) > 0) { goods5.setHigh(goodss.getHigh()); } if (goodss.getLow().compareTo(goods5.getLow()) < 0) { goods5.setLow(goodss.getLow()); } goods5.setClosePrice(goodss.getClosePrice()); goods5.setVolume(goods5.getVolume().add(goodss.getVolume())); baseMapper.update(null,new UpdateWrapper<GoodsKlineMinute5Info>() .setSql("volume=volume+"+goodss.getVolume()) .set("highest_price",goods5.getHigh()) .set("lowest_price",goods5.getLow()) .set("closing_price",goods5.getClosePrice()) .eq("id",goods5.getId())); taskExecutor.execute(()-> { try { goodsKlineMinute15InfoService.toCompoundData15MinuteByMinute5(goodss); }catch (Exception e){ log.info("十五分钟数据更新失败:"+ExceptionUtils.getFullStackTrace(e)); } }); goodsKlineMinute5InfoHashMap.put(stockCode,goods5); } else if(goods5==null || goods5.getDate().before(fiveDateStart)){ GoodsKlineMinute5Info fiveMinuteDataSynthesis = new GoodsKlineMinute5Info(); fiveMinuteDataSynthesis.setLow(goodss.getLow()); fiveMinuteDataSynthesis.setHigh(goodss.getHigh()); fiveMinuteDataSynthesis.setOpenPrice(goodss.getOpenPrice()); fiveMinuteDataSynthesis.setClosePrice(goodss.getClosePrice()); fiveMinuteDataSynthesis.setCode(goodss.getCode()); fiveMinuteDataSynthesis.setVolume(goodss.getVolume()); if(goods5==null) { goods5 = goodsKlineMinute5InfoHashMap.get(stockCode); } if(goods5!=null){ fiveMinuteDataSynthesis.setPrevClose(goods5.getClosePrice().stripTrailingZeros().toPlainString()); } fiveMinuteDataSynthesis.setDate(fiveDateStart); Date nowDate = DealDateUtil.getNowDate(); fiveMinuteDataSynthesis.setTimestamp(nowDate); fiveMinuteDataSynthesis.setCreateTime(nowDate); fiveMinuteDataSynthesis.setDateYmd(DealDateUtil.getYearMonthDay(DealDateUtil.dateToLocalDateTime(iniDate)).toDate()); baseMapper.insert(fiveMinuteDataSynthesis); goodsKlineMinute5InfoHashMap.put(stockCode,fiveMinuteDataSynthesis); } }catch (Exception e){ log.error("合成5分钟数据失败:\n"+ ExceptionUtils.getFullStackTrace(e)); } } }
48.344262
160
0.624279
dd5e7d43ee920755fb91046f966552fb0926a5ac
1,701
package com.github.ericdriggs.cicdash.jenkins; import com.fasterxml.jackson.annotation.*; import java.util.Map; public class JenkinsJobQuery { private String jenkinsServerUrl; private String jobNamePattern; private Map<String, String> links; @JsonCreator public JenkinsJobQuery() { } public JenkinsJobQuery(String jenkinsServerUrl, String jobNamePattern, Map<String, String> links) { this.jenkinsServerUrl = jenkinsServerUrl; this.jobNamePattern = jobNamePattern; this.links = links; } @JsonGetter("jenkinsServerUrl") public String getJenkinsServerUrl() { return jenkinsServerUrl; } @JsonSetter("jenkinsServerUrl") public JenkinsJobQuery setJenkinsServerUrl(String jenkinsServerUrl) { this.jenkinsServerUrl = jenkinsServerUrl; return this; } @JsonGetter("jobNamePattern") public String getJobNamePattern() { return jobNamePattern; } @JsonSetter("jobNamePattern") public JenkinsJobQuery setJobNamePattern(String jobNamePattern) { this.jobNamePattern = jobNamePattern; return this; } @JsonGetter("links") public Map<String, String> getLinks() { return links; } @JsonSetter("links") public JenkinsJobQuery setLinks(Map<String, String> links) { this.links = links; return this; } @Override public String toString() { return "JenkinsJobQuery{" + "jenkinsServerUrl='" + jenkinsServerUrl + '\'' + ", jobNamePattern='" + jobNamePattern + '\'' + ", links='" + links + '\'' + '}'; } }
25.014706
78
0.629042
0fba190c4028020449f3316bc370d4d0ba337bd6
6,674
package com.ezwel.htl.interfaces.service.data.allReg; import java.util.List; import com.ezwel.htl.interfaces.commons.abstracts.AbstractSDO; import com.ezwel.htl.interfaces.commons.annotation.APIFields; import com.ezwel.htl.interfaces.commons.annotation.APIModel; import lombok.Data; import lombok.EqualsAndHashCode; /** * <pre> * * </pre> * @author swkim@ebsolution.co.kr * @date 2018. 11. 13. */ @Data @EqualsAndHashCode(callSuper=true) @APIModel(description="시설 정보") public class AllRegDataOutSDO extends AbstractSDO { private static final long serialVersionUID = 1L; @APIFields(description = "시설명칭", required=true, maxLength=200) private String pdtName; @APIFields(description = "시설명칭(영문)", maxLength=200) private String pdtNameEng; @APIFields(description = "상품코드", required=true, maxLength=100) private String pdtNo; @APIFields(description = "트립어드바이져아이디", maxLength=10) private String tripadvisorId; @APIFields(description = "대표이미지", required=true, maxLength=500) private String mainImage; @APIFields(description = "이미지변경여부", required=true, maxLength=1) private String changeImage; @APIFields(description = "서브이미지") private List<AllRegSubImagesOutSDO> subImages = null; @APIFields(description = "상품상세설명(HTML)", required=true, maxLength=50000) private String descHTML; @APIFields(description = "상품상세설명(MOBILE)", maxLength=50000) private String descMobile; @APIFields(description = "판매시작일", required=true, maxLength=8) private String sellStartDate; @APIFields(description = "판매종료일", required=true, maxLength=8) private String sellEndDate; @APIFields(description = "판매기간최저가", required=true) private String sellPrice; @APIFields(description = "시도명", required=true, maxLength=100) private String sido; @APIFields(description = "시도코드", required=true, maxLength=2) private String sidoCode; @APIFields(description = "군구명", required=true, maxLength=100) private String gungu; @APIFields(description = "군구코드", required=true, maxLength=5) private String gunguCode; @APIFields(description = "시설주소", required=true, maxLength=300) private String address; @APIFields(description = "주소타입", required=true, maxLength=1) private String addressType; @APIFields(description = "우편번호", required=true, maxLength=6) private String zipCode; @APIFields(description = "시설대표전화번호", required=true, maxLength=20) private String telephone; @APIFields(description = "채크인시간", maxLength=5) private String checkInTime; @APIFields(description = "체크아웃시간", maxLength=5) private String checkOutTime; @APIFields(description = "시설유형코드", required=true, maxLength=5) private String typeCode; @APIFields(description = "시설등급코드", required=true, maxLength=5) private String gradeCode; @APIFields(description = "위도", maxLength=20, required=true) private String mapX; @APIFields(description = "경도", maxLength=20, required=true) private String mapY; @APIFields(description = "부대시설 유형", maxLength=500) private String serviceCodes; public String getPdtName() { return pdtName; } public void setPdtName(String pdtName) { this.pdtName = pdtName; } public String getPdtNameEng() { return pdtNameEng; } public void setPdtNameEng(String pdtNameEng) { this.pdtNameEng = pdtNameEng; } public String getPdtNo() { return pdtNo; } public void setPdtNo(String pdtNo) { this.pdtNo = pdtNo; } public String getTripadvisorId() { return tripadvisorId; } public void setTripadvisorId(String tripadvisorId) { this.tripadvisorId = tripadvisorId; } public String getMainImage() { return mainImage; } public void setMainImage(String mainImage) { this.mainImage = mainImage; } public String getChangeImage() { return changeImage; } public void setChangeImage(String changeImage) { this.changeImage = changeImage; } public List<AllRegSubImagesOutSDO> getSubImages() { return subImages; } public void setSubImages(List<AllRegSubImagesOutSDO> subImages) { this.subImages = subImages; } public String getDescHTML() { return descHTML; } public void setDescHTML(String descHTML) { this.descHTML = descHTML; } public String getDescMobile() { return descMobile; } public void setDescMobile(String descMobile) { this.descMobile = descMobile; } public String getSellStartDate() { return sellStartDate; } public void setSellStartDate(String sellStartDate) { this.sellStartDate = sellStartDate; } public String getSellEndDate() { return sellEndDate; } public void setSellEndDate(String sellEndDate) { this.sellEndDate = sellEndDate; } public String getSellPrice() { return sellPrice; } public void setSellPrice(String sellPrice) { this.sellPrice = sellPrice; } public String getSido() { return sido; } public void setSido(String sido) { this.sido = sido; } public String getSidoCode() { return sidoCode; } public void setSidoCode(String sidoCode) { this.sidoCode = sidoCode; } public String getGungu() { return gungu; } public void setGungu(String gungu) { this.gungu = gungu; } public String getGunguCode() { return gunguCode; } public void setGunguCode(String gunguCode) { this.gunguCode = gunguCode; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getAddressType() { return addressType; } public void setAddressType(String addressType) { this.addressType = addressType; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getCheckInTime() { return checkInTime; } public void setCheckInTime(String checkInTime) { this.checkInTime = checkInTime; } public String getCheckOutTime() { return checkOutTime; } public void setCheckOutTime(String checkOutTime) { this.checkOutTime = checkOutTime; } public String getTypeCode() { return typeCode; } public void setTypeCode(String typeCode) { this.typeCode = typeCode; } public String getGradeCode() { return gradeCode; } public void setGradeCode(String gradeCode) { this.gradeCode = gradeCode; } public String getMapX() { return mapX; } public void setMapX(String mapX) { this.mapX = mapX; } public String getMapY() { return mapY; } public void setMapY(String mapY) { this.mapY = mapY; } public String getServiceCodes() { return serviceCodes; } public void setServiceCodes(String serviceCodes) { this.serviceCodes = serviceCodes; } }
20.535385
73
0.734492
ac1c50bfc1062b3fd64bc59efc6cd90bf78c12f8
5,519
/* * 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.hop.core.encryption; import org.apache.hop.core.Const; import org.apache.hop.core.HopClientEnvironment; import org.apache.hop.core.exception.HopException; import org.apache.hop.core.plugins.IPlugin; import org.apache.hop.core.plugins.PluginRegistry; import org.apache.hop.core.util.Utils; import org.eclipse.jetty.util.security.Password; /** * This class handles basic encryption of passwords in Hop. Note that it's not really encryption, * it's more obfuscation. Passwords are <b>difficult</b> to read, not impossible. * * @author Matt * @since 17-12-2003 */ public class Encr { private static ITwoWayPasswordEncoder encoder; public Encr() {} public static void init(String encoderPluginId) throws HopException { if (Utils.isEmpty(encoderPluginId)) { throw new HopException( "Unable to initialize the two way password encoder: No encoder plugin type specified."); } PluginRegistry registry = PluginRegistry.getInstance(); IPlugin plugin = registry.findPluginWithId(TwoWayPasswordEncoderPluginType.class, encoderPluginId); if (plugin == null) { throw new HopException("Unable to find plugin with ID '" + encoderPluginId + "'"); } encoder = (ITwoWayPasswordEncoder) registry.loadClass(plugin); // Load encoder specific options... // encoder.init(); } public static final String encryptPassword(String password) { return encoder.encode(password, false); } public static final String decryptPassword(String encrypted) { return encoder.decode(encrypted); } /** * The word that is put before a password to indicate an encrypted form. If this word is not * present, the password is considered to be NOT encrypted */ public static final String PASSWORD_ENCRYPTED_PREFIX = "Encrypted "; /** * Encrypt the password, but only if the password doesn't contain any variables. * * @param password The password to encrypt * @return The encrypted password or the */ public static final String encryptPasswordIfNotUsingVariables(String password) { return encoder.encode(password, true); } /** * Decrypts a password if it contains the prefix "Encrypted " * * @param password The encrypted password * @return The decrypted password or the original value if the password doesn't start with * "Encrypted " */ public static final String decryptPasswordOptionallyEncrypted(String password) { return encoder.decode(password, true); } /** * Gets encoder * * @return value of encoder */ public static ITwoWayPasswordEncoder getEncoder() { return encoder; } /** * Create an encrypted password * * @param args the password to encrypt */ public static void main(String[] args) throws HopException { HopClientEnvironment.init(); if (args.length != 2) { printOptions(); System.exit(9); } String option = args[0]; String password = args[1]; if (Const.trim(option).substring(1).equalsIgnoreCase("hop")) { // Hop password obfuscation // try { String obfuscated = Encr.encryptPasswordIfNotUsingVariables(password); System.out.println(obfuscated); System.exit(0); } catch (Exception ex) { System.err.println("Error encrypting password"); ex.printStackTrace(); System.exit(2); } } else if (Const.trim(option).substring(1).equalsIgnoreCase("server")) { // Jetty password obfuscation // String obfuscated = Password.obfuscate(password); System.out.println(obfuscated); System.exit(0); } else { // Unknown option, print usage // System.err.println("Unknown option '" + option + "'\n"); printOptions(); System.exit(1); } } private static void printOptions() { System.err.println("encr usage:\n"); System.err.println(" encr <-hop|-server> <password>"); System.err.println(" Options:"); System.err.println(" -hop: generate an obfuscated password to include in Hop XML files"); System.err.println( " -server : generate an obfuscated password to include in the hop-server password file 'pwd/hop.pwd'"); System.err.println( "\nThis command line tool obfuscates a plain text password for use in XML and password files."); System.err.println( "Make sure to also copy the '" + PASSWORD_ENCRYPTED_PREFIX + "' prefix to indicate the obfuscated nature of the password."); System.err.println( "Hop will then be able to make the distinction between regular plain text passwords and obfuscated ones."); System.err.println(); } }
32.656805
115
0.690524
2f988400f2cd403e7b98cb00660122c7ad849ce0
901
package com.pengyifan.pubtator.io; import com.pengyifan.bioc.BioCCollection; import com.pengyifan.bioc.io.BioCCollectionReader; import com.pengyifan.pubtator.PubTatorDocument; import com.pengyifan.pubtator.utils.BioC2PubTator; import javax.xml.stream.XMLStreamException; import java.io.IOException; import java.io.Reader; import java.util.List; import java.util.stream.Collectors; class BioCLoader { private static final BioC2PubTator converter = new BioC2PubTator(); public List<PubTatorDocument> load(Reader reader) throws XMLStreamException, IOException { BioCCollectionReader biocReader = new BioCCollectionReader(reader); BioCCollection bioCCollection = biocReader.readCollection(); biocReader.close(); return bioCCollection.getDocuments().stream() .map(d -> converter.apply(d)) .collect(Collectors.toList()); } }
29.064516
72
0.750277
a31c97db94bf42528934791d486a3d963e7d8f1c
5,702
package mygame; import com.jme3.app.SimpleApplication; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.renderer.RenderManager; import com.jme3.scene.Geometry; import com.jme3.scene.shape.Box; import com.jme3.scene.shape.Sphere; import com.jme3.scene.Node; /** * test * @author normenhansen */ public class Main extends SimpleApplication { public static void main(String[] args) { Main app = new Main(); app.start(); } protected Node neck; protected Node LAJ; protected Node LFAJ; protected Node RAJ; protected Node RFAJ; protected Node LLJ; protected Node LFLJ; protected Node RLJ; protected Node RFLJ; @Override public void simpleInitApp() { Material mat1 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); Material mat2 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); Material mat3 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); mat1.setColor("Color", ColorRGBA.DarkGray); mat2.setColor("Color", ColorRGBA.Blue); mat3.setColor("Color", ColorRGBA.White); Box B = new Box(1, 1.8f, 1); Geometry Body = new Geometry("Body", B); Body.setMaterial(mat1); Box H =new Box(0.6f,0.5f,1f); Geometry Head=new Geometry("Head",H); Head.setMaterial(mat2); neck=new Node("Neck"); neck.attachChild(Head); neck.move(0, 1.8f, 0); Head.move(0, 0.5f, 0); // Left arm Box LA = new Box(0.5f, 1.2f, 0.5f); Geometry LeftArm = new Geometry("LeftArm", LA); LeftArm.setMaterial(mat2); LAJ =new Node("LeftArmJoint"); LAJ.attachChild(LeftArm); LAJ.move(-1.5f, 1.2f, 0); LeftArm.move(0f,-0.6f,0f); Box LFA = new Box(0.4f, 1.0f, 0.4f); Geometry LeftFArm = new Geometry("LeftFArm", LFA); LeftFArm.setMaterial(mat3); LFAJ =new Node("LeftFArmJoint"); LFAJ.attachChild(LeftFArm); LFAJ.move(0f, -1.7f, 0); LeftFArm.move(0f,-1.0f,0f); Sphere SLFA =new Sphere(30, 30, 0.4f); Geometry SphereLFA =new Geometry("SphereLA",SLFA); SphereLFA.setMaterial(mat3); LFAJ.attachChild(SphereLFA); // Right arm Box RA = new Box(0.5f, 1.2f, 0.5f); Geometry RightArm = new Geometry("RightArm", RA); RightArm.setMaterial(mat2); RAJ =new Node("RightArmJoint"); RAJ.attachChild(RightArm); RAJ.move(1.5f, 1.2f, 0); RightArm.move(0f,-0.6f,0f); Box RFA = new Box(0.4f, 1.0f, 0.4f); Geometry RightFArm = new Geometry("RighttFArm", RFA); RightFArm.setMaterial(mat3); RFAJ =new Node("RightFArmJoint"); RFAJ.attachChild(RightFArm); RFAJ.move(0f, -1.7f, 0); RightFArm.move(0f,-1.0f,0f); Sphere SRFA =new Sphere(30, 30, 0.5f); Geometry SphereRFA =new Geometry("SphereLA",SRFA); SphereRFA.setMaterial(mat3); RFAJ.attachChild(SphereRFA); // Left leg Box LL = new Box(0.5f, 1.2f, 0.5f); Geometry LeftLeg = new Geometry("LeftLeg", LL); LeftLeg.setMaterial(mat2); LLJ =new Node("LeftLegJoint"); LLJ.attachChild(LeftLeg); LLJ.move(-0.6f, -1.8f, 0); LeftLeg.move(0f,-1.2f,0f); Box LFL = new Box(0.4f, 1.0f, 0.4f); Geometry LeftFLeg = new Geometry("LeftFLeg", LFL); LeftFLeg.setMaterial(mat3); LFLJ =new Node("LeftFLegJoint"); LFLJ.attachChild(LeftFLeg); LFLJ.move(0, -2.2f, 0); LeftFLeg.move(0f,-1.0f,0f); Sphere SLFL =new Sphere(30, 30, 0.5f); Geometry SphereLFL =new Geometry("SphereLA",SLFL); SphereLFL.setMaterial(mat3); LFLJ.attachChild(SphereLFL); // Right leg Box RL = new Box(0.5f, 1.2f, 0.5f); Geometry RightLeg = new Geometry("RightLeg", RL); RightLeg.setMaterial(mat2); RLJ =new Node("RightLegJoint"); RLJ.attachChild(RightLeg); RLJ.move(0.6f, -1.8f, 0); RightLeg.move(0f,-1.2f,0f); Box RFL = new Box(0.4f, 1.0f, 0.5f); Geometry RightFLeg = new Geometry("RightFLeg", RFL); RightFLeg.setMaterial(mat3); RFLJ =new Node("RightFLegJoint"); RFLJ.attachChild(RightFLeg); RFLJ.move(0, -2.2f, 0); RightFLeg.move(0f,-1.0f,0f); Sphere SRFL =new Sphere(30, 30, 0.5f); Geometry SphereRFL =new Geometry("SphereLA",SRFL); SphereRFL.setMaterial(mat3); RFLJ.attachChild(SphereRFL); // ---------------------------------- rootNode.attachChild(Body); rootNode.attachChild(neck); rootNode.attachChild(LAJ); LAJ.attachChild(LFAJ); rootNode.attachChild(RAJ); RAJ.attachChild(RFAJ); rootNode.attachChild(LLJ); LLJ.attachChild(LFLJ); rootNode.attachChild(RLJ); RLJ.attachChild(RFLJ); } @Override public void simpleUpdate(float tpf) { LAJ.rotate(0.01f, 0, 0); // RAJ.rotate(0.01f, 0, 0); // LFAJ.rotate(0, 0, 0.003f); // RFAJ.rotate(0, 0, -0.003f); // LLJ.rotate(0, 0, -0.01f); // RLJ.rotate(0, 0, 0.01f); // LFLJ.rotate(0.001f, 0, 0); // RFLJ.rotate(0.001f, 0, 0); } @Override public void simpleRender(RenderManager rm) { //TODO: add render code } }
30.98913
88
0.561908
2b3cbf380bdcc49538709e5d4a87d55ee0bbb1c9
905
package com.stqa.pft.sand; import org.testng.Assert; import org.testng.annotations.Test; public class EquationTests { @Test public void Test0() { Equation e = new Equation(1,1,1); Assert.assertEquals(e.rootNumber(), 0); } @Test public void Test1() { Equation e = new Equation(1,2,1); Assert.assertEquals(e.rootNumber(), 1); } @Test public void Test2() { Equation e = new Equation(1,5,6); Assert.assertEquals(e.rootNumber(), 2); } @Test public void TestLinear() { Equation e = new Equation(0,1,1); Assert.assertEquals(e.rootNumber(), 1); } @Test public void TestConstant() { Equation e = new Equation(0, 0, 1); Assert.assertEquals(e.rootNumber(), 0); } @Test public void TestZero() { Equation e = new Equation(0, 0, 0); Assert.assertEquals(e.rootNumber(), -1); } }
20.568182
46
0.6
eb563debbb8d4b1f88c8be95d884a58fdff1cb0f
1,376
/* * Created by Michael Carrara <michael.carrara@breadwallet.com> on 7/1/19. * Copyright (c) 2019 Breadwinner AG. All right reserved. * * See the LICENSE file at the project root for license information. * See the CONTRIBUTORS file at the project root for a list of contributors. */ package com.breadwallet.corenative.crypto; public enum BRCryptoComparison { CRYPTO_COMPARE_LT { @Override public int toCore() { return CRYPTO_COMPARE_LT_VALUE; } }, CRYPTO_COMPARE_EQ { @Override public int toCore() { return CRYPTO_COMPARE_EQ_VALUE; } }, CRYPTO_COMPARE_GT { @Override public int toCore() { return CRYPTO_COMPARE_GT_VALUE; } }; private static final int CRYPTO_COMPARE_LT_VALUE = 0; private static final int CRYPTO_COMPARE_EQ_VALUE = 1; private static final int CRYPTO_COMPARE_GT_VALUE = 2; public static BRCryptoComparison fromCore(int nativeValue) { switch (nativeValue) { case CRYPTO_COMPARE_LT_VALUE: return CRYPTO_COMPARE_LT; case CRYPTO_COMPARE_EQ_VALUE: return CRYPTO_COMPARE_EQ; case CRYPTO_COMPARE_GT_VALUE: return CRYPTO_COMPARE_GT; default: throw new IllegalArgumentException("Invalid core value"); } } public abstract int toCore(); }
28.666667
78
0.667151
d8a7e3d8b7a9c8e8d83db56850ced7114f045b20
597
package com.xms.offer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; /** * Created by xms on 2017/9/9. */ public class BlackString { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); while (in.hasNext()) { int n = in.nextInt(); int[] dp = new int [n+1]; dp[1] = 3;dp[2]=9; for( int i = 3; i <= n; i++ ) dp[i] = 2*dp[i-1]+dp[i-2]; System.out.println(dp[n-1]); } } }
24.875
63
0.542714
94c6c3961fe1b4c39be96bb2a2083e0b39bc9e80
779
package e.a.a.a.y0.d.a.e0; import e.a.a.a.y0.b.b; import e.a.a.a.y0.b.w0; import e.a.a.a.y0.m.d0; import e.x.b.l; import e.x.c.i; import e.x.c.k; public final class s extends k implements l<b, d0> { /* renamed from: h reason: collision with root package name */ public final /* synthetic */ w0 f8560h; /* JADX INFO: super call moved to the top of the method (can break code semantics) */ public s(w0 w0Var) { super(1); this.f8560h = w0Var; } public Object invoke(Object obj) { b bVar = (b) obj; i.e(bVar, "it"); w0 w0Var = bVar.n().get(this.f8560h.h()); i.d(w0Var, "it.valueParameters[p.index]"); d0 d = w0Var.d(); i.d(d, "it.valueParameters[p.index].type"); return d; } }
25.129032
89
0.573813
9ffe7e2c2f20658598f98e07688fe021a54201a1
506
// https://leetcode.com/explore/learn/card/fun-with-arrays/523/conclusion/3228/ // O(nlogn) class Solution { public int heightChecker(int[] heights) { int[] sortedHeights = Arrays.copyOf(heights, heights.length); Arrays.sort(sortedHeights); int minChange = 0; for(int i = 0; i < heights.length; i++) { if(sortedHeights[i] != heights[i]) { minChange++; } } return minChange; } }
25.3
79
0.529644
68bdabb3340f29c0493dd0a89173194fdc5e5d0d
111
package com.shengfq.callback; /** * 回调接口 * */ public interface CallBack { void execute(Object... objects); }
15.857143
33
0.684685
428e8cfddba3fa26efb2913f6ebb88a3eaec10a9
692
package de.dirent.tthelper.pages.ranglistenspieler; import java.util.List; import org.acegisecurity.annotation.Secured; import de.dirent.tthelper.entities.JugendRanglistenAusrichtung; import de.dirent.tthelper.entities.RanglistenAusrichtung; import de.dirent.tthelper.pages.SecuredPage; @Secured( "ROLE_ADMIN" ) public class AdminRanglistenAusrichtung extends SecuredPage { public List<RanglistenAusrichtung> getGemeldeteRanglistenAusrichtung() { return getPersistenceManager().getAllRanglistenAusrichtung(); } public List<JugendRanglistenAusrichtung> getGemeldeteJugendRanglistenAusrichtung() { return getPersistenceManager().getAllJugendRanglistenAusrichtung(); } }
26.615385
85
0.82948
020cc0e5845f4d57816471de63672849c42f6a96
1,009
package com.huijava.superiorjavablogs.service.impl; import com.huijava.superiorjavablogs.common.base.AbstractService; import com.huijava.superiorjavablogs.entity.Roles; import com.huijava.superiorjavablogs.mapper.RolesMapper; import com.huijava.superiorjavablogs.service.RolesService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import tk.mybatis.mapper.entity.Example; /** * @author chenhaoxiang * @date 2018-09-12 18:23:40 */ @Service public class RolesServiceImpl extends AbstractService<Roles> implements RolesService { @Autowired private RolesMapper rolesMapper; @Override public Roles selectByName(String users) { Example example = new Example(Roles.class); example.createCriteria().andCondition("name=", users); return rolesMapper.selectOneByExample(example); } @Override public Integer insertSelective(Roles roles) { return rolesMapper.insertSelective(roles); } }
31.53125
86
0.772052
6030b5a4afadef0d0c338b5f4036ab99717c213e
227
package dodona.feedback; public class CloseContext extends AcceptedClose { public CloseContext(Boolean accepted) { super("close-context", accepted); } public CloseContext() { this(null); } }
16.214286
49
0.651982
e13724d788c65dc47c7e420cf74094823a912b9b
3,867
package array; /** * 661. Image Smoother * * Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray * scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. * If a cell has less than 8 surrounding cells, then use as many as you can. * * Example 1: * Input: * [[1,1,1], * [1,0,1], * [1,1,1]] * Output: * [[0, 0, 0], * [0, 0, 0], * [0, 0, 0]] * * Explanation: * For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0 * For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0 * For the point (1,1): floor(8/9) = floor(0.88888889) = 0 * * Note: * 1.The value in the given matrix is in the range of [0, 255]. * 2.The length and width of the given matrix are in the range of [1, 150]. * * Created by zjm on 2019/5/20. */ public class ImageSmoother { //just list every probably public int[][] imageSmoother(int[][] M) { if(M.length == 0) { return M; } int[][] res = new int[M.length][M[0].length]; for(int i = 0; i < M.length; i++) { for(int j = 0; j < M[0].length; j++) { if(i == 0) { if(j == 0 && i < M.length - 1 && j < M[0].length - 1) { res[i][j] = (M[i][j] + M[i+1][j] + M[i][j+1] + M[i+1][j+1]) / 4; }else if(j == 0 && i < M.length - 1) { res[i][j] = (M[i][j] + M[i+1][j]) / 2; }else if(j == 0 && j < M[0].length - 1) { res[i][j] = (M[i][j] + M[i][j+1]) / 2; }else if(j == 0){ res[i][j] = M[i][j]; }else if(j < M[0].length - 1 && i < M.length - 1) { res[i][j] = (M[i][j] + M[i+1][j] + M[i][j+1] + M[i+1][j+1] + M[i][j-1] + M[i+1][j-1]) / 6; }else if(j < M[0].length - 1 && i == M.length - 1){ res[i][j] = (M[i][j] + M[i][j-1] + M[i][j+1]) / 3; }else if(j == M[0].length - 1 && i < M.length - 1) { res[i][j] = (M[i][j] + M[i+1][j] + M[i][j-1] + M[i+1][j-1]) / 4; }else if(j == M[0].length - 1 && i == M.length - 1) { res[i][j] = (M[i][j] + M[i][j-1]) / 2; } }else if(i < M.length - 1) { if(j == 0 && j < M[0].length - 1) { res[i][j] = (M[i][j] + M[i-1][j] + M[i+1][j] + M[i][j+1] + M[i-1][j+1] + M[i+1][j+1]) / 6; }else if(j == 0) { res[i][j] = (M[i][j] + M[i-1][j] + M[i+1][j]) / 3; }else if(j < M[0].length - 1) { res[i][j] = (M[i][j] + M[i-1][j] + M[i+1][j] + M[i][j+1] + M[i-1][j+1] + M[i+1][j+1] + M[i-1][j-1] + M[i][j-1] + M[i+1][j-1]) / 9; }else if(j == M[0].length - 1) { res[i][j] = (M[i][j] + M[i-1][j] + M[i+1][j] + M[i][j-1] + M[i-1][j-1] + M[i+1][j-1]) / 6; } }else { if(j == 0 && j < M[0].length - 1) { res[i][j] = (M[i][j] + M[i-1][j] + M[i][j+1] + M[i-1][j+1]) / 4; }else if(j == 0) { res[i][j] = (M[i][j] + M[i-1][j]) / 2; }else if(j < M[0].length - 1) { res[i][j] = (M[i][j] + M[i-1][j] + M[i][j+1] + M[i][j-1] + M[i-1][j-1] + M[i-1][j+1]) / 6; }else if(j == M[0].length - 1) { res[i][j] = (M[i][j] + M[i-1][j] + M[i][j-1] + M[i-1][j-1]) / 4; } } } } return res; } public int[][] imageSmootherSimple(int[][] M) { if(M.length == 0) { return M; } int[][] res = new int[M.length][M[0].length]; for(int i = 0; i < M.length; i++) { for(int j = 0; j < M[0].length; j++) { int sum = 0; int count = 0; for(int m = i - 1; m < i + 2; m++) { for(int n = j - 1; n < j + 2; n++) { if(m >= 0 && m < M.length && n >= 0 && n < M[0].length) { sum += M[m][n]; count++; } } } res[i][j] = sum / count; } } return res; } }
35.805556
136
0.403155