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
77bec97da622311c386aed00e96ba12ed632cad1
3,727
/** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is: this file * * The Initial Developer of the Original Code is Oliver Becker. * * Portions created by Philip Helger * are Copyright (C) 2016-2017 Philip Helger * All Rights Reserved. */ package jflex; import java.io.File; /** * Collects all global JFlex options. Can be set from command line parser, ant * taks, gui, etc. * * @author Gerwin Klein * @version JFlex 1.6.1 */ public class Options { /** * If true, additional verbose debug information is produced. This is a * compile time option. */ public final static boolean DEBUG = false; /** output directory */ private static File directory; /** strict JLex compatibility */ public static boolean jlex; /** don't run minimization algorithm if this is true */ public static boolean no_minimize; /** don't write backup files if this is true */ public static boolean no_backup; /** If false, only error/warning output will be generated */ public static boolean verbose; /** Whether to warn about unused macros. */ public static boolean unused_warning; /** If true, progress dots will be printed */ public static boolean progress; /** If true, jflex will print time statistics about the generation process */ public static boolean time; /** If true, jflex will write graphviz .dot files for generated automata */ public static boolean dot; /** If true, you will be flooded with information (e.g. dfa tables). */ public static boolean dump; /** * If true, dot (.) metachar matches [^\n] instead of * [^\r\n\u000B\u000C\u0085\u2028\u2029]|"\r\n" */ public static boolean legacy_dot; /** * If true, the generated scanner will include a constructor taking an * InputStream. */ public static boolean emitInputStreamCtor; static { setDefaults (); } /** * @return the output directory */ public static File getDir () { return directory; } /** * Set output directory * * @param dirName * the name of the directory to write output files to */ public static void setDir (final String dirName) { setDir (new File (dirName)); } /** * Set output directory * * @param d * the directory to write output files to */ public static void setDir (final File d) { if (d.isFile ()) { Out.error ("Error: \"" + d + "\" is not a directory."); throw new GeneratorException (); } if (!d.isDirectory () && !d.mkdirs ()) { Out.error ("Error: couldn't create directory \"" + d + "\""); throw new GeneratorException (); } directory = d; } /** * Sets all options back to default values. */ public static void setDefaults () { directory = null; jlex = false; no_minimize = false; no_backup = false; verbose = true; progress = true; unused_warning = true; time = false; dot = false; dump = false; legacy_dot = false; // TODO: in the JFlex version after 1.6, the emitInputStreamCtor option will // cease to exist. emitInputStreamCtor = false; Skeleton.readDefault (); } public static void setSkeleton (final File skel) { Skeleton.readSkelFile (skel); } }
25.703448
80
0.653609
fe0824d069f149ebd831ef1bab44bad8f47091d3
4,283
package org.spongepowered.asm.mixin.transformer.ext.extensions; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.transformer.ext.IDecompiler; import org.spongepowered.asm.mixin.transformer.ext.IExtension; import org.spongepowered.asm.mixin.transformer.ext.ITargetClassContext; import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.perf.Profiler; public class ExtensionClassExporter implements IExtension { private static final String DECOMPILER_CLASS = "org.spongepowered.asm.mixin.transformer.debug.RuntimeDecompiler"; private static final String EXPORT_CLASS_DIR = "class"; private static final String EXPORT_JAVA_DIR = "java"; private static final Logger logger = LogManager.getLogger("mixin"); private final File classExportDir = new File(Constants.DEBUG_OUTPUT_DIR, "class"); private final IDecompiler decompiler; public ExtensionClassExporter(MixinEnvironment env) { this.decompiler = initDecompiler(env, new File(Constants.DEBUG_OUTPUT_DIR, "java")); try { FileUtils.deleteDirectory(this.classExportDir); } catch (IOException ex) { logger.warn("Error cleaning class output directory: {}", new Object[] { ex.getMessage() }); } } public boolean isDecompilerActive() { return (this.decompiler != null); } private IDecompiler initDecompiler(MixinEnvironment env, File outputPath) { if (!env.getOption(MixinEnvironment.Option.DEBUG_EXPORT_DECOMPILE)) return null; try { boolean as = env.getOption(MixinEnvironment.Option.DEBUG_EXPORT_DECOMPILE_THREADED); logger.info("Attempting to load Fernflower decompiler{}", new Object[] { as ? " (Threaded mode)" : "" }); String className = "org.spongepowered.asm.mixin.transformer.debug.RuntimeDecompiler" + (as ? "Async" : ""); Class<? extends IDecompiler> clazz = (Class)Class.forName(className); Constructor<? extends IDecompiler> ctor = clazz.getDeclaredConstructor(new Class[] { File.class }); IDecompiler decompiler = ctor.newInstance(new Object[] { outputPath }); logger.info("Fernflower decompiler was successfully initialised, exported classes will be decompiled{}", new Object[] { as ? " in a separate thread" : "" }); return decompiler; } catch (Throwable th) { logger.info("Fernflower could not be loaded, exported classes will not be decompiled. {}: {}", new Object[] { th .getClass().getSimpleName(), th.getMessage() }); return null; } } private String prepareFilter(String filter) { filter = "^\\Q" + filter.replace("**", "").replace("*", "‚").replace("?", "ƒ") + "\\E$"; return filter.replace("", "\\E.*\\Q").replace("‚", "\\E[^\\.]+\\Q").replace("ƒ", "\\E.\\Q").replace("\\Q\\E", ""); } private boolean applyFilter(String filter, String subject) { return Pattern.compile(prepareFilter(filter), 2).matcher(subject).matches(); } public boolean checkActive(MixinEnvironment environment) { return true; } public void preApply(ITargetClassContext context) {} public void postApply(ITargetClassContext context) {} public void export(MixinEnvironment env, String name, boolean force, byte[] bytes) { if (force || env.getOption(MixinEnvironment.Option.DEBUG_EXPORT)) { String filter = env.getOptionValue(MixinEnvironment.Option.DEBUG_EXPORT_FILTER); if (force || filter == null || applyFilter(filter, name)) { Profiler.Section exportTimer = MixinEnvironment.getProfiler().begin("debug.export"); File outputFile = dumpClass(name.replace('.', '/'), bytes); if (this.decompiler != null) this.decompiler.decompile(outputFile); exportTimer.end(); } } } public File dumpClass(String fileName, byte[] bytes) { File outputFile = new File(this.classExportDir, fileName + ".class"); try { FileUtils.writeByteArrayToFile(outputFile, bytes); } catch (IOException iOException) {} return outputFile; } }
42.83
163
0.705814
133416b78b4ef5cd16eb151b3b524acaaf9d280b
312
package de.njsm.stocks.client.frontend; import de.njsm.stocks.client.config.Configuration; public abstract class UIFactory { public abstract ConfigGenerator getConfigActor(); public abstract CertificateGenerator getCertGenerator(); public abstract MainHandler getMainHandler(Configuration c); }
24
64
0.801282
9725ce3c26b4427082bc1f0a14ef0f7b1ef3a618
444
package com.fiuba.tdp.linkup.util; import android.app.Application; import android.content.Context; /** * Created by alejandro on 9/25/17. */ public class MySuperAppApplication extends Application { private static Application instance; public static Context getContext() { return instance.getApplicationContext(); } @Override public void onCreate() { super.onCreate(); instance = this; } }
19.304348
56
0.684685
aa04cced91920124c9f4cc0be026d4777573f6c3
2,030
/* Copyright 2017 Danny Kunz 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.omnaest.search.classic.utils; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Function; public class ListUtils { /** * Returns a new {@link List} instance which has the elements of the given {@link Collection} in reverse order * <br> * <br> * If the given collection is null, an empty {@link List} is returned * * @param collection * @return a new list instance */ public static <E> List<E> inverse(Collection<E> collection) { List<E> retlist = new ArrayList<>(); if (collection != null) { retlist.addAll(collection); Collections.reverse(retlist); } return retlist; } public static <E> Optional<E> first(List<E> list) { return list != null && !list.isEmpty() ? Optional.of(list.get(0)) : Optional.empty(); } public static <E, R> Optional<R> first(List<E> list, Function<E, R> mapper) { return list != null && !list.isEmpty() ? Optional .of(list.get(0)) .map(mapper) : Optional.empty(); } public static <E> Optional<E> last(List<E> list) { return list != null && !list.isEmpty() ? Optional.of(list.get(list.size() - 1)) : Optional.empty(); } public static <E, R> Optional<R> last(List<E> list, Function<E, R> mapper) { return list != null && !list.isEmpty() ? Optional .of(list.get(list.size() - 1)) .map(mapper) : Optional.empty(); } }
27.432432
111
0.685714
949ae007fb101da13fa283b88fcddeac6017bbe3
5,275
package io.zonky.test.db; import io.zonky.test.db.context.DatabaseContext; import io.zonky.test.db.provider.DatabaseProvider; import io.zonky.test.support.SpyPostProcessor; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.io.ResourceLoader; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestContext; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.support.AbstractTestExecutionListener; import javax.sql.DataSource; import java.util.List; import java.util.Map; import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseType.POSTGRES; import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.RefreshMode.AFTER_EACH_TEST_METHOD; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.springframework.test.context.TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS; @RunWith(SpringRunner.class) @TestExecutionListeners( mergeMode = MERGE_WITH_DEFAULTS, listeners = DatabaseRefreshIntegrationTest.class ) @AutoConfigureEmbeddedDatabase(type = POSTGRES, refresh = AFTER_EACH_TEST_METHOD) @ContextConfiguration public class DatabaseRefreshIntegrationTest extends AbstractTestExecutionListener { private static final String SQL_SELECT_ADDRESS = "select * from test.address"; private static final String SQL_INSERT_ADDRESS = "insert into test.address (id, street) values (?, ?);"; @Configuration static class Config { @Bean public TestDatabaseInitializer testDatabaseInitializer(DataSource dataSource, ResourceLoader resourceLoader) { return new TestDatabaseInitializer(dataSource, resourceLoader); } @Bean public JdbcTemplate jdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } @Bean public BeanPostProcessor spyPostProcessor() { return new SpyPostProcessor((bean, beanName) -> bean instanceof DatabaseContext || beanName.equals("dockerPostgresDatabaseProvider")); } } public static class TestDatabaseInitializer implements InitializingBean { private final DataSource dataSource; private final ResourceLoader resourceLoader; public TestDatabaseInitializer(DataSource dataSource, ResourceLoader resourceLoader) { this.dataSource = dataSource; this.resourceLoader = resourceLoader; } @Override public void afterPropertiesSet() throws Exception { ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.addScript(this.resourceLoader.getResource("db/create_address_table.sql")); DatabasePopulatorUtils.execute(populator, this.dataSource); } } @Autowired private JdbcTemplate jdbcTemplate; @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } @Override public void afterTestClass(TestContext testContext) { ApplicationContext applicationContext = testContext.getApplicationContext(); DatabaseContext databaseContext = applicationContext.getBean(DatabaseContext.class); DatabaseProvider databaseProvider = applicationContext.getBean("dockerPostgresDatabaseProvider", DatabaseProvider.class); verify(databaseContext, times(4)).reset(); verify(databaseContext, never()).apply(any()); verify(databaseProvider, times(3)).createDatabase(any()); Mockito.reset(databaseContext, databaseProvider); } @Test public void isolatedTest1() { List<Map<String, Object>> addresses = jdbcTemplate.queryForList(SQL_SELECT_ADDRESS); assertThat(addresses).isNotNull().hasSize(0); jdbcTemplate.update(SQL_INSERT_ADDRESS, 1, "address"); } @Test public void isolatedTest2() { List<Map<String, Object>> addresses = jdbcTemplate.queryForList(SQL_SELECT_ADDRESS); assertThat(addresses).isNotNull().hasSize(0); jdbcTemplate.update(SQL_INSERT_ADDRESS, 1, "address"); } @Test public void isolatedTest3() { List<Map<String, Object>> addresses = jdbcTemplate.queryForList(SQL_SELECT_ADDRESS); assertThat(addresses).isNotNull().hasSize(0); jdbcTemplate.update(SQL_INSERT_ADDRESS, 1, "address"); } }
39.365672
129
0.759242
695b035bc6ebf2b36ed905e57138a00a9aab66d8
2,803
import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.OperatingSystemMXBean; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.*; import jade.content.lang.sl.*; import jade.core.*; import jade.core.behaviours.*; import jade.domain.*; import jade.domain.AMSService; import jade.domain.FIPAAgentManagement.*; import jade.domain.introspection.*; import jade.domain.JADEAgentManagement.*; public class Reporter extends Agent { private long t0 = 0; private long time() { return System.currentTimeMillis() - t0; } private void print(String s) { System.out.println(time() + ": " + s); } private CyclicBehaviour onTick(Reporter agent) { return (new CyclicBehaviour(agent){ Reporter reporter; Queue<ContainerID> currentContainers; ArrayList<String> accumultatedInfo = new ArrayList<>(); private Queue<ContainerID> getContainers() { LinkedList<ContainerID> list = new LinkedList<ContainerID>(Containers.Instance.available); list.remove(Containers.mainContainer()); list.addLast(Containers.mainContainer()); return list; } private String getData() { OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); java.lang.Runtime runtime = java.lang.Runtime.getRuntime(); runtime.gc(); String host = null; try { host = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { e.printStackTrace(); } return "Computer name: " + host + " | Free memory: " + runtime.freeMemory() + "B | Processing load: " + osBean.getSystemLoadAverage(); } public void onStart() { reporter = (Reporter) myAgent; } public void action() { if (here().equals(Containers.mainContainer())) { currentContainers = getContainers(); //Print accumulated info. print("back at main."); for (String data : accumultatedInfo ) { print(data); } accumultatedInfo = new ArrayList<>(); } // Get current container information and save into agent. accumultatedInfo.add(getData()); print(getLocalName()); //Move to another container. try { Thread.sleep(1000); } catch(InterruptedException ex) { } doMove(currentContainers.remove()); } }); } private WakerBehaviour onWake(Reporter agent) { return (new WakerBehaviour(agent, 10000) { Reporter reporter; public void onStart() { reporter = (Reporter) myAgent; } //agent = myAgent protected void handleElapsedTimeout() { print("Reporter started to run."); addBehaviour(onTick(reporter)); } }); } @Override protected void setup() { // Wait for containers to load. addBehaviour(onWake(this)); t0 = System.currentTimeMillis(); } }
26.695238
138
0.692116
4db0f0ffcaa98b5a330403c34fdd656ef58b6853
7,960
package fr.aerwyn81.headblocks.databases.types; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.pool.HikariPool; import fr.aerwyn81.headblocks.HeadBlocks; import fr.aerwyn81.headblocks.databases.Database; import fr.aerwyn81.headblocks.handlers.ConfigHandler; import fr.aerwyn81.headblocks.utils.FormatUtils; import org.bukkit.Bukkit; import org.javatuples.Pair; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.UUID; public final class MySQL implements Database { private final HeadBlocks main; private final ConfigHandler configHandler; private HikariDataSource hikari; public MySQL(HeadBlocks main) { this.main = main; this.configHandler = main.getConfigHandler(); } @Override public void close() { if (hikari == null) { return; } hikari.close(); } @Override public void open() { if (hikari != null) { return; } try { HikariConfig config = new HikariConfig(); config.setPoolName("HeadBlocksPoolMySQL"); config.setJdbcUrl("jdbc:mysql://" + configHandler.getDatabaseHostname() + ":" + configHandler.getDatabasePort() + "/" + configHandler.getDatabaseName()); config.setUsername(configHandler.getDatabaseUsername()); config.setPassword(configHandler.getDatabasePassword()); config.setMaximumPoolSize(75); config.setMinimumIdle(4); config.addDataSourceProperty("cachePrepStmts", "true"); config.addDataSourceProperty("prepStmtCacheSize", "250"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); hikari = new HikariDataSource(config); HeadBlocks.log.sendMessage(FormatUtils.translate("&aMySQL has been enabled!")); } catch (HikariPool.PoolInitializationException e) { HeadBlocks.log.sendMessage(FormatUtils.translate("&cMySQL has an error on the connection! Now trying with SQLite...")); main.getStorageHandler().changeToSQLite(); } } @Override public void load() { PreparedStatement statement = null; Connection connection = null; try { connection = hikari.getConnection(); statement = connection.prepareStatement("CREATE TABLE IF NOT EXISTS hb_players (`pUUID` varchar(40) NOT NULL, `hUUID` varchar(40) NOT NULL, PRIMARY KEY (pUUID,`hUUID`));"); statement.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } @Override public boolean hasHead(UUID playerUuid, UUID headUuid) { try (Connection connection = hikari.getConnection(); PreparedStatement ps = connection.prepareStatement("SELECT * FROM hb_players WHERE pUUID = '" + playerUuid.toString() + "' AND hUUID = '" + headUuid.toString() + "';"); ResultSet rs = ps.executeQuery()) { if (rs.next()) { return true; } } catch (SQLException e) { e.printStackTrace(); } return false; } @Override public boolean containsPlayer(UUID playerUuid) { try (Connection connection = hikari.getConnection(); PreparedStatement ps = connection.prepareStatement("SELECT * FROM hb_players WHERE pUUID = '" + playerUuid.toString() + "';"); ResultSet rs = ps.executeQuery()) { if (rs.next()) { return true; } } catch (SQLException e) { e.printStackTrace(); } return false; } @Override public ArrayList<UUID> getHeadsPlayer(UUID playerUuid) { ArrayList<UUID> heads = new ArrayList<>(); try (Connection connection = hikari.getConnection(); PreparedStatement ps = connection.prepareStatement("SELECT * FROM hb_players WHERE pUUID = '" + playerUuid.toString() + "';"); ResultSet rs = ps.executeQuery()) { while (rs.next()) { heads.add(UUID.fromString(rs.getString("hUUID"))); } } catch (SQLException e) { e.printStackTrace(); } return heads; } @Override public void savePlayer(UUID playerUuid, UUID headUuid) { try (Connection connection = hikari.getConnection(); PreparedStatement ps = connection.prepareStatement("REPLACE INTO hb_players (pUUID, hUUID) VALUES(?,?)")) { ps.setString(1, playerUuid.toString()); ps.setString(2, headUuid.toString()); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } @Override public void resetPlayer(UUID playerUuid) { Bukkit.getScheduler().runTaskAsynchronously(main, () -> { PreparedStatement ps = null; try { Connection connection = hikari.getConnection(); ps = connection.prepareStatement("DELETE FROM hb_players WHERE pUUID = '" + playerUuid.toString() + "'"); ps.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { if (ps != null) { try { ps.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }); } @Override public void removeHead(UUID headUuid) { Bukkit.getScheduler().runTaskAsynchronously(main, () -> { PreparedStatement ps = null; try { Connection connection = hikari.getConnection(); ps = connection.prepareStatement("DELETE FROM hb_players WHERE hUUID = '" + headUuid.toString() + "'"); ps.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { if (ps != null) { try { ps.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }); } @Override public ArrayList<UUID> getAllPlayers() { ArrayList<UUID> players = new ArrayList<>(); try (Connection connection = hikari.getConnection(); PreparedStatement ps = connection.prepareStatement("SELECT DISTINCT pUUID FROM hb_players"); ResultSet rs = ps.executeQuery()) { while (rs.next()) { players.add(UUID.fromString(rs.getString("pUUID"))); } } catch (SQLException e) { e.printStackTrace(); } return players; } @Override public ArrayList<Pair<UUID, Integer>> getTopPlayers(int limit) { ArrayList<Pair<UUID, Integer>> top = new ArrayList<>(); try (Connection connection = hikari.getConnection(); PreparedStatement ps = connection.prepareStatement("SELECT `pUUID`, COUNT(*) as hCount FROM hb_players GROUP BY `pUUID` ORDER BY hCount DESC LIMIT '" + limit + "'"); ResultSet rs = ps.executeQuery()) { while (rs.next()) { top.add(new Pair<>(UUID.fromString(rs.getString("pUUID")), rs.getInt("hCount"))); } } catch (SQLException e) { e.printStackTrace(); } return top; } }
36.0181
265
0.573492
bbf090bceaaa193c6314c9c341e34c66e0efc691
2,120
package hudson.plugins.sitemonitor; import hudson.plugins.sitemonitor.model.Result; import hudson.plugins.sitemonitor.model.Site; import hudson.plugins.sitemonitor.model.Status; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; public class SiteMonitorRootActionTest extends TestCase { private SiteMonitorRootAction action; public void setUp() { List<Result> results = new ArrayList<Result>(); Result result1 = new Result(Site.builder("http://hudson-ci.org").build(), HttpURLConnection.HTTP_OK, Status.UP, "some note 1"); Result result2 = new Result(Site.builder("http://blah").build(), HttpURLConnection.HTTP_BAD_GATEWAY, Status.ERROR, "some note 2"); results.add(result1); results.add(result2); action = new SiteMonitorRootAction(results); } public void testGetResultsShouldGiveExpectedResults() { List<Result> results = action.getResults(); assertEquals("http://hudson-ci.org", results.get(0).getSite().getUrl()); assertEquals(new Integer(HttpURLConnection.HTTP_OK), results.get(0) .getResponseCode()); assertEquals(Status.UP, results.get(0).getStatus()); assertEquals("some note 1", results.get(0).getNote()); assertEquals("http://blah", results.get(1).getSite().getUrl()); assertEquals(new Integer(HttpURLConnection.HTTP_BAD_GATEWAY), results .get(1).getResponseCode()); assertEquals(Status.ERROR, results.get(1).getStatus()); assertEquals("some note 2", results.get(1).getNote()); } public void testGetDisplayNameShouldGiveExpectedValue() { assertEquals(Messages.SiteMonitor_DisplayName(), action.getDisplayName()); } public void testGetIconFileNameShouldGiveExpectedValue() { assertEquals("/plugin/sitemonitor/images/icon.png", action .getIconFileName()); } public void testGetUrlNameShouldGiveExpectedValue() { assertEquals("sitemonitor", action.getUrlName()); } }
38.545455
82
0.686792
cc59556761577686a5f5422401e9fd7649192022
3,822
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ Copyright 2020 Adobe ~ ~ 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.adobe.cq.wcm.core.components.internal.form; import java.lang.annotation.Annotation; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.osgi.services.HttpClientBuilderFactory; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import com.adobe.cq.wcm.core.components.context.CoreComponentTestContext; import com.adobe.cq.wcm.core.components.services.form.FormHandler; import com.github.tomakehurst.wiremock.WireMockServer; import io.wcm.testing.mock.aem.junit5.AemContext; import io.wcm.testing.mock.aem.junit5.AemContextExtension; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @ExtendWith({AemContextExtension.class}) public class FormHandlerImplTest { public final AemContext context = CoreComponentTestContext.newAemContext(); private WireMockServer wireMockServer; private int wireMockPort; private FormHandler underTest; @BeforeEach void setUp() { wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()); wireMockServer.start(); wireMockPort = wireMockServer.port(); setupStub(); context.registerService(HttpClientBuilderFactory.class, HttpClientBuilder::create); underTest = context.registerInjectActivateService(new FormHandlerImpl()); ((FormHandlerImpl) underTest).activate(new FormHandlerImpl.Config() { @Override public int connectionTimeout() { return 6000; } @Override public int socketTimeout() { return 6000; } @Override public Class<? extends Annotation> annotationType() { return null; } }); } private void setupStub() { wireMockServer.stubFor(post(urlEqualTo("/form/endpoint")) .willReturn(aResponse().withHeader("Content-Type", "application/json") .withStatus(200))); } @AfterEach void tearDown() { wireMockServer.stop(); } @Test void testSendFormDataWithSuccess() throws JSONException { String endPointUrl = "http://localhost:" + wireMockPort + "/form/endpoint"; JSONObject formData = new JSONObject(); formData.append("text", "Hello World!"); assertTrue(underTest.forwardFormData(formData, endPointUrl)); } @Test void testSendFormDataWithError() throws JSONException { String endPointUrl = "http://localhost:" + wireMockPort + "/form/nonExistingEndpoint"; JSONObject formData = new JSONObject(); formData.append("text", "Hello World!"); assertFalse(underTest.forwardFormData(formData, endPointUrl)); } }
37.106796
94
0.680795
685f9fe156871929fbaaac0b7514af76735955da
367
package com.smartgwt.mobile.client.internal.theme; import com.smartgwt.mobile.SGWTInternal; import com.smartgwt.mobile.client.theme.ThemeResources; @SGWTInternal public interface ThemeResourcesBase extends ThemeResources { @Override @Source({ "com/smartgwt/mobile/client/theme/tabs.gwt.css", "tabs.gwt.css" }) public TabSetCssResourceBase tabsCSS(); }
28.230769
80
0.784741
09bbfb84b2b3e43f0961879c12a230dc4dcdff54
15,077
package org.jzy3d.plot3d.rendering.view; import java.util.ArrayList; import java.util.List; import java.util.Vector; import javax.media.opengl.GL2; import javax.media.opengl.glu.GLU; import org.jzy3d.maths.Coord3d; import org.jzy3d.maths.PolygonArray; import org.jzy3d.plot3d.rendering.view.modes.CameraMode; /** A {@link Camera} provides an easy control on the view and target points * in a cartesian coordinate system. * * The {@link Camera} handles the following services: * <ul> * <li>allows setting perspective/orthogonal rendering mode through {@link CameraMode}. * <li>selects the appropriate clipping planes according to a given target box. * <li>ensure the modelview matrix is always available for GL2 calls related to anything else than projection. * <li>methods to convert screen coordinates into 3d coordinates and vice-versa * </ul> * * @author Martin Pernollet */ public class Camera extends AbstractViewport{ /** * Set up a Camera looking at target, with a viewpoint standing * at target+(0,0,100). The top of the camera is set up toward * the positive Z direction. */ public Camera(Coord3d target){ setTarget(target); setEye(DEFAULT_VIEW.cartesian().add(target)); setUp(new Coord3d(0, 0, 1)); setViewPort(1, 1, 0, 1); setRenderingDepth(0.5f, 100000f); setRenderingSphereRadius(1); setStretchToFill(false); } /******************************************************************/ /** Set the eye's position.*/ public void setEye(Coord3d eye){ this.eye = eye; } /** Returns the eye's position.*/ public Coord3d getEye(){ return eye; } /** Set the target point of the camera.*/ public void setTarget(Coord3d target){ this.target = target; } /** Returns the target's position that was set at the last call to lookAt().*/ public Coord3d getTarget(){ return target; } /** Set the top of the camera.*/ public void setUp(Coord3d up){ this.up = up; } /** Returns the top of the camera.*/ public Coord3d getUp(){ return this.up; } public boolean isTiltUp(){ return eye.z < target.z; } /******************************************************************/ /** Set the radius of the sphere that will be contained into the rendered view. * As a side effect, the "far" clipping plane is modified according to the eye-target distance, and * the position of the "near" clipping plane. */ public void setRenderingSphereRadius(float radius){ this.radius = radius; //this.far = near + (float)eye.distance(target) + radius; this.near = (float)eye.distance(target) - radius*2; this.far = (float)eye.distance(target) + radius*2; } /** Return the radius of the sphere that will be contained into the rendered view.*/ public float getRenderingSphereRadius(){ return radius; } /** Manually set the rendering depth (near and far clipping planes). * Note that {@link Camera.setRenderingSphereRadius} modified the "far" * clipping plane. */ public void setRenderingDepth(float near, float far){ this.near = near; this.far = far; } /** Return the position of the "near" clipping plane*/ public float getNear(){ return near; } /** Return the position of the "far" clipping plane*/ public float getFar(){ return far; } /** Return true if the given point is on the left of the vector eye->target.*/ public boolean side(Coord3d point){ return 0 < ( (point.x-target.x)*(eye.y-target.y) - (point.y-target.y)*(eye.x-target.x) ); } /************************** PROJECT / UNPROJECT ****************************/ /** Transform a 2d screen coordinate into a 3d coordinate. * The z component of the screen coordinate indicates a depth value between the * near and far clipping plane of the {@link Camera}. * * @throws a RuntimeException if an error occured while trying to retrieve model coordinates */ public Coord3d screenToModel(GL2 gl, GLU glu, Coord3d screen){ int viewport[] = getViewPortAsInt(gl); float worldcoord[] = new float[3];// wx, wy, wz;// returned xyz coords float realy = screen.y;//viewport[3] - (int)screen.y - 1; boolean s = glu.gluUnProject(screen.x, realy, screen.z, getModelViewAsFloat(gl), 0, getProjectionAsFloat(gl), 0, viewport, 0, worldcoord, 0); if(!s) throw new RuntimeException("Could not retrieve screen coordinates in model."); return new Coord3d(worldcoord[0], worldcoord[1], worldcoord[2]); } /** Transform a 3d point coordinate into its screen position. * @throws a RuntimeException if an error occured while trying to retrieve model coordinates */ public Coord3d modelToScreen(GL2 gl, GLU glu, Coord3d point){ int viewport[] = getViewPortAsInt(gl); float screencoord[] = new float[3];// wx, wy, wz;// returned xyz coords if( ! glu.gluProject(point.x, point.y, point.z, getModelViewAsFloat(gl), 0, getProjectionAsFloat(gl), 0, viewport, 0, screencoord, 0) ) throw new RuntimeException("Could not retrieve model coordinates in screen for " + point); return new Coord3d(screencoord[0], screencoord[1], screencoord[2]); } public Coord3d[] modelToScreen(GL2 gl, GLU glu, Coord3d[] points){ int viewport[] = getViewPortAsInt(gl); float screencoord[] = new float[3]; Coord3d[] projection = new Coord3d[points.length]; for (int i = 0; i < points.length; i++) { if( ! glu.gluProject( points[i].x, points[i].y, points[i].z, getModelViewAsFloat(gl), 0, getProjectionAsFloat(gl), 0, viewport, 0, screencoord, 0 ) ) throw new RuntimeException("Could not retrieve model coordinates in screen for " + points[i]); projection[i] = new Coord3d(screencoord[0], screencoord[1], screencoord[2]); } return projection; } public Coord3d[][] modelToScreen(GL2 gl, GLU glu, Coord3d[][] points){ int viewport[] = getViewPortAsInt(gl); float screencoord[] = new float[3]; Coord3d[][] projection = new Coord3d[points.length][points[0].length]; for (int i = 0; i < points.length; i++) { for (int j = 0; j < points[i].length; j++) { if( ! glu.gluProject( points[i][j].x, points[i][j].y, points[i][j].z, getModelViewAsFloat(gl), 0, getProjectionAsFloat(gl), 0, viewport, 0, screencoord, 0 ) ) throw new RuntimeException("Could not retrieve model coordinates in screen for " + points[i][j]); projection[i][j] = new Coord3d(screencoord[0], screencoord[1], screencoord[2]); } } return projection; } public List<Coord3d> modelToScreen(GL2 gl, GLU glu, List<Coord3d> points){ int viewport[] = getViewPortAsInt(gl); float screencoord[] = new float[3]; List<Coord3d> projection = new Vector<Coord3d>(); for(Coord3d point: points){ if( ! glu.gluProject( point.x, point.y, point.z, getModelViewAsFloat(gl), 0, getProjectionAsFloat(gl), 0, viewport, 0, screencoord, 0 ) ) throw new RuntimeException("Could not retrieve model coordinates in screen for " + point); projection.add( new Coord3d(screencoord[0], screencoord[1], screencoord[2]) ); } return projection; } public ArrayList<ArrayList<Coord3d>> modelToScreen(GL2 gl, GLU glu, ArrayList<ArrayList<Coord3d>> polygons){ int viewport[] = getViewPortAsInt(gl); float screencoord[] = new float[3]; ArrayList<ArrayList<Coord3d>> projections = new ArrayList<ArrayList<Coord3d>>(polygons.size()); for(ArrayList<Coord3d> polygon: polygons){ ArrayList<Coord3d> projection = new ArrayList<Coord3d>(polygon.size()); for(Coord3d point: polygon){ if( ! glu.gluProject( point.x, point.y, point.z, getModelViewAsFloat(gl), 0, getProjectionAsFloat(gl), 0, viewport, 0, screencoord, 0 ) ) throw new RuntimeException("Could not retrieve model coordinates in screen for " + point); projection.add( new Coord3d(screencoord[0], screencoord[1], screencoord[2]) ); } projections.add( projection ); } return projections; } public PolygonArray modelToScreen(GL2 gl, GLU glu, PolygonArray polygon){ int viewport[] = getViewPortAsInt(gl); float screencoord[] = new float[3]; int len = polygon.length(); float[] x = new float[len]; float[] y = new float[len]; float[] z = new float[len]; for (int i = 0; i < len; i++) { if( ! glu.gluProject( polygon.x[i], polygon.y[i], polygon.z[i], getModelViewAsFloat(gl), 0, getProjectionAsFloat(gl), 0, viewport, 0, screencoord, 0 ) ) throw new RuntimeException("Could not retrieve model coordinates in screen for point " + i); x[i] = (float)screencoord[0]; y[i] = (float)screencoord[1]; z[i] = (float)screencoord[2]; } return new PolygonArray(x, y, z); } /*public Grid modelToScreen(GL2 gl, GLU glu, Grid grid){ int viewport[] = getViewPort(gl); double screencoord[] = new double[3]; int xlen = grid.getX().length; int ylen = grid.getY().length; float[] x = new float[xlen]; float[] y = new float[ylen]; float[][] z = new float[xlen][ylen]; for (int i = 0; i < xlen; i++) { for (int j = 0; j < ylen; j++) { if( ! glu.gluProject( grid.getX()[i], grid.getY()[i], grid.getZ()[i][j], getModelView(gl), 0, getProjection(gl), 0, viewport, 0, screencoord, 0 ) ) throw new RuntimeException("Could not retrieve model coordinates in screen for point " + i); x[i] = (float)screencoord[0]; y[j] = (float)screencoord[1]; // STUPID :) z[i][j] = (float)screencoord[2]; } } return new Grid(x, y, z); }*/ public PolygonArray[][] modelToScreen(GL2 gl, GLU glu, PolygonArray[][] polygons){ int viewport[] = getViewPortAsInt(gl); float screencoord[] = new float[3]; PolygonArray[][] projections = new PolygonArray[polygons.length][polygons[0].length]; for (int i = 0; i < polygons.length; i++) { for (int j = 0; j < polygons[i].length; j++) { PolygonArray polygon = polygons[i][j]; int len = polygon.length(); float[] x = new float[len]; float[] y = new float[len]; float[] z = new float[len]; for (int k = 0; k < len; k++) { if( ! glu.gluProject( polygon.x[k], polygon.y[k], polygon.z[k], getModelViewAsFloat(gl), 0, getProjectionAsFloat(gl), 0, viewport, 0, screencoord, 0 ) ) throw new RuntimeException("Could not retrieve model coordinates in screen for point " + k); x[k] = (float)screencoord[0]; y[k] = (float)screencoord[1]; z[k] = (float)screencoord[2]; } projections[i][j] = new PolygonArray(x, y, z); } } return projections; } /*******************************************************************/ protected int[] getViewPortAsInt(GL2 gl){ int viewport[] = new int[4]; gl.glGetIntegerv(GL2.GL_VIEWPORT, viewport, 0); return viewport; } protected double[] getProjectionAsDouble(GL2 gl){ double projection[] = new double[16]; gl.glGetDoublev(GL2.GL_PROJECTION_MATRIX, projection, 0); return projection; } protected float[] getProjectionAsFloat(GL2 gl){ float projection[] = new float[16]; gl.glGetFloatv(GL2.GL_PROJECTION_MATRIX, projection, 0); return projection; } protected double[] getModelViewAsDouble(GL2 gl){ double modelview[] = new double[16]; gl.glGetDoublev(GL2.GL_MODELVIEW_MATRIX, modelview, 0); return modelview; } protected float[] getModelViewAsFloat(GL2 gl){ float modelview[] = new float[16]; gl.glGetFloatv(GL2.GL_MODELVIEW_MATRIX, modelview, 0); return modelview; } /******************************************************************/ /** * Sets the projection, and the mapping of 3d environement to 2d screen. * The projection must be either Camera.PERSPECTIVE or Camera.ORTHOGONAL. * <br> * Finally calls the GL2 function glLookAt, according to the stored * eye, target, up and scale values. * <br> * Note that the Camera set by itselft the MatrixMode to model view * at the end of a shoot(). * <br> * * @param gl GL2 context. * @param glu GLU context. * @param projection the projection mode. * @throws a Runtime Exception if the projection mode is neither Camera.PERSPECTIVE nor Camera.ORTHOGONAL. */ public void shoot(GL2 gl, GLU glu, CameraMode projection){ shoot(gl, glu, projection, false); } public void shoot(GL2 gl, GLU glu, CameraMode projection, boolean doPushMatrixBeforeShooting){ gl.glMatrixMode(GL2.GL_PROJECTION); if(doPushMatrixBeforeShooting) gl.glPushMatrix(); gl.glLoadIdentity(); doShoot(gl, glu, projection); } public void doShoot(GL2 gl, GLU glu, CameraMode projection){ // Set viewport applyViewPort(gl, glu); // Set perspective if(projection==CameraMode.PERSPECTIVE){ glu.gluPerspective( computeFieldOfView(radius*2, eye.distance(target)), stretchToFill?((float)screenWidth)/((float)screenHeight):1, near, far); } else if(projection==CameraMode.ORTHOGONAL){ gl.glOrtho(-radius, +radius, -radius, +radius, near, far); } else throw new RuntimeException("Camera.shoot(): unknown projection mode '" + projection + "'"); // Set camera position glu.gluLookAt(eye.x, eye.y, eye.z, target.x, target.y, target.z, up.x, up.y, up.z); //System.out.println("eye:" + eye); } /** Compute the field of View, in order to occupy the entire screen in PERSPECTIVE mode.*/ protected double computeFieldOfView(double size, double distance){ double radtheta; double degtheta; radtheta = 2.0 * Math.atan2(size/2.0, distance); degtheta = (180.0 * radtheta) / Math.PI; return degtheta; } /********************************************************/ /** * Print out in console information concerning the surface. */ public String toString(){ return toString(eye, target, up); } private String toString(Coord3d eye, Coord3d target, Coord3d up){ String output = "(Camera)"; output += (" lookFrom = {" + eye.x + ", " + eye.y + ", " + eye.z + "}"); output += (" lookTo = {" + target.x + ", " + target.y + ", " + target.z + "}"); output += (" topToward = {" + up.x + ", " + up.y + ", " + up.z + "}"); return output; } /******************************************************************/ protected Coord3d eye; protected Coord3d target; protected Coord3d up; protected float radius; protected float near; protected float far; /** The polar default view point, i.e. Coord3d(Math.PI/3,Math.PI/5,500).*/ protected static final Coord3d DEFAULT_VIEW = new Coord3d(Math.PI/3,Math.PI/5,500); }
36.506053
166
0.622405
49132c226e73abb34b146305073b0f376765cb92
755
package org.jessenpan.leetcode.array; import java.util.HashMap; import java.util.Map; /** * @author jessenpan * tag:array */ public class S169MajorityElement { public int majorityElement(int[] nums) { int lengthOfNums = nums.length; float halfLengthOfNums = (float) (lengthOfNums / 2.0); Map<Integer, Integer> counter = new HashMap<>(); for (int i = 0; i < lengthOfNums; i++) { Integer currentCount = counter.get(nums[i]); currentCount = currentCount == null ? 1 : currentCount + 1; if (currentCount > halfLengthOfNums) { return nums[i]; } else { counter.put(nums[i], currentCount); } } return 0; } }
26.964286
71
0.569536
75334ef7d3728f2117eff79126af7a01d93c4115
363
package com.pawnrace; public class BoardDisplayProgram { public static void main(String[] args){ Board board = new Board('c', 'f'); board.display(); Square w2 = board.getSquare(1,1); Square e2 = board.getSquare(3,1); Move move = new Move(w2, e2, false); board.applyMove(move); board.display(); } }
25.928571
44
0.584022
100ba2ebdf7c98b5fb8f96557b37b4e37b6b15cd
614
package com.rent.project.orderservice.models.productmodels; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.io.Serializable; @Entity @Data @AllArgsConstructor @NoArgsConstructor public class ProductDurationRate implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "duration") private String duration; // @OneToMany(mappedBy = "productDurationRates") // //@JsonBackReference // private Set<product> products; }
22.740741
60
0.732899
d835f025c02bf1af3645bd6dc06eb5c58d283c66
1,706
package com.ibeetl.cms.entity; import java.util.Date; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Null; import org.beetl.sql.core.annotatoin.AutoID; import org.beetl.sql.core.annotatoin.SeqID; import com.ibeetl.admin.core.util.ValidateConfig; import org.beetl.sql.core.TailBean; import java.math.*; import com.ibeetl.admin.core.annotation.Dict; import com.ibeetl.admin.core.entity.BaseEntity; import org.beetl.sql.core.annotatoin.InsertIgnore; import org.beetl.sql.core.annotatoin.Version; import org.beetl.sql.core.annotatoin.LogicDelete; /* * * gen by Spring Boot2 Admin 2020-03-15 */ public class CoreArticle extends BaseEntity{ @NotNull(message = "ID不能为空", groups =ValidateConfig.UPDATE.class) @SeqID(name = ORACLE_CORE_SEQ_NAME) @AutoID private Integer id ; private String title ; private Date pubdata ; private String contents ; private Integer uid ; public CoreArticle(){ } public Integer getId(){ return id; } public void setId(Integer id){ this.id = id; } public String getTitle(){ return title; } public void setTitle(String title){ this.title = title; } public Date getPubdata(){ return pubdata; } public void setPubdata(Date pubdata){ this.pubdata = pubdata; } public String getContents(){ return contents; } public void setContents(String contents){ this.contents = contents; } public Integer getUid(){ return uid; } public void setUid(Integer uid){ this.uid = uid; } }
19.168539
69
0.672919
5855be614f93106a076e3dc9d9f5e08eaaa2c915
7,946
package ownerszz.libraries.dependency.injection.core; import ownerszz.libraries.dependency.injection.annotation.scanner.AnnotationScanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ownerszz.libraries.dependency.injection.logging.ContainerLogger; import java.io.File; import java.io.FilenameFilter; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * Copied from: * * Find classes in the classpath (reads JARs and classpath folders). * https://gist.github.com/pal * @author P&aring;l Brattberg, [email protected] * */ public class ClassScanner { private static final Logger logger = LoggerFactory.getLogger(ClassScanner.class); public static List<Class> scan() throws Throwable{ List<Class> classes = new ArrayList<>(); List<Class> temp = null; try { temp = getAllKnownClasses(); }catch (Throwable ignored){ ContainerLogger.logDebug(logger,ignored.getMessage()); } if (temp == null || temp.size() == 0){ throw new RuntimeException("No classes found"); } for (Class clazz: temp) { try { Boolean resolvable =AnnotationScanner.isResolvable(clazz,1); if (resolvable!= null && resolvable){ classes.add(clazz); } }catch (Throwable ignored){ } } AnnotationScanner.tryResolveSlowClasses(); AnnotationScanner.cleanup(); ContainerLogger.logDebug(logger,"Successfully scanned {} classes", temp.size()); return classes; } public static List<Class> getAllKnownClasses() { List<Class> classFiles = new ArrayList<Class>(); List<File> classLocations = getClassLocationsForCurrentClasspath(); for (File file : classLocations) { try { classFiles.addAll(getClassesFromPath(file)); }catch (Throwable ignored){ ContainerLogger.logDebug(logger,ignored.getMessage()); } } return classFiles; } public static List<Class> getMatchingClasses(Class interfaceOrSuperclass) { List<Class> matchingClasses = new ArrayList<Class>(); List<Class> classes = getAllKnownClasses(); for (Class clazz : classes) { if (interfaceOrSuperclass.isAssignableFrom(clazz)) { matchingClasses.add(clazz); } } return matchingClasses; } public static List<Class> getMatchingClasses(String validPackagePrefix, Class interfaceOrSuperclass) { throw new IllegalStateException("Not yet implemented!"); } public static List<Class> getMatchingClasses(String validPackagePrefix) { throw new IllegalStateException("Not yet implemented!"); } private static Collection<? extends Class> getClassesFromPath(File path) { if (path.isDirectory()) { return getClassesFromDirectory(path); } else { return getClassesFromJarFile(path); } } private static String fromFileToClassName(final String fileName) { return fileName.substring(0, fileName.length() - 6).replaceAll("/|\\\\", "\\."); } private static List<Class> getClassesFromJarFile(File path) { List<Class> classes = new ArrayList<Class>(); try { if (path.canRead()) { JarFile jar = new JarFile(path); Enumeration<JarEntry> en = jar.entries(); while (en.hasMoreElements()) { try { JarEntry entry = en.nextElement(); if (entry.getName().endsWith("class")) { String className = fromFileToClassName(entry.getName()); loadClass(classes, className); } }catch (Throwable e){ } } } } catch (Exception e) { throw new RuntimeException("Failed to read classes from jar file: " + path, e); } return classes; } private static List<Class> getClassesFromDirectory(File path) { List<Class> classes = new ArrayList<Class>(); // get jar files from top-level directory List<File> jarFiles = listFiles(path, new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".jar"); } }, false); for (File file : jarFiles) { classes.addAll(getClassesFromJarFile(file)); } // get all class-files List<File> classFiles = listFiles(path, new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".class"); } }, true); // List<URL> urlList = new ArrayList<URL>(); // List<String> classNameList = new ArrayList<String>(); int substringBeginIndex = path.getAbsolutePath().length() + 1; for (File classfile : classFiles) { try { String className = classfile.getAbsolutePath().substring(substringBeginIndex); className = fromFileToClassName(className); loadClass(classes, className); }catch (Throwable ignored){ } } return classes; } private static List<File> listFiles(File directory, FilenameFilter filter, boolean recurse) { List<File> files = new ArrayList<File>(); File[] entries = directory.listFiles(); // Go over entries for (File entry : entries) { // If there is no filter or the filter accepts the // file / directory, add it to the list if (filter == null || filter.accept(directory, entry.getName())) { files.add(entry); } // If the file is a directory and the recurse flag // is set, recurse into the directory if (recurse && entry.isDirectory()) { files.addAll(listFiles(entry, filter, recurse)); } } // Return collection of files return files; } public static List<File> getClassLocationsForCurrentClasspath() { List<File> urls = new ArrayList<File>(); String javaClassPath = System.getProperty("java.class.path"); if (javaClassPath != null) { for (String path : javaClassPath.split(File.pathSeparator)) { urls.add(new File(path)); } } return urls; } // todo: this is only partial, probably public static URL normalize(URL url) throws MalformedURLException { String spec = url.getFile(); // get url base - remove everything after ".jar!/??" , if exists final int i = spec.indexOf("!/"); if (i != -1) { spec = spec.substring(0, spec.indexOf("!/")); } // uppercase windows drive url = new URL(url, spec); final String file = url.getFile(); final int i1 = file.indexOf(':'); if (i1 != -1) { String drive = file.substring(i1 - 1, 2).toUpperCase(); url = new URL(url, file.substring(0, i1 - 1) + drive + file.substring(i1)); } return url; } private static void loadClass(List<Class> classes, String className) { try { Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); classes.add(clazz); } catch (Throwable ignored) { ContainerLogger.logDebug(logger,"Failed to load class: " + className); } } }
34.103004
106
0.583942
caf521d0cbde13af9c35129d253b222d80356d73
3,310
package com.github.cc3002.finalreality.controller; import com.github.matiasvergaras.finalreality.controller.GameController; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; /** * A class to check that game will be only in one state at a time. * @since Homework 2 * @author Matías Vergara Silva */ public class StateTest { /** * Same as the test of an effective attack from player to cpu but * here the focus is to check if the game is in only one state * at a time. * Test an effective attack from player to cpu. */ @RepeatedTest(3) void EffectivePlayerToCPUAttackTest() throws InterruptedException { GameController gc = new GameController("Player", "CPU", 1); //Check that the game is only in initializing mode. assertTrue(gc.isInitializing()); assertFalse(gc.isFinished()); assertFalse(gc.isActive()); assertFalse(gc.isSettingNewTurn()); assertFalse(gc.isCPUTurn()); assertFalse(gc.isPlayerTurn()); assertFalse(gc.isPerformingAttack()); assertFalse(gc.isSelectingAttackTarget()); //Adds an Engineer to the player party. gc.setSelectedCharacterFactory(0); gc.selectedCharacterFactoryProduce("Domingo Egg"); //Adds an Enemy to the CPU party. gc.setSelectedCharacterFactory(5); gc.selectedCharacterFactoryProduce("Chaos"); //Sets bow factory to create the definitive bow with 10000 power. gc.setSelectedWeaponFactory(0); gc.setSelectedWeaponFactoryPower(10000); //To make sure that the engineer will get the turn at first. gc.setSelectedWeaponFactoryWeight(0); //Instantiate a definitive bow and add it to inventory. Select it. gc.selectedWeaponFactoryProduce("Elbow"); gc.setSelectedWeapon(0); //Sets Domingo Egg as selectedCharacter gc.setSelectedCharacterFromPlayerParty(0); //Equips the bow to Domingo gc.equipSelectedWeaponToSelectedCharacter(); //Starts the game gc.startGame(); //Check that the gameController is only in active mode. assertTrue(gc.isActive()); assertFalse(gc.isFinished()); assertFalse(gc.isInitializing()); //Give some time to make sure that there will be characters in //the queue (as in ActiveCharacter variable). Thread.sleep(3000); //Select Chaos as SelectedCharacter gc.setSelectedCharacterFromCPUParty(0); //Start a attack-movement gc.initAttackMove(); assertTrue(gc.isSelectingAttackTarget()); //Cancel attack-movement gc.cancelAttackMove(); assertTrue(gc.isPlayerTurn()); //Re-start attack gc.initAttackMove(); assertTrue(gc.isSelectingAttackTarget()); assertEquals(gc.getActiveCharacter().getName(), "Domingo Egg"); gc.activeCharacterNormalAttackSelectedCharacter(); //Check that the enemy died. assertFalse(gc.getSelectedCharacter().isAlive()); //Check that the game ended and is only in finished mode. assertTrue(gc.isFinished()); assertFalse(gc.isInitializing()); assertFalse(gc.isActive()); } }
39.404762
74
0.671903
1e170fc93bf92a41ef4bbddf89e52f87624f354e
1,515
/* * Copyright (C) 2009-2016 Hangzhou 2Dfire Technology Co., Ltd. All rights reserved */ package dfire.ziyuan; import dfire.ziyuan.exceptions.FKCException; import java.util.Iterator; import java.util.ServiceLoader; /** * IncubatorFactory 生产incubator的工厂 * * @author ziyuan * @since 2017-01-06 */ public enum IncubatorFactory { INSTANCE; /** * 使用java的spi获取一个Incubator * * @return */ public Incubator getIncubator() throws FKCException { Incubator incubator; ServiceLoader<Incubator> serviceLoader = ServiceLoader.load(Incubator.class); Iterator<Incubator> incubators = serviceLoader.iterator(); if (incubators.hasNext()) { incubator = incubators.next(); return incubator; } throw new FKCException("没有找到相关的SPI扩展实现", System.currentTimeMillis()); } /** * 使用java的spi获取一个Incubator * * @return */ public Incubator getIncubator(KryoPoolConfig kryoPoolConfig) throws FKCException { Incubator incubator; ServiceLoader<Incubator> serviceLoader = ServiceLoader.load(Incubator.class); Iterator<Incubator> incubators = serviceLoader.iterator(); if (incubators.hasNext()) { incubator = incubators.next(); //这里考虑有没有更好的实现方式 ((DefaultIncubator) incubator).setKryoPoolConfig(kryoPoolConfig); return incubator; } throw new FKCException("没有找到相关的SPI扩展实现", System.currentTimeMillis()); } }
27.545455
86
0.658086
aa95638d07ebbeadf412e0e9325cd10edc5af380
2,917
package graphql.resolvers.mutation; import com.linkedin.common.urn.CorpuserUrn; import com.linkedin.datahub.graphql.exception.AuthenticationException; import com.linkedin.datahub.graphql.exception.ValidationException; import com.linkedin.datahub.graphql.generated.CorpUser; import com.linkedin.datahub.graphql.loaders.CorpUserLoader; import com.linkedin.datahub.graphql.mappers.CorpUserMapper; import graphql.PlayQueryContext; import graphql.schema.DataFetcher; import graphql.schema.DataFetchingEnvironment; import org.apache.commons.lang3.StringUtils; import org.dataloader.DataLoader; import play.Logger; import security.AuthUtil; import security.AuthenticationManager; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.concurrent.CompletableFuture; import static security.AuthConstants.*; /** * Resolver responsible for authenticating a user */ public class LogInResolver implements DataFetcher<CompletableFuture<CorpUser>> { @Override public CompletableFuture<CorpUser> get(DataFetchingEnvironment environment) throws Exception { /* Extract arguments */ final String username = environment.getArgument(USER_NAME); final String password = environment.getArgument(PASSWORD); if (StringUtils.isBlank(username)) { throw new ValidationException("username must not be empty"); } PlayQueryContext context = environment.getContext(); context.getSession().clear(); // Create a uuid string for this session if one doesn't already exist String uuid = context.getSession().get(UUID); if (uuid == null) { uuid = java.util.UUID.randomUUID().toString(); context.getSession().put(UUID, uuid); } try { AuthenticationManager.authenticateUser(username, password); } catch (javax.naming.AuthenticationException e) { throw new AuthenticationException("Failed to authenticate user", e); } context.getSession().put(USER, username); String secretKey = context.getAppConfig().getString(SECRET_KEY_PROPERTY); try { // store hashed username within PLAY_SESSION cookie String hashedUserName = AuthUtil.generateHash(username, secretKey.getBytes()); context.getSession().put(AUTH_TOKEN, hashedUserName); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException("Failed to hash username", e); } /* Fetch the latest version of the logged in user. (via CorpUser entity) */ final DataLoader<String, com.linkedin.identity.CorpUser> userLoader = environment.getDataLoader(CorpUserLoader.NAME); return userLoader.load(new CorpuserUrn(username).toString()) .thenApply(CorpUserMapper::map); } }
37.883117
125
0.713747
8075e3561f821b62c6df0b9d0a52f3b827d0c8fa
2,340
/* * Copyright 2016 Flinbor Bogdanov Oleksandr * * 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 in.flinbor.github.publicRepositories.presenter; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import in.flinbor.github.publicRepositories.model.Model; import in.flinbor.github.publicRepositories.presenter.vo.Repository; import in.flinbor.github.publicRepositories.view.fragment.RepoListView; /** * The presenter acts upon the model and the view. * Retrieves data from Model, and formats it for display in the View. */ public interface RepoListPresenter { /** * Set View interface to Presenter layer * * @param view {@link RepoListView} */ void setView(@NonNull RepoListView view); /** * Set model interface to Presenter layer * * @param model {@link Model} */ void setModel(Model model); /** * View created, Restore state * * @param savedInstanceState The bundle with stored state */ void onCreateView(@Nullable Bundle savedInstanceState); /** * On a long click on a list item * @param repository that was clicked */ void longClickRepo(Repository repository); /** * List scrolled to optimal position for request new data * * @param lastReportId The integer ID of the last Repository that you've seen. */ void loadPointReached(int lastReportId); /** * Lifecycle of view - in fragment onResume called */ void onResume(); /** * Lifecycle of view - in fragment onPause called */ void onPause(); /** * Store data before view destroyed * * @param outState The bundle to store into */ void storeState(Bundle outState); }
27.857143
82
0.682051
ff8913ff8826fa0b11dc714caa9ba6ccbf2ecac0
1,631
package ru.intertrust.cm.core.business.impl.universalentity; import java.util.Collection; import javax.annotation.Nonnull; import ru.intertrust.cm.core.business.api.dto.universalentity.EnumProcessor; import ru.intertrust.cm.core.business.api.dto.universalentity.NonAbstract; import ru.intertrust.cm.core.util.Args; import ru.intertrust.cm.core.util.PackagesScanner; public abstract class ConfigurationSupport { public static void readConfiguration (final @Nonnull String... packageNames) { (new PackagesScanner()).addPackages(Args.notNull(packageNames, "packageNames")).addAnnotationFinder(NonAbstract.class, new Processor()).scan(); } @Nonnull static <T> EnumProcessor<T> getEnumProcessor (final @Nonnull Class<T> clazz) { throw new UnsupportedOperationException(); // TODO } @Nonnull static ClassMeta getClassMeta (final @Nonnull String dopType) { throw new UnsupportedOperationException(); // TODO } @Nonnull static ClassMeta getClassMeta (final @Nonnull Class<?> clazz) { throw new UnsupportedOperationException(); // TODO } @Nonnull static Collection<Collection<String>> getUniqueConstraints (final @Nonnull Class<?> clazz) { throw new UnsupportedOperationException(); // TODO } private static class Processor implements PackagesScanner.ClassFoundCallback { @Override public void processClass (final Class<?> foundClass) { throw new UnsupportedOperationException(); // TODO } } private ConfigurationSupport () { } }
32.62
152
0.699571
cc90ac9a1130d416c700e369fee053a2fcedeabc
2,388
/* * Copyright (c) 2016-2021 Flux Capacitor. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fluxcapacitor.javaclient.test.spring; import io.fluxcapacitor.javaclient.FluxCapacitor; import io.fluxcapacitor.javaclient.configuration.FluxCapacitorBuilder; import io.fluxcapacitor.javaclient.configuration.client.Client; import io.fluxcapacitor.javaclient.configuration.client.WebSocketClient; import io.fluxcapacitor.javaclient.configuration.spring.FluxCapacitorSpringConfig; import io.fluxcapacitor.javaclient.test.TestFixture; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Primary; import java.util.Optional; @Configuration @AllArgsConstructor @Import(FluxCapacitorSpringConfig.class) @Slf4j public class FluxCapacitorTestConfig { private final ApplicationContext context; @Bean @Primary public FluxCapacitor fluxCapacitor(TestFixture testFixture) { return testFixture.getFluxCapacitor(); } @Bean public TestFixture testFixture(FluxCapacitorBuilder fluxCapacitorBuilder) { fluxCapacitorBuilder.makeApplicationInstance(false); Client client = getBean(Client.class).orElseGet(() -> getBean(WebSocketClient.ClientConfig.class).<Client>map( WebSocketClient::newInstance).orElse(null)); if (client == null) { return TestFixture.createAsync(fluxCapacitorBuilder); } return TestFixture.createAsync(fluxCapacitorBuilder, client); } protected <T> Optional<T> getBean(Class<T> type) { return context.getBeansOfType(type).values().stream().findFirst(); } }
37.3125
118
0.773869
867c92a901aff5e146e768b287996315209dc516
9,156
/* * HDDM_W_Test.java * * @author Isvani Frias-Blanco ([email protected]) * * 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 moa.classifiers.core.driftdetection; import moa.core.ObjectRepository; import moa.options.FloatOption; import moa.options.MultiChoiceOption; import moa.tasks.TaskMonitor; /** * <p>Online drift detection method based on McDiarmid's bounds. * HDDM<sub><i>W</i>-test</sub> uses the EWMA statistic as estimator. * It receives as input a stream of real values and returns the estimated status * of the stream: STABLE, WARNING or DRIFT.</p> * * <p>I. Frias-Blanco, J. del Campo-Avila, G. Ramos-Jimenez, R. Morales-Bueno, * A. Ortiz-Diaz, and Y. Caballero-Mota, Online and non-parametric drift * detection methods based on Hoeffding's bound, IEEE Transactions on Knowledge * and Data Engineering, 2014. DOI 10.1109/TKDE.2014.2345382.</p> * * <p>Parameters:</p> <ul> <li>-d : Confidence to the drift</li><li>-w : * Confidence to the warning</li><li>-m : Controls how much weight is given to * more recent data compared to older data. Smaller values mean less weight * given to recent data</li><li>-t : Option to monitor error increments and * decrements (two-sided) or only increments (one-sided)</li> * </ul> * * @author Isvani Frias-Blanco ([email protected]) * */ public class HDDM_W_Test extends AbstractChangeDetector { protected static final long serialVersionUID = 1L; public FloatOption driftConfidenceOption = new FloatOption("driftConfidence", 'd', "Confidence to the drift", 0.001, 0, 1); public FloatOption warningConfidenceOption = new FloatOption("warningConfidence", 'w', "Confidence to the warning", 0.005, 0, 1); public FloatOption lambdaOption = new FloatOption("lambda", 'm', "Controls how much weight is given to more recent data compared to older data. Smaller values mean less weight given to recent data.", 0.050, 0, 1); public MultiChoiceOption oneSidedTestOption = new MultiChoiceOption( "typeOfTest", 't', "Monitors error increments and decrements (two-sided) or only increments (one-sided)", new String[]{ "One-sided", "Two-sided"}, new String[]{ "One-sided", "Two-sided"}, 0); public static class SampleInfo { private static final long serialVersionUID = 1L; public double EWMA_Estimator; public double independentBoundedConditionSum; public SampleInfo() { this.EWMA_Estimator = -1.0; } } private static SampleInfo sample1_IncrMonitoring, sample2_IncrMonitoring, sample1_DecrMonitoring, sample2_DecrMonitoring, total; protected double incrCutPoint, decrCutPoint; protected double lambda; protected double warningConfidence; protected double driftConfidence; protected boolean oneSidedTest; protected int width; public HDDM_W_Test() { resetLearning(); } @Override public void resetLearning() { super.resetLearning(); this.total = new SampleInfo(); this.sample1_DecrMonitoring = new SampleInfo(); this.sample1_IncrMonitoring = new SampleInfo(); this.sample2_DecrMonitoring = new SampleInfo(); this.sample2_IncrMonitoring = new SampleInfo(); this.incrCutPoint = Double.MAX_VALUE; this.decrCutPoint = Double.MIN_VALUE; this.lambda = this.lambdaOption.getValue(); this.driftConfidence = this.driftConfidenceOption.getValue(); this.warningConfidence = this.warningConfidenceOption.getValue(); this.oneSidedTest = this.oneSidedTestOption.getChosenIndex() == 0; this.width = 0; this.delay = 0; } public void input(boolean prediction) { double value = prediction == false ? 1.0 : 0.0; input(value); } @Override public void input(double value) { double auxDecayRate = 1.0 - lambda; this.width++; if (total.EWMA_Estimator < 0) { total.EWMA_Estimator = value; total.independentBoundedConditionSum = 1; } else { total.EWMA_Estimator = lambda * value + auxDecayRate * total.EWMA_Estimator; total.independentBoundedConditionSum = lambda * lambda + auxDecayRate * auxDecayRate * total.independentBoundedConditionSum; } updateIncrStatistics(value, driftConfidence); if (monitorMeanIncr(value, driftConfidence)) { resetLearning(); this.isChangeDetected = true; this.isWarningZone = false; } else if (monitorMeanIncr(value, warningConfidence)) { this.isChangeDetected = false; this.isWarningZone = true; } else { this.isChangeDetected = false; this.isWarningZone = false; } updateDecrStatistics(value, driftConfidence); if (!oneSidedTest && monitorMeanDecr(value, driftConfidence)) { resetLearning(); } this.estimation = this.total.EWMA_Estimator; } public boolean detectMeanIncrement(SampleInfo sample1, SampleInfo sample2, double confidence) { if (sample1.EWMA_Estimator < 0 || sample2.EWMA_Estimator < 0) { return false; } double bound = Math.sqrt((sample1.independentBoundedConditionSum + sample2.independentBoundedConditionSum) * Math.log(1 / confidence) / 2); return sample2.EWMA_Estimator - sample1.EWMA_Estimator > bound; } void updateIncrStatistics(double valor, double confidence) { double auxDecay = 1.0 - lambda; double bound = Math.sqrt(total.independentBoundedConditionSum * Math.log(1.0 / driftConfidence) / 2); if (total.EWMA_Estimator + bound < incrCutPoint) { incrCutPoint = total.EWMA_Estimator + bound; sample1_IncrMonitoring.EWMA_Estimator = total.EWMA_Estimator; sample1_IncrMonitoring.independentBoundedConditionSum = total.independentBoundedConditionSum; sample2_IncrMonitoring = new SampleInfo(); this.delay = 0; } else { this.delay++; if (sample2_IncrMonitoring.EWMA_Estimator < 0) { sample2_IncrMonitoring.EWMA_Estimator = valor; sample2_IncrMonitoring.independentBoundedConditionSum = 1; } else { sample2_IncrMonitoring.EWMA_Estimator = lambda * valor + auxDecay * sample2_IncrMonitoring.EWMA_Estimator; sample2_IncrMonitoring.independentBoundedConditionSum = lambda * lambda + auxDecay * auxDecay * sample2_IncrMonitoring.independentBoundedConditionSum; } } } protected boolean monitorMeanIncr(double valor, double confidence) { return detectMeanIncrement(sample1_IncrMonitoring, sample2_IncrMonitoring, confidence); } void updateDecrStatistics(double valor, double confidence) { double auxDecay = 1.0 - lambda; double epsilon = Math.sqrt(total.independentBoundedConditionSum * Math.log(1.0 / driftConfidence) / 2); if (total.EWMA_Estimator - epsilon > decrCutPoint) { decrCutPoint = total.EWMA_Estimator - epsilon; sample1_DecrMonitoring.EWMA_Estimator = total.EWMA_Estimator; sample1_DecrMonitoring.independentBoundedConditionSum = total.independentBoundedConditionSum; sample2_DecrMonitoring = new SampleInfo(); } else { if (sample2_DecrMonitoring.EWMA_Estimator < 0) { sample2_DecrMonitoring.EWMA_Estimator = valor; sample2_DecrMonitoring.independentBoundedConditionSum = 1; } else { sample2_DecrMonitoring.EWMA_Estimator = lambda * valor + auxDecay * sample2_DecrMonitoring.EWMA_Estimator; sample2_DecrMonitoring.independentBoundedConditionSum = lambda * lambda + auxDecay * auxDecay * sample2_DecrMonitoring.independentBoundedConditionSum; } } } protected boolean monitorMeanDecr(double valor, double confidence) { return detectMeanIncrement(sample2_DecrMonitoring, sample1_DecrMonitoring, confidence); } @Override protected void prepareForUseImpl(TaskMonitor monitor, ObjectRepository repository) { resetLearning(); } public void getDescription(StringBuilder sb, int indent) { } }
42.586047
170
0.66066
7d8cb1fd18c67fe352b9556418e164d1f4bcac98
1,271
package lv.llu.science.dwh.domain.metadata; import com.mongodb.DBObject; import lv.llu.science.utils.time.TimeMachine; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.stereotype.Service; import java.util.Optional; import static java.util.Optional.ofNullable; @Service public class MetadataService { private final MongoOperations operations; private final TimeMachine timeMachine; @Autowired public MetadataService(MongoOperations operations, TimeMachine timeMachine) { this.operations = operations; this.timeMachine = timeMachine; } public void registerEvent(EventType eventType, DBObject metadata) { Event event = new Event(); event.setEventTs(timeMachine.now()); event.setType(eventType); event.setMetadata(metadata); operations.save(event); if (eventType == EventType.ReportUpdated) { operations.save(new ReportMetadata(metadata.get("reportId").toString(), timeMachine.now())); } } public Optional<ReportMetadata> getReportMetadata(String reportId) { return ofNullable(operations.findById(reportId, ReportMetadata.class)); } }
31
104
0.733281
28862a5bcb7f3c968b6b08b5f60a48c48ddbfeba
1,033
package br.edu.uepb.nutes.haniot.data.model; import android.content.Context; import br.edu.uepb.nutes.haniot.R; /** * Contains constants that represent the type of measurement context. * * @author Douglas Rafael <[email protected]> * @version 1.0 * @copyright Copyright (c) 2017, NUTES UEPB */ public class ContextMeasurementType { public static final int GLUCOSE_CARBOHYDRATE = 1; public static final int GLUCOSE_MEAL = 2; public static final int GLUCOSE_LOCATION = 3; public static final int GLUCOSE_TYPE = 4; public static final int TEMPERATURE_TYPE = 5; /** * Retrieve the mapped type name in resources. * * @param context ContextMeasurement * @param type int * @return String */ public static String getString(Context context, int type) { String types[] = context.getResources().getStringArray(R.array.measurement_context_types_array); if (type < 1 || type > types.length) return ""; return types[type - 1]; } }
28.694444
104
0.688287
f785144b0a5363cf91466a2383a73e6f80c9ab86
207
package org.code.completion.custom; /** * Fraze */ public class Frase { public String text; public int offset; public Frase(String text, int offset) { this.text = text; this.offset = offset; } }
13.8
40
0.676329
215695d25b6a3380a30a7bacc4032070ff34579a
1,399
package at.porscheinformatik.tapestry.csrfprotection.tests.auto.services; import org.apache.tapestry5.SymbolConstants; import at.porscheinformatik.tapestry.csrfprotection.CsrfConstants; import at.porscheinformatik.tapestry.csrfprotection.CsrfProtectionMode; import org.apache.tapestry5.commons.Configuration; import org.apache.tapestry5.commons.MappedConfiguration; import org.apache.tapestry5.ioc.ServiceBinder; import org.apache.tapestry5.services.LibraryMapping; /** * The integration test contain a module definition for each mode of the cross-site request forgery protection. This * module configures the auto mode for the tests. */ public class AutoModeModule { public static void bind(ServiceBinder binder) { } public static void contributeApplicationDefaults( MappedConfiguration<String, String> configuration) { configuration.add(SymbolConstants.SUPPORTED_LOCALES, "en"); configuration.add(SymbolConstants.PRODUCTION_MODE, "false"); configuration.add(SymbolConstants.APPLICATION_VERSION, "1.0-SNAPSHOT"); configuration.add(CsrfConstants.CSRF_PROTECTION_MODE, CsrfProtectionMode.AUTO.name()); } public static void contributeComponentClassResolver(Configuration<LibraryMapping> configuration) { configuration.add(new LibraryMapping("", "at.porscheinformatik.tapestry.csrfprotection.tests.auto")); } }
39.971429
116
0.787706
ef524a689f106737697d795d93d14336a8c8829c
18,466
package ch.sbb.maven.plugins.iib.mojos; import static org.twdata.maven.mojoexecutor.MojoExecutor.artifactId; import static org.twdata.maven.mojoexecutor.MojoExecutor.configuration; import static org.twdata.maven.mojoexecutor.MojoExecutor.element; import static org.twdata.maven.mojoexecutor.MojoExecutor.executeMojo; import static org.twdata.maven.mojoexecutor.MojoExecutor.executionEnvironment; import static org.twdata.maven.mojoexecutor.MojoExecutor.goal; import static org.twdata.maven.mojoexecutor.MojoExecutor.groupId; import static org.twdata.maven.mojoexecutor.MojoExecutor.name; import static org.twdata.maven.mojoexecutor.MojoExecutor.plugin; import static org.twdata.maven.mojoexecutor.MojoExecutor.version; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Enumeration; import java.util.List; import java.util.Properties; import org.apache.commons.io.FilenameUtils; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.BuildPluginManager; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.twdata.maven.mojoexecutor.MojoExecutor.ExecutionEnvironment; import ch.sbb.maven.plugins.iib.utils.ApplyBarOverride; import ch.sbb.maven.plugins.iib.utils.ConfigurableProperties; import ch.sbb.maven.plugins.iib.utils.ConfigurationValidator; import ch.sbb.maven.plugins.iib.utils.ReadBar; import ch.sbb.maven.plugins.iib.utils.SkipUtil; import com.ibm.broker.config.proxy.LogEntry; /** * Validates override .properties files and (optionally) applies them to the default .bar file. */ @Mojo(name = "apply-bar-overrides", defaultPhase = LifecyclePhase.PROCESS_CLASSES) public class ApplyBarOverridesMojo extends AbstractMojo { /** * Whether the applybaroverride command should be executed or not */ @Parameter(property = "applyBarOverrides", defaultValue = "true", required = true) protected Boolean applyBarOverrides; /** * The basename of the trace file to use when applybaroverriding bar files */ @Parameter(property = "applyBarOverrideTraceFile", defaultValue = "${project.build.directory}/applybaroverridetrace.txt", required = true) protected File applyBarOverrideTraceFile; /** * The name of the BAR (compressed file format) archive file where the result is stored. * */ @Parameter(property = "barName", defaultValue = "${project.build.directory}/${project.artifactId}-${project.version}.bar", required = true) protected File barName; /** * The name of the default properties file to be generated from the bar file. * */ @Parameter(property = "defaultPropertiesFile", defaultValue = "${project.build.directory}/default.properties", required = true) protected File defaultPropertiesFile; /** * Whether or not to fail the build if properties are found to be invalid. */ @Parameter(property = "failOnInvalidProperties", defaultValue = "true", required = true) protected Boolean failOnInvalidProperties; /** * The Maven Project Object */ @Parameter(property = "project", required = true, readonly = true) protected MavenProject project; /** * The Maven Session Object */ @Parameter(property = "session", required = true, readonly = true) protected MavenSession session; /** * The Maven PluginManager Object */ @Component protected BuildPluginManager buildPluginManager; public void execute() throws MojoFailureException { if (new SkipUtil().isSkip(this.getClass())) { return; } copyAndFilterResources(); getLog().info("Reading bar file: " + barName); // / gets the overridable properties from readbar ConfigurableProperties overridableProperties; try { overridableProperties = getOverridableProperties(); } catch (IOException e) { throw new MojoFailureException("Error extracting configurable properties from bar file: " + barName.getAbsolutePath(), e); } // / writes the overridable properties to the default properties file writeToFile(overridableProperties, defaultPropertiesFile); // / create a defined-default.properties file writeDefinedDefaultProperties(overridableProperties); // / copy the default properties file to iib-overrides\<<artifactId>>.properties File defaultBarFilePropsDirectory = new File(project.getBuild().getDirectory(), "iib-overrides"); defaultBarFilePropsDirectory.mkdirs(); validatePropertiesFiles(overridableProperties); if (applyBarOverrides) { executeApplyBarOverrides(); } } private void writeDefinedDefaultProperties(ConfigurableProperties overridableProperties) { File definedPropertiesFile = new File(defaultPropertiesFile.getParentFile(), "defined-default.properties"); Properties definedProperties = new Properties(); for (String key : overridableProperties.keySet()) { String value = overridableProperties.get(key); boolean isDefined = value != null && !value.trim().isEmpty(); if (isDefined) { definedProperties.setProperty(key, value); } } FileOutputStream fos; try { fos = new FileOutputStream(definedPropertiesFile); String message = "This contains only the defined values of the default.properties produced by mqsiread of bar file."; definedProperties.store(fos, message); fos.flush(); fos.close(); } catch (Exception e) { getLog().warn("unable to write defined-default.properties file to " + definedPropertiesFile.getAbsolutePath()); getLog().warn(e.toString()); } } private void copyAndFilterResources() throws MojoFailureException { getLog().debug("Project Build Resources: " + project.getBuild().getResources().toString()); try { validateResourceDirectories(); // copy the main resources Plugin copyResourcesPlugin = plugin(groupId("org.apache.maven.plugins"), artifactId("maven-resources-plugin"), version("2.6")); String goal = goal("copy-resources"); Xpp3Dom resourcesConfiguration = configuration( element(name("outputDirectory"), "${project.build.directory}/iib-overrides"), // The output directory into which to copy the resources. element(name("resources"), element(name("resource"), // The list of resources we want to transfer. See the Maven Model for a description of how to code the resources element. // TODO hard-coding this isn't great form // see also ValidateConfigurablePropertiesMojo.java element(name("directory"), "src/main/resources"), // right now, this value is hardcoded to default value element(name("filtering"), "true"))) // If false, don't use the filters specified in the build/filters section of the POM when processing resources in this mojo execution. ); ExecutionEnvironment executionEnvironment = executionEnvironment(project, session, buildPluginManager); executeMojo(copyResourcesPlugin, goal, resourcesConfiguration, executionEnvironment); } catch (MojoExecutionException e) { throw new MojoFailureException("Error while copying and filtering resources", e); } } /** * */ private void validateResourceDirectories() { String warning = null; String resourceDirectoryPath = project.getBasedir().getAbsolutePath(); if (!resourceDirectoryPath.endsWith(File.separator)) { resourceDirectoryPath += File.separator; } resourceDirectoryPath += "src" + File.separator + "main" + File.separator + "resources"; File resourceDirectory = new File(resourceDirectoryPath); if (!resourceDirectory.exists() || !resourceDirectory.isDirectory()) { warning = "No resource directory found at " + resourceDirectoryPath; getLog().warn(warning); } else { File[] resourceFiles = resourceDirectory.listFiles(); if (resourceFiles == null || resourceFiles.length == 0) { warning = "No resources found in resource directory at " + resourceDirectoryPath; getLog().warn(warning); } } if (warning != null) { String projectBaseDir = project.getBasedir().getAbsolutePath(); ConfigurationValidator.warnOnApplyBarOverrides(projectBaseDir, resourceDirectory, getLog(), warning); } } private void executeApplyBarOverrides() throws MojoFailureException { for (File propFile : getTargetPropertiesFiles()) { // / if ENVIRONMENT1.properties in the src\main\resources\ directory is a prop file, // / then ENVIRONMENT1.properties gets written to /target/iib-overrides/ENVIRONMENT1.properties // / the resulting target bar file name should be // / then the targetBarFilename should be target\iib\xyz.bar // / then the targetBarFile gets populated with the combination of the output bar and the propFile String baseFilename = project.getArtifactId() + "-" + project.getVersion() + "-" + FilenameUtils.getBaseName(propFile.getName()); // / HDR-6.0-ENVIRONMENT1 String barFileName = baseFilename + ".bar"; // / HDR-6.0-ENVIRONMENT1.bar String brokerFileName = FilenameUtils.getBaseName(propFile.getName()) + ".broker"; // ENVIRONMENT1.properties String serverFileName = FilenameUtils.getBaseName(propFile.getName()) + ".config"; // ENVIRONMENT1.config String targetBarFilename = (new File(propFile.getParent(), barFileName)).getAbsolutePath(); // ...target/iib-overrides/HDR-6.0-ENVIRONMENT1.bar String targetBrokerFilename = (new File(propFile.getParent(), brokerFileName)).getAbsolutePath(); // ...target/iib-overrides/ENVIRONMENT1.broker String targetConfigFilename = (new File(propFile.getParent(), serverFileName)).getAbsolutePath(); // ...target/iib-overrides/ENVIRONMENT1.config checkTargetBrokerFilePresent(targetBarFilename, targetBrokerFilename); checkTargetConfigFilePresent(targetConfigFilename); try { getLog().info("applybaroverrides being executed against " + barName + " with properties " + propFile); Enumeration<LogEntry> logEntries = ApplyBarOverride.applyBarOverride(barName.getAbsolutePath(), propFile.getAbsolutePath(), targetBarFilename); getLog().info("applybaroverrides successfully created " + targetBarFilename); writeTraceFile(logEntries, propFile); } catch (IOException e) { // TODO handle exception throw new MojoFailureException("Error applying properties file " + propFile.getAbsolutePath(), e); } } } private void checkTargetConfigFilePresent(String targetConfigFilename) { // / check for the presence of the targetConfigFilename and warn if it not present or not populated File targetConfigFile = new File(targetConfigFilename); if (!targetConfigFile.exists()) { String message = "No server file found with name " + targetConfigFile.getName(); getLog().warn(message); } } private void checkTargetBrokerFilePresent(String targetBarFilename, String targetBrokerFilename) { // / check for the presence of the targetBrokerFilename and warn if it not present File targetBrokerFile = new File(targetBrokerFilename); if (!targetBrokerFile.exists()) { String message = "No broker file found with name " + targetBrokerFile.getName() + "; The bar file at '" + targetBarFilename + "' will not be deployed"; getLog().warn(message); message = "For instructions on creating a broker file - See https://www-01.ibm.com/support/knowledgecenter/SSMKHH_9.0.0/com.ibm.etools.mft.doc/be10460_.htm"; getLog().warn(message); } } /** * @param logEntries * @param propFile */ private void writeTraceFile(Enumeration<LogEntry> logEntries, File propFile) { String traceFilePath = getTraceFileParameter(propFile); if (logEntries == null) { getLog().info("logEntries are null; no entries to write to " + traceFilePath); new File(traceFilePath).delete(); return; } if (!logEntries.hasMoreElements()) { getLog().info("no logEntries to write to " + traceFilePath); new File(traceFilePath).delete(); return; } try { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(traceFilePath))); while (logEntries.hasMoreElements()) { LogEntry logEntry = logEntries.nextElement(); writer.write(logEntry.toString()); } writer.flush(); writer.close(); } catch (IOException e) { // TODO handle exception throw new RuntimeException(e); } } /** * @param propFile the name of the apply bar override property file * @return the value to be passed to the (-v) Trace parameter on the command line */ protected String getTraceFileParameter(File propFile) { String filename = FilenameUtils.getBaseName(applyBarOverrideTraceFile.getAbsolutePath()) + "-" + FilenameUtils.getBaseName(propFile.getName()) + ".txt"; String directory = propFile.getParent(); return new File(directory, filename).getAbsolutePath(); } /** * This finds all of the properties files from the resource directories (except for the default.properties). * It checks to see if the resource and test resource property files don't have properties that * are not discoverable in the bar file using readbar command. * * * @param overrideableProperties * @throws MojoFailureException */ private void validatePropertiesFiles(ConfigurableProperties overrideableProperties) throws MojoFailureException { boolean invalidPropertiesFound = false; List<File> propFiles = null; propFiles = getTargetPropertiesFiles(); getLog().info("Validating properties files"); for (File file : propFiles) { getLog().info(" " + file.getAbsolutePath()); try { ConfigurableProperties definedProps = new ConfigurableProperties(); definedProps.load(defaultPropertiesFile); // check if all the defined properties are valid if (!overrideableProperties.keySet().containsAll(definedProps.keySet())) { getLog().error("Invalid properties found in " + file.getAbsolutePath()); invalidPropertiesFound = true; // list the invalid properties in this file for (Object definedProp : definedProps.keySet()) { if (!overrideableProperties.containsKey(ConfigurableProperties.getPropName((String) definedProp))) { getLog().error(" " + definedProp); } } } } catch (IOException e) { throw new MojoFailureException("Error loading properties file: " + file.getAbsolutePath(), e); } } if (failOnInvalidProperties && invalidPropertiesFound) { throw new MojoFailureException("Invalid properties were found"); } } private void writeToFile(ConfigurableProperties configurableProperties, File file) throws MojoFailureException { getLog().info("Writing overridable properties to: " + defaultPropertiesFile.getAbsolutePath()); try { configurableProperties.save(defaultPropertiesFile); } catch (IOException e) { throw new MojoFailureException("Error writing properties file: " + file.getAbsolutePath(), e); } } /** * @return a sorted list of properties that can be overridden for a given bar file * @throws IOException */ protected ConfigurableProperties getOverridableProperties() throws IOException { return ReadBar.getOverridableProperties(barName.getAbsolutePath()); } /** * gets a list of all property files in the iib and iib-test directories. A copy of the default * properties file will be copied into the iib-overrides directory if both iib directories are empty. * * @return * @throws MojoFailureException */ @SuppressWarnings("unchecked") private List<File> getTargetPropertiesFiles() throws MojoFailureException { List<File> propFiles = null; File targetIibDirectory = new File(project.getBuild().getDirectory(), "iib-overrides"); try { // see also PrepareIibBarPackagingMojo.java // String excludedDefaultPropertyFileName = defaultPropertiesFile.getName(); propFiles = FileUtils.getFiles(targetIibDirectory, "*.properties", null);// excludedDefaultPropertyFileName); } catch (IOException e) { // TODO handle exception throw new MojoFailureException("Error searching for properties files under " + targetIibDirectory, e); } return propFiles; } }
40.853982
199
0.666089
8477b705df303f44f3ec890d9678c13ead970f5a
916
package com.soft.design.demo3; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import java.util.List; import java.util.stream.Collectors; @Slf4j public class TemplateAServiceImpl extends TemplateService { @Override public String handler(String req) { return super.handler(req); } @Override public boolean step() { log.info("step A"); return false; } public static void main(String[] args) { List<Integer> prizeIdDtoList = Lists.newArrayList(5,6); // 若编辑判断交集 boolean update = Boolean.TRUE; List<Integer> prizeIdDbList = Lists.newArrayList(1, 2, 3,4,5); List<Integer> existList = prizeIdDbList.stream().filter(prizeIdDtoList::contains).collect(Collectors.toList()); prizeIdDtoList.addAll(existList); int size = prizeIdDtoList.size(); System.out.println(size); } }
25.444444
119
0.668122
aa31e0095ba1dd25a1c04007e3581be413a909d7
1,109
package alu.linking.launcher; import java.io.File; import alu.linking.config.constants.FilePaths; import alu.linking.config.kg.EnumModelType; import alu.linking.executable.preprocessing.setup.surfaceform.processing.url.webcrawl.NP_HSFURLContentSaver; /** * Downloads a bunch of websites as defined in the URL-based noun-phrase * (helping) surface forms (NP_URL_HSF) * * @author Kristian Noullet * */ public class LauncherDownloadHTML { public static void main(String[] args) { final EnumModelType KG = EnumModelType.CRUNCHBASE; final NP_HSFURLContentSaver contentSaver = new NP_HSFURLContentSaver(KG); final File urlFolder = new File(FilePaths.DIR_QUERY_OUT_NP_URL_HELPING_SURFACEFORM.getPath(KG)); // try { // System.out.println("Google: " + new Crawler().crawlSimple("http://www.google.com")); // } catch (IOException e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // } // if (true) // return; try { contentSaver.exec(urlFolder, false); } catch (Exception e) { e.printStackTrace(); } System.out.println("Done querying all websites!"); } }
28.435897
108
0.732191
ebabf9cdd9140356de38cc5afd9368d5e4b88b39
2,605
/* * Copyright 2019-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aot.factories; import com.squareup.javapoet.ClassName; import org.springframework.aot.build.context.BuildContext; import org.springframework.nativex.domain.reflect.ClassDescriptor; import org.springframework.nativex.hint.Flag; /** * {@link FactoriesCodeContributor} that contributes source code for * {@link org.springframework.test.context.TestExecutionListener} implementations. * <p>Instead of instantiating them statically, we make sure that * {@link org.springframework.core.io.support.SpringFactoriesLoader#loadFactoryNames(Class, ClassLoader)} * will return their names and that reflection metadata is registered for native images. * * @author Sam Brannen * @author Brian Clozel * @see org.springframework.nativex.substitutions.framework.test.Target_AbstractTestContextBootstrapper * @see org.springframework.test.context.support.AbstractTestContextBootstrapper.instantiateListeners */ class TestExecutionListenerFactoriesCodeContributor implements FactoriesCodeContributor { @Override public boolean canContribute(SpringFactory factory) { return factory.getFactoryType().getClassName().equals("org.springframework.test.context.TestExecutionListener"); } @Override public void contribute(SpringFactory factory, CodeGenerator code, BuildContext context) { ClassName factoryTypeClass = ClassName.bestGuess(factory.getFactoryType().getClassName()); generateReflectionMetadata(factory, context); code.writeToStaticBlock(builder -> { builder.addStatement("names.add($T.class, $S)", factoryTypeClass, factory.getFactory().getClassName()); }); } private void generateReflectionMetadata(SpringFactory factory, BuildContext context) { String factoryClassName = factory.getFactory().getClassName(); ClassDescriptor factoryDescriptor = ClassDescriptor.of(factoryClassName); factoryDescriptor.setFlag(Flag.allDeclaredConstructors); context.describeReflection(reflect -> reflect.add(factoryDescriptor)); } }
42.016129
114
0.796161
aa94ff074a1f634248ce8014eb9ae9f8df9efeb5
12,712
/* * Copyright (c) 2016 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.couchbase.client.java; 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 static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import com.couchbase.client.java.bucket.BucketManager; import com.couchbase.client.java.error.DesignDocumentAlreadyExistsException; import com.couchbase.client.java.error.DesignDocumentDoesNotExistException; import com.couchbase.client.java.error.DesignDocumentException; import com.couchbase.client.java.util.ClusterDependentTest; import com.couchbase.client.java.view.DefaultView; import com.couchbase.client.java.view.DesignDocument; import com.couchbase.client.java.view.SpatialView; import com.couchbase.client.java.view.View; import org.junit.Before; import org.junit.Test; /** * Verifies the functionality of the Design Document management facilities. * * @author Michael Nitschinger * @since 2.0 */ public class DesignDocumentTest extends ClusterDependentTest { private BucketManager manager; @Before public void setup() { manager = bucket().bucketManager(); List<DesignDocument> designDocuments = manager.getDesignDocuments(); for (DesignDocument ddoc : designDocuments) { manager.removeDesignDocument(ddoc.name()); } } @Test public void shouldInsertDesignDocument() { List<View> views = Arrays.asList(DefaultView.create("v1", "function(d,m){}", "_count")); DesignDocument designDocument = DesignDocument.create("insert1", views); manager.insertDesignDocument(designDocument); DesignDocument found = manager.getDesignDocument("insert1"); assertNotNull(found); assertEquals("insert1", found.name()); assertEquals(1, found.views().size()); assertEquals("function(d,m){}", found.views().get(0).map()); assertEquals("_count", found.views().get(0).reduce()); } @Test(expected = DesignDocumentException.class) public void shouldFailOnInvalidMapFunction() { List<View> views = Arrays.asList(DefaultView.create("v1", "notValid")); DesignDocument designDocument = DesignDocument.create("invalidInsert", views); manager.insertDesignDocument(designDocument); } @Test(expected = DesignDocumentAlreadyExistsException.class) public void shouldNotDoubleInsertDesignDocument() { List<View> views = Arrays.asList(DefaultView.create("v1", "function(d,m){}", "_count")); DesignDocument designDocument = DesignDocument.create("insert2", views); manager.insertDesignDocument(designDocument); DesignDocument found = manager.getDesignDocument("insert2"); assertNotNull(found); assertEquals("insert2", found.name()); assertEquals(1, found.views().size()); assertEquals("function(d,m){}", found.views().get(0).map()); assertEquals("_count", found.views().get(0).reduce()); manager.insertDesignDocument(designDocument); } @Test public void shouldUpsertDesignDocument() { List<View> views = Arrays.asList(DefaultView.create("v1", "function(d,m){}")); DesignDocument designDocument = DesignDocument.create("upsert1", views); manager.upsertDesignDocument(designDocument); DesignDocument found = manager.getDesignDocument("upsert1"); assertNotNull(found); assertEquals("upsert1", found.name()); assertEquals(1, found.views().size()); assertEquals("function(d,m){}", found.views().get(0).map()); assertNull(found.views().get(0).reduce()); } @Test public void shouldDoubleUpsertDesignDocument() { List<View> views = Arrays.asList(DefaultView.create("v1", "function(d,m){}")); DesignDocument designDocument = DesignDocument.create("upsert2", views); manager.upsertDesignDocument(designDocument); DesignDocument found = manager.getDesignDocument("upsert2"); assertNotNull(found); assertEquals("upsert2", found.name()); assertEquals(1, found.views().size()); assertEquals("function(d,m){}", found.views().get(0).map()); assertNull(found.views().get(0).reduce()); views = Arrays.asList( DefaultView.create("v1", "function(d,m){}", "_count"), DefaultView.create("v2", "function(d,m){}", "_count") ); designDocument = DesignDocument.create("upsert2", views); manager.upsertDesignDocument(designDocument); found = manager.getDesignDocument("upsert2"); assertNotNull(found); assertEquals("upsert2", found.name()); assertEquals(2, found.views().size()); assertEquals("function(d,m){}", found.views().get(0).map()); assertEquals("_count", found.views().get(0).reduce()); assertEquals("function(d,m){}", found.views().get(1).map()); assertEquals("_count", found.views().get(1).reduce()); } @Test public void shouldHaveLessViewsWhenUpsertingWithOnlyNewViews() { List<View> views = Collections.singletonList(DefaultView.create("v1", "function(d,m){}")); DesignDocument designDocument = DesignDocument.create("upsert3", views); manager.upsertDesignDocument(designDocument); DesignDocument found = manager.getDesignDocument("upsert3"); assertNotNull(found); assertEquals("upsert3", found.name()); assertEquals(1, found.views().size()); assertEquals("v1", found.views().get(0).name()); assertNull(found.views().get(0).reduce()); views = Collections.singletonList(DefaultView.create("v2", "function(d,m){}", "_count")); designDocument = DesignDocument.create("upsert3", views); manager.upsertDesignDocument(designDocument); found = manager.getDesignDocument("upsert3"); assertNotNull(found); assertEquals("upsert3", found.name()); assertEquals(1, found.views().size()); assertEquals("v2", found.views().get(0).name()); assertEquals("_count", found.views().get(0).reduce()); } @Test public void shouldUseLatestDefinitionWhenAddingViewNameTwice() { List<View> views = new ArrayList<View>(); views.add(DefaultView.create("v1", "function(d,m){}")); DesignDocument designDocument = DesignDocument.create("upsert4", views); designDocument.views().add(DefaultView.create("v1", "function(d,m){emit(null,null);}", "_count")); manager.upsertDesignDocument(designDocument); DesignDocument found = manager.getDesignDocument("upsert4"); assertNotNull(found); assertEquals("upsert4", found.name()); assertEquals(1, found.views().size()); assertEquals("v1", found.views().get(0).name()); assertEquals("function(d,m){emit(null,null);}", found.views().get(0).map()); assertEquals("_count", found.views().get(0).reduce()); //make also sure that the getDesignDocument views list is mutable found.views().add(DefaultView.create("v1", "function(d,m){emit(d.type, null);}", null)); manager.upsertDesignDocument(found); found = manager.getDesignDocument("upsert4"); assertNotNull(found); assertEquals("upsert4", found.name()); assertEquals(1, found.views().size()); assertEquals("v1", found.views().get(0).name()); assertEquals("function(d,m){emit(d.type, null);}", found.views().get(0).map()); assertNull(found.views().get(0).reduce()); } @Test public void shouldGetDesignDocuments() { List<View> views = Arrays.asList(DefaultView.create("v1", "function(d,m){}")); DesignDocument designDocument1 = DesignDocument.create("doc1", views); DesignDocument designDocument2 = DesignDocument.create("doc3", views); DesignDocument designDocument3 = DesignDocument.create("doc2", views); manager.upsertDesignDocument(designDocument1); manager.upsertDesignDocument(designDocument2); manager.upsertDesignDocument(designDocument3); List<DesignDocument> docs = manager.getDesignDocuments(); assertTrue(docs.size() >= 3); int found = 0; for (DesignDocument doc : docs) { if (doc.name().equals("doc1") || doc.name().equals("doc2") || doc.name().equals("doc3")) { found++; } } assertEquals(3, found); } @Test(expected = DesignDocumentDoesNotExistException.class) public void shouldRemoveDesignDocument() { List<View> views = Arrays.asList( DefaultView.create("v1", "function(d,m){}"), DefaultView.create("v2", "function(d,m){}", "_count") ); DesignDocument designDocument = DesignDocument.create("remove1", views); manager.upsertDesignDocument(designDocument); DesignDocument found = manager.getDesignDocument("remove1"); assertNotNull(found); assertEquals("remove1", found.name()); assertEquals(2, found.views().size()); assertTrue(manager.removeDesignDocument("remove1")); manager.getDesignDocument("remove1"); } @Test public void shouldPublishDesignDocument() { List<View> views = Arrays.asList( DefaultView.create("v1", "function(d,m){}"), DefaultView.create("v2", "function(d,m){}", "_count") ); DesignDocument designDocument = DesignDocument.create("pub1", views); manager.upsertDesignDocument(designDocument, true); manager.publishDesignDocument("pub1"); DesignDocument found = manager.getDesignDocument("pub1"); assertNotNull(found); assertEquals("pub1", found.name()); assertEquals(2, found.views().size()); } @Test(expected = DesignDocumentAlreadyExistsException.class) public void shouldNotOverrideOnPublish() { List<View> views = Arrays.asList( DefaultView.create("v1", "function(d,m){}"), DefaultView.create("v2", "function(d,m){}", "_count") ); DesignDocument designDocument = DesignDocument.create("pub2", views); manager.upsertDesignDocument(designDocument, true); manager.publishDesignDocument("pub2"); manager.publishDesignDocument("pub2"); } @Test public void shouldInsertAndGetWithSpatial() { List<View> views = Arrays.asList( SpatialView.create("geo", "function (doc) {if(doc.type == \"city\") { emit([doc.lon, doc.lat], null);}}") ); DesignDocument designDocument = DesignDocument.create("withSpatial", views); manager.upsertDesignDocument(designDocument); DesignDocument found = manager.getDesignDocument("withSpatial"); assertEquals(1, found.views().size()); View view = found.views().get(0); assertTrue(view instanceof SpatialView); assertEquals("geo", view.name()); assertNotNull(view.map()); assertNull(view.reduce()); assertFalse(view.hasReduce()); } @Test public void shouldCreateAndLoadDesignDocumentWithOptions() { List<View> views = Arrays.asList(DefaultView.create("vOpts", "function(d,m){}", "_count")); Map<DesignDocument.Option, Long> options = new HashMap<DesignDocument.Option, Long>(); options.put(DesignDocument.Option.UPDATE_MIN_CHANGES, 100L); options.put(DesignDocument.Option.REPLICA_UPDATE_MIN_CHANGES, 5000L); DesignDocument designDocument = DesignDocument.create("upsertWithOpts", views, options); manager.upsertDesignDocument(designDocument); DesignDocument loaded = manager.getDesignDocument("upsertWithOpts"); assertEquals((Long) 100L, loaded.options().get(DesignDocument.Option.UPDATE_MIN_CHANGES)); assertEquals((Long) 5000L, loaded.options().get(DesignDocument.Option.REPLICA_UPDATE_MIN_CHANGES)); } }
41.678689
117
0.669053
306cfa79f81f03344cbb65384aaf66d61ed751bb
399
package manifold.ij.psi; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiField; /** */ public interface ManLightFieldBuilder extends PsiField { ManLightFieldBuilder withContainingClass( PsiClass psiClass ); ManLightFieldBuilder withModifier( String modifier ); ManLightFieldBuilder withNavigationElement( PsiElement navigationElement ); }
23.470588
77
0.814536
c66b4810e84c7236d3bcb246d4aa055221d18173
2,013
package org.apache.maven.plugins.shade.resource; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.maven.plugins.shade.relocation.Relocator; import org.codehaus.plexus.util.IOUtil; public class ResourceBundleAppendingTransformer implements ResourceTransformer { private Map<String, ByteArrayOutputStream> dataMap = new HashMap(); private Pattern resourceBundlePattern; public ResourceBundleAppendingTransformer() {} public void setBasename(String basename) { resourceBundlePattern = Pattern.compile(basename + "(_[a-zA-Z]+){0,3}\\.properties"); } public boolean canTransformResource(String r) { if ((resourceBundlePattern != null) && (resourceBundlePattern.matcher(r).matches())) { return true; } return false; } public void processResource(String resource, InputStream is, List<Relocator> relocators) throws IOException { ByteArrayOutputStream data = (ByteArrayOutputStream)dataMap.get(resource); if (data == null) { data = new ByteArrayOutputStream(); dataMap.put(resource, data); } IOUtil.copy(is, data); data.write(10); } public boolean hasTransformedResource() { return !dataMap.isEmpty(); } public void modifyOutputStream(JarOutputStream jos) throws IOException { for (Map.Entry<String, ByteArrayOutputStream> dataEntry : dataMap.entrySet()) { jos.putNextEntry(new JarEntry((String)dataEntry.getKey())); IOUtil.copy(new ByteArrayInputStream(((ByteArrayOutputStream)dataEntry.getValue()).toByteArray()), jos); ((ByteArrayOutputStream)dataEntry.getValue()).reset(); } } }
20.752577
110
0.716841
4f88ac1691bce1d30db2ff79de2772b5963c8dbd
3,966
/* 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.batik.anim.dom; import org.apache.batik.css.engine.CSSEngine; import org.apache.batik.css.engine.CSSStyleSheetNode; import org.apache.batik.css.engine.StyleSheet; import org.apache.batik.dom.AbstractDocument; import org.apache.batik.dom.StyleSheetFactory; import org.apache.batik.dom.StyleSheetProcessingInstruction; import org.apache.batik.dom.util.HashTable; import org.apache.batik.util.ParsedURL; import org.w3c.dom.DOMException; import org.w3c.dom.Node; /** * This class provides an implementation of the 'xml-stylesheet' processing * instructions. * * @author <a href="mailto:[email protected]">Stephane Hillion</a> * @version $Id$ */ public class SVGStyleSheetProcessingInstruction extends StyleSheetProcessingInstruction implements CSSStyleSheetNode { /** * The style-sheet. */ protected StyleSheet styleSheet; /** * Creates a new ProcessingInstruction object. */ protected SVGStyleSheetProcessingInstruction() { } /** * Creates a new ProcessingInstruction object. */ public SVGStyleSheetProcessingInstruction(String data, AbstractDocument owner, StyleSheetFactory f) { super(data, owner, f); } /** * Returns the URI of the referenced stylesheet. */ public String getStyleSheetURI() { SVGOMDocument svgDoc = (SVGOMDocument) getOwnerDocument(); ParsedURL url = svgDoc.getParsedURL(); String href = (String)getPseudoAttributes().get("href"); if (url != null) { return new ParsedURL(url, href).toString(); } return href; } /** * Returns the associated style-sheet. */ public StyleSheet getCSSStyleSheet() { if (styleSheet == null) { HashTable attrs = getPseudoAttributes(); String type = (String)attrs.get("type"); if ("text/css".equals(type)) { String title = (String)attrs.get("title"); String media = (String)attrs.get("media"); String href = (String)attrs.get("href"); String alternate = (String)attrs.get("alternate"); SVGOMDocument doc = (SVGOMDocument)getOwnerDocument(); ParsedURL durl = doc.getParsedURL(); ParsedURL burl = new ParsedURL(durl, href); CSSEngine e = doc.getCSSEngine(); styleSheet = e.parseStyleSheet(burl, media); styleSheet.setAlternate("yes".equals(alternate)); styleSheet.setTitle(title); } } return styleSheet; } /** * <b>DOM</b>: Implements {@link * org.w3c.dom.ProcessingInstruction#setData(String)}. */ public void setData(String data) throws DOMException { super.setData(data); styleSheet = null; } /** * Returns a new uninitialized instance of this object's class. */ protected Node newNode() { return new SVGStyleSheetProcessingInstruction(); } }
33.610169
75
0.638174
ef1b893b8f59dc951991ef0a1a0085e28733f26b
359
package com.shy.covidDashboard.repository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.shy.covidDashboard.model.User; @Repository public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findByUserName(String userName); }
25.642857
67
0.832869
2fe6cf138840f4e0e55d2d8ec25fc7c826703bbc
7,854
package com.puppycrawl.tools.checkstyle.checks.indentation.indentation; //indent:0 exp:0 import java.util.Arrays; //indent:0 exp:0 /** //indent:0 exp:0 * This test-input is intended to be checked using following configuration: //indent:1 exp:1 * //indent:1 exp:1 * arrayInitIndent = 4 //indent:1 exp:1 * basicOffset = 4 //indent:1 exp:1 * braceAdjustment = 0 //indent:1 exp:1 * caseIndent = 4 //indent:1 exp:1 * forceStrictCondition = false //indent:1 exp:1 * lineWrappingIndentation = 4 //indent:1 exp:1 * tabWidth = 4 //indent:1 exp:1 * throwsIndent = 4 //indent:1 exp:1 * //indent:1 exp:1 * @author jrichard //indent:1 exp:1 */ //indent:1 exp:1 public class InputIndentationValidMethodIndent extends Object { //indent:0 exp:0 // ctor with rcurly on same line //indent:4 exp:4 public InputIndentationValidMethodIndent() { //indent:4 exp:4 } //indent:4 exp:4 private InputIndentationValidMethodIndent(boolean test) { //indent:4 exp:4 boolean test2 = true; //indent:8 exp:>=8 int i = 4 + //indent:8 exp:8 4; //indent:12 exp:>=12 } //indent:4 exp:4 private InputIndentationValidMethodIndent(boolean test, //indent:4 exp:4 boolean test2) { //indent:8 exp:>=8 boolean test3 = true; //indent:8 exp:>=8 int i = 4 + //indent:8 exp:8 4; //indent:12 exp:>=12 } //indent:4 exp:4 private InputIndentationValidMethodIndent(boolean test, //indent:4 exp:4 boolean test2, boolean test3) //indent:8 exp:>=8 { //indent:4 exp:4 boolean test4 = true; //indent:8 exp:8 int i = 4 + //indent:8 exp:8 4; //indent:12 exp:>=12 } //indent:4 exp:4 // ctor with rcurly on next line //indent:4 exp:4 public InputIndentationValidMethodIndent(int dummy) //indent:4 exp:4 { //indent:4 exp:4 } //indent:4 exp:4 // method with rcurly on same line //indent:4 exp:4 public String method1() { //indent:4 exp:4 return "hi"; //indent:8 exp:>=8 } //indent:4 exp:4 // method with rcurly on next line //indent:4 exp:4 public void method2() //indent:4 exp:4 { //indent:4 exp:4 } //indent:4 exp:4 // method with a bunch of params //indent:4 exp:4 public int method2(int x, int y, int w, int h) //indent:4 exp:4 { //indent:4 exp:4 return 1; //indent:8 exp:8 } //indent:4 exp:4 // params on multiple lines //indent:4 exp:4 public void method2(int x, int y, int w, int h, //indent:4 exp:4 int x1, int y1, int w1, int h1) //indent:8 exp:>=8 { //indent:4 exp:4 } //indent:4 exp:4 // params on multiple lines //indent:4 exp:4 public void method3(int x, int y, int w, int h, //indent:4 exp:4 int x1, int y1, int w1, int h1) //indent:8 exp:>=8 { //indent:4 exp:4 System.getProperty("foo"); //indent:8 exp:8 } //indent:4 exp:4 // params on multiple lines //indent:4 exp:4 public void method4(int x, int y, int w, int h, //indent:4 exp:4 int x1, int y1, int w1, int h1) //indent:8 exp:8 { //indent:4 exp:4 boolean test = true; //indent:8 exp:8 int i = 4 + //indent:8 exp:8 4; //indent:12 exp:>=12 i += 5; //indent:8 exp:8 i += 5 //indent:8 exp:8 + 4; //indent:12 exp:>=12 if (test) //indent:8 exp:8 { //indent:8 exp:8 System.getProperty("foo"); //indent:12 exp:12 } else { //indent:8 exp:8 System.getProperty("foo"); //indent:12 exp:12 } //indent:8 exp:8 for (int j=0;j<10; j++) { //indent:8 exp:8 System.getProperty("foo"); //indent:12 exp:12 } //indent:8 exp:8 myfunc2(10, 10, 10, //indent:8 exp:8 myfunc3(11, 11, //indent:12 exp:>=12 11, 11), //indent:16 exp:>=16 10, 10, //indent:12 exp:>=12 10); //indent:12 exp:>=12 myfunc3(11, 11, Integer. //indent:8 exp:8 getInteger("mytest").intValue(), //indent:16 exp:>=12 11); //indent:12 exp:>=12 myfunc3( //indent:8 exp:8 1, //indent:12 exp:>=12 2, //indent:12 exp:>=12 3, //indent:16 exp:>=12 4); //indent:16 exp:>=12 } //indent:4 exp:4 // strange IMHO, but I suppose this should be allowed //indent:4 exp:4 public //indent:4 exp:4 void //indent:4 exp:8 warn method5() { //indent:4 exp:8 warn } //indent:4 exp:4 private void myfunc2(int a, int b, int c, int d, int e, int f, int g) { //indent:4 exp:4 } //indent:4 exp:4 private int myfunc3(int a, int b, int c, int d) { //indent:4 exp:4 return 1; //indent:8 exp:8 } //indent:4 exp:4 void method6() { //indent:4 exp:4 System.identityHashCode("methods are: " + Arrays.asList( //indent:8 exp:8 new String[] {"method"}).toString()); //indent:12 exp:>=12 System.identityHashCode("methods are: " + Arrays.asList( //indent:8 exp:8 new String[] {"method"} //indent:12 exp:>=12 ).toString()); //indent:8 exp:8 System.identityHashCode("methods are: " + Arrays.asList( //indent:8 exp:8 new String[] {"method"}).toString() //indent:12 exp:>=12 ); //indent:8 exp:8 myfunc2(3, 4, 5, //indent:8 exp:8 6, 7, 8, 9); //indent:12 exp:>=12 myfunc2(3, 4, method2(3, 4, 5, 6) + 5, //indent:8 exp:8 6, 7, 8, 9); //indent:12 exp:>=12 System.identityHashCode("methods are: " + //indent:8 exp:8 Arrays.asList( //indent:12 exp:>=12 new String[] {"method"}).toString()); //indent:16 exp:>=16 System.identityHashCode("methods are: " //indent:8 exp:8 + Arrays.asList( //indent:12 exp:>=12 new String[] {"method"}).toString()); //indent:16 exp:>=16 String blah = (String) System.getProperty( //indent:8 exp:8 new String("type")); //indent:12 exp:>=12 System.identityHashCode(method1() + "mytext" //indent:8 exp:8 + " at indentation level not at correct indentation, " //indent:12 exp:>=12 + method1()); //indent:12 exp:>=12 System.identityHashCode( //indent:8 exp:8 method1() + "mytext" //indent:12 exp:>=12 + " at indentation level not at correct indentation, " //indent:16 exp:>=12 + method1()); //indent:16 exp:>=12 String.CASE_INSENSITIVE_ORDER.toString() //indent:8 exp:8 .equals("blah"); //indent:12 exp:>=12 } //indent:4 exp:4 private int[] getArray() { //indent:4 exp:4 return new int[] {1}; //indent:8 exp:8 } //indent:4 exp:4 private void indexTest() { //indent:4 exp:4 getArray()[0] = 2; //indent:8 exp:8 } //indent:4 exp:4 // the following lines have tabs //indent:4 exp:4 @SuppressWarnings( //indent:4 exp:4 value="" //indent:8 exp:8 ) //indent:4 exp:4 public void testStartOfSequence() { //indent:4 exp:4 } //indent:4 exp:4 } //indent:0 exp:0
38.5
94
0.510568
4f1340bc8d598048d648bc9191833b8983742a6b
2,811
package com.example.musicplayerproject.adapters; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.example.musicplayerproject.R; import java.util.ArrayList; public class RecentPlaysRVAdapter extends RecyclerView.Adapter<RecentPlaysRVAdapter.MyViewHolder>{ private static final String TAG = "RecentPlaysRVAdapter"; Context mContext; private ArrayList<String> mRPlistNames = new ArrayList<>(); private ArrayList<String> mRPImageRes = new ArrayList<>(); private ArrayList<Integer> mRPGradResources = new ArrayList<>(); public RecentPlaysRVAdapter(Context mContext, ArrayList<String> mRPlistNames, ArrayList<String> mRPImageRes, ArrayList<Integer> mRPGradResources) { this.mContext = mContext; this.mRPlistNames = mRPlistNames; this.mRPImageRes = mRPImageRes; this.mRPGradResources = mRPGradResources; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { Log.d(TAG, "onCreateViewHolder: called"); View view3 = LayoutInflater.from(parent.getContext()).inflate(R.layout.recentplays_carditem, parent, false); return new MyViewHolder(view3); } @Override public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) { Log.d(TAG, "onBindViewHolder: called"); Glide.with(mContext).asBitmap().load(mRPImageRes.get(position)).into(holder.album_covers); holder.grad_image2.setImageResource(mRPGradResources.get(position)); holder.rp_txt2.setText(mRPlistNames.get(position)); holder.grad_image2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "onClick: Clicked on image at pos: "+mRPlistNames.get(position)); Toast.makeText(mContext,mRPlistNames.get(position),Toast.LENGTH_LONG).show(); } }); } @Override public int getItemCount() { return mRPlistNames.size(); } public class MyViewHolder extends RecyclerView.ViewHolder{ ImageView grad_image2, album_covers; TextView rp_txt2; public MyViewHolder(@NonNull View itemView) { super(itemView); grad_image2 = (ImageView)itemView.findViewById(R.id.rec_grad); rp_txt2 = (TextView)itemView.findViewById(R.id.rp_title); album_covers = (ImageView)itemView.findViewById(R.id.rp_coverImg); } } }
36.986842
151
0.712914
8f5218ba56742bdc038575fd2220e20448fb0c48
1,903
import fi.helsinki.cs.tmc.edutestutils.MockStdio; import fi.helsinki.cs.tmc.edutestutils.Points; import org.junit.*; import static org.junit.Assert.*; @Points("52") public class ReversingNameTest { @Rule public MockStdio io = new MockStdio(); @Test public void noExceptions() throws Exception { io.setSysIn("pekka\n"); try { ReversingName.main(new String[0]); } catch (Exception e) { String v = "press button \"show backtrace\" and you find the cause of the problem by scrollong down to the " + "\"Caused by\""; throw new Exception("With input \"Pekka\" " + v, e); } } @Test public void test1() { testaa("Pekka", "akkeP"); } @Test public void test2() { testaa("Katariina", "aniirataK"); } @Test public void test3() { testaa("saippuakauppias", "saippuakauppias"); } @Test public void test4() { testaa("m", "m"); } @Test public void test5() { testaa("Oa", "aO"); } @Test public void test6() { testaa("jIk", "kIj"); } @Test public void test7() { testaa("apfjviaweojmfviaowfjisadfklnrnwaieraisdf", "fdsiareiawnrnlkfdasijfwoaivfmjoewaivjfpa"); } @Test public void test8() { testaa("ujoPoju", "ujoPoju"); } @Test public void test9() { testaa("aattonaJanottaa", "aattonaJanottaa"); } private void testaa(String alkup, String oletettu) { io.setSysIn(alkup + "\n"); ReversingName.main(new String[0]); assertTrue(getViesti(alkup, oletettu), io.getSysOut().contains(oletettu)); } private String getViesti(String alkup, String oletettu) { return "Check that with input " + alkup + " you print " + oletettu; } }
22.654762
120
0.561745
9f2d54b95e014ff0a7b9809cde5f1d9c9ea114f8
782
package com.github.kingjava.user.utils; import com.github.kingjava.user.api.module.Menu; import com.github.kingjava.user.excel.model.MenuExcelModel; import org.springframework.beans.BeanUtils; import java.util.ArrayList; import java.util.List; /** * 菜单工具类 * * @author kingjava * @date 2018/10/28 15:57 */ public class MenuUtil { private MenuUtil() { } /** * 转换对象 * @param menus menus * @return List */ public static List<MenuExcelModel> convertToExcelModel(List<Menu> menus) { List<MenuExcelModel> menuExcelModels = new ArrayList<>(menus.size()); menus.forEach(menu -> { MenuExcelModel menuExcelModel = new MenuExcelModel(); BeanUtils.copyProperties(menu, menuExcelModel); menuExcelModels.add(menuExcelModel); }); return menuExcelModels; } }
21.722222
75
0.731458
76986ef8a2d4f0175ccb4f959a8b16ecdde9945b
2,541
package org.knowm.xchange.bitcointoyou.dto.marketdata; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; import javax.annotation.Generated; import org.apache.commons.lang3.builder.ToStringBuilder; /** * Public trade Bitcointoyou Exchange representation. * * @author Danilo Guimaraes * @author Jonathas Carrijo */ @JsonInclude(JsonInclude.Include.NON_NULL) @Generated("org.jsonschema2pojo") @JsonPropertyOrder({"date", "price", "amount", "tid", "type", "currency"}) public class BitcointoyouPublicTrade { private final Integer date; private final BigDecimal price; private final BigDecimal amount; private final Integer tid; private final String type; private final String currency; @JsonIgnore private final Map<String, Object> additionalProperties = new HashMap<>(); public BitcointoyouPublicTrade( @JsonProperty("date") Integer date, @JsonProperty("price") BigDecimal price, @JsonProperty("amount") BigDecimal amount, @JsonProperty("tid") Integer tid, @JsonProperty("type") String type, @JsonProperty("currency") String currency) { this.date = date; this.price = price; this.amount = amount; this.tid = tid; this.type = type; this.currency = currency; } public Integer getDate() { return date; } public BigDecimal getPrice() { return price; } public BigDecimal getAmount() { return amount; } public Integer getTid() { return tid; } public String getType() { return type; } public String getCurrency() { return currency; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } @Override public String toString() { return new ToStringBuilder(this) .append("date", date) .append("price", price) .append("amount", amount) .append("tid", tid) .append("type", type) .append("currency", currency) .append("additionalProperties", additionalProperties) .toString(); } }
24.2
87
0.70917
937898dea3f801ce1f802665eda10147d78b578c
4,478
/* * (c) Copyright 2016 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.tritium.metrics.caffeine; import static com.palantir.logsafe.Preconditions.checkNotNull; import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.google.common.collect.ImmutableMap; import com.palantir.logsafe.Safe; import com.palantir.logsafe.SafeArg; import com.palantir.logsafe.logger.SafeLogger; import com.palantir.logsafe.logger.SafeLoggerFactory; import com.palantir.tritium.metrics.InternalCacheMetrics; import com.palantir.tritium.metrics.MetricRegistries; import com.palantir.tritium.metrics.registry.TaggedMetricRegistry; import java.util.concurrent.TimeUnit; import java.util.function.Function; public final class CaffeineCacheStats { private static final SafeLogger log = SafeLoggerFactory.get(CaffeineCacheStats.class); private static final String STATS_DISABLED = "cache.stats.disabled"; private CaffeineCacheStats() {} /** * Register specified cache with the given metric registry. * * Callers should ensure that they have {@link Caffeine#recordStats() enabled stats recording} * {@code Caffeine.newBuilder().recordStats()} otherwise there are no cache metrics to register. * * @param registry metric registry * @param cache cache to instrument * @param name cache name * * @deprecated use {@link #registerCache(TaggedMetricRegistry, Cache, String)} */ @Deprecated public static void registerCache(MetricRegistry registry, Cache<?, ?> cache, String name) { checkNotNull(registry, "registry"); checkNotNull(cache, "cache"); checkNotNull(name, "name"); if (cache.policy().isRecordingStats()) { CaffeineCacheMetrics.create(cache, name) .getMetrics() .forEach((key, value) -> MetricRegistries.registerWithReplacement(registry, key, value)); } else { warnNotRecordingStats(name, registry.counter(MetricRegistry.name(name, STATS_DISABLED))); } } /** * Register specified cache with the given metric registry. * * Callers should ensure that they have {@link Caffeine#recordStats() enabled stats recording} * {@code Caffeine.newBuilder().recordStats()} otherwise there are no cache metrics to register. * * @param registry metric registry * @param cache cache to instrument * @param name cache name */ public static void registerCache(TaggedMetricRegistry registry, Cache<?, ?> cache, @Safe String name) { checkNotNull(registry, "registry"); checkNotNull(cache, "cache"); checkNotNull(name, "name"); if (cache.policy().isRecordingStats()) { CaffeineCacheTaggedMetrics.create(cache, name).getMetrics().forEach(registry::registerWithReplacement); } else { warnNotRecordingStats( name, registry.counter(InternalCacheMetrics.taggedMetricName(name).apply(STATS_DISABLED))); } } private static void warnNotRecordingStats(@Safe String name, Counter counter) { counter.inc(); log.warn( "Registered cache does not have stats recording enabled, stats will always be zero. " + "To enable cache metrics, stats recording must be enabled when constructing the cache: " + "Caffeine.newBuilder().recordStats()", SafeArg.of("cacheName", name)); } static <K> ImmutableMap<K, Gauge<?>> createCacheGauges(Cache<?, ?> cache, Function<String, K> metricNamer) { return InternalCacheMetrics.createMetrics(CaffeineStats.create(cache, 1, TimeUnit.SECONDS), metricNamer); } }
42.245283
115
0.698749
fa20f20570c3eb8ec2df10d84de36fcf5676f899
6,995
/* * The MIT License * * Copyright (c) 2018-2022, qinglangtech Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.qlangtech.tis.solrextend.queryparse.s4WaitingUser; import java.util.HashMap; import java.util.Map; import org.apache.lucene.index.DocValues; import org.apache.lucene.index.NumericDocValues; import org.apache.lucene.index.SortedDocValues; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopFieldCollector; import org.apache.lucene.search.TopFieldDocs; import org.apache.lucene.util.FixedBitSet; import org.apache.solr.common.SolrException; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.CursorMarkParams; import org.apache.solr.common.params.SolrParams; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.schema.IndexSchema; import org.apache.solr.search.CursorMark; import org.apache.solr.search.LuceneQParserPlugin; import org.apache.solr.search.QParser; import org.apache.solr.search.SortSpec; import org.apache.solr.search.SortSpecParsing; import org.apache.solr.search.SyntaxError; import com.qlangtech.tis.solrextend.queryparse.BitQuery; /* * 生抽的需求,waiting记录中会有多个相同的orderid出现,需要对这些orderid进行去重<br> * 如果两个时间相同的话就取最小的那一个 * * @author 百岁([email protected]) * @date 2019年1月17日 */ public class DistinctOrderQparserPlugin extends LuceneQParserPlugin { // private static final Logger logger = LoggerFactory.getLogger(DistinctOrderQparserPlugin.class); // 第一次命中结果集取的条数 private static final int DEFAULT_ROW_COUNT = 300; public static final String waitingorder_id = "waitingorder_id"; public static final String create_time = "create_time"; public static final String order_id = "order_id"; @Override public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) { // final long allstart = System.currentTimeMillis(); try { Map<Integer, OrderCompare> /* orderid order */ orderReducer = new HashMap<>(); IndexSchema schema = req.getSchema(); SortSpec sortSpec = SortSpecParsing.parseSortSpec(params.get(CommonParams.SORT), req); CursorMark mark = new CursorMark(schema, sortSpec); mark.parseSerializedTotem(params.get(CursorMarkParams.CURSOR_MARK_PARAM, CursorMarkParams.CURSOR_MARK_START)); QParser parser = super.createParser(qstr, localParams, params, req); Query sortedQuery = parser.parse(); // long start = System.currentTimeMillis(); TopFieldCollector collector = null; try { collector = TopFieldCollector.create(sortSpec.getSort(), DEFAULT_ROW_COUNT, mark.getSearchAfterFieldDoc(), false, false, false); req.getSearcher().search(sortedQuery, collector); } finally { // logger.info("search consume:" + (System.currentTimeMillis() - start) + "ms,sort:" + sortSpec.getSort()); } final TopFieldDocs sortedDocs = collector.topDocs(); // 这个调用在大数据量的时候非常耗时 SortedDocValues orderidVals = null; NumericDocValues createtimeVals = null; SortedDocValues pkVals = null; // start = System.currentTimeMillis(); try { orderidVals = DocValues.getSorted(req.getSearcher().getLeafReader(), order_id); createtimeVals = DocValues.getNumeric(req.getSearcher().getLeafReader(), create_time); pkVals = DocValues.getSorted(req.getSearcher().getLeafReader(), waitingorder_id); } finally { // logger.info("consume:" + (System.currentTimeMillis() - start) + "ms"); } int orderIdOrd; long createTimeVal; int pkOrd; OrderCompare ordCompare = null; // bitSet用来快速排序 final FixedBitSet bitSet = new FixedBitSet(req.getSearcher().getIndexReader().maxDoc()); for (ScoreDoc hitDoc : sortedDocs.scoreDocs) { orderIdOrd = orderidVals.getOrd(hitDoc.doc); // 这样可以控制 if (orderIdOrd < 0) { continue; } createTimeVal = createtimeVals.get(hitDoc.doc); pkOrd = pkVals.getOrd(hitDoc.doc); ordCompare = orderReducer.get(orderIdOrd); if (ordCompare == null) { ordCompare = new OrderCompare(); ordCompare.docid = hitDoc.doc; ordCompare.createTimeVal = createTimeVal; ordCompare.pkOrd = pkOrd; orderReducer.put(orderIdOrd, ordCompare); } else { // 比较是否要取代之前已经存在的 if ((createTimeVal < ordCompare.createTimeVal) || (createTimeVal == ordCompare.createTimeVal && pkOrd < ordCompare.pkOrd)) { ordCompare.docid = hitDoc.doc; ordCompare.createTimeVal = createTimeVal; ordCompare.pkOrd = pkOrd; } } } // 去重之后灌装 for (OrderCompare o : orderReducer.values()) { bitSet.set(o.docid); } final BitQuery bitQuery = new BitQuery(bitSet); return new QParser(qstr, localParams, params, req) { @Override public Query parse() throws SyntaxError { return bitQuery; } }; } catch (Exception e) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e); } finally { // logger.info("allconsume:" + (System.currentTimeMillis() - allstart)); } } private static class OrderCompare { private int docid; private long createTimeVal; private int pkOrd; } }
43.71875
144
0.652609
e1bff50aa59c3935cd671cda3073238162a463e5
922
package chadbot.bot.synonyms; import chadbot.bot.synonyms.SynonymGroup; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class SynonymGroupTest { String[] SynonymArray = {"Happy", "Sad", "Mad", "Bad"}; SynonymGroup testGroup = new SynonymGroup(SynonymArray); //Test Create SynonymGroup @Test void testCreateSynonymGroup() { assertTrue(testGroup != null); } //Test get Synonym Array @Test void testGetSynonymArray() { assertEquals(SynonymArray, testGroup.getSynonymArray()); } //Test get Synonym Array @Test void testGetSynonymFromIndex() { assertEquals(SynonymArray[1], testGroup.getSynonymFromIndex(1)); } //Test get Synonym Array @Test void testAddSynonym() { testGroup.addSynonym("Jolly"); assertTrue(testGroup.getSynonymArray().length > SynonymArray.length); } }
24.918919
77
0.678959
d04e00879b0029e6e143dee630c22b9cb17bb969
2,587
package com.sequenceiq.cloudbreak.core.flow2.event; import java.util.Collections; import java.util.Map; import java.util.Set; import com.sequenceiq.cloudbreak.common.event.AcceptResult; import com.sequenceiq.cloudbreak.common.type.ScalingType; import reactor.rx.Promise; public class ClusterAndStackDownscaleTriggerEvent extends ClusterDownscaleTriggerEvent { private final ScalingType scalingType; public ClusterAndStackDownscaleTriggerEvent(String selector, Long stackId, Map<String, Integer> hostGroupWithAdjustment, ScalingType scalingType) { super(selector, stackId, hostGroupWithAdjustment, Collections.emptyMap(), Collections.emptyMap()); this.scalingType = scalingType; } public ClusterAndStackDownscaleTriggerEvent(String selector, Long stackId, Map<String, Integer> hostGroupWithAdjustment, Map<String, Set<Long>> hostGroupWithPrivateIds, Map<String, Set<String>> hostGroupWithHostNames, ScalingType scalingType) { super(selector, stackId, hostGroupWithAdjustment, hostGroupWithPrivateIds, hostGroupWithHostNames); this.scalingType = scalingType; } public ClusterAndStackDownscaleTriggerEvent(String selector, Long stackId, Map<String, Integer> hostGroupWithAdjustment, Map<String, Set<Long>> hostGroupWithPrivateIds, ScalingType scalingType, Promise<AcceptResult> accepted, ClusterDownscaleDetails details) { super(selector, stackId, hostGroupWithAdjustment, hostGroupWithPrivateIds, Collections.emptyMap(), accepted, details); this.scalingType = scalingType; } public ClusterAndStackDownscaleTriggerEvent(String selector, Long stackId, Map<String, Set<Long>> hostGroupWithPrivateIds, ScalingType scalingType, Promise<AcceptResult> accepted, ClusterDownscaleDetails details) { super(selector, stackId, Collections.emptyMap(), hostGroupWithPrivateIds, Collections.emptyMap(), accepted, details); this.scalingType = scalingType; } public ClusterAndStackDownscaleTriggerEvent(String selector, Long stackId, Map<String, Integer> hostGroupWithAdjustment, Map<String, Set<Long>> hostGroupWithPrivateIds, Map<String, Set<String>> hostGroupWithHostNames, ScalingType scalingType, Promise<AcceptResult> accepted, ClusterDownscaleDetails details) { super(selector, stackId, hostGroupWithAdjustment, hostGroupWithPrivateIds, hostGroupWithHostNames, accepted, details); this.scalingType = scalingType; } public ScalingType getScalingType() { return scalingType; } }
51.74
151
0.771937
633d0cf9863529390b9537a2a87a610bd53265f0
1,163
/* * Copyright 2020 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package com.google.cloud.healthcare.fdamystudies.dao; import java.util.HashSet; import java.util.List; import java.util.Map; import org.json.JSONArray; import com.google.cloud.healthcare.fdamystudies.beans.AppOrgInfoBean; import com.google.cloud.healthcare.fdamystudies.model.AppInfoDetailsBO; import com.google.cloud.healthcare.fdamystudies.model.StudyInfoBO; public interface CommonDao { public String validatedUserAppDetailsByAllApi(String userId, String email, int appId, int orgId); public AppOrgInfoBean getUserAppDetailsByAllApi(String userId, String appId, String orgId); public Integer getUserInfoDetails(String userId); public List<AppInfoDetailsBO> getAppInfoSet(HashSet<String> appIds); public List<StudyInfoBO> getStudyInfoSet(HashSet<String> studyInfoSet); public Map<Integer, Map<String, JSONArray>> getStudyLevelDeviceToken( List<StudyInfoBO> studyInfoIds); public String getParticicpantId(Integer id, String customeStudyId); }
32.305556
99
0.798796
102f927b8e598c65002c9fc11d546f61cd27d923
826
package net.glowstone.datapack.loader.model.external.predicate; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import net.glowstone.datapack.loader.model.external.advancement.condition.prop.Entity; public class EntityPropertiesPredicate implements Predicate { public static final String TYPE_ID = "minecraft:entity_properties"; private final String entity; private final Entity predicate; @JsonCreator public EntityPropertiesPredicate( @JsonProperty("entity") String entity, @JsonProperty("predicate") Entity predicate) { this.entity = entity; this.predicate = predicate; } public String getEntity() { return entity; } public Entity getPredicate() { return predicate; } }
28.482759
86
0.730024
43366824788517b3d362aaee34bf4150c8ac4bac
1,110
package com.blakebr0.cucumber.block; import net.minecraft.block.BlockState; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.IWorldReader; import java.util.function.Function; public class BaseOreBlock extends BaseBlock { private final int minExp; private final int maxExp; public BaseOreBlock(Material material, Function<Properties, Properties> properties, int minExp, int maxExp) { super(material, properties); this.minExp = minExp; this.maxExp = maxExp; } public BaseOreBlock(Material material, SoundType sound, float hardness, float resistance, int minExp, int maxExp) { super(material, sound, hardness, resistance); this.minExp = minExp; this.maxExp = maxExp; } @Override public int getExpDrop(BlockState state, IWorldReader world, BlockPos pos, int fortune, int silktouch) { return silktouch == 0 ? MathHelper.nextInt(RANDOM, this.minExp, this.maxExp) : 0; } }
33.636364
119
0.72973
d71e1ff4650d5206cffe08da3f214fa65fd7ae26
2,524
package com.sw.project.controller; import java.net.URI; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.sw.project.domain.Problem; import com.sw.project.domain.subProblem; import com.sw.project.domain.subProblemBody; import com.sw.project.exception.DataFormatException; import com.sw.project.exception.ResourceNotFoundException; import com.sw.project.service.ProblemService; import com.sw.project.service.subProblemService; @RestController @RequestMapping(value = "api/subproblem") public class subProblemController { @Autowired subProblemService subproblemService; @Autowired ProblemService problemService; @RequestMapping(value="", method = RequestMethod.POST, produces = {"application/json"}) public ResponseEntity<?> saveSubProblem(@Valid @RequestBody subProblemBody problemBody/*subProblem subproblem*/){ if(problemBody.getContent().length() < 10 || problemBody.getContent().equals("")) { throw new DataFormatException("Please check your content, content must be more than 10 length"); } //content length check Problem problem = problemService.getProblemById(problemBody.getPro_idx()) // problem search with idx .orElseThrow(()-> new ResourceNotFoundException("Cannot found problem with that idx")); subProblem subproblem = new subProblem(problemBody.getContent(), problem); if(subproblemService.saveSubProblem(subproblem)) { //save problem.addSubProblem(subproblem); URI location = ServletUriComponentsBuilder.fromCurrentRequest().buildAndExpand(subproblem.getIdx()).toUri(); return ResponseEntity.created(location).build(); } return new ResponseEntity<Void> (HttpStatus.INTERNAL_SERVER_ERROR); } /*@RequestMapping(value="/{idx}/all", method = RequestMethod.GET, produces = {"application/json"}) public ResponseEntity<?> getSubProblem(@Valid @PathVariable final String idx){ if(idx == null) throw new DataFormatException("Please check your content, content must have idx"); }*/ }
33.653333
114
0.786054
65d7204850780521fdcd1d03f47ad3d5f5fb83c9
8,719
class Payment { /** * 统一下单接口. * * @param request * @param response * * @return JSONObject json_return */ @Override public JSONObject createUnifiedOrder(HttpServletRequest request,HttpServletResponse response) { logger.info("微信 统一下单 接口调用"); //设置最终返回对象 JSONObject resultJson = new JSONObject(); //创建条件 Criteria criteria = new Criteria(); //接受参数(金额) String amount = request.getParameter("amount"); //接受参数(openid) String openid = request.getParameter("openid"); //接口调用总金额单位为分换算一下(测试金额改成1,单位为分则是0.01,根据自己业务场景判断是转换成float类型还是int类型) //String amountFen = Integer.valueOf((Integer.parseInt(amount)*100)).toString(); //String amountFen = Float.valueOf((Float.parseFloat(amount)*100)).toString(); String amountFen = "1"; //创建hashmap(用户获得签名) SortedMap<String, String> paraMap = new TreeMap<String, String>(); //设置body变量 (支付成功显示在微信支付 商品详情中) String body = "啦啦啦测试"; //设置随机字符串 String nonceStr = Utils.getUUIDString().replaceAll("-", ""); //设置商户订单号 String outTradeNo = Utils.getUUIDString().replaceAll("-", ""); //设置请求参数(小程序ID) paraMap.put("appid", APPLYID); //设置请求参数(商户号) paraMap.put("mch_id", MCHID); //设置请求参数(随机字符串) paraMap.put("nonce_str", nonceStr); //设置请求参数(商品描述) paraMap.put("body", body); //设置请求参数(商户订单号) paraMap.put("out_trade_no", outTradeNo); //设置请求参数(总金额) paraMap.put("total_fee", amountFen); //设置请求参数(终端IP) paraMap.put("spbill_create_ip", WebUtils.getIpAddress(request, response)); //设置请求参数(通知地址) paraMap.put("notify_url", WebUtils.getBasePath()+"wechat/wechatAppletGolf/payCallback"); //设置请求参数(交易类型) paraMap.put("trade_type", "JSAPI"); //设置请求参数(openid)(在接口文档中 该参数 是否必填项 但是一定要注意 如果交易类型设置成'JSAPI'则必须传入openid) paraMap.put("openid", openid); //调用逻辑传入参数按照字段名的 ASCII 码从小到大排序(字典序) String stringA = formatUrlMap(paraMap, false, false); //第二步,在stringA最后拼接上key得到stringSignTemp字符串,并对stringSignTemp进行MD5运算,再将得到的字符串所有字符转换为大写,得到sign值signValue。(签名) String sign = MD5Util.MD5(stringA+"&key="+KEY).toUpperCase(); //将参数 编写XML格式 StringBuffer paramBuffer = new StringBuffer(); paramBuffer.append("<xml>"); paramBuffer.append("<appid>"+APPLYID+"</appid>"); paramBuffer.append("<mch_id>"+MCHID+"</mch_id>"); paramBuffer.append("<nonce_str>"+paraMap.get("nonce_str")+"</nonce_str>"); paramBuffer.append("<sign>"+sign+"</sign>"); paramBuffer.append("<body>"+body+"</body>"); paramBuffer.append("<out_trade_no>"+paraMap.get("out_trade_no")+"</out_trade_no>"); paramBuffer.append("<total_fee>"+paraMap.get("total_fee")+"</total_fee>"); paramBuffer.append("<spbill_create_ip>"+paraMap.get("spbill_create_ip")+"</spbill_create_ip>"); paramBuffer.append("<notify_url>"+paraMap.get("notify_url")+"</notify_url>"); paramBuffer.append("<trade_type>"+paraMap.get("trade_type")+"</trade_type>"); paramBuffer.append("<openid>"+paraMap.get("openid")+"</openid>"); paramBuffer.append("</xml>"); try { //发送请求(POST)(获得数据包ID)(这有个注意的地方 如果不转码成ISO8859-1则会告诉你body不是UTF8编码 就算你改成UTF8编码也一样不好使 所以修改成ISO8859-1) Map<String,String> map = doXMLParse(getRemotePortData(URL, new String(paramBuffer.toString().getBytes(), "ISO8859-1"))); //应该创建 支付表数据 if(map!=null){ //清空 criteria.clear(); //设置openId条件 criteria.put("openId", openid); //获取数据 List<WechatAppletGolfPayInfo> payInfoList = appletGolfPayInfoMapper.selectByExample(criteria); //如果等于空 则证明是第一次支付 if(CollectionUtils.isEmpty(payInfoList)){ //创建支付信息对象 WechatAppletGolfPayInfo appletGolfPayInfo = new WechatAppletGolfPayInfo(); //设置主键 appletGolfPayInfo.setPayId(outTradeNo); //设置openid appletGolfPayInfo.setOpenId(openid); //设置金额 appletGolfPayInfo.setAmount(Long.valueOf(amount)); //设置支付状态 appletGolfPayInfo.setPayStatus("0"); //插入Dao int sqlRow = appletGolfPayInfoMapper.insert(appletGolfPayInfo); //判断 if(sqlRow == 1){ logger.info("微信 统一下单 接口调用成功 并且新增支付信息成功"); resultJson.put("prepayId", map.get("prepay_id")); resultJson.put("outTradeNo", paraMap.get("out_trade_no")); return resultJson; } }else{ //判断 是否等于一条 if(payInfoList.size() == 1){ //获取 需要更新数据 WechatAppletGolfPayInfo wechatAppletGolfPayInfo = payInfoList.get(0); //更新 该条的 金额 wechatAppletGolfPayInfo.setAmount(Long.valueOf(amount)); //更新Dao int sqlRow = appletGolfPayInfoMapper.updateByPrimaryKey(wechatAppletGolfPayInfo); //判断 if(sqlRow == 1){ logger.info("微信 统一下单 接口调用成功 修改支付信息成功"); resultJson.put("prepayId", map.get("prepay_id")); resultJson.put("outTradeNo", paraMap.get("out_trade_no")); return resultJson; } } } } //将 数据包ID 返回 System.out.println(map); } catch (UnsupportedEncodingException e) { logger.info("微信 统一下单 异常:"+e.getMessage()); e.printStackTrace(); } catch (Exception e) { logger.info("微信 统一下单 异常:"+e.getMessage()); e.printStackTrace(); } logger.info("微信 统一下单 失败"); return resultJson; } /** * 方法名: getRemotePortData * 描述: 发送远程请求 获得代码示例 * 参数: @param urls 访问路径 * 参数: @param param 访问参数-字符串拼接格式, 例:port_d=10002&port_g=10007&country_a= * 创建人: Xia ZhengWei * 创建时间: 2017年3月6日 下午3:20:32 * 版本号: v1.0 * 返回类型: String */ private String getRemotePortData(String urls, String param){ logger.info("开始执行http请求"); try { URL url = new URL(urls); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置连接超时时间 conn.setConnectTimeout(30000); // 设置读取超时时间 conn.setReadTimeout(30000); conn.setRequestMethod("POST"); // if(StringUtil.isNotBlank(param)) { // conn.setRequestProperty("Origin", "https://sirius.searates.com");// 主要参数 // conn.setRequestProperty("Referer", "https://sirius.searates.com/cn/port?A=ChIJP1j2OhRahjURNsllbOuKc3Y&D=567&G=16959&shipment=1&container=20st&weight=1&product=0&request=&weightcargo=1&"); // conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");// 主要参数 // } // 需要输出 conn.setDoInput(true); // 需要输入 conn.setDoOutput(true); // 设置是否使用缓存 conn.setUseCaches(false); // 设置请求属性 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接 conn.setRequestProperty("Charset", "UTF-8"); if(StringUtil.isNotBlank(param)) { // 建立输入流,向指向的URL传入参数 DataOutputStream dos=new DataOutputStream(conn.getOutputStream()); dos.writeBytes(param); dos.flush(); dos.close(); } // 输出返回结果 InputStream input = conn.getInputStream(); int resLen =0; byte[] res = new byte[1024]; StringBuilder sb=new StringBuilder(); while((resLen=input.read(res))!=-1){ sb.append(new String(res, 0, resLen)); } return sb.toString(); } catch (MalformedURLException e) { e.printStackTrace(); logger.info("url请求异常 : " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); logger.info("url 请求IO异常 : " + e.getMessage()); } logger.info("返回结果为空"); return ""; } }
42.740196
206
0.549604
0f15f4647aac4f168d68c8b36c57a63142ebb118
2,346
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.commands.autons; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.ParallelCommandGroup; import edu.wpi.first.wpilibj2.command.ParallelRaceGroup; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import frc.robot.Parameters; import frc.robot.RobotContainer; import frc.robot.commands.StopEverything; import frc.robot.commands.hood.HomeHood; import frc.robot.commands.intake.ColorSensorIntaking; import frc.robot.commands.shooting.PrepareShooterForVision; import frc.robot.commands.swerve.TurnToAngleVision; import frc.robot.commands.swerve.driving.DriveForTime; import frc.robot.commands.swerve.driving.SpinForTime; import frc.robot.subsystems.climber.HomeClimberTubes; // NOTE: Consider using this command inline, rather than writing a subclass. For more // information, see: // https://docs.wpilib.org/en/stable/docs/software/commandbased/convenience-features.html public class TwoBallAuton extends SequentialCommandGroup { public TwoBallAuton() { // Add your commands in the addCommands() call, e.g. // addCommands(new FooCommand(), new BarCommand()); addCommands( new InstantCommand( () -> RobotContainer.intakeWinch.setCurrentDistance( Parameters.intake.spool.HOME_DISTANCE)), new ParallelCommandGroup( new HomeHood(), new HomeClimberTubes(), new InstantCommand( () -> RobotContainer.intakeWinch.setDesiredDistance( Parameters.intake.spool.DOWN_DISTANCE))), new ParallelRaceGroup(new DriveForTime(1, 3), new ColorSensorIntaking()), new SpinForTime(1, 3.2), new ParallelRaceGroup( new TurnToAngleVision(true, false), new PrepareShooterForVision()) .withTimeout(3), new StopEverything()); } }
46
98
0.647485
4ca9deb6ecc97ce39a35fcfba65a8696f7f5c12e
499
package net.dirtydeeds.discordsoundboard; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; /** * This is the MainController for the SpringBoot application */ @SpringBootApplication @EnableAsync public class MainController { public MainController() { } public static void main(String[] args) { SpringApplication.run(MainController.class, args); } }
23.761905
68
0.799599
6dfaa182dde265723f5334b006a4d078530384e1
102
package pack1; public class Avo1 { public final int CINCO = 5; public void metodo1() { } }
8.5
28
0.627451
0df7c8dc155440f7ea52c0998c3f6e71a3b1b1bd
9,720
package genetics.common.mixin; import genetics.common.genetics.*; import genetics.init.Initializer; import genetics.items.ItemBlockChickenCube; import genetics.items.ItemBlockJar; import genetics.util.Logger; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.damage.DamageSource; import net.minecraft.entity.passive.ChickenEntity; import net.minecraft.entity.passive.CowEntity; import net.minecraft.entity.passive.LlamaEntity; import net.minecraft.entity.passive.PolarBearEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.DyeItem; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundTag; import net.minecraft.sound.SoundEvents; import net.minecraft.util.Hand; import net.minecraft.util.registry.Registry; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.Arrays; import static genetics.util.Logger.debugLog; import static genetics.util.Logger.log; @Mixin(Entity.class) public class EntityGeneticEvents implements IGeneticBase { @Shadow public World world; private Entity e = (Entity) (Object) this; private BaseGenetics myGenes = new BaseGenetics((Entity) (Object) this); @Inject(at = @At("RETURN"), method = "toTag") public void toTag(CompoundTag tag, CallbackInfoReturnable cir) { if (e instanceof LivingEntity) if (!world.isClient) { tag.putIntArray("genetics:genes", myGenes.getGenetics()); tag.putBoolean("genetics:hasGenetics", myGenes.hasGenetics); debugLog("Saved to tag Genetics " + Arrays.toString(myGenes.getGenetics())); } } @Inject(at = @At("RETURN"), method = "<init>", cancellable = true) public void init(EntityType<?> entityType_1, World world_1, CallbackInfo ci) { if (e instanceof LivingEntity) { if (e instanceof CowEntity) {// this should probably not be in the event but in a function called by the event myGenes = new CowGenetics((Entity) (Object) this); myGenes.initializeGenetics(); } else if(e instanceof LlamaEntity){ myGenes = new LlamaGenetics((Entity) (Object) this); ((LlamaGenetics)myGenes).initializeGenetics((LlamaEntity) (Object)this); }else if(e instanceof PolarBearEntity) { myGenes = new PolarBearGenetics((Entity) (Object) this); }else{ myGenes.initializeGenetics(); } } } @Inject(at = @At("RETURN"), method = "fromTag", cancellable = true) public void fromTag(CompoundTag tag, CallbackInfo ci) { if (e instanceof LivingEntity) //if (!world.isClient) { myGenes.setGenetics(tag.getIntArray("genetics:genes")); myGenes.hasGenetics = tag.getBoolean("genetics:hasGenetics"); debugLog("Loaded from tag Genetics " + Arrays.toString(myGenes.getGenetics())); //} } @Inject(at = @At("RETURN"), method = "interact", cancellable = true) public void interact(PlayerEntity playerEntity_1, Hand hand_1, CallbackInfoReturnable cir) { log("called interact event"); if (e instanceof LivingEntity) { log("Interacting with: " + myGenes.getEntityID() + " Genes: " + Arrays.toString(myGenes.getGenetics())); if (!world.isClient) { ItemStack itemStack_1 = playerEntity_1.getStackInHand(hand_1); if (itemStack_1.getItem() == Initializer.SYRINGE_EMPTY && !playerEntity_1.abilities.creativeMode) { e.damage(DamageSource.GENERIC, 0.5f); itemStack_1.setCount(itemStack_1.getCount() - 1); ItemStack newSyringe = new ItemStack(Initializer.SYRINGE_FULL); CompoundTag geneInfo = new CompoundTag(); geneInfo.putString("genetics:entitytype", e.getName().getString()); geneInfo.putIntArray("genetics:genes", ((IGeneticBase) e).getGenetics()); newSyringe.setTag(geneInfo); if (itemStack_1.isEmpty()) { playerEntity_1.setStackInHand(hand_1, newSyringe); } else if (!playerEntity_1.inventory.insertStack(newSyringe)) { playerEntity_1.dropItem(newSyringe, false); } cir.setReturnValue(true); }else if(e instanceof ChickenEntity || e instanceof PolarBearEntity){ if(itemStack_1.getItem() instanceof DyeItem){ int[] tempGenes = myGenes.getGenetics(); tempGenes[0] = ((DyeItem)itemStack_1.getItem()).getColor().getId(); myGenes.setGenetics(tempGenes); if(!playerEntity_1.abilities.creativeMode){ itemStack_1.setCount(itemStack_1.getCount() - 1); if(e instanceof PolarBearEntity){ ((PolarBearEntity) e).setTarget(playerEntity_1); } } } } if (itemStack_1.getItem() == Initializer.BLOCK_JAR.asItem() || itemStack_1.getItem() == Initializer.BLOCK_CHICKENCUBE.asItem()) { ItemStack newItem = null; CompoundTag entityInfo = new CompoundTag(); CompoundTag entity = new CompoundTag(); if(itemStack_1.getItem() == Initializer.BLOCK_CHICKENCUBE.asItem()){ ItemBlockChickenCube theItem= (ItemBlockChickenCube)itemStack_1.getItem(); Logger.log("was CUBE"); if(theItem.isEmpty) { Logger.log("was Empty"); if (e instanceof ChickenEntity) { newItem = new ItemStack(Initializer.BLOCK_CHICKENCUBE.asItem()); e.toTag(entity); entityInfo.putString("genetics:entitytype", e.getName().getString()); entityInfo.putString("entity_id", Registry.ENTITY_TYPE.getId(e.getType()).toString()); entityInfo.put("entityData", entity); newItem.setTag(entityInfo); e.removed = true; itemStack_1.setCount(itemStack_1.getCount() - 1); if (itemStack_1.isEmpty()) { playerEntity_1.setStackInHand(hand_1, newItem); } else if (!playerEntity_1.inventory.insertStack(newItem)) { playerEntity_1.dropItem(newItem, false); } } } }else if(itemStack_1.getItem() == Initializer.BLOCK_JAR.asItem()) { Logger.log("was JAR"); ItemBlockJar theItem = (ItemBlockJar) itemStack_1.getItem(); if (theItem.isEmpty) { Logger.log("was Empty"); newItem = new ItemStack(Initializer.BLOCK_JAR.asItem()); e.toTag(entity); entityInfo.putString("genetics:entitytype", e.getName().getString()); entityInfo.putString("entity_id", Registry.ENTITY_TYPE.getId(e.getType()).toString()); entityInfo.put("entityData", entity); System.out.println("ENTITYINFO AS STRING: " + entityInfo.asString()); newItem.setTag(entityInfo); e.removed = true; itemStack_1.setCount(itemStack_1.getCount() - 1); } if (newItem != null){ if(itemStack_1.isEmpty()) { playerEntity_1.setStackInHand(hand_1, newItem); } else if (!playerEntity_1.inventory.insertStack(newItem)) { playerEntity_1.dropItem(newItem, false); } } } } } } } @Override public void initializeGenetics() { myGenes.initializeGenetics(); } @Override public void initializeGenetics(int[] mum, int[] dad) { myGenes.initializeGenetics(mum, dad); } @Override public void setGeneticsFromPacket(int[] geneticArray) { myGenes.setGeneticsFromPacket(geneticArray); } @Override public int[] getGenetics() { return myGenes.getGenetics(); } @Override public int[] generateGenetics(int[] parent1, int[] parent2) { return myGenes.generateGenetics(parent1, parent2); } @Override public int[] generateGenetics() { return myGenes.generateGenetics(); } @Override public int getGeneticByIndex(int in) { return myGenes.getGeneticByIndex(in); } @Override public void setGeneticsInherited(int[] arr) { myGenes.setGeneticsInherited(arr); } }
45.633803
145
0.575617
ac10569d10a9e43cd3d68484049d02ab4953dd77
909
package com.datacloudsec.config.conf.intercepor; import java.io.Serializable; /** * AnalysisEventMappingBean * * @author gumizy 2017/9/7 */ public class AnalysisEventMappingBean implements Serializable { private String from; private String to; private Object defaultValue; private Boolean toString; public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public Object getDefaultValue() { return defaultValue; } public void setDefaultValue(Object defaultValue) { this.defaultValue = defaultValue; } public Boolean getToString() { return toString; } public void setToString(Boolean toString) { this.toString = toString; } }
17.480769
63
0.635864
356111683fcd20317426624b0a710458ac8ed59c
681
package com.webank.keygen.crypto; import org.bouncycastle.crypto.PBEParametersGenerator; import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator; import org.bouncycastle.crypto.params.KeyParameter; public enum PBKDF2WithHmacSha512 { INSTANCE; public byte[] kdf(char[] chars, byte[] salt) { PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(new SHA512Digest()); generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(chars), salt, 2048); KeyParameter key = (KeyParameter) generator.generateDerivedMacParameters(512); return key.getKey(); } }
40.058824
98
0.781204
b43b5fc1aab376bae705720fe94d1743fd3b61a1
15,109
/*=========================================================================== Copyright (C) 2014 by the Okapi Framework contributors ----------------------------------------------------------------------------- Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===========================================================================*/ package net.sf.okapi.filters.xliff2; import java.io.StringWriter; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Stack; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.sf.okapi.common.BOMNewlineEncodingDetector; import net.sf.okapi.common.Event; import net.sf.okapi.common.EventType; import net.sf.okapi.common.IParameters; import net.sf.okapi.common.LocaleId; import net.sf.okapi.common.MimeTypeMapper; import net.sf.okapi.common.UsingParameters; import net.sf.okapi.common.encoder.EncoderManager; import net.sf.okapi.common.filters.FilterConfiguration; import net.sf.okapi.common.filters.FilterUtil; import net.sf.okapi.common.filters.IFilter; import net.sf.okapi.common.filters.IFilterConfigurationMapper; import net.sf.okapi.common.filterwriter.IFilterWriter; import net.sf.okapi.common.resource.Ending; import net.sf.okapi.common.resource.ITextUnit; import net.sf.okapi.common.resource.Property; import net.sf.okapi.common.resource.RawDocument; import net.sf.okapi.common.resource.Segment; import net.sf.okapi.common.resource.StartDocument; import net.sf.okapi.common.resource.StartGroup; import net.sf.okapi.common.resource.StartSubDocument; import net.sf.okapi.common.skeleton.ISkeletonWriter; import net.sf.okapi.lib.xliff2.core.Directionality; import net.sf.okapi.lib.xliff2.core.MidFileData; import net.sf.okapi.lib.xliff2.core.Skeleton; import net.sf.okapi.lib.xliff2.core.StartFileData; import net.sf.okapi.lib.xliff2.core.StartGroupData; import net.sf.okapi.lib.xliff2.core.StartXliffData; import net.sf.okapi.lib.xliff2.core.Unit; import net.sf.okapi.lib.xliff2.reader.XLIFFReader; import net.sf.okapi.lib.xliff2.writer.XLIFFWriter; @UsingParameters(Parameters.class) public class XLIFF2Filter implements IFilter { public static final String XML_SPACE = "xml:space"; private final Logger logger = LoggerFactory.getLogger(getClass()); private Parameters params; private X2ToOkpConverter cvt; private boolean canceled; private XLIFFReader reader; private LocaleId srcLoc; private LocaleId trgLoc; private EncoderManager encoderManager; private Stack<String> idStack; private XMLSkeleton skel; private StartDocument startDoc; private StartSubDocument startSubDoc; private String lb; private LinkedList<Event> queue; private XLIFFWriter writer; private StringWriter writerBuffer; public XLIFF2Filter () { params = new Parameters(); } @Override public String getName () { return "okf_xliff2"; } @Override public String getDisplayName () { return "XLIFF-2 Filter (Experimental)"; } @Override public void open (RawDocument input) { canceled = false; // Determine encoding based on BOM, if any input.setEncoding("UTF-8"); // Default for XML, other should be auto-detected BOMNewlineEncodingDetector detector = new BOMNewlineEncodingDetector(input.getStream(), input.getEncoding()); detector.detectBom(); boolean hasUTF8BOM = detector.hasUtf8Bom(); lb = detector.getNewlineType().toString(); String encoding = "UTF-8"; if ( detector.isAutodetected() ) { encoding = detector.getEncoding(); } srcLoc = input.getSourceLocale(); trgLoc = input.getTargetLocale(); String docName = null; if ( input.getInputURI() != null ) { docName = input.getInputURI().getPath(); } int validation = (params.getMaxValidation() ? XLIFFReader.VALIDATION_MAXIMAL : XLIFFReader.VALIDATION_MINIMAL); reader = new XLIFFReader(validation); reader.open(input.getStream()); idStack = new Stack<>(); queue = new LinkedList<>(); skel = new XMLSkeleton(); startDoc = new StartDocument(idStack.push("docid")); startDoc.setName(docName); startDoc.setEncoding(encoding, hasUTF8BOM); startDoc.setFilterParameters(getParameters()); startDoc.setFilterWriter(createFilterWriter()); startDoc.setType(MimeTypeMapper.XLIFF2_MIME_TYPE); startDoc.setMimeType(MimeTypeMapper.XLIFF2_MIME_TYPE); startDoc.setMultilingual(true); startDoc.setLineBreak(lb); // The XML declaration is not reported by the parser, so we need to // create it as a document part when starting startDoc.setProperty(new Property(Property.ENCODING, encoding, false)); skel.add("<?xml version=\"1.0\" encoding=\""); skel.addValuePlaceholder(startDoc, Property.ENCODING, LocaleId.EMPTY); skel.add("\"?>"+lb); startDoc.setSkeleton(skel); writer = new XLIFFWriter(); writer.setLineBreak(lb); writer.setUseIndentation(true); writerBuffer = new StringWriter(); // Compile code finder rules if (params.getUseCodeFinder()) { params.getCodeFinder().compile(); } } @Override public void open (RawDocument input, boolean generateSkeleton) { open(input); // Skeleton option is just ignored } @Override public void close () { if ( reader != null ) { reader.close(); } reader = null; } @Override public boolean hasNext () { if ( !queue.isEmpty() ) return true; if ( canceled ) return false; return reader.hasNext(); } @Override public Event next () { // Dispatch queued events first if ( queue.isEmpty() ) { while ( !readNext() ) ; } return queue.poll(); } private boolean readNext () { // Otherwise process get the next event net.sf.okapi.lib.xliff2.reader.Event x2Event = reader.next(); switch ( x2Event.getType() ) { case START_DOCUMENT: // Handled in START_XLIFF return false; case START_XLIFF: StartXliffData sxd = x2Event.getStartXliffData(); processLocales(sxd); skel.add(conv(sxd)); queue.add(new Event(EventType.START_DOCUMENT, startDoc)); skel = new XMLSkeleton(); // send DEEPEN_SEGMENTATION event to SegmenterStep if needed if (params.getNeedsSegmentation()) { queue.add(FilterUtil.createDeepenSegmentationEvent()); } return true; case START_FILE: StartFileData sfd = x2Event.getStartFileData(); startSubDoc = new StartSubDocument(idStack.peek(), sfd.getId()); idStack.push(sfd.getId()); startSubDoc.setName(sfd.getOriginal()); skel.add(conv(sfd)); return false; case MID_FILE: skel.add(conv(x2Event.getMidFileData())); return false; case SKELETON: skel.add(conv(x2Event.getSkeletonData())); return false; case START_GROUP: sendStartSubDocumentIfNeeded(); StartGroupData sgd = x2Event.getStartGroupData(); StartGroup sg = new StartGroup(idStack.peek(), sgd.getId()); idStack.push(sgd.getId()); // skel.add(true, conv(sg)); queue.add(new Event(EventType.START_GROUP, sg, skel)); skel = new XMLSkeleton(); return true; case TEXT_UNIT: sendStartSubDocumentIfNeeded(); Unit unit = x2Event.getUnit(); ITextUnit tu = cvt.convert(unit); tu.getAlignedSegments().align(trgLoc); if (params.getUseCodeFinder()) { for(Segment s : tu.getAlignedSegments()) { params.getCodeFinder().process(s.text); params.getCodeFinder().process(tu.getTargetSegment(trgLoc, s.id, false).text); } // FIXME: new codes may need to be escaped for XML!!! } createUnitSkeleton(tu, unit, skel); tu.setMimeType(getMimeType()); queue.add(new Event(EventType.TEXT_UNIT, tu, skel)); skel = new XMLSkeleton(); return true; case END_GROUP: Ending eg = new Ending("end"+idStack.pop()); skel.add(convEndGroup()); queue.add(new Event(EventType.END_SUBDOCUMENT, eg, skel)); skel = new XMLSkeleton(); return true; case END_FILE: Ending esd = new Ending("end"+idStack.pop()); skel.add(convEndFile()); queue.add(new Event(EventType.END_SUBDOCUMENT, esd, skel)); skel = new XMLSkeleton(); return true; case END_XLIFF: // End is handled in END_DOCUMENT return false; case END_DOCUMENT: Ending ed = new Ending("end"+idStack.pop()); skel.add(convEndDocument()); queue.add(new Event(EventType.END_DOCUMENT, ed, skel)); skel = new XMLSkeleton(); return true; case INSIGNIFICANT_PART: skel.add(x2Event.getInsingnificantPartData().getData()); return false; } // Should never get here return false; } private void addTuProperties(ITextUnit tu, Unit unit) { if (unit.getName() != null) tu.setProperty(new Property(XMLSkeletonWriter.NAME, unit.getName())); tu.setProperty(new Property(XMLSkeletonWriter.CANRESEGMENT, unit.getCanResegment() ? "yes" : "no")); tu.setProperty(new Property(XMLSkeletonWriter.TRANSLATE, unit.getTranslate() ? "yes" : "no")); if (unit.getSourceDir() != Directionality.AUTO) tu.setProperty(new Property(XMLSkeletonWriter.SRCDIR, unit.getSourceDir().toString())); if (unit.getTargetDir() != Directionality.AUTO) tu.setProperty(new Property(XMLSkeletonWriter.TRGDIR, unit.getTargetDir().toString())); if (unit.getType() != null) tu.setProperty(new Property(XMLSkeletonWriter.TYPE, unit.getType())); } private void createUnitSkeleton(ITextUnit tu, Unit unit, XMLSkeleton skel) { addTuProperties(tu, unit); skel.add(String.format("<unit id=\"%s\"", unit.getId())); if (tu.hasProperty(XMLSkeletonWriter.NAME)) skel.add(XMLSkeletonWriter.NAME_PLACEHOLDER); if (tu.hasProperty(XMLSkeletonWriter.CANRESEGMENT)) skel.add(XMLSkeletonWriter.CANRESEGMENT_PLACEHOLDER); if (tu.hasProperty(XMLSkeletonWriter.TRANSLATE)) skel.add(XMLSkeletonWriter.TRANSLATE_PLACEHOLDER); if (tu.hasProperty(XMLSkeletonWriter.SRCDIR)) skel.add(XMLSkeletonWriter.SRCDIR_PLACEHOLDER); if (tu.hasProperty(XMLSkeletonWriter.TRGDIR)) skel.add(XMLSkeletonWriter.TRGDIR_PLACEHOLDER); if (tu.hasProperty(XMLSkeletonWriter.TYPE)) skel.add(XMLSkeletonWriter.TYPE_PLACEHOLDER); // close unit start tag skel.add(">\n"); skel.add(XMLSkeletonWriter.SEGMENTS_PLACEHOLDER); skel.add("</unit>\n"); } private void sendStartSubDocumentIfNeeded () { if ( startSubDoc == null ) return; // Done already queue.add(new Event(EventType.START_SUBDOCUMENT, startSubDoc, skel)); skel = new XMLSkeleton(); startSubDoc = null; } private String conv (StartXliffData sxd) { writer.writeStartDocument(sxd, null); String tmp = writerBuffer.toString(); writerBuffer.getBuffer().setLength(0); // Strip the XML declaration which is already in the skeleton return tmp.substring(tmp.indexOf("<xlif")); } private String conv (StartFileData sfd) { writer.writeStartFile(sfd); String tmp = writerBuffer.toString(); writerBuffer.getBuffer().setLength(0); return tmp; } private String conv (MidFileData mfd) { writer.writeMidFile(mfd); String tmp = writerBuffer.toString(); writerBuffer.getBuffer().setLength(0); return tmp; } private String conv (Skeleton skelData) { writer.writeSkeleton(skelData); String tmp = writerBuffer.toString(); writerBuffer.getBuffer().setLength(0); return tmp; } private String convEndGroup () { writer.writeEndGroup(); String tmp = writerBuffer.toString(); writerBuffer.getBuffer().setLength(0); return tmp; } private String convEndFile () { writer.writeEndFile(); String tmp = writerBuffer.toString(); writerBuffer.getBuffer().setLength(0); return tmp; } private String convEndDocument () { writer.writeEndDocument(); String tmp = writerBuffer.toString(); writerBuffer.getBuffer().setLength(0); return tmp; } /** * Checks the source and target locales of the document and * deal with any discrepancy if needed. * @param sxd the START_XLIFF data */ private void processLocales (StartXliffData sxd) { // Check the source String src = sxd.getSourceLanguage(); if ( srcLoc != null && !srcLoc.equals(LocaleId.EMPTY)) { if ( srcLoc.compareTo(src) != 0 ) { logger.warn("Discripancy between expected source ({}) and source in document ({}), Using '{}'", srcLoc.toString(), src, src); // Use the locale in the file srcLoc = LocaleId.fromBCP47(src); } } else { // source locale was to be guessed srcLoc = LocaleId.fromBCP47(src); } startDoc.setLocale(srcLoc); writer.create(writerBuffer, srcLoc.toBCP47()); // Check the target String trg = sxd.getTargetLanguage(); if ( trg != null) { if ( trgLoc != null && !trgLoc.equals(LocaleId.EMPTY)) { // Compare raw-document settings with real file if ( trgLoc.compareTo(trg) != 0 ) { logger.warn("Discripancy between expected target ({}) and target in document ({}), Using '{}'", trgLoc.toString(), trg, trg); // Use the locale in the file trgLoc = LocaleId.fromBCP47(trg); } } else { // Nothing set in raw-document: use the one in the file trgLoc = LocaleId.fromBCP47(trg); } } else { if ( trgLoc == null ) { // No target locale specified (in either raw-document or document itself) throw new NullPointerException("Target language not set and cannot be guessed."); } } cvt = new X2ToOkpConverter(true, trgLoc); } @Override public void cancel () { canceled = true; queue.clear(); queue.add(new Event(EventType.CANCELED)); close(); } @Override public IParameters getParameters () { return params; } @Override public void setParameters (IParameters params) { this.params = (Parameters)params; } @Override public void setFilterConfigurationMapper (IFilterConfigurationMapper fcMapper) { // TODO Auto-generated method stub } @Override public ISkeletonWriter createSkeletonWriter () { // TODO implement real skeleton writer XMLSkeletonWriter writer = new XMLSkeletonWriter(); return writer; } @Override public IFilterWriter createFilterWriter () { //TODO: Implement real filter writer as needed return new XMLFilterWriter(createSkeletonWriter(), getEncoderManager()); } @Override public EncoderManager getEncoderManager () { //TODO: implement real encoder if needed if ( encoderManager == null ) { encoderManager = new EncoderManager(); encoderManager.setMapping(MimeTypeMapper.XLIFF2_MIME_TYPE, "net.sf.okapi.common.encoder.XMLEncoder"); } return encoderManager; } @Override public String getMimeType () { return MimeTypeMapper.XLIFF2_MIME_TYPE; } @Override public List<FilterConfiguration> getConfigurations () { List<FilterConfiguration> list = new ArrayList<FilterConfiguration>(); list.add(new FilterConfiguration(getName(), MimeTypeMapper.XLIFF2_MIME_TYPE, getClass().getName(), "XLIFF-2", "Configuration for XLIFF-2 documents.", null, ".xlf")); return list; } }
32.078556
137
0.716791
87cf854d3f925cc8f6140e53fc2cbef2a66b12b2
3,418
/* * 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.netbeans.modules.groovy.grails.server; import javax.swing.Action; import org.netbeans.api.project.Project; import org.netbeans.api.project.ProjectInformation; import org.netbeans.modules.groovy.grails.api.GrailsConstants; import org.netbeans.modules.groovy.grails.api.GrailsProjectConfig; import org.openide.nodes.AbstractNode; import org.openide.nodes.Children; import org.openide.nodes.Node; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import org.openide.util.actions.NodeAction; import org.openide.util.actions.SystemAction; /** * * @author Petr Hejl */ public class ApplicationNode extends AbstractNode { public ApplicationNode(final Project project, final Process process) { super(Children.LEAF); GrailsProjectConfig config = GrailsProjectConfig.forProject(project); ProjectInformation info = project.getLookup().lookup(ProjectInformation.class); setDisplayName(NbBundle.getMessage( GrailsInstance.class, "ApplicationNode.displayName", info.getDisplayName(), config.getPort())); setIconBaseWithExtension(GrailsConstants.GRAILS_ICON_16x16); getCookieSet().add(new ProcessCookie() { public Process getProcess() { return process; } }); } @Override public Action[] getActions(boolean context) { return new Action[] {SystemAction.get(StopAction.class)}; } private static class StopAction extends NodeAction { public StopAction() { super(); } @Override protected boolean enable(Node[] activatedNodes) { for (Node node : activatedNodes) { ProcessCookie cookie = node.getCookie(ProcessCookie.class); if (cookie == null) { return false; } } return true; } @Override protected void performAction(Node[] activatedNodes) { for (Node node : activatedNodes) { ProcessCookie cookie = node.getCookie(ProcessCookie.class); if (cookie != null) { cookie.getProcess().destroy(); } } } @Override public HelpCtx getHelpCtx() { return HelpCtx.DEFAULT_HELP; } @Override public String getName() { return NbBundle.getMessage(ApplicationNode.class, "ApplicationNode.stopActionName"); } @Override protected boolean asynchronous() { return false; } } }
32.245283
111
0.658572
7226241b25ab44560aa03acf66522f2d80418011
560
/** * RestifErrorDto.java * (C) 2013,2015, Hitachi, Ltd. */ package org.o3project.mlo.server.dto; import javax.xml.bind.annotation.XmlElement; /** * This is the DTO class of error information. */ public class RestifErrorDto { /** A cause of the error. */ @XmlElement(name = "Cause") public String cause; /** A detail description. */ @XmlElement(name = "Detail") public String detail; /** Slice name. */ @XmlElement(name = "SliceName") public String sliceName; /** Slice ID. */ @XmlElement(name = "SliceId") public String sliceId; }
18.666667
47
0.667857
9c530884cd76d465046f1c831dc20870aa415e7a
174
package datastructures; public class BinaryTrieTest extends MembershipTest { @Override protected Membership getInstance() { return new BinaryTrie(); } }
19.333333
52
0.712644
2c517f722bfc0efac4dc9062aa71db930c30914f
498
package pnet.data.api.util; import java.util.Collection; /** * Restricts todo ids. * * @author ham * @param <SELF> the type of the filter for chaining */ public interface RestrictTodoId<SELF extends Restrict<SELF>> extends Restrict<SELF> { default SELF todoId(Integer... todoIds) { return restrict("todoId", (Object[]) todoIds); } default SELF todoIds(Collection<Integer> todoIds) { return todoId(todoIds.toArray(new Integer[todoIds.size()])); } }
19.92
83
0.668675
3b24eb4846d77703adcb871ad9d500d53f9b99e6
9,027
/** * Copyright (c) 2013-2014, TU Braunschweig * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of California, Los Angeles nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER 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 avrora.sim.platform.devices; import avrora.sim.mcu.TWIData; import avrora.sim.mcu.TWIDevice; import avrora.sim.platform.sensors.Sensor; import avrora.sim.platform.sensors.SensorSource; //import java.math.BigInteger; /** * * @author S. Willenborg */ public class BMP085 extends Sensor implements TWIDevice { private static final int TEMP = 0; private static final int PRESSURE = 1; private static final byte ADDRESS = (byte) 0xee; private static final short EEPROM_START = 0xaa; private static final short EEPROM_END = 0xbf; private static final byte MODE_TEMP = 0x2e; private static final byte MODE_PRESSURE_0 = 0x34; private static final byte MODE_PRESSURE_1 = 0x74; private static final byte MODE_PRESSURE_2 = (byte) 0xb4; private static final byte MODE_PRESSURE_3 = (byte) 0xf4; private static final short DATA_START = 0xf6; private static final byte CONTROL_REGISTER = (byte) 0xf4; private static final short AC1 = 408; private static final short AC2 = -72; private static final short AC3 = -14383; private static final short AC4 = 32741; private static final short AC5 = 32757; private static final short AC6 = 23153; private static final short B1 = 6190; private static final short B2 = 4; private static final short MB = -32768; private static final short MC = -8711; private static final short MD = 2868; private SensorSource source; private boolean active = false; private int writecount = 0; private byte reg = 0; private final short[] koeffz = {AC1, AC2, AC3, AC4, AC5, AC6, B1, B2, MB, MC, MD}; int measure_data = 0x00; int measure_mode = 0x00; private final Channel[] channels = new Channel[] { new Channel("Temperature", "C", -40, 85, 0.0), // resolution: 1/10 C new Channel("Pressure", "Pa", 3000, 11000, 0.0) }; public BMP085() { } @Override public Channel[] getChannels() { return channels; } @Override public void setSensorSource(SensorSource src) { source = src; } public final int convertTemperature(double temp) { System.out.printf("convertTemperature(%f)%n", temp); int T = (int) (temp * 10); int converted = (int) (((Math.sqrt(MD * MD + (((T + 1) << 5) - (2 << 4)) * MD - (MC << 13) + (((T) * (T + 1)) << 8) + 64) - MD + ((T + 1) << 4) - 8) / AC5) * (1 << 14) + AC6); return converted; } /** * Converts pressure data in Pa to data as emitted by the sensor device. * * @param temp Temperature [C] uses (max 1/10 C) resolution * @param pressure Pressure [Pa] * @param mode operation mode. [0 .. 3] * @return */ public final int convertPressure(double temp, int pressure, int mode) { int x1 = (convertTemperature(temp) - AC6) * AC5 >> 15; int x2 = (MC * 2048) / (x1 + MD); int b5 = x1 + x2; int b6 = b5 - 4000; int b3 = ((((AC1) * 4 + (((B2 * ((b6 * b6) >> 12)) >> 11) + ((AC2 * b6) >> 11))) << mode) + 2) >> 2; int b4 = (AC4 * ((((((AC3 * b6) / 8192) + ((B1 * ((b6 * b6) / 4096)) / 65536)) + 2) / 4) + 32768)) / 32768; int pt = pressure; int p = pt; int direction; if (pt <= 48361) { direction = -1; } else if (pt <= 48384) { direction = 1; } else if (pt <= 48512) { direction = -1; } else if (pt <= 48640) { direction = 1; } else if (pt <= 48673) { direction = -1; } else if (pt <= 110080) { direction = 1; } else if (pt <= 110120) { direction = -1; } else if (pt <= 110336) { direction = 1; } else if (pt <= 110476) { direction = -1; } else if (pt <= 110593) { direction = 1; } else if (pt <= 110833) { direction = -1; } else if (pt <= 110850) { direction = 1; } else { direction = -1; } while (pt != (p + (((((((p >> 8) * (p >> 8) * 1519 * 2) >> 16) + ((-7357 * p) >> 16) + 3791))) >> 4))) { p += direction; } // int b7 = BigInteger.valueOf(p).multiply(BigInteger.valueOf(b4)).divide(BigInteger.valueOf(2)).intValue(); int b7 = (int) (((long) p) * b4 / 2); return (b7 / (50000 >> mode) + b3 + 1) << (8 - mode); } private void refresh_values(byte measure_mode) { this.measure_mode = measure_mode; switch (measure_mode) { case MODE_TEMP: // Temperature measure_data = convertTemperature(source.read(TEMP)); break; case MODE_PRESSURE_0: // Pressure (osrs =0) measure_data = convertPressure(source.read(TEMP), (int) Math.round(source.read(PRESSURE)), 0); break; case MODE_PRESSURE_1: // Pressure (osrs =1) measure_data = convertPressure(source.read(TEMP), (int) Math.round(source.read(PRESSURE)), 1); break; case MODE_PRESSURE_2: // Pressure (osrs =2) measure_data = convertPressure(source.read(TEMP), (int) Math.round(source.read(PRESSURE)), 2); break; case MODE_PRESSURE_3: // Pressure (osrs =3) measure_data = convertPressure(source.read(TEMP), (int) Math.round(source.read(PRESSURE)), 3); break; } } public final byte getSensorCoefficent(byte addr) { byte index = (byte) ((addr & 0xff) - EEPROM_START); return (byte) (((koeffz[index / 2] >> ((1 - (index % 2)) * 8))) & 0xff); } // eeprom 0xaa -0xbf // temp or preasure value: 0xf6(msb, 0xf7 lsb, 0xf8 xlsb @Override public Boolean writeByte(byte data, boolean ack) { if (!active) { return null; } // first byte is register address if (writecount == 0) { reg = data; // second byte is control register data } else if (writecount == 1) { if (reg == CONTROL_REGISTER) { refresh_values(data); } } else { // not supported! } writecount++; return ack; } @Override public TWIData readByte(boolean ack) { if (!active) { return null; } byte result = 0x00; if (isEEPROM(reg)) { result = getSensorCoefficent(reg); } else { int i = ((reg & 0xff) - DATA_START); if (measure_mode == MODE_TEMP && i < 2) { result = (byte) ((measure_data >> ((1 - i) * 8)) & 0xff); } else if (i < 3) { result = (byte) ((measure_data >> ((2 - i) * 8)) & 0xff); } } reg++; return new TWIData(result, ack); } @Override public Boolean start(byte address, boolean write, boolean rep, boolean ack) { active = (address == ADDRESS); if (!active) { return null; } writecount = 0; return ack; } @Override public Boolean stop() { if (!active) { return null; } return true; } private boolean isEEPROM(byte reg) { return (reg & 0xff) >= EEPROM_START && (reg & 0xff) <= EEPROM_END; } }
34.586207
183
0.573502
43e5613bed45ba6c5a14ba2478bc646b0ec342df
11,061
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.ei.tools.converter.common.builder; import org.ballerinalang.model.BLangPackage; import org.ballerinalang.model.BLangProgram; import org.ballerinalang.model.BallerinaFile; import org.ballerinalang.model.GlobalScope; import org.ballerinalang.model.NativeScope; import org.ballerinalang.model.builder.BLangModelBuilder; import org.ballerinalang.model.types.SimpleTypeName; import org.ballerinalang.util.program.BLangPackages; import org.ballerinalang.util.program.BLangPrograms; import org.ballerinalang.util.repository.PackageRepository; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.Stack; /** * {@code BallerinaASTModelBuilder} is a high level API to build ballerina AST from BLangModelBuilder class */ public class BallerinaASTModelBuilder { private static final PackageRepository PACKAGE_REPOSITORY = new PackageRepository() { @Override public PackageSource loadPackage(Path path) { return null; } @Override public PackageSource loadFile(Path path) { return null; } }; private boolean processingActionInvocationStmt = false; private Stack<BLangModelBuilder.NameReference> nameReferenceStack = new Stack<>(); private Stack<SimpleTypeName> typeNameStack = new Stack<>(); private BLangProgram programScope; private BLangPackage bLangPackage; private BLangModelBuilder modelBuilder; private Map<String, String> ballerinaPackageMap = new HashMap<String, String>(); // private boolean isWorkerStarted = false; public BallerinaASTModelBuilder() { GlobalScope globalScope = BLangPrograms.populateGlobalScope(); NativeScope nativeScope = BLangPrograms.populateNativeScope(); programScope = new BLangProgram(globalScope, nativeScope, BLangProgram.Category.SERVICE_PROGRAM); bLangPackage = new BLangPackage(".", PACKAGE_REPOSITORY, programScope); BLangPackage.PackageBuilder packageBuilder = new BLangPackage.PackageBuilder(bLangPackage); modelBuilder = new BLangModelBuilder(packageBuilder, "."); String[] packages = BLangPackages.getBuiltinPackageNames(); for (String aPackage : packages) { String[] bits = aPackage.split("\\."); String pkgName = bits[bits.length - 1]; ballerinaPackageMap.put(pkgName, aPackage); } } public void addImportPackage(String pkgPath, String asPkgName) { modelBuilder.addImportPackage(null, null, pkgPath, asPkgName); } /** * TODO: Need to refactor this to support multiple key value pairs of an annotation * * @param pkgName name of the package * @param name functionality name you want to use * @param key annotation attribute key * @param actualvalue annotation attribute value */ public void createAnnotationAttachment(String pkgName, String name, String key, String actualvalue) { modelBuilder.startAnnotationAttachment(null); createNameReference(pkgName, name); if (key != null && actualvalue != null) { modelBuilder.createStringLiteral(null, null, actualvalue); modelBuilder.createLiteralTypeAttributeValue(null, null); modelBuilder.createAnnotationKeyValue(null, key); } } /** * Adds an annotation. For an attachment to be added first it needs to be created using * 'createAnnotationAttachment' method * * @param attributesCount is never used in ballerina side, even though it expects a value */ public void addAnnotationAttachment(int attributesCount) { modelBuilder.addAnnotationAttachment(null, null, nameReferenceStack.pop(), attributesCount); } public void startService() { modelBuilder.startServiceDef(null); } public void startResource() { modelBuilder.startResourceDef(); } public void endOfService(String serviceName) { modelBuilder.createService(null, serviceName); } public void endOfResource(String resourceName, int annotationCount) { modelBuilder.addResource(null, null, resourceName, annotationCount); } public void startFunction() { modelBuilder.startFunctionDef(null); } public void endOfFunction(String functionName) { modelBuilder.addFunction(null, functionName, false); //isNative is false } /** * Add built in ref types * * @param builtInRefTypeName built in type */ public void addTypes(String builtInRefTypeName) { SimpleTypeName simpleTypeName = new SimpleTypeName(builtInRefTypeName); typeNameStack.push(simpleTypeName); } public void createRefereceTypeName() { BLangModelBuilder.NameReference nameReference = nameReferenceStack.pop(); SimpleTypeName typeName = new SimpleTypeName(nameReference.getName(), nameReference.getPackageName(), nameReference.getPackagePath()); typeNameStack.push(typeName); } /** * Create a function parameter * * @param annotationCount number of annotations - this is required in case of PathParam or QueryParam * annotations * @param processingReturnParams return parameter or not * @param paramName name of the function parameter */ public void addParameter(int annotationCount, boolean processingReturnParams, String paramName) { modelBuilder.addParam(null, null, typeNameStack.pop(), paramName, annotationCount, processingReturnParams); } public void startCallableBody() { modelBuilder.startCallableUnitBody(null); } public void endCallableBody() { modelBuilder.endCallableUnitBody(); } //TODO:Ask, what this does public void addMapStructLiteral() { modelBuilder.startMapStructLiteral(); modelBuilder.createMapStructLiteral(null, null); } /** * @param varName name of the variable * @param exprAvailable expression availability */ public void createVariable(String varName, boolean exprAvailable) { SimpleTypeName typeName = typeNameStack.pop(); modelBuilder.addVariableDefinitionStmt(null, null, typeName, varName, exprAvailable); } /** * Create a name reference * * @param pkgName package name * @param name functionality name you want to use */ public void createNameReference(String pkgName, String name) { BLangModelBuilder.NameReference nameReference; nameReference = new BLangModelBuilder.NameReference(pkgName, name); modelBuilder.validateAndSetPackagePath(null, nameReference); nameReferenceStack.push(nameReference); } public void startExprList() { modelBuilder.startExprList(); } public void endExprList(int noOfArguments) { modelBuilder.endExprList(noOfArguments); } public void createVariableRefExpr() { modelBuilder.createVarRefExpr(null, null, nameReferenceStack.pop()); } public void createStringLiteral(String stringLiteral) { modelBuilder.createStringLiteral(null, null, stringLiteral); } public void createIntegerLiteral(String intLiteral) { modelBuilder.createIntegerLiteral(null, null, intLiteral); } public void createBackTickExpression(String content) { //TODO : update to match with new Ballerina changes //modelBuilder.createBacktickExpr(null, null, content); } public void createFunctionInvocation(boolean argsAvailable) { modelBuilder.createFunctionInvocationStmt(null, null, nameReferenceStack.pop(), argsAvailable); } public void createReplyStatement() { modelBuilder.createReplyStmt(null, null); } public void initializeConnector(boolean argsAvailable) { BLangModelBuilder.NameReference nameReference = nameReferenceStack.pop(); SimpleTypeName connectorTypeName = new SimpleTypeName(nameReference.getName(), nameReference.getPackageName(), null); modelBuilder.createConnectorInitExpr(null, null, connectorTypeName, argsAvailable); } public void createVariableRefList() { modelBuilder.startVarRefList(); } public void endVariableRefList(int noArguments) { modelBuilder.endVarRefList(noArguments); } public void createAction(String actionName, boolean argsAvailable) { BLangModelBuilder.NameReference nameReference = nameReferenceStack.pop(); if (processingActionInvocationStmt) { // modelBuilder.createActionInvocationStmt(null, null, nameReference, actionName, argsAvailable); modelBuilder.createActionInvocationStmt(null, null); } else { modelBuilder.addActionInvocationExpr(null, null, nameReference, actionName, argsAvailable); } } public void createAssignmentStatement() { // modelBuilder.createAssignmentStmt(null, null); } public BallerinaFile buildBallerinaFile() { BallerinaFile bFile = modelBuilder.build(); return bFile; } public Map<String, String> getBallerinaPackageMap() { return ballerinaPackageMap; } public void addComment(String comment) { modelBuilder.addCommentStmt(null, null, comment); } public void addFunctionInvocationStatement(boolean argsAvailable) { modelBuilder.createFunctionInvocationStmt(null, null, nameReferenceStack.pop(), argsAvailable); } public void createWorkerInvocationStmt(String workerName) { modelBuilder.createWorkerInvocationStmt(workerName, null, null); } public void enterWorkerDeclaration() { // isWorkerStarted = true; modelBuilder.startWorkerUnit(); modelBuilder.startCallableUnitBody(null); } public void createWorkerDefinition(String workerName) { modelBuilder.createWorkerDefinition(null, workerName); } public void exitWorkerReply(String defaultWorkerName) { modelBuilder.createWorkerReplyStmt(defaultWorkerName, null, null); } public void exitWorkerDeclaration(String workerName) { modelBuilder.endCallableUnitBody(); modelBuilder.createWorker(null, null, workerName); // isWorkerStarted = false; } }
35.565916
118
0.705
9f2953b48641b2f1830648d9209c03a95e151b0f
2,806
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.awt.event; /** * An abstract adapter class for receiving mouse events. * The methods in this class are empty. This class exists as * convenience for creating listener objects. * <P> * Mouse events let you track when a mouse is pressed, released, clicked, * moved, dragged, when it enters a component, when it exits and * when a mouse wheel is moved. * <P> * Extend this class to create a {@code MouseEvent} * (including drag and motion events) or/and {@code MouseWheelEvent} * listener and override the methods for the events of interest. (If you implement the * {@code MouseListener}, * {@code MouseMotionListener} * interface, you have to define all of * the methods in it. This abstract class defines null methods for them * all, so you can only have to define methods for events you care about.) * <P> * Create a listener object using the extended class and then register it with * a component using the component's {@code addMouseListener} * {@code addMouseMotionListener}, {@code addMouseWheelListener} * methods. * The relevant method in the listener object is invoked and the {@code MouseEvent} * or {@code MouseWheelEvent} is passed to it in following cases: * <p><ul> * <li>when a mouse button is pressed, released, or clicked (pressed and released) * <li>when the mouse cursor enters or exits the component * <li>when the mouse wheel rotated, or mouse moved or dragged * </ul> * * @author Carl Quinn * @author Andrei Dmitriev * * @see MouseEvent * @see MouseWheelEvent * @see MouseListener * @see MouseMotionListener * @see MouseWheelListener * @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/mouselistener.html">Tutorial: Writing a Mouse Listener</a> * * @since 1.1 */ public abstract class MouseAdapter implements MouseListener, MouseWheelListener, MouseMotionListener { /** * {@inheritDoc} */ public void mouseClicked(MouseEvent e) {} /** * {@inheritDoc} */ public void mousePressed(MouseEvent e) {} /** * {@inheritDoc} */ public void mouseReleased(MouseEvent e) {} /** * {@inheritDoc} */ public void mouseEntered(MouseEvent e) {} /** * {@inheritDoc} */ public void mouseExited(MouseEvent e) {} /** * {@inheritDoc} * @since 1.6 */ public void mouseWheelMoved(MouseWheelEvent e){} /** * {@inheritDoc} * @since 1.6 */ public void mouseDragged(MouseEvent e){} /** * {@inheritDoc} * @since 1.6 */ public void mouseMoved(MouseEvent e){} }
24.614035
126
0.662153
a09d448de85dbe28dc08af8c615d8c9f55a9a12b
910
package genericsAndCollections.generics.bounds; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Lowerbounded are mutable */ public class LowerBounded { private void addSound(List<? super String> list) { list.add("This is mutable!"); list.add(""); // THIS IS MUTABLE, BUT YOU CAN ADD ONLY STRINGS } public void main() { List<String> strings = new ArrayList<>(); strings.add("aaa"); List<Object> objects = new ArrayList<>(strings); addSound(strings); addSound(objects); } public void testname() throws Exception { List<? super IOException> exceptions = new ArrayList<Exception>(); // exceptions.add(new Exception()); This does not compile, cause we could have an Exception object in there, and it wouldnt fit the List exceptions.add(new IOException()); exceptions.add(new FileNotFoundException()); } }
27.575758
138
0.726374
24d7b8ccde4891d67103b97c1e20a82a057b27de
17,113
import ij.IJ; import ij.ImagePlus; import ij.ImageStack; import ij.gui.Line; import ij.gui.OvalRoi; import ij.gui.Overlay; import ij.gui.PointRoi; import ij.process.ByteProcessor; import ij.process.FloatProcessor; import java.awt.*; import java.util.ArrayList; /** * * * * * In a right-handed coordinate system, the rotations are as follows: 90 degrees CW about x-axis: (x, y, z) -> (x, -z, y) 90 degrees CCW about x-axis: (x, y, z) -> (x, z, -y) 90 degrees CW about y-axis: (x, y, z) -> (-z, y, x) 90 degrees CCW about y-axis: (x, y, z) -> (z, y, -x) 90 degrees CW about z-axis: (x, y, z) -> (y, -x, z) 90 degrees CCW about z-axis: (x, y, z) -> (-y, x, z) * Created by miroslav on 15-2-15. */ public class Zncc2D { private static float arcRes = 1.0f; // private static float samplingStep = 1f; // something that was used for the first version of filtering private float radius; // aa private int N; // aa public int limR, limT; // aa public float[] sigmas; private float sigma_step = .5f; private float sg_min = 1f; public static ArrayList<Float> theta = new ArrayList<Float>(); // list of elements (theta) covering the circle private static ArrayList<float[][]> offstXY = new ArrayList<float[][]>(); // list of filter offsets for each direction private float[][] tplt; // template private float[] tplt_avg; // template average private float[][] tplt_hat; // template - template average private float[] tplt_hat_sum_2; // sum(template- template average)^2 float[][] kernels; // Ndirections*Nscales x limR*limR float[] kernels_avg; // average float[][] kernels_hat; // kernel-average float[] kernels_hat_sum_2; // sum(kernel-average)^2 private static float TWO_PI = (float) (2 * Math.PI); private static float PI = (float) (Math.PI); public Zncc2D(float _radius) { radius = _radius; limT = (int) Math.ceil(radius/samplingStep); // transversal sampling limits limR = 2 * limT + 1; // how many to take radially with given sampling step int rr = (int) Math.ceil(_radius); rr = (rr<1)? 1 : rr; // sigmas define int cnt = 0; for (float sg = sg_min; sg <= .4f*rr; sg+=sigma_step) cnt++; sigmas = new float[cnt]; cnt = 0; for (float sg = sg_min; sg <= .4f*rr; sg+=sigma_step) sigmas[cnt++] = sg; // form N theta (N directions) N = (int) Math.ceil(((PI * radius)/arcRes)); theta.clear(); for (int i=0; i<N; i++) theta.add(i * (PI/N)); offstXY.clear(); // float sumWgt = 0; for (int ii = 0; ii<theta.size(); ii++) { // define offsetsPerDirection, weights (at one direction only) float[][] offsetsPerDirection = new float[limR*limR][2]; // (limR+1) cnt = 0; for (int k=-limT; k<=limT; k++) { for (int i=-limT; i<=limT; i++) { // for (int j = -limT; j<=limT; j++) { float px = i * samplingStep; // float py = j * samplingStep; float py = k * samplingStep; offsetsPerDirection[cnt][0] = px; offsetsPerDirection[cnt][1] = py; // offsetsPerDirection[cnt][2] = pz; cnt++; // } } } // transformation for offsets before adding // transY(radius, offsetsPerDirection); //rotY(-phi+HalfPI, offsetsPerDirection); rotZ(theta.get(ii), offsetsPerDirection); offstXY.add(offsetsPerDirection); //store } // fill the templates in tplt = new float[sigmas.length][limR*limR]; // weights at different sigmas only for the first theta, the rest are the same tplt_avg = new float[sigmas.length]; tplt_hat = new float[sigmas.length][limR*limR]; tplt_hat_sum_2 = new float[sigmas.length]; for (int sig_idx = 0; sig_idx < sigmas.length; sig_idx++) { float minWgt = Float.POSITIVE_INFINITY; float maxWgt = Float.NEGATIVE_INFINITY; cnt = 0; for (int k=-limT; k<=limT; k++) { for (int i = -limT; i <= limT; i++) { float px = i * samplingStep; float py = k * samplingStep; float dstAxis = point2line(0,0, 0,1, px,py); tplt[sig_idx][cnt] = (float) Math.exp(-(dstAxis*dstAxis)/(2*Math.pow(sigmas[sig_idx],2))); if (tplt[sig_idx][cnt]>maxWgt) maxWgt = tplt[sig_idx][cnt]; if (tplt[sig_idx][cnt]<minWgt) minWgt = tplt[sig_idx][cnt]; cnt++; } } // normalize template values (min/max) & calculate average of normalized template values tplt_avg[sig_idx] = 0; for (int iii=0; iii<tplt[sig_idx].length; iii++) { tplt[sig_idx][iii] = (tplt[sig_idx][iii] - minWgt) / (maxWgt - minWgt); tplt_avg[sig_idx] += tplt[sig_idx][iii]; } tplt_avg[sig_idx] /= (float) tplt[sig_idx].length; // calculate mean subtracted template values and their sum of squares tplt_hat_sum_2[sig_idx] = 0; for (int iii=0; iii<tplt[sig_idx].length; iii++) { tplt_hat[sig_idx][iii] = tplt[sig_idx][iii] - tplt_avg[sig_idx]; tplt_hat_sum_2[sig_idx] += Math.pow(tplt_hat[sig_idx][iii], 2); } } // create kernels that will be used for filtering (this is alternative, at first location sampling was used and templates were fixed in tplt variable) // System.out.println(N + " directions, " + sigmas.length + " scales"); kernels = new float[N*sigmas.length][limR*limR]; kernels_avg = new float[N*sigmas.length]; kernels_hat = new float[N*sigmas.length][limR*limR]; kernels_hat_sum_2 = new float[N*sigmas.length]; for (int i = 0; i < kernels.length; i++) { int direc_idx = i % N; int scale_idx = i / N; float sigx = sigmas[scale_idx]; float sigy = limT; // broader than sigmax float ang = direc_idx * (PI / N); float vx = ((float) Math.cos(ang)); // - (float) Math.sin(ang) float vy = ((float) Math.sin(ang)); // + (float) Math.cos(ang) kernels_avg[i] = 0; // average for (int j = 0; j < kernels[i].length; j++) { int xx = j % limR; int yy = j / limR; float currx = (xx - limT) * vx + (yy - limT) * vy; float curry = (xx - limT) * (-vy) + (yy - limT) * vx; kernels[i][j] = (float) Math.exp( -( ((Math.pow(currx,2)/(2*Math.pow(sigx,2))) + (Math.pow(curry,2)/(2*Math.pow(sigy,2))) ) ) ); kernels_avg[i] += kernels[i][j]; } kernels_avg[i] /= kernels[i].length; kernels_hat_sum_2[i] = 0; for (int j = 0; j < kernels[i].length; j++) { // int xx = j % limR; // int yy = j / limR; // float currx = (xx - limT) * vx + (yy - limT) * vy; // float curry = (xx - limT) * (-vy) + (yy - limT) * vx; kernels_hat[i][j] = kernels[i][j] - kernels_avg[i]; kernels_hat_sum_2[i] += Math.pow(kernels_hat[i][j], 2); } } } public ImagePlus getKernels() { ImageStack iskernels = new ImageStack(limR, limR); for (int i = 0; i <kernels.length; i++) { int direc_idx = i % N; int scale_idx = i / N; float ang = direc_idx * (PI / N); iskernels.addSlice(sigmas[scale_idx]+","+limT+","+IJ.d2s(ang,1), new FloatProcessor(limR, limR, kernels[i])); } return new ImagePlus("", iskernels); } private float point2line(float n1x, float n1y, // float n1z, float n2x, float n2y, // float n2z, float px, float py //, float pz ) { float d = 0; double[] p_b = new double[2]; //double[] n21 = new double[3]; float n21Len = (float) Math.sqrt(Math.pow(n2x-n1x,2)+Math.pow(n2y-n1y,2)); // +Math.pow(n2z-n1z,2) float n21x = (n2x-n1x)/n21Len; float n21y = (n2y-n1y)/n21Len; // float n21z = (n2z-n1z)/n21Len; float proj = (px - n1x) * n21x + (py - n1y) * n21y; // + (pz - n1z) * n21z; // dot prod p_b[0] = -(px - n1x) + proj * n21x; p_b[1] = -(py - n1y) + proj * n21y; // p_b[2] = -(pz - n1z) + proj * n21z; return (float) Math.sqrt(p_b[0]*p_b[0] + p_b[1]*p_b[1]); // + p_b[2]*p_b[2] } private void rotZ( float ang, float[][] coords ) { for (int i=0; i<coords.length; i++) { float x_temp = coords[i][0]; float y_temp = coords[i][1]; coords[i][0] = x_temp * (float) Math.cos(ang) - y_temp * (float) Math.sin(ang); coords[i][1] = x_temp * (float) Math.sin(ang) + y_temp * (float) Math.cos(ang); } } public ImagePlus getSampling() { int DIM = 2 * (int) Math.ceil(Math.sqrt(Math.pow(radius,2)+Math.pow(radius, 2))) + 1; float CX = DIM/2f; float CY = CX; ImageStack isOut = new ImageStack(DIM, DIM); Overlay ov = new Overlay(); for (int i=0; i<offstXY.size(); i++) { isOut.addSlice(new ByteProcessor(DIM, DIM)); // center OvalRoi p = new OvalRoi(CX+.5-.25, CY+.5-.25, .5, .5); p.setPosition(i + 1); p.setFillColor(Color.RED); ov.add(p); // sampling for (int i1=0; i1<offstXY.get(i).length; i1++) { float offX = offstXY.get(i)[i1][0]; float offY = offstXY.get(i)[i1][1]; PointRoi p1 = new PointRoi(CX+offX+.5, CY+offY+.5); p1.setPosition(i+1); ov.add(p1); } // arrow direction Line l = new Line(CX+.5, CY+.5, CX+.5+radius*(-Math.sin(theta.get(i))), CY+.5+radius*Math.cos(theta.get(i))); l.setFillColor(new Color(1,0,0,.5f)); l.setStrokeColor(new Color(1,0,0,.5f)); l.setStrokeWidth(0.25); l.setPosition(i+1); ov.add(l); } ImagePlus outIm = new ImagePlus("offsets", isOut); outIm.setOverlay(ov); return outIm; } public ImagePlus getTemplates() { ImageStack is_weights = new ImageStack(limR, limR); for (int sig_idx = 0; sig_idx < sigmas.length; sig_idx++) is_weights.addSlice("sigma="+ IJ.d2s(sigmas[sig_idx],2), new FloatProcessor(limR, limR, tplt[sig_idx])); return new ImagePlus("weights", is_weights); } private void transY( float ty, float[][] coords ) { for (int i=0; i<coords.length; i++){ coords[i][1] += ty; } } // do zncc calculations at one location index public void extract( int _idx, // index from the foreground list int[][] _i2xy, // foreground map using Masker2D float[][] _inimg_xy, // image in array form float[] _i2zncc, // output - list of correlations (from Profiler2D) float[] _i2sigma, // output - index of the sigma (from Profiler2D) float[][] _i2vxy, // output - vector, 2D direction (from Profiler2D) float[] vals ) { int at_x = _i2xy[_idx][0]; int at_y = _i2xy[_idx][1]; // outputs... _i2zncc[_idx] = Float.NEGATIVE_INFINITY; // because we look for the highest _i2sigma[_idx] = Float.NaN; _i2vxy[_idx][0] = Float.NaN; _i2vxy[_idx][1] = Float.NaN; float curr_zncc; // float[] vals = new float[limR*limR]; // can be allocated outside BUT independently for each thread float vals_avg = 0; for (int dir_idx = 0; dir_idx < offstXY.size(); dir_idx++) { // Arrays.fill(vals, 0); // extract values at this direction by interpolating at real 2d locations // min/max normalized values - maybe not necessary! float vals_min = Float.POSITIVE_INFINITY; float vals_max = Float.NEGATIVE_INFINITY; for (int cnt = 0; cnt < offstXY.get(dir_idx).length; cnt++) { float dx = offstXY.get(dir_idx)[cnt][0]; float dy = offstXY.get(dir_idx)[cnt][1]; vals[cnt] = Interpolator.interpolateAt(at_x+dx, at_y+dy, _inimg_xy); if (vals[cnt]<vals_min) vals_min = vals[cnt]; if (vals[cnt]>vals_max) vals_max = vals[cnt]; } vals_avg = 0; for (int cnt = 0; cnt < offstXY.get(dir_idx).length; cnt++) { vals[cnt] = (vals[cnt]-vals_min)/(vals_max-vals_min); vals_avg += vals[cnt]; } vals_avg /= offstXY.get(dir_idx).length; for (int sigma_idx = 0; sigma_idx <sigmas.length; sigma_idx++) { // calculate zncc curr_zncc = zncc(vals, vals_avg, tplt_hat[sigma_idx], tplt_hat_sum_2[sigma_idx]); if (curr_zncc>_i2zncc[_idx]) { _i2zncc[_idx] = curr_zncc; _i2sigma[_idx] = sigmas[sigma_idx]; _i2vxy[_idx][0] = (float) - Math.sin(theta.get(dir_idx)); _i2vxy[_idx][1] = (float) Math.cos(theta.get(dir_idx)); } } } } private float zncc( float[] v, float v_avg, float[] tmplt_hat, float tmplt_hat_sum_sqr ) { // TODO: place the reference here float num = 0; float den = 0; for (int i = 0; i < v.length; i++) { num += (v[i] - v_avg) * tmplt_hat[i]; den += Math.pow(v[i] - v_avg, 2); } return (float) (num / Math.sqrt(den * tmplt_hat_sum_sqr)); } // zncc calculations using oriented patches public void extract2( int _idx, // index from the foreground list int[][] _i2xy, // foreground map using Masker2D float[][] _inimg_xy, // image in array form float[] _i2zncc, // output - list of correlations (from Profiler2D) float[] _i2sigma, // output - index of the sigma (from Profiler2D) float[][] _i2vxy, // output - vector, 2D direction (from Profiler2D) float[] vals ) { int at_x = _i2xy[_idx][0]; int at_y = _i2xy[_idx][1]; // outputs... _i2zncc[_idx] = 0; // lower boundary (because we look for the highest) _i2sigma[_idx] = Float.NaN; _i2vxy[_idx][0] = Float.NaN; _i2vxy[_idx][1] = Float.NaN; float curr_zncc; float vals_avg; for (int kidx = 0; kidx < kernels.length; kidx++) { // float vals_min = Float.POSITIVE_INFINITY; // float vals_max = Float.NEGATIVE_INFINITY; for (int pidx = 0; pidx < kernels[kidx].length; pidx++) { int dx = (pidx % limR) - limT; int dy = (pidx / limR) - limT; int xx = at_x+dx; int yy = at_y+dy; vals[pidx] = 0; if (xx>=0 && xx<_inimg_xy.length && yy>=0 && yy<_inimg_xy[xx].length) { vals[pidx] = _inimg_xy[xx][yy]; } } vals_avg = 0; for (int pidx = 0; pidx < kernels[kidx].length; pidx++) { // vals[cnt] = (vals[cnt]-vals_min)/(vals_max-vals_min); vals_avg += vals[pidx]; } vals_avg /= kernels[kidx].length; // calculate zncc curr_zncc = zncc(vals, vals_avg, kernels_hat[kidx], kernels_hat_sum_2[kidx]); if (curr_zncc>_i2zncc[_idx]) { _i2zncc[_idx] = curr_zncc; int direc_idx = kidx % N; float ang = direc_idx * (PI / N); float vx = -((float) Math.sin(ang)); float vy = ((float) Math.cos(ang)); _i2vxy[_idx][0] = vx; _i2vxy[_idx][1] = vy; int scale_idx = kidx / N; _i2sigma[_idx] = sigmas[scale_idx]; } } } }
34.294589
158
0.501549
5edc85411d0c3fb5d6df6f6ecf82057c6a843218
965
package org.javaswift.joss.instructions; import org.apache.http.HttpEntity; import org.apache.http.entity.InputStreamEntity; import org.javaswift.joss.headers.object.Etag; import java.io.IOException; import java.io.InputStream; public class UploadPayloadInputStream extends UploadPayload { private InputStream inputStream; public UploadPayloadInputStream(final InputStream inputStream) { this.inputStream = inputStream; } @Override public HttpEntity getEntity() { return new InputStreamEntity(inputStream, -1); } @Override public boolean mustBeSegmented(Long segmentationSize) { return false; } @Override public Etag getEtag() throws IOException { return null; } @Override public SegmentationPlan getSegmentationPlan(Long segmentationSize) throws IOException { throw new UnsupportedOperationException("This operation is not support for InputStream"); } }
24.74359
97
0.735751
dea4413dda067084fe3db060c2b9ae1e43add511
11,441
package com.qiniu.shortvideo.app.activity; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.media.MediaPlayer; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.DisplayMetrics; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.WindowManager; import android.widget.MediaController; import com.qiniu.shortvideo.app.R; import com.qiniu.shortvideo.app.utils.ToastUtils; import java.io.IOException; public class PlaybackActivity extends Activity implements MediaController.MediaPlayerControl { private static final String TAG = "PlaybackActivity"; private static final String MP4_PATH = "MP4_PATH"; private static final String PREVIOUS_ORIENTATION = "PREVIOUS_ORIENTATION"; private SurfaceView mSurfaceView; private SurfaceHolder mSurfaceHolder; private MediaPlayer mMediaPlayer; private MediaController mMediaController; private String mVideoPath; private int mPreviousOrientation; private int mSeekingPosition = 0; public static void start(Activity activity, String mp4Path) { Intent intent = new Intent(activity, PlaybackActivity.class); intent.putExtra(MP4_PATH, mp4Path); activity.startActivity(intent); } public static void start(Activity activity, String mp4Path, int previousOrientation) { Intent intent = new Intent(activity, PlaybackActivity.class); intent.putExtra(MP4_PATH, mp4Path); intent.putExtra(PREVIOUS_ORIENTATION, previousOrientation); activity.startActivity(intent); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_playback); mVideoPath = getIntent().getStringExtra(MP4_PATH); mPreviousOrientation = getIntent().getIntExtra(PREVIOUS_ORIENTATION, 1); mMediaPlayer = new MediaPlayer(); if (mMediaPlayer != null) { mMediaPlayer.setOnInfoListener(mOnInfoListener); mMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener); mMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener); mMediaPlayer.setOnCompletionListener(mOnCompletionListener); mMediaPlayer.setOnErrorListener(mOnErrorListener); } else { Log.e(TAG, "creating MediaPlayer instance failed, exit."); return; } mSurfaceView = findViewById(R.id.video); mSurfaceView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!mMediaController.isShowing()) { mMediaController.show(0); } else { mMediaController.hide(); } } }); mSurfaceHolder = mSurfaceView.getHolder(); mSurfaceHolder.addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { mMediaPlayer.setDisplay(mSurfaceHolder); if (!"".equals(mVideoPath) && !mMediaPlayer.isPlaying()) { try { mMediaPlayer.reset(); mMediaPlayer.setLooping(true); mMediaPlayer.setDataSource(mVideoPath); mMediaPlayer.prepare(); mMediaPlayer.seekTo(mSeekingPosition); } catch (IOException e) { e.printStackTrace(); } } makeUpVideoPlayingSize(); mMediaPlayer.start(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { if (mMediaPlayer.isPlaying()) { mSeekingPosition = mMediaPlayer.getCurrentPosition(); mMediaPlayer.stop(); } } }); mMediaController = new MediaController(this); mMediaController.setMediaPlayer(this); mMediaController.setAnchorView(mSurfaceView); } private void makeUpVideoPlayingSize() { int screenWidth, screenHeight, videoWidth, videoHeight, displayWidth, displayHeight; float screenAspectRatio, videoAspectRatio; WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics = new DisplayMetrics(); windowManager.getDefaultDisplay().getMetrics(outMetrics); screenWidth = outMetrics.widthPixels; screenHeight = outMetrics.heightPixels; screenAspectRatio = (float)screenHeight / screenWidth; Log.i(TAG, "Screen size: " + screenWidth + " × " + screenHeight); videoWidth = mMediaPlayer.getVideoWidth(); videoHeight = mMediaPlayer.getVideoHeight(); videoAspectRatio = (float)videoHeight / videoWidth; Log.i(TAG, "Video size: " + screenWidth + " × " + screenHeight); if (screenAspectRatio > videoAspectRatio) { displayWidth = screenWidth; displayHeight = (int) ((float)screenWidth / videoWidth * videoHeight); } else { displayWidth = (int) ((float)screenHeight / videoHeight * videoWidth); displayHeight = screenHeight; } mSurfaceHolder.setFixedSize(displayWidth, displayHeight); } @Override public void finish() { if (0 == mPreviousOrientation) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } super.finish(); } @Override protected void onDestroy() { super.onDestroy(); mMediaPlayer.stop(); mMediaPlayer.release(); } @Override public void start() { mMediaPlayer.start(); } @Override public void pause() { mMediaPlayer.pause(); } @Override public int getDuration() { return mMediaPlayer.getDuration(); } @Override public int getCurrentPosition() { return mMediaPlayer.getCurrentPosition(); } @Override public void seekTo(int pos) { mMediaPlayer.seekTo(pos); } @Override public boolean isPlaying() { return mMediaPlayer.isPlaying(); } @Override public int getBufferPercentage() { return 0; } @Override public boolean canPause() { return true; } @Override public boolean canSeekBackward() { return true; } @Override public boolean canSeekForward() { return true; } @Override public int getAudioSessionId() { return 0; } private MediaPlayer.OnInfoListener mOnInfoListener = new MediaPlayer.OnInfoListener() { @Override public boolean onInfo(MediaPlayer mp, int what, int extra) { Log.i(TAG, "OnInfo, what = " + what + ", extra = " + extra); switch (what) { case MediaPlayer.MEDIA_INFO_UNKNOWN: break; case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING: break; case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START: Log.i(TAG, "video rendering start, ts = " + extra); break; case MediaPlayer.MEDIA_INFO_BUFFERING_START: Log.i(TAG, "onInfo: MediaPlayer.MEDIA_INFO_BUFFERING_START"); break; case MediaPlayer.MEDIA_INFO_BUFFERING_END: Log.i(TAG, "onInfo: MEDIA_INFO_BUFFERING_END"); break; case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING: Log.i(TAG, "onInfo: MEDIA_INFO_BAD_INTERLEAVING"); break; case MediaPlayer.MEDIA_INFO_NOT_SEEKABLE: Log.i(TAG, "onInfo: MEDIA_INFO_NOT_SEEKABLE"); break; case MediaPlayer.MEDIA_INFO_METADATA_UPDATE: Log.i(TAG, "onInfo: MediaPlayer.MEDIA_INFO_METADATA_UPDATE"); break; case MediaPlayer.MEDIA_INFO_UNSUPPORTED_SUBTITLE: Log.i(TAG, "onInfo: MediaPlayer.MEDIA_INFO_UNSUPPORTED_SUBTITLE"); break; case MediaPlayer.MEDIA_INFO_SUBTITLE_TIMED_OUT: Log.i(TAG, "onInfo: MediaPlayer.MEDIA_INFO_SUBTITLE_TIMED_OUT "); break; default: break; } return true; } }; private MediaPlayer.OnErrorListener mOnErrorListener = new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { Log.e(TAG, "Error happened, errorCode = " + extra); final String errorTip; switch (extra) { case MediaPlayer.MEDIA_ERROR_IO: /** * SDK will do reconnecting automatically */ Log.e(TAG, "IO Error!"); return false; case MediaPlayer.MEDIA_ERROR_MALFORMED: errorTip = "Malformed bitstream!"; break; case MediaPlayer.MEDIA_ERROR_UNSUPPORTED: errorTip = "Unsupported bitstream!"; break; case MediaPlayer.MEDIA_ERROR_TIMED_OUT: errorTip = "Timeout!"; break; default: errorTip = "unknown error !"; break; } if (errorTip != null) { runOnUiThread(new Runnable() { @Override public void run() { ToastUtils.s(PlaybackActivity.this, errorTip); } }); } finish(); return true; } }; private MediaPlayer.OnCompletionListener mOnCompletionListener = new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { Log.i(TAG, "Play Completed !"); runOnUiThread(new Runnable() { @Override public void run() { ToastUtils.s(PlaybackActivity.this, "Play Completed !"); } }); finish(); } }; private MediaPlayer.OnBufferingUpdateListener mOnBufferingUpdateListener = new MediaPlayer.OnBufferingUpdateListener() { @Override public void onBufferingUpdate(MediaPlayer mp, int percent) { Log.i(TAG, "onBufferingUpdate: " + percent); } }; private MediaPlayer.OnVideoSizeChangedListener mOnVideoSizeChangedListener = new MediaPlayer.OnVideoSizeChangedListener() { @Override public void onVideoSizeChanged(MediaPlayer mp, int width, int height) { Log.i(TAG, "onVideoSizeChanged: width = " + width + ", height = " + height); } }; }
34.987768
127
0.594004
95be6834380a0997dc6b0c0ec5d35ce773b6cacb
11,448
/* * 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.ivy.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; /** * */ public class ConfiguratorTest { public static class FileTester { private File file; public void setFile(File file) { this.file = file; } public File getFile() { return file; } } public static class City { private final List<Housing> housings = new ArrayList<>(); private final List<Street> streets = new ArrayList<>(); private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Housing> getHousings() { return housings; } public List<Street> getStreets() { return streets; } public void add(Housing h) { housings.add(h); } public void add(Street s) { streets.add(s); } } public static class Street { private Class<?> clazz; private final List<Tree> trees = new ArrayList<>(); private final List<Person> walkers = new ArrayList<>(); public List<Tree> getTrees() { return trees; } public void addConfiguredTree(Tree tree) { trees.add(tree); } public List<Person> getWalkers() { return walkers; } public void addConfiguredWalker(Map<String, String> walkerAttributes) { walkers.add(new Person(walkerAttributes.get("name"))); } public Class<?> getClazz() { return clazz; } public void setClazz(Class<?> clazz) { this.clazz = clazz; } } public abstract static class Housing { private final List<Room> rooms = new ArrayList<>(); private boolean isEmpty; private Person proprietary; public List<Room> getRooms() { return rooms; } public void addRoom(Room r) { rooms.add(r); } public boolean isEmpty() { return isEmpty; } public void setEmpty(boolean isEmpty) { this.isEmpty = isEmpty; } public Person getProprietary() { return proprietary; } public void setProprietary(Person proprietary) { this.proprietary = proprietary; } } public static class House extends Housing { } public static class Tree { private short age; public short getAge() { return age; } public void setAge(short age) { this.age = age; } } public static class Flat extends Housing { private int stage; public int getStage() { return stage; } public void setStage(int stage) { this.stage = stage; } } public static class Room { private short surface; public short getSurface() { return surface; } public void setSurface(short surface) { this.surface = surface; } } public static class Person { private final String name; public Person(String name) { this.name = name; } public String getName() { return name; } } private Configurator conf; @Before public void setUp() { conf = new Configurator(); } @Test public void testSetRoot() { City city = new City(); conf.setRoot(city); assertEquals(city, conf.getCurrent()); } @Test public void testStringAttribute() { City city = new City(); conf.setRoot(city); conf.setAttribute("name", "bordeaux"); assertEquals("bordeaux", city.getName()); } @Test public void testIntAttribute() { Flat flat = new Flat(); conf.setRoot(flat); conf.setAttribute("stage", "4"); assertEquals(4, flat.getStage()); } @Test public void testBooleanAttribute() { Housing housing = new House(); conf.setRoot(housing); conf.setAttribute("empty", "true"); assertTrue(housing.isEmpty()); conf.setAttribute("empty", "false"); assertFalse(housing.isEmpty()); conf.setAttribute("empty", "yes"); assertTrue(housing.isEmpty()); conf.setAttribute("empty", "no"); assertFalse(housing.isEmpty()); conf.setAttribute("empty", "on"); assertTrue(housing.isEmpty()); conf.setAttribute("empty", "off"); assertFalse(housing.isEmpty()); } @Test public void testClassAttribute() { Street street = new Street(); conf.setRoot(street); conf.setAttribute("clazz", getClass().getName()); assertEquals(getClass(), street.getClazz()); } @Test public void testPersonAttribute() { Housing housing = new House(); conf.setRoot(housing); conf.setAttribute("proprietary", "jean"); assertEquals("jean", housing.getProprietary().getName()); } @Test public void testAddRoom() { Housing housing = new House(); conf.setRoot(housing); conf.startCreateChild("room"); assertEquals(1, housing.getRooms().size()); conf.setAttribute("surface", "24"); assertEquals(24, housing.getRooms().get(0).getSurface()); conf.endCreateChild(); assertEquals(housing, conf.getCurrent()); } @Test public void testAddConfiguredTree() { Street street = new Street(); conf.setRoot(street); conf.startCreateChild("tree"); assertTrue(street.getTrees().isEmpty()); conf.setAttribute("age", "400"); conf.endCreateChild(); assertEquals(1, street.getTrees().size()); assertEquals(400, street.getTrees().get(0).getAge()); assertEquals(street, conf.getCurrent()); } @Test public void testAddConfiguredWalker() { Street street = new Street(); conf.setRoot(street); conf.startCreateChild("walker"); assertTrue(street.getWalkers().isEmpty()); conf.setAttribute("name", "xavier"); conf.endCreateChild(); assertEquals(1, street.getWalkers().size()); assertEquals("xavier", street.getWalkers().get(0).getName()); assertEquals(street, conf.getCurrent()); } @Test public void testAddWithTypeDef() throws Exception { City city = new City(); conf.typeDef("house", House.class.getName()); conf.typeDef("flat", Flat.class.getName()); conf.typeDef("street", Street.class.getName()); conf.setRoot(city); conf.startCreateChild("house"); assertEquals(1, city.getHousings().size()); assertTrue(city.getHousings().get(0) instanceof House); conf.endCreateChild(); conf.startCreateChild("flat"); assertEquals(2, city.getHousings().size()); assertTrue(city.getHousings().get(1) instanceof Flat); conf.endCreateChild(); conf.startCreateChild("street"); assertEquals(1, city.getStreets().size()); conf.endCreateChild(); assertEquals(city, conf.getCurrent()); } @Test public void testNested() throws Exception { City city = new City(); conf.typeDef("house", House.class.getName()); conf.setRoot(city); conf.startCreateChild("house"); conf.startCreateChild("room"); conf.setAttribute("surface", "20"); conf.endCreateChild(); conf.startCreateChild("room"); conf.setAttribute("surface", "25"); conf.endCreateChild(); conf.endCreateChild(); assertEquals(city, conf.getCurrent()); assertEquals(2, city.getHousings().get(0).getRooms().size()); assertEquals(20, city.getHousings().get(0).getRooms().get(0).getSurface()); assertEquals(25, city.getHousings().get(0).getRooms().get(1).getSurface()); } @Test public void testMacro() throws Exception { City city = new City(); conf.typeDef("house", House.class.getName()); conf.startMacroDef("castle"); conf.addMacroAttribute("surface", "40"); conf.addMacroElement("addroom", true); conf.startCreateChild("house"); conf.startCreateChild("room"); conf.setAttribute("surface", "@{surface}"); conf.endCreateChild(); conf.startCreateChild("room"); conf.setAttribute("surface", "@{surface}"); conf.endCreateChild(); conf.startCreateChild("addroom"); conf.endCreateChild(); conf.endCreateChild(); conf.endMacroDef(); conf.setRoot(city); conf.startCreateChild("castle"); conf.setAttribute("surface", "10"); conf.endCreateChild(); conf.startCreateChild("castle"); conf.startCreateChild("addroom"); conf.startCreateChild("room"); conf.setAttribute("surface", "20"); conf.endCreateChild(); conf.endCreateChild(); conf.endCreateChild(); assertEquals(city, conf.getCurrent()); assertEquals(2, city.getHousings().size()); // first castle : 2 default rooms of 10 of surface assertEquals(2, city.getHousings().get(0).getRooms().size()); assertEquals(10, city.getHousings().get(0).getRooms().get(0).getSurface()); assertEquals(10, city.getHousings().get(0).getRooms().get(1).getSurface()); // second castle : 2 default rooms of default surface 40, + one addroom of surface 20 assertEquals(3, city.getHousings().get(1).getRooms().size()); assertEquals(40, city.getHousings().get(1).getRooms().get(0).getSurface()); assertEquals(40, city.getHousings().get(1).getRooms().get(1).getSurface()); assertEquals(20, city.getHousings().get(1).getRooms().get(2).getSurface()); } @Test public void testFileAttribute() { FileTester root = new FileTester(); conf.setRoot(root); conf.setAttribute("file", "path/to/file.txt"); String filePath = root.getFile().getPath(); filePath = filePath.replace('\\', '/'); assertEquals("path/to/file.txt", filePath); } }
28.763819
93
0.59137
8d0870d80595ff3d887e0222f877ebd15d78d48d
1,156
package com.example.bank.utils; import javax.validation.constraints.NotBlank; import java.util.Objects; public class AccountInput { @NotBlank(message = "Account number is mandatory") private String accountNumber; @NotBlank(message = "Account name is mandatory") private String accountName; @NotBlank(message = "Amount is mandatory") private double amount; public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public AccountInput() {} public String getAccountNumber() { return accountNumber; } public void setAccountNumber(String accountNumber) { this.accountNumber = accountNumber; } @Override public String toString() { return "AccountInput{" + "accountName='" + accountName + '\'' + ",amount='" + amount + '\'' + ",accountNumber='" + accountNumber + '\'' + '}'; } }
17.784615
59
0.625433
ba08c05e886e599bf4bc19ad7d38b5bc37618b16
1,190
package io.github.apace100.originsclasses.registry; import io.github.apace100.origins.Origins; import net.minecraft.util.Identifier; import virtuoel.pehkui.api.ScaleModifier; import virtuoel.pehkui.api.ScaleRegistries; import virtuoel.pehkui.api.ScaleType; import virtuoel.pehkui.api.TypedScaleModifier; import java.util.Map; public class ModScaleTypes { private static final ScaleType[] MODIFY_SIZE_TYPES = {ScaleType.WIDTH, ScaleType.HEIGHT, ScaleType.DROPS}; public static final ScaleModifier MODIFY_SIZE_MODIFIER = register(ScaleRegistries.SCALE_MODIFIERS, new TypedScaleModifier(() -> ModScaleTypes.MODIFY_SIZE_TYPE)); public static final ScaleType MODIFY_SIZE_TYPE = register(ScaleRegistries.SCALE_TYPES, ScaleType.Builder.create().addDependentModifier(MODIFY_SIZE_MODIFIER).affectsDimensions().build()); private static <T> T register(Map<Identifier, T> registry, T entry) { return ScaleRegistries.register(registry, new Identifier(Origins.MODID, "modify_size"), entry); } public static void init() { for (ScaleType type : MODIFY_SIZE_TYPES) { type.getDefaultBaseValueModifiers().add(MODIFY_SIZE_MODIFIER); } } }
41.034483
190
0.77563
0efb0723122e9bb41aef6bebb690071bfff82809
10,305
package com.googlecode.gtalksms.cmd.smsCmd; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.text.TextUtils; import com.googlecode.gtalksms.Log; import com.googlecode.gtalksms.R; import com.googlecode.gtalksms.SettingsManager; import com.googlecode.gtalksms.data.contacts.ContactsManager; import com.googlecode.gtalksms.data.phone.Phone; import com.googlecode.gtalksms.tools.StringFmt; import com.googlecode.gtalksms.tools.Tools; public class SmsMmsManager { private Context _context; private SettingsManager _settings; private static final String INBOX = "content://sms/inbox"; private static final String SENTBOX = "content://sms/sent"; private static final String COLUMNS[] = new String[] { "person", "address", "body", "date", "status" }; private static final String SORT_ORDER = "date DESC"; public SmsMmsManager(SettingsManager settings, Context baseContext) { _settings = settings; _context = baseContext; Log.initialize(_settings); } /** * Returns a ArrayList of <Sms> with count sms where the contactId match the * argument */ public ArrayList<Sms> getSms(ArrayList<Long> rawIds, String contactName) { if (rawIds.size() > 0) { return getAllSms(false, contactName, "person IN (" + TextUtils.join(", ", rawIds) + ") or person is null", false); } return new ArrayList<Sms>(); } public ArrayList<Sms> getSms(ArrayList<Long> rawIds, String contactName, String message) { if (rawIds.size() > 0) { return getAllSms(false, contactName, "(person IN (" + TextUtils.join(", ", rawIds) + ") or person is null) and body LIKE '%" + StringFmt.encodeSQL(message) + "%'", false); } return new ArrayList<Sms>(); } /** * Returns a ArrayList of <Sms> with count sms where the contactId match the * argument */ public ArrayList<Sms> getAllSentSms() { return getAllSms(true, null, null, true); } public ArrayList<Sms> getAllSentSms(String message) { return getAllSms(true, null, "body LIKE '%" + StringFmt.encodeSQL(message) + "%'", true); } public ArrayList<Sms> getAllReceivedSms() { return getAllSms(false, null, null, false); } public ArrayList<Sms> getAllUnreadSms() { return getAllSms(false, null, "read = 0", false); } /** * Returns an ArrayList with all SMS that match the given criteria. * * @param outgoingSms * @param sender * @param where * @param getMax * @return */ private ArrayList<Sms> getAllSms(boolean outgoingSms, String sender, String where, boolean getMax) { ArrayList<Sms> res = new ArrayList<Sms>(); String folder; // Select the data resource based on the boolean flag if (outgoingSms) { folder = SENTBOX; } else { folder = INBOX; } Uri mSmsQueryUri = Uri.parse(folder); Cursor c = _context.getContentResolver().query(mSmsQueryUri, COLUMNS, where, null, SORT_ORDER); final int maxSms = _settings.smsNumber; int smsCount = 0; if (c != null) { for (boolean hasData = c.moveToFirst(); hasData && (getMax || smsCount < maxSms); hasData = c.moveToNext(), ++smsCount) { Long rawId = Tools.getLong(c, "person"); String address = Tools.getString(c, "address"); String addressName = ContactsManager.getContactName(_context, address); // Sometime, if it's only an external contact to gmail (exchange by instance) // the rawId is not set and with have to check the address (phone number) if (!outgoingSms && rawId == 0 && sender != null && addressName.compareTo(sender) != 0) { smsCount--; continue; } String receiver = outgoingSms ? addressName : _context.getString(R.string.chat_me); String body = Tools.getString(c, "body"); Sms sms = new Sms(address, body, Tools.getDateMilliSeconds(c, "date"), receiver); String currentSender = sender; if (currentSender == null) { currentSender = outgoingSms ? _context.getString(R.string.chat_me) : addressName; } // Setting sender to null here is OK, because it just means // that the name of the sender could not be determined // and therefore the number will be used sms.setSender(currentSender); res.add(sms); } c.close(); } return res; } /** * Returns a ArrayList of <Sms> with count sms where the contactId match the * argument */ public ArrayList<Sms> getSentSms(ArrayList<Phone> phones, ArrayList<Sms> sms) { ArrayList<Sms> res = new ArrayList<Sms>(); for (Sms aSms : sms) { Boolean phoneMatch = false; for (Phone phone : phones) { if (phone.phoneMatch(aSms.getNumber())) { phoneMatch = true; break; } } if (phoneMatch) { res.add(aSms); } } return res; } /** * Marks all SMS from a given phone number as read * * @param smsNumber The phone number * @return true if successfully, otherwise false */ public boolean markAsRead(String smsNumber) { try { ContentResolver cr = _context.getContentResolver(); Uri smsUri = Uri.parse("content://sms/inbox"); ContentValues values = new ContentValues(); values.put("read", "1"); cr.update(smsUri, values, " address='" + smsNumber + "'", null); return true; } catch (Exception e) { Log.w("markAsRead() exception:", e); return false; } } /** Adds the text of the message to the sent box */ public void addSmsToSentBox(String message, String phoneNumber) { ContentValues values = new ContentValues(); values.put("address", phoneNumber); values.put("date", System.currentTimeMillis()); values.put("body", message); _context.getContentResolver().insert(Uri.parse("content://sms/sent"), values); } public int deleteAllSms() { return deleteSms("content://sms", null); } public int deleteSentSms() { return deleteSms("content://sms/sent", null); } public int deleteSmsByContact(ArrayList<Long> rawIds) { int result = -1; if (rawIds.size() > 0) { return deleteThreads("content://sms/inbox", "person IN (" + TextUtils.join(", ", rawIds) + ")"); } return result; } public int deleteSmsByNumber(String smsNumber) { return deleteThreads("content://sms/inbox", "address = '" + smsNumber + "'"); } private int deleteThreads(String url, String where) { int result = 0; ContentResolver cr = _context.getContentResolver(); Uri deleteUri = Uri.parse(url); Cursor c = cr.query(deleteUri, new String[] { "thread_id" }, where, null, null); try { Set<String> threads = new HashSet<String>(); while (c.moveToNext()) { threads.add(c.getString(0)); } for (String thread : threads) { // Delete the SMS String uri = "content://sms/conversations/" + thread; result += cr.delete(Uri.parse(uri), null, null); } } catch (Exception e) { Log.e("exception in deleteSms:", e); if (result == 0) { result = -1; } } return result; } private int deleteSms(String url, String where) { int result = 0; ContentResolver cr = _context.getContentResolver(); Uri deleteUri = Uri.parse(url); Cursor c = cr.query(deleteUri, new String[] { "_id" }, where, null, null); try { while (c.moveToNext()) { // Delete the SMS String uri = "content://sms/" + c.getString(0); result += cr.delete(Uri.parse(uri), null, null); } } catch (Exception e) { Log.e("exception in deleteSms:", e); if (result == 0) { result = -1; } } return result; } public int deleteLastSms(int number) { return deleteLastSms("content://sms", number); } public int deleteLastInSms(int number) { return deleteLastSms("content://sms/inbox", number); } public int deleteLastOutSms(int number) { return deleteLastSms("content://sms/sent", number); } public int deleteLastSms(String url, int number) { int result = 0; ContentResolver cr = _context.getContentResolver(); Uri deleteUri = Uri.parse(url); Cursor c = cr.query(deleteUri, new String[] { "_id" }, null, null, "date desc"); try { for (int i = 0 ; i < number && c.moveToNext() ; ++i) { // Delete the SMS String uri = "content://sms/" + c.getString(0); result += cr.delete(Uri.parse(uri), null, null); } } catch (Exception e) { Log.e("exception in deleteSms:", e); if (result == 0) { result = -1; } } return result; } }
34.69697
155
0.544978
d81d3557d1c58bc19954f2f15f5fec2972266f33
7,095
/* * Tencent is pleased to support the open source community by making BK-JOB蓝鲸智云作业平台 available. * * Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. * * BK-JOB蓝鲸智云作业平台 is licensed under the MIT License. * * License for BK-JOB蓝鲸智云作业平台: * -------------------------------------------------------------------- * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and * to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of * the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package com.tencent.bk.job.backup.service.impl; import com.tencent.bk.job.backup.client.ServiceAccountResourceClient; import com.tencent.bk.job.backup.client.WebAccountResourceClient; import com.tencent.bk.job.backup.service.AccountService; import com.tencent.bk.job.common.exception.ServiceException; import com.tencent.bk.job.common.model.ServiceResponse; import com.tencent.bk.job.manage.model.inner.ServiceAccountDTO; import com.tencent.bk.job.manage.model.web.request.AccountCreateUpdateReq; import com.tencent.bk.job.manage.model.web.vo.AccountVO; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Collections; import java.util.List; /** * @since 24/11/2020 21:08 */ @Slf4j @Service public class AccountServiceImpl implements AccountService { private final ServiceAccountResourceClient serviceAccountResourceClient; private final WebAccountResourceClient webAccountResourceClient; @Autowired public AccountServiceImpl(ServiceAccountResourceClient serviceAccountResourceClient, WebAccountResourceClient webAccountResourceClient) { this.serviceAccountResourceClient = serviceAccountResourceClient; this.webAccountResourceClient = webAccountResourceClient; } @Override public ServiceAccountDTO getAccountAliasById(Long id) { ServiceResponse<ServiceAccountDTO> accountResp = serviceAccountResourceClient.getAccountByAccountId(id); if (accountResp != null) { if (0 == accountResp.getCode()) { ServiceAccountDTO account = accountResp.getData(); if (account != null) { if (StringUtils.isNotBlank(account.getAlias())) { return account; } else { log.error("Account alias of {} is empty!|{}", id, accountResp); } } else { log.error("Account response of {} is empty!|{}", id, accountResp); } } else { log.error("Get account failed!|{}|{}|{}|{}", id, accountResp.getCode(), accountResp.getErrorMsg(), accountResp); } } else { log.error("Get account failed! Empty response!|{}", id); } throw new ServiceException(-1, "Error while getting account info!"); } @Override public List<AccountVO> listAccountByAppId(String username, Long appId) { ServiceResponse<List<AccountVO>> appAccountListResp = webAccountResourceClient.listAccounts(username, appId, null); if (appAccountListResp != null) { if (0 == appAccountListResp.getCode()) { List<AccountVO> accountList = appAccountListResp.getData(); if (CollectionUtils.isNotEmpty(accountList)) { return accountList; } else { log.error("List app account response of {} is empty!|{}", appId, appAccountListResp); } } else { log.error("List app account failed!|{}|{}|{}|{}", appId, appAccountListResp.getCode(), appAccountListResp.getErrorMsg(), appAccountListResp); } } else { log.error("List app account failed! Empty response!|{}", appId); } return Collections.emptyList(); } @Override public Long saveAccount(String username, Long appId, ServiceAccountDTO account) { AccountCreateUpdateReq accountCreateUpdateReq = new AccountCreateUpdateReq(); accountCreateUpdateReq.setAppId(appId); accountCreateUpdateReq.setAccount(account.getAccount()); accountCreateUpdateReq.setAlias(account.getAlias()); accountCreateUpdateReq.setType(account.getType()); accountCreateUpdateReq.setCategory(account.getCategory()); accountCreateUpdateReq.setRemark(account.getRemark()); accountCreateUpdateReq.setOs(account.getOs()); accountCreateUpdateReq.setPassword(account.getPassword()); accountCreateUpdateReq.setDbPassword(account.getDbPassword()); if (account.getDbSystemAccount() != null) { accountCreateUpdateReq.setDbSystemAccountId(account.getDbSystemAccount().getId()); } accountCreateUpdateReq.setDbPassword(account.getDbPassword()); accountCreateUpdateReq.setDbPort(account.getDbPort()); ServiceResponse<Long> saveAccountResp = webAccountResourceClient.saveAccount(username, appId, accountCreateUpdateReq); Integer errorCode = -1; if (saveAccountResp != null) { if (0 == saveAccountResp.getCode()) { Long accountId = saveAccountResp.getData(); if (accountId != null && accountId > 0) { return accountId; } else { log.error("Save account response of {} is empty!|{}", account.getAlias(), saveAccountResp); } } else { log.error("Save account failed!|{}|{}|{}|{}|{}", username, account.getAlias(), saveAccountResp.getCode(), saveAccountResp.getErrorMsg(), saveAccountResp); errorCode = saveAccountResp.getCode(); } } else { log.error("Save account failed! Empty response!|{}|{}", username, account.getAlias()); } throw new ServiceException(errorCode, "Error while save or get account info!"); } }
47.939189
116
0.662156
d39e947bf2e860b9a08b1df5a37049fcd338544d
809
package me.pexcn.mall.controller; import me.pexcn.mall.entity.EasyUITreeNode; import me.pexcn.mall.interfaces.ItemCategoryService; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.List; /** * Created by pexcn on 2018-07-27. */ @RestController public class ItemCategoryController { @Resource private ItemCategoryService itemCategoryService; @RequestMapping("/item/cat/list") public List<EasyUITreeNode> getItemCategoryList( @RequestParam(name = "id", defaultValue = "0") Long parentId) { return itemCategoryService.getItemCategoryList(parentId); } }
31.115385
76
0.751545
777ce59c94f381c7f108e8a540ba5c9d6f6c145c
564
package org.danyuan.identify.base.info; import org.danyuan.identify.base.info.controller.Centroller; /** * * 文件名 : App.java * 包 名 : org.danyuan.identify.base.info * 描 述 : 程序的入口 * 机能名称: * 技能ID : * 作 者 : wang * 时 间 : 2017年3月9日 下午1:48:20 * 版 本 : V1.0 */ public class App { /** * * 方法名: main * 功 能: 程序入口 * 参 数: @param args * 参 数: @throws Exception * 返 回: void * 作 者 : Administrator * @throws */ public static void main(String[] args) throws Exception { // 启动控制 Centroller.run(); } }
17.090909
60
0.551418
0cb670b4e7735f0ffbe1fe8cbd3d6a6e5e1f839f
1,265
package com.example.anitac.flicks.models; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * Created by anitac on 6/28/18. */ public class Config { String imageBaseUrl; //showing images String posterSize; //fetch poster size String backdropSize; //fetch backdrop size public Config(JSONObject object) throws JSONException { JSONObject images = object.getJSONObject("images"); //get image base url imageBaseUrl = images.getString("secure_base_url"); //get poster size JSONArray posterSizeOptions = images.getJSONArray("poster_sizes"); posterSize = posterSizeOptions.optString(3, "w342"); //get backdrop size JSONArray BackdropSizeOptions = images.getJSONArray("backdrop_sizes"); backdropSize = posterSizeOptions.optString(3, "w780"); } public String getBackdropSize() { return backdropSize; } //helper method to construct url public String getImageURL(String size, String path){ return String.format("%s%s%s",imageBaseUrl, size, path); } public String getImageBaseUrl() { return imageBaseUrl; } public String getPosterSize() { return posterSize; } }
25.3
78
0.67668
f95d146280c5067f1278786ae4f699ec03fbbd12
554
package io.coded.seabird_minecraft_backend.event; import net.fabricmc.fabric.api.event.Event; import net.fabricmc.fabric.api.event.EventFactory; import java.util.UUID; public interface EmoteCallback { Event<EmoteCallback> EVENT = EventFactory.createArrayBacked(EmoteCallback.class, (listeners) -> (uuid, sender, action) -> { for (EmoteCallback event : listeners) { event.emote(uuid, sender, action); } } ); void emote(UUID uuid, String sender, String action); }
29.157895
84
0.651625
192bcc7946dee14bda098d57714c369b978b7932
1,155
/******************************************************************************* * Copyright (c) 2019 Eclipse RDF4J contributors. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.console.setting; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.Before; import org.junit.Test; /** * Test query prefix setting * * @author Bart Hanssens */ public class QueryPrefixTest extends AbstractSettingTest { @Before @Override public void setUp() { settings.put(QueryPrefix.NAME, new QueryPrefix()); super.setUp(); } @Test public void testQueryPrefix() { setParameters.execute("set", "queryPrefix=false"); setParameters.execute("set", "queryPrefix"); verify(mockConsoleIO).writeln("queryPrefix: false"); verifyNoMoreInteractions(mockConsoleIO); } }
29.615385
81
0.654545
945e5f24f0f1fe9d0d909626660c628e3e5ef26a
5,382
package com.zhaozhijie.jcartadministrationback.util; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; @Service public class MailService { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private JavaMailSender javaMailSender; @Value("${spring.mail.username}") private String from; private static String projectPath = StringUtils .substringBefore(System.getProperty("user.dir").replaceAll("\\\\", "/"), "/"); static { System.setProperty("mail.mime.splitlongparameters", "false"); } /** * 发送简易邮件 */ @Async public void sendSimpleMail(MailBean mailBean) throws Exception { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from);//发送方 message.setTo(mailBean.getReceiver().split(";"));//接收者 message.setSubject(mailBean.getSubject());//主题 message.setText(mailBean.getContent());//内容 javaMailSender.send(message); logger.info("简单邮件已经发送。"); } /** * 发送带多附件的邮件 * * @param mailBean * @throws Exception */ @Async public void sendMultiAttachmentsMail(MailBean mailBean) throws Exception { MimeMessage message = javaMailSender.createMimeMessage(); // true表示需要创建一个multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(mailBean.getReceiver().split(";")); helper.setSubject(mailBean.getSubject()); helper.setText(mailBean.getContent()); String[] files = mailBean.getAttachment().split("\\|"); for (String fileName : files) { // String path = projectPath + "/temp/" + fileName; String path="d:/img/"+fileName; FileSystemResource file = new FileSystemResource(path); if (file.exists() && file.isFile()) { helper.addAttachment(fileName, file); } } javaMailSender.send(message); logger.info("带附件的邮件已经发送。"); } /** * 发送邮件-邮件正文是HTML * * @param mailBean * @throws Exception */ @Async public void sendMailHtml(MailBean mailBean) throws Exception { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage); helper.setFrom(from); helper.setTo(mailBean.getReceiver().split(";")); helper.setSubject(mailBean.getSubject()); helper.setText(mailBean.getContent(), true); javaMailSender.send(mimeMessage); } /** * 内联资源(静态资源)邮件发送 由于邮件服务商不同,可能有些邮件并不支持内联资源的展示 在测试过程中,新浪邮件不支持,QQ邮件支持 * 不支持不意味着邮件发送不成功,而且内联资源在邮箱内无法正确加载 * * @param mailBean * @throws Exception */ @Async public void sendMailInline(MailBean mailBean) throws MessagingException { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage); helper.setFrom(from); helper.setTo(mailBean.getReceiver().split(";")); helper.setSubject(mailBean.getSubject()); // helper.setText(mailBean.getContent(),true); // helper.addInline(); helper.setText("my text <img src='cid:myLogo'>", true); helper.addInline("myLogo", new ClassPathResource("img/mylogo.gif")); javaMailSender.send(mimeMessage); // mailSender.send(new MimeMessagePreparator() { // public void prepare(MimeMessage mimeMessage) throws MessagingException { // MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // message.setFrom("[email protected]"); // message.setTo("[email protected]"); // message.setSubject("my subject"); // message.setText("my text <img src='cid:myLogo'>", true); // message.addInline("myLogo", new ClassPathResource("img/mylogo.gif")); // message.addAttachment("myDocument.pdf", new ClassPathResource("doc/myDocument.pdf")); // } // }); } /** * 模板邮件发送 * * @param mailBean * @throws Exception */ @Async public void sendMailTemplate(MailBean mailBean) throws MessagingException { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setFrom(from); helper.setTo(mailBean.getReceiver().split(";")); helper.setSubject(mailBean.getSubject()); helper.setText(mailBean.getContent(), true); javaMailSender.send(mimeMessage); } }
31.846154
103
0.658863
6b4f964ab413818ec5064773cd6db80274eeeb8b
5,995
package br.com.sutel.mymaps; import androidx.fragment.app.FragmentActivity; import android.Manifest; import android.graphics.Color; import android.location.LocationManager; import android.os.Bundle; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolygonOptions; import com.google.android.gms.maps.model.PolylineOptions; import java.security.PrivateKey; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); //Requisicao assincriona - o que permite fazer outras cargas de dados em paralelo ao carregamento do mapa mapFragment.getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override //método chamado após o mapa ser carregado public void onMapReady(GoogleMap googleMap) { // Adicionando evento de clique no mapa //OnCLickListener mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { //capturamos lat e lon para criar o toast Double lat = latLng.latitude; Double lon = latLng.longitude; //criamos o Toast Toast.makeText(MapsActivity.this, "EPTC adicionadalo0 Lat:" + lat + " Long:" + lon, Toast.LENGTH_SHORT).show(); mMap.addMarker(new MarkerOptions() .position(latLng) .title("Local Clicado") .snippet("EPTC") .icon(BitmapDescriptorFactory.fromResource(R.drawable.eptc)) ); //Iniciamos a classe polyline PolylineOptions poli = new PolylineOptions(); LatLng poa = new LatLng(-30.0277, -51.2287); poli.add(poa); poli.add(latLng); poli.color(Color.RED); poli.width(20); mMap.addPolyline(poli); LatLng temp = latLng; } }); //OnLongCLickListener mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() { @Override public void onMapLongClick(LatLng latLng) { //capturamos lat e lon para criar o toast Double lat = latLng.latitude; Double lon = latLng.longitude; //criamos o Toast Toast.makeText(MapsActivity.this, "ObservaMOB Adicionado Lat:" + lat + " Long:" + lon, Toast.LENGTH_SHORT).show(); mMap.addMarker(new MarkerOptions() .position(latLng) .title("Local Clicado") .snippet("ObservaMOB") .icon(BitmapDescriptorFactory.fromResource(R.drawable.om)) ); } }); // Add a marker in poa and move the camera LatLng poa = new LatLng(-30.0277, -51.2287); mMap.addMarker(new MarkerOptions() .position(poa) .title("PMPA") //.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)) .icon(BitmapDescriptorFactory.fromResource(R.drawable.pmpa)) ); // Add a marker in poa2 and move the camera LatLng poa2 = new LatLng(-30.034054,-51.2218582); mMap.addMarker(new MarkerOptions() .position(poa2) .title("Porto Alegre") .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)) ); //Circle Options CircleOptions circulo = new CircleOptions(); LatLng eptc = new LatLng(-30.0473819,-51.2197398); circulo.center(eptc); circulo.radius(500);//500 metros circulo.strokeWidth(10); circulo.strokeColor(Color.GRAY); circulo.fillColor(Color.argb(80, 255, 153, 0)); mMap.addCircle(circulo); //PolygonOptions PolygonOptions poligono = new PolygonOptions(); poligono.add(new LatLng(-30.04715457581213, -51.217392598241304)); poligono.add(new LatLng(-30.046950261018317, -51.21569744214389)); poligono.add(new LatLng(-30.047498195196766, -51.215643797963594)); poligono.add(new LatLng(-30.047702508860354, -51.21721020802829)); mMap.addPolygon(poligono); //mMap.moveCamera(CameraUpdateFactory.newLatLng(poa)); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(poa, 14)); } }
38.677419
113
0.626022
d34bc799a596f293e8b950858bcc7375dc7ceecd
4,240
package algorithm.medium; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; /** * 最长回文子串 * 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。 * <p> * 输入: "babad" * 输出: "bab" * 注意: "aba" 也是一个有效答案。 * <p> * <p> * 输入: "cbbd" * 输出: "bb" * * @author [email protected] 2020-04-08 */ public class LongestPalindrome { public String longestPalindrome(String s) { int start = 0; int end = 0; int len = 0; for (int i = 0; i < s.length(); i++) { //处理xaba //a //aaa int len1 = centerLen(s, i, i); if (len1 > len) { start = i - len1 / 2; end = i + (len1 + 1) / 2; len = len1; } // 处理xabba //aa //aaaa int len2 = centerLen(s, i, i + 1); if (len2 > end - start) { start = i - (len2 - 1) / 2; end = i + len2 / 2 + 1; len = len2; } } return s.substring(start, end); } public int centerLen(String s, int left, int right) { int k = 1; if (left == right) { right++; left--; while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { right++; left--; k += 2; } } else { k = 0; while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { right++; left--; k += 2; } } return k; } public String longestPalindrome1(String s) { Set<Character> set = new HashSet<>(); StringBuilder sb = new StringBuilder(); int max = 0; for (int i = 0; i < s.length(); i++) { if (set.contains(s.charAt(i))) { continue; } set.add(s.charAt(i)); ArrayList<Integer> index = new ArrayList<>(); for (int j = i; j < s.length(); j++) { if (s.charAt(j) == s.charAt(i)) { index.add(j); } else { continue; } } if (index.isEmpty()) { continue; } for (int j = index.get(0); j <= index.get(index.size() - 1); j++) { int h = j; int m = index.size() - 1; int k; if ((index.get(m) - h + 1) > max) { while (m >= 0 && index.get(m) >= j && (index.get(m) - j + 1) > max) { for (k = index.get(m); k >= h; k--) { if (s.charAt(h) != s.charAt(k)) { break; } h++; } if (h - 1 == (j + index.get(m)) / 2) { max = index.get(m) - j + 1; sb.setLength(0); for (int n = j; n <= index.get(m); n++) { sb.append(s.charAt(n)); } } m--; h = j; } } } } return sb.toString(); } public static void main(String[] args) { LongestPalindrome lp = new LongestPalindrome(); String a = "babad"; String b = "cbbd"; String c = "abc"; String d = "abcba"; String e = "babadada"; String f = "beabcccb"; String h = "aaaa"; System.out.println(new LongestPalindrome().longestPalindrome(a)); System.out.println(new LongestPalindrome().longestPalindrome(b)); System.out.println(new LongestPalindrome().longestPalindrome(d)); System.out.println(new LongestPalindrome().longestPalindrome(e)); System.out.println(new LongestPalindrome().longestPalindrome(f)); System.out.println(new LongestPalindrome().longestPalindrome(h)); System.out.println(new LongestPalindrome().longestPalindrome(c)); } }
30.285714
90
0.399528
6f6080d2ec428579881f02c4095bd59c2635cd40
16,713
package edu.drake.research.web.lipswithmaps.backend; import com.google.appengine.repackaged.com.google.gson.Gson; import com.google.appengine.repackaged.com.google.gson.GsonBuilder; import com.google.appengine.repackaged.com.google.gson.JsonObject; import com.google.common.reflect.TypeToken; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import com.google.firebase.auth.FirebaseCredentials; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import edu.drake.research.lipswithmaps.Accelerometer; import edu.drake.research.lipswithmaps.LocationLngLat; import edu.drake.research.lipswithmaps.Magnetometer; import edu.drake.research.lipswithmaps.PhoneInfo; import edu.drake.research.lipswithmaps.Reading; import edu.drake.research.lipswithmaps.RotationMeter; import edu.drake.research.lipswithmaps.WifiItem; import edu.drake.research.web.lipswithmaps.backend.constants.ServerConfig; /** * Created by Mahesh Gaya on 3/25/17. */ public class AllReadingServlet extends HttpServlet { private static Logger Log = Logger.getLogger("AllReadingServlet"); public static final String CSV_TYPE = "csv"; public static final String JSON_TYPE = "json"; public static final String FORMAT = "format"; /** * According to format requested output JSON or CSV * Default is JSON * @param req * @param resp * @throws ServletException * @throws IOException */ @Override protected void doGet(HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { String parameter = JSON_TYPE; if (req.getParameterMap().containsKey(FORMAT)) { //get the output format (CSV or JSON) parameter = req.getParameter(FORMAT); } //region Firebase Initialization //Service account is found in the main/resources folder InputStream serviceAccount = this.getClass().getResourceAsStream("/service-account.json"); FirebaseOptions options = new FirebaseOptions.Builder() .setCredential(FirebaseCredentials.fromCertificate(serviceAccount)) .setDatabaseUrl(ServerConfig.FIREBASE_DB_URL) .build(); try { FirebaseApp.initializeApp(options); } catch(Exception error){ Log.info("InitializeApp does not exists"); error.printStackTrace(); } //endregion //region Firebase Query //Firebase queries from a background thread, // thus we need to await for the background thread to complete final CountDownLatch countDownLatch = new CountDownLatch(1); // Read only access service account final DatabaseReference ref = FirebaseDatabase .getInstance() .getReference(Reading.TABLE_NAME); final String formatParameter = parameter; ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { //Output was always getting null value when referencing the data directly //So decided to do it one by one with hardcoded key strings //TODO: change the key string if the names of the variables are updated for the data int childrenCount = (int) dataSnapshot.getChildrenCount(); //return error if there is no content if (childrenCount == 0) { try { String message = "{ \"error\": \"No data in the database\"}"; resp.getWriter().println(message); Log.info(message); } catch (IOException e) { e.printStackTrace(); } } //keep a chronologically ordered Hash Map for the unique wifi bssid //will be used for CSV Output, however, keep the structure for JSON Map<String, String> uniqueWifisMap = new LinkedHashMap<>(); //create a list of the readings from the Firebase Query List<Reading> readingList = new ArrayList<>(); //To be used for the uniqueWifiMaps count, the format is "BSSID<count>", i.e. BSSID243 int wifiCount = 1; Log.info("Count: " + dataSnapshot.getChildrenCount()); //debug //Loop through the datasnapshot list and get all the data for (DataSnapshot readingSnapshot: dataSnapshot.getChildren()) { //region Location //get the location data LocationLngLat location = new LocationLngLat(); if (readingSnapshot.child("location").getChildrenCount() > 0) { location.setAccuracy(Double.parseDouble(readingSnapshot.child("location").child("accuracy").getValue().toString())); location.setLatitude(Double.parseDouble(readingSnapshot.child("location").child("latitude").getValue().toString())); location.setLongitude(Double.parseDouble(readingSnapshot.child("location").child("longitude").getValue().toString())); } //endregion //region Magnetometer //get the magnetometer data Magnetometer magnetometer = new Magnetometer(); if (readingSnapshot.child("magnetometer").getChildrenCount() > 0) { magnetometer.setX(Double.parseDouble(readingSnapshot.child("magnetometer").child("x").getValue().toString())); magnetometer.setY(Double.parseDouble(readingSnapshot.child("magnetometer").child("y").getValue().toString())); magnetometer.setZ(Double.parseDouble(readingSnapshot.child("magnetometer").child("z").getValue().toString())); } //endregion //region RotationMeter //get the rotation meter data RotationMeter rotationMeter = new RotationMeter(); if (readingSnapshot.child("rotationmeter").getChildrenCount() > 0) { rotationMeter.setX(Double.parseDouble(readingSnapshot.child("rotationmeter").child("x").getValue().toString())); rotationMeter.setY(Double.parseDouble(readingSnapshot.child("rotationmeter").child("y").getValue().toString())); rotationMeter.setZ(Double.parseDouble(readingSnapshot.child("rotationmeter").child("z").getValue().toString())); } //endregion //region Accelerometer //get the accelerometer data Accelerometer accelerometer = new Accelerometer(); if (readingSnapshot.child("accelerometer").getChildrenCount() > 0){ accelerometer.setX(Double.parseDouble(readingSnapshot.child("accelerometer").child("x").getValue().toString())); accelerometer.setY(Double.parseDouble(readingSnapshot.child("accelerometer").child("y").getValue().toString())); accelerometer.setZ(Double.parseDouble(readingSnapshot.child("accelerometer").child("z").getValue().toString())); } //endregion //region PhoneInfo //Get the user's device information PhoneInfo phoneInfo = new PhoneInfo(); if (readingSnapshot.child("user").getChildrenCount() > 0){ phoneInfo.setModel(readingSnapshot.child("user").child("model").getValue().toString()); phoneInfo.setProduct(readingSnapshot.child("user").child("product").getValue().toString()); phoneInfo.setDevice(readingSnapshot.child("user").child("device").getValue().toString()); phoneInfo.setSdklevel(readingSnapshot.child("user").child("sdklevel").getValue().toString()); } //endregion //region Wi-Fi List //map of unique bssid with "BSSID<count>" List<WifiItem> wifiList = new ArrayList<>(); if (readingSnapshot.child("wifilist").getChildrenCount() > 0){ for (DataSnapshot wifi: readingSnapshot.child("wifilist").getChildren()) { WifiItem wifiItem = new WifiItem(wifi.child("ssid").getValue().toString(), wifi.child("bssid").getValue().toString(), Integer.parseInt(wifi.child("level").getValue().toString())); wifiList.add(wifiItem); //execute this only if format is CSV type and is not already contained in the hashmap if (formatParameter.equals(CSV_TYPE) && !uniqueWifisMap.containsKey(wifiItem.getBssid())) { //add the Bssid as key and an abstract BSSID<count> as value String uniqueBssid = "BSSID" + wifiCount; uniqueWifisMap.put(wifiItem.getBssid(), uniqueBssid); //increment count for the next unique hash wifiCount++; } } } //endregion //region Timestamp //get the timestamp long timestamp = Long.parseLong(readingSnapshot.child("timestamp").getValue().toString()); Reading reading = new Reading(timestamp, wifiList, location, accelerometer, magnetometer, rotationMeter, phoneInfo); //endregion //add to the list of the Reading class readingList.add(reading); } //region Write to Web Page if (formatParameter.equals(CSV_TYPE)){ //if format is CSV try { //set web page header resp.setHeader("Accept", "text/csv"); resp.setHeader("Content-type", "text/csv"); resp.setHeader("Content-Disposition","inline; filename=all_readings.csv"); //output csv header resp.getWriter().print(csvHeader(uniqueWifisMap)); //output all the rows in csv resp.getWriter().print(convertToCSV(readingList, uniqueWifisMap)); } catch (IOException e){ e.printStackTrace(); } } else{ //default format is JSON Gson gson = new GsonBuilder().setPrettyPrinting().create(); try { //set web page header resp.setHeader("Accept", "application/json"); resp.setHeader("Content-type", "application/json"); resp.setHeader("Content-Disposition","inline; filename=all_readings.json"); //out the data in JSON resp.getWriter().print("{ \"readings\" :" + gson.toJson(readingList) + "}"); } catch (IOException e) { e.printStackTrace(); } } //endregion //background thread job is down so release the latch countDownLatch.countDown(); } @Override public void onCancelled(DatabaseError databaseError) { } }); try { //waits for firebase to query record. countDownLatch.await(); } catch (InterruptedException ex) { ex.printStackTrace(); } //endregion } /** * Loop through the reading list * Output the reading values accordingly * Check the position of the wifi bssid, else set to 0.0 * @param readingList * @return */ public String convertToCSV(List<Reading> readingList, Map<String, String> uniqueReadingMap){ //if error occurred return no data error string if (uniqueReadingMap == null || readingList == null) return "error: no data"; //build the output StringBuilder output = new StringBuilder(); //loop through each reading, build the row and return the whole thing as string for (Reading reading: readingList) { //compare it with the unique wifi hash map //check if the wifi is there, if not set to 0 Integer[] wifiLevelArray = new Integer[uniqueReadingMap.size()]; //set everything to zero first for (int i = 0; i < wifiLevelArray.length; i++){ wifiLevelArray[i] = 0; } //we need to set the level values of the wifis for (WifiItem wifi : reading.getWifilist()) { String bssid = uniqueReadingMap.get(wifi.getBssid()); int count = Integer.parseInt(bssid.substring(5, bssid.length())); //Since we start with 1 for the BSSID<count>, we need to remove 1 wifiLevelArray[count - 1] = wifi.getLevel(); } //build the wifi level row first StringBuilder levelBuilder = new StringBuilder(); for (Integer level: wifiLevelArray){ String levelStr = level + ", "; levelBuilder.append(levelStr); } //build each row completely String out = //user's device information reading.getUser().getDevice() + ", " + reading.getUser().getModel() + ", " + reading.getUser().getProduct() + ", " + reading.getUser().getSdklevel() + ", " + //accelerometer reading.getAccelerometer().getX() + ", " + reading.getAccelerometer().getY() + ", " + reading.getAccelerometer().getZ() + ", " + //magnetometer reading.getMagnetometer().getX() + ", " + reading.getMagnetometer().getY() + ", " + reading.getMagnetometer().getZ() + ", " + reading.getRotationmeter().getX() + ", " + reading.getRotationmeter().getY() + ", " + reading.getRotationmeter().getZ() + ", " + //wifis levelBuilder.toString() + //location reading.getLocation().getLongitude() + ", " + reading.getLocation().getLatitude() + ", " + reading.getLocation().getAccuracy() + "\r\n"; //append the row to the output StringBuilder output.append(out); } return output.toString(); } /** * Returns the csv header with all the unique BSSIDs * @param uniqueWifisMap * @return */ public String csvHeader(Map<String, String> uniqueWifisMap){ StringBuilder uniqueWifis = new StringBuilder(); for (String wifi: uniqueWifisMap.keySet()){ String bssid = uniqueWifisMap.get(wifi) + ", "; uniqueWifis.append(bssid); } return "user_device, user_model, user_product, user_sdklevel, " + "acceleration_x, acceleration_y, acceleration_z, " + "magnetic_x, magnetic_y, magnetic_z, " + "rotation_x, rotation_y, rotation_z, " + uniqueWifis.toString() + "location_longitude, location_latitude, location_accuracy\r\n"; } }
47.078873
142
0.568539
12509b6c26073fb9d47e2d78d2fa43f9794c4cf3
8,120
/*************************************************************************** * Copyright 2001-2009 The VietSpider All rights reserved. * **************************************************************************/ package org.vietspider.html.renderer; import java.text.Normalizer; import java.util.ArrayList; import java.util.List; import org.vietspider.chars.CharsUtil; import org.vietspider.chars.refs.RefsDecoder; import org.vietspider.document.util.OtherLinkRemover2; import org.vietspider.html.HTMLDocument; import org.vietspider.html.HTMLNode; import org.vietspider.html.Name; import org.vietspider.html.NodeIterator; import org.vietspider.html.path2.HTMLExtractor; import org.vietspider.html.path2.NodePath; import org.vietspider.html.path2.NodePathParser; import org.vietspider.html.util.HTMLParentUtils; import org.vietspider.html.util.HTMLText; import org.vietspider.html.util.NodeHandler; /** * Author : Nhu Dinh Thuan * [email protected] * Jan 14, 2009 */ public class ContentRegionSearcher { private NodeHandler nodeHandler = new NodeHandler(); private HTMLParentUtils htmlUtil = new HTMLParentUtils(); private Name [] ignores = {Name.A, Name.MARQUEE}; public void searchNodes(NodeIterator iterator, List<HTMLNode> nodes, Name name) { while(iterator.hasNext()) { HTMLNode n = iterator.next(); if(n.isNode(name)) nodes.add(n); } } public List<HTMLNode> searchNodes(HTMLNode node, Name name) { List<HTMLNode> refsNode = new ArrayList<HTMLNode>(); searchNodes(node.iterator(), refsNode, name); HTMLText htmlText = new HTMLText(); HTMLText.EmptyVerify verify = new HTMLText.EmptyVerify(); List<HTMLNode> contents = new ArrayList<HTMLNode>(); htmlText.searchText(contents, node, verify); return contents; } public String searchMaxSequence(String text, char c) { int index = text.indexOf(c); if(index < 0) return null; int counter = 1; while(index > -1) { counter = searchMaxSequence(text, c, index, counter); index = text.indexOf(c, index+counter); } StringBuilder builder = new StringBuilder(counter); for(int i = 0; i < counter; i++) { builder.append(c); } return builder.toString(); } public int searchMaxSequence(String text, char c, int index, int counter) { int k = index + 1; for(; k < index + counter; k++) { if(k >= text.length() || text.charAt(k) != c) return counter; } k = index + counter ; while(k < text.length()) { if(text.charAt(k) != c) { return k - index; } k++; } return counter; } public NodeRenderer filte(NodeRenderer [] nodeRenders) { NodeRenderer renderer = null; int max = 0; for(int i = 0; i < nodeRenders.length; i++) { int counter = countWord(nodeRenders[i].getNodes()); if(renderer == null) { max = counter; renderer = nodeRenders[i]; } else if (counter >= max) { max = counter; renderer = nodeRenders[i]; } } return renderer; } public int countWord(List<HTMLNode> list) { int counter = 0; for(HTMLNode node : list) { counter += countWord(node); } return counter; } public int countWord(HTMLNode node) { if(node.isNode(Name.CONTENT)) { if(isIgnoreTag(node)) { return 0; } int c = nodeHandler.count(new String(node.getValue())); return c; } return 0; } public int countWordA(List<HTMLNode> list) { int counter = 0; for(HTMLNode node : list) { counter += countWordA(node); } return counter; } public int countWordA(HTMLNode node) { if(node.isNode(Name.CONTENT)) { if(isIgnoreTag(node)) { int c = nodeHandler.count(new String(node.getValue())); return c; } return 0; } return 0; } public boolean isIgnoreTag(HTMLNode node) { return isIgnoreTag(node, 0); } public boolean isIgnoreTag(HTMLNode node, int level) { if(node == null || level >= 5) return false; for(int i = 0; i < ignores.length; i++) { if(node.isNode(ignores[i])) return true; } return isIgnoreTag(node.getParent(), level+1); } public HTMLNode searchParent(HTMLDocument document, int level) throws Exception { HTMLNode body = searchBody(document); ContentRenderer renderer = createContentRenderer(body); int length = renderer.getTextValue().length(); List<HTMLNode> renderNodes = renderer.getNodePositions(0, length); NodeRenderer nodeRenderer = new NodeRenderer(renderer, renderNodes, 0, length); NodeRenderer [] nodeRenderers = {nodeRenderer}; while(true) { nodeRenderer = filte(nodeRenderers); if(nodeRenderer == null) break; String pattern = searchMaxSequence(nodeRenderer.getText(), '\\'); if(pattern == null || pattern.length() < level) break; nodeRenderers = nodeRenderer.split(pattern); } nodeRenderer = filte(nodeRenderers); nodeRenderers = new NodeRenderer[] {nodeRenderer}; int start = nodeRenderer.getStart(); int end = nodeRenderer.getEnd(); return htmlUtil.getUpParent(renderer.getNodePositions(start, end)); } public List<HTMLNode> searchNodes(HTMLDocument document, int level, int step) throws Exception { List<HTMLNode> values = new ArrayList<HTMLNode>(); HTMLNode body = searchBody(document); ContentRenderer renderer = createContentRenderer(body); int length = renderer.getTextValue().length(); List<HTMLNode> renderNodes = renderer.getNodePositions(0, length); NodeRenderer nodeRenderer = new NodeRenderer(renderer, renderNodes, 0, length); NodeRenderer [] nodeRenderers = {nodeRenderer}; while(true) { nodeRenderer = filte(nodeRenderers); if(nodeRenderer == null) break; String pattern = searchMaxSequence(nodeRenderer.getText(), '\\'); if(pattern == null || pattern.length() < level) break; if(pattern.length()%step == 0) { int start = nodeRenderer.getStart(); int end = nodeRenderer.getEnd(); List<HTMLNode> subNodes = renderer.getNodePositions(start, end); values.add(htmlUtil.getUpParent(subNodes)); } nodeRenderers = nodeRenderer.split(pattern); } nodeRenderer = filte(nodeRenderers); nodeRenderers = new NodeRenderer[] {nodeRenderer}; int start = nodeRenderer.getStart(); int end = nodeRenderer.getEnd(); List<HTMLNode> subNodes = renderer.getNodePositions(start, end); values.add(htmlUtil.getUpParent(subNodes)); return values; } protected HTMLNode searchBody(HTMLDocument document) throws Exception { RefsDecoder decoder = new RefsDecoder(); NodeIterator iterator = document.getRoot().iterator(); while(iterator.hasNext()) { HTMLNode node = iterator.next(); if(!node.isNode(Name.CONTENT)) continue; char [] chars = node.getValue(); chars = decoder.decode(chars); chars = CharsUtil.cutAndTrim(chars, 0, chars.length); chars = java.text.Normalizer.normalize(new String(chars), Normalizer.Form.NFC).toCharArray(); node.setValue(chars); } HTMLExtractor extractor = new HTMLExtractor(); NodePathParser pathParser = new NodePathParser(); NodePath nodePath = pathParser.toPath("BODY"); return extractor.lookNode(document.getRoot(), nodePath); } private ContentRenderer createContentRenderer(HTMLNode body) { List<HTMLNode> contents = searchNodes(body, Name.A); OtherLinkRemover2 linkRemover = new OtherLinkRemover2(); List<HTMLNode> nodes = linkRemover.removeLinks(body, null); for(int i = 0; i < nodes.size(); i++) { contents.remove(nodes.get(i)); } return ContentRendererFactory.createContentRenderer(body, null); } }
31.843137
101
0.631281
bb06904d2050af4b892d716f4411c14ffd38a6a8
955
package org.metaborg.meta.lang.dynsem.interpreter.nodes.building; import org.metaborg.meta.lang.dynsem.interpreter.terms.ITerm; import org.metaborg.meta.lang.dynsem.interpreter.terms.TermPlaceholder; import org.metaborg.meta.lang.dynsem.interpreter.utils.SourceUtils; import org.spoofax.interpreter.terms.IStrategoAppl; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.source.SourceSection; public abstract class TermPlaceholderBuild extends TermBuild { public TermPlaceholderBuild(SourceSection source) { super(source); } public static TermPlaceholderBuild create(IStrategoAppl t, FrameDescriptor fd) { return TermPlaceholderBuildNodeGen.create(SourceUtils.dynsemSourceSectionFromATerm(t)); } @Specialization public ITerm executePlaceholder(VirtualFrame frame) { return TermPlaceholder.INSTANCE; } }
32.931034
89
0.831414
2d9e3e50a54503237cd82603ded08743069a03da
30,911
package org.d2rq.mapgen; import java.net.URI; import java.sql.Types; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.d2rq.db.SQLConnection; import org.d2rq.db.schema.ColumnDef; import org.d2rq.db.schema.ForeignKey; import org.d2rq.db.schema.Identifier; import org.d2rq.db.schema.Key; import org.d2rq.db.schema.TableDef; import org.d2rq.db.schema.TableName; import org.d2rq.db.types.DataType; import org.d2rq.db.types.SQLBoolean; import org.d2rq.db.types.SQLExactNumeric; import org.d2rq.db.types.StrdfWKT; import org.d2rq.lang.Microsyntax; import org.d2rq.values.TemplateValueMaker; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.shared.PrefixMapping; import com.hp.hpl.jena.shared.PrefixMapping.IllegalPrefixException; import com.hp.hpl.jena.shared.impl.PrefixMappingImpl; import eu.linkedeodata.geotriples.Config; import eu.linkedeodata.geotriples.WKTLiteral; import eu.linkedeodata.geotriples.gui.ColumnReceipt; /** * Generates a D2RQ mapping by introspecting a database schema. * Result is available as a high-quality Turtle serialization, or * as a parsed model. * * @author Richard Cyganiak ([email protected]) */ public class MappingGenerator { private final static Logger log = LoggerFactory.getLogger(MappingGenerator.class); private final MappingStyle style; private final SQLConnection sqlConnection; private final List<TableName> tablesWithoutUniqueKey = new ArrayList<TableName>(); private final PrefixMapping prefixes = new PrefixMappingImpl(); private Filter filter = Filter.ALL; private boolean finished = false; private boolean generateClasses = true; private boolean generateLabelBridges = false; private boolean generateDefinitionLabels = false; private boolean handleLinkTables = true; private boolean serveVocabulary = true; private boolean skipForeignKeyTargetColumns = true; private boolean useUniqueKeysAsEntityID = true; private boolean suppressWarnings = false; private URI startupSQLScript; private Target target; private TableDef geoTable = null; private String onlytable=null; public MappingGenerator(MappingStyle style, SQLConnection sqlConnection) { this.style = style; this.sqlConnection = sqlConnection; } public void setFilter(Filter filter) { this.filter = filter; } public void setStartupSQLScript(URI uri) { startupSQLScript = uri; } public void setOnlyTable(String onlytable){ this.onlytable=onlytable; } /** * @param flag Generate an rdfs:label property bridge based on the PK? */ public void setGenerateLabelBridges(boolean flag) { this.generateLabelBridges = flag; } /** * @param flag Add <code>rdfs:label</code>s to auto-generated classes and properties? */ public void setGenerateDefinitionLabels(boolean flag) { this.generateDefinitionLabels = flag; } /** * @param flag Generate a d2rq:class for every class map? */ public void setGenerateClasses(boolean flag) { this.generateClasses = flag; } /** * @param flag Handle Link Tables as properties (true) or normal tables (false) */ public void setHandleLinkTables(boolean flag) { this.handleLinkTables = flag; } /** * @param flag Value for d2rq:serveVocabulary in map:Configuration */ public void setServeVocabulary(boolean flag) { this.serveVocabulary = flag; } public void setSkipForeignKeyTargetColumns(boolean flag) { skipForeignKeyTargetColumns = flag; } public void setUseUniqueKeysAsEntityID(boolean flag) { useUniqueKeysAsEntityID = flag; } public void setSuppressWarnings(boolean flag) { suppressWarnings = flag; } public void generate(Target generationTarget) { java.util.Map<TableName, java.util.List<ColumnReceipt>> tablesAndColumns = Config.tablesAndColumns; java.util.Map<TableName, String> tablesAndClasses = Config.tablesAndClasses; if (finished) return; finished = true; target = generationTarget; target.init(style.getBaseIRI(), style.getGeneratedOntologyResource(), serveVocabulary, generateDefinitionLabels); for (String prefix: style.getPrefixes().getNsPrefixMap().keySet()) { target.addPrefix(prefix, style.getPrefixes().getNsPrefixMap().get(prefix)); prefixes.setNsPrefix(prefix, style.getPrefixes().getNsPrefixMap().get(prefix)); } target.generateDatabase(sqlConnection, startupSQLScript == null ? null : startupSQLScript.toString()); List<TableName> tableNames = new ArrayList<TableName>(); for (TableName tableName: sqlConnection.getTableNames(filter.getSingleSchema())) { //ignore meta-tables in the mapping if (!filter.matches(tableName) || tableName.getTable().getName().equals("geography_columns") || tableName.getTable().getName().equals("spatial_ref_sys") || tableName.getTable().getName().equals("geometry_columns")) { log.info("Skipping table " + tableName); System.out.println("Skipping table " + tableName); continue; } if(onlytable!=null){ if(!onlytable.equalsIgnoreCase(tableName.getTable().getName())){ continue; } } tableNames.add(tableName); } log.info("Filter '" + filter + "' matches " + tableNames.size() + " total tables"); for (TableName tableName: tableNames) { if (tablesAndColumns != null) { if (tablesAndColumns.get(tableName) == null) { continue; } } //check if the there is the_geom property TableDef table = sqlConnection.getTable(tableName).getTableDefinition(); List<ColumnDef> columns = table.getColumns(); boolean hasGeom = false; String geoColumn = null; for (int i=0 ; i<columns.size() ; i++) { if (columns.get(i).getDataType().name().equalsIgnoreCase("GEOMETRY")) { geoColumn = columns.get(i).getName().getCanonicalName(); hasGeom = true; break; } } if (tablesAndColumns != null) { java.util.List<ColumnReceipt> cols = tablesAndColumns.get(tableName); if (cols != null) { boolean found = false; for (int i=0 ; i<cols.size() ; i++) { //System.out.println(cols.get(i).getDataType()); if(cols.get(i).getDataType().equalsIgnoreCase("geometry")){ //if (cols.get(i).getColumnName().contains("geom")) { //TODO: check the recognition of geocolumn found = true; break; } } if (!found) { hasGeom = false; } } } //System.out.println(hasGeom + " " + Config.VOCABULARY); if (hasGeom && Config.VOCABULARY.equals("GeoSPARQL")) { processGeometry(tableName, geoColumn); } if (hasGeom && Config.VOCABULARY.equals("stRDF")) { processAtOnce(tableName, hasGeom, tablesAndColumns, tablesAndClasses, geoColumn); } else { processTable(tableName, hasGeom, tablesAndColumns, tablesAndClasses); } } if (!tablesWithoutUniqueKey.isEmpty()) { StringBuilder s = new StringBuilder(); s.append("Sorry, I don't know which columns to put into the "); s.append("d2rq:uriPattern of tables that don't have a "); s.append("primary or unique key. Please specify them manually: "); Iterator<TableName> it = tablesWithoutUniqueKey.iterator(); while (it.hasNext()) { s.append(Microsyntax.toString(it.next())); if (it.hasNext()) { s.append(", "); } } if (!suppressWarnings) { log.warn(s.toString()); } } target.close(); } private void processAtOnce(TableName tableName, boolean hasGeom, java.util.Map<TableName, java.util.List<ColumnReceipt>> tablesAndColumns, java.util.Map<TableName, String> tablesAndClasses, String geoColumn) { TableDef table = sqlConnection.getTable(tableName).getTableDefinition(); ColumnDef additionalColumn = new ColumnDef(Identifier.createDelimited("hasGeometry"), new StrdfWKT("WKT"), true); table.getColumns().add(additionalColumn); table.getColumnNames().add(additionalColumn.getName()); boolean hasprimarykey=table.getPrimaryKey()!=null; //SQLOp op = sqlConnection.getSelectStatement(""); //but first create its geometry view? if (handleLinkTables && isLinkTable(table)) { Iterator<ForeignKey> it = table.getForeignKeys().iterator(); ForeignKey fk1 = it.next(); ForeignKey fk2 = it.next(); TableName referencedTable1 = fk1.getReferencedTable(); TableName referencedTable2 = fk2.getReferencedTable(); if (!filter.matches(referencedTable1) || !filter.matchesAll(referencedTable1, fk1.getLocalColumns()) || !filter.matchesAll(referencedTable1, fk1.getReferencedColumns()) || !filter.matches(referencedTable2) || !filter.matchesAll(referencedTable2, fk2.getLocalColumns()) || !filter.matchesAll(referencedTable2, fk2.getReferencedColumns())) { log.info("Skipping link table " + tableName); return; } target.generateLinkProperty( style.getLinkProperty(tableName), tableName, fk1, fk2); } else { Resource class_ = null; if (tablesAndClasses==null || tablesAndClasses.get(tableName) == null) { class_ = generateClasses ? style.getTableClass(tableName) : null; } else { class_ = generateClasses ? style.getStringClass(tablesAndClasses.get(tableName)) : null; } //System.out.println(class_.getLocalName()); TemplateValueMaker iriTemplate = null; List<Identifier> blankNodeColumns = null; Key key = findBestKey(table); if (key == null) { /* List<ColumnDef> filteredColumns = new ArrayList<ColumnDef>(); for (ColumnDef columnDef: table.getColumns()) { if (filter.matches(tableName, columnDef.getName())) { filteredColumns.add(columnDef); } } if (style.getEntityPseudoKeyColumns(filteredColumns) == null) { tablesWithoutUniqueKey.add(tableName); iriTemplate = style.getEntityIRITemplate(table, null); } else { blankNodeColumns = style.getEntityPseudoKeyColumns(filteredColumns); }*/ key=makeKey(table); } /*else {*/ iriTemplate = style.getEntityIRITemplate(table, key); /*}*/ String query = "SELECT *," + "CONCAT(st_astext(" + geoColumn + "), \'; <http://www.opengis.net/def/crs/EPSG/0/\', ST_SRID(" + geoColumn + "), \'>') as \"hasGeometry\" FROM " + tableName.toString(); if (sqlConnection.getJdbcURL().contains("monetdb")) { query = "SELECT *," + " CONCAT(CONCAT(REPLACE(CAST(" + geoColumn + " AS TEXT), '\"', ''), '; '), \'<http://www.opengis.net/def/crs/EPSG/0/" + Config.EPSG_CODE +">\') as \"hasGeometry\" FROM " + tableName.toString(); } target.generateQueriedEntities(class_, table.getName(), iriTemplate, blankNodeColumns, query); //System.out.println(class_.getURI()); if (class_ != null) { if (tableName.getSchema() != null) { tryRegisterPrefix(tableName.getSchema().getName().toLowerCase(), class_.getNameSpace()); } if (tableName.getCatalog() != null) { tryRegisterPrefix(tableName.getCatalog().getName().toLowerCase(), class_.getNameSpace()); } } if (generateLabelBridges && key != null) { target.generateEntityLabels( style.getEntityLabelTemplate(tableName, key), tableName); } /*else if (generateLabelBridges && key == null) { //key is never null // Key themkey = null; if (table.getColumnNames().contains(Identifier.createDelimited("id"))) { themkey = Key.create(ColumnName.create(table.getName(), Identifier.createDelimited("id"))); } else if (table.getColumnNames().contains(Identifier.createDelimited("gid"))) { themkey = Key.create(Identifier.createDelimited("gid")); } if (themkey == null) { // target.generateEntityLabels( // style.getEntityLabelTemplate(tableName, themkey), tableName); } }*/ for (Identifier column: table.getColumnNames()) { ColumnReceipt colReceipt = null; if (tablesAndColumns != null) { java.util.List<ColumnReceipt> cols = tablesAndColumns.get(tableName); if (cols != null) { boolean found = false; for (int i=0 ; i<cols.size() ; i++) { if (cols.get(i).getColumnName().equals(column.getCanonicalName())) { colReceipt = cols.get(i); found = true; break; } } if (!found && !column.getCanonicalName().equals("hasGeometry")) { continue; } } } if (key != null && hasprimarykey) { //need hasprimarykay because if has not, then must not get in this if if (key.contains(column)) { continue; } } else { if (column.getCanonicalName().equals("gid")) { continue; } } if (skipForeignKeyTargetColumns && isInForeignKey(column, table)) continue; if (!filter.matches(tableName, column)) { log.info("Skipping filtered column " + column); continue; } DataType type = table.getColumnDef(column).getDataType(); if (type == null) { String message = "The datatype is unknown to D2RQ.\n"; message += "You can override the column's datatype using d2rq:xxxColumn and add a property bridge."; if (!suppressWarnings) { log.warn(message); } target.skipColumn(tableName, column, message); continue; } if (type.name().equalsIgnoreCase("GEOMETRY")) { continue; } if (type.isUnsupported()) { String message = "The datatype " + type + " cannot be mapped to RDF."; if (!suppressWarnings) { log.warn(message); } target.skipColumn(tableName, column, message); continue; } Property property = null; if (colReceipt == null) { property = style.getColumnProperty(tableName, column); } else { property = style.getTargetProperty(Identifier.createDelimited(colReceipt.getPredicate())); } target.generateColumnProperty(property, tableName, column, type); tryRegisterPrefix( tableName.getTable().getName().toLowerCase(), property.getNameSpace()); } for (ForeignKey fk: table.getForeignKeys()) { if (!filter.matches(fk.getReferencedTable()) || !filter.matchesAll(tableName, fk.getLocalColumns()) || !filter.matchesAll(fk.getReferencedTable(), fk.getReferencedColumns())) { log.info("Skipping foreign key: " + fk); continue; } target.generateRefProperty( style.getForeignKeyProperty(tableName, fk), tableName, fk); } } } private void processTable(TableName tableName, boolean hasGeom, java.util.Map<TableName, java.util.List<ColumnReceipt>> tablesAndColumns, java.util.Map<TableName, String> tablesAndClasses) { TableDef table = sqlConnection.getTable(tableName).getTableDefinition(); boolean hasprimarykey=table.getPrimaryKey()!=null; //SQLOp op = sqlConnection.getSelectStatement(""); //but first create its geometry view? //if(!filter.matches(tableName) )return; if (handleLinkTables && isLinkTable(table)) { Iterator<ForeignKey> it = table.getForeignKeys().iterator(); ForeignKey fk1 = it.next(); ForeignKey fk2 = it.next(); TableName referencedTable1 = fk1.getReferencedTable(); TableName referencedTable2 = fk2.getReferencedTable(); if (!filter.matches(referencedTable1) || !filter.matchesAll(referencedTable1, fk1.getLocalColumns()) || !filter.matchesAll(referencedTable1, fk1.getReferencedColumns()) || !filter.matches(referencedTable2) || !filter.matchesAll(referencedTable2, fk2.getLocalColumns()) || !filter.matchesAll(referencedTable2, fk2.getReferencedColumns())) { log.info("Skipping link table " + tableName); return; } target.generateLinkProperty( style.getLinkProperty(tableName), tableName, fk1, fk2); } else { Resource class_ = null; if (tablesAndClasses==null || tablesAndClasses.get(tableName) == null) { class_ = generateClasses ? style.getTableClass(tableName) : null; } else { class_ = generateClasses ? style.getStringClass(tablesAndClasses.get(tableName)) : null; } TemplateValueMaker iriTemplate = null; List<Identifier> blankNodeColumns = null; Key key = findBestKey(table); if (key == null) { /* List<ColumnDef> filteredColumns = new ArrayList<ColumnDef>(); for (ColumnDef columnDef: table.getColumns()) { if (filter.matches(tableName, columnDef.getName())) { filteredColumns.add(columnDef); } } if (style.getEntityPseudoKeyColumns(filteredColumns) == null) { tablesWithoutUniqueKey.add(tableName); iriTemplate = style.getEntityIRITemplate(table, null); } else { blankNodeColumns = style.getEntityPseudoKeyColumns(filteredColumns); }*/ key=makeKey(table); } /*else {*/ iriTemplate = style.getEntityIRITemplate(table, key); /*}*/ target.generateEntities(class_, tableName, iriTemplate, blankNodeColumns, false); if (class_ != null) { if (tableName.getSchema() != null) { tryRegisterPrefix(tableName.getSchema().getName().toLowerCase(), class_.getNameSpace()); } if (tableName.getCatalog() != null) { tryRegisterPrefix(tableName.getCatalog().getName().toLowerCase(), class_.getNameSpace()); } } if (generateLabelBridges && key != null) { target.generateEntityLabels( style.getEntityLabelTemplate(tableName, key), tableName); } /*else if (generateLabelBridges && key == null) { //key is never null // Key themkey = null; if (table.getColumnNames().contains(Identifier.createDelimited("id"))) { themkey = Key.create(ColumnName.create(table.getName(), Identifier.createDelimited("id"))); } else if (table.getColumnNames().contains(Identifier.createDelimited("gid"))) { themkey = Key.create(Identifier.createDelimited("gid")); } if (themkey == null) { // target.generateEntityLabels( // style.getEntityLabelTemplate(tableName, themkey), tableName); } }*/ for (Identifier column: table.getColumnNames()) { ColumnReceipt colReceipt = null; if (tablesAndColumns != null) { java.util.List<ColumnReceipt> cols = tablesAndColumns.get(tableName); if (cols != null) { boolean found = false; for (int i=0 ; i<cols.size() ; i++) { if (cols.get(i).getColumnName().equals(column.getCanonicalName())) { colReceipt = cols.get(i); found = true; break; } } if (!found) { continue; } } } if (key != null && hasprimarykey) { //need hasprimarykay because if has not, then must not get in this if if (key.contains(column)) { continue; } } else { if (column.getCanonicalName().equals("gid")) { continue; } } if (skipForeignKeyTargetColumns && isInForeignKey(column, table)) continue; if (!filter.matches(tableName, column)) { log.info("Skipping filtered column " + column); continue; } DataType type = table.getColumnDef(column).getDataType(); if (type == null) { String message = "The datatype is unknown to D2RQ.\n"; message += "You can override the column's datatype using d2rq:xxxColumn and add a property bridge."; if (!suppressWarnings) { log.warn(message); } target.skipColumn(tableName, column, message); continue; } if (type.name().equalsIgnoreCase("GEOMETRY")) { continue; } if (type.isUnsupported()) { String message = "The datatype " + type + " cannot be mapped to RDF."; if (!suppressWarnings) { log.warn(message); } target.skipColumn(tableName, column, message); continue; } Property property = null; if (colReceipt == null) { property = style.getColumnProperty(tableName, column); } else { property = style.getTargetProperty(Identifier.createDelimited(colReceipt.getPredicate())); } target.generateColumnProperty(property, tableName, column, type); tryRegisterPrefix( tableName.getTable().getName().toLowerCase(), property.getNameSpace()); } for (ForeignKey fk: table.getForeignKeys()) { if (!filter.matches(fk.getReferencedTable()) || !filter.matchesAll(tableName, fk.getLocalColumns()) || !filter.matchesAll(fk.getReferencedTable(), fk.getReferencedColumns())) { log.info("Skipping foreign key: " + fk); continue; } target.generateRefProperty( style.getForeignKeyProperty(tableName, fk), tableName, fk); } if (hasGeom){ ((R2RMLTarget)target).generateTemplatePredicateObjectMap(style.getLinkGeometryPropetry(null),style.getGeometryIRITemplate(table, key) , tableName); } } } private void processGeometry(TableName tableName, String geoColumn) { TableDef auxTable = sqlConnection.getTable(tableName).getTableDefinition(); List<ColumnDef> columns = new ArrayList<ColumnDef>(); Identifier ide = Identifier.create(true, "gid"); if (auxTable.getPrimaryKey() != null) { ide = auxTable.getPrimaryKey().get(0); } //ColumnDef id = new ColumnDef(ide, new SQLExactNumeric("int",Types.INTEGER , false), false); ColumnDef dimension = new ColumnDef(Identifier.create(true, "dimension"), new SQLExactNumeric("int",Types.INTEGER, false), false); ColumnDef coordinateDimension = new ColumnDef(Identifier.create(true, "coordinateDimension"), new SQLExactNumeric("int",Types.INTEGER, false), false); ColumnDef spatialDimension = new ColumnDef(Identifier.create(true, "spatialDimension"), new SQLExactNumeric("int",Types.INTEGER, false), false); ColumnDef isEmpty = new ColumnDef(Identifier.create(true, "isEmpty"), new SQLBoolean("Boolean"), false); ColumnDef isSimple = new ColumnDef(Identifier.create(true, "isSimple"), new SQLBoolean("Boolean"), false); ColumnDef is3D = new ColumnDef(Identifier.create(true, "is3D"), new SQLBoolean("Boolean"), false); /*ColumnDef hasSerialization = new ColumnDef(Identifier.create(true, "hasSerialization"), new WKTLiteral("wktLiteral"), false);*/ ColumnDef asWKT = new ColumnDef(Identifier.create(true, "asWKT"), new WKTLiteral("wktLiteral"), false); //Key primaryKey = Key.create(id.getName()); //columns.add(id); columns.add(dimension); columns.add(coordinateDimension); columns.add(spatialDimension); columns.add(isEmpty); columns.add(isSimple); columns.add(is3D); /*columns.add(hasSerialization);*/ columns.add(asWKT); Identifier ident = Identifier.createDelimited(tableName.getTable().getCanonicalName() + "Geo"); TableDef table = new TableDef(TableName.create(auxTable.getName().getCatalog(), auxTable.getName().getSchema(), ident), columns, null, new HashSet<Key>(), new HashSet<ForeignKey>()); geoTable = table; //SQLOp op = sqlConnection.getSelectStatement(""); //but first create its geometry view? if (handleLinkTables && isLinkTable(table)) { Iterator<ForeignKey> it = table.getForeignKeys().iterator(); ForeignKey fk1 = it.next(); ForeignKey fk2 = it.next(); TableName referencedTable1 = fk1.getReferencedTable(); TableName referencedTable2 = fk2.getReferencedTable(); if (!filter.matches(referencedTable1) || !filter.matchesAll(referencedTable1, fk1.getLocalColumns()) || !filter.matchesAll(referencedTable1, fk1.getReferencedColumns()) || !filter.matches(referencedTable2) || !filter.matchesAll(referencedTable2, fk2.getLocalColumns()) || !filter.matchesAll(referencedTable2, fk2.getReferencedColumns())) { log.info("Skipping link table " + tableName); return; } target.generateLinkProperty( style.getLinkProperty(tableName), tableName, fk1, fk2); } else { Resource class_ = generateClasses ? style.getTableClass(tableName) : null; TemplateValueMaker iriTemplate = null; List<Identifier> blankNodeColumns = null; Key key = findBestKey(auxTable); if (key == null) { key=makeKey(auxTable); } /*if (key == null) { List<ColumnDef> filteredColumns = new ArrayList<ColumnDef>(); for (ColumnDef columnDef: table.getColumns()) { if (filter.matches(tableName, columnDef.getName())) { filteredColumns.add(columnDef); } } if (style.getEntityPseudoKeyColumns(filteredColumns) == null) { tablesWithoutUniqueKey.add(tableName); iriTemplate = style.getGeometryIRITemplate(table, key); } else { blankNodeColumns = style.getEntityPseudoKeyColumns(filteredColumns); iriTemplate = style.getGeometryIRITemplate(table, key); } } else {*/ iriTemplate = style.getGeometryIRITemplate(auxTable, key); /*}*/ String query = "SELECT *," + " st_dimension(" + geoColumn + ") as \"dimension\", st_coorddim(" + geoColumn + ") as \"coordinateDimension\", st_coorddim(" + geoColumn + ") as \"spatialDimension\", CASE WHEN st_issimple(" + geoColumn + ") THEN 'true' ELSE 'false' END as \"isSimple\", CASE WHEN st_isempty(" + geoColumn + ") THEN 'true' ELSE 'false' END as \"isEmpty\", CASE WHEN st_coorddim("+geoColumn+")=3 THEN 'true' ELSE 'false' END as \"is3D\", CONCAT(\'<http://www.opengis.net/def/crs/EPSG/0/\', ST_SRID(" + geoColumn + "), \'> \' ,st_astext(" + geoColumn + ")) as \"asWKT\" FROM " + tableName.toString(); if (sqlConnection.getJdbcURL().contains("monetdb")) { query = "SELECT *," + " st_dimension(" + geoColumn + ") as \"dimension\", st_dimension(" + geoColumn + ") as \"coordinateDimension\", st_dimension(" + geoColumn + ") as \"spatialDimension\", st_issimple(" + geoColumn + ") as \"isSimple\", st_isempty(" + geoColumn + ") as \"isEmpty\", CASE WHEN st_dimension("+geoColumn+")=3 THEN 'true' ELSE 'false' END as \"is3D\", CONCAT(\'<http://www.opengis.net/def/crs/EPSG/0/" + Config.EPSG_CODE +"> \' , REPLACE(CAST(" + geoColumn + " AS TEXT), '\"', '')) as \"asWKT\" FROM " + tableName.toString(); } target.generateGeoEntities(class_, table.getName(), iriTemplate, blankNodeColumns, query); if (class_ != null) { if (tableName.getSchema() != null) { tryRegisterPrefix(tableName.getSchema().getName().toLowerCase(), class_.getNameSpace()); } if (tableName.getCatalog() != null) { tryRegisterPrefix(tableName.getCatalog().getName().toLowerCase(), class_.getNameSpace()); } } if (generateLabelBridges && key != null) { target.generateEntityLabels( style.getEntityLabelTemplate(table.getName(), key), table.getName()); } for (Identifier column: table.getColumnNames()) { if (skipForeignKeyTargetColumns && isInForeignKey(column, table)) continue; if (!filter.matches(table.getName(), column)) { log.info("Skipping filtered column " + column); continue; } if (column.getName().equals("the_geom")) { continue; } if (column.getName().equals("type")) { //TODO: treat it differently continue; } /*if (column.getName().equals("gid")) { continue; }*/ DataType type = table.getColumnDef(column).getDataType(); if (type == null) { String message = "The datatype is unknown to D2RQ.\n"; message += "You can override the column's datatype using d2rq:xxxColumn and add a property bridge."; if (!suppressWarnings) { log.warn(message); } target.skipColumn(table.getName(), column, message); continue; } if (type.isUnsupported()) { String message = "The datatype " + type + " cannot be mapped to RDF."; if (!suppressWarnings) { log.warn(message); } target.skipColumn(table.getName(), column, message); continue; } Property property = style.getGeometryColumnProperty(table.getName(), column); target.generateColumnProperty(property, table.getName(), column, type); tryRegisterPrefix( table.getName().getTable().getName().toLowerCase(), property.getNameSpace()); } for (ForeignKey fk: table.getForeignKeys()) { if (!filter.matches(fk.getReferencedTable()) || !filter.matchesAll(table.getName(), fk.getLocalColumns()) || !filter.matchesAll(fk.getReferencedTable(), fk.getReferencedColumns())) { log.info("Skipping foreign key: " + fk); continue; } target.generateRefProperty( style.getForeignKeyProperty(table.getName(), fk), tableName, fk); } } //geoTable = null; } private void tryRegisterPrefix(String prefix, String uri) { if (prefixes.getNsPrefixMap().containsKey(prefix)) return; if (prefixes.getNsPrefixMap().containsValue(uri)) return; try { prefixes.setNsPrefix(prefix, uri); target.addPrefix(prefix, uri); } catch (IllegalPrefixException ex) { // Oh well, no prefix then. } } private Key findBestKey(TableDef table) { if (table.getPrimaryKey() != null) { if (!isExcluded(table, table.getPrimaryKey(), true)) { return table.getPrimaryKey(); } } if (!useUniqueKeysAsEntityID) return null; for (Key uniqueKey: table.getUniqueKeys()) { if (!isExcluded(table, uniqueKey, true)) { return uniqueKey; } } return null; } private boolean isExcluded(TableDef table, Key columns, boolean requireDistinct) { for (Identifier column: columns) { if (isExcluded(table, column, requireDistinct)) return true; } return false; } private boolean isExcluded(TableDef table, Identifier column, boolean requireDistinct) { if (!filter.matches(table.getName(), column)) return true; DataType type = table.getColumnDef(column).getDataType(); return type == null || type.isUnsupported() || (requireDistinct && !type.supportsDistinct()); } private Key makeKey(TableDef table) { ArrayList<Identifier> temp=new ArrayList<Identifier>(); for (Identifier partKey: table.getColumnNames()) { if(!partKey.getName().equalsIgnoreCase("geom")) { temp.add(partKey); } } return Key.createFromIdentifiers(temp); } /** * A table T is considered to be a link table if it has exactly two * foreign key constraints, and the constraints reference other * tables (not T), and the constraints cover all columns of T, * and there are no foreign keys from other tables pointing to this table */ private boolean isLinkTable(TableDef table) { if (table.getForeignKeys().size() != 2) return false; if (sqlConnection.isReferencedByForeignKey(table.getName())) return false; List<Identifier> columns = new ArrayList<Identifier>(); for (ColumnDef qualified: table.getColumns()) { columns.add(qualified.getName()); } for (ForeignKey foreignKey: table.getForeignKeys()) { if (foreignKey.getReferencedTable().equals(table.getName())) return false; columns.removeAll(foreignKey.getLocalColumns().getColumns()); } return columns.isEmpty(); } /** * @return <code>true</code> iff the table contains this column as a local column in a foreign key */ private boolean isInForeignKey(Identifier column, TableDef table) { for (ForeignKey fk: table.getForeignKeys()) { if (fk.getLocalColumns().contains(column)) return true; } return false; } public static String dropTrailingHash(String uri) { if (!uri.endsWith("#")) { return uri; } return uri.substring(0, uri.length() - 1); } }
37.604623
545
0.685808
90a919589c902788afd7882a8e60781346c28835
4,498
package com.github.dynamobee.utils; import static java.util.Arrays.asList; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import org.reflections.Reflections; import org.springframework.context.annotation.Profile; import org.springframework.core.env.Environment; import com.github.dynamobee.changeset.ChangeEntry; import com.github.dynamobee.changeset.ChangeLog; import com.github.dynamobee.changeset.ChangeSet; import com.github.dynamobee.exception.DynamobeeChangeSetException; /** * Utilities to deal with reflections and annotations */ public class ChangeService { private static final String DEFAULT_PROFILE = "default"; private final String changeLogsBasePackage; private final List<String> activeProfiles; public ChangeService(String changeLogsBasePackage) { this(changeLogsBasePackage, null); } public ChangeService(String changeLogsBasePackage, Environment environment) { this.changeLogsBasePackage = changeLogsBasePackage; if (environment != null && environment.getActiveProfiles() != null && environment.getActiveProfiles().length > 0) { this.activeProfiles = asList(environment.getActiveProfiles()); } else { this.activeProfiles = asList(DEFAULT_PROFILE); } } public List<Class<?>> fetchChangeLogs() { Reflections reflections = new Reflections(changeLogsBasePackage); Set<Class<?>> changeLogs = reflections.getTypesAnnotatedWith(ChangeLog.class); // TODO remove dependency, do own method List<Class<?>> filteredChangeLogs = (List<Class<?>>) filterByActiveProfiles(changeLogs); Collections.sort(filteredChangeLogs, new ChangeLogComparator()); return filteredChangeLogs; } public List<Method> fetchChangeSets(final Class<?> type) throws DynamobeeChangeSetException { final List<Method> changeSets = filterChangeSetAnnotation(asList(type.getDeclaredMethods())); final List<Method> filteredChangeSets = (List<Method>) filterByActiveProfiles(changeSets); Collections.sort(filteredChangeSets, new ChangeSetComparator()); return filteredChangeSets; } public boolean isRunAlwaysChangeSet(Method changesetMethod) { if (changesetMethod.isAnnotationPresent(ChangeSet.class)) { ChangeSet annotation = changesetMethod.getAnnotation(ChangeSet.class); return annotation.runAlways(); } else { return false; } } public ChangeEntry createChangeEntry(Method changesetMethod) { if (changesetMethod.isAnnotationPresent(ChangeSet.class)) { ChangeSet annotation = changesetMethod.getAnnotation(ChangeSet.class); return new ChangeEntry( annotation.id(), annotation.author(), new Date(), changesetMethod.getDeclaringClass().getName(), changesetMethod.getName()); } else { return null; } } private boolean matchesActiveSpringProfile(AnnotatedElement element) { if (!ClassUtils.isPresent("org.springframework.context.annotation.Profile", null)) { return true; } if (!element.isAnnotationPresent(Profile.class)) { return true; // no-profiled changeset always matches } List<String> profiles = asList(element.getAnnotation(Profile.class).value()); for (String profile : profiles) { if (profile != null && profile.length() > 0 && profile.charAt(0) == '!') { if (!activeProfiles.contains(profile.substring(1))) { return true; } } else if (activeProfiles.contains(profile)) { return true; } } return false; } private List<?> filterByActiveProfiles(Collection<? extends AnnotatedElement> annotated) { List<AnnotatedElement> filtered = new ArrayList<>(); for (AnnotatedElement element : annotated) { if (matchesActiveSpringProfile(element)) { filtered.add(element); } } return filtered; } private List<Method> filterChangeSetAnnotation(List<Method> allMethods) throws DynamobeeChangeSetException { final Set<String> changeSetIds = new HashSet<>(); final List<Method> changesetMethods = new ArrayList<>(); for (final Method method : allMethods) { if (method.isAnnotationPresent(ChangeSet.class)) { String id = method.getAnnotation(ChangeSet.class).id(); if (changeSetIds.contains(id)) { throw new DynamobeeChangeSetException(String.format("Duplicated changeset id found: '%s'", id)); } changeSetIds.add(id); changesetMethods.add(method); } } return changesetMethods; } }
32.594203
121
0.756336
af0c1c5fb1b2b0c186eb1b518591cdcb7092e469
1,564
package lectureNotes.lesson5.factory; import java.util.ArrayList; import java.util.List; // Wikipedia example for factory method public class F5 { public abstract class Room { abstract void connect(Room room); } public class MagicRoom extends Room { public void connect(Room room) {} } public class OrdinaryRoom extends Room { public void connect(Room room) {} } public abstract class MazeGame { private final List<Room> rooms = new ArrayList<>(); public MazeGame() { Room room1 = makeRoom(); Room room2 = makeRoom(); room1.connect(room2); rooms.add(room1); rooms.add(room2); } // Define an abstract method to let subclass define how to build room // // Roughly obsolete pattern, since it force to inheritance. // Instead of using an abstract method, simply pass a factory as dependency abstract protected Room makeRoom(); } //////////////////////////////////////////////////////////////////////////////////////////////// public class MagicMazeGame extends MazeGame { @Override protected Room makeRoom() { return new MagicRoom(); } } public class OrdinaryMazeGame extends MazeGame { @Override protected Room makeRoom() { return new OrdinaryRoom(); } } MazeGame ordinaryGame = new OrdinaryMazeGame(); MazeGame magicGame = new MagicMazeGame(); }
26.965517
100
0.56266
2d40fe674f887ee5b4047f94003f2a1062807f1f
322
package org.portal.back.pinnacle.darts; import org.portal.back.pinnacle.Constants; import org.portal.back.pinnacle.grabber.LineGrabber; import org.springframework.stereotype.Service; @Service public class DartsLineGrabber extends LineGrabber { public DartsLineGrabber() { super(Constants.DARTS_ID); } }
23
52
0.779503
4d5c5d5f64bbb5710273fc96950560400a773c4f
1,487
package com.coditory.quark.context; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.NoSuchElementException; import java.util.Queue; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.StreamSupport; final class HierarchyIterator implements Iterator<Class<?>> { public static Set<Class<?>> getClassHierarchy(Class<?> forClass) { Iterable<Class<?>> iterable = () -> new HierarchyIterator(forClass); return StreamSupport .stream(iterable.spliterator(), false) .collect(Collectors.toSet()); } private final Queue<Class<?>> remaining = new LinkedList<>(); private final Set<Class<?>> visited = new LinkedHashSet<>(); public HierarchyIterator(Class<?> initial) { append(initial); } private void append(Class<?> toAppend) { if (toAppend != null && !visited.contains(toAppend)) { remaining.add(toAppend); visited.add(toAppend); } } @Override public boolean hasNext() { return remaining.size() > 0; } @Override public Class<?> next() { if (!hasNext()) { throw new NoSuchElementException(); } Class<?> polled = remaining.poll(); append(polled.getSuperclass()); for (Class<?> superInterface : polled.getInterfaces()) { append(superInterface); } return polled; } }
28.596154
76
0.62542
08d4a84a41ce85670060c5aea3ce2d622eed4590
2,949
package com.groupdocs.ui.annotation.annotator; import com.groupdocs.ui.annotation.entity.web.AnnotationDataEntity; import com.groupdocs.annotation.models.PageInfo; import com.groupdocs.ui.common.exception.TotalGroupDocsException; public class AnnotatorFactory { /** * <p> * Create annotator instance depending on type of annotation * </p> * * @return * @param annotationData AnnotationDataEntity * @param pageInfo PageInfo */ public static BaseAnnotator createAnnotator(AnnotationDataEntity annotationData, PageInfo pageInfo) { AnnotationDataEntity roundedAnnotationData = roundCoordinates(annotationData); switch (roundedAnnotationData.getType().toLowerCase()) { // addev .toLowerCase() case "text": case "texthighlight": //textHighlight return new TextHighlightAnnotator(roundedAnnotationData, pageInfo); case "area": return new AreaAnnotator(roundedAnnotationData, pageInfo); case "point": return new PointAnnotator(roundedAnnotationData, pageInfo); case "textstrikeout": //textStrikeout return new TextStrikeoutAnnotator(roundedAnnotationData, pageInfo); case "polyline": return new PolylineAnnotator(roundedAnnotationData, pageInfo); case "textfield": //textField return new TextFieldAnnotator(roundedAnnotationData, pageInfo); case "watermark": return new WatermarkAnnotator(roundedAnnotationData, pageInfo); case "textreplacement": //textReplacement return new TextReplacementAnnotator(roundedAnnotationData, pageInfo); case "arrow": return new ArrowAnnotator(roundedAnnotationData, pageInfo); case "textredaction": //textRedaction return new TextRedactionAnnotator(roundedAnnotationData, pageInfo); case "resourcesredaction": //resourcesRedaction return new ResourceRedactionAnnotator(roundedAnnotationData, pageInfo); case "textunderline": //textUnderline return new TextUnderlineAnnotator(roundedAnnotationData, pageInfo); case "distance": return new DistanceAnnotator(roundedAnnotationData, pageInfo); default: throw new TotalGroupDocsException("Wrong annotation data without annotation type!"); } } private static AnnotationDataEntity roundCoordinates(AnnotationDataEntity annotationData) { annotationData.setHeight((float) Math.round(annotationData.getHeight())); annotationData.setLeft((float) Math.round(annotationData.getLeft())); annotationData.setTop((float) Math.round(annotationData.getTop())); annotationData.setWidth((float) Math.round(annotationData.getWidth())); return annotationData; } }
49.15
105
0.679891
887c6215c35e45449f7f239d39bb743da93d450c
7,711
package com.edasaki.rpg.items.stats; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import com.edasaki.rpg.PlayerDataRPG; public class StatAccumulator { public int level = 1; private int damageLow = 0; private int damageHigh = 0; private int maxHP = 0; private int maxHPMultiplier = 0; private int defense = 0; private int defenseMultiplier = 0; private int speed = 0; private int critChance = 0; private int critDamage = 0; private int rarityFinder = 0; private int manaRegenRate = 0; private int spellDamage = 0; private int attackDamage = 0; private int hpRegen = 0; private int attackSpeed = 0; public void parseAndAccumulate(String s) { for (StatParser sp : StatParser.values()) { sp.parse(this, s); } } public void setDamage(int low, int high) { this.damageLow = low; this.damageHigh = high; } public void setHP(int hp) { this.maxHP = hp; } public void setHPMultiplier(int maxHPMultiplier) { this.maxHPMultiplier = maxHPMultiplier; } public void setDefense(int defense) { this.defense = defense; } public void setDefenseMultiplier(int defenseMultiplier) { this.defenseMultiplier = defenseMultiplier; } public void setCritChance(int chance) { this.critChance = chance; } public void setCritDamage(int damage) { this.critDamage = damage; } public void setRarityFinder(int percent) { this.rarityFinder = percent; } public void setManaRegenRate(int percent) { this.manaRegenRate = percent; } public void setSpeed(int speed) { this.speed = speed; } public void setSpellDamage(int spellDamage) { this.spellDamage = spellDamage; } public void setAttackDamage(int val) { this.attackDamage = val; } public void setHPRegen(int val) { this.hpRegen = val; } public void setAttackSpeed(int val) { this.attackSpeed = val; } public void setSage(boolean sage) { // only use multiply so that stats that are originally 0 are still 0 this.damageLow *= 1.2; this.damageHigh *= 1.2; this.maxHP *= 1.2; this.maxHPMultiplier *= 1.1; this.defense *= 1.2; this.defenseMultiplier *= 1.1; this.critChance *= 1.3; this.critDamage *= 1.1; } public static void clearStats(PlayerDataRPG pd) { pd.damageLow = 0; pd.damageHigh = 0; pd.maxHP = 0; pd.maxHPMultiplier = 0; pd.defense = 0; pd.defenseMultiplier = 0; pd.speed = 0; pd.critChance = 0; pd.critDamage = 150; pd.rarityFinder = 0; pd.manaRegenRate = 0; pd.spellDamage = 0; pd.attackDamage = 0; pd.lifesteal = 0; pd.hpRegen = 0; pd.attackSpeed = 0; } public void apply(PlayerDataRPG pd) { pd.damageLow += damageLow; pd.damageHigh += damageHigh; pd.maxHP += maxHP; pd.maxHPMultiplier += maxHPMultiplier; pd.defense += defense; pd.defenseMultiplier += defenseMultiplier; pd.speed += speed; pd.critChance += critChance; pd.critDamage += critDamage; pd.rarityFinder += rarityFinder; pd.manaRegenRate += manaRegenRate; pd.spellDamage += spellDamage; pd.attackDamage += attackDamage; // pd.lifesteal += lifesteal; pd.hpRegen += hpRegen; pd.attackSpeed += attackSpeed; // ##### // DON'T FORGET TO ADD TO LORE LOL (SCROLL DOWN) // ##### } public static void finalizeStats(PlayerDataRPG pd) { // multipliers are applied here and nowhere else pd.maxHPMultiplier /= 100; pd.maxHP += (int) Math.ceil((pd.baseMaxHP + pd.maxHP) * pd.maxHPMultiplier); pd.defenseMultiplier /= 100; pd.defense += (int) Math.ceil(pd.defense * pd.defenseMultiplier); pd.speed /= 100; //+50% speed -> 0.5 pd.speed++; //0.5 -> 1.5 pd.speed *= 0.2; //1.5 -> 0.3 [base player speed is 0.2] if (pd.speed > 1.0) pd.speed = 1.0f; pd.getPlayer().setWalkSpeed(pd.speed); pd.critChance /= 100; pd.critDamage /= 100; pd.spellDamage /= 100; pd.spellDamage++; pd.attackDamage /= 100; pd.attackDamage++; pd.lifesteal /= 100; pd.hpRegen /= 100; pd.hpRegen++; pd.attackSpeed /= 100; //can't do 0 base damage if (pd.damageLow < 1) pd.damageLow = 1; if (pd.damageHigh < 1) pd.damageHigh = 1; } public List<String> lore() { ArrayList<String> lore = new ArrayList<String>(); boolean space = true; lore.add(StatParser.LEVEL.format(level)); if (damageLow > 0 && damageHigh > 0) { lore.add(StatParser.DAMAGE.format(damageLow, damageHigh)); } space = checkSpace(space, lore); if (maxHP > 0) { lore.add(StatParser.HP.format(maxHP)); space = true; } if (maxHPMultiplier > 0) { lore.add(StatParser.HP_MULT.format(maxHPMultiplier)); space = true; } if (defense > 0) { lore.add(StatParser.DEFENSE.format(defense)); space = true; } if (defenseMultiplier > 0) { lore.add(StatParser.DEFENSE_MULT.format(defenseMultiplier)); space = true; } space = checkSpace(space, lore); if (critChance > 0) { lore.add(StatParser.CRIT_CHANCE.format(critChance)); space = true; } if (critDamage > 0) { lore.add(StatParser.CRIT_DAMAGE.format(critDamage)); space = true; } space = checkSpace(space, lore); if (rarityFinder > 0) { lore.add(StatParser.RARITY_FINDER.format(rarityFinder)); space = true; } if (manaRegenRate > 0) { lore.add(StatParser.MANA_REGEN.format(manaRegenRate)); space = true; } if (speed > 0) { lore.add(StatParser.SPEED.format(speed)); space = true; } if (spellDamage > 0) { lore.add(StatParser.SPELL_DAMAGE.format(spellDamage)); space = true; } if (attackDamage > 0) { lore.add(StatParser.ATTACK_DAMAGE.format(attackDamage)); space = true; } if (hpRegen > 0) { lore.add(StatParser.HP_REGEN.format(hpRegen)); space = true; } if (attackSpeed > 0) { lore.add(StatParser.ATTACK_SPEED.format(attackSpeed)); space = true; } space = checkSpace(space, lore); if (lore.size() > 0 && lore.get(lore.size() - 1).length() == 0) lore.remove(lore.size() - 1); return lore; } private boolean checkSpace(boolean needsSpace, ArrayList<String> lore) { if (needsSpace) lore.add(""); return false; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (Field f : StatAccumulator.class.getDeclaredFields()) { try { sb.append(f.toString() + ":" + f.get(this) + ", "); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return sb.toString(); } }
29.208333
84
0.556737
2d5d9eee4527d19ba54486e3472506b0689dd033
1,292
package de.jeff_media.updatechecker; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; class InternalUpdateCheckListener implements Listener { private final UpdateChecker instance; InternalUpdateCheckListener() { instance = UpdateChecker.getInstance(); } @EventHandler public void notifyOnJoin(PlayerJoinEvent playerJoinEvent) { Player player = playerJoinEvent.getPlayer(); if ((player.isOp() && instance.isNotifyOpsOnJoin()) || (instance.getNotifyPermission() != null && player.hasPermission(instance.getNotifyPermission()))) { Messages.printCheckResultToPlayer(player, false); } } @EventHandler public void onUpdateCheck(UpdateCheckEvent event) { if (!instance.isNotifyRequesters()) return; if (event.getRequesters() == null) return; for (CommandSender commandSender : event.getRequesters()) { if (commandSender instanceof Player) { Messages.printCheckResultToPlayer((Player) commandSender, true); } else { Messages.printCheckResultToConsole(event); } } } }
32.3
162
0.68808
dae33c20352c204fe29a8dc4d3645ccff16982f0
2,704
package com.androidufo.demo; import android.Manifest; import android.content.Intent; import android.view.View; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import androidx.core.app.ActivityCompat; import com.androidufo.demo.configs.ConfigsActivity; import com.androidufo.demo.download.DownloadActivity; import com.androidufo.demo.get.GetActivity; import com.androidufo.demo.post.PostActivity; import com.androidufo.demo.upload.UploadActivity; import com.androidufo.demo.urlenv.MultipleUrlEnvActivity; public class MainActivity extends AppCompatActivity implements View.OnClickListener { public static final int CODE = 1001; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btnGet).setOnClickListener(this); findViewById(R.id.btnGet).setOnClickListener(this); findViewById(R.id.btnPost).setOnClickListener(this); findViewById(R.id.btnDownload).setOnClickListener(this); findViewById(R.id.btnUpload).setOnClickListener(this); findViewById(R.id.btnMultipleUrlEnv).setOnClickListener(this); findViewById(R.id.btnHttpConfigs).setOnClickListener(this); // 注意:获取sdcard权限,这里为了让代码看起来更加简单,就不特别处理是否授予权限,要使用demo就必须授权 ActivityCompat.requestPermissions( this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, CODE ); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnGet: goGet(); break; case R.id.btnPost: goPost(); break; case R.id.btnDownload: goDownload(); break; case R.id.btnUpload: goUpload(); break; case R.id.btnMultipleUrlEnv: goMultipleUrlEnv(); break; case R.id.btnHttpConfigs: goHttpConfigs(); break; } } private void goHttpConfigs() { go(ConfigsActivity.class); } private void goMultipleUrlEnv() { go(MultipleUrlEnvActivity.class); } private void goUpload() { go(UploadActivity.class); } private void goDownload() { go(DownloadActivity.class); } private void goPost() { go(PostActivity.class); } private void goGet() { go(GetActivity.class); } private void go(Class<?> act) { startActivity(new Intent(this, act)); } }
29.391304
85
0.634615
17b04b11606f7b6f28710815640d6c216f42bc89
124
package pl.edu.agh.dsm.common.security; public interface AutorizationContext { public ApplicationUser getActiveUser(); }
17.714286
40
0.806452
52d456dfe2010316e7e2052297051d2aa5a1a8b4
1,022
package com.wwwjf.wlibrary.base; import com.wwwjf.mvplibrary.IMvpView; import com.wwwjf.mvplibrary.base.BaseMvpPresenter; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; public abstract class BasePresenter<T extends IMvpView> extends BaseMvpPresenter<T> { private CompositeDisposable compositeDisposable; public BasePresenter(T view) { super(view); compositeDisposable = new CompositeDisposable(); } /** * 添加订阅 * * @param disposables 订阅 */ public void addSubscription(Disposable... disposables) { compositeDisposable.addAll(disposables); } /** * 移除订阅 */ public void removeSubscription() { if (compositeDisposable != null && !compositeDisposable.isDisposed()) { compositeDisposable.dispose(); compositeDisposable.clear(); } } @Override public void onDestroy() { super.onDestroy(); removeSubscription(); } }
23.227273
85
0.663405
ce30f89b2ce234075b51f9d9dc052d423ce0004e
2,226
package com.homework.lovedog.bean; import com.homework.lovedog.dbmanager.DogInfoDbManager; import com.homework.lovedog.utils.dbutils.DbManager; import com.homework.lovedog.utils.dbutils.db.annotation.Column; import com.homework.lovedog.utils.dbutils.db.annotation.Table; @Table(name = DogInfoDbManager.DOG_ITEM_TABLE) public class DogItem { public static final String COLUMN_ID = "id"; public static final String COLUMN_PET_ID = "petID"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_ENG_NAME = "engName"; public static final String COLUMN_PRICE = "price"; public static final String COLUMN_EN_PRICE = "enPrice"; public static final String COLUMN_COVER_URL = "coverURL"; @Column(name = COLUMN_ID, isId = true, autoGen = true) private int id; @Column(name = COLUMN_PET_ID) private int petID; @Column(name = COLUMN_NAME) private String name; @Column(name = COLUMN_ENG_NAME) private String engName; @Column(name = COLUMN_PRICE) private String price; @Column(name = COLUMN_EN_PRICE) private String enPrice; @Column(name = COLUMN_COVER_URL) private String coverURL; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getPetID() { return petID; } public void setPetID(int petID) { this.petID = petID; } public java.lang.String getName() { return name; } public void setName(java.lang.String name) { this.name = name; } public java.lang.String getEngName() { return engName; } public void setEngName(java.lang.String engName) { this.engName = engName; } public java.lang.String getPrice() { return price; } public void setPrice(java.lang.String price) { this.price = price; } public java.lang.String getEnPrice() { return enPrice; } public void setEnPrice(java.lang.String enPrice) { this.enPrice = enPrice; } public String getCoverURL() { return coverURL; } public void setCoverURL(String coverURL) { this.coverURL = coverURL; } }
24.733333
63
0.659479
5592ad9b68f90d04a98a59a7dd7e5edd50c880de
16,895
package org.cqframework.cql.cql2elm; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.testng.Assert.assertTrue; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.cqframework.cql.cql2elm.LibraryBuilder.SignatureLevel; import org.hl7.cql_annotations.r1.CqlToElmError; import org.hl7.elm.r1.*; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class LibraryTests { ModelManager modelManager; LibraryManager libraryManager; @BeforeClass public void setup() { modelManager = new ModelManager(); libraryManager = new LibraryManager(modelManager); libraryManager.getLibrarySourceLoader().registerProvider(new TestLibrarySourceProvider()); } @AfterClass public void tearDown() { libraryManager.getLibrarySourceLoader().clearProviders(); } @Test public void testLibraryReferences() { CqlTranslator translator = null; try { translator = CqlTranslator.fromStream(LibraryTests.class.getResourceAsStream("LibraryTests/ReferencingLibrary.cql"), modelManager, libraryManager); assertThat(translator.getErrors().size(), is(0)); } catch (IOException e) { e.printStackTrace(); } } @Test public void testLibraryReferencesWithCacheDisabled() { CqlTranslator translator = null; try { translator = CqlTranslator.fromStream(LibraryTests.class.getResourceAsStream("LibraryTests/ReferencingLibrary.cql"), modelManager, libraryManager.withDisableCache()); assertThat(translator.getErrors().size(), is(0)); } catch (IOException e) { e.printStackTrace(); } } @Test public void testIncludedLibraryWithSignatures() { CqlTranslator translator = null; libraryManager = new LibraryManager(modelManager); libraryManager.getLibrarySourceLoader().registerProvider(new TestLibrarySourceProvider()); try { translator = CqlTranslator.fromStream(LibraryTests.class.getResourceAsStream("LibraryTests/ReferencingLibrary.cql"), modelManager, libraryManager, CqlTranslatorException.ErrorSeverity.Info, SignatureLevel.All); assertThat(translator.getErrors().size(), is(0)); Map<String, ExpressionDef> includedLibDefs = new HashMap<>(); Map<String, Library> includedLibraries = translator.getLibraries(); includedLibraries.values().stream().forEach(includedLibrary -> { if (includedLibrary.getStatements() != null) { for (ExpressionDef def : includedLibrary.getStatements().getDef()) { includedLibDefs.put(def.getName(), def); } } }); ExpressionDef baseLibDef = includedLibDefs.get("BaseLibSum"); assertThat(((AggregateExpression)baseLibDef.getExpression()).getSignature().size(), is(1)); } catch (IOException e) { e.printStackTrace(); } } @Test public void testInvalidLibraryReferences() { CqlTranslator translator = null; try { translator = CqlTranslator.fromStream(LibraryTests.class.getResourceAsStream("LibraryTests/InvalidReferencingLibrary.cql"), modelManager, libraryManager); assertThat(translator.getErrors().size(), is(not(0))); } catch (IOException e) { e.printStackTrace(); } } @Test public void testInvalidLibraryReference() { CqlTranslator translator = null; try { translator = CqlTranslator.fromStream(LibraryTests.class.getResourceAsStream("LibraryTests/InvalidLibraryReference.cql"), modelManager, libraryManager); assertThat(translator.getErrors().size(), is(not(0))); } catch (IOException e) { e.printStackTrace(); } } @Test public void testDuplicateExpressionLibrary() { CqlTranslator translator = null; try { translator = CqlTranslator.fromStream(LibraryTests.class.getResourceAsStream("LibraryTests/DuplicateExpressionLibrary.cql"), modelManager, libraryManager); assertThat(translator.getErrors().size(), is(1)); } catch (IOException e) { e.printStackTrace(); } } @Test public void testMissingLibrary() { CqlTranslator translator = null; try { translator = CqlTranslator.fromStream(LibraryTests.class.getResourceAsStream("LibraryTests/MissingLibrary.cql"), modelManager, libraryManager); assertThat(translator.getErrors().size(), is(1)); assertThat(translator.getErrors().get(0), instanceOf(CqlSemanticException.class)); assertThat(translator.getErrors().get(0).getCause(), instanceOf(IllegalArgumentException.class)); } catch (IOException e) { e.printStackTrace(); } } @Test public void testInvalidBaseLibrary() { CqlTranslator translator = null; try { translator = CqlTranslator.fromStream(LibraryTests.class.getResourceAsStream("LibraryTests/ReferencingInvalidBaseLibrary.cql"), modelManager, libraryManager); assertThat(translator.getErrors().size(), is(1)); assertThat(translator.getErrors().get(0), instanceOf(CqlTranslatorException.class)); assertThat(translator.getErrors().get(0).getLocator(), notNullValue()); assertThat(translator.getErrors().get(0).getLocator().getLibrary(), notNullValue()); assertThat(translator.getErrors().get(0).getLocator().getLibrary().getId(), is("InvalidBaseLibrary")); assertThat(translator.toELM(), notNullValue()); assertThat(translator.toELM().getAnnotation(), notNullValue()); assertThat(translator.toELM().getAnnotation().size(), greaterThan(0)); CqlToElmError invalidBaseLibraryError = null; for (Object o : translator.toELM().getAnnotation()) { if (o instanceof CqlToElmError) { invalidBaseLibraryError = (CqlToElmError)o; break; } } assertThat(invalidBaseLibraryError, notNullValue()); assertThat(invalidBaseLibraryError.getLibraryId(), is("InvalidBaseLibrary")); } catch (IOException e) { e.printStackTrace(); } } // This test verifies that when a model load failure prevents proper creation of the context expression, that doesn't lead to internal translator errors. @Test public void testMixedVersionModelReferences() { CqlTranslator translator = null; try { translator = CqlTranslator.fromStream(LibraryTests.class.getResourceAsStream("LibraryTests/TestMeasure.cql"), modelManager, libraryManager); assertThat(translator.getErrors().size(), is(3)); for (CqlTranslatorException error : translator.getErrors()) { assertThat(error.getLocator(), notNullValue()); } } catch (IOException e) { e.printStackTrace(); } } @Test public void testTranslatorOptionsFlowDownWithAnnotations() { try { // Test Annotations are created for both libraries CqlTranslator translator = null; libraryManager = new LibraryManager(modelManager); libraryManager.getLibrarySourceLoader().registerProvider(new TestLibrarySourceProvider()); translator = CqlTranslator.fromStream(LibraryTests.class.getResourceAsStream("LibraryTests/ReferencingLibrary.cql"), modelManager, libraryManager, CqlTranslatorException.ErrorSeverity.Info, SignatureLevel.All, CqlTranslator.Options.EnableAnnotations); assertThat(translator.getErrors().size(), is(0)); Map<String, Library> includedLibraries = translator.getLibraries(); includedLibraries.values().stream().forEach(includedLibrary -> { // Ensure that some annotations are present. assertTrue(includedLibrary.getStatements().getDef().stream().filter(x -> x.getAnnotation().size() > 0).count() > 0); }); } catch (IOException e) { e.printStackTrace(); } } @Test public void testTranslatorOptionsFlowDownWithoutAnnotations() { try { // Test Annotations are created for both libraries CqlTranslator translator = null; libraryManager = new LibraryManager(modelManager); libraryManager.getLibrarySourceLoader().registerProvider(new TestLibrarySourceProvider()); translator = CqlTranslator.fromStream(LibraryTests.class.getResourceAsStream("LibraryTests/ReferencingLibrary.cql"), modelManager, libraryManager, CqlTranslatorException.ErrorSeverity.Info, SignatureLevel.All); assertThat(translator.getErrors().size(), is(0)); Map<String, Library> includedLibraries = translator.getLibraries(); includedLibraries.values().stream().forEach(includedLibrary -> { // Ensure that no annotations are present. assertTrue(includedLibrary.getStatements().getDef().stream().filter(x -> x.getAnnotation().size() > 0).count() == 0); }); } catch (IOException e) { e.printStackTrace(); } } @Test public void testSynaxErrorWithNoLibrary() throws IOException { // Syntax errors in anonymous libraries are reported with the name of the source file as the library identifier CqlTranslator translator = TestUtils.createTranslator("LibraryTests/SyntaxErrorWithNoLibrary.cql"); assertThat(translator.getErrors().size(), greaterThanOrEqualTo(1)); assertThat(translator.getErrors().get(0).getLocator().getLibrary().getId(), equalTo("SyntaxErrorWithNoLibrary")); } @Test public void testSynaxErrorWithNoLibraryFromStream() throws IOException { // Syntax errors in anonymous libraries are reported with the name of the source file as the library identifier CqlTranslator translator = TestUtils.createTranslatorFromStream("LibraryTests/SyntaxErrorWithNoLibrary.cql"); assertThat(translator.getErrors().size(), greaterThanOrEqualTo(1)); assertThat(translator.getErrors().get(0).getLocator().getLibrary().getId(), equalTo("Anonymous")); } @Test public void testSyntaxErrorWithLibrary() throws IOException { CqlTranslator translator = TestUtils.createTranslator("LibraryTests/SyntaxErrorWithLibrary.cql"); assertThat(translator.getErrors().size(), greaterThanOrEqualTo(1)); assertThat(translator.getErrors().get(0).getLocator().getLibrary().getId(), equalTo("SyntaxErrorWithLibrary")); } @Test public void testSyntaxErrorWithLibraryFromStream() throws IOException { CqlTranslator translator = TestUtils.createTranslatorFromStream("LibraryTests/SyntaxErrorWithLibrary.cql"); assertThat(translator.getErrors().size(), greaterThanOrEqualTo(1)); assertThat(translator.getErrors().get(0).getLocator().getLibrary().getId(), equalTo("SyntaxErrorWithLibrary")); } @Test public void testSyntaxErrorReferencingLibrary() throws IOException { CqlTranslator translator = TestUtils.createTranslator("LibraryTests/SyntaxErrorReferencingLibrary.cql"); assertThat(translator.getErrors().size(), greaterThanOrEqualTo(2)); assertThat(translator.getErrors().get(0).getLocator().getLibrary().getId(), equalTo("SyntaxErrorReferencingLibrary")); assertThat(translator.getErrors().get(1).getLocator().getLibrary().getId(), equalTo("SyntaxErrorWithLibrary")); } @Test public void testSyntaxErrorReferencingLibraryFromStream() throws IOException { CqlTranslator translator = TestUtils.createTranslatorFromStream("LibraryTests/SyntaxErrorReferencingLibrary.cql"); assertThat(translator.getErrors().size(), greaterThanOrEqualTo(2)); assertThat(translator.getErrors().get(0).getLocator().getLibrary().getId(), equalTo("SyntaxErrorReferencingLibrary")); assertThat(translator.getErrors().get(1).getLocator().getLibrary().getId(), equalTo("SyntaxErrorWithLibrary")); } private ExpressionDef getExpressionDef(Library library, String name) { for (ExpressionDef def : library.getStatements().getDef()) { if (def.getName().equals(name)) { return def; } } throw new IllegalArgumentException(String.format("Could not resolve name %s", name)); } @Test public void testFluentFunctions1() throws IOException { CqlTranslator translator = TestUtils.createTranslatorFromStream("LibraryTests/TestFluent3.cql"); assertThat(translator.getErrors().size(), equalTo(0)); Library library = translator.toELM(); ExpressionDef def = getExpressionDef(library, "Test"); assertThat(def, notNullValue()); Expression e = def.getExpression(); assertThat(e, notNullValue()); assertThat(e, instanceOf(Equal.class)); Equal eq = (Equal)e; assertThat(eq.getOperand(), notNullValue()); assertThat(eq.getOperand().size(), equalTo(2)); assertThat(eq.getOperand().get(0), instanceOf(FunctionRef.class)); assertThat(((FunctionRef)eq.getOperand().get(0)).getLibraryName(), equalTo("TestFluent1")); } @Test public void testFluentFunctions2() throws IOException { CqlTranslator translator = TestUtils.createTranslatorFromStream("LibraryTests/TestFluent4.cql"); assertThat(translator.getErrors().size(), equalTo(0)); Library library = translator.toELM(); ExpressionDef def = getExpressionDef(library, "Test"); assertThat(def, notNullValue()); Expression e = def.getExpression(); assertThat(e, notNullValue()); assertThat(e, instanceOf(Equal.class)); Equal eq = (Equal)e; assertThat(eq.getOperand(), notNullValue()); assertThat(eq.getOperand().size(), equalTo(2)); assertThat(eq.getOperand().get(0), instanceOf(FunctionRef.class)); assertThat(((FunctionRef)eq.getOperand().get(0)).getLibraryName(), equalTo("TestFluent2")); } @Test public void testFluentFunctions5() throws IOException { CqlTranslator translator = TestUtils.createTranslatorFromStream("LibraryTests/TestFluent5.cql"); assertThat(translator.getErrors().size(), equalTo(1)); // Expects invalid invocation assertThat(translator.getErrors().get(0).getMessage(), equalTo("Operator invalidInvocation with signature (System.String) is a fluent function and can only be invoked with fluent syntax.")); } @Test public void testFluentFunctions6() throws IOException { CqlTranslator translator = TestUtils.createTranslatorFromStream("LibraryTests/TestFluent6.cql"); assertThat(translator.getErrors().size(), equalTo(1)); // Expects invalid fluent invocation assertThat(translator.getErrors().get(0).getMessage(), equalTo("Invocation of operator invalidInvocation with signature (System.String) uses fluent syntax, but the operator is not defined as a fluent function.")); } @Test public void testFluentFunctions7() throws IOException { CqlTranslator translator = TestUtils.createTranslatorFromStream("LibraryTests/TestFluent7.cql"); assertThat(translator.getErrors().size(), equalTo(0)); Library library = translator.toELM(); ExpressionDef def = getExpressionDef(library, "Test"); assertThat(def, notNullValue()); Expression e = def.getExpression(); assertThat(e, notNullValue()); assertThat(e, instanceOf(Equal.class)); Equal eq = (Equal)e; assertThat(eq.getOperand(), notNullValue()); assertThat(eq.getOperand().size(), equalTo(2)); assertThat(eq.getOperand().get(0), instanceOf(FunctionRef.class)); assertThat(((FunctionRef)eq.getOperand().get(0)).getLibraryName(), equalTo("TF1")); } @Test public void testInvalidInvocation() throws IOException { CqlTranslator translator = TestUtils.createTranslatorFromStream("LibraryTests/TestInvalidFunction.cql"); assertThat(translator.getErrors().size(), equalTo(1)); assertThat(translator.getErrors().get(0).getMessage(), equalTo("Could not resolve call to operator invalidInvocation with signature ().")); } }
47.061281
221
0.671323
c57c4d33fd4abac71b557d85eb359e75c2b8ea40
447
/** * */ package com.lq.work.modules.gen.dao; import com.lq.work.common.persistence.CrudDao; import com.lq.work.common.persistence.annotation.MyBatisDao; import com.lq.work.modules.gen.entity.GenTable; import com.lq.work.modules.gen.entity.GenTableColumn; /** * 业务表字段DAO接口 * * @version 2013-10-15 */ @MyBatisDao public interface GenTableColumnDao extends CrudDao<GenTableColumn> { public void deleteByGenTableId(GenTable genTable); }
21.285714
68
0.767338
f62aa2ee5202420134cd0256ae7a4388017c84af
5,447
package sh.isaac.solor.rf2; /* * aks8m - 9/6/18 */ import sh.isaac.MetaData; import sh.isaac.api.Get; import sh.isaac.api.bootstrap.TermAux; import sh.isaac.api.chronicle.Chronology; import sh.isaac.api.chronicle.LatestVersion; import sh.isaac.api.component.concept.ConceptChronology; import sh.isaac.api.component.semantic.SemanticChronology; import sh.isaac.api.observable.ObservableSnapshotService; import sh.isaac.api.observable.semantic.version.ObservableStringVersion; import sh.isaac.api.util.UuidT5Generator; import sh.isaac.solor.utility.ExportLookUpCache; import sh.komet.gui.manifold.Manifold; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; public class RF2ExportHelper { private Manifold manifold; private static ObservableSnapshotService snapshotService; public RF2ExportHelper(Manifold manifold) { this.manifold = manifold; snapshotService = Get.observableSnapshotService(manifold); } public ObservableSnapshotService getSnapshotService() { return snapshotService; } public StringBuilder getRF2CommonElements(Chronology chronology){ int stampNid = 0; if(chronology instanceof ConceptChronology) stampNid = snapshotService.getObservableConceptVersion(chronology.getNid()).getStamps().findFirst().getAsInt(); else if(chronology instanceof SemanticChronology) stampNid = snapshotService.getObservableSemanticVersion(chronology.getNid()).getStamps().findFirst().getAsInt(); return new StringBuilder() .append(getIdString(chronology) + "\t") //id .append(getTimeString(stampNid) + "\t") //time .append(getActiveString(stampNid) + "\t") //active .append(getModuleString(stampNid) + "\t"); //moduleId } public StringBuilder getRF2CommonElements(Chronology chronology, UUID uuid){ int stampNid = 0; if(chronology instanceof ConceptChronology) stampNid = snapshotService.getObservableConceptVersion(chronology.getNid()).getStamps().findFirst().getAsInt(); else if(chronology instanceof SemanticChronology) stampNid = snapshotService.getObservableSemanticVersion(chronology.getNid()).getStamps().findFirst().getAsInt(); return new StringBuilder() .append(uuid.toString() + "\t") //id .append(getTimeString(stampNid) + "\t") //time .append(getActiveString(stampNid) + "\t") //active .append(getModuleString(stampNid) + "\t"); //moduleId } String getIdString(Chronology chronology){ if (ExportLookUpCache.isSCTID(chronology)) { return lookUpIdentifierFromSemantic(snapshotService, TermAux.SNOMED_IDENTIFIER.getNid(), chronology); } else if (ExportLookUpCache.isLoinc(chronology)) { final String loincId = lookUpIdentifierFromSemantic(snapshotService, MetaData.LOINC_ID_ASSEMBLAGE____SOLOR.getNid(), chronology); return UuidT5Generator.makeSolorIdFromLoincId(loincId); } else if (ExportLookUpCache.isRxNorm(chronology)) { final String rxnormId = lookUpIdentifierFromSemantic(snapshotService, MetaData.RXNORM_CUI____SOLOR.getNid(), chronology); return UuidT5Generator.makeSolorIdFromRxNormId(rxnormId); } else { return UuidT5Generator.makeSolorIdFromUuid(chronology.getPrimordialUuid()); } } String getIdString(int nID){ Chronology chronology = null; switch (Get.identifierService().getObjectTypeForComponent(nID)){ case CONCEPT: chronology = Get.concept(nID); break; case SEMANTIC: chronology = Get.assemblageService().getSemanticChronology(nID); break; } return chronology != null? getIdString(chronology) : "null_chronology"; } private String getTimeString(int stampNid){ return new SimpleDateFormat("YYYYMMdd").format(new Date(Get.stampService().getTimeForStamp(stampNid))); } private String getActiveString(int stampNid){ return Get.stampService().getStatusForStamp(stampNid).isActive() ? "1" : "0"; } private String getModuleString(int stampNid){ ConceptChronology moduleConcept = Get.concept(Get.stampService().getModuleNidForStamp(stampNid)); if (ExportLookUpCache.isSCTID(moduleConcept)) { return lookUpIdentifierFromSemantic(snapshotService, TermAux.SNOMED_IDENTIFIER.getNid(), moduleConcept); } else { return UuidT5Generator.makeSolorIdFromUuid(moduleConcept.getPrimordialUuid()); } } private String lookUpIdentifierFromSemantic(ObservableSnapshotService snapshotService , int identifierAssemblageNid, Chronology chronology){ LatestVersion<ObservableStringVersion> stringVersion = (LatestVersion<ObservableStringVersion>) snapshotService.getObservableSemanticVersion( chronology.getSemanticChronologyList().stream() .filter(semanticChronology -> semanticChronology.getAssemblageNid() == identifierAssemblageNid) .findFirst().get().getNid() ); return stringVersion.isPresent() ? stringVersion.get().getString() : ""; } }
40.051471
141
0.684964