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
117e113802296d8241c2e08c5348300696e603d4
562
/* * 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 br.com.livraria.Utils; /** * * @author bruno.falmeida */ public class Constants { // URL de conexão public static final String DB_ADRESS = "jdbc:derby://localhost:1527/Livraria"; // usuario do banco public static final String DB_USER = "adm"; // senha do banco public static final String DB_PASS = "123456"; }
28.1
80
0.658363
365f11b1b6b2cbb9ad3fd367f3f1d869b5faa4c0
1,115
package sg.iss.team10.caps.model; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the admin database table. * */ @Entity @NamedQuery(name="Admin.findAll", query="SELECT a FROM Admin a") public class Admin implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int adminId; private String adminName; private String password; private String username; public Admin() { } public int getAdminId() { return this.adminId; } public void setAdminId(int adminId) { this.adminId = adminId; } public String getAdminName() { return this.adminName; } public void setAdminName(String adminName) { this.adminName = adminName; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } }
17.421875
65
0.684305
bbe13d5c0479c95f8f1b7f967da814a1cdad73f5
674
package app.aifactory.ai.web; import app.aifactory.ai.background.BackgroundUpdater; import com.google.appengine.api.ThreadManager; import com.google.inject.servlet.ServletModule; public class DemoServletModule extends ServletModule { private static Thread backgroundUpdaterThread; @Override protected void configureServlets() { BackgroundUpdater backgroundUpdater = new BackgroundUpdater(); bind(BackgroundUpdater.class).toInstance(backgroundUpdater); serve("/demo").with(DemoServlet.class); backgroundUpdaterThread = ThreadManager.createBackgroundThread(backgroundUpdater); backgroundUpdaterThread.start(); } }
30.636364
90
0.77003
6538af2e2aec73ba12bcb5c6d5a0249de5beb44f
349
import java.io.IOException; import java.util.* ; public class P1011 { public static void main(String[] args) throws IOException { Scanner input = new Scanner ( System.in ) ; double r = input.nextDouble () ; double pi = 3.14159 ; double vol = (4/3.0) * pi * r * r * r ; System.out.printf ( "VOLUME = %.3f\n" , vol ) ; } }
18.368421
63
0.601719
52d2628192d0e1dcf224c513bc73114466f0908f
3,843
/* * This file is part of ELKI: * Environment for Developing KDD-Applications Supported by Index-Structures * * Copyright (C) 2019 * ELKI Development Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.lmu.ifi.dbs.elki.distance.distancefunction; import de.lmu.ifi.dbs.elki.data.NumberVector; import de.lmu.ifi.dbs.elki.data.VectorUtil; import de.lmu.ifi.dbs.elki.data.spatial.SpatialComparable; import de.lmu.ifi.dbs.elki.data.type.SimpleTypeInformation; import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizer; /** * Cosine distance function for <em>unit length</em> feature vectors. * <p> * The cosine distance is computed from the cosine similarity by * <code>1-(cosine similarity)</code>. * <p> * Cosine similarity is defined as * \[ \tfrac{\vec{x}\cdot\vec{y}}{||a||\cdot||b||} * =_{||a||=||b||=1} \vec{x}\cdot\vec{y} * \] * Cosine distance then is defined as * \[ 1 - \tfrac{\vec{x}\cdot\vec{y}}{||a||\cdot||b||} * =_{||a||=||b||=1} 1-\vec{x}\cdot\vec{y} \in [0;2] \] * <p> * This implementation <em>assumes</em> that \(||a||=||b||=1\). If this does not * hold for your data, use {@link CosineDistanceFunction} instead! * <p> * {@link ArcCosineUnitlengthDistanceFunction} may sometimes be more * appropriate, but also more computationally expensive. * * @author Erich Schubert * @since 0.7.5 */ public class CosineUnitlengthDistanceFunction implements SpatialPrimitiveDistanceFunction<NumberVector>, NumberVectorDistanceFunction<NumberVector> { /** * Static instance */ public static final CosineUnitlengthDistanceFunction STATIC = new CosineUnitlengthDistanceFunction(); /** * Constructor - use {@link #STATIC} instead. * * @deprecated Use static instance */ @Deprecated public CosineUnitlengthDistanceFunction() { super(); } /** * Computes the cosine distance for two given feature vectors. * * The cosine distance is computed from the cosine similarity by * <code>1-(cosine similarity)</code>. * * @param v1 first feature vector * @param v2 second feature vector * @return the cosine distance for two given feature vectors v1 and v2 */ @Override public double distance(NumberVector v1, NumberVector v2) { double d = VectorUtil.dot(v1, v2); return (d <= 1) ? 1 - d : 0; } @Override public double minDist(SpatialComparable mbr1, SpatialComparable mbr2) { double d = VectorUtil.minDot(mbr1, mbr2); return (d <= 1) ? 1 - d : 0; } @Override public String toString() { return "CosineUnitlengthDistance"; } @Override public boolean equals(Object obj) { return obj == this || (obj != null && this.getClass().equals(obj.getClass())); } @Override public int hashCode() { return getClass().hashCode(); } @Override public SimpleTypeInformation<? super NumberVector> getInputTypeRestriction() { return NumberVector.VARIABLE_LENGTH; } /** * Parameterization class. * * @author Erich Schubert */ public static class Parameterizer extends AbstractParameterizer { @Override protected CosineUnitlengthDistanceFunction makeInstance() { return CosineUnitlengthDistanceFunction.STATIC; } } }
31.5
149
0.701535
5f1b8597b81202190271e3673072ea3de4308121
189
package com.backendless.transaction; import com.backendless.persistence.DataQueryBuilder; interface UnitOfWorkFind { OpResult find( String tableName, DataQueryBuilder queryBuilder ); }
21
67
0.830688
e15933b6ddb0fb11fdf5864ef1455a3e62ae62f7
15,810
/** * 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.nutch.analysis.lang; // JDK imports import java.io.File; import java.io.InputStream; import java.io.IOException; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.List; import java.util.Vector; import java.util.HashMap; import java.util.Iterator; import java.util.ArrayList; import java.util.Properties; import java.util.Enumeration; // Commons Logging imports import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; // Hadoop imports import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; // Nutch imports import org.apache.nutch.analysis.lang.NGramProfile.NGramEntry; import org.apache.nutch.crawl.CrawlDatum; import org.apache.nutch.parse.Parse; import org.apache.nutch.parse.ParseUtil; import org.apache.nutch.parse.ParseException; import org.apache.nutch.parse.ParserNotFound; import org.apache.nutch.protocol.Content; import org.apache.nutch.protocol.Protocol; import org.apache.nutch.protocol.ProtocolFactory; import org.apache.nutch.protocol.ProtocolNotFound; import org.apache.nutch.protocol.ProtocolException; import org.apache.nutch.util.NutchConfiguration; /** * Identify the language of a content, based on statistical analysis. * * @see <a href="http://www.w3.org/WAI/ER/IG/ert/iso639.htm">ISO 639 * Language Codes</a> * * @author Sami Siren * @author J&eacute;r&ocirc;me Charron */ public class LanguageIdentifier { private final static int DEFAULT_ANALYSIS_LENGTH = 0; // 0 means full content private final static float SCORE_THRESOLD = 0.00F; private final static Log LOG = LogFactory.getLog(LanguageIdentifier.class); private ArrayList languages = new ArrayList(); private ArrayList supportedLanguages = new ArrayList(); /** Minimum size of NGrams */ private int minLength = NGramProfile.DEFAULT_MIN_NGRAM_LENGTH; /** Maximum size of NGrams */ private int maxLength = NGramProfile.DEFAULT_MAX_NGRAM_LENGTH; /** The maximum amount of data to analyze */ private int analyzeLength = DEFAULT_ANALYSIS_LENGTH; /** A global index of ngrams of all supported languages */ private HashMap ngramsIdx = new HashMap(); /** The NGramProfile used for identification */ private NGramProfile suspect = null; /** My singleton instance */ private static LanguageIdentifier identifier = null; /** * Constructs a new Language Identifier. */ public LanguageIdentifier(Configuration conf) { // Gets ngram sizes to take into account from the Nutch Config minLength = conf.getInt("lang.ngram.min.length", NGramProfile.DEFAULT_MIN_NGRAM_LENGTH); maxLength = conf.getInt("lang.ngram.max.length", NGramProfile.DEFAULT_MAX_NGRAM_LENGTH); // Ensure the min and max values are in an acceptale range // (ie min >= DEFAULT_MIN_NGRAM_LENGTH and max <= DEFAULT_MAX_NGRAM_LENGTH) maxLength = Math.min(maxLength, NGramProfile.ABSOLUTE_MAX_NGRAM_LENGTH); maxLength = Math.max(maxLength, NGramProfile.ABSOLUTE_MIN_NGRAM_LENGTH); minLength = Math.max(minLength, NGramProfile.ABSOLUTE_MIN_NGRAM_LENGTH); minLength = Math.min(minLength, maxLength); // Gets the value of the maximum size of data to analyze analyzeLength = conf.getInt("lang.analyze.max.length", DEFAULT_ANALYSIS_LENGTH); Properties p = new Properties(); try { p.load(this.getClass().getResourceAsStream("langmappings.properties")); Enumeration alllanguages = p.keys(); if (LOG.isInfoEnabled()) { LOG.info(new StringBuffer() .append("Language identifier configuration [") .append(minLength).append("-").append(maxLength) .append("/").append(analyzeLength).append("]").toString()); } StringBuffer list = new StringBuffer("Language identifier plugin supports:"); HashMap tmpIdx = new HashMap(); while (alllanguages.hasMoreElements()) { String lang = (String) (alllanguages.nextElement()); InputStream is = this.getClass().getClassLoader().getResourceAsStream( "org/apache/nutch/analysis/lang/" + lang + "." + NGramProfile.FILE_EXTENSION); if (is != null) { NGramProfile profile = new NGramProfile(lang, minLength, maxLength); try { profile.load(is); languages.add(profile); supportedLanguages.add(lang); List ngrams = profile.getSorted(); for (int i=0; i<ngrams.size(); i++) { NGramEntry entry = (NGramEntry) ngrams.get(i); List registered = (List) tmpIdx.get(entry); if (registered == null) { registered = new ArrayList(); tmpIdx.put(entry, registered); } registered.add(entry); entry.setProfile(profile); } list.append(" " + lang + "(" + ngrams.size() + ")"); is.close(); } catch (IOException e1) { if (LOG.isFatalEnabled()) { LOG.fatal(e1.toString()); } } } } // transform all ngrams lists to arrays for performances Iterator keys = tmpIdx.keySet().iterator(); while (keys.hasNext()) { NGramEntry entry = (NGramEntry) keys.next(); List l = (List) tmpIdx.get(entry); if (l != null) { NGramEntry[] array = (NGramEntry[]) l.toArray(new NGramEntry[l.size()]); ngramsIdx.put(entry.getSeq(), array); } } if (LOG.isInfoEnabled()) { LOG.info(list.toString()); } // Create the suspect profile suspect = new NGramProfile("suspect", minLength, maxLength); } catch (Exception e) { if (LOG.isFatalEnabled()) { LOG.fatal(e.toString()); } } } /** * Main method used for command line process. * <br/>Usage is: * <pre> * LanguageIdentifier [-identifyrows filename maxlines] * [-identifyfile charset filename] * [-identifyfileset charset files] * [-identifytext text] * [-identifyurl url] * </pre> * @param args arguments. */ public static void main(String args[]) { String usage = "Usage: LanguageIdentifier " + "[-identifyrows filename maxlines] " + "[-identifyfile charset filename] " + "[-identifyfileset charset files] " + "[-identifytext text] " + "[-identifyurl url]"; int command = 0; final int IDFILE = 1; final int IDTEXT = 2; final int IDURL = 3; final int IDFILESET = 4; final int IDROWS = 5; Vector fileset = new Vector(); String filename = ""; String charset = ""; String url = ""; String text = ""; int max = 0; if (args.length == 0) { System.err.println(usage); System.exit(-1); } for (int i = 0; i < args.length; i++) { // parse command line if (args[i].equals("-identifyfile")) { command = IDFILE; charset = args[++i]; filename = args[++i]; } if (args[i].equals("-identifyurl")) { command = IDURL; filename = args[++i]; } if (args[i].equals("-identifyrows")) { command = IDROWS; filename = args[++i]; max = Integer.parseInt(args[++i]); } if (args[i].equals("-identifytext")) { command = IDTEXT; for (i++; i < args.length - 1; i++) text += args[i] + " "; } if (args[i].equals("-identifyfileset")) { command = IDFILESET; charset = args[++i]; for (i++; i < args.length; i++) { File[] files = null; File f = new File(args[i]); if (f.isDirectory()) { files = f.listFiles(); } else { files = new File[] { f }; } for (int j=0; j<files.length; j++) { fileset.add(files[j].getAbsolutePath()); } } } } Configuration conf = NutchConfiguration.create(); String lang = null; //LanguageIdentifier idfr = LanguageIdentifier.getInstance(); LanguageIdentifier idfr = new LanguageIdentifier(conf); File f; FileInputStream fis; try { switch (command) { case IDTEXT: lang = idfr.identify(text); break; case IDFILE: f = new File(filename); fis = new FileInputStream(f); lang = idfr.identify(fis, charset); fis.close(); break; case IDURL: text = getUrlContent(filename, conf); lang = idfr.identify(text); break; case IDROWS: f = new File(filename); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f))); String line; while (max > 0 && (line = br.readLine()) != null) { line = line.trim(); if (line.length() > 2) { max--; lang = idfr.identify(line); System.out.println("R=" + lang + ":" + line); } } br.close(); System.exit(0); break; case IDFILESET: /* used for benchs for (int j=128; j<=524288; j*=2) { long start = System.currentTimeMillis(); idfr.analyzeLength = j; */ System.out.println("FILESET"); Iterator i = fileset.iterator(); while (i.hasNext()) { try { filename = (String) i.next(); f = new File(filename); fis = new FileInputStream(f); lang = idfr.identify(fis, charset); fis.close(); } catch (Exception e) { System.out.println(e); } System.out.println(filename + " was identified as " + lang); } /* used for benchs System.out.println(j + "/" + (System.currentTimeMillis()-start)); } */ System.exit(0); break; } } catch (Exception e) { System.out.println(e); } System.out.println("text was identified as " + lang); } /** * @param url * @return contents of url */ private static String getUrlContent(String url, Configuration conf) { Protocol protocol; try { protocol = new ProtocolFactory(conf).getProtocol(url); Content content = protocol.getProtocolOutput(new Text(url), new CrawlDatum()).getContent(); Parse parse = new ParseUtil(conf).parse(content).get(content.getUrl()); System.out.println("text:" + parse.getText()); return parse.getText(); } catch (ProtocolNotFound e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (ParserNotFound e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return null; } /** * Identify language of a content. * * @param content is the content to analyze. * @return The 2 letter * <a href="http://www.w3.org/WAI/ER/IG/ert/iso639.htm">ISO 639 * language code</a> (en, fi, sv, ...) of the language that best * matches the specified content. */ public String identify(String content) { return identify(new StringBuffer(content)); } /** * Identify language of a content. * * @param content is the content to analyze. * @return The 2 letter * <a href="http://www.w3.org/WAI/ER/IG/ert/iso639.htm">ISO 639 * language code</a> (en, fi, sv, ...) of the language that best * matches the specified content. */ public String identify(StringBuffer content) { StringBuffer text = content; if ((analyzeLength > 0) && (content.length() > analyzeLength)) { text = new StringBuffer().append(content); text.setLength(analyzeLength); } suspect.analyze(text); Iterator iter = suspect.getSorted().iterator(); float topscore = Float.MIN_VALUE; String lang = ""; HashMap scores = new HashMap(); NGramEntry searched = null; while (iter.hasNext()) { searched = (NGramEntry) iter.next(); NGramEntry[] ngrams = (NGramEntry[]) ngramsIdx.get(searched.getSeq()); if (ngrams != null) { for (int j=0; j<ngrams.length; j++) { NGramProfile profile = ngrams[j].getProfile(); Float pScore = (Float) scores.get(profile); if (pScore == null) { pScore = new Float(0); } float plScore = pScore.floatValue(); plScore += ngrams[j].getFrequency() + searched.getFrequency(); scores.put(profile, new Float(plScore)); if (plScore > topscore) { topscore = plScore; lang = profile.getName(); } } } } return lang; } /** * Identify language from input stream. * This method uses the platform default encoding to read the input stream. * For using a specific encoding, use the * {@link #identify(InputStream, String)} method. * * @param is is the input stream to analyze. * @return The 2 letter * <a href="http://www.w3.org/WAI/ER/IG/ert/iso639.htm">ISO 639 * language code</a> (en, fi, sv, ...) of the language that best * matches the content of the specified input stream. * @throws IOException if something wrong occurs on the input stream. */ public String identify(InputStream is) throws IOException { return identify(is, null); } /** * Identify language from input stream. * * @param is is the input stream to analyze. * @param charset is the charset to use to read the input stream. * @return The 2 letter * <a href="http://www.w3.org/WAI/ER/IG/ert/iso639.htm">ISO 639 * language code</a> (en, fi, sv, ...) of the language that best * matches the content of the specified input stream. * @throws IOException if something wrong occurs on the input stream. */ public String identify(InputStream is, String charset) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int len = 0; while (((len = is.read(buffer)) != -1) && ((analyzeLength == 0) || (out.size() < analyzeLength))) { if (analyzeLength != 0) { len = Math.min(len, analyzeLength - out.size()); } out.write(buffer, 0, len); } return identify((charset == null) ? out.toString() : out.toString(charset)); } }
33.566879
97
0.593612
ec60c7bd2816299d558c9f3fe8d8c11a5b9de1ac
1,205
package warehouses; public class Knob<T> { private warehouses.Knob<T> now; private T evidence; static final double inferiorTethered = 0.07799524888686626; public synchronized void fixedStudy(T records) { double numberPieces; numberPieces = 0.22128385505054982; this.evidence = records; } private warehouses.Knob<T> old; public synchronized warehouses.Knob<T> produceSecond() { int confine; confine = 962493330; return this.now; } public Knob(T intelligence, Knob<T> later, Knob<T> initial) { this.evidence = intelligence; this.now = later; this.old = initial; } public synchronized T becomeStudy() { String speedTrussed; speedTrussed = "bQg8rW"; return this.evidence; } public synchronized void determinedPremature(warehouses.Knob<T> last) { double maximize; maximize = 0.14551504587039943; this.old = last; } public synchronized void situatedForthcoming(warehouses.Knob<T> coming) { int subordinateFettered; subordinateFettered = -1222830138; this.now = coming; } public synchronized warehouses.Knob<T> driveFinal() { int chained; chained = -1599887331; return this.old; } }
23.173077
75
0.697925
8389ce112d18d6c50bb4ea3a15fd457b8c58dc31
1,326
package com.template.flows; import co.paralleluniverse.fibers.Suspendable; import com.r3.corda.lib.tokens.workflows.flows.rpc.CreateEvolvableTokens; import com.template.states.FungEvoTokenType; import net.corda.core.contracts.TransactionState; import net.corda.core.flows.*; import net.corda.core.identity.Party; import net.corda.core.transactions.SignedTransaction; @InitiatingFlow @StartableByRPC public class CreateFungEvoTokenType extends FlowLogic<String> { private Party issuer; private String msg; public CreateFungEvoTokenType(Party issuer, String msg) { this.issuer = issuer; this.msg = msg; } @Override @Suspendable public String call() throws FlowException { final Party notary = getServiceHub().getNetworkMapCache().getNotaryIdentities().get(0); final FungEvoTokenType fungEvoToken = new FungEvoTokenType(this.msg,this.getOurIdentity()); TransactionState transactionState = new TransactionState(fungEvoToken, notary); SignedTransaction stx = subFlow(new CreateEvolvableTokens(transactionState)); return "TokenType Created with Id: " + fungEvoToken.getLinearId().toString(); } } // flow start CreateFungEvoTokenType issuer: InvestorA, msg: hello // run vaultQuery contractStateType: com.template.states.FungEvoTokenType
35.837838
99
0.764706
a3d8aba5eccbce21fcc6ea4cb114240af7aa85d5
640
package redhat.jee_migration_example.management.itemManager; import org.aries.bean.Proxy; import org.aries.tx.service.rmi.RMIProxy; public class ItemManagerProxyForRMI extends RMIProxy implements Proxy<ItemManager> { private ItemManagerInterceptor itemManagerInterceptor; public ItemManagerProxyForRMI(String serviceId, String host, int port) { super(serviceId, host, port); createDelegate(); } protected void createDelegate() { itemManagerInterceptor = new ItemManagerInterceptor(); itemManagerInterceptor.setProxy(this); } @Override public ItemManager getDelegate() { return itemManagerInterceptor; } }
22.068966
84
0.789063
4a01392b3fb24db8778eb45503fee18ab4c177ad
4,010
package com.intellij.xml; import com.intellij.codeInsight.CodeInsightSettings; import com.intellij.codeInsight.completion.CompletionType; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.javaee.ExternalResourceManagerImpl; import com.intellij.testFramework.IdeaTestCase; import com.intellij.testFramework.PlatformTestUtil; import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import java.io.File; import java.util.Arrays; import java.util.List; /** * @author Dmitry Avdeev */ public class XmlSmartCompletionTest extends LightPlatformCodeInsightFixtureTestCase { @SuppressWarnings("JUnitTestCaseWithNonTrivialConstructors") public XmlSmartCompletionTest() { IdeaTestCase.initPlatformPrefix(); } public void testCompletion() throws Exception { doTest(new String[]{"testCompletion.xml", "test.xsd"}, "b"); } public void testCompletionNext() throws Exception { doTest(new String[]{"testCompletionNext.xml", "test.xsd"}, "c"); } public void testCompletion3() throws Exception { doTest(new String[]{"testCompletion3.xml", "test.xsd"}, "c", "d"); } public void testServlet() throws Exception { doTest(new String[]{"Servlet.xml"}, "icon", "servlet-name"); } public void testServletName() throws Exception { doForText("<!DOCTYPE web-app\n" + " PUBLIC \"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\"\n" + " \"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd\">\n" + "<web-app>\n" + "\n" + " <servlet>\n" + " <s<caret>\n" + " </servlet>\n" + "</web-app>", "<!DOCTYPE web-app\n" + " PUBLIC \"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\"\n" + " \"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd\">\n" + "<web-app>\n" + "\n" + " <servlet>\n" + " <servlet-name\n" + " </servlet>\n" + "</web-app>"); } public void testPrefix() throws Exception { doForText("<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + " <ann<caret>\n" + "</xs:schema>", "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + " <xs:annotation\n" + "</xs:schema>"); } private void doForText(String before, String after) { myFixture.configureByText("a.xml", before); myFixture.complete(CompletionType.SMART); myFixture.checkResult(after); } private void doTest(String[] files, String... items) { myFixture.configureByFiles(files); LookupElement[] elements; try { CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION = false; elements = myFixture.complete(CompletionType.SMART); } finally { CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION = true; } assert elements != null; List<String> strings = ContainerUtil.map(elements, new Function<LookupElement, String>() { @Override public String fun(LookupElement lookupElement) { return lookupElement.getLookupString(); } }); assertEquals(Arrays.asList(items), strings); } @Override public void setUp() throws Exception { super.setUp(); ExternalResourceManagerImpl.registerResourceTemporarily("http://java.sun.com/j2ee/dtds/web-app_2_3.dtd", getTestDataPath() + "/web-app_2_3.dtd", getTestRootDisposable()); } @Override protected String getBasePath() { return "/xml/tests/testData/smartCompletion"; } @Override protected String getTestDataPath() { return PlatformTestUtil.getCommunityPath().replace(File.separatorChar, '/') + getBasePath(); } }
33.697479
125
0.630424
949035ba4dbf62836d917160e9a127105d8c4d82
4,487
package io.abnd.rvep.event.service.impl; import io.abnd.rvep.event.dao.intf.RvepEventDAO; import io.abnd.rvep.event.dao.intf.RvepEventItemDAO; import io.abnd.rvep.event.dao.intf.RvepEventProfileDAO; import io.abnd.rvep.event.dao.intf.RvepLocationDAO; import io.abnd.rvep.event.model.RvepEvent; import io.abnd.rvep.event.model.RvepEventItem; import io.abnd.rvep.event.model.RvepLocation; import io.abnd.rvep.event.model.intf.AddEventItemRequest; import io.abnd.rvep.event.service.intf.EventItemService; import io.abnd.rvep.security.dao.intf.RvepUserEventRoleDAO; import io.abnd.rvep.security.model.RvepUserEventRole; import io.abnd.rvep.user.dao.intf.RvepUserProfileDAO; import io.abnd.rvep.user.model.RvepUser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityNotFoundException; import java.util.Calendar; import java.util.List; @Service public class RvepEventItemService implements EventItemService { private RvepUserProfileDAO rvepUserProfileDAO; private RvepEventProfileDAO rvepEventProfileDAO; private RvepEventItemDAO rvepEventItemDAO; private RvepUserEventRoleDAO rvepUserEventRoleDAO; private RvepLocationDAO rvepLocationDAO; private static final Logger logger = LoggerFactory.getLogger(RvepEventItemService.class); public RvepEventItemService(RvepUserProfileDAO rvepUserProfileDAO, RvepEventProfileDAO rvepEventProfileDAO, RvepEventItemDAO rvepEventItemDAO, RvepUserEventRoleDAO rvepUserEventRoleDAO, RvepLocationDAO rvepLocationDAO) { this.rvepUserProfileDAO = rvepUserProfileDAO; this.rvepEventProfileDAO = rvepEventProfileDAO; this.rvepEventItemDAO = rvepEventItemDAO; this.rvepUserEventRoleDAO = rvepUserEventRoleDAO; this.rvepLocationDAO = rvepLocationDAO; } @Override public List<RvepEventItem> getAllEventItems(String eventProfileId, String email) { // get user id RvepUser user = this.rvepUserProfileDAO.findByEmail(email).getRvepUser(); // get event RvepEvent event = rvepEventProfileDAO .findById(Integer.valueOf(eventProfileId).intValue()) .getRvepEvent(); // get user event roles List<RvepUserEventRole> rvepUserEventRoles = this.rvepUserEventRoleDAO .findByRvepUserIdAndRvepEventId(user.getId(), event.getId()); // check if user has roles for the event if (rvepUserEventRoles.size() > 0) { return this.rvepEventItemDAO.findByRvepEventId(event.getId()); } // no access found, throw exception throw new EntityNotFoundException(); } @Override @Transactional public RvepEventItem addEventItem(AddEventItemRequest addEventItemRequest) { // init return RvepEventItem rvepEventItem = new RvepEventItem(); // get calendar Calendar cal = Calendar.getInstance(); // get event RvepEvent rvepEvent = rvepEventProfileDAO.findByRvepEventId(addEventItemRequest.getEventId()).getRvepEvent(); // create event location RvepLocation rvepLocation = new RvepLocation(); rvepLocation.setTitle(addEventItemRequest.getLocationTitle()); rvepLocation.setDescription(addEventItemRequest.getDescription()); rvepLocation.setGeolat(addEventItemRequest.getLocationGeoLat()); rvepLocation.setGeolng(addEventItemRequest.getLocationGeoLng()); rvepLocation.setEnabled((byte)1); // create event item rvepEventItem.setTitle(addEventItemRequest.getTitle()); rvepEventItem.setDescription(addEventItemRequest.getDescription()); rvepEventItem.setDateTime(addEventItemRequest.getDateTime()); rvepEventItem.setCreatedOn(cal.getTime()); rvepEventItem.setUpdatedOn(rvepEventItem.getCreatedOn()); rvepEventItem.setRvepEvent(rvepEvent); rvepEventItem.setRvepLocation(rvepLocation); rvepEventItem.setEnabled((byte)1); try { // store rvepLocationDAO.save(rvepLocation); rvepEventItemDAO.save(rvepEventItem); } catch(Exception e) { logger.error(e.getMessage()); return null; } return rvepEventItem; } }
39.707965
117
0.716069
61e1a30da2371beb4201840c6c725038223d7f26
698
/* * Copyright (c) 2008-2014 Haulmont. All rights reserved. * Use is subject to license terms, see http://www.cuba-platform.com/license for details. */ package com.haulmont.charts.web.toolkit.ui.client.amcharts.events; import com.google.gwt.core.client.JavaScriptObject; /** * @author artamonov * @version $Id$ */ public class JsAxisZoomedEvent extends JavaScriptObject { protected JsAxisZoomedEvent() { } public final native String getAxisId() /*-{ return this.axisId; }-*/; public final native double getStartValue() /*-{ return this.startValue; }-*/; public final native double getEndValue() /*-{ return this.endValue; }-*/; }
23.266667
89
0.670487
1bd49e458c699af57607d374a616f8a1ab9c3a3b
216
package pro.taskana.report; /** * This enum contains all timestamps saved in the database table for a {@link pro.taskana.Task}. */ public enum Timestamp { CREATED, CLAIMED, COMPLETED, MODIFIED, PLANNED, DUE }
24
96
0.726852
9fbb288fc2229bfedb709f56ce4fbff83999ca69
2,882
package com.son.config; import com.son.security.JwtAuthenticationFilter; import com.son.security.UserDetailsServiceImpl; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.BeanIds; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; @Configuration @EnableWebSecurity(debug = true) @RequiredArgsConstructor public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private final UserDetailsServiceImpl userDetailsService; private final JwtAuthenticationFilter jwtAuthenticationFilter; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.httpBasic() .and() .authorizeRequests() .antMatchers(HttpMethod.POST, "/auth/login").permitAll() .antMatchers("/swagger-ui.html").permitAll() .and() .cors() .and() .csrf().disable() .formLogin().disable() .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); } @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean(BeanIds.AUTHENTICATION_MANAGER) @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; } }
38.945946
107
0.767176
6becdd12e9a525756ca7185bad43068ad3e53334
8,664
package com.doyou.cv.widget.legend; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.dongni.tools.DensityUtil; import com.dongni.tools.EmptyUtils; import com.doyou.cv.R; import com.doyou.cv.utils.Utils; import com.doyou.cv.widget.PointView; import java.util.List; import androidx.annotation.Nullable; import androidx.constraintlayout.widget.ConstraintLayout; /** * 图例控件 * @autor hongbing * @date 2019/3/28 */ public class LegendView extends LinearLayout { private Context mContext; // 图例的列宽 private int mColumnWidth; // 图例行间距 private int mLegendVerMargin; // 图例字体颜色 private int mLabelColor; // 图例字体大小 private float mLabelSize; // 图例文案和圆点的间距 private int mLegendLabelAndPointMargin; // 图例每行第一个左侧偏移量 private int mLegendOffsetLeft; // 动态计算出来的列数 private int mColumn; public LegendView(Context context) { this(context, null); } public LegendView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public LegendView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context; setOrientation(LinearLayout.VERTICAL); setGravity(Gravity.CENTER); initAttr(attrs); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); Utils.logD("201812201056", "onLayout->MeasuredWidth = " + getMeasuredWidth() + "->changed = " + changed); } private void initAttr(AttributeSet attrs) { TypedArray ta = mContext.obtainStyledAttributes(attrs,R.styleable.LegendView); mColumnWidth = ta.getDimensionPixelOffset(R.styleable.LegendView_lv_legend_columnW, DensityUtil.dp2px(42)); mLegendVerMargin = ta.getDimensionPixelOffset(R.styleable.LegendView_lv_legend_vertical_margin, DensityUtil.sp2px(mContext, 8)); mLabelColor = ta.getColor(R.styleable.LegendView_lv_legend_font_color, Color.rgb(42, 42, 42)); mLabelSize = ta.getDimensionPixelSize(R.styleable.LegendView_lv_legend_font_size, DensityUtil.sp2px(mContext, 12)); mLegendLabelAndPointMargin = ta.getDimensionPixelOffset(R.styleable.LegendView_lv_legend_labelAndPoint_margin, DensityUtil.dp2px(4)); mLegendOffsetLeft = ta.getDimensionPixelOffset(R.styleable.LegendView_lv_legend_offset_left, 0); ta.recycle(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); Utils.logD("20190328", "onMeasure = " + getMeasuredWidth()); } @Override protected void onFinishInflate() { super.onFinishInflate(); Utils.logD("20190328", "onFinishInflate = " + getMeasuredWidth()); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); Utils.logD("20190328", "onAttachedToWindow = " + getMeasuredWidth()); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); Utils.logD("20190328", "onDetachedFromWindow = " + getMeasuredWidth()); } /** * 动态计算列数 */ private void autoCaclColumn() { if (getParent() instanceof ConstraintLayout) { ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) getLayoutParams(); int margin = params.leftMargin + params.rightMargin; // 计算每行显示列数 mColumn = (getMeasuredWidth() - margin) / mColumnWidth; Utils.logD("201812201056", "动态计算出的列数 = " + mColumn + "->MeasuredWidth = " + getMeasuredWidth() + "->margin = " + margin + "->left = " + getPaddingLeft() + "->right = " + getPaddingRight()); } else { throw new IllegalArgumentException("外层布局需要使用ConstraintLayout"); } } /** * 没有图例内容 */ public void setEmpty() { setVisibility(View.GONE); } /** * 设置图例数据 * * @param legends * @param colors */ public void setData(final List<String> legends, final int[] colors) { if (EmptyUtils.isEmpty(legends)) { setVisibility(View.GONE); return; } if (getVisibility() == View.GONE) { setVisibility(View.VISIBLE); } post(new Runnable() { @Override public void run() { autoCaclColumn(); int size = legends.size(); // 图例行数 int circulation = size / mColumn + (size % mColumn > 0 ? 1 : 0); Utils.logD("201812201056", "图例行数 = " + circulation + "->集合总数size = " + size + "->size / mColumn = " + (size / mColumn) + "->size % mColumn = " + (size % mColumn)); if (mColumn > size) { mColumn = size; } removeAllViews(); LinearLayout labelLayout; PointView pointView; TextView labelTv; LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); LinearLayout.LayoutParams sonParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); for (int i = 0; i < circulation; i++) { labelLayout = new LinearLayout(mContext); labelLayout.setLayoutParams(params); // linearLayout.setBackgroundColor(Color.rgb(123, 180, 248)); if (circulation == 1) { // 只有一行,水平居中 labelLayout.setGravity(Gravity.CENTER); } else { // 左对齐 labelLayout.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL); if (i > 0) { // 大于一行,第一行不设置行间上间距 params.topMargin = mLegendVerMargin; } params.leftMargin = mLegendOffsetLeft; } for (int j = 0; j < mColumn; j++) { // 创建label final int pos = i * mColumn + j; if (pos > size - 1) { // 全取干净了 break; } pointView = new PointView(mContext); pointView.setColor(colors[pos]); if (j > 0) { if (legends.get(pos - 1).length() > 2) { // 针对三个文字的间距设置 sonParams.leftMargin = DensityUtil.dp2px(12); pointView.setLayoutParams(sonParams); } } labelLayout.addView(pointView); labelTv = new TextView(mContext); // if (BuildConfig.DEBUG) { // labelTv.setBackgroundColor(Color.rgb(218, 112, 214)); // } labelTv.setGravity(Gravity.CENTER_VERTICAL); labelTv.setPadding(mLegendLabelAndPointMargin, 0, 0, 0); labelTv.setWidth(mColumnWidth); labelTv.setText(legends.get(pos)); labelTv.setTextColor(mLabelColor); labelTv.setTextSize(TypedValue.COMPLEX_UNIT_PX, mLabelSize); labelLayout.addView(labelTv); labelTv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mListener != null) { mListener.onLegendClick(pos); } } }); } addView(labelLayout); // 会导致onMeasure重新测量 } } }); } private LegendListener mListener; public void setLegendListener(LegendListener listener) { mListener = listener; } public interface LegendListener { void onLegendClick(int label); } }
37.025641
156
0.567059
8b4793ef0ba1b7ed9fc172101d20deeaba3d9837
1,080
package com.grandrain.tetris.logic.bricks; import com.grandrain.tetris.logic.MatrixOperations; import java.util.ArrayList; import java.util.List; final class LBrick implements Brick { private final List<int[][]> brickMatrix = new ArrayList<>(); public LBrick() { brickMatrix.add(new int[][]{ {0, 0, 0, 0}, {0, 3, 3, 3}, {0, 3, 0, 0}, {0, 0, 0, 0} }); brickMatrix.add(new int[][]{ {0, 0, 0, 0}, {0, 3, 3, 0}, {0, 0, 3, 0}, {0, 0, 3, 0} }); brickMatrix.add(new int[][]{ {0, 0, 0, 0}, {0, 0, 3, 0}, {3, 3, 3, 0}, {0, 0, 0, 0} }); brickMatrix.add(new int[][]{ {0, 3, 0, 0}, {0, 3, 0, 0}, {0, 3, 3, 0}, {0, 0, 0, 0} }); } @Override public List<int[][]> getShapeMatrix() { return MatrixOperations.deepCopyList(brickMatrix); } }
24.545455
64
0.399074
83029605bb811710b52850ae73958cfc5be1667a
1,347
package com.validus.music.service; import com.validus.music.entity.Artist; import com.validus.music.repository.ArtistRepository; import com.validus.music.service.exception.ServiceException; import org.springframework.stereotype.Service; @Service public class ArtistService implements GenericService<Artist, Long> { private ArtistRepository artistRepository; public ArtistService(ArtistRepository artistRepository) { this.artistRepository = artistRepository; } @Override public Artist create(Artist artist) { return artistRepository.save(artist); } @Override public Artist read(Long id) { return artistRepository.findOne(id); } @Override public boolean update(Artist artist) { if (artistRepository.exists(artist.getId())) { artistRepository.save(artist); } else { throw new ServiceException("Can't update Artist because it doesn't exist in DB: " + artist); } return true; } @Override public boolean delete(Long id) { if (artistRepository.exists(id)) { artistRepository.delete(id); } else { throw new ServiceException("Can't delete Artist because it doesn't exist in DB: " + id); } return true; } }
28.659574
105
0.647365
3f3bcfbfaf2967d08d06847e56897741b26b0113
1,234
package de.dkiefner.qapital.exercise.data.savingsrule; import com.google.auto.value.AutoValue; import com.pushtorefresh.storio.sqlite.annotations.StorIOSQLiteColumn; import com.pushtorefresh.storio.sqlite.annotations.StorIOSQLiteCreator; import com.pushtorefresh.storio.sqlite.annotations.StorIOSQLiteType; import java.io.Serializable; @AutoValue @StorIOSQLiteType(table = SavingsRule.TABLE_NAME) public abstract class SavingsRule implements Serializable { public static final String TABLE_NAME = "savings_rule"; public static final class FieldInfo { public static final String ID = "id"; public static final String TYPE = "type"; public static final String AMOUNT = "amount"; } public static final class Type { public static final String ROUND_UP = "roundup"; public static final String GUILTY_PLEASURE = "guilty_pleasure"; } @StorIOSQLiteColumn(name = FieldInfo.ID, key = true) public abstract int id(); @StorIOSQLiteColumn(name = FieldInfo.TYPE) public abstract String type(); @StorIOSQLiteColumn(name = FieldInfo.AMOUNT) public abstract float amount(); @StorIOSQLiteCreator static SavingsRule create(int id, String type, float amount) { return new AutoValue_SavingsRule(id, type, amount); } }
29.380952
71
0.786872
7119393579a1c0ffc209aaf5d388b237eef13898
227
package com.myapp.dto; import com.myapp.domain.Micropost; import lombok.Value; @Value public class MicropostParams { private String content; public Micropost toPost() { return new Micropost(content); } }
15.133333
37
0.709251
bdfc0aa8768094036fdfd4f4a7153b363f5d0f1f
317
package com.example.model; import lombok.Data; import java.util.Date; /** * Created by IntelliJ IDEA. * * @author : cchu * Date: 2021/11/10 10:44 */ @Data public class TestBean { private String name; private int age; private double score; private boolean isPass; private Date examDate; }
14.409091
28
0.671924
1fa9d017546c9e453255a36a5ce32260c129ec16
2,679
package com.github.jstrainer; import static java.util.stream.Collectors.toList; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.jstrainer.filter.Filter; import com.github.jstrainer.filter.FilterFactory; public class Strainer { private static final Logger logger = LoggerFactory.getLogger(Strainer.class); public void filter(final Object object) { logger.debug("Filtering object: {}", object.getClass()); final Field[] fields = object.getClass().getDeclaredFields(); for (Field field : fields) { filterField(object, field); } } private void filterField(final Object object, final Field field) { if (field.getAnnotation(Filtered.class) != null) { filterChild(object, field); return; } final List<Annotation> annotations = getAnnotations(field); if (annotations.isEmpty()) { return; } annotations.forEach(annotation -> applyFilters(object, field, annotation)); } private void filterChild(final Object object, final Field field) { field.setAccessible(true); try { filter(field.get(object)); } catch (IllegalArgumentException | IllegalAccessException e) { logger.warn("An error occurred while applying filters on field {}", field.getName(), e); } field.setAccessible(false); } private void applyFilters(final Object object, final Field field, final Annotation annotation) { logger.debug("Filtering field: {}.{}", object.getClass(), field.getName()); field.setAccessible(true); getFilters(annotation).forEach(filter -> setNewValue(object, field, annotation, filter)); field.setAccessible(false); } private void setNewValue(final Object object, final Field field, final Annotation annotation, final Filter filter) { try { final Object oldValue = field.get(object); final Object newValue = filter.filter(oldValue, annotation); field.set(object, newValue); } catch (IllegalArgumentException | IllegalAccessException e) { logger.warn("An error occurred while applying the filter {} on field {}", filter.getClass(), field.getName(), e); } } private List<Filter> getFilters(final Annotation annotation) { final FilteredBy filteredBy = annotation.annotationType().getAnnotation(FilteredBy.class); return Stream.of(filteredBy.value()).map(FilterFactory::getFilter).collect(toList()); } private List<Annotation> getAnnotations(final Field field) { return Arrays.stream(field.getAnnotations()) .filter(a -> a.annotationType().isAnnotationPresent(FilteredBy.class)).collect(toList()); } }
29.766667
117
0.743188
f75e19d7fa5c46bf63961884ef54543c2952c8db
10,508
package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class roomcategory_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory(); private static java.util.List<String> _jspx_dependants; static { _jspx_dependants = new java.util.ArrayList<String>(3); _jspx_dependants.add("/includes/header.jsp"); _jspx_dependants.add("/includes/menu.jsp"); _jspx_dependants.add("/includes/footer.jsp"); } private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector; public java.util.List<String> getDependants() { return _jspx_dependants; } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write(' '); out.write("<!DOCTYPE html>\n"); out.write("<html lang=\"en\">\n"); out.write("<head>\n"); out.write(" \n"); out.write(" <meta charset=\"utf-8\">\n"); out.write(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"); out.write(" <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css\" rel=\"stylesheet\">\n"); out.write(" <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js\"></script>\n"); out.write(" \n"); out.write(" <!--<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\">-->\n"); out.write(" <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"></script>\n"); out.write(" <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"></script>\n"); out.write(" <link href=\"styles/hotelstyle.css\" rel=\"stylesheet\"/>"); out.write("\n"); out.write(" <head>\n"); out.write("<title>roomcategory </title>\n"); out.write("\n"); out.write(" \n"); out.write("</head>\n"); out.write("<body>\n"); out.write(" <!--************Header Form Start************-->\n"); out.write(" \n"); out.write(" <div class=\"container-fluid\">\n"); out.write(" . \n"); out.write(" <div style=\"background-size: cover ;background-image: url('images/people.jpg')\" class=\"p-5 bg-primary text-white text-center\">\n"); out.write(" <h1 class=\"display-1\">Hotel Star</h1>\n"); out.write(" <p class=\"fw-bold\">A hotel is just a place to lay your head.\n"); out.write(" !</p> \n"); out.write(" </div>\n"); out.write(" <!--************Header Form Ends ************-->\n"); out.write("\n"); out.write(" <!--************Menu Form Starts ************-->\n"); out.write(" "); out.write("<nav class=\"navbar navbar-expand-sm bg-dark navbar-dark\">\n"); out.write(" <div class=\"container-fluid\">\n"); out.write(" <a class=\"navbar-brand\" href=\"#\"><img class=\"imgstyle\" src=\"images/logo3.jpg\"></a>\n"); out.write(" <button class=\"navbar-toggler\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#collapsibleNavbar\">\n"); out.write(" <span class=\"navbar-toggler-icon\"></span>\n"); out.write(" </button>\n"); out.write(" <div class=\"collapse navbar-collapse\" id=\"collapsibleNavbar\">\n"); out.write(" <ul class=\"navbar-nav\">\n"); out.write(" <li class=\"nav-item\">\n"); out.write(" <a class=\"nav-link\" href=\"index.jsp\">Home</a>\n"); out.write(" </li>\n"); out.write(" <li class=\"nav-item\">\n"); out.write(" <a class=\"nav-link\" href=\"contact.jsp\">Contact</a>\n"); out.write(" </li>\n"); out.write("\n"); out.write("\n"); out.write(" <li class=\"nav-item dropdown\">\n"); out.write(" <a class=\"nav-link dropdown-toggle\" href=\"#\" role=\"button\" data-bs-toggle=\"dropdown\">Utilities</a>\n"); out.write(" <ul class=\"dropdown-menu\">\n"); out.write(" <li><a class=\"dropdown-item\" href=\"categorymaster.jsp\">Booking</a></li>\n"); out.write(" <li><a class=\"dropdown-item\" href=\"roomcategory.jsp\">Lookup</a></li>\n"); out.write(" <li><a class=\"dropdown-item\" href=\"#\">Cancellation</a></li>\n"); out.write(" </ul>\n"); out.write(" </li>\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write(" </ul>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write("</nav>\n"); out.write("\n"); out.write(" \n"); out.write(" \n"); out.write(" <!--************Menu Form Ends ************-->\n"); out.write(" \n"); out.write(" <!--************Body Starts ************-->\n"); out.write(" <div class=\"container mt-3\"><center>\n"); out.write(" <h1 style=\"color: red\">Room Category </h1>\n"); out.write(" <h4>Please select the room category:</4></center>\n"); out.write(" <table class=\"table\">\n"); out.write(" <thead class=\"table-dark\"></thead>\n"); out.write(" </table>\n"); out.write(" </div>\n"); out.write(" \n"); out.write(" <div class=\"row\">\n"); out.write(" <div class=\"col-md-3\">\n"); out.write(" <div class=\"thumbnail\">\n"); out.write(" <a href=\"singlebed.jsp\">\n"); out.write(" <img src=\"roomimages/3.jpg\" class=\"rahstyle\" alt=\"Lights\" style=\"width:100%\">\n"); out.write(" <div class=\"caption\">\n"); out.write(" <h4>single bed...</h4>\n"); out.write(" </div>\n"); out.write(" </a>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" <div class=\"col-md-3\">\n"); out.write(" <div class=\"thumbnail\">\n"); out.write(" <a href=\"doublebed.jsp\">\n"); out.write(" <img src=\"roomimages/31.jpg\" class=\"rahstyle\" alt=\"Nature\" style=\"width:100%\">\n"); out.write(" <div class=\"caption\">\n"); out.write(" <h4>double bed ...</h4>\n"); out.write(" </div>\n"); out.write(" </a>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" <div class=\"col-md-3\">\n"); out.write(" <div class=\"thumbnail\">\n"); out.write(" <a href=\"luxury.jsp\">\n"); out.write(" <img src=\"roomimages/24.jpg\" class=\"rahstyle\" alt=\"Fjords\" style=\"width:100%\">\n"); out.write(" <div class=\"caption\">\n"); out.write(" <h4>luxury...</h4>\n"); out.write(" </div>\n"); out.write(" </a>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" <div class=\"col-md-3\">\n"); out.write(" <div class=\"thumbnail\">\n"); out.write(" <a href=\"deluxe.jsp\">\n"); out.write(" <img src=\"roomimages/11.jpg\" class=\"rahstyle\" alt=\"Fjords\" style=\"width:100%\">\n"); out.write(" <div class=\"caption\">\n"); out.write(" <h4>deluxe...</h4>\n"); out.write(" </div>\n"); out.write(" </a>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write("</div>\n"); out.write(" \n"); out.write(" \n"); out.write(" \n"); out.write(" <!--************Body Ends ************--> \n"); out.write(" \n"); out.write(" \n"); out.write(" <!--************Footer Form Starts ************--> \n"); out.write(" "); out.write("<div class=\"mt-5 p-4 bg-dark text-white text-center\">\n"); out.write(" <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\">\n"); out.write(" <p>Developed by :</p>\n"); out.write(" <p> GOVIND KUMAR</p>\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("<!-- Add font awesome icons -->\n"); out.write("<a href=\"#\" class=\"fa fa-facebook\"></a>\n"); out.write("<a href=\"#\" class=\"fa fa-twitter\"></a>\n"); out.write("<a href=\"#\" class=\"fa fa-instagram\"></a>\n"); out.write("</div>"); out.write("\n"); out.write(" <!--************Footer Form Ends ************-->\n"); out.write(" \n"); out.write(" </body>\n"); out.write("</html>\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
50.038095
161
0.500952
e6400ca869790605c6b378144d455fe7c9143e7f
1,847
package com.stackroute.user.config; import com.stackroute.user.domain.Mapping; import com.stackroute.user.domain.Material; import com.stackroute.user.domain.Supplier; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory; import org.springframework.kafka.support.serializer.JsonSerializer; import java.util.HashMap; import java.util.Map; @Configuration public class KafkaConfiguration { @Bean public ProducerFactory<String, Supplier> producerFactory1() { Map<String, Object> config = new HashMap<>(); config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); return new DefaultKafkaProducerFactory<>(config); } @Bean public KafkaTemplate<String, Supplier> kafkaTemplate1() { return new KafkaTemplate<>(producerFactory1()); } @Bean public ProducerFactory<String, Mapping> producerFactory2() { Map<String, Object> config = new HashMap<>(); config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); return new DefaultKafkaProducerFactory<>(config); } @Bean public KafkaTemplate<String, Mapping> kafkaTemplate2() { return new KafkaTemplate<>(producerFactory2()); } }
34.849057
83
0.797509
73e9cfca63dbc51a9d73e542af605e37b32e1142
29
public class ClassToTest { }
7.25
24
0.758621
c3a3f660e823b3c88c58737810ffdd74f1496b94
526
package old.datatypes.bindingsite; import old.datatypes.sequence.Sequence; /** * This class represents the unbound state. It is not designed to be used independently, but rather as part of another class. * @author Tristan Bepler * */ public class Unbound extends AbstractNBindingSites{ public Unbound(Sequence seq){ super(seq, new int[]{}, new int[]{}); } protected Unbound(Sequence seq, int[] starts, int[] ends) { super(seq, starts, ends); } @Override public String getName() { return "Unbound"; } }
20.230769
125
0.709125
2af408ec256e0b41fdf2b7c853eb371db742cbfb
458
package com.kqp.tcrafting.mixin.accessor; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Overlay; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; @Mixin(MinecraftClient.class) public interface MinecraftClientAccessor { @Accessor Overlay getOverlay(); }
30.533333
52
0.796943
c84cdaddce743fb648a2fa21c79bee7feed66913
637
package JavaClass12; public class Homework12Part2 { public static void main(String[] args) { forwardsHarmonicCalculator(50000); backwardsHarmonicCalculator(50000); } //Note that the sum isn't the same. public static void forwardsHarmonicCalculator(double n) { double sum = 0; for (double i = 1; i <= n; i++) { sum += 1/i; } System.out.println(sum); } public static void backwardsHarmonicCalculator(double n) { double sum = 0; for (double i = n; i >= 1; i--) { sum += 1/i; } System.out.println(sum); } }
25.48
62
0.56044
d4e36a333628f7d6cb635c1fd733ee42353e7e58
2,312
package br.com.bootcamp01templateecommerce.entity; import br.com.bootcamp01templateecommerce.dto.SenhaLimpaDTO; import br.com.bootcamp01templateecommerce.dto.UsuarioDTO; import io.jsonwebtoken.lang.Assert; import org.hibernate.validator.constraints.Length; import org.springframework.util.StringUtils; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.validation.Valid; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.PastOrPresent; import java.time.LocalDateTime; @Entity public class Usuario { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Email @NotBlank private String email; @NotBlank @Length(min = 6) private String senha; @PastOrPresent private LocalDateTime instanteCriacao; public Usuario() { } public Usuario(Long id, @Email @NotBlank String email, @NotBlank @Length(min = 6) String senha, @PastOrPresent LocalDateTime instanteCriacao) { this.id = id; this.email = email; this.senha = senha; this.instanteCriacao = instanteCriacao; } public Usuario(@Email @NotBlank String email, @Valid @NotNull SenhaLimpaDTO senhaLimpa) { Assert.isTrue(StringUtils.hasLength(email), "email não pode ser em branco"); Assert.notNull(senhaLimpa, "o objeto do tipo senha limpa nao pode ser nulo"); this.email = email; this.senha = senhaLimpa.hash(); this.instanteCriacao = LocalDateTime.now(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public LocalDateTime getInstanteCriacao() { return instanteCriacao; } public void setInstanteCriacao(LocalDateTime instanteCriacao) { this.instanteCriacao = instanteCriacao; } }
25.688889
147
0.695069
c14670029ebfaef577d3052aaf45df9606aa5de3
1,512
package com.wfcrc.repository; import android.content.Context; import com.wfcrc.R; import com.wfcrc.pojos.Document; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; /** * Created by maria on 10/26/16. */ public class InternalStorageDocumentRepository implements Repository{ private Context mContext; public InternalStorageDocumentRepository(Context mContext) { this.mContext = mContext; } @Override public List<Document> getAll() throws RepositoryException{ List<Document> documents = new ArrayList<Document>(); try { FileInputStream fileInputStream = mContext.openFileInput("document_gallery.json"); String jsonStr = null; FileChannel fc = fileInputStream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); jsonStr = Charset.defaultCharset().decode(bb).toString(); fileInputStream.close(); documents = JSONDocumentRepository.getAll(jsonStr); } catch (Exception e) { e.printStackTrace(); throw new RepositoryException(e.getMessage(), e.getCause(), mContext.getString(R.string.document_gallery_error)); } return documents; } }
30.857143
125
0.702381
d4b2c55977d99e1ea0c7334294d219b2f24e6078
956
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.Valid; /** * BQRoutingRetrieveInputModelRoutingInstanceReport */ public class BQRoutingRetrieveInputModelRoutingInstanceReport { private String routingInstanceReportReference = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the control record instance report * @return routingInstanceReportReference **/ public String getRoutingInstanceReportReference() { return routingInstanceReportReference; } public void setRoutingInstanceReportReference(String routingInstanceReportReference) { this.routingInstanceReportReference = routingInstanceReportReference; } }
28.969697
187
0.811715
249e317bf2fffb1a86e88f5731037ac11b44fa91
2,748
package net.minecraft.entity.projectile; import net.minecraft.entity.EntityType; import net.minecraft.entity.IRendersAsItem; import net.minecraft.entity.LivingEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraft.network.datasync.DataParameter; import net.minecraft.network.datasync.DataSerializers; import net.minecraft.network.datasync.EntityDataManager; import net.minecraft.util.Util; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @OnlyIn( value = Dist.CLIENT, _interface = IRendersAsItem.class ) public abstract class ProjectileItemEntity extends ThrowableEntity implements IRendersAsItem { private static final DataParameter<ItemStack> DATA_ITEM_STACK = EntityDataManager.defineId(ProjectileItemEntity.class, DataSerializers.ITEM_STACK); public ProjectileItemEntity(EntityType<? extends ProjectileItemEntity> p_i50155_1_, World p_i50155_2_) { super(p_i50155_1_, p_i50155_2_); } public ProjectileItemEntity(EntityType<? extends ProjectileItemEntity> p_i50156_1_, double p_i50156_2_, double p_i50156_4_, double p_i50156_6_, World p_i50156_8_) { super(p_i50156_1_, p_i50156_2_, p_i50156_4_, p_i50156_6_, p_i50156_8_); } public ProjectileItemEntity(EntityType<? extends ProjectileItemEntity> p_i50157_1_, LivingEntity p_i50157_2_, World p_i50157_3_) { super(p_i50157_1_, p_i50157_2_, p_i50157_3_); } public void setItem(ItemStack p_213884_1_) { if (p_213884_1_.getItem() != this.getDefaultItem() || p_213884_1_.hasTag()) { this.getEntityData().set(DATA_ITEM_STACK, Util.make(p_213884_1_.copy(), (p_213883_0_) -> { p_213883_0_.setCount(1); })); } } protected abstract Item getDefaultItem(); protected ItemStack getItemRaw() { return this.getEntityData().get(DATA_ITEM_STACK); } public ItemStack getItem() { ItemStack itemstack = this.getItemRaw(); return itemstack.isEmpty() ? new ItemStack(this.getDefaultItem()) : itemstack; } protected void defineSynchedData() { this.getEntityData().define(DATA_ITEM_STACK, ItemStack.EMPTY); } public void addAdditionalSaveData(CompoundNBT p_213281_1_) { super.addAdditionalSaveData(p_213281_1_); ItemStack itemstack = this.getItemRaw(); if (!itemstack.isEmpty()) { p_213281_1_.put("Item", itemstack.save(new CompoundNBT())); } } public void readAdditionalSaveData(CompoundNBT p_70037_1_) { super.readAdditionalSaveData(p_70037_1_); ItemStack itemstack = ItemStack.of(p_70037_1_.getCompound("Item")); this.setItem(itemstack); } }
37.135135
167
0.755822
fc2aa0582532dc4d0741c475869823df76f6e944
2,881
M 需斟酌。 Permutation的规律: 1.从小的数字开始变化因为都是从小的数字开始recursive遍历。 2.正因为1的规律,所以找大的断点数字要从末尾开始: 确保swap过后的permutation依然是 前缀固定时 当下最小的。 steps: 1.找到最后一个上升点,k 2.从后往前,找到第一个比k大的点,bigIndex 3.swap k&& bigIndex 4.最后反转(k+1,end) ``` /* Given a list of integers, which denote a permutation. Find the next permutation in ascending order. Example For [1,3,2,3], the next permutation is [1,3,3,2] For [4,3,2,1], the next permutation is [1,2,3,4] Note The list may contains duplicate integers. Tags Expand LintCode Copyright Permutation */ /* http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html?_sm_au_=isV7p50vt5RqMQ1Q Thoughts: Not much info are given. Need to ask. It looks like: We are dong permutation on the given numbers, and find out what's next permutation array based on given order. Ascending order: Permutations that permutation(i) < permutation(i + 1) Goal: To find the next smallest permutation. 1. Find the last increasing index (a peek before decresing): k 2. Find the first bigger permutation: Well, it turns out this first bigger index is always on right side of k. Note: we are trying to get the least significant change on the given permuation. Next Step: reverse (k+1, end). This is because: before the change, right side of K will be the largest possible combination. After swapping K, we need the right side to be the smallest combination. (Well, this is my understanding.... Still a bit confused on why we take these steps in this problem) */ public class Solution { //Revers the given part of a int[] public int[] reverse(int start, int end, int[] nums) { for (int i = start, j = end; i < j; i++, j--) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } return nums; } public int[] nextPermutation(int[] nums) { if (nums == null || nums.length == 0) { return nums; } //Find last increasing point before decreasing. nums[k] < nums[k+1] int k = -1; for (int i = nums.length - 2; i >= 0; i--) { if (nums[i] < nums[i + 1]) { k = i; break; } } if (k == -1) { return reverse(0, nums.length - 1, nums); } //Find first bigger point, from right to left int bigIndex = -1; for (int i = nums.length - 1; i >= 0; i--) { if (nums[i] > nums[k]) { bigIndex = i; break; } } //1. Swap bigger index with k; 2. Reverse the right side of k. [Try to make the smallest next permutation] int temp = nums[k]; nums[k] = nums[bigIndex]; nums[bigIndex] = temp; return reverse(k + 1, nums.length - 1, nums); } } ```
28.524752
129
0.593891
313d67eaff2aa7027da6caf31e84dddd5d66b657
2,751
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cognitree.kronos.model; import com.cognitree.kronos.model.Task.Status; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.util.Map; import java.util.Objects; public class TaskUpdate { @JsonSerialize(as = TaskId.class) @JsonDeserialize(as = TaskId.class) private TaskId taskId; private Status status; private String statusMessage; private Map<String, Object> context; public TaskId getTaskId() { return taskId; } public void setTaskId(TaskId taskId) { this.taskId = taskId; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public String getStatusMessage() { return statusMessage; } public void setStatusMessage(String statusMessage) { this.statusMessage = statusMessage; } public Map<String, Object> getContext() { return context; } public void setContext(Map<String, Object> context) { this.context = context; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof TaskUpdate)) return false; TaskUpdate that = (TaskUpdate) o; return Objects.equals(taskId, that.taskId) && status == that.status && Objects.equals(statusMessage, that.statusMessage) && Objects.equals(context, that.context); } @Override public int hashCode() { return Objects.hash(taskId, status, statusMessage, context); } @Override public String toString() { return "TaskUpdate{" + "taskId=" + taskId + ", status=" + status + ", statusMessage='" + statusMessage + '\'' + ", context=" + context + '}'; } }
29.580645
75
0.653944
c79f3d9a6de9d291c8c0b1b912033229ffbf82b9
1,189
package org.xbill.DNS; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import java.io.IOException; import org.junit.jupiter.api.Test; class DLVRecordTest { Name n = Name.fromConstantString("my.name."); @Test void ctor_0arg() { DLVRecord record = new DLVRecord(); assertEquals(0, record.getFootprint()); assertEquals(0, record.getAlgorithm()); assertEquals(0, record.getDigestID()); assertNull(record.getDigest()); } @Test void ctor_7arg() { DLVRecord record = new DLVRecord(n, DClass.IN, 0, 1, 2, 3, "".getBytes()); assertEquals(1, record.getFootprint()); assertEquals(2, record.getAlgorithm()); assertEquals(3, record.getDigestID()); assertEquals(0, record.getDigest().length); } @Test void rdataFromString() throws IOException { Tokenizer t = new Tokenizer("60485 5 1 CAFEBABE"); DLVRecord record = new DLVRecord(); record.rdataFromString(t, null); assertEquals(60485, record.getFootprint()); assertEquals(5, record.getAlgorithm()); assertEquals(1, record.getDigestID()); assertEquals(4, record.getDigest().length); } }
28.309524
78
0.70143
7c7328fd70321331215df14dcbb9ad15e7db0d46
965
/** * https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/prime-number-8/ */ package hackerearth; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class PrimeNumber { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); boolean prime[] = new boolean[N+1]; for(int i=0;i<N;i++) prime[i] = true; for(int p = 2; p*p <=N; p++) { if(prime[p] == true) { for(int i = p*2; i <= N; i += p) prime[i] = false; } } for(int i = 2; i <= N; i++) { if(prime[i] == true) System.out.print(i + " "); } } }
26.805556
137
0.53886
5be09da3dc574e518dd08824a9376ce7c329657c
281
package com.flagship.startup.utils; import org.junit.Test; public class ZipUtilTest { @Test public void unzipFileTest() throws Exception { String srcPath = "D:\\java_projects\\Startup\\mail_attachment\\flagship.zip"; ZipUtil.decompress(srcPath); } }
21.615385
85
0.697509
0f095a3c84fe078dc4b98cde5f641fe4ae21b8d1
698
package display; import java.awt.image.BufferedImage; import data.ImageLoader; public class Assets { public static BufferedImage blocker, pfdMain, roll, heading, altitude, v_speed; public static void init() { blocker = ImageLoader.loadImage("/textures/PFD_Blocker_1024x768.png"); //pfdMain = ImageLoader.loadImage("/textures/PFD_main.png"); pfdMain = ImageLoader.loadImage("/textures/PFD_main_640x980.png"); roll = ImageLoader.loadImage("/textures/PFD_roll.png"); heading = ImageLoader.loadImage("/textures/PFD_Heading_416x416.png"); altitude = ImageLoader.loadImage("/textures/PFD_Alt_100x1000.png"); v_speed = ImageLoader.loadImage("/textures/PFD_VSI_54x18.png"); } }
31.727273
80
0.762178
bd524f3928d9f4cc851af095e1e182f6ed563695
1,451
package chapter6.topic3; /** * @author donald * @date 2021/02/01 * * `LeetCode 1143`. 最长公共子序列 * * * 给定两个字符串 `text1` 和 `text2`,返回这两个字符串的最长公共子序列的长度。 * * 一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。 * * > 例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。两个字符串的「公共子序列」是这两个字符串所共同拥有的子序列。 * > * > 若这两个字符串没有公共子序列,则返回 0。 * * * ``` * 示例 1: * * 输入:text1 = "abcde", text2 = "ace" * 输出:3 * 解释:最长公共子序列是 "ace",它的长度为 3。 * * * 示例 2: * * 输入:text1 = "abc", text2 = "abc" * 输出:3 * 解释:最长公共子序列是 "abc",它的长度为 3。 * * * 示例 3: * * 输入:text1 = "abc", text2 = "def" * 输出:0 * 解释:两个字符串没有公共子序列,返回 0。 * ``` * * 思路: * 1. 二维数组 dp * 2. dp 压缩 */ public class LeetCode_1143 { // Time: O(n ^ 2), Space: O(m * n), Faster: 72.28% public int longestCommonSubsequence(String text1, String text2) { int m = text1.length(), n = text2.length(); // 定义: 对于 s1[0..i-1] 和 s2[0..j-1], 它们的 lcs 长度是 dp[i][j] // base case: dp[0][..] = dp[..][0] = 0 已初始化 int [][] dp = new int[m + 1][n + 1]; for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { // 状态转移逻辑 if (text1.charAt(i - 1) == text2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); } } } return dp[m][n]; } }
19.346667
83
0.468642
a2742af742b18a2e2efd50df736c63989ae50b6e
361
package com.zyy.app.dinner.integration.mob; import com.zyy.app.dinner.integration.mob.model.PagedResult; import com.zyy.app.dinner.integration.mob.model.CookItem; /** * Created by zhouyinyan on 2019/3/29. */ public interface CookService { CookItem queryById(String id); PagedResult<CookItem> queryByCtgId(String CategoryId, int page, int size); }
24.066667
78
0.761773
4d16b6840b8742bab6a747dfa42268210eba6316
1,001
package de.team33.test.fields.v1; import de.team33.libs.fields.v1.Fields; import org.junit.Test; import java.lang.reflect.Field; import java.util.*; import static java.util.stream.Collectors.toMap; import static org.junit.Assert.assertEquals; public class FieldsMappingTest { @Test public void significantFlat() { final Map<String, Field> result = Fields.Mapping.SIGNIFICANT_FLAT.apply(FieldsTest.Sub.class); assertEquals(Arrays.asList("privateFinalInt", "privateInt"), new ArrayList<>(new TreeSet<>(result.keySet()))); } @Test public void significantDeep() { final Map<String, Field> result = Fields.Mapping.SIGNIFICANT_DEEP.apply(FieldsTest.Sub.class); assertEquals(Arrays.asList("..privateFinalInt", "..privateInt", ".privateFinalInt", ".privateInt", "privateFinalInt", "privateInt"), new ArrayList<>(new TreeSet<>(result.keySet()))); } }
30.333333
102
0.651349
52e601bd46cd73d84fb33e04de5ef15f154635a1
390
package com.lkl.factorycompiler; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) public @interface Factory { /** * 工厂的名字 */ Class type(); /** * 用来表示生成哪个对象的唯一id */ String id(); }
18.571429
44
0.702564
d8e3544f346812dbcb712aa6fb9f30b28b7061c3
2,850
/** * GrantState.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.serena.sbm.ws.client; public class GrantState implements java.io.Serializable { private java.lang.String _value_; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected GrantState(java.lang.String value) { _value_ = value; _table_.put(_value_,this); } public static final java.lang.String _INHERITED = "INHERITED"; public static final java.lang.String _REVOKED = "REVOKED"; public static final java.lang.String _GRANTED = "GRANTED"; public static final GrantState INHERITED = new GrantState(_INHERITED); public static final GrantState REVOKED = new GrantState(_REVOKED); public static final GrantState GRANTED = new GrantState(_GRANTED); public java.lang.String getValue() { return _value_;} public static GrantState fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { GrantState enumeration = (GrantState) _table_.get(value); if (enumeration==null) throw new java.lang.IllegalArgumentException(); return enumeration; } public static GrantState fromString(java.lang.String value) throws java.lang.IllegalArgumentException { return fromValue(value); } public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return _value_;} public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);} public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumSerializer( _javaType, _xmlType); } public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumDeserializer( _javaType, _xmlType); } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(GrantState.class); static { typeDesc.setXmlType(new javax.xml.namespace.QName("urn:sbmappservices72", "GrantState")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } }
39.041096
109
0.666667
35cc4cdb6103aa997701a21850bc70db1b55de8d
1,163
package com.freetymekiyan.algorithms.level.hard; /** * 154. Find Minimum in Rotated Sorted Array II * <p> * Follow up for "Find Minimum in Rotated Sorted Array": * What if duplicates are allowed? * Would this affect the run-time complexity? How and why? * <p> * Suppose a sorted array is rotated at some pivot unknown to you beforehand. * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). * <p> * Find the minimum element. * The array may contain duplicates. * <p> * Tags: Array, Binary Search */ class FindMinimumInRotatedSortedArray2 { /** * Binary Search. * Compare nums[mid] with nums[hi]. * When nums[mid] = nums[hi], we are not sure which side contains the min. * So we just shrink the solution space by 1. * Since nums[mid] is still there, this is fine. * The complexity becomes O(n) in worst case. */ public int findMin(int[] nums) { int lo = 0, hi = nums.length - 1; while (lo < hi) { int mid = lo + (hi - lo) / 2; if (nums[mid] > nums[hi]) { lo = mid + 1; } else if (nums[mid] < nums[hi]) { hi = mid; } else { hi--; } } return nums[lo]; } }
27.690476
77
0.605331
9cf087a4156fd160f04e4f9d8b09e6eacd855f98
1,591
package com.project.npa.model.dto; import com.fasterxml.jackson.annotation.JsonFormat; import com.project.npa.model.Departamento; import com.sun.istack.NotNull; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Lob; import java.time.LocalDate; import java.time.chrono.ChronoLocalDateTime; import java.time.format.DateTimeFormatter; @Data @AllArgsConstructor @NoArgsConstructor public class DepartamentoDTO { private Long id; private String nome; private String descricao; // @JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "dd-MM-yyyy") private String date; public DepartamentoDTO(Departamento departamentoCadastro) { this.id = departamentoCadastro.getId(); this.nome = departamentoCadastro.getNome(); this.descricao = departamentoCadastro.getDescricao(); DateTimeFormatter formater = DateTimeFormatter.ofPattern("dd-MM-yyyy"); this.date = departamentoCadastro.getDate().format(formater); } public Departamento toDepartamento() { var departamento = new Departamento(); departamento.setId(this.id); departamento.setNome(this.nome); departamento.setDescricao(this.descricao); DateTimeFormatter formater = DateTimeFormatter.ofPattern("dd-MM-yyyy"); departamento.setDate(LocalDate.parse(this.date,formater )); return departamento; } }
32.469388
79
0.751728
8f9022af16dc9c7977bf5b8ffafef09eaf113b44
1,376
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.Servo; /** * Created by Robovikings on 10/13/2017. */ @TeleOp(name = "Cube lift Claw", group = "Test") @SuppressWarnings("unused") public class CubeLiftClawOpMode extends OpMode { // Servo servo; private DcMotor cubemotor = null; @Override public void init() { // servo = Viki.getRobotPart(hardwareMap, RobotPart.cubeLiftClaw); // servo.setPosition(Servo.MAX_POSITION*0.25); cubemotor = Viki.getRobotPart(hardwareMap, RobotPart.cubeMotor); cubemotor.setDirection(DcMotorSimple.Direction.FORWARD); cubemotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); } // @Override public void loop() { { // if pressing button then open else close if(gamepad2.right_bumper){ // servo.setPosition(Servo.MAX_POSITION * 0.5); // cubemotor.setPower(0.5); } else if(gamepad1.left_bumper){ // servo.setPosition(Servo.MAX_POSITION*0.25); // cubemotor.setPower(-0.5); } } } }
28.666667
73
0.654797
a6c2076d3d0bae846fd3c57ed8a7450ef3a8e09d
724
class Solution { public int[] singleNumber(int[] nums) { // Code here int ans=0; for(int i=0;i<nums.length;i++) ans=ans^nums[i]; int cpy= ans; int id=0; while(cpy!=0){ int t=1<<id; if((cpy & t)!=0)break; id++; } List<Integer> l= new ArrayList<>(); for(int i=0;i<nums.length;i++){ int t=1<<id; if((nums[i] & t)==(ans & t)) l.add(nums[i]); } for(int i=0;i<l.size();i++) ans= ans^l.get(i); int[] arr= new int[2]; arr[0]=Math.min(ans, ans^cpy); arr[1]=Math.max(ans, ans^cpy); return arr; } }
24.965517
43
0.403315
8f0f7649bb696a7281e3cc9da03a9468a011427b
13,998
/** * This class is generated by jOOQ */ package org.jooq.example.gradle.db.information_schema.tables.records; /** * This class is generated by jOOQ. */ @javax.annotation.Generated(value = { "http://www.jooq.org", "3.5.0" }, comments = "This class is generated by jOOQ") @java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class TypeInfoRecord extends org.jooq.impl.TableRecordImpl<org.jooq.example.gradle.db.information_schema.tables.records.TypeInfoRecord> implements org.jooq.Record14<java.lang.String, java.lang.Integer, java.lang.Integer, java.lang.String, java.lang.String, java.lang.String, java.lang.Boolean, java.lang.Short, java.lang.Short, java.lang.Integer, java.lang.Integer, java.lang.Boolean, java.lang.Short, java.lang.Short> { private static final long serialVersionUID = 152194821; /** * Setter for <code>INFORMATION_SCHEMA.TYPE_INFO.TYPE_NAME</code>. */ public void setTypeName(java.lang.String value) { setValue(0, value); } /** * Getter for <code>INFORMATION_SCHEMA.TYPE_INFO.TYPE_NAME</code>. */ public java.lang.String getTypeName() { return (java.lang.String) getValue(0); } /** * Setter for <code>INFORMATION_SCHEMA.TYPE_INFO.DATA_TYPE</code>. */ public void setDataType(java.lang.Integer value) { setValue(1, value); } /** * Getter for <code>INFORMATION_SCHEMA.TYPE_INFO.DATA_TYPE</code>. */ public java.lang.Integer getDataType() { return (java.lang.Integer) getValue(1); } /** * Setter for <code>INFORMATION_SCHEMA.TYPE_INFO.PRECISION</code>. */ public void setPrecision(java.lang.Integer value) { setValue(2, value); } /** * Getter for <code>INFORMATION_SCHEMA.TYPE_INFO.PRECISION</code>. */ public java.lang.Integer getPrecision() { return (java.lang.Integer) getValue(2); } /** * Setter for <code>INFORMATION_SCHEMA.TYPE_INFO.PREFIX</code>. */ public void setPrefix(java.lang.String value) { setValue(3, value); } /** * Getter for <code>INFORMATION_SCHEMA.TYPE_INFO.PREFIX</code>. */ public java.lang.String getPrefix() { return (java.lang.String) getValue(3); } /** * Setter for <code>INFORMATION_SCHEMA.TYPE_INFO.SUFFIX</code>. */ public void setSuffix(java.lang.String value) { setValue(4, value); } /** * Getter for <code>INFORMATION_SCHEMA.TYPE_INFO.SUFFIX</code>. */ public java.lang.String getSuffix() { return (java.lang.String) getValue(4); } /** * Setter for <code>INFORMATION_SCHEMA.TYPE_INFO.PARAMS</code>. */ public void setParams(java.lang.String value) { setValue(5, value); } /** * Getter for <code>INFORMATION_SCHEMA.TYPE_INFO.PARAMS</code>. */ public java.lang.String getParams() { return (java.lang.String) getValue(5); } /** * Setter for <code>INFORMATION_SCHEMA.TYPE_INFO.AUTO_INCREMENT</code>. */ public void setAutoIncrement(java.lang.Boolean value) { setValue(6, value); } /** * Getter for <code>INFORMATION_SCHEMA.TYPE_INFO.AUTO_INCREMENT</code>. */ public java.lang.Boolean getAutoIncrement() { return (java.lang.Boolean) getValue(6); } /** * Setter for <code>INFORMATION_SCHEMA.TYPE_INFO.MINIMUM_SCALE</code>. */ public void setMinimumScale(java.lang.Short value) { setValue(7, value); } /** * Getter for <code>INFORMATION_SCHEMA.TYPE_INFO.MINIMUM_SCALE</code>. */ public java.lang.Short getMinimumScale() { return (java.lang.Short) getValue(7); } /** * Setter for <code>INFORMATION_SCHEMA.TYPE_INFO.MAXIMUM_SCALE</code>. */ public void setMaximumScale(java.lang.Short value) { setValue(8, value); } /** * Getter for <code>INFORMATION_SCHEMA.TYPE_INFO.MAXIMUM_SCALE</code>. */ public java.lang.Short getMaximumScale() { return (java.lang.Short) getValue(8); } /** * Setter for <code>INFORMATION_SCHEMA.TYPE_INFO.RADIX</code>. */ public void setRadix(java.lang.Integer value) { setValue(9, value); } /** * Getter for <code>INFORMATION_SCHEMA.TYPE_INFO.RADIX</code>. */ public java.lang.Integer getRadix() { return (java.lang.Integer) getValue(9); } /** * Setter for <code>INFORMATION_SCHEMA.TYPE_INFO.POS</code>. */ public void setPos(java.lang.Integer value) { setValue(10, value); } /** * Getter for <code>INFORMATION_SCHEMA.TYPE_INFO.POS</code>. */ public java.lang.Integer getPos() { return (java.lang.Integer) getValue(10); } /** * Setter for <code>INFORMATION_SCHEMA.TYPE_INFO.CASE_SENSITIVE</code>. */ public void setCaseSensitive(java.lang.Boolean value) { setValue(11, value); } /** * Getter for <code>INFORMATION_SCHEMA.TYPE_INFO.CASE_SENSITIVE</code>. */ public java.lang.Boolean getCaseSensitive() { return (java.lang.Boolean) getValue(11); } /** * Setter for <code>INFORMATION_SCHEMA.TYPE_INFO.NULLABLE</code>. */ public void setNullable(java.lang.Short value) { setValue(12, value); } /** * Getter for <code>INFORMATION_SCHEMA.TYPE_INFO.NULLABLE</code>. */ public java.lang.Short getNullable() { return (java.lang.Short) getValue(12); } /** * Setter for <code>INFORMATION_SCHEMA.TYPE_INFO.SEARCHABLE</code>. */ public void setSearchable(java.lang.Short value) { setValue(13, value); } /** * Getter for <code>INFORMATION_SCHEMA.TYPE_INFO.SEARCHABLE</code>. */ public java.lang.Short getSearchable() { return (java.lang.Short) getValue(13); } // ------------------------------------------------------------------------- // Record14 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public org.jooq.Row14<java.lang.String, java.lang.Integer, java.lang.Integer, java.lang.String, java.lang.String, java.lang.String, java.lang.Boolean, java.lang.Short, java.lang.Short, java.lang.Integer, java.lang.Integer, java.lang.Boolean, java.lang.Short, java.lang.Short> fieldsRow() { return (org.jooq.Row14) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public org.jooq.Row14<java.lang.String, java.lang.Integer, java.lang.Integer, java.lang.String, java.lang.String, java.lang.String, java.lang.Boolean, java.lang.Short, java.lang.Short, java.lang.Integer, java.lang.Integer, java.lang.Boolean, java.lang.Short, java.lang.Short> valuesRow() { return (org.jooq.Row14) super.valuesRow(); } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.String> field1() { return org.jooq.example.gradle.db.information_schema.tables.TypeInfo.TYPE_INFO.TYPE_NAME; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Integer> field2() { return org.jooq.example.gradle.db.information_schema.tables.TypeInfo.TYPE_INFO.DATA_TYPE; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Integer> field3() { return org.jooq.example.gradle.db.information_schema.tables.TypeInfo.TYPE_INFO.PRECISION; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.String> field4() { return org.jooq.example.gradle.db.information_schema.tables.TypeInfo.TYPE_INFO.PREFIX; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.String> field5() { return org.jooq.example.gradle.db.information_schema.tables.TypeInfo.TYPE_INFO.SUFFIX; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.String> field6() { return org.jooq.example.gradle.db.information_schema.tables.TypeInfo.TYPE_INFO.PARAMS; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Boolean> field7() { return org.jooq.example.gradle.db.information_schema.tables.TypeInfo.TYPE_INFO.AUTO_INCREMENT; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Short> field8() { return org.jooq.example.gradle.db.information_schema.tables.TypeInfo.TYPE_INFO.MINIMUM_SCALE; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Short> field9() { return org.jooq.example.gradle.db.information_schema.tables.TypeInfo.TYPE_INFO.MAXIMUM_SCALE; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Integer> field10() { return org.jooq.example.gradle.db.information_schema.tables.TypeInfo.TYPE_INFO.RADIX; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Integer> field11() { return org.jooq.example.gradle.db.information_schema.tables.TypeInfo.TYPE_INFO.POS; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Boolean> field12() { return org.jooq.example.gradle.db.information_schema.tables.TypeInfo.TYPE_INFO.CASE_SENSITIVE; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Short> field13() { return org.jooq.example.gradle.db.information_schema.tables.TypeInfo.TYPE_INFO.NULLABLE; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Short> field14() { return org.jooq.example.gradle.db.information_schema.tables.TypeInfo.TYPE_INFO.SEARCHABLE; } /** * {@inheritDoc} */ @Override public java.lang.String value1() { return getTypeName(); } /** * {@inheritDoc} */ @Override public java.lang.Integer value2() { return getDataType(); } /** * {@inheritDoc} */ @Override public java.lang.Integer value3() { return getPrecision(); } /** * {@inheritDoc} */ @Override public java.lang.String value4() { return getPrefix(); } /** * {@inheritDoc} */ @Override public java.lang.String value5() { return getSuffix(); } /** * {@inheritDoc} */ @Override public java.lang.String value6() { return getParams(); } /** * {@inheritDoc} */ @Override public java.lang.Boolean value7() { return getAutoIncrement(); } /** * {@inheritDoc} */ @Override public java.lang.Short value8() { return getMinimumScale(); } /** * {@inheritDoc} */ @Override public java.lang.Short value9() { return getMaximumScale(); } /** * {@inheritDoc} */ @Override public java.lang.Integer value10() { return getRadix(); } /** * {@inheritDoc} */ @Override public java.lang.Integer value11() { return getPos(); } /** * {@inheritDoc} */ @Override public java.lang.Boolean value12() { return getCaseSensitive(); } /** * {@inheritDoc} */ @Override public java.lang.Short value13() { return getNullable(); } /** * {@inheritDoc} */ @Override public java.lang.Short value14() { return getSearchable(); } /** * {@inheritDoc} */ @Override public TypeInfoRecord value1(java.lang.String value) { setTypeName(value); return this; } /** * {@inheritDoc} */ @Override public TypeInfoRecord value2(java.lang.Integer value) { setDataType(value); return this; } /** * {@inheritDoc} */ @Override public TypeInfoRecord value3(java.lang.Integer value) { setPrecision(value); return this; } /** * {@inheritDoc} */ @Override public TypeInfoRecord value4(java.lang.String value) { setPrefix(value); return this; } /** * {@inheritDoc} */ @Override public TypeInfoRecord value5(java.lang.String value) { setSuffix(value); return this; } /** * {@inheritDoc} */ @Override public TypeInfoRecord value6(java.lang.String value) { setParams(value); return this; } /** * {@inheritDoc} */ @Override public TypeInfoRecord value7(java.lang.Boolean value) { setAutoIncrement(value); return this; } /** * {@inheritDoc} */ @Override public TypeInfoRecord value8(java.lang.Short value) { setMinimumScale(value); return this; } /** * {@inheritDoc} */ @Override public TypeInfoRecord value9(java.lang.Short value) { setMaximumScale(value); return this; } /** * {@inheritDoc} */ @Override public TypeInfoRecord value10(java.lang.Integer value) { setRadix(value); return this; } /** * {@inheritDoc} */ @Override public TypeInfoRecord value11(java.lang.Integer value) { setPos(value); return this; } /** * {@inheritDoc} */ @Override public TypeInfoRecord value12(java.lang.Boolean value) { setCaseSensitive(value); return this; } /** * {@inheritDoc} */ @Override public TypeInfoRecord value13(java.lang.Short value) { setNullable(value); return this; } /** * {@inheritDoc} */ @Override public TypeInfoRecord value14(java.lang.Short value) { setSearchable(value); return this; } /** * {@inheritDoc} */ @Override public TypeInfoRecord values(java.lang.String value1, java.lang.Integer value2, java.lang.Integer value3, java.lang.String value4, java.lang.String value5, java.lang.String value6, java.lang.Boolean value7, java.lang.Short value8, java.lang.Short value9, java.lang.Integer value10, java.lang.Integer value11, java.lang.Boolean value12, java.lang.Short value13, java.lang.Short value14) { return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached TypeInfoRecord */ public TypeInfoRecord() { super(org.jooq.example.gradle.db.information_schema.tables.TypeInfo.TYPE_INFO); } /** * Create a detached, initialised TypeInfoRecord */ public TypeInfoRecord(java.lang.String typeName, java.lang.Integer dataType, java.lang.Integer precision, java.lang.String prefix, java.lang.String suffix, java.lang.String params, java.lang.Boolean autoIncrement, java.lang.Short minimumScale, java.lang.Short maximumScale, java.lang.Integer radix, java.lang.Integer pos, java.lang.Boolean caseSensitive, java.lang.Short nullable, java.lang.Short searchable) { super(org.jooq.example.gradle.db.information_schema.tables.TypeInfo.TYPE_INFO); setValue(0, typeName); setValue(1, dataType); setValue(2, precision); setValue(3, prefix); setValue(4, suffix); setValue(5, params); setValue(6, autoIncrement); setValue(7, minimumScale); setValue(8, maximumScale); setValue(9, radix); setValue(10, pos); setValue(11, caseSensitive); setValue(12, nullable); setValue(13, searchable); } }
22.4687
427
0.67774
7b6c3e7cbaf40f16c8ae2c4a54daa15cf4927fb8
2,222
package com.peruncs.gwt.uikit; import elemental2.dom.Element; import elemental2.dom.Node; import jsinterop.annotations.JsMethod; import jsinterop.annotations.JsType; /** * UIKit Nav component wrapper. */ @JsType(isNative = true) public abstract class UKNav extends UKComponent { /** * Component creation. * * @param element - the element for this alert component. * @param options - the initialization options for this component. * @return the component */ @JsMethod(namespace = UIKitNamespace) public native static UKNav nav(String element, Options options); @JsMethod(namespace = UIKitNamespace) public native static UKNav nav(Element element, Options options); @JsMethod(namespace = UIKitNamespace) public native static UKNav nav(String element); @JsMethod(namespace = UIKitNamespace) public native static UKNav nav(Element element); /** * Toggles the content pane. */ public native void toggle(int index, boolean animate); public native void toggle(String index, boolean animate); public native void toggle(Node index, boolean animate); public native void toggle(int index); public native void toggle(String index); public native void toggle(Node index); /** * Options for component initialization. */ @JsType public static class Options { /** * The element(s) to toggle. */ public String targets; /** * The toggle element(s). */ public String toggle; /** * The content element(s). */ public String content; /** * Allow all items to be closed. */ public boolean collapsible; /** * Allow multiple open items. */ public boolean multiple; /** * The transition to use. */ public String transition; /** * The space separated names of animations to use. Comma separate for animation out. */ public String animation; /** * Animation duration in milliseconds. */ public int duration = 150; } }
21.784314
92
0.610711
b693d8f2451a2ab70e46ae81e8522f0ab687fb98
2,755
/* SHOGun, https://terrestris.github.io/shogun/ * * Copyright © 2020-present terrestris GmbH & Co. KG * * 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.txt * * 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 de.terrestris.shogun.lib.service; import de.terrestris.shogun.lib.model.File; import de.terrestris.shogun.lib.repository.BaseFileRepository; import org.apache.tika.exception.TikaException; import org.apache.tomcat.util.http.fileupload.InvalidFileNameException; import org.apache.tomcat.util.http.fileupload.impl.InvalidContentTypeException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.List; import java.util.Optional; import java.util.UUID; public interface IBaseFileService<T extends BaseFileRepository<S, Long> & JpaSpecificationExecutor<S>, S extends File> { Optional<S> findOne(UUID fileUuid); S create(MultipartFile uploadFile) throws Exception; /** * Verifies if the content type of the file matches its content. * * @param file * @throws IOException * @throws TikaException */ void verifyContentType(MultipartFile file) throws IOException, TikaException; /** * Checks if the given filename includes illegal characters. * * @param fileName * @throws InvalidFileNameException */ void isValidFileName(String fileName) throws InvalidFileNameException; /** * Checks if the given contentType is included in the content type whitelist configured via UploadProperties. * * @param contentType * @throws InvalidContentTypeException */ void isValidType(String contentType) throws InvalidContentTypeException; /** * Checks if the file is not null or empty and has a valid content type. * * @param file * @throws Exception */ void isValid(MultipartFile file) throws Exception; /** * Get the list of supported content types. Should be implement by real class. * * @return * @throws NoSuchBeanDefinitionException */ List<String> getSupportedContentTypes() throws NoSuchBeanDefinitionException; }
34.4375
120
0.740472
214b111b26409c03450f90b8de65e1770a78b01c
626
package jdisite.pages; /** * Created by Roman Iovlev on 10.11.2018 * Email: roman.iovlev.jdi@gmail.com; Skype: roman.iovlev */ import com.epam.jdi.light.elements.complex.Menu; import com.epam.jdi.light.elements.composite.Form; import com.epam.jdi.light.elements.pageobjects.annotations.locators.UI; import jdisite.entities.User; public class JDISite { public static HomePage homePage; public static ContactPage contactPage; public static Html5Page htmlPage; public static MarvelousPage marvelousPage; public static Form<User> loginForm; @UI(".sidebar-menu span") public static Menu leftMenu; }
27.217391
71
0.761981
100a844c67ba8d903e378579a22ac09d5d338cce
2,568
package seedu.us.among.logic.commands; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.us.among.logic.commands.CommandResult.exitCommandResult; import static seedu.us.among.logic.commands.CommandResult.helpCommandResult; import static seedu.us.among.logic.commands.CommandResult.listCommandResult; import org.junit.jupiter.api.Test; public class CommandResultTest { @Test public void equals() { CommandResult commandResult = new CommandResult("feedback"); // same values -> returns true assertTrue(commandResult.equals(new CommandResult("feedback"))); assertTrue(commandResult.equals(new CommandResult("feedback"))); // same object -> returns true assertTrue(commandResult.equals(commandResult)); // null -> returns false assertFalse(commandResult.equals(null)); // different types -> returns false assertFalse(commandResult.equals(0.5f)); // different feedbackToUser value -> returns false assertFalse(commandResult.equals(new CommandResult("different"))); // different showHelp value -> returns false assertFalse(commandResult.equals(helpCommandResult("feedback"))); // different exit value -> returns false assertFalse(commandResult.equals(exitCommandResult("feedback"))); // different islist value -> returns false assertFalse(commandResult.equals(listCommandResult("feedback"))); } @Test public void hashcode() { CommandResult commandResult = new CommandResult("feedback"); // same values -> returns same hashcode assertEquals(commandResult.hashCode(), new CommandResult("feedback").hashCode()); // different feedbackToUser value -> returns different hashcode assertNotEquals(commandResult.hashCode(), new CommandResult("different").hashCode()); // different showHelp value -> returns different hashcode assertNotEquals(commandResult.hashCode(), helpCommandResult("feedback").hashCode()); // different exit value -> returns different hashcode assertNotEquals(commandResult.hashCode(), exitCommandResult("feedback").hashCode()); // different isList value -> returns different hashcode assertNotEquals(commandResult.hashCode(), listCommandResult("feedback").hashCode()); } }
39.507692
93
0.719626
8e5f6a0250b68565e16d9155959b0270f355ad2c
13,152
package com.squareup.square.models; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.Objects; /** * This is a model class for LoyaltyAccount type. */ public class LoyaltyAccount { @JsonInclude(JsonInclude.Include.NON_NULL) private final String id; private final String programId; @JsonInclude(JsonInclude.Include.NON_NULL) private final Integer balance; @JsonInclude(JsonInclude.Include.NON_NULL) private final Integer lifetimePoints; @JsonInclude(JsonInclude.Include.NON_NULL) private final String customerId; @JsonInclude(JsonInclude.Include.NON_NULL) private final String enrolledAt; @JsonInclude(JsonInclude.Include.NON_NULL) private final String createdAt; @JsonInclude(JsonInclude.Include.NON_NULL) private final String updatedAt; @JsonInclude(JsonInclude.Include.NON_NULL) private final LoyaltyAccountMapping mapping; @JsonInclude(JsonInclude.Include.NON_NULL) private final List<LoyaltyAccountExpiringPointDeadline> expiringPointDeadlines; /** * Initialization constructor. * @param programId String value for programId. * @param id String value for id. * @param balance Integer value for balance. * @param lifetimePoints Integer value for lifetimePoints. * @param customerId String value for customerId. * @param enrolledAt String value for enrolledAt. * @param createdAt String value for createdAt. * @param updatedAt String value for updatedAt. * @param mapping LoyaltyAccountMapping value for mapping. * @param expiringPointDeadlines List of LoyaltyAccountExpiringPointDeadline value for * expiringPointDeadlines. */ @JsonCreator public LoyaltyAccount( @JsonProperty("program_id") String programId, @JsonProperty("id") String id, @JsonProperty("balance") Integer balance, @JsonProperty("lifetime_points") Integer lifetimePoints, @JsonProperty("customer_id") String customerId, @JsonProperty("enrolled_at") String enrolledAt, @JsonProperty("created_at") String createdAt, @JsonProperty("updated_at") String updatedAt, @JsonProperty("mapping") LoyaltyAccountMapping mapping, @JsonProperty("expiring_point_deadlines") List<LoyaltyAccountExpiringPointDeadline> expiringPointDeadlines) { this.id = id; this.programId = programId; this.balance = balance; this.lifetimePoints = lifetimePoints; this.customerId = customerId; this.enrolledAt = enrolledAt; this.createdAt = createdAt; this.updatedAt = updatedAt; this.mapping = mapping; this.expiringPointDeadlines = expiringPointDeadlines; } /** * Getter for Id. * The Square-assigned ID of the loyalty account. * @return Returns the String */ @JsonGetter("id") public String getId() { return id; } /** * Getter for ProgramId. * The Square-assigned ID of the [loyalty program]($m/LoyaltyProgram) to which the account * belongs. * @return Returns the String */ @JsonGetter("program_id") public String getProgramId() { return programId; } /** * Getter for Balance. * The available point balance in the loyalty account. If points are scheduled to expire, they * are listed in the `expiring_point_deadlines` field. Your application should be able to handle * loyalty accounts that have a negative point balance (`balance` is less than 0). This might * occur if a seller makes a manual adjustment or as a result of a refund or exchange. * @return Returns the Integer */ @JsonGetter("balance") public Integer getBalance() { return balance; } /** * Getter for LifetimePoints. * The total points accrued during the lifetime of the account. * @return Returns the Integer */ @JsonGetter("lifetime_points") public Integer getLifetimePoints() { return lifetimePoints; } /** * Getter for CustomerId. * The Square-assigned ID of the [customer]($m/Customer) that is associated with the account. * @return Returns the String */ @JsonGetter("customer_id") public String getCustomerId() { return customerId; } /** * Getter for EnrolledAt. * The timestamp when enrollment occurred, in RFC 3339 format. * @return Returns the String */ @JsonGetter("enrolled_at") public String getEnrolledAt() { return enrolledAt; } /** * Getter for CreatedAt. * The timestamp when the loyalty account was created, in RFC 3339 format. * @return Returns the String */ @JsonGetter("created_at") public String getCreatedAt() { return createdAt; } /** * Getter for UpdatedAt. * The timestamp when the loyalty account was last updated, in RFC 3339 format. * @return Returns the String */ @JsonGetter("updated_at") public String getUpdatedAt() { return updatedAt; } /** * Getter for Mapping. * Represents the mapping that associates a loyalty account with a buyer. Currently, a loyalty * account can only be mapped to a buyer by phone number. For more information, see [Loyalty * Overview](https://developer.squareup.com/docs/loyalty/overview). * @return Returns the LoyaltyAccountMapping */ @JsonGetter("mapping") public LoyaltyAccountMapping getMapping() { return mapping; } /** * Getter for ExpiringPointDeadlines. * The schedule for when points expire in the loyalty account balance. This field is present * only if the account has points that are scheduled to expire. The total number of points in * this field equals the number of points in the `balance` field. * @return Returns the List of LoyaltyAccountExpiringPointDeadline */ @JsonGetter("expiring_point_deadlines") public List<LoyaltyAccountExpiringPointDeadline> getExpiringPointDeadlines() { return expiringPointDeadlines; } @Override public int hashCode() { return Objects.hash(id, programId, balance, lifetimePoints, customerId, enrolledAt, createdAt, updatedAt, mapping, expiringPointDeadlines); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof LoyaltyAccount)) { return false; } LoyaltyAccount other = (LoyaltyAccount) obj; return Objects.equals(id, other.id) && Objects.equals(programId, other.programId) && Objects.equals(balance, other.balance) && Objects.equals(lifetimePoints, other.lifetimePoints) && Objects.equals(customerId, other.customerId) && Objects.equals(enrolledAt, other.enrolledAt) && Objects.equals(createdAt, other.createdAt) && Objects.equals(updatedAt, other.updatedAt) && Objects.equals(mapping, other.mapping) && Objects.equals(expiringPointDeadlines, other.expiringPointDeadlines); } /** * Converts this LoyaltyAccount into string format. * @return String representation of this class */ @Override public String toString() { return "LoyaltyAccount [" + "programId=" + programId + ", id=" + id + ", balance=" + balance + ", lifetimePoints=" + lifetimePoints + ", customerId=" + customerId + ", enrolledAt=" + enrolledAt + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt + ", mapping=" + mapping + ", expiringPointDeadlines=" + expiringPointDeadlines + "]"; } /** * Builds a new {@link LoyaltyAccount.Builder} object. * Creates the instance with the state of the current model. * @return a new {@link LoyaltyAccount.Builder} object */ public Builder toBuilder() { Builder builder = new Builder(programId) .id(getId()) .balance(getBalance()) .lifetimePoints(getLifetimePoints()) .customerId(getCustomerId()) .enrolledAt(getEnrolledAt()) .createdAt(getCreatedAt()) .updatedAt(getUpdatedAt()) .mapping(getMapping()) .expiringPointDeadlines(getExpiringPointDeadlines()); return builder; } /** * Class to build instances of {@link LoyaltyAccount}. */ public static class Builder { private String programId; private String id; private Integer balance; private Integer lifetimePoints; private String customerId; private String enrolledAt; private String createdAt; private String updatedAt; private LoyaltyAccountMapping mapping; private List<LoyaltyAccountExpiringPointDeadline> expiringPointDeadlines; /** * Initialization constructor. * @param programId String value for programId. */ public Builder(String programId) { this.programId = programId; } /** * Setter for programId. * @param programId String value for programId. * @return Builder */ public Builder programId(String programId) { this.programId = programId; return this; } /** * Setter for id. * @param id String value for id. * @return Builder */ public Builder id(String id) { this.id = id; return this; } /** * Setter for balance. * @param balance Integer value for balance. * @return Builder */ public Builder balance(Integer balance) { this.balance = balance; return this; } /** * Setter for lifetimePoints. * @param lifetimePoints Integer value for lifetimePoints. * @return Builder */ public Builder lifetimePoints(Integer lifetimePoints) { this.lifetimePoints = lifetimePoints; return this; } /** * Setter for customerId. * @param customerId String value for customerId. * @return Builder */ public Builder customerId(String customerId) { this.customerId = customerId; return this; } /** * Setter for enrolledAt. * @param enrolledAt String value for enrolledAt. * @return Builder */ public Builder enrolledAt(String enrolledAt) { this.enrolledAt = enrolledAt; return this; } /** * Setter for createdAt. * @param createdAt String value for createdAt. * @return Builder */ public Builder createdAt(String createdAt) { this.createdAt = createdAt; return this; } /** * Setter for updatedAt. * @param updatedAt String value for updatedAt. * @return Builder */ public Builder updatedAt(String updatedAt) { this.updatedAt = updatedAt; return this; } /** * Setter for mapping. * @param mapping LoyaltyAccountMapping value for mapping. * @return Builder */ public Builder mapping(LoyaltyAccountMapping mapping) { this.mapping = mapping; return this; } /** * Setter for expiringPointDeadlines. * @param expiringPointDeadlines List of LoyaltyAccountExpiringPointDeadline value for * expiringPointDeadlines. * @return Builder */ public Builder expiringPointDeadlines( List<LoyaltyAccountExpiringPointDeadline> expiringPointDeadlines) { this.expiringPointDeadlines = expiringPointDeadlines; return this; } /** * Builds a new {@link LoyaltyAccount} object using the set fields. * @return {@link LoyaltyAccount} */ public LoyaltyAccount build() { return new LoyaltyAccount(programId, id, balance, lifetimePoints, customerId, enrolledAt, createdAt, updatedAt, mapping, expiringPointDeadlines); } } }
35.072
122
0.605383
ff6c6b86938d615cd061167d1f8ad0e4c8a480e1
23,710
package com.skenvy.fluent.xpath; import com.skenvy.fluent.xpath.contextualisers.XPathAttributeContextualisers; import com.skenvy.fluent.xpath.contextualisers.XPathAxisContextualisers; import com.skenvy.fluent.xpath.contextualisers.XPathNodeContextualisers; import com.skenvy.fluent.xpath.predicates.BuildablePredicate; /*** * The contextless builder. Subclassed by the "context aware" builder facades. * There is not any public way to initialise the builder's context classes * without the help of the XPathInitialiser class. */ public abstract class XPathBuilder { /*************************************************************************/ /* The inner class definition and instance */ /*************************************************************************/ /* * Although this inner class only contains a StringBuilder, it serves to * make it possible later to make the process more generic, of having an * "inner" class instance that contains the fields which the "outer" * builder class exposes to the context classes */ /*** * The "inner" class, which contains the fields which are to be exposed to * the context classes via the "outer" builder class. As this is a fluency * pattern, wrapped in the context-facade pattern, the only field of the * inner class is a StringBuilder. */ private final class XPathBuilderInner{ /*** * The StringBuilder for building the string output fluently */ /*Package Private*/ final StringBuilder stringBuilder; /*** * Parameterless constructor to make a new empty StringBuilder */ /*Package Private*/ XPathBuilderInner(){ this.stringBuilder = new StringBuilder(); } /*** * Parameterised constructor to initialise the StringBuilder with an * already existing String. * @param s */ /*Package Private*/ XPathBuilderInner(CharSequence chars) { this.stringBuilder = new StringBuilder(chars); } } /*** * The instance of the inner class. */ /*Package Private*/ final XPathBuilderInner xPathBuilderInner; /*************************************************************************/ /* The super class, and context subclasses, reference variables */ /*************************************************************************/ /*** * Self referential variable, when a context class is created it can invoke * "this" itself as an instance of this superclass to swap context. */ /*Package Private*/ final XPathBuilder xPathBuilder; /*** * Context class instance: The "axis" context */ private XPathAxisContext axisContext; /*** * Context class instance: The "node" context */ private XPathNodeContext nodeContext; /*** * Context class instance: The "predicate" context */ private XPathPredicateContext predicateContext; /*** * Context class instance: The "attribute" context */ private XPathAttributeContext attributeContext; /*************************************************************************/ /* Constructors [mirror all of the inner class', and self referential] */ /*************************************************************************/ /*** * Construct a new instance with a new inner class and self reference. */ /*Package Private*/ XPathBuilder() { this.xPathBuilderInner = new XPathBuilderInner(); this.xPathBuilder = this; } /*** * Construct a new instance with a parameterised * inner class and self reference. */ /*Package Private*/ XPathBuilder(CharSequence chars) { this.xPathBuilderInner = new XPathBuilderInner(chars); this.xPathBuilder = this; } /*** * Construct a new instance which points to the same inner class instance * and uses the same outer class instance to swap between contexts. */ /*Package Private*/ XPathBuilder(XPathBuilder xPathBuilder){ this.xPathBuilderInner = xPathBuilder.xPathBuilderInner; this.xPathBuilder = xPathBuilder; } /*************************************************************************/ /* Context Getters */ /*************************************************************************/ /*** * Context class getters: The "axis" context class * @return XPathAxisContext */ private final XPathAxisContext getAxisContext() { if(this.axisContext == null) { this.axisContext = new XPathAxisContext(this); } return this.axisContext; } /*** * Context class getters: The "node" context class * @return XPathNodeContext */ private final XPathNodeContext getNodeContext() { if(this.nodeContext == null) { this.nodeContext = new XPathNodeContext(this); } return this.nodeContext; } /*** * Context class getters: The "predicate" context class * @return XPathPredicateContext */ private final XPathPredicateContext getPredicateContext() { if(this.predicateContext == null) { this.predicateContext = new XPathPredicateContext(this); } return this.predicateContext; } /*** * Context class getters: The "attribute" context class * @return XPathAttributeContext */ private final XPathAttributeContext getAttributeContext() { if(this.attributeContext == null) { this.attributeContext = new XPathAttributeContext(this); } return this.attributeContext; } /*************************************************************************/ /* Context Swappers */ /*************************************************************************/ /*** * Context class swappers: The "axis" context class * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext swapToAxisContext() { return this.xPathBuilder.getAxisContext(); } /*** * Context class swappers: The "node" context class * @return XPathNodeContext */ /*Package Private*/ final XPathNodeContext swapToNodeContext() { return this.xPathBuilder.getNodeContext(); } /*** * Context class swappers: The "predicate" context class * @return XPathPredicateContext */ /*Package Private*/ final XPathPredicateContext swapToPredicateContext() { return this.xPathBuilder.getPredicateContext(); } /*** * Context class swappers: The "attribute" context class * @return XPathPredicateContext */ /*Package Private*/ final XPathAttributeContext swapToAttributeContext() { return this.xPathBuilder.getAttributeContext(); } /*************************************************************************/ /* Outer class wrapper functionality to interact with the inner class */ /*************************************************************************/ /*** * Interactions with the shared inner class: build the StringBuilder * @return String */ /*Package Private*/ final String buildTheStringBuilder() { return this.xPathBuilderInner.stringBuilder.toString(); } /*** * Interactions with the shared inner class: Append to the StringBuilder */ /*Package Private*/ final XPathBuilder appendStringBuilder(CharSequence chars) { this.xPathBuilderInner.stringBuilder.append(chars); return this; } /*** * Interactions with the shared inner class: Prepend to the StringBuilder */ /*Package Private*/ final XPathBuilder prependStringBuilder(CharSequence chars){ this.xPathBuilderInner.stringBuilder.insert(0, chars); return this; } /*** * Interactions with the shared inner class: Wrap to the StringBuilder */ /*Package Private*/ final XPathBuilder wrapTheStringBuilder(CharSequence append, CharSequence prepend) { prependStringBuilder(prepend); appendStringBuilder(append); return this; } /* * Following is the deduplication of function implementations for functions * defined in the "buildable/not-buildable" and subclass contexts. So that * there can be a 1-1 correspondence between these superclass, "package * private", finalised methods, and the requirement to override functions * of the same function signature, we will bastardise the java naming * conventions, by simply prefacing these superclass defined functions' * names with underscores. Thus we have deduplicated the function * signatures of method bodies defined for the purpose of deduplication! * * Deduplinception! */ /*************************************************************************/ /* Buildability Contextualiser's function deduplication : Buildable */ /*************************************************************************/ /*** * Deduplication of the functionality of the interface method {@code * (new <? implements BuildableContext>).buildToString(); * } * @return String */ /*Package Private*/ final String _buildToString() { return this.buildTheStringBuilder(); } /*************************************************************************/ /* Buildability Contextualiser's function deduplication : Not Buildable */ /*************************************************************************/ /*** * Deduplication of the functionality of the interface method {@code * (new <? implements NotBuildableContext>).whyIsntThisABuildableContext(); * } * @return String */ /*Package Private*/ final void _whyIsntThisABuildableContext(){ System.out.println("Only the node, predicate, and attribute context" + " are buildable contexts. Can't build a" + " terminal axis"); } /*************************************************************************/ /* Buildability Contextualiser's function deduplication : Node Set */ /*************************************************************************/ /*** * Deduplication of the functionality of the interface method {@code * (new <? implements NodeSetContext>).buildTheNodeSetToString(); * } * @return String */ /*Package Private*/ final String _buildTheNodeSetToString() { return _buildToString(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements NodeSetContext>). * wrapAMultiNodeSetContextIntoASingleNodeSetContext(); * } * @return String */ /*Package Private*/ final XPathNodeContext _wrapAMultiNodeSetContextIntoASingleNodeSetContext() { return wrapTheStringBuilder("(", ")").swapToNodeContext(); } /*************************************************************************/ /* Subclass Contextualiser's function deduplication : Axis Context */ /*************************************************************************/ /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withAncestor(); * } * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withAncestor() { appendStringBuilder(XPathAxisContextualisers.ancestor); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withAncestor(); * } for the special case of the current context initialiser * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withAncestor_CurrentContext() { appendStringBuilder(XPathAxisContextualisers.currentContextAncestor); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withAncestorOrSelf(); * } * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withAncestorOrSelf() { appendStringBuilder(XPathAxisContextualisers.ancestorOrSelf); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withAncestorOrSelf(); * } for the special case of the current context initialiser * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withAncestorOrSelf_CurrentContext() { appendStringBuilder(XPathAxisContextualisers. currentContextAncestorOrSelf); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withChild(); * } * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withChild() { appendStringBuilder(XPathAxisContextualisers.child); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withChild(); * } for the special case of the current context initialiser * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withChild_CurrentContext() { appendStringBuilder(XPathAxisContextualisers.currentContextChild); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withDescendant(); * } * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withDescendant() { appendStringBuilder(XPathAxisContextualisers.descendant); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withDescendant(); * } for the special case of the current context initialiser * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withDescendant_CurrentContext() { appendStringBuilder(XPathAxisContextualisers.currentContextDescendant); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withDescendantOrSelf(); * } * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withDescendantOrSelf() { appendStringBuilder(XPathAxisContextualisers.descendantOrSelf); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withDescendantOrSelf(); * } for the special case of the current context initialiser * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withDescendantOrSelf_CurrentContext() { appendStringBuilder(XPathAxisContextualisers. currentContextDescendantOrSelf); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withFollowing(); * } * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withFollowing() { appendStringBuilder(XPathAxisContextualisers.following); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withFollowing(); * } for the special case of the current context initialiser * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withFollowing_CurrentContext(){ appendStringBuilder(XPathAxisContextualisers.currentContextFollowing); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withFollowingSibling(); * } * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withFollowingSibling() { appendStringBuilder(XPathAxisContextualisers.followingSibling); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withFollowingSibling(); * } for the special case of the current context initialiser * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withFollowingSibling_CurrentContext() { appendStringBuilder(XPathAxisContextualisers. currentContextFollowingSibling); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withNamespace(); * } * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withNamespace() { appendStringBuilder(XPathAxisContextualisers.namespace); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withNamespace(); * } for the special case of the current context initialiser * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withNamespace_CurrentContext(){ appendStringBuilder(XPathAxisContextualisers.currentContextNamespace); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withPreceding(); * } * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withPreceding() { appendStringBuilder(XPathAxisContextualisers.preceding); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withPreceding(); * } for the special case of the current context initialiser * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withPreceding_CurrentContext(){ appendStringBuilder(XPathAxisContextualisers.currentContextPreceding); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withPrecedingSibling(); * } * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withPrecedingSibling() { appendStringBuilder(XPathAxisContextualisers.precedingSibling); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withPrecedingSibling(); * } for the special case of the current context initialiser * @return XPathAxisContext */ /*Package Private*/ final XPathAxisContext _withPrecedingSibling_CurrentContext() { appendStringBuilder(XPathAxisContextualisers. currentContextPrecedingSibling); return swapToAxisContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withParent(); * } * @return XPathNodeContext */ /*Package Private*/ final XPathNodeContext _withParent() { appendStringBuilder(XPathAxisContextualisers.parent); return swapToNodeContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withParent(); * } for the special case of the current context initialiser * @return XPathNodeContext */ /*Package Private*/ final XPathNodeContext _withParent_CurrentContext() { appendStringBuilder(XPathAxisContextualisers.currentContextParent); return swapToNodeContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withSelf(); * } * @return XPathNodeContext */ /*Package Private*/ final XPathNodeContext _withSelf() { appendStringBuilder(XPathAxisContextualisers.self); return swapToNodeContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAxisContextualisers>).withSelf(); * } for the special case of the current context initialiser * @return XPathNodeContext */ /*Package Private*/ final XPathNodeContext _withSelf_CurrentContext() { appendStringBuilder(XPathAxisContextualisers.currentContextSelf); return swapToNodeContext(); } /*************************************************************************/ /* Subclass Contextualiser's function deduplication : Node Context */ /*************************************************************************/ /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathNodeContextualisers>).nodeOfAnyType(); * } * @return XPathNodeContext */ /*Package Private*/ final XPathNodeContext _nodeOfAnyType() { appendStringBuilder(XPathNodeContextualisers.nodeWildcard); return swapToNodeContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathNodeContextualisers>).nodeOfType(String * nodeType);} * @param nodeType * @return XPathNodeContext */ /*Package Private*/ final XPathNodeContext _nodeOfType(String nodeType) { appendStringBuilder(nodeType); return swapToNodeContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathNodeContextualisers>).nodeLineage(String... * nodeTypes);} * @param nodeTypes * @return XPathNodeContext */ /*Package Private*/ final XPathNodeContext _nodeLineage(String... nodeTypes) { for(int k = 0; k < nodeTypes.length; k++) { if(k == (nodeTypes.length - 1)) { return this._nodeOfType(nodeTypes[k]); } else { this._nodeOfType(nodeTypes[k]).withChild(); } } return swapToNodeContext(); } /*************************************************************************/ /* Subclass Contextualiser's function deduplication : Predicate Context */ /*************************************************************************/ /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathPredicateContextualisers>).withCustomPredicate( * PredicateBuilder predicate);} * @param predicate * @return XPathPredicateContext */ /*Package Private*/ final XPathPredicateContext _withCustomPredicate( BuildablePredicate predicate) { return appendStringBuilder("["). appendStringBuilder(predicate.buildToString()). appendStringBuilder("]").swapToPredicateContext(); } /*************************************************************************/ /* Subclass Contextualiser's function deduplication : Attribute Context */ /*************************************************************************/ /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAttributeContextualisers>).withAttribute(String * attributeName);} * @param attributeName * @return XPathAttributeContext */ /*Package Private*/ final XPathAttributeContext _withAttribute(String attributeName) { appendStringBuilder(XPathAxisContextualisers.attribute); appendStringBuilder(attributeName); return swapToAttributeContext(); } /*** * Deduplication of the functionality of the interface method {@code * (new <? implements XPathAttributeContextualisers>).withAttribute(String * attributeName);} for the special case of the current context initialiser * @param attributeName * @return XPathAttributeContext */ /*Package Private*/ final XPathAttributeContext _withAttribute_CurrentContext(String attributeName) { appendStringBuilder(XPathAttributeContextualisers .currentContextAttribute); appendStringBuilder(attributeName); return swapToAttributeContext(); } }
34.462209
81
0.659848
8a3c7b4c1f6e68e6274344833a214844899c79fa
2,451
/** * 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.security.token.delegation; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import java.util.Map; import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier; import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenSecretManager; import org.apache.hadoop.hdfs.server.namenode.FSNamesystem; import org.apache.hadoop.io.Text; import org.apache.hadoop.security.token.delegation.AbstractDelegationTokenSecretManager.DelegationTokenInformation; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; public class TestTokenExtractor { private FSNamesystem fsn; private DelegationTokenSecretManager dtsm; @Before public void setUp() { fsn = Mockito.mock(FSNamesystem.class); dtsm = new DelegationTokenSecretManager(0L, 0L, 0L, 0L, fsn); } @Test public void testSimple() { Mockito.doNothing().when(fsn).writeLock(); Mockito.doNothing().when(fsn).writeUnlock(); DelegationTokenIdentifier dtId = new DelegationTokenIdentifier( new Text("mockOwner"), new Text("mockGroup"), new Text("mockRealUser/HOST@REALM.COM")); DelegationTokenInformation dtInfo = Mockito.mock(DelegationTokenInformation.class); dtsm.currentTokens.put(dtId, dtInfo); TokenExtractor extractor = new TokenExtractor(dtsm, fsn); Map<String, Long> tokenLastLogins = extractor.getTokenLastLogins(); assertThat(tokenLastLogins.size(), is(2)); assertThat(tokenLastLogins.containsKey("mockRealUser"), is(true)); assertThat(tokenLastLogins.containsKey("mockOwner"), is(true)); } }
37.707692
115
0.763362
94228edd25eb822bb479685d17977dfe7207ae4a
5,546
package com.alsritter.gateway.config; import cn.hutool.core.util.ArrayUtil; import com.alsritter.common.AppConstant; import com.alsritter.gateway.component.CustomNimbusReactiveOpaqueTokenIntrospector; import com.alsritter.gateway.component.CustomServerWebExchangeMatcher; import com.alsritter.gateway.component.RestAuthenticationEntryPoint; import com.alsritter.gateway.component.RestfulAccessDeniedHandler; import com.alsritter.gateway.filter.IgnoreUrlsRemoveJwtFilter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; import org.springframework.security.config.web.server.SecurityWebFiltersOrder; import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.web.server.SecurityWebFilterChain; import org.springframework.security.web.server.util.matcher.NegatedServerWebExchangeMatcher; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.CorsWebFilter; import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.util.pattern.PathPatternParser; /** * @author alsritter * @version 1.0 **/ @Slf4j @Configuration @RequiredArgsConstructor @EnableWebFluxSecurity public class OAuth2ResourceServerConfig { private final AuthorizationManager authorizationManager; private final RestfulAccessDeniedHandler restfulAccessDeniedHandler; private final RestAuthenticationEntryPoint restAuthenticationEntryPoint; private final IgnoreUrlsRemoveJwtFilter ignoreUrlsRemoveJwtFilter; private final SecureProperties.TokenConfig tokenConfig; private final WebClient.Builder webClient; private final CustomServerWebExchangeMatcher customServerWebExchangeMatcher; @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { http.addFilterAt(corsFilter(), SecurityWebFiltersOrder.CORS); String url = "http://" + AppConstant.APPLICATION_OAUTH2_NAME; String checkTokenEndpointUrl = url + tokenConfig.getCheckTokenEndpointUrl(); log.debug("token 检查地址为 {}", checkTokenEndpointUrl); http.oauth2ResourceServer() .opaqueToken() .introspectionClientCredentials(tokenConfig.getClientId(), tokenConfig.getClientSecret()) .introspectionUri(tokenConfig.getCheckTokenEndpointUrl()) // 要自己写一个不透明 Token 转换器 .introspector(new CustomNimbusReactiveOpaqueTokenIntrospector( checkTokenEndpointUrl, webClient)); //自定义处理请求头过期或签名错误的结果 http.oauth2ResourceServer() .authenticationEntryPoint(restAuthenticationEntryPoint); // 这里是忽略哪些链接,使之不走过滤链 // 参考 https://stackoverflow.com/questions/52740163/web-ignoring-using-spring-webflux // 总之白名单应该使用这个,否则下面这种 .pathMatchers(ArrayUtil.toArray(ignoreUrlsConfig.getUrls(), String.class)).permitAll() // 如果加上了 Authorization 还是会走认证过滤 // 具体两个的区别参考:http.permitAll()与web.ignoring()的区别? // https://www.cnblogs.com/panchanggui/p/14975963.html // http.securityMatcher(new NegatedServerWebExchangeMatcher( // ServerWebExchangeMatchers.pathMatchers(ArrayUtil.toArray(ignoreUrlsConfig.getUrls(), String.class)))); http.securityMatcher(new NegatedServerWebExchangeMatcher(customServerWebExchangeMatcher)); //对白名单路径,直接移除JWT请求头 http.addFilterBefore(ignoreUrlsRemoveJwtFilter, SecurityWebFiltersOrder.AUTHENTICATION); http.authorizeExchange() // .pathMatchers(ArrayUtil.toArray(ignoreUrlsConfig.getUrls(), String.class)).permitAll() .anyExchange().access(authorizationManager)//鉴权管理器配置 .and() .exceptionHandling() .accessDeniedHandler(restfulAccessDeniedHandler) //处理未授权 .authenticationEntryPoint(restAuthenticationEntryPoint)//处理未认证 .and().csrf().disable(); return http.build(); } // @Value("${server.port}") // private int port; // public String getUrl() { // String address = null; // try { // InetAddress host = InetAddress.getLocalHost(); // address = host.getHostAddress(); // } catch (UnknownHostException e) { // address = "127.0.0.1"; // } // return "http://" + address + ":" + this.port; // } @Bean public CorsWebFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.setAllowCredentials(true); // 允许 cookies 跨域 // config.setAllowedOrigins(Arrays.asList(origin)); config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了 config.addAllowedMethod("OPTIONS");// 允许提交请求的方法,* 表示全部允许 config.addAllowedMethod("GET");// 允许 Get 的请求方法 config.addAllowedMethod("POST"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); source.registerCorsConfiguration("/**", config); return new CorsWebFilter(source); } }
47
121
0.734403
b0d4a31357c95fb80f7574010c0aaab91f932b9e
463
package com.github.lykmapipo.common.data; import android.os.Bundle; import androidx.annotation.NonNull; /** * A contract to be implemented by object that will be presented {@link android.os.Bundle}. * * @author lally elias <lallyelias87@gmail.com> * @version 0.1.0 * @since 0.1.0 */ public interface Bundleable { /** * Wrap value into {@link Bundle} * * @return bundle * @since 0.1.0 */ @NonNull Bundle toBundle(); }
19.291667
91
0.647948
1fad119556d5851919e361e666b43dabc5e750af
1,490
package com.xgsama.apiuse.minio; import io.minio.MinioClient; import io.minio.PutObjectArgs; import io.minio.UploadObjectArgs; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; /** * MinioClient * * @author : xgSama * @date : 2021/9/12 00:07:47 */ public class MinioClientTest { private static final String ENDPOINT = "http://xgsama:9555"; private static final String ACCESSKEY = "xgsama"; private static final String SECRETKEY = "xgsama__"; public static void main(String[] args) throws Exception { MinioClient minioClient = MinioClient.builder() .endpoint(ENDPOINT) .credentials(ACCESSKEY, SECRETKEY) .build(); File file = new File("/Users/xgSama/IdeaProjects/java_learning/README.md"); FileInputStream fileInputStream = new FileInputStream(file); // minioClient.uploadObject( // UploadObjectArgs.builder() // .bucket("xgsama-mall") // .object("README.md") // .filename("/Users/xgSama/IdeaProjects/java_learning/README.md") // .build()); minioClient.putObject(PutObjectArgs.builder() .bucket("halo") .stream(fileInputStream, -1, PutObjectArgs.MAX_PART_SIZE) .object("README1.md") .build()); } }
29.215686
89
0.593289
90719d108a8039ef21746229c826784a7e73779e
1,643
/* * Copyright 2012 Lokesh Jain. * * 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.jain.addon.component.upload; import com.vaadin.ui.ProgressBar; import com.vaadin.ui.Upload.ProgressListener; /** * <code>JProgressIndicator<code> default progress indicator for the {@link JImageUpload} * @author Lokesh Jain * @since Aug 28, 2012 * @version 1.0.0 */ public class JProgressIndicator extends ProgressBar implements ProgressListener { private static final long serialVersionUID = 5756898625595137143L; private long readBytes; private long contentLength; public JProgressIndicator() { setWidth("100%"); setValue(0f); } public void updateProgress(long readBytes, long contentLength) { this.readBytes = readBytes; this.contentLength = contentLength; setValue(new Float(readBytes / (float) contentLength)); } public long getReadBytes() { return readBytes; } public void setReadBytes(long readBytes) { this.readBytes = readBytes; } public long getContentLength() { return contentLength; } public void setContentLength(long contentLength) { this.contentLength = contentLength; } }
27.847458
89
0.750456
aa303cf939624cacefcca6cdbe9365aa711f2d90
659
package com.sevenre.trackre.parent.utils; public class Constants { //Bundle public static String ISAUTHENTIC = "com.sevenre.trackre.parent.isauthentic"; public static String SCHOOLID = "com.sevenre.trackre.parent.schoolID"; //Error public static enum ERROR {Incorect_school_id, Error}; //Login public static enum LOGIN {Successful, Wrong_password, No_network, No_user, Wrong_school_code} //Shared Preference public static String PREFERENCE = "com.sevenre.trackre.parentre.pref"; public static enum PREF {SCHOOL_ID, PARENT_MOBILE_NO} public static final int DROP = 1; public static final int PICKUP = 2; }
29.954545
97
0.734446
17ca15820be51fe83ddb3a7f61a912924b857bf9
697
package uk.co.compendiumdev.thingifier.core.domain.definitions.validation; public class VRule { private VRule(){ // don't be tempted, this is a factory class } public static ValidationRule notEmpty() { return new NotEmptyValidationRule(); } public static ValidationRule maximumLength(final int maxLength) { return new MaximumLengthValidationRule(maxLength); } public static ValidationRule matchesRegex(final String regexToMatch) { return new MatchesRegexValidationRule(regexToMatch); } public static ValidationRule satisfiesRegex(final String regexToFind) { return new FindsRegexValidationRule(regexToFind); } }
29.041667
75
0.724534
6efe5c6a8a2996cf6507ff38627dae618c876815
4,103
/* * Copyright 2014-2021 Web Firm Framework * * 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. * @author WFF */ package com.webfirmframework.wffweb.tag.html.html5.attribute.global; import com.webfirmframework.wffweb.InvalidValueException; import com.webfirmframework.wffweb.tag.html.attribute.AttributeNameConstants; import com.webfirmframework.wffweb.tag.html.attribute.core.AbstractAttribute; import com.webfirmframework.wffweb.tag.html.attribute.core.PreIndexedAttributeName; import com.webfirmframework.wffweb.tag.html.identifier.BooleanAttribute; import com.webfirmframework.wffweb.tag.html.identifier.GlobalAttributable; /** * {@code <element hidden> } * * <pre> * The hidden attribute is a boolean attribute. * * When present, it specifies that an element is not yet, or is no longer, relevant. * * Browsers should not display elements that have the hidden attribute specified. * * The hidden attribute can also be used to keep a user from seeing an element until some other condition has been met (like selecting a checkbox, etc.). Then, a JavaScript could remove the hidden attribute, and make the element visible. * </pre> * * @author WFF * */ public class Hidden extends AbstractAttribute implements GlobalAttributable, BooleanAttribute { private static final long serialVersionUID = 1_0_0L; private Boolean hidden; private static final PreIndexedAttributeName PRE_INDEXED_ATTR_NAME; static { PRE_INDEXED_ATTR_NAME = (PreIndexedAttributeName.HIDDEN); } { super.setPreIndexedAttribute(PRE_INDEXED_ATTR_NAME); init(); } /** * sets the default value as <code>hidden</code> (since 2.1.5). If value is not * required then use <code>new Hidden(null)</code>. */ public Hidden() { setAttributeValue(AttributeNameConstants.HIDDEN); } /** * * * @param value the value should be either true or false * @author WFF * @since 1.1.4 */ public Hidden(final String value) { if ("hidden".equals(value) || value == null) { hidden = true; } else if ("true".equals(value) || "false".equals(value)) { hidden = Boolean.parseBoolean(value); } else { throw new InvalidValueException("the value should be either true or false"); } setAttributeValue(value); } public Hidden(final boolean hidden) { setAttributeValue(hidden ? "hidden" : String.valueOf(hidden)); this.hidden = hidden; } /** * invokes only once per object * * @author WFF * @since 1.0.0 */ protected void init() { // to override and use this method } /** * @return the hidden * @author WFF * @since 1.0.0 * @deprecated as there is no affect of boolean values for this attribute this * method will be removed later. */ @Deprecated public boolean isHidden() { return hidden == null || hidden.booleanValue() ? true : false; } /** * @param hidden the hidden to set. {@code null} will remove the value. * @author WFF * @since 1.0.0 * @deprecated as there is no affect of boolean values for this attribute this * method will be removed later. */ @Deprecated public void setHidden(final Boolean hidden) { if (hidden == null) { setAttributeValue(null); } else { setAttributeValue(hidden.booleanValue() ? "hidden" : String.valueOf(hidden)); } this.hidden = hidden; } }
31.083333
237
0.664879
e78033d5821fad8b41fbac41c096685ebf9bf1cc
775
package info.novatec.testit.webtester.eventsystem.events.pageobject; import static java.lang.String.format; import info.novatec.testit.webtester.api.events.Event; import info.novatec.testit.webtester.pageobjects.Form; import info.novatec.testit.webtester.pageobjects.PageObject; /** * This {@link Event event} occurs whenever a form is submitted. * * @see Event * @see Form * @since 1.2 */ @SuppressWarnings("serial") public class FormSubmittedEvent extends AbstractPageObjectEvent{ private static final String MESSAGE_FORMAT = "Submitted form: %s."; public FormSubmittedEvent(PageObject pageObject) { super(pageObject); } @Override public String getEventMessage() { return format(MESSAGE_FORMAT, getSubjectName()); } }
23.484848
71
0.741935
c75d81881138dfe1f0d266ad9c9be5227812f484
228
package pt.po.edimilsonestevam.page; import org.openqa.selenium.WebDriver; import pt.po.edimilsonestevam.setup.Base; public class Categorias extends Base{ public Categorias(WebDriver navegador) { super(navegador); } }
15.2
41
0.780702
6b46b32f25d4a12221eb1257cff676e79171ab45
438
import java.lang.*; import java.util.Scanner; public class GCD { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int divident = scn.nextInt(); int divisor = scn.nextInt(); while (divident % divisor != 0) { int rem = divident % divisor; divident = divisor; divisor = rem; } System.out.println(divisor); } }
17.52
45
0.543379
a72a8fb09c340456ba42247df1a0161a8b1da962
222
package com.example.baserecyclerview.components; /** * Created by Administrator on 2018/5/11 0011. */ public interface OnItemClickListener<T> { void ItemClick(BaseRecyclerViewAdapter.ViewHolder holder, T data); }
20.181818
70
0.765766
9395ebc4d15cf628e6d444e0ab1f30c55ae3d75e
2,618
package io.onedev.server.buildspec.step; import java.util.ArrayList; import java.util.List; import javax.validation.constraints.Size; import org.eclipse.jgit.lib.ObjectId; import org.hibernate.validator.constraints.NotEmpty; import io.onedev.commons.codeassist.InputSuggestion; import io.onedev.k8shelper.CommandExecutable; import io.onedev.k8shelper.Executable; import io.onedev.server.buildspec.BuildSpec; import io.onedev.server.buildspec.BuildSpecAware; import io.onedev.server.buildspec.job.Job; import io.onedev.server.buildspec.job.JobAware; import io.onedev.server.model.Project; import io.onedev.server.util.ComponentContext; import io.onedev.server.web.editable.annotation.Code; import io.onedev.server.web.editable.annotation.Editable; import io.onedev.server.web.editable.annotation.Interpolative; import io.onedev.server.web.page.project.blob.ProjectBlobPage; import io.onedev.server.web.util.SuggestionUtils; import io.onedev.server.web.util.WicketUtils; @Editable(order=100, name="Execute Shell/Batch Commands") public class CommandStep extends Step { private static final long serialVersionUID = 1L; private String image; private List<String> commands; @Editable(order=100, description="Specify docker image to execute commands inside") @Interpolative(variableSuggester="suggestVariables") @NotEmpty public String getImage() { return image; } public void setImage(String image) { this.image = image; } @Editable(order=110, description="Specify content of Linux shell script or Windows command batch to execute " + "under the repository root") @Interpolative @Code(language = Code.SHELL, variableProvider="getVariables") @Size(min=1, message="may not be empty") public List<String> getCommands() { return commands; } public void setCommands(List<String> commands) { this.commands = commands; } @SuppressWarnings("unused") private static List<String> getVariables() { List<String> variables = new ArrayList<>(); ProjectBlobPage page = (ProjectBlobPage) WicketUtils.getPage(); Project project = page.getProject(); ObjectId commitId = page.getCommit(); BuildSpec buildSpec = ComponentContext.get().getComponent().findParent(BuildSpecAware.class).getBuildSpec(); Job job = ComponentContext.get().getComponent().findParent(JobAware.class).getJob(); for (InputSuggestion suggestion: SuggestionUtils.suggestVariables(project, commitId, buildSpec, job, "")) variables.add(suggestion.getContent()); return variables; } @Override public Executable getExecutable(BuildSpec buildSpec) { return new CommandExecutable(image, commands); } }
33.139241
110
0.784568
7151610501ba042eb534110b6a813c4abc215e96
7,927
package com.doc.xpi.af.modules.sequencer; import java.io.IOException; import java.io.InputStream; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException; import com.doc.xpi.af.modules.sequencer.util.AuditLogHelper; import com.doc.xpi.af.modules.sequencer.util.SetSequenceIdParametersHelper; import com.sap.aii.af.lib.mp.module.Module; import com.sap.aii.af.lib.mp.module.ModuleContext; import com.sap.aii.af.lib.mp.module.ModuleData; import com.sap.aii.af.lib.mp.module.ModuleException; import com.sap.engine.interfaces.messaging.api.DeliverySemantics; import com.sap.engine.interfaces.messaging.api.Message; import com.sap.engine.interfaces.messaging.api.MessageKey; import com.sap.engine.interfaces.messaging.api.XMLPayload; import com.sap.engine.interfaces.messaging.api.auditlog.AuditLogStatus; import com.sap.engine.interfaces.messaging.api.exception.InvalidParamException; import com.sap.tc.logging.Location; /** * Session Bean implementation class SetSequenceIdBean */ public class SetSequenceIdBean implements Module { private static final Location TRACE = Location.getLocation(SetSequenceIdBean.class.getName()); /** * Default constructor. */ public SetSequenceIdBean() { // Not used in current implementation } @Override public ModuleData process(ModuleContext moduleContext, ModuleData moduleData) throws ModuleException { Message message = (Message) moduleData.getPrincipalData(); MessageKey messageKey = message.getMessageKey(); AuditLogHelper audit = new AuditLogHelper(messageKey); SetSequenceIdParametersHelper parametersHandler = new SetSequenceIdParametersHelper(); Map<String, String> parameters = parametersHandler.getChannelParameters(moduleContext); parametersHandler.checkInputParameters(parameters); String sequenceId = null; if (!parametersHandler.isParameterError) { XMLPayload payload = message.getDocument(); InputStream payloadInputStream = payload.getInputStream(); if (parametersHandler.xPath != null) { // Determine sequence ID String value = this.applyXPathExtractor(payloadInputStream, parametersHandler.xPath); if (value == null || value.trim().isEmpty()) { TRACE.errorT("No value was extracted for the XPath expression"); } sequenceId = this.constructValue(value, parametersHandler); if (sequenceId != null && sequenceId.length() >= 1 && sequenceId.length() <= 16 && !sequenceId.equals(message.getSequenceId())) { // Overwrite sequence ID and delivery semantics (if not // EOIO) try { TRACE.debugT("Overwriting message sequence ID from " + message.getSequenceId() + " to " + sequenceId); message.setSequenceId(sequenceId); if (message.getDeliverySemantics() != DeliverySemantics.ExactlyOnceInOrder && message.getSequenceId() != null) { TRACE.debugT("Overwriting message delivery semantics from " + message.getDeliverySemantics().toString() + " to " + DeliverySemantics.ExactlyOnceInOrder.toString()); message.setDeliverySemantics(DeliverySemantics.ExactlyOnceInOrder); } moduleData.setPrincipalData(message); } catch (InvalidParamException e) { audit.addAuditLogEntry( AuditLogStatus.WARNING, SetSequenceIdBean.class.getSimpleName() + ": Error setting message delivery semantics / sequence ID: " + e.getMessage()); TRACE.errorT("Error setting message delivery semantics / sequence ID: " + e.getMessage()); } } else { audit.addAuditLogEntry( AuditLogStatus.WARNING, SetSequenceIdBean.class.getSimpleName() + ": Sequence ID cannot be set because of incorrect value: " + sequenceId); TRACE.errorT("Sequence ID cannot be set because of incorrect value: " + sequenceId); } } } else { if (parametersHandler.isTerminateIfError) { throw new ModuleException( "One or several required adapter module parameters are missing or incorrect"); } else { audit.addAuditLogEntry( AuditLogStatus.WARNING, SetSequenceIdBean.class.getSimpleName() + ": One or several required adapter module parameters are missing or incorrect, exiting module execution"); TRACE.errorT("One or several required adapter module parameters are missing or incorrect, exiting module execution"); } } if (message.getSequenceId() == null || !message.getSequenceId().equals(sequenceId)) { if (parametersHandler.isTerminateIfError) { throw new ModuleException( "Failure while attempting to set sequence ID"); } else { audit.addAuditLogEntry( AuditLogStatus.WARNING, SetSequenceIdBean.class.getSimpleName() + ": Failure while attempting to set sequence ID"); } } return moduleData; } private String applyXPathExtractor(InputStream inputStream, String xPathExpressionValue) { String value = null; try { DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); Document document = documentBuilder.parse(inputStream); XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); XPathExpression xPathExpression = xPath.compile(xPathExpressionValue); value = (String) xPathExpression.evaluate(document, XPathConstants.STRING); TRACE.debugT("Value extracted for the XPath expression: " + value); } catch (ParserConfigurationException e) { TRACE.errorT("Error parsing message and applying XPath expression: " + e.getMessage()); } catch (SAXException e) { TRACE.errorT("Error parsing message and applying XPath expression: " + e.getMessage()); } catch (IOException e) { TRACE.errorT("Error parsing message and applying XPath expression: " + e.getMessage()); } catch (XPathExpressionException e) { TRACE.errorT("Error parsing message and applying XPath expression: " + e.getMessage()); } return value; } private String constructValue(String input, SetSequenceIdParametersHelper parametersHandler) { final int SEQ_ID_MAX_LENGTH = 16; String value = input.trim(); // Adoption of the sequence ID value based on optional parameterization if (parametersHandler.isDeleteLeadingChar) { value = value.replaceFirst("^" + parametersHandler.leadingChar + "+(?!$)", ""); TRACE.debugT("Leading characters were deleted, new value: " + value); } if (parametersHandler.isAddPrefix) { value = parametersHandler.prefix + "_" + value; TRACE.debugT("Prefix was added, new value: " + value); } if (parametersHandler.isAddSuffix) { value = value + "_" + parametersHandler.suffix; TRACE.debugT("Suffix was added, new value: " + value); } if (parametersHandler.isReplaceInvalidChar) { value = value.replaceAll("[^\\w]", "_"); TRACE.debugT("Invalid characters were replaced, new value: " + value); } if (parametersHandler.isTruncateStart && value.length() > SEQ_ID_MAX_LENGTH) { value = value.substring(value.length() - SEQ_ID_MAX_LENGTH); TRACE.debugT("Start was truncated, new value: " + value); } if (parametersHandler.isTruncateEnd && value.length() > SEQ_ID_MAX_LENGTH) { value = value.substring(0, SEQ_ID_MAX_LENGTH); TRACE.debugT("End was truncated, new value: " + value); } if (value != null) { value = value.toUpperCase(); } TRACE.debugT("Constructed value for sequence ID: " + value); return value; } }
31.835341
121
0.723981
081585a3f71e5b169d9e79c325c9a396f454d468
2,712
/* * Copyright (c) 2007-2011 by Institute for Computational Biomedicine, * Weill Medical College of Cornell University. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR * WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER * OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE * TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES * OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, * ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER * THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT * SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING. */ package org.broad.igv.goby; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import java.io.File; import java.util.List; import org.broad.igv.feature.LocusScore; import org.junit.Test; /** * Test that the count goby data source can load data. * @author Fabien Campagne * Date: 6/12/11 * Time: 1:34 PM */ public class GobyCountArchiveDataSourceTest { @Test public void iteratePickrell() { GobyCountArchiveDataSource counts = new GobyCountArchiveDataSource(new File("test/data/goby/counts/GDFQPGI-pickrellNA18486_yale")); assertTrue(counts.getAvailableWindowFunctions().size() > 0); List<LocusScore> list1 = counts.getSummaryScoresForRange("chr1", 10000, 2000000, 1); assertTrue(list1.size() > 0); List<LocusScore> list2 = counts.getSummaryScoresForRange("1", 10000, 2000000, 1); assertTrue(list2.size() > 0); assertEquals(list1.size(), list2.size()); } @Test public void iteratePickrellChr3() { GobyCountArchiveDataSource counts = new GobyCountArchiveDataSource(new File("test/data/goby/counts/GDFQPGI-pickrellNA18486_yale")); assertTrue(counts.getAvailableWindowFunctions().size() > 0); List<LocusScore> list1 = counts.getSummaryScoresForRange("chr3", 0,198022431, 0); assertTrue(list1.size() > 0); List<LocusScore> list2 = counts.getSummaryScoresForRange("3", 0,198022431, 0); assertTrue(list2.size() > 0); assertEquals(list1.size(), list2.size()); } }
43.741935
139
0.714971
2547cdc52b0f5d70d01a390c988767a9378a5d7e
1,942
package Symbols; import LayanAST.LayanAST; import java.util.HashMap; import java.util.Map; public class ClassSymbol extends Symbol implements Scope, Type{ public Map<String, Symbol> fields = new HashMap<String, Symbol>(); private Scope enclosingScope; public ClassSymbol superClass; public ClassSymbol(String name, Type type, Scope cs, LayanAST def){ super(name, type, def, cs); enclosingScope = cs; this.evalType = new BuiltInTypeSymbol("void"); } @Override public Scope getEnclosingScope() { return enclosingScope; } @Override public Scope getParentScope() { if(superClass != null) return superClass; return getEnclosingScope(); } @Override public String getScopeName() { return "local scope"; } @Override public void define(Symbol symbol) { System.out.println("def " + symbol.name); fields.put(symbol.name, symbol); } @Override public Symbol resolve(String name) { Symbol symbol = fields.get(name); Scope scope = getParentScope(); while (scope != null && symbol == null){ symbol = scope.resolve(name); if(symbol != null) break; scope = scope.getParentScope(); } return symbol; } @Override public Symbol resolveMember(String name){ Symbol symbol = fields.get(name); if(symbol == null && superClass != null){ symbol = superClass.resolveMember(name); } return symbol; } @Override public String getTypeName() { return this.name; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(getScopeName() + ": "); for (String name: fields.keySet()) stringBuilder.append(name + " "); return stringBuilder.toString(); } }
25.220779
71
0.607621
1683fbc0ee708d56a405f8c46a6bc8feac57d2c0
3,705
package com.sdl.dxa.modules.degrees51.api.mapping; import fiftyone.mobile.detection.Match; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import static com.sdl.webapp.common.util.ApplicationContextHolder.getContext; /** * <p>Mapping between a property in DXA and possible property in 51degrees * which can be resolved either by direct mapping or by building its value by {@link Degrees51Processor} instance.</p> */ public abstract class Degrees51Mapping<T> { /** * Tries to resolve a registered mapping from Spring context by its name. * Typically name of this mapping is a DXA claim name. * * @param dxaKey name of the mapping, typically DXA claim name * @param <T> an expected type of final value for this mapping * @return a mapping if found or null */ @SuppressWarnings("unchecked") public static <T> Degrees51Mapping<T> retrieveMappingByDxaKey(String dxaKey) { try { return (Degrees51Mapping<T>) getContext().getBean(dxaKey, Degrees51Mapping.class); } catch (NoSuchBeanDefinitionException e) { return null; } } /** * Creates a dummy temporal mapping for in-process usage. * * @param degrees51Key a key that will be passed to processor * @param processor processor to get a value * @param <T> type of expected value * @return a dummy mapping with a DXA key 'dummy' */ public static <T> Degrees51Mapping<T> dummyMapping(final String degrees51Key, final Degrees51Processor<T> processor) { return createMapping("dummy", degrees51Key, processor); } /** * Creates a mapping object. * * @param dxaKey DXA claims key * @param degrees51Key optional key for 3rd-party property which will be passed to processor in mapping * @param processor processor to convert/extract value using {@link Match} and this mapping * @param <T> type of value returned by processor * @return a mapping with all fields set */ public static <T> Degrees51Mapping<T> createMapping(final String dxaKey, final String degrees51Key, final Degrees51Processor<T> processor) { return new Degrees51Mapping<T>() { @Override public String getKey() { return degrees51Key; } @Override public String getKeyDxa() { return dxaKey; } @Override public Degrees51Processor<T> getProcessor() { return processor; } }; } /** * Processes value for current mapping. * * @param match match object from 51degrees * @return a value or null if not found */ public T process(Match match) { return getProcessor().process(match, this); } /** * Optional key/property in 51degrees or context. May return <code>null</code>. * * @return key in 51degrees properties or context key or <code>null</code> if there is no direct mapping */ public abstract String getKey(); /** * DXA mapping for {@link com.sdl.webapp.common.api.contextengine.ContextClaims}. Should never return <code>null</code>. * * @return DXA key mapping */ public abstract String getKeyDxa(); /** * Processor for a match from 51degrees to get a real value DXA needs. Never should return null. * * @return processor for a match */ protected abstract Degrees51Processor<T> getProcessor(); @Override public String toString() { return String.format("Degrees51Mapping: %s <> %s", getKey(), getKeyDxa()); } }
34.626168
144
0.644534
e328b46e9c234de95e2c220eab98132744186435
947
package fusewarhw2019.elmeth; import robocode.AdvancedRobot; import robocode.HitRobotEvent; import robocode.Robot; import robocode.ScannedRobotEvent; public class SpinCore extends Core { public SpinCore(AdvancedRobot robot, int weight) { super(robot, weight); } @Override public void run() { // Tell the game that when we take move, // we'll also want to turn right... a lot. robot.setTurnRight(10000); // Limit our speed to 5 robot.setMaxVelocity(5); // Start moving (and turning) robot.ahead(10000); // Repeat. } @Override public void onHitRobot(HitRobotEvent e) { if (e.getBearing() > -10 && e.getBearing() < 10) { robot.fire(3); } if (e.isMyFault()) { robot.turnRight(10); } } @Override public void onScannedRobot(ScannedRobotEvent e) { robot.fire(3); } }
22.547619
58
0.593453
6dbdf821ee93499f3c8499056eac414a8918f5bf
1,836
package com.alipay.api.response; import java.util.List; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.internal.mapping.ApiListField; import com.alipay.api.domain.InfoCode; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.security.risk.rainscore.query response. * * @author auto create * @since 1.0, 2021-07-13 15:44:11 */ public class AlipaySecurityRiskRainscoreQueryResponse extends AlipayResponse { private static final long serialVersionUID = 3649558477251922316L; /** * 风险解释,即本次风险评分中TOP 3风险因子的代码、名称、解释、风险倍数(JSON格式)。详情请参考<a href="https://doc.open.alipay.com/doc2/detail.htm?treeId=214&articleId=104588&docType=1">《风险解释与身份标签》</a> */ @ApiListField("infocode") @ApiField("info_code") private List<InfoCode> infocode; /** * 身份标签,即本次风险评分中评分主体(手机号)相关自然人的推测身份,例如:Scalper_3C(3C行业黄牛)等。没有与当前风险类型相关的推测身份时,身份标签可能为空。详情及申请方式请参考<a href="https://doc.open.alipay.com/doc2/detail.htm?treeId=214&articleId=104588&docType=1#s1">《风险解释及身份标签》</a> */ @ApiListField("label") @ApiField("string") private List<String> label; /** * 风险评分,范围为[0,100],评分越高风险越大 */ @ApiField("score") private String score; /** * 调用订单号 */ @ApiField("unique_id") private String uniqueId; public void setInfocode(List<InfoCode> infocode) { this.infocode = infocode; } public List<InfoCode> getInfocode( ) { return this.infocode; } public void setLabel(List<String> label) { this.label = label; } public List<String> getLabel( ) { return this.label; } public void setScore(String score) { this.score = score; } public String getScore( ) { return this.score; } public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } public String getUniqueId( ) { return this.uniqueId; } }
24.48
208
0.696078
e4d9f8d77263a4372793f27f16bd5a500a207914
464
package org.powlab.jeye.tests.inner; import java.util.ArrayList; import java.util.List; public class InnerClassTest2 { @SuppressWarnings("unchecked") public int getX() { return new Inner1(new ArrayList<String>()).getX(4); } public class Inner1<E> { private final List<E> arg; public Inner1(List<E> arg) { this.arg = arg; } public int getX(int y) { return 2; } } }
17.185185
59
0.571121
eb2c7e0604226002f72b7e945840818a456f7e44
779
package $package; import java.util.Map; import org.wso2.carbon.identity.mgt.policy.AbstractPasswordPolicyEnforcer; public class CustomPasswordValidator extends AbstractPasswordPolicyEnforcer { @Override public void init(Map<String, String> params) { /** * initialization method, loads the properties from * identity-mgt.properties file to Map<String, String> */ // TODO: initialize variables from properties file and etc. } @Override public boolean enforce(Object... args) { // TODO: implement your password validator logic ... /** * HINT: * retrieve the username and password entered using * the following snippet * * String password = args[0].toString(); * String username = args[1].toString(); */ return false; } }
20.5
77
0.70475
b021e7f5025c8d2647d3147a693dc6230746db2f
2,337
/* * Copyright 2016 Red Hat 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 io.apiman.test.integration.ui.support.selenide; import org.openqa.selenium.By; /** * @author jcechace */ public class ByApiman { /** * Create a css based selector for Angular Model attribute "ng-model" * @param property model property * @return By selector */ public static By ngModel(String property) { if (property == null) { throw new IllegalArgumentException("Cannot find elements when model property is null."); } else { return new By.ByCssSelector("*[ng-model='" + property + "']"); } } /** * Create a css based selector for Angular model attribute "ng-show" * @param property model property * @return By selector */ public static By ngShow(String property) { if (property == null) { throw new IllegalArgumentException("Cannot find elements when model property is null."); } else { return new By.ByCssSelector("*[ng-show='" + property + "']"); } } /** * Create a css based selector for i18n attribute "apiman-i18n-key" * * @param element element type * @param key i18n key * @return By selector */ public static By i18n(String element, String key) { if (key == null) { throw new IllegalArgumentException("Cannot find elements when i18n key is null."); } else { return new By.ByCssSelector(element + "[apiman-i18n-key='" + key + "']"); } } /** * Create a css based selector for i18n attribute "apiman-i18n-key" * * @param key i18n key * @return By selector */ public static By i18n(String key) { return i18n("*", key); } }
29.961538
100
0.623877
63898e9b1f547225d1fafd72878d29738321b964
1,285
package com.xinghai.networkframelib.common.lifecycle; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import io.reactivex.subjects.BehaviorSubject; /** * Created on 17/3/24. * author: yuanbaoyu */ public class RxLifecycleAppCompatActivity extends AppCompatActivity { protected BehaviorSubject<ActivityEvent> lifeCycleSubject = BehaviorSubject.create(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); lifeCycleSubject.onNext(ActivityEvent.CREATE); } @Override protected void onStart() { super.onStart(); lifeCycleSubject.onNext(ActivityEvent.START); } @Override protected void onResume() { super.onResume(); lifeCycleSubject.onNext(ActivityEvent.RESUME); } @Override protected void onPause() { lifeCycleSubject.onNext(ActivityEvent.PAUSE); super.onPause(); } @Override protected void onStop() { lifeCycleSubject.onNext(ActivityEvent.STOP); super.onStop(); } @Override protected void onDestroy() { lifeCycleSubject.onNext(ActivityEvent.DESTROY); super.onDestroy(); } }
24.245283
89
0.694942
5ff3073a52c11c8b8fd69536224e51df66ba85b6
12,694
package com.icfolson.aem.library.core.servlets.paragraphs; import com.day.cq.wcm.api.NameConstants; import com.day.cq.wcm.api.WCMMode; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.icfolson.aem.library.api.page.PageDecorator; import com.icfolson.aem.library.api.request.ComponentServletRequest; import com.icfolson.aem.library.core.servlets.AbstractComponentServlet; import org.apache.commons.lang3.StringUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.servlets.ServletResolverConstants; import org.apache.sling.api.wrappers.SlingHttpServletResponseWrapper; import org.osgi.service.component.annotations.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.query.Query; import javax.jcr.query.QueryManager; import javax.jcr.query.QueryResult; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.WriteListener; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.util.List; import java.util.Set; import static com.icfolson.aem.library.core.constants.PathConstants.EXTENSION_HTML; import static com.icfolson.aem.library.core.constants.PathConstants.EXTENSION_JSON; /** * Retrieves HTML for all contained components on a Page. This differs from the * OOB Paragraph servlet, com.day.cq.wcm.foundation.ParagraphServlet, in that * the OOB servlet only pulls content from top level containers while this * servlet will pull content from any container on the Page regardless of depth * of nesting. Concretely, if your page has nested paragraph systems, the OOB * paragraph servlet will not recognize and collect components within the nested * paragraph systems while this servlet will. * <p> * This Servlet is suitable for overriding the OOB behavior of xtypes such as * paragraphreference, causing it to pull all components on a page as opposed to * the top level components. */ @Component(service = Servlet.class, property = { ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES + "=" + NameConstants.NT_PAGE, ServletResolverConstants.SLING_SERVLET_SELECTORS + "=ctparagraphs", ServletResolverConstants.SLING_SERVLET_EXTENSIONS + "=" + EXTENSION_JSON, ServletResolverConstants.SLING_SERVLET_METHODS + "=GET" }) public final class ParagraphJsonServlet extends AbstractComponentServlet { private static final long serialVersionUID = 1L; private static final String CONTAINER_COMPONENTS_FROM_LIBS_XPATH_QUERY = "/jcr:root/libs//element(*,cq:Component)[@cq:isContainer='true']"; private static final String CONTAINER_COMPONENTS_FROM_APPS_XPATH_QUERY = "/jcr:root/apps//element(*,cq:Component)[@cq:isContainer='true']"; private static final String LIBS_PATH_STRING = "/libs/"; private static final String APPS_PATH_STRING = "/apps/"; private static final Logger LOG = LoggerFactory.getLogger(ParagraphJsonServlet.class); @Override public void processGet(final ComponentServletRequest request) throws ServletException, IOException { final SlingHttpServletRequest slingRequest = request.getSlingRequest(); final SlingHttpServletResponse slingResponse = request.getSlingResponse(); WCMMode.DISABLED.toRequest(slingRequest); try { final List<Paragraph> paragraphs = getParagraphs(request); if (paragraphs != null) { LOG.debug("{} paragraphs found on page", paragraphs.size()); writeJsonResponse(slingResponse, ImmutableMap.of("paragraphs", paragraphs)); } else { LOG.info("null returned, indicating a lack of page or a lack of content"); slingResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } } catch (RepositoryException e) { LOG.error("error requesting paragraph HTML for contained components", e); slingResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } @Override public void processPost(final ComponentServletRequest request) throws ServletException, IOException { // nothing to do } /** * @param request component servlet request * @return A List of Paragraphs representing all components which exist * within containers under a given Page * @throws RepositoryException * @throws ServletException * @throws IOException */ @SuppressWarnings("deprecation") private List<Paragraph> getParagraphs(final ComponentServletRequest request) throws RepositoryException, ServletException, IOException { // Request the current page final PageDecorator currentPage = request.getCurrentPage(); if (currentPage == null) { LOG.info("The request is not within the context of a Page"); return null; } // Request the page's content node final Resource pageContentResource = currentPage.getContentResource(); if (pageContentResource == null) { LOG.info("The requested resource does not have a child content resource"); return null; } // Get a handle to the query manager final Session session = request.getResourceResolver().adaptTo(Session.class); final QueryManager queryManager = session.getWorkspace().getQueryManager(); // Find all container components which are children of the requested // resources content node final Set<String> containerComponentResourceTypes = getContainerComponents(queryManager); /* * Construct a query which will request all resources under the current * page's content node which are of a type indicated to be a container * via the cq:isContainer property. */ final List<String> resourceTypeAttributeQueryStrings = Lists.newArrayListWithExpectedSize(containerComponentResourceTypes.size()); for (final String curContainerResourceType : containerComponentResourceTypes) { resourceTypeAttributeQueryStrings.add("@sling:resourceType='" + curContainerResourceType + "'"); } final String resourceTypeAttributeQueryString = StringUtils.join(resourceTypeAttributeQueryStrings, " or "); final String resourceQueryString = "/jcr:root" + pageContentResource.getPath() + "//element(*,nt:unstructured)[" + resourceTypeAttributeQueryString + "]"; LOG.debug("resource query string = {}", resourceQueryString); // Execute the query final Query resourceQuery = queryManager.createQuery(resourceQueryString, Query.XPATH); final QueryResult resourceQueryResult = resourceQuery.execute(); final NodeIterator resourceQueryResultIterator = resourceQueryResult.getNodes(); final List<Paragraph> paragraphs = Lists.newArrayList(); /* * Go through the direct children of each container resource, adding * them to the final list of Paragraphs */ while (resourceQueryResultIterator.hasNext()) { paragraphs.addAll(getChildParagraphs(request, resourceQueryResultIterator.nextNode().getPath(), containerComponentResourceTypes)); } // Return the list of paragraphs return paragraphs; } /** * @param request * @param parentPath * @param containerResourceTypes * @return A list of Paragraphs representing the non-container resources * which are direct children of the resource indicated by the * parentPath * @throws ServletException * @throws IOException */ private List<Paragraph> getChildParagraphs(final ComponentServletRequest request, final String parentPath, final Set<String> containerResourceTypes) throws ServletException, IOException { final List<Paragraph> paragraphs = Lists.newArrayList(); final Resource parentResource = request.getResourceResolver().getResource(parentPath); if (parentResource != null) { for (final Resource resource : parentResource.getChildren()) { if (!containerResourceTypes.contains(resource.getResourceType())) { paragraphs.add(new Paragraph(resource.getPath(), renderResourceHtml(resource, request.getSlingRequest(), request.getSlingResponse()))); } } } return paragraphs; } @SuppressWarnings("deprecation") private Set<String> getContainerComponents(final QueryManager queryManager) throws RepositoryException { final Set<String> containerComponentSet = Sets.newHashSet(); final Query containerComponentsFromLibsQuery = queryManager.createQuery(CONTAINER_COMPONENTS_FROM_LIBS_XPATH_QUERY, Query.XPATH); final Query containerComponentsFromAppsQuery = queryManager.createQuery(CONTAINER_COMPONENTS_FROM_APPS_XPATH_QUERY, Query.XPATH); final QueryResult containerComponentsFromLibsQueryResult = containerComponentsFromLibsQuery.execute(); final QueryResult containerComponentsFromAppsQueryResult = containerComponentsFromAppsQuery.execute(); final NodeIterator containerComponentsFromLibsQueryResultIterator = containerComponentsFromLibsQueryResult.getNodes(); final NodeIterator containerComponentsFromAppsQueryResultIterator = containerComponentsFromAppsQueryResult.getNodes(); LOG.debug("query execution complete"); while (containerComponentsFromLibsQueryResultIterator.hasNext()) { final Node curContainerComponentNode = containerComponentsFromLibsQueryResultIterator.nextNode(); final String curNodePath = curContainerComponentNode.getPath(); LOG.debug("adding {} from libs as a container resource type", curNodePath); if (curNodePath.startsWith(LIBS_PATH_STRING)) { containerComponentSet.add(curNodePath.substring(LIBS_PATH_STRING.length())); } else { containerComponentSet.add(curContainerComponentNode.getPath()); } } while (containerComponentsFromAppsQueryResultIterator.hasNext()) { final Node curContainerComponentNode = containerComponentsFromAppsQueryResultIterator.nextNode(); final String curNodePath = curContainerComponentNode.getPath(); LOG.debug("adding {} from apps as a container resource type", curNodePath); if (curNodePath.startsWith(APPS_PATH_STRING)) { containerComponentSet.add(curNodePath.substring(APPS_PATH_STRING.length())); } else { containerComponentSet.add(curContainerComponentNode.getPath()); } } return containerComponentSet; } private String renderResourceHtml(final Resource resource, final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException { final Writer outputBuffer = new StringWriter(); final ServletOutputStream outputStream = new ServletOutputStream() { @Override public void write(final int b) throws IOException { outputBuffer.append((char) b); } @Override public boolean isReady() { return true; } @Override public void setWriteListener(WriteListener paramWriteListener) { } }; final SlingHttpServletResponseWrapper responseWrapper = new SlingHttpServletResponseWrapper(response) { @Override public ServletOutputStream getOutputStream() { return outputStream; } @Override public PrintWriter getWriter() throws IOException { return new PrintWriter(outputBuffer); } }; final RequestDispatcher requestDispatcher = request.getRequestDispatcher(resource.getPath() + "." + EXTENSION_HTML); requestDispatcher.include(request, responseWrapper); return outputBuffer.toString(); } }
41.214286
116
0.709627
6b8b1b73d9af53bbec9518b0cbf508dca1201535
2,578
package sexybeast.tutorial_island.sections; import org.dreambot.api.methods.dialogues.Dialogues; import org.dreambot.api.methods.interactive.NPCs; import org.dreambot.api.methods.magic.Magic; import org.dreambot.api.methods.magic.Normal; import org.dreambot.api.methods.tabs.Tab; import org.dreambot.api.methods.tabs.Tabs; import org.dreambot.api.methods.walking.impl.Walking; import org.dreambot.api.wrappers.interactive.NPC; import static sexybeast.tutorial_island.utils.Locations.Areas.CHICKEN_AREA; import static sexybeast.tutorial_island.utils.Locations.Areas.CHICKEN_HOUSE; import static sexybeast.tutorial_island.utils.Locations.Tiles.CHICKENS; public class WizardSection extends AbstractSection { private static final String[] DIALOGUE_OPTIONS = {"Yes.", "No, I'm not planning to do that."}; public WizardSection() { super("Magic Instructor"); } @Override public void execute() { if (handleContinue()) { return; } switch (getSectionProgress()) { case 620: if (!CHICKEN_HOUSE.contains(getLocalPlayer()) && Walking.shouldWalk()) { Walking.walk(CHICKEN_HOUSE.getCenter()); } else { talkToInstructor(); } break; case 630: Tabs.openWithMouse(Tab.MAGIC); break; case 640: talkToInstructor(); break; case 650: if (!CHICKEN_AREA.contains(getLocalPlayer()) && Walking.shouldWalk()) { // dont walk?? Walking.clickTileOnMinimap(CHICKENS); } else { attackChicken(); } break; case 670: if (Dialogues.getOptions() != null) { handleDialogues(); } else { talkToInstructor(); } break; } } private void handleDialogues() { for (String s : Dialogues.getOptions()) { for (String s2 : DIALOGUE_OPTIONS) { if (s2.equals(s) && Dialogues.chooseOption(s2)) sleep(1200); } } } private void attackChicken() { NPC chicken = NPCs.closest(npc -> npc.getName().equals("Chicken") && npc.getInteractingCharacter() == null); if (chicken != null && Magic.castSpellOn(Normal.WIND_STRIKE, chicken)) { sleepUntil(() -> getSectionProgress() != 650, 4000); } } }
34.373333
116
0.570209
88eec1ea7850a91d9a301a69a0be068d03478965
216
package com.cmclinnovations.ontochem.model.converter.owl.query.sparql; /** * An interface designed for the MetadataQuery class. * * @author msff2 * */ public interface IMetadataQuery { public void query(); }
18
70
0.736111
bdd2c74325244c99e83bc6424edfc031e83fe358
800
package thedarkdnktv.openbjs.network.packet; import java.io.IOException; import thedarkdnktv.openbjs.api.network.Packet; import thedarkdnktv.openbjs.api.util.PacketBuf; import thedarkdnktv.openbjs.network.handlers.interfaces.IStatusClient; public class S_Pong implements Packet<IStatusClient> { private long clientTime; public S_Pong() {} public S_Pong(long clientTime) { this.clientTime = clientTime; } @Override public void writePacketData(PacketBuf buf) throws IOException { buf.writeLong(this.clientTime); } @Override public void readPacketData(PacketBuf buf) throws IOException { this.clientTime = buf.readLong(); } @Override public void processPacket(IStatusClient handler) { handler.handlePong(this); } public long getClientTime() { return clientTime; } }
21.621622
70
0.77625
1aebd950b74dac476be7182a70d13e0fdfe56316
504
package com.pedelen.curfewer.curfewer; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; /** * Created by Mitch on 8/7/2016. */ public class p_inviteSent extends AppCompatActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.p_add_child); } private void continueRunning() { startActivity(new Intent(this, p_selectChild.class)); } }
24
61
0.732143
8dacc20ffc7c7d10be56fd3b569b0888d59796f3
479
package org.firstinspires.ftc.teamcode.teleop; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; @Disabled @TeleOp(name = "Blue Advanced TeleOp", group = "Remote") public class BlueAdvancedTeleOp extends AdvancedTeleOp { // @Override // public Target[] getTargets() { // return new Target[]{Constants.blueTopGoal, Constants.bluePowershot1, Constants.bluePowershot2, Constants.bluePowershot3}; // } }
36.846154
131
0.76618
2e7891fe317fe20b19cd8004c230d7283974adbb
2,459
import java.util.List; import java.util.Arrays; public class PaginationHelper<I> { private final int itemsPerPage; private final int itemCount; private final int pageCount; /** * The constructor takes in an array of items and a integer indicating how many * items fit within a single page */ public PaginationHelper(List<I> collection, int itemsPerPage) { this.itemsPerPage = itemsPerPage; itemCount = collection.size(); pageCount = (int)Math.ceil((double)itemCount / itemsPerPage); } /** * returns the number of items within the entire collection */ public int itemCount() { return itemCount; } /** * returns the number of pages */ public int pageCount() { return pageCount; } /** * returns the number of items on the current page. page_index is zero based. * this method should return -1 for pageIndex values that are out of range */ public int pageItemCount(int pageIndex) { if (pageIndex < 0) return -1; if (pageIndex >= pageCount) return -1; else if (pageIndex == pageCount - 1) return itemCount % itemsPerPage; else return itemsPerPage; } /** * determines what page an item is on. Zero based indexes * this method should return -1 for itemIndex values that are out of range */ public int pageIndex(int itemIndex) { if (itemIndex < 0) return -1; if (itemIndex >= itemCount) return -1; return itemIndex / itemsPerPage; } public static void main (String [] args) { PaginationHelper<Integer> p = new PaginationHelper<Integer>(Arrays.asList(1,2,3,4,5,6,7,8), 3); System.out.printf("Item count: %d\n", p.itemCount()); System.out.printf("Page count: %d\n", p.pageCount()); System.out.println("Page indexes"); System.out.println(p.pageIndex(0)); System.out.println(p.pageIndex(1)); System.out.println(p.pageIndex(2)); System.out.println(p.pageIndex(-1)); System.out.println("Page items"); System.out.println(p.pageItemCount(0)); System.out.println(p.pageItemCount(1)); System.out.println(p.pageItemCount(2)); System.out.println(p.pageItemCount(3)); System.out.println(p.pageItemCount(4)); } }
27.322222
103
0.602277
949ca8d2483c98e9f44f8dab432eea177dd46f10
936
package io.github.gravetii.scene.start; import io.github.gravetii.client.DiztlClient; import io.github.gravetii.controller.start.QuickOptionsController; import io.github.gravetii.scene.FxComponent; import io.github.gravetii.store.DBService; import javafx.scene.layout.AnchorPane; public class QuickOptionsComponent extends FxComponent<QuickOptionsController, AnchorPane> { private final DiztlClient client; private final DBService dbService; private final StartScene scene; public QuickOptionsComponent(DiztlClient client, DBService dbService, StartScene scene) { super("quickOptions.fxml"); this.client = client; this.dbService = dbService; this.scene = scene; this.create(); } @Override protected QuickOptionsController createController() { return new QuickOptionsController(client, dbService, scene); } @Override protected AnchorPane createNode() { return this.loadNode(); } }
28.363636
92
0.776709
3d0b5ea05f04abf643bc1515e60f8fea6e0faebc
1,375
// Copyright 2004-present Facebook. All Rights Reserved. package com.facebook.stetho.sample; import java.io.PrintStream; import java.util.Iterator; import android.text.TextUtils; import com.facebook.stetho.dumpapp.DumpException; import com.facebook.stetho.dumpapp.DumpUsageException; import com.facebook.stetho.dumpapp.DumperContext; import com.facebook.stetho.dumpapp.DumperPlugin; public class HelloWorldDumperPlugin implements DumperPlugin { private static final String NAME = "hello"; @Override public String getName() { return NAME; } @Override public void dump(DumperContext dumpContext) throws DumpException { PrintStream writer = dumpContext.getStdout(); Iterator<String> args = dumpContext.getArgsAsList().iterator(); String helloToWhom = args.hasNext() ? args.next() : null; if (helloToWhom != null) { doHello(writer, helloToWhom); } else { doUsage(writer); } } private void doHello(PrintStream writer, String name) throws DumpUsageException { if (TextUtils.isEmpty(name)) { // This will print an error to the dumpapp user and cause a non-zero exit of the // script. throw new DumpUsageException("Name is empty"); } writer.println("Hello " + name + "!"); } private void doUsage(PrintStream writer) { writer.println("Usage: dumpapp " + NAME + " <name>"); } }
27.5
86
0.714182
1c3bea5215519cf2bcbb9dc8c73c1a3521473fbe
586
package com.keqi.projectseedfirst.test.mapper; import com.keqi.projectseedfirst.test.domain.Dept; import org.apache.ibatis.annotations.Param; import java.util.List; public interface DeptMapper { int deleteByPrimaryKey(Long deptId); int insert(Dept record); int insertSelective(Dept record); Dept selectByPrimaryKey(Long deptId); int updateByPrimaryKeySelective(Dept record); int updateByPrimaryKey(Dept record); /** * 查询指定deptId下的所有直接子级部门 * * @param parentId parentId * @return deptList */ List<Dept> selectAllByParentId(@Param("parentId") Long parentId); }
19.533333
66
0.769625
72757cb6301bb5b55bc19ccfaa9cd32471747fff
1,043
package uk.gov.hmcts.reform.unspec.model.search; import org.elasticsearch.index.query.QueryBuilder; import java.util.List; import java.util.Objects; import static net.minidev.json.JSONValue.toJSONString; public class Query { private final QueryBuilder queryBuilder; private final List<String> dataToReturn; private final int startIndex; public Query(QueryBuilder queryBuilder, List<String> dataToReturn, int startIndex) { Objects.requireNonNull(queryBuilder, "QueryBuilder cannot be null in search"); if (startIndex < 0) { throw new IllegalArgumentException("Start index cannot be less than 0"); } this.queryBuilder = queryBuilder; this.dataToReturn = dataToReturn; this.startIndex = startIndex; } @Override public String toString() { return "{" + "\"query\": " + queryBuilder.toString() + ", " + "\"_source\": " + toJSONString(dataToReturn) + ", " + "\"from\": " + startIndex + "}"; } }
29.8
88
0.644295
c23f4c230a927c931e6f821c17d3cfa074a0616b
15,494
package org.cass.importer; import com.eduworks.ec.array.EcArray; import com.eduworks.ec.array.EcAsyncHelper; import com.eduworks.ec.crypto.EcPpk; import js.Papa; import js.PapaParseParams; import org.cass.competency.EcAlignment; import org.cass.competency.EcCompetency; import org.cass.competency.EcFramework; import org.cassproject.ebac.identity.EcIdentity; import org.cassproject.ebac.identity.EcIdentityManager; import org.cassproject.ebac.repository.EcRepository; import org.cassproject.schema.cass.competency.Relation; import org.cassproject.schema.general.EcRemoteLinkedData; import org.json.ld.EcLinkedData; import org.stjs.javascript.*; import org.stjs.javascript.functions.Callback0; import org.stjs.javascript.functions.Callback1; import org.stjs.javascript.functions.Callback2; import org.stjs.javascript.functions.Callback3; import static org.stjs.javascript.JSGlobal.typeof; public class CTDLASNCSVImport { public static void analyzeFile(Object file, final Callback2<Integer, Integer> success, final Callback1<Object> failure) { if (file == null) { failure.$invoke("No file to analyze"); return; } if (JSObjectAdapter.$get(file, "name") == null) { failure.$invoke("Invalid file"); } else if (!((String) JSObjectAdapter.$get(file, "name")).endsWith(".csv")) { failure.$invoke("Invalid file type"); } Papa.parse(file, new PapaParseParams() { { encoding = "UTF-8"; complete = new Callback1<Object>() { @Override public void $invoke(Object results) { Array<Array<String>> tabularData = (Array<Array<String>>) JSObjectAdapter.$get(results, "data"); Array<String> colNames = tabularData.$get(0); Object nameToCol = new Object(); for (int i = 0; i < colNames.$length(); i++) JSObjectAdapter.$put(nameToCol, colNames.$get(i), i); int frameworkCounter = 0; int competencyCounter = 0; Integer typeCol = (Integer) JSObjectAdapter.$get(nameToCol, "@type"); if (typeCol == null) { error.$invoke("No @type in CSV."); return; } for (int i = 0; i < tabularData.$length(); i++) { if (i == 0) continue; Array<String> col = tabularData.$get(i); if (col.$get(typeCol) != null && col.$get(typeCol).trim() == "ceasn:CompetencyFramework") frameworkCounter++; else if (col.$get(typeCol) != null && col.$get(typeCol).trim() == "ceasn:Competency") competencyCounter++; else if (col.$get(typeCol) == null || col.$get(typeCol) == "") continue; else { error.$invoke("Found unknown type:" + col.$get(typeCol)); return; } } success.$invoke(frameworkCounter, competencyCounter); } }; error = failure; } }); } public static void importFrameworksAndCompetencies(final EcRepository repo, Object file, final Callback3<Array<EcFramework>, Array<EcCompetency>, Array<EcAlignment>> success, final Callback1<Object> failure, final EcIdentity ceo) { if (file == null) { failure.$invoke("No file to analyze"); return; } if (JSObjectAdapter.$get(file, "name") == null) { failure.$invoke("Invalid file"); } else if (!((String) JSObjectAdapter.$get(file, "name")).endsWith(".csv")) { failure.$invoke("Invalid file type"); } Papa.parse(file, new PapaParseParams() { { header = true; encoding = "UTF-8"; complete = new Callback1<Object>() { @Override public void $invoke(Object results) { Array<Object> tabularData = (Array<Object>) JSObjectAdapter.$get(results, "data"); final Object frameworks = new Object(); final Array frameworkArray = new Array<EcFramework>(); final Object frameworkRows = new Object(); final Array competencies = new Array<EcCompetency>(); final Object competencyRows = new Object(); final Array relations = new Array<EcAlignment>(); final Object relationById = new Object(); new EcAsyncHelper<Object>().each(tabularData, new Callback2<Object, Callback0>() { @Override public void $invoke(final Object pretranslatedE, final Callback0 callback0) { if (JSObjectAdapter.$get(pretranslatedE, "@type") == "ceasn:CompetencyFramework") { EcLinkedData translator = new EcLinkedData(null, null); translator.copyFrom(pretranslatedE); cleanUpTranslator(translator); translator.recast("https://schema.cassproject.org/0.4/ceasn2cass", "https://schema.cassproject.org/0.4", new Callback1<EcLinkedData>() { @Override public void $invoke(EcLinkedData e) { EcFramework f = new EcFramework(); f.copyFrom(e); if (JSObjectAdapter.$get(e, "owner") != null) { EcIdentity id = new EcIdentity(); id.ppk = EcPpk.fromPem((String) JSObjectAdapter.$get(e, "owner")); f.addOwner(id.ppk.toPk()); EcIdentityManager.addIdentityQuietly(id); } if (ceo != null) f.addOwner(ceo.ppk.toPk()); if (EcFramework.template != null && JSObjectAdapter.$get(EcFramework.template,("schema:dateCreated")) != null) { setDateCreated(e, f); } JSObjectAdapter.$put(frameworks, f.id, f); JSObjectAdapter.$put(frameworkRows, f.id, e); JSObjectAdapter.$put(f, "ceasn:hasChild", null); JSObjectAdapter.$put(f, "ceasn:hasTopChild", null); frameworkArray.push(f); f.competency = new Array(); f.relation = new Array(); //Delete ceasn:hasTopChild, ceasn:isChildOf, ceasn:hasChild, etc. callback0.$invoke(); } }, (Callback1) failure); } else if (JSObjectAdapter.$get(pretranslatedE, "@type") == "ceasn:Competency") { EcLinkedData translator = new EcLinkedData(null, null); translator.copyFrom(pretranslatedE); cleanUpTranslator(translator); translator.recast("https://schema.cassproject.org/0.4/ceasn2cass", "https://schema.cassproject.org/0.4", new Callback1<EcLinkedData>() { @Override public void $invoke(EcLinkedData e) { EcCompetency f = new EcCompetency(); f.copyFrom(e); if (JSObjectAdapter.$get(e, "id") == null) { callback0.$invoke(); return; } if (JSObjectAdapter.$get(e, "ceasn:isPartOf") != null) { ((EcFramework) JSObjectAdapter.$get(frameworks, (String) JSObjectAdapter.$get(e, "ceasn:isPartOf"))).competency.push(f.shortId()); } else { Object parent = e; boolean done = false; while (!done && parent != null) { if (JSObjectAdapter.$get(parent, "ceasn:isChildOf") != null && JSObjectAdapter.$get(parent, "ceasn:isChildOf") != "") { parent = JSObjectAdapter.$get(competencyRows, (String) JSObjectAdapter.$get(parent, "ceasn:isChildOf")); } else if (JSObjectAdapter.$get(parent, "ceasn:isTopChildOf") != null && JSObjectAdapter.$get(parent, "ceasn:isTopChildOf") != "") { parent = JSObjectAdapter.$get(frameworkRows, (String) JSObjectAdapter.$get(parent, "ceasn:isTopChildOf")); done = true; } } if (!done) { error.$invoke("Could not find framework:" + JSObjectAdapter.$get(e, "type")); return; } if (parent != null) { if (JSObjectAdapter.$get(parent, "type") == "Framework") { JSObjectAdapter.$put(e, "ceasn:isPartOf", (String) JSObjectAdapter.$get(parent, "id")); ((EcFramework) JSObjectAdapter.$get(frameworks, (String) JSObjectAdapter.$get(parent, "id"))).competency.push(f.shortId()); } else { error.$invoke("Object cannot trace to framework:" + JSObjectAdapter.$get(e, "type")); return; } } else { error.$invoke("Object has no framework:" + JSObjectAdapter.$get(e, "type")); return; } } if (JSObjectAdapter.$get(e, "owner") == null) { if (JSObjectAdapter.$get(JSObjectAdapter.$get(frameworkRows, (String) JSObjectAdapter.$get(e, "ceasn:isPartOf")), "owner") != null) JSObjectAdapter.$put(e, "owner", JSObjectAdapter.$get(JSObjectAdapter.$get(frameworkRows, (String) JSObjectAdapter.$get(e, "ceasn:isPartOf")), "owner")); } EcIdentity id = new EcIdentity(); if (JSObjectAdapter.$get(e, "owner") != null) { id.ppk = EcPpk.fromPem((String) JSObjectAdapter.$get(e, "owner")); if (id.ppk != null) f.addOwner(id.ppk.toPk()); EcIdentityManager.addIdentityQuietly(id); } if (ceo != null) f.addOwner(ceo.ppk.toPk()); if (EcCompetency.template != null && JSObjectAdapter.$get(EcCompetency.template,("schema:dateCreated")) != null) { setDateCreated(e, f); } //isChildOf does not have multiple values if (JSObjectAdapter.$get(e, "ceasn:isChildOf") != null) { createEachRelation(e, "ceasn:isChildOf", Relation.NARROWS, repo, ceo, id, relations, relationById, frameworks, -1); } if (JSObjectAdapter.$get(e, "ceasn:broadAlignment") != null) { createRelations(e, "ceasn:broadAlignment", Relation.NARROWS, repo, ceo, id, relations, relationById, frameworks); } if (JSObjectAdapter.$get(e, "ceasn:narrowAlignment") != null) { createRelations(e, "ceasn:narrowAlignment", Relation.NARROWS, repo, ceo, id, relations, relationById, frameworks); } if (JSObjectAdapter.$get(e, "sameAs") != null) { createRelations(e, "sameAs", Relation.IS_EQUIVALENT_TO, repo, ceo, id, relations, relationById, frameworks); } if (JSObjectAdapter.$get(e, "ceasn:majorAlignment") != null) { createRelations(e, "ceasn:majorAlignment", "majorRelated", repo, ceo, id, relations, relationById, frameworks); } if (JSObjectAdapter.$get(e, "ceasn:minorAlignment") != null) { createRelations(e, "ceasn:minorAlignment", "minorRelated", repo, ceo, id, relations, relationById, frameworks); } if (JSObjectAdapter.$get(e, "ceasn:prerequisiteAlignment") != null) { createRelations(e, "ceasn:prerequisiteAlignment", Relation.REQUIRES, repo, ceo, id, relations, relationById, frameworks); } JSObjectAdapter.$put(f, "ceasn:isTopChildOf", null); JSObjectAdapter.$put(f, "ceasn:isChildOf", null); JSObjectAdapter.$put(f, "ceasn:isPartOf", null); JSObjectAdapter.$put(f, "ceasn:broadAlignment", null); JSObjectAdapter.$put(f, "ceasn:narrowAlignment", null); //Translation of ceasn:exactAlignment JSObjectAdapter.$put(f, "sameAs", null); JSObjectAdapter.$put(f, "ceasn:majorAlignment", null); JSObjectAdapter.$put(f, "ceasn:minorAlignment", null); JSObjectAdapter.$put(f, "ceasn:prerequisiteAlignment", null); JSObjectAdapter.$put(f, "ceasn:hasChild", null); competencies.push(f); JSObjectAdapter.$put(competencyRows, f.id, e); callback0.$invoke(); } }, (Callback1) failure); } else if (JSObjectAdapter.$get(pretranslatedE, "@type") == null || JSObjectAdapter.$get(pretranslatedE, "@type") == "") {callback0.$invoke();return;} else { error.$invoke("Found unknown type:" + JSObjectAdapter.$get(pretranslatedE, "@type")); callback0.$invoke(); return; } } }, new Callback1<Array<Object>>() { @Override public void $invoke(Array<Object> strings) { success.$invoke(frameworkArray, competencies, relations); } }); } }; error = failure; } }); } static void cleanUpTranslator(EcLinkedData translator) { for (String key : JSObjectAdapter.$properties(translator)) { if (JSObjectAdapter.$get(translator, key) == "") { JSObjectAdapter.$put(translator, key, null); } else if (JSObjectAdapter.$get(translator, key) != null){ Object thisKey = JSObjectAdapter.$get(translator, key); if (typeof(thisKey) == "string") { //If it's only whitespace, remove value if (((String)JSObjectAdapter.$get(translator, key)).trim().length() == 0) { JSObjectAdapter.$put(translator, key, null); } //If multiple values, split string into an array else if (((String)thisKey).indexOf("|") != -1) { thisKey = ((String)thisKey).split("|"); JSObjectAdapter.$put(translator, key, thisKey); //Remove whitespace from piped values for (int i = 0; i < ((Array<String>)thisKey).$length(); i++) { if (((Array<String>)thisKey).$get(i) != ((Array<String>)thisKey).$get(i).trim()) { String thisVal = ((Array<String>)thisKey).$get(i).trim(); ((Array<String>)thisKey).$set(i, thisVal); } } } } //Strip whitespace from keys if (key != key.trim()) { String trimKey = key.trim(); JSObjectAdapter.$put(translator, trimKey, JSObjectAdapter.$get(translator, key)); JSObjectAdapter.$put(translator, key, null); } } } } static void createRelations(EcLinkedData e, String field, String type, EcRepository repo, EcIdentity ceo, EcIdentity id, Array relations, Object relationById, Object frameworks) { if (!EcArray.isArray(JSObjectAdapter.$get(e, field))) { Array<String> makeArray = JSGlobal.Array((String)JSObjectAdapter.$get(e, field)); JSObjectAdapter.$put(e, field, makeArray); } for (int i = 0; i < ((Array<String>)JSObjectAdapter.$get(e, field)).$length(); i++) { createEachRelation(e, field, type, repo, ceo, id, relations, relationById, frameworks, i); } } static void createEachRelation(EcLinkedData e, String field, String type, EcRepository repo, EcIdentity ceo, EcIdentity id, Array relations, Object relationById, Object frameworks, int i) { EcAlignment r = new EcAlignment(); r.generateId(repo.selectedServer); if (ceo != null) r.addOwner(ceo.ppk.toPk()); if (id.ppk != null) r.addOwner(id.ppk.toPk()); r.relationType = type; if (field == "ceasn:narrowAlignment") { r.source = ((Array<String>)JSObjectAdapter.$get(e, field)).$get(i); r.target = (String) JSObjectAdapter.$get(e, "id"); } else { r.source = (String) JSObjectAdapter.$get(e, "id"); if (i != -1) { r.target = ((Array<String>) JSObjectAdapter.$get(e, field)).$get(i); } //i = -1 if field is not an array else { r.target = ((String) JSObjectAdapter.$get(e, field)); } } relations.push(r); JSObjectAdapter.$put(relationById, r.shortId(), r); ((EcFramework) JSObjectAdapter.$get(frameworks, (String) JSObjectAdapter.$get(e, "ceasn:isPartOf"))).relation.push(r.shortId()); } public static void setDateCreated(EcLinkedData importObject, EcRemoteLinkedData object) { if (JSObjectAdapter.$get(importObject, "ceasn:dateCreated") == null && JSObjectAdapter.$get(importObject, "schema:dateCreated") == null) { Integer timestamp = object.getTimestamp(); String date; if (timestamp != null) { date = new Date(JSGlobal.parseInt(timestamp)).toISOString(); } else { date = new Date().toISOString(); } JSObjectAdapter.$put(object, "schema:dateCreated", date); } } }
43.158774
232
0.624048
9134e3397f547bf1863d2a9902512cb43ccb89c8
3,296
package de.grundid.fritz; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.xml.bind.DatatypeConverter; import org.springframework.http.converter.FormHttpMessageConverter; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import de.grundid.fritz.entity.SessionInfo; public class FritzTemplate { private static final String EMPTY_SESSION_ID = "0000000000000000"; private String baseUrl = "http://fritz.box"; private RestTemplate restOperations; private String sessionId; private String password; public FritzTemplate(RestTemplate restOperations, String password) { this.restOperations = restOperations; this.password = password; restOperations.getMessageConverters().add(new FormHttpMessageConverter()); } protected String createChallengeResponse(String challenge, String password) { try { byte[] text = (challenge + "-" + password).getBytes(Charset.forName("utf-16le")); byte[] digest = MessageDigest.getInstance("md5").digest(text); return challenge + "-" + DatatypeConverter.printHexBinary(digest).toLowerCase(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } private MultiValueMap<String, String> prepareRequest() { if (sessionId == null) getSessionId(); MultiValueMap<String, String> request = new LinkedMultiValueMap<String, String>(); return request; } public String getSessionId() { SessionInfo sessionInfo = restOperations.getForObject(baseUrl + "/login_sid.lua", SessionInfo.class); if (sessionInfo.getSid().equals(EMPTY_SESSION_ID)) { String response = createChallengeResponse(sessionInfo.getChallenge(), password); MultiValueMap<String, String> request = new LinkedMultiValueMap<String, String>(); request.add("page", ""); request.add("username", ""); request.add("response", response); sessionInfo = restOperations.postForObject(baseUrl + "/login_sid.lua", request, SessionInfo.class); if (sessionInfo.getSid().equals(EMPTY_SESSION_ID)) throw new CannotLoginException(); } sessionId = sessionInfo.getSid(); return sessionId; } public void activateGuestAccess(String guestSsid, String wpaKey) { activateGuestAccess(guestSsid, wpaKey, null); } public void activateGuestAccess(String guestSsid, String wpaKey, GuestAccessSettings settings) { MultiValueMap<String, String> request = prepareRequest(); request.add("activate_guest_access", "on"); request.add("guest_ssid", guestSsid); request.add("wlan_security", "0"); request.add("wpa_key", wpaKey); request.add("wpa_modus", "4"); request.add("btnSave", ""); if (settings != null) { if (settings.hasTimeout()) { request.add("down_time_activ", "on"); request.add("down_time_value", "" + settings.getDisableAfterTime().getMinutes()); } } restOperations.postForEntity(baseUrl + "/wlan/guest_access.lua?sid={sid}", request, String.class, sessionId); } public void deactivateGuestAccess() { MultiValueMap<String, String> request = prepareRequest(); request.add("btnSave", ""); restOperations.postForEntity(baseUrl + "/wlan/guest_access.lua?sid={sid}", request, String.class, sessionId); } }
36.21978
111
0.752124
60e9e21f6b54855218b29cb580239ed8b2b578e5
1,986
/* * Copyright 2017 Chris2011. * * 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.chrisle.netbeans.plugins.nbscratchfile.servicenode; import java.io.File; import java.util.Arrays; import java.util.List; import org.openide.filesystems.FileUtil; import org.openide.loaders.DataObject; import org.openide.loaders.DataObjectNotFoundException; import org.openide.nodes.AbstractNode; import org.openide.nodes.ChildFactory; import org.openide.nodes.Children; import org.openide.nodes.Node; import org.openide.util.lookup.Lookups; /** * * @author Chris2011 */ public class ScratchFileNodeChildFactory extends ChildFactory<File> { private final File scratchDir; public ScratchFileNodeChildFactory(File scratchDir) { this.scratchDir = scratchDir; } @Override protected boolean createKeys(List<File> list) { list.addAll(Arrays.asList(new File(this.scratchDir.getPath()).listFiles())); return true; } @Override protected Node createNodeForKey(File key) { Node result; try { DataObject dataObject = DataObject.find(FileUtil.toFileObject(key)); result = dataObject.getNodeDelegate(); result.setDisplayName(key.getName()); } catch (DataObjectNotFoundException ex) { result = new AbstractNode(Children.LEAF, Lookups.singleton(key)); } return result; } }
31.03125
85
0.694864
3a0e14401caf613acec0b411d158cf115cb1619b
7,313
/* * 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.giraph.utils; import org.apache.giraph.bsp.CentralizedServiceWorker; import org.apache.giraph.comm.ServerData; import org.apache.giraph.comm.WorkerClientRequestProcessor; import org.apache.giraph.comm.messages.ByteArrayMessagesPerVertexStore; import org.apache.giraph.conf.GiraphConfiguration; import org.apache.giraph.conf.ImmutableClassesGiraphConfiguration; import org.apache.giraph.graph.GraphState; import org.apache.giraph.partition.BasicPartitionOwner; import org.apache.giraph.partition.PartitionOwner; import org.apache.giraph.edge.ArrayListEdges; import org.apache.giraph.edge.ConfigurableVertexEdges; import org.apache.giraph.graph.Vertex; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapreduce.Mapper; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; /** simplify mocking for unit testing vertices */ public class MockUtils { private MockUtils() { } /** * mocks and holds "environment objects" that are injected into a vertex * * @param <I> vertex id * @param <V> vertex data * @param <E> edge data * @param <M> message data */ public static class MockedEnvironment<I extends WritableComparable, V extends Writable, E extends Writable, M extends Writable> { private final GraphState<I, V, E, M> graphState; private final Mapper.Context context; private final Configuration conf; private final WorkerClientRequestProcessor workerClientRequestProcessor; public MockedEnvironment() { graphState = Mockito.mock(GraphState.class); context = Mockito.mock(Mapper.Context.class); conf = Mockito.mock(Configuration.class); workerClientRequestProcessor = Mockito.mock(WorkerClientRequestProcessor.class); } /** the injected graph state */ public GraphState getGraphState() { return graphState; } /** the injected mapper context */ public Mapper.Context getContext() { return context; } /** the injected hadoop configuration */ public Configuration getConfiguration() { return conf; } /** the injected worker communications */ public WorkerClientRequestProcessor getWorkerClientRequestProcessor() { return workerClientRequestProcessor; } /** assert that the test vertex message has been sent to a particular vertex */ public void verifyMessageSent(I targetVertexId, M message) { Mockito.verify(workerClientRequestProcessor).sendMessageRequest (targetVertexId, message); } /** assert that the test vertex has sent no message to a particular vertex */ public void verifyNoMessageSent() { Mockito.verifyZeroInteractions(workerClientRequestProcessor); } } /** * prepare a vertex for use in a unit test by setting its internal state and injecting mocked * dependencies, * * @param vertex * @param superstep the superstep to emulate * @param vertexId initial vertex id * @param vertexValue initial vertex value * @param isHalted initial halted state of the vertex * @param <I> vertex id * @param <V> vertex data * @param <E> edge data * @param <M> message data * @return * @throws Exception */ public static <I extends WritableComparable, V extends Writable, E extends Writable, M extends Writable> MockedEnvironment<I, V, E, M> prepareVertex( Vertex<I, V, E, M> vertex, long superstep, I vertexId, V vertexValue, boolean isHalted) throws Exception { MockedEnvironment<I, V, E, M> env = new MockedEnvironment<I, V, E, M>(); Mockito.when(env.getGraphState().getSuperstep()).thenReturn(superstep); Mockito.when(env.getGraphState().getContext()) .thenReturn(env.getContext()); Mockito.when(env.getContext().getConfiguration()) .thenReturn(env.getConfiguration()); Mockito.when(env.getGraphState().getWorkerClientRequestProcessor()) .thenReturn(env.getWorkerClientRequestProcessor()); GiraphConfiguration giraphConf = new GiraphConfiguration(); giraphConf.setVertexClass(vertex.getClass()); ImmutableClassesGiraphConfiguration<I, V, E, M> conf = new ImmutableClassesGiraphConfiguration<I, V, E, M>(giraphConf); vertex.setConf(conf); ConfigurableVertexEdges<I, E> edges = new ArrayListEdges<I, E>(); edges.setConf(conf); edges.initialize(); ReflectionUtils.setField(vertex, "id", vertexId); ReflectionUtils.setField(vertex, "value", vertexValue); ReflectionUtils.setField(vertex, "edges", edges); ReflectionUtils.setField(vertex, "graphState", env.getGraphState()); ReflectionUtils.setField(vertex, "halt", isHalted); return env; } public static CentralizedServiceWorker<IntWritable, IntWritable, IntWritable, IntWritable> mockServiceGetVertexPartitionOwner(final int numOfPartitions) { CentralizedServiceWorker<IntWritable, IntWritable, IntWritable, IntWritable> service = Mockito.mock(CentralizedServiceWorker.class); Answer<PartitionOwner> answer = new Answer<PartitionOwner>() { @Override public PartitionOwner answer(InvocationOnMock invocation) throws Throwable { IntWritable vertexId = (IntWritable) invocation.getArguments()[0]; return new BasicPartitionOwner(vertexId.get() % numOfPartitions, null); } }; Mockito.when(service.getVertexPartitionOwner( Mockito.any(IntWritable.class))).thenAnswer(answer); return service; } public static ServerData<IntWritable, IntWritable, IntWritable, IntWritable> createNewServerData(ImmutableClassesGiraphConfiguration conf, Mapper.Context context) { return new ServerData<IntWritable, IntWritable, IntWritable, IntWritable>( Mockito.mock(CentralizedServiceWorker.class), conf, ByteArrayMessagesPerVertexStore.newFactory( MockUtils.mockServiceGetVertexPartitionOwner(1), conf), context); } }
39.744565
97
0.696021
3de10e0a18969daea2d653365b3cf82a468ef825
434
package com.superhao.spring.cloud.config.client1; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan public class SpringConfigClient1Application { public static void main(String[] args) { SpringApplication.run(SpringConfigClient1Application.class, args); } }
28.933333
68
0.845622
4f6ea3b413476be0293b75df8d45d6a85f28187a
1,111
package com.tuowazi.demo.binary_tree.threadedBinaryTree; /** * User:zhangweixiao * Description: */ public class ThreadedTreeNode<T> { private ThreadedTreeNode lchild; private ThreadedTreeNode rchild; private T data; private boolean isLThread; private boolean isRThread; public ThreadedTreeNode(T data) { this.data=data; } public ThreadedTreeNode getLchild() { return lchild; } public void setLchild(ThreadedTreeNode lchild) { this.lchild = lchild; } public ThreadedTreeNode getRchild() { return rchild; } public void setRchild(ThreadedTreeNode rchild) { this.rchild = rchild; } public T getData() { return data; } public void setData(T data) { this.data = data; } public boolean isLThread() { return isLThread; } public void setLThread(boolean LThread) { isLThread = LThread; } public boolean isRThread() { return isRThread; } public void setRThread(boolean RThread) { isRThread = RThread; } }
18.213115
56
0.622862
4d8e893aafb246b5be69216cadd6cc1ba446815d
5,684
package misskey4j.entity; import java.util.List; /** * ユーザーオブジェクト */ public class User { private String id; private String username; private String name; private String url; private String avatarUrl; private Color avatarColor; private String bannerUrl; private Color bannerColor; private String host; private String description; private String birthday; private String createdAt; private String updatedAt; private String location; private Long followersCount; private Long followingCount; private Long notesCount; private List<String> pinnedNoteIds; private List<Note> pinnedNotes; private Boolean isBot; private Boolean isCat; private Boolean isAdmin; private Boolean isModerator; private Boolean isLocked; private Boolean hasUnreadSpecifiedNotes; private Boolean hasUnreadMentions; private List<Emoji> emojis; private List<Field> fields; // region public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getAvatarUrl() { return avatarUrl; } public void setAvatarUrl(String avatarUrl) { this.avatarUrl = avatarUrl; } public Color getAvatarColor() { return avatarColor; } public void setAvatarColor(Color avatarColor) { this.avatarColor = avatarColor; } public String getBannerUrl() { return bannerUrl; } public void setBannerUrl(String bannerUrl) { this.bannerUrl = bannerUrl; } public Color getBannerColor() { return bannerColor; } public void setBannerColor(Color bannerColor) { this.bannerColor = bannerColor; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getCreatedAt() { return createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public String getUpdatedAt() { return updatedAt; } public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public Long getFollowersCount() { return followersCount; } public void setFollowersCount(Long followersCount) { this.followersCount = followersCount; } public Long getFollowingCount() { return followingCount; } public void setFollowingCount(Long followingCount) { this.followingCount = followingCount; } public Long getNotesCount() { return notesCount; } public void setNotesCount(Long notesCount) { this.notesCount = notesCount; } public List<String> getPinnedNoteIds() { return pinnedNoteIds; } public void setPinnedNoteIds(List<String> pinnedNoteIds) { this.pinnedNoteIds = pinnedNoteIds; } public List<Note> getPinnedNotes() { return pinnedNotes; } public void setPinnedNotes(List<Note> pinnedNotes) { this.pinnedNotes = pinnedNotes; } public Boolean getBot() { return isBot != null ? isBot : false; } public void setBot(Boolean bot) { isBot = bot; } public Boolean getCat() { return isCat != null ? isCat : false; } public void setCat(Boolean cat) { isCat = cat; } public Boolean getAdmin() { return isAdmin != null ? isAdmin : false; } public void setAdmin(Boolean admin) { isAdmin = admin; } public Boolean getModerator() { return isModerator != null ? isModerator : false; } public void setModerator(Boolean moderator) { isModerator = moderator; } public Boolean getLocked() { return isLocked != null ? isLocked : false; } public void setLocked(Boolean locked) { isLocked = locked; } public Boolean getHasUnreadSpecifiedNotes() { return hasUnreadSpecifiedNotes != null ? hasUnreadSpecifiedNotes : false; } public void setHasUnreadSpecifiedNotes(Boolean hasUnreadSpecifiedNotes) { this.hasUnreadSpecifiedNotes = hasUnreadSpecifiedNotes; } public Boolean getHasUnreadMentions() { return hasUnreadMentions != null ? hasUnreadMentions : false; } public void setHasUnreadMentions(Boolean hasUnreadMentions) { this.hasUnreadMentions = hasUnreadMentions; } public List<Emoji> getEmojis() { return emojis; } public void setEmojis(List<Emoji> emojis) { this.emojis = emojis; } public List<Field> getFields() { return fields; } public void setFields(List<Field> fields) { this.fields = fields; } // endregion }
20.820513
81
0.629838
b91d15eaf81fa9a9623884da6d8b9a4ec2e05f20
1,934
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2011 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ package com.zimbra.soap.admin.message; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import java.util.Collections; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.zimbra.common.soap.AccountConstants; import com.zimbra.common.soap.AdminConstants; import com.zimbra.soap.admin.type.DataSourceInfo; @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name=AdminConstants.E_GET_DATA_SOURCES_RESPONSE) public class GetDataSourcesResponse { /** * @zm-api-field-description Information on data sources */ @XmlElement(name=AccountConstants.E_DATA_SOURCE, required=false) private List<DataSourceInfo> dataSources = Lists.newArrayList(); public GetDataSourcesResponse() { } public void setDataSources(Iterable <DataSourceInfo> dataSources) { this.dataSources.clear(); if (dataSources != null) { Iterables.addAll(this.dataSources,dataSources); } } public GetDataSourcesResponse addDataSource(DataSourceInfo dataSource) { this.dataSources.add(dataSource); return this; } public List<DataSourceInfo> getDataSources() { return Collections.unmodifiableList(dataSources); } }
31.193548
76
0.736815
76bc831bc9412c2dcb660cfc6e223fce8848d203
12,634
package de.blackforestsolutions.dravelopsconfigbackend; import com.fasterxml.jackson.core.JsonProcessingException; import de.blackforestsolutions.dravelopsconfigbackend.objectmothers.GitHubFileRequestObjectMother; import de.blackforestsolutions.dravelopsconfigbackend.service.communicationservice.restcalls.CallService; import de.blackforestsolutions.dravelopsconfigbackend.service.supportservice.GitHubHttpCallBuilderService; import de.blackforestsolutions.dravelopsdatamodel.ApiToken; import de.blackforestsolutions.dravelopsdatamodel.util.DravelOpsHttpCallBuilder; import de.blackforestsolutions.dravelopsdatamodel.util.DravelOpsJsonMapper; import de.blackforestsolutions.dravelopsgeneratedcontent.github.GitHubFileRequest; import de.blackforestsolutions.dravelopsgeneratedcontent.github.GitHubFileResponse; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.ResourceAccessException; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class GitHubCallServiceIT{ @Autowired private CallService classUnderTest; @Autowired private GitHubHttpCallBuilderService callBuilderService; @Autowired private ApiToken gitHubConfigApiToken; @Test void test_get_with_correct_variables_succeeds_request() throws JsonProcessingException { DravelOpsJsonMapper mapper = new DravelOpsJsonMapper(); ApiToken testApiToken = new ApiToken(gitHubConfigApiToken); String testPath = callBuilderService.buildGitHubPathWith(testApiToken); testApiToken.setPath(testPath); String testUrl = DravelOpsHttpCallBuilder.buildUrlWith(testApiToken).toString(); HttpHeaders headers = callBuilderService.buildGitHubHttpHeaderWith(testApiToken); HttpEntity<?> getHttpEntity = new HttpEntity<>(headers); ResponseEntity<String> result = classUnderTest.get(testUrl, getHttpEntity); assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(result.getBody()).isNotEmpty(); assertThat(mapper.readValue(result.getBody(), GitHubFileResponse.class)).isInstanceOf(GitHubFileResponse.class); assertThat(mapper.readValue(result.getBody(), GitHubFileResponse.class).getContent()).isNotEmpty(); assertThat(mapper.readValue(result.getBody(), GitHubFileResponse.class).getSha()).isNotEmpty(); assertThat(mapper.readValue(result.getBody(), GitHubFileResponse.class).getPath()).isEqualTo(testApiToken.getFilepath()); } @Test void test_get_with_incorrect_api_token_path_throws_ResourceAccessException() { ApiToken testApiToken = new ApiToken(gitHubConfigApiToken); testApiToken.setPath("wrong path"); String testUrl = DravelOpsHttpCallBuilder.buildUrlWith(testApiToken).toString(); HttpHeaders headers = callBuilderService.buildGitHubHttpHeaderWith(testApiToken); HttpEntity<?> getHttpEntity = new HttpEntity<>(headers); assertThrows(ResourceAccessException.class, () -> classUnderTest.get(testUrl, getHttpEntity)); } @Test void test_get_with_incorrect_api_token_repository_throws_HttpClientErrorException_NotFound() { ApiToken testApiToken = new ApiToken(gitHubConfigApiToken); testApiToken.setRepository("wrong/repository"); String testPath = callBuilderService.buildGitHubPathWith(testApiToken); testApiToken.setPath(testPath); String testUrl = DravelOpsHttpCallBuilder.buildUrlWith(testApiToken).toString(); HttpHeaders headers = callBuilderService.buildGitHubHttpHeaderWith(testApiToken); HttpEntity<?> getHttpEntity = new HttpEntity<>(headers); assertThrows(HttpClientErrorException.NotFound.class, () -> classUnderTest.get(testUrl, getHttpEntity)); } @Test void test_get_with_incorrect_api_token_password_throws_HttpClientErrorException_NotFound() { ApiToken testApiToken = new ApiToken(gitHubConfigApiToken); testApiToken.setPassword("wrongPasswordToken"); String testPath = callBuilderService.buildGitHubPathWith(testApiToken); testApiToken.setPath(testPath); String testUrl = DravelOpsHttpCallBuilder.buildUrlWith(testApiToken).toString(); HttpHeaders headers = callBuilderService.buildGitHubHttpHeaderWith(testApiToken); HttpEntity<?> getHttpEntity = new HttpEntity<>(headers); assertThrows(HttpClientErrorException.NotFound.class, () -> classUnderTest.get(testUrl, getHttpEntity)); } @Test void test_get_with_incorrect_api_token_host_throws_ResourceAccessException() { ApiToken testApiToken = new ApiToken(gitHubConfigApiToken); testApiToken.setHost("wrongHost"); String testPath = callBuilderService.buildGitHubPathWith(testApiToken); testApiToken.setPath(testPath); String testUrl = DravelOpsHttpCallBuilder.buildUrlWith(testApiToken).toString(); HttpHeaders headers = callBuilderService.buildGitHubHttpHeaderWith(testApiToken); HttpEntity<?> getHttpEntity = new HttpEntity<>(headers); assertThrows(ResourceAccessException.class, () -> classUnderTest.get(testUrl, getHttpEntity)); } @Test void test_get_without_requestEntity_throws_HttpClientErrorException_NotFound() { ApiToken testApiToken = new ApiToken(gitHubConfigApiToken); String testPath = callBuilderService.buildGitHubPathWith(testApiToken); testApiToken.setPath(testPath); String testUrl = DravelOpsHttpCallBuilder.buildUrlWith(testApiToken).toString(); assertThrows(HttpClientErrorException.NotFound.class, () -> classUnderTest.get(testUrl, null)); } @Test void test_get_without_url_throws_ResourceAccessException() { ApiToken testApiToken = new ApiToken(gitHubConfigApiToken); String testPath = callBuilderService.buildGitHubPathWith(testApiToken); testApiToken.setPath(testPath); HttpHeaders headers = callBuilderService.buildGitHubHttpHeaderWith(testApiToken); HttpEntity<?> getHttpEntity = new HttpEntity<>(headers); assertThrows(ResourceAccessException.class, () -> classUnderTest.get(null, getHttpEntity)); } @Test void test_get_without_url_and_requestEntity_throws_ResourceAccessException() { assertThrows(ResourceAccessException.class, () -> classUnderTest.get(null, null)); } @Test void test_get_with_empty_HttpHeaders_throws_HttpClientErrorException_NotFound() { ApiToken testApiToken = new ApiToken(gitHubConfigApiToken); String testPath = callBuilderService.buildGitHubPathWith(testApiToken); testApiToken.setPath(testPath); String testUrl = DravelOpsHttpCallBuilder.buildUrlWith(testApiToken).toString(); HttpEntity<?> getHttpEntity = new HttpEntity<>(null); assertThrows(HttpClientErrorException.NotFound.class, () -> classUnderTest.get(testUrl, getHttpEntity)); } @Test void test_getGraphQlApiConfig_from_gitHub_with_correct_api_token_succeeds_request() throws JsonProcessingException { ApiToken testApiToken = new ApiToken(gitHubConfigApiToken); String testPath = callBuilderService.buildGitHubPathWith(testApiToken); testApiToken.setPath(testPath); String testUrl = DravelOpsHttpCallBuilder.buildUrlWith(testApiToken).toString(); HttpHeaders headers = callBuilderService.buildGitHubHttpHeaderWith(testApiToken); HttpEntity<?> getHttpEntity = new HttpEntity<>(headers); ResponseEntity<String> getResult = classUnderTest.get(testUrl, getHttpEntity); DravelOpsJsonMapper mapper = new DravelOpsJsonMapper(); String currentSha = mapper.readValue(getResult.getBody(), GitHubFileResponse.class).getSha(); GitHubFileRequest gitHubFileRequest = GitHubFileRequestObjectMother.getCorrectGitHubFileRequest(); gitHubFileRequest.setSha(currentSha); HttpEntity<?> putHttpEntity = new HttpEntity<>(gitHubFileRequest, headers); ResponseEntity<String> putResult = classUnderTest.put(testUrl, putHttpEntity); assertThat(putResult.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(putResult.getBody()).isNotEmpty(); } @Test void test_getGraphQlApiConfig_from_gitHub_with_incorrect_api_token_password_throws_HttpClientErrorException$NotFound() { ApiToken testApiToken = new ApiToken(gitHubConfigApiToken); testApiToken.setPassword("wrongPassword"); String testPath = callBuilderService.buildGitHubPathWith(testApiToken); testApiToken.setPath(testPath); String testUrl = DravelOpsHttpCallBuilder.buildUrlWith(testApiToken).toString(); HttpHeaders headers = callBuilderService.buildGitHubHttpHeaderWith(testApiToken); GitHubFileRequest request = GitHubFileRequestObjectMother.getCorrectGitHubFileRequest(); HttpEntity<?> putHttpEntity = new HttpEntity<>(request, headers); assertThrows(HttpClientErrorException.NotFound.class, () -> classUnderTest.put(testUrl, putHttpEntity)); } @Test void test_getGraphQlApiConfig_from_gitHub_with_incorrect_api_token_path_throws_HttpClientErrorException$Conflict() { ApiToken testApiToken = new ApiToken(gitHubConfigApiToken); testApiToken.setPath("Wrong/Path"); String testPath = callBuilderService.buildGitHubPathWith(testApiToken); testApiToken.setPath(testPath); String testUrl = DravelOpsHttpCallBuilder.buildUrlWith(testApiToken).toString(); HttpHeaders headers = callBuilderService.buildGitHubHttpHeaderWith(testApiToken); GitHubFileRequest gitHubFileRequest = GitHubFileRequestObjectMother.getCorrectGitHubFileRequest(); HttpEntity<?> putHttpEntity = new HttpEntity<>(gitHubFileRequest, headers); assertThrows(HttpClientErrorException.Conflict.class, () -> classUnderTest.put(testUrl, putHttpEntity)); } @Test void test_getGraphQlApiConfig_from_gitHub_with_incorrect_api_token_sha_throws_HttpClientErrorException$Conflict() { ApiToken testApiToken = new ApiToken(gitHubConfigApiToken); String testPath = callBuilderService.buildGitHubPathWith(testApiToken); testApiToken.setPath(testPath); String testUrl = DravelOpsHttpCallBuilder.buildUrlWith(testApiToken).toString(); HttpHeaders headers = callBuilderService.buildGitHubHttpHeaderWith(testApiToken); GitHubFileRequest gitHubFileRequest = GitHubFileRequestObjectMother.getCorrectGitHubFileRequest(); gitHubFileRequest.setSha("wrongSha"); HttpEntity<?> testHttpEntity = new HttpEntity<>(gitHubFileRequest, headers); assertThrows(HttpClientErrorException.Conflict.class, () -> classUnderTest.put(testUrl, testHttpEntity)); } @Test void test_getGraphQlApiConfig_from_gitHub_with_missing_body_throws_HttpClientErrorException$BadRequest() { ApiToken testApiToken = new ApiToken(gitHubConfigApiToken); String testPath = callBuilderService.buildGitHubPathWith(testApiToken); testApiToken.setPath(testPath); String testUrl = DravelOpsHttpCallBuilder.buildUrlWith(testApiToken).toString(); HttpHeaders headers = callBuilderService.buildGitHubHttpHeaderWith(testApiToken); HttpEntity<?> testHttpEntity = new HttpEntity<>(headers); assertThrows(HttpClientErrorException.BadRequest.class, () -> classUnderTest.put(testUrl, testHttpEntity)); } @Test void test_getGraphQlApiConfig_from_gitHub_with_missing_HttpHeaders_throws_HttpClientErrorException$NotFound() { ApiToken testApiToken = new ApiToken(gitHubConfigApiToken); String testPath = callBuilderService.buildGitHubPathWith(testApiToken); testApiToken.setPath(testPath); String testUrl = DravelOpsHttpCallBuilder.buildUrlWith(testApiToken).toString(); HttpEntity<?> testHttpEntity = new HttpEntity<>(null); assertThrows(HttpClientErrorException.NotFound.class, () -> classUnderTest.put(testUrl, testHttpEntity)); } }
53.761702
129
0.775685
abc00944a5ada7e5bfb4c157907cf7e2ebaa1fd7
1,384
package com.github.hoqhuuep.islandcraft.api; /** * Represents a location in a world. */ public class ICLocation { private final int x; private final int z; /** * Creates an immutable ICLocation. * * @param x * x-coordinate of this location (measured in blocks) * @param z * z-coordinate of this location (measured in blocks) */ public ICLocation(final int x, final int z) { this.x = x; this.z = z; } /** * Returns the x-coordinate of this location (measured in blocks). */ public int getX() { return x; } /** * Returns the z-coordinate of this location (measured in blocks). */ public int getZ() { return z; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + z; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ICLocation other = (ICLocation) obj; if (x != other.x) return false; if (z != other.z) return false; return true; } }
22.322581
70
0.520954
69732d357cc1803c1233b41639fc7327e8e02369
2,610
/* * 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.syncope.core.rest.controller; import javassist.NotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.syncope.client.to.WorkflowDefinitionTO; import org.syncope.core.workflow.UserWorkflowAdapter; import org.syncope.core.workflow.WorkflowException; @Controller @RequestMapping("/workflow") public class WorkflowController extends AbstractController { @Autowired private UserWorkflowAdapter wfAdapter; @PreAuthorize("hasRole('WORKFLOW_DEF_READ')") @RequestMapping(method = RequestMethod.GET, value = "/definition") @Transactional(readOnly = true) public WorkflowDefinitionTO getDefinition() throws WorkflowException { return wfAdapter.getDefinition(); } @PreAuthorize("hasRole('WORKFLOW_DEF_UPDATE')") @RequestMapping(method = RequestMethod.PUT, value = "/definition") public void updateDefinition( @RequestBody final WorkflowDefinitionTO definition) throws NotFoundException, WorkflowException { wfAdapter.updateDefinition(definition); } @PreAuthorize("hasRole('WORKFLOW_TASK_LIST')") @RequestMapping(method = RequestMethod.GET, value = "/tasks") public ModelAndView getDefinedTasks() throws WorkflowException { return new ModelAndView().addObject(wfAdapter.getDefinedTasks()); } }
37.285714
73
0.763218
2cfc416a504605ce3d55af4852bd9e44b459e90f
1,591
package neureka.backend.standard.operations.operator; import neureka.backend.api.operations.AbstractOperation; import neureka.backend.api.operations.OperationBuilder; import neureka.calculus.Function; public class DivisionRightConv extends AbstractOperation { public DivisionRightConv() { super( new OperationBuilder() .setFunction( "div_conv_right" ) .setOperator( "d" + ((char) 187) ) .setArity( 3 ) .setIsOperator( true ) .setIsIndexer( false ) .setIsDifferentiable( true ) .setIsInline( false ) ); } @Override public String stringify(String[] children) { StringBuilder reconstructed = new StringBuilder(); for ( int i = 0; i < children.length; ++i ) { reconstructed.append( children[ i ] ); if ( i < children.length - 1 ) { reconstructed.append(" d" + ((char) 187)+" "); } } return "(" + reconstructed + ")"; } @Override public String asDerivative(Function[] children, int derivationIndex) { throw new IllegalStateException("Operation does not support dynamic derivation!"); } @Override public double calculate( double[] inputs, int j, int d, Function[] src ) { return src[ 0 ].call( inputs, j ); } }
35.355556
90
0.513514