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
1e0a2e5a51aa67088e95781cf786017104c2580a
18,022
/** * 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.camel.processor; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.camel.AsyncCallback; import org.apache.camel.AsyncProcessor; import org.apache.camel.CamelContext; import org.apache.camel.CamelExchangeException; import org.apache.camel.Exchange; import org.apache.camel.Expression; import org.apache.camel.Navigate; import org.apache.camel.Predicate; import org.apache.camel.Processor; import org.apache.camel.spi.ExceptionHandler; import org.apache.camel.spi.IdAware; import org.apache.camel.support.LoggingExceptionHandler; import org.apache.camel.support.ServiceSupport; import org.apache.camel.util.AsyncProcessorHelper; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.ServiceHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A base class for any kind of {@link Processor} which implements some kind of batch processing. * * @version * @deprecated may be removed in the future when we overhaul the resequencer EIP */ @Deprecated public class BatchProcessor extends ServiceSupport implements AsyncProcessor, Navigate<Processor>, IdAware { public static final long DEFAULT_BATCH_TIMEOUT = 1000L; public static final int DEFAULT_BATCH_SIZE = 100; private static final Logger LOG = LoggerFactory.getLogger(BatchProcessor.class); private String id; private long batchTimeout = DEFAULT_BATCH_TIMEOUT; private int batchSize = DEFAULT_BATCH_SIZE; private int outBatchSize; private boolean groupExchanges; private boolean batchConsumer; private boolean ignoreInvalidExchanges; private boolean reverse; private boolean allowDuplicates; private Predicate completionPredicate; private Expression expression; private final CamelContext camelContext; private final Processor processor; private final Collection<Exchange> collection; private ExceptionHandler exceptionHandler; private final BatchSender sender; public BatchProcessor(CamelContext camelContext, Processor processor, Collection<Exchange> collection, Expression expression) { ObjectHelper.notNull(camelContext, "camelContext"); ObjectHelper.notNull(processor, "processor"); ObjectHelper.notNull(collection, "collection"); ObjectHelper.notNull(expression, "expression"); // wrap processor in UnitOfWork so what we send out of the batch runs in a UoW this.camelContext = camelContext; this.processor = processor; this.collection = collection; this.expression = expression; this.sender = new BatchSender(); this.exceptionHandler = new LoggingExceptionHandler(camelContext, getClass()); } @Override public String toString() { return "BatchProcessor[to: " + processor + "]"; } // Properties // ------------------------------------------------------------------------- public Expression getExpression() { return expression; } public ExceptionHandler getExceptionHandler() { return exceptionHandler; } public void setExceptionHandler(ExceptionHandler exceptionHandler) { this.exceptionHandler = exceptionHandler; } public int getBatchSize() { return batchSize; } /** * Sets the <b>in</b> batch size. This is the number of incoming exchanges that this batch processor will * process before its completed. The default value is {@link #DEFAULT_BATCH_SIZE}. * * @param batchSize the size */ public void setBatchSize(int batchSize) { // setting batch size to 0 or negative is like disabling it, so we set it as the max value // as the code logic is dependent on a batch size having 1..n value if (batchSize <= 0) { LOG.debug("Disabling batch size, will only be triggered by timeout"); this.batchSize = Integer.MAX_VALUE; } else { this.batchSize = batchSize; } } public int getOutBatchSize() { return outBatchSize; } /** * Sets the <b>out</b> batch size. If the batch processor holds more exchanges than this out size then the * completion is triggered. Can for instance be used to ensure that this batch is completed when a certain * number of exchanges has been collected. By default this feature is <b>not</b> enabled. * * @param outBatchSize the size */ public void setOutBatchSize(int outBatchSize) { this.outBatchSize = outBatchSize; } public long getBatchTimeout() { return batchTimeout; } public void setBatchTimeout(long batchTimeout) { this.batchTimeout = batchTimeout; } public boolean isGroupExchanges() { return groupExchanges; } public void setGroupExchanges(boolean groupExchanges) { this.groupExchanges = groupExchanges; } public boolean isBatchConsumer() { return batchConsumer; } public void setBatchConsumer(boolean batchConsumer) { this.batchConsumer = batchConsumer; } public boolean isIgnoreInvalidExchanges() { return ignoreInvalidExchanges; } public void setIgnoreInvalidExchanges(boolean ignoreInvalidExchanges) { this.ignoreInvalidExchanges = ignoreInvalidExchanges; } public boolean isReverse() { return reverse; } public void setReverse(boolean reverse) { this.reverse = reverse; } public boolean isAllowDuplicates() { return allowDuplicates; } public void setAllowDuplicates(boolean allowDuplicates) { this.allowDuplicates = allowDuplicates; } public Predicate getCompletionPredicate() { return completionPredicate; } public void setCompletionPredicate(Predicate completionPredicate) { this.completionPredicate = completionPredicate; } public Processor getProcessor() { return processor; } public List<Processor> next() { if (!hasNext()) { return null; } List<Processor> answer = new ArrayList<>(1); answer.add(processor); return answer; } public boolean hasNext() { return processor != null; } public String getId() { return id; } public void setId(String id) { this.id = id; } /** * A strategy method to decide if the "in" batch is completed. That is, whether the resulting exchanges in * the in queue should be drained to the "out" collection. */ private boolean isInBatchCompleted(int num) { return num >= batchSize; } /** * A strategy method to decide if the "out" batch is completed. That is, whether the resulting exchange in * the out collection should be sent. */ private boolean isOutBatchCompleted() { if (outBatchSize == 0) { // out batch is disabled, so go ahead and send. return true; } return collection.size() > 0 && collection.size() >= outBatchSize; } /** * Strategy Method to process an exchange in the batch. This method allows derived classes to perform * custom processing before or after an individual exchange is processed */ protected void processExchange(Exchange exchange) throws Exception { processor.process(exchange); if (exchange.getException() != null) { getExceptionHandler().handleException("Error processing aggregated exchange: " + exchange, exchange.getException()); } } protected void doStart() throws Exception { ServiceHelper.startServices(processor); sender.start(); } protected void doStop() throws Exception { sender.cancel(); ServiceHelper.stopServices(processor); collection.clear(); } public void process(Exchange exchange) throws Exception { AsyncProcessorHelper.process(this, exchange); } /** * Enqueues an exchange for later batch processing. */ public boolean process(Exchange exchange, AsyncCallback callback) { try { // if batch consumer is enabled then we need to adjust the batch size // with the size from the batch consumer if (isBatchConsumer()) { int size = exchange.getProperty(Exchange.BATCH_SIZE, Integer.class); if (batchSize != size) { batchSize = size; LOG.trace("Using batch consumer completion, so setting batch size to: {}", batchSize); } } // validate that the exchange can be used if (!isValid(exchange)) { if (isIgnoreInvalidExchanges()) { LOG.debug("Invalid Exchange. This Exchange will be ignored: {}", exchange); } else { throw new CamelExchangeException("Exchange is not valid to be used by the BatchProcessor", exchange); } } else { // exchange is valid so enqueue the exchange sender.enqueueExchange(exchange); } } catch (Throwable e) { exchange.setException(e); } callback.done(true); return true; } /** * Is the given exchange valid to be used. * * @param exchange the given exchange * @return <tt>true</tt> if valid, <tt>false</tt> otherwise */ private boolean isValid(Exchange exchange) { Object result = null; try { result = expression.evaluate(exchange, Object.class); } catch (Exception e) { // ignore } return result != null; } /** * Sender thread for queued-up exchanges. */ private class BatchSender extends Thread { private Queue<Exchange> queue; private Lock queueLock = new ReentrantLock(); private final AtomicBoolean exchangeEnqueued = new AtomicBoolean(); private final Queue<String> completionPredicateMatched = new ConcurrentLinkedQueue<>(); private Condition exchangeEnqueuedCondition = queueLock.newCondition(); BatchSender() { super(camelContext.getExecutorServiceManager().resolveThreadName("Batch Sender")); this.queue = new LinkedList<>(); } @Override public void run() { // Wait until one of either: // * an exchange being queued; // * the batch timeout expiring; or // * the thread being cancelled. // // If an exchange is queued then we need to determine whether the // batch is complete. If it is complete then we send out the batched // exchanges. Otherwise we move back into our wait state. // // If the batch times out then we send out the batched exchanges // collected so far. // // If we receive an interrupt then all blocking operations are // interrupted and our thread terminates. // // The goal of the following algorithm in terms of synchronisation // is to provide fine grained locking i.e. retaining the lock only // when required. Special consideration is given to releasing the // lock when calling an overloaded method i.e. sendExchanges. // Unlocking is important as the process of sending out the exchanges // would otherwise block new exchanges from being queued. queueLock.lock(); try { do { try { if (!exchangeEnqueued.get()) { LOG.trace("Waiting for new exchange to arrive or batchTimeout to occur after {} ms.", batchTimeout); exchangeEnqueuedCondition.await(batchTimeout, TimeUnit.MILLISECONDS); } // if the completion predicate was triggered then there is an exchange id which denotes when to complete String id = null; if (!completionPredicateMatched.isEmpty()) { id = completionPredicateMatched.poll(); } if (id != null || !exchangeEnqueued.get()) { if (id != null) { LOG.trace("Collecting exchanges to be aggregated triggered by completion predicate"); } else { LOG.trace("Collecting exchanges to be aggregated triggered by batch timeout"); } drainQueueTo(collection, batchSize, id); } else { exchangeEnqueued.set(false); boolean drained = false; while (isInBatchCompleted(queue.size())) { drained = true; drainQueueTo(collection, batchSize, id); } if (drained) { LOG.trace("Collecting exchanges to be aggregated triggered by new exchanges received"); } if (!isOutBatchCompleted()) { continue; } } queueLock.unlock(); try { try { sendExchanges(); } catch (Throwable t) { // a fail safe to handle all exceptions being thrown getExceptionHandler().handleException(t); } } finally { queueLock.lock(); } } catch (InterruptedException e) { break; } } while (isRunAllowed()); } finally { queueLock.unlock(); } } /** * This method should be called with queueLock held */ private void drainQueueTo(Collection<Exchange> collection, int batchSize, String exchangeId) { for (int i = 0; i < batchSize; ++i) { Exchange e = queue.poll(); if (e != null) { try { collection.add(e); } catch (Exception t) { e.setException(t); } catch (Throwable t) { getExceptionHandler().handleException(t); } if (exchangeId != null && exchangeId.equals(e.getExchangeId())) { // this batch is complete so stop draining break; } } else { break; } } } public void cancel() { interrupt(); } public void enqueueExchange(Exchange exchange) { LOG.debug("Received exchange to be batched: {}", exchange); queueLock.lock(); try { // pre test whether the completion predicate matched if (completionPredicate != null) { boolean matches = completionPredicate.matches(exchange); if (matches) { LOG.trace("Exchange matched completion predicate: {}", exchange); // add this exchange to the list of exchanges which marks the batch as complete completionPredicateMatched.add(exchange.getExchangeId()); } } queue.add(exchange); exchangeEnqueued.set(true); exchangeEnqueuedCondition.signal(); } finally { queueLock.unlock(); } } private void sendExchanges() throws Exception { Iterator<Exchange> iter = collection.iterator(); while (iter.hasNext()) { Exchange exchange = iter.next(); iter.remove(); try { LOG.debug("Sending aggregated exchange: {}", exchange); processExchange(exchange); } catch (Throwable t) { // must catch throwable to avoid growing memory getExceptionHandler().handleException("Error processing aggregated exchange: " + exchange, t); } } } } }
36.116232
131
0.588115
59089f0851713366693bc204633e8a0df208d789
1,146
/** * Copyright 2021 jb51.net */ package com.qianyitian.hope2.spider.model; import com.alibaba.fastjson.annotation.JSONField; import java.util.Date; /** * Auto-generated: 2021-01-27 10:33:18 * * @author jb51.net (i@jb51.net) * @website http://tools.jb51.net/code/json2javabean */ public class AchievementList { @JSONField(name = "fund_code") private String fundCode; private String fundsname; @JSONField(name = "post_date") private Date postDate; @JSONField(name = "cp_rate") private double cpRate; public void setFundCode(String fundCode) { this.fundCode = fundCode; } public String getFundCode() { return fundCode; } public void setFundsname(String fundsname) { this.fundsname = fundsname; } public String getFundsname() { return fundsname; } public void setPostDate(Date postDate) { this.postDate = postDate; } public Date getPostDate() { return postDate; } public void setCpRate(double cpRate) { this.cpRate = cpRate; } public double getCpRate() { return cpRate; } }
19.758621
52
0.640489
1bc0413ec68383f225a667059e7ba52d137633c9
451
package cc.eamon.open.mapping.mapper.valid; import javax.validation.constraints.Min; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.FIELD}) @Retention(RetentionPolicy.SOURCE) public @interface MapperMax { String[] value() default {}; String[] message() default {}; long[] maxValue() default {}; }
21.47619
44
0.756098
d980497d22e3e60d863534bece25a61693c343fc
331
package org.jeecg.modules.hudong.hdExcel.service; import org.jeecg.modules.hudong.hdExcel.entity.HdExcel; import com.baomidou.mybatisplus.extension.service.IService; /** * @Description: Excel模版管理 * @author: jeecg-boot * @date: 2019-07-31 * @version: V1.0 */ public interface IHdExcelService extends IService<HdExcel> { }
22.066667
60
0.755287
f7dbc5ead0ce0a9b8daf8b970fd2d20d64059d62
324
package biz.golek.whattodofordinner.business.contract.response_data; import java.io.Serializable; /** * Created by Bartosz Gołek on 2016-02-08. */ public class DinnerListItem implements Serializable { public Long id; public String name; @Override public String toString() { return name; } }
19.058824
68
0.70679
acdafa75a02b9f55c215ba4f7b8fdfcf24e46f1e
1,017
package com.wexalian.jtrakt.endpoint.sync; import com.wexalian.jtrakt.endpoint.TraktItemType; import com.wexalian.jtrakt.endpoint.episodes.TraktEpisode; import com.wexalian.jtrakt.endpoint.movies.TraktMovie; import com.wexalian.jtrakt.endpoint.shows.TraktShow; import java.time.OffsetDateTime; public class TraktPlayback { private float progress; private OffsetDateTime paused_at; private int id; private TraktItemType type; private TraktMovie movie; private TraktShow show; private TraktEpisode episode; public float getProgress() { return progress; } public OffsetDateTime getPausedAt() { return paused_at; } public int getId() { return id; } public TraktItemType getType() { return type; } public TraktMovie getMovie() { return movie; } public TraktShow getShow() { return show; } public TraktEpisode getEpisode() { return episode; } }
21.638298
58
0.665683
a20a55a2f9eb63d6eff23240dfb3587f05a7b1be
429
package com.prim.primweb.core.uicontroller; /** * ================================================ * 作 者:linksus * 版 本:1.0 * 创建日期:6/20 0020 * 描 述: * 修订历史: * ================================================ */ public interface IndicatorController { void show(); void hide(); void reset(); void setProgress(int n); void progress(int newProgress); IBaseIndicatorView getIndicator(); }
17.16
51
0.468531
a7c5655eeef8f8ead39f03cce4793d32145672eb
38,367
package io.github.jayzhang.mybatis.generator.plugin; import static org.mybatis.generator.internal.util.StringUtility.stringHasValue; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; import org.apache.commons.lang.StringUtils; import org.mybatis.generator.api.GeneratedJavaFile; import org.mybatis.generator.api.GeneratedXmlFile; import org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.PluginAdapter; import org.mybatis.generator.api.dom.OutputUtilities; import org.mybatis.generator.api.dom.java.CompilationUnit; import org.mybatis.generator.api.dom.java.Field; import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; import org.mybatis.generator.api.dom.java.InnerEnum; import org.mybatis.generator.api.dom.java.Interface; import org.mybatis.generator.api.dom.java.JavaVisibility; import org.mybatis.generator.api.dom.java.Method; import org.mybatis.generator.api.dom.java.Parameter; import org.mybatis.generator.api.dom.java.TopLevelClass; import org.mybatis.generator.api.dom.xml.Attribute; import org.mybatis.generator.api.dom.xml.Document; import org.mybatis.generator.api.dom.xml.TextElement; import org.mybatis.generator.api.dom.xml.XmlElement; import org.mybatis.generator.codegen.mybatis3.ListUtilities; import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities; import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.AbstractXmlElementGenerator; import org.mybatis.generator.config.GeneratedKey; import org.mybatis.generator.config.PropertyRegistry; import org.mybatis.generator.internal.util.JavaBeansUtil; import org.springframework.beans.BeanUtils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import io.github.jayzhang.mybatis.generator.plugin.utils.DateISO8601TimeDeserializer; import io.github.jayzhang.mybatis.generator.plugin.utils.DateISO8601TimeSerializer; import io.github.jayzhang.mybatis.generator.plugin.utils.ISO8601TimeDeserializer; import io.github.jayzhang.mybatis.generator.plugin.utils.ISO8601TimeSerializer; import lombok.Getter; public class MybatisPlusPlugin extends PluginAdapter { private String targetProject; private String targetPackage; private GeneratedJavaFile getJavaFile(CompilationUnit compilationUnit) { GeneratedJavaFile gjf = new GeneratedJavaFile(compilationUnit, targetProject, context.getProperty(PropertyRegistry.CONTEXT_JAVA_FILE_ENCODING), context.getJavaFormatter()); return gjf; } @Override public void setProperties(Properties properties) { super.setProperties(properties); targetProject = properties.getProperty("targetProject"); targetPackage = properties.getProperty("targetPackage"); } private ServiceProperties getServiceProperties(IntrospectedTable introspectedTable) { ServiceProperties serviceProperties = new ServiceProperties(); for (Object key : properties.keySet()) { String k = (String) key; if (k.contains(".")) { List<String> arr = Splitter.on(".").splitToList(k); String table = arr.get(0); if (table.equals("*") || table.equals(introspectedTable.getFullyQualifiedTableNameAtRuntime())) { String method = arr.get(1); String v = (String) properties.get(key); try { java.lang.reflect.Field f = ServiceProperties.class.getDeclaredField(method); if (f != null) { try { f.set(serviceProperties, Boolean.parseBoolean(v)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (NoSuchFieldException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (SecurityException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } } return serviceProperties; } @Override public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(IntrospectedTable introspectedTable) { ServiceProperties serviceProperties = getServiceProperties(introspectedTable); MybatisPlusServiceGenerator generator = new MybatisPlusServiceGenerator(targetProject, introspectedTable, serviceProperties, targetPackage); generator.setContext(context); List<GeneratedJavaFile> javaFiles = generator.getCompilationUnits().stream().map(i -> getJavaFile(i)) .collect(Collectors.toList()); return javaFiles; } @Override public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) { ServiceProperties serviceProperties = getServiceProperties(introspectedTable); if(serviceProperties.optimizedPage) { addPageXml(document.getRootElement(), introspectedTable); } if(serviceProperties.createBatch) { BatchInsertElementGenerator elementGenerator = new BatchInsertElementGenerator(); elementGenerator.setContext(context); elementGenerator.setIntrospectedTable(introspectedTable); elementGenerator.addElements(document.getRootElement()); } return super.sqlMapDocumentGenerated(document, introspectedTable); } /** * 性能优化版分页查询 */ private void addPageXml(XmlElement parentElement, IntrospectedTable introspectedTable) { XmlElement resultMap = new XmlElement("resultMap"); //$NON-NLS-1$ resultMap.addAttribute(new Attribute("id", //$NON-NLS-1$ introspectedTable.getBaseResultMapId())); String returnType = introspectedTable.getBaseRecordType(); resultMap.addAttribute(new Attribute("type", //$NON-NLS-1$ returnType)); for (IntrospectedColumn introspectedColumn : introspectedTable .getPrimaryKeyColumns()) { XmlElement resultElement = new XmlElement("id"); //$NON-NLS-1$ resultElement.addAttribute(generateColumnAttribute(introspectedColumn)); resultElement.addAttribute(new Attribute( "property", introspectedColumn.getJavaProperty())); //$NON-NLS-1$ resultElement.addAttribute(new Attribute("jdbcType", //$NON-NLS-1$ introspectedColumn.getJdbcTypeName())); if (stringHasValue(introspectedColumn.getTypeHandler())) { resultElement.addAttribute(new Attribute( "typeHandler", introspectedColumn.getTypeHandler())); //$NON-NLS-1$ } resultMap.addElement(resultElement); } for (IntrospectedColumn introspectedColumn : introspectedTable.getNonPrimaryKeyColumns()) { XmlElement resultElement = new XmlElement("result"); //$NON-NLS-1$ resultElement.addAttribute(generateColumnAttribute(introspectedColumn)); resultElement.addAttribute(new Attribute( "property", introspectedColumn.getJavaProperty())); //$NON-NLS-1$ resultElement.addAttribute(new Attribute("jdbcType", //$NON-NLS-1$ introspectedColumn.getJdbcTypeName())); if (stringHasValue(introspectedColumn.getTypeHandler())) { resultElement.addAttribute(new Attribute( "typeHandler", introspectedColumn.getTypeHandler())); //$NON-NLS-1$ } resultMap.addElement(resultElement); } parentElement.addElement(resultMap); XmlElement select = new XmlElement("select"); parentElement.addElement(select); select.addAttribute(new Attribute("id", "page")); select.addAttribute(new Attribute("parameterType", introspectedTable.getBaseRecordType())); select.addAttribute(new Attribute("resultMap", "BaseResultMap")); select.addElement(new TextElement("select")); XmlElement choose = new XmlElement("choose"); select.addElement(choose); XmlElement when = new XmlElement("when"); choose.addElement(when); when.addAttribute(new Attribute("test", "fields != null")); XmlElement foreach0 = new XmlElement("foreach"); when.addElement(foreach0); foreach0.addAttribute(new Attribute("close", "")); foreach0.addAttribute(new Attribute("open", "")); foreach0.addAttribute(new Attribute("collection", "fields")); foreach0.addAttribute(new Attribute("item", "field")); foreach0.addAttribute(new Attribute("separator", ",")); foreach0.addElement(new TextElement("B.${field} AS ${field}")); XmlElement otherwise = new XmlElement("otherwise"); choose.addElement(otherwise); StringBuilder sb = new StringBuilder(); Iterator<IntrospectedColumn> iter = introspectedTable .getNonBLOBColumns().iterator(); while (iter.hasNext()) { sb.append("B."); String field = MyBatis3FormattingUtilities.getSelectListPhrase(iter .next()); sb.append(field); sb.append(" AS "); sb.append(field); if (iter.hasNext()) { sb.append(", "); //$NON-NLS-1$ } if (sb.length() > 80) { otherwise.addElement(new TextElement(sb.toString())); sb.setLength(0); } } if (sb.length() > 0) { otherwise.addElement(new TextElement(sb.toString())); } List<String> pklist = introspectedTable.getPrimaryKeyColumns().stream().map(i->i.getActualColumnName()).collect(Collectors.toList()); String pks = Joiner.on(",").join(pklist); select.addElement(new TextElement("FROM ( SELECT " + pks + " FROM ${tableName} ")) ; XmlElement ifwhere = new XmlElement("if"); select.addElement(ifwhere); XmlElement where = new XmlElement("where"); ifwhere.addElement(where); XmlElement trim = new XmlElement("trim"); trim.addAttribute(new Attribute("prefix", "(")); trim.addAttribute(new Attribute("prefixOverrides", "AND")); trim.addAttribute(new Attribute("suffix", ")")); where.addElement(trim); List<String> fieldsNotNulls = new ArrayList<>(); List<IntrospectedColumn> cols = introspectedTable.getNonBLOBColumns(); for (IntrospectedColumn col : cols) { JSONObject columnMeta = JSON.parseObject(col.getRemarks()); if(columnMeta == null) continue; String filter = columnMeta.getString(CommentJsonKeys.FILTER); if(filter == null) { continue; } List<String> filterOpts = Splitter.on(",").splitToList(filter); if(filterOpts.contains(FilterOperators.IN)) //如果有in,则省略eq { filterOpts = filterOpts.stream().filter(i->!FilterOperators.EQ.equals(i)).collect(Collectors.toList()); } String fieldName = col.getJavaProperty(); String colName = col.getActualColumnName(); for(String opt: filterOpts) { XmlElement ifcmp = new XmlElement("if"); String f = fieldName; if(FilterOperators.EQ.equals(opt)) { ifcmp.addElement(new TextElement("AND "+ colName + " = #{" + f + "}")); } else if(FilterOperators.GT.equals(opt)) { f += "Gt"; ifcmp.addElement(new TextElement("AND "+ colName + " <![CDATA[>]]> #{" + f + "}")); } else if(FilterOperators.GTE.equals(opt)) { f += "Gte"; ifcmp.addElement(new TextElement("AND "+ colName + " <![CDATA[>=]]> #{" + f + "}")); } else if(FilterOperators.LTE.equals(opt)) { f += "Lte"; ifcmp.addElement(new TextElement(" AND "+ colName + " <![CDATA[<=]]> #{" + f + "}")); } else if(FilterOperators.LT.equals(opt)) { f += "Lt"; ifcmp.addElement(new TextElement("AND " + colName + " <![CDATA[<]]> #{" + f + "}")); } else if(FilterOperators.IN.equals(opt)) { ifcmp.addElement(new TextElement("AND " + colName + " IN ")); XmlElement foreach = new XmlElement("foreach"); foreach.addAttribute(new Attribute("open", "(")); foreach.addAttribute(new Attribute("close", ")")); foreach.addAttribute(new Attribute("collection", fieldName)); foreach.addAttribute(new Attribute("item", "listItem")); foreach.addElement(new TextElement("#{listItem}")); foreach.addAttribute(new Attribute("separator", ",")); ifcmp.addElement(foreach); } else if(FilterOperators.LIKE.equals(opt)) { f += "Like"; ifcmp.addElement(new TextElement("AND " + colName + " LIKE #{" + f + "}")); } ifcmp.addAttribute(new Attribute("test", f + " != null")); trim.addElement(ifcmp); fieldsNotNulls.add(f + " != null"); } } String testif = Joiner.on(" or ").join(fieldsNotNulls); ifwhere.addAttribute(new Attribute("test", testif)); XmlElement iforder = new XmlElement("if"); select.addElement(iforder); iforder.addElement(new TextElement("ORDER BY ")); iforder.addAttribute(new Attribute("test", "orderByFields != null")); XmlElement foreachOrder = new XmlElement("foreach"); iforder.addElement(foreachOrder); foreachOrder.addAttribute(new Attribute("open", "")); foreachOrder.addAttribute(new Attribute("close", "")); foreachOrder.addAttribute(new Attribute("collection", "orderByFields")); foreachOrder.addAttribute(new Attribute("item", "field")); foreachOrder.addAttribute(new Attribute("separator", ",")); for (IntrospectedColumn introspectedColumn : introspectedTable.getNonPrimaryKeyColumns()) { String javaField = introspectedColumn.getJavaProperty(); XmlElement ifField = new XmlElement("if"); ifField.addAttribute(new Attribute("test", "field.field.equals('"+javaField+"')")); ifField.addElement(new TextElement(introspectedColumn.getActualColumnName())); foreachOrder.addElement(ifField); } // foreachOrder.addElement(new TextElement("${field.field}")); XmlElement chooseAsc = new XmlElement("choose"); foreachOrder.addElement(chooseAsc); XmlElement whenAsc = new XmlElement("when"); chooseAsc.addElement(whenAsc); whenAsc.addAttribute(new Attribute("test", "field.asc")); whenAsc.addElement(new TextElement("ASC")); XmlElement otherwiseAsc = new XmlElement("otherwise"); otherwiseAsc.addElement(new TextElement("DESC")); chooseAsc.addElement(otherwiseAsc); String oncond = Joiner.on(" AND ").join(pklist.stream().map(i-> ("A." + i + " = B." + i)).collect(Collectors.toList())); select.addElement(new TextElement("LIMIT #{skip} , #{limit} ) AS A LEFT JOIN ${tableName} AS B ON " + oncond)); } private Attribute generateColumnAttribute(IntrospectedColumn introspectedColumn) { return new Attribute("column", //$NON-NLS-1$ MyBatis3FormattingUtilities.getRenamedColumnNameForResultMap(introspectedColumn)); } @Override public boolean clientGenerated(Interface interfaze, IntrospectedTable introspectedTable) { ServiceProperties serviceProperties = getServiceProperties(introspectedTable); if(serviceProperties.createBatch) { Method method = getBatchInsertMethod("insertBatch", introspectedTable); interfaze.addMethod(method); interfaze.addImportedType(FullyQualifiedJavaType.getNewListInstance()); } interfaze.addImportedType(new FullyQualifiedJavaType(BaseMapper.class.getName())); interfaze.addImportedType(new FullyQualifiedJavaType(introspectedTable.getBaseRecordType())); FullyQualifiedJavaType baseMapper = new FullyQualifiedJavaType(BaseMapper.class.getSimpleName()); String modelSimpleTypeName = StringUtils.substringAfterLast(introspectedTable.getBaseRecordType(), "."); baseMapper.addTypeArgument(new FullyQualifiedJavaType(modelSimpleTypeName)); interfaze.addSuperInterface(baseMapper); if(serviceProperties.optimizedPage) { FullyQualifiedJavaType listType = FullyQualifiedJavaType.getNewListInstance(); listType.addTypeArgument(new FullyQualifiedJavaType(introspectedTable.getBaseRecordType())); Method method = new Method("page"); method.setVisibility(JavaVisibility.PUBLIC); method.setReturnType(listType); method.setAbstract(true); String modelClassName = introspectedTable.getBaseRecordType() + "List"; String modelClassNameSingle = StringUtils.substringAfterLast(modelClassName, "."); method.addParameter(new Parameter(new FullyQualifiedJavaType(modelClassNameSingle), "list")); interfaze.addMethod(method); interfaze.addImportedType(new FullyQualifiedJavaType(modelClassName)); interfaze.addImportedType(FullyQualifiedJavaType.getNewListInstance()); } return true; } private Method getBatchInsertMethod(String name, IntrospectedTable introspectedTable) { FullyQualifiedJavaType listType = FullyQualifiedJavaType.getNewListInstance(); listType.addTypeArgument(new FullyQualifiedJavaType(introspectedTable.getBaseRecordType())); Method method = new Method(name); method.setVisibility(JavaVisibility.PUBLIC); method.setReturnType(FullyQualifiedJavaType.getIntInstance()); method.setAbstract(true); method.addParameter(new Parameter(listType, "records")); return method; } public class BatchInsertElementGenerator extends AbstractXmlElementGenerator { @Override public void addElements(XmlElement parentElement) { XmlElement answer = new XmlElement("insert"); //$NON-NLS-1$ answer.addAttribute(new Attribute( "id", "insertBatch")); //$NON-NLS-1$ answer.addAttribute(new Attribute("parameterType", //$NON-NLS-1$ List.class.getName())); GeneratedKey gk = introspectedTable.getGeneratedKey(); if (gk != null) { introspectedTable.getColumn(gk.getColumn()).ifPresent(introspectedColumn -> { // if the column is null, then it's a configuration error. The // warning has already been reported if (gk.isJdbcStandard()) { answer.addAttribute(new Attribute( "useGeneratedKeys", "true")); //$NON-NLS-1$ //$NON-NLS-2$ answer.addAttribute(new Attribute( "keyProperty", introspectedColumn.getJavaProperty())); //$NON-NLS-1$ answer.addAttribute(new Attribute( "keyColumn", introspectedColumn.getActualColumnName())); //$NON-NLS-1$ } else { answer.addElement(getSelectKey(introspectedColumn, gk)); } }); } StringBuilder insertClause = new StringBuilder(); insertClause.append("insert into "); //$NON-NLS-1$ insertClause.append(introspectedTable .getFullyQualifiedTableNameAtRuntime()); insertClause.append(" ("); //$NON-NLS-1$ XmlElement foreach = new XmlElement("foreach"); foreach.addAttribute(new Attribute("collection","list")); foreach.addAttribute(new Attribute("item","item")); foreach.addAttribute(new Attribute("separator",",")); foreach.addAttribute(new Attribute("open","")); foreach.addAttribute(new Attribute("close","")); StringBuilder valuesClause = new StringBuilder(); valuesClause.append(" ("); //$NON-NLS-1$ List<String> valuesClauses = new ArrayList<>(); List<IntrospectedColumn> columns = ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()); for (int i = 0; i < columns.size(); i++) { IntrospectedColumn introspectedColumn = columns.get(i); insertClause.append(MyBatis3FormattingUtilities .getEscapedColumnName(introspectedColumn)); valuesClause.append("#{item."); //$NON-NLS-1$ valuesClause.append(introspectedColumn.getJavaProperty()); valuesClause.append(",jdbcType="); //$NON-NLS-1$ valuesClause.append(introspectedColumn.getJdbcTypeName()); if (stringHasValue(introspectedColumn.getTypeHandler())) { valuesClause.append(",typeHandler="); //$NON-NLS-1$ valuesClause.append(introspectedColumn.getTypeHandler()); } valuesClause.append('}'); if (i + 1 < columns.size()) { insertClause.append(", "); //$NON-NLS-1$ valuesClause.append(", "); //$NON-NLS-1$ } if (valuesClause.length() > 80) { answer.addElement(new TextElement(insertClause.toString())); insertClause.setLength(0); OutputUtilities.xmlIndent(insertClause, 1); valuesClauses.add(valuesClause.toString()); valuesClause.setLength(0); OutputUtilities.xmlIndent(valuesClause, 1); } } insertClause.append(")\n\tvalues"); answer.addElement(new TextElement(insertClause.toString())); answer.addElement(foreach); valuesClause.append(')'); valuesClauses.add(valuesClause.toString()); for (String clause : valuesClauses) { foreach.addElement(new TextElement(clause)); } parentElement.addElement(new TextElement("\n")); parentElement.addElement(answer); } } @Override public boolean validate(List<String> warnings) { return true; } @Override public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { JavaGeneratorUtils.cleanClass(topLevelClass);//清理掉原来的class,重新生成 topLevelClass.setVisibility(JavaVisibility.PUBLIC); JavaGeneratorUtils.addLombokAnnotations(topLevelClass); JavaGeneratorUtils.addSerializable(topLevelClass); //序列化 topLevelClass.addAnnotation("@TableName(\""+introspectedTable.getFullyQualifiedTableNameAtRuntime()+"\")"); topLevelClass.addAnnotation("@JsonInclude(Include.NON_NULL) "); topLevelClass.addImportedType(JsonInclude.class.getName()); topLevelClass.addImportedType(JsonInclude.class.getName() + ".Include"); topLevelClass.addImportedType(TableName.class.getName()); topLevelClass.addSuperInterface(new FullyQualifiedJavaType("Cloneable")); List<IntrospectedColumn> introspectedColumns = JavaGeneratorUtils.getColumnsInThisClass(introspectedTable); for (IntrospectedColumn introspectedColumn : introspectedColumns) { JSONObject columnMeta = JSON.parseObject(introspectedColumn.getRemarks()); Field field = JavaBeansUtil.getJavaBeansField(introspectedColumn, context, introspectedTable); if(introspectedColumn.isIdentity() && introspectedColumn.isAutoIncrement()) { field.addAnnotation("@TableId(type=IdType.AUTO)"); topLevelClass.addImportedType(IdType.class.getName()); topLevelClass.addImportedType(TableId.class.getName()); } JavaGeneratorUtils.addFieldComment(field, columnMeta); JavaGeneratorUtils.addFieldAnnotations(topLevelClass, field, columnMeta); if(JavaGeneratorUtils.isTimeField(columnMeta)) { field.addAnnotation("@JsonDeserialize(using=ISO8601TimeDeserializer.class)"); field.addAnnotation("@JsonSerialize(using=ISO8601TimeSerializer.class)"); topLevelClass.addImportedType(ISO8601TimeDeserializer.class.getName()); topLevelClass.addImportedType(ISO8601TimeSerializer.class.getName()); topLevelClass.addImportedType(JsonDeserialize.class.getName()); topLevelClass.addImportedType(JsonSerialize.class.getName()); } else if(introspectedColumn.getFullyQualifiedJavaType().getFullyQualifiedName().equals(Date.class.getName())) { field.addAnnotation("@JsonDeserialize(using=DateISO8601TimeDeserializer.class)"); field.addAnnotation("@JsonSerialize(using=DateISO8601TimeSerializer.class)"); topLevelClass.addImportedType(DateISO8601TimeDeserializer.class.getName()); topLevelClass.addImportedType(DateISO8601TimeSerializer.class.getName()); topLevelClass.addImportedType(JsonDeserialize.class.getName()); topLevelClass.addImportedType(JsonSerialize.class.getName()); } JavaGeneratorUtils.addStringLengthValidationAnnotations(topLevelClass, introspectedColumn, field); topLevelClass.addField(field); topLevelClass.addImportedType(field.getType()); } InnerEnum enumClass = getFieldEnumClass(introspectedTable); topLevelClass.addInnerEnum(enumClass); topLevelClass.addImportedType(new FullyQualifiedJavaType(Getter.class.getName())); Method cloneMethod = new Method("clone"); cloneMethod.setVisibility(JavaVisibility.PUBLIC); cloneMethod.setReturnType(topLevelClass.getType()); cloneMethod.addBodyLine(topLevelClass.getType().getShortName() + " obj = new " + topLevelClass.getType().getShortName() + "();"); cloneMethod.addBodyLine("BeanUtils.copyProperties(this, obj);"); cloneMethod.addBodyLine("return obj;"); topLevelClass.addMethod(cloneMethod); topLevelClass.addImportedType(BeanUtils.class.getName()); return true; } private InnerEnum getFieldEnumClass(IntrospectedTable table) { String className = "Fields"; InnerEnum enumClass = new InnerEnum(className); enumClass.setVisibility(JavaVisibility.PUBLIC); Field field = new Field("column", FullyQualifiedJavaType.getStringInstance()); field.setVisibility(JavaVisibility.PRIVATE); field.addAnnotation("@Getter"); enumClass.addField(field); for(IntrospectedColumn col: table.getAllColumns()) { enumClass.addEnumConstant(col.getJavaProperty() + "(\"" + col.getActualColumnName() + "\")"); } Method method = new Method(className); method.setConstructor(true); method.setVisibility(JavaVisibility.PRIVATE); method.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "column")); method.addBodyLine("this.column = column;"); enumClass.addMethod(method); return enumClass; } @Override public boolean clientBasicCountMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientBasicDeleteMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientBasicInsertMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientBasicInsertMultipleMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientBasicInsertMultipleHelperMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientBasicSelectManyMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientBasicSelectOneMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientBasicUpdateMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientCountByExampleMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientDeleteByExampleMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientDeleteByPrimaryKeyMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientGeneralCountMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientGeneralDeleteMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientGeneralSelectDistinctMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientGeneralSelectMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientGeneralUpdateMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientInsertMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientInsertMultipleMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientSelectByExampleWithBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientSelectByExampleWithoutBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientSelectByPrimaryKeyMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientSelectListFieldGenerated(Field field, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientSelectOneMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientUpdateAllColumnsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientUpdateSelectiveColumnsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientUpdateByExampleSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientUpdateByExampleWithBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientUpdateByExampleWithoutBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientUpdateByPrimaryKeySelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientUpdateByPrimaryKeyWithBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated( Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean modelExampleClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { return false; } @Override public boolean sqlMapResultMapWithoutBLOBsElementGenerated( XmlElement element, IntrospectedTable introspectedTable) { return false; } @Override public boolean sqlMapCountByExampleElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { return false; } @Override public boolean sqlMapDeleteByExampleElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { return false; } @Override public boolean sqlMapDeleteByPrimaryKeyElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { return false; } @Override public boolean sqlMapExampleWhereClauseElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { return false; } /** * 生成mapper.xml,文件内容会被清空再写入 * */ @Override public boolean sqlMapGenerated(GeneratedXmlFile sqlMap, IntrospectedTable introspectedTable) { sqlMap.setMergeable(false); return super.sqlMapGenerated(sqlMap, introspectedTable); } @Override public boolean sqlMapInsertElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { return false; } @Override public boolean sqlMapResultMapWithBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { return false; } @Override public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated( XmlElement element, IntrospectedTable introspectedTable) { return false; } @Override public boolean sqlMapSelectByExampleWithBLOBsElementGenerated( XmlElement element, IntrospectedTable introspectedTable) { return false; } @Override public boolean sqlMapSelectByPrimaryKeyElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { return false; } @Override public boolean sqlMapUpdateByExampleSelectiveElementGenerated( XmlElement element, IntrospectedTable introspectedTable) { return false; } @Override public boolean sqlMapUpdateByExampleWithBLOBsElementGenerated( XmlElement element, IntrospectedTable introspectedTable) { return false; } @Override public boolean sqlMapUpdateByExampleWithoutBLOBsElementGenerated( XmlElement element, IntrospectedTable introspectedTable) { return false; } @Override public boolean sqlMapUpdateByPrimaryKeySelectiveElementGenerated( XmlElement element, IntrospectedTable introspectedTable) { return false; } @Override public boolean sqlMapUpdateByPrimaryKeyWithBLOBsElementGenerated( XmlElement element, IntrospectedTable introspectedTable) { return false; } @Override public boolean sqlMapUpdateByPrimaryKeyWithoutBLOBsElementGenerated( XmlElement element, IntrospectedTable introspectedTable) { return false; } @Override public boolean sqlMapInsertSelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientInsertSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public void initialized(IntrospectedTable introspectedTable) { } @Override public boolean sqlMapBaseColumnListElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { return false; } @Override public boolean sqlMapBlobColumnListElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientSelectAllMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean sqlMapSelectAllElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { return false; } }
38.87234
141
0.66982
e230e1cf9125daa30924d98febf55f70dbc8286e
4,888
package simorion; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import java.awt.Color; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JButton; /** * @author Vlad * @author Paul */ public class ButtonTest { public ButtonTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } /** * Testing the getState method of Button class. * @author Vlad */ @Test public void testGetState(){ //instantiating a new Button Button rbn = new Button(""); //forcing a click event to happen. rbn.changeColour(); System.out.println("The button has been clicked for the first time."); boolean currentState = rbn.getState(); //asserting that the button is toggled after the first click. assertEquals(currentState, true); System.out.println("The current state of toggled is: " + currentState); //second click event rbn.changeColour(); System.out.println("The button has been clicked for the second time."); boolean newState = rbn.getState(); //asserting that the button is not toggled after the second click. assertEquals(newState, false); System.out.println("The current state of toggled is: " + newState); } /** * Testing the changeColour method of Button class. * @author Vlad */ @Test public void testChangeColour(){ //instantiating a new Button with an empty label Button rbn = new Button(""); //first call - not toggled so change colour to orange rbn.changeColour(); Color buttonColour = rbn.getBackground(); Color firstColour = Color.ORANGE; assertEquals(buttonColour, firstColour); System.out.println("The button has been toggled and its color is now orange"); //second call - already toggled so should change colour back to white rbn.changeColour(); Color secondButtonColour = rbn.getBackground(); Color secondColour = Color.WHITE; assertEquals(secondButtonColour, secondColour); System.out.println("The button has been deactivated and its color is now white"); } /** * Testing the clockHandOrange method of Button class. * @author Paul */ @Test public void testClockHandOrange() { //instantiating a new clock hand called ch Button ch = new Button(""); //changing the background colour to orange ch.clockHandOrange(); Color chColour = ch.getBackground(); assertEquals(chColour, Color.ORANGE); System.out.println("The colour of the clock hand is orange."); } /** * Testing the clockHandWhite method of Button class. * @author Paul */ @Test public void testClockHandWhite() { //instantiating a new clock hand called ch Button ch = new Button(""); //changing the background colour to orange and toggling it ch.clockHandOrange(); ch.clockHandWhite(); Color chColour = ch.getBackground(); assertEquals(chColour, Color.WHITE); System.out.println("The colour of the clock hand is white."); } /** * Testing the resetColour method of Button class. * @author Paul */ @Test public void testResetColour() { //instantiating a new clock hand called ch Button ch = new Button(""); //changing the background colour to orange ch.clockHandOrange(); //resetting its colour - should turn to white. ch.resetColour(); Color chColour = ch.getBackground(); assertEquals(chColour, Color.WHITE); System.out.println("The colour of the clock has been reset to white"); } /** * Testing the turnOff method of Button class. * @author Paul */ @Test public void testTurnOff() { //instantiating a new clock hand called ch Button rbn = new Button(""); //changing the background colour and toggling a button. rbn.changeColour(); //turning the button off and checking its colour and toggled state rbn.turnOff(); Color rbnColour = rbn.getBackground(); boolean rbnToggled = rbn.getState(); assertEquals(rbnColour, Color.WHITE); assertEquals(rbnToggled, false); System.out.println("The colour of the button has been reset to white"); System.out.println("The button's toggled state is false"); } }
32.586667
90
0.606997
81abe41771ceeac9da548e3288109ebc7d4fb7bb
958
package com.weme.group.action; import android.content.Context; import android.text.TextUtils; import com.weme.group.utils.DidHelper; import java.util.HashMap; import java.util.Map; /** * 用于上报数据提交,默认已经提交了did,equipment_id, os_version, device_info */ public class ActionParams { private Map<String,Object> params; ActionParams(Context context){ params = new HashMap<>(); params.put("did", DidHelper.getInstance(context).getDid()); params.put("equipment_id", CommHelper.getEquipmentId()); params.put("os_version", CommHelper.getOsVersion()); params.put("device_info", CommHelper.getDeviceInfo(context).toJSON().toString()); params.put("type",2); } ActionParams addParams(String key, Object value){ if(!TextUtils.isEmpty(key) && value != null){ params.put(key,value); } return this; } Map<String,Object> build(){ return params; } }
24.564103
89
0.658664
ad59ede2bd59365381ace3718295e451642cb688
7,487
/** * Created by mmucito on 18/09/17. */ package com.paymentez.example; import com.paymentez.example.model.Customer; import com.paymentez.example.sdk.Paymentez; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.http.HttpEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; @RestController @SpringBootApplication public class Main { public static void main(String[] args) throws Exception { SpringApplication.run(Main.class, args); } @RequestMapping("/") String index() { return "Great, your backend is set up. Now you can configure the Paymentez example apps to point here."; } /** * This code simulates "loading the customer for your current session". * Your own logic will likely look very different. * * @return customer for your current session */ Customer getAuthenticatedCustomer(String uid, HttpServletRequest request){ Customer customer = new Customer(uid, "dev@paymentez.com", request.getRemoteAddr()); return customer; } /** * This endpoint receives an uid and gives you all their cards assigned to that user. * Your own logic shouldn't Call Paymentez on every request, instead, you should cache the cards on your own servers. * * @param uid Customer identifier. This is the identifier you use inside your application; you will receive it in notifications. * * @return a json with all the customer cards */ @RequestMapping(value = "/get-cards", method = RequestMethod.GET, produces = "application/json") String getCards(@RequestParam(value = "uid") String uid, HttpServletResponse response) { Map<String, String> mapResponse = Paymentez.doGetRequest(Paymentez.PAYMENTEZ_DEV_URL + "/v2/card/list?uid="+uid); response.setStatus(Integer.parseInt(mapResponse.get(Paymentez.RESPONSE_HTTP_CODE))); return mapResponse.get(Paymentez.RESPONSE_JSON); } /** * This endpoint is used by Android/ios example app to create a charge. * * @param uid Customer identifier. This is the identifier you use inside your application; you will receive it in notifications. * @param session_id string used for fraud purposes. * @param token Card identifier. This token is unique among all cards. * @param amount Amount to debit. * @param dev_reference Merchant order reference. You will identify this purchase using this reference. * @param description Clear descriptions help Customers to better understand what they’re buying. * * @return a json with the response */ @RequestMapping(value = "/create-charge", method = RequestMethod.POST, produces = "application/json") String createCharge(@RequestParam(value = "uid") String uid, @RequestParam(value = "session_id", required = false) String session_id, @RequestParam(value = "token") String token, @RequestParam(value = "amount") double amount, @RequestParam(value = "dev_reference") String dev_reference, @RequestParam(value = "description") String description, HttpServletRequest request, HttpServletResponse response) { Customer customer = getAuthenticatedCustomer(uid, request); String jsonPaymentezDebit = Paymentez.paymentezDebitJson(customer, session_id, token, amount, dev_reference, description); Map<String, String> mapResponse = Paymentez.doPostRequest(Paymentez.PAYMENTEZ_DEV_URL + "/v2/transaction/debit", jsonPaymentezDebit); response.setStatus(Integer.parseInt(mapResponse.get(Paymentez.RESPONSE_HTTP_CODE))); return mapResponse.get(Paymentez.RESPONSE_JSON); } /** * This endpoint is used by Android/ios example app to delete a card. * * @param uid Customer identifier. This is the identifier you use inside your application; you will receive it in notifications. * @param token Card identifier. This token is unique among all cards. * * @return a json with the response */ @RequestMapping(value = "/delete-card", method = RequestMethod.POST, produces = "application/json") String deleteCard(@RequestParam(value = "uid") String uid, @RequestParam(value = "token") String token, HttpServletResponse response) { String jsonPaymentezDelete = Paymentez.paymentezDeleteJson(uid, token); Map<String, String> mapResponse = Paymentez.doPostRequest(Paymentez.PAYMENTEZ_DEV_URL + "/v2/card/delete", jsonPaymentezDelete); response.setStatus(Integer.parseInt(mapResponse.get(Paymentez.RESPONSE_HTTP_CODE))); return mapResponse.get(Paymentez.RESPONSE_JSON); } /** * This endpoint is used by Android/ios example app to verify a card or transaction. * * @param uid Customer identifier. This is the identifier you use inside your application; you will receive it in notifications. * @param transaction_id Transaction identifier. This is code is unique among all transactions. * @param type It identifies if the value is authorization code or amount (BY_AMOUNT / BY_AUTH_CODE) * @param value The authorization code provided by the financial entity to the buyer or the transaction amount. * * @return a json with the response */ @RequestMapping(value = "/verify-transaction", method = RequestMethod.POST, produces = "application/json") String verifyTransaction(@RequestParam(value = "uid") String uid, @RequestParam(value = "transaction_id") String transaction_id, @RequestParam(value = "type") String type, @RequestParam(value = "value") String value, HttpServletResponse response) { String jsonPaymentezVerify = Paymentez.paymentezVerifyJson(uid, transaction_id, type, value); Map<String, String> mapResponse = Paymentez.doPostRequest(Paymentez.PAYMENTEZ_DEV_URL + "/v2/transaction/verify", jsonPaymentezVerify); response.setStatus(Integer.parseInt(mapResponse.get(Paymentez.RESPONSE_HTTP_CODE))); return mapResponse.get(Paymentez.RESPONSE_JSON); } /** * This endpoint is used for: * * Every time a transaction gets approved or cancelled you will get an HTTP POST request from Paymentez to your callback_url (configured using the admin cpanel). * * @param httpEntity A json with fields of the transaction, for more detail please look at: https://paymentez.github.io/api-doc * * @return For every transaction you must return an HTTP status 200, this status is only used to know that you received correctly the call. * */ @RequestMapping(value = "/web-hook-callback", method = RequestMethod.POST, produces = "application/json") String WebHookCallback(HttpEntity<String> httpEntity, HttpServletResponse response) { String json = httpEntity.getBody(); System.out.println(json); response.setStatus(200); return "{}"; } }
48.616883
165
0.706024
3fc1a94b756c0367cf365ac5da4d320af235093e
951
package com.argusapm.android.core.job.net.i; import com.argusapm.android.core.job.net.NetInfo; /** * OkHttp相关,对外暴露的接口 * * @author ArgusAPM Team */ public class QOKHttp { /** * 记录一次网络请求 * * @param url 请求url * @param code 状态码 * @param requestSize 发送的数据大小 * @param responseSize 接收的数据大小 * @param startTime 发起时间 * @param costTime 耗时 */ public static void recordUrlRequest(String url, int code, long requestSize, long responseSize, long startTime, long costTime) { NetInfo netInfo = new NetInfo(); netInfo.setStartTime(startTime); netInfo.setURL(url); netInfo.setStatusCode(code); netInfo.setSendBytes(requestSize); netInfo.setRecordTime(System.currentTimeMillis()); netInfo.setReceivedBytes(responseSize); netInfo.setCostTime(costTime); netInfo.end(); } }
27.970588
98
0.610936
59e237c13381160679ec81fd3127a3796086d929
8,328
package com.sproutigy.verve.resources; import com.sproutigy.verve.resources.exceptions.ChildrenNotAvailableResourceException; import com.sproutigy.verve.resources.exceptions.InvalidResolvePathResourceException; import com.sproutigy.verve.resources.props.DataAccessJSONProps; import com.sproutigy.verve.resources.props.JSONProps; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Iterator; import java.util.Objects; import java.util.Optional; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; public abstract class AbstractResource implements Resource { private static final String PROPS_FILENAME = ".props.json"; protected final Executor executor = Executors.newSingleThreadExecutor(new ThreadFactory() { private ThreadFactory parent = Executors.defaultThreadFactory(); @Override public Thread newThread(Runnable r) { Thread thread = parent.newThread(r); thread.setDaemon(true); return thread; } }); public AbstractResource() { } @Override public int hashCode() { if (getDescriptor() != null) { return getDescriptor().hashCode(); } else { return super.hashCode(); } } @Override public boolean equals(Object obj) { if (obj instanceof Resource) { Resource other = (Resource)obj; if (this.getDescriptor() != null) { return Objects.equals(this.getDescriptor(), other.getDescriptor()); } } return super.equals(obj); } @Override public boolean hasParent() { return getParent().isPresent(); } @Override public Optional<? extends Resource> getParent() { return Optional.empty(); } @Override public Resource getRoot() throws IOException { Resource cur = this; while (true) { Optional<? extends Resource> optParent = cur.getParent(); if (optParent.isPresent()) { if (optParent.get() != cur) { cur = optParent.get(); } else { break; } } else { break; } } return cur; } @Override public boolean create() throws IOException { throw new IOException("Resource could not be created"); } @Override public boolean createContainer() throws IOException { throw new IOException("Resource could not be created as a container"); } @Override public boolean isContainer() { return hasChildren(); } @Override public boolean hasChildren() { try { return iterator().hasNext(); } catch (RuntimeException re) { if (re.getCause() instanceof ChildrenNotAvailableResourceException) { return false; } throw re; } } @Override public boolean hasChild(String name) throws IOException { for (Resource resource : getChildren(true)) { if (Objects.equals(resource.getName(), name)) { return true; } } return false; } @Override public final Resource child(String name) throws IOException { if (name.contains("/") || name.contains("\\")) { throw new IllegalArgumentException("Child name cannot contain special path characters"); } return resolveChild(name); } @Override public boolean hasData() { return false; } @Override public DataAccess data() { return null; //TODO } @Override public boolean hasProps() throws IOException { if (!exists()) { return false; } if (isContainer()) { return hasChild(PROPS_FILENAME); } else { if (!hasParent()) { return false; } return getParent().get().hasChild(getName() + PROPS_FILENAME); } } @Override public JSONProps props() throws IOException { if (!exists()) { throw new IOException("Cannot fetch props of non-existing resource"); } if (isContainer()) { return new DataAccessJSONProps(child(PROPS_FILENAME).data()); } else { if (!hasParent()) { throw new IOException("No parent - cannot fetch props"); } Resource propsResource = getParent().get().child(getName() + PROPS_FILENAME); return new DataAccessJSONProps(propsResource.data()); } } @Override public boolean delete(DeleteOption... options) throws IOException { throw new IOException("Resource is unmodifiable"); } @Override public Optional<File> toLocalFile() throws IOException { return Optional.empty(); } @Override public Optional<Path> toFilePath() { Optional<URI> optURI = toURI(); if (optURI.isPresent()) { try { return Optional.of(Paths.get(optURI.get())); } catch(Exception ignore) { } } return Optional.empty(); } @Override public Optional<URL> toURL() { return Optional.empty(); } @Override public Optional<URI> toURI() { return Optional.empty(); } @Override public boolean isModifiable() { return false; } @Override public boolean isLockable() { return false; } protected void ensureExistence() throws IOException { if (!exists()) { throw new IllegalStateException("Resource not exists"); } } @SuppressWarnings("unchecked") @Override public Iterator<Resource> iterator() { try { try { return (Iterator<Resource>) getChildren().iterator(); } catch (ChildrenNotAvailableResourceException noChildren) { return Collections.emptyIterator(); } } catch (IOException e) { throw new RuntimeException("Could not iterate children resources", e); } } @Override public Resource resolve(String path) throws IOException { if (path == null || path.isEmpty() || path.equals(".")) { return this; } if (path.indexOf('\\') > 0) { path = path.replace("\\", "/"); } if (path.charAt(0) == PATH_SEPARATOR) { return getRoot().resolve(path.substring(1)); } if (path.startsWith("./")) { if (!hasParent()) { throw new InvalidResolvePathResourceException(); } return resolve(path.substring(2)); } if (path.startsWith("../")) { if (hasParent()) { throw new InvalidResolvePathResourceException(); } return getParent().get().resolve(path.substring(3)); } if (path.indexOf(PATH_SEPARATOR) > -1) { Resource resource = child(path.substring(0, path.indexOf(PATH_SEPARATOR))); return resource.resolve(path.substring(path.indexOf(PATH_SEPARATOR)+1)); } else { return child(path); } } @Override public Iterable<? extends Resource> getChildren() throws IOException { return getChildren(false); } protected Resource resolveChild(String name) throws IOException { throw new IOException("Could not resolve child resource"); } @Override public String toString() { String descriptor = getDescriptor(); if (descriptor == null || descriptor.isEmpty()) { return super.toString(); } return descriptor; } @Override public void close() throws Exception { } protected boolean isSpecialChildName(String childName) { if (childName.endsWith(PROPS_FILENAME)) { return true; } if (childName.startsWith(".~")) { return true; } return false; } }
26.864516
100
0.574207
30dcfaa1a81d8a318ce629f22bdfb06d0d601cdf
935
class Solution { public void XXX(int[] nums) { //遇见0和前面的交换,遇见1不动 int zeroPosition = -1; int twoposition = nums.length; for (int i = 0; i < nums.length; i++) { //提高效率,后面都是2了 if(nums[i] == 2 && i == twoposition - 1){ break; } //遇见0和左侧0的下一个位置进行交换 if (nums[i] == 0) { swap(nums, i, ++zeroPosition); } //右侧元素和当前2交换的时候可能存在副作用,如果遇见0和2和当前的2交换,都需要继续从当前位置开始 if (nums[i] == 2 && i < twoposition - 1 && nums[twoposition - 1] == 1) { swap(nums, i, --twoposition); } else if (nums[i] == 2 && i < twoposition - 1) { swap(nums, i, --twoposition); i--;//注意 } } } public void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }
29.21875
84
0.428877
4baa447caa7b7537a2937e7b7a20dd435d360d84
4,504
package net.okair.springcloud.gateway.admin.rest; import io.swagger.annotations.*; import lombok.extern.slf4j.Slf4j; import net.okair.springcloud.common.core.entity.vo.Result; import net.okair.springcloud.gateway.admin.entity.form.GatewayRouteForm; import net.okair.springcloud.gateway.admin.entity.form.GatewayRouteQueryForm; import net.okair.springcloud.gateway.admin.entity.param.GatewayRouteQueryParam; import net.okair.springcloud.gateway.admin.entity.po.GatewayRoute; import net.okair.springcloud.gateway.admin.entity.vo.GatewayRouteVo; import net.okair.springcloud.gateway.admin.service.IGatewayRouteService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; /** * @author LiuShiZeng * @since 2020/1/14 */ @RestController @RequestMapping("/gateway/routes") @Api("gateway routes") @Slf4j public class GatewayRouteController { @Autowired private IGatewayRouteService gatewayRoutService; @ApiOperation(value = "新增网关路由", notes = "新增一个网关路由") @ApiImplicitParam(name = "gatewayRoutForm", value = "新增网关路由form表单", required = true, dataType = "GatewayRouteForm") @PostMapping public Result add(@Valid @RequestBody GatewayRouteForm gatewayRoutForm) { log.info("name:", gatewayRoutForm); GatewayRoute gatewayRout = gatewayRoutForm.toPo(GatewayRoute.class); return Result.success(gatewayRoutService.add(gatewayRout)); } @ApiOperation(value = "删除网关路由", notes = "根据url的id来指定删除对象") @ApiImplicitParam(paramType = "path", name = "id", value = "网关路由ID", required = true, dataType = "long") @DeleteMapping(value = "/{id}") public Result delete(@PathVariable String id) { return Result.success(gatewayRoutService.delete(id)); } @ApiOperation(value = "修改网关路由", notes = "修改指定网关路由信息") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "网关路由ID", required = true, dataType = "long"), @ApiImplicitParam(name = "gatewayRoutForm", value = "网关路由实体", required = true, dataType = "GatewayRouteForm") }) @PutMapping(value = "/{id}") public Result update(@PathVariable String id, @Valid @RequestBody GatewayRouteForm gatewayRoutForm) { GatewayRoute gatewayRout = gatewayRoutForm.toPo(GatewayRoute.class); gatewayRout.setId(id); return Result.success(gatewayRoutService.update(gatewayRout)); } @ApiOperation(value = "获取网关路由", notes = "根据id获取指定网关路由信息") @ApiImplicitParam(paramType = "path", name = "id", value = "网关路由ID", required = true, dataType = "long") @GetMapping(value = "/{id}") public Result get(@PathVariable String id) { log.info("get with id:{}", id); return Result.success(new GatewayRouteVo(gatewayRoutService.get(id))); } @ApiOperation(value = "根据uri获取网关路由", notes = "根据uri获取网关路由信息,简单查询") @ApiImplicitParam(paramType = "query", name = "name", value = "网关路由路径", required = true, dataType = "string") @ApiResponses( @ApiResponse(code = 200, message = "处理成功", response = Result.class) ) @GetMapping public Result getByUri(@RequestParam String uri) { return Result.success(gatewayRoutService.query(new GatewayRouteQueryParam(uri)).stream().findFirst()); } @ApiOperation(value = "搜索网关路由", notes = "根据条件查询网关路由信息") @ApiImplicitParam(name = "gatewayRoutQueryForm", value = "网关路由查询参数", required = true, dataType = "GatewayRouteQueryForm") @ApiResponses( @ApiResponse(code = 200, message = "处理成功", response = Result.class) ) @PostMapping(value = "/conditions") public Result search(@Valid @RequestBody GatewayRouteQueryForm gatewayRouteQueryForm) { return Result.success(gatewayRoutService.query(gatewayRouteQueryForm.toParam(GatewayRouteQueryParam.class))); } @ApiOperation(value = "重载网关路由", notes = "将所以网关的路由全部重载到redis中") @ApiResponses( @ApiResponse(code = 200, message = "处理成功", response = Result.class) ) @PostMapping(value = "/overload") public Result overload() { return Result.success(gatewayRoutService.overload()); } @ApiOperation(value = "获取所有网关路由", notes = "获取所有网关路由") @ApiResponses( @ApiResponse(code = 200, message = "处理成功", response = Result.class) ) @GetMapping(value = "/all") public Result getAll(){ List<GatewayRoute> list = gatewayRoutService.getAll(); return Result.success(list); } }
42.093458
125
0.704041
9227552b424c7b064948637b4c83c016dc15c1c9
188
package me.rubenicos.mc.picospacos.core.paco.rule.comparator; import me.rubenicos.mc.picospacos.core.paco.rule.ComparatorType; public class EqualComparator implements ComparatorType { }
31.333333
64
0.835106
7b35988d86dd90b189652a2407e7d0b418cf882a
545
package org.loader.shotcutsstatic; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; /** * Created by qibin on 16-10-20. */ public class SettingsActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setTextSize(40); tv.setText("设置"); setContentView(tv); } }
24.772727
66
0.715596
3da821cb72e66c1be6faf0b24aa3d007262d27b3
575
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static String repeat(char c, int n) { String s = ""; for (int i = 0; i < n; i++) { s += c; } return s; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); for (int i = 1; i <= n; i++) { System.out.println(repeat(' ', n-i) + "" + repeat('#', i)); } } }
20.535714
71
0.45913
ec86ec93fca1a948b06c611e42de9e9407783c99
4,020
package therent.view.delivery; import com.jfoenix.controls.JFXButton; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Tab; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import therent.Main; import therent.control.deliver.CDeliver; import therent.model.beans.DetalleEntrega; import therent.model.beans.DetalleRenta; import java.sql.SQLException; public class DeliveryWindowController{ @FXML private Tab tab_pane_entrega; @FXML private TableView<DetalleEntrega> tabla_entrega; @FXML private TableColumn<DetalleEntrega, String> column_auto; @FXML private TableColumn<DetalleEntrega, Integer> column_año; @FXML private TableColumn<DetalleEntrega, String> column_color; @FXML private TableColumn<DetalleEntrega, String> column_placa; @FXML private TableColumn<DetalleEntrega, String> column_cliente; @FXML private Tab tab_pane_recepcion; @FXML private TableView<DetalleEntrega> tabla_recepcion; @FXML private TableColumn<DetalleEntrega, String> column_auto2; @FXML private TableColumn<DetalleEntrega, Integer> column_año2; @FXML private TableColumn<DetalleEntrega, String> column_color2; @FXML private TableColumn<DetalleEntrega, String> column_placa2; @FXML private TableColumn<DetalleEntrega, String> column_cliente2; @FXML private JFXButton fx_button_entrega; @FXML private JFXButton fx_button_recibo; private ObservableList<DetalleEntrega> aEntregar; private ObservableList<DetalleEntrega> aRecibir; private Main main; public void setMain(Main main) { this.main = main; } public void initialize(){ column_auto.setCellValueFactory(dv->dv.getValue().autoProperty()); column_año.setCellValueFactory(dv->dv.getValue().añoProperty().asObject()); column_color.setCellValueFactory(dv->dv.getValue().colorProperty()); column_placa.setCellValueFactory(dv->dv.getValue().placaProperty()); column_cliente.setCellValueFactory(dv->dv.getValue().clienteProperty()); column_auto2.setCellValueFactory(dv->dv.getValue().autoProperty()); column_año2.setCellValueFactory(dv->dv.getValue().añoProperty().asObject()); column_color2.setCellValueFactory(dv->dv.getValue().colorProperty()); column_placa2.setCellValueFactory(dv->dv.getValue().placaProperty()); column_cliente2.setCellValueFactory(dv->dv.getValue().clienteProperty()); refreshTables(); } public void refreshTables(){ try { aEntregar= FXCollections.observableArrayList(CDeliver.aEntregar()); aRecibir=FXCollections.observableArrayList(CDeliver.aRecibir()); } catch (SQLException e) { e.printStackTrace(); }finally { tabla_entrega.setItems(aEntregar); tabla_recepcion.setItems(aRecibir); } } @FXML public void handleEntrega(){ DetalleEntrega det=tabla_entrega.getSelectionModel().getSelectedItem(); if (det==null){ msgerr("Por favor seleccione un elemento de la tabla"); return; } main.showEntregar(det, false); refreshTables(); } @FXML public void handleRecibo(){ DetalleEntrega det=tabla_recepcion.getSelectionModel().getSelectedItem(); if (det==null){ msgerr("Por favor seleccione un elemento de la tabla"); return; } main.showEntregar(det,true); refreshTables(); } @FXML public void handleBack(){ main.redirectMain(); } @FXML public void msgerr(String msg){ Alert al=new Alert(Alert.AlertType.ERROR); al.setTitle("TheRent Link System"); al.setHeaderText("ERROR"); al.setContentText(msg); al.showAndWait(); } }
27.724138
84
0.690796
585137f4b88bda86417857201f8bc7cdc3db75cf
4,110
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2014 - 2016 Board of Regents of the University of * Wisconsin-Madison, University of Konstanz and Brian Northan. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package net.imagej.ops.special.computer; import net.imagej.ops.special.BinaryOp; import net.imagej.ops.special.function.BinaryFunctionOp; import net.imagej.ops.special.inplace.BinaryInplaceOp; /** * A binary <em>computer</em> computes a result from two given inputs, storing * it into the specified output reference. The contents of the inputs are not * affected. * <p> * A binary computer may be treated as a {@link UnaryComputerOp} by holding the * second input constant, or treated as a {@link NullaryComputerOp} by holding * both inputs constant. * </p> * * @author Curtis Rueden * @param <I1> type of first input * @param <I2> type of second input * @param <O> type of output * @see BinaryFunctionOp * @see BinaryInplaceOp */ public interface BinaryComputerOp<I1, I2, O> extends BinaryOp<I1, I2, O>, UnaryComputerOp<I1, O> { /** * Computes the output given two inputs. * * @param input1 first argument to the computation, which * <em>must be non-null</em> * @param input2 second argument to the computation, which * <em>must be non-null</em> * @param output object where the computation's result will be stored, which * <em>must be non-null and a different object than * {@code input1} and {@code input2}</em> */ void compute2(I1 input1, I2 input2, O output); // -- BinaryOp methods -- @Override default O run(final I1 input1, final I2 input2, final O output) { // check computer preconditions if (input1 == null) throw new NullPointerException("input1 is null"); if (input2 == null) throw new NullPointerException("input2 is null"); if (output == null) throw new NullPointerException("output is null"); if (input1 == output) { throw new IllegalArgumentException("Computer expects input1 != output"); } if (input2 == output) { throw new IllegalArgumentException("Computer expects input2 != output"); } // compute the result compute2(input1, input2, output); return output; } // -- UnaryComputerOp methods -- @Override default void compute1(final I1 input, final O output) { compute2(input, in2(), output); } // -- Runnable methods -- @Override default void run() { setOutput(run(in1(), in2(), out())); } // -- Threadable methods -- @Override default BinaryComputerOp<I1, I2, O> getIndependentInstance() { // NB: We assume the op instance is thread-safe by default. // Individual implementations can override this assumption if they // have state (such as buffers) that cannot be shared across threads. return this; } }
35.73913
79
0.720195
f7f637570d95954927f6e02d0856ef24b6257a8c
875
package cc.cc4414.spring.resource.core; import java.io.Serializable; import java.util.List; import lombok.Data; import lombok.experimental.Accessors; /** * 基础用户,一些用户的公共字段,需要用到这些字段的用户类直接继承该类 * * @author cc 2019年10月21日 */ @Data @Accessors(chain = true) public class BaseUser implements Serializable { private static final long serialVersionUID = 1L; /** 主键 */ private String id; /** 名称 */ private String name; /** 部门id */ private String deptId; /** 部门名称 */ private String deptName; /** 逻辑删除:0为未删除,1为删除 */ private Integer deleted; /** 禁用:0为未禁用,1为禁用 */ private Integer disabled; /** 租户id */ private String tenantId; /** 用户名 */ private String username; /** 密码 */ private String password; /** 用户类型:0为普通用户,1为第三方应用 */ private Integer type; /** 部门id列表 */ private List<String> deptIds; }
16.203704
50
0.645714
b5660729ee5e843fd7887e7274e61af53129a3cb
6,348
/** * Copyright 2016 Jan Petendi <jan.petendi@p-acs.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.petendi.seccoco.android; import android.annotation.TargetApi; import android.os.Build; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyProperties; import org.spongycastle.util.encoders.Base64; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.StringReader; import java.security.InvalidKeyException; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.util.Properties; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.IvParameterSpec; import de.petendi.commons.crypto.AsymmetricCrypto; import de.petendi.commons.crypto.connector.SecurityProviderConnector; import de.petendi.seccoco.android.connector.AndroidSecurityProviderConnector; import de.petendi.seccoco.android.connector.SCSecurityProviderConnector; public class AndroidAPI23Configurator extends Configurator { private PKCS12Configurator pkcs12Configurator; private final File dataDirectory; private char[] appSecret = null; private static final String ALIAS = Constants.SECCOCO + "AES"; private static final String PASSWORD_FILE = "api23.props"; public AndroidAPI23Configurator(File dataDirectory) { this.dataDirectory = dataDirectory; pkcs12Configurator = null; } @Override boolean isConfigured() { try { KeyStore ks = KeyStore.getInstance(Constants.ANDROID_KEY_STORE); ks.load(null); return ks.containsAlias(ALIAS); } catch (Exception e) { throw new IllegalStateException(e); } } @Override Token readToken() { KeyStore keyStore; try { keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); SecretKey key = (SecretKey) keyStore.getKey(ALIAS, null); File passwordFile = new File(dataDirectory, PASSWORD_FILE); final String dat1 = "dat1"; readAppPassword(dat1,passwordFile,key); pkcs12Configurator = new PKCS12Configurator(dataDirectory, new String(appSecret).getBytes()); return pkcs12Configurator.readToken(); } catch (Exception e) { throw new IllegalStateException(e); } } @TargetApi(Build.VERSION_CODES.M) @Override void configure() { KeyGenerator keyGenerator; try { keyGenerator = KeyGenerator.getInstance( KeyProperties.KEY_ALGORITHM_AES, Constants.ANDROID_KEY_STORE); keyGenerator.init( new KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_GCM) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) .build()); SecretKey key = keyGenerator.generateKey(); File passwordFile = new File(dataDirectory, PASSWORD_FILE); final String dat1 = "dat1"; storeAppPassword(dat1,passwordFile,key); pkcs12Configurator = new PKCS12Configurator(dataDirectory, new String(appSecret).getBytes()); pkcs12Configurator.configure(); } catch (Exception e) { throw new IllegalStateException(e); } } @Override Seccoco.UnlockResult getUnlockResult() { return pkcs12Configurator.getUnlockResult(); } @TargetApi(Build.VERSION_CODES.M) private void readAppPassword(String dat1, File passwordFile, SecretKey key) { Properties metaDataProps = new Properties(); try { metaDataProps.load(new FileReader(passwordFile)); String encBase64 = metaDataProps.getProperty(dat1); String ivBase64 = metaDataProps.getProperty(dat1+"iv"); byte[] iv = Base64.decode(ivBase64); byte[] enc = Base64.decode(encBase64); byte[] decrypted; GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128,iv); Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, key,gcmParameterSpec); decrypted = cipher.doFinal(enc); appSecret = Base64.toBase64String(decrypted).toCharArray(); } catch (Exception e) { throw new IllegalArgumentException(e); } } private void storeAppPassword(String key, File passwordFile,SecretKey secretKey) { Properties metaDataProps = new Properties(); byte[] password = new SCSecurityProviderConnector().generateSecretKey().getEncoded(); appSecret = Base64.toBase64String(password).toCharArray(); Cipher cipher; try { cipher = Cipher.getInstance("AES/GCM/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] iv = cipher.getIV(); byte[] encryptedPassword = cipher.doFinal(password); byte[] base64 = Base64.encode(encryptedPassword); byte[] base64Iv = Base64.encode(iv); metaDataProps.put(key, new String(base64)); metaDataProps.put(key+"iv", new String(base64Iv)); metaDataProps.store(new FileWriter(passwordFile), "Data"); } catch (Exception e) { throw new IllegalArgumentException(e); } } }
38.240964
105
0.677221
2e9a9ec352e20f798fe5c4dc14658708864f2849
429
package com.JTweaks.Main; import com.JTweaks.Main.Items.*; import cpw.mods.fml.common.*; import cpw.mods.fml.common.Mod.*; import cpw.mods.fml.common.event.*; import cpw.mods.fml.common.registry.*; import net.minecraft.item.*; public class Fuel implements IFuelHandler { @Override public int getBurnTime(ItemStack fuel) { if( fuel.getItem() == JItems.ItemBackpack) return 200; else return 0; } }
21.45
45
0.701632
b4e070048a61cd139d2f895d203d1d44dceb317e
2,671
package wusc.edu.pay.facade.user.service.impl; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import wusc.edu.pay.common.exceptions.BizException; import wusc.edu.pay.common.page.PageBean; import wusc.edu.pay.common.page.PageParam; import wusc.edu.pay.core.user.biz.UserOperatorBiz; import wusc.edu.pay.facade.user.entity.UserOperator; import wusc.edu.pay.facade.user.service.UserOperatorFacade; /** * * @描述: 用户操作员Dubbo服务接口实现类. * @作者: WuShuicheng. * @创建: 2014-5-28,下午12:01:07 * @版本: V1.0 * */ @Component("userOperatorFacade") public class UserOperatorFacadeImpl implements UserOperatorFacade{ @Autowired private UserOperatorBiz userOperatorBiz; /** * 根据登录名获取用户操作员信息.<br/> * @param loginName 登录名. * @return */ public UserOperator getUserOperatorByLoginName(String loginName) { return userOperatorBiz.getUserOperatorByLoginName(loginName); } /** * 创建用户操作员信息.<br/> * @param operator <br/> * @return ID.<br/> * @throws BizException */ public long createUserOperator(UserOperator operator) { return userOperatorBiz.createMerchantOperator(operator); } /** * 更新用户操作员信息.<br/> * @param operator.<br/> * @return * @throws BizException */ public long updateUserOperator(UserOperator operator) { return userOperatorBiz.updateUserOperator(operator); } /** * 根据ID获取操作员信息.<br/> * @param id 操作员ID.<br/> * @return operator.<br/> * @throws BizException */ public UserOperator getUserOperatorById(long id) { return userOperatorBiz.getUserOperatorById(id); } /** * 根据商户ID列出该商户的所有操作员. * @param merchantId 商户ID. * @return MerchantOperatorList . */ public List<UserOperator> listUserOperatorByUserNo(String userNo) { return userOperatorBiz.listUserOperatorByUserNo(userNo); } /** * 分页查询 * @param pageParam * @param params * @return */ public PageBean listUserOperatorForPage(PageParam pageParam, Map<String,Object> params) { return userOperatorBiz.listUserOperatorForPage(pageParam, params); } /*** * 根据用户编号,修改该用户下所有操作员的状态.<br/> * @param userNo 用户编号.<br/> * @param status 要更新的状态.<br/> */ public void updateUserOperatorStatusByUserNo(String userNo, int status) { userOperatorBiz.updateUserOperatorStatusByUserNo(userNo, status); } /*** * 重置操作员密码 * @param loginName 登录名 * @param newPwd 新密码-加密后的数据 */ public void resetUserOperatorPassword(String loginName, String newPwd) { userOperatorBiz.resetUserOperatorPassword(loginName, newPwd); } }
24.731481
91
0.707226
8550827a85f97c270dfb0540c1c22be7b0284f32
261
package io.github.fatihbozik.oca.polymorphism.example3; public class Capybara extends Rodent { public static void main(String[] args) { Rodent rodent = new Rodent(); Capybara capybara = (Capybara) rodent; // Throws ClassCastException at runtime } }
26.1
79
0.743295
f34bd60302f10fee8ddfc09d1ee7fe69aba7593c
1,521
/* * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.server.pm; import android.os.Binder; class KeySetHandle extends Binder{ private final long mId; private int mRefCount; protected KeySetHandle(long id) { mId = id; mRefCount = 1; } /* * Only used when reading state from packages.xml */ protected KeySetHandle(long id, int refCount) { mId = id; mRefCount = refCount; } public long getId() { return mId; } protected int getRefCountLPr() { return mRefCount; } /* * Only used when reading state from packages.xml */ protected void setRefCountLPw(int newCount) { mRefCount = newCount; return; } protected void incrRefCountLPw() { mRefCount++; return; } protected int decrRefCountLPw() { mRefCount--; return mRefCount; } }
23.765625
79
0.637738
366b0fa227081c5b39dea82fbd8e9ef64e1aeea4
8,892
package org.iota.jota.dto.response; /** * * Contains information about the result of a successful {@code getNodeInfo} API call. * */ public class GetNodeInfoResponse extends AbstractResponse { /** * Name of the IOTA software you're currently using. (IRI stands for IOTA Reference Implementation) */ private String appName; /** * The version of the IOTA software this node is running. */ private String appVersion; /** * Available cores for JRE on this node. */ private int jreAvailableProcessors; /** * The amount of free memory in the Java Virtual Machine. */ private long jreFreeMemory; /** * The JRE version this node runs on */ private String jreVersion; /** * The maximum amount of memory that the Java virtual machine will attempt to use. */ private long jreMaxMemory; /** * The total amount of memory in the Java virtual machine. */ private long jreTotalMemory; /** * The hash of the latest transaction that was signed off by the coordinator. */ private String latestMilestone; /** * Index of the {@link #latestMilestone} */ private int latestMilestoneIndex; /** * The hash of the latest transaction which is solid and is used for sending transactions. * For a milestone to become solid, your local node must approve the subtangle of coordinator-approved transactions, * and have a consistent view of all referenced transactions. */ private String latestSolidSubtangleMilestone; /** * Index of the {@link #latestSolidSubtangleMilestone} */ private int latestSolidSubtangleMilestoneIndex; /** * The start index of the milestones. * This index is encoded in each milestone transaction by the coordinator */ private int milestoneStartIndex; /** * Number of neighbors this node is directly connected with. */ private int neighbors; /** * The amount of transaction packets which are currently waiting to be broadcast. */ private int packetsQueueSize; /** * The difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC */ private long time; /** * Number of tips in the network. */ private int tips; /** * When a node receives a transaction from one of its neighbors, * this transaction is referencing two other transactions t1 and t2 (trunk and branch transaction). * If either t1 or t2 (or both) is not in the node's local database, * then the transaction hash of t1 (or t2 or both) is added to the queue of the "transactions to request". * At some point, the node will process this queue and ask for details about transactions in the * "transaction to request" queue from one of its neighbors. * This number represents the amount of "transaction to request" */ private int transactionsToRequest; /** * Every node can have features enabled or disabled. * This list will contain all the names of the features of a node as specified in {@link Feature}. */ private String[] features; /** * The address of the Coordinator being followed by this node. */ private String coordinatorAddress; /** * Creates a new {@link GetNodeInfoResponse} * * @param appName {@link #appName} * @param appVersion {@link #appVersion} * @param jreAvailableProcessors {@link #jreAvailableProcessors} * @param jreFreeMemory {@link #jreFreeMemory} * @param jreVersion {@link #jreVersion} * @param maxMemory {@link #jreMaxMemory} * @param totalMemory {@link #jreTotalMemory} * @param latestMilestone {@link #latestMilestone} * @param latestMilestoneIndex {@link #latestMilestoneIndex} * @param latestSolidSubtangleMilestone {@link #latestSolidSubtangleMilestone} * @param latestSolidSubtangleMilestoneIndex {@link #latestSolidSubtangleMilestoneIndex} * @param milestoneStartIndex {@link #milestoneStartIndex} * @param neighbors {@link #neighbors} * @param packetsQueueSize {@link #packetsQueueSize} * @param currentTimeMillis {@link #time} * @param tips {@link #tips} * @param numberOfTransactionsToRequest {@link #transactionsToRequest} * @param features {@link #features} * @param coordinatorAddress {@link #coordinatorAddress} * @return a {@link GetNodeInfoResponse} filled with all the provided parameters */ public static AbstractResponse create(String appName, String appVersion, int jreAvailableProcessors, long jreFreeMemory, String jreVersion, long maxMemory, long totalMemory, String latestMilestone, int latestMilestoneIndex, String latestSolidSubtangleMilestone, int latestSolidSubtangleMilestoneIndex, int milestoneStartIndex, int neighbors, int packetsQueueSize, long currentTimeMillis, int tips, int numberOfTransactionsToRequest, String[] features, String coordinatorAddress) { final GetNodeInfoResponse res = new GetNodeInfoResponse(); res.appName = appName; res.appVersion = appVersion; res.jreAvailableProcessors = jreAvailableProcessors; res.jreFreeMemory = jreFreeMemory; res.jreVersion = jreVersion; res.jreMaxMemory = maxMemory; res.jreTotalMemory = totalMemory; res.latestMilestone = latestMilestone; res.latestMilestoneIndex = latestMilestoneIndex; res.latestSolidSubtangleMilestone = latestSolidSubtangleMilestone; res.latestSolidSubtangleMilestoneIndex = latestSolidSubtangleMilestoneIndex; res.milestoneStartIndex = milestoneStartIndex; res.neighbors = neighbors; res.packetsQueueSize = packetsQueueSize; res.time = currentTimeMillis; res.tips = tips; res.transactionsToRequest = numberOfTransactionsToRequest; res.features = features; res.coordinatorAddress = coordinatorAddress; return res; } /** * * @return {@link #appName} */ public String getAppName() { return appName; } /** * * @return {@link #appVersion} */ public String getAppVersion() { return appVersion; } /** * * @return {@link #jreAvailableProcessors} */ public int getJreAvailableProcessors() { return jreAvailableProcessors; } /** * * @return {@link #jreFreeMemory} */ public long getJreFreeMemory() { return jreFreeMemory; } /** * * @return {@link #jreMaxMemory} */ public long getJreMaxMemory() { return jreMaxMemory; } /** * * @return {@link #jreTotalMemory} */ public long getJreTotalMemory() { return jreTotalMemory; } /** * * @return {@link #jreVersion} */ public String getJreVersion() { return jreVersion; } /** * * @return {@link #latestMilestone} */ public String getLatestMilestone() { return latestMilestone; } /** * * @return {@link #latestMilestoneIndex} */ public int getLatestMilestoneIndex() { return latestMilestoneIndex; } /** * * @return {@link #latestSolidSubtangleMilestone} */ public String getLatestSolidSubtangleMilestone() { return latestSolidSubtangleMilestone; } /** * * @return {@link #latestSolidSubtangleMilestoneIndex} */ public int getLatestSolidSubtangleMilestoneIndex() { return latestSolidSubtangleMilestoneIndex; } /** * * @return {@link #milestoneStartIndex} */ public int getMilestoneStartIndex() { return milestoneStartIndex; } /** * * @return {@link #neighbors} */ public int getNeighbors() { return neighbors; } /** * * @return {@link #packetsQueueSize} */ public int getPacketsQueueSize() { return packetsQueueSize; } /** * * @return {@link #time} */ public long getTime() { return time; } /** * * @return {@link #tips} */ public int getTips() { return tips; } /** * * @return {@link #transactionsToRequest} */ public int getTransactionsToRequest() { return transactionsToRequest; } /** * * @return {@link #features} */ public String[] getFeatures() { return features; } /** * * @return {@link #coordinatorAddress} */ public String getCoordinatorAddress() { return coordinatorAddress; } }
27.444444
124
0.631691
606f006dadb6abbb9d0c3f16318a24e92ff26dc2
2,084
/* * 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 daos; import beans.RegisterBean; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import utilities.DBConnection; /** * * @author Home */ public class RegisterDao { public String registerUser(RegisterBean registerBean){ String name = registerBean.getName(); String username = registerBean.getUsername(); String rollno = registerBean.getRollno(); String date = registerBean.getDate(); String classSpec = registerBean.getClass_spec(); String specification = registerBean.getSpecification(); String password = registerBean.getPassword(); Connection con = null; PreparedStatement preparedStatement = null; try { con = DBConnection.createConnection(); String query = "insert into users(name, username, rollno, dateOfJoin, classSpec, specification ,passwordHash) values (?,?,?,?,?,?,?)"; //Insert user details into the table 'USERS' preparedStatement = con.prepareStatement(query); //Making use of prepared statements here to insert bunch of data preparedStatement.setString(1, name); preparedStatement.setString(2, username); preparedStatement.setString(3, rollno); preparedStatement.setString(4, date); preparedStatement.setString(5, classSpec); preparedStatement.setString(6, specification); preparedStatement.setString(7, password); int i= preparedStatement.executeUpdate(); if (i!=0) //ensure data has been inserted into the database return "User Registered Successfully."; } catch(SQLException e) { e.printStackTrace(); } return "User Registration Failed..!"; // On failure, send a message from here. } }
38.592593
188
0.652591
0f6c5affb3175f97de0ff2f4cf2051c13c0f1823
4,078
package org.jetbrains.android.formatter; import com.intellij.application.options.XmlCodeStyleSettingsProvider; import com.intellij.ide.highlighter.XmlFileType; import com.intellij.notification.NotificationDisplayType; import com.intellij.notification.NotificationsConfiguration; import com.intellij.notification.impl.NotificationsConfigurationImpl; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.ui.EditorNotificationPanel; import com.intellij.ui.EditorNotifications; import org.jetbrains.android.facet.AndroidFacet; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; /** * @author Eugene.Kudelevsky */ public class AndroidCodeStyleNotificationProvider extends EditorNotifications.Provider<AndroidCodeStyleNotificationProvider.MyPanel> { private static final Key<MyPanel> KEY = Key.create("android.xml.code.style.notification"); @NonNls private static final String ANDROID_XML_CODE_STYLE_NOTIFICATION_GROUP = "Android XML code style notification"; private final Project myProject; private final EditorNotifications myNotifications; public AndroidCodeStyleNotificationProvider(Project project, final EditorNotifications notifications) { myProject = project; myNotifications = notifications; } @Override public Key<MyPanel> getKey() { return KEY; } @Nullable @Override public MyPanel createNotificationPanel(VirtualFile file, FileEditor fileEditor) { if (file.getFileType() != XmlFileType.INSTANCE || !(fileEditor instanceof TextEditor)) { return null; } final Module module = ModuleUtilCore.findModuleForFile(file, myProject); if (module == null) { return null; } final AndroidFacet facet = AndroidFacet.getInstance(module); if (facet == null) { return null; } final VirtualFile parent = file.getParent(); final VirtualFile resDir = parent != null ? parent.getParent() : null; if (resDir == null || !facet.getLocalResourceManager().isResourceDir(resDir)) { return null; } final CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(myProject); final AndroidXmlCodeStyleSettings androidSettings = AndroidXmlCodeStyleSettings.getInstance(settings); if (androidSettings.USE_CUSTOM_SETTINGS) { return null; } if (NotificationsConfigurationImpl.getSettings(ANDROID_XML_CODE_STYLE_NOTIFICATION_GROUP). getDisplayType() == NotificationDisplayType.NONE) { return null; } NotificationsConfiguration.getNotificationsConfiguration().register( ANDROID_XML_CODE_STYLE_NOTIFICATION_GROUP, NotificationDisplayType.BALLOON, false); return new MyPanel(); } public class MyPanel extends EditorNotificationPanel { MyPanel() { setText("You can format your XML resources in the 'standard' Android way. " + "Choose 'Set from... | Android' in the XML code style settings."); createActionLabel("Open code style settings", new Runnable() { @Override public void run() { ShowSettingsUtil.getInstance().showSettingsDialog( myProject, XmlCodeStyleSettingsProvider.CONFIGURABLE_DISPLAY_NAME); myNotifications.updateAllNotifications(); } }); createActionLabel("Disable notification", new Runnable() { @Override public void run() { NotificationsConfiguration.getNotificationsConfiguration() .changeSettings(ANDROID_XML_CODE_STYLE_NOTIFICATION_GROUP, NotificationDisplayType.NONE, false); myNotifications.updateAllNotifications(); } }); } } }
37.412844
134
0.757479
0e49b1e58513c5a8b8cba52abd4271419d7c792c
671
package eu.dareed.rdfmapper.xml; import eu.dareed.eplus.model.idd.AnnotatedObject; import org.semanticweb.owlapi.vocab.OWL2Datatype; /** * @author <a href="mailto:kiril.tonev@kit.edu">Kiril Tonev</a> */ enum DataProperty { INTEGER(OWL2Datatype.XSD_INTEGER.getIRI().toString()), REAL(OWL2Datatype.XSD_DOUBLE.getIRI().toString()), ALPHA(OWL2Datatype.XSD_STRING.getIRI().toString()); final String typeURI; DataProperty(String typeURI) { this.typeURI = typeURI; } static DataProperty parseDataTypeInField(AnnotatedObject field) { return DataProperty.valueOf(field.getParameter("type").value().toUpperCase().trim()); } }
27.958333
93
0.718331
6c7a2e5938fc4500ac41973b33732f1a5034e86a
6,034
/* * 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 unifavip.estruturadados; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author douglasfrari */ public class VetorTest { public VetorTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of adicionaAluno method, of class Vetor. * @return */ public Vetor carregarAlunos(){ Vetor vetor = new Vetor(); for (int i = 0; i < 500000; i++) { Aluno aluno = new Aluno("aluno"+i); vetor.adicionaAluno(aluno); } return vetor; } @Test public void testRemover(){ Vetor vetor = this.carregarAlunos(); vetor.remove(50); assertTrue(vetor.tamanho() == 499999); } @Test public void testAdicionaAluno_Aluno() { System.out.println("adicionaAluno"); long inicio = System.currentTimeMillis(); Vetor vetor = new Vetor(); for (int i = 0; i < 500000; i++) { Aluno aluno = new Aluno("aluno"+i); vetor.adicionaAluno(aluno); } long fim = System.currentTimeMillis(); System.out.println((fim - inicio)/1000 +"s"); assertTrue(vetor.tamanho() == 500000); } @Test public void testAdicionaAluno_comeco(){ //adicion um aluno no comeco da lista Vetor vetor = this.carregarAlunos(); System.out.println("Adiciona aluno no inicio da lista"); long inicio = System.currentTimeMillis(); Aluno aluno_inicio = new Aluno("zuckerberg"); int posicao_inicio = 0; vetor.adicionaAluno(posicao_inicio, aluno_inicio); long fim = System.currentTimeMillis(); System.out.print((fim - inicio)/1000 +" s"); assertTrue(vetor.pegaAluno(posicao_inicio) == aluno_inicio); assertTrue(vetor.tamanho() == 500001); } /** * Test of adicionaAluno method, of class Vetor. */ @Test public void testAdicionarAluno_fim(){ //adiciona um aluno no fim da lista Vetor vetor = this.carregarAlunos(); System.out.println("Adiciona aluno no fim da lista"); Aluno aluno_fim = new Aluno("Walison Filipe"); int posicao_fim = vetor.tamanho()-1; vetor.adicionaAluno(posicao_fim, aluno_fim); assertTrue(vetor.pegaAluno(posicao_fim) == aluno_fim); } @Test public void testeAdicionAluno_meio(){ Vetor vetor = this.carregarAlunos(); System.out.println("adiciona Aluno no meio da lista"); Aluno aluno_meio = new Aluno("Bill Gates"); int posicao = (vetor.tamanho()/2)-1; vetor.adicionaAluno(posicao-1, aluno_meio); assertTrue(vetor.pegaAluno(posicao-1) == aluno_meio); } @Test public void testAdicionaAluno_int_Aluno() { //adiciona 500.000 registros na lista de alunos Vetor vetor = new Vetor(); for (int i = 0; i < 500000; i++) { Aluno aluno = new Aluno("aluno"+i); vetor.adicionaAluno(aluno); } System.out.println("totalAlnos = "+vetor.tamanho()); assertTrue(vetor.tamanho() == 500000); } /** * Test of pegaAluno method, of class Vetor. */ @Test public void testPegaAluno() { System.out.println("pegaAluno"); int posicao = 0; Vetor instance = new Vetor(); Aluno expResult = new Aluno("Batman"); instance.adicionaAluno(expResult); Aluno result = instance.pegaAluno(posicao); assertEquals(expResult, result); assertTrue(expResult.equals(result)); } /** * Test of remove method, of class Vetor. */ @Test public void testRemove() { System.out.println("remove"); int posicao = 0; Vetor instance = new Vetor(); Aluno aluno = new Aluno("Ryu"); instance.adicionaAluno(aluno); instance.remove(posicao); assertTrue(instance.tamanho() == 0); } /** * Test of contem method, of class Vetor. */ @Test public void testContem() { System.out.println("contem"); Aluno aluno = new Aluno("Xuxa"); Vetor instance = new Vetor(); instance.adicionaAluno(aluno); boolean expResult = true; boolean result = instance.contem(aluno); assertEquals(expResult, result); } /** * Test of tamanho method, of class Vetor. */ @Test public void testTamanho() { System.out.println("tamanho"); Vetor instance = new Vetor(); int expResult = 0; int result = instance.tamanho(); assertEquals(expResult, result); } /** * Test of listaTodos method, of class Vetor. */ @Test public void testListaTodos() { System.out.println("listaTodos"); Vetor instance = new Vetor(); String expResult = "[]"; String result = instance.listaTodos(); assertEquals(expResult, result); } /** * Test of toString method, of class Vetor. */ @Test public void testToString() { System.out.println("toString"); Vetor instance = new Vetor(); String expResult = "[]"; String result = instance.toString(); assertEquals(expResult, result); } }
25.896996
79
0.561651
8bcfae62277501c3ccc75b00a940a996c7d52a36
6,083
package edu.ucla.cs.wis.bigdatalog.compiler; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import edu.ucla.cs.wis.bigdatalog.compiler.predicate.Predicate; import edu.ucla.cs.wis.bigdatalog.compiler.type.CompilerTypeBase; import edu.ucla.cs.wis.bigdatalog.compiler.type.CompilerType; import edu.ucla.cs.wis.bigdatalog.compiler.variable.CompilerVariableList; public class Rule extends CompilerTypeBase implements Serializable{ private static final long serialVersionUID = 1L; protected String id; protected Predicate head; protected List<Predicate> body; protected boolean isRewritten; // true if the rule was rewritten protected boolean isResultOfRewrite; // true if the rule is a result of a rewrite protected boolean allFunctionsMonotonic; protected boolean generateSealingAggregate; protected MonotonicRuleType monotonicRuleType; protected Rule originalRule; // to track the original program public Rule(String id, Predicate head, List<Predicate> body) { super(CompilerType.RULE); this.id = id; this.head = head; if (body == null) this.body = new ArrayList<>(); else this.body = body; this.isRewritten = false; this.isResultOfRewrite = false; this.allFunctionsMonotonic = false; this.generateSealingAggregate = false; this.monotonicRuleType = MonotonicRuleType.N2N; } public String getRuleId() { return this.id; } public Predicate getHead() { return this.head; } public List<Predicate> getBody() { return this.body; } public boolean isRewritten() { return this.isRewritten; } public void setRewritten(boolean value) { this.isRewritten = value; } public boolean isResultOfRewrite() { return this.isResultOfRewrite; } public void setResultOfRewrite(boolean value) { this.isResultOfRewrite = value; } public Rule getOriginalRule() { return this.originalRule; } public void setOriginalRule(Rule originalRule) { this.originalRule = originalRule; } public void setAnnotations(String text) { if (text.toLowerCase().contains("monotonic")) this.allFunctionsMonotonic = true; else if (text.toLowerCase().contains("final")) this.generateSealingAggregate = true; } public boolean allFunctionsMonotonic() { return this.allFunctionsMonotonic; } public boolean generateSealingAggregate() { return this.generateSealingAggregate; } public MonotonicRuleType getMonotonicRuleType() { return this.monotonicRuleType; } public void setMonotonicRuleType(MonotonicRuleType monotonicRuleType) { this.monotonicRuleType = monotonicRuleType; } public Rule copy() { CompilerVariableList variableList = new CompilerVariableList(); Predicate newHead = this.head.copy(variableList); List<Predicate> newBody = new ArrayList<>(); for (Predicate goal : this.body) newBody.add(goal.copy()); return new Rule(this.id, newHead, newBody); } public int getNumberOfLiterals() { return this.body.size(); } public Predicate getLiteral(int position) { return this.body.get(position); } public String toString() { StringBuilder output = new StringBuilder(); output.append(this.id); output.append(") "); output.append(this.head.toString()); if (this.body.size() > 0) { output.append(" <- "); String spacer = ""; for (int i = 0; i < output.length(); i++) spacer += " "; for (int i = 0; i < this.body.size(); i++) { if (i > 0) { output.append(", "); if (i % 3 == 0) { output.append("\n"); output.append(spacer); } } output.append(this.body.get(i).toString()); } } output.append("."); return output.toString(); } public String toStringIndent(int level) { StringBuilder output = new StringBuilder(); output.append(super.toStringIndent(level)); output.append(this.id); output.append(") "); output.append(this.head.toString()); if (this.body.size() > 0) { output.append(" <- "); String spacer = ""; for (int i = 0; i < output.length(); i++) spacer += " "; for (int i = 0; i < this.body.size(); i++) { if (i > 0) { output.append(", "); if (i % 3 == 0) { output.append("\n"); output.append(spacer); } } output.append(this.body.get(i).toString()); } } output.append("."); return output.toString(); } public String toStringCompilable() { StringBuilder output = new StringBuilder(); output.append(this.head.toString()); if (this.body.size() > 0) { output.append(" <- "); for (int i = 0; i < this.body.size(); i++) { if (i > 0) output.append(", "); output.append(this.body.get(i).toStringCompilable()); } } output.append("."); return output.toString(); } public String toJson() { StringBuilder output = new StringBuilder(); //output.append("{\"head\":"); output.append("{\"head\":\""); output.append(this.head.toStringShort()); //output.append(this.head.toJson()); output.append("\", \"body\":["); if (this.body.size() > 0) { for (int i = 0; i < this.body.size(); i++) { if (i > 0) output.append(","); output.append("\""); //output.append(this.body.get(i).toJson()); output.append(this.body.get(i).toStringShort()); output.append("\""); } } output.append("]}"); return output.toString(); } @Override public CompilerTypeBase copy(CompilerVariableList variableList) { return copy(); } @Override public boolean equals(CompilerTypeBase other) { if (other == null) return false; if (!(other instanceof Rule)) return false; Rule otherRule = (Rule)other; if (!this.id.equals(otherRule.getRuleId())) return false; if (this.head == null && otherRule.getHead() != null) return false; if (!this.head.equals(otherRule.getHead())) return false; if (this.body == null && otherRule.getBody() != null) return false; if (this.body.size() != otherRule.getBody().size()) return false; for (int i = 0; i < this.body.size(); i++) if (!this.body.get(i).equals(otherRule.getBody().get(i))) return false; return true; } }
27.035556
85
0.668091
cb9aac3f5a63026bccefb1ab50b2bab0d734fd7a
215
package net.collaud.fablab.manager.data.type; /** * * @author Gaetan Collaud <gaetancollaud@gmail.com> */ public enum AuditAction { INSERT, UPDATE, SAVE, SIGNUP, DELETE, CONFIRM, LOGIN, LOGOUT, OTHER }
11.944444
51
0.697674
7577e20adb7e48405686b1454f2e79b03ffb171e
1,598
package io.jenkins.x.client.kube; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import io.fabric8.kubernetes.client.CustomResource; import java.util.HashMap; import java.util.Map; /** */ @JsonDeserialize( using = JsonDeserializer.None.class ) public class PipelineActivity extends CustomResource { private PipelineActivitySpec spec; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); public PipelineActivity() { setKind("PipelineActivity"); } @Override public String toString() { return "PipelineActivity{" + "apiVersion='" + getApiVersion() + '\'' + ", metadata=" + getMetadata() + ", spec=" + spec + '}'; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } public void setAdditionalProperties(Map<String, Object> additionalProperties) { this.additionalProperties = additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } public PipelineActivitySpec getSpec() { return spec; } public void setSpec(PipelineActivitySpec spec) { this.spec = spec; } }
27.084746
85
0.686483
d6ff1c721822faf162ef62f3211cf9ee9aa882c6
371
package com.example.einkbitcoinpriceticker.models; import java.time.LocalDateTime; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @AllArgsConstructor @NoArgsConstructor @Getter @Setter public class UserIpEntity { String userIp; String currency; Boolean nightMode; LocalDateTime lastPageRefresh; }
19.526316
50
0.827493
a197b082bbf1d9d4e20e6b12a4f8c782face7012
1,417
package controller; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.UserDAO; import entity.User; public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String phonenumber = request.getParameter("phone"); String password = request.getParameter("password"); System.out.println("phonenumber="+phonenumber); System.out.println("password="+password); UserDAO dao = new UserDAO(); List<User> users = dao.findAll(); System.out.println("size="+users.size()); for(User user : users){ String number = user.getPhonenumber(); String pwd = user.getPassword(); System.out.println("number="+number); System.out.println("pwd="+pwd); if((phonenumber.equals(number)&&password.equals(pwd))){ response.sendRedirect("html/Second.html"); }else{ request.setAttribute("login_failed","用户名或密码错误"); request.getRequestDispatcher("/WEB-INF/login_failed.jsp").forward(request, response); } } } }
32.953488
121
0.726182
2139e05f692f49cba9794ee85cfd35b63b105dd3
495
package net.su.common.items; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.su.client.gui.GuiRun; public class Book extends Item { public ItemStack onItemRightClick(ItemStack item, World world, EntityPlayer player) { Minecraft.getMinecraft().displayGuiScreen(new GuiRun()); return super.onItemRightClick(item, world, player); } }
29.117647
86
0.79798
09fd0e2bcdec414dab2edd2c039efd17c5d46b8e
753
package net.sorenon.mcxr.play.mixin.accessor; import com.mojang.math.Vector3f; import net.minecraft.client.Camera; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.BlockGetter; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; @Mixin(Camera.class) public interface CameraAcc { @Accessor("initialized") void ready(boolean ready); @Accessor("level") void area(BlockGetter area); @Accessor("entity") void focusedEntity(Entity entity); @Accessor("detached") void thirdPerson(boolean thirdPerson); @Accessor("xRot") void pitch(float pitch); @Accessor("yRot") void yaw(float yaw); @Accessor("left") Vector3f diagonalPlane(); }
22.147059
48
0.722444
eab1333225ac22d1d6e61a2b7b90e48b18944830
1,433
package br.com.tiagohs.popmovies.model.dto; import android.graphics.Bitmap; import android.os.Parcel; import android.os.Parcelable; /** * Created by Tiago on 22/01/2017. */ public class ImageSaveDTO implements Parcelable { private Bitmap mBitmap; private String mPath; public ImageSaveDTO(Bitmap bitmap, String path) { mBitmap = bitmap; mPath = path; } public Bitmap getBitmap() { return mBitmap; } public void setBitmap(Bitmap bitmap) { mBitmap = bitmap; } public String getPath() { return mPath; } public void setPath(String path) { mPath = path; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeParcelable(this.mBitmap, flags); dest.writeString(this.mPath); } protected ImageSaveDTO(Parcel in) { this.mBitmap = in.readParcelable(Bitmap.class.getClassLoader()); this.mPath = in.readString(); } public static final Parcelable.Creator<ImageSaveDTO> CREATOR = new Parcelable.Creator<ImageSaveDTO>() { @Override public ImageSaveDTO createFromParcel(Parcel source) { return new ImageSaveDTO(source); } @Override public ImageSaveDTO[] newArray(int size) { return new ImageSaveDTO[size]; } }; }
22.046154
107
0.629449
2ca79e0eba82d1caa7f9fd05f8328ce139180e55
1,144
package com.csc480.game; import com.badlogic.gdx.Application; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.backends.headless.HeadlessApplication; import com.badlogic.gdx.graphics.GL20; import org.junit.AfterClass; import org.junit.BeforeClass; import org.mockito.Mockito; public class TestRunner { private static Application application; @BeforeClass public static void init() { application = new HeadlessApplication(new ApplicationListener() { @Override public void create() {} @Override public void resize(int width, int height) {} @Override public void render() {} @Override public void pause() {} @Override public void resume() {} @Override public void dispose() {} }); Gdx.gl20 = Mockito.mock(GL20.class); Gdx.gl = Gdx.gl20; } @AfterClass public static void cleanUp() { // Exit the application first application.exit(); application = null; } public static Application application() { return application; } }
27.902439
73
0.656469
456aec9bda52659262d700ef8ca9aff1173a34b7
233
package com.procesualHito3.CoronaVirusWeb; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class CoronaVirusWebApplicationTests { @Test void contextLoads() { } }
16.642857
60
0.806867
7e2a2302be317ae5431d976a8f35b3240c690eb5
1,368
package co.yixiang.modules.shop.web.vo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; /** * <p> * 购物车表 查询结果对象 * </p> * * @author hupeng * @date 2019-10-25 */ @Data @ApiModel(value = "YxStoreCartQueryVo对象", description = "购物车表查询参数") public class YxStoreCartQueryVo implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "购物车表ID") private Long id; @ApiModelProperty(value = "用户ID") private Integer uid; @ApiModelProperty(value = "类型") private String type; @ApiModelProperty(value = "商品ID") private Integer productId; @ApiModelProperty(value = "商品属性") private String productAttrUnique; @ApiModelProperty(value = "商品数量") private Integer cartNum; @ApiModelProperty(value = "添加时间") private Integer addTime; @ApiModelProperty(value = "拼团id") private Integer combinationId; @ApiModelProperty(value = "秒杀产品ID") private Integer seckillId; @ApiModelProperty(value = "砍价id") private Integer bargainId; private YxStoreProductQueryVo productInfo; private Double costPrice; private Double truePrice; private Integer trueStock; private Double vipTruePrice; private String unique; private Integer isReply; }
20.41791
67
0.708333
d943abd1fa21b40ceeb5e1462b4f5549743bd8a3
7,594
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.components.devtools_bridge; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.PowerManager; import org.chromium.components.devtools_bridge.ui.ServiceUIFactory; import org.chromium.components.devtools_bridge.util.LooperExecutor; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Android service mixin implementing DevTools Bridge features that not depend on * WebRTC signaling. Ability to host this class in different service classes allows: * 1. Parametrization. * 2. Simplified signaling for tests. * * Service starts foreground once any remote client starts a debugging session. Stops when all * remote clients disconnect. * * Must be called on service's main thread. */ public class DevToolsBridgeServer implements SignalingReceiver { public final int NOTIFICATION_ID = 1; public final String DISCONNECT_ALL_CLIENTS_ACTION = "action.DISCONNECT_ALL_CLIENTS_ACTION"; public final String WAKELOCK_KEY = "wake_lock.DevToolsBridgeServer"; private final Service mHost; private final String mSocketName; private final ServiceUIFactory mServiceUIFactory; private final LooperExecutor mExecutor; private final SessionDependencyFactory mFactory = new SessionDependencyFactory(); private final Map<String, ServerSession> mSessions = new HashMap<String, ServerSession>(); private PowerManager.WakeLock mWakeLock; private Runnable mForegroundCompletionCallback; public DevToolsBridgeServer(Service host, String socketName, ServiceUIFactory uiFactory) { mHost = host; mSocketName = socketName; mServiceUIFactory = uiFactory; mExecutor = LooperExecutor.newInstanceForMainLooper(mHost); checkCalledOnHostServiceThread(); } private void checkCalledOnHostServiceThread() { assert mExecutor.isCalledOnSessionThread(); } public Service getContext() { return mHost; } public SharedPreferences getPreferences() { return getPreferences(mHost); } public static SharedPreferences getPreferences(Context context) { return context.getSharedPreferences( DevToolsBridgeServer.class.getName(), Context.MODE_PRIVATE); } /** * Should be called in service's onStartCommand. If it can handle then the method should * delegate the work to the server. */ public boolean canHandle(Intent intent) { String action = intent.getAction(); return DISCONNECT_ALL_CLIENTS_ACTION.equals(action); } public int onStartCommand(Intent intent) { assert canHandle(intent); String action = intent.getAction(); if (DISCONNECT_ALL_CLIENTS_ACTION.equals(action)) { closeAllSessions(); } return Service.START_NOT_STICKY; } /** * Should be called in service's onDestroy. */ public void dispose() { checkCalledOnHostServiceThread(); for (ServerSession session : mSessions.values()) { session.dispose(); } mFactory.dispose(); } @Override public void startSession( String sessionId, RTCConfiguration config, String offer, SessionBase.NegotiationCallback callback) { checkCalledOnHostServiceThread(); if (mSessions.containsKey(sessionId)) { callback.onFailure("Session already exists"); return; } ServerSession session = new ServerSession(mFactory, mExecutor, mSocketName); session.setEventListener(new SessionEventListener(sessionId)); mSessions.put(sessionId, session); session.startSession(config, offer, callback); if (mSessions.size() == 1) startForeground(); } @Override public void renegotiate( String sessionId, String offer, SessionBase.NegotiationCallback callback) { checkCalledOnHostServiceThread(); if (!mSessions.containsKey(sessionId)) { callback.onFailure("Session does not exist"); return; } ServerSession session = mSessions.get(sessionId); session.renegotiate(offer, callback); } @Override public void iceExchange( String sessionId, List<String> clientCandidates, SessionBase.IceExchangeCallback callback) { checkCalledOnHostServiceThread(); if (!mSessions.containsKey(sessionId)) { callback.onFailure("Session does not exist"); return; } ServerSession session = mSessions.get(sessionId); session.iceExchange(clientCandidates, callback); } protected void startForeground() { mForegroundCompletionCallback = startSticky(); checkCalledOnHostServiceThread(); mHost.startForeground( NOTIFICATION_ID, mServiceUIFactory.newForegroundNotification(mHost, DISCONNECT_ALL_CLIENTS_ACTION)); } protected void stopForeground() { checkCalledOnHostServiceThread(); mHost.stopForeground(true); mForegroundCompletionCallback.run(); mForegroundCompletionCallback = null; } public void postOnServiceThread(Runnable runnable) { mExecutor.postOnSessionThread(0, runnable); } private class SessionEventListener implements SessionBase.EventListener { private final String mSessionId; public SessionEventListener(String sessionId) { mSessionId = sessionId; } public void onCloseSelf() { checkCalledOnHostServiceThread(); mSessions.remove(mSessionId); if (mSessions.size() == 0) { stopForeground(); } } } private void closeAllSessions() { if (mSessions.isEmpty()) return; for (ServerSession session : mSessions.values()) { session.stop(); } mSessions.clear(); stopForeground(); } /** * Helper method for doing background tasks. Usage: * * int onStartCommand(...) { * if (..*) { * startWorkInBackground(startSticky()); * return START_STICKY; * } * ... * } * * void doWorkInBackground(final Runable completionHandler) { * ... start background task * @Override * void run() { * ... * completionHandler.run(); * } * } */ public Runnable startSticky() { checkCalledOnHostServiceThread(); if (mWakeLock == null) { PowerManager pm = (PowerManager) mHost.getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY); } mWakeLock.acquire(); return new StartStickyCompletionHandler(); } private class StartStickyCompletionHandler implements Runnable { @Override public void run() { postOnServiceThread(new Runnable() { @Override public void run() { mWakeLock.release(); if (!mWakeLock.isHeld()) mHost.stopSelf(); } }); } } }
31.774059
99
0.644983
33fc94dc635aa635d0b3cb432361a03d9dc7fa56
1,154
/* * Copyright 2019 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package me.porcelli.nio.jgit.impl.op.model; import java.io.File; import java.util.List; import java.util.Map; import org.eclipse.jgit.revwalk.RevCommit; public class MergeCommitContent extends DefaultCommitContent { private final List<RevCommit> parents; public MergeCommitContent(final Map<String, File> content, final List<RevCommit> parents) { super(content); this.parents = parents; } public List<RevCommit> getParents() { return parents; } }
28.146341
75
0.70364
2e3bbaa76f7ee694328e4cf9017366e1feacfb34
551
package br.gov.df.emater.negocio.pessoa.pessoa; import org.springframework.stereotype.Component; import br.com.frazao.cadeiaresponsabilidade.Comando; import br.com.frazao.cadeiaresponsabilidade.Contexto; import br.gov.df.emater.repositorio_principal.entidade.principal.Pessoa; @Component public class PessoaIniciarCmd extends Comando { @Override protected void procedimento(final Contexto contexto) throws Exception { final Pessoa modelo = (Pessoa) contexto.getRequisicao(); if (modelo == null) { } contexto.setResposta(modelo); } }
23.956522
72
0.794918
53fb7742a8b8153d0ca3a5a370d800d7f85295ae
765
package com.fengwenyi.apistarter.constraints; /** * @author <a href="https://www.fengwenyi.com">Erwin Feng</a> * @since 2021-08-09 */ import com.fengwenyi.apistarter.validator.PhoneValidator; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.*; import static java.lang.annotation.ElementType.*; /** * @author <a href="https://www.fengwenyi.com">Erwin Feng</a> * @since 2021-08-09 */ @Constraint(validatedBy = {PhoneValidator.class}) @Documented @Retention(RetentionPolicy.RUNTIME) @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER}) public @interface Phone { String message() default "手机号码格式错误"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
24.677419
65
0.72549
85bf6e50ea9f5c82b59e14d1a14d57dc1c7a21c9
1,183
/* * Copyright 2021 EPAM Systems, Inc * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. 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.epam.deltix.qsrv.hf.tickdb.impl; import com.epam.deltix.timebase.messages.IdentityKey; import com.epam.deltix.qsrv.hf.pub.md.RecordClassSet; /** * Allows the remote layer to directly retrieve the RecordClassSet object * from a TickStreamImpl. */ public interface FriendlyStream { public RecordClassSet getMetaData (); public boolean hasWriter(IdentityKey id); public void addInstrument(IdentityKey id); }
34.794118
80
0.735418
e80b9cca124b2f999ba82526bb7e1d654de1ca45
3,075
package org.eclipse.php.internal.ui.editor.contentassist; import org.eclipse.dltk.core.CompletionProposal; import org.eclipse.dltk.core.DLTKCore; import org.eclipse.dltk.utils.TextUtils; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.TextUtilities; import org.eclipse.swt.graphics.Image; public class PHPStubCompletionProposal extends PHPCompletionProposal implements IPHPCompletionProposalExtension { private CompletionProposal typeProposal; private IDocument document; public PHPStubCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, int relevance, CompletionProposal typeProposal, IDocument document) { super(replacementString, replacementOffset, replacementLength, image, displayString, relevance); this.typeProposal = typeProposal; this.document = document; } private boolean fReplacementStringComputed = false; public String getReplacementString() { if (!fReplacementStringComputed) setReplacementString(computeReplacementString()); return super.getReplacementString(); } private String computeReplacementString() { fReplacementStringComputed = true; // IType type = (IType) typeProposal.getModelElement(); // type.getElementName(); String result = "class " //$NON-NLS-1$ + typeProposal.getModelElement().getElementName() + "{\r\n\t\r\n}"; //$NON-NLS-1$ result = addComment(result); result = addIndent(result, typeProposal.getReplaceStart()); return result; } private String addComment(String result) { // TODO Auto-generated method stub // return "/**\r\n *\r\n */\r\n" + result; return result; } private String addIndent(String result, int offset) { final String[] lines = TextUtils.splitLines(result); if (lines.length > 1) { final String delimeter = TextUtilities .getDefaultLineDelimiter(document); final String indent = calculateIndent(document, offset); final StringBuffer buffer = new StringBuffer(lines[0]); // Except first line for (int i = 1; i < lines.length; i++) { buffer.append(delimeter); buffer.append(indent); buffer.append(lines[i]); } return buffer.toString(); } return result; } protected String calculateIndent(IDocument document, int offset) { try { final IRegion region = document.getLineInformationOfOffset(offset); String indent = document.get(region.getOffset(), offset - region.getOffset()); int i = 0; while (i < indent.length() && isSpaceOrTab(indent.charAt(i))) { ++i; } if (i > 0) { return indent.substring(0, i); } } catch (BadLocationException e) { if (DLTKCore.DEBUG) { e.printStackTrace(); } } return ""; //$NON-NLS-1$ } /** * Tests if specified char is tab or space * * @param ch * @return */ private boolean isSpaceOrTab(char ch) { return ch == ' ' || ch == '\t'; } public Object getExtraInfo() { return typeProposal.getExtraInfo(); } }
28.211009
79
0.720325
b3cfa8a6e04882ff78bea3b11f871c7313152ed7
2,904
// // Copyright 2021 SenX S.A.S. // // 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.warp10.script.ext.http; import io.warp10.warp.sdk.WarpScriptExtension; import java.util.HashMap; import java.util.Map; /** * Extension for HTTP function */ public class HttpWarpScriptExtension extends WarpScriptExtension { // // Authorization // /** * If set to true, HTTP requires the stack to be authenticated */ public static final String WARPSCRIPT_HTTP_AUTHENTICATION_REQUIRED = "warpscript.http.authentication.required"; /** * If set, this capability is inspected */ public static final String WARPSCRIPT_HTTP_CAPABILITY = "warpscript.http.capability"; // // Web control // /** * Allowed and excluded host patterns. */ public static final String WARPSCRIPT_HTTP_HOST_PATTERNS = "warpscript.http.host.patterns"; // // Stack attributes // /** * Number of calls to HTTP so far in the sessions and cap name for raising related limit */ public static final String ATTRIBUTE_HTTP_REQUESTS = "http.requests"; /** * Current HTTP so far in the sessions and cap name for raising related limit */ public static final String ATTRIBUTE_HTTP_SIZE = "http.size"; /** * Cap name for raising max chunk size */ public static final String ATTRIBUTE_CHUNK_SIZE = "http.chunksize"; // // Configurable limits (can be raised with capabilities) // /** * Maximum number of calls to HTTP */ public static final String WARPSCRIPT_HTTP_REQUESTS = "warpscript.http.maxrequests"; /** * Maximum cumulative size allowed to be downloaded by HTTP */ public static final String WARPSCRIPT_HTTP_SIZE = "warpscript.http.maxsize"; /** * Maximum chunk size allowed when downloading per chunk using HTTP */ public static final String WARPSCRIPT_CHUNK_SIZE = "warpscript.http.maxchunksize"; // // Defaults limits if configuration not present // public static final long DEFAULT_HTTP_REQUESTS = 1L; public static final long DEFAULT_HTTP_MAXSIZE = 65536L; public static final long DEFAULT_HTTP_CHUNK_SIZE = 65536L; // // Init extension // private static final Map<String, Object> functions = new HashMap<String, Object>(); static { functions.put("HTTP", new HTTP("HTTP")); } public Map<String, Object> getFunctions() { return functions; } }
26.162162
113
0.710055
cd4636b6fe32814c793609abcf9ab09f897610d4
8,950
/* * 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.qpid.systest.rest.acl; import java.io.File; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.qpid.server.logging.logback.VirtualHostFileLogger; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.model.VirtualHostLogger; import org.apache.qpid.server.model.VirtualHostNode; import org.apache.qpid.server.security.acl.AbstractACLTestCase; import org.apache.qpid.server.virtualhost.ProvidedStoreVirtualHostImpl; import org.apache.qpid.server.virtualhostnode.JsonVirtualHostNode; import org.apache.qpid.systest.rest.QpidRestTestCase; import org.apache.qpid.test.utils.TestBrokerConfiguration; public class VirtualHostACLTest extends QpidRestTestCase { private static final String VHN_WITHOUT_VH = "myVhnWithoutVh"; private static final String ALLOWED_USER = "user1"; private static final String DENIED_USER = "user2"; private static final String RESTRICTED_USER = "restricted"; @Override protected void customizeConfiguration() throws Exception { super.customizeConfiguration(); final TestBrokerConfiguration defaultBrokerConfiguration = getDefaultBrokerConfiguration(); defaultBrokerConfiguration.configureTemporaryPasswordFile(ALLOWED_USER, DENIED_USER, RESTRICTED_USER); AbstractACLTestCase.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT", "ACL ALLOW-LOG " + ALLOWED_USER + " ALL VIRTUALHOST", "ACL ALLOW-LOG " + RESTRICTED_USER + " ALL VIRTUALHOST attributes=\"description\"", "ACL DENY-LOG " + DENIED_USER + " ALL VIRTUALHOST", "ACL DENY-LOG ALL ALL"); Map<String, Object> virtualHostNodeAttributes = new HashMap<>(); virtualHostNodeAttributes.put(VirtualHostNode.NAME, VHN_WITHOUT_VH); virtualHostNodeAttributes.put(VirtualHostNode.TYPE, getTestProfileVirtualHostNodeType()); // TODO need better way to determine the VHN's optional attributes virtualHostNodeAttributes.put(JsonVirtualHostNode.STORE_PATH, getStoreLocation(VHN_WITHOUT_VH)); defaultBrokerConfiguration.addObjectConfiguration(VirtualHostNode.class, virtualHostNodeAttributes); } public void testCreateVirtualHostAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String hostName = getTestName(); int responseCode = createVirtualHost(VHN_WITHOUT_VH, hostName); assertEquals("Virtual host creation should be allowed", HttpServletResponse.SC_CREATED, responseCode); assertVirtualHostExists(VHN_WITHOUT_VH, hostName); } public void testCreateVirtualHostDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String hostName = getTestName(); int responseCode = createVirtualHost(VHN_WITHOUT_VH, hostName); assertEquals("Virtual host creation should be denied", HttpServletResponse.SC_FORBIDDEN, responseCode); assertVirtualHostDoesNotExist(VHN_WITHOUT_VH, hostName); } public void testDeleteVirtualHostDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest("virtualhost/" + TEST2_VIRTUALHOST + "/" + TEST2_VIRTUALHOST, "DELETE", HttpServletResponse.SC_FORBIDDEN); assertVirtualHostExists(TEST2_VIRTUALHOST, TEST2_VIRTUALHOST); } public void testUpdateRestrictedAttributes() throws Exception { getRestTestHelper().setUsernameAndPassword(RESTRICTED_USER, RESTRICTED_USER); String virtualHostUrl = "virtualhost/" + TEST2_VIRTUALHOST + "/" + TEST2_VIRTUALHOST; getRestTestHelper().submitRequest(virtualHostUrl, "PUT", Collections.singletonMap(VirtualHost.CONTEXT, Collections.singletonMap("test1", "test2")), HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(virtualHostUrl, "PUT", Collections.singletonMap(VirtualHost.DESCRIPTION, "Test Description"), HttpServletResponse.SC_OK); } public void testUpdateVirtualHostDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(VirtualHost.NAME, TEST2_VIRTUALHOST); attributes.put(VirtualHost.DESCRIPTION, "new description"); getRestTestHelper().submitRequest("virtualhost/" + TEST2_VIRTUALHOST + "/" + TEST2_VIRTUALHOST, "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); } public void testDownloadVirtualHostLoggerFileAllowedDenied() throws Exception { final String virtualHostName = "testVirtualHost"; final String loggerName = "testFileLogger"; final String loggerPath = "virtualhostlogger/" + VHN_WITHOUT_VH + "/" + virtualHostName + "/" + loggerName; getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); createVirtualHost(VHN_WITHOUT_VH, virtualHostName); Map<String, Object> attributes = new HashMap<>(); attributes.put(VirtualHostLogger.NAME, loggerName); attributes.put(ConfiguredObject.TYPE, VirtualHostFileLogger.TYPE); getRestTestHelper().submitRequest("virtualhostlogger/" + VHN_WITHOUT_VH + "/" + virtualHostName, "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_OK); getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_OK); getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_FORBIDDEN); } /* === Utility Methods === */ private int createVirtualHost(final String testVirtualHostNode, String virtualHostName) throws Exception { Map<String, Object> data = new HashMap<>(); data.put(VirtualHost.NAME, virtualHostName); data.put(VirtualHost.TYPE, ProvidedStoreVirtualHostImpl.VIRTUAL_HOST_TYPE); return getRestTestHelper().submitRequest("virtualhost/" + testVirtualHostNode + "/" + virtualHostName, "PUT", data); } private void assertVirtualHostDoesNotExist(final String virtualHostNodeName, String virtualHostName) throws Exception { assertVirtualHostExistence(virtualHostNodeName, virtualHostName, false); } private void assertVirtualHostExists(final String virtualHostNodeName, String virtualHostName) throws Exception { assertVirtualHostExistence(virtualHostNodeName, virtualHostName, true); } private void assertVirtualHostExistence(final String virtualHostNodeName, String virtualHostName, boolean exists) throws Exception { String path = "virtualhost/" + virtualHostNodeName + "/" + virtualHostName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private String getStoreLocation(String hostName) { return new File(TMP_FOLDER, "store-" + hostName + "-" + System.currentTimeMillis()).getAbsolutePath(); } }
47.354497
157
0.722011
b44cec801f21e1c2e1677332f448b330afae9450
3,720
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.training.dataset; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * {@code BatchSampler} is a {@link Sampler} that returns a single epoch over the data. * * <p>{@code BatchSampler} wraps another {@link ai.djl.training.dataset.Sampler.SubSampler} to yield * a mini-batch of indices. */ public class BatchSampler implements Sampler { private Sampler.SubSampler subSampler; private int batchSize; private boolean dropLast; /** * Creates a new instance of {@code BatchSampler} that samples from the given {@link * ai.djl.training.dataset.Sampler.SubSampler}, and yields a mini-batch of indices. * * <p>The last batch will not be dropped. The size of the last batch maybe smaller than batch * size in case the size of the dataset is not a multiple of batch size. * * @param subSampler the {@link ai.djl.training.dataset.Sampler.SubSampler} to sample from * @param batchSize the required batch size */ public BatchSampler(Sampler.SubSampler subSampler, int batchSize) { this(subSampler, batchSize, false); } /** * Creates a new instance of {@code BatchSampler} that samples from the given {@link * ai.djl.training.dataset.Sampler.SubSampler}, and yields a mini-batch of indices. * * @param subSampler the {@link ai.djl.training.dataset.Sampler.SubSampler} to sample from * @param batchSize the required batch size * @param dropLast whether the {@code BatchSampler} should drop the last few samples in case the * size of the dataset is not a multiple of batch size */ public BatchSampler(Sampler.SubSampler subSampler, int batchSize, boolean dropLast) { this.subSampler = subSampler; this.batchSize = batchSize; this.dropLast = dropLast; } /** {@inheritDoc} */ @Override public Iterator<List<Long>> sample(RandomAccessDataset dataset) { return new Iterate(dataset); } /** {@inheritDoc} */ @Override public int getBatchSize() { return batchSize; } class Iterate implements Iterator<List<Long>> { private long size; private long current; private Iterator<Long> itemSampler; Iterate(RandomAccessDataset dataset) { current = 0; if (dropLast) { this.size = dataset.size() / batchSize; } else { this.size = (dataset.size() + batchSize - 1) / batchSize; } itemSampler = subSampler.sample(dataset); } /** {@inheritDoc} */ @Override public boolean hasNext() { return current < size; } /** {@inheritDoc} */ @Override public List<Long> next() { List<Long> batchIndices = new ArrayList<>(); while (itemSampler.hasNext()) { batchIndices.add(itemSampler.next()); if (batchIndices.size() == batchSize) { break; } } current++; return batchIndices; } } }
34.12844
120
0.634409
6c1be9276ede84ff8b5966a5fd478d5e5cd855c1
1,183
package org.gooru.nucleus.reports.infra.routes; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Created by ashish on 26/4/16. */ public class RouteConfiguration implements Iterable<RouteConfigurator> { private final Iterator<RouteConfigurator> internalIterator; public RouteConfiguration() { List<RouteConfigurator> configurators = new ArrayList<>(32); // First the global handler to enable to body reading etc configurators.add(new RouteGlobalConfigurator()); // For rest of handlers, Auth should always be first one configurators.add(new RouteInternalConfigurator()); configurators.add(new RouteDownloadReportConfigurator()); internalIterator = configurators.iterator(); } @Override public Iterator<RouteConfigurator> iterator() { return new Iterator<RouteConfigurator>() { @Override public boolean hasNext() { return internalIterator.hasNext(); } @Override public RouteConfigurator next() { return internalIterator.next(); } }; } }
27.511628
72
0.654269
0a79da202547f449eee32b31bb994095b112ebe1
5,122
package io.github.dunwu.module.cas.controller; import io.github.dunwu.module.cas.entity.Menu; import io.github.dunwu.module.cas.entity.dto.MenuDto; import io.github.dunwu.module.cas.entity.query.MenuQuery; import io.github.dunwu.module.cas.entity.vo.MenuVo; import io.github.dunwu.module.cas.service.MenuService; import io.github.dunwu.tool.data.DataListResult; import io.github.dunwu.tool.data.DataResult; import io.github.dunwu.tool.data.PageResult; import io.github.dunwu.tool.data.validator.annotation.AddCheck; import io.github.dunwu.tool.data.validator.annotation.EditCheck; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Pageable; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.servlet.http.HttpServletResponse; /** * 系统菜单信息 Controller 类 * * @author <a href="mailto:forbreak@163.com">Zhang Peng</a> * @since 2020-05-24 */ @RestController @RequestMapping("cas/menu") @Api(tags = "系统:菜单管理") @RequiredArgsConstructor public class MenuController { private final MenuService service; @ApiOperation("添加一条 Menu 记录") @PostMapping("add") public DataResult<Boolean> add(@Validated(AddCheck.class) @RequestBody Menu entity) { return DataResult.ok(service.insert(entity)); } @ApiOperation("批量添加 Menu 记录") @PostMapping("add/batch") public DataResult<Boolean> addBatch(@Validated(AddCheck.class) @RequestBody Collection<Menu> list) { return DataResult.ok(service.insertBatch(list)); } @ApiOperation("根据 id 更新一条 Menu 记录") @PostMapping("edit") public DataResult<Boolean> edit(@Validated(EditCheck.class) @RequestBody Menu entity) { return DataResult.ok(service.updateById(entity)); } @ApiOperation("根据 id 批量更新 Menu 记录") @PostMapping("edit/batch") public DataResult<Boolean> editBatch(@Validated(EditCheck.class) @RequestBody Collection<Menu> list) { return DataResult.ok(service.updateBatchById(list)); } @ApiOperation("根据 id 删除一条 Menu 记录") @PostMapping("del/{id}") public DataResult<Boolean> deleteById(@PathVariable Serializable id) { return DataResult.ok(service.deleteById(id)); } @ApiOperation("根据 id 列表批量删除 Menu 记录") @PostMapping("del/batch") public DataResult<Boolean> deleteBatchByIds(@RequestBody Collection<? extends Serializable> ids) { return DataResult.ok(service.deleteBatchByIds(ids)); } @ApiOperation("根据 MenuQuery 查询 MenuDto 列表") @GetMapping("list") public DataListResult<MenuDto> list(MenuQuery query) { return DataListResult.ok(service.pojoListByQuery(query)); } @ApiOperation("根据 MenuQuery 和 Pageable 分页查询 MenuDto 列表") @GetMapping("page") public PageResult<MenuDto> page(MenuQuery query, Pageable pageable) { return PageResult.ok(service.pojoSpringPageByQuery(query, pageable)); } @ApiOperation("根据 id 查询 MenuDto") @GetMapping("{id}") public DataResult<MenuDto> getById(@PathVariable Serializable id) { return DataResult.ok(service.pojoById(id)); } @ApiOperation("根据 MenuQuery 查询匹配条件的记录数") @GetMapping("count") public DataResult<Integer> count(MenuQuery query) { return DataResult.ok(service.countByQuery(query)); } @ApiOperation("根据 id 列表查询 MenuDto 列表,并导出 excel 表单") @PostMapping("export/list") public void exportList(@RequestBody Collection<? extends Serializable> ids, HttpServletResponse response) { service.exportList(ids, response); } @ApiOperation("根据 MenuQuery 和 Pageable 分页查询 MenuDto 列表,并导出 excel 表单") @GetMapping("export/page") public void exportPage(MenuQuery query, Pageable pageable, HttpServletResponse response) { service.exportPage(query, pageable, response); } @PreAuthorize("@exp.check('menu:view')") @ApiOperation("根据 query 条件,返回 SysMenuDto 树形列表") @GetMapping("treeList") public DataListResult<MenuDto> treeList(MenuQuery query) { return DataListResult.ok(service.treeList(query)); } @PreAuthorize("@exp.check('menu:view')") @ApiOperation("根据ID获取同级与上级数据") @PostMapping("superiorTreeList") public DataListResult<MenuDto> superiorTreeList(@RequestBody Collection<Serializable> ids) { return DataListResult.ok(service.treeListByIds(ids)); } @PreAuthorize("@exp.check('menu:view')") @ApiOperation("根据ID获取所有孩子节点ID") @GetMapping("childrenIds") public DataListResult<Long> childrenIds(Long id) { List<Long> ids = new ArrayList<>(); ids.add(id); ids.addAll(service.childrenIds(id)); return DataListResult.ok(ids); } @ApiOperation("获取当前用户展示于前端的菜单列表") @GetMapping(value = "mine") public DataListResult<MenuVo> mineList() { return DataListResult.ok(service.buildMenuListForCurrentUser()); } }
35.569444
111
0.723741
cbf5b886dbd6580974d30db50ffce730e3c1d968
343
package ru.fusionsoft.dbgit.integration.primitives.files; import java.io.IOException; import java.util.Map; public interface TextResourceGroup { void add(String name, String content) throws IOException; void clean() throws IOException; TextResource file(String... name); Map<String, TextResource> all() throws IOException; }
28.583333
61
0.763848
501157f9a5b812a9568bc672e0bfb57916df9e1e
1,298
package com.getcapacitor; import android.content.Context; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.inputmethod.BaseInputConnection; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import org.xwalk.core.XWalkView; public class CapacitorXWalkView extends XWalkView { private BaseInputConnection capInputConnection; public CapacitorXWalkView(Context context, AttributeSet attrs) { super(context, attrs); } @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { CapConfig config = new CapConfig(getContext().getAssets(), null); boolean captureInput = config.getBoolean("android.captureInput", false); if (captureInput) { if (capInputConnection == null) { capInputConnection = new BaseInputConnection(this, false); } return capInputConnection; } return super.onCreateInputConnection(outAttrs); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { return false; // Do not let Crosswalk handle the Back button! } return super.dispatchKeyEvent(event); } }
33.282051
80
0.706471
52ccad14a742088dd6bb8667489f5d5f90c25133
288
package server.life; public interface MonsterListener { /** * * @param monster The monster that was killed * @param highestDamageChar The char that did the highest damage to the * monster. Can be null if that char is offline. */ void monsterKilled(); }
22.153846
75
0.663194
a147ad82171192639fee7bbcb02883b6c25963af
2,566
package com.example.demo; import com.example.demo.InputStreamTransactionLoader; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.DynamicTest.dynamicTest; class TransactionLoaderTest { @TestFactory List<DynamicTest> testLoad() throws IOException { return List.of( dynamicTest("test1", () -> { var data = """ ID, Date, Amount, Merchant, Type, Related Transaction WLMFRDGD, 20/08/2020 12:45:33, 59.99, Kwik-E-Mart, PAYMENT, YGXKOEIA, 20/08/2020 12:46:17, 10.95, Kwik-E-Mart, PAYMENT, """; var loader = new InputStreamTransactionLoader(new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8))); var loadedData = loader.load(); assertThat(loadedData.size()).isEqualTo(2); }), dynamicTest("test2", () -> { var data = """ ID, Date, Amount, Merchant, Type, Related Transaction WLMFRDGD, 20/08/2020 12:45:33, 59.99, Kwik-E-Mart, PAYMENT, """; var loader = new InputStreamTransactionLoader(new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8))); var loadedData = loader.load(); assertThat(loadedData.size()).isEqualTo(1); }) ); } @TestFactory List<DynamicTest> testLoadFromFiles() { var csvFiles = Map.of( "/input_test1.csv", 1, "/input_test2.csv", 2, "/input_test3.csv", 6 ); return csvFiles.keySet().stream() .map(key -> dynamicTest("test#" + key, () -> { var data = getClass().getResourceAsStream(key); var loader = new InputStreamTransactionLoader(data); var loadedData = loader.load(); assertThat(loadedData.size()).isEqualTo(csvFiles.get(key)); }) ) .collect(Collectors.toList()); } }
38.298507
131
0.535853
31760de44111ff05c9b6b2e87880fea6b52c1cfd
2,374
package no.nav.vedtak.sikkerhet.abac; import java.lang.reflect.Method; import javax.jws.WebMethod; import javax.jws.WebService; import javax.ws.rs.Path; class ActionUthenter { private static final String SLASH = "/"; private ActionUthenter() { } static String action(Class<?> clazz, Method method) { return clazz.getAnnotation(WebService.class) != null ? actionForWebServiceMethod(clazz, method) : actionForRestMethod(clazz, method); } private static String actionForRestMethod(Class<?> clazz, Method method) { Path pathOfClass = clazz.getAnnotation(Path.class); Path pathOfMethod = method.getAnnotation(Path.class); String path = ""; if (pathOfClass != null) { path += ensureStartsWithSlash(pathOfClass.value()); } if (pathOfMethod != null) { path += ensureStartsWithSlash(pathOfMethod.value()); } return path; } private static String actionForWebServiceMethod(Class<?> clazz, Method method) { WebMethod webMethodAnnotation = finnWebMethod(method); if (webMethodAnnotation.action().isEmpty()) { throw new IllegalArgumentException( "Mangler action på @WebMethod-annotering for metode på Webservice " + clazz.getName() + "." + method.getName()); } return webMethodAnnotation.action(); } private static WebMethod finnWebMethod(Method method) { // annoteringen finnes i et av interfacene for (Class<?> anInterface : method.getDeclaringClass().getInterfaces()) { try { Method deklarertMetode = anInterface.getDeclaredMethod(method.getName(), method.getParameterTypes()); WebMethod annotation = deklarertMetode.getAnnotation(WebMethod.class); if (annotation != null) { return annotation; } } catch (NoSuchMethodException e) { // forventet hvis webservice arver fra flere interface } } throw new IllegalArgumentException("Mangler @WebMethod-annotering i interface for " + method.getDeclaringClass() + "." + method.getName()); } private static String ensureStartsWithSlash(String value) { return value.startsWith(SLASH) ? value : SLASH + value; } }
35.969697
147
0.63353
cc5c3b1ee1e7f7c8b10c58834f9cc3d9f2e7d1a3
635
package FreeWheel; import java.util.Scanner; public class FW_template { public static void main(String[] args) { // 处理输入 Scanner sc = new Scanner(System.in); // 解析输入 int n = sc.nextInt(); int m = sc.nextInt(); // 主要逻辑 + 输出返回 System.out.println(new FW_template().solve(n, m)); // 关闭输入 sc.close(); } // 处理逻辑 + 构造输出 public String solve(int n, int m) { StringBuilder buf = new StringBuilder(); // TODO buf.append(n); buf.append(m); buf.append(String.format("%.2f", n)); return buf.toString(); } }
22.678571
58
0.529134
31f6ac528bd540b53624cd02aae0b08153863bf3
4,653
package net.njit.ms.cs.service; import lombok.extern.slf4j.Slf4j; import net.njit.ms.cs.exception.BadRequestRequestException; import net.njit.ms.cs.exception.ResourceNotCreatedException; import net.njit.ms.cs.exception.ResourceNotDeletedException; import net.njit.ms.cs.exception.ResourceNotFoundException; import net.njit.ms.cs.model.dto.request.BuildingDto; import net.njit.ms.cs.model.entity.Building; import net.njit.ms.cs.repository.BuildingRepository; import org.springframework.stereotype.Service; import java.util.List; @Service @Slf4j public class BuildingService { private final BuildingRepository buildingRepository; private final StaffService staffService; private final StudentService studentService; public BuildingService(BuildingRepository buildingRepository, StaffService staffService, StudentService studentService) { this.buildingRepository = buildingRepository; this.staffService = staffService; this.studentService = studentService; } public List<Building> getAllBuildings() { return this.buildingRepository.findAll(); } public Building getBuildingById(Integer number) { return this.buildingRepository.findById(number).orElseThrow(() -> new ResourceNotFoundException(String.format("Building with number: %s not found", number))); } public Building getCreatedBuilding(BuildingDto buildingDto) { if (this.buildingRepository.existsById(buildingDto.getNumber())) { String message = String.format("Building with number: %s already exists.", buildingDto.getNumber()); log.error(message); throw new BadRequestRequestException(message); } return this.getCreateOrReplacedBuilding(this.getNewBuilding(buildingDto)); } public Building getUpdatedBuilding(Integer number, BuildingDto buildingDto) { Building building = this.getBuildingById(number); if (!number.equals(buildingDto.getNumber())) { String message = String.format("Building number: %s cannot be changed in update", number); log.error(message); throw new BadRequestRequestException(message); } building.setName(buildingDto.getName()); building.setLocation(buildingDto.getLocation()); return this.getCreateOrReplacedBuilding(building); } public void deleteBuilding(Integer number) { Building building = this.getBuildingById(number); handleFacultyForDepartmentDeletion(building); handleStudentsForDepartmentDeletion(building); try { this.buildingRepository.delete(building); } catch (Exception e) { String message = String.format( "Something went wrong deleting building with number: %s to backend", number); log.error("{} {}", message, e.getMessage()); throw new ResourceNotDeletedException(message); } } private Building getCreateOrReplacedBuilding(Building building) { try { return this.buildingRepository.save(building); } catch (Exception e) { String message = String.format( "Something went wrong creating or replacing building with number: %s to backend %s", building.getNumber(), e.getCause()); log.error("{} {}", message, e.getMessage()); throw new ResourceNotCreatedException(message); } } private void handleFacultyForDepartmentDeletion(Building building) { building.getDepartments().forEach(department -> { department.getFaculties().forEach(faculty -> { faculty.getDepartments().remove(department); this.staffService.getCreateOrReplacedStaff(faculty); }); }); } private void handleStudentsForDepartmentDeletion(Building building) { building.getDepartments().forEach(department -> { department.getStudents().forEach(student -> { student.setDepartmentCode(null); this.studentService.getCreateOrReplacedStudent(student); }); }); } private Building getNewBuilding(BuildingDto buildingDto) { Building building = new Building(); building.setNumber(buildingDto.getNumber()); building.setName(buildingDto.getName()); building.setLocation(buildingDto.getLocation()); return building; } }
39.432203
113
0.656351
a86103c1f287335498b3897d6bc2d79188a0e943
650
package arez.component; import javax.annotation.Nonnull; /** * Interface implemented by components that have references that need to be eagerly resolved. * The method on this interface should only be invoked by the runtime and not directly by external code. */ public interface Linkable { /** * Resolve any references. */ void link(); /** * Link specified object if it is linkable. * * @param object the object to link if linkable. */ static void link( @Nonnull final Object object ) { if ( object instanceof Linkable ) { final Linkable linkable = (Linkable) object; linkable.link(); } } }
21.666667
104
0.675385
4b9cc93d6b1137340eef0fa004a53d7c12561fef
1,133
package cn.binarywang.wx.miniapp.bean; import cn.binarywang.wx.miniapp.util.json.WxMaGsonBuilder; import com.google.gson.annotations.SerializedName; /** * {"session_key":"nzoqhc3OnwHzeTxJs+inbQ==","expires_in":2592000,"openid":"oVBkZ0aYgDMDIywRdgPW8-joxXc4"} * * @author <a href="https://github.com/binarywang">Binary Wang</a> */ public class WxMaJscode2SessionResult { @SerializedName("session_key") private String sessionKey; @SerializedName("expires_in") private Integer expiresin; @SerializedName("openid") private String openid; public String getSessionKey() { return sessionKey; } public void setSessionKey(String sessionKey) { this.sessionKey = sessionKey; } public Integer getExpiresin() { return expiresin; } public void setExpiresin(Integer expiresin) { this.expiresin = expiresin; } public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } public static WxMaJscode2SessionResult fromJson(String json) { return WxMaGsonBuilder.create().fromJson(json, WxMaJscode2SessionResult.class); } }
22.66
106
0.731686
100aaa040391774f395c7b87c2d43bf906623194
2,952
package com.alibaba.alink.operator.common.clustering; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.common.typeinfo.Types; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.ml.api.misc.param.Params; import org.apache.flink.table.api.TableSchema; import org.apache.flink.types.Row; import com.alibaba.alink.common.linalg.DenseVector; import com.alibaba.alink.common.linalg.Vector; import com.alibaba.alink.common.linalg.VectorUtil; import com.alibaba.alink.common.mapper.RichModelMapper; import com.alibaba.alink.common.utils.TableUtil; import com.alibaba.alink.operator.common.statistics.basicstatistic.MultivariateGaussian; import com.alibaba.alink.params.clustering.GmmPredictParams; import java.util.List; /** * Model mapper of Gaussian Mixture Model. */ public class GmmModelMapper extends RichModelMapper { private static final long serialVersionUID = -4999832537099548829L; private int vectorColIdx; private GmmModelData modelData; private MultivariateGaussian[] multivariateGaussians; private transient ThreadLocal <double[]> threadLocalProb; public GmmModelMapper(TableSchema modelSchema, TableSchema dataSchema, Params params) { super(modelSchema, dataSchema, params); String vectorColName = this.params.get(GmmPredictParams.VECTOR_COL); vectorColIdx = TableUtil.findColIndexWithAssertAndHint(dataSchema.getFieldNames(), vectorColName); } @Override protected Object predictResult(SlicedSelectedSample selection) throws Exception { return predictResultDetail(selection).f0; } @Override protected Tuple2 <Object, String> predictResultDetail(SlicedSelectedSample selection) throws Exception { Vector sample = VectorUtil.getVector(selection.get(vectorColIdx)); double[] prob = threadLocalProb.get(); int k = modelData.k; double probSum = 0.; for (int i = 0; i < k; i++) { double density = this.multivariateGaussians[i].pdf(sample); double p = modelData.data.get(i).weight * density; prob[i] = p; probSum += p; } for (int i = 0; i < k; i++) { prob[i] /= probSum; } int maxIndex = 0; double maxProb = prob[0]; for (int i = 1; i < k; i++) { if (prob[i] > maxProb) { maxProb = prob[i]; maxIndex = i; } } return Tuple2.of((long) maxIndex, new DenseVector(prob).toString()); } @Override protected TypeInformation <?> initPredResultColType(TableSchema modelSchema) { return Types.LONG; } @Override public void loadModel(List <Row> modelRows) { this.modelData = new GmmModelDataConverter().load(modelRows); this.multivariateGaussians = new MultivariateGaussian[this.modelData.k]; for (int i = 0; i < this.modelData.k; i++) { this.multivariateGaussians[i] = new MultivariateGaussian(modelData.data.get(i).mean, GmmModelData.expandCovarianceMatrix(modelData.data.get(i).cov, modelData.dim)); } threadLocalProb = ThreadLocal.withInitial(() -> new double[this.modelData.k]); } }
33.931034
105
0.757453
e52cbbda86624596899e6cb4af1b6f11456ba15b
504
//Lambada表达式例子 interface Command { //接口定义process方法用于封装"处理行为" void process(int[] target); } class ProcessArray{ public void process(int[] target,Command cmd) { cmd.process(target); } } public class Test086 { public static void main(String[] args) { ProcessArray pa = new ProcessArray(); int[] array = {3,-4, 6,4}; //处理数组,具体处理行为取决于匿名内部类 pa.process(array, (int[] target)->{ int sum = 0; for(int tmp : target) { sum += tmp; } System.out.println("数组元素的总和是:"+sum); }); } }
18
48
0.640873
ce288cf688e80123bcc605360078a4901ccc9dbf
81
package org.gwtproject.resources.client; public interface ResourcePrototype { }
16.2
40
0.82716
dd61ffb9fdc56c5ef72c968ba416f1354837167d
613
package com.puc.cmfback.repository; import com.puc.cmfback.model.entity.Produto; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import javax.transaction.Transactional; import java.util.List; @Repository public interface ProdutoRepository extends JpaRepository<Produto, Integer> { Produto findByNome(String nome); List<Produto> findByNomeStartingWith(String nome); }
29.190476
76
0.828711
d0c093a1d51e70638bcfbe2be634c00f42d40865
64
package test.factory; public class DataProviderConFactory { }
10.666667
37
0.796875
429c9a16a136290779b5fc016d401492dd60a70a
139
package net.liplum.coroutine; public class WaitForNextTick extends WaitForTicks{ public WaitForNextTick() { super(1); } }
17.375
50
0.697842
6680c4375f19e4947ee3740d5d4fc5dab7074f5d
870
package racingCar; import utils.RandomUtils; public class Car { private static final int MIN_VALUE = 0; private static final int MOVING_STANDARD = 4; private static final int MAX_VALUE = 9; private final String name; private int position = 0; public Car(String name){ this.name = name; } public int getRandomNumber(){ return RandomUtils.nextInt(MIN_VALUE, MAX_VALUE); } public void move(int randomNumber){ if(MOVING_STANDARD <= randomNumber){ this.position++; } } public String getName(){ return this.name; } public int getPosition(){ return this.position; } public void printRaceResult(){ System.out.print(this.name); System.out.print(" : "); for (int i = 0; i < this.position; i++){ System.out.print("-"); } System.out.println(); } public void raceResult(){ move(getRandomNumber()); printRaceResult(); } }
17.4
51
0.686207
daa7170eae6c01ba07405c0e7b0009b5e6879ba5
1,934
package pumpkinpotions.effect; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.ai.attributes.AttributeModifierManager; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.potion.Effect; import net.minecraft.potion.EffectType; import javax.annotation.Nonnull; public class GhostEffect extends Effect { public GhostEffect(EffectType typeIn, int liquidColorIn) { super(typeIn, liquidColorIn); } @Override public void applyAttributesModifiersToEntity(@Nonnull LivingEntity entity, @Nonnull AttributeModifierManager attributes, int amplifier) { super.applyAttributesModifiersToEntity(entity, attributes, amplifier); if (!entity.getEntityWorld().isRemote && entity instanceof PlayerEntity) { updateEffect(true, (PlayerEntity) entity); ((PlayerEntity) entity).sendPlayerAbilities(); } } @Override public void removeAttributesModifiersFromEntity(@Nonnull LivingEntity entity, @Nonnull AttributeModifierManager attributes, int amplifier) { super.removeAttributesModifiersFromEntity(entity, attributes, amplifier); if (!entity.getEntityWorld().isRemote && entity instanceof PlayerEntity) { updateEffect(false, (PlayerEntity) entity); ((PlayerEntity) entity).abilities.isFlying = false; ((PlayerEntity) entity).sendPlayerAbilities(); } } public static void updateEffect(boolean effectActive, PlayerEntity player) { boolean before = player.abilities.allowFlying; if (effectActive) { player.abilities.allowFlying = true; player.abilities.flySpeed = 0.01f; } else { player.abilities.allowFlying = player.isCreative(); player.abilities.flySpeed = 0.05f; } if (before != player.abilities.allowFlying) { player.sendPlayerAbilities(); } } }
38.68
144
0.701655
893b1ee05cc5db180dab698c1b3daa74fe0d8b12
384
package org.apache.ibatis.reflection; import java.util.ArrayList; /** * 描述: * * @author: huifer * @date: 2019-12-09 */ public class Man extends People implements TestManInterface { @Override public Integer inte() { return 1; } public String hello() { return "hello"; } public ArrayList<String> getlist() { return null; } }
15.36
61
0.604167
e4176afcda8c184cb7c0da284cd85905d397afd0
5,813
package com.xt.ws.impl; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Request; import javax.ws.rs.core.UriInfo; import org.apache.struts2.json.JSONUtil; import com.xt.ws.IRESTSample; import com.xt.ws.MapBean; import com.xt.ws.User; import com.xt.ws.Users; /* 注释(Annotation):在 javax.ws.rs.* 中定义,是 JAX-RS (JSR 311) 规范的一部分。 @Path:定义资源基 URI。由上下文根和主机名组成,资源标识符类似于 http://localhost:8080/RESTful/rest/hello。 @GET:这意味着以下方法可以响应 HTTP GET 方法。 @Produces:以纯文本方式定义响应内容 MIME 类型。 @Context: 使用该注释注入上下文对象,比如 Request、Response、UriInfo、ServletContext 等。 @Path("{contact}"):这是 @Path 注释,与根路径 “/contacts” 结合形成子资源的 URI。 @PathParam("contact"):该注释将参数注入方法参数的路径,在本例中就是联系人 id。其他可用的注释有 @FormParam、@QueryParam 等。 @Produces:响应支持多个 MIME 类型。在本例和上一个示例中,APPLICATION/XML 将是默认的 MIME 类型。 */ /** * <b>function:</b> CXF RESTful风格WebService * @author hoojo * @createDate 2012-7-20 下午01:23:04 * @file RESTSampleSource.java * @package com.hoo.service * @project CXFWebService * @blog http://blog.csdn.net/IBM_hoojo * @email hoojo_@126.com * @version 1.0 */ @Path(value = "/sample") public class RESTSampleSourceImpl implements IRESTSample { @Context private UriInfo uriInfo;//解析你的请求地址 @Context private Request request; @GET @Produces(MediaType.TEXT_PLAIN) public String doGet() { return "this is get rest request"; } @GET @Produces(MediaType.TEXT_PLAIN) @Path("/request/{param}") public String doRequest(@PathParam("param") String param, @Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse) { System.out.println(servletRequest); System.out.println(servletResponse); System.out.println("参数是:"+param); System.out.println(servletRequest.getContentType()); System.out.println(servletResponse.getCharacterEncoding()); System.out.println(servletResponse.getContentType()); return "success"; } @GET @Path("/bean/{id}") @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public User getBean(@PathParam("id") int id) { System.out.println("####getBean#####"); System.out.println("id:" + id); System.out.println("Method:" + request.getMethod()); System.out.println("uri:" + uriInfo.getPath()); System.out.println(uriInfo.getPathParameters()); User user = new User(); user.setId(id); user.setUsername("JojO"); return user; } @GET @Path("/list") @Produces({ MediaType.TEXT_PLAIN}) public String getList() { System.out.println("####getList#####"); System.out.println("Method:" + request.getMethod()); System.out.println("uri:" + uriInfo.getPath()); System.out.println(uriInfo.getPathParameters()); List<User> list = new ArrayList<User>(); User user = null; for (int i = 0; i < 4;i ++) { user = new User(); user.setId(i); user.setAccount("xiaoming-"+i); user.setPassword("11111-"+i); user.setUsername("JojO-" + i); list.add(user); } Users users = new Users(); users.setUsers(list); try { return JSONUtil.serialize(users); } catch (Exception e) { return null; } } @GET @Path("/map") @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public MapBean getMap() { System.out.println("####getMap#####"); System.out.println("Method:" + request.getMethod()); System.out.println("uri:" + uriInfo.getPath()); System.out.println(uriInfo.getPathParameters()); Map<String, User> map = new HashMap<String, User>(); User user = null; for (int i = 0; i < 4;i ++) { user = new User(); user.setId(i); user.setUsername("JojO-" + i); map.put("key-" + i, user); } MapBean bean = new MapBean(); bean.setMap(map); return bean; } /* @Consumes:声明该方法使用 HTML FORM。 @FormParam:注入该方法的 HTML 属性确定的表单输入。 @Response.created(uri).build(): 构建新的 URI 用于新创建的联系人(/contacts/{id})并设置响应代码(201/created)。 您可以使用 http://localhost:8080/Jersey/rest/contacts/<id> 访问新联系人 */ @POST @Path("/postData") @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public User postData(User user) throws IOException { System.out.println(user); user.setUsername("jojo##12321321"); return user; } @PUT @Path("/putData/{id}") @Produces({ MediaType.APPLICATION_XML }) public User putData(@PathParam("id") int id, User user) { System.out.println("#####putData#####"); System.out.println(user); user.setId(id); user.setUsername("hoojo"); System.out.println(user); return user; } @DELETE @Path("/removeData/{id}") public void deleteData(@PathParam("id") int id) { System.out.println("#######deleteData#######" + id); } }
32.116022
104
0.598486
6911ee14e2ff99b431f6a25bee5d556574a13828
274
package Absyn; import Symbol.Symbol; public class FieldList extends Absyn { public Symbol name; public Symbol typ; public FieldList tail; public boolean escape = true; public FieldList(int p, Symbol n, Symbol t, FieldList x) {pos=p; name=n; typ=t; tail=x;} }
27.4
91
0.715328
26fd2654239f9e5ea5f70d32d926fa225a16a6d6
8,284
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.hardware.display; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.SystemApi; import android.annotation.TestApi; import android.os.Parcel; import android.os.Parcelable; import com.android.internal.util.Preconditions; import java.time.LocalDate; import java.util.Arrays; import java.util.Objects; /** * AmbientBrightnessDayStats stores and manipulates brightness stats over a single day. * {@see DisplayManager.getAmbientBrightnessStats()} * * @hide */ @SystemApi @TestApi public final class AmbientBrightnessDayStats implements Parcelable { /** The localdate for which brightness stats are being tracked */ private final LocalDate mLocalDate; /** Ambient brightness values for creating bucket boundaries from */ private final float[] mBucketBoundaries; /** Stats of how much time (in seconds) was spent in each of the buckets */ private final float[] mStats; /** * Initialize day stats from the given state. The time spent in each of the bucket is * initialized to 0. * * @param localDate The date for which stats are being tracked * @param bucketBoundaries Bucket boundaries used from creating the buckets from * @hide */ public AmbientBrightnessDayStats(@NonNull LocalDate localDate, @NonNull float[] bucketBoundaries) { this(localDate, bucketBoundaries, null); } /** * Initialize day stats from the given state * * @param localDate The date for which stats are being tracked * @param bucketBoundaries Bucket boundaries used from creating the buckets from * @param stats Time spent in each of the buckets (in seconds) * @hide */ public AmbientBrightnessDayStats(@NonNull LocalDate localDate, @NonNull float[] bucketBoundaries, float[] stats) { Objects.requireNonNull(localDate); Objects.requireNonNull(bucketBoundaries); Preconditions.checkArrayElementsInRange(bucketBoundaries, 0, Float.MAX_VALUE, "bucketBoundaries"); if (bucketBoundaries.length < 1) { throw new IllegalArgumentException("Bucket boundaries must contain at least 1 value"); } checkSorted(bucketBoundaries); if (stats == null) { stats = new float[bucketBoundaries.length]; } else { Preconditions.checkArrayElementsInRange(stats, 0, Float.MAX_VALUE, "stats"); if (bucketBoundaries.length != stats.length) { throw new IllegalArgumentException( "Bucket boundaries and stats must be of same size."); } } mLocalDate = localDate; mBucketBoundaries = bucketBoundaries; mStats = stats; } /** * @return The {@link LocalDate} for which brightness stats are being tracked. */ public LocalDate getLocalDate() { return mLocalDate; } /** * @return Aggregated stats of time spent (in seconds) in various buckets. */ public float[] getStats() { return mStats; } /** * Returns the bucket boundaries (in lux) used for creating buckets. For eg., if the bucket * boundaries array is {b1, b2, b3}, the buckets will be [b1, b2), [b2, b3), [b3, inf). * * @return The list of bucket boundaries. */ public float[] getBucketBoundaries() { return mBucketBoundaries; } private AmbientBrightnessDayStats(Parcel source) { mLocalDate = LocalDate.parse(source.readString()); mBucketBoundaries = source.createFloatArray(); mStats = source.createFloatArray(); } public static final @android.annotation.NonNull Creator<AmbientBrightnessDayStats> CREATOR = new Creator<AmbientBrightnessDayStats>() { @Override public AmbientBrightnessDayStats createFromParcel(Parcel source) { return new AmbientBrightnessDayStats(source); } @Override public AmbientBrightnessDayStats[] newArray(int size) { return new AmbientBrightnessDayStats[size]; } }; @Override public boolean equals(@Nullable Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } AmbientBrightnessDayStats other = (AmbientBrightnessDayStats) obj; return mLocalDate.equals(other.mLocalDate) && Arrays.equals(mBucketBoundaries, other.mBucketBoundaries) && Arrays.equals(mStats, other.mStats); } @Override public int hashCode() { final int prime = 31; int result = 1; result = result * prime + mLocalDate.hashCode(); result = result * prime + Arrays.hashCode(mBucketBoundaries); result = result * prime + Arrays.hashCode(mStats); return result; } @NonNull @Override public String toString() { StringBuilder bucketBoundariesString = new StringBuilder(); StringBuilder statsString = new StringBuilder(); for (int i = 0; i < mBucketBoundaries.length; i++) { if (i != 0) { bucketBoundariesString.append(", "); statsString.append(", "); } bucketBoundariesString.append(mBucketBoundaries[i]); statsString.append(mStats[i]); } return new StringBuilder() .append(mLocalDate).append(" ") .append("{").append(bucketBoundariesString).append("} ") .append("{").append(statsString).append("}").toString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mLocalDate.toString()); dest.writeFloatArray(mBucketBoundaries); dest.writeFloatArray(mStats); } /** * Updates the stats by incrementing the time spent for the appropriate bucket based on ambient * brightness reading. * * @param ambientBrightness Ambient brightness reading (in lux) * @param durationSec Time spent with the given reading (in seconds) * @hide */ public void log(float ambientBrightness, float durationSec) { int bucketIndex = getBucketIndex(ambientBrightness); if (bucketIndex >= 0) { mStats[bucketIndex] += durationSec; } } private int getBucketIndex(float ambientBrightness) { if (ambientBrightness < mBucketBoundaries[0]) { return -1; } int low = 0; int high = mBucketBoundaries.length - 1; while (low < high) { int mid = (low + high) / 2; if (mBucketBoundaries[mid] <= ambientBrightness && ambientBrightness < mBucketBoundaries[mid + 1]) { return mid; } else if (mBucketBoundaries[mid] < ambientBrightness) { low = mid + 1; } else if (mBucketBoundaries[mid] > ambientBrightness) { high = mid - 1; } } return low; } private static void checkSorted(float[] values) { if (values.length <= 1) { return; } float prevValue = values[0]; for (int i = 1; i < values.length; i++) { Preconditions.checkState(prevValue < values[i]); prevValue = values[i]; } return; } }
33.95082
99
0.620715
d9c48fbd23a55dc00ca5c615c84a1110e21121a1
3,012
package cn.mobile.entity; /** * Created by LucasX on 2016/4/27. * <p> * WAP版的商户信息 */ public class Shop { //shopList页面就可以直接获取到的信息 private String shopId; private String shopName; private String avgPrice; private String address; private String rank;//星级--从图片链接src中取,src="/static/img/irr-star50.png"就代表"五星" private String bigType;//商户大类 -- 从type.xml中直接传入,不需要解析 //需要二次请求到商户详情页才能获取 private String phoneNumber; private String recommendInfo;//网友推荐 private String commentNum;//点评条数 public Shop(String shopId, String shopName, String avgPrice, String address, String rank, String bigType, String phoneNumber, String recommendInfo, String commentNum) { this.shopId = shopId; this.shopName = shopName; this.avgPrice = avgPrice; this.address = address; this.rank = rank; this.bigType = bigType; this.phoneNumber = phoneNumber; this.recommendInfo = recommendInfo; this.commentNum = commentNum; } public Shop() { } public String getShopId() { return shopId; } public void setShopId(String shopId) { this.shopId = shopId; } public String getShopName() { return shopName; } public void setShopName(String shopName) { this.shopName = shopName; } public String getAvgPrice() { return avgPrice; } public void setAvgPrice(String avgPrice) { this.avgPrice = avgPrice; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getRank() { return rank; } public void setRank(String rank) { this.rank = rank; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getRecommendInfo() { return recommendInfo; } public void setRecommendInfo(String recommendInfo) { this.recommendInfo = recommendInfo; } public String getCommentNum() { return commentNum; } public void setCommentNum(String commentNum) { this.commentNum = commentNum; } public String getBigType() { return bigType; } public void setBigType(String bigType) { this.bigType = bigType; } @Override public String toString() { return "Shop{" + "shopId='" + shopId + '\'' + ", shopName='" + shopName + '\'' + ", avgPrice='" + avgPrice + '\'' + ", address='" + address + '\'' + ", rank='" + rank + '\'' + ", bigType='" + bigType + '\'' + ", phoneNumber='" + phoneNumber + '\'' + ", recommendInfo='" + recommendInfo + '\'' + ", commentNum='" + commentNum + '\'' + '}'; } }
23.904762
100
0.573373
d49e11d51868a4309107e01958d737ba9d114748
1,838
/* * Licensed to Elastic Search and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Elastic Search 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.elasticsearch.common.util.concurrent; import java.lang.annotation.*; /** * Immutable * <p/> * The class to which this annotation is applied is immutable. This means that * its state cannot be seen to change by callers. Of necessity this means that * all public fields are final, and that all public final reference fields refer * to other immutable objects, and that methods do not publish references to any * internal state which is mutable by implementation even if not by design. * Immutable objects may still have internal mutable state for purposes of * performance optimization; some state variables may be lazily computed, so * long as they are computed from immutable state and that callers cannot tell * the difference. * <p/> * Immutable objects are inherently thread-safe; they may be passed between * threads or published without synchronization. * * @author kimchy (Shay Banon) */ @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) public @interface Immutable { }
39.106383
80
0.76333
6c431ea2fa61764c20d48353a16042b45a12ac48
1,511
/* ### * IP: GHIDRA * * 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 ghidra.app.plugin.assembler.sleigh.symbol; import java.util.*; import ghidra.app.plugin.assembler.sleigh.grammars.AssemblyGrammar; import ghidra.app.plugin.assembler.sleigh.tree.AssemblyParseToken; /** * A terminal that accepts the end of input */ public class AssemblyEOI extends AssemblyTerminal { /** The end-of-input terminal */ public static final AssemblyEOI EOI = new AssemblyEOI(); private AssemblyEOI() { super("$"); } @Override public String toString() { return "$"; } @Override public Collection<AssemblyParseToken> match(String buffer, int pos, AssemblyGrammar grammar, Map<String, Long> labels) { if (pos == buffer.length()) { return Collections.singleton(new AssemblyParseToken(grammar, this, "")); } return Collections.emptySet(); } @Override public Collection<String> getSuggestions(String got, Map<String, Long> labels) { return Collections.singleton(""); } }
28.509434
93
0.72998
cd3ab90d51532f20d2919eee0a3bd0b9224b0dab
878
package org.distributeme.registry.ui.action; import net.anotheria.maf.action.Action; import net.anotheria.maf.action.ActionCommand; import net.anotheria.maf.action.ActionMapping; import net.anotheria.maf.bean.FormBean; import org.distributeme.core.ServiceDescriptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Action that unbinds item from registry. * @author dsilenko */ public class RegistryUnbindAction extends BaseRegistryAction implements Action { @Override public ActionCommand execute(ActionMapping mapping, FormBean formBean, HttpServletRequest req, HttpServletResponse res) throws Exception { String unbindId = req.getParameter(ID_PARAMETER_NAME); ServiceDescriptor toUnBind = ServiceDescriptor.fromRegistrationString(unbindId); getRegistry().unbind(toUnBind); return mapping.redirect(); } }
30.275862
139
0.817768
e12fb709fa37709bbc2d0c312436d0db8e7d09a2
1,717
package ru.job4j.html; import java.util.Objects; /** * @author Aleksandr Karpachov * @version 1.0 * @since 26.10.2019 */ public class User { String name; String surname; String gender; String description; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } User demoUser = (User) o; return Objects.equals(name, demoUser.name) && Objects.equals(surname, demoUser.surname) && Objects.equals(gender, demoUser.gender) && Objects.equals(description, demoUser.description); } @Override public int hashCode() { return Objects.hash(name, surname, gender, description); } @Override public String toString() { return "DemoUser{" + "name='" + name + '\'' + ", surname='" + surname + '\'' + ", gender='" + gender + '\'' + ", description='" + description + '\'' + '}'; } }
21.734177
69
0.531741
3af5354d410b0163e9666706ff38f6c8c324d221
620
package com.speyejack.learning.neat; import java.awt.Dimension; import java.io.Serializable; import java.util.HashMap; import java.util.Map; public class Innovation implements Serializable{ private static final long serialVersionUID = 4527372854080147954L; private int inno = 0; private Map<Dimension, Integer> innovations = new HashMap<Dimension, Integer>(); public int getInnovation(int in, int out) { Dimension dim = new Dimension(in, out); if (!innovations.containsKey(dim)) innovations.put(dim, inno++); return innovations.get(dim); } public void clearInnovation(){ innovations.clear(); } }
24.8
81
0.754839
d2233d7a7fd4cd83f451b059984dd332e67258ea
149
package com.laytonsmith.abstraction; /** * * @author Jim */ public interface MCLightningStrike extends MCEntity{ public boolean isEffect(); }
12.416667
52
0.731544
9273a90cbc141f109b6f59f0d68b570a1963d33d
40,678
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////////// package Associations; import java.util.Iterator; import java.util.Vector; import org.pegasus.jmpi.AssociatorProvider; import org.pegasus.jmpi.CIMClass; import org.pegasus.jmpi.CIMDataType; import org.pegasus.jmpi.CIMException; import org.pegasus.jmpi.CIMInstance; import org.pegasus.jmpi.CIMObjectPath; import org.pegasus.jmpi.CIMOMHandle; import org.pegasus.jmpi.CIMProperty; import org.pegasus.jmpi.CIMValue; import org.pegasus.jmpi.InstanceProvider; import org.pegasus.jmpi.OperationContext; import org.pegasus.jmpi.UnsignedInt8; import org.pegasus.jmpi.UnsignedInt64; public class JMPIAssociationProvider implements InstanceProvider, AssociatorProvider { private CIMOMHandle handle = null; private Vector paths = new Vector (); private Vector instances = new Vector (); private boolean fEnableModifications = true; private final boolean DEBUG = false; public void initialize (CIMOMHandle handle) throws CIMException { if (DEBUG) { System.err.println ("JMPIAssociationProvider::initialize: handle = " + handle); } this.handle = handle; createDefaultInstances (); } public void cleanup () throws CIMException { if (DEBUG) { System.err.println ("JMPIAssociationProvider::cleanup"); } } public CIMObjectPath createInstance (CIMObjectPath cop, CIMInstance cimInstance) throws CIMException { if (DEBUG) { System.err.println ("JMPIAssociationProvider::createInstance: cop = " + cop); System.err.println ("JMPIAssociationProvider::createInstance: cimInstance = " + cimInstance); } throw new CIMException (CIMException.CIM_ERR_NOT_SUPPORTED); } public void deleteInstance (CIMObjectPath cop) throws CIMException { if (DEBUG) { System.err.println ("JMPIAssociationProvider::deleteInstance: cop = " + cop); } throw new CIMException (CIMException.CIM_ERR_NOT_SUPPORTED); } // enumerateInstanceNames public Vector enumInstances (CIMObjectPath cop, boolean deepInheritance, CIMClass cimClass) throws CIMException { if (DEBUG) { System.err.println ("JMPIAssociationProvider::enumerateInstanceNames: cop = " + cop); System.err.println ("JMPIAssociationProvider::enumerateInstanceNames: deepInheritance = " + deepInheritance); System.err.println ("JMPIAssociationProvider::enumerateInstanceNames: cimClass = " + cimClass); } // Enusre that the namespace is valid if (!cop.getNameSpace ().equalsIgnoreCase (NAMESPACE)) { throw new CIMException (CIMException.CIM_ERR_INVALID_NAMESPACE); } // Ensure that the class exists in the specified namespace if (cop.getObjectName ().equalsIgnoreCase (SAMPLE_TEACHER)) { return _enumerateInstanceNames (teacherInstances); } else if (cop.getObjectName ().equalsIgnoreCase (SAMPLE_STUDENT)) { return _enumerateInstanceNames (studentInstances); } else if (cop.getObjectName ().equalsIgnoreCase (SAMPLE_TEACHERSTUDENT)) { return _enumerateInstanceNames (TSassociationInstances); } else if (cop.getObjectName ().equalsIgnoreCase (SAMPLE_ADVISORSTUDENT)) { return _enumerateInstanceNames (ASassociationInstances); } else { throw new CIMException (CIMException.CIM_ERR_INVALID_CLASS); } } public Vector enumInstances (CIMObjectPath cop, boolean deepInheritance, CIMClass cimClass, boolean localOnly) throws CIMException { if (DEBUG) { System.err.println ("JMPIAssociationProvider::enumerateInstances: cop = " + cop); System.err.println ("JMPIAssociationProvider::enumerateInstances: deepInheritance = " + deepInheritance); System.err.println ("JMPIAssociationProvider::enumerateInstances: cimClass = " + cimClass); System.err.println ("JMPIAssociationProvider::enumerateInstances: localOnly = " + localOnly); } // Enusre that the namespace is valid if (!cop.getNameSpace ().equalsIgnoreCase (NAMESPACE)) { throw new CIMException (CIMException.CIM_ERR_INVALID_NAMESPACE); } Vector vectorReturn = null; // Ensure that the class exists in the specified namespace if (cop.getObjectName ().equalsIgnoreCase (SAMPLE_TEACHER)) { vectorReturn = _enumerateInstances (teacherInstances); } else if (cop.getObjectName ().equalsIgnoreCase (SAMPLE_STUDENT)) { vectorReturn = _enumerateInstances (studentInstances); } else if (cop.getObjectName ().equalsIgnoreCase (SAMPLE_TEACHERSTUDENT)) { vectorReturn = _enumerateInstances (TSassociationInstances); } else if (cop.getObjectName ().equalsIgnoreCase (SAMPLE_ADVISORSTUDENT)) { vectorReturn = _enumerateInstances (ASassociationInstances); } else { throw new CIMException (CIMException.CIM_ERR_INVALID_CLASS); } if (DEBUG) { System.err.println ("JMPIAssociationProvider::enumerateInstances: returning " + vectorReturn.size () + " instances"); } return vectorReturn; } public CIMInstance getInstance (CIMObjectPath cop, CIMClass cimClass, boolean localOnly) throws CIMException { if (DEBUG) { System.err.println ("JMPIAssociationProvider::getInstance: cop = " + cop); System.err.println ("JMPIAssociationProvider::getInstance: cimClass = " + cimClass); System.err.println ("JMPIAssociationProvider::getInstance: localOnly = " + localOnly); } CIMObjectPath localObjectPath = (CIMObjectPath)cop.clone (); localObjectPath.setHost (""); localObjectPath.setNameSpace (NAMESPACE); // Ensure that the class exists in the specified namespace if (cop.getObjectName ().equalsIgnoreCase (SAMPLE_TEACHER)) { return _getInstance (teacherInstances, localObjectPath); } else if (cop.getObjectName ().equalsIgnoreCase (SAMPLE_STUDENT)) { return _getInstance (studentInstances, localObjectPath); } else if (cop.getObjectName ().equalsIgnoreCase (SAMPLE_TEACHERSTUDENT)) { return _getInstance (TSassociationInstances, localObjectPath); } else if (cop.getObjectName ().equalsIgnoreCase (SAMPLE_ADVISORSTUDENT)) { return _getInstance (ASassociationInstances, localObjectPath); } else { throw new CIMException (CIMException.CIM_ERR_INVALID_CLASS); } } public void setInstance (CIMObjectPath cop, CIMInstance cimInstance) throws CIMException { if (DEBUG) { System.err.println ("JMPIAssociationProvider::modifyInstance: cop = " + cop); System.err.println ("JMPIAssociationProvider::modifyInstance: cimInstance = " + cimInstance); } throw new CIMException (CIMException.CIM_ERR_NOT_SUPPORTED); } public Vector execQuery (CIMObjectPath cop, String queryStatement, int queryLanguage, CIMClass cimClass) throws CIMException { if (DEBUG) { System.err.println ("JMPIAssociationProvider::execQuery: cop = " + cop); System.err.println ("JMPIAssociationProvider::execQuery: queryStatement = " + queryStatement); System.err.println ("JMPIAssociationProvider::execQuery: queryLanguage = " + queryLanguage); System.err.println ("JMPIAssociationProvider::execQuery: cimClass = " + cimClass); } throw new CIMException (CIMException.CIM_ERR_NOT_SUPPORTED); } public Vector associatorNames (CIMObjectPath assocName, CIMObjectPath objectName, String resultClass, String role, String resultRole) throws CIMException { if (DEBUG) { System.err.println ("JMPIAssociationProvider::associatorNames: assocName = " + assocName); System.err.println ("JMPIAssociationProvider::associatorNames: objectName = " + objectName); System.err.println ("JMPIAssociationProvider::associatorNames: resultClass = " + resultClass); System.err.println ("JMPIAssociationProvider::associatorNames: role = " + role); System.err.println ("JMPIAssociationProvider::associatorNames: resultRole = " + resultRole); } // Enusre that the namespace is valid if (!assocName.getNameSpace ().equalsIgnoreCase (NAMESPACE)) { throw new CIMException (CIMException.CIM_ERR_INVALID_NAMESPACE); } CIMObjectPath localObjectPath = new CIMObjectPath (objectName.getObjectName (), objectName.getKeys ()); localObjectPath.setHost (""); localObjectPath.setNameSpace (NAMESPACE); Vector vectorReturn = null; if (assocName.getObjectName ().equalsIgnoreCase (SAMPLE_TEACHERSTUDENT)) { vectorReturn = _associatorNames (TSassociationInstances, localObjectPath, role, resultClass, resultRole); } else if (assocName.getObjectName ().equalsIgnoreCase (SAMPLE_ADVISORSTUDENT)) { vectorReturn = _associatorNames (ASassociationInstances, localObjectPath, role, resultClass, resultRole); } else { throw new CIMException (CIMException.CIM_ERR_INVALID_CLASS, assocName.getObjectName () + " is not supported"); } if (DEBUG) { System.err.println ("JMPIAssociationProvider::associatorNames: returning " + vectorReturn.size () + " instances"); } return vectorReturn; } public Vector associators (CIMObjectPath assocName, CIMObjectPath objectName, String resultClass, String role, String resultRole, boolean includeQualifiers, boolean includeClassOrigin, String[] propertyList) throws CIMException { if (DEBUG) { System.err.println ("JMPIAssociationProvider::associators: assocName = " + assocName); System.err.println ("JMPIAssociationProvider::associators: objectName = " + objectName); System.err.println ("JMPIAssociationProvider::associators: resultClass = " + resultClass); System.err.println ("JMPIAssociationProvider::associators: role = " + role); System.err.println ("JMPIAssociationProvider::associators: resultRole = " + resultRole); System.err.println ("JMPIAssociationProvider::associators: includeQualifiers = " + includeQualifiers); System.err.println ("JMPIAssociationProvider::associators: includeClassOrigin = " + includeClassOrigin); System.err.println ("JMPIAssociationProvider::associators: propertyList = " + propertyList); } // Enusre that the namespace is valid if (!assocName.getNameSpace ().equalsIgnoreCase (NAMESPACE)) { throw new CIMException (CIMException.CIM_ERR_INVALID_NAMESPACE); } CIMObjectPath localObjectPath = new CIMObjectPath (objectName.getObjectName (), objectName.getKeys ()); localObjectPath.setHost (""); localObjectPath.setNameSpace (NAMESPACE); Vector vectorReturn = null; if (assocName.getObjectName ().equalsIgnoreCase (SAMPLE_TEACHERSTUDENT)) { vectorReturn = _associators (TSassociationInstances, localObjectPath, role, resultClass, resultRole); } else if (assocName.getObjectName ().equalsIgnoreCase (SAMPLE_ADVISORSTUDENT)) { vectorReturn = _associators (ASassociationInstances, localObjectPath, role, resultClass, resultRole); } else { throw new CIMException (CIMException.CIM_ERR_INVALID_CLASS, assocName.getObjectName () + " is not supported"); } if (DEBUG) { System.err.println ("JMPIAssociationProvider::associators: returning " + vectorReturn.size () + " instances"); } return vectorReturn; } public Vector referenceNames (CIMObjectPath assocName, CIMObjectPath objectName, String role) throws CIMException { if (DEBUG) { System.err.println ("JMPIAssociationProvider::referenceNames: assocName = " + assocName); System.err.println ("JMPIAssociationProvider::referenceNames: objectName = " + objectName); System.err.println ("JMPIAssociationProvider::referenceNames: role = " + role); } // Enusre that the namespace is valid if (!assocName.getNameSpace ().equalsIgnoreCase (NAMESPACE)) { throw new CIMException (CIMException.CIM_ERR_INVALID_NAMESPACE); } CIMObjectPath localObjectPath = new CIMObjectPath (objectName.getObjectName (), objectName.getKeys ()); localObjectPath.setHost (""); localObjectPath.setNameSpace (NAMESPACE); // Filter the instances from the list of association instances against // the specified role filter // Vector resultInstances; if (assocName.getObjectName ().equalsIgnoreCase (SAMPLE_TEACHERSTUDENT)) { resultInstances = _filterAssociationInstancesByRole (TSassociationInstances, localObjectPath, role); } else if (assocName.getObjectName ().equalsIgnoreCase (SAMPLE_ADVISORSTUDENT)) { resultInstances = _filterAssociationInstancesByRole (ASassociationInstances, localObjectPath, role); } else { throw new CIMException (CIMException.CIM_ERR_INVALID_CLASS, assocName.getObjectName () + " is not supported"); } Vector vectorReturn = new Vector (); // return the instance names for (int i = 0, si = resultInstances.size (); i < si; i++) { CIMObjectPath objectPath = ((CIMInstance)resultInstances.elementAt (i)).getObjectPath (); vectorReturn.addElement (objectPath); } if (DEBUG) { System.err.println ("JMPIAssociationProvider::referenceNames: returning " + vectorReturn.size () + " instances"); } return vectorReturn; } public Vector references (CIMObjectPath assocName, CIMObjectPath objectName, String role, boolean includeQualifiers, boolean includeClassOrigin, String[] propertyList) throws CIMException { if (DEBUG) { System.err.println ("JMPIAssociationProvider::references: assocName = " + assocName); System.err.println ("JMPIAssociationProvider::references: objectName = " + objectName); System.err.println ("JMPIAssociationProvider::references: role = " + role); System.err.println ("JMPIAssociationProvider::references: includeQualifiers = " + includeQualifiers); System.err.println ("JMPIAssociationProvider::references: includeClassOrigin = " + includeClassOrigin); System.err.println ("JMPIAssociationProvider::references: propertyList = " + propertyList); } // Enusre that the namespace is valid if (!assocName.getNameSpace ().equalsIgnoreCase (NAMESPACE)) { throw new CIMException (CIMException.CIM_ERR_INVALID_NAMESPACE); } CIMObjectPath localObjectPath = new CIMObjectPath (objectName.getObjectName (), objectName.getKeys ()); localObjectPath.setHost (""); localObjectPath.setNameSpace (NAMESPACE); // Filter the instances from the list of association instances against // the specified role filter // Vector resultInstances; if (assocName.getObjectName ().equalsIgnoreCase (SAMPLE_TEACHERSTUDENT)) { resultInstances = _filterAssociationInstancesByRole (TSassociationInstances, localObjectPath, role); } else if (assocName.getObjectName ().equalsIgnoreCase (SAMPLE_ADVISORSTUDENT)) { resultInstances = _filterAssociationInstancesByRole (ASassociationInstances, localObjectPath, role); } else { throw new CIMException (CIMException.CIM_ERR_INVALID_CLASS, assocName.getObjectName () + " is not supported"); } if (DEBUG) { System.err.println ("JMPIAssociationProvider::references: returning " + resultInstances.size () + " instances"); } return resultInstances; } private void createDefaultInstances () { // // create 4 instances of the SAMPLE_TEACHER class // teacherInstances.add (createInstance (SAMPLE_TEACHER, "Teacher1", 1)); teacherInstances.add (createInstance (SAMPLE_TEACHER, "Teacher2", 2)); teacherInstances.add (createInstance (SAMPLE_TEACHER, "Teacher3", 3)); teacherInstances.add (createInstance (SAMPLE_TEACHER, "Teacher4", 4)); // // create 3 instances of the SAMPLE_STUDENT class // studentInstances.add (createInstance (SAMPLE_STUDENT, "Student1", 1)); studentInstances.add (createInstance (SAMPLE_STUDENT, "Student2", 2)); studentInstances.add (createInstance (SAMPLE_STUDENT, "Student3", 3)); // // create the instances for the SAMPLE_TEACHERSTUDENT association class // (Teacher1, Student1) // (Teacher1, Student2) // (Teacher1, Student3) // (Teacher2, Student1) // (Teacher2, Student2) // (Teacher3, Student2) // (Teacher3, Student3) // (Teacher4, Student1) // TSassociationInstances.add (createTSAssociationInstance (getPath (teacherInstances, 0), getPath (studentInstances, 0))); TSassociationInstances.add (createTSAssociationInstance (getPath (teacherInstances, 0), getPath (studentInstances, 1))); TSassociationInstances.add (createTSAssociationInstance (getPath (teacherInstances, 0), getPath (studentInstances, 2))); TSassociationInstances.add (createTSAssociationInstance (getPath (teacherInstances, 1), getPath (studentInstances, 0))); TSassociationInstances.add (createTSAssociationInstance (getPath (teacherInstances, 1), getPath (studentInstances, 1))); TSassociationInstances.add (createTSAssociationInstance (getPath (teacherInstances, 2), getPath (studentInstances, 1))); TSassociationInstances.add (createTSAssociationInstance (getPath (teacherInstances, 2), getPath (studentInstances, 2))); TSassociationInstances.add (createTSAssociationInstance (getPath (teacherInstances, 3), getPath (studentInstances, 0))); // // create the instances for the SAMPLE_ADVISORSTUDENT association class // (Teacher1, Student1) // (Teacher1, Student2) // (Teacher2, Student3) // ASassociationInstances.add (createASAssociationInstance (getPath (teacherInstances, 0), getPath (studentInstances, 0))); ASassociationInstances.add (createASAssociationInstance (getPath (teacherInstances, 0), getPath (studentInstances, 1))); ASassociationInstances.add (createASAssociationInstance (getPath (teacherInstances, 1), getPath (studentInstances, 2))); } private CIMObjectPath getPath (Vector v, int i) { try { CIMInstance c = (CIMInstance)v.elementAt (i); return c.getObjectPath (); } catch (Exception e) { System.err.println ("JMPIAssociationProvider::getPath: Caught Exception " + e); } return null; } private CIMInstance createInstance (String className, String name, int id) { try { CIMProperty[] props = { new CIMProperty ("Name", new CIMValue (name)), /* @TBD: cimcli doesnt pass this in: className */ new CIMProperty ("Identifier", new CIMValue (new UnsignedInt8 (Integer.toString (id)))) /* @TBD: ... className */ }; CIMObjectPath cop = new CIMObjectPath (className, NAMESPACE); CIMInstance instance = new CIMInstance (className); for (int i = 0; i < props.length; i++) { instance.setProperty (props[i].getName (), props[i].getValue ()); cop.addKey (props[i].getName (), props[i].getValue ()); } cop.setHost (""); instance.setObjectPath (cop); return instance; } catch (CIMException e) { return null; } } private CIMInstance createTSAssociationInstance (CIMObjectPath ref1, CIMObjectPath ref2) { try { CIMProperty[] props = { new CIMProperty ("Teaches", new CIMValue (ref1)), new CIMProperty ("TaughtBy", new CIMValue (ref2)) }; CIMObjectPath cop = new CIMObjectPath (SAMPLE_TEACHERSTUDENT, NAMESPACE); CIMInstance instance = new CIMInstance (SAMPLE_TEACHERSTUDENT); for (int i = 0; i < props.length; i++) { instance.setProperty (props[i].getName (), props[i].getValue ()); cop.addKey (props[i].getName (), props[i].getValue ()); } cop.setHost (""); instance.setObjectPath (cop); return instance; } catch (CIMException e) { return null; } } private CIMInstance createASAssociationInstance (CIMObjectPath ref1, CIMObjectPath ref2) { try { CIMProperty[] props = { new CIMProperty ("Advises", new CIMValue (ref1)), new CIMProperty ("AdvisedBy", new CIMValue (ref2)) }; CIMObjectPath cop = new CIMObjectPath (SAMPLE_ADVISORSTUDENT, NAMESPACE); CIMInstance instance = new CIMInstance (SAMPLE_ADVISORSTUDENT); for (int i = 0; i < props.length; i++) { instance.setProperty (props[i].getName (), props[i].getValue ()); cop.addKey (props[i].getName (), props[i].getValue ()); } cop.setHost (""); instance.setObjectPath (cop); return instance; } catch (CIMException e) { return null; } } private CIMInstance _getInstance (Vector instances, CIMObjectPath localObjectPath) { Iterator iteratorInstances = instances.iterator (); while (iteratorInstances.hasNext ()) { CIMInstance elm = (CIMInstance)iteratorInstances.next (); CIMObjectPath elmPath = elm.getObjectPath (); if (equals (localObjectPath, elmPath)) { return elm; } } return null; } private Vector _enumerateInstances (Vector instances) { return instances; } private Vector _enumerateInstanceNames (Vector instances) { Vector returnPaths = new Vector (); Iterator iteratorInstances = instances.iterator (); while (iteratorInstances.hasNext ()) { CIMInstance elm = (CIMInstance)iteratorInstances.next (); returnPaths.addElement (elm.getObjectPath ()); } return returnPaths; } private Vector _associators (Vector associationInstances, CIMObjectPath localObjectPath, String role, String resultClass, String resultRole) { Vector vectorReturn = new Vector (); // Filter the instances from the list of association instances against // the specified role filter // Vector assocInstances = null; assocInstances = _filterAssociationInstancesByRole (associationInstances, localObjectPath, role); if (DEBUG) { System.err.println ("JMPIAssociationProvider::_associators: assocInstances.size () = " + assocInstances.size ()); } // Now filter the result association instances against the specified // resultClass and resultRole filters // for (int i = 0, si = assocInstances.size (); i < si; i++) { Vector resultPaths; resultPaths = _filterAssociationInstances ((CIMInstance)assocInstances.elementAt (i), localObjectPath, resultClass, resultRole); if (DEBUG) { System.err.println ("JMPIAssociationProvider::_associators: resultPaths.size () = " + resultPaths.size ()); } for (int j = 0, sj = resultPaths.size (); j < sj; j++) { String className = ((CIMObjectPath)resultPaths.elementAt (j)).getObjectName (); if (className.equalsIgnoreCase (SAMPLE_TEACHER)) { if (DEBUG) { System.err.println ("JMPIAssociationProvider::_associators: teacherInstances.size () = " + teacherInstances.size ()); } // find instance that corresponds to the reference for (int k = 0, s = teacherInstances.size (); k < s; k++) { CIMObjectPath path = ((CIMInstance)teacherInstances.elementAt (k)).getObjectPath (); if (DEBUG) { System.err.println ("JMPIAssociationProvider::_associators: path = " + path); System.err.println ("JMPIAssociationProvider::_associators: resultPaths.elementAt (" + j + ") = " + resultPaths.elementAt (j)); } if (equals (((CIMObjectPath)resultPaths.elementAt (j)), path)) { if (DEBUG) { System.err.println ("JMPIAssociationProvider::_associators: adding!"); } // return the instance // Note: See below. vectorReturn.addElement (((CIMInstance)teacherInstances.elementAt (k)).clone ()); } } } else if (className.equalsIgnoreCase (SAMPLE_STUDENT)) { if (DEBUG) { System.err.println ("JMPIAssociationProvider::_associators: studentInstances.size () = " + studentInstances.size ()); } // find instance that corresponds to the reference for (int k = 0, s = studentInstances.size (); k < s; k++) { CIMObjectPath path = ((CIMInstance)studentInstances.elementAt (k)).getObjectPath (); if (DEBUG) { System.err.println ("JMPIAssociationProvider::_associators: path = " + path); System.err.println ("JMPIAssociationProvider::_associators: resultPaths.elementAt (" + j + ") = " + resultPaths.elementAt (j)); } if (equals (((CIMObjectPath)resultPaths.elementAt (j)), path)) { if (DEBUG) { System.err.println ("JMPIAssociationProvider::_associators: adding!"); } // return the instance // Note: We must clone what is being returned since otherwise our // copy will be modified. // The CIMObjectPath will change from: // root/SampleProvider:JMPIAssociation_Student.Identifier=1,Name="Student1" // to: // root/SampleProvider:JMPIAssociation_Student.Name="Student1" vectorReturn.addElement (((CIMInstance)studentInstances.elementAt (k)).clone ()); } } } } } return vectorReturn; } private Vector _associatorNames (Vector associationInstances, CIMObjectPath localObjectPath, String role, String resultClass, String resultRole) { Vector vectorReturn = new Vector (); // Filter the instances from the list of association instances against // the specified role filter // Vector assocInstances; assocInstances = _filterAssociationInstancesByRole (associationInstances, localObjectPath, role); if (DEBUG) { System.err.println ("JMPIAssociationProvider::_associatorNames: assocInstances.size () = " + assocInstances.size ()); } // Now filter the result association instances against the specified // resultClass and resultRole filters // for (int i = 0, si = assocInstances.size (); i < si; i++) { Vector resultPaths; resultPaths = _filterAssociationInstances ((CIMInstance)assocInstances.elementAt (i), localObjectPath, resultClass, resultRole); if (DEBUG) { System.err.println ("JMPIAssociationProvider::_associatorNames: resultPaths.size () = " + resultPaths.size ()); } vectorReturn.addAll (resultPaths); } return vectorReturn; } private Vector _filterAssociationInstancesByRole (Vector associationInstances, CIMObjectPath targetObjectPath, String role) { Vector returnInstances = new Vector (); if (DEBUG) { System.err.println ("JMPIAssociationProvider::_filterAssociationInstancesByRole: associationInstances.size () = " + associationInstances.size ()); System.err.println ("JMPIAssociationProvider::_filterAssociationInstancesByRole: targetObjectPath = " + targetObjectPath); System.err.println ("JMPIAssociationProvider::_filterAssociationInstancesByRole: role = " + role); } try { // Filter the instances from the list of association instances against // the specified role filter // for (int i = 0, si = associationInstances.size (); i < si; i++) { CIMInstance instance = (CIMInstance)associationInstances.elementAt (i); // Search the association instance for all reference properties for (int j = 0, sj = instance.getPropertyCount (); j < sj; j++) { CIMProperty p = instance.getProperty (j); if (p.getType ().getType () == CIMDataType.REFERENCE) { CIMObjectPath copRef = (CIMObjectPath)p.getValue ().getValue (); if (DEBUG) { System.err.println ("JMPIAssociationProvider::_filterAssociationInstancesByRole: p = " + p); System.err.println ("JMPIAssociationProvider::_filterAssociationInstancesByRole: copRef = " + copRef); } if ( (role.equalsIgnoreCase ("")) || (p.getName ().equalsIgnoreCase (role)) ) { if (DEBUG) { System.err.println ("JMPIAssociationProvider::_filterAssociationInstancesByRole: targetObjectPath = " + targetObjectPath); } if (targetObjectPath.toString ().equalsIgnoreCase (copRef.toString ())) { if (DEBUG) { System.err.println ("JMPIAssociationProvider::_filterAssociationInstancesByRole: adding!"); } returnInstances.addElement (instance); } } } } } } catch (CIMException e) { } return returnInstances; } private Vector _filterAssociationInstances (CIMInstance assocInstance, CIMObjectPath sourceObjectPath, String resultClass, String resultRole) { Vector returnPaths = new Vector (); try { if (DEBUG) { System.err.println ("JMPIAssociationProvider::_filterAssociationInstances: assocInstance.getPropertyCount () = " + assocInstance.getPropertyCount ()); System.err.println ("JMPIAssociationProvider::_filterAssociationInstances: sourceObjectPath = " + sourceObjectPath); System.err.println ("JMPIAssociationProvider::_filterAssociationInstances: resultClass = " + resultClass); System.err.println ("JMPIAssociationProvider::_filterAssociationInstances: resultRole = " + resultRole); } // get all Reference properties for (int i = 0, si = assocInstance.getPropertyCount (); i < si; i++) { CIMProperty p = assocInstance.getProperty (i); if (p.getType ().getType () == CIMDataType.REFERENCE) { CIMObjectPath copRef = (CIMObjectPath)p.getValue ().getValue (); if (DEBUG) { System.err.println ("JMPIAssociationProvider::_filterAssociationInstances: p = " + p); System.err.println ("JMPIAssociationProvider::_filterAssociationInstances: copRef = " + copRef); } if (!equals (sourceObjectPath, copRef)) { if ( resultClass.equalsIgnoreCase ("") || resultClass == copRef.getObjectName () ) { if ( (resultRole.equalsIgnoreCase ("")) || (p.getName ().equalsIgnoreCase (resultRole)) ) { if (DEBUG) { System.err.println ("JMPIAssociationProvider::_filterAssociationInstances: adding!"); } returnPaths.addElement (copRef); } } } } } } catch (CIMException e) { } return returnPaths; } private boolean equals (CIMObjectPath l, CIMObjectPath r) { String ls = l.toString (); String rs = r.toString (); return ls.equalsIgnoreCase (rs); } private Vector teacherInstances = new Vector (); private Vector studentInstances = new Vector (); private Vector TSassociationInstances = new Vector (); private Vector ASassociationInstances = new Vector (); private String NAMESPACE = new String ("root/SampleProvider"); // Class names private String SAMPLE_TEACHER = new String ("JMPIAssociation_Teacher"); private String SAMPLE_STUDENT = new String ("JMPIAssociation_Student"); private String SAMPLE_TEACHERSTUDENT = new String ("JMPIAssociation_TeacherStudent"); private String SAMPLE_ADVISORSTUDENT = new String ("JMPIAssociation_AdvisorStudent"); }
40.037402
162
0.556124
e37a98fc32609d014ed968dee4abd9110c62cc76
9,288
package de.rosariop.trovoapi.chat; import java.io.Closeable; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.concurrent.TimeUnit; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; import org.jetbrains.annotations.Nullable; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import co.casterlabs.apiutil.auth.ApiAuthException; import co.casterlabs.apiutil.web.ApiException; import de.rosariop.trovoapi.TrovoApiJava; import de.rosariop.trovoapi.TrovoScope; import de.rosariop.trovoapi.TrovoUserAuth; import de.rosariop.trovoapi.chat.messages.TrovoChatMessage; import de.rosariop.trovoapi.chat.messages.TrovoCustomSpellMessage; import de.rosariop.trovoapi.chat.messages.TrovoFollowMessage; import de.rosariop.trovoapi.chat.messages.TrovoGiftSubMessage; import de.rosariop.trovoapi.chat.messages.TrovoGiftSubRandomlyMessage; import de.rosariop.trovoapi.chat.messages.TrovoMagicChatMessage; import de.rosariop.trovoapi.chat.messages.TrovoMessage; import de.rosariop.trovoapi.chat.messages.TrovoPlatformEventMessage; import de.rosariop.trovoapi.chat.messages.TrovoRaidWelcomeMessage; import de.rosariop.trovoapi.chat.messages.TrovoSpellMessage; import de.rosariop.trovoapi.chat.messages.TrovoSubscriptionMessage; import de.rosariop.trovoapi.chat.messages.TrovoWelcomeMessage; import de.rosariop.trovoapi.util.HttpUtil; import lombok.NonNull; import lombok.Setter; import xyz.e3ndr.fastloggingframework.logging.FastLogger; import xyz.e3ndr.fastloggingframework.logging.LogLevel; public class TrovoChat implements Closeable { private static final String CHAT_TOKEN_URL = "https://open-api.trovo.live/openplatform/chat/token"; private static final long KEEPALIVE = TimeUnit.SECONDS.toMillis(20); private static URI CHAT_URI; private @Setter @Nullable ChatListener listener; private Connection conn; private JsonObject auth; static { try { CHAT_URI = new URI("wss://open-chat.trovo.live/chat"); } catch (URISyntaxException e) { e.printStackTrace(); } } public TrovoChat(@NonNull TrovoUserAuth auth) throws ApiException, ApiAuthException, IOException { auth.checkScope(TrovoScope.CHAT_CONNECT); this.auth = HttpUtil.sendHttpGet(CHAT_TOKEN_URL, auth); } public void connect() { if (this.conn == null) { this.conn = new Connection(); this.conn.connect(); } else { throw new IllegalStateException("You must close the connection before reconnecting."); } } public void connectBlocking() throws InterruptedException { if (this.conn == null) { this.conn = new Connection(); this.conn.connectBlocking(); } else { throw new IllegalStateException("You must close the connection before reconnecting."); } } public boolean isOpen() { return this.conn != null; } @Override public void close() { this.conn.close(); } private class Connection extends WebSocketClient { private long nonce = 0; public Connection() { super(CHAT_URI); } @Override public void onOpen(ServerHandshake handshakedata) { this.sendMessage("AUTH", auth); Thread t = new Thread(() -> { while (this.isOpen()) { try { this.sendMessage("PING", null); Thread.sleep(KEEPALIVE); } catch (Exception ignored) {} } }); t.setName("TrovoChat KeepAlive"); t.start(); if (listener != null) { listener.onOpen(); } } public void sendMessage(String type, @Nullable JsonObject data) { JsonObject payload = new JsonObject(); this.nonce++; payload.addProperty("type", type); payload.addProperty("nonce", String.valueOf(this.nonce)); if (data != null) { payload.add("data", data); } this.send(payload.toString()); } @Override public void onMessage(String raw) { JsonObject message = TrovoApiJava.GSON.fromJson(raw, JsonObject.class); FastLogger.logStatic(LogLevel.TRACE, raw); String type = message.get("type").getAsString(); if (type.equals("CHAT")) { if (listener != null) { JsonObject data = message.getAsJsonObject("data"); JsonArray chats = data.getAsJsonArray("chats"); if (chats != null) { boolean isCatchup = chats.size() > 1; for (JsonElement e : chats) { TrovoMessage chat = this.parseChat(e.getAsJsonObject(), isCatchup); if (chat != null) { this.fireListener(chat); } } } } } } private void fireListener(TrovoMessage chat) { switch (chat.getType()) { case CHAT: listener.onChatMessage((TrovoChatMessage) chat); break; case FOLLOW: listener.onFollow((TrovoFollowMessage) chat); break; case GIFT_SUB_RANDOM: listener.onGiftSubRandomly((TrovoGiftSubRandomlyMessage) chat); break; case GIFT_SUB_USER: listener.onGiftSub((TrovoGiftSubMessage) chat); break; case MAGIC_CHAT_BULLET_SCREEN: case MAGIC_CHAT_COLORFUL: case MAGIC_CHAT_SPELL: case MAGIC_CHAT_SUPER_CAP: listener.onMagicChat((TrovoMagicChatMessage) chat); break; case SPELL: listener.onSpell((TrovoSpellMessage) chat); break; case PLATFORM_EVENT: listener.onPlatformEvent((TrovoPlatformEventMessage) chat); break; case RAID_WELCOME: listener.onRaidWelcome((TrovoRaidWelcomeMessage) chat); break; case SUBSCRIPTION: listener.onSubscription((TrovoSubscriptionMessage) chat); break; case WELCOME: listener.onWelcome((TrovoWelcomeMessage) chat); break; case CUSTOM_SPELL: listener.onCustomSpell((TrovoCustomSpellMessage) chat); break; case UNKNOWN: break; } } public TrovoMessage parseChat(JsonObject chat, boolean isCatchup) { TrovoRawChatMessage raw = TrovoApiJava.GSON.fromJson(chat, TrovoRawChatMessage.class); TrovoMessageType type = TrovoMessageType.lookup(raw.type); raw.is_catchup = isCatchup; if ((raw.avatar != null) && !raw.avatar.contains("://")) { raw.avatar = "https://headicon.trovo.live/user/" + raw.avatar; // Damn you Trovo. } switch (type) { case CHAT: return new TrovoChatMessage(raw); case FOLLOW: return new TrovoFollowMessage(raw); case GIFT_SUB_RANDOM: return new TrovoGiftSubRandomlyMessage(raw); case GIFT_SUB_USER: return new TrovoGiftSubMessage(raw); case MAGIC_CHAT_BULLET_SCREEN: case MAGIC_CHAT_COLORFUL: case MAGIC_CHAT_SPELL: case MAGIC_CHAT_SUPER_CAP: return new TrovoMagicChatMessage(raw, type); case PLATFORM_EVENT: return new TrovoPlatformEventMessage(raw); case RAID_WELCOME: return new TrovoRaidWelcomeMessage(raw); case SPELL: return new TrovoSpellMessage(raw, TrovoApiJava.GSON.fromJson(raw.content, JsonObject.class)); case SUBSCRIPTION: return new TrovoSubscriptionMessage(raw); case WELCOME: return new TrovoWelcomeMessage(raw); case CUSTOM_SPELL: return new TrovoCustomSpellMessage(raw, TrovoApiJava.GSON.fromJson(raw.content, JsonObject.class)); case UNKNOWN: default: return null; } } @Override public void onClose(int code, String reason, boolean remote) { conn = null; if (listener != null) { listener.onClose(remote); } } @Override public void onError(Exception e) { e.printStackTrace(); } } }
32.362369
119
0.573643
4f75315329dab08d690219a3f397c542272c87d0
5,783
package com.amirnadiv.project.utils.common; import static com.amirnadiv.project.utils.common.Assert.ExceptionType.ILLEGAL_ARGUMENT; import static com.amirnadiv.project.utils.common.Assert.ExceptionType.UNEXPECTED_FAILURE; import static com.amirnadiv.project.utils.common.Assert.ExceptionType.UNREACHABLE_CODE; import static com.amirnadiv.project.utils.common.Assert.ExceptionType.UNSUPPORTED_OPERATION; import com.amirnadiv.project.utils.common.exception.UnexpectedFailureException; import com.amirnadiv.project.utils.common.exception.UnreachableCodeException; public abstract class Assert { public static <T> T assertNotNull(T object) { return assertNotNull(object, null, null, (Object[]) null); } public static <T> T assertNotNull(T object, String message, Object...args) { return assertNotNull(object, null, message, args); } public static <T> T assertNotNull(T object, ExceptionType exceptionType, String message, Object...args) { if (object == null) { if (exceptionType == null) { exceptionType = ILLEGAL_ARGUMENT; } throw exceptionType.newInstance(getMessage(message, args, "[Assertion failed] - the argument is required; it must not be null")); } return object; } public static <T> T assertNull(T object) { return assertNull(object, null, null, (Object[]) null); } public static <T> T assertNull(T object, String message, Object...args) { return assertNull(object, null, message, args); } public static <T> T assertNull(T object, ExceptionType exceptionType, String message, Object...args) { if (object != null) { if (exceptionType == null) { exceptionType = ILLEGAL_ARGUMENT; } throw exceptionType.newInstance(getMessage(message, args, "[Assertion failed] - the object argument must be null")); } return object; } public static void assertTrue(boolean expression) { assertTrue(expression, null, null, (Object[]) null); } public static void assertTrue(boolean expression, String message, Object...args) { assertTrue(expression, null, message, args); } public static void assertTrue(boolean expression, ExceptionType exceptionType, String message, Object...args) { if (!expression) { if (exceptionType == null) { exceptionType = ILLEGAL_ARGUMENT; } throw exceptionType.newInstance(getMessage(message, args, "[Assertion failed] - the expression must be true")); } } public static <T> T unreachableCode() { unreachableCode(null, (Object[]) null); return null; } public static <T> T unreachableCode(String message, Object...args) { throw UNREACHABLE_CODE.newInstance(getMessage(message, args, "[Assertion failed] - the code is expected as unreachable")); } public static <T> T unexpectedException(Throwable e) { unexpectedException(e, null, (Object[]) null); return null; } public static <T> T unexpectedException(Throwable e, String message, Object...args) { RuntimeException exception = UNEXPECTED_FAILURE.newInstance(getMessage(message, args, "[Assertion failed] - unexpected exception is thrown")); exception.initCause(e); throw exception; } public static <T> T fail() { fail(null, (Object[]) null); return null; } public static <T> T fail(String message, Object...args) { throw UNEXPECTED_FAILURE.newInstance(getMessage(message, args, "[Assertion failed] - unexpected failure")); } public static <T> T unsupportedOperation() { unsupportedOperation(null, (Object[]) null); return null; } public static <T> T unsupportedOperation(String message, Object...args) { throw UNSUPPORTED_OPERATION.newInstance(getMessage(message, args, "[Assertion failed] - unsupported operation or unimplemented function")); } private static String getMessage(String message, Object[] args, String defaultMessage) { if (message == null) { message = defaultMessage; } if (args == null || args.length == 0) { return message; } return String.format(message, args); } public static enum ExceptionType { ILLEGAL_ARGUMENT { @Override RuntimeException newInstance(String message) { return new IllegalArgumentException(message); } }, ILLEGAL_STATE { @Override RuntimeException newInstance(String message) { return new IllegalStateException(message); } }, NULL_POINT { @Override RuntimeException newInstance(String message) { return new NullPointerException(message); } }, UNREACHABLE_CODE { @Override RuntimeException newInstance(String message) { return new UnreachableCodeException(message); } }, UNEXPECTED_FAILURE { @Override RuntimeException newInstance(String message) { return new UnexpectedFailureException(message); } }, UNSUPPORTED_OPERATION { @Override RuntimeException newInstance(String message) { return new UnsupportedOperationException(message); } }; abstract RuntimeException newInstance(String message); } }
32.857955
115
0.620612
73b1d23462de3b9680470a286a13a47f34882b17
10,376
package com.muyoumumumu.QuShuChe.ui.acitivity; import android.app.AlertDialog; import android.app.Service; import android.content.ContentValues; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.os.Vibrator; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.muyoumumumu.QuShuChe.R; import com.muyoumumumu.QuShuChe.model.bean.Mnn; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class Car_count extends AppCompatActivity { //判定单双时间 private static int DOUBLE_CLICK_TIME = 350; private List<Long> times = new ArrayList<>(); private Handler mHandler = new Handler(); private Runnable r; private List<Long> times1 = new ArrayList<>(); private Handler mHandler1 = new Handler(); private Runnable r1; private List<Long> times2 = new ArrayList<>(); private Handler mHandler2 = new Handler(); private Runnable r2; private List<Long> times3 = new ArrayList<>(); private Handler mHandler3 = new Handler(); private Runnable r3; private ContentValues values; private String name; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); name = Mnn.getInstance().getName_mark()[0]; setContentView(R.layout.car_count); Button btnt1 = (Button) findViewById(R.id.btn_diaotou); Button btnt2 = (Button) findViewById(R.id.btn_zuozhuan); Button btnt3 = (Button) findViewById(R.id.btn_zhixing); Button btnt4 = (Button) findViewById(R.id.btn_youzhuan); assert btnt1 != null; btnt1.setOnClickListener(btnt1Listener); assert btnt2 != null; btnt2.setOnClickListener(btnt2Listener); assert btnt3 != null; btnt3.setOnClickListener(btnt3Listener); assert btnt4 != null; btnt4.setOnClickListener(btnt4Listener); } /** btn1的注释*/ /** * 双击事件判断 */ private boolean diaotou() { if (times.size() == 2) { if (times.get(times.size() - 1) - times.get(0) < DOUBLE_CLICK_TIME) { times.clear(); insert_dache_diaotou(); if (mHandler != null) { if (r != null) { //移除回调 mHandler.removeCallbacks(r); r = null; } } return true; } else { //这种情况下,第一次点击的时间已经没有用处了,第二次就是“第一次” times.remove(0); } } //此处可以添加提示 //showTips(); r = new Runnable() { @Override public void run() { insert_xiaoche_diaotou(); } }; //DOUBLE_CLICK_TIME时间后提示单击事件 mHandler.postDelayed(r, DOUBLE_CLICK_TIME); return false; } private OnClickListener btnt1Listener = new OnClickListener() { @Override public void onClick(View v) { times.add(SystemClock.uptimeMillis()); diaotou(); try { Vibrator vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE); vibrator.vibrate(new long[]{0, 1000}, -1); } catch (Exception ignored) { } } }; /**** * 单双击按钮事件响应调用方法 * 由于太长的time13位很影响sqlite操作,而也不能在表中插入text型的time吧,根本不利于查找,于是 * 只插入9位数的time,有瑕疵不管不影响应用 ***/ // 单击响应事件 private void insert_xiaoche_diaotou() { //为values分配内存 values = new ContentValues(); values.put("direction", "掉头"); values.put("type", "小车"); values.put("time", (int) ((new Date().getTime()) % 1000000000));//插入9位的时间数 values.put("systime", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())); Main_activity.mDb.insert(name, null, values); //关闭value回收内存 values.clear(); } // 双击响应事件 private void insert_dache_diaotou() { //为values分配内存 values = new ContentValues(); values.put("direction", "掉头"); values.put("type", "大车"); values.put("time", (int) ((new Date().getTime()) % 1000000000)); values.put("systime", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())); Main_activity.mDb.insert(name, null, values); //关闭value回收内存 values.clear(); } /** btn2的注释*/ /** * 双击事件判断 */ private boolean zuozhuan() { if (times1.size() == 2) { if (times1.get(times1.size() - 1) - times1.get(0) < DOUBLE_CLICK_TIME) { times1.clear(); insert_dache_zuozhuan(); if (mHandler1 != null) { if (r1 != null) { //移除回调 mHandler1.removeCallbacks(r1); r1 = null; } } return true; } else { //这种情况下,第一次点击的时间已经没有用处了,第二次就是“第一次” times1.remove(0); } } //此处可以添加提示 //showTips(); r1 = new Runnable() { @Override public void run() { insert_xiaoche_zuozhuan(); } }; //DOUBLE_CLICK_TIME时间后提示单击事件 mHandler1.postDelayed(r1, DOUBLE_CLICK_TIME); return false; } private OnClickListener btnt2Listener = new OnClickListener() { @Override public void onClick(View v) { times1.add(SystemClock.uptimeMillis()); zuozhuan(); try { Vibrator vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE); vibrator.vibrate(new long[]{0, 1000}, -1); } catch (Exception ignored) { } // } // @Override // public void onClick(View v) { // nb++; // ettext.setText(nb+""); // } }; // 单击响应事件 private void insert_xiaoche_zuozhuan() { // Log.i(TAG, "singleClick"); //为values分配内存 values = new ContentValues(); values.put("direction", "左转"); values.put("type", "小车"); values.put("time", (int) ((new Date().getTime()) % 1000000000)); values.put("systime", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())); Main_activity.mDb.insert(name, null, values); //关闭value回收内存 values.clear(); } // 双击响应事件 private void insert_dache_zuozhuan() { // Log.i(TAG, "doubleClick"); //为values分配内存 values = new ContentValues(); values.put("direction", "左转"); values.put("type", "大车"); values.put("time", (int) ((new Date().getTime()) % 1000000000)); values.put("systime", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())); Main_activity.mDb.insert(name, null, values); //关闭value回收内存 values.clear(); } /** btn3的注释*/ /** * 双击事件判断 */ private boolean zhixing() { if (times2.size() == 2) { if (times2.get(times2.size() - 1) - times2.get(0) < DOUBLE_CLICK_TIME) { times2.clear(); insert_dache_zhixing(); if (mHandler2 != null) { if (r2 != null) { //移除回调 mHandler2.removeCallbacks(r2); r2 = null; } } return true; } else { //这种情况下,第一次点击的时间已经没有用处了,第二次就是“第一次” times2.remove(0); } } //此处可以添加提示 //showTips(); r2 = new Runnable() { @Override public void run() { insert_xiaoche_zhixin(); } }; //DOUBLE_CLICK_TIME时间后提示单击事件 mHandler2.postDelayed(r2, DOUBLE_CLICK_TIME); return false; } private OnClickListener btnt3Listener = new OnClickListener() { @Override public void onClick(View v) { times2.add(SystemClock.uptimeMillis()); zhixing(); try { Vibrator vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE); vibrator.vibrate(new long[]{0, 1000}, -1); } catch (Exception ignored) { } } // @Override // public void onClick(View v) { // nb++; // ettext.setText(nb+""); // } }; // 单击响应事件 private void insert_xiaoche_zhixin() { // Log.i(TAG, "singleClick"); values = new ContentValues(); values.put("direction", "直行"); values.put("type", "小车"); values.put("time", (int) ((new Date().getTime()) % 1000000000)); values.put("systime", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())); Main_activity.mDb.insert(name, null, values); //关闭value回收内存 values.clear(); } // 双击响应事件 private void insert_dache_zhixing() { // Log.i(TAG, "doubleClick"); values = new ContentValues(); values.put("direction", "直行"); values.put("type", "大车"); values.put("time", (int) ((new Date().getTime()) % 1000000000)); values.put("systime", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())); Main_activity.mDb.insert(name, null, values); //关闭value回收内存 values.clear(); } /** btn4的注释*/ /** * 双击事件判断 */ private boolean youzhuan() { if (times3.size() == 2) { if (times3.get(times3.size() - 1) - times3.get(0) < DOUBLE_CLICK_TIME) { times3.clear(); insert_dache_youzhuan(); if (mHandler3 != null) { if (r3 != null) { //移除回调 mHandler3.removeCallbacks(r3); r3 = null; } } return true; } else { //这种情况下,第一次点击的时间已经没有用处了,第二次就是“第一次” times3.remove(0); } } //此处可以添加提示 //showTips(); r3 = new Runnable() { @Override public void run() { insert_xiaoche_youzhuan(); } }; //DOUBLE_CLICK_TIME时间后提示单击事件 mHandler3.postDelayed(r3, DOUBLE_CLICK_TIME); return false; } private OnClickListener btnt4Listener = new OnClickListener() { @Override public void onClick(View v) { times3.add(SystemClock.uptimeMillis()); youzhuan(); try { Vibrator vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE); vibrator.vibrate(new long[]{0, 1000}, -1); } catch (Exception ignored) { } } // @Override // public void onClick(View v) { // nb++; // ettext.setText(nb+""); // } }; // 单击响应事件 private void insert_xiaoche_youzhuan() { values = new ContentValues(); values.put("direction", "右转"); values.put("type", "小车"); values.put("time", (int) ((new Date().getTime()) % 1000000000)); values.put("systime", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())); Main_activity.mDb.insert(name, null, values); //关闭value回收内存 values.clear(); } // 双击响应事件 private void insert_dache_youzhuan() { values = new ContentValues(); values.put("direction", "右转"); values.put("type", "大车"); values.put("time", (int) ((new Date().getTime()) % 1000000000)); values.put("systime", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())); Main_activity.mDb.insert(name, null, values); //关闭value回收内存 values.clear(); } @Override public void onBackPressed() { new AlertDialog.Builder(this).setTitle("确认退出采集界面吗?") .setIcon(R.drawable.iiii) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 点击“确认”后的操作 Car_count.this.finish(); } }) .setNegativeButton("返回", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 点击“返回”后的操作,这里不设置没有任何操作 } }).show(); } }
23.212528
88
0.65054
2d21074b349e1159ad95990e12e19ee3aa7d0686
542
package com.jd.blockchain.ledger.core; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.BlockchainIdentity; import utils.Bytes; /** * 账户访问策略; * * @author huanghaiquan * */ public interface AccountAccessPolicy { /** * Check access policy before committing the specified account; <br> * * @param account * @return Return true if it satisfies this policy, or false if it doesn't; */ boolean checkDataWriting(BlockchainIdentity account); boolean checkRegistering(Bytes address, PubKey pubKey); }
19.357143
76
0.739852
2f3f9075a0b0d6e62305b8ddb5e18b4a9287e658
2,292
/* * Copyright (C) 2016 Kyle Fricilone * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.oldscape.tool.cache.sprite; import com.oldscape.tool.cache.Cache; import com.oldscape.tool.cache.Container; import com.oldscape.tool.cache.Identifiers; import com.oldscape.tool.cache.ReferenceTable; import com.oldscape.tool.cache.ReferenceTable.Entry; import com.oldscape.tool.cache.type.CacheIndex; import com.oldscape.tool.util.crypto.Djb2; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by Kyle Fricilone on Sep 15, 2016. */ public class Sprites { private static Logger logger = Logger.getLogger(Sprites.class.getName()); private static Sprite[] sprites; private static Identifiers identifiers; public static void initialize(Cache cache) { int count = 0; try { ReferenceTable table = cache.getReferenceTable(8); sprites = new Sprite[table.capacity()]; for (int i = 0; i < table.capacity(); i++) { Entry e = table.getEntry(i); if (e == null) continue; Container c = cache.read(CacheIndex.SPRITES, i); Sprite sprite = Sprite.decode(c.getData()); sprites[i] = sprite; count++; } identifiers = table.getIdentifiers(); } catch (Exception e) { logger.log(Level.SEVERE, "Error Loading Sprite(s)!", e); } logger.info("Loaded " + count + " Sprite(s)!"); } public static final Sprite getSprite(int id) { return sprites[id]; } public static final Sprite getSprite(String name) { int id = identifiers.getFile(Djb2.hash(name)); if (id == -1) { return null; } return sprites[id]; } }
27.614458
75
0.684991
7075b694f0298efed3ed01050659f72bb54a32ae
102
package com.adaptris.labs.verify.report.sonar; public enum Type { BUG, VULNERABILITY, CODE_SMELL }
17
46
0.77451
d2b7d086a6729129e29b0e257c7d077d9ca8e92d
3,491
/* Copyright (c) 2000-2017 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.util; import java.util.Arrays; import java.util.TimeZone; import org.lockss.test.LockssTestCase; /** * @deprecated {@link org.lockss.util.TimeZoneUtil} is deprecated (but is used * in plugins); use {@link org.lockss.util.time.TimeZoneUtil} in * lockss-util instead. */ @Deprecated public class TestTimeZoneUtil extends LockssTestCase { /** * @deprecated {@link org.lockss.util.TimeZoneUtil} is deprecated (but is used * in plugins); use {@link org.lockss.util.time.TimeZoneUtil} in * lockss-util instead. */ @Deprecated public void testIsBasicTimeZoneDataAvailable() { assertTrue(TimeZoneUtil.isBasicTimeZoneDataAvailable()); } /** * @deprecated {@link org.lockss.util.TimeZoneUtil} is deprecated (but is used * in plugins); use {@link org.lockss.util.time.TimeZoneUtil} in * lockss-util instead. */ @Deprecated public void testGoodTimeZones() throws Exception { for (String id : TimeZoneUtil.BASIC_TIME_ZONES) { TimeZone tz = TimeZoneUtil.getExactTimeZone(id); assertEquals(id, tz.getID()); assertEquals("GMT".equals(id), "GMT".equals(tz.getID())); } } /** * @deprecated {@link org.lockss.util.TimeZoneUtil} is deprecated (but is used * in plugins); use {@link org.lockss.util.time.TimeZoneUtil} in * lockss-util instead. */ @Deprecated public void testBadTimeZones() throws Exception { for (String id : Arrays.asList(null, "Foo", "America/Copenhagen", "Europe/Tokyo")) { try { TimeZone tz = TimeZoneUtil.getExactTimeZone(id); fail("Should have thrown IllegalArgumentException: " + id); } catch (IllegalArgumentException iae) { if (id == null) { assertEquals("Time zone identifier cannot be null", iae.getMessage()); } else { assertEquals("Unknown time zone identifier: " + id, iae.getMessage()); } } } } }
36.747368
80
0.68204
9b1aebc32e4738ce80e17933f8828d0f1725cc93
4,822
/* * Copyright (c) 2018 victords * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package me.victorsantiago.footballprobabilitymodel.calculator.impl; import me.victorsantiago.footballprobabilitymodel.model.Match; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; /** * Return values provided by Wolfram Alpha for individual calculations, * or manually calculated here to test correct filters. */ public class PoissonCalculatorTest { private static final double DELTA = 0.001; private PoissonCalculator toTest; private List<Match> sampleMatches; @Before public void setup() { toTest = new PoissonCalculator(); sampleMatches = getSampleMatches(); } @Test public void shouldReturnCorrectPoissonProbability() { final double expectedNumberOfGoals = 1.123; Assert.assertEquals(0.205, toTest.getPoissonProbability(2, expectedNumberOfGoals), DELTA); Assert.assertEquals(0.365, toTest.getPoissonProbability(1, expectedNumberOfGoals), DELTA); Assert.assertEquals(0.325, toTest.getPoissonProbability(0, expectedNumberOfGoals), DELTA); } @Test public void shouldReturnCorrectExpectedGoals() { double aAttackStrength = 1 / ((1+1+1+1+3) / 6.0); double bDefensiveStrength = 2 / ((1+1+1+1+3) / 6.0); double aAverageGoalsAtHome = 1; Assert.assertEquals(aAttackStrength * bDefensiveStrength * aAverageGoalsAtHome, toTest.getExpectedHomeTeamGoals("A", "B", sampleMatches), DELTA); } @Test public void shouldGetTeamsDefensiveStrength() { double allAverageGoalsConcealed = (2+1+2) / 6.0; double aTeamAverageGoalsConcealed = 1; Assert.assertEquals((aTeamAverageGoalsConcealed / allAverageGoalsConcealed), toTest.getHomeTeamsDefensiveStrength("A", sampleMatches), DELTA); } @Test public void shouldGetTeamsAttackStrength() { double allAverageGoals = (1+1+1+1+3) / 6.0; double aTeamAverageGoals = 1; Assert.assertEquals((aTeamAverageGoals / allAverageGoals), toTest.getHomeTeamsAttackStrength("A", sampleMatches), DELTA); } @Test public void shouldReturnCorrectGoalsAverage() { double correctHomeAverage = (1+1+1+1+3) / 6.0; double correctAwayAverage = (2+1+2) / 6.0; Assert.assertEquals(correctHomeAverage, toTest.getAverageGoalsScoredAtHome(sampleMatches), DELTA); Assert.assertEquals(correctHomeAverage, toTest.getAverageGoalsConcealedAway(sampleMatches), DELTA); Assert.assertEquals(correctAwayAverage, toTest.getAverageGoalsScoredAway(sampleMatches), DELTA); Assert.assertEquals(correctAwayAverage, toTest.getAverageGoalsConcealedAtHome(sampleMatches), DELTA); } private List<Match> getSampleMatches() { sampleMatches = new ArrayList<>(); sampleMatches.add(Match.builder().home("A").homeGoals(1) .away("B").awayGoals(2).build()); sampleMatches.add(Match.builder().home("A").homeGoals(1) .away("C").awayGoals(0).build()); sampleMatches.add(Match.builder().home("B").homeGoals(1) .away("A").awayGoals(1).build()); sampleMatches.add(Match.builder().home("B").homeGoals(1) .away("C").awayGoals(2).build()); sampleMatches.add(Match.builder().home("C").homeGoals(3) .away("B").awayGoals(0).build()); sampleMatches.add(Match.builder().home("C").homeGoals(0) .away("A").awayGoals(0).build()); return sampleMatches; } }
38.576
109
0.678971
1a0573cebf00b828f470dc3734b1c363cb7065fc
181
package Graphs4Beginners; public class Edge { Vertex to; int weight; Edge(Vertex toVertex, int weight) { to = toVertex; this.weight = weight; } }
13.923077
39
0.596685
2e6cfd0067ab4815ff767fbb4ec84eda8c027477
2,170
package system.gui.menus.examplemenu; import system.gui.DynamicSelectionZone; import system.gui.HALMenu; import system.gui.Payload; import system.gui.event.DataPacket; import system.gui.menus.TextSelectionMenu; import system.gui.viewelement.TextElement; import system.gui.viewelement.eventlistener.EntireViewButton; import system.gui.viewelement.eventlistener.ViewButton; import util.control.Button; @DynamicSelectionZone(pattern = {true}) public class ExampleMenu extends HALMenu { @Override protected void init(Payload payload) { if (payload.idPresent(TextSelectionMenu.ENTERED_TEXT_ID)) { System.out.println("Entered text: " + payload.get(TextSelectionMenu.ENTERED_TEXT_ID)); } //selectionZone = new SelectionZone(1,2); addItem(new ViewButton("# | Fun Times") .onClick(new Button<>(1, Button.BooleanInputs.x), (DataPacket packet) -> { gui.inflate(new ExampleMenu2()); }) ); addItem(new TextElement("# | LOOK! its new text!")); addItem(new ViewButton("# | More fun stuff") .onClick(new Button<>(1, Button.BooleanInputs.a), (DataPacket packet) -> { gui.inflate(new ExampleMenu2()); })); addItem(new EntireViewButton() .onClick(new Button<>(1, Button.BooleanInputs.b), (DataPacket packet) -> { gui.inflate(new ExampleMenu3()); })); addItem(new TextElement("# | LOOK! its new text!")); addItem(new TextElement("# | LOOK! its new text!")); addItem(new TextElement("# | LOOK! its new text!")); addItem(new EntireViewButton() .onClick(new Button<>(1, Button.BooleanInputs.y), (DataPacket packet) -> { gui.forward(); })); addItem(new TextElement("# | LOOK! its new text!")); addItem(new TextElement("# | LOOK! its new text!")); addItem(new TextElement("# | LOOK! its new text!")); addItem(new TextElement("# | LOOK! its new text!")); addItem(new TextElement("# | You found the end of the page!")); } }
43.4
98
0.613364
24b9504f587cb3d78eee8a19cc93402d35a93c63
8,456
package mkl.testarea.pdfbox2.extract; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.util.Arrays; import org.apache.fontbox.util.BoundingBox; import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.font.PDCIDFontType2; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDSimpleFont; import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont; import org.apache.pdfbox.pdmodel.font.PDType0Font; import org.apache.pdfbox.pdmodel.font.PDType3CharProc; import org.apache.pdfbox.pdmodel.font.PDType3Font; import org.apache.pdfbox.pdmodel.font.PDVectorFont; import org.apache.pdfbox.pdmodel.graphics.image.PDImage; import org.apache.pdfbox.util.Matrix; import org.apache.pdfbox.util.Vector; /** * <a href="https://stackoverflow.com/questions/52821421/how-do-determine-location-of-actual-pdf-content-with-pdfbox"> * How do determine location of actual PDF content with PDFBox? * </a> * <p> * This stream engine determines the bounding box of the static content * of a page. Beware, it is not very sophisticated; in particular it * does not ignore invisible content like a white background rectangle, * text drawn in rendering mode "invisible", arbitrary content covered * by a white filled path, white parts of bitmap images, ... Furthermore, * it ignores clip paths. * </p> * * @author mklink */ public class BoundingBoxFinder extends PDFGraphicsStreamEngine { public BoundingBoxFinder(PDPage page) { super(page); } public Rectangle2D getBoundingBox() { return rectangle; } // // Text // @Override protected void showGlyph(Matrix textRenderingMatrix, PDFont font, int code, Vector displacement) throws IOException { super.showGlyph(textRenderingMatrix, font, code, displacement); Shape shape = calculateGlyphBounds(textRenderingMatrix, font, code); if (shape != null) { Rectangle2D rect = shape.getBounds2D(); add(rect); } } /** * Copy of <code>org.apache.pdfbox.examples.util.DrawPrintTextLocations.calculateGlyphBounds(Matrix, PDFont, int)</code>. */ private Shape calculateGlyphBounds(Matrix textRenderingMatrix, PDFont font, int code) throws IOException { GeneralPath path = null; AffineTransform at = textRenderingMatrix.createAffineTransform(); at.concatenate(font.getFontMatrix().createAffineTransform()); if (font instanceof PDType3Font) { // It is difficult to calculate the real individual glyph bounds for type 3 fonts // because these are not vector fonts, the content stream could contain almost anything // that is found in page content streams. PDType3Font t3Font = (PDType3Font) font; PDType3CharProc charProc = t3Font.getCharProc(code); if (charProc != null) { BoundingBox fontBBox = t3Font.getBoundingBox(); PDRectangle glyphBBox = charProc.getGlyphBBox(); if (glyphBBox != null) { // PDFBOX-3850: glyph bbox could be larger than the font bbox glyphBBox.setLowerLeftX(Math.max(fontBBox.getLowerLeftX(), glyphBBox.getLowerLeftX())); glyphBBox.setLowerLeftY(Math.max(fontBBox.getLowerLeftY(), glyphBBox.getLowerLeftY())); glyphBBox.setUpperRightX(Math.min(fontBBox.getUpperRightX(), glyphBBox.getUpperRightX())); glyphBBox.setUpperRightY(Math.min(fontBBox.getUpperRightY(), glyphBBox.getUpperRightY())); path = glyphBBox.toGeneralPath(); } } } else if (font instanceof PDVectorFont) { PDVectorFont vectorFont = (PDVectorFont) font; path = vectorFont.getPath(code); if (font instanceof PDTrueTypeFont) { PDTrueTypeFont ttFont = (PDTrueTypeFont) font; int unitsPerEm = ttFont.getTrueTypeFont().getHeader().getUnitsPerEm(); at.scale(1000d / unitsPerEm, 1000d / unitsPerEm); } if (font instanceof PDType0Font) { PDType0Font t0font = (PDType0Font) font; if (t0font.getDescendantFont() instanceof PDCIDFontType2) { int unitsPerEm = ((PDCIDFontType2) t0font.getDescendantFont()).getTrueTypeFont().getHeader().getUnitsPerEm(); at.scale(1000d / unitsPerEm, 1000d / unitsPerEm); } } } else if (font instanceof PDSimpleFont) { PDSimpleFont simpleFont = (PDSimpleFont) font; // these two lines do not always work, e.g. for the TT fonts in file 032431.pdf // which is why PDVectorFont is tried first. String name = simpleFont.getEncoding().getName(code); path = simpleFont.getPath(name); } else { // shouldn't happen, please open issue in JIRA System.out.println("Unknown font class: " + font.getClass()); } if (path == null) { return null; } return at.createTransformedShape(path.getBounds2D()); } // // Bitmaps // @Override public void drawImage(PDImage pdImage) throws IOException { Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); for (int x = 0; x < 2; x++) { for (int y = 0; y < 2; y++) { add(ctm.transformPoint(x, y)); } } } // // Paths // @Override public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3) throws IOException { addToPath(p0, p1, p2, p3); } @Override public void clip(int windingRule) throws IOException { } @Override public void moveTo(float x, float y) throws IOException { addToPath(x, y); } @Override public void lineTo(float x, float y) throws IOException { addToPath(x, y); } @Override public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3) throws IOException { addToPath(x1, y1); addToPath(x2, y2); addToPath(x3, y3); } @Override public Point2D getCurrentPoint() throws IOException { return new Point2D.Float(); } @Override public void closePath() throws IOException { } @Override public void endPath() throws IOException { rectanglePath = null; } @Override public void strokePath() throws IOException { addPath(); } @Override public void fillPath(int windingRule) throws IOException { addPath(); } @Override public void fillAndStrokePath(int windingRule) throws IOException { addPath(); } @Override public void shadingFill(COSName shadingName) throws IOException { } void addToPath(Point2D... points) { Arrays.asList(points).forEach(p -> addToPath(p.getX(), p.getY())); } void addToPath(double newx, double newy) { if (rectanglePath == null) { rectanglePath = new Rectangle2D.Double(newx, newy, 0, 0); } else { rectanglePath.add(newx, newy); } } void addPath() { if (rectanglePath != null) { add(rectanglePath); rectanglePath = null; } } void add(Rectangle2D rect) { if (rectangle == null) { rectangle = new Rectangle2D.Double(); rectangle.setRect(rect); } else { rectangle.add(rect); } } void add(Point2D... points) { for (Point2D point : points) { add(point.getX(), point.getY()); } } void add(double newx, double newy) { if (rectangle == null) { rectangle = new Rectangle2D.Double(newx, newy, 0, 0); } else { rectangle.add(newx, newy); } } Rectangle2D rectanglePath = null; Rectangle2D rectangle = null; }
32.775194
129
0.621097
102c1c8cb69f25330550815a2e7543dceeef9883
2,927
package com.nainai.mapper; import com.nainai.domain.ShopModule; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import java.util.List; public interface ShopModuleMapper { int deleteByPrimaryKey(String id); int insert(ShopModule record); int insertSelective(ShopModule record); ShopModule selectByPrimaryKey(String id); int updateByPrimaryKeySelective(ShopModule record); int updateByPrimaryKey(ShopModule record); /** * 根据shopId查找店铺模块信息 * @param shopId * @return */ @Select("select * from shop_module where shop_id=#{shopId} and is_show=1 order by sort, create_time asc ") @Results({ @Result(column = "shop_id", property = "shopId"), @Result(column = "picture_path", property = "picturePath"), @Result(column = "is_show", property = "isShow"), @Result(column = "create_time", property = "createTime"), @Result(column = "update_time", property = "updateTime") }) List<ShopModule> selectShopModuleShopId(String shopId); /** * 根据shopId查找店铺模块信息-后台系统 * @param shopId * @return */ @Select("select * from shop_module where shop_id=#{shopId} order by sort, create_time asc ") @Results({ @Result(column = "shop_id", property = "shopId"), @Result(column = "picture_path", property = "picturePath"), @Result(column = "is_show", property = "isShow"), @Result(column = "create_time", property = "createTime"), @Result(column = "update_time", property = "updateTime") }) List<ShopModule> selectShopModuleShopIdBS(String shopId); /** * 查找所有店铺模块信息 * @return */ @Select("select * from shop_module order by create_time asc") @Results({ @Result(column = "shop_id", property = "shopId"), @Result(column = "picture_path", property = "picturePath"), @Result(column = "is_show", property = "isShow"), @Result(column = "create_time", property = "createTime"), @Result(column = "update_time", property = "updateTime") }) List<ShopModule> selectShopModuleAll(); /** * 根据店铺id与名称模糊查询店铺模块信息 * @param shopId * @param name * @return */ @Select("select * from shop_module where shop_id=#{shopId} and name like CONCAT('%',#{name},'%') order by sort, create_time asc ") @Results({ @Result(column = "shop_id", property = "shopId"), @Result(column = "picture_path", property = "picturePath"), @Result(column = "is_show", property = "isShow"), @Result(column = "create_time", property = "createTime"), @Result(column = "update_time", property = "updateTime") }) List<ShopModule> selectShopModuleShopIdAndName(String shopId ,String name); }
36.135802
135
0.626238
722350e44b262f09dca2e6955250df3f39df28e7
402
// https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ class Solution { public int maxProfit(int[] prices) { int min_price = Integer.MAX_VALUE, max_profit = 0; for(int i = 0; i < prices.length; i++){ min_price = Math.min(min_price, prices[i]); max_profit = Math.max(max_profit, prices[i] - min_price); } return max_profit; } }
33.5
69
0.599502
ddff1709eb739d205da49d9651edf76a5bc87f10
972
package com.shubham.prep.search; import java.util.Arrays; public class Leetcode875 { public int minEatingSpeed(int[] piles, int h) { int low = 1; int high = Arrays.stream(piles).max().getAsInt(); int ans = Integer.MAX_VALUE; while(low <= high) { int mid = low + (high - low)/2; if(possible(mid, h, piles)) { ans = Math.min(mid, ans); high = mid - 1; } else { low = mid + 1; } } return ans; } private boolean possible(int k, int h, int[] piles) { int count = 0; for(int i = 0; i < piles.length; i++) { count += Math.ceil((double)piles[i]/(double)k); } return count <= h; } public static void main(String[] args) { Leetcode875 leetcode875 = new Leetcode875(); System.out.println(leetcode875.minEatingSpeed(new int[]{30,11,23,4,20}, 6)); } }
27
84
0.509259
6b0523845417c5284b0616deb078096ef221bc5b
1,055
package org.jetbrains.plugin.devkt.clojure.psi.impl; import org.jetbrains.annotations.NotNull; import org.jetbrains.kotlin.com.intellij.lang.ASTNode; import org.jetbrains.kotlin.com.intellij.psi.PsiElement; import org.jetbrains.plugin.devkt.clojure.psi.ClojurePsiElement; import org.jetbrains.plugin.devkt.clojure.psi.ClojurePsiElementImpl; import org.jetbrains.plugin.devkt.clojure.psi.api.ClKeyword; /** * @author ilyas */ public class ClMapEntryImpl extends ClojurePsiElementImpl implements ClMapEntry { public ClMapEntryImpl(@NotNull ASTNode astNode) { super(astNode, "ClMapEntry"); } public ClKeyword getKeywordKey() { return findChildByClass(ClKeyword.class); } public ClojurePsiElement getKey() { final PsiElement child = getFirstChild(); if (child instanceof ClojurePsiElement) { return (ClojurePsiElement) child; } return null; } public ClojurePsiElement getValue() { final PsiElement child = getLastChild(); if (child instanceof ClojurePsiElement) { return (ClojurePsiElement) child; } return null; } }
27.051282
81
0.778199
917a08322cd03f2d6de0d2115dfa1688965f35d6
1,289
package org.backmeup.discmailing.test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import org.backmeup.discmailing.DiscmailingDatasink; import org.backmeup.plugin.api.connectors.Progressable; import org.backmeup.plugin.api.storage.Storage; import org.backmeup.plugin.api.storage.StorageException; import org.backmeup.plugin.api.storage.filesystem.LocalFilesystemStorage; public class DiscmailingDatasinkTest { public static void main(String args[]) throws FileNotFoundException, IOException, StorageException { System.out.println("DiscDatasinkTest"); Properties props = new Properties(); props.load(new FileInputStream(new File("/tmp/auth.props"))); Date date = new Date(); DateFormat df = new SimpleDateFormat("dd_MM_yy_hh_mm_ss"); props.setProperty ("org.backmeup.tmpdir", "BMU_plugin_" + df.format(date)); DiscmailingDatasink sink = new DiscmailingDatasink(); Storage sr = new LocalFilesystemStorage(); sr.open("/data/backmeup/users/1/"); sink.upload(props, sr, new Progressable(){ @Override public void progress(String message) {} }); } }
33.921053
101
0.77114
907d4c921ec99e0b7f8f1e65244d3214385457cc
5,625
package com.lin.server.bean; import java.io.Serializable; import java.util.Date; import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Index; @Entity /* * @author Naresh Pokhriyal * This entity is used in Admin(Accounts) to save advertisers/agencies of company's DFP */ @Index public class DFPTaskEntity implements Serializable{ public static final String STATUS_PENDING = "pending"; public static final String STATUS_IN_PROGRESS = "in-progress"; public static final String STATUS_COMPLETED = "completed"; public static final String STATUS_FAILED = "failed"; public static final String STATUS_PENDING_REPORT = "pendingReport"; public static final String STATUS_FINISHED_REPORT = "finishedReport"; public static final String STATUS_PENDING_DOWNLOAD = "pendingDownload"; public static final String STATUS_FINISHED_DOWNLOAD = "finishedDownload"; public static final String STATUS_PENDING_RAW = "pendingRaw"; public static final String STATUS_FINISHED_RAW = "finishedRaw"; public static final String STATUS_PENDING_PROC = "pendingProc"; public static final String STATUS_FINISHED_PROC = "finishedProc"; @Id private Long id; private String taskName; private String networkCode; private String startDate; private String endDate; private String taskGroupKey; private String status ; private String rawTableId; private String csRawFilePath; private String procTableId; private String dfpFileUrl; private String loadType; private String errorDesc; private String orderId; private Date startTime = new Date(); private Date lastModifiedTime = new Date(); private String taskType; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } public String getNetworkCode() { return networkCode; } public void setNetworkCode(String networkCode) { this.networkCode = networkCode; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public String getTaskGroupKey() { return taskGroupKey; } public void setTaskGroupKey(String taskGroupKey) { this.taskGroupKey = taskGroupKey; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getRawTableId() { return rawTableId; } public void setRawTableId(String rawTableId) { this.rawTableId = rawTableId; } public String getLoadType() { return loadType; } public void setLoadType(String loadType) { this.loadType = loadType; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getLastModifiedTime() { return lastModifiedTime; } public void setLastModifiedTime(Date lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } public static String getStatusPending() { return STATUS_PENDING; } public static String getStatusInProgress() { return STATUS_IN_PROGRESS; } public static String getStatusCompleted() { return STATUS_COMPLETED; } public static String getStatusFailed() { return STATUS_FAILED; } public String getErrorDesc() { return errorDesc; } public void setErrorDesc(String errorDesc) { this.errorDesc = errorDesc; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public String getCsRawFilePath() { return csRawFilePath; } public void setCsRawFilePath(String csRawFilePath) { this.csRawFilePath = csRawFilePath; } public String getProcTableId() { return procTableId; } public void setProcTableId(String procTableId) { this.procTableId = procTableId; } public String getDfpFileUrl() { return dfpFileUrl; } public void setDfpFileUrl(String dfpFileUrl) { this.dfpFileUrl = dfpFileUrl; } public String getTaskType() { return taskType; } public void setTaskType(String taskType) { this.taskType = taskType; } public DFPTaskEntity(String taskName, String networkCode, String startDate, String endDate, String taskGroupKey, String loadType) { super(); this.taskName = taskName; this.networkCode = networkCode; this.startDate = startDate; this.endDate = endDate; this.taskGroupKey = taskGroupKey; this.loadType = loadType; } public DFPTaskEntity(){} public DFPTaskEntity(String taskName, String networkCode, String startDate, String endDate, String taskGroupKey, String status, String loadType, Date startTime, Date lastModifiedTime, String orderId) { super(); this.taskName = taskName; this.networkCode = networkCode; this.startDate = startDate; this.endDate = endDate; this.taskGroupKey = taskGroupKey; this.status = status; this.loadType = loadType; this.startTime = startTime; this.lastModifiedTime = lastModifiedTime; this.orderId = orderId; } @Override public String toString() { return "DFPTaskEntity [id=" + id + ", taskName=" + taskName + ", networkCode=" + networkCode + ", startDate=" + startDate + ", endDate=" + endDate + ", taskGroupKey=" + taskGroupKey + ", status=" + status + ", rawTableId=" + rawTableId + ", loadType=" + loadType + ", startTime=" + startTime + ", lastModifiedTime=" + lastModifiedTime + ",taskType=" + taskType + "]"; } }
27.173913
132
0.744178
91f90275eeea58da48b66dbdb902ecd4ef0bc859
1,744
/*- * ============LICENSE_START======================================================= * Copyright (C) 2021 Nordix Foundation. * ================================================================================ * 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. * * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ package org.onap.policy.clamp.controlloop.models.controlloop.concepts; public enum ControlLoopOrderedState { /** * The control loop or control loop element should become uninitialised on participants, it should not exist on * participants. */ UNINITIALISED, /** * The control loop or control loop element should initialised on the participants and be passive, that is, it is * not handling control loop messages yet. */ PASSIVE, /** The control loop or control loop element should running and is executing control loops. */ RUNNING; public boolean equalsControlLoopState(final ControlLoopState controlLoopState) { return this.name().equals(controlLoopState.name()); } public ControlLoopState asState() { return ControlLoopState.valueOf(this.name()); } }
38.755556
117
0.629014