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
562637f912ccc159ecafc46ad4cbc4ec58cb88df
123
package io.khasang.gahelp.dao; import io.khasang.gahelp.entity.Role; public interface RoleDao extends BasicDao<Role> { }
17.571429
49
0.788618
c252c6b0778eba175ad57508b29ca7fe01bdc376
1,897
/* * Copyright (c) 2018. paascloud.net All Rights Reserved. * 项目名称:paascloud快速搭建企业级分布式微服务平台 * 类名称:PcAuthenticationFailureHandler.java * 创建人:刘兆明 * 联系方式:paascloud.net@gmail.com * 开源地址: https://github.com/paascloud * 博客地址: http://blog.paascloud.net * 项目官网: http://paascloud.net */ package com.paascloud.service.security; import com.fasterxml.jackson.databind.ObjectMapper; import com.paascloud.wrapper.WrapMapper; import org.springframework.http.HttpStatus; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; import org.springframework.stereotype.Component; import javax.annotation.Resource; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 认证失败处理器 * * @author paascloud.net @gmail.com */ @Component("pcAuthenticationFailureHandler") public class PcAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { @Resource private ObjectMapper objectMapper; /** * On authentication failure. * * @param request the request * @param response the response * @param exception the exception * * @throws IOException the io exception * @throws ServletException the servlet exception */ @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { logger.info("登录失败"); //FIXME 记录失败次数 和原因 ip等信息 5次登录失败,锁定用户, 不允许再次登录 response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); response.setContentType("application/json;charset=UTF-8"); response.getWriter().write(objectMapper.writeValueAsString(WrapMapper.error(exception.getMessage()))); } }
30.111111
110
0.777016
c880060c0329b650f2104461367dab482913b0f8
1,975
/* * Copyright 2011 by TalkingTrends (Amsterdam, The Netherlands) * * 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://opensahara.com/licenses/apache-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. */ /** * Taken from useekm: https://dev.opensahara.com/projects/useekm */ package gov.nasa.jpl.docweb.spring; import org.apache.commons.lang.Validate; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.springframework.transaction.TransactionSystemException; class SesameTransactionObject { private RepositoryConnection connection; private boolean existing; private boolean rollbackOnly;// = false; SesameTransactionObject(boolean isExisting) { this.existing = isExisting; } void setExisting(boolean e) { this.existing = e; } boolean isExisting() { return existing; } void setRollbackOnly(boolean rbo) { this.rollbackOnly = rbo; } boolean isRollbackOnly() { return rollbackOnly; } RepositoryConnection getConnection() { return connection; } void setConnection(RepositoryConnection connection) throws RepositoryException { Validate.notNull(connection); if (this.connection != null && this.connection != connection) throw new TransactionSystemException("Change of connection detected in @Transactional managed code"); if (this.connection == null) connection.setAutoCommit(false); this.connection = connection; } }
31.854839
113
0.715949
5701ebb927c6f9e5a0a12844bda9422f98060950
849
package com.projeto.model; import java.io.Serializable; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; import lombok.*; @Data @EqualsAndHashCode(onlyExplicitlyIncluded = true) @Entity @Table(name = "TAB_ROLE") public class Role implements Serializable{ private static final long serialVersionUID = 1L; public static long getSerialversionuid() { return serialVersionUID; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ROLE_ID") private Long role_id; @Column(name = "ROLE_NOME") private String role_nome; @ManyToMany(mappedBy = "roles") private List<Usuario> usuarios; }
21.225
52
0.779741
c70eb6299dc6d97fd167a20e859825fb1336c732
201
package net.plavcak.maven.plugins.docker.core.tasks; import net.plavcak.maven.plugins.docker.core.TaskResult; public interface Task<T> { TaskResult run(T input) throws InvalidInputException; }
20.1
57
0.78607
16837ee8d033df2a9a227b77471a5f8b6ee0ad6c
866
package org.wikiup.modules.webdav.method; import org.wikiup.core.inf.Document; import org.wikiup.core.util.StringUtil; import org.wikiup.modules.webdav.imp.WebdavFileSystem; import org.wikiup.modules.webdav.util.StatusUtil; import org.wikiup.modules.webdav.util.WebdavUtil; import org.wikiup.servlet.ServletProcessorContext; import org.wikiup.servlet.inf.ServletAction; public class UnlockRequestMethod implements ServletAction { public void doAction(ServletProcessorContext context, Document desc) { String src = WebdavUtil.getWebdavFilePath(context); String token = context.getHeader("Lock-Token"); if(token != null) token = StringUtil.trim(token, "(<>)"); if(!WebdavFileSystem.getInstance().unlock(context, src, token)) WebdavUtil.sendError(context, StatusUtil.SC_LOCKED); } }
41.238095
75
0.732102
dcad1a553d982a6af4919656e3129203a7e1be50
1,148
package me.young1lin.offer.list; import java.util.Deque; import java.util.LinkedList; /** * 从尾到头打印链表 * 不允许修改链表结构 * 用栈来实现,LinkedList 就是默认的栈 * * @author <a href="mailto:young1lin0108@gmail.com">young1lin</a> * @since 2021/1/28 下午11:40 * @version 1.0 */ public class ReversePrintlnList { private static final ListNode HEAD = new ListNode(); private static final int LIST_LENGTH = 50; static { initListNode(); } private static class ListNode { int value; ListNode next; } private static void initListNode() { ListNode prev = ReversePrintlnList.HEAD; for (int i = 0; i < LIST_LENGTH; i++) { ListNode tmp = new ListNode(); prev.value = i; prev.next = tmp; prev = tmp; } } public static void main(String[] args) { ListNode next = HEAD; while (next.next != null) { System.out.println(next.value); next = next.next; } System.out.println("======="); // 反向打印 Deque<Integer> stack = new LinkedList<>(); ListNode next2 = HEAD; while (next2.next != null) { stack.push(next2.value); next2 = next2.next; } while (!stack.isEmpty()) { System.out.println(stack.poll()); } } }
18.222222
65
0.648955
d8005ceb7f43d4c67f7ee9eb2b1827c493ce850a
630
package com.github.shaquu.utils; public class PrimitiveObject { public static byte[] toByteArrPrimitive(Byte[] bytesObject) { byte[] bytesPrimitive = new byte[bytesObject.length]; for (int i = 0; i < bytesObject.length; i++) { bytesPrimitive[i] = bytesObject[i]; } return bytesPrimitive; } public static Byte[] toByteArrObject(byte[] bytesPrimitive) { Byte[] bytesObject = new Byte[bytesPrimitive.length]; for (int i = 0; i < bytesPrimitive.length; i++) { bytesObject[i] = bytesPrimitive[i]; } return bytesObject; } }
24.230769
65
0.607937
fa3d441fd510cf9209746237814b4f481dc5c726
1,898
package com.laycoding.service.impl; import com.laycoding.bo.UploadInfoBO; import com.laycoding.common.utils.LayUtils; import com.laycoding.common.utils.OssUtils; import com.laycoding.common.utils.ResultUtil; import com.laycoding.entity.OssConfig; import com.laycoding.mapper.OssConfigMapper; import com.laycoding.service.IOssConfigService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; /** * <p> * 服务实现类 * </p> * * @author laycoding * @since 2021-10-27 */ @Service public class OssConfigServiceImpl extends ServiceImpl<OssConfigMapper, OssConfig> implements IOssConfigService { @Value("${local-oss.windows}") private String windowsPath; @Value("${local-oss.linux}") private String linuxPath; @Override public ResultUtil<UploadInfoBO> uploadImage(HttpServletRequest req, MultipartFile file) { String path = LayUtils.isWindows() ? windowsPath : linuxPath; //2.根据时间戳创建新的文件名,这样即便是第二次上传相同名称的文件,也不会把第一次的文件覆盖了 String fileName = System.currentTimeMillis() + file.getOriginalFilename(); //3.通过req.getServletContext().getRealPath("") 获取当前项目的真实路径,然后拼接前面的文件名 String destFileName = path + File.separator + fileName; Boolean isSuccess = OssUtils.uploadImage(path, destFileName, file); if (isSuccess) { UploadInfoBO uploadInfoBO = new UploadInfoBO(); uploadInfoBO.setFileName(fileName); uploadInfoBO.setFilePath(path); uploadInfoBO.setFileUrl("/upload/" + fileName); uploadInfoBO.setFileType(0); return ResultUtil.success(uploadInfoBO); } return ResultUtil.success(null); } }
34.509091
112
0.731823
0d256a551c63e0c475ae1ac2afbc798e23dfd97c
835
package net.jbock.examples; import net.jbock.examples.fixture.ParserTestFixture; import org.junit.jupiter.api.Test; import java.util.Optional; import static net.jbock.examples.fixture.ParserTestFixture.assertEquals; class GradleArgumentsFooTest { private final GradleArguments_FooParser parser = new GradleArguments_FooParser(); private final ParserTestFixture<GradleArguments.Foo> f = ParserTestFixture.create(parser::parse); @Test void testParserForNestedClass() { f.assertThat("--bar=4").succeeds("bar", Optional.of(4)); } @Test void testPrint() { String[] actual = parser.parse("--help") .getLeft().map(f::getUsageDocumentation).orElseThrow(); assertEquals(actual, "USAGE", " foo [OPTIONS]", "", "OPTIONS", " --bar BAR ", ""); } }
23.857143
83
0.676647
ed02157a1d86010892eab168b8a987d8a30f30b2
2,299
package com.zeoflow.stylar.movement; import android.text.Spanned; import android.text.method.LinkMovementMethod; import android.text.method.MovementMethod; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.zeoflow.stylar.AbstractStylarPlugin; import com.zeoflow.stylar.core.CorePlugin; /** * @since 3.0.0 */ public class MovementMethodPlugin extends AbstractStylarPlugin { @Nullable private final MovementMethod movementMethod; /** * Since 4.5.0 change to be <em>nullable</em> */ @SuppressWarnings("WeakerAccess") MovementMethodPlugin(@Nullable MovementMethod movementMethod) { this.movementMethod = movementMethod; } /** * Creates plugin that will ensure that there is movement method registered on a TextView. * Uses Android system LinkMovementMethod as default * * @see #create(MovementMethod) * @see #link() * @deprecated 4.5.0 use {@link #link()} */ @NonNull @Deprecated public static MovementMethodPlugin create() { return create(LinkMovementMethod.getInstance()); } /** * @since 4.5.0 */ @NonNull public static MovementMethodPlugin link() { return create(LinkMovementMethod.getInstance()); } /** * Special {@link MovementMethodPlugin} that is <strong>not</strong> applying a MovementMethod on a TextView * implicitly * * @since 4.5.0 */ @NonNull public static MovementMethodPlugin none() { return new MovementMethodPlugin(null); } @NonNull public static MovementMethodPlugin create(@NonNull MovementMethod movementMethod) { return new MovementMethodPlugin(movementMethod); } @Override public void configure(@NonNull Registry registry) { registry.require(CorePlugin.class) .hasExplicitMovementMethod(true); } @Override public void beforeSetText(@NonNull TextView textView, @NonNull Spanned markdown) { // @since 4.5.0 check for equality final MovementMethod current = textView.getMovementMethod(); if (current != movementMethod) { textView.setMovementMethod(movementMethod); } } }
24.98913
112
0.672031
2af3d33cbd03753f65a54c9f9038f80f007b7763
446
package org.givwenzen.reflections.scanners; import com.google.common.base.Predicate; import com.google.common.collect.Multimap; import org.givwenzen.reflections.Configuration; /** * */ public interface Scanner { void scan(final Object cls); void setConfiguration(Configuration configuration); void setStore(Multimap<String, String> store); String getIndexName(); Scanner filterBy(Predicate<String> filter); }
19.391304
53
0.742152
08ae9022585bfdedc2a697a79399fef4b0d0e18d
370
package com.jota.marvel.data; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; @RunWith(RobolectricTestRunner.class) @Config(constants = BuildConfig.class, manifest = "src/main/AndroidManifest.xml", application = ApplicationStub.class, sdk = 21) public abstract class ApplicationTestCase { }
33.636364
94
0.808108
fa79af3fa1cda76458cfddd9f90c8085662ca510
2,470
package com.lance.activiti.common.captcha; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Date; import java.util.Properties; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.code.kaptcha.Producer; import com.google.code.kaptcha.util.Config; /** * 基本验证码 * @author lance * @since 2016年11月5日下午11:01:25 */ public abstract class AbstractBaseKaptcha { private Producer kaptchaProducer = null; private String sessionKeyDateValue = null; /** * 创建验证码属性配置 * @author lance * @since 2016年11月5日下午11:00:55 * @see com.google.code.kaptcha.Constants * @return */ public abstract Properties getProperties(); /** * 初始化对象 * @author lance * @since 2016年11月5日下午11:41:31 */ private void init() { ImageIO.setUseCache(false); Config config = new Config(getProperties()); this.kaptchaProducer = config.getProducerImpl(); this.sessionKeyDateValue = config.getSessionDate(); } /** * map it to the /url/captcha.jpg * @param req * @param resp * @throws ServletException * @throws IOException */ public void captcha(HttpServletRequest req, HttpServletResponse resp, String key) throws ServletException, IOException { init(); // Set standard HTTP/1.1 no-cache headers. resp.setHeader("Cache-Control", "no-store, no-cache"); // return a jpeg resp.setContentType("image/jpeg"); // create the text for the image String capText = this.kaptchaProducer.createText(); // store the date in the session so that it can be compared // against to make sure someone hasn't taken too long to enter // their kaptcha req.getSession().setAttribute(this.sessionKeyDateValue, new Date()); // create the image with the text BufferedImage bi = this.kaptchaProducer.createImage(capText); ServletOutputStream out = resp.getOutputStream(); // write the data out ImageIO.write(bi, "jpg", out); // fixes issue #69: set the attributes after we write the image in case // the image writing fails. // store the text in the session req.getSession().setAttribute(key, capText); } }
29.058824
124
0.665587
ee3cb1c131a3704640a423becff73672f98d9a3a
211
package tr.metu.ceng.construction.server.exception; public class PlayerNotFoundException extends RuntimeException { public PlayerNotFoundException(String errorMessage) { super(errorMessage); } }
30.142857
63
0.781991
95c9b6cf233c11add606a8c82778c5bb3d8c9746
5,456
/** * %SVN.HEADER% */ package net.sf.javaml.featureselection.ranking; import java.util.HashSet; import java.util.Set; import libsvm.LibSVM; import libsvm.SelfOptimizingLinearLibSVM; import net.sf.javaml.core.Dataset; import net.sf.javaml.core.DefaultDataset; import net.sf.javaml.core.Instance; import net.sf.javaml.featureselection.FeatureRanking; import net.sf.javaml.filter.RemoveAttributes; import net.sf.javaml.utils.ArrayUtils; /** * Implements the recursive feature elimination procedure for linear support * vector machines. * * Starting with the full feature set, attributes are ranked according to the * weights they get in a linear SVM. Subsequently, a percentage of the worst * ranked features are eliminated and the SVM is retrained with the left-over * attributes. The process is repeated until only one feature is retained. The * result is a feature ranking. * * The C-parameter of the internal SVM can be optimized or can be fixed. * * * @version %SVN.VERSION% * * @author Thomas Abeel * */ public class RecursiveFeatureEliminationSVM implements FeatureRanking { /* * The final ranking of the attributes, this is constructed with the build * method. */ private int[] ranking; /* * The percentage of worst feature that should be removed in each iteration. */ private double removePercentage = 0.20; /* In case of optimization of the C-parameter, the number of folds to use */ private int internalFolds; /* * Whether the internal SVM should optimize the C-parameter, when this is * not done it defaults to 1 */ private boolean optimize; /** * * @param folds * the number of internal folds to eliminate features * @param positiveClass * @param removePercentage * @param rg */ public RecursiveFeatureEliminationSVM(double removePercentage) { this(removePercentage, false); } public RecursiveFeatureEliminationSVM(double removePercentage, boolean optimize) { this(removePercentage, optimize, 4); } public RecursiveFeatureEliminationSVM(double removePercentage, boolean optimize, int internalFolds) { this.removePercentage = removePercentage; this.optimize = optimize; this.internalFolds = internalFolds; } public void build(Dataset data) { /* The order of the importance of the features */ int[] ordering = new int[data.noAttributes()]; /* Bitmap of removed attributes */ boolean[] removedAttributes = new boolean[data.noAttributes()]; /* * Number of removed attributes, is always equal to the number of true * values in the above bitmap */ int removed = 0; while (data.noAttributes() > 1) { Dataset training = data; LibSVM svm; if (optimize) svm = new SelfOptimizingLinearLibSVM(-4, 4, internalFolds); else { svm = new LibSVM(); svm.getParameters().C=1; } svm.buildClassifier(training); double[] weights = svm.getWeights(); /* Use absolute values of the weights */ ArrayUtils.abs(weights); /* Order weights */ int[] order = ArrayUtils.sort(weights); /* Determine the number of attributes to prune, round up */ int numRemove = (int) (order.length * removePercentage + 1); if (numRemove > order.length) numRemove = order.length - 1; Set<Integer> toRemove = new HashSet<Integer>(); int[] trueIndices = new int[numRemove]; for (int i = 0; i < numRemove; i++) { toRemove.add(order[i]); trueIndices[i] = getTrueIndex(order[i], removedAttributes); ordering[ordering.length - removed - 1] = trueIndices[i]; removed++; } // This needs to be done afterwards, otherwise the getTrueIndex // method will fail. for (int i = 0; i < numRemove; i++) { removedAttributes[trueIndices[i]] = true; } RemoveAttributes filter = new RemoveAttributes(toRemove); Dataset filtered=new DefaultDataset(); for(Instance i:data){ filter.filter(i); filtered.add(i); } data=filtered; } int index = 0; if (data.noAttributes() == 1) { for (int i = 0; i < removedAttributes.length; i++) { if (!removedAttributes[i]) index = i; } ordering[0] = index; } ranking = new int[ordering.length]; for (int i = 0; i < ranking.length; i++) ranking[ordering[i]] = i; } private int getTrueIndex(int i, boolean[] removedAttributes) { int index = 0; while (i >= 0) { if (!removedAttributes[index]) i--; index++; } return index - 1; } public int rank(int attIndex) { return ranking[attIndex]; } public int noAttributes() { return ranking.length; } }
31.177143
106
0.576796
ba700534e187c407ca3baa0adfd1963990457f24
892
package com.github.a4ad.port.in.server; import com.github.a4ad.common.SelfValidating; import lombok.EqualsAndHashCode; import lombok.Value; import javax.validation.constraints.NotBlank; public interface DeleteServerUseCase { void deleteServer(DeleteServerUseCaseCommand command) throws ServerNotFoundRuntimeException; @Value @EqualsAndHashCode(callSuper = false) class DeleteServerUseCaseCommand extends SelfValidating<DeleteServerUseCaseCommand> { @NotBlank String name; public DeleteServerUseCaseCommand(String name) { this.name = name; validateSelf(); } } class ServerNotFoundRuntimeException extends RuntimeException { public ServerNotFoundRuntimeException(DeleteServerUseCaseCommand command) { super("Server with name '" + command.getName() + "' not found"); } } }
26.235294
96
0.719731
c932a17094c0080992b15f546a399d44389cee96
363
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.xmlb; import com.intellij.serialization.MutableAccessor; import org.jetbrains.annotations.NotNull; public interface NestedBinding extends Binding { @NotNull MutableAccessor getAccessor(); }
33
140
0.798898
d52473ee2a803f8f7aefeae9e189d46f6099979e
577
package de.npruehs.missionrunner.client.controller.mission; import dagger.Subcomponent; import de.npruehs.missionrunner.client.ActivityScope; import de.npruehs.missionrunner.client.view.mission.MissionDetailsFragment; import de.npruehs.missionrunner.client.view.mission.ShowMissionsFragment; @ActivityScope @Subcomponent public interface MissionComponent { @Subcomponent.Factory interface Factory { MissionComponent create(); } void inject(ShowMissionsFragment showMissionsFragment); void inject(MissionDetailsFragment missionDetailsFragment); }
30.368421
75
0.818024
9429a5323d00b9cfc3c22f4bb507b5510c99664f
2,489
/* * Copyright (c) 2020 , <Pierre Falda> [ pierre@reacted.io ] * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ package io.reacted.core.reactorsystem; import io.reacted.core.config.ChannelId; import io.reacted.core.drivers.system.NullDriver; import io.reacted.core.drivers.system.NullDriverConfig; import io.reacted.core.drivers.system.ReActorSystemDriver; import io.reacted.core.messages.AckingPolicy; import io.reacted.core.messages.reactors.DeliveryStatus; import io.reacted.patterns.NonNullByDefault; import io.reacted.patterns.Try; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.Serializable; import java.util.Properties; import java.util.concurrent.CompletionStage; @NonNullByDefault public final class NullReActorSystemRef extends ReActorSystemRef { public static final NullReActorSystemRef NULL_REACTOR_SYSTEM_REF = new NullReActorSystemRef(ReActorSystemId.NO_REACTORSYSTEM_ID, NullDriver.NULL_DRIVER_PROPERTIES, NullDriver.NULL_DRIVER); public NullReActorSystemRef() { /* Required by Externalizable */ } private NullReActorSystemRef(ReActorSystemId reActorSystemId, Properties channelProperties, ReActorSystemDriver<NullDriverConfig> reActorSystemDriver) { super(reActorSystemDriver, channelProperties, ChannelId.NO_CHANNEL_ID, reActorSystemId); } @Override public <PayloadT extends Serializable> CompletionStage<Try<DeliveryStatus>> tell(ReActorRef src, ReActorRef dst, AckingPolicy ackingPolicy, PayloadT message) { return NullDriver.NULL_DRIVER.tell(src, dst,ackingPolicy, message); } @Override public ReActorSystemId getReActorSystemId() { return ReActorSystemId.NO_REACTORSYSTEM_ID; } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); } }
42.186441
132
0.666131
2b221d33a29d3450ff20e6f1e30b179820f72673
1,209
import org.infai.ses.senergy.operators.Config; import org.infai.ses.senergy.utils.ConfigProvider; import java.time.ZoneId; public class EstimatorFactory { public static Estimator createNewInstance() { Config config = ConfigProvider.getConfig(); return createNewInstanceWithConfig(config); } public static Estimator createNewInstanceWithConfig(Config config){ String algorithm = config.getConfigValue("Algorithm", "apache-simple"); String configTimezone = config.getConfigValue("Timezone", "+02"); ZoneId timezone = ZoneId.of(configTimezone); //As configured long ignoreValuesOlderThanMs = Long.parseLong(config.getConfigValue("ignoreValuesOlderThanMs", "31557600000")); EstimatorInterface estimator; switch(algorithm) { case "moa-fimtdd": estimator = new MoaFIMTDDRegression(); break; case "moa-arf": estimator = new MoaARF(); break; case "apache-simple": default: estimator = new ApacheSimpleRegression(); } return new Estimator(estimator, timezone, ignoreValuesOlderThanMs); } }
36.636364
119
0.651778
27e2c572d70d5c0fb60ed32c51944a5191a3b369
989
/* * Copyright 2016, Joseph B. Ottinger * * 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.autumncode.components; import org.slf4j.Logger; public interface LogThing { Logger getLog(); default void doSomething() { getLog().trace("trace message"); getLog().debug("debug message"); getLog().warn("warn message"); getLog().info("info message"); getLog().error("error message"); } }
31.903226
78
0.669363
29e1615737f5d0e53833c3b2de0064234ac14a30
1,369
package org.iubbo.proxy.config; import lombok.AllArgsConstructor; import lombok.Getter; /** * 请求常量类 * * @author idea * @date 2020/1/2 * @version V1.0 */ public class CommonConstants { public final static String SAMPLE_REQ = "{\n" + " \"interfaceName\": \"com.sise.dubbo.provider.api.EchoService\",\n" + " \"methodName\": \"echoPojo\",\n" + " \"argTypes\": [\n" + " \"com.sise.dubbo.provider.model.Pojo\"\n" + " ],\n" + " \"argObjects\": [\n" + " {\n" + " \"count\": 1,\n" + " \"value\": \"val\"\n" + " }\n" + " ],\n" + " \"version\": \"1.0\",\n" + " \"group\": \"test\",\n" + " \"attachments\": {\n" + " \"key\": \"value\"\n" + " }\n" + "}"; @AllArgsConstructor @Getter public enum LoadbalanceEnum{ RANDOM_TYPE(0,"random"), ROUND_ROBIN_TYPE(1,"roundrobin"), LEASTACTIVE_TYPE(2,"leastactive"); Integer code; String des; } @Getter @AllArgsConstructor public enum RegisterTypeEnum{ ZOOKEEPER(1,"zookeeper"), NACOS(2,"nacos"); Integer code; String name; } }
21.390625
85
0.431702
3fb975889f2e5ce51c85a578808610f98c1474cc
439
package com.clausgames.crystalmagic.blocks.plants; import com.clausgames.crystalmagic.lib.LibMisc; import net.minecraft.block.material.Material; public class CoalInfusedStone extends OreInfusedStone { protected CoalInfusedStone(Material material) { super(Material.rock); this.setBlockName("CoalInfusedStone"); this.setBlockTextureName(LibMisc.MODID + ":" + this.getUnlocalizedName().substring(5)); } }
31.357143
95
0.751708
d46d0f4cd3628ab4e7d5a2cc8ceafe56ca7793e1
831
package com.indirectionsoftware.runtime.nlu; import java.util.ArrayList; import java.util.List; import com.indirectionsoftware.metamodel.IDCAttribute; public class IDCValue { public String value; public List<IDCAttributeValueDataList> attrVals = new ArrayList<IDCAttributeValueDataList>(); /*****************************************************************************/ public IDCValue(String value) { this.value = value; attrVals = new ArrayList<IDCAttributeValueDataList>(); } /*****************************************************************************/ public String toString() { String ret = "IDCValue: " + value + " -> {"; for(IDCAttributeValueDataList ent : attrVals) { ret += " " + ent.toString() + ""; } ret += " }"; return ret; } }
22.459459
95
0.524669
8706b9482c181e377d0f4b6fd5a8179573c49dae
104
package com.github.sadikovi; import java.util.List; interface LoxGetter { Object get(Token name); }
13
28
0.75
9b30faea5273bca825110786b408fafcc1f36b24
699
package br.com.orange.cdc.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.validation.constraints.NotBlank; import br.com.orange.cdc.config.validation.ValorUnico; @Entity public class Categoria { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotBlank @Column(unique = true, nullable = false) @ValorUnico(message = "Categoria já cadastrada", campo = "nome", entity = "Categoria") private String nome; @Deprecated public Categoria() { } public Categoria(@NotBlank String nome) { this.nome = nome; } }
21.181818
87
0.76681
06cc8474abb5c291cfa36120c087f7ce041c9154
4,874
package cx.rain.mc.bukkit.ieconomy; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.EconomyResponse; import org.bukkit.OfflinePlayer; import java.util.List; public class EconomyImpl implements Economy { public EconomyImpl() { } @Override public boolean isEnabled() { return false; } @Override public String getName() { return null; } @Override public boolean hasBankSupport() { return false; } @Override public int fractionalDigits() { return 0; } @Override public String format(double amount) { return null; } @Override public String currencyNamePlural() { return null; } @Override public String currencyNameSingular() { return null; } @Override public boolean hasAccount(String playerName) { return false; } @Override public boolean hasAccount(OfflinePlayer player) { return false; } @Override public boolean hasAccount(String playerName, String worldName) { return false; } @Override public boolean hasAccount(OfflinePlayer player, String worldName) { return false; } @Override public double getBalance(String playerName) { return 0; } @Override public double getBalance(OfflinePlayer player) { return 0; } @Override public double getBalance(String playerName, String world) { return 0; } @Override public double getBalance(OfflinePlayer player, String world) { return 0; } @Override public boolean has(String playerName, double amount) { return false; } @Override public boolean has(OfflinePlayer player, double amount) { return false; } @Override public boolean has(String playerName, String worldName, double amount) { return false; } @Override public boolean has(OfflinePlayer player, String worldName, double amount) { return false; } @Override public EconomyResponse withdrawPlayer(String playerName, double amount) { return null; } @Override public EconomyResponse withdrawPlayer(OfflinePlayer player, double amount) { return null; } @Override public EconomyResponse withdrawPlayer(String playerName, String worldName, double amount) { return null; } @Override public EconomyResponse withdrawPlayer(OfflinePlayer player, String worldName, double amount) { return null; } @Override public EconomyResponse depositPlayer(String playerName, double amount) { return null; } @Override public EconomyResponse depositPlayer(OfflinePlayer player, double amount) { return null; } @Override public EconomyResponse depositPlayer(String playerName, String worldName, double amount) { return null; } @Override public EconomyResponse depositPlayer(OfflinePlayer player, String worldName, double amount) { return null; } @Override public EconomyResponse createBank(String name, String player) { return null; } @Override public EconomyResponse createBank(String name, OfflinePlayer player) { return null; } @Override public EconomyResponse deleteBank(String name) { return null; } @Override public EconomyResponse bankBalance(String name) { return null; } @Override public EconomyResponse bankHas(String name, double amount) { return null; } @Override public EconomyResponse bankWithdraw(String name, double amount) { return null; } @Override public EconomyResponse bankDeposit(String name, double amount) { return null; } @Override public EconomyResponse isBankOwner(String name, String playerName) { return null; } @Override public EconomyResponse isBankOwner(String name, OfflinePlayer player) { return null; } @Override public EconomyResponse isBankMember(String name, String playerName) { return null; } @Override public EconomyResponse isBankMember(String name, OfflinePlayer player) { return null; } @Override public List<String> getBanks() { return null; } @Override public boolean createPlayerAccount(String playerName) { return false; } @Override public boolean createPlayerAccount(OfflinePlayer player) { return false; } @Override public boolean createPlayerAccount(String playerName, String worldName) { return false; } @Override public boolean createPlayerAccount(OfflinePlayer player, String worldName) { return false; } }
21.283843
98
0.6508
bf590510ce672420ead4858dfb7045bfd43557ee
842
package com.subrosagames.subrosa.event; /** * An exception thrown when an event is unable to be scheduled. */ public class EventException extends Exception { private static final long serialVersionUID = 1301604863966351742L; /** * Default constructor. */ public EventException() { } /** * Construct with message. * * @param s message */ public EventException(String s) { super(s); } /** * Construct with message and cause. * * @param s message * @param throwable cause */ public EventException(String s, Throwable throwable) { super(s, throwable); } /** * Construct with cause. * * @param throwable cause */ public EventException(Throwable throwable) { super(throwable); } }
19.136364
70
0.587886
d58d52e83680d11640c08cfe69f308e4dcbd68b1
1,410
package html; public class HtmlCreator { private StringBuilder stringBuilder; private Tag tag; private String padding; public HtmlCreator(Tag tag) { this.tag = tag; stringBuilder = new StringBuilder(); padding = manyTab(tag.getLevel()); } public StringBuilder toHtmlText() { createOpenTag(); createBodyTag(); createCloseTag(); return stringBuilder; } private void createOpenTag() { stringBuilder.append(padding + "<" + tag.name); for (String key : tag.listAttribute.keySet()) { stringBuilder.append(" " + key + "=" + "\"" + tag.listAttribute.get(key) + "\""); } stringBuilder.append(">"); } private void createBodyTag() { if (tag.getInnerHtml() != null) stringBuilder.append("\n\t" + padding + tag.getInnerHtml()); for (HtmlElement key : tag.listSubElement) { stringBuilder.append("\n"); Tag tag = (Tag) key; tag.setLevel(this.tag.getLevel() + 1); stringBuilder.append(new HtmlCreator((Tag) key).toHtmlText()); } } private void createCloseTag() { stringBuilder.append("\n" + padding + "</" + tag.name + ">"); } private String manyTab(int level) { return new String(new char[level]).replace("\0", "\t"); } }
29.375
101
0.553901
bfdabcc20a2b2c10944d83eed33ab0e91f470f47
586
package io.junq.examples.usercenter.util; public final class UserCenterMapping { public static final String BASE = "/api/"; public static final String USERS = "api/users"; public static final String PRIVILEGES = "api/privileges"; public static final String ROLES = "api/roles"; public static final String AUTHENTICATION = "api/authentication"; public static final class Singular { public static final String USER = "user"; public static final String PRIVILEGE = "privilege"; public static final String ROLE = "role"; } }
27.904762
69
0.687713
358fe34eb23d7c8c63aa65f63ff68778dc4f4e7a
3,938
/* * Copyright 2018 Google LLC All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigtable.hbase.async; import static com.google.cloud.bigtable.hbase.test_env.SharedTestEnvRule.COLUMN_FAMILY; import com.google.cloud.bigtable.hbase.AbstractTestCreateTable; import com.google.cloud.bigtable.hbase.DataGenerationHelper; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import org.apache.hadoop.hbase.HRegionLocation; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.AsyncAdmin; import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; import org.apache.hadoop.hbase.client.TableDescriptor; import org.apache.hadoop.hbase.client.TableDescriptorBuilder; public class TestAsyncCreateTable extends AbstractTestCreateTable { protected static DataGenerationHelper dataHelper = new DataGenerationHelper(); @Override protected void createTable(TableName tableName) throws Exception { try { getAsyncAdmin().createTable(createDescriptor(tableName)).get(); } catch (ExecutionException e) { throw (Exception) e.getCause(); } } @Override protected void createTable(TableName tableName, byte[] start, byte[] end, int splitCount) throws Exception { try { getAsyncAdmin().createTable(createDescriptor(tableName), start, end, splitCount).get(); } catch (ExecutionException e) { throw (Exception) e.getCause(); } } @Override protected void createTable(TableName tableName, byte[][] ranges) throws Exception { try { getAsyncAdmin().createTable(createDescriptor(tableName), ranges).get(); } catch (ExecutionException e) { throw (Exception) e.getCause(); } } private TableDescriptor createDescriptor(TableName tableName) { return TableDescriptorBuilder.newBuilder(tableName) .addColumnFamily(ColumnFamilyDescriptorBuilder.newBuilder(COLUMN_FAMILY).build()) .build(); } private AsyncAdmin getAsyncAdmin() throws InterruptedException, ExecutionException { return AbstractAsyncTest.getAsyncConnection().getAdmin(); } @Override protected List<HRegionLocation> getRegions(TableName tableName) throws Exception { byte[] rowKey = dataHelper.randomData("TestAsyncCreateTable-"); List<HRegionLocation> regionLocationList = new ArrayList<>(); HRegionLocation hRegionLocation = AbstractAsyncTest.getAsyncConnection() .getRegionLocator(tableName) .getRegionLocation(rowKey, true) .get(); regionLocationList.add(hRegionLocation); return regionLocationList; } @Override protected boolean asyncGetRegions(TableName tableName) throws Exception { return getAsyncAdmin().getRegions(tableName).get().size() == 1 ? true : false; } @Override protected boolean isTableEnabled(TableName tableName) throws Exception { return getAsyncAdmin().isTableEnabled(tableName).get(); } @Override protected void disableTable(TableName tableName) throws Exception { getAsyncAdmin().disableTable(tableName).get(); } @Override protected void adminDeleteTable(TableName tableName) throws Exception { getAsyncAdmin().deleteTable(tableName).get(); } @Override protected boolean tableExists(TableName tableName) throws Exception { return getAsyncAdmin().tableExists(tableName).get(); } }
35.160714
93
0.751397
589118d59cc41805bd5c888c23ad15d08dddb51b
1,788
// GPars - Groovy Parallel Systems // // Copyright © 2008-10 The original author or authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package groovyx.gpars.actor; import groovy.lang.Closure; /** * An actor representing a reactor. When it receives a message, the supplied block of code is run with the message * as a parameter and the result of the code is send in reply. * <p/> * <pre> * final def doubler = reactor {message -> * 2 * message * }* * def result = doubler.sendAndWait(10) * <p/> * </pre> * * @author Vaclav Pech, Alex Tkachman * Date: Jun 26, 2009 */ public class ReactiveActor extends AbstractLoopingActor { private static final long serialVersionUID = 2709208258556647528L; public ReactiveActor(final Closure body) { final Closure cloned = (Closure) body.clone(); cloned.setDelegate(this); cloned.setResolveStrategy(Closure.DELEGATE_FIRST); initialize(new Closure(this) { private static final long serialVersionUID = 4092639210342260198L; @Override public Object call(final Object arguments) { ReactiveActor.this.replyIfExists(cloned.call(new Object[]{arguments})); return null; } }); } }
32.509091
114
0.681767
cbf5d11cb101e68ad3be2090bf62eeb66e71d780
342
package org.chathamrobotics.ftcutils; /*! * ftc-utils * Copyright (c) 2017 Chatham Robotics * MIT License * @Last Modified by: Carson Storm * @Last Modified time: 5/26/2017 */ /** * A common driver interface. */ public interface Driver { /** * Stops all driving functionality. */ void stop(); }
17.1
40
0.605263
e3bf28526f77ce0a773c9289f1c0e79e9d31eab6
2,143
/* * Copyright 2014 Space Dynamics Laboratory - Utah State University Research 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. */ package edu.usu.sdl.openstorefront.web.rest.model; import edu.usu.sdl.openstorefront.storage.model.Component; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Objects; /** * * @author dshurtleff */ public class ComponentRelationshipView { private String componentId; private String name; private Date updateDts; public ComponentRelationshipView() { } public static ComponentRelationshipView toView(Component component) { Objects.requireNonNull(component, "Component Required"); ComponentRelationshipView relationshipView = new ComponentRelationshipView(); relationshipView.setComponentId(component.getComponentId()); relationshipView.setName(component.getName()); return relationshipView; } public static List<ComponentRelationshipView> toViewList(List<Component> components) { List<ComponentRelationshipView> views = new ArrayList<>(); components.forEach(component -> { views.add(toView(component)); }); return views; } public String getComponentId() { return componentId; } public void setComponentId(String componentId) { this.componentId = componentId; } public String getName() { return name; } public void setName(String name) { this.name = name; } /** * @return the updateDts */ public Date getUpdateDts() { return updateDts; } /** * @param updateDts the updateDts to set */ public void setUpdateDts(Date updateDts) { this.updateDts = updateDts; } }
22.797872
88
0.745217
635108f26990158294e982255e91dad28ce805fe
281
package com.github.t3t5u.common.expression; import java.io.Serializable; public interface BinaryExpression<L extends Serializable, R extends Serializable, T extends Serializable> extends Expression<T> { Expression<L> getLeftExpression(); Expression<R> getRightExpression(); }
28.1
129
0.807829
62aa47dfd3d9baf5a27bdc0ef8381b68b3e9db5d
1,376
package com.csxiaoshang.xml; import org.junit.Test; import java.io.*; import java.text.MessageFormat; public class XmlUtilsTest { @Test public void readXml() throws IOException { System.out.println( XmlUtils.readXml("D:\\github\\jenkins\\xmljenkins\\src\\main\\resources\\test.xml")); System.out.println("-----------------------------------------"); MessageFormat messageFormat =new MessageFormat(XmlUtils.readXml("D:\\github\\jenkins\\xmljenkins\\src\\main\\resources\\test.xml")); String string = messageFormat.format(new Object[]{"xiaoming","asdf","asdf"}); System.out.println("result "+ string); System.out.println(this.getClass()); } /* @Test public void freemarker() throws ParserConfigurationException, SAXException, IOException, TemplateException { Configuration configuration = new Configuration(); configuration.setDirectoryForTemplateLoading(new File("D:\\github\\jenkins\\xmljenkins\\src\\main\\resources\\templates")); Template template = configuration.getTemplate("/config.ftl"); Map person = new HashMap(); person.put("id",1); person.put("flag","svn"); Map root =new HashMap(); root.put("person",person); Writer out = new StringWriter(); template.process(root,out); System.out.println(out); }*/ }
41.69697
140
0.645349
a15c3be54471be7059963ec0c9db0ef9a4810949
757
package za.org.grassroot.graph.repository; import lombok.extern.slf4j.Slf4j; import org.neo4j.ogm.session.event.Event; import org.neo4j.ogm.session.event.EventListenerAdapter; import za.org.grassroot.graph.domain.GrassrootGraphEntity; import java.time.Instant; @Slf4j public class PreSaveListener extends EventListenerAdapter { @Override public void onPreSave(Event event) { log.debug("Saving entity to graph: {}", event.getObject()); if (event.getObject() instanceof GrassrootGraphEntity) { GrassrootGraphEntity graphEntity = (GrassrootGraphEntity) event.getObject(); if (graphEntity.getCreationTime() == null) { graphEntity.setCreationTime(Instant.now()); } } } }
32.913043
88
0.705416
255a88dd8c839ed7e1044cb478569acbb5fdbdb5
18,943
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package com.firebase.ui.database; public final class R { private R() {} public static final class attr { private attr() {} public static final int buttonSize = 0x7f030056; public static final int circleCrop = 0x7f03007b; public static final int colorScheme = 0x7f030097; public static final int fastScrollEnabled = 0x7f0300f8; public static final int fastScrollHorizontalThumbDrawable = 0x7f0300f9; public static final int fastScrollHorizontalTrackDrawable = 0x7f0300fa; public static final int fastScrollVerticalThumbDrawable = 0x7f0300fb; public static final int fastScrollVerticalTrackDrawable = 0x7f0300fc; public static final int font = 0x7f0300ff; public static final int fontProviderAuthority = 0x7f030101; public static final int fontProviderCerts = 0x7f030102; public static final int fontProviderFetchStrategy = 0x7f030103; public static final int fontProviderFetchTimeout = 0x7f030104; public static final int fontProviderPackage = 0x7f030105; public static final int fontProviderQuery = 0x7f030106; public static final int fontStyle = 0x7f030107; public static final int fontWeight = 0x7f030109; public static final int imageAspectRatio = 0x7f030124; public static final int imageAspectRatioAdjust = 0x7f030125; public static final int layoutManager = 0x7f03013b; public static final int reverseLayout = 0x7f0301af; public static final int scopeUris = 0x7f0301b1; public static final int spanCount = 0x7f0301c5; public static final int stackFromEnd = 0x7f0301cb; } public static final class bool { private bool() {} public static final int abc_action_bar_embed_tabs = 0x7f040000; } public static final class color { private color() {} public static final int common_google_signin_btn_text_dark = 0x7f050030; public static final int common_google_signin_btn_text_dark_default = 0x7f050031; public static final int common_google_signin_btn_text_dark_disabled = 0x7f050032; public static final int common_google_signin_btn_text_dark_focused = 0x7f050033; public static final int common_google_signin_btn_text_dark_pressed = 0x7f050034; public static final int common_google_signin_btn_text_light = 0x7f050035; public static final int common_google_signin_btn_text_light_default = 0x7f050036; public static final int common_google_signin_btn_text_light_disabled = 0x7f050037; public static final int common_google_signin_btn_text_light_focused = 0x7f050038; public static final int common_google_signin_btn_text_light_pressed = 0x7f050039; public static final int common_google_signin_btn_tint = 0x7f05003a; public static final int notification_action_color_filter = 0x7f05007a; public static final int notification_icon_bg_color = 0x7f05007b; public static final int notification_material_background_media_default_color = 0x7f05007c; public static final int primary_text_default_material_dark = 0x7f050081; public static final int ripple_material_light = 0x7f050086; public static final int secondary_text_default_material_dark = 0x7f050087; public static final int secondary_text_default_material_light = 0x7f050088; } public static final class dimen { private dimen() {} public static final int compat_button_inset_horizontal_material = 0x7f06004e; public static final int compat_button_inset_vertical_material = 0x7f06004f; public static final int compat_button_padding_horizontal_material = 0x7f060050; public static final int compat_button_padding_vertical_material = 0x7f060051; public static final int compat_control_corner_material = 0x7f060052; public static final int fastscroll_default_thickness = 0x7f060083; public static final int fastscroll_margin = 0x7f060084; public static final int fastscroll_minimum_range = 0x7f060085; public static final int item_touch_helper_max_drag_scroll_per_frame = 0x7f06008d; public static final int item_touch_helper_swipe_escape_max_velocity = 0x7f06008e; public static final int item_touch_helper_swipe_escape_velocity = 0x7f06008f; public static final int notification_action_icon_size = 0x7f0600c0; public static final int notification_action_text_size = 0x7f0600c1; public static final int notification_big_circle_margin = 0x7f0600c2; public static final int notification_content_margin_start = 0x7f0600c3; public static final int notification_large_icon_height = 0x7f0600c4; public static final int notification_large_icon_width = 0x7f0600c5; public static final int notification_main_column_padding_top = 0x7f0600c6; public static final int notification_media_narrow_margin = 0x7f0600c7; public static final int notification_right_icon_size = 0x7f0600c8; public static final int notification_right_side_padding_top = 0x7f0600c9; public static final int notification_small_icon_background_padding = 0x7f0600ca; public static final int notification_small_icon_size_as_large = 0x7f0600cb; public static final int notification_subtext_size = 0x7f0600cc; public static final int notification_top_pad = 0x7f0600cd; public static final int notification_top_pad_large_text = 0x7f0600ce; } public static final class drawable { private drawable() {} public static final int common_full_open_on_phone = 0x7f070061; public static final int common_google_signin_btn_icon_dark = 0x7f070062; public static final int common_google_signin_btn_icon_dark_focused = 0x7f070063; public static final int common_google_signin_btn_icon_dark_normal = 0x7f070064; public static final int common_google_signin_btn_icon_dark_normal_background = 0x7f070065; public static final int common_google_signin_btn_icon_disabled = 0x7f070066; public static final int common_google_signin_btn_icon_light = 0x7f070067; public static final int common_google_signin_btn_icon_light_focused = 0x7f070068; public static final int common_google_signin_btn_icon_light_normal = 0x7f070069; public static final int common_google_signin_btn_icon_light_normal_background = 0x7f07006a; public static final int common_google_signin_btn_text_dark = 0x7f07006b; public static final int common_google_signin_btn_text_dark_focused = 0x7f07006c; public static final int common_google_signin_btn_text_dark_normal = 0x7f07006d; public static final int common_google_signin_btn_text_dark_normal_background = 0x7f07006e; public static final int common_google_signin_btn_text_disabled = 0x7f07006f; public static final int common_google_signin_btn_text_light = 0x7f070070; public static final int common_google_signin_btn_text_light_focused = 0x7f070071; public static final int common_google_signin_btn_text_light_normal = 0x7f070072; public static final int common_google_signin_btn_text_light_normal_background = 0x7f070073; public static final int googleg_disabled_color_18 = 0x7f07007e; public static final int googleg_standard_color_18 = 0x7f07007f; public static final int notification_action_background = 0x7f07008f; public static final int notification_bg = 0x7f070090; public static final int notification_bg_low = 0x7f070091; public static final int notification_bg_low_normal = 0x7f070092; public static final int notification_bg_low_pressed = 0x7f070093; public static final int notification_bg_normal = 0x7f070094; public static final int notification_bg_normal_pressed = 0x7f070095; public static final int notification_icon_background = 0x7f070096; public static final int notification_template_icon_bg = 0x7f070097; public static final int notification_template_icon_low_bg = 0x7f070098; public static final int notification_tile_bg = 0x7f070099; public static final int notify_panel_notification_icon_bg = 0x7f07009a; } public static final class id { private id() {} public static final int action0 = 0x7f08000d; public static final int action_container = 0x7f080015; public static final int action_divider = 0x7f080017; public static final int action_image = 0x7f080018; public static final int action_text = 0x7f08001e; public static final int actions = 0x7f08001f; public static final int adjust_height = 0x7f080022; public static final int adjust_width = 0x7f080023; public static final int async = 0x7f080028; public static final int auto = 0x7f080029; public static final int blocking = 0x7f08002c; public static final int cancel_action = 0x7f08002f; public static final int center = 0x7f080030; public static final int chronometer = 0x7f08003b; public static final int dark = 0x7f080050; public static final int end_padder = 0x7f08005e; public static final int forever = 0x7f08006c; public static final int icon = 0x7f080075; public static final int icon_group = 0x7f080076; public static final int icon_only = 0x7f080077; public static final int info = 0x7f08007a; public static final int italic = 0x7f08007e; public static final int item_touch_helper_previous_elevation = 0x7f08007f; public static final int light = 0x7f080083; public static final int line1 = 0x7f080084; public static final int line3 = 0x7f080085; public static final int media_actions = 0x7f080096; public static final int none = 0x7f0800a5; public static final int normal = 0x7f0800a6; public static final int notification_background = 0x7f0800a7; public static final int notification_main_column = 0x7f0800a8; public static final int notification_main_column_container = 0x7f0800a9; public static final int radio = 0x7f0800ba; public static final int right_icon = 0x7f0800c4; public static final int right_side = 0x7f0800c5; public static final int standard = 0x7f0800f5; public static final int status_bar_latest_event_content = 0x7f0800f7; public static final int tag_transition_group = 0x7f0800fc; public static final int text = 0x7f0800ff; public static final int text2 = 0x7f080100; public static final int time = 0x7f080108; public static final int title = 0x7f080109; public static final int wide = 0x7f080124; public static final int wrap_content = 0x7f080127; } public static final class integer { private integer() {} public static final int cancel_button_image_alpha = 0x7f090004; public static final int google_play_services_version = 0x7f090008; public static final int status_bar_notification_info_maxnum = 0x7f09000f; } public static final class layout { private layout() {} public static final int notification_action = 0x7f0b003e; public static final int notification_action_tombstone = 0x7f0b003f; public static final int notification_media_action = 0x7f0b0040; public static final int notification_media_cancel_action = 0x7f0b0041; public static final int notification_template_big_media = 0x7f0b0042; public static final int notification_template_big_media_custom = 0x7f0b0043; public static final int notification_template_big_media_narrow = 0x7f0b0044; public static final int notification_template_big_media_narrow_custom = 0x7f0b0045; public static final int notification_template_custom_big = 0x7f0b0046; public static final int notification_template_icon_group = 0x7f0b0047; public static final int notification_template_lines_media = 0x7f0b0048; public static final int notification_template_media = 0x7f0b0049; public static final int notification_template_media_custom = 0x7f0b004a; public static final int notification_template_part_chronometer = 0x7f0b004b; public static final int notification_template_part_time = 0x7f0b004c; } public static final class string { private string() {} public static final int common_google_play_services_enable_button = 0x7f0e002c; public static final int common_google_play_services_enable_text = 0x7f0e002d; public static final int common_google_play_services_enable_title = 0x7f0e002e; public static final int common_google_play_services_install_button = 0x7f0e002f; public static final int common_google_play_services_install_text = 0x7f0e0030; public static final int common_google_play_services_install_title = 0x7f0e0031; public static final int common_google_play_services_notification_channel_name = 0x7f0e0032; public static final int common_google_play_services_notification_ticker = 0x7f0e0033; public static final int common_google_play_services_unknown_issue = 0x7f0e0034; public static final int common_google_play_services_unsupported_text = 0x7f0e0035; public static final int common_google_play_services_update_button = 0x7f0e0036; public static final int common_google_play_services_update_text = 0x7f0e0037; public static final int common_google_play_services_update_title = 0x7f0e0038; public static final int common_google_play_services_updating_text = 0x7f0e0039; public static final int common_google_play_services_wear_update_text = 0x7f0e003a; public static final int common_open_on_phone = 0x7f0e003b; public static final int common_signin_button_text = 0x7f0e003c; public static final int common_signin_button_text_long = 0x7f0e003d; public static final int fcm_fallback_notification_channel_label = 0x7f0e0049; public static final int status_bar_notification_info_overflow = 0x7f0e005b; } public static final class style { private style() {} public static final int TextAppearance_Compat_Notification = 0x7f0f0116; public static final int TextAppearance_Compat_Notification_Info = 0x7f0f0117; public static final int TextAppearance_Compat_Notification_Info_Media = 0x7f0f0118; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0f0119; public static final int TextAppearance_Compat_Notification_Line2_Media = 0x7f0f011a; public static final int TextAppearance_Compat_Notification_Media = 0x7f0f011b; public static final int TextAppearance_Compat_Notification_Time = 0x7f0f011c; public static final int TextAppearance_Compat_Notification_Time_Media = 0x7f0f011d; public static final int TextAppearance_Compat_Notification_Title = 0x7f0f011e; public static final int TextAppearance_Compat_Notification_Title_Media = 0x7f0f011f; public static final int Widget_Compat_NotificationActionContainer = 0x7f0f01c5; public static final int Widget_Compat_NotificationActionText = 0x7f0f01c6; } public static final class styleable { private styleable() {} public static final int[] FontFamily = { 0x7f030101, 0x7f030102, 0x7f030103, 0x7f030104, 0x7f030105, 0x7f030106 }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f0300ff, 0x7f030107, 0x7f030108, 0x7f030109, 0x7f030233 }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_android_ttcIndex = 3; public static final int FontFamilyFont_android_fontVariationSettings = 4; public static final int FontFamilyFont_font = 5; public static final int FontFamilyFont_fontStyle = 6; public static final int FontFamilyFont_fontVariationSettings = 7; public static final int FontFamilyFont_fontWeight = 8; public static final int FontFamilyFont_ttcIndex = 9; public static final int[] LoadingImageView = { 0x7f03007b, 0x7f030124, 0x7f030125 }; public static final int LoadingImageView_circleCrop = 0; public static final int LoadingImageView_imageAspectRatio = 1; public static final int LoadingImageView_imageAspectRatioAdjust = 2; public static final int[] RecyclerView = { 0x10100c4, 0x10100f1, 0x7f0300f8, 0x7f0300f9, 0x7f0300fa, 0x7f0300fb, 0x7f0300fc, 0x7f03013b, 0x7f0301af, 0x7f0301c5, 0x7f0301cb }; public static final int RecyclerView_android_orientation = 0; public static final int RecyclerView_android_descendantFocusability = 1; public static final int RecyclerView_fastScrollEnabled = 2; public static final int RecyclerView_fastScrollHorizontalThumbDrawable = 3; public static final int RecyclerView_fastScrollHorizontalTrackDrawable = 4; public static final int RecyclerView_fastScrollVerticalThumbDrawable = 5; public static final int RecyclerView_fastScrollVerticalTrackDrawable = 6; public static final int RecyclerView_layoutManager = 7; public static final int RecyclerView_reverseLayout = 8; public static final int RecyclerView_spanCount = 9; public static final int RecyclerView_stackFromEnd = 10; public static final int[] SignInButton = { 0x7f030056, 0x7f030097, 0x7f0301b1 }; public static final int SignInButton_buttonSize = 0; public static final int SignInButton_colorScheme = 1; public static final int SignInButton_scopeUris = 2; } }
65.09622
183
0.746819
27600d53c632af830b46a1f92336ca9d61aac623
17,680
/** */ package org.ecore.component.componentDefinition.util; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl; import org.eclipse.emf.ecore.EObject; import org.ecore.base.documentation.AbstractDocumentedElement; import org.ecore.component.componentDefinition.*; /** * <!-- begin-user-doc --> * The <b>Adapter Factory</b> for the model. * It provides an adapter <code>createXXX</code> method for each class of the model. * <!-- end-user-doc --> * @see org.ecore.component.componentDefinition.ComponentDefinitionPackage * @generated */ public class ComponentDefinitionAdapterFactory extends AdapterFactoryImpl { /** * The cached model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static ComponentDefinitionPackage modelPackage; /** * Creates an instance of the adapter factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ComponentDefinitionAdapterFactory() { if (modelPackage == null) { modelPackage = ComponentDefinitionPackage.eINSTANCE; } } /** * Returns whether this factory is applicable for the type of the object. * <!-- begin-user-doc --> * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model. * <!-- end-user-doc --> * @return whether this factory is applicable for the type of the object. * @generated */ @Override public boolean isFactoryForType(Object object) { if (object == modelPackage) { return true; } if (object instanceof EObject) { return ((EObject) object).eClass().getEPackage() == modelPackage; } return false; } /** * The switch that delegates to the <code>createXXX</code> methods. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ComponentDefinitionSwitch<Adapter> modelSwitch = new ComponentDefinitionSwitch<Adapter>() { @Override public Adapter caseComponentDefModel(ComponentDefModel object) { return createComponentDefModelAdapter(); } @Override public Adapter caseComponentDefinition(ComponentDefinition object) { return createComponentDefinitionAdapter(); } @Override public Adapter caseActivity(Activity object) { return createActivityAdapter(); } @Override public Adapter caseActivityExtension(ActivityExtension object) { return createActivityExtensionAdapter(); } @Override public Adapter caseInputHandler(InputHandler object) { return createInputHandlerAdapter(); } @Override public Adapter caseServiceRepoImport(ServiceRepoImport object) { return createServiceRepoImportAdapter(); } @Override public Adapter caseOutputPort(OutputPort object) { return createOutputPortAdapter(); } @Override public Adapter caseRequestPort(RequestPort object) { return createRequestPortAdapter(); } @Override public Adapter caseInputPort(InputPort object) { return createInputPortAdapter(); } @Override public Adapter caseAnswerPort(AnswerPort object) { return createAnswerPortAdapter(); } @Override public Adapter caseComponentPort(ComponentPort object) { return createComponentPortAdapter(); } @Override public Adapter caseComponentPortExtension(ComponentPortExtension object) { return createComponentPortExtensionAdapter(); } @Override public Adapter caseRequestHandler(RequestHandler object) { return createRequestHandlerAdapter(); } @Override public Adapter caseAbstractComponentElement(AbstractComponentElement object) { return createAbstractComponentElementAdapter(); } @Override public Adapter caseComponentSubNode(ComponentSubNode object) { return createComponentSubNodeAdapter(); } @Override public Adapter caseComponentSubNodeObserver(ComponentSubNodeObserver object) { return createComponentSubNodeObserverAdapter(); } @Override public Adapter caseInputPortLink(InputPortLink object) { return createInputPortLinkAdapter(); } @Override public Adapter caseRequestPortLink(RequestPortLink object) { return createRequestPortLinkAdapter(); } @Override public Adapter caseAbstractComponentLink(AbstractComponentLink object) { return createAbstractComponentLinkAdapter(); } @Override public Adapter caseNamedComponentElement(NamedComponentElement object) { return createNamedComponentElementAdapter(); } @Override public Adapter caseDerivedComponentElement(DerivedComponentElement object) { return createDerivedComponentElementAdapter(); } @Override public Adapter caseAbstractDocumentedElement(AbstractDocumentedElement object) { return createAbstractDocumentedElementAdapter(); } @Override public Adapter defaultCase(EObject object) { return createEObjectAdapter(); } }; /** * Creates an adapter for the <code>target</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param target the object to adapt. * @return the adapter for the <code>target</code>. * @generated */ @Override public Adapter createAdapter(Notifier target) { return modelSwitch.doSwitch((EObject) target); } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.ComponentDefModel <em>Component Def Model</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.ComponentDefModel * @generated */ public Adapter createComponentDefModelAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.ComponentDefinition <em>Component Definition</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.ComponentDefinition * @generated */ public Adapter createComponentDefinitionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.Activity <em>Activity</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.Activity * @generated */ public Adapter createActivityAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.ActivityExtension <em>Activity Extension</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.ActivityExtension * @generated */ public Adapter createActivityExtensionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.InputHandler <em>Input Handler</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.InputHandler * @generated */ public Adapter createInputHandlerAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.ServiceRepoImport <em>Service Repo Import</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.ServiceRepoImport * @generated */ public Adapter createServiceRepoImportAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.OutputPort <em>Output Port</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.OutputPort * @generated */ public Adapter createOutputPortAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.RequestPort <em>Request Port</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.RequestPort * @generated */ public Adapter createRequestPortAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.InputPort <em>Input Port</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.InputPort * @generated */ public Adapter createInputPortAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.AnswerPort <em>Answer Port</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.AnswerPort * @generated */ public Adapter createAnswerPortAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.ComponentPort <em>Component Port</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.ComponentPort * @generated */ public Adapter createComponentPortAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.ComponentPortExtension <em>Component Port Extension</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.ComponentPortExtension * @generated */ public Adapter createComponentPortExtensionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.RequestHandler <em>Request Handler</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.RequestHandler * @generated */ public Adapter createRequestHandlerAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.AbstractComponentElement <em>Abstract Component Element</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.AbstractComponentElement * @generated */ public Adapter createAbstractComponentElementAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.ComponentSubNode <em>Component Sub Node</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.ComponentSubNode * @generated */ public Adapter createComponentSubNodeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.ComponentSubNodeObserver <em>Component Sub Node Observer</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.ComponentSubNodeObserver * @generated */ public Adapter createComponentSubNodeObserverAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.InputPortLink <em>Input Port Link</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.InputPortLink * @generated */ public Adapter createInputPortLinkAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.RequestPortLink <em>Request Port Link</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.RequestPortLink * @generated */ public Adapter createRequestPortLinkAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.AbstractComponentLink <em>Abstract Component Link</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.AbstractComponentLink * @generated */ public Adapter createAbstractComponentLinkAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.NamedComponentElement <em>Named Component Element</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.NamedComponentElement * @generated */ public Adapter createNamedComponentElementAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.component.componentDefinition.DerivedComponentElement <em>Derived Component Element</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.component.componentDefinition.DerivedComponentElement * @generated */ public Adapter createDerivedComponentElementAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.ecore.base.documentation.AbstractDocumentedElement <em>Abstract Documented Element</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.ecore.base.documentation.AbstractDocumentedElement * @generated */ public Adapter createAbstractDocumentedElementAdapter() { return null; } /** * Creates a new adapter for the default case. * <!-- begin-user-doc --> * This default implementation returns null. * <!-- end-user-doc --> * @return the new adapter. * @generated */ public Adapter createEObjectAdapter() { return null; } } //ComponentDefinitionAdapterFactory
34.065511
161
0.724774
4d9fb21743aeb9350388adcd69e573a999c24f3b
2,954
/* * Original author: Daniel Jaschob <djaschob .at. uw.edu> * * Copyright 2019 University of Washington - Seattle, WA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.yeastrc.limelight.limelight_webapp.cached_data_in_file; import java.io.File; /** * Parameters to CachedDataInFileMgmt_WriteFile_Async * * Package Private * */ class CachedDataInFileMgmt_WriteFile_Async_Parameters { private byte[] webservice_Request_Data; private byte[] webservice_Response_Data; private File controllerPath_Dir; private File subdir_1; private File subdir_2; private File cachedDataFile_Webservice_Request_File; private File cachedDataFile_Webservice_Response_File; private File cachedDataFile_Done_File; public byte[] getWebservice_Request_Data() { return webservice_Request_Data; } public void setWebservice_Request_Data(byte[] webservice_Request_Data) { this.webservice_Request_Data = webservice_Request_Data; } public byte[] getWebservice_Response_Data() { return webservice_Response_Data; } public void setWebservice_Response_Data(byte[] webservice_Response_Data) { this.webservice_Response_Data = webservice_Response_Data; } public File getCachedDataFile_Webservice_Request_File() { return cachedDataFile_Webservice_Request_File; } public void setCachedDataFile_Webservice_Request_File(File cachedDataFile_Webservice_Request_File) { this.cachedDataFile_Webservice_Request_File = cachedDataFile_Webservice_Request_File; } public File getCachedDataFile_Webservice_Response_File() { return cachedDataFile_Webservice_Response_File; } public void setCachedDataFile_Webservice_Response_File(File cachedDataFile_Webservice_Response_File) { this.cachedDataFile_Webservice_Response_File = cachedDataFile_Webservice_Response_File; } public File getCachedDataFile_Done_File() { return cachedDataFile_Done_File; } public void setCachedDataFile_Done_File(File cachedDataFile_Done_File) { this.cachedDataFile_Done_File = cachedDataFile_Done_File; } public File getSubdir_1() { return subdir_1; } public void setSubdir_1(File subdir_1) { this.subdir_1 = subdir_1; } public File getSubdir_2() { return subdir_2; } public void setSubdir_2(File subdir_2) { this.subdir_2 = subdir_2; } public File getControllerPath_Dir() { return controllerPath_Dir; } public void setControllerPath_Dir(File controllerPath_Dir) { this.controllerPath_Dir = controllerPath_Dir; } }
32.461538
103
0.803995
c877174107836b0f0d0501ce0a5ba001d8133b1e
571
package com.dao; import com.entity.Customer; import com.entity.User; import java.util.List; /** * Created by yangzhe on 2017/5/2. */ public interface CustomerDao extends BaseDao<Customer> { // public void add(Customer customer); // public List<Customer> findCustomers(); // public Customer findOne(Integer cid); // public void delete(Customer customer); // public void updata(Customer customer); public Integer findCount(); public List<Customer> findPage(Integer begin,Integer pageSize); List<Customer> findCondition(Customer customer); }
27.190476
67
0.728546
cbfd6571ec22ab91e49ca8fbd2915b1aab471cc8
16,878
package ai.verta.modeldb; import static ai.verta.modeldb.utils.TestConstants.RESOURCE_OWNER_ID; import ai.verta.modeldb.authservice.AuthService; import ai.verta.modeldb.authservice.AuthServiceUtils; import ai.verta.modeldb.authservice.PublicAuthServiceUtils; import ai.verta.modeldb.authservice.PublicRoleServiceUtils; import ai.verta.modeldb.authservice.RoleService; import ai.verta.modeldb.authservice.RoleServiceUtils; import ai.verta.modeldb.utils.ModelDBUtils; import ai.verta.modeldb.versioning.DeleteRepositoryRequest; import ai.verta.modeldb.versioning.GetRepositoryRequest; import ai.verta.modeldb.versioning.ListRepositoriesRequest; import ai.verta.modeldb.versioning.Pagination; import ai.verta.modeldb.versioning.Repository; import ai.verta.modeldb.versioning.RepositoryIdentification; import ai.verta.modeldb.versioning.RepositoryNamedIdentification; import ai.verta.modeldb.versioning.SetRepository; import ai.verta.modeldb.versioning.SetRepository.Response; import ai.verta.modeldb.versioning.VersioningServiceGrpc; import ai.verta.modeldb.versioning.VersioningServiceGrpc.VersioningServiceBlockingStub; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.Status.Code; import io.grpc.StatusRuntimeException; import io.grpc.inprocess.InProcessChannelBuilder; import io.grpc.inprocess.InProcessServerBuilder; import io.grpc.testing.GrpcCleanupRule; import java.io.IOException; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.runners.MethodSorters; @RunWith(JUnit4.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class RepositoryTest { private static final Logger LOGGER = LogManager.getLogger(RepositoryTest.class); public static final String NAME = "repository_name"; public static final String NAME_2 = "repository_name2"; /** * This rule manages automatic graceful shutdown for the registered servers and channels at the * end of test. */ @Rule public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); private ManagedChannel channel = null; private ManagedChannel client2Channel = null; private ManagedChannel authServiceChannel = null; private static String serverName = InProcessServerBuilder.generateName(); private static InProcessServerBuilder serverBuilder = InProcessServerBuilder.forName(serverName).directExecutor(); private static InProcessChannelBuilder channelBuilder = InProcessChannelBuilder.forName(serverName).directExecutor(); private static InProcessChannelBuilder client2ChannelBuilder = InProcessChannelBuilder.forName(serverName).directExecutor(); private static AuthClientInterceptor authClientInterceptor; private static App app; @SuppressWarnings("unchecked") @BeforeClass public static void setServerAndService() throws Exception { Map<String, Object> propertiesMap = ModelDBUtils.readYamlProperties(System.getenv(ModelDBConstants.VERTA_MODELDB_CONFIG)); Map<String, Object> testPropMap = (Map<String, Object>) propertiesMap.get("test"); Map<String, Object> databasePropMap = (Map<String, Object>) testPropMap.get("test-database"); app = App.getInstance(); AuthService authService = new PublicAuthServiceUtils(); RoleService roleService = new PublicRoleServiceUtils(authService); Map<String, Object> authServicePropMap = (Map<String, Object>) propertiesMap.get(ModelDBConstants.AUTH_SERVICE); if (authServicePropMap != null) { String authServiceHost = (String) authServicePropMap.get(ModelDBConstants.HOST); Integer authServicePort = (Integer) authServicePropMap.get(ModelDBConstants.PORT); app.setAuthServerHost(authServiceHost); app.setAuthServerPort(authServicePort); authService = new AuthServiceUtils(); roleService = new RoleServiceUtils(authService); } App.initializeServicesBaseOnDataBase( serverBuilder, databasePropMap, propertiesMap, authService, roleService); serverBuilder.intercept(new ModelDBAuthInterceptor()); Map<String, Object> testUerPropMap = (Map<String, Object>) testPropMap.get("testUsers"); if (testUerPropMap != null && testUerPropMap.size() > 0) { authClientInterceptor = new AuthClientInterceptor(testPropMap); channelBuilder.intercept(authClientInterceptor.getClient1AuthInterceptor()); client2ChannelBuilder.intercept(authClientInterceptor.getClient2AuthInterceptor()); } } @AfterClass public static void removeServerAndService() { App.initiateShutdown(0); } @After public void clientClose() { if (!channel.isShutdown()) { channel.shutdownNow(); } if (!client2Channel.isShutdown()) { client2Channel.shutdownNow(); } if (app.getAuthServerHost() != null && app.getAuthServerPort() != null) { if (!authServiceChannel.isShutdown()) { authServiceChannel.shutdownNow(); } } } @Before public void initializeChannel() throws IOException { grpcCleanup.register(serverBuilder.build().start()); channel = grpcCleanup.register(channelBuilder.maxInboundMessageSize(1024).build()); client2Channel = grpcCleanup.register(client2ChannelBuilder.maxInboundMessageSize(1024).build()); if (app.getAuthServerHost() != null && app.getAuthServerPort() != null) { authServiceChannel = ManagedChannelBuilder.forTarget(app.getAuthServerHost() + ":" + app.getAuthServerPort()) .usePlaintext() .intercept(authClientInterceptor.getClient1AuthInterceptor()) .build(); } } public static Long createRepository( VersioningServiceBlockingStub versioningServiceBlockingStub, String repoName) { SetRepository setRepository = SetRepository.newBuilder() .setId( RepositoryIdentification.newBuilder() .setNamedId( RepositoryNamedIdentification.newBuilder().setName(repoName).build()) .build()) .setRepository(Repository.newBuilder().setName(repoName)) .build(); Response result = versioningServiceBlockingStub.createRepository(setRepository); return result.getRepository().getId(); } @Test public void createDeleteRepositoryTest() { LOGGER.info("Create and delete repository test start................................"); VersioningServiceBlockingStub versioningServiceBlockingStub = VersioningServiceGrpc.newBlockingStub(channel); long id = createRepository(versioningServiceBlockingStub, NAME); DeleteRepositoryRequest deleteRepository = DeleteRepositoryRequest.newBuilder() .setRepositoryId(RepositoryIdentification.newBuilder().setRepoId(id)) .build(); DeleteRepositoryRequest.Response deleteResult = versioningServiceBlockingStub.deleteRepository(deleteRepository); Assert.assertTrue(deleteResult.getStatus()); LOGGER.info("Create and delete repository test end................................"); } @Test public void createDeleteRepositoryNegativeTest() { LOGGER.info("Create and delete repository negative test start................................"); VersioningServiceBlockingStub versioningServiceBlockingStub = VersioningServiceGrpc.newBlockingStub(channel); long id = createRepository(versioningServiceBlockingStub, NAME); try { SetRepository setRepository = SetRepository.newBuilder() .setId( RepositoryIdentification.newBuilder() .setNamedId( RepositoryNamedIdentification.newBuilder() .setWorkspaceName("test1verta_gmail_com") .setName(NAME_2) .build()) .build()) .setRepository(Repository.newBuilder().setName(NAME)) .build(); versioningServiceBlockingStub.createRepository(setRepository); Assert.fail(); } catch (StatusRuntimeException e) { Assert.assertTrue( Code.PERMISSION_DENIED.equals(e.getStatus().getCode()) || Code.ALREADY_EXISTS.equals(e.getStatus().getCode())); } DeleteRepositoryRequest deleteRepository = DeleteRepositoryRequest.newBuilder() .setRepositoryId(RepositoryIdentification.newBuilder().setRepoId(id)) .build(); DeleteRepositoryRequest.Response deleteResult = versioningServiceBlockingStub.deleteRepository(deleteRepository); Assert.assertTrue(deleteResult.getStatus()); try { deleteRepository = DeleteRepositoryRequest.newBuilder() .setRepositoryId(RepositoryIdentification.newBuilder().setRepoId(id)) .build(); versioningServiceBlockingStub.deleteRepository(deleteRepository); Assert.fail(); } catch (StatusRuntimeException e) { Assert.assertEquals(Code.NOT_FOUND, e.getStatus().getCode()); } LOGGER.info("Create and delete repository negative test end................................"); } @Test public void updateRepositoryByNameTest() { LOGGER.info("Update repository by name test start................................"); VersioningServiceBlockingStub versioningServiceBlockingStub = VersioningServiceGrpc.newBlockingStub(channel); long id = createRepository(versioningServiceBlockingStub, NAME); SetRepository setRepository = SetRepository.newBuilder() .setId( RepositoryIdentification.newBuilder() .setNamedId(RepositoryNamedIdentification.newBuilder().setName(NAME).build()) .build()) .setRepository(Repository.newBuilder().setName(NAME_2)) .build(); SetRepository.Response result = versioningServiceBlockingStub.updateRepository(setRepository); Assert.assertTrue(result.hasRepository()); Assert.assertEquals(NAME_2, result.getRepository().getName()); GetRepositoryRequest getRepositoryRequest = GetRepositoryRequest.newBuilder() .setId( RepositoryIdentification.newBuilder() .setNamedId(RepositoryNamedIdentification.newBuilder().setName(NAME_2))) .build(); GetRepositoryRequest.Response getByNameResult = versioningServiceBlockingStub.getRepository(getRepositoryRequest); Assert.assertEquals( "Repository Id not match with expected repository Id", id, getByNameResult.getRepository().getId()); Assert.assertEquals( "Repository name not match with expected repository name", NAME_2, getByNameResult.getRepository().getName()); if (app.getAuthServerHost() != null && app.getAuthServerPort() != null) { Assert.assertEquals(RESOURCE_OWNER_ID, getByNameResult.getRepository().getOwner()); } DeleteRepositoryRequest deleteRepository = DeleteRepositoryRequest.newBuilder() .setRepositoryId(RepositoryIdentification.newBuilder().setRepoId(id)) .build(); DeleteRepositoryRequest.Response deleteResult = versioningServiceBlockingStub.deleteRepository(deleteRepository); Assert.assertTrue(deleteResult.getStatus()); LOGGER.info("Update repository by name test end................................"); } @Test public void getRepositoryByIdTest() { LOGGER.info("Get repository by Id test start................................"); VersioningServiceBlockingStub versioningServiceBlockingStub = VersioningServiceGrpc.newBlockingStub(channel); long id = createRepository(versioningServiceBlockingStub, NAME); // check id GetRepositoryRequest getRepositoryRequest = GetRepositoryRequest.newBuilder() .setId(RepositoryIdentification.newBuilder().setRepoId(id).build()) .build(); GetRepositoryRequest.Response getByIdResult = versioningServiceBlockingStub.getRepository(getRepositoryRequest); Assert.assertEquals( "Repository Id not match with expected repository Id", id, getByIdResult.getRepository().getId()); DeleteRepositoryRequest deleteRepository = DeleteRepositoryRequest.newBuilder() .setRepositoryId(RepositoryIdentification.newBuilder().setRepoId(id)) .build(); DeleteRepositoryRequest.Response deleteResult = versioningServiceBlockingStub.deleteRepository(deleteRepository); Assert.assertTrue(deleteResult.getStatus()); LOGGER.info("Get repository by Id test end................................"); } @Test public void getRepositoryByNameTest() { LOGGER.info("Get repository by name test start................................"); VersioningServiceBlockingStub versioningServiceBlockingStub = VersioningServiceGrpc.newBlockingStub(channel); long id = createRepository(versioningServiceBlockingStub, NAME); GetRepositoryRequest getRepositoryRequest = GetRepositoryRequest.newBuilder() .setId( RepositoryIdentification.newBuilder() .setNamedId(RepositoryNamedIdentification.newBuilder().setName(NAME))) .build(); GetRepositoryRequest.Response getByNameResult = versioningServiceBlockingStub.getRepository(getRepositoryRequest); Assert.assertEquals( "Repository name not match with expected repository name", NAME, getByNameResult.getRepository().getName()); if (app.getAuthServerHost() != null && app.getAuthServerPort() != null) { Assert.assertEquals(RESOURCE_OWNER_ID, getByNameResult.getRepository().getOwner()); } DeleteRepositoryRequest deleteRepository = DeleteRepositoryRequest.newBuilder() .setRepositoryId(RepositoryIdentification.newBuilder().setRepoId(id)) .build(); DeleteRepositoryRequest.Response deleteResult = versioningServiceBlockingStub.deleteRepository(deleteRepository); Assert.assertTrue(deleteResult.getStatus()); LOGGER.info("Get repository by name test end................................"); } @Test public void listRepositoryTest() { LOGGER.info("List repository test start................................"); VersioningServiceBlockingStub versioningServiceBlockingStub = VersioningServiceGrpc.newBlockingStub(channel); long repoId1 = createRepository(versioningServiceBlockingStub, NAME); long repoId2 = createRepository(versioningServiceBlockingStub, NAME_2); Long[] repoIds = new Long[2]; repoIds[0] = repoId1; repoIds[1] = repoId2; ListRepositoriesRequest listRepositoriesRequest = ListRepositoriesRequest.newBuilder().build(); ListRepositoriesRequest.Response listRepositoriesResponse = versioningServiceBlockingStub.listRepositories(listRepositoriesRequest); Assert.assertEquals( "Repository count not match with expected repository count", 2, listRepositoriesResponse.getRepositoriesCount()); Assert.assertEquals( "Repository name not match with expected repository name", NAME_2, listRepositoriesResponse.getRepositories(0).getName()); Assert.assertEquals( "Repository name not match with expected repository name", NAME, listRepositoriesResponse.getRepositories(1).getName()); listRepositoriesRequest = ListRepositoriesRequest.newBuilder() .setPagination(Pagination.newBuilder().setPageLimit(1).setPageNumber(1).build()) .build(); listRepositoriesResponse = versioningServiceBlockingStub.listRepositories(listRepositoriesRequest); Assert.assertEquals( "Repository count not match with expected repository count", 1, listRepositoriesResponse.getRepositoriesCount()); Assert.assertEquals( "Repository name not match with expected repository name", NAME_2, listRepositoriesResponse.getRepositories(0).getName()); for (long repoId : repoIds) { DeleteRepositoryRequest deleteRepository = DeleteRepositoryRequest.newBuilder() .setRepositoryId(RepositoryIdentification.newBuilder().setRepoId(repoId)) .build(); DeleteRepositoryRequest.Response deleteResult = versioningServiceBlockingStub.deleteRepository(deleteRepository); Assert.assertTrue(deleteResult.getStatus()); } LOGGER.info("List repository test end................................"); } }
41.367647
100
0.710333
129fcddee318d8a831147d116c4c70b212da9827
4,424
package norswap.autumn; import norswap.autumn.positions.LineMap; import norswap.autumn.util.ArrayStack; import norswap.utils.Strings; /** * A stack of {@link ParserCallFrame} representing parser invocations at a certain position. */ public final class ParserCallStack extends ArrayStack<ParserCallFrame> { // --------------------------------------------------------------------------------------------- /** * Pushes a new call frame onto the stack. */ public void push (Parser parser, int position) { push(new ParserCallFrame(parser, position)); } // --------------------------------------------------------------------------------------------- private static final int MIN_LINE_WIDTH = 4; private static final int MIN_COLUMN_WIDTH = 3; /** * Appends a nicely formatted string representation of the parser call stack to {@code b}, * indented with {@code indent} tabs. The appended content never ends with a newline. * * @param map If non-null, used to translate input positions in terms of lines and columns. * * @param onlyRules If true, only parsers which are are grammar rules (i.e. have a non-null * {@link Parser#rule()}) will be included in the representation. * * @param filePath If non-null, appended in front of the input positions position in order for * them to be become clickable in IntelliJ (and potentially other editors). This is only useful * if a {@code map} is also supplied. Note that in IntelliJ, only absolute paths enable linking * to colums in addition to lines. */ public void appendTo ( StringBuilder b, int indent, LineMap map, boolean onlyRules, String filePath) { // Use spaces and not tabs, as tabs inhibit hyperlinking of the file path in IntelliJ. String tabs = Strings.repeat(' ', indent * 4); for (ParserCallFrame frame: this) if (!onlyRules || frame.parser.rule() != null) { b.append(tabs); b.append("at "); if (filePath != null) b .append(filePath).append(":") .append(LineMap.string(map, frame.position)); else b.append(LineMap.string(map, frame.position, MIN_LINE_WIDTH, MIN_COLUMN_WIDTH)); b.append(" in "); b.append(frame.parser); b.append("\n"); } if (!isEmpty()) Strings.pop(b, 1); } // --------------------------------------------------------------------------------------------- /** * Returns a string representation of this call stack, as per {@link #appendTo(StringBuilder, * int, LineMap, boolean, String)} (with no indentation). * * @param map If non-null, used to translate input positions in terms of lines and columns. * * @param onlyRules If true, only parsers which are are grammar rules (i.e. have a non-null * {@link Parser#rule()}) will be included in the representation. * * @param filePath If non-null, appended in front of the input positions position in order for * them to be become clickable in IntelliJ (and potentially other editors). This is only useful * if a {@code map} is also supplied. Note that in IntelliJ, only absolute paths enable linking * to colums in addition to lines. */ public String toString (LineMap map, boolean onlyRules, String filePath) { StringBuilder b = new StringBuilder(); appendTo(b, 0, map, onlyRules, filePath); return b.toString(); } // --------------------------------------------------------------------------------------------- /** * Returns a string representation of this call stack, as per {@link #appendTo(StringBuilder, * int, LineMap, boolean, String)} (with no identation, and no line map conversion). */ @Override public String toString() { StringBuilder b = new StringBuilder(); appendTo(b, 0, null, false, null); return b.toString(); } // --------------------------------------------------------------------------------------------- @Override public ParserCallStack clone() { return (ParserCallStack) super.clone(); } // --------------------------------------------------------------------------------------------- }
39.855856
100
0.54679
1c7796bec1f54eae330eb71d51a91b34f56d70e9
650
package lista2.atividade8; import java.util.Scanner; public class AppTriangulo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Triangulo t = new Triangulo(); System.out.println("Digite 3 valores:"); float x = sc.nextFloat(); float y = sc.nextFloat(); float z = sc.nextFloat(); sc.close(); if ((x+y) > z && (x+z) > y && (y+z) > x) { t.setLados(x, y, z); System.out.println("Forma um triangulo: " + t.getTipo()); } else System.out.println("Não forma um triangulo"); } }
28.26087
70
0.516923
f37da29dd21b04fec11731fbde485756e6b0d5ae
4,474
package pages; import org.junit.Assert; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.FindBy; import utils.BasePage; public class HomePage extends BasePage { // Elements @FindBy(xpath = "//p//button[@type=\"submit\"]") private WebElement calculateButton; @FindBy(xpath = "//a[@href='/privacy']") private WebElement privacylink; @FindBy(xpath = "//p[@id='resultDiv']") private WebElement resulttext; @FindBy(xpath = "//a[@href='/terms']") private WebElement termslink; @FindBy(xpath = "//div/h1[@class=\"margin-base-vertical text-center\"]") private WebElement h1Title; @FindBy(xpath = "//input[@id=\"number\"]") private WebElement inputFieldempty; @FindBy(xpath = "//a[contains(@href,'source=qa')]") private WebElement qxF2serviceslink; @FindBy(xpath = "//p[@id='resultDiv']") private WebElement factresultdiv; // Constructor public HomePage(WebDriver driver, WebDriverWait wait) { super(driver, wait); } // Methods public HomePage clickCalculate() { log.debug("clickCalculate();"); waitForElement(calculateButton); clickOnElement(calculateButton); return new HomePage(driver,wait); } public HomePage validateHomePageTitleString(String pageTitleString) { log.debug("validateHomePageTitleString();"); waitForElement(h1Title); Assert.assertTrue( "validatePageTitleString method failed due to string: \"" + h1Title.getText() + "\" not matching expected string: \"" + pageTitleString + "\"", getTextFromElement(h1Title).toLowerCase().contains(pageTitleString.toLowerCase())); return new HomePage(driver, wait); } public HomePage validateHomePageCaculatebuttonString(String submitButtonString) { log.debug("validateHomePageCaculatebuttonString();"); waitForElement(calculateButton); Assert.assertTrue( "validatePageCaculatebuttonString method failed due to string: \"" + calculateButton.getText() + "\" not matching expected string: \"" + submitButtonString + "\"", getTextFromElement(calculateButton).toLowerCase().contains(submitButtonString.toLowerCase())); return new HomePage(driver, wait); } public HomePage validateHomePagePrivacyLinkString(String privacyLinkText) { log.debug("validateHomePagePrivacyLinkString();"); waitForElement(privacylink); Assert.assertTrue( "ValidatePrivacyLinkString method failed due to string: \"" + privacylink.getText() + "\" not matching expected string: \"" + privacyLinkText + "\"", getTextFromElement(privacylink).toLowerCase().contains(privacyLinkText.toLowerCase())); return new HomePage(driver, wait); } public HomePage validateHomePageTermsLinkString(String termsLinkText) { log.debug("validateHomePageTermsLinkString();"); waitForElement(termslink); Assert.assertTrue( "validateTermsLinkString method failed due to string: \"" + termslink.getText() + "\" not matching expected string: \"" + termsLinkText + "\"", getTextFromElement(termslink).toLowerCase().contains(termsLinkText.toLowerCase())); return new HomePage(driver, wait); } public HomePage validateHomePageqxFLinkString(String qxFLinkText) { log.debug("validateHomePageqxFLinkString();"); waitForElement(qxF2serviceslink); Assert.assertTrue( "validateqxFLinkString method failed due to string: \"" + qxF2serviceslink.getText() + "\" not matching expected string: \"" + qxFLinkText + "\"", getTextFromElement(qxF2serviceslink).toLowerCase().contains(qxFLinkText.toLowerCase())); return new HomePage(driver, wait); } public HomePage clickInputFieldAndEnterInteger(int inputNumber) { log.debug("clickInputFieldAndEnterInteger();"); enterText(inputFieldempty, String.valueOf(inputNumber)); return new HomePage(driver, wait); } public HomePage clickInputFieldAndEnterString(String inputString) { log.debug("clickInputFieldAndEnterString();"); enterText(inputFieldempty, inputString); return new HomePage(driver, wait); } public HomePage validateFactorialResults(String factorialResults) { log.debug("validateFactorialResults();"); waitForElement(factresultdiv); Assert.assertTrue( "validateFactorialResults method failed due to: \"" + factresultdiv.getText() + "\" not matching expected: \"" + factorialResults + "\"", getTextFromElement(factresultdiv).toLowerCase().contains(factorialResults.toLowerCase())); return new HomePage(driver, wait); } }
37.596639
98
0.746312
b109c62cf0e51d0f7cf05fc2ad22d2565b3d9cac
57
package org.itt.data.list; public class LinkedList { }
9.5
26
0.736842
d04b2078bccee90c9feb7a3205a2287e4330ef02
9,224
package org.compiere.model; import de.metas.cache.CCache; import de.metas.logging.LogManager; import de.metas.util.StringUtils; import org.adempiere.ad.trx.api.ITrx; import org.adempiere.exceptions.AdempiereException; import org.adempiere.exceptions.DBException; import org.adempiere.service.ISysConfigBL; import org.compiere.util.DB; import org.slf4j.Logger; import javax.annotation.Nullable; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import java.util.function.Supplier; /** * System Configuration * * @author Armen Rizal * @author Teo Sarca, SC ARHIPAC SERVICE SRL <li>BF [ 1885496 ] Performance NEEDS * @version $Id: MSysConfig.java,v 1.5 2005/11/28 11:56:45 armen Exp $ * Contributor: Carlos Ruiz - globalqss - [ 1800371 ] System Configurator Enhancements * @deprecated Please use {@link ISysConfigBL} */ @Deprecated public class MSysConfig extends X_AD_SysConfig { /** * */ private static final long serialVersionUID = -5271070197457739666L; public MSysConfig(final Properties ctx, final int AD_SysConfig_ID, final String trxName) { super(ctx, AD_SysConfig_ID, trxName); } public MSysConfig(final Properties ctx, final ResultSet rs, final String trxName) { super(ctx, rs, trxName); } /** * Static Logger */ private static final Logger s_log = LogManager.getLogger(MSysConfig.class); /** * Cache */ private static final CCache<String, String> s_cache = new CCache<>(Table_Name, 40, 0); // expire=never private static final String NO_Value = ""; // NOTE: new instance to make sure it's unique /** * Get system configuration property of type string */ @Nullable public static String getValue(final String Name, @Nullable final String defaultValue) { return getValue(Name, defaultValue, 0, 0); } /** * Get system configuration property of type string */ @Nullable public static String getValue(final String Name) { return getValue(Name, null); } /** * Get system configuration property of type int */ public static int getIntValue(final String Name, final int defaultValue) { final String s = getValue(Name); if (s == null) return defaultValue; if (s.length() == 0) return defaultValue; // try { return Integer.parseInt(s); } catch (final NumberFormatException e) { s_log.error("getIntValue (" + Name + ") = " + s, e); } return defaultValue; } /** * Get system configuration property of type boolean */ public static boolean getBooleanValue(final String Name, final boolean defaultValue) { final String s = getValue(Name); if (s == null || s.length() == 0) return defaultValue; return StringUtils.toBoolean(s); } /** * Get system configuration property of type string */ @Nullable public static String getValue(final String Name, final int AD_Client_ID) { return getValue(Name, null, AD_Client_ID, 0); } /** * Get system configuration property of type int */ public static int getIntValue(final String Name, final int defaultValue, final int AD_Client_ID) { final String s = getValue(Name, AD_Client_ID); if (s == null) return defaultValue; if (s.length() == 0) return defaultValue; // try { return Integer.parseInt(s); } catch (final NumberFormatException e) { s_log.error("getIntValue (" + Name + ") = " + s, e); } return defaultValue; } /** * Get system configuration property of type boolean */ public static boolean getBooleanValue(final String Name, final boolean defaultValue, final int AD_Client_ID) { final String s = getValue(Name, AD_Client_ID); if (s == null || s.length() == 0) return defaultValue; return StringUtils.toBoolean(s); } /** * Get client configuration property of type string */ @Nullable public static String getValue(final String Name, @Nullable final String defaultValue, final int AD_Client_ID, final int AD_Org_ID) { // // Get/retrieve the sysconfig's value final String key = "" + AD_Client_ID + "_" + AD_Org_ID + "_" + Name; final String value = s_cache.get(key, (Supplier<String>)() -> { final String valueRetrieved = retrieveSysConfigValue(Name, AD_Client_ID, AD_Org_ID); return valueRetrieved == null ? NO_Value : valueRetrieved; }); // // If we got no value, return the defaultValue provided. // NOTE: we don't expect "value" to be null, but it would be the same decission as for NO_Value. if (value == null || value == NO_Value) { return defaultValue; } return value; } /** * @return sysconfig's value or <code>null</code> if it was not found */ @Nullable private static String retrieveSysConfigValue(final String Name, final int AD_Client_ID, final int AD_Org_ID) { final String sql = "SELECT Value FROM AD_SysConfig" + " WHERE Name=? AND AD_Client_ID IN (0, ?) AND AD_Org_ID IN (0, ?) AND IsActive='Y'" + " ORDER BY AD_Client_ID DESC, AD_Org_ID DESC"; final Object[] sqlParams = new Object[] { Name, AD_Client_ID, AD_Org_ID }; PreparedStatement pstmt = null; ResultSet rs = null; String value = null; try { pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None); DB.setParameters(pstmt, sqlParams); rs = pstmt.executeQuery(); if (rs.next()) { value = rs.getString(1); } } catch (final SQLException sqlEx) { final DBException ex = new DBException(sqlEx, sql, sqlParams); s_log.error("Failed retrieving the sysconfig value", ex); value = null; } finally { DB.close(rs, pstmt); } return value; } /** * Get system configuration property of type string */ @Nullable private static String getValue(final String Name, final int AD_Client_ID, final int AD_Org_ID) { return getValue(Name, null, AD_Client_ID, AD_Org_ID); } /** * Get system configuration property of type int */ public static int getIntValue(final String Name, final int defaultValue, final int AD_Client_ID, final int AD_Org_ID) { final String s = getValue(Name, AD_Client_ID, AD_Org_ID); if (s == null) return defaultValue; if (s.length() == 0) return defaultValue; // try { return Integer.parseInt(s); } catch (final NumberFormatException e) { s_log.error("getIntValue (" + Name + ") = " + s, e); } return defaultValue; } @Override protected boolean beforeSave(final boolean newRecord) { log.debug("New={}", newRecord); if (getAD_Client_ID() > 0 || getAD_Org_ID() > 0) { // Get the configuration level from the System Record String configLevel = null; String sql = "SELECT ConfigurationLevel FROM AD_SysConfig WHERE Name=? AND AD_Client_ID = 0 AND AD_Org_ID = 0 AND IsActive='Y'"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setString(1, getName()); rs = pstmt.executeQuery(); if (rs.next()) configLevel = rs.getString(1); } catch (final SQLException e) { throw new DBException(e, sql); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } if (configLevel == null) { // not found for system // if saving an org parameter - look config in client if (getAD_Org_ID() > 0) { // Get the configuration level from the System Record sql = "SELECT ConfigurationLevel FROM AD_SysConfig WHERE Name=? AND AD_Client_ID = ? AND AD_Org_ID = 0"; try { pstmt = DB.prepareStatement(sql, null); pstmt.setString(1, getName()); pstmt.setInt(2, getAD_Client_ID()); rs = pstmt.executeQuery(); if (rs.next()) configLevel = rs.getString(1); } catch (final SQLException e) { s_log.error("getValue", e); } finally { DB.close(rs, pstmt); } } } if (configLevel != null) { setConfigurationLevel(configLevel); // Disallow saving org parameter if the system parameter is marked as 'S' or 'C' if (getAD_Org_ID()> 0 && (configLevel.equals(MSysConfig.CONFIGURATIONLEVEL_System) || configLevel.equals(MSysConfig.CONFIGURATIONLEVEL_Client))) { throw new AdempiereException("Can't Save Org Level. This is a system or client parameter, you can't save it as organization parameter"); } // Disallow saving client parameter if the system parameter is marked as 'S' if (getAD_Client_ID() > 0 && configLevel.equals(MSysConfig.CONFIGURATIONLEVEL_System)) { throw new AdempiereException("Can't Save Client Level. This is a system parameter, you can't save it as client parameter"); } } else { // fix possible wrong config level if (getAD_Org_ID() > 0) setConfigurationLevel(CONFIGURATIONLEVEL_Organization); else if (getAD_Client_ID() > 0 && MSysConfig.CONFIGURATIONLEVEL_System.equals(getConfigurationLevel())) setConfigurationLevel(CONFIGURATIONLEVEL_Client); } } return true; } @Override public String toString() { return getClass().getSimpleName() + "[" + get_ID() + ", " + getName() + "=" + getValue() + ", ConfigurationLevel=" + getConfigurationLevel() + ", Client|Org=" + getAD_Client_ID() + "|" + getAD_Org_ID() + ", EntityType=" + getEntityType() + "]"; } }
25.765363
141
0.680616
3ece184286d28588f95455f6bdb878c7ce8e54f7
334
package test.activator; import org.osgi.framework.*; public class Activator11 implements BundleActivator { @Override public void start(BundleContext context) throws Exception {/**/} @Override public void stop(BundleContext context) throws Exception {/**/} public void modded(BundleContext context) throws Exception {/**/} }
22.266667
66
0.763473
2a3485fd7fd03b03f4d37c61c352b4d0c4ebb191
4,448
/* * BSD 3-Clause License - imaJe * * Copyright (c) 2016, Michael Ludwig * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * 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. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * 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 HOLDER 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. */ package com.lhkbob.imaje.data.types; /** * BinaryRepresentation * ==================== * * A binary representation is an interface for mapping a bit format of fixed bit size (up to 64 * bits) to a Java `double` so that it can be used in calculations effectively before being turned * back into the particular bit representation. The conversion to and from bits to `double` can be * lossy and should preserve as much value and correctness as possible. This is similar to the loss * that occurs when casting between a `double` and the other primitive types like `float` or `int`. * * Some binary representations have minimum and maximum values, in which case `double` values * outside of that range will be clamped to a valid value before being converted into a bit pattern. * * BinaryRepresentation implementations should be immutable and thread-safe. * * @author Michael Ludwig */ public interface BinaryRepresentation { /** * @return The number of bits required to represent the number */ int getBitSize(); /** * @return The maximum value representable by this instance */ double getMaxValue(); /** * @return The minimum value representable by this instance */ double getMinValue(); /** * Get whether or not this representation is a floating point representation that has an exponent * and mantissa instead of a fixed point representation that uses a constant scale for * normalization. Floating point representations have different decimal resolutions depending on * the magnitude of the value being represented. * * @return True if the representation is floating point */ boolean isFloatingPoint(); /** * @return Whether or not the representation only stores unsigned values, i.e. {@link * #getMinValue()} returns 0 */ boolean isUnsigned(); /** * Convert the given real number to the closest representable value as its bit pattern. The * returned bit field will have representation-dependent bits between `0` and `getBitSize() - 1`, * and all higher bits will be set to 0. If `value` is outside the range defined by {@link * #getMaxValue()} and {@link #getMinValue()} then the value is clamped to that range before being * converted into a bit field. * * @param value * The number to convert to bit representation * @return The binary representation closest to value */ long toBits(double value); /** * Convert the given bit field to a Java `double` based on the binary representation this instance * describes. The bits from `0` to `getBitSize() - 1` are used, higher bits are ignored. * * @param bits * The bit field to convert to a real number * @return The real number closes to the value represented by `bits` in this representation */ double toNumericValue(long bits); }
41.962264
100
0.733588
550339b0a2a6fd3dbeb100921f7afb66ce4871fb
59
package com.alibaba.csp.sentinel.dashboard.rule.zookeeper;
29.5
58
0.847458
22685b3400d0523f07a324f3c997201bc8146b39
19,936
/* SPDX-License-Identifier: Apache 2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.accessservices.connectedasset.handlers; import org.odpi.openmetadata.accessservices.connectedasset.converters.TypeConverter; import org.odpi.openmetadata.accessservices.connectedasset.ffdc.exceptions.InvalidParameterException; import org.odpi.openmetadata.accessservices.connectedasset.ffdc.exceptions.UnrecognizedAssetGUIDException; import org.odpi.openmetadata.accessservices.connectedasset.ffdc.exceptions.UnrecognizedConnectionGUIDException; import org.odpi.openmetadata.accessservices.connectedasset.ffdc.exceptions.UnrecognizedGUIDException; import org.odpi.openmetadata.accessservices.connectedasset.mappers.*; import org.odpi.openmetadata.frameworks.connectors.ffdc.PropertyServerException; import org.odpi.openmetadata.frameworks.connectors.ffdc.UserNotAuthorizedException; import org.odpi.openmetadata.frameworks.connectors.properties.beans.*; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.*; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.repositoryconnector.OMRSRepositoryConnector; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.repositoryconnector.OMRSRepositoryHelper; import java.util.*; /** * AssetHandler retrieves basic information about an Asset and caches it to allow the * the ConnectedAssetRESTServices to retrieve all it needs. Each instance serves a single REST request. * * The calls to the metadata repositories happen in the constructor. Then getters are available to * populate the response to the REST request. */ public class AssetHandler { private static final String connectionTypeGUID = "114e9f8f-5ff3-4c32-bd37-a7eb42712253"; private static final String connectionConnectorTypeRelationshipGUID = "e542cfc1-0b4b-42b9-9921-f0a5a88aaf96"; private static final String connectionEndpointRelationshipGUID = "887a7132-d6bc-4b92-a483-e80b60c86fb2"; private static final String connectionToAssetRelationshipGUID = "e777d660-8dbe-453e-8b83-903771f054c0"; private static final String qualifiedNamePropertyName = "qualifiedName"; private static final String displayNamePropertyName = "displayName"; private static final String additionalPropertiesName = "additionalProperties"; private static final String securePropertiesName = "securedProperties"; private static final String descriptionPropertyName = "description"; private static final String connectorProviderPropertyName = "connectorProviderClassName"; private static final String ownerPropertyName = "owner"; private static final String shortDescriptionPropertyName = "assetSummary"; private static final String endpointProtocolPropertyName = "protocol"; private static final String endpointEncryptionPropertyName = "encryptionMethod"; private static final int MAX_PAGE_SIZE = 25; private String serviceName; private OMRSRepositoryHelper repositoryHelper = null; private String serverName = null; private ErrorHandler errorHandler; private TypeConverter typeHandler = new TypeConverter(); private EntityDetail assetEntity; private String connectionGUID; private RepositoryHandler repositoryHandler; private int annotationCount = 0; private int certificationCount = 0; private int commentCount = 0; private int connectionCount = 0; private int externalIdentifierCount = 0; private int externalReferencesCount = 0; private int informalTagCount = 0; private int licenseCount = 0; private int likeCount = 0; private int knownLocationsCount = 0; private int noteLogsCount = 0; private int ratingsCount = 0; private int relatedAssetCount = 0; private int relatedMediaReferenceCount = 0; private SchemaType schemaType = null; /** * Construct the asset handler with a link to the property server's connector and this access service's * official name. Then retrieve the asset and its relationships. * * @param serviceName name of this service * @param serverName name of this server * @param repositoryConnector connector to the property server. * @param userId userId of user making request. * @param assetGUID unique id for asset. * * @throws InvalidParameterException one of the parameters is null or invalid. * @throws UnrecognizedAssetGUIDException the supplied GUID is not recognized by the metadata repository. * @throws PropertyServerException there is a problem retrieving information from the property (metadata) server. * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. */ public AssetHandler(String serviceName, String serverName, OMRSRepositoryConnector repositoryConnector, String userId, String assetGUID) throws InvalidParameterException, UnrecognizedAssetGUIDException, PropertyServerException, UserNotAuthorizedException { this.serviceName = serviceName; this.serverName = serverName; this.repositoryHelper = repositoryConnector.getRepositoryHelper(); this.errorHandler = new ErrorHandler(repositoryConnector); this.repositoryHandler = new RepositoryHandler(serviceName, serverName, repositoryConnector); try { this.assetEntity = repositoryHandler.retrieveEntity(userId, AssetMapper.TYPE_NAME, assetGUID); this.countAssetAttachments(userId, assetGUID); } catch (UnrecognizedGUIDException error) { throw new UnrecognizedAssetGUIDException(error.getReportedHTTPCode(), error.getReportingClassName(), error.getReportingActionDescription(), error.getErrorMessage(), error.getReportedSystemAction(), error.getReportedUserAction(), assetGUID); } } /** * Construct the asset handler with a link to the property server's connector and this access service's * official name. Then retrieve the asset and its relationships. * * @param serviceName name of this service * @param serverName name of this server * @param repositoryConnector connector to the property server. * @param userId userId of user making request. * @param assetGUID unique id for asset. * @param connectionGUID unique id for connection used to access asset. * * @throws InvalidParameterException one of the parameters is null or invalid. * @throws UnrecognizedAssetGUIDException the supplied GUID is not recognized by the metadata repository. * @throws UnrecognizedConnectionGUIDException the supplied GUID is not recognized by the metadata repository. * @throws PropertyServerException there is a problem retrieving information from the property (metadata) server. * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. */ public AssetHandler(String serviceName, String serverName, OMRSRepositoryConnector repositoryConnector, String userId, String assetGUID, String connectionGUID) throws InvalidParameterException, UnrecognizedAssetGUIDException, UnrecognizedConnectionGUIDException, PropertyServerException, UserNotAuthorizedException { this(serviceName, serverName, repositoryConnector, userId, assetGUID); this.connectionGUID = connectionGUID; } /** * Return the asset bean. This is extracted from the asset entity detail object retrieved from * one of the repositories. * * @return unique identifier */ public Asset getAsset() { final String methodName = "getAsset"; if (assetEntity != null) { Asset asset = new Asset(); asset.setType(typeHandler.getElementType(assetEntity.getType(), assetEntity.getInstanceProvenanceType(), assetEntity.getMetadataCollectionId(), serverName, assetEntity.getInstanceLicense())); asset.setGUID(assetEntity.getGUID()); asset.setURL(assetEntity.getInstanceURL()); InstanceProperties instanceProperties = assetEntity.getProperties(); if (instanceProperties != null) { Iterator<String> propertyNames = instanceProperties.getPropertyNames(); while (propertyNames.hasNext()) { String propertyName = propertyNames.next(); if (propertyName != null) { asset.setQualifiedName(repositoryHelper.getStringProperty(serviceName, qualifiedNamePropertyName, instanceProperties, methodName)); asset.setDisplayName(repositoryHelper.getStringProperty(serviceName, displayNamePropertyName, instanceProperties, methodName)); asset.setDescription(repositoryHelper.getStringProperty(serviceName, descriptionPropertyName, instanceProperties, methodName)); asset.setOwner(repositoryHelper.getStringProperty(serviceName, ownerPropertyName, instanceProperties, methodName)); asset.setAdditionalProperties(repositoryHelper.getMapFromProperty(serviceName, additionalPropertiesName, instanceProperties, methodName)); asset.setZoneMembership(repositoryHelper.getStringArrayProperty(serviceName, ownerPropertyName, instanceProperties, methodName)); } } /* protected List<Meaning> meanings = null; protected String shortDescription = null; */ } return asset; } else { return null; } } /** * * @param userId * @param assetGUID * @throws InvalidParameterException * @throws UnrecognizedGUIDException * @throws PropertyServerException * @throws UserNotAuthorizedException */ private void countAssetAttachments(String userId, String assetGUID) throws InvalidParameterException, UnrecognizedGUIDException, PropertyServerException, UserNotAuthorizedException { int elementCount = 0; List<Relationship> retrievedRelationships; do { retrievedRelationships = repositoryHandler.retrieveAllRelationships(userId, AssetMapper.TYPE_NAME, assetGUID, elementCount, MAX_PAGE_SIZE); if (retrievedRelationships != null) { if (retrievedRelationships.isEmpty()) { retrievedRelationships = null; } else { certificationCount = certificationCount + countRelationshipsOfACertainType(retrievedRelationships, CertificationMapper.RELATIONSHIP_TYPE_NAME); commentCount = commentCount + countRelationshipsOfACertainType(retrievedRelationships, CommentMapper.RELATIONSHIP_TYPE_NAME); connectionCount = connectionCount + countRelationshipsOfACertainType(retrievedRelationships, ConnectionMapper.RELATIONSHIP_TYPE_NAME); externalIdentifierCount = externalIdentifierCount + countRelationshipsOfACertainType(retrievedRelationships, ExternalIdentifierMapper.RELATIONSHIP_TYPE_NAME); externalReferencesCount = externalReferencesCount + countRelationshipsOfACertainType(retrievedRelationships, ExternalReferenceMapper.RELATIONSHIP_TYPE_NAME); informalTagCount = informalTagCount + countRelationshipsOfACertainType(retrievedRelationships, InformalTagMapper.RELATIONSHIP_TYPE_NAME); licenseCount = licenseCount + countRelationshipsOfACertainType(retrievedRelationships, LicenseMapper.RELATIONSHIP_TYPE_NAME); likeCount = likeCount + countRelationshipsOfACertainType(retrievedRelationships, LikeMapper.RELATIONSHIP_TYPE_NAME); knownLocationsCount = knownLocationsCount + countRelationshipsOfACertainType(retrievedRelationships, LocationMapper.RELATIONSHIP_TYPE_NAME); noteLogsCount = noteLogsCount + countRelationshipsOfACertainType(retrievedRelationships, NoteLogMapper.RELATIONSHIP_TYPE_NAME); ratingsCount = ratingsCount + countRelationshipsOfACertainType(retrievedRelationships, RatingMapper.RELATIONSHIP_TYPE_NAME); relatedAssetCount = relatedAssetCount + countRelationshipsOfACertainType(retrievedRelationships, AssetMapper.RELATIONSHIP_TYPE_NAME); relatedMediaReferenceCount = relatedMediaReferenceCount + countRelationshipsOfACertainType(retrievedRelationships, RelatedMediaReferenceMapper.RELATIONSHIP_TYPE_NAME); if (schemaType == null) { schemaType = getSchemaType(userId, retrievedRelationships); } if (retrievedRelationships.size() == MAX_PAGE_SIZE) { /* * There may be more relationships to retrieve. */ elementCount = elementCount + MAX_PAGE_SIZE; } } } } while (retrievedRelationships != null); } /** * Return the number of relationships (attachments) of a requested type on the asset. * * @param relationships list of asset relationships retrieved from the repository. * @param relationshipTypeName type name of interest. * @return count of the relationships. */ private int countRelationshipsOfACertainType(List<Relationship> relationships, String relationshipTypeName) { List<Relationship> classifiedRelationships = repositoryHandler.getRelationshipsOfACertainType(relationships, relationshipTypeName); if (classifiedRelationships == null) { return 0; } else { return classifiedRelationships.size(); } } /** * Retrieve the schema type (if any) attached to the asset. * * @param userId userId of the call to retrieve the schema type entity. * @param relationships list of relationships attached to the asset. * @return SchemaType bean or null. */ private SchemaType getSchemaType(String userId, List<Relationship> relationships) { return null; } /** * Return the count of attached certification. * * @return count */ public int getCertificationCount() { return certificationCount; } /** * Return the count of attached comments. * * @return count */ public int getCommentCount() { return commentCount; } /** * Return the count of connections for the asset. * * @return count */ public int getConnectionCount() { return connectionCount; } /** * Return the count of external identifiers for this asset. * * @return count */ public int getExternalIdentifierCount() { return externalIdentifierCount; } /** * Return the count of attached external references. * * @return count */ public int getExternalReferencesCount() { return externalReferencesCount; } /** * Return the count of attached informal tags. * * @return count */ public int getInformalTagCount() { return informalTagCount; } /** * Return the count of license for this asset. * * @return count */ public int getLicenseCount() { return licenseCount; } /** * Return the number of likes for the asset. * * @return count */ public int getLikeCount() { return likeCount; } /** * Return the count of known locations. * * @return count */ public int getKnownLocationsCount() { return knownLocationsCount; } /** * Return the count of attached note logs. * * @return count */ public int getNoteLogsCount() { return noteLogsCount; } /** * Return the count of attached ratings. * * @return count */ public int getRatingsCount() { return ratingsCount; } /** * Return the count of related assets. * * @return count */ public int getRelatedAssetCount() { return relatedAssetCount; } /** * Return the count of related media references. * * @return count */ public int getRelatedMediaReferenceCount() { return relatedMediaReferenceCount; } /** * Is there an attached schema? * * @return schema type bean */ public SchemaType getSchemaType() { return schemaType; } /** * JSON-style toString * * @return return string containing the property names and values */ /** * Return comparison result based on the content of the properties. * * @param objectToCompare test object * @return result of comparison */ /** * Return hash code for this object * * @return int hash code */ }
40.602851
187
0.604635
6b7108ae07b71a57eafbcd012ada08580f8f1cbc
3,587
package pro.taskana.impl; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pro.taskana.TaskanaRole; import pro.taskana.exceptions.InvalidArgumentException; import pro.taskana.exceptions.NotAuthorizedException; import pro.taskana.impl.report.header.TimeIntervalColumnHeader; import pro.taskana.impl.report.item.DetailedMonitorQueryItem; import pro.taskana.impl.report.item.MonitorQueryItem; import pro.taskana.impl.report.preprocessor.DaysToWorkingDaysPreProcessor; import pro.taskana.mappings.TaskMonitorMapper; import pro.taskana.report.ClassificationReport; import pro.taskana.report.ClassificationReport.DetailedClassificationReport; /** The implementation of ClassificationReportBuilder. */ public class ClassificationReportBuilderImpl extends TimeIntervalReportBuilderImpl< ClassificationReport.Builder, MonitorQueryItem, TimeIntervalColumnHeader> implements ClassificationReport.Builder { private static final Logger LOGGER = LoggerFactory.getLogger(ClassificationReport.Builder.class); ClassificationReportBuilderImpl( InternalTaskanaEngine taskanaEngine, TaskMonitorMapper taskMonitorMapper) { super(taskanaEngine, taskMonitorMapper); } @Override public ClassificationReport buildReport() throws InvalidArgumentException, NotAuthorizedException { LOGGER.debug("entry to buildReport(), this = {}", this); this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); try { this.taskanaEngine.openConnection(); ClassificationReport report = new ClassificationReport(this.columnHeaders); List<MonitorQueryItem> monitorQueryItems = this.taskMonitorMapper.getTaskCountOfClassifications( this.workbasketIds, this.states, this.categories, this.domains, this.classificationIds, this.excludedClassificationIds, this.customAttributeFilter); report.addItems( monitorQueryItems, new DaysToWorkingDaysPreProcessor<>(this.columnHeaders, this.inWorkingDays)); return report; } finally { this.taskanaEngine.returnConnection(); LOGGER.debug("exit from buildReport()."); } } @Override public DetailedClassificationReport buildDetailedReport() throws InvalidArgumentException, NotAuthorizedException { LOGGER.debug("entry to buildDetailedReport(), this = {}", this); this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); try { this.taskanaEngine.openConnection(); DetailedClassificationReport report = new DetailedClassificationReport(this.columnHeaders); List<DetailedMonitorQueryItem> detailedMonitorQueryItems = this.taskMonitorMapper.getTaskCountOfDetailedClassifications( this.workbasketIds, this.states, this.categories, this.domains, this.classificationIds, this.excludedClassificationIds, this.customAttributeFilter); report.addItems( detailedMonitorQueryItems, new DaysToWorkingDaysPreProcessor<>(this.columnHeaders, this.inWorkingDays)); return report; } finally { this.taskanaEngine.returnConnection(); LOGGER.debug("exit from buildDetailedReport()."); } } @Override protected ClassificationReport.Builder _this() { return this; } @Override protected String determineGroupedBy() { return "CLASSIFICATION_KEY"; } }
36.979381
99
0.7385
a60ed79a9d965a5d95ffbbb30a588f50f87c87d3
261
package org.sogive.server; import org.sogive.data.user.RepeatDonation; import com.winterwell.web.app.CrudServlet; public class RepeatdonationServlet extends CrudServlet<RepeatDonation> { public RepeatdonationServlet() { super(RepeatDonation.class); } }
20.076923
72
0.804598
46aa3e31599a7a63f9e19f1901e45d8b109b0af8
1,840
package ru.pavelkr.priorauniver; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * Created by pavel on 19.04.2017. */ public class LogFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.fragment_log, container, false); final TextView textView = (TextView) rootView.findViewById(R.id.section_label); textView.setText(getString(R.string.section_format, 2)); rootView.findViewById(R.id.getlogbutton).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { StringBuilder sb = new StringBuilder(); MyBaseHelper baseHelper = new MyBaseHelper(v.getContext()); Cursor cursor = baseHelper.getReadableDatabase(). rawQuery("select * from " + MyBaseHelper.MYBASE_TABLE_NAME + " order by 1 desc limit 5", null); cursor.moveToFirst(); do { sb.append(cursor.getString(1)); sb.append("\n"); sb.append("\n"); } while (cursor.moveToNext()); textView.setText(sb.toString()); cursor.close(); baseHelper.close(); } } ); return rootView; } }
36.078431
128
0.53587
8737083d6d1d7c27696254f90b081b4519b2758c
29,156
//---------------------------------------------------- // The following code was generated by CUP v0.11b 20141202 (SVN rev 60) //---------------------------------------------------- package hoc4; import java_cup.runtime.*; import java.io.FileReader; import java.lang.Math; import java_cup.runtime.XMLElement; /** CUP v0.11b 20141202 (SVN rev 60) generated parser. */ @SuppressWarnings({"rawtypes"}) public class AnalizadorSintactico extends java_cup.runtime.lr_parser { public final Class getSymbolContainer() { return AnalizadorSintacticoSym.class; } /** Default constructor. */ public AnalizadorSintactico() {super();} /** Constructor which sets the default scanner. */ public AnalizadorSintactico(java_cup.runtime.Scanner s) {super(s);} /** Constructor which sets the default scanner. */ public AnalizadorSintactico(java_cup.runtime.Scanner s, java_cup.runtime.SymbolFactory sf) {super(s,sf);} /** Production table. */ protected static final short _production_table[][] = unpackFromStrings(new String[] { "\000\021\000\002\002\002\000\002\002\004\000\002\002" + "\003\000\002\002\005\000\002\003\005\000\002\004\003" + "\000\002\004\003\000\002\004\003\000\002\004\003\000" + "\002\004\005\000\002\004\005\000\002\004\005\000\002" + "\004\005\000\002\004\005\000\002\004\006\000\002\004" + "\004\000\002\004\005" }); /** Access to production table. */ public short[][] production_table() {return _production_table;} /** Parse-action table. */ protected static final short[][] _action_table = unpackFromStrings(new String[] { "\000\037\000\022\002\001\005\001\012\001\014\004\015" + "\001\016\001\017\001\020\001\001\002\000\020\002\uffff" + "\005\uffff\012\uffff\015\uffff\016\uffff\017\uffff\020\uffff\001" + "\002\000\020\002\012\005\010\012\016\015\006\016\013" + "\017\011\020\015\001\002\000\020\004\ufffc\005\ufffc\006" + "\ufffc\007\ufffc\011\ufffc\013\ufffc\014\ufffc\001\002\000\020" + "\004\ufff9\005\ufff9\006\ufff9\007\ufff9\011\ufff9\013\ufff9\014" + "\ufff9\001\002\000\016\005\010\012\016\015\006\016\013" + "\017\011\020\015\001\002\000\020\004\ufffa\005\ufffa\006" + "\ufffa\007\ufffa\011\ufffa\013\ufffa\014\ufffa\001\002\000\004" + "\002\000\001\002\000\022\004\ufffb\005\ufffb\006\ufffb\007" + "\ufffb\010\037\011\ufffb\013\ufffb\014\ufffb\001\002\000\016" + "\004\023\005\024\006\022\007\021\011\020\014\036\001" + "\002\000\004\012\033\001\002\000\016\005\010\012\016" + "\015\006\016\013\017\011\020\015\001\002\000\016\004" + "\023\005\024\006\022\007\021\011\020\013\025\001\002" + "\000\016\005\010\012\016\015\006\016\013\017\011\020" + "\015\001\002\000\016\005\010\012\016\015\006\016\013" + "\017\011\020\015\001\002\000\016\005\010\012\016\015" + "\006\016\013\017\011\020\015\001\002\000\016\005\010" + "\012\016\015\006\016\013\017\011\020\015\001\002\000" + "\016\005\010\012\016\015\006\016\013\017\011\020\015" + "\001\002\000\020\004\ufff4\005\ufff4\006\ufff4\007\ufff4\011" + "\ufff4\013\ufff4\014\ufff4\001\002\000\020\004\ufff7\005\ufff7" + "\006\022\007\021\011\020\013\ufff7\014\ufff7\001\002\000" + "\020\004\ufff8\005\ufff8\006\022\007\021\011\020\013\ufff8" + "\014\ufff8\001\002\000\020\004\ufff6\005\ufff6\006\ufff6\007" + "\ufff6\011\020\013\ufff6\014\ufff6\001\002\000\020\004\ufff5" + "\005\ufff5\006\ufff5\007\ufff5\011\020\013\ufff5\014\ufff5\001" + "\002\000\020\004\ufff1\005\ufff1\006\ufff1\007\ufff1\011\ufff1" + "\013\ufff1\014\ufff1\001\002\000\016\005\010\012\016\015" + "\006\016\013\017\011\020\015\001\002\000\016\004\023" + "\005\024\006\022\007\021\011\020\013\035\001\002\000" + "\020\004\ufff3\005\ufff3\006\ufff3\007\ufff3\011\ufff3\013\ufff3" + "\014\ufff3\001\002\000\020\002\ufffe\005\ufffe\012\ufffe\015" + "\ufffe\016\ufffe\017\ufffe\020\ufffe\001\002\000\016\005\010" + "\012\016\015\006\016\013\017\011\020\015\001\002\000" + "\020\004\023\005\024\006\022\007\021\011\020\013\ufffd" + "\014\ufffd\001\002\000\020\004\ufff2\005\ufff2\006\ufff2\007" + "\ufff2\011\ufff2\013\ufff2\014\ufff2\001\002" }); /** Access to parse-action table. */ public short[][] action_table() {return _action_table;} /** <code>reduce_goto</code> table. */ protected static final short[][] _reduce_table = unpackFromStrings(new String[] { "\000\037\000\004\002\004\001\001\000\002\001\001\000" + "\006\003\006\004\013\001\001\000\002\001\001\000\002" + "\001\001\000\006\003\006\004\040\001\001\000\002\001" + "\001\000\002\001\001\000\002\001\001\000\002\001\001" + "\000\002\001\001\000\006\003\006\004\016\001\001\000" + "\002\001\001\000\006\003\006\004\031\001\001\000\006" + "\003\006\004\030\001\001\000\006\003\006\004\027\001" + "\001\000\006\003\006\004\026\001\001\000\006\003\006" + "\004\025\001\001\000\002\001\001\000\002\001\001\000" + "\002\001\001\000\002\001\001\000\002\001\001\000\002" + "\001\001\000\006\003\006\004\033\001\001\000\002\001" + "\001\000\002\001\001\000\002\001\001\000\006\003\006" + "\004\037\001\001\000\002\001\001\000\002\001\001" }); /** Access to <code>reduce_goto</code> table. */ public short[][] reduce_table() {return _reduce_table;} /** Instance of action encapsulation class. */ protected CUP$AnalizadorSintactico$actions action_obj; /** Action encapsulation object initializer. */ protected void init_actions() { action_obj = new CUP$AnalizadorSintactico$actions(this); } /** Invoke a user supplied parse action. */ public java_cup.runtime.Symbol do_action( int act_num, java_cup.runtime.lr_parser parser, java.util.Stack stack, int top) throws java.lang.Exception { /* call code in generated class */ return action_obj.CUP$AnalizadorSintactico$do_action(act_num, parser, stack, top); } /** Indicates start state. */ public int start_state() {return 0;} /** Indicates start production. */ public int start_production() {return 1;} /** <code>EOF</code> Symbol index. */ public int EOF_sym() {return 0;} /** <code>error</code> Symbol index. */ public int error_sym() {return 1;} Main interfaz; Float variables[] = new Float[26]; MaquinaHoc4 maquinaHoc4; public void report_error(String mensaje, Object info) { StringBuilder m = new StringBuilder("Error"); if(info instanceof java_cup.runtime.Symbol) { java_cup.runtime.Symbol s = (java_cup.runtime.Symbol) info; if(s.left >= 0) { m.append(" en la línea " + (s.left+1)); if(s.right >= 0) { m.append(", columna " + (s.right+1)); } } } m.append(": " + mensaje); System.err.println(m); } public void report_fatal_error(String message, Object info) { report_error(message, info); System.exit(1); } /** Cup generated class to encapsulate user supplied action code.*/ @SuppressWarnings({"rawtypes", "unchecked", "unused"}) class CUP$AnalizadorSintactico$actions { private final AnalizadorSintactico parser; /** Constructor */ CUP$AnalizadorSintactico$actions(AnalizadorSintactico parser) { this.parser = parser; } /** Method 0 with the actual generated action code for actions 0 to 300. */ public final java_cup.runtime.Symbol CUP$AnalizadorSintactico$do_action_part00000000( int CUP$AnalizadorSintactico$act_num, java_cup.runtime.lr_parser CUP$AnalizadorSintactico$parser, java.util.Stack CUP$AnalizadorSintactico$stack, int CUP$AnalizadorSintactico$top) throws java.lang.Exception { /* Symbol object for return from actions */ java_cup.runtime.Symbol CUP$AnalizadorSintactico$result; /* select the action based on the action number */ switch (CUP$AnalizadorSintactico$act_num) { /*. . . . . . . . . . . . . . . . . . . .*/ case 0: // list ::= { Object RESULT =null; CUP$AnalizadorSintactico$result = parser.getSymbolFactory().newSymbol("list",0, ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), RESULT); } return CUP$AnalizadorSintactico$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 1: // $START ::= list EOF { Object RESULT =null; int start_valleft = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-1)).left; int start_valright = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-1)).right; Object start_val = (Object)((java_cup.runtime.Symbol) CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-1)).value; RESULT = start_val; CUP$AnalizadorSintactico$result = parser.getSymbolFactory().newSymbol("$START",0, ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-1)), ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), RESULT); } /* ACCEPT */ CUP$AnalizadorSintactico$parser.done_parsing(); return CUP$AnalizadorSintactico$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 2: // list ::= Enter { Object RESULT =null; CUP$AnalizadorSintactico$result = parser.getSymbolFactory().newSymbol("list",0, ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), RESULT); } return CUP$AnalizadorSintactico$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 3: // list ::= list expr Enter { Object RESULT =null; int eleft = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-1)).left; int eright = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-1)).right; Integer e = (Integer)((java_cup.runtime.Symbol) CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-1)).value; InstrucPrograma inst1 = new InstrucPrograma(); inst1.TipInstr = EnumTipoInstr.INSTRUC; inst1.Instruc = EnumInstrMaq.PRINT; /*InstrucPrograma inst2 = new InstrucPrograma(); inst2.TipInstr = EnumTipoInstr.INSTRUC; inst2.Instruc = EnumInstrMaq.STOP;*/ maquinaHoc4.code(inst1); CUP$AnalizadorSintactico$result = parser.getSymbolFactory().newSymbol("list",0, ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)), ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), RESULT); } return CUP$AnalizadorSintactico$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 4: // asgn ::= VAR OpAsig expr { Integer RESULT =null; int vleft = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)).left; int vright = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)).right; SymbolHoc v = (SymbolHoc)((java_cup.runtime.Symbol) CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)).value; InstrucPrograma inst1 = new InstrucPrograma(); inst1.TipInstr = EnumTipoInstr.INSTRUC; inst1.Instruc = EnumInstrMaq.VARPUSH; InstrucPrograma inst2 = new InstrucPrograma(); inst2.TipInstr = EnumTipoInstr.SYMBOL; inst2.symbolHoc = v; InstrucPrograma inst3 = new InstrucPrograma(); inst3.TipInstr = EnumTipoInstr.INSTRUC; inst3.Instruc = EnumInstrMaq.ASSIGN; RESULT = maquinaHoc4.code3(inst1, inst2, inst3); CUP$AnalizadorSintactico$result = parser.getSymbolFactory().newSymbol("asgn",1, ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)), ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), RESULT); } return CUP$AnalizadorSintactico$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 5: // expr ::= NUM { Integer RESULT =null; int nleft = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()).left; int nright = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()).right; SymbolHoc n = (SymbolHoc)((java_cup.runtime.Symbol) CUP$AnalizadorSintactico$stack.peek()).value; InstrucPrograma inst1 = new InstrucPrograma(); inst1.TipInstr = EnumTipoInstr.INSTRUC; inst1.Instruc = EnumInstrMaq.CONSTPUSH; InstrucPrograma inst2 = new InstrucPrograma(); inst2.TipInstr = EnumTipoInstr.SYMBOL; inst2.symbolHoc = n; RESULT = maquinaHoc4.code2(inst1, inst2); CUP$AnalizadorSintactico$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), RESULT); } return CUP$AnalizadorSintactico$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 6: // expr ::= VAR { Integer RESULT =null; int vleft = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()).left; int vright = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()).right; SymbolHoc v = (SymbolHoc)((java_cup.runtime.Symbol) CUP$AnalizadorSintactico$stack.peek()).value; InstrucPrograma inst1 = new InstrucPrograma(); inst1.TipInstr = EnumTipoInstr.INSTRUC; inst1.Instruc = EnumInstrMaq.VARPUSH; InstrucPrograma inst2 = new InstrucPrograma(); inst2.TipInstr = EnumTipoInstr.SYMBOL; inst2.symbolHoc = v; InstrucPrograma inst3 = new InstrucPrograma(); inst3.TipInstr = EnumTipoInstr.INSTRUC; inst3.Instruc = EnumInstrMaq.EVAL; RESULT = maquinaHoc4.code3(inst1, inst2, inst3); CUP$AnalizadorSintactico$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), RESULT); } return CUP$AnalizadorSintactico$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 7: // expr ::= CONST_PRED { Integer RESULT =null; int nleft = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()).left; int nright = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()).right; SymbolHoc n = (SymbolHoc)((java_cup.runtime.Symbol) CUP$AnalizadorSintactico$stack.peek()).value; InstrucPrograma inst1 = new InstrucPrograma(); inst1.TipInstr = EnumTipoInstr.INSTRUC; inst1.Instruc = EnumInstrMaq.CONSTPUSH; InstrucPrograma inst2 = new InstrucPrograma(); inst2.TipInstr = EnumTipoInstr.SYMBOL; inst2.symbolHoc = n; RESULT = maquinaHoc4.code2(inst1, inst2); CUP$AnalizadorSintactico$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), RESULT); } return CUP$AnalizadorSintactico$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 8: // expr ::= asgn { Integer RESULT =null; int indleft = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()).left; int indright = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()).right; Integer ind = (Integer)((java_cup.runtime.Symbol) CUP$AnalizadorSintactico$stack.peek()).value; RESULT = ind; CUP$AnalizadorSintactico$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), RESULT); } return CUP$AnalizadorSintactico$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 9: // expr ::= expr OpSuma expr { Integer RESULT =null; InstrucPrograma inst1 = new InstrucPrograma(); inst1.TipInstr = EnumTipoInstr.INSTRUC; inst1.Instruc = EnumInstrMaq.ADD; RESULT = maquinaHoc4.code(inst1); CUP$AnalizadorSintactico$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)), ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), RESULT); } return CUP$AnalizadorSintactico$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 10: // expr ::= expr OpResta expr { Integer RESULT =null; int e1left = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)).left; int e1right = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)).right; Integer e1 = (Integer)((java_cup.runtime.Symbol) CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)).value; int e2left = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()).left; int e2right = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()).right; Integer e2 = (Integer)((java_cup.runtime.Symbol) CUP$AnalizadorSintactico$stack.peek()).value; InstrucPrograma inst1 = new InstrucPrograma(); inst1.TipInstr = EnumTipoInstr.INSTRUC; inst1.Instruc = EnumInstrMaq.SUB; RESULT = maquinaHoc4.code(inst1); CUP$AnalizadorSintactico$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)), ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), RESULT); } return CUP$AnalizadorSintactico$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 11: // expr ::= expr OpProd expr { Integer RESULT =null; int e1left = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)).left; int e1right = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)).right; Integer e1 = (Integer)((java_cup.runtime.Symbol) CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)).value; int e2left = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()).left; int e2right = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()).right; Integer e2 = (Integer)((java_cup.runtime.Symbol) CUP$AnalizadorSintactico$stack.peek()).value; InstrucPrograma inst1 = new InstrucPrograma(); inst1.TipInstr = EnumTipoInstr.INSTRUC; inst1.Instruc = EnumInstrMaq.MUL; RESULT = maquinaHoc4.code(inst1); CUP$AnalizadorSintactico$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)), ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), RESULT); } return CUP$AnalizadorSintactico$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 12: // expr ::= expr OpDiv expr { Integer RESULT =null; int e1left = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)).left; int e1right = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)).right; Integer e1 = (Integer)((java_cup.runtime.Symbol) CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)).value; int e2left = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()).left; int e2right = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()).right; Integer e2 = (Integer)((java_cup.runtime.Symbol) CUP$AnalizadorSintactico$stack.peek()).value; InstrucPrograma inst1 = new InstrucPrograma(); inst1.TipInstr = EnumTipoInstr.INSTRUC; inst1.Instruc = EnumInstrMaq.DIV; RESULT = maquinaHoc4.code(inst1); CUP$AnalizadorSintactico$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)), ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), RESULT); } return CUP$AnalizadorSintactico$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 13: // expr ::= ParIzq expr ParDer { Integer RESULT =null; int eleft = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-1)).left; int eright = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-1)).right; Integer e = (Integer)((java_cup.runtime.Symbol) CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-1)).value; RESULT = e; CUP$AnalizadorSintactico$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)), ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), RESULT); } return CUP$AnalizadorSintactico$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 14: // expr ::= BLTIN ParIzq expr ParDer { Integer RESULT =null; int vleft = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-3)).left; int vright = ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-3)).right; SymbolHoc v = (SymbolHoc)((java_cup.runtime.Symbol) CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-3)).value; InstrucPrograma inst1 = new InstrucPrograma(); inst1.TipInstr = EnumTipoInstr.INSTRUC; inst1.Instruc = EnumInstrMaq.BLTIN; InstrucPrograma inst2 = new InstrucPrograma(); inst2.TipInstr = EnumTipoInstr.BLTIN; inst2.Func_BLTIN = v.FuncPredef; RESULT = maquinaHoc4.code2(inst1, inst2); CUP$AnalizadorSintactico$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-3)), ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), RESULT); } return CUP$AnalizadorSintactico$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 15: // expr ::= OpResta expr { Integer RESULT =null; InstrucPrograma inst1 = new InstrucPrograma(); inst1.TipInstr = EnumTipoInstr.INSTRUC; inst1.Instruc = EnumInstrMaq.NEGATE; RESULT = maquinaHoc4.code(inst1); CUP$AnalizadorSintactico$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-1)), ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), RESULT); } return CUP$AnalizadorSintactico$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 16: // expr ::= expr OpExp expr { Integer RESULT =null; InstrucPrograma inst1 = new InstrucPrograma(); inst1.TipInstr = EnumTipoInstr.INSTRUC; inst1.Instruc = EnumInstrMaq.POWER; RESULT = maquinaHoc4.code(inst1); CUP$AnalizadorSintactico$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.elementAt(CUP$AnalizadorSintactico$top-2)), ((java_cup.runtime.Symbol)CUP$AnalizadorSintactico$stack.peek()), RESULT); } return CUP$AnalizadorSintactico$result; /* . . . . . .*/ default: throw new Exception( "Invalid action number "+CUP$AnalizadorSintactico$act_num+"found in internal parse table"); } } /* end of method */ /** Method splitting the generated action code into several parts. */ public final java_cup.runtime.Symbol CUP$AnalizadorSintactico$do_action( int CUP$AnalizadorSintactico$act_num, java_cup.runtime.lr_parser CUP$AnalizadorSintactico$parser, java.util.Stack CUP$AnalizadorSintactico$stack, int CUP$AnalizadorSintactico$top) throws java.lang.Exception { return CUP$AnalizadorSintactico$do_action_part00000000( CUP$AnalizadorSintactico$act_num, CUP$AnalizadorSintactico$parser, CUP$AnalizadorSintactico$stack, CUP$AnalizadorSintactico$top); } } }
55.961612
271
0.572369
f863db01453ebe86383b369dd881422bb81cf4dd
8,018
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapreduce.security; import java.io.IOException; import java.net.URI; import java.util.Collection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier; import org.apache.hadoop.hdfs.server.namenode.NameNode; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapreduce.MRJobConfig; import org.apache.hadoop.mapreduce.security.token.JobTokenIdentifier; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.TokenStorage; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.hadoop.security.UserGroupInformation; /** * This class provides user facing APIs for transferring secrets from * the job client to the tasks. * The secrets can be stored just before submission of jobs and read during * the task execution. */ @InterfaceStability.Evolving public class TokenCache { private static final Log LOG = LogFactory.getLog(TokenCache.class); private static TokenStorage tokenStorage; /** * auxiliary method to get user's secret keys.. * @param alias * @return secret key from the storage */ public static byte[] getSecretKey(Text alias) { if(tokenStorage == null) return null; return tokenStorage.getSecretKey(alias); } /** * auxiliary methods to store user' s secret keys * @param alias * @param key */ public static void addSecretKey(Text alias, byte[] key) { getTokenStorage().addSecretKey(alias, key); } /** * auxiliary method to add a delegation token */ public static void addDelegationToken( String namenode, Token<? extends TokenIdentifier> t) { getTokenStorage().addToken(new Text(namenode), t); } /** * auxiliary method * @return all the available tokens */ public static Collection<Token<? extends TokenIdentifier>> getAllTokens() { return getTokenStorage().getAllTokens(); } /** * Convenience method to obtain delegation tokens from namenodes * corresponding to the paths passed. * @param ps array of paths * @param conf configuration * @throws IOException */ public static void obtainTokensForNamenodes(Path [] ps, Configuration conf) throws IOException { if (!UserGroupInformation.isSecurityEnabled()) { return; } obtainTokensForNamenodesInternal(ps, conf); } static void obtainTokensForNamenodesInternal(Path [] ps, Configuration conf) throws IOException { // get jobtracker principal id (for the renewer) Text jtCreds = new Text(conf.get(MRJobConfig.JOB_JOBTRACKER_ID, "")); for(Path p: ps) { FileSystem fs = FileSystem.get(p.toUri(), conf); if(fs instanceof DistributedFileSystem) { DistributedFileSystem dfs = (DistributedFileSystem)fs; URI uri = fs.getUri(); String fs_addr = buildDTServiceName(uri); // see if we already have the token Token<DelegationTokenIdentifier> token = TokenCache.getDelegationToken(fs_addr); if(token != null) { LOG.debug("DT for " + token.getService() + " is already present"); continue; } // get the token token = dfs.getDelegationToken(jtCreds); if(token==null) throw new IOException("Token from " + fs_addr + " is null"); token.setService(new Text(fs_addr)); TokenCache.addDelegationToken(fs_addr, token); LOG.info("getting dt for " + p.toString() + ";uri="+ fs_addr + ";t.service="+token.getService()); } } } /** * file name used on HDFS for generated job token */ @InterfaceAudience.Private public static final String JOB_TOKEN_HDFS_FILE = "jobToken"; /** * conf setting for job tokens cache file name */ @InterfaceAudience.Private public static final String JOB_TOKENS_FILENAME = "mapreduce.job.jobTokenFile"; private static final Text JOB_TOKEN = new Text("ShuffleAndJobToken"); /** * * @param namenode * @return delegation token */ @SuppressWarnings("unchecked") @InterfaceAudience.Private public static Token<DelegationTokenIdentifier> getDelegationToken(String namenode) { return (Token<DelegationTokenIdentifier>)getTokenStorage(). getToken(new Text(namenode)); } /** * @return TokenStore object */ @InterfaceAudience.Private public static TokenStorage getTokenStorage() { if(tokenStorage==null) tokenStorage = new TokenStorage(); return tokenStorage; } /** * sets TokenStorage * @param ts */ @InterfaceAudience.Private public static void setTokenStorage(TokenStorage ts) { if(tokenStorage != null) LOG.warn("Overwriting existing token storage with # keys=" + tokenStorage.numberOfSecretKeys()); tokenStorage = ts; } /** * load token storage and stores it * @param conf * @return Loaded TokenStorage object * @throws IOException */ @InterfaceAudience.Private public static TokenStorage loadTaskTokenStorage(String fileName, JobConf conf) throws IOException { if(tokenStorage != null) return tokenStorage; tokenStorage = loadTokens(fileName, conf); return tokenStorage; } /** * load job token from a file * @param conf * @throws IOException */ @InterfaceAudience.Private public static TokenStorage loadTokens(String jobTokenFile, JobConf conf) throws IOException { Path localJobTokenFile = new Path (jobTokenFile); FileSystem localFS = FileSystem.getLocal(conf); FSDataInputStream in = localFS.open(localJobTokenFile); TokenStorage ts = new TokenStorage(); ts.readFields(in); if(LOG.isDebugEnabled()) { LOG.debug("Task: Loaded jobTokenFile from: "+localJobTokenFile.toUri().getPath() +"; num of sec keys = " + ts.numberOfSecretKeys()); } in.close(); return ts; } /** * store job token * @param t */ @InterfaceAudience.Private public static void setJobToken(Token<? extends TokenIdentifier> t, TokenStorage ts) { ts.addToken(JOB_TOKEN, t); } /** * * @return job token */ @SuppressWarnings("unchecked") @InterfaceAudience.Private public static Token<JobTokenIdentifier> getJobToken(TokenStorage ts) { return (Token<JobTokenIdentifier>) ts.getToken(JOB_TOKEN); } static String buildDTServiceName(URI uri) { int port = uri.getPort(); if(port == -1) port = NameNode.DEFAULT_PORT; // build the service name string "ip:port" StringBuffer sb = new StringBuffer(); sb.append(NetUtils.normalizeHostName(uri.getHost())).append(":").append(port); return sb.toString(); } }
30.838462
87
0.70005
13e59b873469d035b0b6c9dd0ff109d675f7b215
225
package com.dtask.center.remoteTaskModule.bo; import lombok.Data; /** * Created by zhong on 2020-5-8. */ @Data public class RemoteTaskMemberBo { int userID; int nodeID; String username; boolean isAdmin; }
15
45
0.693333
2c8d4fe7d67ba268289e89e0c30ff38537b5b5db
3,271
/* * 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.james.util.retry; import org.apache.james.util.retry.api.RetrySchedule; /** * <code>DoublingRetrySchedule</code> is an implementation of <code>RetrySchedule</code> that * returns the lesser of an interval that is double the proceeding interval and the maximum interval. * * <p>When the initial interval is 0, the next interval is 1. * * <p>A multiplier can be specified to scale the results. */ /** * <code>DoublingRetrySchedule</code> */ public class DoublingRetrySchedule implements RetrySchedule { private long startInterval = 0; private long maxInterval = 0; private long multiplier = 1; /** * Creates a new instance of DoublingRetrySchedule. * */ private DoublingRetrySchedule() { } /** * Creates a new instance of DoublingRetrySchedule. * * @param startInterval * The interval for an index of 0 * @param maxInterval * The maximum interval for any index */ public DoublingRetrySchedule(long startInterval, long maxInterval) { this(startInterval, maxInterval, 1); } /** * Creates a new instance of DoublingRetrySchedule. * * @param startInterval * The interval for an index of 0 * @param maxInterval * The maximum interval for any index * @param multiplier * The multiplier to apply to the result */ public DoublingRetrySchedule(long startInterval, long maxInterval, int multiplier) { this(); this.startInterval = Math.max(0, startInterval); this.maxInterval = Math.max(0, maxInterval); this.multiplier = Math.max(1, multiplier); } @Override public long getInterval(int index) { if (startInterval > 0) { return getInterval(index, startInterval); } return index == 0 ? 0 : getInterval(index - 1, 1); } private long getInterval(int index, long startInterval) { return multiplier * Math.min((long) (startInterval * Math.pow(2, index)), maxInterval); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("DoublingRetrySchedule [startInterval=").append(startInterval).append( ", maxInterval=").append(maxInterval).append(", multiplier=").append(multiplier).append("]"); return builder.toString(); } }
32.71
109
0.664629
d9269b226f4f838b363dfe7edeebe21be15accb9
984
package org.polyglotted.graphonomy.model; import static com.google.common.base.Preconditions.checkNotNull; import java.util.List; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.Accessors; import com.google.common.collect.Lists; @Accessors(chain = true) @Getter @NoArgsConstructor @Setter public class MetaSpec { private List<NoteClass> noteClasses = Lists.newArrayList(); private List<RelationClass> relationClasses = Lists.newArrayList(); private List<TermClass> termClasses = Lists.newArrayList(); public MetaSpec addNoteClass(NoteClass noteClass) { noteClasses.add(checkNotNull(noteClass)); return this; } public MetaSpec addRelationClass(RelationClass relationClass) { relationClasses.add(relationClass); return this; } public MetaSpec addTermClass(TermClass termClass) { termClasses.add(checkNotNull(termClass)); return this; } }
25.894737
71
0.745935
6cacc88b45644b0f1e91360706971582b427db82
3,477
package login; import account.AccountManager; import utils.Utils; import java.util.Scanner; public class LogInPage { Scanner input = new Scanner(System.in); public void run() { while (true) { Utils.print("========Insurance Management System========"); Utils.print("1)Log In"); Utils.print("2)Sign Up"); Utils.print("0)Exit"); Utils.print("Type your choice:"); int choice = input.nextInt(); int choiceAccount; String emailInput; String passwordInput; boolean isExit = false; switch (choice) { case 1 -> { Utils.print("Log In Your Account"); Utils.print("========================"); Utils.print("1)Individual Account"); Utils.print("2)Enterprise Account"); Utils.print("0)Go Back To Main Menu"); Utils.print("Your choice: "); choiceAccount = input.nextInt(); switch (choiceAccount) { case 1 -> { Utils.print("======Individual Account======"); Utils.print("Email: "); emailInput = input.next(); Utils.print("Password: "); passwordInput = input.next(); AccountManager.logIn(emailInput, passwordInput, choiceAccount); } case 2 -> { Utils.print("======Enterprise Account======"); Utils.print("Email: "); emailInput = input.next(); Utils.print("Password: "); passwordInput = input.next(); AccountManager.logIn(emailInput, passwordInput, choiceAccount); } case 0 -> Utils.print("Leaving Menu..."); } } case 2 -> { Utils.print("Sign Up Your Account"); Utils.print("========================"); Utils.print("1)Individual Account"); Utils.print("2)Enterprise Account"); Utils.print("0)Go Back To Main Menu"); Utils.print("Your choice: "); choiceAccount = input.nextInt(); switch (choiceAccount) { case 1 -> { Utils.print("======Individual Account======"); Individual accountIndividual = new Individual(new User()); accountIndividual.signUp(); } case 2 -> { Utils.print("======Enterprise Account======"); Enterprise accountEnterprise = new Enterprise(new User()); accountEnterprise.signUp(); } case 0 -> Utils.print(""); } } case 0 -> isExit = true; default -> Utils.print("Invalid Entry"); } if (isExit) { Utils.print("Goodbye :)"); break; } } } }
37.387097
91
0.395456
799b3be6c1c80478f0527d2d545713344582002d
2,528
package com.lichkin.application.apis.GetModuleList; import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.springframework.stereotype.Service; import com.lichkin.framework.db.beans.Condition; import com.lichkin.framework.db.beans.Order; import com.lichkin.framework.db.beans.QuerySQL; import com.lichkin.framework.db.beans.SysAppEmployeeModuleConfigR; import com.lichkin.framework.db.beans.SysAppEmployeeModuleR; import com.lichkin.framework.db.beans.eq; import com.lichkin.framework.db.beans.isNotNull; import com.lichkin.framework.defines.enums.LKCodeEnum; import com.lichkin.framework.defines.exceptions.LKRuntimeException; import com.lichkin.springframework.controllers.ApiKeyValues; import com.lichkin.springframework.entities.impl.SysAppEmployeeModuleConfigEntity; import com.lichkin.springframework.entities.impl.SysAppEmployeeModuleEntity; import com.lichkin.springframework.services.LKApiBusGetListService; import lombok.Getter; import lombok.RequiredArgsConstructor; @Service(Statics.SERVICE_NAME) public class S extends LKApiBusGetListService<I, O, SysAppEmployeeModuleConfigEntity> { @Getter @RequiredArgsConstructor enum ErrorCodes implements LKCodeEnum { You_have_no_authority(40002), ; private final Integer code; } @Override protected void initSQL(I cin, ApiKeyValues<I> params, QuerySQL sql) { // 主表 sql.select(SysAppEmployeeModuleConfigR.id); sql.select(SysAppEmployeeModuleConfigR.moduleName); sql.select(SysAppEmployeeModuleConfigR.icon); sql.select(SysAppEmployeeModuleConfigR.url); sql.leftJoin( SysAppEmployeeModuleEntity.class, new Condition(new eq(SysAppEmployeeModuleConfigR.auth, Boolean.TRUE)), new Condition(SysAppEmployeeModuleConfigR.id, SysAppEmployeeModuleR.configId), new Condition(new eq(SysAppEmployeeModuleR.employeeId, params.getUser().getId())) ); // 筛选条件(必填项) sql.eq(SysAppEmployeeModuleConfigR.moduleType, cin.getModuleType()); sql.eq(SysAppEmployeeModuleConfigR.onLine, Boolean.TRUE); sql.where( new Condition(true, new Condition(new isNotNull(SysAppEmployeeModuleR.configId)), new Condition(false, new eq(SysAppEmployeeModuleConfigR.auth, Boolean.FALSE)) ) ); // 排序条件 sql.addOrders(new Order(SysAppEmployeeModuleConfigR.id)); } @Override protected List<O> afterQuery(I cin, ApiKeyValues<I> params, List<O> list) { if (CollectionUtils.isEmpty(list)) { throw new LKRuntimeException(ErrorCodes.You_have_no_authority); } return list; } }
28.088889
87
0.799446
f9bcdb1066feea872a3139cfb4a4c0f32a864083
1,829
package brv.notifier.packt; import java.util.Locale; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.scheduling.annotation.EnableScheduling; import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties; import brv.notifier.packt.configuration.EmailConfiguration; import brv.notifier.packt.configuration.TwitterConfiguration; import brv.notifier.packt.constants.PlaceholderValue; import brv.notifier.packt.util.MessageHelper; @SpringBootApplication @EnableScheduling @EnableEncryptableProperties @EnableFeignClients @Import({TwitterConfiguration.class, EmailConfiguration.class}) public class NotifierPacktApplication { public static void main(String[] args) { SpringApplication.run(NotifierPacktApplication.class, args); } @Bean public Locale getLocale(@Value(PlaceholderValue.LANG) String lang) { return new Locale(lang); } @Bean(name = "messageSource") public MessageSource getMessageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:messages"); return messageSource; } @Bean public MessageHelper getAppMessageHelper(@Qualifier("messageSource") MessageSource messageSource, Locale locale) { return new MessageHelper(messageSource, locale); } }
33.87037
115
0.83871
4ee46c91209a8fc178331977d728e06280701929
491
package me.kevinnovak.treasurehunt; public class PermissionManager { public String base = "treasurehunt."; public String command = "command."; public String item = base + "item"; public String help = base + command + "help"; public String list = base + command + "list"; public String top = base + command + "top"; public String start = base + command + "start"; public String despawn = base + command + "despawn"; public PermissionManager() { } }
28.882353
55
0.653768
e28a363c0931db210fd1d66c1039dc07021eb298
1,442
import java.util.Scanner; public class bell { private int D[]; private int num_ver; public static final int MAX_VALUE = 999; private int n; public bell(int n) { this.n=n; D = new int[n+1]; } public void shortest(int s,int A[][]) { for (int i=1;i<=n;i++) { D[i]=MAX_VALUE; } D[s] = 0; for(int k=1;k<=n-1;k++) { for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(A[i][j]!=MAX_VALUE) { if(D[j]>D[i]+A[i][j]) D[j]=D[i]+A[i][j]; } } } } for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(A[i][j]!=MAX_VALUE) { if(D[j]>D[i]+A[i][j]) { System.out.println("The Graph contains negative egde cycle"); return; } } } } for(int i=1;i<=n;i++) { System.out.println("Distance of source " + s + " to "+ i + " is " + D[i]); } } public static void main(String[ ] args) { int n=0,s; Scanner sc = new Scanner(System.in); System.out.println("Enter the number of vertices"); n = sc.nextInt(); int A[][] = new int[n+1][n+1]; System.out.println("Enter the Weighted matrix"); for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { A[i][j]=sc.nextInt(); if(i==j) { A[i][j]=0; continue; } if(A[i][j]==0) { A[i][j]=MAX_VALUE; } } } System.out.println("Enter the source vertex"); s=sc.nextInt(); bell b = new bell(n); b.shortest(s,A); sc.close(); } }
16.767442
77
0.493759
5b0098b44142677c631da1ed12600e1640213bcc
462
package Java_Object; public class Person { private String name; private char gender; private int age; public String getName() { return name; } public void setName(String _name) { this.name=_name; } public char getGender() { return gender; } public void setGender(char _gender) { this.gender=_gender; } public int getAge() { return age; } public void setAge(int _age) { this.age=_age; } }
13.2
37
0.623377
e71c2f41ad08c97310edd29d87ff42d4b9d5b90b
197
package jp.toufu3.ChatServer; public enum PermissionEnum { INVITE_CHANNNEL, MANAGEMENT_MES, SEND_MES, SEND_MENTION_MES, READ_MES, KNOW_EXIST, CREATE_ROOM, }
16.416667
30
0.664975
1c413a18c17034872af4e2c884b68f10bfaa8b82
516
package com.atguigu.spring.rabbitmq; import org.junit.jupiter.api.Test; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class SpringRabbitmqApplicationTests { @Autowired private RabbitTemplate rabbitTemplate; @Test void contextLoads() { rabbitTemplate.convertAndSend("spring-rabbitmq-exchage","spring.routingKey","你好rabbitmq"); } }
27.157895
98
0.78876
44f32573001119f550b12da25aec2077175e05a2
279
package kuina.spring_social_sbox; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SandBoxController { @GetMapping("/secured") public String secured() { return "OK"; } }
21.461538
62
0.795699
cd709e25d1e88986b01ab903b882c6da11f2a984
30,665
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2018 Groupon, Inc * Copyright 2014-2018 The Billing Project, LLC * * The Billing Project 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.killbill.billing.plugin.analytics.reports; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import javax.annotation.Nullable; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.killbill.billing.ObjectType; import org.killbill.billing.osgi.libs.killbill.OSGIConfigPropertiesService; import org.killbill.billing.osgi.libs.killbill.OSGIKillbillAPI; import org.killbill.billing.osgi.libs.killbill.OSGIKillbillDataSource; import org.killbill.billing.plugin.analytics.BusinessExecutor; import org.killbill.billing.plugin.analytics.dao.BusinessDBIProvider; import org.killbill.billing.plugin.analytics.json.Chart; import org.killbill.billing.plugin.analytics.json.CounterChart; import org.killbill.billing.plugin.analytics.json.DataMarker; import org.killbill.billing.plugin.analytics.json.NamedXYTimeSeries; import org.killbill.billing.plugin.analytics.json.ReportConfigurationJson; import org.killbill.billing.plugin.analytics.json.TableDataSeries; import org.killbill.billing.plugin.analytics.json.XY; import org.killbill.billing.plugin.analytics.reports.analysis.Smoother; import org.killbill.billing.plugin.analytics.reports.analysis.Smoother.SmootherType; import org.killbill.billing.plugin.analytics.reports.configuration.ReportsConfigurationModelDao; import org.killbill.billing.plugin.analytics.reports.configuration.ReportsConfigurationModelDao.ReportType; import org.killbill.billing.plugin.analytics.reports.scheduler.JobsScheduler; import org.killbill.billing.plugin.analytics.reports.sql.Metadata; import org.killbill.billing.util.api.RecordIdApi; import org.killbill.billing.util.callcontext.CallContext; import org.killbill.billing.util.callcontext.TenantContext; import org.killbill.commons.embeddeddb.EmbeddedDB; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.IDBI; import org.skife.jdbi.v2.tweak.HandleCallback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Function; import com.google.common.base.MoreObjects; import com.google.common.base.Predicate; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; public class ReportsUserApi { private static final Logger logger = LoggerFactory.getLogger(ReportsUserApi.class); private static final String ANALYTICS_REPORTS_NB_THREADS_PROPERTY = "org.killbill.billing.plugin.analytics.dashboard.nbThreads"; // Part of the public API public static final String DAY_COLUMN_NAME = "day"; public static final String TS_COLUMN_NAME = "ts"; public static final String LABEL = "label"; public static final String COUNT_COLUMN_NAME = "count"; private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.S"); private final OSGIKillbillAPI killbillAPI; private final IDBI dbi; private final EmbeddedDB.DBEngine dbEngine; private final ExecutorService dbiThreadsExecutor; private final ReportsConfiguration reportsConfiguration; private final JobsScheduler jobsScheduler; private final Metadata sqlMetadata; public ReportsUserApi(final OSGIKillbillAPI killbillAPI, final OSGIKillbillDataSource osgiKillbillDataSource, final OSGIConfigPropertiesService osgiConfigPropertiesService, final EmbeddedDB.DBEngine dbEngine, final ReportsConfiguration reportsConfiguration, final JobsScheduler jobsScheduler) { this.killbillAPI = killbillAPI; this.dbEngine = dbEngine; this.reportsConfiguration = reportsConfiguration; this.jobsScheduler = jobsScheduler; dbi = BusinessDBIProvider.get(osgiKillbillDataSource.getDataSource()); final String nbThreadsMaybeNull = Strings.emptyToNull(osgiConfigPropertiesService.getString(ANALYTICS_REPORTS_NB_THREADS_PROPERTY)); this.dbiThreadsExecutor = BusinessExecutor.newCachedThreadPool(nbThreadsMaybeNull == null ? 10 : Integer.valueOf(nbThreadsMaybeNull), "osgi-analytics-dashboard"); this.sqlMetadata = new Metadata(Sets.<String>newHashSet(Iterables.transform(reportsConfiguration.getAllReportConfigurations(null).values(), new Function<ReportsConfigurationModelDao, String>() { @Override public String apply(final ReportsConfigurationModelDao reportConfiguration) { return reportConfiguration.getSourceTableName(); } } )), osgiKillbillDataSource.getDataSource()); } public void shutdownNow() { dbiThreadsExecutor.shutdownNow(); } // TODO Cache per tenant public void clearCaches(final CallContext context) { sqlMetadata.clearCaches(); } public ReportConfigurationJson getReportConfiguration(final String reportName, final TenantContext context) throws SQLException { final Long tenantRecordId = getTenantRecordId(context); final ReportsConfigurationModelDao reportsConfigurationModelDao = reportsConfiguration.getReportConfigurationForReport(reportName, tenantRecordId); if (reportsConfigurationModelDao != null) { return new ReportConfigurationJson(reportsConfigurationModelDao, sqlMetadata.getTable(reportsConfigurationModelDao.getSourceTableName())); } else { return null; } } public void createReport(final ReportConfigurationJson reportConfigurationJson, final CallContext context) { final Long tenantRecordId = getTenantRecordId(context); final ReportsConfigurationModelDao reportsConfigurationModelDao = new ReportsConfigurationModelDao(reportConfigurationJson); reportsConfiguration.createReportConfiguration(reportsConfigurationModelDao, tenantRecordId); } public void updateReport(final String reportName, final ReportConfigurationJson reportConfigurationJson, final CallContext context) { final Long tenantRecordId = getTenantRecordId(context); final ReportsConfigurationModelDao currentReportsConfigurationModelDao = reportsConfiguration.getReportConfigurationForReport(reportName, tenantRecordId); final ReportsConfigurationModelDao reportsConfigurationModelDao = new ReportsConfigurationModelDao(reportConfigurationJson, currentReportsConfigurationModelDao); reportsConfiguration.updateReportConfiguration(reportsConfigurationModelDao, tenantRecordId); } public void deleteReport(final String reportName, final CallContext context) { final Long tenantRecordId = getTenantRecordId(context); reportsConfiguration.deleteReportConfiguration(reportName, tenantRecordId); } public void refreshReport(final String reportName, final CallContext context) { final Long tenantRecordId = getTenantRecordId(context); final ReportsConfigurationModelDao reportsConfigurationModelDao = reportsConfiguration.getReportConfigurationForReport(reportName, tenantRecordId); jobsScheduler.scheduleNow(reportsConfigurationModelDao); } public List<ReportConfigurationJson> getReports(final TenantContext context) { final Long tenantRecordId = getTenantRecordId(context); final List<ReportsConfigurationModelDao> reports = Ordering.natural() .nullsLast() .onResultOf(new Function<ReportsConfigurationModelDao, String>() { @Override public String apply(final ReportsConfigurationModelDao input) { return input.getReportPrettyName(); } }) .immutableSortedCopy(reportsConfiguration.getAllReportConfigurations(tenantRecordId).values()); return Lists.<ReportsConfigurationModelDao, ReportConfigurationJson>transform(reports, new Function<ReportsConfigurationModelDao, ReportConfigurationJson>() { @Override public ReportConfigurationJson apply(final ReportsConfigurationModelDao input) { try { return new ReportConfigurationJson(input, sqlMetadata.getTable(input.getSourceTableName())); } catch (SQLException e) { throw new RuntimeException(e); } } } ); } // Useful for testing public List<String> getSQLForReport(final Iterable<String> rawReportNames, @Nullable final DateTime startDate, @Nullable final DateTime endDate, final TenantContext context) { final Long tenantRecordId = getTenantRecordId(context); final List<String> sqlQueries = new LinkedList<String>(); for (final String rawReportName : rawReportNames) { final ReportSpecification reportSpecification = new ReportSpecification(rawReportName); final ReportsConfigurationModelDao reportConfigurationForReport = reportsConfiguration.getReportConfigurationForReport(reportSpecification.getReportName(), tenantRecordId); if (reportConfigurationForReport != null) { final SqlReportDataExtractor sqlReportDataExtractor = new SqlReportDataExtractor(reportConfigurationForReport.getSourceTableName(), reportSpecification, startDate, endDate, dbEngine, tenantRecordId); sqlQueries.add(sqlReportDataExtractor.toString()); } } return sqlQueries; } public List<Chart> getDataForReport(final Iterable<String> rawReportNames, @Nullable final DateTime startDate, @Nullable final DateTime endDate, @Nullable final SmootherType smootherType, final TenantContext context) { final Long tenantRecordId = getTenantRecordId(context); final List<Chart> result = new LinkedList<Chart>(); final Map<String, Map<String, List<XY>>> timeSeriesData = new ConcurrentHashMap<String, Map<String, List<XY>>>(); // Parse the reports final List<ReportSpecification> reportSpecifications = new ArrayList<ReportSpecification>(); for (final String rawReportName : rawReportNames) { reportSpecifications.add(new ReportSpecification(rawReportName)); } // Fetch the latest reports configurations final Map<String, ReportsConfigurationModelDao> reportsConfigurations = reportsConfiguration.getAllReportConfigurations(tenantRecordId); final List<Future> jobs = new LinkedList<Future>(); for (final ReportSpecification reportSpecification : reportSpecifications) { final String reportName = reportSpecification.getReportName(); final ReportsConfigurationModelDao reportConfiguration = getReportConfiguration(reportName, reportsConfigurations); final String tableName = reportConfiguration.getSourceTableName(); final String prettyName = reportConfiguration.getReportPrettyName(); final ReportType reportType = reportConfiguration.getReportType(); jobs.add(dbiThreadsExecutor.submit(new Runnable() { @Override public void run() { switch (reportType) { case COUNTERS: List<DataMarker> counters = getCountersData(tableName, tenantRecordId); result.add(new Chart(ReportType.COUNTERS, prettyName, counters)); break; case TIMELINE: final Map<String, List<XY>> data = getTimeSeriesData(tableName, reportSpecification, reportConfiguration, startDate, endDate, tenantRecordId); timeSeriesData.put(reportName, data); break; case TABLE: List<DataMarker> tables = getTablesData(tableName, tenantRecordId); result.add(new Chart(ReportType.TABLE, prettyName, tables)); break; default: throw new RuntimeException("Unknown reportType " + reportType); } } })); } waitForJobCompletion(jobs); // // Normalization and smoothing of time series if needed // if (!timeSeriesData.isEmpty()) { normalizeAndSortXValues(timeSeriesData, startDate, endDate); if (smootherType != null) { final Smoother smoother = smootherType.createSmoother(timeSeriesData); smoother.smooth(); result.addAll(buildNamedXYTimeSeries(smoother.getDataForReports(), reportsConfigurations)); } else { result.addAll(buildNamedXYTimeSeries(timeSeriesData, reportsConfigurations)); } } return result; } private List<Chart> buildNamedXYTimeSeries(final Map<String, Map<String, List<XY>>> dataForReports, final Map<String, ReportsConfigurationModelDao> reportsConfigurations) { final List<Chart> results = new LinkedList<Chart>(); final List<DataMarker> timeSeries = new LinkedList<DataMarker>(); for (final String reportName : dataForReports.keySet()) { final ReportsConfigurationModelDao reportConfiguration = getReportConfiguration(reportName, reportsConfigurations); // Sort the pivots by name for a consistent display in the dashboard for (final String timeSeriesName : Ordering.natural().sortedCopy(dataForReports.get(reportName).keySet())) { final List<XY> dataForReport = dataForReports.get(reportName).get(timeSeriesName); timeSeries.add(new NamedXYTimeSeries(timeSeriesName, dataForReport)); } results.add(new Chart(ReportType.TIMELINE, reportConfiguration.getReportPrettyName(), timeSeries)); } return results; } // TODO PIERRE Naive implementation private void normalizeAndSortXValues(final Map<String, Map<String, List<XY>>> dataForReports, @Nullable final DateTime startDate, @Nullable final DateTime endDate) { DateTime minDate = null; if (startDate != null) { minDate = startDate; } DateTime maxDate = null; if (endDate != null) { maxDate = endDate; } // If no min and/or max was specified, infer them from the data if (minDate == null || maxDate == null) { for (final Map<String, List<XY>> dataForReport : dataForReports.values()) { for (final List<XY> dataForPivot : dataForReport.values()) { for (final XY xy : dataForPivot) { if (minDate == null || xy.getxDate().isBefore(minDate)) { minDate = xy.getxDate(); } if (maxDate == null || xy.getxDate().isAfter(maxDate)) { maxDate = xy.getxDate(); } } } } } if (minDate == null || maxDate == null) { throw new IllegalStateException(String.format("minDate and maxDate shouldn't be null! minDate=%s, maxDate=%s, dataForReports=%s", minDate, maxDate, dataForReports)); } // Add 0 for missing days DateTime curDate = minDate; while (!curDate.isAfter(maxDate)) { for (final Map<String, List<XY>> dataForReport : dataForReports.values()) { for (final List<XY> dataForPivot : dataForReport.values()) { addMissingValueForDateIfNeeded(curDate, dataForPivot); } } curDate = curDate.plusDays(1); } // Sort the data for the dashboard for (final String reportName : dataForReports.keySet()) { for (final String pivotName : dataForReports.get(reportName).keySet()) { Collections.sort(dataForReports.get(reportName).get(pivotName), new Comparator<XY>() { @Override public int compare(final XY o1, final XY o2) { return o1.getxDate().compareTo(o2.getxDate()); } } ); } } } private void addMissingValueForDateIfNeeded(final DateTime curDate, final List<XY> dataForPivot) { final XY valueForCurrentDate = Iterables.tryFind(dataForPivot, new Predicate<XY>() { @Override public boolean apply(final XY xy) { return xy.getxDate().compareTo(curDate) == 0; } @Override public boolean test(@Nullable final XY input) { return apply(input); } }).orNull(); if (valueForCurrentDate == null) { dataForPivot.add(new XY(curDate, (float) 0)); } } private List<DataMarker> getCountersData(final String tableName, final Long tenantRecordId) { return dbi.withHandle(new HandleCallback<List<DataMarker>>() { @Override public List<DataMarker> withHandle(final Handle handle) throws Exception { final List<Map<String, Object>> results = handle.select("select * from " + tableName + " where tenant_record_id = " + tenantRecordId); if (results.size() == 0) { return Collections.emptyList(); } final List<DataMarker> counters = new LinkedList<DataMarker>(); for (final Map<String, Object> row : results) { final Object labelObject = row.get(LABEL); final Object countObject = row.get(COUNT_COLUMN_NAME); if (labelObject == null || countObject == null) { continue; } final String label = labelObject.toString(); final Float value = Float.valueOf(countObject.toString()); final DataMarker counter = new CounterChart(label, value); counters.add(counter); } return counters; } }); } private List<DataMarker> getTablesData(final String tableName, final Long tenantRecordId) { return dbi.withHandle(new HandleCallback<List<DataMarker>>() { @Override public List<DataMarker> withHandle(final Handle handle) throws Exception { final List<Map<String, Object>> results = handle.select("select * from " + tableName + " where tenant_record_id = " + tenantRecordId); if (results.size() == 0) { return Collections.emptyList(); } // Keep the original ordering of the view final List<String> header = new LinkedList<String>(); final List<Map<String, Object>> schemaResults = handle.select("select column_name from information_schema.columns where table_schema = schema() and table_name = '" + tableName + "' order by ordinal_position"); for (final Map<String, Object> row : schemaResults) { header.add(String.valueOf(row.get("column_name"))); } final List<List<Object>> values = new LinkedList<List<Object>>(); for (final Map<String, Object> row : results) { final List<Object> tableRow = new LinkedList<Object>(); for (final String headerName : header) { tableRow.add(row.get(headerName)); } values.add(tableRow); } return ImmutableList.<DataMarker>of(new TableDataSeries(tableName, header, values)); } }); } private Map<String, List<XY>> getTimeSeriesData(final String tableName, final ReportSpecification reportSpecification, final ReportsConfigurationModelDao reportsConfiguration, @Nullable final DateTime startDate, @Nullable final DateTime endDate, final Long tenantRecordId) { final SqlReportDataExtractor sqlReportDataExtractor = new SqlReportDataExtractor(tableName, reportSpecification, startDate, endDate, dbEngine, tenantRecordId); return dbi.withHandle(new HandleCallback<Map<String, List<XY>>>() { @Override public Map<String, List<XY>> withHandle(final Handle handle) throws Exception { final List<Map<String, Object>> results = handle.select(sqlReportDataExtractor.toString()); if (results.size() == 0) { Collections.emptyMap(); } final Map<String, List<XY>> timeSeries = new LinkedHashMap<String, List<XY>>(); for (final Map<String, Object> row : results) { // Day Object dateObject = row.get(DAY_COLUMN_NAME); if (dateObject == null) { // Timestamp dateObject = row.get(TS_COLUMN_NAME); if (dateObject == null) { continue; } dateObject = DATE_TIME_FORMATTER.parseDateTime(dateObject.toString()).toString(); } final String date = dateObject.toString(); final String legendWithDimensions = createLegendWithDimensionsForSeries(row, reportSpecification); for (final String column : row.keySet()) { if (isMetric(column, reportSpecification)) { // Create a unique name for that result set final String seriesName = MoreObjects.firstNonNull(reportSpecification.getLegend(), column) + (legendWithDimensions == null ? "" : (": " + legendWithDimensions)); if (timeSeries.get(seriesName) == null) { timeSeries.put(seriesName, new LinkedList<XY>()); } final Object value = row.get(column); final Float valueAsFloat = value == null ? 0f : Float.valueOf(value.toString()); timeSeries.get(seriesName).add(new XY(date, valueAsFloat)); } } } return timeSeries; } }); } private String createLegendWithDimensionsForSeries(final Map<String, Object> row, final ReportSpecification reportSpecification) { int i = 0; final StringBuilder seriesNameBuilder = new StringBuilder(); for (final String column : row.keySet()) { if (shouldUseColumnAsDimensionMultiplexer(column, reportSpecification)) { if (i > 0) { seriesNameBuilder.append(" :: "); } seriesNameBuilder.append(row.get(column) == null ? "NULL" : row.get(column).toString()); i++; } } if (i == 0) { return null; } else { return seriesNameBuilder.toString(); } } private boolean shouldUseColumnAsDimensionMultiplexer(final String column, final ReportSpecification reportSpecification) { // Don't multiplex the day column if (DAY_COLUMN_NAME.equals(column)) { return false; } if (reportSpecification.getDimensions().isEmpty()) { if (reportSpecification.getMetrics().isEmpty()) { // If no dimension and metric are specified, assume all columns are dimensions except the "count" one return !COUNT_COLUMN_NAME.equals(column); } else { // Otherwise, all non-metric columns are dimensions return !reportSpecification.getMetrics().contains(column); } } else { return reportSpecification.getDimensions().contains(column); } } private boolean isMetric(final String column, final ReportSpecification reportSpecification) { if (reportSpecification.getMetrics().isEmpty()) { if (reportSpecification.getDimensions().isEmpty()) { // If no dimension and metric are specified, assume the only metric is the "count" one return COUNT_COLUMN_NAME.equals(column); } else { // Otherwise, all non-dimension columns are metrics return !DAY_COLUMN_NAME.equals(column) && !reportSpecification.getDimensions().contains(column); } } else { return reportSpecification.getMetrics().contains(column); } } private ReportsConfigurationModelDao getReportConfiguration(final String reportName, final Map<String, ReportsConfigurationModelDao> reportsConfigurations) { final ReportsConfigurationModelDao reportConfiguration = reportsConfigurations.get(reportName); if (reportConfiguration == null) { throw new IllegalArgumentException("Report " + reportName + " is not configured"); } return reportConfiguration; } private void waitForJobCompletion(final List<Future> jobs) { for (final Future job : jobs) { try { job.get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } } private Long getTenantRecordId(final TenantContext context) { // See convention in InternalCallContextFactory if (context.getTenantId() == null) { return 0L; } else { final RecordIdApi recordIdApi = killbillAPI.getRecordIdApi(); return recordIdApi.getRecordId(context.getTenantId(), ObjectType.TENANT, context); } } }
53.053633
225
0.578771
be03c87363338e6d91f2c2b6907c1f5216f805b6
10,124
package de.unistuttgart.vis.dsass2021.ex05.p2; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; // author: Siyu Chen (3494095) st169719@stud.uni-stuttgart.de // Xuefeng Hou (3502673) st175367@stud.uni-stuttgart.de // Leqi Xu (3556962) st176119@stud.uni-stuttgart.de import de.unistuttgart.vis.dsass2021.ex05.p1.Rectangle; /** * This class represents a two-dimensional collision map. A collision map is a * data structure that stores a set of rectangles. Given another rectangle, this * data structure allows retrieving all rectangles that intersect this * rectangle. */ public class CollisionMap { // If the resolution of the grid is not specified by the user we use this // default resolution. private static final int GRID_RESOLUTION_X = 100; private static final int GRID_RESOLUTION_Y = 100; /** * Rectangle that encapsulates all rectangles in the collision map. */ private final Rectangle gridRectangle; /** * A two-dimensional array of {@link java.util.List} serves as the data * structure for storing the rectangles. Each element of the array holds a list * of rectangles. At the same time, each element of the array is associated with * an area of the bounding rectangle {@link CollisionMap.gridRectangle} through * the transform methods ({@link CollisionMap.transformX} and * {@link CollisionMap.transformY}. These areas are called cells. */ private List<Rectangle>[][] map; /** * Creates a {@link CollisionMap} from a set of rectangles. * * @param rectangles that are placed in the collision map * @throws CollisionMapException */ public CollisionMap(final Set<Rectangle> rectangles) throws IllegalArgumentException { this(rectangles, GRID_RESOLUTION_X, GRID_RESOLUTION_Y); } /** * Creates a {@link CollisionMap} from a set of rectangles and specified grid * resolutions. * * @param rectangles that are placed in the collision map, must be != null * @param gridResolutionX the resolution in x direction, must be >= 1 * @param gridResolutionY the grid resolution in y direction, must be >= 1 * @throws IllegalArgumentException if any parameter has an invalid value */ public CollisionMap(final Set<Rectangle> rectangles, final int gridResolutionX, final int gridResolutionY) throws IllegalArgumentException { if (rectangles == null || gridResolutionX < 1 || gridResolutionY < 1) { throw new IllegalArgumentException("rectangles is null or gridResolution is less than 1"); } this.gridRectangle = Rectangle.getBoundingBox(rectangles); generateCollisionMap(gridResolutionX, gridResolutionY); try { fillCollisionMap(rectangles); } catch (final CollisionMapOutOfBoundsException exception) { exception.printStackTrace(); } } /** * Fill this collision map with a set of rectangles. A rectangle is added to a * cell if it overlaps with it (that includes just touching it). Afterwards, * each cell of the collision map should contain all rectangles that cover the * cell. * * @param rectangles is a set of rectangles to insert, it must be != null * @throws CollisionMapOutOfBoundsException if a rectangle is out of the bounds * of this rectangle */ private void fillCollisionMap(Set<Rectangle> rectangles) throws CollisionMapOutOfBoundsException { // TODO Insert code for assignment 5.2.a for(Rectangle rectangle:rectangles){ if(rectangle.getX() < this.gridRectangle.getX() || rectangle.getX() + rectangle.getWidth() > this.gridRectangle.getX() + this.gridRectangle.getWidth() || rectangle.getY() < this.gridRectangle.getY() || rectangle.getY() + rectangle.getHeight() > this.gridRectangle.getY() + this.gridRectangle.getHeight() ){ throw new CollisionMapOutOfBoundsException("a rectangle is out of the bounds of this rectangle"); } int startX = (int)transformX(rectangle.getX()); int startY = (int)transformY(rectangle.getY()); int endX = (int)transformX(rectangle.getX() + rectangle.getWidth()); if(endX == this.GRID_RESOLUTION_X){ endX = this.GRID_RESOLUTION_X - 1; } int endY = (int)transformY(rectangle.getY() + rectangle.getHeight()); if(endY == this.GRID_RESOLUTION_Y){ endY = this.GRID_RESOLUTION_Y - 1; } for(int i = startX; i <= endX; i++){ for(int j = startY; j<=endY; j++){ map[j][i].add(rectangle); } } } } /** * Given a rectangle, this method returns a set of potential colliding * rectangles (rectangles in the same cells). * * @param rectangle the rectangle to test overlap with must be != null * @return a set with all Rectangles that possibly overlap with rectangle * @throws CollisionMapOutOfBoundsException if the rectangle is out of the * bounding box for this CollisionMap */ private Set<Rectangle> getCollisionCandidates(final Rectangle rectangle) throws CollisionMapOutOfBoundsException { // TODO Insert code for assignment 5.2.b if( rectangle.getX() < this.gridRectangle.getX() || rectangle.getX() + rectangle.getWidth() > this.gridRectangle.getX() + this.gridRectangle.getWidth() || rectangle.getY() < this.gridRectangle.getY() || rectangle.getY() + rectangle.getHeight() > this.gridRectangle.getY() + this.gridRectangle.getHeight() ){ throw new CollisionMapOutOfBoundsException("a rectangle is out of the bounds of this rectangle"); } Set<Rectangle> rectangleSet = new HashSet<>(); int startX = (int)transformX(rectangle.getX()); int startY = (int)transformY(rectangle.getY()); int endX = (int)transformX(rectangle.getX() + rectangle.getWidth()) + 1; int endY = (int)transformY(rectangle.getY() + rectangle.getHeight()) + 1; for(int i = startX; i <= endX; i++){ for(int j = startY; j<=endY; j++){ for(Rectangle re :map[j][i]){ rectangleSet.add(re); } } } return rectangleSet; } /** * Transform a x coordinate from rectangle space to the internal space of the * {@link CollisionMap}. For accessing specific cells of the grid the return * value must be rounded and cast appropriately. * * @param x coordinate of a point * @return x coordinate of given point in the internal space * @throws CollisionMapOutOfBoundsException if x is too low or too high */ private float transformX(final float x) throws CollisionMapOutOfBoundsException { if (x < this.gridRectangle.getX() || x > this.gridRectangle.getX() + this.gridRectangle.getWidth()) { throw new CollisionMapOutOfBoundsException("x coordinate is outside the defined range."); } else { return ((x - this.gridRectangle.getX()) / this.gridRectangle.getWidth()) * map[0].length; } } /** * Transform a y coordinate from rectangle space to the internal space of the * {@link CollisionMap}. For accessing specific cells of the grid the return * value must be rounded and cast appropriately. * * @param y coordinate of a point * @return y coordinate of given point in the internal space * @throws CollisionMapOutOfBoundsException if y is too low or too high */ private float transformY(float y) throws CollisionMapOutOfBoundsException { if (y < this.gridRectangle.getY() || y > this.gridRectangle.getY() + this.gridRectangle.getHeight()) { throw new CollisionMapOutOfBoundsException("y coordinate is outside the defined range."); } else { return ((y - this.gridRectangle.getY()) / this.gridRectangle.getHeight()) * map.length; } } /** * Check if the given rectangle collides with rectangles in the * {@link CollisionMap}. * * @param rectangle the rectangle to check for collision * @return true if the given rectangle intersects one of the rectangles in the * collision map. * @throws IllegalArgumentException if rectangle is null */ public boolean collide(final Rectangle rectangle) { // TODO Insert code for assignment 5.2.c if(rectangle == null){ throw new IllegalArgumentException("rectangle is null"); } boolean flag = false; try{ Set<Rectangle> rectangleSet = this.getCollisionCandidates(rectangle); for(Rectangle re:rectangleSet){ if(re.intersects(rectangle)){ flag = true; } } }catch (Exception e){ System.out.println(e.getMessage()); }finally { return flag; } } /** * Allocate the collision map * * @param gridResolutionX * @param gridResolutionY */ @SuppressWarnings("unchecked") private void generateCollisionMap(int gridResolutionX, int gridResolutionY) { map = new ArrayList[gridResolutionY][gridResolutionX]; for (int y = 0; y < gridResolutionY; ++y) { for (int x = 0; x < gridResolutionX; ++x) { map[y][x] = new ArrayList<Rectangle>(); } } } public List<Rectangle>[][] getMap(){ return this.map; } }
43.264957
119
0.617345
e48b82de3c74cc9c0c201b17d9615a64492bbdb0
536
package configuration.marvel.csv; import configuration.marvel.domain.MCUPhases; import configuration.marvel.domain.MediaVehicle; import lombok.Builder; import lombok.Data; import org.apache.commons.lang3.Range; import org.jetbrains.annotations.Nullable; import java.time.LocalDate; @Data @Builder(toBuilder = true) public class MarvelUniverseMedia { @Nullable Long id; @Nullable String title; @Nullable LocalDate releaseDate; @Nullable MCUPhases phase; @Nullable MediaVehicle filmTv; @Nullable Range<Integer> inUniverseYear; }
24.363636
48
0.813433
680db674074680dd82892af6aa0b8792353edc06
3,319
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 4.0.2 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package br.com.johnathan.gdx.effekseer.api; public class EffekseerManagerCore { private transient long swigCPtr; protected transient boolean swigCMemOwn; protected EffekseerManagerCore(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } protected static long getCPtr(EffekseerManagerCore obj) { return (obj == null) ? 0 : obj.swigCPtr; } @SuppressWarnings("deprecation") protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; GDXJNI.delete_EffekseerManagerCore(swigCPtr); } swigCPtr = 0; } } public EffekseerManagerCore() { this(GDXJNI.new_EffekseerManagerCore(), true); } public boolean Initialize(int spriteMaxCount, int id) { return GDXJNI.EffekseerManagerCore_Initialize(swigCPtr, this, spriteMaxCount, id); } public void Update(float deltaFrames) { GDXJNI.EffekseerManagerCore_Update(swigCPtr, this, deltaFrames); } public int Play(EffekseerEffectCore effect) { return GDXJNI.EffekseerManagerCore_Play(swigCPtr, this, EffekseerEffectCore.getCPtr(effect), effect); } public boolean IsPlaing(int handle) { return GDXJNI.EffekseerManagerCore_IsPlaing(swigCPtr, this, handle); } public float Speed(int handle) { return GDXJNI.EffekseerManagerCore_Speed(swigCPtr, this, handle); } public void DrawBack() { GDXJNI.EffekseerManagerCore_DrawBack(swigCPtr, this); } public void DrawFront() { GDXJNI.EffekseerManagerCore_DrawFront(swigCPtr, this); } public void SetPause(int handle, boolean pause) { GDXJNI.EffekseerManagerCore_SetPause(swigCPtr, this, handle, pause); } public void SetProjectionMatrix(float[] matrix44, float[] matrix44C, boolean view, float width, float heith) { GDXJNI.EffekseerManagerCore_SetProjectionMatrix(swigCPtr, this, matrix44, matrix44C, view, width, heith); } public void SetEffectRotateAxis(int handle, float x, float y, float z, float angle) { GDXJNI.EffekseerManagerCore_SetEffectRotateAxis(swigCPtr, this, handle, x, y, z, angle); } public void SetEffectPosition(int handle, float x, float y, float z) { GDXJNI.EffekseerManagerCore_SetEffectPosition(swigCPtr, this, handle, x, y, z); } public void SetEffectScale(int handle, float x, float y, float z) { GDXJNI.EffekseerManagerCore_SetEffectScale(swigCPtr, this, handle, x, y, z); } public void Stop(int i) { GDXJNI.EffekseerManagerCore_Stop(swigCPtr, this, i); } public int InstacieCount(int handle) { return GDXJNI.EffekseerManagerCore_InstacieCount(swigCPtr, this, handle); } public float[] GetMatrix(int handle) { return GDXJNI.EffekseerManagerCore_GetMatrix(swigCPtr, this, handle); } public void SetMatrix(int handle, float[] matrix43) { GDXJNI.EffekseerManagerCore_SetMatrix(swigCPtr, this, handle, matrix43); } }
30.731481
112
0.693281
7a5ab9554cb7c8e396cf1d2ed2c2f0a6eecc5ce8
22,411
package scalc; import org.junit.Assert; import org.junit.Test; import scalc.exceptions.CalculationException; import scalc.internal.converter.INumberConverter; import scalc.test.model.Money; import scalc.test.model.MoneyConverter; import scalc.test.model.TestDto; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; public class SCalcTest { @Test public void calc_SimpleExpression_1() { Map<String, Object> params = new HashMap<>(); params.put("a", 10); params.put("b", 2.1); Double result = SCalcBuilder.doubleInstance() .expression("a + b") .build() .params(params) .calc(); Assert.assertEquals(12.1, result, 0); } @Test public void calc_SimpleExpression_2() { Double result = SCalcBuilder.doubleInstance() .expression("a + b - c") .build() .parameter("a", 10) .parameter("b", 5) .parameter("c", 15) .calc(); Assert.assertEquals(0.0, result, 0); } @Test public void calc_BigDecimal() { BigDecimal result = SCalcBuilder.bigDecimalInstance() .expression("4 * 4 - var1") .build() .parameter("var1", new BigDecimal(2)) .calc(); Assert.assertEquals(14.0, result.doubleValue(), 0); } @Test public void calc_ComplexExpression_2() { Map<String, Object> params = new HashMap<>(); params.put("a", 10); params.put("b", 2); BigDecimal result = SCalcBuilder.bigDecimalInstance() .expression("a + b * √(16)") .resultScale(1, RoundingMode.HALF_UP) .build() .params(params) .calc(); Assert.assertEquals(new BigDecimal("18.0"), result); } @Test public void calc_Constant() { Double result = SCalcBuilder.doubleInstance() .expression("20.11") .buildAndCalc(); Assert.assertEquals(20.11, result, 0); } @Test public void calc_Variable() { Map<String, Object> params = new HashMap<>(); params.put("someFancyVar1", 10); Double result = SCalcBuilder.doubleInstance() .expression(" someFancyVar1 ") .build() .params(params) .calc(); Assert.assertEquals(10.0, result, 0); } @Test public void calc_Function() { Map<String, Object> params = new HashMap<>(); params.put("var1", 4); Double result = SCalcBuilder.doubleInstance() .expression("Wurzel(var1)") .build() .params(params) .calc(); Assert.assertEquals(2.0, result, 0); } @Test public void calc_Function_Pow() { Map<String, Object> params = new HashMap<>(); params.put("var1", 4); Double result = SCalcBuilder.doubleInstance() .expression("Wurzel(var1) ^ 3") .build() .params(params) .calc(); Assert.assertEquals(8.0, result, 0); } @Test public void calc_MultiplyAll() { Double result = SCalcBuilder.doubleInstance() .multiplyExpression() .build() .params(2, 3, null, 4) .calc(); Assert.assertEquals(0.0, result, 0); } @Test public void calc_NotRemoveNullParameters() { Double result = SCalcBuilder.doubleInstance() .multiplyExpression() .build() .params(2, 3, null, 4) .calc(); Assert.assertEquals(0.0, result, 0); } @Test public void calc_AddAll() { Double result = SCalcBuilder.doubleInstance() .sumExpression() .build() .params(2, 3, 2) .calc(); Assert.assertEquals(7.0, result, 0); } @Test public void calc_PowAll() { Double result = SCalcBuilder.doubleInstance() .powExpression() .build() .params(2, 3, 2) .calc(); Assert.assertEquals(64.0, result, 0); } @Test public void calc_DivideAll() { Double result = SCalcBuilder.doubleInstance() .divideExpression() .build() .params(20, 5, 2) .calc(); Assert.assertEquals(2.0, result, 0); } @Test public void calc_ParamNameValue() { Double result = SCalcBuilder.doubleInstance() .subtractExpression() .build() .params("a", 10, "b", 100, "c", 20) .calc(); Assert.assertEquals(-110.0, result, 0); } @Test public void calc_Money() { Map<String, Object> params = new HashMap<>(); params.put("var1", 4); Money result = SCalcBuilder.instanceFor(Money.class) .expression("(√(16, 4) + 2) / (99.99 - 79.99 - 16)") .registerConverter(Money.class, MoneyConverter.class) .build() .params(params) .calc(); Assert.assertEquals(1.0, result.getValue(), 0); } @Test public void calc_Money_Global() { SCalcBuilder.registerGlobalConverter(Money.class, MoneyConverter.class); Money result = SCalcBuilder.instanceFor(Money.class) .expression("var1 - var2") .build() .params("var1", 10.9, "var2", 0.9) .calc(); Assert.assertEquals(10.0, result.getValue(), 0); } @Test public void calc_Pow() { Double result = SCalcBuilder.doubleInstance() .expression("Wurzel(4 ^ 2)") .build() .calc(); Assert.assertEquals(4.0, result, 0); } @Test public void calc_ParamName() { Double result = SCalcBuilder.doubleInstance() .expression("u*Wurzel(u)") .build() .parameter("u", 81) .calc(); Assert.assertEquals(9.0 * 81.0, result, 0); } @Test public void calc_ComplexMultiline() { Double result = SCalcBuilder.doubleInstance() .expression( "f(x, y)=10 + (x * y) - 1;\r\n" + "g(x) = wurzel(x);" + "variable1 = 7; " + "return f(2, 3) + g(4) - variable1;") .buildAndCalc(); Assert.assertEquals(10.0, result, 0); } @Test(expected = CalculationException.class) public void calc_ComplexMultiline_NoReturn() { SCalcBuilder.doubleInstance() .expression( "a=10;\r\n" + "b=12;") .buildAndCalc(); } @Test public void calc_ComplexMultiline2() { Double result = SCalcBuilder.doubleInstance() .expression( "f(x, y)=10 + (x * y) - 1;\r\n" + "g(x) = wurzel(x);" + "variable1 = 7; " + "return f(2, 3) + g(4) - variable1;") .buildAndCalc(); Assert.assertEquals(10.0, result, 0); } @Test public void calc_MultiParam() { Double result = SCalcBuilder.doubleInstance() .expression("Wurzel(4, 2)") .buildAndCalc(); Assert.assertEquals(2.0, result, 0); } @Test public void calc_SumAllParams() { Double result = SCalcBuilder.doubleInstance() .expression("Sum(ALL_PARAMS) * 2") .build() .params(10, 5, 2, 7) .calc(); Assert.assertEquals(48.0, result, 0); } @Test public void calc_SumAllParams_NoParams() { Double result = SCalcBuilder.doubleInstance() .expression("Sum(ALL_PARAMS)") .buildAndCalc(); Assert.assertEquals(0.0, result, 0); } @Test public void calc_GlobalConstants() { Double result = SCalcBuilder.doubleInstance() .expression("PI * 2 - π") .resultScale(2) .buildAndCalc(); Assert.assertEquals(3.14, result, 0); } @Test public void calc_CaseInsensitiveNames() { Double result = SCalcBuilder.doubleInstance() .expression("pI * 2 - π + VAR1") .resultScale(2) .build() .parameter("var1", 1) .calc(); Assert.assertEquals(4.14, result, 0); } @Test public void calc_FloatingPoint1() { Double result = SCalcBuilder.doubleInstance() .expression("a+b") .build() .parameter("a", 0.7) .parameter("b", 0.1) .calc(); Assert.assertEquals(0.8, result, 0); Assert.assertEquals(0.7999999999999999, 0.7 + 0.1, 0); result = SCalcBuilder.doubleInstance() .expression("0.9 - 0.1") .buildAndCalc(); Assert.assertEquals(0.8, result, 0); Assert.assertEquals(0.8, 0.9 - 0.1, 0); } @Test public void calc_0E10() { Double result = SCalcBuilder.doubleInstance() .expression("a+b") .build() .parameter("a", new BigDecimal("0E-10")) .parameter("b", 5) .calc(); Assert.assertEquals(5.0, result, 0); } @Test public void calc_SumDtos() { Set<TestDto> dtos = new HashSet<>(); dtos.add(new TestDto(10.0)); dtos.add(new TestDto(5.1)); dtos.add(null); dtos.add(new TestDto(2.0)); INumberConverter<TestDto> numberConverter = new INumberConverter<TestDto>() { @Override public BigDecimal toBigDecimal(TestDto input) { if (input == null) { return null; } return BigDecimal.valueOf(input.getValueToExtract()).setScale(2, RoundingMode.HALF_UP); } @Override public TestDto fromBigDecimal(BigDecimal input) { throw new RuntimeException("Not implemented"); } }; Double result = SCalcBuilder.doubleInstance() .sumExpression() .registerConverter(TestDto.class, numberConverter) .build() .paramsAsCollection(dtos) .calc(); Assert.assertEquals(17.1, result, 0); result = SCalcBuilder.doubleInstance() .expression("∑(ALL_PARAMS)") .registerConverter(TestDto.class, numberConverter) .build() .paramsAsCollection(dtos) .calc(); Assert.assertEquals(17.1, result, 0); } @Test public void calc_PowChar() { Double result = SCalcBuilder.doubleInstance() .expression("a² / b³") .build() .params("a", 3, "b", 2) .calc(); Assert.assertEquals(1.125, result, 0); } @Test public void calc_Min() { Double result = SCalcBuilder.doubleInstance() .expression("min(16, 4, 24, 1)") .buildAndCalc(); Assert.assertEquals(1.0, result, 0); } @Test public void calc_Min2() { Double result = SCalcBuilder.doubleInstance() .expression("min(16, -4, 24, 1)") .buildAndCalc(); Assert.assertEquals(-4.0, result, 0); } @Test public void calc_Min3() { Double result = SCalcBuilder.doubleInstance() .expression("-min(16, -4 / 2, 24, 1)") .buildAndCalc(); Assert.assertEquals(2.0, result, 0); } @Test public void calc_Max() { Double result = SCalcBuilder.doubleInstance() .expression("max(16, 4, 24, 1)") .buildAndCalc(); Assert.assertEquals(24.0, result, 0); } @Test public void calc_Avg() { Double result = SCalcBuilder.doubleInstance() .expression("avg(16, 4, 24, 1)") .buildAndCalc(); Assert.assertEquals(11.25, result, 0); } @Test public void calc_Abs() { Double result = SCalcBuilder.doubleInstance() .expression("abs(16)") .buildAndCalc(); Assert.assertEquals(16.0, result, 0); } @Test public void calc_Abs2() { Double result = SCalcBuilder.doubleInstance() .expression("abs(-16)") .buildAndCalc(); Assert.assertEquals(16.0, result, 0); } @Test public void calc_MultiLineCalculation() { Double result = SCalcBuilder.doubleInstance() .expression( "umsatzProMonat = 50000;" + "umsatzProJahr = umsatzProMonat * 12;" + "kostenProMonat = 2000;" + "kostenProJahr = kostenProMonat * 12;" + "gewinnProJahr = umsatzProJahr - kostenProJahr;" + "return gewinnProJahr;" ) .buildAndCalc(); Assert.assertEquals(576000.0, result, 0); } @Test public void calc_Scale() { Double result = SCalcBuilder.doubleInstance() .expression("root(11) * 100000") .calculationScale(4) .buildAndCalc(); Assert.assertEquals(331660.0, result, 0); System.err.println(Math.sqrt(11)); } @Test(expected = CalculationException.class) public void calc_DivisionByZero() { try { SCalcBuilder.bigDecimalInstance() .expression("(var1 / var2) + 77") .build() .parameter("var1", 100.0) .parameter("var2", 0.0) .calc(); } catch (Throwable e) { e.printStackTrace(); throw e; } } @Test public void testNullParameter() { double result = SCalcBuilder.doubleInstance() .expression("AVG(anleihen, investmentfonds, aktien, hedgefonds, optionsscheine, zertifikate, beteiligungen)") .resultScale(2, RoundingMode.HALF_UP) .build() .parameter("anleihen", 1.0) .parameter("investmentfonds", 2.0) .parameter("aktien", 3.0) .parameter("hedgefonds", null) .parameter("optionsscheine", 1.0) .parameter("zertifikate", 2.0) .parameter("beteiligungen", 3.0) .calc(); Assert.assertEquals(12.0 / 7.0, result, 0.01); } @Test public void testNullParameter_FirstPlace() { int result = SCalcBuilder.doubleInstance() .expression("AVG(anleihen, investmentfonds, aktien, hedgefonds, optionsscheine, zertifikate, beteiligungen)") .resultScale(0, RoundingMode.HALF_UP) .build() .parameter("anleihen", null) .parameter("investmentfonds", null) .parameter("aktien", null) .parameter("hedgefonds", null) .parameter("optionsscheine", null) .parameter("zertifikate", null) .parameter("beteiligungen", null) .calc() .intValue(); Assert.assertEquals(0, result); } @Test public void testNullParameter_Round_OneParam() { double result = SCalcBuilder.doubleInstance() .expression("round(0.5)") .buildAndCalc(); Assert.assertEquals(0.5, result, 0); } @Test public void testNullParameter_Round_TwoParams() { double result = SCalcBuilder.doubleInstance() .expression("round(0.5, 0)") .buildAndCalc(); Assert.assertEquals(1.0, result, 0); } @Test public void testNullParameter_Round_ThreeParams() { double result = SCalcBuilder.doubleInstance() .expression("round(0.5, 0, HALF_DOWN)") .buildAndCalc(); Assert.assertEquals(0.0, result, 0); } @Test public void testNullParameter_Round_ThreeParams2() { double result = SCalcBuilder.doubleInstance() .expression("round(0.999999999, 4, HALF_UP)") .buildAndCalc(); Assert.assertEquals(1.0, result, 0); } @Test public void testParamsAsList() { double result = SCalcBuilder.doubleInstance() .expression("param0 + param1 - param2 + param3") .build() .params(10.0, 20.0, 5.0) .params(1) .calc(); Assert.assertEquals(26.0, result, 0); } @Test public void testParametersWithExtractor() { Set<TestDto> dtos = new HashSet<>(); dtos.add(new TestDto(100.0)); dtos.add(new TestDto(0.01)); dtos.add(null); dtos.add(new TestDto(200.0)); dtos.add(new TestDto(null)); double result = SCalcBuilder.doubleInstance() .sumExpression() .build() .paramsAsCollection(TestDto::getValueToExtract, dtos) .params(TestDto::getValueToExtract, dtos.toArray(new TestDto[] {})) .calc(); Assert.assertEquals(600.02, result, 0); } @Test public void testSinFunction() { double result = SCalcBuilder.doubleInstance() .expression("sin(6)") .buildAndCalc(); Assert.assertEquals(-0.27941549819, result, 0.00001); } @Test public void testCosFunction() { double result = SCalcBuilder.doubleInstance() .expression("cos(6)") .buildAndCalc(); Assert.assertEquals(0.96017028665, result, 0.00001); } @Test public void testTanFunction() { double result = SCalcBuilder.doubleInstance() .expression("tan(6)") .buildAndCalc(); Assert.assertEquals(-0.29100619138, result, 0.00001); } @Test public void testLnFunction() { double result = SCalcBuilder.doubleInstance() .expression("ln(6)") .buildAndCalc(); Assert.assertEquals(1.79175946923, result, 0.00001); } @Test public void testLogFunction() { double result = SCalcBuilder.doubleInstance() .expression("log(6)") .buildAndCalc(); Assert.assertEquals(0.77815125038, result, 0.00001); } @Test public void testAllParamsConstant() { List<TestDto> dtos = new ArrayList<>(); dtos.add(new TestDto(10.0)); dtos.add(new TestDto(20.0)); dtos.add(new TestDto(30.0)); dtos.add(new TestDto(40.0)); double result = SCalcBuilder.doubleInstance() .expression("summe_alle = sum(ALL_PARAMS); faktor(x) = param0 * param2 * x; return summe_alle / faktor(3);") .debug(true) .debugLogger(System.out::println) .build() .paramsAsCollection(TestDto::getValueToExtract, dtos) .calc(); Assert.assertEquals(0.11111111111, result, 0.00001); } @Test public void testConstantNameAsFunctionName() { double result = SCalcBuilder.doubleInstance() .expression("E(x)=E * x; return E(2);") .debug(true) .buildAndCalc(); Assert.assertEquals(Math.E * 2, result, 0.0001); } @Test public void testConstantNameInFunctionName() { double result = SCalcBuilder.doubleInstance() .expression("funcE(x)=E * x; return funcE(2);") .debug(true) .buildAndCalc(); Assert.assertEquals(Math.E * 2, result, 0.0001); } @Test public void testConstantNameInParamName() { double result = SCalcBuilder.doubleInstance() .expression("paramE * 2") .debug(true) .build() .parameter("paramE", 2) .calc(); Assert.assertEquals(4.0, result, 0); } @Test(expected = CalculationException.class) public void testInvalidAssignment() { SCalcBuilder.doubleInstance() .expression("=2") .buildAndCalc(); } @Test public void testEmptyExpression() { double result = SCalcBuilder.doubleInstance() .expression("") .buildAndCalc(); Assert.assertEquals(0.0, result, 0); } @Test(expected = CalculationException.class) public void testUnknownFunction() { SCalcBuilder.doubleInstance() .expression("abc(2)") .buildAndCalc(); } @Test public void testOnlyNumberInput() { double result = SCalcBuilder.doubleInstance() .expression("5.5") .buildAndCalc(); Assert.assertEquals(5.5, result, 0); } @Test public void testSpaces() { Assert.assertEquals(4.0, SCalcBuilder.doubleInstance().expression(" 12 - 8 ").buildAndCalc(), 0); Assert.assertEquals(133.0, SCalcBuilder.doubleInstance().expression("142 -9 ").buildAndCalc(), 0); } @Test public void testParenthesis() { Assert.assertEquals(5.0, SCalcBuilder.doubleInstance().expression("(((((5)))))").buildAndCalc(), 0); Assert.assertEquals(30.0, SCalcBuilder.doubleInstance().expression("(( ((2)) + 4))*((5))").buildAndCalc(), 0); } @Test public void testUnbalancedParenthesis() { Assert.assertEquals(6.0, SCalcBuilder.doubleInstance().expression("((2)) * ((3").buildAndCalc(), 0); Assert.assertEquals(6.0, SCalcBuilder.doubleInstance().expression("((2) * ((3").buildAndCalc(), 0); Assert.assertEquals(24.0, SCalcBuilder.doubleInstance().expression("6 * ( 2 + 2").buildAndCalc(), 0); } @Test(expected = CalculationException.class) public void testUnbalancedParenthesisError() { SCalcBuilder.doubleInstance() .expression("6 * ) 2 + 2") .buildAndCalc(); } @Test public void testComplexFormula() { int a = 6; double b = 4.32; short c = (short) 24.15; double result = SCalcBuilder.doubleInstance() .expression("(((9-a/2)*2-b)/2-a-1)/(2+c/(2+4))") .calculationScale(16) .resultScale(16) .build() .params("a", a, "b", b, "c", c) .calc(); Assert.assertEquals((((9 - a / 2.0) * 2 - b) / 2 - a - 1) / (2 + c / (2.0 + 4.0)), result, 0); } @Test public void testRoundingZero() { double result = SCalcBuilder.doubleInstance() .expression("round(a, 2) + round(b, 3) + round(c, 4)") .build() .parameter("a", "0.002") .parameter("b", "0.0002") .parameter("c", "0.00002") .calc(); Assert.assertEquals(0.0, result, 0); } @Test public void testRounding() { BigDecimal result = SCalcBuilder.bigDecimalInstance() .expression("round(a, 2) + round(b, 3) + round(c, 5)") .resultScale(6) .build() .parameter("a", "0.002") .parameter("b", "0.0002") .parameter("c", "0.00002") .calc(); Assert.assertEquals("0.000020", result.toPlainString()); } @Test public void testRounding_CalculationScaleForSumCalculation() { BigDecimal result = SCalcBuilder.bigDecimalInstance() .expression("round(a, 2) + round(b, 3) + round(c, 5)") .resultScale(6) .calculationScale(3) .build() .parameter("a", "0.002") .parameter("b", "0.0002") .parameter("c", "0.00002") .calc(); Assert.assertEquals("0.000000", result.toPlainString()); } }
27.033776
113
0.566909
55b65ded3b2d85e9c9e00adb65af0160835404bd
5,671
import java.io.*; import java.util.*; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Group; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.stage.Stage; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; public class GraphicsAttempt extends Application { public static TextArea gameText; public TextField userText; int roll; int numberOfMoves = 0; static Character player; static GameStructure gameMap; boolean movesLeft = true; boolean win = false; boolean dead = false; LinkedHashMap<String, Commands> commands = new LinkedHashMap<>(); public static LinkedHashMap<String, ArrayList<String>> dialogue = new LinkedHashMap<>(); public static void main(String[] args) { player = new Character(); gameMap = new GameStructure(player); launch(GraphicsAttempt.class, args); } @Override public void start(Stage theStage) throws Exception { theStage.setTitle("Silicon Valley"); Scene theScene = StartScene.makeScene(); theStage.setScene(theScene); //replace with button theScene.setOnKeyPressed(new EventHandler<KeyEvent>() { public void handle(KeyEvent e) { if (e.getCode() == KeyCode.SPACE) theStage.setScene(new Scene(gameScene())); } }); theStage.show(); } public Parent gameScene() { Group game = new Group(); Canvas canvas = new Canvas(1000, 500); game.getChildren().add(canvas); GraphicsContext gc = canvas.getGraphicsContext2D(); GraphicsContext gc2 = canvas.getGraphicsContext2D(); Image backdrop = new Image("Images/forestThing.jpg", 1000, 370, false, false); Image dirt = new Image("Images/dirt.jpg", 1000, 365, false, false); gc.drawImage(backdrop, 0, 0); gc2.drawImage(dirt, 0, 365); gameText = new TextArea(); gameText.setEditable(false); gameText.setPrefSize(1000, 100); gameText.setOpacity(0.75); userText = new TextField("Type here"); userText.setFocusTraversable(true); userText.setPrefSize(1000, 0); userText.setOpacity(0.75); VBox box = new VBox(7, gameText, userText); box.setPrefSize(1000, 125); box.setPadding(new Insets(7)); box.setLayoutY(372); //game.getChildren().add(userText); //game.getChildren().add(gameText); game.getChildren().add(box); initCommands(); initGame(); if(win) return WinScene.makeScene(); userText.setOnAction(e -> { String input = userText.getText(); userText.clear(); onInput(input); }); return game; } public void initGame() { gameMap.index = -1; print("Welcome to Silicon Valley!"); print("You are going to be adventuring throughout an unknown world in this game. Your goal is to make it to the end of the world and survive!"); print("You will have a set amount of hp, food supplies, and water supplies at the start of the journey. Keep track of them as you progress."); print("Various spaces you stop at may throw you into minigame scenarios, or may let you pause for a chance to recharge your character."); print("You only have 30 moves to make it to the end of the game, though, so be careful how many breaks you take!"); print("If your health, food, or water reach 0, it's game over."); print("Can you survive the Silicon Valley?\n"); print("Type 'roll' to roll or 'help' for more commands."); } public void initCommands() { commands.put("exit", new Commands("exit", "Close the game", Platform::exit)); commands.put("roll", new Commands("roll", "Roll the dice", this::roll)); commands.put("stats", new Commands("stats", "Display player stats", this::stats)); commands.put("map", new Commands("map", "Tell player position", this::map)); } public void onInput(String line) { if(commands.containsKey(line)) commands.get(line).execute(); else print("There is no such command."); } public static void print(String text) { gameText.appendText(text + "\n"); } public void roll() { roll = DiceAndTimer.roll(); numberOfMoves++; print("\nYou rolled across the map..."); print("You rolled: " + roll); gameMap.index += roll; checkPosition(); } public void stats() { print("Food left: " + player.getFood()); print("HP left: " + player.getHP()); print("Water left: " + player.getWater()); } public void map() { print("You are at position " + (gameMap.index + 1) + " out of 25"); } public void checkPosition() { if(gameMap.index >= 25) { print("\nCongratulations! You made it to the end of the Silicon Valley!!"); print("Here's a reward for your win:"); win = true; } else { print("beep boop"); //gameMap.gameSpace(player); TextScen.food1(); } } }
31.159341
152
0.614354
75da31e71bafc646e8fd8be1f9ccc0f8636940c3
1,874
package cn.hkxj.platform.service.wechat.handler.messageHandler; import cn.hkxj.platform.builder.TextBuilder; import cn.hkxj.platform.config.wechat.WechatMpPlusProperties; import cn.hkxj.platform.service.wechat.StudentBindService; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.session.WxSessionManager; import me.chanjar.weixin.mp.api.WxMpMessageHandler; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; import org.springframework.stereotype.Component; import javax.annotation.Resource; import javax.annotation.Resources; import java.util.Map; /** * 用户关注事件发送引导信息 */ @Slf4j @Component public class SubscribeEventHandler implements WxMpMessageHandler { @Resource private TextBuilder textBuilder; @Resource private StudentBindService studentBindService; @Resource private WechatMpPlusProperties wechatMpPlusProperties; @Override public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) { String appId = wxMpService.getWxMpConfigStorage().getAppId(); String fromUser = wxMessage.getFromUser(); StringBuffer buffer = new StringBuffer(); buffer.append("同学,你终于找到我们黑科校际了!我们在这已经等候多时了,很高兴遇见你~"); buffer.append("\n\n"); buffer.append("为了更好地为你服务,").append(studentBindService.getBindUrlByOpenid(appId, fromUser, "请点击我进行绑定!!!")); if(wechatMpPlusProperties.getAppId().equals(appId)){ buffer.append("\n\n").append("回复 【订阅】,即可开启课程成绩提醒黑科技"); } buffer.append("\n\n").append("使用过程中有问题记得在后台留言,我们会尽快解决的"); return textBuilder.build(new String(buffer), wxMessage, wxMpService); } }
35.358491
150
0.762006
5223a98c5aed0412448881bf8936ff890ccc432b
5,442
/* * Copyright 1999-2004 The Apache Software 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. */ /* * $Id: ProcessorKey.java,v 1.14 2004/08/17 18:18:08 jycli Exp $ */ package org.apache.xalan.processor; import java.util.Vector; import org.apache.xalan.res.XSLMessages; import org.apache.xalan.res.XSLTErrorResources; import org.apache.xalan.templates.KeyDeclaration; import org.xml.sax.Attributes; /** * TransformerFactory for xsl:key markup. * <pre> * <!ELEMENT xsl:key EMPTY> * <!ATTLIST xsl:key * name %qname; #REQUIRED * match %pattern; #REQUIRED * use %expr; #REQUIRED * > * </pre> * @see <a href="http://www.w3.org/TR/xslt#dtd">XSLT DTD</a> * @see <a href="http://www.w3.org/TR/xslt#key">key in XSLT Specification</a> */ class ProcessorKey extends XSLTElementProcessor { static final long serialVersionUID = 4285205417566822979L; /** * Receive notification of the start of an xsl:key element. * * @param handler The calling StylesheetHandler/TemplatesBuilder. * @param uri The Namespace URI, or the empty string if the * element has no Namespace URI or if Namespace * processing is not being performed. * @param localName The local name (without prefix), or the * empty string if Namespace processing is not being * performed. * @param rawName The raw XML 1.0 name (with prefix), or the * empty string if raw names are not available. * @param attributes The attributes attached to the element. If * there are no attributes, it shall be an empty * Attributes object. */ public void startElement( StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes) throws org.xml.sax.SAXException { KeyDeclaration kd = new KeyDeclaration(handler.getStylesheet(), handler.nextUid()); kd.setDOMBackPointer(handler.getOriginatingNode()); kd.setLocaterInfo(handler.getLocator()); setPropertiesFromAttributes(handler, rawName, attributes, kd); handler.getStylesheet().setKey(kd); } /** * Set the properties of an object from the given attribute list. * @param handler The stylesheet's Content handler, needed for * error reporting. * @param rawName The raw name of the owner element, needed for * error reporting. * @param attributes The list of attributes. * @param target The target element where the properties will be set. */ void setPropertiesFromAttributes( StylesheetHandler handler, String rawName, Attributes attributes, org.apache.xalan.templates.ElemTemplateElement target) throws org.xml.sax.SAXException { XSLTElementDef def = getElemDef(); // Keep track of which XSLTAttributeDefs have been processed, so // I can see which default values need to be set. Vector processedDefs = new Vector(); int nAttrs = attributes.getLength(); for (int i = 0; i < nAttrs; i++) { String attrUri = attributes.getURI(i); String attrLocalName = attributes.getLocalName(i); XSLTAttributeDef attrDef = def.getAttributeDef(attrUri, attrLocalName); if (null == attrDef) { // Then barf, because this element does not allow this attribute. handler.error(attributes.getQName(i) + "attribute is not allowed on the " + rawName + " element!", null); } else { String valueString = attributes.getValue(i); if (valueString.indexOf(org.apache.xpath.compiler.Keywords.FUNC_KEY_STRING + "(") >= 0) handler.error( XSLMessages.createMessage( XSLTErrorResources.ER_INVALID_KEY_CALL, null), null); processedDefs.addElement(attrDef); attrDef.setAttrValue(handler, attrUri, attrLocalName, attributes.getQName(i), attributes.getValue(i), target); } } XSLTAttributeDef[] attrDefs = def.getAttributes(); int nAttrDefs = attrDefs.length; for (int i = 0; i < nAttrDefs; i++) { XSLTAttributeDef attrDef = attrDefs[i]; String defVal = attrDef.getDefault(); if (null != defVal) { if (!processedDefs.contains(attrDef)) { attrDef.setDefAttrValue(handler, target); } } if (attrDef.getRequired()) { if (!processedDefs.contains(attrDef)) handler.error( XSLMessages.createMessage( XSLTErrorResources.ER_REQUIRES_ATTRIB, new Object[]{ rawName, attrDef.getName() }), null); } } } }
35.109677
106
0.62771
eae514d29b0979ac327a6d17d00d4d859e05ba80
3,457
package com.mongodb; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import static com.mongodb.client.model.Filters.*; import org.bson.Document; import org.bson.conversions.Bson; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Author Mike Clovis * Date: 10/22/2015 * Time: 2:36 PM */ public class FindWithFilterTest { public static void main(String[] args) { MongoClient client = new MongoClient(); MongoDatabase db = client.getDatabase("course"); MongoCollection<Document> collection = db.getCollection("findWithFilterTest"); collection.drop(); //insert 10 documents with random x and y for(int idx = 0;idx<10;idx++){ collection.insertOne(new Document("x",new Random().nextInt(2)) .append("y",new Random().nextInt(100))); } //put all into a list List<Document> docs = collection.find().into(new ArrayList<Document>()); for(Document doc:docs){ Helper.prettyPrintJSON(doc); } long count = collection.count(); System.out.println("\nCount: "); System.out.println(count); Bson filterXByDocument = new Document("x",0); // or this is the same Bson filterXByHelper = eq("x", 0); //static import of Filters System.out.println("\nCount of x==0"); System.out.println(collection.count(filterXByDocument)); System.out.println("Let's limit by filter what is returned"); List<Document> filteredDocs = collection.find(filterXByHelper).into(new ArrayList<Document>()); System.out.println("\nCount returned: "); System.out.println(filteredDocs.size()); System.out.println(""); for(Document doc:filteredDocs){ Helper.prettyPrintJSON(doc); } // y is greater than 10 Bson filterYByDocument = new Document("y", new Document("$gt",10)); //or equivalent Bson filterYByHelper = gt("y",10);// again using static import of filters System.out.println("\nCount of docs that match y greater than 10"); System.out.println(collection.count(filterYByHelper)); filteredDocs = collection.find(filterYByDocument).into(new ArrayList<Document>()); System.out.println("\nActual number returned"); System.out.println(filteredDocs.size()); System.out.println(); for(Document doc:filteredDocs){ Helper.prettyPrintJSON(doc); } // create an interval for y between 10 and 90 filterYByDocument = new Document("y", new Document("$gt",10).append("$lt",90)); //implicit and filterYByHelper = and(gt("y", 10), lt("y", 90)); System.out.println("\nCount of documents in collection that match: "); System.out.println(collection.count(filterYByDocument)); filteredDocs = collection.find(filterYByHelper).into(new ArrayList<Document>()); System.out.println("\nNumber of documents returned: "); System.out.println(filteredDocs.size()); System.out.println("\nAnd the docs are: "); for(Document doc:filteredDocs){ Helper.prettyPrintJSON(doc); } } }
28.570248
91
0.602546
00bd54a31542cc1a95aa078f855315e28b6746ae
3,452
package org.vorthmann.j3d; import java.awt.Component; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; /** * Description here. * * @author Scott Vorthmann 2003 */ public class MouseListenerSwitch extends MouseAdapter implements MouseTool { protected MouseTool first, second; protected MouseEvent lastPosition; protected boolean dragging = false, wasSecond = false; public MouseListenerSwitch() {} public void setFirst( MouseTool listener ) { first = listener; } public void setSecond( MouseTool listener ) { second = listener; } public synchronized void toggle() { boolean inDrag = dragging && lastPosition != null; if ( inDrag ) mouseReleased( lastPosition ); MouseTool temp = first; first = second; second = temp; if ( inDrag ) mousePressed( lastPosition ); } @Override public void attach( Component component ) { component .addMouseListener( this ); component .addMouseMotionListener( this ); component .addMouseWheelListener( this ); } @Override public void detach( Component component ) { component .removeMouseListener( this ); component .removeMouseMotionListener( this ); component .removeMouseWheelListener( this ); } protected static boolean isSecondButton( MouseEvent e ) { return ( e .getModifiers() & ( MouseEvent.BUTTON2_MASK | MouseEvent.BUTTON3_MASK ) ) != 0; } @Override public void mouseClicked( MouseEvent e ) { lastPosition = e; if ( isSecondButton( e ) ) second .mouseClicked( e ); else first .mouseClicked( e ); } @Override public void mousePressed( MouseEvent e ) { lastPosition = e; dragging = true; wasSecond = isSecondButton( e ); if ( wasSecond ) second .mousePressed( e ); else first .mousePressed( e ); } @Override public void mouseDragged( MouseEvent e ) { lastPosition = e; dragging = true; boolean wasFirst = ! wasSecond; wasSecond = isSecondButton( e ); if ( wasSecond ) { if ( wasFirst ) { first .mouseReleased( lastPosition ); second .mousePressed( lastPosition ); } second .mouseDragged( e ); } else { if ( ! wasFirst ) { second .mouseReleased( lastPosition ); first .mousePressed( lastPosition ); } first .mouseDragged( e ); } } @Override public void mouseMoved( MouseEvent e ) { lastPosition = e; first .mouseMoved( e ); } @Override public void mouseReleased( MouseEvent e ) { lastPosition = e; dragging = false; boolean wasFirst = ! wasSecond; wasSecond = isSecondButton( e ); if ( wasSecond ) { if ( wasFirst ) { first .mouseReleased( lastPosition ); second .mousePressed( lastPosition ); } second .mouseReleased( e ); } else { if ( wasFirst ) { second .mouseReleased( lastPosition ); first .mousePressed( lastPosition ); } first .mouseReleased( e ); } } /* (non-Javadoc) * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent) */ @Override public void mouseWheelMoved( MouseWheelEvent e ) { wasSecond = isSecondButton( e ); if ( wasSecond ) second .mouseWheelMoved( e ); else first .mouseWheelMoved( e ); } }
21.710692
98
0.634705
ff3ca5f886ef2971b3911224bd73e357ef6aa7ab
1,645
package com.zkyking.springaop.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.Collections; /** * @author zky * @date 2019/3/1014:16 */ @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2).select() .apis(RequestHandlerSelectors.basePackage("cn.itweknow.sbaop.controller")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfo("Spring Boot项目集成Swagger实例文档", "我的博客网站:https://itweknow.cn,欢迎大家访问。", "API V1.0", "Terms of service", new Contact("名字想好没", "https://itweknow.cn", "gancy.programmer@gmail.com"), "Apache", "http://www.apache.org/", Collections.emptyList()); } }
35.76087
128
0.580547
f9293fe95c4d90c9ef713efe64ce813f18544977
1,248
package com.ibm.ABCDEF; import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.TimeUnit; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.test.context.junit4.SpringRunner; import com.ibm.ABCDEF.config.BlogProperties; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class ApplicationTests { @Autowired private BlogProperties blogProperties; @Autowired private RedisTemplate<String, String> stringRedisTemplate; // @Test public void getHello() throws Exception { assertThat(blogProperties.getName()).isEqualTo("程序猿DD"); assertThat(blogProperties.getTitle()).isEqualTo("Spring Boot教程"); } @Test public void operationRedis() { for (;;) { try { TimeUnit.MILLISECONDS.sleep(500); stringRedisTemplate.boundValueOps("name").set(String.valueOf(System.currentTimeMillis())); } catch (InterruptedException e) { e.printStackTrace(); } } } }
28.363636
94
0.78766
a7a9d0bde5f852359ceaac50c814e1bfbae4fb6d
3,644
package com.minapp.android.sdk.content; import androidx.annotation.NonNull; import com.minapp.android.sdk.Global; import com.minapp.android.sdk.database.query.Query; import com.minapp.android.sdk.util.BaseCallback; import com.minapp.android.sdk.util.PagedList; import com.minapp.android.sdk.util.Util; import java.util.concurrent.Callable; public abstract class Contents { /** * 内容列表 * 分类 ID 和内容库 ID 至少填一个 * @see Content#QUERY_CATEGORY_ID * @see Content#QUERY_CONTENT_GROUP_ID * @param query * @return * @throws Exception */ public static PagedList<Content> contents(@NonNull Query query) throws Exception { return Global.httpApi().contents(query).execute().body().readonly(); } public static void contentsInBackground(@NonNull final Query query, @NonNull BaseCallback<PagedList<Content>> cb) { Util.inBackground(cb, new Callable<PagedList<Content>>() { @Override public PagedList<Content> call() throws Exception { return Contents.contents(query); } }); } /** * 内容明细 * @param id * @return * @throws Exception */ public static Content content(String id) throws Exception { return Global.httpApi().content(id).execute().body(); } public static void contentInBackground(final String id, @NonNull BaseCallback<Content> cb) { Util.inBackground(cb, new Callable<Content>() { @Override public Content call() throws Exception { return Contents.content(id); } }); } /** * 内容库列表 * @param query * @return * @throws Exception */ public static PagedList<ContentGroup> contentGroups(@NonNull Query query) throws Exception { return Global.httpApi().contentGroups(query).execute().body().readonly(); } public static void contentGroupsInBackground(@NonNull final Query query, @NonNull BaseCallback<PagedList<ContentGroup>> cb) { Util.inBackground(cb, new Callable<PagedList<ContentGroup>>() { @Override public PagedList<ContentGroup> call() throws Exception { return Contents.contentGroups(query); } }); } /** * 分类列表 * @param query 至少包含内容库 ID {@link ContentCategory#QUERY_GROUP_ID} * @return * @throws Exception */ public static PagedList<ContentCategory> contentCategories(@NonNull Query query) throws Exception { return Global.httpApi().contentCategories(query).execute().body().readonly(); } public static void contentCategoriesInBackground(@NonNull final Query query, @NonNull BaseCallback<PagedList<ContentCategory>> cb) { Util.inBackground(cb, new Callable<PagedList<ContentCategory>>() { @Override public PagedList<ContentCategory> call() throws Exception { return Contents.contentCategories(query); } }); } /** * 分类详情(包含第一级的子分类列表{@link ContentCategory#CHILDREN}) * @param id * @return * @throws Exception */ public static ContentCategory contentCategory(String id) throws Exception { return Global.httpApi().contentCategory(id).execute().body(); } public static void contentCategoryInBackground(final String id, @NonNull BaseCallback<ContentCategory> cb) { Util.inBackground(cb, new Callable<ContentCategory>() { @Override public ContentCategory call() throws Exception { return Contents.contentCategory(id); } }); } }
32.535714
136
0.641054
bbc76b8e7b4c724a6f5b4307c3e6df6c4fa4c8db
5,678
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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.openqa.selenium.interactions; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.openqa.selenium.interactions.internal.Coordinates; import org.openqa.selenium.internal.Locatable; /** * Unit test for all simple keyboard actions. * */ @RunWith(JUnit4.class) public class IndividualMouseActionsTest { @Mock private Mouse mockMouse; @Mock private Coordinates mockCoordinates; @Mock private Locatable locatableStub; @Before public void setUp() { MockitoAnnotations.initMocks(this); when(locatableStub.getCoordinates()).thenReturn(mockCoordinates); } @Test public void mouseClickAndHoldAction() { ClickAndHoldAction action = new ClickAndHoldAction(mockMouse, locatableStub); action.perform(); InOrder order = Mockito.inOrder(mockMouse, mockCoordinates); order.verify(mockMouse).mouseMove(mockCoordinates); order.verify(mockMouse).mouseDown(mockCoordinates); order.verifyNoMoreInteractions(); } @Test public void mouseClickAndHoldActionOnCurrentLocation() { ClickAndHoldAction action = new ClickAndHoldAction(mockMouse, null); action.perform(); InOrder order = Mockito.inOrder(mockMouse, mockCoordinates); order.verify(mockMouse).mouseDown(null); order.verifyNoMoreInteractions(); } @Test public void mouseReleaseAction() { ButtonReleaseAction action = new ButtonReleaseAction(mockMouse, locatableStub); action.perform(); InOrder order = Mockito.inOrder(mockMouse, mockCoordinates); order.verify(mockMouse).mouseMove(mockCoordinates); order.verify(mockMouse).mouseUp(mockCoordinates); order.verifyNoMoreInteractions(); } @Test public void mouseReleaseActionOnCurrentLocation() { ButtonReleaseAction action = new ButtonReleaseAction(mockMouse, null); action.perform(); InOrder order = Mockito.inOrder(mockMouse, mockCoordinates); order.verify(mockMouse).mouseUp(null); order.verifyNoMoreInteractions(); } @Test public void mouseClickAction() { ClickAction action = new ClickAction(mockMouse, locatableStub); action.perform(); InOrder order = Mockito.inOrder(mockMouse, mockCoordinates); order.verify(mockMouse).mouseMove(mockCoordinates); order.verify(mockMouse).click(mockCoordinates); order.verifyNoMoreInteractions(); } @Test public void mouseClickActionOnCurrentLocation() { ClickAction action = new ClickAction(mockMouse, null); action.perform(); InOrder order = Mockito.inOrder(mockMouse, mockCoordinates); order.verify(mockMouse).click(null); order.verifyNoMoreInteractions(); } @Test public void mouseDoubleClickAction() { DoubleClickAction action = new DoubleClickAction(mockMouse, locatableStub); action.perform(); InOrder order = Mockito.inOrder(mockMouse, mockCoordinates); order.verify(mockMouse).mouseMove(mockCoordinates); order.verify(mockMouse).doubleClick(mockCoordinates); order.verifyNoMoreInteractions(); } @Test public void mouseDoubleClickActionOnCurrentLocation() { DoubleClickAction action = new DoubleClickAction(mockMouse, null); action.perform(); InOrder order = Mockito.inOrder(mockMouse, mockCoordinates); order.verify(mockMouse).doubleClick(null); order.verifyNoMoreInteractions(); } @Test public void mouseMoveAction() { MoveMouseAction action = new MoveMouseAction(mockMouse, locatableStub); action.perform(); InOrder order = Mockito.inOrder(mockMouse, mockCoordinates); order.verify(mockMouse).mouseMove(mockCoordinates); order.verifyNoMoreInteractions(); } @Test public void mouseMoveActionToCoordinatesInElement() { MoveToOffsetAction action = new MoveToOffsetAction(mockMouse, locatableStub, 20, 20); action.perform(); InOrder order = Mockito.inOrder(mockMouse, mockCoordinates); order.verify(mockMouse).mouseMove(mockCoordinates, 20, 20); order.verifyNoMoreInteractions(); } @Test public void mouseContextClickAction() { ContextClickAction action = new ContextClickAction(mockMouse, locatableStub); action.perform(); InOrder order = Mockito.inOrder(mockMouse, mockCoordinates); order.verify(mockMouse).mouseMove(mockCoordinates); order.verify(mockMouse).contextClick(mockCoordinates); order.verifyNoMoreInteractions(); } @Test public void mouseContextClickActionOnCurrentLocation() { ContextClickAction action = new ContextClickAction(mockMouse, null); action.perform(); InOrder order = Mockito.inOrder(mockMouse, mockCoordinates); order.verify(mockMouse).contextClick(null); order.verifyNoMoreInteractions(); } }
32.445714
89
0.756252
f49ed08b0299da55b2822d903294cc5890d4790f
4,734
/* * Copyright (c) 2019 Dario Lucia (https://www.dariolucia.eu) * * 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 eu.dariolucia.ccsds.tmtc.cop1.fop; import java.util.EnumMap; import java.util.Map; import java.util.function.Function; public abstract class AbstractFopState { protected final FopEngine engine; protected final Map<FopEvent.EventNumber, Function<FopEvent, AbstractFopState>> event2handler = new EnumMap<>(FopEvent.EventNumber.class); public AbstractFopState(FopEngine engine) { this.engine = engine; registerHandlers(); } protected abstract void registerHandlers(); public AbstractFopState event(FopEvent event) { Function<FopEvent, AbstractFopState> handler = event2handler.get(event.getNumber()); if(handler != null) { return handler.apply(event); } else { return this; } } public abstract FopState getState(); protected AbstractFopState reject(FopEvent fopEvent) { engine.reject(fopEvent); return this; } protected AbstractFopState ignore(FopEvent fopEvent) { // NOSONAR event required to match event interface approach // Ignore return this; } protected AbstractFopState e21(FopEvent fopEvent) { engine.accept(fopEvent.getFrame()); engine.transmitTypeBdFrame(fopEvent.getFrame()); return this; } // Except for S6 protected AbstractFopState e29(FopEvent fopEvent) { engine.accept(fopEvent.getDirectiveTag(), fopEvent.getDirectiveId(), fopEvent.getDirectiveQualifier()); engine.alert(FopAlertCode.TERM); engine.confirm(fopEvent.getDirectiveTag(), fopEvent.getDirectiveId(), fopEvent.getDirectiveQualifier()); return new S6FopState(engine); } protected AbstractFopState e36(FopEvent fopEvent) { engine.accept(fopEvent.getDirectiveTag(), fopEvent.getDirectiveId(), fopEvent.getDirectiveQualifier()); engine.setFopSlidingWindow(fopEvent.getDirectiveQualifier()); engine.confirm(fopEvent.getDirectiveTag(), fopEvent.getDirectiveId(), fopEvent.getDirectiveQualifier()); return this; } protected AbstractFopState e37(FopEvent fopEvent) { engine.accept(fopEvent.getDirectiveTag(), fopEvent.getDirectiveId(), fopEvent.getDirectiveQualifier()); engine.setT1Initial(fopEvent.getDirectiveQualifier()); engine.confirm(fopEvent.getDirectiveTag(), fopEvent.getDirectiveId(), fopEvent.getDirectiveQualifier()); return this; } protected AbstractFopState e38(FopEvent fopEvent) { engine.accept(fopEvent.getDirectiveTag(), fopEvent.getDirectiveId(), fopEvent.getDirectiveQualifier()); engine.setTransmissionLimit(fopEvent.getDirectiveQualifier()); engine.confirm(fopEvent.getDirectiveTag(), fopEvent.getDirectiveId(), fopEvent.getDirectiveQualifier()); return this; } protected AbstractFopState e39(FopEvent fopEvent) { engine.accept(fopEvent.getDirectiveTag(), fopEvent.getDirectiveId(), fopEvent.getDirectiveQualifier()); engine.setTimeoutType(fopEvent.getDirectiveQualifier()); engine.confirm(fopEvent.getDirectiveTag(), fopEvent.getDirectiveId(), fopEvent.getDirectiveQualifier()); return this; } protected AbstractFopState e42(FopEvent fopEvent) { // NOSONAR part of CCSDS standard engine.alert(FopAlertCode.LLIF); return new S6FopState(engine); } protected AbstractFopState e44(FopEvent fopEvent) { // NOSONAR part of CCSDS standard, separate event engine.alert(FopAlertCode.LLIF); return new S6FopState(engine); } protected AbstractFopState e45(FopEvent fopEvent) { // NOSONAR part of CCSDS standard engine.setBdOutReadyFlag(true); // engine.accept(fopEvent.getFrame()); // TODO: the CCSDS standard reports an accept here, but this would duplicate the accept at E22. Write to the CCSDS WG. return this; } protected AbstractFopState e46(FopEvent fopEvent) { // NOSONAR part of CCSDS standard, separate event engine.alert(FopAlertCode.LLIF); return new S6FopState(engine); } }
39.45
165
0.709759
e3bb72deb8463fe76d36372bf5e853a3239ac051
460
package com.whiletrue.ct4j.tasks; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface ClusterTask { String name(); int defaultPriority() default -1; int maxRetries() default -1; int retryDelay() default -1; float retryBackoffFactor() default -1; }
25.555556
44
0.765217
c54d56aa3f42cffe58a29909be3ef97b10d52b1c
2,319
package com.example.pcbackend.Components.Queue; import com.example.pcbackend.BackController.WebController; import com.example.pcbackend.Components.Component; import com.example.pcbackend.Components.Machine.MachineComponent; import com.example.pcbackend.TheSystem; import com.example.pcbackend.Timer; import java.util.ArrayList; import java.util.Queue; public class QueueComponent extends Component implements Runnable { private final QueueController MyQueue; public QueueComponent(int ID, WebController listener) { super(ID); MyQueue = new QueueController(ID, listener); } public void restart() { IsFinished.set(false); MyQueue.BeforeFinished.set(false); MyQueue.Produced.set(0); } public void StartThread(ArrayList<Thread> threads) { Thread Controller = new Thread(MyQueue); Thread ComponentThread = new Thread(this); threads.add(Controller); threads.add(ComponentThread); Controller.start(); ComponentThread.start(); } public Queue<Boolean> GetQueueReference() { return MyQueue.ToSend; } public void AddAfter(MachineComponent component) { MyQueue.ChainAfter.add(component); } public void AddInput() { MyQueue.ToSend.add(true); synchronized (MyQueue.ToSend) { MyQueue.ToSend.notify(); } } public int getID() { return ID; } @Override public void run() { boolean CheckFinish = false; while (!CheckFinish) { CheckFinish = true; for (var Component : ChainBefore) { CheckFinish &= Component.IsFinished(); } if (ID == 0) CheckFinish &= TheSystem.FinishedAiring.get(); if (CheckFinish) { MyQueue.BeforeFinished.set(true); } CheckFinish &= MyQueue.ToSend.isEmpty(); } try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } IsFinished.set(true); System.out.println("Queue " + ID + " Finished " + MyQueue.ToSend.isEmpty() + " : " + (System.currentTimeMillis() - Timer.time)); } }
28.280488
137
0.598103
4b403ef6dc52d72ede014b0204910a80cd497af5
1,955
package no.nav.modiapersonoversikt.service.plukkoppgave; import no.nav.modiapersonoversikt.legacy.api.domain.Oppgave; import no.nav.modiapersonoversikt.legacy.api.domain.Temagruppe; import no.nav.modiapersonoversikt.legacy.api.service.OppgaveBehandlingService; import no.nav.modiapersonoversikt.infrastructure.tilgangskontroll.Policies; import no.nav.modiapersonoversikt.infrastructure.tilgangskontroll.Tilgangskontroll; import java.util.List; public class PlukkOppgaveServiceImpl implements PlukkOppgaveService { private final OppgaveBehandlingService oppgaveBehandlingService; private final Tilgangskontroll tilgangskontroll; public PlukkOppgaveServiceImpl(OppgaveBehandlingService oppgaveBehandlingService, Tilgangskontroll tilgangskontroll) { this.oppgaveBehandlingService = oppgaveBehandlingService; this.tilgangskontroll = tilgangskontroll; } @Override public List<Oppgave> plukkOppgaver(Temagruppe temagruppe, String saksbehandlersValgteEnhet) { List<Oppgave> oppgaver = oppgaveBehandlingService.plukkOppgaverFraGsak(temagruppe, saksbehandlersValgteEnhet); if (!oppgaver.isEmpty() && !saksbehandlerHarTilgangTilBruker(oppgaver.get(0))) { return leggTilbakeOgPlukkNyeOppgaver(oppgaver, temagruppe, saksbehandlersValgteEnhet); } return oppgaver; } private List<Oppgave> leggTilbakeOgPlukkNyeOppgaver(List<Oppgave> oppgaver, Temagruppe temagruppe, String saksbehandlersValgteEnhet) { oppgaver.forEach(oppgave -> oppgaveBehandlingService.systemLeggTilbakeOppgaveIGsak(oppgave.oppgaveId, temagruppe, saksbehandlersValgteEnhet)); return plukkOppgaver(temagruppe, saksbehandlersValgteEnhet); } private boolean saksbehandlerHarTilgangTilBruker(Oppgave oppgave) { return tilgangskontroll .check(Policies.tilgangTilBruker.with(oppgave.fnr)) .getDecision() .isPermit(); } }
45.465116
150
0.784655
7ebc5f5dffe87e7ec5b7cb0bc3565a622f2d6a09
356
package to; import to.reports.FbPictureData; /** * Created by arkady on 06/04/16. */ public class FbPicture { private FbPictureData data; public FbPicture() { } public FbPicture(FbPictureData data) { this.data = data; } public FbPictureData getData() { return data; } public void setData(FbPictureData data) { this.data = data; } }
13.185185
42
0.688202
3b68f8ef7e5090304916798e9767fe99ff0db90a
1,819
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.databox.v2019_09_01; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonSubTypes; /** * The base class for the secrets. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "jobSecretsType", defaultImpl = JobSecrets.class) @JsonTypeName("JobSecrets") @JsonSubTypes({ @JsonSubTypes.Type(name = "DataBoxDisk", value = DataBoxDiskJobSecrets.class), @JsonSubTypes.Type(name = "DataBoxHeavy", value = DataBoxHeavyJobSecrets.class), @JsonSubTypes.Type(name = "DataBox", value = DataboxJobSecrets.class) }) public class JobSecrets { /** * Dc Access Security Code for Customer Managed Shipping. */ @JsonProperty(value = "dcAccessSecurityCode") private DcAccessSecurityCode dcAccessSecurityCode; /** * Get dc Access Security Code for Customer Managed Shipping. * * @return the dcAccessSecurityCode value */ public DcAccessSecurityCode dcAccessSecurityCode() { return this.dcAccessSecurityCode; } /** * Set dc Access Security Code for Customer Managed Shipping. * * @param dcAccessSecurityCode the dcAccessSecurityCode value to set * @return the JobSecrets object itself. */ public JobSecrets withDcAccessSecurityCode(DcAccessSecurityCode dcAccessSecurityCode) { this.dcAccessSecurityCode = dcAccessSecurityCode; return this; } }
33.685185
138
0.736668
3a2b6652e86bdfeceab72ffe321fd132f43031b4
966
package com.DearBaby.www.mapper; import com.DearBaby.www.entity.MyOrder; import java.util.List; /** * 我的订单模块持久化操作接口 * Created by chenfumei on 2017/7/3. */ public interface MyOrderMapper { /** * 查询所有订单信息 * Created by chenfumei on 2017/6/30. * @param * @return 订单信息 */ public List<MyOrder> selectMyOrder(); /** * 查询最新订单信息 * Created by chenfumei on 2017/6/30. * @param * @return 订单信息 */ public List<MyOrder> selectNewOrder(); /** * 查询今日订单信息 * Created by chenfumei on 2017/6/30. * @param * @return 订单信息 */ public List<MyOrder> selectTodayOrder(); /** * 查询未处理订单信息 * Created by chenfumei on 2017/6/30. * @param * @return 订单信息 */ public List<MyOrder> selectUntreatedOrder(); /** * 查询所有订单信息 * Created by chenfumei on 2017/7/04. * @param * @return 所有订单信息 */ public List<MyOrder> selectAllOrder(); }
18.226415
48
0.57971
cb2836c9349dee0559bf5143382f1f9a052467da
1,741
package com.asofdate.batch.dao.impl; import com.asofdate.batch.dao.BatchGroupHistoryDao; import com.asofdate.batch.dao.impl.sql.BatchSqlText; import com.asofdate.batch.entity.BatchGroupHistoryEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by hzwy23 on 2017/6/17. */ @Repository public class BatchGroupHistoryDaoImpl implements BatchGroupHistoryDao { @Autowired private JdbcTemplate jdbcTemplate; @Autowired private BatchSqlText batchSqlText; @Override public List<BatchGroupHistoryEntity> findAll(String uuid) { RowMapper<BatchGroupHistoryEntity> rowMapper = new BeanPropertyRowMapper<>(BatchGroupHistoryEntity.class); List<BatchGroupHistoryEntity> list = jdbcTemplate.query(batchSqlText.getSql("sys_rdbms_197"), rowMapper, uuid); for (BatchGroupHistoryEntity bh : list) { String gid = bh.getSuiteKey(); Integer totalCnt = getTotalJobs(uuid, gid); Integer completeCnt = getCompleteJobs(uuid, gid); bh.setTotalJobsCnt(totalCnt); bh.setCompleteJobsCnt(completeCnt); } return list; } private Integer getTotalJobs(String uuid, String gid) { return jdbcTemplate.queryForObject(batchSqlText.getSql("sys_rdbms_198"), Integer.class, uuid, gid); } private Integer getCompleteJobs(String uuid, String gid) { return jdbcTemplate.queryForObject(batchSqlText.getSql("sys_rdbms_199"), Integer.class, uuid, gid); } }
37.042553
119
0.745549
2951e98b6ac98f1161c9d920f490c40934ff1704
341
package top.pippen.compress; /** * 消息体压缩工厂 * @author pippen */ public class CompressorFactory { public static Compressor get(byte extraInfo) { switch (extraInfo & 24) { case 0x0: return new SnappyCompressor(); default: return new SnappyCompressor(); } } }
18.944444
50
0.557185
461b91e772b9527c90975054a7d9c11f91a6d1ac
2,085
package com.burcumirza.HenryChess.Pieces; import com.burcumirza.HenryChess.Logic.*; import java.util.*; public class King extends Piece { public King(Chessboard board, int row, int col, int color) { super(board, row, col, color, 5, 12, "King"); abbreviation = "K"; } public void addToBoard() { board.add(this); } public void setValue(int value) { myValue = value; } public void move(int newRow, int newCol) { board.recordMove(this, newRow, newCol); myRow = newRow; myCol = newCol; } public void findMoves(ArrayList<Move> moves, boolean actualMove) { int toRow, toCol; for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { toRow = myRow + i; toCol = myCol + j; if (!(i == 0 && j == 0) && board.canAdd(this, toRow, toCol, actualMove)) { addKingMove(moves, new Move(this, toRow, toCol, false), -1); } } } if (board.getCanCastle(myColor, 0)) { boolean queenSideCastle = true; for (int i = 1; i < 4; i++) { if (!board.isEmpty(i, myCol)) { queenSideCastle = false; } } if (queenSideCastle) { addKingMove(moves, new Move(this, 2, myCol, false), 0); } } if (board.getCanCastle(myColor, 1)) { boolean kingSideCastle = true; for (int i = 5; i < 7; i++) { if (!board.isEmpty(i, myCol)) { kingSideCastle = false; } } if (kingSideCastle) { addKingMove(moves, new Move(this, 6, myCol, false), 1); } } } private void addKingMove(ArrayList<Move> moves, Move aMove, int index) { moves.add(aMove); if (index != -1) { aMove.changeCastleIndex(index); } } }
29.366197
91
0.464748
01c0bd1e1bb55de7fa4b593a361bdeb1a090e041
2,342
/* * Copyright (C) 2006-2011 by Benedict Paten (benedictpaten@gmail.com) * * Released under the MIT license, see LICENSE.txt */ /* * Created on Feb 11, 2005 */ package bp.pecan.dimensions; import bp.common.fp.Function_2Args; import bp.common.fp.Functions; import bp.common.fp.Functions_2Args; /** * @author benedictpaten */ public class SlicedDimensionTest extends AbstractDimensionTest { /** * Constructor for SlicedDimensionTest. * * @param arg0 */ public SlicedDimensionTest(final String arg0) { super(arg0); } public void testTinySequenceSlice() { final int start = 10, length = 1, originalLength = 200; this.testComplete(this.getDimension(start, length, originalLength), this.getFunction(), length, 1); } public void testZeroLengthSequenceSlice() { final int start = 10, length = 0, originalLength = 200; this.testComplete(this.getDimension(start, length, originalLength), this.getFunction(), length, 1); } public void testZeroLengthSequenceSliceOfZeroLengthSequence() { final int start = 0, length = 0, originalLength = 0; this.testComplete(this.getDimension(start, length, originalLength), this.getFunction(), length, 1); } Dimension getDimension(final int start, final int length, final int originalLength) { final Function_2Args fn = Functions_2Args.lPipe(super.getFunction(), Functions.rCurry( Functions_2Args.subtract(), new Double(start))); return new SlicedDimension(DimensionTools.getSequenceOfFunction( Functions.rCurry(fn, new Double(0)), originalLength), start, length); } /* (non-Javadoc) * @see bp.pecan.dimensions.AbstractDimensionTest#getDimension() */ @Override Dimension getDimension() { final int start = 10, originalLength = 200; return this.getDimension(start, this.length(), originalLength); } /* (non-Javadoc) * @see bp.pecan.dimensions.AbstractDimensionTest#length() */ @Override int length() { return 100; } /* (non-Javadoc) * @see bp.pecan.dimensions.AbstractDimensionTest#subDimensionsNumber() */ @Override int subDimensionsNumber() { return 1; } }
29.275
107
0.649018
911d79a38528579d0392dfe8e49d3686a2e90ff8
7,587
package com.example.lab.android.nuc.crizyandroid; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.DisplayMetrics; import android.view.Display; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class MainActivity extends Activity { private ViewPager mViewPager; private List<ImageView> images; private List<View> dots; private int currentItem; private Context con = this; private int stopthread = 0; //记录上一次点击的位置 private int oldPosition = 0; //存放图片的id private int[] imageIds = new int[]{ R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d }; //存放图片的标题 private String[] titls = new String[]{ "中北大学的图书馆一角,下雪了!", "中北打学17级学生的第一节军体理论课", "中北大学的17实践部团土集合", "中北大学安卓实验室比赛迫在眉睫" }; private TextView title; private ViewPagerAdapter adapter; private ScheduledExecutorService scheduledExecutorService; private Button settingsButton; private Button lightButton; //定义飞机飞行的速度 private int speed = 10; @SuppressLint("ClickableViewAccessibility") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // //去掉窗口标题 // requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); // //全屏显示 // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, // WindowManager.LayoutParams.FLAG_FULLSCREEN);xx setContentView(R.layout.activity_main); //获取布局文件中的LinearLayout容器 // LinearLayout root = (LinearLayout) findViewById(R.id.root); // plane(); lightButton = (Button) findViewById(R.id.changeButton); lightButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,LightActivity.class); startActivity(intent); } }); settingsButton = (Button) findViewById(R.id.button); settingsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,SettingsActivity.class); startActivity(intent); } }); mViewPager = (ViewPager) findViewById(R.id.vp); //显示图片 images = new ArrayList<ImageView>(); for (int i = 0; i < imageIds.length; i++) { ImageView imageView = new ImageView(this); imageView.setBackgroundResource(imageIds[i]); images.add(imageView); } //显示的小点 dots = new ArrayList<View>(); dots.add(findViewById(R.id.dot_0)); dots.add(findViewById(R.id.dot_1)); dots.add(findViewById(R.id.dot_2)); dots.add(findViewById(R.id.dot_3)); title = (TextView) findViewById(R.id.title); title.setText(titls[0]); adapter = new ViewPagerAdapter(); mViewPager.setAdapter(adapter); mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { title.setText(titls[position]); dots.get(position).setBackgroundResource(R.drawable.dot_focused); dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal); oldPosition = position; currentItem = position; } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { } }); mViewPager.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { stopthread = 1; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: stopthread = 1; break; case MotionEvent.ACTION_UP: stopthread = 0; break; case MotionEvent.ACTION_MOVE: stopthread = 1; break; } return false; }}); } /** * 自定义Adapter * @author wanghao */ private class ViewPagerAdapter extends PagerAdapter{ @Override public int getCount() { return images.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(images.get(position)); } @Override public Object instantiateItem(ViewGroup container, int position) { ImageView v = images.get(position); final int num = position; v.setOnClickListener(new View.OnClickListener() { @SuppressLint("WrongConstant") @Override public void onClick(View v) { Toast.makeText(con, "this is" + num,500).show(); } }); container.addView(images.get(position)); return v; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main,menu); return true; } /* 利用线程池执行图片轮播 */ @Override protected void onStart() { // TODO Auto-generated method stub super.onStart(); scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); scheduledExecutorService.scheduleWithFixedDelay( new ViewPageTask(), 2, 2, TimeUnit.SECONDS); } private class ViewPageTask implements Runnable{ @Override public void run() { if(stopthread==0) { currentItem = (currentItem + 1) % imageIds.length; mHandler.sendEmptyMessage(0); } } } /** * 接收子线程传递过来的数据 */ @SuppressLint("HandlerLeak") private Handler mHandler = new Handler(){ public void handleMessage(android.os.Message msg) { mViewPager.setCurrentItem(currentItem); }; }; @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); } }
28.738636
102
0.600896
cbd251ab68fedab42f050874641fd8ca72ffb98f
4,353
package com.slimgears.util.sample; import com.google.auto.value.AutoValue; import com.google.common.reflect.TypeToken; import com.slimgears.util.autovalue.annotations.BuilderPrototype; import com.slimgears.util.autovalue.annotations.HasMetaClass; import com.slimgears.util.autovalue.annotations.MetaBuilder; import com.slimgears.util.autovalue.annotations.MetaClass; import com.slimgears.util.autovalue.annotations.PropertyMeta; import com.slimgears.util.autovalue.annotations.PropertyType; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import javax.annotation.Generated; @Generated("com.slimgears.util.autovalue.apt.AutoValuePrototypeAnnotationProcessor") @AutoValue public abstract class StringIntegerInterface implements StringIntegerInterfacePrototype, HasMetaClass<StringIntegerInterface> { @Override public MetaClass<StringIntegerInterface> metaClass() { return metaClass; } public static final Meta metaClass = new Meta(); public static class Meta implements MetaClass<StringIntegerInterface> { private final TypeToken<StringIntegerInterface> objectType = new TypeToken<StringIntegerInterface>(){}; private final TypeToken<Builder> builderClass = new TypeToken<Builder>(){}; private final Map<String, PropertyMeta<StringIntegerInterface, ?>> propertyMap = new LinkedHashMap<>(); public final PropertyMeta<StringIntegerInterface, String> name = PropertyMeta.<StringIntegerInterface, String, Builder>create(this, "name", new PropertyType<String>(){}, obj -> obj.name(), Builder::name); public final PropertyMeta<StringIntegerInterface, String> key = PropertyMeta.<StringIntegerInterface, String, Builder>create(this, "key", new PropertyType<String>(){}, obj -> obj.key(), Builder::key); public final PropertyMeta<StringIntegerInterface, Integer> value = PropertyMeta.<StringIntegerInterface, Integer, Builder>create(this, "value", new PropertyType<Integer>(){}, obj -> obj.value(), Builder::value); Meta() { propertyMap.put("name", name); propertyMap.put("key", key); propertyMap.put("value", value); } @Override public TypeToken<Builder> builderClass() { return this.builderClass; } @Override public TypeToken<StringIntegerInterface> asType() { return this.objectType; } @Override public Iterable<PropertyMeta<StringIntegerInterface, ?>> properties() { return propertyMap.values(); } @Override @SuppressWarnings("unchecked") public <__V> PropertyMeta<StringIntegerInterface, __V> getProperty(String name) { return (PropertyMeta<StringIntegerInterface, __V>)propertyMap.get(name); } @Override public <B extends MetaBuilder<StringIntegerInterface>> B createBuilder() { return (B)(BuilderPrototype)StringIntegerInterface.builder(); } @Override public int hashCode() { return Objects.hash(objectType, builderClass); } @Override public boolean equals(Object obj) { return obj instanceof Meta && Objects.equals(((Meta)obj).asType(), asType()) && Objects.equals(((Meta)obj).builderClass(), builderClass()); } } public static StringIntegerInterface create( String name, String key, Integer value) { return StringIntegerInterface.builder() .name(name) .key(key) .value(value) .build(); } public abstract Builder toBuilder(); public static Builder builder() { return Builder.create(); } @AutoValue.Builder public interface Builder extends BuilderPrototype<StringIntegerInterface, Builder>, StringIntegerInterfacePrototypeBuilder<Builder>{ public static Builder create() { return new AutoValue_StringIntegerInterface.Builder(); } @Override Builder name(String name); @Override Builder key(String key); @Override Builder value(Integer value); } @Override public abstract String name(); @Override public abstract String key(); @Override public abstract Integer value(); }
36.579832
219
0.681829
74cb1004819a4ec46f6bc7213c40c70d420167ad
112
package pl.jacob_the_liar.calculator.window; public interface Refresh { void refreshControls(); }
14
45
0.714286
6f1192943a9f9ea1851ad09043dec613a9198f0c
2,588
package edu.cnm.deepdive.dungeonrunclient.viewmodel; import android.app.Application; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.LifecycleObserver; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import edu.cnm.deepdive.dungeonrunclient.model.Attempt; import edu.cnm.deepdive.dungeonrunclient.service.AttemptRepository; import edu.cnm.deepdive.dungeonrunclient.service.UserRepository; import io.reactivex.disposables.CompositeDisposable; import java.util.List; import java.util.UUID; /** * For the leaderboard to be set up and viewed in the application. */ public class LeaderboardViewModel extends AndroidViewModel implements LifecycleObserver { private final UserRepository userRepository; private final AttemptRepository attemptRepository; private final MutableLiveData<Throwable> throwable; private final MutableLiveData<UUID> userId; private final MutableLiveData<Integer> difficulty; private final CompositeDisposable pending; private final MutableLiveData<List<Attempt>> attempts; private final MutableLiveData<Integer> selectedItem; /** * Sets the fields of the leaderboard to be used for the viewmodels to be displayed when called. * * @param application creates an Instance of application. */ public LeaderboardViewModel(@NonNull Application application) { super(application); userRepository = new UserRepository(application); attemptRepository = new AttemptRepository(application); throwable = new MutableLiveData<>(); userId = new MutableLiveData<>(); pending = new CompositeDisposable(); attempts = new MutableLiveData<>(); difficulty = new MutableLiveData<>(); selectedItem = new MutableLiveData<>(); } /** * Gets the live data from the list of Attempts in the server side to use. * * @return */ public LiveData<List<Attempt>> getAttempts() { return attempts; } /** * Gets throwables to use when the current instance of data is not needed. * * @return */ public LiveData<Throwable> getThrowable() { return throwable; } /** * Gets any attempts and sorts them by difficulty of level associated with. * * @param difficulty An instance of Difficulty in an int. */ public void getAttemptsByDifficulty(int difficulty) { throwable.postValue(null); pending.add( attemptRepository.getLeaderboard(difficulty) .subscribe( attempts::postValue, throwable::postValue ) ); } }
31.180723
98
0.739567
9287c3c55f8a1ab5e78ab639acdc477c6b3f98f0
8,539
/* * Copyright 2007 Penn State University * 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 edu.psu.citeseerx.myciteseer.domain; import java.io.Serializable; import java.util.ArrayList; import org.springframework.security.GrantedAuthority; import org.springframework.security.userdetails.UserDetails; import org.springframework.security.GrantedAuthorityImpl; /** * User Account data carrier. * @author Isaac Councill * @version $Rev$ $Date$ */ public class Account implements Serializable, UserDetails { /** * */ private static final long serialVersionUID = 5338982532448066159L; private String username; private String password; private String email; private String firstName; private String middleName; private String lastName; private String status; private String affiliation1; private String affiliation2; private String country; private String province; private String webPage; private boolean enabled = false; private Long internalId; private java.util.Date updated; private String appid; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } //- setUsername public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } //- setPassword public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } //- setEmail public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } //- setFirstName public String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this.middleName = middleName; } //- getFirstName public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } //- setLastName public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } //- setStatus public String getAffiliation1() { return affiliation1; } public void setAffiliation1(String affiliation1) { this.affiliation1 = affiliation1; } //- setAffiliation1 public String getAffiliation2() { return affiliation2; } public void setAffiliation2(String affiliation2) { this.affiliation2 = affiliation2; } //- setAffiliation2 public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } //- setCountry public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } //- setProvince public String getWebPage() { return webPage; } public void setWebPage(String webPage) { this.webPage = webPage; } //- setWebPage public void setEnabled(boolean enabled) { this.enabled = enabled; } //- setEnabled public String getAppid() { return appid; } //- getAppid public void setAppid(String appid) { this.appid = appid; } //- setAppid public Long getInternalId() { return internalId; } //- getInternalId public void setInternalId(Long internalId) { this.internalId = internalId; } //- setInternalId public java.util.Date getUpdated() { return updated; } //- getUpdated public void setUpdated(java.util.Date updated) { this.updated = updated; } //- setUpdated // ======================================================== // Additional Spring Security UserDetails Interface // ======================================================== public final ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); public void addGrantedAuthority(GrantedAuthority authority) { grantedAuthorities.add(authority); } public void removeGrantedAuthority(GrantedAuthority authority) { for (GrantedAuthority auth : grantedAuthorities) { if (auth.getAuthority().equals(authority.getAuthority())) { grantedAuthorities.remove(auth); break; } } } public GrantedAuthority[] getAuthorities() { if (grantedAuthorities.isEmpty()) { return new GrantedAuthority[] {new GrantedAuthorityImpl("HOLDER")}; } else { GrantedAuthority[] authorities = new GrantedAuthority[grantedAuthorities.size()]; for (int i=0; i<grantedAuthorities.size(); i++){ authorities[i] = grantedAuthorities.get(i); } return authorities; } } //- getAuthorities public boolean isAccountNonExpired() { return true; } public boolean isAccountNonLocked() { return true; } public boolean isCredentialsNonExpired() { return true; } public boolean isEnabled() { return enabled; } public boolean isComplete() { if ((firstName != null) && (lastName != null) && (email != null) && (affiliation1 != null)) { return true; } else { return false; } } public boolean isAdmin() { GrantedAuthority[] authorities = this.getAuthorities(); for (GrantedAuthority authority : authorities) { if (authority.getAuthority().equals("ADMIN")) { return true; } } return false; } public void setAdmin(boolean admin) { if (admin && !isAdmin()) { addGrantedAuthority(new GrantedAuthorityImpl("ADMIN")); } if (!admin && isAdmin()) { removeGrantedAuthority(new GrantedAuthorityImpl("ADMIN")); } } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("username: "); buf.append(this.getUsername()); buf.append("; "); buf.append("password: "); buf.append(this.getPassword()); buf.append("; "); buf.append("firstName: "); buf.append(this.getFirstName()); buf.append("; "); buf.append("middleName: "); buf.append(this.getMiddleName()); buf.append("; "); buf.append("lastName: "); buf.append(this.getLastName()); buf.append("; "); buf.append("email: "); buf.append(this.getEmail()); buf.append("; "); buf.append("affil1: "); buf.append(this.getAffiliation1()); buf.append("; "); buf.append("country: "); buf.append(this.getCountry()); buf.append("; "); buf.append("province: "); buf.append(this.getProvince()); buf.append("; "); buf.append("webPage: "); buf.append(this.getWebPage()); buf.append("; "); buf.append("status: "); buf.append(this.getStatus()); buf.append("; "); buf.append("enabled: "); buf.append(this.isEnabled()); buf.append("; "); buf.append("updated: "); buf.append(this.getUpdated()); buf.append("; "); buf.append("internalId: "); buf.append(this.getInternalId()); buf.append("; "); GrantedAuthority[] authorities = this.getAuthorities(); buf.append("authorities: "); for (int i=0; i<authorities.length; i++) { buf.append(authorities[i].getAuthority()); if (i<authorities.length-1) { buf.append(", "); } } return buf.toString(); } //- toString(); } //- class Account
29.243151
79
0.590467
6d91443a3798fe995c1ffde4add80725f0919537
1,994
/******************************************************************************* * Copyright (c) 2016 Sebastian Stenzel and others. * This file is licensed under the terms of the MIT license. * See the LICENSE.txt file for more info. * * Contributors: * Sebastian Stenzel - initial API and implementation *******************************************************************************/ package org.cryptomator.filesystem.jackrabbit; import java.net.URI; import org.apache.commons.lang3.StringUtils; import org.apache.jackrabbit.webdav.DavLocatorFactory; import org.apache.jackrabbit.webdav.util.EncodeUtil; import org.cryptomator.filesystem.Folder; public class FileSystemResourceLocatorFactory implements DavLocatorFactory { private final FileSystemLocator fs; public FileSystemResourceLocatorFactory(URI contextRootUri, Folder root) { String pathPrefix = StringUtils.removeEnd(contextRootUri.toString(), "/"); this.fs = new FileSystemLocator(this, pathPrefix, root); } @Override public FileSystemResourceLocator createResourceLocator(String prefix, String href) { final String fullPrefix = StringUtils.removeEnd(prefix, "/"); final String remainingHref = StringUtils.removeStart(href, fullPrefix); final String unencodedRemaingingHref = EncodeUtil.unescape(remainingHref); return createResourceLocator(unencodedRemaingingHref); } @Override public FileSystemResourceLocator createResourceLocator(String prefix, String workspacePath, String resourcePath) { return createResourceLocator(resourcePath); } @Override public FileSystemResourceLocator createResourceLocator(String prefix, String workspacePath, String path, boolean isResourcePath) { return createResourceLocator(path); } private FileSystemResourceLocator createResourceLocator(String path) { if (StringUtils.isEmpty(path) || "/".equals(path)) { return fs; } else if (path.endsWith("/")) { return fs.resolveFolder(path); } else { return fs.resolveFile(path); } } }
34.982456
131
0.723671