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
67040afc80b19a8c7af58aed82801583a3377efb
1,921
package org.innovateuk.ifs.management.controller.application.list.controller; import org.innovateuk.ifs.management.application.list.controller.CompetitionManagementApplicationsController; import org.innovateuk.ifs.security.BaseControllerSecurityTest; import org.junit.Test; public class CompetitionManagementApplicationsControllerSecurityTest extends BaseControllerSecurityTest<CompetitionManagementApplicationsController> { @Override protected Class<? extends CompetitionManagementApplicationsController> getClassUnderTest() { return CompetitionManagementApplicationsController.class; } long competitionId = 1L; @Test public void testApplicationsMenu() { assertAccessDenied(() -> classUnderTest.applicationsMenu(null, competitionId, null), () -> { }); } @Test public void testAllApplications() { assertAccessDenied(() -> classUnderTest.allApplications(null, competitionId, null, 0, null, null, null), () -> { }); } @Test public void testSubmittedApplications() { assertAccessDenied(() -> classUnderTest.submittedApplications(null, competitionId, null, 0, null, null), () -> { }); } @Test public void testIneligibleApplications() { assertAccessDenied(() -> classUnderTest.ineligibleApplications(null, null, competitionId, null, 0, null, null), () -> { }); } @Test public void testPreviousApplications() { assertAccessDenied(() -> classUnderTest.previousApplications(null, competitionId, null, 0, 0, null, null, null), () -> { }); } @Test public void testMarkApplicationAsSuccessful() { assertAccessDenied(() -> classUnderTest.markApplicationAsSuccessful(competitionId, 0L), () -> { }); } }
32.559322
150
0.654347
e201adf950286856d065b4188e70550b014d01ab
2,613
/* * Copyright 2017, Harsha R. * * 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 gov.sanjoseca.programs.walknroll.internal.faces; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Framework Class: Implements a servlet response wrapper. */ public class FrameworkServletResponseWrapper extends HttpServletResponseWrapper { private static final String CLASS_NAME = FrameworkServletResponseWrapper.class.getName(); private static final Logger LOGGER = Logger.getLogger(CLASS_NAME); public FrameworkServletResponseWrapper(HttpServletResponse response) { super(response); } @Override public void sendRedirect(String location) throws IOException { if (location.endsWith("html/")) { // This should be treated as an error. sendError(404); } else { super.sendRedirect(location); } } @Override public void setStatus(int statusCode) { setStatus(statusCode, null); } @Override public void setStatus(int statusCode, String message) { final String METHOD_NAME = "setStatus(int,String)"; // JSF Bug // c.f. http://java.net/jira/browse/JAVASERVERFACES-2680 // if (400 <= statusCode && statusCode < 600) { LOGGER.logp(Level.INFO, CLASS_NAME, METHOD_NAME, "Faces did not send the error code, we're doing it instead: " + statusCode); try { if (message == null) { sendError(statusCode); } else { sendError(statusCode, message); } } catch (IOException e) { LOGGER.logp(Level.WARNING, CLASS_NAME, METHOD_NAME, "Unable to send the error code!", e); } } if (message == null) { super.setStatus(statusCode); } else { super.setStatus(statusCode, message); } } }
32.6625
105
0.643705
bc5ea3fb1f1cb4a0ca254c737a76e5bedbbbbc5e
847
package com.dx168.patchserver.manager.service; import com.dx168.patchserver.core.domain.Relation; import com.dx168.patchserver.core.mapper.RelationMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** */ @Service public class RelationService { @Autowired private RelationMapper serverMapper; public Integer insert(Relation relation) { return serverMapper.insert(relation); } public List<Relation> findRelation(Relation relation) { return serverMapper.findRelation(relation); } public List<Relation> findLeader(String sub_account) { return serverMapper.findLeader(sub_account); } public void deleteById(Relation relation) { serverMapper.deleteByRelationPhone(relation); } }
23.527778
62
0.747344
51cb5ea4baaf7149a68325e24687d4213047c56b
2,891
/*- * #%L * Liquibase extension for Clickhouse * %% * Copyright (C) 2020 Mediarithmics * %% * 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. * #L% */ package liquibase.ext.clickhouse.sqlgenerator; import liquibase.ext.clickhouse.database.ClickHouseDatabase; import liquibase.database.Database; import liquibase.ext.clickhouse.params.ClusterConfig; import liquibase.ext.clickhouse.params.ParamsLoader; import liquibase.sql.Sql; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.sqlgenerator.core.CreateDatabaseChangeLogTableGenerator; import liquibase.statement.core.CreateDatabaseChangeLogTableStatement; import java.util.Locale; public class CreateDatabaseChangeLogTableClickHouse extends CreateDatabaseChangeLogTableGenerator { @Override public int getPriority() { return PRIORITY_DATABASE; } @Override public boolean supports(CreateDatabaseChangeLogTableStatement statement, Database database) { return database instanceof ClickHouseDatabase; } @Override public Sql[] generateSql( CreateDatabaseChangeLogTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { ClusterConfig properties = ParamsLoader.getLiquibaseClickhouseProperties(); String tableName = database.getDatabaseChangeLogTableName(); String createTableQuery = String.format( "CREATE TABLE IF NOT EXISTS %s.%s " + SqlGeneratorUtil.generateSqlOnClusterClause(properties) + "(" + "ID String," + "AUTHOR String," + "FILENAME String," + "DATEEXECUTED DateTime64," + "ORDEREXECUTED UInt64," + "EXECTYPE String," + "MD5SUM Nullable(String)," + "DESCRIPTION Nullable(String)," + "COMMENTS Nullable(String)," + "TAG Nullable(String)," + "LIQUIBASE Nullable(String)," + "CONTEXTS Nullable(String)," + "LABELS Nullable(String)," + "DEPLOYMENT_ID Nullable(String)) " + SqlGeneratorUtil.generateSqlEngineClause( properties, tableName.toLowerCase(Locale.ROOT)), database.getDefaultSchemaName(), tableName); return SqlGeneratorUtil.generateSql(database, createTableQuery); } }
35.691358
99
0.68523
c825d1f33e246ec15dc2aca31a390dd1cfb526a6
4,307
package everyos.bot.luwu.run.command.modules.starboard; import java.util.Map; import java.util.function.Consumer; import everyos.bot.chat4j.entity.ChatGuild; import everyos.bot.luwu.core.database.DBArray; import everyos.bot.luwu.core.database.DBDocument; import everyos.bot.luwu.core.database.DBObject; import everyos.bot.luwu.core.entity.Channel; import everyos.bot.luwu.core.entity.ChannelID; import everyos.bot.luwu.core.entity.Connection; import everyos.bot.luwu.core.entity.EmojiID; import everyos.bot.luwu.core.entity.Server; import everyos.bot.luwu.util.Tuple; import reactor.core.publisher.Mono; public class StarboardServer extends Server { protected StarboardServer(Connection connection, ChatGuild server, Map<String, DBDocument> documents) { super(connection, server, documents); } public Mono<StarboardInfo> getInfo() { return getGlobalDocument().map(doc->{ return new StarboardInfoImp(doc.getObject()); }); } private class StarboardInfoImp implements StarboardInfo { private DBObject object; public StarboardInfoImp(DBObject object) { this.object = object; } @Override public EmojiID getStarEmoji() { return EmojiID.of(object.getOrDefaultString("star", null)); } @Override public boolean enabled() { return object.has("star"); } @Override public ChannelID getStarboardChannelID() { return new ChannelID(getConnection(), object.getOrDefaultLong("starc", -1L), getClient().getID()); } @Override public ChannelID[] getExcludedChannels() { return new ChannelID[] {}; } @SuppressWarnings("unchecked") @Override public Tuple<ChannelID, Integer>[] getChannelOverrides() { return new Tuple[] {}; } @SuppressWarnings("unchecked") @Override public Tuple<Integer, EmojiID>[] getEmojiLevels() { DBArray starsArr = object.getOrCreateArray("stars"); if (starsArr.getLength() == 0) { addDefaultStars(starsArr); } Tuple<Integer, EmojiID>[] stars = new Tuple[starsArr.getLength()/2]; int j = 0; for (int i=0; i<starsArr.getLength(); i+=2) { stars[j++] = Tuple.of(starsArr.getInt(i), EmojiID.of(starsArr.getString(i+1))); } return stars; } @Override public Mono<Channel> getStarboardChannel() { return getStarboardChannelID().getChannel(); } } private class StarboardEditSpecImp implements StarboardEditSpec { private DBObject object; public StarboardEditSpecImp(DBObject object) { this.object = object; } //TODO: Reset @Override public void setReaction(EmojiID id) { object.set("star", id.toString()); } @Override public void setOutputChannel(ChannelID id) { object.set("starc", id.getLong()); } @Override public StarboardInfo getInfo() { return new StarboardInfoImp(object); } @Override public void addChannelOverride(ChannelID channelID, int requiredStars) { } @Override public void addEmojiLevel(int level, EmojiID emoji) { removeEmojiLevel(level); DBArray starsArr = object.getOrCreateArray("stars"); starsArr.add(level); starsArr.add(emoji.toString()); } @Override public void removeEmojiLevel(int level) { DBArray starsArr = object.getOrCreateArray("stars"); if (starsArr.getLength() == 0) { addDefaultStars(starsArr); } for (int i=0; i<starsArr.getLength(); i+=2) { if (starsArr.getInt(i)==level) { starsArr.remove(i); starsArr.remove(i); break; } } } @Override public void ignoreChannel(ChannelID channelID) { } @Override public void unignoreChannel(ChannelID channelID) { } @Override public void reset() { object.remove("star"); object.remove("starc"); object.remove("stars"); } } public Mono<Void> edit(Consumer<StarboardEditSpec> func) { return getGlobalDocument().flatMap(doc->{ func.accept(new StarboardEditSpecImp(doc.getObject())); return doc.save(); }); } private void addDefaultStars(DBArray starsArr) { starsArr.add(3); starsArr.add("\u2b50"); starsArr.add(5); starsArr.add("\uD83C\uDF1F"); } public static StarboardServerFactory type = new StarboardServerFactory(); }
24.611429
105
0.676341
ca372be1ddef2baa40fcd52cf77b6a9753bd1946
3,497
package my.alkarps; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author alkarps * create date 16.07.2020 12:57 */ public class CollectionsTest { @Test public void addAllTest_whenDiyArrayListIsEmpty() { int sourceSize = 100; List<Integer> source = getIntegerValue(sourceSize); List<Integer> destination = new DiyArrayList<>(); Collections.addAll(destination, source.toArray(new Integer[0])); assertNotNull(destination); assertEquals(sourceSize, destination.size()); for (int i = 0; i < source.size(); i++) { assertEquals(source.get(i), destination.get(i)); } } @Test public void addAllTest_whenDiyArrayListIsFill() { int destOriginalSize = 100; int sourceSize = 100; List<Integer> source = getIntegerValue(sourceSize); List<Integer> destination = new DiyArrayList<>(); destination.addAll(IntStream.rangeClosed(1, destOriginalSize) .boxed() .map(integer -> 0) .collect(Collectors.toList())); Collections.addAll(destination, source.toArray(new Integer[0])); assertNotNull(destination); assertEquals(destOriginalSize + sourceSize, destination.size()); for (int i = 0; i < destOriginalSize; i++) { assertEquals(0, destination.get(i)); } for (int i = 0; i < source.size(); i++) { assertEquals(source.get(i), destination.get(i + destOriginalSize)); } } @Test public void copy() { int sourceSize = 100; List<Integer> source = getIntegerValue(sourceSize); List<Integer> destination = new DiyArrayList<>(); destination.addAll(IntStream.rangeClosed(1, sourceSize) .boxed() .map(integer -> 0) .collect(Collectors.toList())); Collections.copy(destination, source); assertNotNull(destination); assertEquals(sourceSize, destination.size()); for (int i = 0; i < source.size(); i++) { assertEquals(source.get(i), destination.get(i)); } } @Test public void revers() { int size = 100; List<Integer> destination = new DiyArrayList<>(getIntegerValue(size)); assertEquals(size, destination.size()); Collections.reverse(destination); assertEquals(size, destination.size()); for (int i = size; i > 0; i--) { assertEquals(i, destination.get(size - i)); } } @Test public void sort() { int size = 100; List<Integer> source = getIntegerValue(size); Collections.reverse(source); List<Integer> destination = new DiyArrayList<>(source); Collections.sort(destination); assertNotNull(destination); assertEquals(size, destination.size()); for (int i = 0; i < source.size(); i++) { assertEquals(i + 1, destination.get(i)); } } private List<Integer> getIntegerValue(int sourceSize) { if (sourceSize < 1) { sourceSize = 1; } return IntStream.rangeClosed(1, sourceSize) .boxed() .collect(Collectors.toList()); } }
33.304762
79
0.602516
f72583b45780e4ec3264b98199c5d224f03be33b
1,206
package com.imarcats.internal.server.infrastructure.notification.trades; import com.imarcats.interfaces.client.v100.dto.MatchedTradeDto; import com.imarcats.interfaces.server.v100.dto.mapping.MatchedTradeDtoMapping; import com.imarcats.model.MatchedTrade; /** * Implementation of Trade Notification Session * @author Adam * */ public class TradeNotificationSessionImpl implements TradeNotificationSession { private final TradeNotificationBroker _tradeNotificationBroker; public TradeNotificationSessionImpl( TradeNotificationBroker tradeNotificationBroker_) { super(); _tradeNotificationBroker = tradeNotificationBroker_; } @Override public void recordMatchedTrades(MatchedTrade[] trades_) { for (MatchedTrade matchedTrade : trades_) { MatchedTradeDto clonedMatchedTrade = cloneMatchedTrade(matchedTrade); notify(clonedMatchedTrade); } } protected void notify(MatchedTradeDto clonedMatchedTrade) { _tradeNotificationBroker.notifyListeners(new MatchedTradeDto[] { clonedMatchedTrade }); } private MatchedTradeDto cloneMatchedTrade(MatchedTrade matchedTrade_) { return MatchedTradeDtoMapping.INSTANCE.toDto(matchedTrade_); } }
31.736842
90
0.795191
71aa58ffdc68174462870c6ec7558d27c8e7a3a5
4,728
// // ======================================================================== // Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.websocket.mux.op; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import org.eclipse.jetty.websocket.mux.MuxControlBlock; import org.eclipse.jetty.websocket.mux.MuxOp; public class MuxDropChannel implements MuxControlBlock { /** * Outlined in <a href="https://tools.ietf.org/html/draft-ietf-hybi-websocket-multiplexing-05#section-9.4.1">Section 9.4.1. Drop Reason Codes</a> */ public static enum Reason { // Normal Close : (1000-1999) NORMAL_CLOSURE(1000), // Failures in Physical Connection : (2000-2999) PHYSICAL_CONNECTION_FAILED(2000), INVALID_ENCAPSULATING_MESSAGE(2001), CHANNEL_ID_TRUNCATED(2002), ENCAPSULATED_FRAME_TRUNCATED(2003), UNKNOWN_MUX_CONTROL_OPC(2004), UNKNOWN_MUX_CONTROL_BLOCK(2005), CHANNEL_ALREADY_EXISTS(2006), NEW_CHANNEL_SLOT_VIOLATION(2007), NEW_CHANNEL_SLOT_OVERFLOW(2008), BAD_REQUEST(2009), UNKNOWN_REQUEST_ENCODING(2010), BAD_RESPONSE(2011), UNKNOWN_RESPONSE_ENCODING(2012), // Failures in Logical Connections : (3000-3999) LOGICAL_CHANNEL_FAILED(3000), SEND_QUOTA_VIOLATION(3005), SEND_QUOTA_OVERFLOW(3006), IDLE_TIMEOUT(3007), DROP_CHANNEL_ACK(3008), // Other Peer Actions : (4000-4999) USE_ANOTHER_PHYSICAL_CONNECTION(4001), BUSY(4002); private static final Map<Integer, Reason> codeMap; static { codeMap = new HashMap<>(); for (Reason r : values()) { codeMap.put(r.getValue(),r); } } public static Reason valueOf(int code) { return codeMap.get(code); } private final int code; private Reason(int code) { this.code = code; } public int getValue() { return code; } } public static MuxDropChannel parse(long channelId, ByteBuffer payload) { // TODO Auto-generated method stub return null; } private final long channelId; private final Reason code; private String phrase; private int rsv; /** * Normal Drop. no reason Phrase. * * @param channelId * the logical channel Id to perform drop against. */ public MuxDropChannel(long channelId) { this(channelId,Reason.NORMAL_CLOSURE,null); } /** * Drop with reason code and optional phrase * * @param channelId * the logical channel Id to perform drop against. * @param code * reason code * @param phrase * optional human readable phrase */ public MuxDropChannel(long channelId, int code, String phrase) { this(channelId, Reason.valueOf(code), phrase); } /** * Drop with reason code and optional phrase * * @param channelId * the logical channel Id to perform drop against. * @param code * reason code * @param phrase * optional human readable phrase */ public MuxDropChannel(long channelId, Reason code, String phrase) { this.channelId = channelId; this.code = code; this.phrase = phrase; } public ByteBuffer asReasonBuffer() { // TODO: convert to reason buffer return null; } public long getChannelId() { return channelId; } public Reason getCode() { return code; } @Override public int getOpCode() { return MuxOp.DROP_CHANNEL; } public String getPhrase() { return phrase; } public int getRsv() { return rsv; } public void setRsv(int rsv) { this.rsv = rsv; } }
25.695652
149
0.571912
d75c7adf86fa2d8ce7776899c9977edf3bf1029f
1,263
package me.dylanmullen.bingo.configs; import java.io.File; import java.util.ArrayList; import java.util.List; public class ConfigManager { private static ConfigManager instance; private List<Config> uiConfigs; /** * @return Returns an instance of the Config Manager */ public static ConfigManager getInstance() { if (instance == null) instance = new ConfigManager(); return instance; } /** * Manages the configs of the server */ public ConfigManager() { this.uiConfigs = new ArrayList<Config>(); load(); } /** * Loads all config names */ private void load() { loadUIFiles(); } public void loadUIFiles() { for (File file : IOController.getController().getUIConfigFolder().listFiles()) { if (!file.getName().endsWith(".csv")) return; uiConfigs.add(new Config(file.getName(), file)); } } /** * @param name Config File Name * @return Returns the config file identified by the name */ public Config getUIConfig(String name) { System.out.println(name); for (Config cfg : uiConfigs) if (cfg.getName().equals(name)) return cfg; return null; } public List<Config> getUiConfigs() { return uiConfigs; } }
17.788732
81
0.63658
4062e51d275964dd8c28ff8c886321a2be6b1a7d
373
package com.shinobicontrols.charts; public class EaseInOutAnimationCurve extends AnimationCurve { public float valueAtTime(float time) { if (time < 0.5f) { time *= 2.0f; return ((time * time) * time) * 0.5f; } time = 1.0f - ((time - 0.5f) * 2.0f); return ((1.0f - ((time * time) * time)) * 0.5f) + 0.5f; } }
28.692308
63
0.530831
22788b1eb6bafaf1b9187a839a261f7a4008d70c
5,516
package zserio.emit.doc; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import zserio.ast.AstNode; import zserio.ast.ChoiceType; import zserio.ast.Constant; import zserio.ast.EnumType; import zserio.ast.Package; import zserio.ast.Root; import zserio.ast.ServiceType; import zserio.ast.SqlDatabaseType; import zserio.ast.SqlTableType; import zserio.ast.StructureType; import zserio.ast.Subtype; import zserio.ast.UnionType; import zserio.emit.common.ZserioEmitException; import zserio.tools.StringJoinUtil; import freemarker.template.Template; import freemarker.template.TemplateException; public class OverviewEmitter extends DefaultHtmlEmitter { public OverviewEmitter(String outputPath) { super(outputPath); } public Set<String> getPackageNames() { return packageNames; } @Override public void endRoot(Root root) throws ZserioEmitException { try { for (Map.Entry<Package, List<AstNode>> packageEntry : packages.entrySet()) { for (AstNode type : packageEntry.getValue()) { final String typeName = DocEmitterTools.getZserioName(type); boolean isDoubleDefinedType = Boolean.TRUE.equals(doubleTypeNames.get(typeName)); LinkedType linkedType = new LinkedType(type, isDoubleDefinedType); typeMap.put(getFullTypeName(typeName, packageEntry.getKey()), linkedType); } } Template tpl = cfg.getTemplate("doc/overview.html.ftl"); openOutputFile(directory, "overview" + HTML_EXT); tpl.process(this, writer); } catch (IOException exception) { throw new ZserioEmitException(exception.getMessage()); } catch (TemplateException exception) { throw new ZserioEmitException(exception.getMessage()); } finally { if (writer != null) writer.close(); } } @Override public void beginPackage(Package packageToken) throws ZserioEmitException { super.beginPackage(packageToken); localTypes = new ArrayList<AstNode>(); } @Override public void endPackage(Package packageToken) throws ZserioEmitException { for (AstNode type : localTypes) { final String typeName = DocEmitterTools.getZserioName(type); if (doubleTypeNames.containsKey(typeName)) doubleTypeNames.put(typeName, true); else doubleTypeNames.put(typeName, false); } String pkgName = currentPackage.getPackageName().toString(); pkgName = pkgName.replace('.', '_'); packageNames.add(pkgName); packages.put(currentPackage, localTypes); } @Override public void beginConst(Constant constant) throws ZserioEmitException { localTypes.add(constant); } @Override public void beginSubtype(Subtype subType) throws ZserioEmitException { localTypes.add(subType); } @Override public void beginStructure(StructureType structureType) throws ZserioEmitException { localTypes.add(structureType); } @Override public void beginChoice(ChoiceType choiceType) throws ZserioEmitException { localTypes.add(choiceType); } @Override public void beginUnion(UnionType unionType) throws ZserioEmitException { localTypes.add(unionType); } @Override public void beginEnumeration(EnumType enumType) throws ZserioEmitException { localTypes.add(enumType); } @Override public void beginSqlTable(SqlTableType sqlTableType) throws ZserioEmitException { localTypes.add(sqlTableType); } @Override public void beginSqlDatabase(SqlDatabaseType sqlDatabaseType) throws ZserioEmitException { localTypes.add(sqlDatabaseType); } @Override public void beginService(ServiceType service) throws ZserioEmitException { localTypes.add(service); } public Collection<LinkedType> getTypes() { return typeMap.values(); } private String getFullTypeName(String typeName, Package pkg) { if (pkg.getPackageName().isEmpty()) return typeName; return typeName + "." + getReversePackageName(pkg); } private static String getReversePackageName(Package pkg) { final List<String> packageIds = new ArrayList<String>(); for (String id : pkg.getPackageName().getIdList()) packageIds.add(id); final List<String> reversePackageIds = new ArrayList<String>(); for (int i = packageIds.size() - 1; i >= 0; i--) reversePackageIds.add(packageIds.get(i)); return StringJoinUtil.joinStrings(reversePackageIds, "."); } private final Map<String, LinkedType> typeMap = new TreeMap<String, LinkedType>(); private final Map<String, Boolean> doubleTypeNames = new HashMap<String, Boolean>(); private final HashSet<String> packageNames = new HashSet<String>(); private final Map<Package, List<AstNode>> packages = new HashMap<Package, List<AstNode>>(); private List<AstNode> localTypes = new ArrayList<AstNode>(); }
29.497326
101
0.660261
788174607b3ad7b8718ef662f713a98e23455eaa
4,334
package com.xceptance.xlt.api.util; import java.util.Arrays; import java.util.List; import org.junit.Assert; import org.junit.Test; import com.xceptance.xlt.engine.util.TimerUtils; public class LightweightHtmlPageUtilsTest { @Test public final void testGetAllAnchorLinks() { final String content = "<html><body>" + "<a href=\"http://1\">Test</a>" + "<A href=\"2\">Test</a>" + "<a title=\"test\" href=\"3\">Test</a>" + "<a href= \"4\">Test</a>" + "<a HREF=\"5\">Test</a>" + "<a href='6'>Test</a>" + "<a href='7'>Test</a>" + "<a title=\"this is an href\" href=\"8\">" + "<a href=\" 9 \">Test</a>" + "<a\nhref=\"10\">Test</a>" + "<a title=\"Test\"\nhref=\"11\">Test</a>" + "</body></html>"; final List<String> list = LightweightHtmlPageUtils.getAllAnchorLinks(content); Assert.assertEquals(11, list.size()); Assert.assertTrue(Arrays.deepEquals(new String[] { "http://1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11" }, list.toArray())); } @Test public final void testGetAllImageLinks() { final String content = "<html><body>" + "<img src=\"http://1\">" + "<IMG src=\"2\">" + "<img title=\"test\" src=\"3\">" + "<img src= \"4\">" + "<img SRC=\"5\">" + "<img src='6'>" + "<img src='7'>" + "<img title=\"this is an src\" src=\"8\">" + "<img src=\" 9 \">" + "<img src=\"10\"/>" + "<img src=\"11\" />" + "<img\nsrc=\"12\">" + "<img title=\"Test\"\nsrc=\"13\">" + "</body></html>"; final List<String> list = LightweightHtmlPageUtils.getAllImageLinks(content); Assert.assertEquals(13, list.size()); Assert.assertTrue(Arrays.deepEquals(new String[] { "http://1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13" }, list.toArray())); } @Test public final void testGetAllLinkLinks() { final String content = "<html><body>" + "<link href=\"http://1\">Test</a>" + "<LINK href=\"2\">Test</a>" + "<link title=\"test\" href=\"3\">Test</a>" + "<link href= \"4\">Test</a>" + "<link HREF=\"5\">Test</a>" + "<link href='6'>Test</a>" + "<link href='7'>Test</a>" + "<link title=\"this is an href\" href=\"8\">" + "<link href=\" 9 \">Test</a>" + "<link\nhref=\"10\">Test</a>" + "<link title=\"Test\"\nhref=\"11\">Test</a>" + "</body></html>"; final List<String> list = LightweightHtmlPageUtils.getAllLinkLinks(content); Assert.assertEquals(11, list.size()); Assert.assertTrue(Arrays.deepEquals(new String[] { "http://1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11" }, list.toArray())); } @Test public final void testGetAllScriptLinks() { final String content = "<html><body>" + "<script src=\"http://1\">" + "<SCRIPT src=\"2\">" + "<script title=\"test\" src=\"3\">" + "<script src= \"4\">" + "<script SRC=\"5\">" + "<script src='6'>" + "<script src='7'>" + "<script title=\"this is an src\" src=\"8\">" + "<script src=\" 9 \">" + "<script src=\"10\"/>" + "<script src=\"11\" />" + "<script\nsrc=\"12\">" + "<script title=\"Test\"\nsrc=\"13\">" + "</body></html>"; final List<String> list = LightweightHtmlPageUtils.getAllScriptLinks(content); for (int i = 0; i < 100000; i++) { LightweightHtmlPageUtils.getAllScriptLinks(content); } final long s = TimerUtils.getTime(); for (int i = 0; i < 100000; i++) { LightweightHtmlPageUtils.getAllScriptLinks(content); } System.out.println("script: " + (TimerUtils.getTime() - s)); Assert.assertEquals(13, list.size()); Assert.assertTrue(Arrays.deepEquals(new String[] { "http://1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13" }, list.toArray())); } }
47.626374
136
0.460083
2560d594f8dd9e772919e1a28476eca370eaf04b
834
package lv.ctco.cukesrest; /** * List of variables and options used in cukes-rest. */ public interface CukesOptions { int CUKES_BEFORE_HOOK_STARTUP_ORDER = 500; String PROPERTIES_PREFIX = "cukes."; String HEADER_PREFIX = "header."; String DELIMITER = ","; String RESOURCES_ROOT = "resources_root"; String BASE_URI = "base_uri"; String PLUGINS = "plugins"; String PROXY = "proxy"; String AUTH_TYPE = "auth_type"; String USERNAME = "username"; String PASSWORD = "password"; String URL_ENCODING_ENABLED = "url_encoding_enabled"; String RELAXED_HTTPS = "relaxed_https"; String CONTEXT_INFLATING_ENABLED = "context_inflating_enabled"; String ASSERTIONS_DISABLED = "assertions_disabled"; String LOADRUNNER_FILTER_BLOCKS_REQUESTS = "loadrunner_filter_blocks_requests"; }
30.888889
83
0.724221
8bc7d295020cc33654a0254149a80e17196c6183
23,810
/** * Copyright 2015 Mike Baum * * 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 tigerui.event; import static java.util.Objects.requireNonNull; import static tigerui.Preconditions.checkArgument; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import rx.Observable; import rx.Subscriber; import rx.subscriptions.Subscriptions; import tigerui.EventLoop; import tigerui.event.operator.Operator; import tigerui.event.operator.OperatorChanges; import tigerui.event.operator.OperatorDebounce; import tigerui.event.operator.OperatorFilter; import tigerui.event.operator.OperatorMap; import tigerui.event.operator.OperatorScan; import tigerui.event.operator.OperatorScanOptional; import tigerui.event.operator.OperatorSwitchMap; import tigerui.event.operator.OperatorTake; import tigerui.event.publisher.EventPublisher; import tigerui.event.publisher.FlattenPublisher; import tigerui.event.publisher.LiftEventPublisher; import tigerui.event.publisher.MergeEventPublisher; import tigerui.property.Property; import tigerui.property.PropertyStream; import tigerui.subscription.RollingSubscription; import tigerui.subscription.Subscription; /** * An EventStream represents a stream that emits discrete events. This differs * from a {@link Property} since an {@link EventStream} does not have a current * value. * * <p> * Notes: * <ol> * <li>An Event Stream will emit zero, one or many events followed by one * completed event. * <li>An Event Stream can only be interacted with on the same thread that it * was created on. Attempting to access any of the methods outside of the thread * it was created on will throw an {@link IllegalStateException} * <li>An Event Stream does not <i><b>"remember"</b></i> the last event that it * published. Therefore new observers will not be called back immediately as * with a {@link Property}. * </ol> * * @param <E> * The type of events emitted by this event stream. */ public class EventStream<E> { private final EventPublisher<E> eventPublisher; private final EventLoop eventLoop; protected EventStream(EventPublisher<E> eventPublisher, EventLoop eventLoop) { this.eventPublisher = requireNonNull(eventPublisher); this.eventLoop = requireNonNull(eventLoop); } /** * Creates an EventStream using the provided {@link EventPublisher}. * * @param eventPublisher * some {@link EventPublisher} to back this stream. */ public EventStream(EventPublisher<E> eventPublisher) { this(eventPublisher, EventLoop.createEventLoop()); } /** * Subscribes to new events emitted by this stream. * * @param eventHandler * some event handler that should be fired when a new event is * emitted by this stream. * @return a {@link Subscription} that can be used to stop the eventHandler * from consuming events from this stream. * @throws IllegalStateException * if called from a thread other than the thread that this event * stream was created on. */ public final Subscription onEvent(Consumer<E> eventHandler) { return observe(EventObserver.create(eventHandler)); } /** * Subscribes to the completed event of this stream. * * @param onCompletedAction some Runnable to execute when this stream is completed. * @return a {@link Subscription} that can be used to stop the onCompletedAction * from firing when this stream completes. * @throws IllegalStateException * if called from a thread other than the thread that this event * stream was created on. */ public final Subscription onCompleted(Runnable onCompletedAction) { return observe(EventObserver.create(onCompletedAction)); } /** * Subscribes to onEvents and onCompleted events, via the provided * eventHandler and onCompleteAction. * * @param eventHandler * some {@link Consumer} to observe events emitted from this * stream. * @param onCompleteAction * some {@link Runnable} to execute when this stream is * completed. * @return a {@link Subscription} that can be used to stop this observer * from responding to events. * @throws IllegalStateException * if called from a thread other than the thread that this event * stream was created on. */ public final Subscription observe(Consumer<E> eventHandler, Runnable onCompleteAction) { return eventPublisher.subscribe(EventObserver.create(eventHandler, onCompleteAction)); } /** * Subscribes to onEvents and onCompleted events, via the provided observer. * * @param observer * some {@link EventObserver} to observe this stream. * @return a {@link Subscription} that can be used to stop this observer * from responding to events. * @throws IllegalStateException * if called from a thread other than the thread that this event * stream was created on. */ public final Subscription observe(EventObserver<E> observer) { eventLoop.checkInEventLoop(); return eventPublisher.subscribe(observer); } /** * Transforms this stream by the provided operator, creating a new stream. * * @param operator * some operator to transform this stream by. * @return a new {@link EventStream} transformed by the provided operator. * @param <R> * the type of the event stream created by applying the lift function */ public final <R> EventStream<R> lift(Operator<E, R> operator) { requireNonNull(operator); return new EventStream<>(new LiftEventPublisher<>(operator, eventPublisher), eventLoop); } /** * Creates a new stream that transforms events emitted by this stream by the * provided mapper. * * @param mapper * some function to transform the events emitted by this stream. * @return a new {@link EventStream}, that transforms events emitted by this * stream by the provided mapper. * @param <R> * the type of the event stream created by applying the map function */ public final <R> EventStream<R> map(Function<E, R> mapper) { return lift(new OperatorMap<>(mapper)); } /** * Creates a new stream that filters the events emitted by this stream, such * that only those that satisfy the provided predicate are emitted. * * @param predicate * some predicate to filter this stream by. * @return A new {@link EventStream} that only emits values emitted by this * stream that satisfy the provided predicate. */ public final EventStream<E> filter(Predicate<E> predicate) { return lift(new OperatorFilter<>(predicate)); } /** * Throttles emissions from this event stream, such that an event will only * be emitted after an amount of event silence. * * @param timeout * amount of event silence to wait for before emitting an event * @param timeUnit * time unit for the provided time. * @return an {@link EventStream} that will only emit values after the * prescribed amount of event silence has passed. */ public final EventStream<E> debounce(long timeout, TimeUnit timeUnit) { return lift(new OperatorDebounce<>(eventLoop, timeout, timeUnit)); } /** * Scans this stream by combining the previously computed value of R with * every event that is emitted generating a new R. * * The event stream created by this method, will not emit a value until an * event is emitted. * * @param scanFunction * some function that will be applied to each emitted value and * the last computed value generating a new R. * @return a new {@link EventStream} of values computed as per the scan * function. * @param <R> * the type of the event stream created by applying the scan function */ public final <R> EventStream<R> scan(BiFunction<E, Optional<R>, R> scanFunction) { return lift(new OperatorScanOptional<>(scanFunction)); } /** * Scans this stream by combining the previously computed value of R with * every event that is emitted generating a new R. * * The event stream created by this method, will emit a value immediately * using the seed value and then a new value every time this stream emits an * event. * * @param scanFunction * some function that will be applied to each emitted value and * the last computed value generating a new R. * @param seed * some initial value to start the scan operation with. This * value will be emitted immediately to all subscribers. * @return a new {@link EventStream} of values computed as per the scan * function. * @param <R> * the type of the event stream created by applying the scan function */ public final <R> EventStream<R> scan(BiFunction<E, R, R> scanFunction, R seed) { return lift(new OperatorScan<>(scanFunction, seed)); } /** * Scans this stream by combining the previously computed value of R with * every event that is emitted generating a new R. * * The event stream created by this method, will emit a value immediately * using the seed value and then a new value every time this stream emits an * event. * * This method is provided as a convenience, since * {@link #scan(BiFunction, Object)} could be called directly. * * @param accumulator * some accumulator function that will be applied to each emitted * value and the last computed value generating a new R. * @param initialValue * some initial value to start the scan operation with. This * value will be emitted immediately to all subscribers. * @return a new {@link EventStream} of values computed as per the scan * function. */ public final EventStream<E> accumulate(BinaryOperator<E> accumulator, E initialValue) { return scan(accumulator, initialValue); } /** * Creates a new event stream that emits a new event ever time there has * been a event and applies the provided function the current event and the * last emitted event. * * @param changeEventFactory * some function that will be called with the current event and * the last emitted event * @return an {@link EventStream} of change events for this stream. The * stream will not emit a value after subscribing until the stream * has emitted at least two events. * @param <C> * the type of the event stream created by applying the change * event factory function */ public final <C> EventStream<C> changes(BiFunction<E, E, C> changeEventFactory) { return lift(new OperatorChanges<>(changeEventFactory)); } /** * Creates a new {@link EventStream} that when subscribed to will * only every emit as many items as specified by the provided numberToTake * parameter.<br> * * @param numberToTake * the number of events to emit * @return a new {@link EventStream} that only emits as many items as * specified in the amount parameter * @throws IllegalArgumentException if zero elements is requested */ public final EventStream<E> take(int numberToTake) { return lift(new OperatorTake<>(numberToTake)); } /** * Merges the provided streams with this streams. * * See {@link #merge(EventStream...)} * * @param streams * streams to merge with this stream * @return a new {@link EventStream} that results from merging this stream * will all the provided streams. */ @SafeVarargs public final EventStream<E> mergeWith(EventStream<E>... streams) { EventStream<E>[] eventStreams = Arrays.copyOf(streams, streams.length + 1); eventStreams[eventStreams.length -1] = this; return EventStream.merge(eventStreams); } /** * Merges the provided streams with this streams. * * See {@link #merge(EventStream...)} * * @param streams * streams to merge with this stream * @return a new {@link EventStream} that results from merging this stream * will all the provided streams. */ public final EventStream<E> mergeWith(Iterable<EventStream<E>> streams) { List<EventStream<E>> streamList = StreamSupport.stream(streams.spliterator(), false).collect(Collectors.toList()); streamList.add(this); return EventStream.merge(streamList); } /** * Creates a new stream that can switch the output stream by the provided * switchFunction. Visually, this is roughly equivalent to the following: * <br> * _________________________________ * | switchFunction | * | [stream 1] --- | * [this stream] --- | [stream 2] --- switches between | --- [stream 1 | stream 2 | stream 3] * | [stream 3] --- streams | * |_________________________________| * <br> * @param switchFunction * function that can be used to switch between a set of source * event streams. * @return a new event stream that uses the provided switchFunction to switch * between a set of source event streams. * @param <R> * the type of the event stream created by applying the switch function */ public final <R> EventStream<R> switchMap(Function<E, EventStream<R>> switchFunction) { return lift(new OperatorSwitchMap<>(switchFunction)); } /** * Like {@link #switchMap(Function)}, except that the switchMap creates * property streams. The property stream that is created, will have the same * lifetime as this event stream. * * @param switchFunction * function that can be used to switch between a set of source * property streams. * @param initialValue * the initial value for the property stream that is returned. * @return a new property stream that uses the provided switchFunction to * switch between a set of source property streams. * @param <R> * the type of the property stream created by applying the lift function */ public final <R> PropertyStream<R> switchMap(Function<E, PropertyStream<R>> switchFunction, R initialValue) { Property<R> property = Property.create(initialValue); RollingSubscription subscription = new RollingSubscription(); EventStream<PropertyStream<R>> propertyEventStream = map(switchFunction); Subscription propertyStreamSubscription = propertyEventStream.observe(stream -> subscription.set(property.bind(stream)), property::dispose); property.onDisposed(propertyStreamSubscription::dispose); return property; } /** * Creates a property that is bound to this stream. * * @param initialValue * some value to initialize the property with. * @return a new {@link Property}, that is bound to this stream and is * initialized with the provided intialValue. * @throws IllegalStateException * if called from a thread other than the thread that this event * stream was created on. * TODO: perhaps this should return a PropertyStream instead? */ public final Property<E> toProperty(E initialValue) { Property<E> property = Property.create(initialValue); Subscription subscription = property.bind(this); property.onDisposed(subscription::dispose); return property; } /** * Creates a new {@link Observable} backed by this event stream. * * <p> * <b>Note:</b> The created observable can only be subscribed to from the same * thread as this stream was created on. Attempting to subscribe on a * different thread will throw an {@link IllegalStateException}. * * @return an {@link Observable} backed by this event stream. */ public final Observable<E> asObservable() { return Observable.create(subscriber -> { observe(EventObserver.create(subscriber::onNext, subscriber::onCompleted)); }); } /** * Creates an event stream that whose source of events is some observable. * * @param observable * an {@link Observable} to provide the source of events to the * created event stream. * @return A new {@link EventStream} whose source of events is the provided * observable. * @param <E> * the type of the event stream created from the provided Observable */ public static final <E> EventStream<E> from(Observable<E> observable) { return new EventStream<>(eventObserver -> { EventSubscriber<E> subscriber = new EventSubscriber<>(eventObserver); rx.Subscriber<E> rxSubscriber = new Subscriber<E>() { @Override public void onCompleted() { subscriber.onCompleted(); } @Override public void onError(Throwable e) { // TODO: What to do here, perhaps complete and send the error to the global error handler. } @Override public void onNext(E event) { subscriber.onEvent(event); } }; observable.subscribe(rxSubscriber); Subscription eventStreamSubscription = Subscription.create(rxSubscriber::unsubscribe); rxSubscriber.add(Subscriptions.create(eventStreamSubscription::dispose)); return eventStreamSubscription; }); } /** * Creates an event stream from the provided events. Each subscriber to the * returned event stream will be dispatched all the events and then be * completed. * * @param events * some events to create an event stream for. * @return a new {@link EventStream} that will dispatch all the events when * subscribed to and then complete. * @param <T> * the type of the event stream created from the provided array */ @SafeVarargs public static final <T> EventStream<T> fromArray(T... events) { return fromIterable(Arrays.asList(events)); } /** * Creates an event stream from the provided iterable of events. Each subscriber to the * returned event stream will be dispatched all the events and then be * completed. * * @param eventList * some {@link Iterable} of events to create an event stream for. * @return a new {@link EventStream} that will dispatch all the events when * subscribed to and then complete. * @param <T> * the type of the event stream created from the provided iterable */ public static <T> EventStream<T> fromIterable(Iterable<T> eventList) { return new EventStream<>(observer -> { EventSubscriber<T> subscriber = new EventSubscriber<>(observer); eventList.forEach(subscriber::onEvent); subscriber.onCompleted(); return subscriber; }); } /** * Create a new stream that results from merging all events emitted by the * provided streams. * * @param eventStreams * some event streams to merge, must contain at least one stream. * @return a new {@link EventStream} that will emit all the events emitted * by the source event streams * @throws IllegalArgumentException * if the provided array of streams is empty * @param <E> * the type of the event stream created by merging the provided streams */ @SafeVarargs public final static <E> EventStream<E> merge(EventStream<E>... eventStreams) { checkArgument(eventStreams.length > 0, "You must provide at least one stream to merge"); if (eventStreams.length == 1) return eventStreams[0]; return new EventStream<E>(new MergeEventPublisher<>(Arrays.asList(eventStreams))); } /** * Create a new stream that results from merging all events emitted by the * provided streams. * * @param eventStreams * some event streams to merge, must contain at least one stream. * @return a new {@link EventStream} that will emit all the events emitted * by the source event streams * @throws IllegalArgumentException * if the provided array of streams is empty * @param <E> * the type of the event stream created by merging the provided streams */ public final static <E> EventStream<E> merge(Iterable<EventStream<E>> eventStreams) { Collection<EventStream<E>> streamList; if ( eventStreams instanceof Collection ) { streamList = (Collection<EventStream<E>>) eventStreams; } else { streamList = StreamSupport.stream(eventStreams.spliterator(), false).collect(Collectors.toList()); } checkArgument(streamList.size() > 0, "You must provide at least one stream to merge"); if (streamList.size() == 1) return streamList.iterator().next(); return new EventStream<>(new MergeEventPublisher<>(streamList)); } /** * Removes one level of nesting from a stream of streams. * * @param streamOfStreams * a stream of streams to flatten * @return a new event stream with one level of nesting removed. * @param <E> * the type of the event stream created by flattening the stream * of streams */ public final static <E> EventStream<E> flatten(EventStream<EventStream<E>> streamOfStreams) { return new EventStream<>(new FlattenPublisher<>(streamOfStreams)); } }
39.617304
113
0.640445
b4e243b9cb5e6ecad0d695b0a00ac43ab8fe353a
1,201
/* * (C) Copyright IBM Corp. 2016,2020 * * SPDX-License-Identifier: Apache-2.0 */ package com.ibm.whc.deid.etl; import com.ibm.whc.deid.util.Tuple; import java.util.ArrayList; import java.util.List; public class Pipeline { /** The Pipeline object list. */ List<PipelineObject> pipelineObjectList; /** * From json string pipeline. * * @param jsonConfiguration the json configuration * @return the pipeline */ public static Pipeline fromJSONString(String jsonConfiguration) { return new Pipeline(); } /** * Instantiates a new Pipeline. * * @param objects the objects */ public Pipeline(List<PipelineObject> objects) { this.pipelineObjectList = new ArrayList<>(objects); } /** Instantiates a new Pipeline. */ public Pipeline() { this.pipelineObjectList = new ArrayList<>(); } /** * Run string. * * @param input the input * @return the string */ public String run(String input) { for (PipelineObject object : pipelineObjectList) { Tuple<String, Boolean> result = object.apply(input); if (!result.getSecond()) { break; } input = result.getFirst(); } return input; } }
20.355932
67
0.646128
4aea73f0d6d496e283bcf5e0021383ab293b936b
4,605
package com.gazman.disk_cache; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Random; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { private VIF VIF; @Before public void setUp() { Context appContext = InstrumentationRegistry.getTargetContext(); VIF = new VIF(appContext, "test_db_" + System.currentTimeMillis(), 1024 * 1024 * 2); } @After public void tearDown() { VIF.shutDownAndWait(); } @Test public void testPutGetAsObject() throws Exception { final String message = "Hello there"; ByteArrayInputStream inputStream = new ByteArrayInputStream(message.getBytes("UTF-8")); VIF.put("key1", inputStream); VIF.getAsObject("key1", new VIF.ParserCallback<String>() { @Override public String parse(File file) throws IOException { FileInputStream fileInputStream = new FileInputStream(file); byte[] buffer = new byte[fileInputStream.available()]; //noinspection ResultOfMethodCallIgnored fileInputStream.read(buffer); return new String(buffer, "UTF-8"); } @Override public void onError(Throwable e) { fail(e.getMessage()); } @Override public void onResult(String result) { assertEquals(message, result); } }); } @Test public void testPutGetAsFile() throws Exception { final String message = "Hello there"; final ByteArrayInputStream inputStream = new ByteArrayInputStream(message.getBytes("UTF-8")); VIF.put("key1", inputStream); VIF.getAsFile("key1", new VIF.FileCallback() { @Override public void onResult(File file) { if (file != null) { assertTrue(file.exists()); } else { fail("File is null"); } } }); } @Test public void testDelete() throws Exception { final String message = "Hello there"; ByteArrayInputStream inputStream = new ByteArrayInputStream(message.getBytes("UTF-8")); VIF.put("key1", inputStream); VIF.delete("key1"); VIF.getAsObject("key1", new VIF.ParserCallback<String>() { @Override public String parse(File file) throws Exception { FileInputStream fileInputStream = new FileInputStream(file); byte[] buffer = new byte[fileInputStream.available()]; //noinspection ResultOfMethodCallIgnored fileInputStream.read(buffer); return new String(buffer, "UTF-8"); } @Override public void onError(Throwable e) { fail(e.getMessage()); } @Override public void onResult(String result) { assertEquals(result, null); } }); } @Test public void testAutoDelete() throws Exception { VIF.put("object1", createObject(1024 * 1024)); VIF.put("object2", createObject(1024 * 1024)); validateObject("object1", false); VIF.put("object3", createObject(1024 * 1024)); validateObject("object1", false); validateObject("object3", false); validateObject("object2", true); } private void validateObject(final String key, final boolean deleted) { VIF.getAsFile(key, new VIF.FileCallback() { @Override public void onResult(File file) { assertEquals(key, deleted, file == null || !file.exists()); } }); } private InputStream createObject(int size) { Random random = new Random(size); byte[] data = new byte[size]; random.nextBytes(data); return new ByteArrayInputStream(data); } }
31.326531
101
0.601954
0f207ceb3120b0f2338248036d8679587c33b985
221
package com.flat502.rox.server.response; public interface Response { /** The content of the response. */ public byte[] getContent(); /** The mimetype of the content. */ public String getContentType(); }
22.1
40
0.674208
b669d4049c8d70d072ecfbb1d6b3ae3a5e544780
275
package com.collabra.backend.dto; import java.util.List; public class UserListDTO { private List<UserDTO> userList; public List<UserDTO> getUserList() { return userList; } public void setUserList(List<UserDTO> userList) { this.userList = userList; } }
16.176471
51
0.712727
7dc497b42b2a1c2d94bcea491b38d77b64a7b1d2
43,930
package com.botongsoft.rfid.ui.fragment; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.ProgressBar; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import com.botongsoft.rfid.BaseApplication; import com.botongsoft.rfid.R; import com.botongsoft.rfid.Receiver.KeyReceiver; import com.botongsoft.rfid.bean.classity.CheckError; import com.botongsoft.rfid.bean.classity.CheckPlanDeatil; import com.botongsoft.rfid.bean.classity.CheckPlanDeatilDel; import com.botongsoft.rfid.bean.classity.Epc; import com.botongsoft.rfid.bean.classity.Kf; import com.botongsoft.rfid.bean.classity.Mjj; import com.botongsoft.rfid.bean.classity.Mjjg; import com.botongsoft.rfid.bean.classity.Mjjgda; import com.botongsoft.rfid.common.Constant; import com.botongsoft.rfid.common.db.DBDataUtils; import com.botongsoft.rfid.common.db.SearchDb; import com.botongsoft.rfid.common.utils.ConverJavaBean; import com.botongsoft.rfid.common.utils.LogUtils; import com.botongsoft.rfid.common.utils.SNUtil; import com.botongsoft.rfid.common.utils.SoundUtil; import com.botongsoft.rfid.common.utils.ToastUtils; import com.botongsoft.rfid.listener.OnItemClickListener; import com.botongsoft.rfid.ui.adapter.ScanCheckPlanDetailAdapter; import com.botongsoft.rfid.ui.widget.RecyclerViewDecoration.ListViewDescDecoration; import com.handheld.UHFLonger.UHFLongerManager; import com.yanzhenjie.recyclerview.swipe.Closeable; import com.yanzhenjie.recyclerview.swipe.OnSwipeMenuItemClickListener; import com.yanzhenjie.recyclerview.swipe.SwipeMenu; import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator; import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import butterknife.BindView; import static com.botongsoft.rfid.common.Constant.coverNum; import static com.botongsoft.rfid.common.Constant.getMjjg; import static com.botongsoft.rfid.common.db.DBDataUtils.getCount; import static com.botongsoft.rfid.common.db.DBDataUtils.getInfo; import static com.botongsoft.rfid.ui.activity.BaseActivity.activity; /** * 出错这里要报警,RFID读取要终止。要不读取档案记录的话还会添加进去。 * 出错返回activity 要有提示 * Created by pc on 2017/6/26. */ public class ScanCheckPlanDetailFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener { private static final int UI_SUCCESS = 0; private static final int UI_NOMJG_ERROR = 1; private static final int UI_NOSCANFW_ERROR = 2; private static final int MSG_UPDATE_INFO = 1; private static final int UI_SAVE_ERROR = 3; @BindView(R.id.recycler_view) SwipeMenuRecyclerView mSwipeMenuRecyclerView; // @BindView(R.id.tx_layout) // TextInputLayout mTextInputLayout; // @BindView(R.id.input_tx) // TextInputEditText mTextInputEditText; @BindView(R.id.st_saoma) Switch mSwitch; @BindView(R.id.st_ajzt) Switch mSwitch_ajzt; @BindView(R.id.tv_info) TextView mTextView; // CheckPlanDetailActivity parentActivity; private static String scanInfoLocal = "";//扫描的格子位置 根据“/”拆分后存入数据库 // private static String scanInfoNow = "";//扫描的格子位置 private String editString; private List<Mjjgda> mDataLists = new ArrayList<Mjjgda>(); private Set<String> ajztList = new HashSet<String>(); private List<Mjj> mjjLists = new ArrayList<>(); private List mjjgList = new ArrayList(); private List<CheckPlanDeatilDel> delTempList = new ArrayList<>(); private String[] srrArray; private Set<String> stringList = new HashSet<String>();//用来存放扫描过的密集格档案 防止重复扫描 private ScanCheckPlanDetailAdapter scanCheckPlanDetailAdapter; private ScanCheckPlanDetailFragment mContext; private HandlerThread mCheckMsgThread;//Handler线程池 //后台运行的handler private Handler mCheckMsgHandler; //与UI线程管理的handler private Handler mHandler; private boolean isOnScreen;//是否在屏幕上 private boolean isRun;//是否在RFID读取 private boolean ajztFlag; //传递后台运行消息队列 Message msg; //传递UI前台显示消息队列 Message mHandlerMessage; Bundle mBundle; Bundle saveErrBundele; private int type; private int pdid; private String fw; // private static int size1 = 1; private static int oldMjjId; private static int oldMjgId; private static int oldKfId; private static int oldZy; // private SoundPool soundPool; // private PlaySoundPool soundPool; Thread thread; private boolean runFlag = true; private boolean startFlag = false; private KeyReceiver keyReceiver; private static UHFLongerManager manager; public static ScanCheckPlanDetailFragment newInstance(int type, int pdid, String fw) { Bundle args = new Bundle(); args.putInt("type", type); args.putInt("pdid", pdid); args.putString("fw", fw); ScanCheckPlanDetailFragment fragment = new ScanCheckPlanDetailFragment(); fragment.setArguments(args); return fragment; } @Override public void onRefresh() { } @Override protected void initRootView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.scancheckplandetail_fragment, container, false); if (getArguments() != null) { type = getArguments().getInt("type"); pdid = getArguments().getInt("pdid"); fw = getArguments().getString("fw"); srrArray = fw.split(","); } } @Override protected void initEvents() { try { manager = BaseApplication.application.getmanager(); SharedPreferences sp = BaseApplication.application.getSharedPreferences("power", 0); // int value = ShareManager.getInt(this, "power"); int value = sp.getInt("value", 0); if (value == 0) { value = 30; } if (manager != null) { manager.setOutPower((short) value); } } catch (Exception e) { e.printStackTrace(); } mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { // 开启switch,设置提示信息 startFlag = true; } else { // 关闭swtich,设置提示信息 startFlag = false; } } }); mSwitch_ajzt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { // 开启switch,设置提示信息 ajztFlag = true; switchChange(); } else { // 关闭swtich,设置提示信息 ajztFlag = false; switchChange(); } } }); thread = new ThreadMe(); thread.start(); keyReceiver = new KeyReceiver(manager, false, mSwitch); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("android.rfid.FUN_KEY"); activity.registerReceiver(keyReceiver, intentFilter); } private void switchChange() { if (mDataLists != null && mDataLists.size() > 0) { mDataLists.clear(); } if (ajztList != null && ajztList.size() > 0) { ajztList.clear(); } if (mjjgList != null && mjjgList.size() > 0) { mjjgList.remove(0); } scanCheckPlanDetailAdapter.notifyDataSetChanged(); } @Override public void onCreate(Bundle savedInstanceState) { //此处可以设置Dialog的style等等 super.onCreate(savedInstanceState); // setCancelable(false);//无法直接点击外部取消dialog // setStyle(DialogFragment.STYLE_NO_FRAME,0); //NO_FRAME就是dialog无边框,0指的是默认系统Theme // parentActivity = (CheckPlanDetailActivity) getActivity();//目测没用 先注释掉 initUiHandler(); } @Override protected void initData(boolean isSavedNull) { LinearLayoutManager layout = new LinearLayoutManager(getContext()); mSwipeMenuRecyclerView.setLayoutManager(layout);// 布局管理器。 // layout.setStackFromEnd(true);//列表再底部开始展示,反转后由上面开始展示 // layout.setReverseLayout(true);//列表翻转 mSwipeMenuRecyclerView.setHasFixedSize(true);// 如果Item够简单,高度是确定的,打开FixSize将提高性能。 // mSwipeMenuRecyclerView.setItemAnimator(new DefaultItemAnimator());// 设置Item默认动画,加也行,不加也行。 mSwipeMenuRecyclerView.addItemDecoration(new ListViewDescDecoration());// 添加分割线。 // mTextInputEditText.addTextChangedListener(new TextWatcher() { // @Override // public void beforeTextChanged(CharSequence s, int start, int count, int after) { // // 输入前的监听 // // Log.e("输入前确认执行该方法", "开始输入"); // mCheckMsgHandler.removeMessages(MSG_UPDATE_INFO); // } // // @Override // public void onTextChanged(CharSequence s, int start, int before, int count) { // // 输入的内容变化的监听 // // Log.e("输入过程中执行该方法", "文字变化"); // if (mCheckMsgHandler != null) { // mCheckMsgHandler.removeCallbacks(delayRun); // } // mCheckMsgHandler.removeMessages(MSG_UPDATE_INFO); // } // // @Override // public void afterTextChanged(Editable editable) { // // 输入后的监听 // // Log.e("输入结束执行该方法", "输入结束"); // Log.e("Handler textChanged--->", String.valueOf(Thread.currentThread().getName())); // if (mTextInputEditText.length() != 0) { // if (mCheckMsgHandler != null) { // mCheckMsgHandler.removeCallbacks(delayRun); // } // //延迟800ms,如果不再输入字符,则执行该线程的run方法 模拟扫描输入 // msg = mCheckMsgHandler.obtainMessage(); // msg.what = MSG_UPDATE_INFO; // mCheckMsgHandler.sendMessageDelayed(msg, Constant.delayRun); // } // } // }); // 添加滚动监听。 // mSwipeMenuRecyclerView.addOnScrollListener(mOnScrollListener); // 设置菜单创建器。 mSwipeMenuRecyclerView.setSwipeMenuCreator(swipeMenuCreator); // 设置菜单Item点击监听。 mSwipeMenuRecyclerView.setSwipeMenuItemClickListener(menuItemClickListener); scanCheckPlanDetailAdapter = new ScanCheckPlanDetailAdapter(getActivity(), mDataLists); scanCheckPlanDetailAdapter.setOnItemClickListener(onItemClickListener); mSwipeMenuRecyclerView.setAdapter(scanCheckPlanDetailAdapter); } private void initUiHandler() { mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case UI_SUCCESS: if (mBundle != null) { mTextView.setText(mBundle.getString("info")); } // mTextInputEditText.setText(""); // smoothMoveToPosition(mSwipeMenuRecyclerView, mDataLists.size() + 1); if (msg.obj != null) { int position = (int) msg.obj; scanCheckPlanDetailAdapter.notifyItemChanged(position); } else { scanCheckPlanDetailAdapter.notifyDataSetChanged(); } // scanCheckPlanDetailAdapter.notifyDataSetChanged(); break; case UI_NOMJG_ERROR: // mTextInputEditText.setText(""); Toast.makeText(getContext(), "请先扫描密集格后再进行操作", Toast.LENGTH_SHORT).show(); break; case UI_NOSCANFW_ERROR: // mTextInputEditText.setText(""); Toast.makeText(getContext(), "该密集格不在盘点范围内", Toast.LENGTH_SHORT).show(); break; case UI_SAVE_ERROR: if (saveErrBundele != null) { // mTextInputEditText.setText(""); String bm = (saveErrBundele.getString("bm")); String jlid = (saveErrBundele.getString("jlid")); String mjg = (saveErrBundele.getString("mjg")); Toast.makeText(getContext(), "记录保存失败," + "错误记录编码 " + bm + "-" + jlid, Toast.LENGTH_SHORT).show(); } break; default: super.handleMessage(msg);//这里最好对不需要或者不关心的消息抛给父类,避免丢失消息 break; } } }; } /* * 目标项是否在最后一个可见项之后 */ boolean mShouldScroll; /** * 记录目标项位置 */ int mToPosition; /** * 滑动到指定位置 * * @param mRecyclerView * @param position */ public void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) { // 第一个可见位置 int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0)); // 最后一个可见位置 int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1)); if (position < firstItem) { // 如果跳转位置在第一个可见位置之前,就smoothScrollToPosition可以直接跳转 mRecyclerView.smoothScrollToPosition(position); } else if (position <= lastItem) { // 跳转位置在第一个可见项之后,最后一个可见项之前 // smoothScrollToPosition根本不会动,此时调用smoothScrollBy来滑动到指定位置 int movePosition = position - firstItem; if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) { int top = mRecyclerView.getChildAt(movePosition).getTop(); mRecyclerView.smoothScrollBy(0, top); } } else { // 如果要跳转的位置在最后可见项之后,则先调用smoothScrollToPosition将要跳转的位置滚动到可见位置 // 再通过onScrollStateChanged控制再次调用smoothMoveToPosition,执行上一个判断中的方法 mRecyclerView.smoothScrollToPosition(position); mToPosition = position; mShouldScroll = true; } } @Override public void onResume() { super.onResume(); Log.e("onResume--->", String.valueOf(Thread.currentThread().getName())); isOnScreen = true; // if(isOnScreen && isRun) { if (isOnScreen) { //开启新进程 // mCheckMsgThread = new HandlerThread("BackThread");// 创建一个BackHandlerThread对象,它是一个线程 // mCheckMsgThread.start();// 启动线程 //创建后台线程 // initBackThread(); } mSwitch.setChecked(false); mSwitch_ajzt.setChecked(false); } private void initBackThread() { mCheckMsgHandler = new Handler(mCheckMsgThread.getLooper()) { @Override public void handleMessage(Message msg) { Log.e("Handler BackThread--->", String.valueOf(Thread.currentThread().getName())); switch (msg.what) { case MSG_UPDATE_INFO: // checkForUpdate();// break; default: super.handleMessage(msg);//这里最好对不需要或者不关心的消息抛给父类,避免丢失消息 break; } } }; } /** * 延迟线程,看是否还有下一个字符输入 */ private void checkForUpdate() { mCheckMsgHandler.post(delayRun); } private Runnable delayRun = new Runnable() { @Override public void run() { //在这里调用服务器的接口,获取数据 Log.e("Handler delayRun--->", String.valueOf(Thread.currentThread().getName())); // mHandler.obtainMessage(UI_SUCCESS).sendToTarget(); // mTextView.post(new Runnable() { // @Override // public void run() { // Log.e("setText--->", String.valueOf(Thread.currentThread().getName())); // mTextView.setText(mTextInputEditText.getText()); // mTextInputEditText.setText(""); // } // }); //在这里读取数据库增加list值,界面显示读取的标签信息 //这里定义发送通知ui更新界面 // mHandlerMessage = mHandler.obtainMessage(); // mHandlerMessage.what = UI_SUCCESS; // editString = mTextInputEditText.getText().toString(); // searchDB(editString); // mHandler.sendMessage(mHandlerMessage); } }; private static int text = 0; private static int nowMjjgId = 0; private static int nowMjjId = 0; private static int nowKfId = 0; private static int nowMjjgZy = 0; private void searchDB(String editString) { boolean tempStr = true;//防止重复扫描状态标记 boolean temp = true;//是否在盘点范围标记 boolean ajztTempFlag = true; mHandlerMessage = mHandler.obtainMessage(); mHandler.sendMessage(mHandlerMessage); int lx = Constant.getLx(editString);//根据传入的值返回对象类型 switch (lx) { case Constant.LX_MJJG: displayMjg(editString, temp); break; } switch (lx) { case Constant.LX_AJZT: if (ajztTempFlag && ajztFlag) { if (scanInfoLocal.equals("")) { mHandlerMessage.what = UI_NOMJG_ERROR; } else { tempStr = newfcf(editString, tempStr, ajztTempFlag, lx);//新防重复(有案卷载体开关) if (tempStr) { int code = Integer.parseInt(editString.substring(1, editString.length())); List<Epc> epcList = (List<Epc>) DBDataUtils.getInfos(Epc.class, "ztcode", String.valueOf(code)); if (epcList != null && epcList.size() > 0) { for (Epc epc1 : epcList) { String epcs = String.valueOf(epc1.getEpccode()); epcs = coverNum(epcs); for (int i = mDataLists.size() - 1; i >= 0; i--) { Mjjgda mjjgda = mDataLists.get(i); String epcCode = coverNum(mjjgda.getEpccode()); // if ((mjjgda.getBm().equals(ecp.getBm())) && (String.valueOf(mjjgda.getJlid()).equals(ecp.getJlid()))) { if (epcCode.equals(epcs)) { if (mjjgda.getFlag() == 1) { mjjgda.setColor(3);//外借被找到 } else { mjjgda.setColor(2);//正确 } mHandlerMessage.obj = i; text = 1; break; } if (i == 0) {//如果循环完毕 都没有在这个格子中找到扫描的这个档案,变量设成0,然后在下面加入mDataLists中显示出新的条目数据 text = 0; } } if (text == 0) { Mjjgda mjjgda = new Mjjgda(); mjjgda.setBm(epc1.getBm()); mjjgda.setJlid(String.valueOf(epc1.getJlid())); mjjgda.setColor(4);//多扫描或错架 mjjgda.setMjjid(nowMjjId); mjjgda.setKfid(nowKfId); mjjgda.setMjgid(nowMjjgId); mjjgda.setTitle(epc1.getArchiveno()); mjjgda.setEpccode(String.valueOf(epc1.getEpccode())); mDataLists.add(mjjgda); SoundUtil.play(1, 0); } } } } } } break; case Constant.LX_MJGDA: if (scanInfoLocal.equals("")) { mHandlerMessage.what = UI_NOMJG_ERROR; } else { //防止扫描重复判断 // tempStr = oldfcf(editString, tempStr);//旧防重复(没有案卷载体开关) if (!ajztFlag) { tempStr = newfcf(editString, tempStr, ajztTempFlag, lx);//新防重复(有案卷载体开关) if (tempStr) { //这里要先查询一次对照表 获得该扫描记录的bm与jlid // Epc ecp = (Epc) DBDataUtils.getInfo(Epc.class, "epccode", editString); for (int i = mDataLists.size() - 1; i >= 0; i--) { Mjjgda mjjgda = mDataLists.get(i); String epcCode = coverNum(mjjgda.getEpccode()); // if ((mjjgda.getBm().equals(ecp.getBm())) && (String.valueOf(mjjgda.getJlid()).equals(ecp.getJlid()))) { if (epcCode.equals(editString)) { if (mjjgda.getFlag() == 1) { mjjgda.setColor(3);//外借被找到 } else { mjjgda.setColor(2);//正确 } mHandlerMessage.obj = i; text = 1; break; } if (i == 0) {//如果循环完毕 都没有在这个格子中找到扫描的这个档案,变量设成0,然后在下面加入mDataLists中显示出新的条目数据 text = 0; } } if (text == 0) { Epc ecp = (Epc) DBDataUtils.getInfo(Epc.class, "epccode", editString); LogUtils.d("newErrorData", ecp.getBm() + "-" + ecp.getJlid()); Mjjgda mjjgda = new Mjjgda(); mjjgda.setBm(ecp.getBm()); mjjgda.setJlid(String.valueOf(ecp.getJlid())); mjjgda.setColor(4);//多扫描或错架 mjjgda.setMjjid(nowMjjId); mjjgda.setKfid(nowKfId); mjjgda.setMjgid(nowMjjgId); mjjgda.setTitle(ecp.getArchiveno()); mjjgda.setEpccode(String.valueOf(ecp.getEpccode())); mDataLists.add(mjjgda); SoundUtil.play(1, 0); } stringList.add(editString); } } } break; case Constant.LX_MJJG: // displayMjg(editString, temp); break; } } private void displayMjg(String editString, boolean temp) { String s[] = Constant.reqDatas(editString); //如果不重复查询密集格表 // Mjjg mjjg = (Mjjg) DBDataUtils.getInfo(Mjjg.class, "mjjid", Integer.valueOf(s[2]).toString(), "zy", Integer.valueOf(s[3]).toString(), // "cs", Integer.valueOf(s[5]).toString(), "zs", Integer.valueOf(s[4]).toString()); Mjjg mjjg = getMjjg(s); if (mjjg != null) { nowMjjgId = mjjg.getId(); nowMjjgZy = mjjg.getZy(); int tt = SearchDb.countPdfw(srrArray, mjjg);//先判断是否在该批次的盘点范围内 if (tt == 0) { temp = false;//false为不在盘点范围 mHandlerMessage.what = UI_NOSCANFW_ERROR; } if (temp) {//temp=true 在盘点范围内 Mjj mjj = (Mjj) getInfo(Mjj.class, "id", String.valueOf(mjjg.getMjjid())); nowMjjId = mjj.getId(); nowKfId = mjj.getKfid(); mjjgList.add(0, editString); if (mjjgList.size() >= 2) {//再判断上一次是否是扫描过的格子,防止重复读取数据库; if (mjjgList.get(0).equals(mjjgList.get(1))) {//当前读取的跟上一次读取的id相同 mjjgList.remove(0); } else { //判断当前格子是否被扫描过(同批次),有的话清除已扫描的错误记录表 clearOrSaveCheckError(mjjg, mjj); //保存错误记录 boolean save = savePdjl(mDataLists, pdid); //保存成功 读取新密集格内档案数据显示在列表上 if (save == true) { dislapView(mjjg); } else { mjjgList.remove(0); } } } else if (mjjgList.size() <= 1) {//list为空或小于1 代表第一次读取 //判断当前格子是否被扫描过(同批次),有的话清除已扫描的错误记录表 clearOrSaveCheckError(mjjg, mjj); //读取密集格内档案数据显示在列表上 dislapView(mjjg); } } } } /*/ 新防重复 */ private boolean newfcf(String editString, boolean tempStr, boolean ajztTempFlag, int lx) { if (ajztFlag) {// tempStr = false; if (lx == Constant.LX_AJZT) { if (ajztList != null && ajztList.size() == 0) { ajztTempFlag = true; tempStr = true; ajztList.add(editString); } else { if (ajztList.contains(editString)) { if (ajztTempFlag) { ajztList.add(editString); } tempStr = true; } else { tempStr = false; ajztTempFlag = false; } /* for (String s : ajztList) { if (s.equals(editString)) { ajztTempFlag = false; tempStr = false; break; } else { tempStr = true; } } if (ajztTempFlag) { ajztList.add(editString); }*/ } } } else { //防止扫描重复判断 if (lx != Constant.LX_AJZT) { tempStr = oldfcf(editString, tempStr); } } return tempStr; } private boolean oldfcf(String editString, boolean tempStr) { if (stringList.size() > 0) { if (stringList.contains(editString)) { tempStr = false; } /*for (String s : stringList) { if (s.equals(editString)) { tempStr = false; break; } }*/ } return tempStr; } private void clearOrSaveCheckError(Mjjg mjjg, Mjj mjj) { // 判断当前格子是否被扫描过(同批次),有的话清除已扫描的错误记录表 CheckError ce = (CheckError) DBDataUtils.getInfo(CheckError.class, "pdid", String.valueOf(pdid), "mjgid", String.valueOf(mjjg.getId()), "zy", String.valueOf(mjjg.getZy()), "mjjid", String.valueOf(mjjg.getMjjid()), "kfid", String.valueOf(mjj.getKfid())); if (ce != null) {//数据库有扫描过该格子了 List<CheckPlanDeatil> mCheckPlanDeatilList = (List) DBDataUtils.getInfosHasOp(CheckPlanDeatil.class, "pdid", "=", String.valueOf(pdid), "mjgid", "=", String.valueOf(mjjg.getId())); if (mCheckPlanDeatilList != null && !mCheckPlanDeatilList.isEmpty()) { for (CheckPlanDeatil checkPlanDeatil : mCheckPlanDeatilList) { CheckPlanDeatilDel cd = ConverJavaBean.toAnotherObj(checkPlanDeatil, CheckPlanDeatilDel.class); delTempList.add(cd); } DBDataUtils.saveAll(delTempList); } //清楚数据库扫过的该批次的格子内容 DBDataUtils.deleteInfos(CheckPlanDeatil.class, "pdid", String.valueOf(pdid), "mjgid", String.valueOf(mjjg.getId())); delTempList.clear(); ce.setAnchor(0);//将扫描过的版本号设置为0,提交服务器的时候 ,服务器会删除该格子的旧数据。 DBDataUtils.update(ce); } else { CheckError mCheckError = new CheckError(); mCheckError.setMjgid(mjjg.getId()); mCheckError.setPdid(pdid); mCheckError.setZy(mjjg.getZy()); mCheckError.setMjjid(mjjg.getMjjid()); mCheckError.setKfid(mjj.getKfid()); mCheckError.setStatus(0); // mCheckError.setAnchor(SNUtil.nextSid()); mCheckError.setAnchor(0); DBDataUtils.save(mCheckError); } } private boolean savePdjl(List<Mjjgda> mDataLists, int pdid) { boolean save = true; for (Mjjgda mDataList : mDataLists) { if (mDataList.getColor() != 2) { CheckPlanDeatil mCheckPlanDeatil = null; if (save) { try { mCheckPlanDeatil = new CheckPlanDeatil(); mCheckPlanDeatil.setBm(mDataList.getBm()); mCheckPlanDeatil.setJlid(Integer.valueOf(mDataList.getJlid())); mCheckPlanDeatil.setMjgid(mDataList.getMjgid()); mCheckPlanDeatil.setKfid(mDataList.getKfid()); mCheckPlanDeatil.setZy(oldZy); mCheckPlanDeatil.setMjjid(oldMjjId); mCheckPlanDeatil.setPdid(pdid); mCheckPlanDeatil.setAnchor(SNUtil.nextSid()); mCheckPlanDeatil.setStatus(0); if (mDataList.getColor() == 3) { mCheckPlanDeatil.setType(3); } else if (mDataList.getColor() == 0) { mCheckPlanDeatil.setType(2); } else if (mDataList.getColor() == 4) { mCheckPlanDeatil.setType(4); } DBDataUtils.save(mCheckPlanDeatil); } catch (Exception e) { save = false; //出错这里要报警,RFID读取要终止。要不读取档案记录的话还会添加进去。 SoundUtil.play(2, 0); mHandlerMessage.what = UI_SAVE_ERROR; saveErrBundele = new Bundle(); saveErrBundele.putString("mjg", String.valueOf(mDataList.getMjgid())); saveErrBundele.putString("bm", mDataList.getBm()); saveErrBundele.putString("jlid", mDataList.getJlid()); mHandlerMessage.setData(saveErrBundele); Log.e("记录保存失败", "Exception = " + e); e.printStackTrace(); } } } } return save; } private void dislapView(Mjjg mjjg) { stringList.clear(); mDataLists.clear(); displayTextLocal(mjjg);//界面显示扫描的格子位置 displayMjgdaLocal(mjjg);//显示该格子内的档案数据 } private void displayMjgdaLocal(Mjjg mjjg) { List<Mjjgda> mjjgdaList = new ArrayList<>(); mjjgdaList = (List<Mjjgda>) DBDataUtils.getInfos(Mjjgda.class, "mjgid", String.valueOf(mjjg.getId())); for (Mjjgda mjjgdaThemp : mjjgdaList) { Epc ecp = (Epc) DBDataUtils.getInfo(Epc.class, "bm", mjjgdaThemp.getBm(), "jlid", mjjgdaThemp.getJlid()); if (ecp != null) { mjjgdaThemp.setEpccode(String.valueOf(ecp.getEpccode())); mjjgdaThemp.setTitle(ecp.getArchiveno()); } } mDataLists.addAll(mjjgdaList); } /** * 界面显示当前扫描的格子位置 * * @param mjjg */ private void displayTextLocal(Mjjg mjjg) { StringBuilder sb = new StringBuilder(); String kfname = ""; String mjjname = ""; String nLOrR = ""; Kf kf = null; Mjj mjj = (Mjj) getInfo(Mjj.class, "id", String.valueOf(mjjg.getMjjid())); if (mjj != null) { mjjname = mjj.getMc() + "/"; kf = (Kf) getInfo(Kf.class, "id", String.valueOf(mjj.getKfid())); } if (kf != null) { kfname = kf.getMc() + "/"; } nLOrR = mjjg.getZy() == 1 ? "左" : "右"; // String name = kfname + mjjname + nLOrR + "/" + mjjg.getZs() + "组" + mjjg.getCs() + "层"; int countemp = getCount(Mjjgda.class, "mjgid", "=", String.valueOf(mjjg.getId())); int outCountTemp = getCount(Mjjgda.class, "mjgid", "=", String.valueOf(mjjg.getId()), "flag", "=", "1"); sb.append(kfname).append(mjjname).append(nLOrR).append("/").append(mjjg.getZs()).append("组").append(mjjg.getCs()).append("层").append("\n"); sb.append("共").append(countemp).append("案卷,").append("外借").append(outCountTemp).append("卷"); String temple = kf.getId() + "/" + mjj.getId() + "/" + mjjg.getId();//这里的值用来拆分存放位置存入档案表 mBundle = new Bundle(); mBundle.putString("info", sb.toString()); scanInfoLocal = temple; oldMjjId = mjj.getId(); oldMjgId = mjjg.getId(); oldKfId = kf.getId(); oldZy = mjjg.getZy(); mHandlerMessage.setData(mBundle); } @Override public void onDestroyView() { savePdjl(mDataLists, pdid); stringList.clear(); scanInfoLocal = ""; startFlag = false; runFlag = false; getActivity().unregisterReceiver(keyReceiver); thread.interrupt(); super.onDestroyView(); } /** * 菜单创建器。在Item要创建菜单的时候调用。 */ private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() { @Override public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) { int width = getResources().getDimensionPixelSize(R.dimen.item_height); // MATCH_PARENT 自适应高度,保持和内容一样高;也可以指定菜单具体高度,也可以用WRAP_CONTENT。 int height = ViewGroup.LayoutParams.MATCH_PARENT; // 添加左侧的,如果不添加,则左侧不会出现菜单。 /* { SwipeMenuItem addItem = new SwipeMenuItem(mContext) .setBackgroundDrawable(R.drawable.selector_green)// 点击的背景。 .setImage(R.mipmap.ic_action_add) // 图标。 .setWidth(width) // 宽度。 .setHeight(height); // 高度。 swipeLeftMenu.addMenuItem(addItem); // 添加一个按钮到左侧菜单。 SwipeMenuItem closeItem = new SwipeMenuItem(mContext) .setBackgroundDrawable(R.drawable.selector_red) .setImage(R.mipmap.ic_action_close) .setWidth(width) .setHeight(height); swipeLeftMenu.addMenuItem(closeItem); // 添加一个按钮到左侧菜单。 }*/ // 添加右侧的,如果不添加,则右侧不会出现菜单。 /* { SwipeMenuItem deleteItem = new SwipeMenuItem(mContext) .setBackgroundDrawable(R.drawable.selector_red) .setImage(R.mipmap.ic_action_delete) .setText("删除") // 文字,还可以设置文字颜色,大小等。。 .setTextColor(Color.WHITE) .setWidth(width) .setHeight(height); swipeRightMenu.addMenuItem(deleteItem);// 添加一个按钮到右侧侧菜单。 SwipeMenuItem closeItem = new SwipeMenuItem(mContext) .setBackgroundDrawable(R.drawable.selector_purple) .setImage(R.mipmap.ic_action_close) .setWidth(width) .setHeight(height); swipeRightMenu.addMenuItem(closeItem); // 添加一个按钮到右侧菜单。 SwipeMenuItem addItem = new SwipeMenuItem(mContext) .setBackgroundDrawable(R.drawable.selector_green) .setText("添加") .setTextColor(Color.WHITE) .setWidth(width) .setHeight(height); swipeRightMenu.addMenuItem(addItem); // 添加一个按钮到右侧菜单。 }*/ } }; /** * 菜单点击监听。 */ private OnSwipeMenuItemClickListener menuItemClickListener = new OnSwipeMenuItemClickListener() { /** * Item的菜单被点击的时候调用。 * @param closeable closeable. 用来关闭菜单。 * @param adapterPosition adapterPosition. 这个菜单所在的item在Adapter中position。 * @param menuPosition menuPosition. 这个菜单的position。比如你为某个Item创建了2个MenuItem,那么这个position可能是是 0、1, * @param direction 如果是左侧菜单,值是:SwipeMenuRecyclerView#LEFT_DIRECTION,如果是右侧菜单,值是:SwipeMenuRecyclerView * #RIGHT_DIRECTION. */ @Override public void onItemClick(Closeable closeable, int adapterPosition, int menuPosition, int direction) { closeable.smoothCloseMenu();// 关闭被点击的菜单。 if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) { Toast.makeText(getContext(), "list第" + adapterPosition + "; 右侧菜单第" + menuPosition, Toast.LENGTH_SHORT).show(); } else if (direction == SwipeMenuRecyclerView.LEFT_DIRECTION) { Toast.makeText(getContext(), "list第" + adapterPosition + "; 左侧菜单第" + menuPosition, Toast.LENGTH_SHORT).show(); } // TODO 推荐调用Adapter.notifyItemRemoved(position),也可以Adapter.notifyDataSetChanged(); if (menuPosition == 0) {// 删除按钮被点击。 mDataLists.remove(adapterPosition); scanCheckPlanDetailAdapter.notifyItemRemoved(adapterPosition); } } }; private OnItemClickListener onItemClickListener = new OnItemClickListener() { @Override public void onItemClick(int position) { //详细信息 StringBuilder sb = new StringBuilder(); // sb.append("Title:").append(mDataLists.get(position).get("title")).append("\n"); // sb.append("位置:").append(mDataLists.get(position).get("local")).append("\n"); // new AlertDialog.Builder(BaseActivity.activity) // .setTitle("详细信息:") // .setMessage(sb) // .setOnDismissListener(new DialogInterface.OnDismissListener() { // @Override // public void onDismiss(DialogInterface dialog) { // // } // }) // .create().show(); } @Override public void onItemClick(int position, int listSize) { // Toast.makeText(getContext(), "我是第" + position + "条。", Toast.LENGTH_SHORT).show(); new AlertDialog.Builder(getContext()) .setMessage("确定要忽略这条错误吗?") .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (position != -1) { mDataLists.get(position).setColor(2); scanCheckPlanDetailAdapter.notifyItemChanged(position); // mDataLists.remove(position); // scanCheckPlanDetailAdapter.notifyItemRemoved(position); // scanCheckPlanDetailAdapter.notifyItemRangeChanged(position, listSize); } } }) .create().show(); } @Override public void onItemClick(int position, int listSize, ProgressBar pb) { } }; class ThreadMe extends Thread { private List<String> epcList; @Override public void run() { super.run(); while (runFlag) { if (startFlag) { if (BaseApplication.application.getmanager() != null) { epcList = BaseApplication.application.getmanager().inventoryRealTime(); // if (epcList != null && !epcList.isEmpty()) { SoundUtil.play(1, 0); Message sMessage = mHandler.obtainMessage(); sMessage.what = UI_SUCCESS; for (String epc : epcList) { searchDB(epc); } mHandler.sendMessage(sMessage); } epcList = null; try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { runFlag = false; startFlag = false; getActivity().runOnUiThread(new Runnable() { public void run() { ToastUtils.showLong("硬件链接失败"); } }); } } } } } }
43.366239
173
0.508354
791a6654b0525f7d846194f11bc603e3942a5445
1,679
/* The contents of this file are subject to the license and copyright terms * detailed in the license directory at the root of the source tree (also * available online at http://fedora-commons.org/license/). */ package org.fcrepo.client.objecteditor; import java.awt.event.ActionListener; import java.io.IOException; import java.io.InputStream; /** * Edit content of certain types in a JComponent. */ public abstract class ContentEditor extends ContentViewer { /** * Always returns true. */ @Override public final boolean isEditor() { return true; } public void setPIDAndDSID(String pid, String dsid) { } /** * Called when the caller wants what is in the view to be considered "not * dirty" because it's been saved that way. */ public abstract void changesSaved(); /** * Called when the caller wants to update the view back to the data was * originally passed in. */ public abstract void undoChanges(); /** * Returns true if the content should be considered "dirty" (e.g. it has * changed due to some form of editing). */ public abstract boolean isDirty(); /** * Sets the listener that this ContentEditor will notify via * listener.actionPerformed(...) when any content-changing events occur that * could potentially affect its "dirty state" (whether going from not dirty * to dirty, or dirty to not dirty). */ public abstract void setContentChangeListener(ActionListener listener); /** * Gets the content in its edited state. */ public abstract InputStream getContent() throws IOException; }
27.983333
80
0.674806
e445628b2dc0c74c012fcd134ce1ea5e1edc0820
784
package com.forasterisk.ilkeok.api; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; import rx.Observable; /** * Created by yearnning on 15. 10. 21.. */ public interface ApiInterface { @GET("search/msearch.nhn") Observable<ResponseBody> WebtoonDetailApi(@Query("keyword") String keyword, @Query("searchType") String search_type, @Query("version") String version, @Query("page") String page); @GET("webtoon/list.nhn") Observable<ResponseBody> EpisodeListApi(@Query("titleId") String naver_id, @Query("page") int page); }
31.36
86
0.566327
d75fd1773f53e8408c85965e62adc6bb39c6fd3f
3,058
/******************************************************************************* * Copyright 2009-2019 Exactpro (Exactpro Systems Limited) * * 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.exactpro.sf.embedded.statistics.storage.utils; import static java.util.Objects.requireNonNull; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; public class Conditions { public static ICondition create(String value) { return new SimpleCondition(value); } public static ICondition or(ICondition... conditions) { return new MultipleCondition(Operator.OR, conditions); } public static ICondition and(ICondition... conditions) { return new MultipleCondition(Operator.AND, conditions); } public static ICondition wrap(ICondition condition) { return new WrapCondition(condition); } private static class MultipleCondition extends SimpleCondition { private MultipleCondition(Operator operator, ICondition... conditions) { super(condition(operator, conditions)); } private static String condition(Operator operator, ICondition... conditions) { requireNonNull(operator, "'Operator' parameter"); return Stream.of(requireNonNull(conditions, "'Conditions' parameter")) .filter(Objects::nonNull) .map(ICondition::getCondition) .collect(Collectors.joining(" " + operator.getValue() + " ")); } } private static class SimpleCondition implements ICondition { private final String value; private SimpleCondition(String value) { if (StringUtils.isBlank(value)) { throw new IllegalArgumentException("condition can't be blank"); } this.value = value; } @Override public String getCondition() { return value; } } private static class WrapCondition extends SimpleCondition { private WrapCondition(ICondition condition) { super("(" + condition.getCondition() + ")"); } } private enum Operator { OR("or"), AND("and"); private final String value; Operator(String value) { this.value = value; } public String getValue() { return value; } } }
31.854167
86
0.61707
00a24006607e27c15355cd2043874abb141ebfe9
2,915
package org.apache.archiva.event; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.ConcurrentHashMap; public class EventManager implements EventSource { private static final Logger LOG = LoggerFactory.getLogger(EventManager.class); private final ConcurrentHashMap<EventType<? extends Event>, Set<EventHandler>> handlerMap = new ConcurrentHashMap<>(); private final Object source; public EventManager(Object source) { if (source==null) { throw new IllegalArgumentException("The source may not be null"); } this.source = source; } @Override public <T extends Event> void registerEventHandler(EventType<T> type, EventHandler<? super T> eventHandler) { Set<EventHandler> handlers = handlerMap.computeIfAbsent(type, t -> new LinkedHashSet<>()); if (!handlers.contains(eventHandler)) { handlers.add(eventHandler); } } @Override public <T extends Event> void unregisterEventHandler(EventType<T> type, EventHandler<? super T> eventHandler) { if (handlerMap.containsKey(type)) { handlerMap.get(type).remove(eventHandler); } } public void fireEvent(Event fireEvent) { final EventType<? extends Event> type = fireEvent.getType(); Event event; if (fireEvent.getSource()!=source) { event = fireEvent.copyFor(source); } else { event = fireEvent; } for (EventType<? extends Event> handlerType : handlerMap.keySet()) { if (EventType.isInstanceOf(type, handlerType)) { for (EventHandler handler : handlerMap.get(handlerType)) { try { handler.handle(event); } catch (Exception e) { // We catch all errors from handlers LOG.error("An error occured during event handling: {}", e.getMessage(), e); } } } } } }
35.987654
122
0.639794
2b49c119b9d18eec4324e5a5ee45ae5132323372
6,404
package SocketsChat; //Blibliotecas Importadas import javax.swing.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.ArrayList; public class Cliente { public static void main(String[] args) { MarcoCliente mimarco=new MarcoCliente(); //LLama la Clase del Frame mimarco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Activael cerrar } } class MarcoCliente extends JFrame{ public MarcoCliente(){ setBounds(600,300,280,350); LaminaMarcoCliente milamina=new LaminaMarcoCliente(); add(milamina); setVisible(true); addWindowListener(new EnvioOnline()); } } //-----------------------ENVIO SEÑAL ONLINE-------------------------- class EnvioOnline extends WindowAdapter{ public void windowOpened(WindowEvent e){ try{ Socket misocket = new Socket("192.168.56.1",9999); PaqueteEnvio datos = new PaqueteEnvio(); datos.setMensaje(" online"); ObjectOutputStream paquete_datos=new ObjectOutputStream (misocket.getOutputStream()); paquete_datos.writeObject(datos); misocket.close(); }catch(Exception e2){} } } //clase que contiene la interfaz se ejecuta con hilos class LaminaMarcoCliente extends JPanel implements Runnable { public LaminaMarcoCliente(){ String nick_usuario = JOptionPane.showInputDialog("Nick: "); //instancia de los componentes para la creación de la interfaz JLabel n_nick = new JLabel("Nick: "); nick = new JLabel(); nick.setText(nick_usuario); JLabel texto = new JLabel("Online: "); ip = new JComboBox(); campochat = new JTextArea(12,20); campo1 = new JTextField(20); miboton = new JButton("Enviar"); EnviaTexto mievento = new EnviaTexto(); miboton.addActionListener(mievento); //agregan los componentes a la lamina add(nick); add(texto); add(ip); add(campochat); add(campo1); add(miboton); //instancia del hilo Thread mihilo = new Thread(this); mihilo.start();//comienza la ejecución del hilo } @Override public void run() { try{ ServerSocket servidor_cliente = new ServerSocket(9090); Socket cliente; //crea instancia para construir el objeto serializar PaqueteEnvio paqueteRecibido; while(true){ cliente = servidor_cliente.accept(); //crea un flujo paquete de entrada ObjectInputStream flujoentrada = new ObjectInputStream (cliente.getInputStream()); paqueteRecibido = (PaqueteEnvio) flujoentrada.readObject(); if(!paqueteRecibido.getMensaje().equals(" online")){ campochat.append("\n" + paqueteRecibido.getNick() + ": " + paqueteRecibido.getMensaje()); }else{ // ArrayList <String> IpsMenu = new ArrayList <String>(); IpsMenu=paqueteRecibido.getIps(); ip.removeAllItems(); for(String z:IpsMenu){ ip.addItem(z); } } } }catch(Exception e){ System.out.println(e.getMessage()); } } //clase que implementa la accion del boton enviar private class EnviaTexto implements ActionListener { @Override public void actionPerformed(ActionEvent ae) { //agrega a campochat lo que se ha escrito en el campo de texto campochat.append("\n " + campo1.getText()); try { //instancia del socket a la que le asignamos la ip del servidor //y un puerto Socket misocket = new Socket("192.168.56.1",9999); //instancia del la clase paqueteEnvio para empaquetar los daros //poder enviar y recibir PaqueteEnvio datos = new PaqueteEnvio(); //pasamos lo que hay escrito en TextField get y lo almacenamos //para el nick, ip y campo1 datos.setNick(nick.getText()); datos.setIp(ip.getSelectedItem().toString()); datos.setMensaje(campo1.getText()); //instancia ObjectOutputStream para crear un flujo de datos de //salida del texto en paquete_Datos y enviarlo pro la red ObjectOutputStream paquete_datos = new ObjectOutputStream (misocket.getOutputStream()); paquete_datos.writeObject(datos);//indica que escriba en el //flujo de datos } catch (IOException ex) { System.out.println(ex.getMessage());//mensaje que lanza la //excepcion si no conecta } } } //creamos los componentes necesarios para la interfaz del usuario private JTextField campo1; private JComboBox ip; private JLabel nick; private JButton miboton; private JTextArea campochat; } class PaqueteEnvio implements Serializable {//implementamos la serialización para //que todas las instancias se conviertan en bits y mandarlas vía internet // enviar los datos necesarios private String nick, ip, mensaje; private ArrayList<String> Ips; //ArrayList que almacenara las ips public ArrayList<String> getIps(){ return Ips; } //se generan los setters y getters correpondientes para guardar y obtener datos public void setIps(ArrayList<String> ips){ this.Ips = ips; } public String getNick() { return nick; } public void setNick(String nick) { this.nick = nick; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getMensaje() { return mensaje; } public void setMensaje(String mensaje) { this.mensaje = mensaje; } }
34.06383
84
0.564179
18f413e4503eb708baddc81fb6ca347037f85ea4
2,994
package com.thedazzler.droidicon.util; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.content.Context; import android.content.res.Resources.NotFoundException; import android.graphics.Typeface; import android.util.Log; import com.thedazzler.droidicon.R; /** * Helper class that wraps icon fonts and manages {@link Typeface} loading. */ public class TypefaceManager { private static final String TAG = "TypefaceManager"; private TypefaceManager() { } public enum IconicTypeface { ENTYPO(R.raw.entypo), ENTYPO_SOCIAL(R.raw.entypo_social), FONT_AWESOME(R.raw.fontawesome_webfont), ICONIC(R.raw.iconic), GOOGLE_MATERIAL_DESIGN(R.raw.google_material_design), METEOCON(R.raw.meteocons); private final int mTypefaceResourceId; private Typeface mTypeface; private IconicTypeface(int typefaceResourceId) { mTypefaceResourceId = typefaceResourceId; } /** * Loads a {@link Typeface} for the given icon font. * {@link Typeface} is loaded only once to avoid memory consumption. * * @param context * @return {@link Typeface} */ public Typeface getTypeface(final Context context) { if (mTypeface == null) { mTypeface = createTypefaceFromResource(context, mTypefaceResourceId); } return mTypeface; } } private static Typeface createTypefaceFromResource(final Context context, final int resource) { Typeface typeface = null; InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = context.getResources().openRawResource(resource); } catch (NotFoundException ex) { Log.e(TAG, "Could not find typeface in resources.", ex); } String outPath = context.getCacheDir() + "/tmp.raw"; try { byte[] buffer = new byte[inputStream.available()]; outputStream = new BufferedOutputStream(new FileOutputStream(outPath)); int l = 0; while ((l = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, l); } typeface = Typeface.createFromFile(outPath); new File(outPath).delete(); } catch (IOException ex) { Log.e(TAG, "Error reading typeface from resource.", ex); } finally { try { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } catch (IOException ex) { Log.e(TAG, "Error closing typeface streams.", ex); } } return typeface; } }
29.352941
99
0.599866
92a51c89ba1ebca24f462193dd4791f042aaad0c
7,807
package it.polimi.dima.mediatracker.dialogs; import android.app.AlertDialog; import android.app.Dialog; import android.graphics.drawable.GradientDrawable; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import java.util.ArrayList; import java.util.List; import it.polimi.dima.mediatracker.R; /** * Dialog that allows to pick a color among several options */ public class ColorPickerDialog extends DialogFragment { private final static String TITLE_PARAMETER = "TITLE_PARAMETER"; private final static String OPTIONS_PARAMETER = "OPTIONS_PARAMETER"; private final static String SELECTED_OPTION_PARAMETER = "SELECTED_OPTION_PARAMETER"; private final static String COLUMN_NUMBER_PARAMETER = "COLUMN_NUMBER_PARAMETER"; private ColorPickerGridAdapter colorGridAdapter; private ColorPickerListener listener; private int[] colorChoices; private int columnNumber; private int selectedColor = 0; private int title; /** * Allows to create a new instance of the dialog * @param title the dialog title * @param colors the dialog options * @param selectedColor the first selected option * @param columnNumber the number of columns in which the options are placed * @return the dialog instance */ public static ColorPickerDialog newInstance(int title, int[] colors, int selectedColor, int columnNumber) { ColorPickerDialog colorPicker = new ColorPickerDialog(); Bundle args = new Bundle(); args.putInt(TITLE_PARAMETER, title); args.putIntArray(OPTIONS_PARAMETER, colors); args.putInt(SELECTED_OPTION_PARAMETER, selectedColor); args.putInt(COLUMN_NUMBER_PARAMETER, columnNumber); colorPicker.setArguments(args); return colorPicker; } /** * {@inheritDoc} */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Parameters Bundle args = getArguments(); title = args.getInt(TITLE_PARAMETER, 0); colorChoices = args.getIntArray(OPTIONS_PARAMETER); if(selectedColor==0) selectedColor = args.getInt(SELECTED_OPTION_PARAMETER, 0); columnNumber = args.getInt(COLUMN_NUMBER_PARAMETER, 0); } /** * {@inheritDoc} */ @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Set layout (pass null as the parent view because its going in the dialog layout) LayoutInflater layoutInflater = LayoutInflater.from(getActivity()); View dialogView = layoutInflater.inflate(R.layout.dialog_color_picker_grid, null); // Setup grid GridView colorGrid = (GridView) dialogView.findViewById(R.id.color_picker_grid); colorGrid.setNumColumns(columnNumber); // Add click listener on the grid elements colorGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> listView, View view, int position, long itemId) { colorGridAdapter.setSelectedColor(colorGridAdapter.getItem(position)); if (listener != null) listener.onColorSelected(colorGridAdapter.getItem(position)); dismiss(); } }); // Setup adapter if(isAdded() && colorGridAdapter==null) { colorGridAdapter = new ColorPickerGridAdapter(); } if(colorGridAdapter!=null) { colorGridAdapter.setSelectedColor(selectedColor); colorGrid.setAdapter(colorGridAdapter); } // Create dialog AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); return builder .setView(dialogView) .setTitle(title) .create(); } /** * Setter * @param listener the listener for the color picker */ public void setColorPickerListener(ColorPickerListener listener) { this.listener = listener; } /** * Setter * @param selectedColor the new selected color resource ID */ public void setSelectedColor(int selectedColor) { this.selectedColor = selectedColor; } /** * Getter * @return the selected color resource ID */ public int getSelectedColor() { Log.v("XXXXX", "----------gsc="+selectedColor); return selectedColor; } /** * Getter * @return true if the dialog is currently shown */ public boolean isShowing() { return this.getDialog()!=null; } /** * Listener for color selected in color picker */ public interface ColorPickerListener { /** * Called when the user selects a color in the color picker * @param color the selected color */ void onColorSelected(int color); } /** * The adapter of the color picker */ private class ColorPickerGridAdapter extends BaseAdapter { private List<Integer> colors = new ArrayList<>(); /** * Constructor */ private ColorPickerGridAdapter() { for(int color: colorChoices) { colors.add(color); } } /** * {@inheritDoc} */ @Override public int getCount() { return colors.size(); } /** * {@inheritDoc} */ @Override public Integer getItem(int position) { return colors.get(position); } /** * {@inheritDoc} */ @Override public long getItemId(int position) { return getItem(position); } /** * {@inheritDoc} */ @Override public View getView(int position, View convertView, ViewGroup container) { // Create the view if necessary if(convertView==null) { convertView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_color_picker_item, container, false); } // Get color at this position int color = getItem(position); // Get UI elements ImageView colorItem = (ImageView) convertView.findViewById(R.id.color_picker_item); ImageView colorSelectedIcon = (ImageView) convertView.findViewById(R.id.color_picker_selected_icon); // Set option background GradientDrawable colorItemBackground = (GradientDrawable) colorItem.getBackground(); colorItemBackground.setColor(ContextCompat.getColor(getActivity(), color)); // Set the selected icon if necessary if(color==selectedColor) colorSelectedIcon.setImageResource(R.drawable.ic_completed); else colorSelectedIcon.setImageDrawable(null); return convertView; } /** * Setter * @param selectedColor the currently selected color */ public void setSelectedColor(int selectedColor) { if(ColorPickerDialog.this.selectedColor!=selectedColor) { ColorPickerDialog.this.selectedColor = selectedColor; notifyDataSetChanged(); } } } }
29.684411
126
0.626489
5ddc9546c1bda34db0e8818d347a37228c9216e0
2,039
package com.bookstore.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.Timestamp; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.bookstore.*; import com.bookstore.dao.UserDao; import com.bookstore.entity.*; import com.bookstore.db.*; /** * Servlet implementation class RegisterServlet */ @MultipartConfig public class RegisterServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public RegisterServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out= response.getWriter(); response.setContentType("text/html"); String first_name=request.getParameter("fname"); String address=request.getParameter("address"); String email=request.getParameter("uemail"); String uname=request.getParameter("name"); String pass=request.getParameter("upass"); // user object save all data to user object User user=new User(first_name, address, email, uname, pass); // user dao object UserDao dao=new UserDao(jdbcconnection.getConnection()); if(dao.saveUser(user)) { out.println("Register"); response.sendRedirect("Login.jsp"); } else { out.println("Registratin failed!!"); } } }
27.186667
120
0.710152
c96b11d8a42e6b340d34f0206f2b501ce309c20e
307
package com.example; import javax.annotation.Generated; @Generated("org.realityforge.webtack") public final class IncomingEventTestCompile { static IncomingEvent $typeReference$; public static void onInvoke(final IncomingEvent $instance, final MyEvent event) { $instance.onInvoke( event ); } }
23.615385
83
0.775244
9cc90cd261d8e60b162067d89efc863b750790ef
3,243
// Copyright (C) 2017 polybellum // Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> package polybellum.http; /** * A class representing a generic Response from a source with a response code integer and * a byte array data value * * @author Nic Wilson (mtear) * */ public class Response { /*__/////////////////////////////////////////////////////////////////////////////////////////////// ____/////////////////////////////// MEMBER VARIABLES ////////////////////////////////////////////// ____/////////////////////////////////////////////////////////////////////////////////////////////*/ /** * A number representing a response code for this Response */ private int _response; /** * A byte array of data for this Response */ private byte[] _data = null; /*__/////////////////////////////////////////////////////////////////////////////////////////////// ____////////////////////////////// PROTECTED METHODS ////////////////////////////////////////////// ____/////////////////////////////////////////////////////////////////////////////////////////////*/ /** * Set the data byte array for this Response * * @param data The byte array to set as data for this Response */ protected void setDataByteArray(byte[] data){ _data = data; } /** * Set the integer response code for this Response * @param response The new Response code */ protected void setResponse(int response){ _response = response; } /*__/////////////////////////////////////////////////////////////////////////////////////////////// ____/////////////////////////////// PUBLIC METHODS //////////////////////////////////////////////// ____/////////////////////////////////////////////////////////////////////////////////////////////*/ /** * Getter for the data byte array * @return The data byte array set for this Response */ public byte[] getDataByteArray(){ return _data; } /** * Get the data byte array for this Response as a generic String * @return A generic String made from the data byte array */ public String getDataString(){ if(_data == null) return ""; return new String(getDataByteArray()); } /** * Get the String representation of the data byte array using the specified encoding * @param encoding The String encoding to use to encode the data byte array * @return The data byte array encoded using the specified encoding */ public String getDataString(String encoding){ try{ //Get a plain text (ISO) array of bytes from the data byte ptext[] = new String(getDataByteArray()).getBytes("ISO_8859_1"); //Encode the bytes with the given encoding String value = new String(ptext, encoding); return value; }catch(Exception e){ //Return the original bytes as a generic String on error return getDataString(); } } /** * Get the integer response code from this Response * @return The integer response code from this Response */ public int getResponse(){ return _response; } /** * Whether or not the Request that generated this Response had an Exception * @return If this object is an instance of ExceptionResponse */ public boolean hadException(){ return this instanceof ExceptionResponse; } }
30.59434
99
0.526981
65c71b80774b238401fbd188ea718552b0b1e6be
944
package com.tinkerpop.gremlin.test.sideeffect; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.pipes.Pipe; import com.tinkerpop.pipes.util.structures.Tree; import junit.framework.TestCase; import java.util.Map; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class TreeStepTest extends TestCase { public void testCompliance() { assertTrue(true); } public void test_g_v1_out_out_treeXnameX_cap(final Pipe<Vertex, Tree> pipe) { Map map = pipe.next(); assertFalse(pipe.hasNext()); assertEquals(map.size(), 1); assertTrue(map.containsKey("marko")); assertEquals(((Map) map.get("marko")).size(), 1); assertTrue(((Map) map.get("marko")).containsKey("josh")); assertTrue(((Map) ((Map) map.get("marko")).get("josh")).containsKey("lop")); assertTrue(((Map) ((Map) map.get("marko")).get("josh")).containsKey("ripple")); } }
32.551724
87
0.661017
204de94c0fe199c474b9c3e7cb60cb9d83880bbb
3,129
public Query(String query) throws QuerySyntaxError { int groupSpecial = 1; int groupContent = 2; Pattern commentPattern = Pattern.compile("^" + any(SPACE) + literal("#") + optional(group(literal("!"))) + group(any(".")) + "$", Pattern.MULTILINE); Matcher matcher = commentPattern.matcher(query); groupOperations = new ArrayList<Grouping>(); int level = 0; StringBuilder buffer = new StringBuilder(); int idx = 0; while (matcher.find(idx)) { buffer.append(query.substring(idx, matcher.start())); if (matcher.group(groupSpecial) != null) { String commandLine = matcher.group(groupContent); int groupGroup = 1; int headingGroup = 2; int hideGroup = 3; Pattern commandPattern = Pattern.compile("^" + any(SPACE) + choice(group(literal("group")), group(literal("heading")), group(literal("hide"))) + literal(":") + any(SPACE)); Matcher commandMatcher = commandPattern.matcher(commandLine); if (!commandMatcher.lookingAt()) { throw new QuerySyntaxError("Invalid command line: Expected command in '" + commandLine + "'"); } String commandArg = commandLine.substring(commandMatcher.end()); if (commandMatcher.group(groupGroup) != null) { String[] columns = commandArg.split(any(SPACE) + literal(",") + any(SPACE)); groupOperations.add(new Group(columns)); } else if (commandMatcher.group(hideGroup) != null) { String[] columns = commandArg.split(any(SPACE) + literal(",") + any(SPACE)); for (String column : columns) { hiddenColumns.add(column); } } else if (commandMatcher.group(headingGroup) != null) { int varGroup = 1; Pattern varPattern = Pattern.compile(literal("${") + group(many(notIn("}"))) + literal("}")); List<String> columns = new ArrayList<String>(); Matcher varMatcher = varPattern.matcher(commandArg); int varIdx = 0; while (varMatcher.find(varIdx)) { String varName = varMatcher.group(varGroup); columns.add(varName); varIdx = varMatcher.end(); } int columnCount = columns.size(); if (columnCount == 0) { throw new QuerySyntaxError("Invalid heading command: Missing variable reference in heading command."); } groupOperations.add(new Heading(columns.toArray(new String[columnCount]), level++, commandArg)); } else { throw new AssertionError("Unreachable."); } } idx = matcher.end(); } buffer.append(query.substring(idx, query.length())); sql = buffer.toString(); }
55.875
188
0.525727
66a1a1a960fd26224acc64444c645d7df1cebd0e
1,698
package br.dev.simon.booksapi.domain; import java.sql.Date; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.validation.constraints.NotEmpty; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; @Entity public class Author { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotEmpty(message = "Nome não pode ser vazio.") // Validação. @JsonInclude(Include.NON_NULL) // Só mostra no JSON se não for NULL. private String nome; @JsonInclude(Include.NON_NULL) @JsonFormat(pattern = "dd/MM/yyyy") private Date nascimento; @JsonInclude(Include.NON_NULL) private String nacionalidade; @JsonIgnore @OneToMany(mappedBy = "autor") // Um autor tem vários livros. private List<Book> books; public Author() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Date getNascimento() { return nascimento; } public void setNascimento(Date nascimento) { this.nascimento = nascimento; } public String getNacionalidade() { return nacionalidade; } public void setNacionalidade(String nacionalidade) { this.nacionalidade = nacionalidade; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } }
20.214286
69
0.750294
5a3556736c91c8a91aed283aadde11b3c30d14f8
14,506
/* * Copyright (C) 2014 Fastboot Mobile, LLC. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; * if not, see <http://www.gnu.org/licenses>. */ package com.fastbootmobile.encore.app.fragments; import android.app.Activity; import android.app.ActivityOptions; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v7.graphics.Palette; import android.util.Log; import android.util.Pair; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ExpandableListView; import android.widget.ImageView; import android.widget.ProgressBar; import com.fastbootmobile.encore.app.AlbumActivity; import com.fastbootmobile.encore.app.ArtistActivity; import com.fastbootmobile.encore.app.PlaylistActivity; import com.fastbootmobile.encore.app.R; import com.fastbootmobile.encore.app.adapters.SearchAdapter; import com.fastbootmobile.encore.app.ui.MaterialTransitionDrawable; import com.fastbootmobile.encore.framework.PlaybackProxy; import com.fastbootmobile.encore.model.Album; import com.fastbootmobile.encore.model.Artist; import com.fastbootmobile.encore.model.Playlist; import com.fastbootmobile.encore.model.SearchResult; import com.fastbootmobile.encore.model.Song; import com.fastbootmobile.encore.providers.ILocalCallback; import com.fastbootmobile.encore.providers.IMusicProvider; import com.fastbootmobile.encore.providers.ProviderAggregator; import com.fastbootmobile.encore.utils.Utils; import java.lang.ref.WeakReference; import java.util.List; /** * Fragment displaying search results */ public class SearchFragment extends Fragment implements ILocalCallback { private static final String TAG = "SearchFragment"; private static final int MSG_UPDATE_RESULTS = 1; private static final int MSG_DATASET_CHANGED = 2; public static final String KEY_SPECIAL_MORE = "__encore_plus"; private SearchAdapter mAdapter; private Handler mHandler; private List<SearchResult> mSearchResults; private String mQuery; private ProgressBar mLoadingBar; private int mNumProvidersResponse; private static class SearchHandler extends Handler { private WeakReference<SearchFragment> mParent; public SearchHandler(WeakReference<SearchFragment> parent) { mParent = parent; } @Override public void handleMessage(Message msg) { if (msg.what == MSG_UPDATE_RESULTS) { mParent.get().updateSearchResults(); } else if (msg.what == MSG_DATASET_CHANGED) { mParent.get().mAdapter.notifyDataSetChanged(); } } } /** * Default constructor */ public SearchFragment() { mHandler = new SearchHandler(new WeakReference<>(this)); setRetainInstance(true); } public void setArguments(String query) { mQuery = query; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View root = inflater.inflate(R.layout.fragment_search, container, false); assert root != null; mLoadingBar = (ProgressBar) root.findViewById(R.id.pbLoading); mAdapter = new SearchAdapter(); ExpandableListView listView = (ExpandableListView) root.findViewById(R.id.expandablelv_search); listView.setAdapter(mAdapter); listView.setGroupIndicator(null); for (int i = 0; i < 4; i++) { listView.expandGroup(i, false); } listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i2, long l) { if (mSearchResults != null) { switch (i) { case SearchAdapter.ARTIST: onArtistClick(i2, view); break; case SearchAdapter.ALBUM: onAlbumClick(i2, view); break; case SearchAdapter.SONG: onSongClick(i2); break; case SearchAdapter.PLAYLIST: onPlaylistClick(i2, view); break; default: Log.e(TAG, "Unknown child group id " + i); break; } return true; } else { return false; } } }); // Restore previous search results, in case we're rotating if (mSearchResults != null) { mAdapter.appendResults(mSearchResults); mAdapter.notifyDataSetChanged(); } return root; } @Override public void onAttach(Activity activity) { super.onAttach(activity); ProviderAggregator.getDefault().addUpdateCallback(this); } @Override public void onDetach() { super.onDetach(); ProviderAggregator.getDefault().removeUpdateCallback(this); } public void resetResults() { if (mAdapter != null) { mAdapter.clear(); } } private void onSongClick(int i) { SearchAdapter.SearchEntry entry = mAdapter.getChild(SearchAdapter.SONG, i); if (entry.ref.equals(KEY_SPECIAL_MORE)) { mAdapter.setGroupMaxCount(SearchAdapter.SONG, mAdapter.getGroupMaxCount(SearchAdapter.SONG) + 5); } else { final ProviderAggregator aggregator = ProviderAggregator.getDefault(); Song song = aggregator.retrieveSong(entry.ref, entry.identifier); if (song != null) { PlaybackProxy.playSong(song); } } } private void onAlbumClick(int i, View v) { if (mAdapter.getChildrenCount(SearchAdapter.ALBUM) > 1) { SearchAdapter.SearchEntry entry = mAdapter.getChild(SearchAdapter.ALBUM, i); if (entry.ref.equals(KEY_SPECIAL_MORE)) { mAdapter.setGroupMaxCount(SearchAdapter.ALBUM, mAdapter.getGroupMaxCount(SearchAdapter.ALBUM) + 5); } else { SearchAdapter.ViewHolder holder = (SearchAdapter.ViewHolder) v.getTag(); Bitmap hero = ((MaterialTransitionDrawable) holder.albumArtImageView.getDrawable()).getFinalDrawable().getBitmap(); int color = 0xffffff; if (hero != null) { Palette palette = Palette.generate(hero); Palette.Swatch darkVibrantColor = palette.getDarkVibrantSwatch(); Palette.Swatch darkMutedColor = palette.getDarkMutedSwatch(); if (darkVibrantColor != null) { color = darkVibrantColor.getRgb(); } else if (darkMutedColor != null) { color = darkMutedColor.getRgb(); } else { color = getResources().getColor(R.color.default_album_art_background); } } Intent intent = AlbumActivity.craftIntent(getActivity(), hero, entry.ref, entry.identifier, color); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { ImageView ivCover = holder.albumArtImageView; ActivityOptions opt = ActivityOptions.makeSceneTransitionAnimation(getActivity(), new Pair<View, String>(ivCover, "itemImage")); getActivity().startActivity(intent, opt.toBundle()); } else { startActivity(intent); } } } } private void onArtistClick(int i, View v) { if (mAdapter.getChildrenCount(SearchAdapter.ARTIST) > 1) { SearchAdapter.SearchEntry entry = mAdapter.getChild(SearchAdapter.ARTIST, i); if (entry.ref.equals(KEY_SPECIAL_MORE)) { mAdapter.setGroupMaxCount(SearchAdapter.ARTIST, mAdapter.getGroupMaxCount(SearchAdapter.ARTIST) + 5); } else { SearchAdapter.ViewHolder holder = (SearchAdapter.ViewHolder) v.getTag(); ImageView ivCover = holder.albumArtImageView; Bitmap hero = ((MaterialTransitionDrawable) ivCover.getDrawable()).getFinalDrawable().getBitmap(); int color = 0xffffff; if (hero != null) { Palette palette = Palette.generate(hero); Palette.Swatch darkVibrantColor = palette.getDarkVibrantSwatch(); Palette.Swatch darkMutedColor = palette.getDarkMutedSwatch(); if (darkVibrantColor != null) { color = darkVibrantColor.getRgb(); } else if (darkMutedColor != null) { color = darkMutedColor.getRgb(); } else { color = getResources().getColor(R.color.default_album_art_background); } } Intent intent = new Intent(getActivity(), ArtistActivity.class); intent.putExtra(ArtistActivity.EXTRA_ARTIST, entry.ref); intent.putExtra(ArtistActivity.EXTRA_BACKGROUND_COLOR, color); Utils.queueBitmap(ArtistActivity.BITMAP_ARTIST_HERO, hero); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { ActivityOptions opt = ActivityOptions.makeSceneTransitionAnimation(getActivity(), ivCover, "itemImage"); getActivity().startActivity(intent, opt.toBundle()); } else { startActivity(intent); } } } } private void onPlaylistClick(int i, View v) { if (mAdapter.getChildrenCount(SearchAdapter.PLAYLIST) > 1) { final ProviderAggregator aggregator = ProviderAggregator.getDefault(); final SearchAdapter.SearchEntry entry = mAdapter.getChild(SearchAdapter.PLAYLIST, i); if (entry.ref.equals(KEY_SPECIAL_MORE)) { mAdapter.setGroupMaxCount(SearchAdapter.PLAYLIST, mAdapter.getGroupMaxCount(SearchAdapter.PLAYLIST) + 5); } else { Playlist playlist = aggregator.retrievePlaylist(entry.ref, entry.identifier); if (playlist != null) { Intent intent = PlaylistActivity.craftIntent(getActivity(), playlist, ((BitmapDrawable) getResources().getDrawable(R.drawable.album_placeholder)).getBitmap()); startActivity(intent); } } } } @Override public void onSongUpdate(List<Song> s) { if (mAdapter == null) { return; } for (Song song : s) { if (mAdapter.contains(song)) { mHandler.removeMessages(MSG_DATASET_CHANGED); mHandler.sendEmptyMessage(MSG_DATASET_CHANGED); return; } } } @Override public void onAlbumUpdate(List<Album> a) { if (mAdapter == null) { return; } for (Album album : a) { if (mAdapter.contains(album)) { mHandler.removeMessages(MSG_DATASET_CHANGED); mHandler.sendEmptyMessage(MSG_DATASET_CHANGED); return; } } } @Override public void onPlaylistUpdate(List<Playlist> p) { if (mAdapter == null) { return; } for (Playlist playlist : p) { if (mAdapter.contains(playlist)) { mHandler.removeMessages(MSG_DATASET_CHANGED); mHandler.sendEmptyMessage(MSG_DATASET_CHANGED); return; } } } @Override public void onPlaylistRemoved(String ref) { } @Override public void onArtistUpdate(List<Artist> a) { if (mAdapter == null) { return; } for (Artist artist : a) { if (mAdapter.contains(artist)) { mHandler.removeMessages(MSG_DATASET_CHANGED); mHandler.sendEmptyMessage(MSG_DATASET_CHANGED); return; } } } @Override public void onProviderConnected(IMusicProvider provider) { } @Override public void onSearchResult(final List<SearchResult> searchResults) { for (SearchResult searchResult : searchResults) { if (searchResult.getQuery().equals(mQuery)) { mSearchResults = searchResults; mHandler.sendEmptyMessage(MSG_UPDATE_RESULTS); mNumProvidersResponse++; break; } } } private void updateSearchResults() { final Activity act = getActivity(); if (act != null) { getActivity().setTitle("'" + mSearchResults.get(0).getQuery() + "'"); getActivity().setProgressBarIndeterminateVisibility(false); if (mNumProvidersResponse >= 2) { mLoadingBar.setVisibility(View.GONE); } } else { mHandler.sendEmptyMessage(MSG_UPDATE_RESULTS); } if (mAdapter != null) { mAdapter.appendResults(mSearchResults); mAdapter.notifyDataSetChanged(); } } }
36.447236
131
0.595891
471c20fd8c76b5e0ae93a174eb8b30c7142a637e
695
package org.hyperdex.client; import java.util.*; public class LessEqual extends Predicate { public LessEqual(Object upper) throws AttributeError { if ( ! Client.isBytes(upper) && ! (upper instanceof Long) && ! (upper instanceof Double) ) { throw new AttributeError("LessEqual must be a byte[], ByteArray, String, Long, or Double"); } List<Map.Entry<hyperpredicate,Object>> raw = new Vector<Map.Entry<hyperpredicate,Object>>(1); raw.add(new AbstractMap.SimpleEntry<hyperpredicate,Object>( hyperpredicate.HYPERPREDICATE_LESS_EQUAL,upper)); this.raw = raw; } }
26.730769
103
0.614388
0328411d39b97ebd5750fd5ec90dd94682a5e9c1
1,903
package li.cil.tis3d.api; /** * API entry point for access to the tiny font renderer used on execution * modules, for example. * <p> * Keep in mind that the list of printable characters is very small for this * font renderer, due to the small number of characters in the font sheet. */ public final class FontRendererAPI { /** * Render the specified string. * * @param string the string to render. */ public static void drawString(final String string) { if (API.fontRendererAPI != null) API.fontRendererAPI.drawString(string); } /** * Render up to the specified amount of characters of the specified string. * <p> * This is intended as a convenience method for clamped-width rendering, * avoiding additional string operations such as <tt>substring</tt>. * * @param string the string to render. * @param maxChars the maximum number of characters to render. */ public static void drawString(final String string, final int maxChars) { if (API.fontRendererAPI != null) API.fontRendererAPI.drawString(string, maxChars); } /** * Get the width of the characters drawn with the font renderer, in pixels. * * @return the width of the drawn characters. */ public static int getCharWidth() { if (API.fontRendererAPI != null) return API.fontRendererAPI.getCharWidth(); return 0; } /** * Get the height of the characters drawn with the font renderer, in pixels. * * @return the height of the drawn characters. */ public static int getCharHeight() { if (API.fontRendererAPI != null) return API.fontRendererAPI.getCharHeight(); return 0; } // --------------------------------------------------------------------- // private FontRendererAPI() { } }
30.693548
80
0.614293
cdc710b05ac8f65db8352e483d0a5bcc55a6e511
356
package com.controller.hello; /** * @program: spring * @description: TODO * @author: yangyang.liu01@weimob.com * @date: 2021/4/25 18:41 */ public class HelloWorld { public void sayHello(){ System.out.println("Hello World!"); } public static void main(String[] args) { HelloWorld helloWorld = new HelloWorld(); helloWorld.sayHello(); } }
16.952381
43
0.679775
fa481e0b7d368766697bfc755b2d237b965e7c5d
223
package com.dong.design.mediator; public class List extends Component { @Override public void update() { System.out.println("新添加一个条目"); } public void select(){ System.out.println("列表选中张无忌"); } }
14.866667
38
0.650224
7a5bda9bea26d300356dd8e5f87fd496ae519319
564
import java.util.*; public class u11369_shopaholic { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int caseT = sc.nextInt(); for(int cIdx=0; cIdx < caseT; cIdx++) { int N = sc.nextInt(); int[] val = new int[N]; for(int i=0; i<N; i++) val[i] = sc.nextInt(); Arrays.sort(val); long disc = 0; for(int i=val.length-3; i>=0; i-=3) disc += val[i]; // System.out.println(Arrays.toString(val)); System.out.println(disc); } } }
21.692308
55
0.569149
3349ef386fcb6505b9c5fde000a84947f1533510
349
package cellsociety.exceptions; /** * Exception thrown when a user requests an invalid cell * @author Alex Xu */ public class InvalidCellException extends RuntimeException { public InvalidCellException(Throwable cause) { super(cause); } public InvalidCellException(Throwable cause, String message) { super(message, cause); } }
20.529412
64
0.74212
a57289d8cc257c74308766e97706464002638868
1,775
package com.ggj.java.teach; import java.util.Scanner; /** * @author:gaoguangjin * @date:2018/4/2 */ public class BasicType { private static boolean boolFlag; public static void main(String[] args) { new BasicType().tests(); //byte 等于8 bit bit为二进制的单位 byte maxByte=Byte.MAX_VALUE; byte minByte=Byte.MIN_VALUE; int maxInt=2147483647+1; System.out.println("maxInt = [" + maxInt + "]"); System.out.println("最大值:"+maxByte+";最小值"+minByte); //1 int=4 byte int a=Integer.MAX_VALUE; int b=Integer.MIN_VALUE; //int类型数据范围 System.out.println("最大值:"+a+";最小值"+b); long c=Long.MAX_VALUE; long d=Long.MIN_VALUE; //long类型数据范围 System.out.println("最大值:"+c+";最小值"+d); if(boolFlag){ } //类型转换 //低类型往高类型自动转换 int e=maxByte; //高类型往地类型转换需要强制,可能溢出或者丢失精度 int f= (int) c; System.out.println("long类型强制转换成int类型,溢出,原来是:"+c+";转换后是:"+f); //溢出 int g=a+a; System.out.println(g); float h=11.00f; //丢失精度 int i= (int) h; System.out.println("丢失精度:"+i); float j=a; System.out.println(""+j); //从低位类型到高位类型自动转换;从高位类型到低位类型需要强制类型转换: //算术运算 中的类型转换:1 基本就是先转换为高位数据类型,再参加运算,结果也是最高位的数据类型; System.out.println(h/2); System.out.println(16/2.0); char charA='a'; //char+char,char+int——类型均提升为int int charB=charA+charA; int charC=charA+2; int changeA=charA; char china='中'; System.out.println(china+0); System.out.println("args = [" + changeA + "]"); } private void tests() { System.out.println("test 全局变量"+boolFlag+";"); } }
23.355263
68
0.547606
61a1a2add420e1475a6fc9f26d7d5d1b64279479
396
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package at.rocworks.oa4j.logger.base; /** * * @author vogler */ public class CacheItem { public int threadNr = -1; public long timeMS = -1L; public int nanos = -1; public int addNanos = 0; }
22
79
0.679293
c206334bf3fde3eb11afddfe33145c4e5a24ce2a
25,665
package de.fearnixx.jeak.teamspeak; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PermissionSID { private static Map<String, PermissionSID> INSTANCES = new HashMap<>(); private static final Pattern PERMID_EXTR = Pattern.compile("^(?:i_|b_)(.+)$"); public static final PermissionSID ALLOW_QUERY_LOGIN = of("b_serverquery_login"); public static final PermissionSID ICON_ID = of("i_icon_id"); public static final PermissionSID MAX_ICON_SIZE = of("i_max_icon_filesize"); public static final PermissionSID PERMISSION_MODIFY_POWER = of("i_permission_modify_power"); public static final PermissionSID PERMISSION_MODIFY_POWER_IGNORE = of("b_permission_modify_power_ignore"); public static final PermissionSID CLIENT_PERMISSION_MODIFY_POWER = of("i_client_permission_modify_power"); public static final PermissionSID CLIENT_NEEDED_PERMISSION_MODIFY_POWER = of("i_client_needed_permission_modify_power"); public static final PermissionSID CLIENT_MAX_CLONES_PER_UID = of("i_client_max_clones_uid"); public static final PermissionSID CLIENT_MAX_IDLE_TIME = of("i_client_max_idletime"); public static final PermissionSID CLIENT_MAX_AVATAR_SIZE = of("i_client_max_avatar_filesize"); public static final PermissionSID CLIENT_MAX_CHANNEL_SUBSCRIPTIONS = of("i_client_max_channel_subscriptions"); public static final PermissionSID CLIENT_IS_PRIORITY_SPEAKER = of("b_client_is_priority_speaker"); public static final PermissionSID CLIENT_SKIP_CHANNELGROUP_PERMISSIONS = of("b_client_skip_channelgroup_permissions"); public static final PermissionSID CLIENT_FORCE_PUSH_TO_TALK = of("b_client_force_push_to_talk"); public static final PermissionSID CLIENT_IGNORE_BANS = of("b_client_ignore_bans"); public static final PermissionSID CLIENT_IGNORE_ANTIFLOOED = of("b_client_ignore_antiflood"); public static final PermissionSID CLIENT_ALLOW_CLIENT_QUERY_COMMANDS = of("b_client_issue_client_query_command"); public static final PermissionSID CLIENT_USE_RESERVED_SLOT = of("b_client_use_reserved_slot"); public static final PermissionSID CLIENT_USE_CHANNEL_COMMANDER = of("b_client_use_channel_commander"); public static final PermissionSID CLIENT_REQUEST_TALK_POWER = of("b_client_request_talker"); public static final PermissionSID CLIENT_AVATAR_DELETE_OTHER = of("b_client_avatar_delete_other"); public static final PermissionSID CLIENT_IS_STICKY = of("b_client_is_sticky"); public static final PermissionSID CLIENT_IGNORE_STICKY = of("b_client_ignore_sticky"); public static final PermissionSID CLIENT_INFO = of("b_client_info_view"); public static final PermissionSID CLIENT_VIEW_PERMISSION_OVERVIEW = of("b_client_permissionoverview_view"); public static final PermissionSID CLIENT_VIEW_PERMISSION_OVERVIEW_OWN = of("b_client_permissionoverview_own"); public static final PermissionSID CLIENT_VIEW_REMOTE_ADDRESSES = of("b_client_remoteaddress_view"); public static final PermissionSID CLIENT_VIEW_CUSTOMINFO = of("b_client_custom_info_view"); public static final PermissionSID CLIENT_KICK_SERVER_POWER = of("i_client_kick_from_server_power"); public static final PermissionSID CLIENT_NEEDED_KICK_SERVER_POWER = of("i_client_needed_kick_from_server_power"); public static final PermissionSID CLIENT_KICK_CHANNEL_POWER = of("i_client_kick_from_channel_power"); public static final PermissionSID CLIENT_NEEDED_KICK_CHANNEL_POWER = of("i_client_needed_kick_from_channel_power"); public static final PermissionSID CLIENT_BAN_POWER = of("i_client_ban_power"); public static final PermissionSID CLIENT_NEEDED_BAN_POWER = of("i_client_needed_ban_power"); public static final PermissionSID CLIENT_MOVE_POWER = of("i_client_move_power"); public static final PermissionSID CLIENT_NEEDED_MOVE_POWER = of("i_client_needed_move_power"); public static final PermissionSID CLIENT_COMPLAIN_POWER = of("i_client_complain_power"); public static final PermissionSID CLIENT_NEEDED_COMPLAIN_POWER = of("i_client_needed_complain_power"); public static final PermissionSID CLIENT_COMPLAIN_LIST = of("b_client_complain_list"); public static final PermissionSID CLIENT_COMPLAIN_DELETE_OWN = of("b_client_complain_delete_own"); public static final PermissionSID CLIENT_COMPLAIN_DELETE = of("b_client_complain_delete"); public static final PermissionSID CLIENT_BAN_LIST = of("b_client_ban_list"); public static final PermissionSID CLIENT_BAN = of("b_client_ban_create"); public static final PermissionSID CLIENT_BAN_DELETE_OWN = of("b_client_ban_delete_own"); public static final PermissionSID CLIENT_BAN_DELETE = of("b_client_ban_delete"); public static final PermissionSID CLIENT_BAN_MAX_TIME = of("i_client_ban_max_bantime"); public static final PermissionSID CLIENT_TEXTMESSAGE_PRIVATE_POWER = of("i_client_private_textmessage_power"); public static final PermissionSID CLIENT_NEEDED_TEXTMESSAGE_PRIVATE_POWER = of("i_client_needed_private_textmessage_power"); public static final PermissionSID CLIENT_TEXTMESSAGE_SERVER = of("b_client_server_textmessage_send"); public static final PermissionSID CLIENT_TEXTMESSAGE_CHANNEL = of("b_client_channel_textmessage_send"); public static final PermissionSID CLIENT_TEXTMESSAGE_OFFLINE = of("b_client_offline_textmessage_send"); public static final PermissionSID CLIENT_TALKPOWER = of("i_client_talk_power"); public static final PermissionSID CLIENT_NEEDED_TALKPOWER = of("i_client_needed_talk_power"); public static final PermissionSID CLIENT_POKE_POWER = of("i_client_poke_power"); public static final PermissionSID CLIENT_NEEDED_POKE_POWER = of("i_client_needed_poke_power"); public static final PermissionSID CLIENT_GRANT_TALKPOWER = of("b_client_set_flag_talker"); public static final PermissionSID CLIENT_WHISPER_POWER = of("i_client_whisper_power"); public static final PermissionSID CLIENT_NEEDED_WHISPER_POWER = of("i_client_needed_whisper_power"); public static final PermissionSID CLIENT_MODIFY_DESCRIPTION = of("b_client_modify_description"); public static final PermissionSID CLIENT_MODIFY_DESCRIPTION_OWN = of("b_client_modify_own_description"); public static final PermissionSID CLIENT_MODIFY_DBPROPS = of("b_client_modify_dbproperties"); public static final PermissionSID CLIENT_DELETE_DBPROPS = of("b_client_delete_dbproperties"); public static final PermissionSID CLIENT_CREATE_QUERY_LOGIN = of("b_client_create_modify_serverquery_login"); public static final PermissionSID GROUP_MODIFY_POWER = of("i_group_modify_power"); public static final PermissionSID GROUP_NEEDED_MODIFY_POWER = of("i_group_needed_modify_power"); public static final PermissionSID GROUP_MEMBER_ADD_POWER = of("i_group_member_add_power"); public static final PermissionSID GROUP_NEEDED_MEMBER_ADD_POWER = of("i_group_needed_member_add_power"); public static final PermissionSID GROUP_MEMBER_DEL_POWER = of("i_group_member_remove_power"); public static final PermissionSID GROUP_NEEDED_MEMBER_DEL_POWER = of("i_group_needed_member_remove_power"); public static final PermissionSID GROUP_IS_PERMANENT = of("b_group_is_permanent"); public static final PermissionSID GROUP_AUTO_UPDATE_TYPE = of("i_group_auto_update_type"); public static final PermissionSID GROUP_AUTO_UPDATE_MAX = of("i_group_auto_update_max_value"); public static final PermissionSID GROUP_SORT_ID = of("i_group_sort_id"); public static final PermissionSID GROUP_SHOW_IN_TREE = of("i_group_show_name_in_tree"); public static final PermissionSID FILETRANSFER_IGNORE_PASSWORD = of("b_ft_ignore_password"); public static final PermissionSID FILETRANSFER_LIST = of("b_ft_ignore_password"); public static final PermissionSID FILETRANSFER_UPLOAD_POWER = of("i_ft_file_upload_power"); public static final PermissionSID FILETRANSFER_NEEDED_UPLOAD_POWER = of("i_ft_needed_file_upload_power"); public static final PermissionSID FILETRANSFER_DOWNLOAD_POWER = of("i_ft_file_download_power"); public static final PermissionSID FILETRANSFER_NEEDED_DOWNLOAD_POWER = of("i_ft_needed_file_download_power"); public static final PermissionSID FILETRANSFER_DELETE_POWER = of("i_ft_file_delete_power"); public static final PermissionSID FILETRANSFER_NEEDED_DELETE_POWER = of("i_ft_needed_file_delete_power"); public static final PermissionSID FILETRANSFER_RENAME_POWER = of("i_ft_file_rename_power"); public static final PermissionSID FILETRANSFER_NEEDED_RENAME_POWER = of("i_ft_needed_file_rename_power"); public static final PermissionSID FILETRANSFER_BROWSE_POWER = of("i_ft_file_browse_power"); public static final PermissionSID FILETRANSFER_NEEDED_BROWSE_POWER = of("i_ft_needed_file_browse_power"); public static final PermissionSID FILETRANSFER_MKDIR_POWER = of("i_ft_directory_create_power"); public static final PermissionSID FILETRANSFER_NEEDED_MKDIR_POWER = of("i_ft_needed_directory_create_power"); public static final PermissionSID FILETRANSFER_CLIENT_DOWNLOAD_QUOTA = of("i_ft_quota_mb_download_per_client"); public static final PermissionSID FILETRANSFER_CLIENT_UPLOAD_QUOTA = of("i_ft_quota_mb_upload_per_client"); public static final PermissionSID SERVER_CREATE = of("b_virtualserver_create"); public static final PermissionSID SERVER_DELETE = of("b_virtualserver_delete"); public static final PermissionSID SERVER_START_ANY = of("b_virtualserver_start_any"); public static final PermissionSID SERVER_START_ONE = of("b_virtualserver_start"); public static final PermissionSID SERVER_STOP_ANY = of("b_virtualserver_stop_any"); public static final PermissionSID SERVER_STOP_ONE = of("b_virtualserver_stop"); public static final PermissionSID SERVER_CHANGE_MACHINE_ID = of("b_virtualserver_change_machine_id"); public static final PermissionSID SERVER_CHANGE_TEMPLATE = of("b_virtualserver_change_template"); public static final PermissionSID SERVER_SELECT = of("b_virtualserver_select"); public static final PermissionSID SERVER_INFO_VIEW = of("b_virtualserver_info_view"); public static final PermissionSID SERVER_CONNECTION_INFO = of("b_virtualserver_connectioninfo_view"); public static final PermissionSID SERVER_CHANNEL_LIST = of("b_virtualserver_channel_list"); public static final PermissionSID SERVER_CHANNEL_SEARCH = of("b_virtualserver_channel_search"); public static final PermissionSID SERVER_CLIENT_LIST = of("b_virtualserver_client_list"); public static final PermissionSID SERVER_CLIENT_SEARCH = of("b_virtualserver_client_search"); public static final PermissionSID SERVER_CLIENT_LIST_DB = of("b_virtualserver_client_dblist"); public static final PermissionSID SERVER_CLIENT_SEARCH_DB = of("b_virtualserver_client_dbsearch"); public static final PermissionSID SERVER_CLIENT_DB_INFO = of("b_virtualserver_client_dbinfo"); public static final PermissionSID SERVER_PERMISSION_FIND = of("b_virtualserver_permission_find"); public static final PermissionSID SERVER_CUSTOM_SEARCH = of("b_virtualserver_custom_search"); public static final PermissionSID SERVER_TOKEN_LIST = of("b_virtualserver_token_list"); public static final PermissionSID SERVER_TOKEN_ADD = of("b_virtualserver_token_add"); public static final PermissionSID SERVER_TOKEN_USE = of("b_virtualserver_token_use"); public static final PermissionSID SERVER_TOKEN_DELETE = of("b_virtualserver_token_delete"); public static final PermissionSID SERVER_LOG_VIEW = of("b_virtualserver_log_view"); public static final PermissionSID SERVER_LOG_ADD = of("b_virtualserver_log_add"); public static final PermissionSID SERVER_IGNORE_JOIN_PASSWORD = of("b_virtualserver_join_ignore_password"); public static final PermissionSID SERVER_NOTIFICATION_REGISTER = of("b_virtualserver_notify_register"); public static final PermissionSID SERVER_NOTIFICATION_UNREGISTER = of("b_virtualserver_notify_unregister"); public static final PermissionSID SERVER_SNAPSHOT_CREATE = of("b_virtualserver_snapshot_create"); public static final PermissionSID SERVER_SNAPSHOT_DEPLOY = of("b_virtualserver_snapshot_deploy"); public static final PermissionSID SERVER_RESET_PERMISSIONS = of("b_virtualserver_permission_reset"); public static final PermissionSID SERVER_MODIFY_NAME = of("b_virtualserver_modify_name"); public static final PermissionSID SERVER_MODIFY_WELCOME_MESSAGE = of("b_virtualserver_modify_welcomemessage"); public static final PermissionSID SERVER_MODIFY_MAX_CLIENTS = of("b_virtualserver_modify_maxclients"); public static final PermissionSID SERVER_MODIFY_RESERVED_SLOTS = of("b_virtualserver_modify_reserved_slots"); public static final PermissionSID SERVER_MODIFY_PASSWORD = of("b_virtualserver_modify_password"); public static final PermissionSID SERVER_MODIFY_DEFAULT_SERVERGROUP = of("b_virtualserver_modify_default_servergroup"); public static final PermissionSID SERVER_MODIFY_DEFAULT_CHANNELGROUP = of("b_virtualserver_modify_channelgroup"); public static final PermissionSID SERVER_MODIFY_DEFAULT_CHANNELADMINGROUP = of("b_virtualserver_modify_channeladmingroup"); public static final PermissionSID SERVER_MODIFY_FORCED_SILENCE = of("b_virtualserver_modify_channel_forced_silence"); public static final PermissionSID SERVER_MODIFY_COMPLAIN = of("b_virtualserver_modify_complain"); public static final PermissionSID SERVER_MODIFY_ANTIFLOOD = of("b_virtualserver_modify_antiflood"); public static final PermissionSID SERVER_MODIFY_FILETRANSFER_SETTINGS = of("b_virtualserver_modify_ft_settings"); public static final PermissionSID SERVER_MODIFY_FILETRANSFER_QUOTAS = of("b_virtualserver_modify_ft_quotas"); public static final PermissionSID SERVER_MODIFY_HOST_MESSAGE = of("b_virtualserver_modify_hostmessage"); public static final PermissionSID SERVER_MODIFY_HOST_BANNER = of("b_virtualserver_modify_hostbanner"); public static final PermissionSID SERVER_MODIFY_HOST_BUTTON = of("b_virtualserver_modify_hostbutton"); public static final PermissionSID SERVER_MODIFY_PORT = of("b_virtualserver_modify_port"); public static final PermissionSID SERVER_MODIFY_AUTOSTART = of("b_virtualserver_modify_autostart"); public static final PermissionSID SERVER_MODIFY_ID_SECURITY_LEVEL = of("b_virtualserver_modify_needed_identity_security_level"); public static final PermissionSID SERVER_MODIFY_PRIO_SPEAKER_DIMMING = of("b_virtualserver_modify_priority_speaker_dimm_modificator"); public static final PermissionSID SERVER_MODIFY_LOG_SETTINGS = of("b_virtualserver_modify_log_settings"); public static final PermissionSID SERVER_MODIFY_MIN_CLIENTVERSION = of("b_virtualserver_modify_min_client_version"); public static final PermissionSID SERVER_MODIFY_ICON_ID = of("b_virtualserver_modify_icon_id"); public static final PermissionSID SERVER_MODIFY_WEBLIST = of("b_virtualserver_modify_weblist"); public static final PermissionSID SERVER_MODIFY_CODEC_ENCRYPTION = of("b_virtualserver_modify_codec_encryption_mode"); public static final PermissionSID SERVER_MODIFY_TEMP_PASSWORDS = of("b_virtualserver_modify_temporary_passwords"); public static final PermissionSID SERVER_MODIFY_TEMP_PASSWORDS_OWN = of("b_virtualserver_modify_temporary_passwords_own"); public static final PermissionSID SERVER_LIST_SERVERGROUP = of("b_virtualserver_servergroup_list"); public static final PermissionSID SERVER_LIST_SERVERGROUP_PERMISSIONS = of("b_virtualserver_servergroup_permission_list"); public static final PermissionSID SERVER_LIST_SERVERGROUP_CLIENTS = of("b_virtualserver_servergroup_client_list"); public static final PermissionSID SERVER_LIST_CHANNELGROUP = of("b_virtualserver_channelgroup_list"); public static final PermissionSID SERVER_LIST_CHANNELGROUP_PERMISSIONS = of("b_virtualserver_channelgroup_permission_list"); public static final PermissionSID SERVER_LIST_CHANNELGROUP_CLIENTS = of("b_virtualserver_channelgroup_client_list"); public static final PermissionSID SERVER_LIST_CLIENT_PERMISSIONS = of("b_virtualserver_client_permission_list"); public static final PermissionSID SERVER_LIST_CHANNEL_PERMISSIONS = of("b_virtualserver_channel_permission_list"); public static final PermissionSID SERVER_LIST_CHANNEL_CLIENT_PERMISSIONS = of("b_virtualserver_channelclient_permission_list"); public static final PermissionSID SERVER_CREATE_SERVERGROUP = of("b_virtualserver_servergroup_create"); public static final PermissionSID SERVER_DELETE_SERVERGROUP = of("b_virtualserver_servergroup_delete"); public static final PermissionSID SERVER_CREATE_CHANNELGROUP = of("b_virtualserver_channelgroup_create"); public static final PermissionSID SERVER_DELETE_CHANNELGROUP = of("b_virtualserver_channelgroup_delete"); public static final PermissionSID INSTANCE_HELP = of("b_serverinstance_help_view"); public static final PermissionSID INSTANCE_VERSION = of("b_serverinstance_version_view"); public static final PermissionSID INSTANCE_INFO_VIEW = of("b_serverinstance_info_view"); public static final PermissionSID INSTANCE_LIST_VIRTUAL_SERVERS = of("b_serverinstance_virtualserver_list"); public static final PermissionSID INSTANCE_LIST_BINDINGS = of("b_serverinstance_binding_list"); public static final PermissionSID INSTANCE_LIST_PERMISSIONS = of("b_serverinstance_permission_list"); public static final PermissionSID INSTANCE_FIND_PERMISSION = of("b_serverinstance_permission_find"); public static final PermissionSID INSTANCE_SEND_GLOBAL_TEXTMESSAGE = of("b_serverinstance_textmessage_send"); public static final PermissionSID INSTANCE_LOG_VIEW = of("b_serverinstance_log_view"); public static final PermissionSID INSTANCE_LOG_ADD = of("b_serverinstance_log_add"); public static final PermissionSID INSTANCE_STOP = of("b_serverinstance_stop"); public static final PermissionSID INSTANCE_MODIFY_SETTINGS = of("b_serverinstance_modify_settings"); public static final PermissionSID INSTANCE_MODIFY_QUERY_GROUP = of("b_serverinstance_modify_querygroup"); public static final PermissionSID INSTANCE_MODIFY_TEMPLATES = of("b_serverinstance_modify_template"); public static final PermissionSID CHANNEL_MIN_DEPTH = of("i_channel_min_depth"); public static final PermissionSID CHANNEL_MAX_DEPTH = of("i_channel_max_depth"); public static final PermissionSID CHANNEL_PERMISSION_MODIFY_POWER = of("i_channel_permission_modify_power"); public static final PermissionSID CHANNEL_INFO_VIEW = of("b_channel_info_view"); public static final PermissionSID CHANNEL_CREATE_CHILD = of("b_channel_create_child"); public static final PermissionSID CHANNEL_CREATE_PERMANENT = of("b_channel_create_permanent"); public static final PermissionSID CHANNEL_CREATE_SEMI_PERMANENT = of("b_channel_create_semi_permanent"); public static final PermissionSID CHANNEL_CREATE_TEMPORARY = of("b_channel_create_temporary"); public static final PermissionSID CHANNEL_CREATE_WITH_TOPIC = of("b_channel_create_with_topic"); public static final PermissionSID CHANNEL_CREATE_WITH_DESCRIPTION = of("b_channel_create_with_description"); public static final PermissionSID CHANNEL_CREATE_WITH_PASSWORD = of("b_channel_create_with_password"); public static final PermissionSID CHANNEL_CREATE_CODEC_SPEEX8 = of("b_channel_create_modify_with_codec_speex8"); public static final PermissionSID CHANNEL_CREATE_CODEC_SPEEX16 = of("b_channel_create_modify_with_codec_speex16"); public static final PermissionSID CHANNEL_CREATE_CODEC_SPEEX32 = of("b_channel_create_modify_with_codec_speex32"); public static final PermissionSID CHANNEL_CREATE_CODEC_CELTMONO48 = of("b_channel_create_modify_with_codec_celtmono48"); public static final PermissionSID CHANNEL_CREATE_CODEC_CUSTOM_QUALITY = of("i_channel_create_modify_with_codec_maxquality"); public static final PermissionSID CHANNEL_CREATE_CODEC_CUSTOM_LATENCY = of("i_channel_create_modify_with_codec_latency_factor_min"); public static final PermissionSID CHANNEL_CREATE_WITH_MAXCLIENTS = of("b_channel_create_with_maxclients"); public static final PermissionSID CHANNEL_CREATE_WITH_MAXFAMILYCLIENTS = of("b_channel_create_with_maxfamilyclients"); public static final PermissionSID CHANNEL_CREATE_WITH_SORTORDER = of("b_channel_create_with_sortorder"); public static final PermissionSID CHANNEL_CREATE_WITH_DEFAULT = of("b_channel_create_with_default"); public static final PermissionSID CHANNEL_CREATE_WITH_TALKPOWER = of("b_channel_create_with_needed_talk_power"); public static final PermissionSID CHANNEL_CREATE_FORCE_PASSWORD = of("b_channel_create_modify_with_force_password"); public static final PermissionSID CHANNEL_MODIFY_PARENT = of("b_channel_modify_parent"); public static final PermissionSID CHANNEL_MODIFY_MAKE_DEFAULT = of("b_channel_modify_make_default"); public static final PermissionSID CHANNEL_MODIFY_MAKE_PERMANENT = of("b_channel_modify_make_permanent"); public static final PermissionSID CHANNEL_MODIFY_MAKE_SEMI_PERMANENT = of("b_channel_modify_make_semi_permament"); public static final PermissionSID CHANNEL_MODIFY_MAKE_TEMPORARY = of("b_channel_modify_make_temporary"); public static final PermissionSID CHANNEL_MODIFY_NAME = of("b_channel_modify_name"); public static final PermissionSID CHANNEL_MODIFY_TOPIC = of("b_channel_modify_topic"); public static final PermissionSID CHANNEL_MODIFY_DESCRIPTION = of("b_channel_modify_description"); public static final PermissionSID CHANNEL_MODIFY_PASSWORD = of("b_channel_modify_password"); public static final PermissionSID CHANNEL_MODIFY_CODEC = of("b_channel_modify_codec"); public static final PermissionSID CHANNEL_MODIFY_CODEC_QUALITY = of("b_channel_modify_codec_quality"); public static final PermissionSID CHANNEL_MODIFY_CODEC_LATENCY = of("b_channel_modify_codec_latency_factor"); public static final PermissionSID CHANNEL_MODIFY_MAXCLIENTS = of("b_channel_modify_maxclients"); public static final PermissionSID CHANNEL_MODIFY_MAXFAMILYCLIENTS = of("b_channel_modify_maxfamilyclients"); public static final PermissionSID CHANNEL_MODIFY_SORTORDER = of("b_channel_modify_sortorder"); public static final PermissionSID CHANNEL_MODIFY_NEEDED_TALKPOWER = of("b_channel_modify_needed_talk_power"); public static final PermissionSID CHANNEL_CHANNEL_MODIFY_POWER = of("i_channel_modify_power"); public static final PermissionSID CHANNEL_NEEDED_MODIFY_POWER = of("i_channel_needed_modify_power"); public static final PermissionSID CHANNEL_MODIFY_ENABLE_ENCRYPTION = of("b_channel_modify_make_codec_encrypted"); public static final PermissionSID CHANNEL_DELETE_PERMANENT = of("b_channel_delete_permanent"); public static final PermissionSID CHANNEL_DELETE_SEMI_PERMANENT = of("b_channel_delete_semi_permanent"); public static final PermissionSID CHANNEL_DELETE_TEMPORARY = of("b_channel_delete_temporary"); public static final PermissionSID CHANNEL_DELETE_FORCEFULLY = of("b_channel_delete_flag_force"); public static final PermissionSID CHANNEL_DELETE_POWER = of("i_channel_delete_power"); public static final PermissionSID CHANNEL_NEEDED_DELETE_POWER = of("i_channel_needed_delete_power"); public static final PermissionSID CHANNEL_NEEDED_JOIN_POWER = of("i_channel_needed_join_power"); public static final PermissionSID CHANNEL_NEEDED_SUBSCRIBE_POWER = of("i_channel_needed_subscribe_power"); public static final PermissionSID CHANNEL_NEEDED_DESCRIPTION_VIEW_POWER = of("i_channel_needed_description_view_power"); public static final PermissionSID CHANNEL_JOIN_PERMANENT = of("b_channel_join_permanent"); public static final PermissionSID CHANNEL_JOIN_SEMI_PERMANENT = of("b_channel_join_semi_permanent"); public static final PermissionSID CHANNEL_JOIN_TEMPORARY = of("b_channel_join_temporary"); public static final PermissionSID CHANNEL_JOIN_POWER = of("i_channel_join_power"); public static final PermissionSID CHANNEL_SUBSCRIBE_POWER = of("i_channel_subscribe_power"); public static final PermissionSID CHANNEL_DESCRIPTION_VIEW_POWER = of("i_channel_description_view_power"); public static final PermissionSID MANAGE_ICONS = of("b_icon_manage"); public static final PermissionSID END_INHERITANCE = of("b_channel_group_inheritance_end"); public static final PermissionSID SERVERQUERY_VIEW_POWER = of("i_client_serverquery_view_power"); public static final PermissionSID SERVERQUERY_NEEDED_VIEW_POWER = of("i_client_needed_serverquery_view_power"); public static Optional<PermissionSID> getSID(String permSID) { return Optional.ofNullable(INSTANCES.getOrDefault(permSID, null)); } private static PermissionSID of(String permSID) { PermissionSID perm = new PermissionSID(permSID); INSTANCES.put(permSID, perm); return perm; } private final String permSID; private PermissionSID(String permSID) { this.permSID = permSID; } public String getPermSID() { return permSID; } /** * Also referred to as the "grant" permission. */ public String getNeededModifySID() { Matcher matcher = PERMID_EXTR.matcher(permSID); if (!matcher.matches()) { throw new IllegalStateException("Protected PermSID"); } return String.format("i_needed_modify_power_%s", matcher.group(1)); } }
90.052632
138
0.827041
824da67f8a1a30b01fcb30c537d5ed416c17bfd6
937
package doko.database.player; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "players") public class Player implements Comparable<Player> { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(nullable = false) private String name; public Player(String name) { this.name = name; } public Player() { } public Long getId() { return id; } public String getName() { return name; } @Override public int compareTo(Player otherPlayer) { return Long.compare(id, otherPlayer.id); } @Override public boolean equals(Object otherPlayer) { if (otherPlayer instanceof Player) { return id == ((Player) otherPlayer).id; } return false; } @Override public int hashCode() { return (int) id; } }
17.351852
51
0.72572
2d0d5ddcfa8d5949e363ef3266f7000ae247556a
3,576
package lc.common.crypto; import java.security.KeyStoreException; import java.security.PublicKey; import java.util.HashMap; import java.util.Map.Entry; /** * Certificate registry. Used to keep a chain of keys and to determine if a * particular key is known by the trust registry. * * @author AfterLifeLochie * */ public class KeyTrustRegistry { /** The local registry key map */ private final HashMap<String, PublicKey> keyMap = new HashMap<String, PublicKey>(); /** * Create a new key trust registry with a blank key chain. */ public KeyTrustRegistry() { /* Do nothing */ } /** * <p> * Place a key into the registry. The key and the label must be unique in * the registry. The label-key association is recorded until the key is * forgotten. * </p> * * @param label * The label for the key * @param pk * The public key * @throws KeyStoreException * If the key store already contains a key of this label or of * this key. */ public final void placeKey(String label, PublicKey pk) throws KeyStoreException { synchronized (keyMap) { if (keyMap.containsKey(label)) throw new KeyStoreException("Entry with label already exists"); if (keyMap.containsValue(pk)) throw new KeyStoreException("Public key already in key map"); keyMap.put(label, pk); } } /** * <p> * Causes the registry to forget about a stored label-key association, * removing the public key from the trust chain. * </p> * * @param label * The label of the key to forget */ public final void forget(String label) { synchronized (keyMap) { keyMap.remove(label); } } /** * <p> * Causes the registry to forget about all instances of a public key, * removing it from any places in the trust chain. * </p> * * @param pk * The public key to forget */ public final void forget(PublicKey pk) { synchronized (keyMap) { String key = label(pk); if (key != null) keyMap.remove(key); } } /** * <p> * Request the label associated with a public key. * </p> * * @param pk * The public key * @return The label, or null if the key is not known by the registry */ public final String label(PublicKey pk) { synchronized (keyMap) { String key = null; for (Entry<String, PublicKey> pair : keyMap.entrySet()) if (pair.getValue().equals(pk)) key = pair.getKey(); return key; } } /** * <p> * Checks the chain to see if the public key provided is in the chain. If * the public key is in the chain, true is returned; else false is returned. * </p> * * @param pk * The public key * @return If the key is in the trust chain */ public final boolean checkTrust(PublicKey pk) { synchronized (keyMap) { for (Entry<String, PublicKey> pair : keyMap.entrySet()) if (pair.getValue().equals(pk)) return true; return false; } } /** * <p> * Empties the key chain. All keys are immediately released and forgotten * from the key-chain * </p> */ public final void purge() { synchronized (keyMap) { keyMap.clear(); } } /** * <p> * Fetches the contents of all public keys in the chain. * </p> * * @return The contents of the key chain */ public final PublicKey[] contents() { synchronized (keyMap) { return keyMap.values().toArray(new PublicKey[0]); } } }
24.162162
85
0.610459
1c6140f80e5b08fd9b827dfaad5aa87894a16a81
1,543
package dk.viabnb.sep3.group6.dataserver.rest.t3.dao.guestreview; import dk.viabnb.sep3.group6.dataserver.rest.t3.models.GuestReview; import java.util.List; public interface GuestReviewDAO { /** * Create a new GuestReview object and store it in a database * * @param guestReview The new object * @return newly created GuestReview object * @throws IllegalArgumentException if connection to database failed or executing the update failed */ GuestReview createGuestReview(GuestReview guestReview); /** * Update a GuestReview object and store it in a database * * @param guestReview The new updated object * @return newly updated GuestReview object * @throws IllegalArgumentException if connection to database failed or executing the update failed */ GuestReview updateGuestReview(GuestReview guestReview); /** * Query a list of GuestReview objects based on the given parameter * * @param id The id of the Guest whom the GuestReview objects belongs to * @return A list of GuestReview objects * @throws IllegalArgumentException if connection to database failed or query execution failed */ List<GuestReview> getAllGuestReviewsByHostId(int id); /** * Query a list of GuestReview objects based on the given parameter * * @param id The targeted GuestReview's Guest's id * @return A list of GuestReview Object * @throws IllegalStateException if connection to database failed or query execution failed */ List<GuestReview> getAllGuestReviewsByGuestId(int id); }
36.738095
101
0.755671
73a297451499f5a24a4852526e4f3c85d4e6c586
1,049
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.yql; import com.google.common.collect.Sets; import org.antlr.v4.runtime.Parser; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTree; import java.util.Set; /** * Provides semantic helper functions to Parser. */ abstract class ParserBase extends Parser { private static String arrayRuleName = "array"; public ParserBase(TokenStream input) { super(input); } private Set<String> arrayParameters = Sets.newHashSet(); public void registerParameter(String name, String typeName) { if (typeName.equals(arrayRuleName)) { arrayParameters.add(name); } } public boolean isArrayParameter(ParseTree nameNode) { String name = nameNode.getText(); if (name.startsWith("@")) { name = name.substring(1); } return name != null && arrayParameters.contains(name); } }
26.225
118
0.678742
6d843c172a3cf99ab0425cfac04453447b6a2b93
3,023
// Copyright (c) 2003-present, Jodd Team (http://jodd.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 jodd.madvoc.result; import jodd.io.StreamUtil; import jodd.madvoc.ActionRequest; import jodd.madvoc.component.MadvocEncoding; import jodd.madvoc.meta.In; import jodd.madvoc.meta.scope.MadvocContext; import jodd.util.StringPool; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; /** * Text result returns a result value, i.e. a string. * Useful for JSON responses, when resulting string is built * in the action. */ public class TextActionResult implements ActionResult { @In @MadvocContext protected MadvocEncoding madvocEncoding; @Override public void render(final ActionRequest actionRequest, final Object resultValue) throws Exception { final TextResult textResult; if (resultValue == null) { textResult = TextResult.of(StringPool.EMPTY); } else { if (resultValue instanceof String) { textResult = TextResult.of((String)resultValue); } else { textResult = (TextResult) resultValue; } } final HttpServletResponse response = actionRequest.getHttpServletResponse(); String encoding = response.getCharacterEncoding(); if (encoding == null) { encoding = madvocEncoding.getEncoding(); } response.setContentType(textResult.contentType()); response.setCharacterEncoding(encoding); response.setStatus(textResult.status()); String text = textResult.value(); if (text == null) { text = StringPool.EMPTY; } final byte[] data = text.getBytes(encoding); response.setContentLength(data.length); OutputStream out = null; try { out = response.getOutputStream(); out.write(data); } finally { StreamUtil.close(out); } } }
32.858696
99
0.754548
ad50e0c16a247388e259849b5e8bc33917bee9b9
496
package io.leopard.convert; import io.leopard.lang.Paging; import java.util.List; public class ConvertUtil { public static <S, T> T bean(S source, Class<T> clazz) { return new BeanConvert<S, T>(source, clazz).convert(); } public static <S, T> List<T> list(List<S> list, Class<T> clazz) { return new ListConvert<S, T>(list, clazz).convert(); } public static <S, T> Paging<T> paging(Paging<S> paging, Class<T> clazz) { return new PagingConvert<S, T>(paging, clazz).convert(); } }
23.619048
74
0.683468
af171e39a53b648717f15d9fac91554d03c77906
5,886
package org.sdase.commons.server.kafka.config; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Properties; import org.apache.kafka.common.config.SaslConfigs; import org.junit.Test; import org.sdase.commons.server.kafka.KafkaConfiguration; import org.sdase.commons.server.kafka.KafkaProperties; public class KafkaPropertiesTest { @Test public void itShouldUseGlobalConfig() { KafkaConfiguration config = new KafkaConfiguration(); config.getConfig().put("setting", "from.global"); assertThat(KafkaProperties.forProducer(config).get("setting")).isEqualTo("from.global"); assertThat(KafkaProperties.forConsumer(config).get("setting")).isEqualTo("from.global"); assertThat(KafkaProperties.forAdminClient(config).get("setting")).isEqualTo("from.global"); } @Test public void itShouldUseAdminConfigOverGlobalConfig() { KafkaConfiguration config = new KafkaConfiguration(); AdminConfig adminConfig = new AdminConfig(); adminConfig.getConfig().put("setting", "from.admin"); config.setAdminConfig(adminConfig); config.getConfig().put("setting", "from.global"); assertThat(KafkaProperties.forProducer(config).get("setting")).isEqualTo("from.global"); assertThat(KafkaProperties.forConsumer(config).get("setting")).isEqualTo("from.global"); assertThat(KafkaProperties.forAdminClient(config).get("setting")).isEqualTo("from.admin"); } @Test public void itShouldBuildSaslStringCorrectly() { KafkaConfiguration config = new KafkaConfiguration(); Security sec = new Security(); sec.setPassword("password"); sec.setUser("user"); sec.setProtocol(ProtocolType.SASL_SSL); config.setSecurity(sec); Properties props = KafkaProperties.forProducer(config); final String saslJaasConfig = "org.apache.kafka.common.security.plain.PlainLoginModule required username='user' password='password';"; assertThat(props.getProperty("sasl.jaas.config")).isEqualTo(saslJaasConfig); } @Test public void itShouldConfigureSecurityForAdminConfig() { KafkaConfiguration config = new KafkaConfiguration(); Security sec = new Security(); sec.setPassword("password"); sec.setUser("user"); sec.setProtocol(ProtocolType.SASL_SSL); config.setSecurity(sec); Properties props = KafkaProperties.forAdminClient(config); final String saslJaasConfig = "org.apache.kafka.common.security.plain.PlainLoginModule required username='user' password='password';"; assertThat(props.getProperty("sasl.jaas.config")).isEqualTo(saslJaasConfig); assertThat(props.getProperty("sasl.mechanism")).isEqualTo("PLAIN"); } @Test public void itShouldUseCustomConfigForAdminConfig() { KafkaConfiguration config = new KafkaConfiguration(); Security sec = new Security(); sec.setPassword("password"); sec.setUser("user"); sec.setProtocol(ProtocolType.SASL_SSL); config.setSecurity(sec); AdminConfig adminConfig = new AdminConfig(); adminConfig.getConfig().put("custom.property", "custom.property.value"); adminConfig.getConfig().put("sasl.jaas.config", "custom.sasl.jaas.config"); adminConfig.getConfig().put("sasl.mechanism", "SCRAM-SHA-512"); config.setAdminConfig(adminConfig); Properties props = KafkaProperties.forAdminClient(config); assertThat(props.getProperty("custom.property")).isEqualTo("custom.property.value"); assertThat(props.getProperty("sasl.jaas.config")).isEqualTo("custom.sasl.jaas.config"); assertThat(props.getProperty("sasl.mechanism")).isEqualTo("SCRAM-SHA-512"); } @Test public void itShouldBuildSaslStringCorrectlyForSCRAM() { KafkaConfiguration config = new KafkaConfiguration(); Security sec = new Security(); sec.setPassword("password"); sec.setUser("user"); sec.setSaslMechanism("SCRAM-SHA-512"); sec.setProtocol(ProtocolType.SASL_PLAINTEXT); config.setSecurity(sec); Properties props = KafkaProperties.forProducer(config); final String saslJaasConfig = "org.apache.kafka.common.security.scram.ScramLoginModule required username='user' password='password';"; assertThat(props.getProperty("sasl.jaas.config")).isEqualTo(saslJaasConfig); } @Test public void itShouldThrowForUnknownSaslMechanism() { KafkaConfiguration config = new KafkaConfiguration(); Security sec = new Security(); sec.setPassword("password"); sec.setUser("user"); sec.setProtocol(ProtocolType.SASL_SSL); sec.setSaslMechanism("OAUTHBEARER"); config.setSecurity(sec); assertThatThrownBy(() -> KafkaProperties.forProducer(config)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Unsupported SASL mechanism OAUTHBEARER"); } @Test public void itShouldNotConfigureSaslForPLAINTEXT() { KafkaConfiguration config = new KafkaConfiguration(); Security sec = new Security(); sec.setPassword("password"); sec.setUser("user"); sec.setSaslMechanism("PLAIN"); sec.setProtocol(ProtocolType.PLAINTEXT); config.setSecurity(sec); Properties props = KafkaProperties.forProducer(config); assertThat(props.getProperty(SaslConfigs.SASL_JAAS_CONFIG)).isNull(); assertThat(props.getProperty(SaslConfigs.SASL_MECHANISM)).isNull(); } @Test public void itShouldNotConfigureSaslForSSL() { KafkaConfiguration config = new KafkaConfiguration(); Security sec = new Security(); sec.setPassword("password"); sec.setUser("user"); sec.setSaslMechanism("PLAIN"); sec.setProtocol(ProtocolType.SSL); config.setSecurity(sec); Properties props = KafkaProperties.forProducer(config); assertThat(props.getProperty(SaslConfigs.SASL_JAAS_CONFIG)).isNull(); assertThat(props.getProperty(SaslConfigs.SASL_MECHANISM)).isNull(); } }
34.623529
112
0.739212
0c50bbebb7c07216570ca2474ccb0115e1ebc18a
221
package UTDC.Controllers; import UTDC.Models.UTDCModel; import UTDC.Views.ViewInterface; public interface ControllerInterface { void setView(ViewInterface v); void setModel(UTDCModel m); void startFlow(); }
20.090909
38
0.764706
01eef1810dd5eaf4f2f13ded817cc9eabc2bfaef
534
package assembly; public class BoundingBox { public int minX; public int maxX; public int minY; public int maxY; public BoundingBox(int minX, int maxX, int minY, int maxY) { this.minX = minX; this.maxX = maxX; this.minY = minY; this.maxY = maxY; } public void encompass(BoundingBox boundingBox) { this.minX = Math.min(this.minX, boundingBox.minX); this.minY = Math.min(this.minY, boundingBox.minY); this.maxX = Math.max(this.maxX, boundingBox.maxX); this.maxY = Math.max(this.maxY, boundingBox.maxY); } }
21.36
61
0.702247
2205fdfc2537675b743b94fc272436e5a9f8aa5c
2,225
package com.hui.Math; /** * @author: shenhaizhilong * @date: 2018/8/29 14:54 */ public class StudentAttendanceRecord { /** * * 551. Student Attendance Record I * DescriptionHintsSubmissionsDiscussSolution * You are given a string representing an attendance record for a student. The record only contains the following three characters: * 'A' : Absent. * 'L' : Late. * 'P' : Present. * A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late). * * You need to return whether the student could be rewarded according to his attendance record. * * Example 1: * Input: "PPALLP" * Output: True * Example 2: * Input: "PPALLL" * Output: False * * @param s * @return */ public static boolean checkRecord(String s) { if(s == null || s.length() == 0)return true; int[] counter = new int[26]; char[] data = s.toCharArray(); for (int i = 0; i < data.length; i++) { counter[data[i] - 'A']++; if(counter[0] >1)return false; if(i <= data.length -3 && data[i] == 'L' && data[i+1] == 'L' && data[i+2] == 'L') { return false; } } return true; } public static boolean checkRecord2(String s) { if(s == null || s.length() == 0)return true; int counter = 0; char[] data = s.toCharArray(); for (int i = 0; i < data.length; i++) { if(data[i] == 'A') { counter++; if(counter >1)return false; }else if(data[i] == 'L') { if(i <= data.length -3 && data[i+1] == 'L' && data[i+2] == 'L') { return false; } } } return true; } public static void main(String[] args) { System.out.println(checkRecord2("PPALALP")); System.out.println(checkRecord2("PPALLL")); System.out.println(checkRecord2("PLLPAL")); } }
29.276316
143
0.488539
f19d27d8422698f773d2101b54d7ced268d0e41d
635
package com.example.demo; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class HomeController { @RequestMapping("/emailRequestForm") public String requestEmailForm() { return "emailFormTemplate"; } @RequestMapping("/processEmailRequestForm") public String loadFromEmailPage(@RequestParam("email") String email, Model model) { model.addAttribute("emailVal", email); return "emailConfirmationPage"; } }
30.238095
87
0.75748
98f2266216dbcf57ea436344d4010736e8ea9428
4,927
/*- * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. 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. * ============LICENSE_END========================================================= */ package org.openecomp.mso.cloud; import java.security.GeneralSecurityException; import com.fasterxml.jackson.annotation.JsonProperty; import org.openecomp.mso.utils.CryptoUtils; import org.openecomp.mso.logger.MessageEnum; import org.openecomp.mso.logger.MsoLogger; /** * JavaBean JSON class for a Cloudify Manager. This bean represents a Cloudify * node through which TOSCA-based VNFs may be deployed. Each CloudSite in the * CloudConfig may have a Cloudify Manager for deployments using TOSCA blueprints. * Cloudify Managers may support multiple Cloud Sites, but each site will have * at most one Cloudify Manager. * * This does not replace the ability to use the CloudSite directly via Openstack. * * Note that this is only used to access Cloud Configurations loaded from a * JSON config file, so there are no explicit setters. * * @author JC1348 */ public class CloudifyManager { private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); @JsonProperty private String id; @JsonProperty ("cloudify_url") private String cloudifyUrl; @JsonProperty("username") private String username; @JsonProperty("password") private String password; @JsonProperty("version") private String version; private static String cloudKey = "aa3871669d893c7fb8abbcda31b88b4f"; public CloudifyManager() {} public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCloudifyUrl() { return cloudifyUrl; } public void setCloudifyUrl(String cloudifyUrl) { this.cloudifyUrl = cloudifyUrl; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { try { return CryptoUtils.decrypt (password, cloudKey); } catch (GeneralSecurityException e) { LOGGER.error (MessageEnum.RA_GENERAL_EXCEPTION, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in getMsoPass", e); return null; } } public void setPassword(String password) { this.password = password; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } @Override public String toString() { return "CloudifyManager: id=" + id + ", cloudifyUrl=" + cloudifyUrl + ", username=" + username + ", password=" + password + ", version=" + version; } @Override public CloudifyManager clone() { CloudifyManager cloudifyManagerCopy = new CloudifyManager(); cloudifyManagerCopy.id = this.id; cloudifyManagerCopy.cloudifyUrl = this.cloudifyUrl; cloudifyManagerCopy.username = this.username; cloudifyManagerCopy.password = this.password; cloudifyManagerCopy.version = this.version; return cloudifyManagerCopy; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((cloudifyUrl == null) ? 0 : cloudifyUrl.hashCode()); result = prime * result + ((username == null) ? 0 : username.hashCode()); result = prime * result + ((password == null) ? 0 : password.hashCode()); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CloudifyManager other = (CloudifyManager) obj; if (!cmp(id, other.id)) return false; if (!cmp(cloudifyUrl, other.cloudifyUrl)) return false; if (!cmp(username, other.username)) return false; if (!cmp(version, other.version)) return false; if (!cmp(password, other.password)) return false; return true; } private boolean cmp(Object a, Object b) { if (a == null) { return (b == null); } else { return a.equals(b); } } }
28.982353
141
0.662269
2e7aa7077be8322834523afa0871b9016fd72806
1,464
package edu.rpi.tw.data.csv.querylets.structural; import java.nio.charset.Charset; import org.openrdf.model.Resource; import org.openrdf.query.BindingSet; import edu.rpi.tw.data.rdf.sesame.query.impl.OnlyOneContextQuerylet; /** * */ // https://github.com/timrdf/csv2rdf4lod-automation/issues/277 public class CharsetQuerylet extends OnlyOneContextQuerylet<Charset> { protected String charset = "UTF-8"; protected boolean set = false; public CharsetQuerylet(Resource context) { super(context); } @Override public String getQueryString(Resource context) { this.addNamespace("conversion"); String select = "?charset"; String graphPattern = "?dataset conversion:conversion_process [ conversion:charset ?charset ] ."; String orderBy = "?charset"; String limit = ""; return this.composeQuery(select, context, graphPattern, orderBy, limit); } @Override public void handleBindingSet(BindingSet bindingSet) { String cs = bindingSet.getValue("charset").stringValue(); if( !set ) { this.charset = bindingSet.getValue("charset").stringValue(); System.err.println(getClass().getSimpleName() + "(*) ." + this.charset + "."); }else { System.err.println(getClass().getSimpleName() + "(*) IGNORING ." + cs + "."); } } @Override public Charset get() { return Charset.forName(this.charset); } }
28.705882
103
0.656421
08fdbef7afa553560e1cac0d4974c91c18e6c9f9
679
package pg.gipter.core.producers; import org.junit.jupiter.api.Test; import pg.gipter.core.ApplicationPropertiesFactory; import java.util.Arrays; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; class LinuxDiffProducerTest { @Test void given_listOfCommands_when_getFullCommand_then_returnFullCommand() { LinuxDiffProducer producer = new LinuxDiffProducer( ApplicationPropertiesFactory.getInstance(new String[]{"preferredArgSource=FILE"}) ); List<String> actual = producer.getFullCommand(Arrays.asList("c", "\"c2\"", "c3")); assertThat(actual).containsExactly("c", "c2", "c3"); } }
29.521739
97
0.724595
8062149b06ff59413e666d78bec594399f100590
4,064
/* * 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.sling.api.wrappers.impl; import java.time.Instant; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import org.osgi.util.converter.ConversionException; import org.osgi.util.converter.Converter; import org.osgi.util.converter.Converters; import org.osgi.util.converter.TypeRule; /** * Converts objects to specific types. */ public final class ObjectConverter { private ObjectConverter() { } private static Converter converter; private static Converter getConverter() { // TODO at some point it may be practical to have TypeRules as OSGI services to // add more complex conversions much in the way that adaptTo has evolved if (converter == null) { synchronized (ObjectConverter.class) { if (converter == null) { converter = Converters.newConverterBuilder() .rule(new TypeRule<String, GregorianCalendar>(String.class, GregorianCalendar.class, ObjectConverter::toCalendar)) .rule(new TypeRule<Date, GregorianCalendar>(Date.class, GregorianCalendar.class, ObjectConverter::toCalendar)) .rule(new TypeRule<String, Date>(String.class, Date.class, ObjectConverter::toDate)) .rule(new TypeRule<Calendar, String>(Calendar.class, String.class, ObjectConverter::toString)) .rule(new TypeRule<Date, String>(Date.class, String.class, ObjectConverter::toString)) .rule(new TypeRule<GregorianCalendar, Date>(GregorianCalendar.class, Date.class, ObjectConverter::toDate)) .build(); } } } return converter; } private static String toString(Calendar cal) { return cal.toInstant().toString(); } private static String toString(Date cal) { return cal.toInstant().toString(); } private static GregorianCalendar toCalendar(String date) { Calendar response = Calendar.getInstance(); response.setTime(Date.from(Instant.parse(date))); return (GregorianCalendar) response; } private static GregorianCalendar toCalendar(Date date) { Calendar response = Calendar.getInstance(); response.setTime(date); return (GregorianCalendar) response; } private static Date toDate(String date) { return Date.from(Instant.parse(date)); } private static Date toDate(Calendar cal) { return cal.getTime(); } /** * Converts the object to the given type. * * @param obj * object * @param type * type * @param <T> * Target type * @return the converted object */ public static <T> T convert(Object obj, Class<T> type) { if (obj == null) { return null; } try { return getConverter().convert(obj).to(type); } catch (ConversionException ce) { return null; } } }
35.034483
114
0.618602
66490a1ab85356602d19fd4b2892c89c0511489e
722
package com.leyou.item.bo; import lombok.Data; /** * 秒杀参数设置 */ @Data public class SeckillParameter { /** * 要秒杀的sku id */ private Long id; /** * 秒杀开始时间 */ private String startTime; /** * 秒杀结束时间 */ private String endTime; /** * 参与秒杀的商品数量 */ private Integer count; /** * 折扣 */ private double discount; @Override public String toString() { return "SeckillParameter{" + "id=" + id + ", startTime='" + startTime + '\'' + ", endTime='" + endTime + '\'' + ", count=" + count + ", discount=" + discount + '}'; } }
15.361702
52
0.433518
ff3a3b83527cb1fb22d247e79ed8db1fa99a6b72
18,038
package org.im97mori.ble.service.bcs.peripheral; import static org.im97mori.ble.constants.CharacteristicUUID.BODY_COMPOSITION_FEATURE_CHARACTERISTIC; import static org.im97mori.ble.constants.CharacteristicUUID.BODY_COMPOSITION_MEASUREMENT_CHARACTERISTIC; import static org.im97mori.ble.constants.DescriptorUUID.CLIENT_CHARACTERISTIC_CONFIGURATION_DESCRIPTOR; import static org.im97mori.ble.constants.ServiceUUID.BODY_COMPOSITION_SERVICE; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.os.Build; import androidx.test.filters.RequiresDevice; import androidx.test.filters.SdkSuppress; import org.im97mori.ble.characteristic.u2a9b.BodyCompositionFeature; import org.im97mori.ble.characteristic.u2a9c.BodyCompositionMeasurement; import org.im97mori.ble.characteristic.u2a9c.BodyCompositionMeasurementPacket; import org.im97mori.ble.descriptor.u2902.ClientCharacteristicConfiguration; import org.im97mori.ble.test.peripheral.AbstractPeripheralTest; import org.junit.Test; import java.util.LinkedList; import java.util.List; public class BodyCompositionServiceMockCallbackBuilderTest extends AbstractPeripheralTest { @Test @RequiresDevice @SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP) public void test_exception_00001() { Exception exception = null; try { new BodyCompositionServiceMockCallback.Builder<>().build(); } catch (RuntimeException e) { exception = e; } assertNotNull(exception); assertEquals("no Body Composition Feature data", exception.getMessage()); } @Test @RequiresDevice @SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP) public void test_exception_00002() { Exception exception = null; try { new BodyCompositionServiceMockCallback.Builder<>() .addBodyCompositionFeature(new BodyCompositionFeature(new byte[4])) .build(); } catch (RuntimeException e) { exception = e; } assertNotNull(exception); assertEquals("no Body Composition Measurement data", exception.getMessage()); } @Test @RequiresDevice @SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP) public void test_exception_00003() { Exception exception = null; try { new BodyCompositionServiceMockCallback.Builder<>() .addBodyCompositionFeature(new BodyCompositionFeature(new byte[4])) .addBodyCompositionMeasurement(new BodyCompositionMeasurement(new BodyCompositionMeasurementPacket(new byte[]{0, 0, (byte) 0xff, (byte) 0xff})) , new ClientCharacteristicConfiguration(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE)) .build(); } catch (RuntimeException e) { exception = e; } assertNull(exception); } @Test @RequiresDevice @SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP) public void test_addBodyCompositionFeature_00001() { BodyCompositionFeature bodyCompositionFeature = new BodyCompositionFeature(new byte[4]); final List<BluetoothGattService> bluetoothGattServiceList = new LinkedList<>(); MOCK_BLE_SERVER_CONNECTION.setCreateAddServiceTaskBluetoothGattServiceList(bluetoothGattServiceList); Exception exception = null; try { BodyCompositionServiceMockCallback callback = new BodyCompositionServiceMockCallback.Builder<>() .addBodyCompositionFeature(bodyCompositionFeature) .addBodyCompositionMeasurement(new BodyCompositionMeasurement(new BodyCompositionMeasurementPacket(new byte[]{0, 0, (byte) 0xff, (byte) 0xff})) , new ClientCharacteristicConfiguration(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE)) .build(); callback.setup(MOCK_BLE_SERVER_CONNECTION); } catch (RuntimeException e) { exception = e; } assertNull(exception); assertFalse(bluetoothGattServiceList.isEmpty()); assertEquals(1, bluetoothGattServiceList.size()); BluetoothGattService bluetoothGattService = bluetoothGattServiceList.get(0); assertEquals(BODY_COMPOSITION_SERVICE, bluetoothGattService.getUuid()); assertEquals(BluetoothGattService.SERVICE_TYPE_PRIMARY, bluetoothGattService.getType()); BluetoothGattCharacteristic bluetoothGattCharacteristic = bluetoothGattService.getCharacteristic(BODY_COMPOSITION_FEATURE_CHARACTERISTIC); assertNotNull(bluetoothGattCharacteristic); assertEquals(BODY_COMPOSITION_FEATURE_CHARACTERISTIC, bluetoothGattCharacteristic.getUuid()); assertEquals(BluetoothGattCharacteristic.PROPERTY_READ, bluetoothGattCharacteristic.getProperties()); assertEquals(BluetoothGattCharacteristic.PERMISSION_READ, bluetoothGattCharacteristic.getPermissions()); assertArrayEquals(bodyCompositionFeature.getBytes(), bluetoothGattCharacteristic.getValue()); } @Test @RequiresDevice @SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP) public void test_addBodyCompositionFeature_00101() { BodyCompositionFeature bodyCompositionFeature = new BodyCompositionFeature(new byte[4]); final List<BluetoothGattService> bluetoothGattServiceList = new LinkedList<>(); MOCK_BLE_SERVER_CONNECTION.setCreateAddServiceTaskBluetoothGattServiceList(bluetoothGattServiceList); Exception exception = null; try { BodyCompositionServiceMockCallback callback = new BodyCompositionServiceMockCallback.Builder<>() .addBodyCompositionFeature(bodyCompositionFeature.getBytes()) .addBodyCompositionMeasurement(new BodyCompositionMeasurement(new BodyCompositionMeasurementPacket(new byte[]{0, 0, (byte) 0xff, (byte) 0xff})) , new ClientCharacteristicConfiguration(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE)) .build(); callback.setup(MOCK_BLE_SERVER_CONNECTION); } catch (RuntimeException e) { exception = e; } assertNull(exception); assertFalse(bluetoothGattServiceList.isEmpty()); assertEquals(1, bluetoothGattServiceList.size()); BluetoothGattService bluetoothGattService = bluetoothGattServiceList.get(0); assertEquals(BODY_COMPOSITION_SERVICE, bluetoothGattService.getUuid()); assertEquals(BluetoothGattService.SERVICE_TYPE_PRIMARY, bluetoothGattService.getType()); BluetoothGattCharacteristic bluetoothGattCharacteristic = bluetoothGattService.getCharacteristic(BODY_COMPOSITION_FEATURE_CHARACTERISTIC); assertNotNull(bluetoothGattCharacteristic); assertEquals(BODY_COMPOSITION_FEATURE_CHARACTERISTIC, bluetoothGattCharacteristic.getUuid()); assertEquals(BluetoothGattCharacteristic.PROPERTY_READ, bluetoothGattCharacteristic.getProperties()); assertEquals(BluetoothGattCharacteristic.PERMISSION_READ, bluetoothGattCharacteristic.getPermissions()); assertArrayEquals(bodyCompositionFeature.getBytes(), bluetoothGattCharacteristic.getValue()); } @Test @RequiresDevice @SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP) public void test_addBodyCompositionFeature_00201() { BodyCompositionFeature bodyCompositionFeature = new BodyCompositionFeature(new byte[4]); final List<BluetoothGattService> bluetoothGattServiceList = new LinkedList<>(); MOCK_BLE_SERVER_CONNECTION.setCreateAddServiceTaskBluetoothGattServiceList(bluetoothGattServiceList); Exception exception = null; try { BodyCompositionServiceMockCallback callback = new BodyCompositionServiceMockCallback.Builder<>() .addBodyCompositionFeature(BluetoothGatt.GATT_SUCCESS, 0, bodyCompositionFeature.getBytes()) .addBodyCompositionMeasurement(new BodyCompositionMeasurement(new BodyCompositionMeasurementPacket(new byte[]{0, 0, (byte) 0xff, (byte) 0xff})) , new ClientCharacteristicConfiguration(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE)) .build(); callback.setup(MOCK_BLE_SERVER_CONNECTION); } catch (RuntimeException e) { exception = e; } assertNull(exception); assertFalse(bluetoothGattServiceList.isEmpty()); assertEquals(1, bluetoothGattServiceList.size()); BluetoothGattService bluetoothGattService = bluetoothGattServiceList.get(0); assertEquals(BODY_COMPOSITION_SERVICE, bluetoothGattService.getUuid()); assertEquals(BluetoothGattService.SERVICE_TYPE_PRIMARY, bluetoothGattService.getType()); BluetoothGattCharacteristic bluetoothGattCharacteristic = bluetoothGattService.getCharacteristic(BODY_COMPOSITION_FEATURE_CHARACTERISTIC); assertNotNull(bluetoothGattCharacteristic); assertEquals(BODY_COMPOSITION_FEATURE_CHARACTERISTIC, bluetoothGattCharacteristic.getUuid()); assertEquals(BluetoothGattCharacteristic.PROPERTY_READ, bluetoothGattCharacteristic.getProperties()); assertEquals(BluetoothGattCharacteristic.PERMISSION_READ, bluetoothGattCharacteristic.getPermissions()); assertArrayEquals(bodyCompositionFeature.getBytes(), bluetoothGattCharacteristic.getValue()); } @Test @RequiresDevice @SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP) public void test_removeBodyCompositionFeature_00001() { BodyCompositionFeature bodyCompositionFeature = new BodyCompositionFeature(new byte[4]); Exception exception = null; try { new BodyCompositionServiceMockCallback.Builder<>() .addBodyCompositionFeature(bodyCompositionFeature) .addBodyCompositionMeasurement(new BodyCompositionMeasurement(new BodyCompositionMeasurementPacket(new byte[]{0, 0, (byte) 0xff, (byte) 0xff})) , new ClientCharacteristicConfiguration(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE)) .removeBodyCompositionFeature() .build(); } catch (RuntimeException e) { exception = e; } assertNotNull(exception); assertEquals("no Body Composition Feature data", exception.getMessage()); } @Test @RequiresDevice @SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP) public void test_addBodyCompositionMeasurement_00001() { BodyCompositionMeasurement bodyCompositionMeasurement = new BodyCompositionMeasurement(new BodyCompositionMeasurementPacket(new byte[]{0, 0, (byte) 0xff, (byte) 0xff})); byte[] value = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE; ClientCharacteristicConfiguration clientCharacteristicConfiguration = new ClientCharacteristicConfiguration(value); final List<BluetoothGattService> bluetoothGattServiceList = new LinkedList<>(); MOCK_BLE_SERVER_CONNECTION.setCreateAddServiceTaskBluetoothGattServiceList(bluetoothGattServiceList); Exception exception = null; try { BodyCompositionServiceMockCallback userDataServiceMockCallback = new BodyCompositionServiceMockCallback.Builder<>() .addBodyCompositionMeasurement(bodyCompositionMeasurement, clientCharacteristicConfiguration) .addBodyCompositionFeature(new BodyCompositionFeature(new byte[4])) .build(); userDataServiceMockCallback.setup(MOCK_BLE_SERVER_CONNECTION); } catch (RuntimeException e) { exception = e; } assertNull(exception); assertFalse(bluetoothGattServiceList.isEmpty()); assertEquals(1, bluetoothGattServiceList.size()); BluetoothGattService bluetoothGattService = bluetoothGattServiceList.get(0); assertEquals(BODY_COMPOSITION_SERVICE, bluetoothGattService.getUuid()); assertEquals(BluetoothGattService.SERVICE_TYPE_PRIMARY, bluetoothGattService.getType()); BluetoothGattCharacteristic bluetoothGattCharacteristic = bluetoothGattService.getCharacteristic(BODY_COMPOSITION_MEASUREMENT_CHARACTERISTIC); assertNotNull(bluetoothGattCharacteristic); assertEquals(BODY_COMPOSITION_MEASUREMENT_CHARACTERISTIC, bluetoothGattCharacteristic.getUuid()); assertEquals(BluetoothGattCharacteristic.PROPERTY_INDICATE, bluetoothGattCharacteristic.getProperties()); assertEquals(0, bluetoothGattCharacteristic.getPermissions()); assertArrayEquals(bodyCompositionMeasurement.getBytes(), bluetoothGattCharacteristic.getValue()); BluetoothGattDescriptor bluetoothGattDescriptor = bluetoothGattCharacteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIGURATION_DESCRIPTOR); assertNotNull(bluetoothGattDescriptor); assertEquals(CLIENT_CHARACTERISTIC_CONFIGURATION_DESCRIPTOR, bluetoothGattDescriptor.getUuid()); assertEquals(BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_WRITE, bluetoothGattDescriptor.getPermissions()); assertArrayEquals(clientCharacteristicConfiguration.getBytes(), bluetoothGattDescriptor.getValue()); } @Test @RequiresDevice @SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP) public void test_addBodyCompositionMeasurement_00101() { BodyCompositionMeasurement bodyCompositionMeasurement = new BodyCompositionMeasurement(new BodyCompositionMeasurementPacket(new byte[]{0, 0, (byte) 0xff, (byte) 0xff})); byte[] value = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE; ClientCharacteristicConfiguration clientCharacteristicConfiguration = new ClientCharacteristicConfiguration(value); int characteristicResponseCode = 1; long characteristicDelay = 2; int notificationCount = 3; int descriptorResponseCode = 4; long descriptorDelay = 5; final List<BluetoothGattService> bluetoothGattServiceList = new LinkedList<>(); MOCK_BLE_SERVER_CONNECTION.setCreateAddServiceTaskBluetoothGattServiceList(bluetoothGattServiceList); Exception exception = null; try { BodyCompositionServiceMockCallback userDataServiceMockCallback = new BodyCompositionServiceMockCallback.Builder<>() .addBodyCompositionMeasurement(characteristicResponseCode, characteristicDelay, bodyCompositionMeasurement.getBytes(), notificationCount, descriptorResponseCode, descriptorDelay, clientCharacteristicConfiguration.getBytes()) .addBodyCompositionFeature(new BodyCompositionFeature(new byte[4])) .build(); userDataServiceMockCallback.setup(MOCK_BLE_SERVER_CONNECTION); } catch (RuntimeException e) { exception = e; } assertNull(exception); assertFalse(bluetoothGattServiceList.isEmpty()); assertEquals(1, bluetoothGattServiceList.size()); BluetoothGattService bluetoothGattService = bluetoothGattServiceList.get(0); assertEquals(BODY_COMPOSITION_SERVICE, bluetoothGattService.getUuid()); assertEquals(BluetoothGattService.SERVICE_TYPE_PRIMARY, bluetoothGattService.getType()); BluetoothGattCharacteristic bluetoothGattCharacteristic = bluetoothGattService.getCharacteristic(BODY_COMPOSITION_MEASUREMENT_CHARACTERISTIC); assertNotNull(bluetoothGattCharacteristic); assertEquals(BODY_COMPOSITION_MEASUREMENT_CHARACTERISTIC, bluetoothGattCharacteristic.getUuid()); assertEquals(BluetoothGattCharacteristic.PROPERTY_INDICATE, bluetoothGattCharacteristic.getProperties()); assertEquals(0, bluetoothGattCharacteristic.getPermissions()); assertArrayEquals(bodyCompositionMeasurement.getBytes(), bluetoothGattCharacteristic.getValue()); BluetoothGattDescriptor bluetoothGattDescriptor = bluetoothGattCharacteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIGURATION_DESCRIPTOR); assertNotNull(bluetoothGattDescriptor); assertEquals(CLIENT_CHARACTERISTIC_CONFIGURATION_DESCRIPTOR, bluetoothGattDescriptor.getUuid()); assertEquals(BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_WRITE, bluetoothGattDescriptor.getPermissions()); assertArrayEquals(clientCharacteristicConfiguration.getBytes(), bluetoothGattDescriptor.getValue()); } @Test @RequiresDevice @SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP) public void test_removeRegisteredUser_00001() { BodyCompositionMeasurement bodyCompositionMeasurement = new BodyCompositionMeasurement(new BodyCompositionMeasurementPacket(new byte[]{0, 0, (byte) 0xff, (byte) 0xff})); byte[] value = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE; ClientCharacteristicConfiguration clientCharacteristicConfiguration = new ClientCharacteristicConfiguration(value); Exception exception = null; try { new BodyCompositionServiceMockCallback.Builder<>() .addBodyCompositionMeasurement(bodyCompositionMeasurement, clientCharacteristicConfiguration) .addBodyCompositionFeature(new BodyCompositionFeature(new byte[4])) .removeBodyCompositionMeasurement() .build(); } catch (RuntimeException e) { exception = e; } assertNotNull(exception); assertEquals("no Body Composition Measurement data", exception.getMessage()); } }
55.16208
244
0.749362
b5a0d1435c9634201ff80f9e2d5672d60a02bd75
909
package edu.wzm.tool; import org.springframework.beans.MutablePropertyValues; import org.springframework.web.servlet.mvc.method.annotation.ExtendedServletRequestDataBinder; import javax.servlet.ServletRequest; import java.util.Map; /** * @author Jimmy Wong */ public class ParamAliasDataBinder extends ExtendedServletRequestDataBinder { private final Map<String, String> renameMapping; public ParamAliasDataBinder(Object target, String objectName, Map<String, String> renameMapping) { super(target, objectName); this.renameMapping = renameMapping; } @Override protected void addBindValues(MutablePropertyValues mpvs, ServletRequest request) { super.addBindValues(mpvs, request); renameMapping.forEach((k, v) -> { if (mpvs.contains(k)){ mpvs.add(v, mpvs.getPropertyValue(k).getValue()); } }); } }
28.40625
102
0.706271
361a8fbf93c72c80bdffc0976b366e7dcceca5c8
1,065
package xyz.cirno.clever.bus; import java.util.List; import org.json.JSONObject; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; public class NavAdapter extends ArrayAdapter { private final int resourceId; public NavAdapter(Context context, int textViewResourceId, List objects) { super(context, textViewResourceId, objects); resourceId = textViewResourceId; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = LayoutInflater.from(getContext()).inflate(resourceId, null); TextView name_field = (TextView) v.findViewById(R.id.name); TextView desc_field = (TextView) v.findViewById(R.id.desc); ImageView icon_field = (ImageView) v.findViewById(R.id.icon); NavItem item = (NavItem) getItem(position); icon_field.setImageResource(item.icon); name_field.setText(item.name); desc_field.setText(item.desc); return v; } }
31.323529
75
0.781221
f19b99c49e826302512cb480996a7cda403ae1c0
3,486
package view; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.JTabbedPane; import controller.Controller; public class MainPanel extends JPanel { private static final long serialVersionUID = 1L; private InstrumentsPanel ip; private RABPanel rbp; private GroundSensorsPanel gsp; private ProximityAndLightSensorsPanel plp; private LedsPanel lp; private JTabbedPane trgb; private MsgPanel msg; private JPanel mainPanel; private Controller controller; public MainPanel(Controller c) { this.controller = c; init(); } private void init() { this.mainPanel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); this.lp = new LedsPanel(this); c.gridx = 0; c.gridy = 0; this.mainPanel.add(this.lp); //TODO: to remove /*for(int i=0; i<8; i++) { this.controller.setLedsActuator(i, 0); }*/ this.trgb = new JTabbedPane(); for(int id=0; id<3; id++) { RGBPanel rgb = new RGBPanel(id, this); this.trgb.addTab("RGB "+(id+1), null, rgb, "RGB Led Sensor "+(id+1)); } c.gridx = 1; this.mainPanel.add(this.trgb,c); this.rbp = new RABPanel(this); c.gridx = 2; c.insets = new Insets(10,8,0,0); this.mainPanel.add(this.rbp,c); c.insets = new Insets(-20,-8,0,0); JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints ct = new GridBagConstraints(); ct.gridx = 0; ct.gridy = 0; this.gsp = new GroundSensorsPanel(); this.gsp.setValue(0, 0, 0); panel.add(this.gsp,ct); ct.gridy = 1; ct.insets = new Insets(5,0,0,0); this.msg = new MsgPanel(); panel.add(this.msg,ct); c.gridx = 0; c.gridy = 1; this.mainPanel.add(panel,c); this.plp = new ProximityAndLightSensorsPanel(); c.gridx = 1; this.mainPanel.add(this.plp,c); this.ip = new InstrumentsPanel(this); c.gridx = 2; c.anchor = GridBagConstraints.SOUTHEAST; this.mainPanel.add(this.ip,c); this.mainPanel.setBorder(BorderFactory.createEmptyBorder(0,5,5,5)); this.add(this.mainPanel); } public void setGroundSensors(double[] ground) { if(ground.length == 3) { this.gsp.setValue(ground[0], ground[1], ground[2]); } } public void setProximitySensors(double[] proximity) { this.plp.setProximitySensors(proximity); } public void setLightSensors(double[] light) { this.plp.setLightSensors(light); } public void setRABSensors(String[] angleRangeData) { this.rbp.addMessage(angleRangeData); } public void setIRSensors(int[] dataAndSensorId, double[] rangeAndAngle) { } public void setMessage(String s) { this.msg.setMessage(s); } public void setWheelsActuator(double vl, double vr) { this.controller.setWheelsActuator(vl,vr); } public void setWheelsActuator(boolean enabled) { this.controller.setWheelsActuator(enabled); } public void setRGBActuator(int id, Color color) { this.plp.setRGB(id, color); this.controller.setRGBActuator(id, color); } public void setRGBActuator(int id, boolean enabled) { this.controller.setRGBActuator(id, enabled); } public void setLedsActuator(int id, int on) { //off=0, on=1, null=2 this.plp.setLed(id, on%2); this.controller.setLedsActuator(id, on); } public void setRABActuator(String[] s) { this.controller.setRABActuator(s); } public void setRABActuator(boolean enabled) { this.controller.setRABActuator(enabled); } }
23.714286
74
0.702238
1e6702f3156f7c4c092269b533b2d855a255b1f2
947
package com.synopsys.integration.util; import static org.junit.jupiter.api.Assertions.*; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; public class IntegrationEscapeUtilTest { @Test public void testEscapingForUri() { final IntegrationEscapeUtil integrationEscapeUtil = new IntegrationEscapeUtil(); assertEquals(null, integrationEscapeUtil.replaceWithUnderscore((String)null)); assertEquals("", integrationEscapeUtil.replaceWithUnderscore("")); assertEquals("_a_b_c_1_2___3", integrationEscapeUtil.replaceWithUnderscore("!a$b:c@1 2-- 3")); final List<String> messyStrings = Arrays.asList(new String[] { "#A(B)C++=", "def", "~\tgh1<>23*i.." }); final List<String> cleanStrings = Arrays.asList(new String[] { "_A_B_C___", "def", "__gh1__23_i__" }); assertEquals(cleanStrings, integrationEscapeUtil.replaceWithUnderscore(messyStrings)); } }
41.173913
111
0.724393
63dd59d5fa6a1db004754a27b5671b1c956ff4a9
592
package com.github.jiangxch.courselearningmanagement.all; import com.spring4all.swagger.EnableSwagger2Doc; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author: sanjin * @date: 2020/2/26 下午3:58 */ @SpringBootApplication( scanBasePackages = "com.github.jiangxch.courselearningmanagement" ) @EnableSwagger2Doc public class CourseLearningManagementAllApplication { public static void main(String[] args) { SpringApplication.run(CourseLearningManagementAllApplication.class, args); } }
29.6
82
0.793919
3e6578834e21c95a091038745671babb727f5839
3,998
/* * 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.pdfbox.examples.pdmodel; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.apache.pdfbox.Loader; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationRubberStamp; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceEntry; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceStream; import org.apache.pdfbox.rendering.PDFRenderer; import org.junit.jupiter.api.Test; /** * Test for RubberStampWithImage */ class TestRubberStampWithImage { @Test void test() throws IOException { String documentFile = "src/test/resources/org/apache/pdfbox/examples/pdmodel/document.pdf"; String stampFile = "src/test/resources/org/apache/pdfbox/examples/pdmodel/stamp.jpg"; String outFile = "target/test-output/TestRubberStampWithImage.pdf"; new File("target/test-output").mkdirs(); BufferedImage bim1; try (PDDocument doc1 = Loader.loadPDF(new File(documentFile))) { bim1 = new PDFRenderer(doc1).renderImage(0); } String[] args = new String[] { documentFile, outFile, stampFile }; RubberStampWithImage rubberStamp = new RubberStampWithImage(); rubberStamp.doIt(args); try (PDDocument doc2 = Loader.loadPDF(new File(outFile))) { BufferedImage bim2 = new PDFRenderer(doc2).renderImage(0); assertFalse(compareImages(bim1, bim2)); PDAnnotationRubberStamp rubberStampAnnotation = (PDAnnotationRubberStamp) doc2.getPage(0).getAnnotations().get(0); PDAppearanceDictionary appearance = rubberStampAnnotation.getAppearance(); PDAppearanceEntry normalAppearance = appearance.getNormalAppearance(); PDAppearanceStream appearanceStream = normalAppearance.getAppearanceStream(); PDImageXObject ximage = (PDImageXObject) appearanceStream.getResources().getXObject(COSName.getPDFName("Im1")); BufferedImage actualStampImage = ximage.getImage(); BufferedImage expectedStampImage = ImageIO.read(new File(stampFile)); assertTrue(compareImages(expectedStampImage, actualStampImage)); } } private boolean compareImages(BufferedImage bim1, BufferedImage bim2) { if (bim1.getWidth() != bim2.getWidth()) { return false; } if (bim1.getHeight() != bim2.getHeight()) { return false; } for (int x = 0; x < bim1.getWidth(); ++x) { for (int y = 0; y < bim1.getHeight(); ++y) { if (bim1.getRGB(x, y) != bim2.getRGB(x, y)) { return false; } } } return true; } }
38.815534
126
0.691846
9aaaac396fbf5478110b312cb846647819fc8f04
998
package edu.purdue.cs.util; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.TypeDeclaration; /** * @author XiangzheXu * create-time: 2019-02-09 */ public class SimpleCountVisitor extends ASTVisitor { private static long loc; private static long classNumber; public static void init() { loc = classNumber = 0; } public static long getLoc() { return loc; } public static long getClassNumber() { return classNumber; } @Override public boolean visit(TypeDeclaration node) { classNumber++; return super.visit(node); } @Override public boolean visit(CompilationUnit node) { int oriLength = node.toString().length(); int emittedLength = node.toString().replaceAll("\n", "").length(); int loc = oriLength - emittedLength; SimpleCountVisitor.loc += loc; return super.visit(node); } }
23.761905
74
0.650301
4b910cb15af48a3e0c2e6338050d714d8c501ee8
4,434
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.web.analytics; import java.util.List; import org.threeten.bp.Instant; import com.google.common.collect.ImmutableList; import com.opengamma.engine.marketdata.spec.MarketDataSpecification; import com.opengamma.id.UniqueId; import com.opengamma.id.VersionCorrection; import com.opengamma.util.ArgumentChecker; /** * Contains all the parameters a client needs to provide to the server to create a view for calculating portfolio * analytics. */ public class ViewRequest { /** The unique identifier of the view definition. */ private final UniqueId _viewDefinitionId; /** The unique identifier of an existing view process to attach to. */ private final UniqueId _viewProcessId; /** Used for aggregating the view's portfolio. */ private final List<String> _aggregators; /** Valuation time used by the calculation engine. */ private final Instant _valuationTime; /** Sources of market data used in the calculation in priority order. */ private final List<MarketDataSpecification> _marketDataSpecs; /** Version time and correction time for the portfolio used as a basis for the calculations. */ private final VersionCorrection _portfolioVersionCorrection; /** Whether to display blotter columns in the portfolio view showing a summary of the security details. */ private final boolean _blotter; /** * * @param viewDefinitionId The unqiue identifier of the view definition, not null * @param viewProcessId the unique identifier of an existing view process to connect to, null to use the default * @param aggregators Used for aggregating the view's portfolio, not null * @param marketDataSpecs The source(s) of market data for the view, not empty * @param valuationTime The valuation time used when calculating the analytics, can be null * @param blotter Whether to show blotter columns containing security and trade data in the portfolio grid * @param portfolioVersionCorrection Version and correction time for the portfolio used when calculating the analytics */ public ViewRequest(final UniqueId viewDefinitionId, final UniqueId viewProcessId, final List<String> aggregators, final List<MarketDataSpecification> marketDataSpecs, final Instant valuationTime, final VersionCorrection portfolioVersionCorrection, final boolean blotter) { ArgumentChecker.notNull(viewDefinitionId, "viewDefinitionId"); ArgumentChecker.notNull(aggregators, "aggregators"); ArgumentChecker.notEmpty(marketDataSpecs, "marketDataSpecs"); ArgumentChecker.notNull(portfolioVersionCorrection, "portfolioVersionCorrection"); _marketDataSpecs = marketDataSpecs; _valuationTime = valuationTime; _viewDefinitionId = viewDefinitionId; _viewProcessId = viewProcessId; _aggregators = ImmutableList.copyOf(aggregators); _portfolioVersionCorrection = portfolioVersionCorrection; _blotter = blotter; } /** * @return the unique identifier of the view definition, not null */ public UniqueId getViewDefinitionId() { return _viewDefinitionId; } /** * @return the unique identifier of an existing view process to attach to, null to use the default */ public UniqueId getViewProcessId() { return _viewProcessId; } /** * @return Used for aggregating the view's portfolio, not null but can be empty */ public List<String> getAggregators() { return _aggregators; } /** * @return Valuation time used by the calculation engine, can be null to use the default */ public Instant getValuationTime() { return _valuationTime; } /** * @return Sources of market data used in the calculation in priority order */ public List<MarketDataSpecification> getMarketDataSpecs() { return _marketDataSpecs; } /** * @return Version time and correction time for the portfolio used as a basis for the calculations */ public VersionCorrection getPortfolioVersionCorrection() { return _portfolioVersionCorrection; } /** * @return Whether to show blotter columns in the portfolio view which show a summary of the security details. */ public boolean showBlotterColumns() { return _blotter; } }
37.576271
120
0.736581
90ce4acd4cfb310ecd940792283a97eaa02258f4
1,002
package org.openstack4j.openstack.murano.v1.internal; import org.openstack4j.api.Apis; import org.openstack4j.api.murano.v1.*; /** * This class contains getters for all implementation of the available Murano services * * @author Nikolay Mahotkin */ public class MuranoService extends BaseMuranoServices implements AppCatalogService { @Override public MuranoEnvironmentService environments() { return Apis.get(MuranoEnvironmentService.class); } @Override public MuranoSessionService sessions() { return Apis.get(MuranoSessionService.class); } @Override public MuranoApplicationService services() { return Apis.get(MuranoApplicationService.class); } @Override public MuranoDeploymentService deployments() { return Apis.get(MuranoDeploymentService.class); } @Override public MuranoActionService actions() { return Apis.get(MuranoActionService.class); } }
25.692308
87
0.697605
175fb5beffb347ea5f7dcdfb20c2ffcbf7f357ab
629
public class SR{ public static void main(String args[]){ int i = 1, j = 99; System.out.print("Serie for: "); for(i=1; i<=100; i++){ if(i<=100){ System.out.print(i+", "); } } for(i=99; i>=1; i--){ if(i>1){ System.out.print(i+", "); } else{ System.out.print(i); } } //nuevo modo System.out.println(""); System.out.println(""); //nuevo modo i = 1; System.out.print("Serie for intercalada: "); for(i=1; i<=100; i++){ if(i<100){ System.out.print(i+", "); System.out.print(j+", "); } else{ System.out.print(i+", "); System.out.print(j); } j--; } } }
16.128205
46
0.503975
fafdc0790ea1d8b799edb5320416ec9d39e9688c
5,492
package com.github.ayltai.newspaper.view; import java.util.Date; import java.util.List; import javax.annotation.Nonnull; import android.graphics.Point; import androidx.annotation.CallSuper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.UiThread; import com.github.ayltai.newspaper.data.model.Image; import com.github.ayltai.newspaper.data.model.Item; import com.github.ayltai.newspaper.data.model.Video; import com.github.ayltai.newspaper.util.Irrelevant; import com.github.ayltai.newspaper.util.Optional; import io.reactivex.Flowable; public class ItemPresenter<V extends ItemPresenter.View> extends ModelPresenter<Item, V> { public interface View extends Presenter.View { @UiThread void setIcon(@Nonnull @NonNull @lombok.NonNull String iconUrl); @UiThread void setSource(@Nullable CharSequence source); @UiThread void setPublishDate(@Nullable Date date); @UiThread void setTitle(@Nullable CharSequence title); @UiThread void setDescription(@Nullable CharSequence description); @UiThread void setLink(@Nullable CharSequence link); @UiThread void setImages(@Nonnull @NonNull @lombok.NonNull List<Image> images); @UiThread void setVideos(@Nonnull @NonNull @lombok.NonNull List<Video> videos); @UiThread void setIsRead(boolean isRead); @UiThread void setIsBookmarked(boolean isBookmarked); @Nullable Flowable<Optional<Point>> clicks(); @Nullable Flowable<Irrelevant> iconClicks(); @Nullable Flowable<Irrelevant> sourceClicks(); @Nullable Flowable<Irrelevant> publishDateClicks(); @Nullable Flowable<Irrelevant> titleClicks(); @Nullable Flowable<Irrelevant> descriptionClicks(); @Nullable Flowable<Irrelevant> linkClicks(); @Nullable Flowable<Integer> imageClicks(); @Nullable Flowable<Integer> videoClicks(); @Nullable Flowable<Irrelevant> bookmarkClicks(); } @UiThread @CallSuper @Override public void bindModel() { if (this.getView() != null && this.getModel() != null) { this.getView().setIsRead(this.getModel().isRead()); this.getView().setIcon(this.getModel().getSource().getImageUrl()); this.getView().setSource(this.getModel().getSource().getDisplayName()); this.getView().setPublishDate(this.getModel().getPublishDate()); this.getView().setTitle(this.getModel().getTitle()); this.getView().setDescription(this.getModel().getDescription()); this.getView().setLink(this.getModel().getUrl()); this.getView().setIsBookmarked(this.getModel().isBookmarked()); this.getView().setImages(this.getModel().getImages()); this.getView().setVideos(this.getModel().getVideos()); } } @CallSuper @Override public void onViewAttached(@NonNull final V view, final boolean isFirstTimeAttachment) { super.onViewAttached(view, isFirstTimeAttachment); if (view.clicks() != null) this.manageDisposable(view.clicks().subscribe(this::onClick)); if (view.iconClicks() != null) this.manageDisposable(view.iconClicks().subscribe(irrelevant -> this.onIconClick())); if (view.sourceClicks() != null) this.manageDisposable(view.sourceClicks().subscribe(irrelevant -> this.onSourceClick())); if (view.publishDateClicks() != null) this.manageDisposable(view.publishDateClicks().subscribe(irrelevant -> this.onPublishDateClick())); if (view.titleClicks() != null) this.manageDisposable(view.titleClicks().subscribe(irrelevant -> this.onTitleClick())); if (view.descriptionClicks() != null) this.manageDisposable(view.descriptionClicks().subscribe(irrelevant -> this.onDescriptionClick())); if (view.linkClicks() != null) this.manageDisposable(view.linkClicks().subscribe(irrelevant -> this.onLinkClick())); if (view.bookmarkClicks() != null) this.manageDisposable(view.bookmarkClicks().subscribe(irrelevant -> this.onBookmarkClick())); if (view.imageClicks() != null) this.manageDisposable(view.imageClicks().subscribe(index -> this.onImageClick(this.getModel().getImages().get(index)))); if (view.videoClicks() != null) this.manageDisposable(view.videoClicks().subscribe(index -> this.onVideoClick(this.getModel().getVideos().get(index)))); } @CallSuper protected void onClick(@NonNull final Optional<Point> location) { if (this.getView() != null) { this.getView().setIsRead(true); final Item item = this.getModel(); //if (!DevUtils.isRunningUnitTest()) Flow.get(this.getView().getContext()).set(DetailsView.Key.create(item, location.isPresent() ? location.get() : null)); } } protected void onIconClick() { } protected void onSourceClick() { } protected void onPublishDateClick() { } protected void onTitleClick() { } protected void onDescriptionClick() { } protected void onLinkClick() { } protected void onBookmarkClick() { } protected void onImageClick(@Nonnull @NonNull @lombok.NonNull final Image image) { } protected void onVideoClick(@Nonnull @NonNull @lombok.NonNull final Video video) { } }
34.540881
167
0.671522
b0c5ef509ee597ecc2852ffbf3d6b722cf69fa8b
1,682
/** Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags 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 bftsmart.tom.core.messages; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; public class SerializationTest { /** * @param args * the command line arguments */ public static void main(String[] args) throws Exception { // TODO code application logic here TOMMessage tm = new TOMMessage(0, 0, 0, 0, new String("abc").getBytes(), 0, TOMMessageType.ORDERED_REQUEST); ByteArrayOutputStream baos = new ByteArrayOutputStream(4); DataOutputStream oos = new DataOutputStream(baos); tm.wExternal(oos); oos.flush(); // oos.writeObject(tm); byte[] message = baos.toByteArray(); System.out.println(message.length); ByteArrayInputStream bais = new ByteArrayInputStream(message); DataInputStream ois = new DataInputStream(bais); // TOMMessage tm2 = (TOMMessage) ois.readObject(); TOMMessage tm2 = new TOMMessage(); tm2.rExternal(ois); // System.out.println(new String(tm2.getContent())); } }
31.148148
117
0.752675
d1b77793bac3a98b76abcaa28b012bec0f98ff21
1,626
package com.evanxie.yelang.web.commons; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.webapp.WebAppContext; public class StartWeb { public static void main(String[] args){ Server server = new Server(); server.setStopAtShutdown(true); SelectChannelConnector connector = new SelectChannelConnector(); connector.setReuseAddress(false); //Configuration config=ApplicationProperties.get(); //int port=config.getInt("sysimple.webserver.port", DefaultConfiguration.SYSIMPLE_WEBSERVER_PORT.getInt()); connector.setPort(3000); server.setConnectors(new Connector[]{connector}); WebAppContext webAppContext; if(args.length==0){ webAppContext = new WebAppContext("src/main/webapp","/"); webAppContext.setDescriptor("src/main/webapp/WEB-INF/web.xml"); webAppContext.setResourceBase("src/main/webapp"); }else{ webAppContext = new WebAppContext(); webAppContext.setWar(args[0]); } webAppContext.setDisplayName("jetty"); webAppContext.setClassLoader(Thread.currentThread().getContextClassLoader()); webAppContext.setConfigurationDiscovered(true); webAppContext.setParentLoaderPriority(true); server.setHandler(webAppContext); try{ server.start(); System.out.println("********************************************************"); System.out.println("The Yelang Has Started !!!"); }catch(Exception e){ } } }
41.692308
110
0.669742
b172fc7e32f1364a94f61d55e77792c72a6c6335
1,322
/* * Copyright (c) 2018 Bixbit - Krzysztof Benedyczak. All rights reserved. * See LICENCE.txt file for licensing information. */ package io.imunity.upman.groups; import pl.edu.icm.unity.engine.api.project.DelegatedGroup; import pl.edu.icm.unity.webui.common.Images; /** * Tree node used in {@link GroupsTree} * * @author P.Piernik * */ class GroupNode { public final DelegatedGroup group; public final GroupNode parent; public final String htmlPrivacyIcon; public final String htmlIcon; public GroupNode(DelegatedGroup group) { this(group, null); } public GroupNode(DelegatedGroup group, GroupNode parent) { this.group = group; this.parent = parent; this.htmlPrivacyIcon = group.open ? Images.padlock_unlock.getHtml() : ""; this.htmlIcon = group.delegationConfiguration.enabled ? Images.workplace.getHtml() : ""; } public String getPath() { return group.path; } @Override public String toString() { return group.displayedName; } public boolean isOpen() { return group.open; } @Override public int hashCode() { return group.hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof String) return group.path.equals(obj); if (obj instanceof GroupNode) return group.path.equals(((GroupNode) obj).group.path); return false; } }
19.15942
90
0.717852
843785d2cccca083106b3eb3cf0e8cff3776d09b
538
package se.sundsvall.messaging.integration.smssender; import java.time.Duration; import org.springframework.boot.context.properties.ConfigurationProperties; import se.sundsvall.messaging.integration.AbstractRestIntegrationProperties; import lombok.Getter; import lombok.Setter; @Getter @Setter @ConfigurationProperties(prefix = "integration.sms-sender") public class SmsSenderIntegrationProperties extends AbstractRestIntegrationProperties { private Duration pollDelay = Duration.ofSeconds(5); private int maxRetries = 3; }
26.9
87
0.832714
5c0aaf3eaba1d294a4ded85d643367d3c939d26f
1,503
// Generated from io\onedev\server\u005Cutil\u005Cusermatch\UserMatch.g4 by ANTLR 4.7.2 package io.onedev.server.util.usermatch; import org.antlr.v4.runtime.tree.ParseTreeVisitor; /** * This interface defines a complete generic visitor for a parse tree produced * by {@link UserMatchParser}. * * @param <T> The return type of the visit operation. Use {@link Void} for * operations with no return type. */ public interface UserMatchVisitor<T> extends ParseTreeVisitor<T> { /** * Visit a parse tree produced by {@link UserMatchParser#userMatch}. * @param ctx the parse tree * @return the visitor result */ T visitUserMatch(UserMatchParser.UserMatchContext ctx); /** * Visit a parse tree produced by {@link UserMatchParser#criteria}. * @param ctx the parse tree * @return the visitor result */ T visitCriteria(UserMatchParser.CriteriaContext ctx); /** * Visit a parse tree produced by {@link UserMatchParser#exceptCriteria}. * @param ctx the parse tree * @return the visitor result */ T visitExceptCriteria(UserMatchParser.ExceptCriteriaContext ctx); /** * Visit a parse tree produced by {@link UserMatchParser#userCriteria}. * @param ctx the parse tree * @return the visitor result */ T visitUserCriteria(UserMatchParser.UserCriteriaContext ctx); /** * Visit a parse tree produced by {@link UserMatchParser#groupCriteria}. * @param ctx the parse tree * @return the visitor result */ T visitGroupCriteria(UserMatchParser.GroupCriteriaContext ctx); }
34.953488
87
0.745176
cadcabbcf3d8abe57d8f91d712923832732f7dbc
516
package co.lq.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import lombok.Data; /** * reids相关配置 * * @author billy * @since 2020-02-27 */ @Data @Configuration @ConfigurationProperties(prefix = "spring.redis") public class RedisConfigProperties { private String host = "host"; private String port = "port"; private String password = "password"; private String database = "database"; }
20.64
75
0.73062
064778bb6b58f7057ddbdc155ed0b6c39435f606
3,672
/* Copyright 2020 Luzhuo. 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 me.luzhuo.lib_core.ui.calculation; import android.content.Context; import android.content.res.Resources; import android.graphics.Paint; import android.graphics.Rect; import android.util.DisplayMetrics; import android.view.View; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.TextView; /** * Description: UI计算 * * @Author: Luzhuo * @Creation Date: 2020/5/27 23:19 * @Copyright: Copyright 2020 Luzhuo. All rights reserved. **/ public class UICalculation { private Context context; public UICalculation(Context context){ this.context = context.getApplicationContext(); } /** * dp to px * @param dp * @return px */ public int dp2px(float dp){ float density = context.getResources().getDisplayMetrics().density; return (int) (dp * density + 0.5f); } /** * px to dp * @param px * @return dp */ public int px2dp(float px) { final float density = context.getResources().getDisplayMetrics().density; return (int) (px / density + 0.5f); } /** * 获取屏幕宽高 * get width and height form phone display * @return wh [width, height] */ public int[] getDisplay() { final Resources res = context.getResources(); int width = res.getDisplayMetrics().widthPixels; int height = res.getDisplayMetrics().heightPixels; return new int[]{width, height}; } /** * 获取根据屏幕缩小指定比例的 LayoutParams * get LayoutParams from scaled by display * * Example: * <pre> * Button.setLayoutParams(DisplayMatchUtils.getParamsScale(0.5f,null)); * </pre> * * @param widthScale 0.5f(50%) or null(MATCH_PARENT), [0f,1f] * @param heightScale 0.5f(50%) or null(MATCH_PARENT), [0f,1f] * @return */ public LinearLayout.LayoutParams getParamsScale(Float widthScale, Float heightScale) { int[] wh = getDisplay(); int width = wh[0]; int height = wh[1]; int widthParams = LinearLayout.LayoutParams.MATCH_PARENT; int heightParams = LinearLayout.LayoutParams.MATCH_PARENT; if(widthScale != null) widthParams = (int) (width * widthScale + 0.5f); if(heightScale != null) heightParams = (int) (height * heightScale + 0.5f); return new LinearLayout.LayoutParams(widthParams, heightParams); } /** * 获取 statusbar 高度 * get statusbar hieght * @param v * @return */ public int getStatusBarHeight(View v) { if (v == null) return 0; Rect frame = new Rect(); v.getWindowVisibleDisplayFrame(frame); return frame.top; } /** * 从 textview 获取字体高度 * get font height by textview * @param textView * @return */ public int getFontHeight(TextView textView) { Paint paint = new Paint(); paint.setTextSize(textView.getTextSize()); Paint.FontMetrics fm = paint.getFontMetrics(); return (int) Math.ceil(fm.bottom - fm.top); } }
28.913386
90
0.644608
7ec9b0f20a0f6543f178524c5c158f9db617e013
1,536
/** * */ package com.xnzk.flash.meta; import org.eclipse.emf.ecore.EFactory; /** * <!-- begin-user-doc --> * The <b>Factory</b> for the model. * It provides a create method for each non-abstract class of the model. * <!-- end-user-doc --> * @see com.xnzk.flash.meta.MetaPackage * @generated */ public interface MetaFactory extends EFactory { /** * The singleton instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ MetaFactory eINSTANCE = com.xnzk.flash.meta.impl.MetaFactoryImpl.init(); /** * Returns a new object of class '<em>Base Entity</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Base Entity</em>'. * @generated */ BaseEntity createBaseEntity(); /** * Returns a new object of class '<em>Audit</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Audit</em>'. * @generated */ Audit createAudit(); /** * Returns a new object of class '<em>Named</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Named</em>'. * @generated */ Named createNamed(); /** * Returns the package supported by this factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the package supported by this factory. * @generated */ MetaPackage getMetaPackage(); } //MetaFactory
24.774194
76
0.558594
1f1da7ee9570813b39c866c5579f7c777447332e
9,480
/** * Copyright 2014 University of Patras * * 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 gr.upatras.ece.nam.baker.impl; import gr.upatras.ece.nam.baker.model.IRepositoryWebClient; import gr.upatras.ece.nam.baker.model.InstalledBun; import gr.upatras.ece.nam.baker.model.InstalledBunStatus; import gr.upatras.ece.nam.baker.model.BunMetadata; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.nio.file.Path; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.ExecuteException; import org.apache.commons.exec.Executor; import org.apache.commons.exec.PumpStreamHandler; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class InstalledBunLifecycleMgmt { private static final transient Log logger = LogFactory.getLog(InstalledBunLifecycleMgmt.class.getName()); InstalledBun installedBun; IRepositoryWebClient repoWebClient; BakerJpaController bakerJpaController; private InstalledBunStatus targetStatus; private Boolean restartTriggered = false; private BunMetadata bunMetadata = null; public InstalledBunLifecycleMgmt(InstalledBun b, IRepositoryWebClient rwc, BakerJpaController jpactr, InstalledBunStatus ts) { installedBun = b; repoWebClient = rwc; bakerJpaController = jpactr; targetStatus = ts; logger.info("ServiceLifecycleMgmt uuid:" + installedBun.getUuid() + " name:" + installedBun.getName()); processState(); } public void processState() { logger.info("Task for uuid:" + installedBun.getUuid() + " is:" + installedBun.getStatus()); InstalledBunStatus entryState = installedBun.getStatus(); //this is used to restart the service. usefull if reconfiguring. if ((targetStatus == InstalledBunStatus.STARTED) && (entryState == InstalledBunStatus.STARTED ) && (!restartTriggered) ){ logger.info("Entry and Target state are STARTED. A restart will be triggered, with confguration applied."); restartTriggered = true; }else restartTriggered = false; switch (entryState) { case INIT: downLoadMetadataInfo(); break; case DOWNLOADING: if (targetStatus == InstalledBunStatus.STOPPED) { installedBun.setStatus(InstalledBunStatus.STOPPING); } else if (targetStatus == InstalledBunStatus.UNINSTALLED) { installedBun.setStatus(InstalledBunStatus.STOPPING); }else{ startPackageDownloading(); } break; case DOWNLOADED: if (targetStatus == InstalledBunStatus.STOPPED) { installedBun.setStatus(InstalledBunStatus.STOPPING); } else if (targetStatus == InstalledBunStatus.UNINSTALLED) { installedBun.setStatus(InstalledBunStatus.STOPPING); }else{ startPackageInstallation(); } break; case INSTALLING: break; case INSTALLED: execInstalledPhase(); break; case CONFIGURING: execConfiguringPhase(); break; case STARTING: execStartingPhase(); break; case STARTED: if (targetStatus == InstalledBunStatus.STOPPED) { installedBun.setStatus(InstalledBunStatus.STOPPING); } else if (targetStatus == InstalledBunStatus.UNINSTALLED) { installedBun.setStatus(InstalledBunStatus.STOPPING); } else if ( (targetStatus == InstalledBunStatus.STARTED) && restartTriggered) { installedBun.setStatus(InstalledBunStatus.STOPPING); } break; case STOPPING: execStoppingPhase(); break; case STOPPED: if (targetStatus == InstalledBunStatus.UNINSTALLED) { installedBun.setStatus(InstalledBunStatus.UNINSTALLING); } else if (targetStatus == InstalledBunStatus.STARTED) { installedBun.setStatus(InstalledBunStatus.CONFIGURING); } break; case UNINSTALLING: execUninstallingPhase(); break; case UNINSTALLED: break; default: break; } bakerJpaController.updateInstalledBun(installedBun); if ((targetStatus != installedBun.getStatus()) && (installedBun.getStatus() != InstalledBunStatus.FAILED)) processState(); } private void downLoadMetadataInfo() { logger.info("Downloading metadata info..."); bunMetadata = null; if (repoWebClient != null) bunMetadata = repoWebClient.fetchMetadata(installedBun.getUuid(), installedBun.getRepoUrl()); else logger.info("repoWebClient == null...FAILED PLEASE CHECK"); if (bunMetadata != null) { installedBun.setStatus(InstalledBunStatus.DOWNLOADING); } else { logger.info("smetadata == null...FAILED"); installedBun.setStatus(InstalledBunStatus.FAILED); } } private void startPackageDownloading() { logger.info("Downloading installation package: " + bunMetadata.getPackageLocation() ); Path destFile = repoWebClient.fetchPackageFromLocation(installedBun.getUuid(), bunMetadata.getPackageLocation()); if ((destFile != null) && (extractPackage(destFile) == 0)) { installedBun.setStatus(InstalledBunStatus.DOWNLOADED); Path packageLocalPath = destFile.getParent(); installedBun.setPackageLocalPath(packageLocalPath.toString()); } else { logger.info("FAILED Downloading installation package from: " + bunMetadata.getPackageLocation()); installedBun.setStatus(InstalledBunStatus.FAILED); } } public int extractPackage(Path targetPath) { String cmdStr = "tar --strip-components=1 -xvzf " + targetPath + " -C " + targetPath.getParent() + File.separator; return executeSystemCommand(cmdStr); } private void startPackageInstallation() { installedBun.setStatus(InstalledBunStatus.INSTALLING); logger.info("Installing..."); String cmdStr = installedBun.getPackageLocalPath() + "/recipes/onInstall"; logger.info("Will execute recipe 'onInstall' of:" + cmdStr); if (executeSystemCommand(cmdStr) == 0) { installedBun.setStatus(InstalledBunStatus.INSTALLED); } else installedBun.setStatus(InstalledBunStatus.FAILED); } private void execInstalledPhase() { logger.info("execInstalledPhase..."); String cmdStr = installedBun.getPackageLocalPath() + "/recipes/onInstallFinish"; logger.info("Will execute recipe 'onInstallFinish' of:" + cmdStr); executeSystemCommand(cmdStr); // we don't care for the exit code if (executeSystemCommand(cmdStr) == 0) { installedBun.setStatus(InstalledBunStatus.CONFIGURING); installedBun.setName(bunMetadata.getName()); installedBun.setPackageURL(bunMetadata.getPackageLocation() ); installedBun.setInstalledVersion(bunMetadata.getVersion()); } else installedBun.setStatus(InstalledBunStatus.FAILED); } private void execConfiguringPhase() { logger.info("execInstalledPhase..."); String cmdStr = installedBun.getPackageLocalPath() + "/recipes/onApplyConf"; logger.info("Will execute recipe 'onApplyConf' of:" + cmdStr); executeSystemCommand(cmdStr); // we don't care for the exit code if (executeSystemCommand(cmdStr) == 0) { installedBun.setStatus(InstalledBunStatus.STARTING); } else installedBun.setStatus(InstalledBunStatus.FAILED); } private void execStartingPhase() { logger.info("execStartingPhase..."); String cmdStr = installedBun.getPackageLocalPath() + "/recipes/onStart"; logger.info("Will execute recipe 'onStart' of:" + cmdStr); if (executeSystemCommand(cmdStr) == 0) { installedBun.setStatus(InstalledBunStatus.STARTED); } else installedBun.setStatus(InstalledBunStatus.STOPPED); } private void execStoppingPhase() { logger.info("execStoppingPhase..."); String cmdStr = installedBun.getPackageLocalPath() + "/recipes/onStop"; logger.info("Will execute recipe 'onStop' of:" + cmdStr); // if (executeSystemCommand(cmdStr) == 0) { // whatever is the return value...it will go to stopped executeSystemCommand(cmdStr); installedBun.setStatus(InstalledBunStatus.STOPPED); } private void execUninstallingPhase() { logger.info("execUninstallingPhase..."); String cmdStr = installedBun.getPackageLocalPath() + "/recipes/onUninstall"; logger.info("Will execute recipe 'onUninstall' of:" + cmdStr); // if (executeSystemCommand(cmdStr) == 0) { // whatever is the return value...it will go to stopped executeSystemCommand(cmdStr); installedBun.setStatus(InstalledBunStatus.UNINSTALLED); } public int executeSystemCommand(String cmdStr) { logger.info(" ================> Execute :" + cmdStr); CommandLine cmdLine = CommandLine.parse(cmdStr); final Executor executor = new DefaultExecutor(); // create the executor and consider the exitValue '0' as success executor.setExitValue(0); ByteArrayOutputStream out = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(out); executor.setStreamHandler(streamHandler); int exitValue = -1; try { exitValue = executor.execute(cmdLine); logger.info(" ================> EXIT ("+exitValue+") FROM :" + cmdStr); } catch (ExecuteException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } logger.info("out>" + out); return exitValue; } }
30.384615
127
0.739979
5e7152acd6abd160f91bd1cf9e9de73e912fa84a
5,570
/* * Copyright 2018 Alfresco, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.cloud.events.adapter; import org.activiti.cloud.events.adapter.util.EventReceiverUtil; import org.activiti.cloud.events.adapter.util.TestUtil; import org.activiti.cloud.services.events.adapter.streams.EventsAdapterConsumerChannel; import org.apache.activemq.junit.EmbeddedActiveMQBroker; import org.junit.After; import org.junit.AfterClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.integration.channel.AbstractMessageChannel; import org.springframework.messaging.support.GenericMessage; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest public class ActivitiCloudEventsAdapterTest { @ClassRule public static EmbeddedActiveMQBroker broker = new EmbeddedActiveMQBroker(); private static ApplicationContext applicationContext; @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") @Autowired private EventsAdapterConsumerChannel channel; @Autowired private EventReceiverUtil receiverUtil; @Autowired private void setContext(ApplicationContext applicationContext) { ActivitiCloudEventsAdapterTest.applicationContext = applicationContext; } @AfterClass public static void afterClass() { ((ConfigurableApplicationContext) applicationContext).close(); } @After public void tearDown() { receiverUtil.reset(); } @Test public void testProcessStartedEvent() throws Exception { AbstractMessageChannel adapterConsumer = (AbstractMessageChannel) this.channel.eventsAdapterConsumer(); final String payload = getEventResourceAsString("aggregated-processStarted.json"); adapterConsumer.send(new GenericMessage<>(payload)); // wait for a few seconds to get all the messages await().untilAsserted(() -> { List<String> result = receiverUtil.getEvents(); assertEquals("11 events must have been sent.", 11, result.size()); //Checked the received events checkExpectedJson(getEventResourceAsString("public-processCreated-01.json"), result.get(0)); checkExpectedJson(getEventResourceAsString("public-variableCreated-02.json"), result.get(1)); checkExpectedJson(getEventResourceAsString("public-variableCreated-03.json"), result.get(2)); checkExpectedJson(getEventResourceAsString("public-variableCreated-04.json"), result.get(3)); checkExpectedJson(getEventResourceAsString("public-processStarted-05.json"), result.get(4)); checkExpectedJson(getEventResourceAsString("public-activityStarted-06.json"), result.get(5)); checkExpectedJson(getEventResourceAsString("public-activityCompleted-07.json"), result.get(6)); checkExpectedJson(getEventResourceAsString("public-sequenceFlowTaken-08.json"), result.get(7)); checkExpectedJson(getEventResourceAsString("public-activityStarted-09.json"), result.get(8)); checkExpectedJson(getEventResourceAsString("public-taskCandidateGroupAdded-10.json"), result.get(9)); checkExpectedJson(getEventResourceAsString("public-taskCreated-11.json"), result.get(10)); }); } @Test public void testTaskAssignedEvent() throws Exception { AbstractMessageChannel adapterConsumer = (AbstractMessageChannel) this.channel.eventsAdapterConsumer(); final String payload = getEventResourceAsString("aggregated-taskAssigned.json"); adapterConsumer.send(new GenericMessage<>(payload)); // wait for a few seconds to get all the messages await().untilAsserted(()->{ List<String> result = receiverUtil.getEvents(); assertEquals("1 event must have been sent.", 1, result.size()); //Checked the received events checkExpectedJson(getEventResourceAsString("public-taskAssigned.json"), result.get(0)); }); } private void checkExpectedJson(String expectedJsonBody, String actualJsonBody) throws Exception { // Enable strict mode - as we require all of the elements requested to be returned. // We can do that as our arrays of elements are always returned in the same order. JSONAssert.assertEquals(expectedJsonBody, actualJsonBody, true); } private String getEventResourceAsString(String eventFileName) throws Exception { return TestUtil.getResourceFileAsString("events/" + eventFileName); } }
44.919355
113
0.744524
a294b97e4ee6e12bc9e2ad429820b42bde12090b
1,411
/* * 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.aliyuncs.marketing_event.transform.v20210101; import com.aliyuncs.marketing_event.model.v20210101.SyncSignInInfoResponse; import com.aliyuncs.transform.UnmarshallerContext; public class SyncSignInInfoResponseUnmarshaller { public static SyncSignInInfoResponse unmarshall(SyncSignInInfoResponse syncSignInInfoResponse, UnmarshallerContext _ctx) { syncSignInInfoResponse.setRequestId(_ctx.stringValue("SyncSignInInfoResponse.RequestId")); syncSignInInfoResponse.setCode(_ctx.stringValue("SyncSignInInfoResponse.Code")); syncSignInInfoResponse.setSuccess(_ctx.booleanValue("SyncSignInInfoResponse.Success")); syncSignInInfoResponse.setMessage(_ctx.stringValue("SyncSignInInfoResponse.Message")); syncSignInInfoResponse.setData(_ctx.integerValue("SyncSignInInfoResponse.Data")); return syncSignInInfoResponse; } }
42.757576
123
0.80652
0e8e6b1235d953caf5cd9830617c44e4be7d2ddf
576
package org.jessenpan.leetcode.binarysearch; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * @author jessenpan * tag:binarysearch */ public class S658FindKClosestElements { public List<Integer> findClosestElements(int[] arr, int k, int x) { List<Integer> list = Arrays.stream(arr).boxed().sorted((a, b) -> a.equals(b) ? a - b : Math.abs(a-x) - Math.abs(b-x)).collect(Collectors.toList()); list = list.subList(0, k); Collections.sort(list); return list; } }
26.181818
155
0.671875
e197af1bb41dd258739a066d06e61286d5c7867c
1,821
/******************************************************************************* * Copyright (c) 2020 DisCo Group - Universidad de Zaragoza. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 1.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-1.0/ * * SPDX-License-Identifier: EPL-1.0 * * Contributors: * Abel Gómez * Ignacio Requeno * Diego Pérez *******************************************************************************/ package es.unizar.disco.simulation.models.definition.impl; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import org.apache.commons.lang.StringUtils; import org.eclipse.emf.ecore.util.EcoreUtil; import es.unizar.disco.simulation.models.datatypes.DatatypesPackage; import es.unizar.disco.simulation.models.definition.DefinitionFactory; import es.unizar.disco.simulation.models.definition.InputVariableValue; public class CustomInputVariableImpl extends InputVariableImpl { private static final String DELIM = ","; @Override public String serializeValues() { List<String> values = new ArrayList<>(); for (InputVariableValue value : getValues()) { values.add(value.getValue().toString()); } return StringUtils.join(values.toArray(), DELIM); } @Override public void deserializeValues(String values) { StringTokenizer tokenizer = new StringTokenizer(values, DELIM); while (tokenizer.hasMoreElements()) { String token = tokenizer.nextToken(); InputVariableValue value = DefinitionFactory.eINSTANCE.createInputVariableValue(); Number number = (Number) EcoreUtil.createFromString(DatatypesPackage.Literals.NUMBER, token); value.setValue(number); getValues().add(value); } } }
33.722222
96
0.694124
0420c3081529888e9b8f86ebcdd5b1500d7caf64
658
package fr.formation.view.beans; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; @ManagedBean @RequestScoped public class Page4Bean implements Serializable{ private static final long serialVersionUID = 1L; private String nom; private String prenom; public Page4Bean() { super(); } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public String getPrenom() { return prenom; } public void setPrenom(String prenom) { this.prenom = prenom; } public String go() { return "page4"; // return "page4?faces-redirect=true"; } }
15.666667
49
0.715805
4dad4327b99ac13ba714824ea123b284e74d97a7
96
package jp.ossc.nimbus.service.trade; public class IndexTimeSeries extends TimeSeries{ }
13.714286
48
0.770833
ffaee37a84b95e8611223adff0fcd995a6ef700b
459
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pl.altkom.gemalto.spring.service; import pl.altkom.gemalto.spring.model.Customer; /** * * @author admin */ public interface CustomerService { void create(Customer customer); Customer loadById(long id); void save(Iterable<Customer> list); }
19.125
79
0.716776
dc8c82d6d695328b5bdf7efa96f55d45b915e95e
345
package kotlin; @Metadata(mo40251bv = {1, 0, 3}, mo40252d1 = {"kotlin/NumbersKt__BigDecimalsKt", "kotlin/NumbersKt__BigIntegersKt", "kotlin/NumbersKt__NumbersJVMKt", "kotlin/NumbersKt__NumbersKt"}, mo40254k = 4, mo40255mv = {1, 4, 1}, mo40257xi = 1) public final class NumbersKt extends NumbersKt__NumbersKt { private NumbersKt() { } }
43.125
233
0.742029
accb3568edc6add02a049c7aa11262191e020a34
2,097
package net.violet.platform.api.actions.storecities; import java.util.LinkedList; import java.util.List; import net.violet.platform.api.actions.AbstractAction; import net.violet.platform.api.actions.ActionParam; import net.violet.platform.api.exceptions.APIErrorMessage; import net.violet.platform.api.exceptions.InvalidDataException; import net.violet.platform.api.exceptions.InvalidParameterException; import net.violet.platform.api.maps.store.StoreCityInformationMap; import net.violet.platform.datamodel.Application; import net.violet.platform.datamodel.Application.ApplicationClass; import net.violet.platform.dataobjects.CountryData; import net.violet.platform.dataobjects.StoreCityData; import net.violet.platform.util.Constantes; public class GetStoreCities extends AbstractAction { @Override protected Object doProcessRequest(ActionParam inParam) throws InvalidParameterException, InvalidDataException { final String theCountryCode = inParam.getMainParamAsString(); CountryData theCountry = null; theCountry = CountryData.findByCode(theCountryCode); if (theCountry == null) { throw new InvalidDataException(APIErrorMessage.NO_SUCH_COUNTRY); } final List<StoreCityInformationMap> theCityInformationList = new LinkedList<StoreCityInformationMap>(); final List<StoreCityData> aux = StoreCityData.getByCountry(theCountry); for (final StoreCityData inCity : aux) { theCityInformationList.add(new StoreCityInformationMap(inCity)); } return theCityInformationList; } /** * @see net.violet.platform.api.actions.Action#isCacheable() */ public boolean isCacheable() { return true; } /** * User informations may be cached one day * * @see net.violet.platform.api.actions.Action#getExpirationTime() */ public long getExpirationTime() { return Constantes.ONE_DAY_IN_S; } /** * Read Only action * * @see net.violet.platform.api.actions.Action#getType() */ public ActionType getType() { return ActionType.GET; } @Override public List<ApplicationClass> getAuthorizedApplicationClasses() { return Application.CLASSES_UI; } }
31.298507
112
0.793038
26e8bae0cd61fff4dafdce7dd625bb65809d72c5
4,309
package com.kunminx.samples.ui.operators; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.kunminx.samples.R; import com.kunminx.samples.utils.AppConstant; import io.reactivex.rxjava3.core.Observer; import io.reactivex.rxjava3.disposables.Disposable; import io.reactivex.rxjava3.subjects.BehaviorSubject; /** * Created by amitshekhar on 17/12/16. */ public class BehaviorSubjectExampleFragment extends Fragment { private static final String TAG = BehaviorSubjectExampleFragment.class.getSimpleName(); Button btn; TextView textView; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_example, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); btn = view.findViewById(R.id.btn); textView = view.findViewById(R.id.textView); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { doSomeWork(); } }); } /* When an observer subscribes to a BehaviorSubject, it begins by emitting the item most * recently emitted by the source Observable (or a seed/default value if none has yet been * emitted) and then continues to emit any other items emitted later by the source Observable(s). * It is different from Async Subject as async emits the last value (and only the last value) * but the Behavior Subject emits the last and the subsequent values also. */ private void doSomeWork() { BehaviorSubject<Integer> source = BehaviorSubject.create(); source.subscribe(getFirstObserver()); // it will get 1, 2, 3, 4 and onComplete source.onNext(1); source.onNext(2); source.onNext(3); /* * it will emit 3(last emitted), 4 and onComplete for second observer also. */ source.subscribe(getSecondObserver()); source.onNext(4); source.onComplete(); } private Observer<Integer> getFirstObserver() { return new Observer<Integer>() { @Override public void onSubscribe(Disposable d) { Log.d(TAG, " First onSubscribe : " + d.isDisposed()); } @Override public void onNext(Integer value) { textView.append(" First onNext : value : " + value); textView.append(AppConstant.LINE_SEPARATOR); Log.d(TAG, " First onNext value : " + value); } @Override public void onError(Throwable e) { textView.append(" First onError : " + e.getMessage()); textView.append(AppConstant.LINE_SEPARATOR); Log.d(TAG, " First onError : " + e.getMessage()); } @Override public void onComplete() { textView.append(" First onComplete"); textView.append(AppConstant.LINE_SEPARATOR); Log.d(TAG, " First onComplete"); } }; } private Observer<Integer> getSecondObserver() { return new Observer<Integer>() { @Override public void onSubscribe(Disposable d) { textView.append(" Second onSubscribe : isDisposed :" + d.isDisposed()); Log.d(TAG, " Second onSubscribe : " + d.isDisposed()); textView.append(AppConstant.LINE_SEPARATOR); } @Override public void onNext(Integer value) { textView.append(" Second onNext : value : " + value); textView.append(AppConstant.LINE_SEPARATOR); Log.d(TAG, " Second onNext value : " + value); } @Override public void onError(Throwable e) { textView.append(" Second onError : " + e.getMessage()); textView.append(AppConstant.LINE_SEPARATOR); Log.d(TAG, " Second onError : " + e.getMessage()); } @Override public void onComplete() { textView.append(" Second onComplete"); textView.append(AppConstant.LINE_SEPARATOR); Log.d(TAG, " Second onComplete"); } }; } }
29.923611
130
0.678116
019e821893188310478c3a23a497ebca6166f443
3,674
/* Copyright 2009-2016 Igor Polevoy 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.javalite.activejdbc; import org.javalite.activejdbc.associations.Many2ManyAssociation; import org.javalite.activejdbc.logging.LogFilter; import org.javalite.activejdbc.logging.LogLevel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * @author Igor Polevoy */ class MetaModels { private static final Logger LOGGER = LoggerFactory.getLogger(MetaModels.class); private final Map<String, MetaModel> metaModelsByTableName = new CaseInsensitiveMap<>(); private final Map<String, MetaModel> metaModelsByClassName = new HashMap<>(); //these are all many to many associations across all models. private final List<Many2ManyAssociation> many2ManyAssociations = new ArrayList<>(); void addMetaModel(MetaModel mm, Class<? extends Model> modelClass) { Object o = metaModelsByClassName.put(modelClass.getName(), mm); if (o != null) { LogFilter.log(LOGGER, LogLevel.WARNING, "Double-register: {}: {}", modelClass, o); } o = metaModelsByTableName.put(mm.getTableName(), mm); many2ManyAssociations.addAll(mm.getManyToManyAssociations(Collections.<Association>emptyList())); if (o != null) { LogFilter.log(LOGGER, LogLevel.WARNING, "Double-register: {}: {}", mm.getTableName(), o); } } MetaModel getMetaModel(Class<? extends Model> modelClass) { return metaModelsByClassName.get(modelClass.getName()); } MetaModel getMetaModel(String tableName) { return metaModelsByTableName.get(tableName); } String[] getTableNames(String dbName) { ArrayList<String> tableNames = new ArrayList<>(); for (MetaModel metaModel : metaModelsByTableName.values()) { if (metaModel.getDbName().equals(dbName)) tableNames.add(metaModel.getTableName()); } return tableNames.toArray(new String[tableNames.size()]); } Class<? extends Model> getModelClass(String tableName) { MetaModel mm = metaModelsByTableName.get(tableName); return mm == null ? null : mm.getModelClass(); } String getTableName(Class<? extends Model> modelClass) { return metaModelsByClassName.containsKey(modelClass.getName())? metaModelsByClassName.get(modelClass.getName()).getTableName():null; } public void setColumnMetadata(String table, Map<String, ColumnMetadata> metaParams) { metaModelsByTableName.get(table).setColumnMetadata(metaParams); } /** * An edge is a table in a many to many relationship that is not a join. * * @param join join table * * @return edges for a join. */ protected List<String> getEdges(String join) { List<String> results = new ArrayList<>(); for (Many2ManyAssociation a : many2ManyAssociations) { if (a.getJoin().equalsIgnoreCase(join)) { results.add(getMetaModel(a.getSourceClass()).getTableName()); results.add(getMetaModel(a.getTargetClass()).getTableName()); } } return results; } }
36.74
105
0.689711
6aa9261cb45e71a8ed9b95cbc93f892cb9bb5078
450
package myCB.gui.element; public class Point { int x, y, printX, printY; public Point(int inX, int inY) { x = inX; y = inY; } public int getX() { return printX; } public int getY() { return printY; } public void adjust( int xMax, int xMin, int xSize, int yMax, int yMin, int ySize) { printX = (int)((x - xMin) * (xSize/(xMax - (float)xMin))); printY = (int)((yMax - y) * (ySize/(yMax - (float)yMin))); } }
17.307692
60
0.575556
5638953091759b1f4b9d14a011c9c700feaa27ee
4,675
package com.bird.service.common.grid.executor; import com.bird.service.common.grid.GridClassContainer; import com.bird.service.common.grid.GridDefinition; import com.bird.service.common.grid.enums.GridActionEnum; import com.bird.service.common.grid.exception.GridException; import com.bird.service.common.grid.interceptor.IGridInterceptor; import com.bird.service.common.grid.interceptor.IGridQueryInterceptor; import com.bird.service.common.service.query.PagedListQuery; import com.bird.service.common.service.query.PagedResult; import org.apache.commons.lang3.ArrayUtils; import org.springframework.beans.factory.BeanFactory; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @author liuxx * @since 2021/1/22 */ public class GridExecuteContext { private final BeanFactory beanFactory; private final GridClassContainer container; private final Map<DialectType, IGridExecutor> gridExecutors; private final Map<GridActionEnum, List<IGridInterceptor>> actionInterceptorMap; public GridExecuteContext(BeanFactory beanFactory, GridClassContainer container, IGridExecutorLoader gridExecutorLoader, List<IGridInterceptor> interceptors) { this.beanFactory = beanFactory; this.container = container; this.gridExecutors = gridExecutorLoader.loadExecutors(); this.actionInterceptorMap = new HashMap<>(4); for (GridActionEnum actionEnum : GridActionEnum.values()) { List<IGridInterceptor> actionInterceptors = interceptors.stream() .filter(i -> ArrayUtils.contains(i.actions(), actionEnum)) .sorted(Comparator.comparingInt(IGridInterceptor::getOrder)) .collect(Collectors.toList()); actionInterceptorMap.put(actionEnum, actionInterceptors); } } /** * 执行表格操作 * * @param gridName 表格名称 * @param actionEnum 表格操作 * @param inputData 传入的数据 */ public Object execute(String gridName, GridActionEnum actionEnum, Object inputData) { GridDefinition gridDefinition = this.container.getGridDefinition(gridName); List<IGridInterceptor> interceptors = this.actionInterceptorMap.get(actionEnum); int cursor = -1; for (IGridInterceptor interceptor : interceptors) { if (!interceptor.preHandle(actionEnum, gridDefinition, inputData)) { break; } cursor++; } Object outputData = this.doExecute(actionEnum, gridDefinition, inputData); while (cursor >= 0) { outputData = interceptors.get(cursor).afterHandle(actionEnum, gridDefinition, outputData); cursor--; } return outputData; } private Object doExecute(GridActionEnum actionEnum, GridDefinition gridDefinition, Object inputData) { IGridExecutor gridExecutor = this.gridExecutor(gridDefinition); switch (actionEnum) { case QUERY: IGridQueryInterceptor queryInterceptor = null; PagedListQuery query = (PagedListQuery) inputData; if (gridDefinition.getQueryInterceptorClass() != null) { queryInterceptor = this.beanFactory.getBean(gridDefinition.getQueryInterceptorClass()); } if (queryInterceptor != null) { queryInterceptor.preQuery(query); } PagedResult<Map<String, Object>> result = gridExecutor.listPaged(gridDefinition, query); if (queryInterceptor != null) { queryInterceptor.afterQuery(result); } return result; case INSERT: return gridExecutor.add(gridDefinition, (Map<String, Object>) inputData); case UPDATE: return gridExecutor.edit(gridDefinition, (Map<String, Object>) inputData); case DELETE: return gridExecutor.delete(gridDefinition, inputData); default: return null; } } /** * 获取表格查询执行器 * * @param gridDefinition 表格描述符 * @return 执行器 */ private IGridExecutor gridExecutor(GridDefinition gridDefinition) { if (gridDefinition == null) { throw new GridException("未找到对应的表格定义"); } DialectType dialectType = gridDefinition.getDialectType(); IGridExecutor gridExecutor = gridExecutors.get(dialectType); if (gridExecutor == null) { throw new GridException("不支持的表格处理器"); } return gridExecutor; } }
38.00813
163
0.660963
691e9285c71e792a18105be7e5c964ccf8db4036
1,189
package pl.kubakra.flywithus.flight; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import pl.kubakra.flywithus.tech.serialization.LocalDateDeserializer; import java.time.LocalDate; public class GetFlightsCriteria { @JsonProperty private String from; @JsonProperty private String to; @JsonDeserialize(using = LocalDateDeserializer.class) private LocalDate when; @JsonDeserialize(using = LocalDateDeserializer.class) private LocalDate returnDate; @JsonProperty private int peopleCount; // used by jackson to deserialize public GetFlightsCriteria() { } GetFlightsCriteria(String from, String to, LocalDate when, LocalDate returnDate, int peopleCount) { this.from = from; this.to = to; this.when = when; this.returnDate = returnDate; this.peopleCount = peopleCount; } boolean isOneWayTicket() { return returnDate == null; } public boolean areDatesAfterThan(LocalDate now) { return when.isAfter(now) && (returnDate == null || (returnDate != null && returnDate.isAfter(now))); } }
28.309524
108
0.708158
6f446027c0ff4fc71bc6aa22f96d8433be284cba
2,204
/* * Copyright 2020 ChenJun (power4j@outlook.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.power4j.ji.common.core.model; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import org.springframework.lang.Nullable; import java.io.Serializable; import java.util.function.Function; import java.util.function.Predicate; /** * Wrapper for response data * <p> * * @author CJ (jclazz@outlook.com) * @date 2020-11-17 * @since 1.0 */ @Getter @Setter @Accessors(chain = true) @Schema(title = "响应") public class ApiResponse<T> implements Serializable { private static final long serialVersionUID = 1L; @Schema(title = "错误代码") private Integer code; @Schema(title = "提示信息") @Nullable private String msg; @Schema(title = "业务数据") @Nullable private T data; public static <E> ApiResponse<E> of(int code, @Nullable String msg, @Nullable E data) { return new ApiResponse<E>().setCode(code).setMsg(msg).setData(data); } public static <E> ApiResponse<E> of(int code, @Nullable String msg) { return of(code, msg, null); } public static <E> ApiResponse<E> of(int code) { return of(code, null, null); } /** * 转换数据类型 * @param predicate * @param func * @param <U> * @return */ public <U> ApiResponse<U> map(Predicate<? super T> predicate, Function<? super T, ? extends U> func) { return predicate.test(data) ? of(code, msg, func.apply(data)) : of(code, msg, null); } /** * 转换数据类型 * @param func * @param <U> * @return */ public <U> ApiResponse<U> mapIfPresent(Function<? super T, ? extends U> func) { return map((x) -> x != null, func); } }
24.488889
103
0.696007
149f40ae32ceafc014844ef51e0ae983b0052367
1,624
package chapter7; /* * (Game: pick four cards) Write a program that picks four cards from a deck of 52 * cards and computes their sum. An Ace, King, Queen, and Jack represent 1, 13, * 12, and 11, respectively. Your program should display the number of picks that * yields the sum of 24. */ public class Exercise_07_29 { public static void main(String[] args) { int[] deck; // Create array do { // Initialize deck deck = new int[52]; // Pick four cards pickFourCards(deck); } while (sum(deck) != 24); // Display the number of picks that yields the sum 24 print(deck); } /** * pickFourCards randomly picks four cards */ public static void pickFourCards(int[] deck) { for (int i = 0; i < 4; i++) { deck[(int) (Math.random() * 52)]++; } } /** * sum computes the sum of cards picked */ public static int sum(int[] deck) { int sum = 0; for (int i = 0; i < deck.length; i++) { sum += ((i + 1) % 13) * deck[i]; } return sum; } /** * print displays the number of picks */ public static void print(int[] deck) { String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"}; System.out.print("The number of picks that yields the sum of 24: "); for (int i = 0; i < deck.length; i++) { if (deck[i] > 0) System.out.print(ranks[i % 13] + " "); } System.out.println(); } }
26.622951
82
0.505542
b46ace1fb26e2c88c735db70e88506ca4755dc42
4,127
package com.fhuber.schwarz.alternate.app; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.net.URL; import java.security.Permission; import com.fhuber.schwarz.alternate.service.Anagram2Service; import com.fhuber.schwarz.alternate.service.impl.Anagram2FileService; import com.fhuber.schwarz.solution.exception.AnagramException; import com.fhuber.schwarz.solution.model.AnagramMap; import com.fhuber.schwarz.solution.service.impl.AnagramMapStorage; import org.jboss.weld.junit5.WeldInitiator; import org.jboss.weld.junit5.WeldSetup; import org.jboss.weld.junit5.auto.EnableAutoWeld; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @EnableAutoWeld public class AppTest { private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); private final PrintStream originalOut = System.out; private final PrintStream originalErr = System.err; protected static class ExitException extends SecurityException { public final int status; public ExitException(int status) { super("There is no escape!"); this.status = status; } } private static class NoExitSecurityManager extends SecurityManager { @Override public void checkPermission(Permission perm) { // allow anything. } @Override public void checkPermission(Permission perm, Object context) { // allow anything. } @Override public void checkExit(int status) { throw new ExitException(status); } } @WeldSetup public WeldInitiator weld = WeldInitiator .of(WeldInitiator.createWeld() .addPackages(Anagram2Service.class, AnagramMap.class) .addBeanClasses(AnagramMapStorage.class, Anagram2FileService.class)); // static Bean<?> createSelectedAlternativeBean() { // return // MockBean.builder().types(AnagramOutputService.class).selectedAlternative(AnagramSystemWriterService.class) // .creating(new AnagramSystemWriterService()).build(); // } @BeforeEach public void setUpStreams() { System.setOut(new PrintStream(outContent)); System.setErr(new PrintStream(errContent)); System.setSecurityManager(new NoExitSecurityManager()); } @AfterEach public void restoreStreams() { System.setOut(originalOut); System.setErr(originalErr); System.setSecurityManager(null); } @BeforeAll public static void setup() { // String path = AnagramApp.class.getClassLoader() // .getResource("logging.properties") // .getFile(); // System.setProperty("java.util.logging.config.file", path); // System.setProperty("key", value) } @Test public void shouldThrowException() { String[] args = { "test" }; AnagramException thrown = assertThrows(AnagramException.class, () -> { AnagramApp.main(args); }); assertEquals("File not found", thrown.getMessage()); } @Test public void shouldRefuseExecution() { String[] args = { "" }; ExitException thrown = assertThrows(ExitException.class, () -> { AnagramApp.main(args); }); assertEquals(1, thrown.status); assertEquals("Proper Usage is: java program filename", errContent.toString().trim()); } @Test public void shouldWork() { URL url = this.getClass().getResource("sample.txt"); String path = url.getPath(); String[] args = { path }; assertDoesNotThrow(() -> { AnagramApp.main(args); }); assertEquals("act cat", outContent.toString().trim()); } }
32.496063
113
0.675309
e65de580fe1356895bd80d377f7ae001721b0b02
2,210
package com.google.common.io; import com.google.common.base.Preconditions; import java.io.Closeable; import java.io.Flushable; import java.io.IOException; import java.io.Writer; import org.checkerframework.checker.nullness.compatqual.NullableDecl; class AppendableWriter extends Writer { private boolean closed; private final Appendable target; AppendableWriter(Appendable appendable) { this.target = (Appendable) Preconditions.checkNotNull(appendable); } public void write(char[] cArr, int i, int i2) throws IOException { checkNotClosed(); this.target.append(new String(cArr, i, i2)); } public void write(int i) throws IOException { checkNotClosed(); this.target.append((char) i); } public void write(@NullableDecl String str) throws IOException { checkNotClosed(); this.target.append(str); } public void write(@NullableDecl String str, int i, int i2) throws IOException { checkNotClosed(); this.target.append(str, i, i2 + i); } public void flush() throws IOException { checkNotClosed(); Appendable appendable = this.target; if (appendable instanceof Flushable) { ((Flushable) appendable).flush(); } } public void close() throws IOException { this.closed = true; Appendable appendable = this.target; if (appendable instanceof Closeable) { ((Closeable) appendable).close(); } } public Writer append(char c) throws IOException { checkNotClosed(); this.target.append(c); return this; } public Writer append(@NullableDecl CharSequence charSequence) throws IOException { checkNotClosed(); this.target.append(charSequence); return this; } public Writer append(@NullableDecl CharSequence charSequence, int i, int i2) throws IOException { checkNotClosed(); this.target.append(charSequence, i, i2); return this; } private void checkNotClosed() throws IOException { if (this.closed) { throw new IOException("Cannot write to a closed writer."); } } }
28.333333
101
0.647511
4f6700d20f2e328d462b2a408a77f753c6cee361
1,664
package com.example.demo.web; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.List; @Configuration @EnableWebMvc // To make Spring Data's `Sort`, `Pageable` and QueryDsl PredicatesArgument resolvable in the controller method arguments. // add @EnableSpringDataWebSupport to enable it. @ComponentScan( basePackageClasses = WebConfig.class, useDefaultFilters = false, includeFilters = { @ComponentScan.Filter( type = FilterType.ANNOTATION, classes = {RestController.class, RestControllerAdvice.class} ) } ) public class WebConfig implements WebMvcConfigurer { @Autowired ObjectMapper objectMapper; @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { var jackson2MessageConverter = new MappingJackson2HttpMessageConverter(objectMapper); converters.add(jackson2MessageConverter); } }
39.619048
122
0.772837
481a37324ec4770e20d8f4bc206676e65fc2feff
2,027
package org.wikipedia.views; import android.content.Context; import android.support.annotation.ColorRes; import android.support.annotation.NonNull; import android.support.constraint.ConstraintLayout; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; import org.wikipedia.R; import static android.support.v4.content.ContextCompat.getColor; import static android.support.v4.graphics.drawable.DrawableCompat.setTint; public class ConfigurableTabLayout extends ConstraintLayout { @ColorRes private static final int TAB_ENABLED_COLOR = android.R.color.white; @ColorRes private static final int TAB_DISABLED_COLOR = R.color.base30; public ConfigurableTabLayout(Context context) { this(context, null); } public ConfigurableTabLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ConfigurableTabLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void enableTab(int index) { View tab = getChildAt(index); if (tab != null) { setEnabled(tab, true); } } public void disableTab(int index) { View tab = getChildAt(index); if (tab != null) { setEnabled(tab, false); } } public void enableAllTabs() { for (int i = 0; i < getChildCount(); i++) { enableTab(i); } } public boolean isEnabled(@NonNull View tab) { return !isDisabled(tab); } public boolean isDisabled(@NonNull View tab) { return tab.getTag() != null && tab.getTag() instanceof DisabledTag; } private void setEnabled(@NonNull View tab, boolean enabled) { tab.setTag(enabled ? null : new DisabledTag()); // noinspection ConstantConditions setTint(((ImageView) tab).getDrawable(), getColor(getContext(), enabled ? TAB_ENABLED_COLOR : TAB_DISABLED_COLOR)); } private class DisabledTag { } }
29.376812
123
0.678836
530fd2564b5c36aff67966c7056ad167e1b83df1
1,393
package com.ssm.promotion.core.dto; import com.ssm.promotion.core.entity.Course; /** * 视频类管理课程 * @author 尤少辉 * @日期 2018年7月2日 */ public class VideoCategoryCourseDto { private int videoCategoryId; private String videoCategoryName; private String videoCategoryDescribe; private Course course=new Course(); public int getVideoCategoryId() { return videoCategoryId; } public void setVideoCategoryId(int videoCategoryId) { this.videoCategoryId = videoCategoryId; } public String getVideoCategoryName() { return videoCategoryName; } public void setVideoCategoryName(String videoCategoryName) { this.videoCategoryName = videoCategoryName; } public String getVideoCategoryDescribe() { return videoCategoryDescribe; } public void setVideoCategoryDescribe(String videoCategoryDescribe) { this.videoCategoryDescribe = videoCategoryDescribe; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } public VideoCategoryCourseDto(int videoCategoryId, String videoCategoryName, String videoCategoryDescribe, Course course) { super(); this.videoCategoryId = videoCategoryId; this.videoCategoryName = videoCategoryName; this.videoCategoryDescribe = videoCategoryDescribe; this.course = course; } public VideoCategoryCourseDto() { super(); } }
26.788462
108
0.751615