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
ea96eea99b10f5e1a051f1d5d07268767d15c854
756
package org.firstinspires.ftc.teamcode.MPC.geometry; import java.text.DecimalFormat; public class Circle2d extends Translation2d { private double radius; public Circle2d(double x, double y, double radius) { super(x, y); setRadius(radius); } public Circle2d(Translation2d translation, double radius) { super(translation); setRadius(radius); } public double getRadius() { return radius; } public void setRadius(double radius) { this.radius = radius; } @Override public String toString() { final DecimalFormat format = new DecimalFormat("#0.000"); return format.format(x_) + "," + format.format(y_) + "," + format.format(getRadius()); } }
22.909091
94
0.634921
da362f1431f5d877392e3e042b29a07b7d547923
358
package cn.aradin.spring.lts.starter; import org.springframework.context.annotation.Configuration; import com.github.ltsopensource.spring.boot.annotation.EnableJobClient; import com.github.ltsopensource.spring.boot.annotation.EnableTaskTracker; @Configuration @EnableTaskTracker @EnableJobClient public class AradinLtsAutoConfiguration { }
25.571429
74
0.824022
86fefbe4763b1ba1c176fd0811b39a2f1080995a
1,740
package com.artsafin.tgalarm.bot.routing; import com.artsafin.tgalarm.alarm.ScheduledAlarm; import com.artsafin.tgalarm.bot.command.*; import com.artsafin.tgalarm.bot.user.UserSession; import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.Update; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MessageRouter implements Router, ChainableRouter { private Router successor; @Override public Command route(Update update, UserSession session) throws UnprocessableUpdateException { Message inputMessage = Optional.ofNullable(update.getMessage()).orElse(update.getEditedMessage()); if (inputMessage == null || !inputMessage.hasText()) { return passToSuccessor(update, session); } if (update.hasEditedMessage()) { return new UpdateAlarmCommand( ScheduledAlarm.createId(session.userId, update.getEditedMessage().getMessageId()), inputMessage.getText() ); } if (inputMessage.getText().equals("/alarms")) { return new ListAlarmsCommand(); } Matcher alarmMatcher = Pattern.compile("/alarm(\\d+)").matcher(inputMessage.getText()); if (alarmMatcher.matches()) { return new ShowIndividualAlarmCommand(alarmMatcher.group(1)); } return new NewAlarmCommand(inputMessage.getText(), update.getMessage().getMessageId()); } @Override public Router setSuccessor(Router successor) { this.successor = successor; return this; } @Override public Router getSuccessor() { return successor; } }
32.222222
106
0.678161
2d2484602a951aea2b2476d495a75ec1c82334ed
4,388
package org.hisp.dhis.coldchain.catalog; import static org.hisp.dhis.i18n.I18nUtils.getCountByName; import static org.hisp.dhis.i18n.I18nUtils.getObjectsBetween; import static org.hisp.dhis.i18n.I18nUtils.getObjectsBetweenByName; import java.util.Collection; import org.hisp.dhis.i18n.I18nService; import org.springframework.transaction.annotation.Transactional; @Transactional public class DefaultCatalogTypeAttributeService implements CatalogTypeAttributeService { // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- private CatalogTypeAttributeStore catalogTypeAttributeStore; public void setCatalogTypeAttributeStore( CatalogTypeAttributeStore catalogTypeAttributeStore ) { this.catalogTypeAttributeStore = catalogTypeAttributeStore; } private I18nService i18nService; public void setI18nService( I18nService service ) { i18nService = service; } // ------------------------------------------------------------------------- // CatalogTypeAttribute // ------------------------------------------------------------------------- /* @Override public int addCatalogTypeAttribute( CatalogTypeAttribute catalogTypeAttribute ) { return catalogTypeAttributeStore.addCatalogTypeAttribute( catalogTypeAttribute ); } @Override public void deleteCatalogTypeAttribute( CatalogTypeAttribute catalogTypeAttribute ) { catalogTypeAttributeStore.deleteCatalogTypeAttribute( catalogTypeAttribute ); } @Override public Collection<CatalogTypeAttribute> getAllCatalogTypeAttributes() { return catalogTypeAttributeStore.getAllCatalogTypeAttributes(); } @Transactional @Override public void updateCatalogTypeAttribute( CatalogTypeAttribute catalogTypeAttribute ) { catalogTypeAttributeStore.updateCatalogTypeAttribute( catalogTypeAttribute ); } @Override public CatalogTypeAttribute getCatalogTypeAttribute( int id ) { return catalogTypeAttributeStore.getCatalogTypeAttribute( id ); } @Override public CatalogTypeAttribute getCatalogTypeAttributeByName( String name ) { return catalogTypeAttributeStore.getCatalogTypeAttributeByName( name ); } */ // ------------------------------------------------------------------------- // CatalogTypeAttribute // ------------------------------------------------------------------------- @Override public int addCatalogTypeAttribute( CatalogTypeAttribute catalogTypeAttribute ) { return catalogTypeAttributeStore.save( catalogTypeAttribute ); } @Override public void deleteCatalogTypeAttribute( CatalogTypeAttribute catalogTypeAttribute ) { catalogTypeAttributeStore.delete( catalogTypeAttribute ); } @Override public void updateCatalogTypeAttribute( CatalogTypeAttribute catalogTypeAttribute ) { catalogTypeAttributeStore.update( catalogTypeAttribute ); } @Override public Collection<CatalogTypeAttribute> getAllCatalogTypeAttributes() { return catalogTypeAttributeStore.getAllCatalogTypeAttributes(); } @Override public CatalogTypeAttribute getCatalogTypeAttribute( int id ) { return catalogTypeAttributeStore.getCatalogTypeAttribute( id ); } @Override public CatalogTypeAttribute getCatalogTypeAttributeByName( String name ) { return catalogTypeAttributeStore.getCatalogTypeAttributeByName( name ); } //Methods public int getCatalogTypeAttributeCount() { return catalogTypeAttributeStore.getCount(); } public int getCatalogTypeAttributeCountByName( String name ) { return getCountByName( i18nService, catalogTypeAttributeStore, name ); } public Collection<CatalogTypeAttribute> getCatalogTypeAttributesBetween( int first, int max ) { return getObjectsBetween( i18nService, catalogTypeAttributeStore, first, max ); } public Collection<CatalogTypeAttribute> getCatalogTypeAttributesBetweenByName( String name, int first, int max ) { return getObjectsBetweenByName( i18nService, catalogTypeAttributeStore, name, first, max ); } }
34.825397
116
0.663856
e83c3b37b1fc3bca4583d7a9f7c6bc8fed808662
2,547
import twitter4j.*; import java.io.IOException; import java.util.ArrayList; public final class PrintFilterStream { public static void main(String[] args) throws TwitterException, IOException { final Preprocesser Preproc; Preproc= new Preprocesser(); Preproc.preparefiles(); System.out.println("File Prepared!"); final String target="الجمعه"; new tweetToinstance ("!أنا أحب يوم الجمعه كثيرا",target, Preproc,"1").start(); new tweetToinstance (" تافه حقير واحقد عليه أنا أكره يوم الجمعه كثيرا",target, Preproc,"2").start(); new tweetToinstance ("الجمعه #السودان #عمان #الامارات #الكويت !!! http://uae.ae",target, Preproc,"2").start(); /*StatusListener listener = new StatusListener() { public void onStatus(Status status) { System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText()); // if(status.isRetweet()==false) //new tweetToinstance (status.getText(),target, Preproc,""+status.getId()).start(); } public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { //System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId()); } public void onTrackLimitationNotice(int numberOfLimitedStatuses) { // System.out.println("Got track limitation notice:" + numberOfLimitedStatuses); } public void onScrubGeo(long userId, long upToStatusId) { // System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId); } public void onStallWarning(StallWarning warning) { // System.out.println("Got stall warning:" + warning); } public void onException(Exception ex) { ex.printStackTrace(); } }; TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); twitterStream.addListener(listener); ArrayList<String> word=new ArrayList<String>(); word.add(target); String[] trackArray=new String [word.size()]; trackArray= word.toArray(trackArray); // filter() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously. twitterStream.filter(new FilterQuery(0, null, trackArray)); */ } }
36.913043
142
0.612878
31cf1e6dabcf800e7564c38f3c1929adb0041fbb
1,485
package com.orientechnologies.orient.jdbc; import org.junit.Test; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import static org.assertj.core.api.Assertions.assertThat; public class OrientJdbcStatementTest extends OrientJdbcBaseTest { @Test public void shouldCreateStatement() throws Exception { Statement stmt = conn.createStatement(); assertThat(stmt).isNotNull(); ; stmt.close(); assertThat(stmt.isClosed()).isTrue(); } @Test public void shouldReturnEmptyResultSetOnEmptyQuery() throws SQLException { Statement stmt = conn.createStatement(); assertThat(stmt.execute("")).isFalse(); assertThat(stmt.getResultSet()).isNull(); ; assertThat(stmt.getMoreResults()).isFalse(); } @Test public void shouldExectuteSelectOne() throws SQLException { Statement st = conn.createStatement(); assertThat(st.execute("select 1")).isTrue(); assertThat(st.getResultSet()).isNotNull(); ResultSet resultSet = st.getResultSet(); resultSet.first(); assertThat(resultSet.getInt("1")).isEqualTo(1); assertThat(st.getMoreResults()).isFalse(); } @Test(expected = SQLException.class) public void shouldThrowSqlExceptionOnError() throws SQLException { String query = String.format("select sequence('%s').next()", "theSequence"); Statement stmt = conn.createStatement(); stmt.executeQuery(query); } }
27
81
0.692929
69899632f6add332dec5b8a6e5223c2efe441e4a
9,188
/* * JaamSim Discrete Event Simulation * Copyright (C) 2014 Ausenco Engineering Canada 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.jaamsim.rng; import static org.junit.Assert.assertTrue; import org.junit.Test; public class TestMRG1999a { @Test public void testKnownStreams() { long[] seeds1 = { 0, 0, 1, 0, 0, 1 }; String[] known1 = { "0, 0, 1, 0, 0, 1", "949770784, 3580155704, 1230515664, 1610723613, 1022607788, 2093834863", "3106427820, 3199155377, 4290900039, 3167429889, 3572939265, 698814233", "693938118, 3153461912, 1636264737, 2581649800, 1834943086, 290967548", "3188270128, 1934119675, 826363896, 4070445105, 1933248566, 3962062826", "3757485922, 572568472, 2395114552, 3590438463, 538674679, 2165238291", "4075809725, 1035961073, 56103715, 329763193, 1230302420, 3869031993", "687667041, 1179017059, 5861898, 3354556565, 1742222303, 2941424961", "2481284279, 4288164505, 1177260757, 567967482, 784865788, 3134382704", "1515873698, 4089072055, 163684167, 1094056604, 3798743924, 3295131466", "920035025, 408996081, 2433373148, 673478093, 1620020757, 2269902114" }; String test1 = String.format("%d, %d, %d, %d, %d, %d", seeds1[0], seeds1[1], seeds1[2], seeds1[3], seeds1[4], seeds1[5]); assertTrue(test1.equals(known1[0])); for (int i = 1; i < known1.length; i++) { MRG1999a.advanceStream(seeds1); test1 = String.format("%d, %d, %d, %d, %d, %d", seeds1[0], seeds1[1], seeds1[2], seeds1[3], seeds1[4], seeds1[5]); assertTrue(test1.equals(known1[i])); } String[] known2 = { "12345, 12345, 12345, 12345, 12345, 12345", "3692455944, 1366884236, 2968912127, 335948734, 4161675175, 475798818", "1015873554, 1310354410, 2249465273, 994084013, 2912484720, 3876682925", "2338701263, 1119171942, 2570676563, 317077452, 3194180850, 618832124", "1597262096, 3906379055, 3312112953, 1016013135, 4099474108, 275305423", "97147054, 3131372450, 829345164, 3691032523, 3006063034, 4259826321", "796079799, 2105258207, 955365076, 2923159030, 4116632677, 3067683584", "3281794178, 2616230133, 1457051261, 2762791137, 2480527362, 2282316169", "3777646647, 1837464056, 4204654757, 664239048, 4190510072, 2959195122", "4215590817, 3862461878, 1087200967, 1544910132, 936383720, 1611370123", "1683636369, 362165168, 814316280, 869382050, 980203903, 2062101717" }; long[] seeds2 = { 12345, 12345, 12345, 12345, 12345, 12345 }; String test2 = String.format("%d, %d, %d, %d, %d, %d", seeds2[0], seeds2[1], seeds2[2], seeds2[3], seeds2[4], seeds2[5]); assertTrue(test2.equals(known2[0])); for (int i = 1; i < known2.length; i++) { MRG1999a.advanceStream(seeds2); test2 = String.format("%d, %d, %d, %d, %d, %d", seeds2[0], seeds2[1], seeds2[2], seeds2[3], seeds2[4], seeds2[5]); assertTrue(test2.equals(known2[i])); } } @Test public void testKnownSubstreams() { long[] seeds1 = { 0, 0, 1, 0, 0, 1 }; String[] known1 = { "0, 0, 1, 0, 0, 1", "4127413238, 1871391091, 69195019, 1610795712, 3889917532, 3708466080", "99651939, 2329303404, 2931758910, 878035866, 1926628839, 3196114006", "230171794, 3210181465, 3536018417, 2865846472, 1249197731, 3331097822", "1314332382, 1588259595, 2508077280, 3182508868, 3038399593, 2980208068", "4010413858, 401645099, 2106045662, 384279948, 1923026173, 564222425", "2307614257, 2703042396, 2823695054, 2384208331, 3412123799, 1365035178", "520437440, 4210727080, 3707259965, 804702670, 2645232736, 4072194992", "4049009082, 4183591379, 1453913233, 4095757548, 789475914, 2145357457", "2828141255, 752526256, 2097509046, 2724043008, 84549310, 1412103825", "2040707498, 3221815101, 1825015381, 3287341287, 2602801723, 4228411920" }; String test1 = String.format("%d, %d, %d, %d, %d, %d", seeds1[0], seeds1[1], seeds1[2], seeds1[3], seeds1[4], seeds1[5]); assertTrue(test1.equals(known1[0])); for (int i = 1; i < known1.length; i++) { MRG1999a.advanceSubstream(seeds1); test1 = String.format("%d, %d, %d, %d, %d, %d", seeds1[0], seeds1[1], seeds1[2], seeds1[3], seeds1[4], seeds1[5]); assertTrue(test1.equals(known1[i])); } String[] known2 = { "12345, 12345, 12345, 12345, 12345, 12345", "870504860, 2641697727, 884013853, 339352413, 2374306706, 3651603887", "460387934, 1532391390, 877287553, 120103512, 2153115941, 335837774", "3775110060, 3208296044, 1257177538, 378684317, 2867112178, 2201306083", "1870130441, 490396226, 1081325149, 3685085721, 2348042618, 1094489500", "934940479, 1950100692, 4183308048, 1834563867, 1457690863, 2911850358", "36947768, 3877286680, 1490366786, 2869536097, 1753150659, 575546150", "2591627614, 2744298060, 626085041, 644044487, 2091171169, 3539660345", "2906523984, 140710505, 1144258739, 2076719571, 1742524362, 768984958", "2483450279, 3767309577, 2486764677, 4056403678, 792164890, 998062628", "1065618315, 827657608, 299165607, 461289958, 2074659312, 274796520" }; long[] seeds2 = { 12345, 12345, 12345, 12345, 12345, 12345 }; String test2 = String.format("%d, %d, %d, %d, %d, %d", seeds2[0], seeds2[1], seeds2[2], seeds2[3], seeds2[4], seeds2[5]); assertTrue(test2.equals(known2[0])); for (int i = 1; i < known2.length; i++) { MRG1999a.advanceSubstream(seeds2); test2 = String.format("%d, %d, %d, %d, %d, %d", seeds2[0], seeds2[1], seeds2[2], seeds2[3], seeds2[4], seeds2[5]); assertTrue(test2.equals(known2[i])); } } @Test public void testKnownStates() { MRG1999a test1 = new MRG1999a(0, 0, 1, 0, 0, 1); String[] known1 = { "0, 0, 1, 0, 0, 1", "0, 1, 0, 0, 1, 527612", "1, 0, 1403580, 1, 527612, 3497978192", "0, 1403580, 4294156359, 527612, 3497978192, 3281754271", "1403580, 4294156359, 2941890554, 3497978192, 3281754271, 1673476130", "4294156359, 2941890554, 489343630, 3281754271, 1673476130, 1430724370", "2941890554, 489343630, 1831234280, 1673476130, 1430724370, 893509979", "489343630, 1831234280, 2758233149, 1430724370, 893509979, 3280220074", "1831234280, 2758233149, 939574583, 893509979, 3280220074, 361718588", "2758233149, 939574583, 3228066636, 3280220074, 361718588, 951529882", "939574583, 3228066636, 513534955, 361718588, 951529882, 856588367" }; assertTrue(test1.toString().equals(known1[0])); for (int i = 1; i < known1.length; i++) { test1.nextUniform(); // advance the state assertTrue(test1.toString().equals(known1[i])); } MRG1999a test2 = new MRG1999a(12345, 12345, 12345, 12345, 12345, 12345); String[] known2 = { "12345, 12345, 12345, 12345, 12345, 12345", "12345, 12345, 3023790853, 12345, 12345, 2478282264", "12345, 3023790853, 3023790853, 12345, 2478282264, 1655725443", "3023790853, 3023790853, 3385359573, 2478282264, 1655725443, 2057415812", "3023790853, 3385359573, 1322208174, 1655725443, 2057415812, 2070190165", "3385359573, 1322208174, 2930192941, 2057415812, 2070190165, 1978299747", "1322208174, 2930192941, 2462079208, 2070190165, 1978299747, 171163572", "2930192941, 2462079208, 2386811717, 1978299747, 171163572, 321902337", "2462079208, 2386811717, 2989318136, 171163572, 321902337, 1462200156", "2386811717, 2989318136, 3378525425, 321902337, 1462200156, 2794459678", "2989318136, 3378525425, 1773647758, 1462200156, 2794459678, 2822254363" }; assertTrue(test2.toString().equals(known2[0])); for (int i = 1; i < known2.length; i++) { test2.nextUniform(); // advance the state assertTrue(test2.toString().equals(known2[i])); } } @Test public void testCachedSeeds() { MRG1999a test1 = new MRG1999a(0, 0); MRG1999a test2 = new MRG1999a(12345, 12345, 12345, 12345, 12345, 12345); assertTrue(test1.toString().equals(test2.toString())); // test stream 1 for each test1 = new MRG1999a(1, 0); long[] seeds2 = { 12345, 12345, 12345, 12345, 12345, 12345 }; MRG1999a.advanceStream(seeds2); test2 = new MRG1999a(seeds2[0], seeds2[1], seeds2[2], seeds2[3], seeds2[4], seeds2[5]); assertTrue(test1.toString().equals(test2.toString())); // test stream 10500 for each test1 = new MRG1999a(10500, 0); long[] seeds3 = { 12345, 12345, 12345, 12345, 12345, 12345 }; for (int i = 0; i < 10500; i++) { MRG1999a.advanceStream(seeds3); } test2 = new MRG1999a(seeds3[0], seeds3[1], seeds3[2], seeds3[3], seeds3[4], seeds3[5]); assertTrue(test1.toString().equals(test2.toString())); // test stream 20000 for each test1 = new MRG1999a(20000, 0); long[] seeds4 = { 12345, 12345, 12345, 12345, 12345, 12345 }; for (int i = 0; i < 20000; i++) { MRG1999a.advanceStream(seeds4); } test2 = new MRG1999a(seeds4[0], seeds4[1], seeds4[2], seeds4[3], seeds4[4], seeds4[5]); assertTrue(test1.toString().equals(test2.toString())); } }
45.485149
123
0.701894
f951676e0a65a873805d87f41b2fc35d4afada44
705
package com.mgu.csp.sudoku; import com.mgu.csp.Assignment; import com.mgu.csp.VariableIdentity; public class PrettyPrinter { public static void printBoard(final Assignment<Integer> assignment) { final StringBuilder sb = new StringBuilder(); for (int row = 0; row < 9; row++) { for (int col = 0; col < 9; col++) { final VariableIdentity id = IdGenerator.identityOfVariableAt(row, col); final String assignedValue = assignment.valueOf(id) == null ? "." : String.valueOf(assignment.valueOf(id)); sb.append(assignedValue); } sb.append("\n"); } System.out.println(sb.toString()); } }
35.25
123
0.602837
feca8338b3be1c39a27ee3e73878efaf8f2866a4
7,334
/* * GridGain Community Edition Licensing * Copyright 2019 GridGain Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause * Restriction; 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. * * Commons Clause Restriction * * The Software is provided to you by the Licensor under the License, as defined below, subject to * the following condition. * * Without limiting other conditions in the License, the grant of rights under the License will not * include, and the License does not grant to you, the right to Sell the Software. * For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you * under the License to provide to third parties, for a fee or other consideration (including without * limitation fees for hosting or consulting/ support services related to the Software), a product or * service whose value derives, entirely or substantially, from the functionality of the Software. * Any license notice or attribution required by the License must also include this Commons Clause * License Condition notice. * * For purposes of the clause above, the “Licensor” is Copyright 2019 GridGain Systems, Inc., * the “License” is the Apache License, Version 2.0, and the Software is the GridGain Community * Edition software provided with this notice. */ package org.apache.ignite.internal.processors.cache.persistence; import java.util.ArrayList; import java.util.List; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteDataStreamer; import org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.DataRegionConfiguration; import org.apache.ignite.configuration.DataStorageConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.processors.cache.GatewayProtectedCacheProxy; import org.apache.ignite.internal.util.typedef.G; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; /** * Base class for {@link IgnitePdsDestroyCacheTest} and {@link IgnitePdsDestroyCacheWithoutCheckpointsTest} */ public abstract class IgnitePdsDestroyCacheAbstractTest extends GridCommonAbstractTest { /** */ protected static final int CACHES = 3; /** */ protected static final int NODES = 3; /** */ private static final int NUM_OF_KEYS = 100; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); return cfg.setDataStorageConfiguration(new DataStorageConfiguration() .setDefaultDataRegionConfiguration(new DataRegionConfiguration() .setMaxSize(200 * 1024 * 1024) .setPersistenceEnabled(true))); } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { super.beforeTest(); cleanPersistenceDir(); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { stopAllGrids(); cleanPersistenceDir(); super.afterTest(); } /** * @param ignite Ignite. */ private void loadCaches(Ignite ignite) { for (int i = 0; i < CACHES; i++) { try (IgniteDataStreamer<Object, Object> s = ignite.dataStreamer(cacheName(i))) { s.allowOverwrite(true); for (int j = 0; j < NUM_OF_KEYS; j++) s.addData(j, "cache: " + i + " data: " + j); s.flush(); } } } /** * @param ignite Ignite. */ protected void checkDestroyCaches(Ignite ignite) throws Exception { loadCaches(ignite); log.warning("destroying caches...."); ignite.cache(cacheName(0)).destroy(); ignite.cache(cacheName(1)).destroy(); assertEquals(CACHES - 2, ignite.cacheNames().size()); log.warning("Stopping grid"); stopAllGrids(false); log.warning("Grid stopped"); log.warning("Starting grid"); ignite = startGrids(NODES); ignite.cluster().active(true); log.warning("Grid started"); assertEquals("Check that caches don't survived", CACHES - 2, ignite.cacheNames().size()); for(Ignite ig: G.allGrids()) { IgniteCache cache = ig.cache(cacheName(2)); for (int j = 0; j < NUM_OF_KEYS; j++) assertNotNull("Check that cache2 contains key: " + j + " node: " + ignite.name(), cache.get(j)); } } /** * @param ignite Ignite instance. */ protected void checkDestroyCachesAbruptly(Ignite ignite) throws Exception { loadCaches(ignite); log.warning("Destroying caches"); ((GatewayProtectedCacheProxy)ignite.cache(cacheName(0))).destroyAsync(); ((GatewayProtectedCacheProxy)ignite.cache(cacheName(1))).destroyAsync(); log.warning("Stopping grid"); stopAllGrids(); log.warning("Grid stopped"); log.warning("Starting grid"); ignite = startGrids(NODES); ignite.cluster().active(true); log.warning("Grid started"); for(Ignite ig: G.allGrids()) { assertTrue(ig.cacheNames().contains(cacheName(2))); IgniteCache cache = ig.cache(cacheName(2)); for (int j = 0; j < NUM_OF_KEYS; j++) assertNotNull("Check that survived cache cache2 contains key: " + j + " node: " + ig.name(), cache.get(j)); } } /** * @param ignite Ignite. */ protected void startCachesDynamically(Ignite ignite) { List<CacheConfiguration> ccfg = new ArrayList<>(CACHES); for (int i = 0; i < CACHES; i++) ccfg.add(new CacheConfiguration<>(cacheName(i)) .setBackups(1) .setAffinity(new RendezvousAffinityFunction(false, 32))); ignite.createCaches(ccfg); } /** * @param ignite Ignite instance. */ protected void startGroupCachesDynamically(Ignite ignite) { List<CacheConfiguration> ccfg = new ArrayList<>(CACHES); for (int i = 0; i < CACHES; i++) ccfg.add(new CacheConfiguration<>(cacheName(i)) .setGroupName(i % 2 == 0 ? "grp-even" : "grp-odd") .setBackups(1) .setAffinity(new RendezvousAffinityFunction(false, 32))); ignite.createCaches(ccfg); } /** * Generate cache name from idx. * * @param idx Index. */ protected String cacheName(int idx) { return "cache" + idx; } }
33.797235
123
0.650668
725e71b41e9d9053f155163c9e9cbf833acb61d4
10,883
package com.txt.video.trtc.videolayout; import android.content.Context; import android.content.res.TypedArray; import androidx.annotation.Nullable; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.ToggleButton; import com.tencent.rtmp.ui.TXCloudVideoView; import com.tencent.trtc.TRTCCloudDef; import com.txt.video.R; import java.lang.ref.WeakReference; import java.util.HashMap; /** * Module: TRTCVideoLayout * <p> * Function: * <p> * 此 TRTCVideoLayout 封装了{@link TXCloudVideoView} 以及业务逻辑 UI 控件 * 作用: * 1. 实现了手势监听,配合 {@link TRTCVideoLayoutManager} 能够实现自由拖动 View。 * 详情可见:{@link TRTCVideoLayout#initGestureListener()} * 实现原理:利用 RelativeLayout 的 margin 实现了能够在父容器自由定位的特性;需要注意,{@link TRTCVideoLayout} 不能增加约束规则,如 alignParentRight 等,否则无法自由定位。 * <p> * 2. 对{@link TXCloudVideoView} 与逻辑 UI 进行组合,在 muteLocal、音量回调等情况,能够进行 UI 相关的变化。若您的项目中,也相关的业务逻辑,可以参照 Demo 的相关实现。 */ public class TRTCVideoLayout extends RelativeLayout implements View.OnClickListener { public WeakReference<IVideoLayoutListener> mWefListener; private TXCloudVideoView mVideoView; private OnClickListener mClickListener; private GestureDetector mSimpleOnGestureListener; private ImageView mPbAudioVolume; private LinearLayout mLlController; private Button mBtnMuteVideo, mBtnMuteAudio, mBtnFill; private FrameLayout mLlNoVideo; private TextView mTvContent; private ImageView mIvNoS; private ViewGroup mVgFuc; private HashMap<Integer, Integer> mNoSMap = null; private boolean mMoveable; private boolean mEnableFill = false; private boolean mEnableAudio = true; private boolean mEnableVideo = true; private boolean isSelf = false; public boolean isSelf() { return isSelf; } public void setSelf(boolean self) { isSelf = self; } public TRTCVideoLayout(Context context) { this(context, null); } public TRTCVideoLayout(Context context, AttributeSet attrs) { super(context, attrs); handleTypedArray(context,attrs); initFuncLayout(); initGestureListener(); initNoS(); } private void handleTypedArray(Context context, AttributeSet attrs){ TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.tx_VideoView); isSelf = typedArray.getBoolean(R.styleable.tx_VideoView_tx_isself, false); typedArray.recycle(); } public TRTCVideoLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs,defStyleAttr); handleTypedArray(context,attrs); initFuncLayout(); initGestureListener(); initNoS(); } public TXCloudVideoView getVideoView() { return mVideoView; } public void updateNetworkQuality(int quality) { if (quality < TRTCCloudDef.TRTC_QUALITY_Excellent) { quality = TRTCCloudDef.TRTC_QUALITY_Excellent; } if (quality > TRTCCloudDef.TRTC_QUALITY_Down) { quality = TRTCCloudDef.TRTC_QUALITY_Down; } if (mIvNoS != null) { mIvNoS.setImageResource(mNoSMap.get(Integer.valueOf(quality).intValue())); } } public void setBottomControllerVisibility(int visibility) { if (mLlController != null) mLlController.setVisibility(visibility); } public void updateNoVideoLayout(String text, int visibility) { if (mTvContent != null) { mTvContent.setText(text); } if (mLlNoVideo != null) { mLlNoVideo.setVisibility(visibility); } } public void setAudioVolumeProgress(int progress) { if (mPbAudioVolume != null) { //1-19 //20-39 //40-59 //60-79 //80-100 if (progress == -1) { mPbAudioVolume.setImageResource(R.drawable.tx_icon_volume_mute); } else if (progress == 0) { mPbAudioVolume.setImageResource(R.drawable.tx_icon_volume_0); } else if (progress >= 1 && progress <= 19) { mPbAudioVolume.setImageResource(R.drawable.tx_icon_volume_1); } else if (progress >= 20 && progress <= 39) { mPbAudioVolume.setImageResource(R.drawable.tx_icon_volume_2); } else if (progress >= 40 && progress <= 59) { mPbAudioVolume.setImageResource(R.drawable.tx_icon_volume_3); } else if (progress >= 60 && progress <= 79) { mPbAudioVolume.setImageResource(R.drawable.tx_icon_volume_4); } else if (progress >= 80 && progress <= 100) { mPbAudioVolume.setImageResource(R.drawable.tx_icon_volume_5); } } } public void setAudioVolumeProgressBarVisibility(int visibility) { if (mPbAudioVolume != null) { mPbAudioVolume.setVisibility(visibility); } } private void initNoS() { mNoSMap = new HashMap<>(); mNoSMap.put(Integer.valueOf(TRTCCloudDef.TRTC_QUALITY_Down), Integer.valueOf(R.drawable.tx_signal1)); mNoSMap.put(Integer.valueOf(TRTCCloudDef.TRTC_QUALITY_Vbad), Integer.valueOf(R.drawable.tx_signal2)); mNoSMap.put(Integer.valueOf(TRTCCloudDef.TRTC_QUALITY_Bad), Integer.valueOf(R.drawable.tx_signal3)); mNoSMap.put(Integer.valueOf(TRTCCloudDef.TRTC_QUALITY_Poor), Integer.valueOf(R.drawable.tx_signal4)); mNoSMap.put(Integer.valueOf(TRTCCloudDef.TRTC_QUALITY_Good), Integer.valueOf(R.drawable.tx_signal5)); mNoSMap.put(Integer.valueOf(TRTCCloudDef.TRTC_QUALITY_Excellent), Integer.valueOf(R.drawable.tx_signal6)); } private void initFuncLayout() { if (isSelf) { mVgFuc = (ViewGroup) LayoutInflater.from(getContext()).inflate(R.layout.tx_layout_trtc_func_big, this, true); }else{ mVgFuc = (ViewGroup) LayoutInflater.from(getContext()).inflate(R.layout.tx_layout_trtc_func_float, this, true); } mVideoView = (TXCloudVideoView) mVgFuc.findViewById(R.id.trtc_tc_cloud_view); mPbAudioVolume = (ImageView) mVgFuc.findViewById(R.id.trtc_pb_audio); mLlController = (LinearLayout) mVgFuc.findViewById(R.id.trtc_ll_controller); mBtnMuteVideo = (Button) mVgFuc.findViewById(R.id.trtc_btn_mute_video); mBtnMuteVideo.setOnClickListener(this); mBtnMuteAudio = (Button) mVgFuc.findViewById(R.id.trtc_btn_mute_audio); mBtnMuteAudio.setOnClickListener(this); mBtnFill = (Button) mVgFuc.findViewById(R.id.trtc_btn_fill); mBtnFill.setOnClickListener(this); mLlNoVideo = (FrameLayout) mVgFuc.findViewById(R.id.trtc_fl_no_video); mTvContent = (TextView) mVgFuc.findViewById(R.id.trtc_tv_content); mIvNoS = (ImageView) mVgFuc.findViewById(R.id.trtc_iv_nos); ToggleButton muteBtn = (ToggleButton) mVgFuc.findViewById(R.id.mute_in_speaker); muteBtn.setOnClickListener(this); } private void initGestureListener() { mSimpleOnGestureListener = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { if (mClickListener != null) { mClickListener.onClick(TRTCVideoLayout.this); } return true; } @Override public boolean onDown(MotionEvent e) { return true; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (!mMoveable) return false; ViewGroup.LayoutParams params = TRTCVideoLayout.this.getLayoutParams(); // 当 TRTCVideoView 的父容器是 RelativeLayout 的时候,可以实现拖动 if (params instanceof LayoutParams) { LayoutParams layoutParams = (LayoutParams) TRTCVideoLayout.this.getLayoutParams(); int newX = (int) (layoutParams.leftMargin + (e2.getX() - e1.getX())); int newY = (int) (layoutParams.topMargin + (e2.getY() - e1.getY())); layoutParams.leftMargin = newX; layoutParams.topMargin = newY; TRTCVideoLayout.this.setLayoutParams(layoutParams); } return true; } }); this.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return mSimpleOnGestureListener.onTouchEvent(event); } }); } @Override public void setOnClickListener(@Nullable OnClickListener l) { mClickListener = l; } public void setMoveable(boolean enable) { mMoveable = enable; } @Override public void onClick(View v) { IVideoLayoutListener listener = mWefListener != null ? mWefListener.get() : null; if (listener == null) return; int id = v.getId(); if (id == R.id.trtc_btn_fill) { mEnableFill = !mEnableFill; if (mEnableFill) { v.setBackgroundResource(R.drawable.tx_fill_scale); } else { v.setBackgroundResource(R.drawable.tx_fill_adjust); } listener.onClickFill(this, mEnableFill); } else if (id == R.id.trtc_btn_mute_audio) { mEnableAudio = !mEnableAudio; if (mEnableAudio) { v.setBackgroundResource(R.drawable.tx_remote_audio_enable); } else { v.setBackgroundResource(R.drawable.tx_remote_audio_disable); } listener.onClickMuteAudio(this, !mEnableAudio); } else if (id == R.id.trtc_btn_mute_video) { mEnableVideo = !mEnableVideo; if (mEnableVideo) { v.setBackgroundResource(R.drawable.tx_remote_video_enable); } else { v.setBackgroundResource(R.drawable.tx_remote_video_disable); } listener.onClickMuteVideo(this, !mEnableVideo); } else if (id == R.id.mute_in_speaker) { listener.onClickMuteInSpeakerAudio(this, ((ToggleButton) v).isChecked()); } } public void setIVideoLayoutListener(IVideoLayoutListener listener) { if (listener == null) { mWefListener = null; } else { mWefListener = new WeakReference<IVideoLayoutListener>(listener); } } }
38.052448
123
0.649545
6621c6aae07b820d301eaed3447da98b7eacece2
854
package hr.fer.zemris.java.hw05.db; /** * Class represents one token extracted by lexical grouping. * @author Blaz Bagic * @version 1.0 */ public class Token { /** The type of the token. */ private TokenType type; /** The value of the token. */ private String value; /** * Default constructor for the token. * @param type null is not allowed * @param value some value */ public Token(TokenType type, String value) { if (type == null) throw new IllegalArgumentException("Token type can not be null."); this.type = type; this.value = value; } /** * Gets the value of the token. * @return value of the token */ public String getValue() { return value; } /** * Gets the type of the token. * @return type of the token */ public TokenType getType() { return type; } }
20.333333
72
0.625293
766e6f360d6bb936ebe95404a8c8070080873c1f
3,271
// 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.subsystems; import com.ctre.phoenix.motorcontrol.ControlMode; import com.ctre.phoenix.motorcontrol.FeedbackDevice; import com.ctre.phoenix.motorcontrol.can.TalonSRX; import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX; import edu.wpi.first.wpilibj.SPI; import edu.wpi.first.wpilibj.drive.DifferentialDrive; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Constants; import com.kauailabs.navx.frc.AHRS; public class DriveTrain extends SubsystemBase { private final WPI_TalonSRX _leftDriveTalon; private final WPI_TalonSRX _rightDriveTalon; private AHRS navx = new AHRS(SPI.Port.kMXP); private double ticksToCm = 80.0/10180.5; // in centimeters private final int ticksInOneRevolution = 4096; private DifferentialDrive _diffDrive; // creates a new drive train public DriveTrain() { _leftDriveTalon = new WPI_TalonSRX(Constants.DriveTrainPorts.LeftDriveTalonPort); _rightDriveTalon = new WPI_TalonSRX(Constants.DriveTrainPorts.RightDriveTalonPort); _leftDriveTalon.setInverted(true); _rightDriveTalon.setInverted(false); _diffDrive = new DifferentialDrive(_leftDriveTalon, _rightDriveTalon); _leftDriveTalon.configFactoryDefault(); _leftDriveTalon.configSelectedFeedbackSensor(FeedbackDevice.CTRE_MagEncoder_Relative, 0, 10); _rightDriveTalon.configFactoryDefault(); _rightDriveTalon.configSelectedFeedbackSensor(FeedbackDevice.CTRE_MagEncoder_Relative, 0, 10); } @Override public void periodic() { // This method will be called once per scheduler run } public void resetEncoders(){ _leftDriveTalon.setSelectedSensorPosition(0,0,10); _rightDriveTalon.setSelectedSensorPosition(0,0,10); } public void setInverted(){ _rightDriveTalon.setSensorPhase(true); } public double getPosition(){ return (((_leftDriveTalon.getSelectedSensorPosition(0) + _rightDriveTalon.getSelectedSensorPosition(0))/2) * (ticksToCm)); } public double getVelocity(){ return (((_leftDriveTalon.getSensorCollection().getPulseWidthVelocity() + _rightDriveTalon.getSensorCollection().getPulseWidthVelocity())/2) * (ticksToCm)); } public double getTicks(){ return (_leftDriveTalon.getSelectedSensorPosition(0) + _rightDriveTalon.getSelectedSensorPosition(0)) / 2; } public double getLeftTicks(){ return _leftDriveTalon.getSelectedSensorPosition(0); } public double getRightTicks(){ return _rightDriveTalon.getSelectedSensorPosition(0); } public double getAngleAndReset(){ double degrees = navx.getAngle(); navx.reset(); return degrees; } public double getAngle(){ return navx.getAngle(); } public void reset(){ navx.reset(); } public void tankDrive(double leftSpeed, double rightSpeed) { _leftDriveTalon.set(ControlMode.PercentOutput, -leftSpeed); _rightDriveTalon.set(ControlMode.PercentOutput, -rightSpeed); //_diffDrive.tankDrive(leftSpeed, rightSpeed); } public void arcadeDrive(double speed, double rotation) { _diffDrive.arcadeDrive(speed, rotation); } }
30.858491
160
0.767655
6a5f1833eddb829c56b0497adffad0a3c4377773
4,740
package io.github.wayerr.ft.swing; import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.lang.reflect.InvocationTargetException; /** * an example of Focus-traverse usage * Created by wayerr on 10.02.15. */ public final class Example implements Runnable { private static final int GAP = 3; public static void main(String args[]) throws InvocationTargetException, InterruptedException { Example example = new Example(); EventQueue.invokeAndWait(example); } @Override public void run() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setJMenuBar(createMenuBar()); Container pane = frame.getContentPane(); GroupLayout gl = new GroupLayout(pane); pane.setLayout(gl); JComponent one = new JScrollPane(new JTextArea("hold ALT \nthen move focus by arrow keys\n" + "enter to container by pgDown\nleave container by pgUp")); JComponent two = new JScrollPane(new JTextArea("sample")); JComponent three = new JScrollPane(new JTextArea("sample")); JComponent four = createPanel(); gl.setVerticalGroup(gl.createParallelGroup() .addGroup(gl.createSequentialGroup() .addGroup(gl.createParallelGroup() .addComponent(one, 0, GroupLayout.PREFERRED_SIZE, Integer.MAX_VALUE) .addComponent(two, 0, GroupLayout.PREFERRED_SIZE, Integer.MAX_VALUE) ) .addGap(GAP) .addComponent(three, 0, GroupLayout.PREFERRED_SIZE, Integer.MAX_VALUE) ) .addComponent(four, 0, GroupLayout.PREFERRED_SIZE, Integer.MAX_VALUE) ); gl.setHorizontalGroup(gl.createSequentialGroup() .addGroup(gl.createParallelGroup() .addGroup(gl.createSequentialGroup() .addComponent(two, 0, GroupLayout.PREFERRED_SIZE, Integer.MAX_VALUE) .addGap(GAP) .addComponent(one, 0, GroupLayout.PREFERRED_SIZE, Integer.MAX_VALUE) ) .addComponent(three, 0, GroupLayout.PREFERRED_SIZE, Integer.MAX_VALUE) ) .addGap(GAP) .addComponent(four, 100, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE) ); // code for using of TraverseFocusSupport TraverseFocusSupport tfs = new TraverseFocusSupport(); tfs.setFocusPainter(new DefaultFocusPainter(tfs)); DefaultKeyboardAdapter keyboardAdapter = new DefaultKeyboardAdapter(tfs); keyboardAdapter.install(); tfs.install(); // end code Dimension ss = Toolkit.getDefaultToolkit().getScreenSize(); double x = ss.width / 3d; double y = ss.height / 3d; frame.setBounds((int) x, (int) y, (int) ((ss.width - x) / 2d), (int) ((ss.height - y) / 2d)); frame.setVisible(true); } private JComponent createPanel() { JPanel panel = new JPanel(); GroupLayout gl = new GroupLayout(panel); panel.setLayout(gl); JComponent one = new JCheckBox("checkbox 1"); JComponent two = new JCheckBox("checkbox 2"); JComponent three = new JButton("ok"); JComponent four = new JButton("cancel"); gl.setVerticalGroup(gl.createSequentialGroup() .addComponent(one) .addGap(GAP) .addComponent(two) .addGap(GAP) .addGroup(gl.createParallelGroup() .addComponent(three) .addComponent(four) ) ); gl.setHorizontalGroup(gl.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(two, 0, GroupLayout.PREFERRED_SIZE, Integer.MAX_VALUE) .addComponent(one, 0, GroupLayout.PREFERRED_SIZE, Integer.MAX_VALUE) .addGroup(gl.createSequentialGroup() .addGap(0, 10, Integer.MAX_VALUE) .addComponent(three) .addGap(GAP) .addComponent(four) .addGap(GAP) ) ); gl.linkSize(three, four); return panel; } private JMenuBar createMenuBar() { JMenuBar bar = new JMenuBar(); bar.add(createMenu("one", "one 1", "one 2", "one 3")); bar.add(createMenu("two", "two 1", "two 2", "two 3")); bar.add(createMenu("three", "three 1", "three 2", "three 3")); return bar; } private JMenu createMenu(String menuName, String... childs) { JMenu menu = new JMenu(menuName); for (String child : childs) { menu.add(child); } return menu; } }
37.03125
101
0.60443
dab0fba80aded49d9d72bc1fb1ae88919e5f87ec
2,724
package mekanism.common.item.block; import javax.annotation.Nonnull; import mekanism.common.registration.impl.ItemDeferredRegister; import mekanism.common.util.MekanismUtils; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemPlacementContext; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemUsageContext; import net.minecraft.sound.BlockSoundGroup; import net.minecraft.sound.SoundCategory; import net.minecraft.util.ActionResult; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; /** * Created by Thiakil on 19/11/2017. */ //TODO: Re-evaluate this class public abstract class ItemBlockMultipartAble<BLOCK extends Block> extends ItemBlockMekanism<BLOCK> { public ItemBlockMultipartAble(BLOCK block) { super(block, ItemDeferredRegister.getMekBaseProperties()); } /** * Reimplementation of onItemUse that will divert to MCMultipart placement functions if applicable */ @Nonnull @Override public ActionResult useOnBlock(ItemUsageContext context) { PlayerEntity player = context.getPlayer(); if (player == null) { return ActionResult.PASS; } ItemStack stack = player.getStackInHand(context.getHand()); if (stack.isEmpty()) { return ActionResult.FAIL;//WTF } World world = context.getWorld(); BlockPos pos = context.getBlockPos(); if (!MekanismUtils.isValidReplaceableBlock(world, pos)) { pos = pos.offset(context.getSide()); } if (player.canPlaceOn(pos, context.getSide(), stack)) { ItemPlacementContext blockItemUseContext = new ItemPlacementContext(context); BlockState state = getPlacementState(blockItemUseContext); if (state == null) { return ActionResult.FAIL; } if (place(blockItemUseContext, state)) { state = world.getBlockState(pos); BlockSoundGroup soundtype = state.getSoundType(world, pos, player); world.playSound(player, pos, soundtype.getPlaceSound(), SoundCategory.BLOCKS, (soundtype.getVolume() + 1) / 2F, soundtype.getPitch() * 0.8F); stack.decrement(1); } return ActionResult.SUCCESS; } return ActionResult.FAIL; } @Override public boolean place(@Nonnull ItemPlacementContext context, @Nonnull BlockState state) { if (MekanismUtils.isValidReplaceableBlock(context.getWorld(), context.getBlockPos())) { return super.place(context, state); } return false; } }
38.366197
157
0.680617
10606df7b088da5231222db232d5c970913e2e08
3,060
package com.pineone.icbms.sda.itf.ci.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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 com.pineone.icbms.sda.itf.ci.dto.CiDTO; import com.pineone.icbms.sda.itf.ci.service.CiService; @RestController @RequestMapping(value = "/itf") public class CiController { private final Log log = LogFactory.getLog(this.getClass()); @Resource(name = "ciService") private CiService ciService; // http://localhost:8080/sda/itf/ci/ @RequestMapping(value = "/ci/", method = RequestMethod.GET) public List<Map<String, Object>> selectList(Map<String, Object> commandMap) { List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>(); if (log.isDebugEnabled()) { log.debug("selectList"); } try { lists = ciService.selectList(commandMap); } catch (Exception e) { e.printStackTrace(); } return lists; } // http://localhost:8080/sda/itf/ci/CQ-1-1-001 @RequestMapping(value = "/ci/{idx}", method = RequestMethod.GET) public CiDTO selectOne(@PathVariable String idx) { CiDTO list = new CiDTO(); try { list = ciService.selectOne(idx); } catch (Exception e) { e.printStackTrace(); } return list; } // http://localhost:8080/sda/itf/ci/ // [{"parent_idx":5000, "title":"title5000", "contents":"5000", "hit_cnt":0, // "del_gb":"N", "crea_dtm":"aaaa", "crea_id":"Admin"}] // [{"parent_idx":100, "title":"title200", "contents":"내용100", "hit_cnt":0, // "del_gb":"N", "crea_dtm":"aaaa", "crea_id":"Admin"},{"parent_idx":100, // "title":"title201", "contents":"내용100", "hit_cnt":0, "del_gb":"N", // "crea_dtm":"aaaa", "crea_id":"Admin"},{"parent_idx":100, // "title":"title202", "contents":"내용100", "hit_cnt":0, "del_gb":"N", // "crea_dtm":"aaaa", "crea_id":"Admin"}] @RequestMapping(value = "/ci/", method = RequestMethod.POST) public int insert(@RequestBody CiDTO[] cmDTO) { int rtn_cnt = 0; List<CiDTO> list = new ArrayList<CiDTO>(); Map<String, Object> map = new HashMap<String, Object>(); for (int i = 0; i < cmDTO.length; i++) { list.add(cmDTO[i]); } map.put("list", list); try { rtn_cnt = ciService.insert(map); } catch (Exception e) { e.printStackTrace(); } return rtn_cnt; } // http://localhost:8080/sda/itf/ci/CQ-1-1-001 @RequestMapping(value = "/ci/{idx}", method = RequestMethod.DELETE) public int delete(@PathVariable String idx) { int rtn_cnt = 0; try { rtn_cnt = ciService.delete(idx); } catch (Exception e) { e.printStackTrace(); } return rtn_cnt; } }
31.22449
79
0.666667
07130ad05b03f9c43436ee39aecfc7ab5b9dc387
2,044
package com.example.opengles.act; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.blankj.utilcode.util.ToastUtils; import com.chad.library.adapter.base.BaseQuickAdapter; import com.example.opengles.R; import com.example.opengles.adapter.HomeSimpleAdapter; import java.util.ArrayList; import java.util.List; public class HomeSimpleAct extends AppCompatActivity { private List<String> dataList; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.act_home_simple); initData(); initView(); } private void initView() { RecyclerView recyclerView = findViewById(R.id.rv_home_simple); recyclerView.setLayoutManager(new LinearLayoutManager(this)); HomeSimpleAdapter homeSimpleAdapter = new HomeSimpleAdapter(R.layout.item_home_adapter_simple, dataList); homeSimpleAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN); homeSimpleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() { @Override public void onItemClick(BaseQuickAdapter adapter, View view, int position) { ToastUtils.showShort("Item Click:" + position); } }); homeSimpleAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() { @Override public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) { ToastUtils.showShort("Child Item Click:" + position); } }); recyclerView.setAdapter(homeSimpleAdapter); } private void initData() { dataList = new ArrayList<>(); for (int i = 'A'; i <= 'Z'; i++) { dataList.add(String.valueOf((char) i)); } } }
34.066667
113
0.701566
0a2cf5891a1b25acc40b6a37f1b5583b48590cb8
3,994
/* * 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.solr.search; import java.lang.invoke.MethodHandles; import java.util.Map; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.queryparser.xml.CoreParser; import org.apache.lucene.queryparser.xml.QueryBuilder; import org.apache.lucene.queryparser.xml.builders.SpanQueryBuilder; import org.apache.solr.common.SolrException; import org.apache.solr.common.util.NamedList; import org.apache.solr.core.SolrResourceLoader; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.util.plugin.NamedListInitializedPlugin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Assembles a QueryBuilder which uses Query objects from Solr's <code>search</code> module * in addition to Query objects supported by the Lucene <code>CoreParser</code>. */ public class SolrCoreParser extends CoreParser implements NamedListInitializedPlugin { private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); protected final SolrQueryRequest req; public SolrCoreParser(String defaultField, Analyzer analyzer, SolrQueryRequest req) { super(defaultField, analyzer); queryFactory.addBuilder("LegacyNumericRangeQuery", new LegacyNumericRangeQueryBuilder()); this.req = req; } @Override public void init(NamedList initArgs) { if (initArgs == null || initArgs.size() == 0) { return; } final SolrResourceLoader loader; if (req == null) { loader = new SolrResourceLoader(); } else { loader = req.getCore().getResourceLoader(); } final Iterable<Map.Entry<String,Object>> args = initArgs; for (final Map.Entry<String,Object> entry : args) { final String queryName = entry.getKey(); final String queryBuilderClassName = (String)entry.getValue(); try { final SolrSpanQueryBuilder spanQueryBuilder = loader.newInstance( queryBuilderClassName, SolrSpanQueryBuilder.class, null, new Class[] {String.class, Analyzer.class, SolrQueryRequest.class, SpanQueryBuilder.class}, new Object[] {defaultField, analyzer, req, this}); this.addSpanQueryBuilder(queryName, spanQueryBuilder); } catch (Exception outerException) { try { final SolrQueryBuilder queryBuilder = loader.newInstance( queryBuilderClassName, SolrQueryBuilder.class, null, new Class[] {String.class, Analyzer.class, SolrQueryRequest.class, QueryBuilder.class}, new Object[] {defaultField, analyzer, req, this}); this.addQueryBuilder(queryName, queryBuilder); } catch (Exception innerException) { log.error("Class {} not found or not suitable: {} {}", queryBuilderClassName, outerException, innerException); throw new SolrException( SolrException.ErrorCode.SERVER_ERROR, "Cannot find suitable " + SolrSpanQueryBuilder.class.getCanonicalName() + " or " + SolrQueryBuilder.class.getCanonicalName() + " class: " + queryBuilderClassName + " in " + loader); } } } } }
39.544554
103
0.706059
1cd7ff76687930b31ee99ca21b00b09c6a784fb9
354
package me.chibitxt.smsc; public class ChibiUtil { public static boolean getBooleanProperty(String key, String defaultValue) { int value = Integer.parseInt( System.getProperty(key, defaultValue) ); boolean property; if(value == 1) { property = true; } else { property = false; } return property; } }
17.7
77
0.638418
2fee2e13a90f2f76c57c79bacd82e33421afd05b
2,576
/* * Copyright (c) 2002, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ package sun.jvm.hotspot.memory; import java.io.*; import java.util.*; import sun.jvm.hotspot.debugger.*; import sun.jvm.hotspot.gc_interface.*; import sun.jvm.hotspot.runtime.*; import sun.jvm.hotspot.types.*; public abstract class SharedHeap extends CollectedHeap { private static AddressField permGenField; private static VirtualConstructor ctor; static { VM.registerVMInitializedObserver(new Observer() { public void update(Observable o, Object data) { initialize(VM.getVM().getTypeDataBase()); } }); } private static synchronized void initialize(TypeDataBase db) { Type type = db.lookupType("SharedHeap"); permGenField = type.getAddressField("_perm_gen"); ctor = new VirtualConstructor(db); ctor.addMapping("CompactingPermGen", CompactingPermGen.class); ctor.addMapping("CMSPermGen", CMSPermGen.class); } public SharedHeap(Address addr) { super(addr); } /** These functions return the "permanent" generation, in which reflective objects are allocated and stored. Two versions, the second of which returns the view of the perm gen as a generation. (FIXME: this distinction is strange and seems unnecessary, and should be cleaned up.) */ public PermGen perm() { return (PermGen) ctor.instantiateWrapperFor(permGenField.getValue(addr)); } public CollectedHeapName kind() { return CollectedHeapName.SHARED_HEAP; } public Generation permGen() { return perm().asGen(); } }
33.454545
79
0.724379
656dbeb0d8c051a71a33a2cc2392a2436a1911cd
278
package example.imagetaskgang.servermodel; import java.net.URL; import java.util.List; import retrofit.http.Body; import retrofit.http.POST; public interface ImageStreamService { @POST("/ImageStreamServlet") ServerResponse execute(@Body List<List<URL>> inputURLs); }
21.384615
60
0.776978
2711a65ba52737d6ecac79d2b2cc4311f4daebe8
73
package io.undertow.test.jsp.classref.testname; public class MyTest { }
14.6
47
0.780822
3df1bf0e68b5b11fa71c8856557927d2b07777be
196
package com.gls.common.user.api.model.query; import lombok.Data; import lombok.experimental.Accessors; /** * @author george */ @Data @Accessors(chain = true) public class QueryClientModel { }
15.076923
44
0.744898
9899c3f46ffb7b1f4a15e378fda85a4525bb9f11
3,889
package com.bringardner.openscad.polygon; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class ImageDiff { private static boolean merge(Rectangle r1, Rectangle r2, int hpad,int vpad) { boolean ret = false; int mnx = r1.x-hpad; int mxx = r1.x+r1.width+hpad; int mny = r1.y-vpad; int mxy = r1.y+r1.height+vpad; ret = r2.x >= mnx && r2.x <= mxx && r2.y >= mny && r2.y <= mxy ; if( !ret ) { Rectangle r3 = new Rectangle(r1); r3.x-=hpad; r3.width+=hpad; r3.y-=vpad; r3.height+=vpad; ret = r3.intersects(r2); } return ret; } private static void merge(Rectangle r2, List<Rectangle> list, int hgap,int vpad) { for (Rectangle r : list) { boolean b = r.intersects(r2) || merge(r,r2,hgap,vpad) || merge(r2,r,hgap,vpad); if( b ) { r.add(r2); return; } } list.add(r2); } private static Rectangle find(Rectangle[][] m,int x, int y, int gap) { Rectangle ret = null; // at 200 dpi transit has 5.2 space between the two segments :-( for(int r=0; ret==null && r <= gap;r++ ) { ret = lookBehind(r,x,y,m); } if( ret == null && y > 0 ) { try { ret = m[y-1][x]; } catch (Exception e) { } } return ret; } private static Rectangle lookBehind(int r, int x, int y, Rectangle[][] m) { Rectangle ret = null; int tx = x-r; if( tx >= 0 && tx < m[0].length) { // this array is backwards ret = m[y][tx]; } return ret; } public static List<Rectangle> findEdges(boolean[][] img,Rectangle rect, int hgap,int vgap) { //System.out.println("r="+rect); //System.out.println("w="+img.length+" h="+img[0].length); List<Rectangle> ret = new ArrayList<Rectangle>(); Rectangle m [][] = new Rectangle[img.length][img[0].length]; //System.out.println("r w="+m.length+" r h="+m[0].length); //if( rect.y >= 0 && rect.x >= hgap ) { for(int x=rect.x,maxx = rect.x+rect.width; x<maxx; x++ ) { for(int y=rect.y,maxy=rect.y+rect.height; y<maxy; y++ ) { // include 'gap' pixels to the left of the rectangle, no, no, no :-( if( y < img.length && x < img[0].length ) { try { if( img[y][x] ) { Rectangle cur = find(m,x,y,hgap); if( cur == null ) { cur = new Rectangle(x, y, 1, 1); ret.add(cur); } else { cur.add(x,y); } if( y< m.length && x < m[0].length) { m[y][x] = cur; } } } catch(Throwable e) { //DebugDialog.println("ImageDiff.findEdges e="+e +" x="+x+" y="+y+" maxx="+img.length+" maxy="+img[0].length); e.printStackTrace(); } } } } //} // Add 1 to w + h if( ret.size() > 0 ) { for (Rectangle r : ret) { r.width++; r.height++; } Collections.sort(ret, new Comparator<Rectangle>() { public int compare(Rectangle o1, Rectangle o2) { int ret = o1.x - o2.x; return ret; }; }); boolean done = false; do { Rectangle r = ret.get(0); List<Rectangle> list = new ArrayList<Rectangle>(); list.add(r); for(int idx=1,sz1=ret.size(); idx < sz1; idx++ ) { Rectangle r2 = ret.get(idx); merge(r2,list,hgap,vgap); } done = list.size() == ret.size(); ret = list; } while(!done); } Collections.sort(ret, new Comparator<Rectangle>() { @Override public int compare(Rectangle arg0, Rectangle arg1) { return arg0.x - arg1.x; } }); /* for(int idx=0,sz1=ret.size(); idx < sz1; idx++ ) { Rectangle r = ret.get(idx); if( ctx.isDebug(r)){ ImagePanel.print("ImageDiff.findEdges exit idx="+idx, r, ctx.getImg()); } } */ return ret; } }
22.876471
118
0.53407
d0084081c8ab10d2bcffebcdf8178bce4520a7e6
1,180
package consultan.vanke.com.viewmodel; import android.app.Application; import android.util.Base64; import consultan.vanke.com.R; import consultan.vanke.com.bean.NewLoginResultBean; import consultan.vanke.com.constant.ConstantLibrary; import consultan.vanke.com.utils.ToastUtils; import io.reactivex.Maybe; import java.util.HashMap; public class LoginViewModel extends BaseViewModel { public LoginViewModel(Application application) { super(application); } public Maybe<NewLoginResultBean.DataBean> login(String name, String pwd) { if (name.equals("") || pwd.equals("")) { NewLoginResultBean.DataBean bean = new NewLoginResultBean.DataBean(); return Maybe.error(new LoginException()); } HashMap<String, String> params = new HashMap<>(); params.put("mobile", name); params.put("password", Base64.encodeToString(pwd.getBytes(), Base64.NO_WRAP)); params.put("authType", "REG"); return netApi.salesLogin(params); } static class LoginException extends RuntimeException { public LoginException() { super(ConstantLibrary.LOGINERROR); } } }
29.5
86
0.692373
43d42b0bca18825593c52420329a1b5ee89f4f60
8,242
package com.example.test1; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.DialogFragment; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TimePicker; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthUserCollisionException; import com.google.firebase.auth.FirebaseUser; 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 java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class form extends AppCompatActivity { EditText dateformat; EditText editTextTime; int hour,min; FirebaseDatabase rootNode; DatabaseReference reference; private FirebaseUser user; private String userID; DatePickerDialog.OnDateSetListener setListener; EditText editTextTextPersonName2; EditText editTextTextPostalAddress; EditText editTextLanguage; EditText editTextNumber; Button bookbutton; private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { ActionBar actionBar; actionBar = getSupportActionBar(); // Define ColorDrawable object and parse color // using parseColor method // with color hash code as its parameter ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#3889f4")); //getActionBar().setTitle("Hello world App"); getSupportActionBar().setTitle("Write4H"); // Set BackgroundDrawable actionBar.setBackgroundDrawable(colorDrawable); super.onCreate(savedInstanceState); setContentView(R.layout.activity_form); editTextTime = (EditText) findViewById(R.id.editTextTime); user = FirebaseAuth.getInstance().getCurrentUser(); reference = FirebaseDatabase.getInstance().getReference("client"); userID=user.getUid(); editTextTextPersonName2 = (EditText) findViewById(R.id.editTextTextPersonName2); editTextLanguage = (EditText) findViewById(R.id.editTextLanguage); editTextTime = (EditText) findViewById(R.id.editTextTime); editTextTextPostalAddress = (EditText) findViewById(R.id.editTextTextPostalAddress); editTextNumber = (EditText) findViewById(R.id.editTextNumber); bookbutton = findViewById(R.id.bookbtn); bookbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { rootNode = FirebaseDatabase.getInstance(); reference = rootNode.getReference("exam"); String name = editTextTextPersonName2.getText().toString(); String language = editTextLanguage.getText().toString(); String date = dateformat.getText().toString(); String time = editTextTime.getText().toString(); String address = editTextTextPostalAddress.getText().toString(); String amount = editTextNumber.getText().toString(); if(name.isEmpty()) { editTextTextPersonName2.setError("Name is required"); editTextTextPersonName2.requestFocus(); } if(language.isEmpty()) { editTextLanguage.setError("Language is required"); editTextLanguage.requestFocus(); } if(date.isEmpty()) { dateformat.setError("date is required"); dateformat.requestFocus(); return; } if(time.isEmpty()) { editTextTime.setError("Time is required"); editTextTime.requestFocus(); return; } if(address.isEmpty()) { editTextTextPostalAddress.setError("address is required"); editTextTextPostalAddress.requestFocus(); return; } if (amount.isEmpty()) { editTextNumber.setError("Amount is required"); editTextNumber.requestFocus(); return; } formhelper fh = new formhelper(name,language,date,time,address,amount,"None","0"); reference.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(fh); finish(); Toast.makeText(form.this, "Successfully booked", Toast.LENGTH_LONG).show(); Intent intent = new Intent(form.this, client_profile.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } }); editTextTime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TimePickerDialog timePickerDialog = new TimePickerDialog( form.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { hour = hourOfDay; min = minute; String time = hour +":"+ min; //Calendar cal = Calendar.getInstance(); //cal.set(0,0,0,hour,min); SimpleDateFormat f24hours = new SimpleDateFormat( "HH:mm" ); try { Date date=f24hours.parse(time); SimpleDateFormat f12hours=new SimpleDateFormat("hh:mm aa"); editTextTime.setText(f12hours.format(date)); } catch (ParseException e) { e.printStackTrace(); } } },12,0,false ); timePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); timePickerDialog.updateTime(hour,min); timePickerDialog.show(); } }); dateformat=(EditText) findViewById(R.id.dateformatID); final Calendar calendar = Calendar.getInstance(); final int year = calendar.get(Calendar.YEAR); final int month = calendar.get(Calendar.MONTH); final int day = calendar.get(Calendar.DAY_OF_MONTH); dateformat.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { DatePickerDialog datePickerDialog = new DatePickerDialog( form.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int day) { month = month+1; String date = day+"/"+month+"/"+year; dateformat.setText(date); } },year,month,day); datePickerDialog.show(); } }); } }
39.625
127
0.587115
13226a80bb302d7920a2d05c6258801eeae9da8d
1,607
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.appboy.ui; import android.webkit.WebChromeClient; import android.webkit.WebView; // Referenced classes of package com.appboy.ui: // AppboyWebViewActivity class AppboyWebViewActivity$1 extends WebChromeClient { public void onProgressChanged(WebView webview, int i) { if(i < 100) //* 0 0:iload_2 //* 1 1:bipush 100 //* 2 3:icmpge 15 { setProgressBarVisibility(true); // 3 6:aload_0 // 4 7:getfield #15 <Field AppboyWebViewActivity this$0> // 5 10:iconst_1 // 6 11:invokevirtual #25 <Method void AppboyWebViewActivity.setProgressBarVisibility(boolean)> return; // 7 14:return } else { setProgressBarVisibility(false); // 8 15:aload_0 // 9 16:getfield #15 <Field AppboyWebViewActivity this$0> // 10 19:iconst_0 // 11 20:invokevirtual #25 <Method void AppboyWebViewActivity.setProgressBarVisibility(boolean)> return; // 12 23:return } } final AppboyWebViewActivity this$0; AppboyWebViewActivity$1() { this$0 = AppboyWebViewActivity.this; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #15 <Field AppboyWebViewActivity this$0> super(); // 3 5:aload_0 // 4 6:invokespecial #18 <Method void WebChromeClient()> // 5 9:return } }
28.696429
104
0.608587
b176601b964f9838529d23eeece886d25fa3b49b
1,168
package com.youngadessi.demo.auth.exception.handler; import com.youngadessi.demo.auth.exception.NotFoundException; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import java.util.HashMap; import java.util.Map; @ControllerAdvice @Slf4j public class GenericExceptionHandler { @ExceptionHandler(NotFoundException.class) public ResponseEntity<Map> handleNotfoundException(NotFoundException exception) { Map<String, String> response = new HashMap<>(); response.put("message", exception.getMessage()); return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response); } @ExceptionHandler(Exception.class) public ResponseEntity<Map> handleException(Exception exception) { exception.printStackTrace(); Map<String, String> response = new HashMap<>(); response.put("message", exception.getMessage()); return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(response); } }
35.393939
85
0.768836
9826d5cdd816625cec083cc6a3fd6b4b375ae5d3
851
package com.utrust.api.model.merchant; import com.google.gson.annotations.SerializedName; public class LoginMerchantResponse { @SerializedName("data") private Data data; static class Data { @SerializedName("type") private String type; @SerializedName("id") private String id; @SerializedName("attributes") private Attributes attributes; } static class Attributes { @SerializedName("token") private String token; @SerializedName("tfa_missing") private boolean tfa; } public String getType() { return data.type; } public String getId() { return data.id; } public String getToken() { return data.attributes.token; } public boolean isTfa() { return data.attributes.tfa; } }
18.5
50
0.612221
c7b5db0c62ecc73c970041282d56b5b1663e9296
3,448
package de.tototec.cmdoption.handler; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import de.tototec.cmdoption.internal.I18n; import de.tototec.cmdoption.internal.I18n.PreparedI18n; import de.tototec.cmdoption.internal.I18nFactory; /** * Apply an one-arg option to a {@link Boolean} (or <code>boolean</code>) field * or method. * * Evaluates the argument to <code>true</code> if it is "true", "on" or "1". * * You can customize the words interpreted as <code>true</code> or * <code>false</code> by using the non-default constructor. * * @since 0.3.0 */ public class BooleanHandler implements CmdOptionHandler { private final String[] trueWords; private final String[] falseWords; private final boolean caseSensitive; public BooleanHandler() { this(new String[] { "on", "true", "1" }, new String[] { "off", "false", "0" }, false); } /** * If the list of falseWords is empty or <code>null</code>, any words not in * trueWords is considered as false. * * @param trueWords * @param falseWords * @param caseSensitive */ public BooleanHandler(final String[] trueWords, final String[] falseWords, final boolean caseSensitive) { this.trueWords = trueWords; this.falseWords = falseWords; this.caseSensitive = caseSensitive; } public boolean canHandle(final AccessibleObject element, final int argCount) { if (element instanceof Field && argCount == 1) { final Field field = (Field) element; return !Modifier.isFinal(field.getModifiers()) && (field.getType().equals(Boolean.class) || field.getType().equals(boolean.class)); } else if (element instanceof Method && argCount == 1) { final Method method = (Method) element; if (method.getParameterTypes().length == 1) { final Class<?> type = method.getParameterTypes()[0]; return boolean.class.equals(type) || Boolean.class.equals(type); } } return false; } public void applyParams(final Object config, final AccessibleObject element, final String[] args, final String optionName) throws CmdOptionHandlerException { String arg = args[0]; if (!caseSensitive) { arg = arg.toLowerCase(); } Boolean decission = null; for (final String word : trueWords) { if (arg.equals(caseSensitive ? word : word.toLowerCase())) { decission = true; break; } } if (decission == null) { if (falseWords == null || falseWords.length == 0) { decission = false; } else { for (final String word : falseWords) { if (arg.equals(caseSensitive ? word : word.toLowerCase())) { decission = false; break; } } } } if (decission == null) { final I18n i18n = I18nFactory.getI18n(BooleanHandler.class); final PreparedI18n msg = i18n.preparetr("Could not parse argument \"{0}\" as boolean parameter.", args[0]); throw new CmdOptionHandlerException(msg.notr(), msg.tr()); } try { if (element instanceof Field) { final Field field = (Field) element; field.set(config, decission); } else { final Method method = (Method) element; method.invoke(config, decission.booleanValue()); } } catch (final Exception e) { final I18n i18n = I18nFactory.getI18n(BooleanHandler.class); final PreparedI18n msg = i18n.preparetr("Could not apply argument \"{0}\".", args[0]); throw new CmdOptionHandlerException(msg.notr(), e, msg.tr()); } } }
30.245614
110
0.685905
1003a4bfb18e2aef2a91e1479718c802601a62f0
5,467
package io.opensphere.core.model; import java.io.Serializable; import io.opensphere.core.units.length.Length; import io.opensphere.core.units.length.Meters; import io.opensphere.core.util.Constants; import io.opensphere.core.util.MathUtil; import io.opensphere.core.util.lang.UnexpectedEnumException; /** * A model for an altitude above a defined reference level. */ public final class Altitude implements Serializable { /** Zero altitude with ellipsoid reference. */ public static final Altitude ZERO_ELLIPSOID = new Altitude(0., ReferenceLevel.ELLIPSOID); /** Zero altitude with origin reference. */ public static final Altitude ZERO_ORIGIN = new Altitude(0., ReferenceLevel.ORIGIN); /** Zero altitude with terrain reference. */ public static final Altitude ZERO_TERRAIN = new Altitude(0., ReferenceLevel.TERRAIN); /** Serial version UID. */ private static final long serialVersionUID = 1L; /** * The altitude in meters, referenced according to {@link #myReferenceLevel} * . */ private final double myMeters; /** Reference level for the altitude. */ private final ReferenceLevel myReferenceLevel; /** * Create using meters. * * @param altitudeMeters The altitude in meters. * @param referenceLevel The reference level. * @return The altitude instance. */ public static Altitude createFromMeters(double altitudeMeters, ReferenceLevel referenceLevel) { return altitudeMeters == 0. ? getZero(referenceLevel) : new Altitude(altitudeMeters, referenceLevel); } /** * Get a zero altitude constant for the given reference level. * * @param referenceLevel The reference level. * @return The constant. */ private static Altitude getZero(ReferenceLevel referenceLevel) { if (referenceLevel == ReferenceLevel.ELLIPSOID) { return ZERO_ELLIPSOID; } else if (referenceLevel == ReferenceLevel.ORIGIN) { return ZERO_ORIGIN; } else if (referenceLevel == ReferenceLevel.TERRAIN) { return ZERO_TERRAIN; } else { throw new UnexpectedEnumException(referenceLevel); } } /** * Create from a length object. * * @param magnitude The magnitude of the altitude. * @param referenceLevel The reference level for the altitude. */ public Altitude(Length magnitude, ReferenceLevel referenceLevel) { this(magnitude.inMeters(), referenceLevel); } /** * Private constructor to enforce use of factory methods. * * @param altitudeMeters The magnitude of the altitude. * @param altitudeReference The reference level for the altitude. */ private Altitude(double altitudeMeters, ReferenceLevel altitudeReference) { myMeters = altitudeMeters; myReferenceLevel = altitudeReference; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Altitude other = (Altitude)obj; return myReferenceLevel == other.myReferenceLevel && Math.abs(myMeters - other.myMeters) <= MathUtil.DBL_EPSILON; } /** * Get the altitude in kilometers, relative to the level given by * {@link #getReferenceLevel()}. * * @return The altitude in meters. */ public double getKilometers() { return myMeters / Constants.UNIT_PER_KILO; } /** * Get the altitude, relative to the level given by * {@link #getReferenceLevel()}. * * @return The altitude in meters. */ public Length getMagnitude() { return new Meters(myMeters); } /** * Get the altitude in meters, relative to the level given by * {@link #getReferenceLevel()}. * * @return The altitude in meters. */ public double getMeters() { return myMeters; } /** * Get the reference level for the altitude. * * @return The reference level for the altitude. */ public ReferenceLevel getReferenceLevel() { return myReferenceLevel; } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(myMeters); result = prime * result + (int)(temp ^ temp >>> 32); result = prime * result + (myReferenceLevel == null ? 0 : myReferenceLevel.hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()).append(" [").append(getMeters()).append("m ").append(myReferenceLevel).append(']'); return sb.toString(); } /** * Types of altitude reference. */ public enum ReferenceLevel { /** Altitude is relative to the configured ellipsoid. */ ELLIPSOID, /** Altitude is relative to the center of the model. */ ORIGIN, /** Altitude is relative to local elevation. */ TERRAIN, } }
28.623037
130
0.602341
0b0384f663c42e1391a27fbe0d46f3e75c0f3777
349
package qunar.tc.qconfig.server.web.servlet; /** * @author zhenyu.nie created on 2014 2014/10/29 12:17 */ public class ForceLoadV1Servlet extends AbstractForceLoadServlet { private static final long serialVersionUID = 4291294666859848420L; @Override protected String getVersion() { return V1Version; } }
21.8125
71
0.696275
6d8e6e9a8af69e3add7a944487788fa69cd5e808
1,450
/** * */ package com.ricex.aft.servlet.gcm; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** Executor for sending messages to the GCM servers * * @author Mitchell Caisse * */ public enum MessageExecutor { /** The singleton instance */ INSTANCE; /** The executor that will be used to execute sync messages */ private ScheduledExecutorService executor; private MessageExecutor() { //default executor executor = new ScheduledThreadPoolExecutor(1); } /** Executes the given command now * * @param command The command to execute */ public void executeNow(Runnable command) { executor.execute(command); } /** Schedules the specified command to be executed with the specified delay. * * @param command The command to execute * @param delay The delay in units to wait * @param unit The unit of the delay * @return The delayed result of the command */ public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return executor.schedule(command,delay,unit); } /** * @return the executor */ public ScheduledExecutorService getExecutor() { return executor; } /** * @param executor the executor to set */ public void setExecutor(ScheduledExecutorService executor) { this.executor = executor; } }
21.014493
82
0.722069
4193a0768d1fdef53a20705727db40d68332a9e8
3,721
package com.xm.bus.search.self; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Filter; import android.widget.Filterable; import android.widget.TextView; public class AutoCompleteAdapter extends BaseAdapter implements Filterable{ private Context context; private ArrayFilter mFilter; private ArrayList<String> mOriginalValues;//所有的Item private List<String> mObjects;//过滤后的item private final Object mLock = new Object(); private int maxMatch;//最多显示多少个选项,负数表示全部 public AutoCompleteAdapter(Context context,List<String> mObjects,int maxMatch){ this.context=context; this.mObjects=mObjects; this.maxMatch=maxMatch; } public AutoCompleteAdapter(Context context,String[] mObjects,int maxMatch){ this.context=context; this.mObjects=Arrays.asList(mObjects); this.maxMatch=maxMatch; } @Override public int getCount() { if(maxMatch<0||mObjects.size()<maxMatch){//maxMatch负数返回全部,否则返回maxMatch个数 return mObjects.size(); } return maxMatch; } @Override public Object getItem(int position) { return mObjects.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View view, ViewGroup parent) { ViewHolder holder; if(view==null){ holder=new ViewHolder(); LayoutInflater inflater=LayoutInflater.from(context); view=inflater.inflate(android.R.layout.simple_dropdown_item_1line, null); holder.textView=(TextView) view.findViewById(android.R.id.text1); view.setTag(holder); }else{ holder=(ViewHolder) view.getTag(); } holder.textView.setText(mObjects.get(position)); return view; } private class ViewHolder{ TextView textView; } @Override public Filter getFilter() { if(mFilter==null){ mFilter=new ArrayFilter(); } return mFilter; } private class ArrayFilter extends Filter{ @Override protected FilterResults performFiltering(CharSequence prefix) { FilterResults results=new FilterResults(); if(mOriginalValues==null){ synchronized (mLock) { mOriginalValues=new ArrayList<String>(mObjects); } } if(prefix==null||prefix.equals("")){ ArrayList<String> list; synchronized (mLock) { list=new ArrayList<String>(mOriginalValues); } results.values=list; //设置检索结果个数 if(maxMatch<0){//maxMatch负数返回全部检索结果,否则返回maxMatch个数 results.count=list.size(); }else{ results.count=maxMatch; } }else{ String prefixString = prefix.toString().toLowerCase(); ArrayList<String> values; synchronized (mLock) { values=new ArrayList<String>(mOriginalValues); } final int count=values.size(); final ArrayList<String> newValues = new ArrayList<String>(); for(int i=0;i<count;i++){ final String value=values.get(i); final String valueText=value.toString().toLowerCase(); if(valueText.startsWith(prefixString)){ newValues.add(value); } if(maxMatch>0){//当maxMatch非负时,检索结果超过maxMatch时立即停止检索 if(newValues.size()>maxMatch-1){ break; } } } results.values = newValues; results.count = newValues.size(); } return results; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { mObjects = (List<String>) results.values; if (results.count > 0) { notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } } } }
25.486301
80
0.694168
add3eccf02095bc82add51d4d59c9dd7d9c40249
2,692
/* * Copyright 2021 wssccc * * 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.ngscript.parser; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; import org.ngscript.parseroid.grammar.Grammar; import org.ngscript.parseroid.grammar.GrammarLoader; import org.ngscript.parseroid.table.LALRTable; import org.ngscript.parseroid.table.TableGenerator; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; /** * @author wssccc */ @Slf4j public class ParserLoader { private LALRTable table; public static ParserLoader INSTANCE = new ParserLoader(); private ParserLoader() { try { init(); } catch (Exception ex) { throw new RuntimeException(ex); } } public LALRTable getTable() { return table; } private void init() throws Exception { InputStream resource = getClass().getResourceAsStream("/grammar/ngscript-bnf.txt"); if (resource == null) { throw new RuntimeException("Could not load grammar"); } String bnfString = IOUtils.toString(resource, StandardCharsets.UTF_8); String hash = DigestUtils.sha256Hex(bnfString); String tableCacheFile = "ng_bnf_cache_" + hash + ".table"; Path cacheFilePath = Paths.get(System.getProperty("java.io.tmpdir"), tableCacheFile); File cacheFile = cacheFilePath.toFile(); if (cacheFile.exists()) { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(cacheFile))) { table = (LALRTable) ois.readObject(); return; } catch (Exception ex) { log.warn("Failed to load parser table cache", ex); } } // build parser table cache Grammar g = GrammarLoader.loadBnfString(bnfString); table = new TableGenerator(g).generate(false); // write cache file try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(cacheFile))) { oos.writeObject(table); } } }
33.234568
97
0.671248
90a2be4fe3325bebab7764d1ba52e62dc369dce8
10,354
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|parse package|; end_package begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|* import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|common operator|. name|type operator|. name|Date import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|serde2 operator|. name|io operator|. name|DateWritableV2 import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_class specifier|public class|class name|TestSemanticAnalyzer block|{ annotation|@ name|Test specifier|public name|void name|testNormalizeColSpec parameter_list|() throws|throws name|Exception block|{ comment|// Hive normalizes partition spec for dates to yyyy-mm-dd format. Some versions of Java will comment|// accept other formats for Date.valueOf, e.g. yyyy-m-d, and who knows what else in the future; comment|// some will not accept other formats, so we cannot test normalization with them - type check comment|// will fail before it can ever happen. Thus, test in isolation. name|checkNormalization argument_list|( literal|"date" argument_list|, literal|"2010-01-01" argument_list|, literal|"2010-01-01" argument_list|, name|Date operator|. name|valueOf argument_list|( literal|"2010-01-01" argument_list|) argument_list|) expr_stmt|; name|checkNormalization argument_list|( literal|"date" argument_list|, literal|"2010-1-01" argument_list|, literal|"2010-01-01" argument_list|, name|Date operator|. name|valueOf argument_list|( literal|"2010-01-01" argument_list|) argument_list|) expr_stmt|; name|checkNormalization argument_list|( literal|"date" argument_list|, literal|"2010-1-1" argument_list|, literal|"2010-01-01" argument_list|, name|Date operator|. name|valueOf argument_list|( literal|"2010-01-01" argument_list|) argument_list|) expr_stmt|; name|checkNormalization argument_list|( literal|"string" argument_list|, literal|"2010-1-1" argument_list|, literal|"2010-1-1" argument_list|, literal|"2010-1-1" argument_list|) expr_stmt|; try|try block|{ name|checkNormalization argument_list|( literal|"date" argument_list|, literal|"foo" argument_list|, literal|"" argument_list|, literal|"foo" argument_list|) expr_stmt|; comment|// Bad format. name|fail argument_list|( literal|"should throw" argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|SemanticException name|ex parameter_list|) block|{ } try|try block|{ name|checkNormalization argument_list|( literal|"date" argument_list|, literal|"2010-01-01" argument_list|, literal|"2010-01-01" argument_list|, literal|"2010-01-01" argument_list|) expr_stmt|; comment|// Bad value type. name|fail argument_list|( literal|"should throw" argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|SemanticException name|ex parameter_list|) block|{ } block|} specifier|public name|void name|checkNormalization parameter_list|( name|String name|colType parameter_list|, name|String name|originalColSpec parameter_list|, name|String name|result parameter_list|, name|Object name|colValue parameter_list|) throws|throws name|SemanticException block|{ specifier|final name|String name|colName init|= literal|"col" decl_stmt|; name|Map argument_list|< name|String argument_list|, name|String argument_list|> name|partSpec init|= operator|new name|HashMap argument_list|< name|String argument_list|, name|String argument_list|> argument_list|() decl_stmt|; name|partSpec operator|. name|put argument_list|( name|colName argument_list|, name|originalColSpec argument_list|) expr_stmt|; name|BaseSemanticAnalyzer operator|. name|normalizeColSpec argument_list|( name|partSpec argument_list|, name|colName argument_list|, name|colType argument_list|, name|originalColSpec argument_list|, name|colValue argument_list|) expr_stmt|; name|assertEquals argument_list|( name|result argument_list|, name|partSpec operator|. name|get argument_list|( name|colName argument_list|) argument_list|) expr_stmt|; if|if condition|( name|colValue operator|instanceof name|Date condition|) block|{ name|DateWritableV2 name|dw init|= operator|new name|DateWritableV2 argument_list|( operator|( name|Date operator|) name|colValue argument_list|) decl_stmt|; name|BaseSemanticAnalyzer operator|. name|normalizeColSpec argument_list|( name|partSpec argument_list|, name|colName argument_list|, name|colType argument_list|, name|originalColSpec argument_list|, name|dw argument_list|) expr_stmt|; name|assertEquals argument_list|( name|result argument_list|, name|partSpec operator|. name|get argument_list|( name|colName argument_list|) argument_list|) expr_stmt|; block|} block|} annotation|@ name|Test specifier|public name|void name|testUnescapeSQLString parameter_list|() block|{ name|assertEquals argument_list|( literal|"abcdefg" argument_list|, name|BaseSemanticAnalyzer operator|. name|unescapeSQLString argument_list|( literal|"\"abcdefg\"" argument_list|) argument_list|) expr_stmt|; comment|// String enclosed by single quotes. name|assertEquals argument_list|( literal|"C0FFEE" argument_list|, name|BaseSemanticAnalyzer operator|. name|unescapeSQLString argument_list|( literal|"\'C0FFEE\'" argument_list|) argument_list|) expr_stmt|; comment|// Strings including single escaped characters. name|assertEquals argument_list|( literal|"\u0000" argument_list|, name|BaseSemanticAnalyzer operator|. name|unescapeSQLString argument_list|( literal|"'\\0'" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"\'" argument_list|, name|BaseSemanticAnalyzer operator|. name|unescapeSQLString argument_list|( literal|"\"\\'\"" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"\"" argument_list|, name|BaseSemanticAnalyzer operator|. name|unescapeSQLString argument_list|( literal|"'\\\"'" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"\b" argument_list|, name|BaseSemanticAnalyzer operator|. name|unescapeSQLString argument_list|( literal|"\"\\b\"" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"\n" argument_list|, name|BaseSemanticAnalyzer operator|. name|unescapeSQLString argument_list|( literal|"'\\n'" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"\r" argument_list|, name|BaseSemanticAnalyzer operator|. name|unescapeSQLString argument_list|( literal|"\"\\r\"" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"\t" argument_list|, name|BaseSemanticAnalyzer operator|. name|unescapeSQLString argument_list|( literal|"'\\t'" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"\u001A" argument_list|, name|BaseSemanticAnalyzer operator|. name|unescapeSQLString argument_list|( literal|"\"\\Z\"" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"\\" argument_list|, name|BaseSemanticAnalyzer operator|. name|unescapeSQLString argument_list|( literal|"'\\\\'" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"\\%" argument_list|, name|BaseSemanticAnalyzer operator|. name|unescapeSQLString argument_list|( literal|"\"\\%\"" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"\\_" argument_list|, name|BaseSemanticAnalyzer operator|. name|unescapeSQLString argument_list|( literal|"'\\_'" argument_list|) argument_list|) expr_stmt|; comment|// String including '\000' style literal characters. name|assertEquals argument_list|( literal|"3 + 5 = \u0038" argument_list|, name|BaseSemanticAnalyzer operator|. name|unescapeSQLString argument_list|( literal|"'3 + 5 = \\070'" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"\u0000" argument_list|, name|BaseSemanticAnalyzer operator|. name|unescapeSQLString argument_list|( literal|"\"\\000\"" argument_list|) argument_list|) expr_stmt|; comment|// String including invalid '\000' style literal characters. name|assertEquals argument_list|( literal|"256" argument_list|, name|BaseSemanticAnalyzer operator|. name|unescapeSQLString argument_list|( literal|"\"\\256\"" argument_list|) argument_list|) expr_stmt|; comment|// String including a '\u0000' style literal characters (\u732B is a cat in Kanji). name|assertEquals argument_list|( literal|"How cute \u732B are" argument_list|, name|BaseSemanticAnalyzer operator|. name|unescapeSQLString argument_list|( literal|"\"How cute \\u732B are\"" argument_list|) argument_list|) expr_stmt|; comment|// String including a surrogate pair character comment|// (\uD867\uDE3D is Okhotsk atka mackerel in Kanji). name|assertEquals argument_list|( literal|"\uD867\uDE3D is a fish" argument_list|, name|BaseSemanticAnalyzer operator|. name|unescapeSQLString argument_list|( literal|"\"\\uD867\uDE3D is a fish\"" argument_list|) argument_list|) expr_stmt|; block|} block|} end_class end_unit
17.489865
813
0.792544
66e7d027a8d489d0fb9945b986132a8714b68409
6,307
/* * Copyright 2003-2009 the original author or authors. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.jdon.jivejdon.presentation.action.message; import com.jdon.controller.WebAppUtil; import com.jdon.controller.events.EventModel; import com.jdon.jivejdon.util.Constants; import com.jdon.jivejdon.domain.model.ForumMessage; import com.jdon.jivejdon.infrastructure.dto.AnemicMessageDTO; import com.jdon.jivejdon.presentation.form.MessageForm; import com.jdon.jivejdon.api.ForumMessageService; import com.jdon.model.ModelForm; import com.jdon.strutsutil.FormBeanUtil; import com.jdon.util.UtilValidate; import org.apache.commons.beanutils.PropertyUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.struts.action.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.InvocationTargetException; /** * Response for post a reply message. * * @author banq * */ public class ReBlogAction extends Action { private final static Logger logger = LogManager.getLogger(ReBlogAction.class); public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { logger.debug("enter ReBlogAction"); MessageForm messageReplyForm = (MessageForm) form; try { if (!UtilValidate.isEmpty(request.getParameter("onlyreblog"))) onlyreBlog(messageReplyForm, request); else if (!UtilValidate.isEmpty(request.getParameter("reblog"))) reBlog(messageReplyForm, request); else return mapping.findForward("onlyreply"); } catch (Exception e) { ActionMessages errors = new ActionMessages(); ActionMessage error = new ActionMessage(e.getMessage()); errors.add(ActionMessages.GLOBAL_MESSAGE, error); saveErrors(request, errors); return mapping.findForward(FormBeanUtil.FORWARD_FAILURE_NAME); } return mapping.findForward(FormBeanUtil.FORWARD_SUCCESS_NAME); } protected void onlyreBlog(MessageForm messageReplyForm, HttpServletRequest request) throws Exception { try { if (messageReplyForm.getParentMessage() == null || messageReplyForm.getParentMessage().getMessageId() == null) { throw new Exception("parentMessage.messageId is null"); } Long pmessageId = messageReplyForm.getParentMessage().getMessageId(); ForumMessageService forumMessageService = (ForumMessageService) WebAppUtil.getService("forumMessageService", request); ForumMessage pmsg = forumMessageService.getMessage(pmessageId); if (pmsg == null) { throw new Exception("parentMessage is null"); } Long topicMessageId = createTopic(messageReplyForm, request); if (topicMessageId == null) throw new Exception(Constants.ERRORS); forumMessageService.reBlog(pmessageId, topicMessageId); // reload reblog to collection, the parant has new child; pmsg.setReBlogVO(null); messageReplyForm.setMessageId(topicMessageId); } catch (Exception e) { logger.error(e); throw new Exception(e); } } protected void reBlog(MessageForm messageReplyForm, HttpServletRequest request) throws Exception { try { Long topicMessageId = createTopic(messageReplyForm, request); if (topicMessageId == null) throw new Exception(Constants.ERRORS); Long replyMessageId = createReply(messageReplyForm, request); if (replyMessageId == null) throw new Exception(Constants.ERRORS); ForumMessageService forumMessageService = (ForumMessageService) WebAppUtil.getService("forumMessageService", request); forumMessageService.reBlog(replyMessageId, topicMessageId); messageReplyForm.setMessageId(replyMessageId); } catch (Exception e) { logger.error(e); throw new Exception(e); } } protected Long createTopic(MessageForm messageReplyForm, HttpServletRequest request) throws Exception { ForumMessageService forumMessageService = (ForumMessageService) WebAppUtil.getService("forumMessageService", request); AnemicMessageDTO anemicMessageDTO = new AnemicMessageDTO(); Long topicMessageId = null; try { formCopyToModelIF(messageReplyForm, anemicMessageDTO); EventModel em = new EventModel(); em.setModelIF(anemicMessageDTO); topicMessageId = forumMessageService.createTopicMessage(em); if (em.getErrors() != null) { throw new Exception(em.getErrors()); } } catch (Exception e) { logger.error(e); throw new Exception(Constants.ERRORS); } return topicMessageId; } protected Long createReply(MessageForm messageReplyForm, HttpServletRequest request) throws Exception { Long replyMessageId = null; try { AnemicMessageDTO anemicMessageDTO = new AnemicMessageDTO(); formCopyToModelIF(messageReplyForm, anemicMessageDTO); EventModel em = new EventModel(); em = new EventModel(); em.setModelIF(anemicMessageDTO); ForumMessageService forumMessageService = (ForumMessageService) WebAppUtil.getService("forumMessageService", request); replyMessageId = forumMessageService.createReplyMessage(em); if (em.getErrors() != null) { throw new Exception(em.getErrors()); } } catch (Exception e) { logger.error(e); throw new Exception(Constants.ERRORS); } return replyMessageId; } public void formCopyToModelIF(ModelForm form, Object model) throws Exception { if (model == null || form == null) return; try { PropertyUtils.copyProperties(model, form); } catch (InvocationTargetException ie) { String error = "error happened in getXXX method of ModelForm:" + form.getClass().getName() + " error:" + ie; throw new Exception(error); } catch (Exception e) { String error = " ModelForm:" + form.getClass().getName() + " copy To Model:" + model.getClass().getName() + " error:" + e; throw new Exception(error); } } }
36.456647
146
0.758998
41f343dbdaacbb069d2fd638bf39a2da5c38c40c
7,652
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package ai.vespa.rankingexpression.importer.tensorflow; import com.yahoo.searchlib.rankingexpression.RankingExpression; import com.yahoo.searchlib.rankingexpression.evaluation.Context; import com.yahoo.searchlib.rankingexpression.evaluation.ContextIndex; import com.yahoo.searchlib.rankingexpression.evaluation.ExpressionOptimizer; import com.yahoo.searchlib.rankingexpression.evaluation.MapContext; import com.yahoo.searchlib.rankingexpression.evaluation.TensorValue; import ai.vespa.rankingexpression.importer.ImportedModel; import com.yahoo.searchlib.rankingexpression.rule.CompositeNode; import com.yahoo.searchlib.rankingexpression.rule.ExpressionNode; import com.yahoo.searchlib.rankingexpression.rule.ReferenceNode; import com.yahoo.tensor.Tensor; import com.yahoo.tensor.TensorType; import org.tensorflow.SavedModelBundle; import org.tensorflow.Session; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.util.List; import static org.junit.Assert.assertEquals; /** * Helper for TensorFlow import tests: Imports a model and provides asserts on it. * * @author bratseth */ public class TestableTensorFlowModel { private SavedModelBundle tensorFlowModel; private ImportedModel model; // Spec of the input vector private final boolean floatInput; // false: double private final int d0Size; private final int d1Size; public TestableTensorFlowModel(String modelName, String modelDir) { this(modelName, modelDir, 1, 784); } public TestableTensorFlowModel(String modelName, String modelDir, int d0Size, int d1Size) { this(modelName, modelDir, d0Size, d1Size, true); } public TestableTensorFlowModel(String modelName, String modelDir, int d0Size, int d1Size, boolean floatInput) { tensorFlowModel = SavedModelBundle.load(modelDir, "serve"); model = new TensorFlowImporter().importModel(modelName, modelDir, tensorFlowModel); this.d0Size = d0Size; this.d1Size = d1Size; this.floatInput = floatInput; } public ImportedModel get() { return model; } /** Compare that computing the expressions produce the same result to within some tolerance delta */ public void assertEqualResultSum(String inputName, String operationName, double delta) { Tensor tfResult = tensorFlowExecute(tensorFlowModel, inputName, operationName); Context context = contextFrom(model); Tensor placeholder = vespaInputArgument(); context.put(inputName, new TensorValue(placeholder)); model.functions().forEach((k, v) -> evaluateFunction(context, model, k)); RankingExpression expression = model.expressions().get(operationName); ExpressionOptimizer optimizer = new ExpressionOptimizer(); optimizer.optimize(expression, (ContextIndex)context); Tensor vespaResult = expression.evaluate(context).asTensor(); assertEquals("Operation '" + operationName + "' produces equal results", tfResult.sum().asDouble(), vespaResult.sum().asDouble(), delta); } /** Compare tensors 100% exactly */ public void assertEqualResult(String inputName, String operationName) { Tensor tfResult = tensorFlowExecute(tensorFlowModel, inputName, operationName); Context context = contextFrom(model); Tensor inputValue = vespaInputArgument(); context.put(inputName, new TensorValue(inputValue)); model.functions().forEach((k, v) -> evaluateFunction(context, model, k)); RankingExpression expression = model.expressions().get(operationName); ExpressionOptimizer optimizer = new ExpressionOptimizer(); optimizer.optimize(expression, (ContextIndex)context); Tensor vespaResult = expression.evaluate(context).asTensor(); assertEquals("Operation '" + operationName + "': Actual value from Vespa equals expected value from TensorFlow", tfResult, vespaResult); } private Tensor tensorFlowExecute(SavedModelBundle model, String inputName, String operationName) { Session.Runner runner = model.session().runner(); org.tensorflow.Tensor<?> input = floatInput ? tensorFlowFloatInputArgument() : tensorFlowDoubleInputArgument(); runner.feed(inputName, input); List<org.tensorflow.Tensor<?>> results = runner.fetch(operationName).run(); assertEquals(1, results.size()); return TensorConverter.toVespaTensor(results.get(0)); } static Context contextFrom(ImportedModel result) { TestableModelContext context = new TestableModelContext(); result.largeConstants().forEach((name, tensor) -> context.put("constant(" + name + ")", new TensorValue(Tensor.from(tensor)))); result.smallConstants().forEach((name, tensor) -> context.put("constant(" + name + ")", new TensorValue(Tensor.from(tensor)))); return context; } /** Must be the same as vespaInputArgument() */ private org.tensorflow.Tensor<?> tensorFlowDoubleInputArgument() { DoubleBuffer fb = DoubleBuffer.allocate(d0Size * d1Size); int i = 0; for (int d0 = 0; d0 < d0Size; d0++) for (int d1 = 0; d1 < d1Size; ++d1) fb.put(i++, (d1 * 1.0 / d1Size)); return org.tensorflow.Tensor.create(new long[]{ d0Size, d1Size }, fb); } /** Must be the same as vespaInputArgument() */ private org.tensorflow.Tensor<?> tensorFlowFloatInputArgument() { FloatBuffer fb = FloatBuffer.allocate(d0Size * d1Size); int i = 0; for (int d0 = 0; d0 < d0Size; d0++) for (int d1 = 0; d1 < d1Size; ++d1) fb.put(i++, (float)(d1 * 1.0 / d1Size)); return org.tensorflow.Tensor.create(new long[]{ d0Size, d1Size }, fb); } /** Must be the same as tensorFlowFloatInputArgument() */ private Tensor vespaInputArgument() { Tensor.Builder b = Tensor.Builder.of(new TensorType.Builder().indexed("d0", d0Size).indexed("d1", d1Size).build()); for (int d0 = 0; d0 < d0Size; d0++) for (int d1 = 0; d1 < d1Size; d1++) b.cell(d1 * 1.0 / d1Size, d0, d1); return b.build(); } private void evaluateFunction(Context context, ImportedModel model, String functionName) { if (!context.names().contains(functionName)) { RankingExpression e = RankingExpression.from(model.functions().get(functionName)); evaluateFunctionDependencies(context, model, e.getRoot()); context.put(functionName, new TensorValue(e.evaluate(context).asTensor())); } } private void evaluateFunctionDependencies(Context context, ImportedModel model, ExpressionNode node) { if (node instanceof ReferenceNode) { String name = node.toString(); if (model.functions().containsKey(name)) { evaluateFunction(context, model, name); } } else if (node instanceof CompositeNode) { for (ExpressionNode child : ((CompositeNode)node).children()) { evaluateFunctionDependencies(context, model, child); } } } private static class TestableModelContext extends MapContext implements ContextIndex { @Override public int size() { return bindings().size(); } @Override public int getIndex(String name) { throw new UnsupportedOperationException(this + " does not support index lookup by name"); } } }
43.977011
135
0.68505
e15cf725f77aa0d7360fca37dd8528d60abc5df1
750
package question2; import java.util.ArrayList; public class GameWorld { private ArrayList<Placeable> placeableItems; public GameWorld() { placeableItems = new ArrayList<Placeable>(); } public Placeable getPlaceableItem(int index) { if(!placeableItems.isEmpty() && index >= 0 && index < placeableItems.size()) { return placeableItems.get(index); } return null; } public void addPlaceableItem(Placeable item) { if(item != null) { placeableItems.add(item); } } public void removePlaceableItem(int index) { if(!placeableItems.isEmpty() && index >= 0 && index < placeableItems.size()) { placeableItems.remove(index); } } public void removePlaceableItem(Placeable item) { placeableItems.remove(item); } }
20.833333
80
0.702667
85633009b80be5f67838ff40dc131cd17258a879
1,009
package br.com.softblue.loucademia.interfaces.shared.web; import java.io.Serializable; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.ApplicationScoped; import javax.inject.Named; import br.com.softblue.loucademia.application.service.DataService; import br.com.softblue.loucademia.domain.aluno.Aluno.Sexo; import br.com.softblue.loucademia.domain.aluno.Aluno.Situacao; import br.com.softblue.loucademia.domain.aluno.Estado; @Named @ApplicationScoped public class DataBean implements Serializable { private static final long serialVersionUID = 1L; @EJB private DataService dataService; public Sexo[] getSexos() { return dataService.getSexos(); } public Situacao[] getSituacoes() { return dataService.getSituacoes(); } public List<Estado> getEstados() { return dataService.listEstados(); } public String formatTelefone(Integer ddd, Integer numero) { if (ddd == null || numero == null) { return ""; } return "(" + ddd + ") " + numero; } }
22.931818
66
0.750248
6055dc20a57d559698b7fb3b1173f11d12e1ce58
146
package com.example.springlearndemo.aop.overview; public interface EchoService { String echo(String message) throws NullPointerException; }
20.857143
60
0.808219
4475b5c7a7a0920a5eb8c0027cf1f687f1a5ab27
1,249
/* * Copyright 1999-2015 dangdang.com. * <p> * 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. * </p> */ package com.dangdang.ddframe.job; import com.dangdang.ddframe.reg.zookeeper.NestedZookeeperServers; import com.google.common.base.Joiner; import org.junit.Before; public abstract class AbstractNestedZookeeperBaseTest { public static final int PORT = 3181; public static final String TEST_TEMP_DIRECTORY = String.format("target/test_zk_data/%s/", System.nanoTime()); public static final String ZK_CONNECTION_STRING = Joiner.on(":").join("localhost", PORT); @Before public void setUp() { NestedZookeeperServers.getInstance().startServerIfNotStarted(PORT, TEST_TEMP_DIRECTORY); } }
33.756757
113
0.733387
b595f828dac62f3ee777074c61616b8325b59448
1,452
package com.law.flappy.input; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; public class InputHandler implements KeyListener, MouseListener { public boolean[] keys = new boolean[65536]; public boolean[] mouseButtons = new boolean[4]; public int mouseX, mouseY; @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if(keyCode > 0 && keyCode < keys.length) { keys[keyCode] = true; } } @Override public void keyReleased(KeyEvent e) { int keyCode = e.getKeyCode(); if(keyCode > 0 && keyCode < keys.length) { keys[keyCode] = false; } } @Override public void mousePressed(MouseEvent e) { int mouseCode = e.getButton(); if(mouseCode > 0 && mouseCode < mouseButtons.length) { mouseX = e.getX(); mouseY = e.getY(); mouseButtons[mouseCode] = true; } } @Override public void mouseReleased(MouseEvent e) { int mouseCode = e.getButton(); if(mouseCode > 0 && mouseCode < mouseButtons.length) { mouseX = e.getX(); mouseY = e.getY(); mouseButtons[mouseCode] = false; } } @Override public void keyTyped(KeyEvent e) { } @Override public void mouseClicked(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } }
19.890411
65
0.686639
7f0684d2697b3017b14553d5ec1c4cfd8ac09eb8
7,020
package com.github.trackexpenses.fragments; import android.content.Intent; import android.content.res.ColorStateList; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.cardview.widget.CardView; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.github.trackexpenses.IItems; import com.github.trackexpenses.R; import com.github.trackexpenses.activities.ExpenseActivity; import com.github.trackexpenses.activities.MainActivity; import com.github.trackexpenses.adapters.ExpenseViewHolder; import com.github.trackexpenses.adapters.MultipleViewAdapter; import com.github.trackexpenses.models.Category; import com.github.trackexpenses.models.Expense; import com.github.trackexpenses.models.Week; import com.github.trackexpenses.utils.TimeUtils; import com.google.gson.Gson; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.ArrayList; import static com.github.trackexpenses.utils.WeekUtils.getNow; public class HomeFragment extends Fragment implements ExpenseViewHolder.ExpenseClickListener { private static final String TAG = "HomeFragment"; private static final String ARG_PARAM1 = "ARG_PARAM1"; private int arg; private RecyclerView week_overview; private ProgressBar now_progress; private TextView expense_home, remaining, empty_warning; private CardView card_info; private MultipleViewAdapter adapter; private ArrayList<IItems> items; private ArrayList<Category> categories; private Week now; public HomeFragment() { // Required empty public constructor } public static HomeFragment newInstance(int arg) { HomeFragment fragment = new HomeFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, new Gson().toJson(arg)); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG,"onCreate"); if (getArguments() != null) { arg = new Gson().fromJson(getArguments().getString(ARG_PARAM1), Integer.class); } fetchData(); } public boolean fetchData() { if(getActivity() == null) { Log.d(TAG,"Error getActivity NULL"); return false; } now = getNow(((MainActivity) getActivity()).weeks); //fetch data ArrayList<Expense> weekly_expenses = ((MainActivity) getActivity()).db.getCurrentWeekExpenses(); categories = ((MainActivity) getActivity()).db.getCategories(); items = TimeUtils.separateWithTitle(weekly_expenses,false); return true; } public void refresh() { Log.d(TAG,"refresh"); if (getView() == null) { Log.d(TAG,"VIEW NULL"); fetchData(); return; } boolean wasNul = false; if(now == null) { setupView(); wasNul = true; } if(fetchData()) { if(wasNul) { setupView(); } if(now == null) { setupView(); } else updateCardView(); Log.d(TAG,"NOW: " + now); if(adapter != null) { adapter.setCurrency(((MainActivity)getActivity()).currency); adapter.setItems(items); adapter.setCategories(categories); adapter.notifyDataSetChanged(); } } } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); week_overview = view.findViewById(R.id.current_week_expenses); now_progress = view.findViewById(R.id.now_progress); expense_home = view.findViewById(R.id.expense_home); remaining = view.findViewById(R.id.remaining); card_info = view.findViewById(R.id.card_info); empty_warning = view.findViewById(R.id.empty_warning); setupView(); } private void setupView() { //This case happen ONLY if no expenses has been made this week if(now == null) { empty_warning.setVisibility(View.VISIBLE); card_info.setVisibility(View.GONE); return; } else { empty_warning.setVisibility(View.GONE); card_info.setVisibility(View.VISIBLE); } if(getActivity() == null) { Log.d(TAG,"Error getActivity NULL"); return; } updateCardView(); if(adapter == null) adapter = new MultipleViewAdapter(items, categories, ((MainActivity)getActivity()).currency, this); week_overview.setAdapter(adapter); week_overview.setLayoutManager(new LinearLayoutManager(getContext())); } private void updateCardView() { Log.d(TAG,"updateCardView"); MainActivity main = (MainActivity) getActivity(); DecimalFormat df = new DecimalFormat("#.##"); df.setRoundingMode(RoundingMode.CEILING); expense_home.setText(main.currency + " " + df.format(now.getSpent())); remaining.setText(main.currency + " " + df.format(now.getGoal()-now.getSpent())); if(now.getSpent() < now.getGoal()) { now_progress.setMax((int) now.getGoal()); now_progress.setProgress((int) now.getSpent()); now_progress.setProgressTintList(ColorStateList.valueOf(getContext().getColor(R.color.purple))); } else { now_progress.setMax(100); now_progress.setProgress(100); now_progress.setProgressTintList(ColorStateList.valueOf(getContext().getColor(R.color.red))); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_home, container, false); } @Override public void onItemClick(View view, int position) { if(getActivity() == null) { Log.d(TAG,"onItemClick getActivity null returning."); return; } Log.d(TAG,"Clicked " + ((Expense) items.get(position)).getTitle() ); Intent intent = new Intent(getActivity(), ExpenseActivity.class); intent.putExtra("categories", new Gson().toJson(categories)); intent.putExtra("expense", new Gson().toJson(items.get(position))); intent.putExtra("settings", new Gson().toJson(((MainActivity) getActivity()).getSettings())); getActivity().startActivityForResult(intent, MainActivity.EXPENSE_ACTIVITY); } }
32.201835
111
0.646439
78ccd9bcac540d6194583e7b99c0092082000606
6,396
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ /* * @(#)DeliveryStatus.java 1.6 07/05/04 */ package com.sun.mail.dsn; import java.io.*; import java.util.*; import javax.activation.*; import javax.mail.*; import javax.mail.internet.*; import com.sun.mail.util.LineOutputStream; // XXX /** * A message/delivery-status message content, as defined in * <A HREF="http://www.ietf.org/rfc/rfc3464.txt">RFC 3464</A>. */ public class DeliveryStatus { private static boolean debug = false; static { try { String s = System.getProperty("mail.dsn.debug"); // default to false debug = s != null && !s.equalsIgnoreCase("false"); } catch (SecurityException sex) { // ignore it } } /** * The DSN fields for the message. */ protected InternetHeaders messageDSN; /** * The DSN fields for each recipient. */ protected InternetHeaders[] recipientDSN; /** * Construct a delivery status notification with no content. */ public DeliveryStatus() throws MessagingException { messageDSN = new InternetHeaders(); recipientDSN = new InternetHeaders[0]; } /** * Construct a delivery status notification by parsing the * supplied input stream. */ public DeliveryStatus(InputStream is) throws MessagingException, IOException { messageDSN = new InternetHeaders(is); if (debug) System.out.println("DSN: got messageDSN"); Vector v = new Vector(); try { while (is.available() > 0) { InternetHeaders h = new InternetHeaders(is); if (debug) System.out.println("DSN: got recipientDSN"); v.addElement(h); } } catch (EOFException ex) { if (debug) System.out.println("DSN: got EOFException"); } if (debug) System.out.println("DSN: recipientDSN size " + v.size()); recipientDSN = new InternetHeaders[v.size()]; v.copyInto(recipientDSN); } /** * Return all the per-message fields in the delivery status notification. * The fields are defined as: * * <pre> * per-message-fields = * [ original-envelope-id-field CRLF ] * reporting-mta-field CRLF * [ dsn-gateway-field CRLF ] * [ received-from-mta-field CRLF ] * [ arrival-date-field CRLF ] * *( extension-field CRLF ) * </pre> */ // XXX - could parse each of these fields public InternetHeaders getMessageDSN() { return messageDSN; } /** * Set the per-message fields in the delivery status notification. */ public void setMessageDSN(InternetHeaders messageDSN) { this.messageDSN = messageDSN; } /** * Return the number of recipients for which we have * per-recipient delivery status notification information. */ public int getRecipientDSNCount() { return recipientDSN.length; } /** * Return the delivery status notification information for * the specified recipient. */ public InternetHeaders getRecipientDSN(int n) { return recipientDSN[n]; } /** * Add deliver status notification information for another * recipient. */ public void addRecipientDSN(InternetHeaders h) { InternetHeaders[] rh = new InternetHeaders[recipientDSN.length + 1]; System.arraycopy(recipientDSN, 0, rh, 0, recipientDSN.length); recipientDSN = rh; recipientDSN[recipientDSN.length - 1] = h; } public void writeTo(OutputStream os) throws IOException, MessagingException { // see if we already have a LOS LineOutputStream los = null; if (os instanceof LineOutputStream) { los = (LineOutputStream) os; } else { los = new LineOutputStream(os); } writeInternetHeaders(messageDSN, los); los.writeln(); for (int i = 0; i < recipientDSN.length; i++) { writeInternetHeaders(recipientDSN[i], los); los.writeln(); } } private static void writeInternetHeaders(InternetHeaders h, LineOutputStream los) throws IOException { Enumeration e = h.getAllHeaderLines(); try { while (e.hasMoreElements()) los.writeln((String)e.nextElement()); } catch (MessagingException mex) { Exception ex = mex.getNextException(); if (ex instanceof IOException) throw (IOException)ex; else throw new IOException("Exception writing headers: " + mex); } } public String toString() { return "DeliveryStatus: Reporting-MTA=" + messageDSN.getHeader("Reporting-MTA", null) + ", #Recipients=" + recipientDSN.length; } }
30.898551
79
0.682458
c8c59f4abfc2fbf3f67df9921a32a67226da6876
2,529
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.wgzhao.datax.plugin.writer.hdfswriter; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Created by shf on 15/10/8. */ public class Key { // must have public static final String PATH = "path"; //must have public static final String DEFAULT_FS = "defaultFS"; //must have public static final String FILE_TYPE = "fileType"; // must have public static final String FILE_NAME = "fileName"; // must have for column public static final String COLUMN = "column"; public static final String NAME = "name"; public static final String TYPE = "type"; // public static final String DATE_FORMAT = "dateFormat" // must have public static final String WRITE_MODE = "writeMode"; // must have public static final String FIELD_DELIMITER = "fieldDelimiter"; // not must, default UTF-8 public static final String ENCODING = "encoding"; // not must, default no compress public static final String COMPRESS = "compress"; // not must, not default \N // public static final String NULL_FORMAT = "nullFormat" // Kerberos public static final String HAVE_KERBEROS = "haveKerberos"; public static final String KERBEROS_KEYTAB_FILE_PATH = "kerberosKeytabFilePath"; public static final String KERBEROS_PRINCIPAL = "kerberosPrincipal"; // hadoop config public static final String HADOOP_CONFIG = "hadoopConfig"; // decimal type public static final String PRECISION = "precision"; public static final String SCALE = "scale"; // hdfs format protected static final Set<String> SUPPORT_FORMAT = new HashSet<>(Arrays.asList("ORC", "PARQUET", "TEXT")); private Key() {} }
36.128571
111
0.713325
85e545d60ad17599db781532c2d550e39854291f
246
package com.joindata.demo.pangu.dubbo.provider.biz; public interface DubboProviderService { /** * 生成一些 UUID * * @param count 生成几个 * @return 生成后的 UUID 数组 */ public String[] generateUuid(int count); }
18.923077
52
0.601626
cfb22b6df8387c9c57c9ec32714e07b93a61bdfb
493
package io.github.privacystreams.sensor; import android.hardware.Sensor; import android.hardware.SensorEvent; /** * Provide a live stream of air pressure sensor updates. */ class AirPressureUpdatesProvider extends SensorUpdatesProvider { AirPressureUpdatesProvider(int sensorDelay) { super(Sensor.TYPE_PRESSURE, sensorDelay); } @Override protected void handleSensorEvent(SensorEvent sensorEvent) { output(new AirPressure(sensorEvent.values[0])); } }
23.47619
64
0.750507
3a8578551f581e90b36075d7b47e359bb0b168da
8,712
package aQute.bnd.classpath; import java.io.*; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.jdt.core.*; import org.eclipse.jdt.ui.wizards.*; import org.eclipse.jface.viewers.*; import org.eclipse.jface.wizard.*; import org.eclipse.swt.*; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; import aQute.bnd.build.*; import aQute.bnd.plugin.*; public class BndContainerPage extends WizardPage implements IClasspathContainerPage, IClasspathContainerPageExtension { // private Activator activator = Activator.getActivator(); private Table table; private Project model; private File basedir; private IJavaProject javaProject; /** * Default Constructor - sets title, page name, description */ public BndContainerPage() { super("bnd", "bnd - classpath", null); setDescription("Ensures that bnd sees the same classpath as eclipse. The table will show the current contents. If there is no bnd file, you can create it with the button"); setPageComplete(true); } /* * (non-Javadoc) * * @see org.eclipse.jdt.ui.wizards.IClasspathContainerPageExtension#initialize(org.eclipse.jdt.core.IJavaProject, * org.eclipse.jdt.core.IClasspathEntry[]) */ public void initialize(IJavaProject project, IClasspathEntry[] currentEntries) { javaProject = project; model = Activator.getDefault().getCentral().getModel(project); basedir = project.getProject().getLocation().makeAbsolute().toFile(); } /* * (non-Javadoc) * * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) */ public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NULL); composite.setLayout(new FormLayout()); composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL)); composite.setFont(parent.getFont()); setControl(composite); final Button wCreate = new Button(composite, SWT.NONE); wCreate.setEnabled(model == null); final FormData fd_wCreate = new FormData(); fd_wCreate.bottom = new FormAttachment(100, -5); fd_wCreate.right = new FormAttachment(100, -4); wCreate.setLayoutData(fd_wCreate); wCreate.setText("Create bnd.bnd"); final TableViewer tableViewer = new TableViewer(composite, SWT.BORDER); table = tableViewer.getTable(); final FormData fd_table = new FormData(); fd_table.top = new FormAttachment(0, 3); fd_table.left = new FormAttachment(0, 3); fd_table.right = new FormAttachment(100, -4); fd_table.bottom = new FormAttachment(100, -37); table.setLayoutData(fd_table); table.setLinesVisible(true); table.setHeaderVisible(true); final TableColumn wBsn = new TableColumn(table, SWT.NONE); wBsn.setWidth(200); wBsn.setText("Bundle Symbolic Name"); final TableColumn wVersion = new TableColumn(table, SWT.NONE); wVersion.setWidth(100); wVersion.setText("Version"); final TableColumn wOptions = new TableColumn(table, SWT.NONE); wOptions.setWidth(200); wOptions.setText("Options"); final TableColumn wFile = new TableColumn(table, SWT.NONE); wFile.setWidth(100); wFile.setText("File"); tableViewer.setContentProvider(new IStructuredContentProvider() { public Object[] getElements(Object inputElement) { if (model != null) try { return model.getBuildpath().toArray(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return new Object[0]; } public void dispose() { // TODO Auto-generated method stub } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } }); tableViewer.setLabelProvider(new ITableLabelProvider() { public Image getColumnImage(Object element, int columnIndex) { // TODO Auto-generated method stub return null; } public String getColumnText(Object element, int columnIndex) { Container c = (Container) element; switch (columnIndex) { case 0: return c.getBundleSymbolicName(); case 1: return c.getVersion(); case 2: return c.getError(); case 3: return c.getFile() + " (" + (c.getFile()!=null && c.getFile().exists() ? "exists" : "?") + ")"; } return null; } public void addListener(ILabelProviderListener listener) { // TODO Auto-generated method stub } public void dispose() { // TODO Auto-generated method stub } public boolean isLabelProperty(Object element, String property) { // TODO Auto-generated method stub return false; } public void removeListener(ILabelProviderListener listener) { // TODO Auto-generated method stub } }); tableViewer.setInput(model); wCreate.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { //System.out.println("defw selected"); } public void widgetSelected(SelectionEvent e) { wCreate.setEnabled(!createBnd()); tableViewer.setInput(model); } }); } protected boolean createBnd() { if (basedir != null && basedir.isDirectory()) { File bnd = new File(basedir, "bnd.bnd"); try { FileOutputStream out = new FileOutputStream(bnd); PrintStream ps = new PrintStream(out); try { ps.println("# Auto generated by bnd, please adapt"); ps.println(); ps.println("Export-Package: "); ps.println("Private-Package: "); ps .println("Bundle-Name: ${Bundle-SymbolicName}"); ps.println("Bundle-Version: 1.0"); ps.println(); ps.println("#Example buildpath"); ps .println("-buildpath: osgi; version=4.0, \\"); ps .println(" com.springsource.junit; version=\"[3.8,4)\""); } finally { out.close(); ps.close(); } javaProject.getResource().refreshLocal(IResource.DEPTH_ONE, null); model = Activator.getDefault().getCentral().getModel(javaProject); return model != null; } catch (IOException e) { e.printStackTrace(); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return false; } /* * (non-Javadoc) * * @see org.eclipse.jdt.ui.wizards.IClasspathContainerPage#finish() */ public boolean finish() { return true; } /* * (non-Javadoc) * * @see org.eclipse.jdt.ui.wizards.IClasspathContainerPage#getSelection() */ public IClasspathEntry getSelection() { IPath containerPath = BndContainerInitializer.ID; IClasspathEntry cpe = JavaCore.newContainerEntry(containerPath); return cpe; } /* * (non-Javadoc) * * @see org.eclipse.jdt.ui.wizards.IClasspathContainerPage#setSelection(org.eclipse.jdt.core.IClasspathEntry) */ public void setSelection(IClasspathEntry containerEntry) { if (containerEntry != null) { // initPath = containerEntry.getPath(); } } }
34.434783
180
0.551997
76d284e7fedaad8ebdc6760b14dc0f55fcaa4a66
7,085
/** * SPDX-FileCopyrightText: 2018-2021 SAP SE or an SAP affiliate company and Cloud Security Client Java contributors * * SPDX-License-Identifier: Apache-2.0 */ package com.sap.cloud.security.xsuaa.client; import com.sap.cloud.security.config.ClientCredentials; import com.sap.cloud.security.config.ClientIdentity; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestOperations; import java.net.URI; import java.util.HashMap; import java.util.Map; import static com.sap.cloud.security.xsuaa.client.OAuth2TokenServiceConstants.*; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.eq; @RunWith(MockitoJUnitRunner.class) public class XsuaaOAuth2TokenServiceUserTokenTest { OAuth2TokenService cut; ClientIdentity clientIdentity; URI tokenEndpoint; Map<String, String> responseMap; private static final String userTokenToBeExchanged = "65a84cd45c554c6993ea26cb8f9cf3a2"; @Mock RestOperations mockRestOperations; @Before public void setup() { cut = new XsuaaOAuth2TokenService(mockRestOperations); clientIdentity = new ClientCredentials("clientid", "mysecretpassword"); tokenEndpoint = URI.create("https://subdomain.myauth.server.com/oauth/token"); responseMap = new HashMap<>(); responseMap.put(REFRESH_TOKEN, "2170b564228448c6aed8b1ddfdb8bf53-r"); responseMap.put(ACCESS_TOKEN, "4d841646fcc340f59b1b7b43df4b050d"); // opaque access token responseMap.put(EXPIRES_IN, "43199"); responseMap.put(TOKEN_TYPE, "bearer"); } @Test public void retrieveToken_throwsOnNullValues() { assertThatThrownBy(() -> cut.retrieveAccessTokenViaUserTokenGrant(null, clientIdentity, userTokenToBeExchanged, null, null)).isInstanceOf(IllegalArgumentException.class).hasMessageStartingWith("tokenEndpointUri"); assertThatThrownBy( () -> cut.retrieveAccessTokenViaUserTokenGrant(tokenEndpoint, null, userTokenToBeExchanged, null, null)) .isInstanceOf(IllegalArgumentException.class).hasMessageStartingWith("clientIdentity"); assertThatThrownBy( () -> cut.retrieveAccessTokenViaUserTokenGrant(tokenEndpoint, clientIdentity, null, null, null)) .isInstanceOf(IllegalArgumentException.class).hasMessageStartingWith("token"); } @Test(expected = OAuth2ServiceException.class) public void retrieveToken_throwsIfHttpStatusUnauthorized() throws OAuth2ServiceException { Mockito.when(mockRestOperations.postForEntity(any(URI.class), any(HttpEntity.class), eq(Map.class))) .thenThrow(new HttpClientErrorException(HttpStatus.UNAUTHORIZED)); cut.retrieveAccessTokenViaUserTokenGrant(tokenEndpoint, clientIdentity, userTokenToBeExchanged, null, null); } @Test(expected = OAuth2ServiceException.class) public void retrieveToken_throwsIfHttpStatusNotOk() throws OAuth2ServiceException { Mockito.when(mockRestOperations.postForEntity(any(URI.class), any(HttpEntity.class), eq(Map.class))) .thenThrow(new HttpClientErrorException(HttpStatus.BAD_REQUEST)); cut.retrieveAccessTokenViaUserTokenGrant(tokenEndpoint, clientIdentity, userTokenToBeExchanged, null, null); } @Test public void retrieveToken() throws OAuth2ServiceException { TokenServiceHttpEntityMatcher tokenHttpEntityMatcher = new TokenServiceHttpEntityMatcher(); tokenHttpEntityMatcher.setGrantType(OAuth2TokenServiceConstants.GRANT_TYPE_USER_TOKEN); tokenHttpEntityMatcher.addParameter(OAuth2TokenServiceConstants.PARAMETER_CLIENT_ID, clientIdentity.getId()); HttpHeaders expectedHeaders = new HttpHeaders(); expectedHeaders.add(HttpHeaders.ACCEPT, "application/json"); expectedHeaders.add(HttpHeaders.AUTHORIZATION, "Bearer " + userTokenToBeExchanged); HttpEntity expectedRequest = new HttpEntity(expectedHeaders); Mockito.when(mockRestOperations .postForEntity( eq(tokenEndpoint), argThat(tokenHttpEntityMatcher), eq(Map.class))) .thenReturn(new ResponseEntity<>(responseMap, HttpStatus.OK)); OAuth2TokenResponse accessToken = cut.retrieveAccessTokenViaUserTokenGrant(tokenEndpoint, clientIdentity, userTokenToBeExchanged, null, null); assertThat(accessToken.getRefreshToken(), is(responseMap.get(REFRESH_TOKEN))); assertThat(accessToken.getAccessToken(), is(responseMap.get(ACCESS_TOKEN))); assertThat(accessToken.getTokenType(), is(responseMap.get(TOKEN_TYPE))); assertNotNull(accessToken.getExpiredAt()); } @Test public void retrieveToken_withOptionalParamaters() throws OAuth2ServiceException { Map<String, String> additionalParameters = new HashMap<>(); additionalParameters.put("add-param-1", "value1"); additionalParameters.put("add-param-2", "value2"); TokenServiceHttpEntityMatcher tokenHttpEntityMatcher = new TokenServiceHttpEntityMatcher(); tokenHttpEntityMatcher.setGrantType(OAuth2TokenServiceConstants.GRANT_TYPE_USER_TOKEN); tokenHttpEntityMatcher.addParameter(OAuth2TokenServiceConstants.PARAMETER_CLIENT_ID, clientIdentity.getId()); tokenHttpEntityMatcher.addParameters(additionalParameters); Mockito.when(mockRestOperations.postForEntity( eq(tokenEndpoint), argThat(tokenHttpEntityMatcher), eq(Map.class))) .thenReturn(new ResponseEntity<>(responseMap, HttpStatus.OK)); OAuth2TokenResponse accessToken = cut.retrieveAccessTokenViaUserTokenGrant(tokenEndpoint, clientIdentity, userTokenToBeExchanged, null, additionalParameters); assertThat(accessToken.getRefreshToken(), is(responseMap.get(REFRESH_TOKEN))); } @Test public void retrieveToken_requiredParametersCanNotBeOverwritten() throws OAuth2ServiceException { TokenServiceHttpEntityMatcher tokenHttpEntityMatcher = new TokenServiceHttpEntityMatcher(); tokenHttpEntityMatcher.setGrantType(OAuth2TokenServiceConstants.GRANT_TYPE_USER_TOKEN); tokenHttpEntityMatcher.addParameter(OAuth2TokenServiceConstants.PARAMETER_CLIENT_ID, clientIdentity.getId()); Mockito.when( mockRestOperations.postForEntity( eq(tokenEndpoint), argThat(tokenHttpEntityMatcher), eq(Map.class))) .thenReturn(new ResponseEntity<>(responseMap, HttpStatus.OK)); Map<String, String> overwrittenGrantType = new HashMap<>(); overwrittenGrantType.put(OAuth2TokenServiceConstants.GRANT_TYPE, "overwrite-obligatory-param"); OAuth2TokenResponse accessToken = cut.retrieveAccessTokenViaUserTokenGrant(tokenEndpoint, clientIdentity, userTokenToBeExchanged, null, overwrittenGrantType); assertThat(accessToken.getRefreshToken(), is(responseMap.get(REFRESH_TOKEN))); } }
44.559748
115
0.814679
a33387287a6698d5d9a1cedb147cd317a0c89a67
1,208
package com.chairbender.consensus.webservice.entity; import javax.persistence.*; /** * Represents a review of a paper by a user */ @Entity public class Review { @Id @GeneratedValue private long id; @Column(name = "userId") private long userId; @Column(name = "paperId") private long paperId; private boolean accept; Review() { // jpa only } /** * * @param pUserId id of user whose review this is * @param pPaperId id of the paper this review is for * @param pAccept whether the review is an accept or reject */ public Review(long pUserId, long pPaperId, boolean pAccept) { userId = pUserId; paperId = pPaperId; accept = pAccept; } public long getId() { return id; } public long getUserId() { return userId; } public void setUserId(int pUserId) { userId = pUserId; } public long getPaperId() { return paperId; } public void setPaperId(int pPaperId) { paperId = pPaperId; } public boolean isAccept() { return accept; } public void setAccept(boolean pAccept) { accept = pAccept; } }
18.875
65
0.596026
426468f8b924c75d779d584db5e0b45a363fcae2
2,742
package org.citrusframework.simulator.http; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.EnvironmentAware; import org.springframework.core.env.Environment; import javax.annotation.PostConstruct; /** * @author Christoph Deppisch */ @ConfigurationProperties(prefix = "citrus.simulator.rest") public class SimulatorRestConfigurationProperties implements EnvironmentAware { /** Logger */ private static Logger log = LoggerFactory.getLogger(SimulatorRestConfigurationProperties.class); /** * System property constants and environment variable names. Post construct callback reads these values and overwrites * settings in this property class in order to add support for environment variables. */ private static final String SIMULATOR_URL_MAPPING_PROPERTY = "citrus.simulator.rest.url.mapping"; private static final String SIMULATOR_URL_MAPPING_ENV = "CITRUS_SIMULATOR_REST_URL_MAPPING"; /** * Global option to enable/disable REST support, default is true. */ private boolean enabled = true; /** * The web service message dispatcher servlet mapping. Clients must use this * context path in order to access the web service support on the simulator. */ private String urlMapping = "/services/rest/**"; /** * The Spring application context environment auto injected by environment aware mechanism. */ private Environment env; @PostConstruct private void loadProperties() { urlMapping = env.getProperty(SIMULATOR_URL_MAPPING_PROPERTY, env.getProperty(SIMULATOR_URL_MAPPING_ENV, urlMapping)); log.info("Using the simulator configuration: {}", this.toString()); } /** * Gets the enabled. * * @return */ public boolean isEnabled() { return enabled; } /** * Sets the enabled. * * @param enabled */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * Gets the urlMapping. * * @return */ public String getUrlMapping() { return urlMapping; } /** * Sets the urlMapping. * * @param urlMapping */ public void setUrlMapping(String urlMapping) { this.urlMapping = urlMapping; } @Override public String toString() { return this.getClass().getSimpleName() + "{" + "enabled='" + enabled + '\'' + ", urlMapping='" + urlMapping + '\'' + '}'; } @Override public void setEnvironment(Environment environment) { this.env = environment; } }
27.69697
125
0.664843
4d40c5094cd964c6f839dbbd1d49a170d972eed0
11,059
package net.minecraft.client.gui.screen; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonIOException; import com.google.gson.stream.JsonWriter; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.serialization.DataResult; import com.mojang.serialization.DynamicOps; import com.mojang.serialization.JsonOps; import com.mojang.serialization.DataResult.PartialResult; import it.unimi.dsi.fastutil.booleans.BooleanConsumer; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.concurrent.ExecutionException; import java.util.function.Function; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.DialogTexts; import net.minecraft.client.gui.toasts.SystemToast; import net.minecraft.client.gui.widget.TextFieldWidget; import net.minecraft.client.gui.widget.button.Button; import net.minecraft.util.Util; import net.minecraft.util.math.MathHelper; import net.minecraft.util.registry.DynamicRegistries; import net.minecraft.util.registry.WorldGenSettingsExport; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.gen.settings.DimensionGeneratorSettings; import net.minecraft.world.storage.FolderName; import net.minecraft.world.storage.SaveFormat; import net.minecraft.world.storage.WorldSummary; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @OnlyIn(Dist.CLIENT) public class EditWorldScreen extends Screen { private static final Logger LOGGER = LogManager.getLogger(); private static final Gson WORLD_GEN_SETTINGS_GSON = (new GsonBuilder()).setPrettyPrinting().serializeNulls().disableHtmlEscaping().create(); private static final ITextComponent NAME_LABEL = new TranslationTextComponent("selectWorld.enterName"); private Button renameButton; private final BooleanConsumer callback; private TextFieldWidget nameEdit; private final SaveFormat.LevelSave levelAccess; public EditWorldScreen(BooleanConsumer p_i232318_1_, SaveFormat.LevelSave p_i232318_2_) { super(new TranslationTextComponent("selectWorld.edit.title")); this.callback = p_i232318_1_; this.levelAccess = p_i232318_2_; } public void tick() { this.nameEdit.tick(); } protected void init() { this.minecraft.keyboardHandler.setSendRepeatsToGui(true); Button button = this.addButton(new Button(this.width / 2 - 100, this.height / 4 + 0 + 5, 200, 20, new TranslationTextComponent("selectWorld.edit.resetIcon"), (p_214309_1_) -> { FileUtils.deleteQuietly(this.levelAccess.getIconFile()); p_214309_1_.active = false; })); this.addButton(new Button(this.width / 2 - 100, this.height / 4 + 24 + 5, 200, 20, new TranslationTextComponent("selectWorld.edit.openFolder"), (p_214303_1_) -> { Util.getPlatform().openFile(this.levelAccess.getLevelPath(FolderName.ROOT).toFile()); })); this.addButton(new Button(this.width / 2 - 100, this.height / 4 + 48 + 5, 200, 20, new TranslationTextComponent("selectWorld.edit.backup"), (p_214304_1_) -> { boolean flag = makeBackupAndShowToast(this.levelAccess); this.callback.accept(!flag); })); this.addButton(new Button(this.width / 2 - 100, this.height / 4 + 72 + 5, 200, 20, new TranslationTextComponent("selectWorld.edit.backupFolder"), (p_214302_1_) -> { SaveFormat saveformat = this.minecraft.getLevelSource(); Path path = saveformat.getBackupPath(); try { Files.createDirectories(Files.exists(path) ? path.toRealPath() : path); } catch (IOException ioexception) { throw new RuntimeException(ioexception); } Util.getPlatform().openFile(path.toFile()); })); this.addButton(new Button(this.width / 2 - 100, this.height / 4 + 96 + 5, 200, 20, new TranslationTextComponent("selectWorld.edit.optimize"), (p_214310_1_) -> { this.minecraft.setScreen(new ConfirmBackupScreen(this, (p_214305_1_, p_214305_2_) -> { if (p_214305_1_) { makeBackupAndShowToast(this.levelAccess); } this.minecraft.setScreen(OptimizeWorldScreen.create(this.minecraft, this.callback, this.minecraft.getFixerUpper(), this.levelAccess, p_214305_2_)); }, new TranslationTextComponent("optimizeWorld.confirm.title"), new TranslationTextComponent("optimizeWorld.confirm.description"), true)); })); this.addButton(new Button(this.width / 2 - 100, this.height / 4 + 120 + 5, 200, 20, new TranslationTextComponent("selectWorld.edit.export_worldgen_settings"), (p_239023_1_) -> { DynamicRegistries.Impl dynamicregistries$impl = DynamicRegistries.builtin(); DataResult<String> dataresult; try (Minecraft.PackManager minecraft$packmanager = this.minecraft.makeServerStem(dynamicregistries$impl, Minecraft::loadDataPacks, Minecraft::loadWorldData, false, this.levelAccess)) { DynamicOps<JsonElement> dynamicops = WorldGenSettingsExport.create(JsonOps.INSTANCE, dynamicregistries$impl); DataResult<JsonElement> dataresult1 = DimensionGeneratorSettings.CODEC.encodeStart(dynamicops, minecraft$packmanager.worldData().worldGenSettings()); dataresult = dataresult1.flatMap((p_239017_1_) -> { Path path = this.levelAccess.getLevelPath(FolderName.ROOT).resolve("worldgen_settings_export.json"); try (JsonWriter jsonwriter = WORLD_GEN_SETTINGS_GSON.newJsonWriter(Files.newBufferedWriter(path, StandardCharsets.UTF_8))) { WORLD_GEN_SETTINGS_GSON.toJson(p_239017_1_, jsonwriter); } catch (JsonIOException | IOException ioexception) { return DataResult.error("Error writing file: " + ioexception.getMessage()); } return DataResult.success(path.toString()); }); } catch (ExecutionException | InterruptedException interruptedexception) { dataresult = DataResult.error("Could not parse level data!"); } ITextComponent itextcomponent = new StringTextComponent(dataresult.get().map(Function.identity(), PartialResult::message)); ITextComponent itextcomponent1 = new TranslationTextComponent(dataresult.result().isPresent() ? "selectWorld.edit.export_worldgen_settings.success" : "selectWorld.edit.export_worldgen_settings.failure"); dataresult.error().ifPresent((p_239018_0_) -> { LOGGER.error("Error exporting world settings: {}", (Object)p_239018_0_); }); this.minecraft.getToasts().addToast(SystemToast.multiline(this.minecraft, SystemToast.Type.WORLD_GEN_SETTINGS_TRANSFER, itextcomponent1, itextcomponent)); })); this.renameButton = this.addButton(new Button(this.width / 2 - 100, this.height / 4 + 144 + 5, 98, 20, new TranslationTextComponent("selectWorld.edit.save"), (p_214308_1_) -> { this.onRename(); })); this.addButton(new Button(this.width / 2 + 2, this.height / 4 + 144 + 5, 98, 20, DialogTexts.GUI_CANCEL, (p_214306_1_) -> { this.callback.accept(false); })); button.active = this.levelAccess.getIconFile().isFile(); WorldSummary worldsummary = this.levelAccess.getSummary(); String s = worldsummary == null ? "" : worldsummary.getLevelName(); this.nameEdit = new TextFieldWidget(this.font, this.width / 2 - 100, 38, 200, 20, new TranslationTextComponent("selectWorld.enterName")); this.nameEdit.setValue(s); this.nameEdit.setResponder((p_214301_1_) -> { this.renameButton.active = !p_214301_1_.trim().isEmpty(); }); this.children.add(this.nameEdit); this.setInitialFocus(this.nameEdit); } public void resize(Minecraft p_231152_1_, int p_231152_2_, int p_231152_3_) { String s = this.nameEdit.getValue(); this.init(p_231152_1_, p_231152_2_, p_231152_3_); this.nameEdit.setValue(s); } public void onClose() { this.callback.accept(false); } public void removed() { this.minecraft.keyboardHandler.setSendRepeatsToGui(false); } private void onRename() { try { this.levelAccess.renameLevel(this.nameEdit.getValue().trim()); this.callback.accept(true); } catch (IOException ioexception) { LOGGER.error("Failed to access world '{}'", this.levelAccess.getLevelId(), ioexception); SystemToast.onWorldAccessFailure(this.minecraft, this.levelAccess.getLevelId()); this.callback.accept(true); } } public static void makeBackupAndShowToast(SaveFormat p_241651_0_, String p_241651_1_) { boolean flag = false; try (SaveFormat.LevelSave saveformat$levelsave = p_241651_0_.createAccess(p_241651_1_)) { flag = true; makeBackupAndShowToast(saveformat$levelsave); } catch (IOException ioexception) { if (!flag) { SystemToast.onWorldAccessFailure(Minecraft.getInstance(), p_241651_1_); } LOGGER.warn("Failed to create backup of level {}", p_241651_1_, ioexception); } } public static boolean makeBackupAndShowToast(SaveFormat.LevelSave p_239019_0_) { long i = 0L; IOException ioexception = null; try { i = p_239019_0_.makeWorldBackup(); } catch (IOException ioexception1) { ioexception = ioexception1; } if (ioexception != null) { ITextComponent itextcomponent2 = new TranslationTextComponent("selectWorld.edit.backupFailed"); ITextComponent itextcomponent3 = new StringTextComponent(ioexception.getMessage()); Minecraft.getInstance().getToasts().addToast(new SystemToast(SystemToast.Type.WORLD_BACKUP, itextcomponent2, itextcomponent3)); return false; } else { ITextComponent itextcomponent = new TranslationTextComponent("selectWorld.edit.backupCreated", p_239019_0_.getLevelId()); ITextComponent itextcomponent1 = new TranslationTextComponent("selectWorld.edit.backupSize", MathHelper.ceil((double)i / 1048576.0D)); Minecraft.getInstance().getToasts().addToast(new SystemToast(SystemToast.Type.WORLD_BACKUP, itextcomponent, itextcomponent1)); return true; } } public void render(MatrixStack p_230430_1_, int p_230430_2_, int p_230430_3_, float p_230430_4_) { this.renderBackground(p_230430_1_); drawCenteredString(p_230430_1_, this.font, this.title, this.width / 2, 15, 16777215); drawString(p_230430_1_, this.font, NAME_LABEL, this.width / 2 - 100, 24, 10526880); this.nameEdit.render(p_230430_1_, p_230430_2_, p_230430_3_, p_230430_4_); super.render(p_230430_1_, p_230430_2_, p_230430_3_, p_230430_4_); } }
51.199074
212
0.718329
3d96ba0d24767baa8dd89aa6cf5dccbfdd2197d4
8,248
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.didichuxing.datachannel.agent.common.metrics.impl; import com.didichuxing.datachannel.agent.common.metrics.MetricsFilter; import com.didichuxing.datachannel.agent.common.metrics.MetricsPlugin; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.configuration.SubsetConfiguration; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MetricsConfig extends SubsetConfiguration { private static final Logger LOGGER = LoggerFactory .getLogger(MetricsConfig.class); static final String DEFAULT_FILE_NAME = "metrics.properties"; static final String PREFIX_DEFAULT = "*."; static final String PERIOD_KEY = "period"; static final int PERIOD_DEFAULT = 10; // seconds static final String QUEUE_CAPACITY_KEY = "queue.capacity"; static final int QUEUE_CAPACITY_DEFAULT = 1; static final String RETRY_DELAY_KEY = "retry.delay"; static final int RETRY_DELAY_DEFAULT = 10; // seconds static final String RETRY_BACKOFF_KEY = "retry.backoff"; static final int RETRY_BACKOFF_DEFAULT = 2; // back off factor static final String RETRY_COUNT_KEY = "retry.count"; static final int RETRY_COUNT_DEFAULT = 1; static final String JMX_CACHE_TTL_KEY = "jmx.cache.ttl"; static final int JMX_CACHE_TTL_DEFAULT = 10000; // millis static final String CONTEXT_KEY = "context"; static final String NAME_KEY = "name"; static final String DESC_KEY = "description"; static final String SOURCE_KEY = "source"; static final String SINK_KEY = "sink"; static final String METRIC_FILTER_KEY = "metric.filter"; static final String RECORD_FILTER_KEY = "record.filter"; static final String SOURCE_FILTER_KEY = "source.filter"; static final Pattern INSTANCE_REGEX = Pattern.compile("([^.*]+)\\..+"); MetricsConfig(Configuration c, String prefix) { super(c, prefix.toLowerCase(Locale.US), "."); } static MetricsConfig create(String prefix) { return loadFirst(prefix, "metrics" + prefix.toLowerCase(Locale.US) + ".properties", DEFAULT_FILE_NAME); } static MetricsConfig create(String prefix, String... fileNames) { return loadFirst(prefix, fileNames); } /** * Load configuration from a list of files until the first successful load * @param prefix the configuration prefix * @param fileNames the list of filenames to try * @return the configuration object */ static MetricsConfig loadFirst(String prefix, String... fileNames) { for (String fname : fileNames) { try { Configuration cf = new PropertiesConfiguration(fname).interpolatedConfiguration(); LOGGER.info("loaded properties from " + fname); return new MetricsConfig(cf, prefix); } catch (ConfigurationException e) { if (e.getMessage().startsWith("Cannot locate configuration")) { continue; } throw new MetricsConfigException(e); } } throw new MetricsConfigException("Cannot locate configuration: tried " + StringUtils.join(fileNames, ", ")); } @Override public MetricsConfig subset(String prefix) { return new MetricsConfig(this, prefix); } /** * Return sub configs for instance specified in the config. * Assuming format specified as follows:<pre> * [type].[instance].[option] = [value]</pre> * Note, '*' is a special default instance, which is excluded in the result. * @param type of the instance * @return a map with [instance] as key and config object as value */ Map<String, MetricsConfig> getInstanceConfigs(String type) { HashMap<String, MetricsConfig> map = new HashMap<String, MetricsConfig>(); MetricsConfig sub = subset(type); for (String key : sub.keys()) { Matcher matcher = INSTANCE_REGEX.matcher(key); if (matcher.matches()) { String instance = matcher.group(1); if (!map.containsKey(instance)) { map.put(instance, sub.subset(instance)); } } } return map; } Iterable<String> keys() { return new Iterable<String>() { @SuppressWarnings("unchecked") public Iterator<String> iterator() { return (Iterator<String>) getKeys(); } }; } /** * Will poke parents for defaults * @param key to lookup * @return the value or null */ @Override public Object getProperty(String key) { Object value = super.getProperty(key); if (value == null) { LOGGER.debug("poking parent " + getParent().getClass().getSimpleName() + " for " + key); return getParent().getProperty( key.startsWith(PREFIX_DEFAULT) ? key : PREFIX_DEFAULT + key); } return value; } <T extends MetricsPlugin> T getPlugin(String name) { String classKey = name.isEmpty() ? "class" : name + ".class"; String pluginClassName = getString(classKey); if (pluginClassName == null || pluginClassName.isEmpty()) { return null; } try { Class<?> pluginClass = Class.forName(pluginClassName); @SuppressWarnings("unchecked") T plugin = (T) pluginClass.getConstructor().newInstance(); plugin.init(name.isEmpty() ? this : subset(name)); return plugin; } catch (Exception e) { throw new MetricsConfigException("Error creating plugin: " + pluginClassName, e); } } MetricsFilter getFilter(String prefix) { // don't create filter instances without out options if (subset(prefix).isEmpty()) return null; return (MetricsFilter) getPlugin(prefix); } @Override public String toString() { return toString(this); } String toString(Configuration c) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(buffer); PropertiesConfiguration tmp = new PropertiesConfiguration(); tmp.copy(c); try { tmp.save(ps); } catch (Exception e) { throw new MetricsConfigException(e); } return buffer.toString(); } }
39.653846
109
0.610087
3d949cacf061e89e403c35f4905d99dd11de9a27
1,082
package salaryIncrease; import java.text.DecimalFormat; public class Person { private String firstName; private String lastName; private int age; private double salary; public Person(String firstName, String lastName, int age, double salary) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.salary = salary; } private String getFirstName() { return firstName; } private String getLastName() { return lastName; } private Integer getAge() { return age; } private double getSalary() { return salary; } private void setSalary(double salary) { this.salary = salary; } public void increaseSalary(double bonus) { if (this.getAge() < 30) { bonus /= 2; } double percent = 1 + bonus / 100; this.setSalary(this.getSalary() * percent); } @Override public String toString() { DecimalFormat salaryFormater = new DecimalFormat("#.0##########"); return String.format("%s %s gets ", this.getFirstName(), this.getLastName()) + salaryFormater.format(this.getSalary()) + " leva"; } }
19.321429
75
0.674677
83fd8a0fe93e3884618c667a8897868d82a9c62f
761
package Leetcode; import java.util.Arrays; /** * #537 ComplexNumberMultiplication */ class ComplexNumberMultiplication { public static String complexNumberMultiply(String a1, String b1) { String[] A = a1.split("\\+", 2); String[] B = b1.split("\\+", 2); int a = Integer.parseInt(A[0]); int b = Integer.parseInt(A[1].substring(0, A[1].length() - 1)); int c = Integer.parseInt(B[0]); int d = Integer.parseInt(B[1].substring(0, B[1].length() - 1)); int realValue = (a * c) - (b * d); int complexValue = (a * d) + (b * c); return realValue + "+" + complexValue + "i"; } public static void main(String[] args) { String a = "1+-1i"; String b = "1+1i"; System.out.println(complexNumberMultiply(a, b)); } }
27.178571
68
0.599212
352637daaa6718bafd133008cea035a0f5d7c001
895
package com.gitee.code4fun.facerecognition.gui.util; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerConfig; import java.util.Properties; /** * @author yujingze * @data 2018/9/6 */ public class KafkaUtils { private static Producer<String,String> producer = null; static{ Properties properties = new Properties(); properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"localhost:9092,localhost:9093,localhost:9094"); properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.IntegerSerializer"); properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer"); producer = new KafkaProducer(properties); } }
31.964286
134
0.776536
4cfa7e614150e6c45cef77d49e4392405a8de9e1
1,349
package ru.shemplo.pluses.network.message; import org.json.JSONObject; public class ControlMessage extends AbsAppMessage { /** * */ private static final long serialVersionUID = -2101506025334294654L; public static enum ControlType { ERROR, ID, INFO, JSON } protected final ControlType TYPE; protected final String COMMENT; protected final int CODE; public ControlMessage (Message reply, MessageDirection direction, ControlType type, int code, String comment) { super (reply, direction); this.COMMENT = comment; this.TYPE = type; this.CODE = code; } public ControlMessage (MessageDirection direction, ControlType type, int code, String comment) { this (null, direction, type, code, comment); } @Override public JSONObject toJSON (JSONObject root) { JSONObject tmp = super.toJSON (root); tmp.put ("type", "controlmessage"); tmp.put ("comment", getComment ()); tmp.put ("kind", getType ()); tmp.put ("code", getCode ()); return tmp; } public ControlType getType () { return TYPE; } public int getCode () { return CODE; } public String getComment () { return COMMENT; } }
24.089286
73
0.595256
31047e45ba716f2f0114fca4410801816cbc602a
2,251
/* * 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.beam.runners.dataflow.worker; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.junit.Assert.assertEquals; import java.util.Set; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Sets; import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link LogSaver}. */ @RunWith(JUnit4.class) public class LogSaverTest { @Test public void testInitialization() { LogSaver saver = new LogSaver(); assertThat(saver.getLogs(), empty()); } @Test public void testPublishedLogsAreSaved() { int numLogsToPublish = 10; LogSaver saver = new LogSaver(); Set<LogRecord> records = Sets.newHashSet(); for (int i = 0; i < numLogsToPublish; i++) { LogRecord record = new LogRecord(Level.WARNING, "message #" + i); records.add(record); saver.publish(record); } assertEquals(records, Sets.newHashSet(saver.getLogs())); } @Test public void testJulIntegration() { Logger log = Logger.getLogger("any.logger"); LogSaver saver = new LogSaver(); log.addHandler(saver); log.warning("foobar"); assertThat(saver.getLogs(), Matchers.hasItem(LogRecordMatcher.hasLog(Level.WARNING, "foobar"))); } }
33.102941
100
0.731675
9b7f8c8a3d02bfb3f1332149b4b7592c7b64f04d
2,955
package com.zyb.myWeather.adapter; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.zyb.myWeather.R; import com.zyb.myWeather.model.County; import com.zyb.myWeather.model.UserCity; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2017/2/28 0028. */ public class CityManagerAdapter extends BaseAdapter { private List<UserCity> countyList = new ArrayList<>(); private Context ctx = null; private boolean isEdit = false; public boolean isEdit() { return isEdit; } public void setEdit(boolean edit) { isEdit = edit; } public CityManagerAdapter(Context ctx) { super(); this.ctx = ctx; } public List<UserCity> getCountyList() { return countyList; } public void setCityList(List<UserCity> countyList) { this.countyList.clear(); this.countyList.addAll(countyList); } @Override public int getCount() { return this.countyList.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder vh = null; if(convertView == null){ vh = new ViewHolder(); convertView = View.inflate(ctx,R.layout.city_item,null); vh.txt_cityName = (TextView) convertView.findViewById(R.id.txt_cityName); vh.txt_curCity = (TextView) convertView.findViewById(R.id.txt_curCity); vh.btn_del = (ImageButton) convertView.findViewById(R.id.btn_del); vh.img_location = (ImageView) convertView.findViewById(R.id.img_location); convertView.setTag(vh); }else{ vh = (ViewHolder) convertView.getTag(); } //当前定位 if(position == 0){ vh.img_location.setVisibility(View.VISIBLE); }else{ vh.img_location.setVisibility(View.GONE); } //如果处于编辑状态 if(isEdit){ vh.btn_del.setVisibility(View.VISIBLE); }else{ vh.btn_del.setVisibility(View.GONE); } vh.txt_cityName.setText(countyList.get(position).getCounty_name()); //给删除按钮添加点击事件 vh.btn_del.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { countyList.remove(position); notifyDataSetChanged(); } }); return convertView; } class ViewHolder{ TextView txt_cityName; ImageButton btn_del; ImageView img_location; TextView txt_curCity; } }
25.474138
86
0.625719
a11e29847a42ed7a153e3066c44d203d7300835d
13,487
package com.clilystudio.netbook.ui.ugcbook; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import com.clilystudio.netbook.MyApplication; import com.clilystudio.netbook.R; import com.clilystudio.netbook.a_pack.BaseAsyncTask; import com.clilystudio.netbook.api.ApiServiceProvider; import com.clilystudio.netbook.event.BusProvider; import com.clilystudio.netbook.event.UgcDraftEvent; import com.clilystudio.netbook.model.Account; import com.clilystudio.netbook.model.Author; import com.clilystudio.netbook.model.BookSummary; import com.clilystudio.netbook.model.ResultStatus; import com.clilystudio.netbook.model.UGCBookDetail; import com.clilystudio.netbook.model.UGCBookDetailRoot; import com.clilystudio.netbook.model.UGCNewCollection; import com.clilystudio.netbook.ui.BaseActivity; import com.clilystudio.netbook.ui.BaseCallBack; import com.clilystudio.netbook.ui.BookInfoActivity; import com.clilystudio.netbook.util.BaseDownloadAdapter; import com.clilystudio.netbook.util.CommonUtil; import com.clilystudio.netbook.util.DateTimeUtil; import com.clilystudio.netbook.util.ToastUtil; import com.clilystudio.netbook.widget.CoverView; import com.clilystudio.netbook.widget.SmartImageView; import com.squareup.otto.Subscribe; import java.util.ArrayList; import java.util.List; public class UGCDetailActivity extends BaseActivity implements View.OnClickListener { private TextView a; private TextView b; private TextView c; private TextView e; private TextView f; private SmartImageView g; private ImageButton i; private ListView j; private BaseDownloadAdapter<UGCBookDetail.UGCBookContainer> k; private View l; private View m; private String mBookId; private UGCBookDetail r; private Author s; private View.OnClickListener t; public UGCDetailActivity() { this.t = new View.OnClickListener() { @Override public void onClick(View v) { UGCDetailActivity.this.e.setMaxLines(Integer.MAX_VALUE); UGCDetailActivity.this.e.setEllipsize(null); UGCDetailActivity.this.i.setVisibility(View.GONE); UGCDetailActivity.this.e.setClickable(false); } }; } static void c(final UGCDetailActivity uGCDetailActivity) { Account account = CommonUtil.checkLogin(uGCDetailActivity); if (account != null) { new BaseAsyncTask<String, Void, ResultStatus>() { @Override protected ResultStatus doInBackground(String... params) { return ApiServiceProvider.getApiService().addCollectedBookList(params[0], params[1]); } @Override protected void onPostExecute(ResultStatus resultStatus) { super.onPostExecute(resultStatus); if (resultStatus != null && resultStatus.isOk()) { ToastUtil.showShortToast(uGCDetailActivity, "已收藏"); return; } ToastUtil.showShortToast(uGCDetailActivity, "收藏失败,请检查网络或稍后再试"); } }.b(account.getToken(), uGCDetailActivity.mBookId); } } private void a(UGCBookDetail uGCBookDetail) { this.e(1); Author author = uGCBookDetail.getAuthor(); String u = uGCBookDetail.getTitle(); String v = uGCBookDetail.getDesc(); if (author != null) { this.g.setImageUrl(author.getScaleAvatar()); this.b.setText(author.getNickname()); } this.a.setText(DateTimeUtil.e(uGCBookDetail.getCreated())); this.c.setText(u); this.e.setText(v); this.e.post(new Runnable() { @Override public void run() { if (UGCDetailActivity.this.e.getLineCount() > 5) { UGCDetailActivity.this.i.setVisibility(View.VISIBLE); UGCDetailActivity.this.e.setEllipsize(TextUtils.TruncateAt.END); UGCDetailActivity.this.e.setClickable(true); UGCDetailActivity.this.e.setOnClickListener(UGCDetailActivity.this.t); } } }); this.f.setText(String.valueOf(uGCBookDetail.getCollectorCount())); this.k.setDatas(uGCBookDetail.getBooks()); } private void b() { this.e(0); BaseAsyncTask<String, Void, UGCBookDetailRoot> r2 = new BaseAsyncTask<String, Void, UGCBookDetailRoot>() { @Override protected UGCBookDetailRoot doInBackground(String... params) { return ApiServiceProvider.getApiService().getUGCBookDetailRoot(params[0]); } @Override protected void onPostExecute(UGCBookDetailRoot uGCBookDetailRoot) { super.onPostExecute(uGCBookDetailRoot); if (uGCBookDetailRoot != null && uGCBookDetailRoot.isOk() && uGCBookDetailRoot.getBookList() != null) { UGCBookDetail uGCBookDetail = uGCBookDetailRoot.getBookList(); UGCDetailActivity.this.r = uGCBookDetail; UGCDetailActivity.this.s = uGCBookDetail.getAuthor(); UGCDetailActivity.this.a(uGCBookDetail); } else { UGCDetailActivity.this.e(2); } } }; r2.b(this.mBookId); } private void e(int n) { switch (n) { default: { return; } case 1: { this.j.setVisibility(View.VISIBLE); this.l.setVisibility(View.GONE); this.m.setVisibility(View.GONE); return; } case 0: { this.j.setVisibility(View.GONE); this.l.setVisibility(View.VISIBLE); this.m.setVisibility(View.GONE); return; } case 2: } this.j.setVisibility(View.GONE); this.l.setVisibility(View.GONE); this.m.setVisibility(View.VISIBLE); } @Override public void onClick(View view) { switch (view.getId()) { default: { return; } case R.id.load_error_view: } this.b(); } /* * Enabled aggressive block sorting */ @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); this.setContentView(R.layout.activity_ugcbook_detail); BusProvider.getInstance().register(this); if (this.getIntent().getData() != null) { List<String> list = this.getIntent().getData().getPathSegments(); this.mBookId = list.get(-1 + list.size()); } else { this.mBookId = this.getIntent().getStringExtra("book_id"); } String string = "收藏"; this.a("书单详情", string, new BaseCallBack() { @Override public void a() { UGCDetailActivity.c(UGCDetailActivity.this); } }); this.j = (ListView) this.findViewById(R.id.list); this.l = this.findViewById(R.id.pb_loading); this.m = this.findViewById(R.id.load_error_view); this.m.setOnClickListener(this); View view = LayoutInflater.from(this).inflate(R.layout.ugcbook_detail_header, this.j, false); this.g = (SmartImageView) view.findViewById(R.id.avatar); this.a = (TextView) view.findViewById(R.id.author_time); this.b = (TextView) view.findViewById(R.id.author_info); this.c = (TextView) view.findViewById(R.id.list_title); this.e = (TextView) view.findViewById(R.id.list_comment); this.f = (TextView) view.findViewById(R.id.list_fav_count); this.i = (ImageButton) view.findViewById(R.id.ugcbook_more); this.i.setOnClickListener(this.t); this.j.addHeaderView(view, null, false); this.k = new BaseDownloadAdapter<UGCBookDetail.UGCBookContainer>(this.getLayoutInflater(), R.layout.list_item_ugcbook_detail) { @Override protected void a(int var1, UGCBookDetail.UGCBookContainer var2) { UGCBookDetail.UGCBookContainer.UGCBookItem ugcBookItem; if (var2.getComment() != null && var2.getComment().trim().length() > 6) { this.setText(2, var2.getComment()); this.setVisibility(7, false); } else { this.setVisibility(7, true); } if ((ugcBookItem = var2.getBook()) != null) { this.setText(0, ugcBookItem.getTitle()); this.setText(1, String.valueOf(ugcBookItem.getLatelyFollower())); CoverView coverView = this.getTagView(3); coverView.setImageUrl(ugcBookItem.getFullCover(), R.drawable.cover_default); this.setText(4, ugcBookItem.getAuthor()); long l = ugcBookItem.getWordCount(); if (l <= 0) { this.setVisibility(5, true); this.setVisibility(6, true); this.setVisibility(8, true); return; } String string = " \u5b57"; if (l > 10000) { l /= 10000; string = " \u4e07\u5b57"; } else if (l > 100) { l /= 100; string = " \u767e\u5b57"; } this.setText(5, "" + l); this.setText(6, string); this.setVisibility(5, false); this.setVisibility(6, false); this.setVisibility(8, false); } } @Override protected int[] getViewIds() { return new int[]{R.id.title, R.id.message_count, R.id.desc, R.id.avatar, R.id.author, R.id.message_textcount, R.id.message_textunit, R.id.desc_layout, R.id.message_separate}; } }; this.j.setAdapter(this.k); View view2 = this.getLayoutInflater().inflate(R.layout.ugcbook_listview_footer, (ViewGroup) getWindow().getDecorView(), false); this.j.addFooterView(view2); this.j.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { UGCBookDetail.UGCBookContainer uGCBookDetail$UGCBookContainer; int n2 = position - UGCDetailActivity.this.j.getHeaderViewsCount(); if (n2 >= 0 && n2 < UGCDetailActivity.this.k.getCount() && (uGCBookDetail$UGCBookContainer = UGCDetailActivity.this.k.getItem(n2)) != null && uGCBookDetail$UGCBookContainer.getBook() != null) { Intent intent = new Intent(UGCDetailActivity.this, BookInfoActivity.class); intent.putExtra("book_id", uGCBookDetail$UGCBookContainer.getBook().get_id()); UGCDetailActivity.this.startActivity(intent); } } }); UGCNewCollection uGCNewCollection = (UGCNewCollection) this.getIntent().getSerializableExtra("modify_update"); if (uGCNewCollection == null) { this.b(); return; } this.s = (Author) this.getIntent().getSerializableExtra("my_author"); UGCBookDetail uGCBookDetail = new UGCBookDetail(); uGCBookDetail.setTitle(uGCNewCollection.getTitle()); uGCBookDetail.setDesc(uGCNewCollection.getDesc()); List<BookSummary> list = uGCNewCollection.getBooks(); UGCBookDetail.UGCBookContainer[] arruGCBookDetail$UGCBookContainer = new UGCBookDetail.UGCBookContainer[list.size()]; for (int i2 = 0; i2 < list.size(); ++i2) { BookSummary bookSummary = list.get(i2); UGCBookDetail.UGCBookContainer bookContainer = new UGCBookDetail.UGCBookContainer(); UGCBookDetail.UGCBookContainer.UGCBookItem ugcBookItem = new UGCBookDetail.UGCBookContainer.UGCBookItem(); ugcBookItem.set_id(bookSummary.getId()); ugcBookItem.setCover(bookSummary.getCover()); ugcBookItem.setTitle(bookSummary.getTitle()); ugcBookItem.setAuthor(bookSummary.getAuthor()); ugcBookItem.setLatelyFollower(bookSummary.getLatelyFollower()); ugcBookItem.setWordCount(bookSummary.getWordCount()); bookContainer.setBook(ugcBookItem); bookContainer.setComment(bookSummary.getAppendComment()); arruGCBookDetail$UGCBookContainer[i2] = bookContainer; } uGCBookDetail.setBooks(arruGCBookDetail$UGCBookContainer); this.r = uGCBookDetail; if (this.s != null) { this.r.setAuthor(this.s); } this.a(this.r); } @Override protected void onDestroy() { super.onDestroy(); BusProvider.getInstance().unregister(this); } @Subscribe public void onUgcDraftEvent(UgcDraftEvent e2) { this.finish(); } }
42.278997
209
0.606213
7b5e6f8e6f134c1dd27b8b0301658e9846adfd1c
3,798
package com.example.oukenghua.mobilephonehelper; import android.Manifest; import android.app.Activity; import android.app.DownloadManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Environment; import android.support.annotation.NonNull; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; public class SelectActivity extends AppCompatActivity { public static final String SELECT_NAME = "select_name"; public static final String SELECT_IMAGE_ID = "select_image_id"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select); Intent intent = getIntent(); String selectName = intent.getStringExtra(SELECT_NAME); int selectImageId = intent.getIntExtra(SELECT_IMAGE_ID,0); double selectSize = intent.getDoubleExtra("Size",4); String content = intent.getStringExtra("Content"); final String url = intent.getStringExtra("Url"); Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout)findViewById(R.id.collapsing_toolbar); ImageView selectImageView = (ImageView)findViewById(R.id.select_image_view); final TextView selectContentText = (TextView)findViewById(R.id.select_content_text); TextView selectSizeText = (TextView)findViewById(R.id.select_size_text); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if(actionBar != null){ actionBar.setDisplayHomeAsUpEnabled(true); } collapsingToolbar.setTitle(selectName); Glide.with(this).load(selectImageId).into(selectImageView); selectContentText.setText(content); selectSizeText.setText("应用大小:"+String.valueOf(selectSize)+"M"); FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.float_button); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); //String fileName = "1.apk"; String fileName = url.substring(url.lastIndexOf("=")); fileName = fileName.replace("=",""); fileName = fileName + ".apk"; //String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath(); request.setDestinationInExternalPublicDir("/storage/emulated/0",fileName); request.setVisibleInDownloadsUi(true); DownloadManager downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE); downloadManager.enqueue(request); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } }
41.736264
134
0.694839
ed4c1422ac085578c8b6b4745071712c4d889185
3,537
package com.devdatto.sandbox.cityconnect.controller; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.devdatto.sandbox.cityconnect.exception.BadRequestException; import com.devdatto.sandbox.cityconnect.model.CityConnectApiResponse; import com.devdatto.sandbox.cityconnect.model.CityConnectRequest; import com.devdatto.sandbox.cityconnect.model.CityConnectResponse; import com.devdatto.sandbox.cityconnect.service.CityConnectService; import com.devdatto.sandbox.cityconnect.util.ApiConstants; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import lombok.extern.slf4j.Slf4j; @RestController @Slf4j @Api(value = "/", description = "City Connectivity operations") public class CityConnectApiController { @Autowired CityConnectService cityConnectService; @ApiOperation( value = "city connectivity service", notes = "Checks if there is a path between two cities, " + "passed through URL parameters as origin and destination", response = CityConnectApiResponse.class ) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success|OK"), @ApiResponse(code = 400, message = "bad request!")}) @GetMapping(value="/connected", headers = "Accept=application/json", produces = "application/json; charset=utf-8") @ResponseBody @ResponseStatus(HttpStatus.OK) public CityConnectApiResponse<CityConnectRequest, CityConnectResponse> getCityConnectivity(@RequestParam(name = "origin") String origin, @RequestParam(name = "destination") String destination) { CityConnectRequest request = buildRequest(origin, destination); boolean pathExists = cityConnectService.validatePathExists(request); CityConnectResponse response = CityConnectResponse.builder().pathExists(pathExists).build(); CityConnectApiResponse<CityConnectRequest, CityConnectResponse> apiResponse = CityConnectApiResponse.<CityConnectRequest, CityConnectResponse>builder() .request(request) .response(response) .hasErrorResponse(false) .build(); return apiResponse; } public CityConnectRequest buildRequest(String origin, String destination) { if (StringUtils.isBlank(origin) && StringUtils.isBlank(destination)) { log.error("Both Origin and Destination parameters are not provided"); throw new BadRequestException("Both Origin and Destination parameters blank.", ApiConstants.ERROR_CODE_BAD_REQUEST); } else if (StringUtils.isBlank(origin)) { log.error("Origin parameter is not provided"); throw new BadRequestException("Origin parameter blank.", ApiConstants.ERROR_CODE_BAD_REQUEST); } else if (StringUtils.isBlank(destination)) { log.error("Destination parameter is not provided"); throw new BadRequestException("Destination parameter blank.", ApiConstants.ERROR_CODE_BAD_REQUEST); } CityConnectRequest request = CityConnectRequest.builder() .origin(origin) .destination(destination) .build(); return request; } }
41.611765
102
0.773254
e89d45d14f8dc2fd7d5ffc9b6740cda0ef5a5f60
7,072
/* * Copyright (C) 2014 TopCoder Inc., All Rights Reserved. */ package gov.nasa.asteroid.hunter.services.impl; import gov.nasa.asteroid.hunter.LoggingHelper; import gov.nasa.asteroid.hunter.Helper; import gov.nasa.asteroid.hunter.models.HelpItem; import gov.nasa.asteroid.hunter.models.HelpItemSearchCriteria; import gov.nasa.asteroid.hunter.models.HelpTopic; import gov.nasa.asteroid.hunter.models.SearchResult; import gov.nasa.asteroid.hunter.services.HelpService; import gov.nasa.asteroid.hunter.services.ServiceException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; /** * <p> * This class is the implementation of HelpService. * </p> * * <p> * This service provides methods to access help contents. * </p> * * <p> * <b>Thread Safety:</b> This class is effectively thread safe (injected * configurations are not considered as thread safety factor). * </p> * * @author albertwang, TCSASSEMBLER * @version 1.0 */ public class HelpServiceImpl extends BasePersistenceService implements HelpService { /** * <p> * Represents the name of the class for logging. * </p> */ private static final String CLASS_NAME = HelpServiceImpl.class.getName(); /** * <p> * Represents the percent mark use for like query in JQL. * </p> */ private static final String PERCENT_MARK = "%"; /** * <p> * Represents the parameter name of the keyword. * </p> */ private static final String KEYWORD_PARAMETER_NAME = "keyword"; /** * <p> * Represents the parameter name of the topic id. * </p> */ private static final String TOPIC_ID_PARAMETER_NAME = "topicId"; /** * <p> * Represents the keyword where cause. * </p> */ private static final String KEYWORD_WHERE_CAUSE = " AND (UPPER(e.content) LIKE UPPER(:keyword) OR UPPER(e.title) LIKE UPPER(:keyword))"; /** * <p> * Represents the topic id where cause. * </p> */ private static final String TOPIC_ID_WHERE_CAUSE = " AND e.topic.id = :topicId"; /** * <p> * Represents the prefix of the where cause. * </p> */ private static final String WHERE_CAUSE_PREFIX = "1 = 1"; /** * <p> * Represents the query to select the topics. * </p> */ private static final String SELECT_TOPIC_QUERY = "SELECT t FROM HelpTopic t"; /** * <p> * This is the default constructor of <code>HelpServiceImpl</code>. * </p> */ public HelpServiceImpl() { // does nothing } /** * <p> * Get all help topics. * </p> * @return the topics * * @throws ServiceException if any error occurred during the operation */ @Override public List<HelpTopic> getHelpTopics() throws ServiceException { // prepare for logging Logger logger = getLogger(); final String signature = CLASS_NAME + ".getHelpTopics()"; // log the entrance LoggingHelper.logEntrance(logger, signature, null, null); try { List<HelpTopic> result = Helper.getResultList(logger, signature, getEntityManager().createQuery(SELECT_TOPIC_QUERY, HelpTopic.class)); // log the exit LoggingHelper.logExit(logger, signature, new Object[] {result}); return result; } catch (ServiceException e) { // log the error and re-throw throw LoggingHelper.logException(logger, signature, e); } } /** * <p> * This method is used to search help items. * </p> * * @param criteria the search criteria * @return the search result. * * @throws IllegalArgumentException if criteria is null or invalid * @throws ServiceException if any other error occurred during the operation * */ @Override public SearchResult<HelpItem> searchHelpItems(HelpItemSearchCriteria criteria) throws ServiceException { // prepare for logging Logger logger = getLogger(); final String signature = CLASS_NAME + ".searchHelperItems(HelpItemSearchCriteria)"; // log the entrance LoggingHelper.logEntrance(logger, signature, new String[] {"criteria"}, new Object[] {criteria}); // validate the parameters Helper.checkBaseSearchParameters(logger, signature, "criteria", criteria, Arrays.asList("id", "title", "content")); StringBuffer sb = new StringBuffer(WHERE_CAUSE_PREFIX); Map<String, Object> queryParameters = new HashMap<String, Object>(); // Append criteria if (criteria.getTopicId() != null) { sb.append(TOPIC_ID_WHERE_CAUSE); queryParameters.put(TOPIC_ID_PARAMETER_NAME, criteria.getTopicId()); } if (criteria.getKeyword() != null && criteria.getKeyword().trim().length() > 0) { sb.append(KEYWORD_WHERE_CAUSE); queryParameters.put(KEYWORD_PARAMETER_NAME, PERCENT_MARK + criteria.getKeyword() + PERCENT_MARK); } try { SearchResult<HelpItem> result = search(criteria, sb.toString(), queryParameters, HelpItem.class); // log the exit LoggingHelper.logExit(logger, signature, new Object[] {result}); return result; } catch (ServiceException e) { // log the exception and re-throw throw LoggingHelper.logException(logger, signature, e); } } /** * <p> * This method is used to retrieve a help item. * </p> * * @param id the ID of the help item * * @return the help item, null will be returned if there's no such entity. * * @throws IllegalArgumentException: if id is not positive * @throws ServiceException if any other error occurred during the operation * */ @Override public HelpItem getHelpItem(long id) throws ServiceException { // prepare for logging Logger logger = getLogger(); final String signature = CLASS_NAME + ".getHelpItem(long)"; // log the entrance LoggingHelper.logEntrance(logger, signature, new String[] { "id" }, new Object[] { id }); // check the parameters Helper.checkPositive(logger, signature, "id", id); try { HelpItem result = getEntityManager().find(HelpItem.class, id); // log the exit LoggingHelper.logExit(logger, signature, new Object[] { result }); return result; } catch (IllegalArgumentException e) { throw LoggingHelper.logException(logger, signature, new ServiceException("Failed to get the result.", e)); } } }
30.747826
119
0.602941
0b1f2a40f361b79631c5d4fc238ea57487b9fd07
417
package com.walkhub.walkhub.global.exception; import com.walkhub.walkhub.global.error.exception.ErrorCode; import com.walkhub.walkhub.global.error.exception.WalkhubException; public class InvalidRoleException extends WalkhubException { public static final WalkhubException EXCEPTION = new InvalidRoleException(); private InvalidRoleException() { super(ErrorCode.INVALID_ROLE); } }
27.8
67
0.772182
7338d41d1cbcb78da0efe6ecb31a4ddfe5ba9410
2,359
package pers.ui.main; import java.awt.EventQueue; import java.awt.Font; import java.awt.Insets; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JSplitPane; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.border.Border; import javax.swing.plaf.BorderUIResource; import javax.swing.plaf.InsetsUIResource; import org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper; import org.jb2011.lnf.beautyeye.ch3_button.BEButtonUI; import org.jvnet.substance.*; import org.jvnet.substance.skin.*; import org.jvnet.substance.theme.SubstanceLightAquaTheme; import org.jvnet.substance.watermark.SubstanceBubblesWatermark; import pers.data.ManageSocketData; import pers.data.ProtocolType; import pers.data.SocketInfo; import pers.dll.infc.*; //import UncleHeart.DLL.Interface.JavaInvokeCPlus; public class MainLoader { private MainFrame mainFrame; public MainLoader() { // TODO Auto-generated constructor stub mainFrame=new MainFrame(); } public static void main(String[] args) throws InterruptedException { try { BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.osLookAndFeelDecorated; org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF(); Border bd = new org.jb2011.lnf.beautyeye.ch8_toolbar.BEToolBarUI.ToolBarBorder( UIManager.getColor("ToolBar.shadow") //Floatable时触点的颜色 , UIManager.getColor("ToolBar.highlight")//Floatable时触点的阴影颜色 , new Insets(6, 0, 11, 0)); //border的默认insets UIManager.put("RootPane.setupButtonVisible",false); //设置JTabbedPane的缩进 UIManager.put("TabbedPane.tabAreaInsets" , new javax.swing.plaf.InsetsUIResource(0,0,0,0)); //UIManager.put("TabbedPane.contentBorderInsets", new InsetsUIResource(0,0,2,0));//TabbedPane那里的虚线,上下的空格,最左的空距离,,最右的空距离 UIManager.put("TabbedPane.tabInsets", new InsetsUIResource(1,10,9,10));//TabbedPane面板的大小,第1第3个数控制上下的,第2和第4的数控制左右的 UIManager.put("FileChooser.useSystemExtensionHiding", false); } catch(Exception e) { //TODO exception } new MainLoader(); } }
25.923077
129
0.69309
0301e6b2f1d59117a0d7e6c64a65f0b05d29a191
631
package stonering.screen.util; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.utils.TimeUtils; import stonering.util.lang.StaticSkin; public class CounterLabel extends Label { private final String prefix; private long lastSecond; private int counter; public CounterLabel(String prefix) { super(prefix, StaticSkin.getSkin()); this.prefix = prefix; lastSecond = TimeUtils.millis(); counter = 0; } public void add() { counter++; } public void flush() { setText(prefix + counter); counter = 0; } }
21.033333
48
0.633914
02def6e78a791ad6ea222c023580f4ffab4407d2
1,319
/* * Copyright 2014-2019, Andrew Lindesay * Distributed under the terms of the MIT License. */ package org.haiku.haikudepotserver.passwordreset.controller; import org.haiku.haikudepotserver.passwordreset.PasswordResetServiceImpl; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; /** * <p>This services a GET request that redirects to the single-page environment and that will provide a user * interface that allows the user to reset the password based on the supplied token.</p> */ @Controller public class PasswordResetController { private final static String KEY_TOKEN = "token"; // TODO; separate so that it is not configured from the orchestration service. private final static String SEGMENT_PASSWORDRESET = PasswordResetServiceImpl.URL_SEGMENT_PASSWORDRESET; @RequestMapping(value = "/" + SEGMENT_PASSWORDRESET + "/{"+KEY_TOKEN+"}", method = RequestMethod.GET) public ModelAndView handleGet( @PathVariable(value = KEY_TOKEN) String token) { return new ModelAndView("redirect:/#!/completepasswordreset/"+token); } }
37.685714
108
0.777104
ce1f868cb416fb3e4f7a231da8f22eb8a5b1f223
5,267
package cli.BAM_Statistics; import picocli.CommandLine; import picocli.CommandLine.ArgGroup; import picocli.CommandLine.Command; import picocli.CommandLine.Option; import picocli.CommandLine.Parameters; import java.util.Scanner; import java.util.Vector; import java.util.concurrent.Callable; import java.io.File; import java.io.IOException; import util.ExtensionFileFilter; import scripts.BAM_Statistics.BAMGenomeCorrelation; /** BAM_StatisticsCLI/SEStats */ @Command(name = "bam-correlation", mixinStandardHelpOptions = true, description="Genome-Genome correlations for replicate comparisons given multiple sorted and indexed (BAI) BAM files.", sortOptions = false) public class BAMGenomeCorrelationCLI implements Callable<Integer> { @Parameters( index = "0..", description = "The BAM file whose statistics we want.") private File[] inputFiles; @Option(names = {"-f", "--files"}, description = "Input file list of BAM filepaths to correlate (formatted so each path is on its own line)") private boolean fileList = false; @Option(names = {"-o", "--output"}, description = "Specify output file, default is \"correlation_matrix\" or the input filename if -f flag used") private File outputBasename = null; //Read @ArgGroup(exclusive = true, multiplicity = "0..1", heading = "%nSelect Read to output:%n\t@|fg(red) (select no more than one of these options)|@%n") ReadType readType = new ReadType(); static class ReadType { @Option(names = {"-1", "--read1"}, description = "output read 1 (default)") boolean read1 = false; @Option(names = {"-2", "--read2"}, description = "output read 2") boolean read2 = false; @Option(names = {"-a", "--all-reads"}, description = "output combined") boolean allreads = false; @Option(names = {"-m", "--midpoint"}, description = "output midpoint (require PE)") boolean midpoint = false; } @Option(names = {"-t", "--tag-shift"}, description = "tag shift in bp (default 0)") private int tagshift = 0; @Option(names = {"-b", "--bin-size"}, description = "bin size in bp (default 10)") private int binSize = 10; @Option(names = {"--cpu"}, description = "CPUs to use (default 1)") private int cpu = 1; private int READ = 0; private Vector<File> bamFiles = new Vector<File>(); @Override public Integer call() throws Exception { System.err.println( ">BAMGenomeCorrelationCLI.call()" ); String validate = validateInput(); if(!validate.equals("")){ System.err.println( validate ); System.err.println("Invalid input. Check usage using '-h' or '--help'"); return(1); } BAMGenomeCorrelation script_obj = new BAMGenomeCorrelation( bamFiles, outputBasename, true, tagshift, binSize, cpu, READ); script_obj.getBAMGenomeCorrelation(false); System.err.println("Calculations Complete"); return(0); } private String validateInput() throws IOException { String r = ""; if(inputFiles==null){ r += "(!)Please indicate at least one file.\n"; return(r); //Import files as Vector list (scan input file if -f flag used) }else if(fileList){ //load files from input filelist if(inputFiles.length>1){ r += "(!)Please indicate only one file with bam filepaths when using the -f flag.\n"; return(r); }else if(!inputFiles[0].exists()){ r += "(!)File of list of file inputs does not exist: " + inputFiles[0].getCanonicalPath() + "\n"; return(r); }else{ Scanner scan = new Scanner(inputFiles[0]); while (scan.hasNextLine()) { bamFiles.add(new File(scan.nextLine().trim())); } scan.close(); } outputBasename = new File(ExtensionFileFilter.stripExtension(inputFiles[0])); }else{ //load input files into bam vector for(int x=0; x<inputFiles.length; x++){ bamFiles.add(inputFiles[x]); } } //check each file in Vector for(int x=0; x<bamFiles.size(); x++){ File BAM = bamFiles.get(x); File BAI = new File(BAM+".bai"); //check input exists if(!BAM.exists()|| BAM.isDirectory()){ r += "(!)BAM[" + x + "] file does not exist: " + BAM.getName() + "\n"; //check input extensions }else if(!"bam".equals(ExtensionFileFilter.getExtension(BAM))){ r += "(!)Is this a BAM file? Check extension: " + BAM.getName() + "\n"; //check BAI exists }else if(!BAI.exists() || BAI.isDirectory()){ r += "(!)BAI Index File does not exist for: " + BAM.getName() + "\n"; } } if(!r.equals("")){ return(r); } //set default output filename if(outputBasename==null){ outputBasename = new File("correlation_matrix"); //check output filename is valid }else{ //no check ext //check directory if(outputBasename.getParent()==null){ // System.err.println("default to current directory"); } else if(!new File(outputBasename.getParent()).exists()){ r += "(!)Check output directory exists: " + outputBasename.getParent() + "\n"; } } //Assign type value after validating if(readType.read1) { READ = 0; } else if(readType.read2) { READ = 1; } else if(readType.allreads) { READ = 2; } else if(readType.midpoint) { READ = 3; } //validate binSize, and CPU count if(binSize<1){ r += "(!)Please indicate a binSize of at least 1: " + binSize + "\n"; } if(cpu<1){ r += "(!)Cannot use less than 1 CPU: " + cpu + "\n"; } return(r); } }
36.324138
149
0.667173
577c9400cf685aae396525cbdc406a9d3ae71c91
730
package net.flyingfishflash.ledger.foundation; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component public class HttpSessionListenerLogging implements HttpSessionListener { private static final Logger logger = LoggerFactory.getLogger(HttpSessionListenerLogging.class); @Override public void sessionCreated(HttpSessionEvent se) { logger.info("* sessionCreated: sessionId = {}", se.getSession().getId()); } @Override public void sessionDestroyed(HttpSessionEvent se) { logger.info("* sessionDestroyed: sessionId = {}", se.getSession().getId()); } }
29.2
97
0.783562
e7d5964866669d194736c56a630ff783e28d3a12
6,517
package lab03; import java.util.Scanner; /** * Interface de menu para a classe Agenda. */ public class MenuAgenda { /** * A agenda a ser manipulada. */ private Agenda agenda = new Agenda(); /** * A string do menu principal. */ final private String menuPrincipal = "(C)adastrar Contato" + System.lineSeparator() + "(L)istar Contatos" + System.lineSeparator() + "(E)xibir Contato" + System.lineSeparator() + "(S)air"; /** * A string do texto que vem antes da escolha da opção de modo. */ final private String textoPreOpcao = "Opção> "; /** * Scanner para recolher entradas do usuario. */ private Scanner input = new Scanner(System.in); /** * Recolhe a opção escolhida pelo usuario. O método também mostra as opções disponiveis e * abre uma especie de prompt. * * @return A opção escolhida pelo usuario. */ private char escolheOpcao() { System.out.print(menuPrincipal + System.lineSeparator() + System.lineSeparator() + textoPreOpcao); String opcao = input.nextLine().trim().toUpperCase(); if (opcao.equals("")) { return 'X'; } else { return opcao.charAt(0); } } /** * Recolhe entrada do usuario para a execução do metodo da "cadastrarContatos" dp objeto "agenda". */ private void opcaoCadastrarContatos() { System.out.println(); try { System.out.print("Posição: "); int posicao = recolhePosicao(); System.out.print("Nome: "); String nome = recolheNome(); System.out.print("Sobrenome: "); String sobrenome = recolheSobrenome(); System.out.print("Telefone: "); String telefone = recolheTelefone(); agenda.cadastrarContato(nome, sobrenome, telefone, posicao); System.out.println("CADASTRO REALIZADO!"); } catch (IllegalArgumentException e) { System.out.println("Argumento inválido: " + e.getMessage()); } } /** * Recolhe a posição atraves da entrada do usuário e garante a integridade do dado dessa entrada. * Se os dados não estiverem integros, o metodo lançará uma exceção dependendo do erro. * * @return A posição digitada pelo usuário. */ private int recolhePosicao() { String stringPosicao = input.nextLine().trim(); if (stringPosicao.equals("")) { throw new IllegalArgumentException("Posição Vazia"); } int numPosicao; try { numPosicao = Integer.parseInt(stringPosicao); } catch (NumberFormatException e) { throw new NumberFormatException("Posição com letras ou maior que o suportado num inteiro."); } if (!(numPosicao >= 1 && numPosicao <= agenda.getLenght())) { throw new IllegalArgumentException("Posição fora dos limites da agenda."); } return numPosicao; } /** * Recolhe o nome atraves da entrada do usuário e garante a integridade do dado dessa entrada. * Se os dados não estiverem integros, o metodo lançará uma exceção dependendo do erro. * * @return O nome digitado pelo usuário. */ private String recolheNome() { String nome = input.nextLine().trim(); if (nome.equals("")) { throw new IllegalArgumentException("Nome vazio."); } return nome; } /** * Recolhe o sobrenome atraves da entrada do usuário e garante a integridade do dado dessa entrada. * Se os dados não estiverem integros, o metodo lançará uma exceção dependendo do erro. * * @return O sobrenome digitado pelo usuário. */ private String recolheSobrenome() { String nome = input.nextLine().trim(); if (nome.equals("")) { throw new IllegalArgumentException("Sobrenome vazio."); } return nome; } /** * Recolhe o telefone atraves da entrada do usuário e garante a integridade do dado dessa entrada. * Se os dados não estiverem integros, o metodo lançará uma exceção dependendo do erro. * * @return O telefone digitado pelo usuário. */ private String recolheTelefone() { String telefone = input.nextLine().trim(); if (telefone.equals("")) { throw new IllegalArgumentException("Telefone vazio."); } return telefone; } /** * Lista para o usuário todos os contatos da "agenda". */ private void opcaoListarContatos() { System.out.println(System.lineSeparator() + this.agenda); } /** * Exibe um contato específico para o usuário. */ private void opcaoExibirContato() { System.out.print("Contato> "); try { int posicaoContato = recolhePosicao(); Contato contato = this.agenda.acharContato(posicaoContato); if (contato == null) { System.out.println("Contato inexistente."); } else { System.out.println(contato); } } catch (IllegalArgumentException e) { System.out.println("Argumento inválido: " + e.getMessage()); } } /** * Fecha o input. */ private void opcaoSair() { input.close(); System.out.println("Até mais!"); } /** * Permite a interação do usuário com o objeto menu atráves da escolha de uma opção de modo. * O metodo finalizará quando a opção selecionada for "S" (Sair). */ public void init() { char opcao; loop: while (true) { opcao = this.escolheOpcao(); switch (opcao) { case 'C': this.opcaoCadastrarContatos(); break; case 'L': this.opcaoListarContatos(); break; case 'E': this.opcaoExibirContato(); break; case 'S': this.opcaoSair(); break loop; default: System.out.println("OPÇÃO INVÁLIDA!"); break; } System.out.println(); } } }
26.929752
104
0.550714
b886f968bc4569f270918c65b5fd0642928ccacc
299
package edu.abhi.test.applet; import java.applet.Applet; import java.awt.Graphics; public class Simple extends Applet{ /** * */ private static final long serialVersionUID = 7560346105217166222L; public void paint(Graphics g){ g.drawString("welcome to applet",150,150); } }
18.6875
67
0.705686
51705a05b4045e2ba4140f69f7fcfafa733b794a
1,090
package com.tim.scientific.portal.back.db.models; import com.fasterxml.jackson.databind.JsonNode; import com.tim.scientific.portal.back.db.models.crm.type.PageType; import com.tim.scientific.portal.back.db.models.security.UserPage; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.Type; import javax.persistence.*; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.UUID; @Entity @Table(name = "pages") @Getter @Setter public class Page { @Id @GeneratedValue() private UUID pageId; private String name; @ManyToOne(optional = false, cascade = CascadeType.ALL) @JoinColumn(name = "page_type_id") private PageType pageType; private Boolean active; private LocalDateTime createdAt; @OneToMany(mappedBy = "page") private List<Module> modules = new ArrayList<>(); @Type(type = "jsonb-node") @Column(columnDefinition = "jsonb") private JsonNode byPageData; @OneToMany(mappedBy = "page") private List<UserPage> editingUser = new ArrayList<>(); }
24.222222
66
0.731193
c919fa9e89627a99ae04b10cecc56ecb6c292b6d
2,514
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.test.tool.schema; import java.util.HashMap; import java.util.Map; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.SessionFactory; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.model.process.internal.ScanningCoordinator; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Environment; import org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.testing.TestForIssue; import org.hibernate.testing.jta.TestingJtaBootstrap; import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.logger.LoggerInspectionRule; import org.hibernate.testing.logger.Triggerable; import org.hibernate.test.resource.transaction.jta.JtaPlatformStandardTestingImpl; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jboss.logging.Logger; import static org.junit.Assert.assertEquals; /** * @author Vlad Mihalcea */ @TestForIssue( jiraKey = "HHH-12763" ) public class JtaPlatformLoggingTest extends BaseNonConfigCoreFunctionalTestCase { @Rule public LoggerInspectionRule logInspection = new LoggerInspectionRule( Logger.getMessageLogger( CoreMessageLogger.class, JtaPlatformInitiator.class.getName() ) ); private Triggerable triggerable = logInspection.watchForLogMessages( "HHH000490" ); @Override protected void addSettings(Map settings) { TestingJtaBootstrap.prepare( settings ); settings.put( AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, "jta" ); } @Test public void test() { assertEquals( "HHH000490: Using JtaPlatform implementation: [org.hibernate.testing.jta.TestingJtaPlatformImpl]", triggerable.triggerMessage() ); } @Override protected Class[] getAnnotatedClasses() { return new Class[] { TestEntity.class }; } @Entity( name = "TestEntity" ) @Table( name = "TestEntity" ) public static class TestEntity { @Id public Integer id; String name; } }
31.037037
102
0.798727
de4cae5b9be587b12fbe4f64f75e337302966f80
3,278
package com.wlcb.jpower.dbs.entity; import com.alibaba.fastjson.annotation.JSONField; import com.baomidou.mybatisplus.annotation.TableField; import com.fasterxml.jackson.annotation.JsonFormat; import com.wlcb.jpower.module.base.annotation.Dict; import com.wlcb.jpower.module.base.annotation.Excel; import com.wlcb.jpower.module.common.utils.DateUtil; import com.wlcb.jpower.module.tenant.entity.TenantEntity; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * @ClassName TbCoreUser * @Description TODO 登录用户信息 * @Author 郭丁志 * @Date 2020-05-18 17:12 * @Version 1.0 */ @Data public class TbCoreUser extends TenantEntity implements Serializable { private static final long serialVersionUID = 8829495593714085987L; @ApiModelProperty("登录用户名") @Excel(name = "登录用户名") private String loginId; @ApiModelProperty(name = "密码",hidden = true) private String password; @ApiModelProperty("头像") private String avatar; @ApiModelProperty("昵称") @Excel(name = "昵称") private String nickName; @ApiModelProperty("用户姓名") @Excel(name = "用户姓名") private String userName; @ApiModelProperty("证件类型 字典ID_TYPE") @Excel(name = "证件类型",readConverterExp = "1=身份证,2=中国护照,3=台胞证,4=外国护照,5=外国人永居证",combo={"身份证","中国护照","台胞证","外国护照","外国人永居证"}) @Dict(name = "ID_TYPE",attributes = "idTypeStr") private Integer idType; @ApiModelProperty("证件号码") @Excel(name = "证件号码") private String idNo; @ApiModelProperty("用户类型 字典USER_TYPE") @Excel(name ="用户类型",readConverterExp = "0=系统用户,1=普通用户,2=单位用户,3=会员,9=匿名用户",combo={"系统用户,","普通用户","单位用户","会员"}) @Dict(name = "USER_TYPE",attributes = "userTypeStr") private Integer userType; @ApiModelProperty("出生日期") @Excel(name ="出生日期") @JSONField(format="yyyy-MM-dd") @JsonFormat(shape = JsonFormat.Shape.STRING,timezone = "GMT+8", pattern = DateUtil.PATTERN_DATE,locale = "zh_CN") private Date birthday; @ApiModelProperty("邮箱") @Excel(name ="邮箱") private String email; @ApiModelProperty("电话") @Excel(name ="电话") private String telephone; @ApiModelProperty("地址") @Excel(name ="地址") private String address; @ApiModelProperty("邮编") @Excel(name ="邮编") private String postCode; @ApiModelProperty("第三方平台标识") private String otherCode; @ApiModelProperty("最后登录日期") @Excel(name ="最后登录日期",dateFormat = "yyyy-MM-dd HH:mm:ss",type = Excel.Type.EXPORT) @JSONField(format="yyyy-MM-dd HH:mm:ss") @JsonFormat(shape = JsonFormat.Shape.STRING,timezone = "GMT+8", pattern = DateUtil.PATTERN_DATETIME,locale = "zh_CN") private Date lastLoginTime; @ApiModelProperty("登录次数") @Excel(name ="登录次数",type = Excel.Type.EXPORT) private Integer loginCount; @ApiModelProperty("是否激活 字典YN01") @Excel(name ="是否激活",readConverterExp = "1=是,0=否",combo={"是,","否"}) @Dict(name = "YN01",attributes = "activationStatusStr") private Integer activationStatus; @ApiModelProperty("激活码") private String activationCode; @ApiModelProperty("部门主键") @Excel(name = "部门ID",type = Excel.Type.IMPORT) private String orgId; @ApiModelProperty("角色ID,多个逗号分割") @TableField(exist = false) private String roleIds; }
34.87234
124
0.697682
c3df78a7ec61ea43cd257138db73d9352e9e589d
6,313
/* * (c) Copyright 2021 Felipe Orozco, Robert Kruszewski. 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.gradlets.gradle.npm; import java.io.File; import org.gradle.api.artifacts.PublishArtifact; import org.gradle.api.internal.artifacts.dsl.LazyPublishArtifact; import org.gradle.api.internal.file.FileResolver; import org.gradle.api.internal.tasks.TaskDependencyContainer; import org.gradle.api.model.ObjectFactory; import org.gradle.api.provider.Provider; import org.gradle.api.tasks.bundling.AbstractArchiveTask; import org.gradle.internal.Cast; import org.gradle.internal.exceptions.DiagnosticsVisitor; import org.gradle.internal.typeconversion.NotationConvertResult; import org.gradle.internal.typeconversion.NotationConverter; import org.gradle.internal.typeconversion.NotationParser; import org.gradle.internal.typeconversion.NotationParserBuilder; import org.gradle.internal.typeconversion.TypeConversionException; public class DefaultNpmNotationParseFactory { private final ObjectFactory objectFactory; private final FileResolver fileResolver; public DefaultNpmNotationParseFactory(ObjectFactory objectFactory, FileResolver fileResolver) { this.objectFactory = objectFactory; this.fileResolver = fileResolver; } public final NotationParser<Object, NpmPublicationArtifact> create() { FileNotationConverter fileNotationConverter = new FileNotationConverter(fileResolver); ArchiveTaskNotationConverter archiveTaskNotationConverter = new ArchiveTaskNotationConverter(); PublishArtifactNotationConverter publishArtifactNotationConverter = new PublishArtifactNotationConverter(); ProviderNotationConverter providerNotationConverter = new ProviderNotationConverter(); return NotationParserBuilder.toType(NpmPublicationArtifact.class) .fromType(AbstractArchiveTask.class, archiveTaskNotationConverter) .fromType(PublishArtifact.class, publishArtifactNotationConverter) .fromType(Provider.class, Cast.uncheckedCast(providerNotationConverter)) .converter(fileNotationConverter) .toComposite(); } private final class ArchiveTaskNotationConverter implements NotationConverter<AbstractArchiveTask, NpmPublicationArtifact> { @Override public void convert( AbstractArchiveTask archiveTask, NotationConvertResult<? super NpmPublicationArtifact> result) throws TypeConversionException { NpmPublicationArtifact artifact = objectFactory.newInstance(ArchiveTaskBasedNpmArtifact.class, archiveTask); result.converted(artifact); } @Override public void describe(DiagnosticsVisitor visitor) { visitor.candidate("Instances of AbstractArchiveTask").example("distNpm"); } } private final class PublishArtifactNotationConverter implements NotationConverter<PublishArtifact, NpmPublicationArtifact> { @Override public void convert( PublishArtifact publishArtifact, NotationConvertResult<? super NpmPublicationArtifact> result) throws TypeConversionException { NpmPublicationArtifact artifact = objectFactory.newInstance(PublishArtifactBasedNpmArtifact.class, publishArtifact); result.converted(artifact); } @Override public void describe(DiagnosticsVisitor visitor) { visitor.candidate("Instances of PublishArtifact"); } } private final class ProviderNotationConverter implements NotationConverter<Provider<?>, NpmPublicationArtifact> { @Override public void convert(Provider<?> publishArtifact, NotationConvertResult<? super NpmPublicationArtifact> result) throws TypeConversionException { NpmPublicationArtifact artifact = objectFactory.newInstance( PublishArtifactBasedNpmArtifact.class, new LazyPublishArtifact(publishArtifact, fileResolver)); result.converted(artifact); } @Override public void describe(DiagnosticsVisitor visitor) { visitor.candidate("Instances of Provider"); } } private final class FileNotationConverter implements NotationConverter<Object, NpmPublicationArtifact> { private final NotationParser<Object, File> fileResolverNotationParser; private FileNotationConverter(FileResolver fileResolver) { this.fileResolverNotationParser = fileResolver.asNotationParser(); } @Override public void convert(Object notation, NotationConvertResult<? super NpmPublicationArtifact> result) throws TypeConversionException { File file = fileResolverNotationParser.parseNotation(notation); NpmPublicationArtifact mavenArtifact = objectFactory.newInstance(FileBasedNpmArtifact.class, file); if (notation instanceof TaskDependencyContainer) { TaskDependencyContainer taskDependencyContainer = (TaskDependencyContainer) notation; if (notation instanceof Provider) { // wrap to disable special handling of providers by DefaultTaskDependency in this case // (workaround for https://github.com/gradle/gradle/issues/11054) taskDependencyContainer = context -> context.add(notation); } mavenArtifact.builtBy(taskDependencyContainer); } result.converted(mavenArtifact); } @Override public void describe(DiagnosticsVisitor visitor) { fileResolverNotationParser.describe(visitor); } } }
46.419118
120
0.725329
879232cf33078d6cb335f4c11751b55ae93aaa47
7,364
/* * DefaultListFacadeTest.java * Copyright James Dempsey, 2012 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Created on 09/06/2012 11:30:14 AM * * $Id$ */ package pcgen.core.facade.util; import pcgen.facade.util.DefaultListFacade; import static org.junit.Assert.*; import java.util.Arrays; import java.util.List; import org.junit.Test; import pcgen.facade.util.event.ListEvent; import pcgen.facade.util.event.ListListener; /** * The Class <code></code> ... * * <br/> * Last Editor: $Author$ * Last Edited: $Date$ * * @author James Dempsey <jdempsey@users.sourceforge.net> * @version $Revision$ */ public class DefaultListFacadeTest { /** * Test method for {@link pcgen.core.facade.util.DefaultListFacade#updateContents(java.util.List)}. */ @Test public void testUpdateContents() { TestListener listener = new TestListener(); DefaultListFacade<String> theList = new DefaultListFacade<String>(Arrays.asList(new String[]{"A", "B", "C", "E"})); theList.addListListener(listener); List<String> newElements = Arrays.asList(new String[]{"A", "C", "D", "E"}); theList.updateContents(newElements); assertEquals("Lists have not been made the same", newElements, theList.getContents()); assertEquals("Incorrect number of adds", 1, listener.addCount); assertEquals("Incorrect number of removes", 1, listener.removeCount); assertEquals("Incorrect number of changes", 0, listener.changeCount); assertEquals("Incorrect number of modifies", 0, listener.modifyCount); } /** * Test method for {@link pcgen.core.facade.util.DefaultListFacade#updateContents(java.util.List)}. */ @Test public void testUpdateContentsDisparate() { TestListener listener = new TestListener(); DefaultListFacade<String> theList = new DefaultListFacade<String>(Arrays.asList(new String[]{"A", "B", "C", "E"})); theList.addListListener(listener); List<String> newElements = Arrays.asList(new String[]{"F", "G", "H", "I", "M"}); theList.updateContents(newElements); assertEquals("Lists have not been made the same", newElements, theList.getContents()); assertEquals("Incorrect number of adds", 5, listener.addCount); assertEquals("Incorrect number of removes", 4, listener.removeCount); assertEquals("Incorrect number of changes", 0, listener.changeCount); assertEquals("Incorrect number of modifies", 0, listener.modifyCount); } /** * Test method for {@link pcgen.core.facade.util.DefaultListFacade#updateContents(java.util.List)}. */ @Test public void testUpdateContentsFromEmpty() { TestListener listener = new TestListener(); DefaultListFacade<String> theList = new DefaultListFacade<String>(); theList.addListListener(listener); List<String> newElements = Arrays.asList(new String[]{"A", "C", "D", "E"}); theList.updateContents(newElements); assertEquals("Lists have not been made the same", newElements, theList.getContents()); assertEquals("Incorrect number of adds", 0, listener.addCount); assertEquals("Incorrect number of removes", 0, listener.removeCount); assertEquals("Incorrect number of changes", 1, listener.changeCount); assertEquals("Incorrect number of modifies", 0, listener.modifyCount); } /** * Test method for {@link pcgen.core.facade.util.DefaultListFacade#updateContents(java.util.List)}. */ @Test public void testUpdateContentsToEmpty() { TestListener listener = new TestListener(); DefaultListFacade<String> theList = new DefaultListFacade<String>(Arrays.asList(new String[]{"A", "B", "C", "E"})); theList.addListListener(listener); List<String> newElements = Arrays.asList(); theList.updateContents(newElements); assertEquals("Lists have not been made the same", newElements, theList.getContents()); assertEquals("Incorrect number of adds", 0, listener.addCount); assertEquals("Incorrect number of removes", 0, listener.removeCount); assertEquals("Incorrect number of changes", 1, listener.changeCount); assertEquals("Incorrect number of modifies", 0, listener.modifyCount); } /** * Test method for {@link pcgen.core.facade.util.DefaultListFacade#updateContents(java.util.List)}. */ @Test public void testUpdateContentsTooLarge() { TestListener listener = new TestListener(); DefaultListFacade<String> theList = new DefaultListFacade<String>(Arrays.asList(new String[]{"A", "B", "C", "E"})); theList.addListListener(listener); List<String> newElements = Arrays.asList(new String[]{"A", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}); theList.updateContents(newElements); assertEquals("Lists have not been made the same", newElements, theList.getContents()); assertEquals("Incorrect number of adds", 0, listener.addCount); assertEquals("Incorrect number of removes", 0, listener.removeCount); assertEquals("Incorrect number of changes", 1, listener.changeCount); assertEquals("Incorrect number of modifies", 0, listener.modifyCount); } /** * Test method for {@link pcgen.core.facade.util.DefaultListFacade#updateContents(java.util.List)}. */ @Test public void testUpdateContentsTooLargeFrom() { TestListener listener = new TestListener(); DefaultListFacade<String> theList = new DefaultListFacade<String>( Arrays.asList(new String[]{"A", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"})); theList.addListListener(listener); List<String> newElements = Arrays.asList(new String[]{"A", "B", "C", "E"}); theList.updateContents(newElements); assertEquals("Lists have not been made the same", newElements, theList.getContents()); assertEquals("Incorrect number of adds", 0, listener.addCount); assertEquals("Incorrect number of removes", 0, listener.removeCount); assertEquals("Incorrect number of changes", 1, listener.changeCount); assertEquals("Incorrect number of modifies", 0, listener.modifyCount); } private class TestListener implements ListListener<String> { int addCount = 0; int removeCount = 0; int changeCount = 0; int modifyCount = 0; /** * {@inheritDoc} */ @Override public void elementAdded(ListEvent<String> e) { addCount++; } /** * {@inheritDoc} */ @Override public void elementRemoved(ListEvent<String> e) { removeCount++; } /** * {@inheritDoc} */ @Override public void elementsChanged(ListEvent<String> e) { changeCount++; } /** * {@inheritDoc} */ @Override public void elementModified(ListEvent<String> e) { modifyCount++; } } }
32.875
100
0.700299
0ec75f6eeaa9ca29aedb64b6b99f4f5d2321e4c7
5,268
package de.tum.mitfahr.networking.models.response; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import de.tum.mitfahr.networking.models.Conversation; import de.tum.mitfahr.networking.models.Rating; import de.tum.mitfahr.networking.models.Ride; import de.tum.mitfahr.networking.models.RideRequest; import de.tum.mitfahr.networking.models.User; /** * Created by amr on 31/05/14. */ public class SearchResponse implements Serializable { private int id; private String destination; private double price; private String car; private User passengers[]; private Conversation conversations[]; private Rating ratings[]; private RideRequest requests[]; private boolean is_ride_request; private User ride_owner; private String departure_place; private int ride_type; private String departure_time; private String created_at; private String updated_at; private int free_seats; private String meeting_point; private double departure_latitude; private double departure_longitude; private double destination_latitude; private double destination_longitude; private int user_id; private double realtime_km; private String realtime_departure_time; private double regular_ride_id; private double is_finished; public SearchResponse(int id, double is_finished, String destination, double price, String car, User[] passengers, Rating[] ratings, RideRequest[] requests, Conversation[] conversations, boolean is_ride_request, String departure_place, User ride_owner, int ride_type, String departure_time, String created_at, String updated_at, int free_seats, String meeting_point, double departure_latitude, double departure_longitude, double destination_latitude, double destination_longitude, int user_id, double realtime_km, String realtime_departure_time, double regular_ride_id) { this.id = id; this.is_finished = is_finished; this.destination = destination; this.price = price; this.car = car; this.passengers = passengers; this.ratings = ratings; this.requests = requests; this.conversations = conversations; this.is_ride_request = is_ride_request; this.departure_place = departure_place; this.ride_owner = ride_owner; this.ride_type = ride_type; this.departure_time = departure_time; this.created_at = created_at; this.updated_at = updated_at; this.free_seats = free_seats; this.meeting_point = meeting_point; this.departure_latitude = departure_latitude; this.departure_longitude = departure_longitude; this.destination_latitude = destination_latitude; this.destination_longitude = destination_longitude; this.user_id = user_id; this.realtime_km = realtime_km; this.realtime_departure_time = realtime_departure_time; this.regular_ride_id = regular_ride_id; } public int getId() { return id; } public String getDestination() { return destination; } public double getPrice() { return price; } public String getCar() { return car; } public User[] getPassengers() { return passengers; } public Conversation[] getConversations() { return conversations; } public Rating[] getRatings() { return ratings; } public RideRequest[] getRequests() { return requests; } public boolean is_ride_request() { return is_ride_request; } public User getRide_owner() { return ride_owner; } public String getDeparture_place() { return departure_place; } public int getRide_type() { return ride_type; } public String getDeparture_time() { return departure_time; } public String getCreated_at() { return created_at; } public String getUpdated_at() { return updated_at; } public int getFree_seats() { return free_seats; } public String getMeeting_point() { return meeting_point; } public double getDeparture_latitude() { return departure_latitude; } public double getDeparture_longitude() { return departure_longitude; } public double getDestination_latitude() { return destination_latitude; } public double getDestination_longitude() { return destination_longitude; } public int isUser_id() { return user_id; } public double getRealtime_km() { return realtime_km; } public String getRealtime_departure_time() { return realtime_departure_time; } public double getRegular_ride_id() { return regular_ride_id; } public double getIs_finished() { return is_finished; } public List<Ride> getRides() { return null; } public void setDestination_longitude(double destination_longitude) { this.destination_longitude = destination_longitude; } public void setDestination_latitude(double destination_latitude) { this.destination_latitude = destination_latitude; } }
27.581152
575
0.689446
9a93b903555b3db714486ebe8d4f428b78a35a63
329
package mod.linguardium.instantport.mixin; import net.minecraft.entity.player.PlayerEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @Mixin(PlayerEntity.class) public class NetherPortalTimeMixin { @Overwrite public int getMaxNetherPortalTime() { return 1; } }
23.5
48
0.772036
897518ea10dfcbef2e42ab5da76fef8482c9304a
2,509
package tutoraid.logic.parser; import java.util.regex.Matcher; import java.util.regex.Pattern; import tutoraid.commons.core.Messages; import tutoraid.logic.commands.DeleteCommand; import tutoraid.logic.commands.DeleteLessonCommand; import tutoraid.logic.commands.DeleteProgressCommand; import tutoraid.logic.commands.DeleteStudentCommand; import tutoraid.logic.commands.DeleteStudentFromLessonCommand; import tutoraid.logic.commands.HelpCommand; import tutoraid.logic.parser.exceptions.ParseException; /** * Checks if a given delete command is to delete a student/lesson from TutorAid * or to delete the progress note of a student or to delete students from lessons. */ public class DeleteCommandParser implements Parser<DeleteCommand> { /** * Used for initial separation of command flag ('-s', '-l', -p' or '-sl') and args. */ private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandFlag>\\S+)(?<arguments>.*)"); /** * Parses user input into a specific delete command for execution. * @param userInput user input string after the 'del' keyword has been removed * @return the specific add command (delete student or delete progress) based on the user input * @throws ParseException if the user input does not conform the expected format */ @Override public DeleteCommand parse(String userInput) throws ParseException { final Matcher matcher; final String commandFlag; final String arguments; matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim()); if (!matcher.matches()) { throw new ParseException(String.format( Messages.MESSAGE_INVALID_DELETE_COMMAND, HelpCommand.MESSAGE_USAGE)); } commandFlag = matcher.group("commandFlag"); arguments = matcher.group("arguments"); switch (commandFlag) { case DeleteStudentCommand.COMMAND_FLAG: return new DeleteStudentCommandParser().parse(arguments); case DeleteProgressCommand.COMMAND_FLAG: return new DeleteProgressCommandParser().parse(arguments); case DeleteStudentFromLessonCommand.COMMAND_FLAG: return new DeleteStudentFromLessonCommandParser().parse(arguments); case DeleteLessonCommand.COMMAND_FLAG: return new DeleteLessonCommandParser().parse(arguments); default: throw new ParseException(Messages.MESSAGE_INVALID_DELETE_COMMAND); } } }
38.6
99
0.718214
d7e4d3b86b26fefba828f7e29f99444a0092de42
6,791
package me.wallhacks.spark.manager; import com.mojang.realmsclient.gui.ChatFormatting; import me.wallhacks.spark.Spark; import me.wallhacks.spark.event.player.PacketReceiveEvent; import me.wallhacks.spark.util.MC; import me.wallhacks.spark.util.objects.Notification; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.play.server.SPacketDestroyEntities; import net.minecraft.network.play.server.SPacketEntityStatus; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import me.wallhacks.spark.systems.hud.huds.Notifications; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class PopManager implements MC { public PopManager() { Spark.eventBus.register(this); } private Map<EntityPlayer, Integer> popList = new ConcurrentHashMap<>(); public final Map<EntityPlayer, Notification> toAnnouce = new ConcurrentHashMap<>(); @SubscribeEvent public void onPacketReceive(PacketReceiveEvent event) { if (event.getPacket() instanceof SPacketDestroyEntities) { SPacketDestroyEntities packetIn = (SPacketDestroyEntities)event.getPacket(); for(int i = 0; i < packetIn.getEntityIDs().length; ++i) { Entity entity = mc.world.getEntityByID(packetIn.getEntityIDs()[i]); if (entity instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer)entity; if(player.getHealth() <= 0.0f) { if (!player.equals(mc.player) && Notifications.INSTANCE.death.getValue() && Notifications.INSTANCE.isEnabled()) { if (toAnnouce.containsKey(player)) { Notification notification = toAnnouce.get(player); notification.text = getPopString(player); if (Notifications.notifications.contains(notification)) { if (notification.stage >= 2) { notification.stage = 2; notification.animateTimer.reset(); } notification.timer.reset(); } else { notification = new Notification(getDeathString(player)); toAnnouce.remove(player); toAnnouce.put(player, notification); Notifications.addNotification(notification); } } else { toAnnouce.put(player, new Notification(getDeathString(player))); Notifications.addNotification(toAnnouce.get(player)); } } resetPops(player); } } } } if (event.getPacket() instanceof SPacketEntityStatus) { SPacketEntityStatus packet = (SPacketEntityStatus) event.getPacket(); try { if (packet.getOpCode() == 0x23 && packet.getEntity(mc.world) instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) packet.getEntity(mc.world); popTotem(player); if (!player.equals(mc.player) && player.isEntityAlive() && Notifications.INSTANCE.pop.getValue() && Notifications.INSTANCE.isEnabled()) { if (toAnnouce.containsKey(player)) { Notification notification = toAnnouce.get(player); notification.text = getPopString(player); if (Notifications.notifications.contains(notification)) { if (notification.stage >= 2) { notification.stage = 2; notification.animateTimer.reset(); } notification.timer.reset(); } else { notification = new Notification(getPopString(player)); toAnnouce.remove(player); toAnnouce.put(player, notification); Notifications.addNotification(notification); } } else { toAnnouce.put(player, new Notification(getPopString(player))); Notifications.addNotification(toAnnouce.get(player)); } } } } catch (Exception ignored) { } } } public void resetPops(EntityPlayer player) { this.setTotemPops(player, 0); } public void popTotem(EntityPlayer player) { this.popList.merge(player, 1, Integer::sum); } public void setTotemPops(EntityPlayer player, int amount) { this.popList.put(player, amount); } public int getTotemPops(EntityPlayer player) { return this.popList.get(player) == null ? 0 : this.popList.get(player); } private String getDeathString(EntityPlayer player) { int pops = getTotemPops(player); if (Spark.socialManager.isFriend(player.getName())) { return "you just let " + ChatFormatting.AQUA + player.getName() + ChatFormatting.RESET + " die after popping " + ChatFormatting.RED + ChatFormatting.BOLD + pops + ChatFormatting.RESET + (pops == 1 ? " totem" : " totems"); } else { return ChatFormatting.RED + player.getName() + ChatFormatting.RESET + " just died after popping " + ChatFormatting.RED + ChatFormatting.BOLD + pops + ChatFormatting.RESET + (pops == 1 ? " totem" : " totems"); } } private String getPopString(EntityPlayer player) { int pops = getTotemPops(player); if (Spark.socialManager.isFriend(player.getName())) { return "ur friend " + ChatFormatting.AQUA + player.getName() + ChatFormatting.RESET + " has now popped " + ChatFormatting.RED + ChatFormatting.BOLD + pops + ChatFormatting.RESET + (pops == 1 ? " totem" : " totems") + " go help them"; } else { return ChatFormatting.RED + player.getName() + ChatFormatting.RESET + " has now popped " + ChatFormatting.RED + ChatFormatting.BOLD + pops + ChatFormatting.RESET + (pops == 1 ? " totem" : " totems"); } } }
48.507143
157
0.541599
c155e9041122520f38d57342beb3888a9485a840
7,927
/** * BigBlueButton open source conferencing system - http://www.bigbluebutton.org/ * * Copyright (c) 2012 BigBlueButton Inc. and by respective authors (see below). * * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation; either version 3.0 of the License, or (at your option) any later * version. * * BigBlueButton is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with BigBlueButton; if not, see <http://www.gnu.org/licenses/>. * */ package org.bigbluebutton.deskshare.server.servlet; import java.util.*; import java.awt.Point; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.bigbluebutton.deskshare.common.Dimension; import org.bigbluebutton.deskshare.server.session.ISessionManagerGateway; import org.springframework.context.ApplicationContext; import org.springframework.http.HttpStatus; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; public class HttpTunnelStreamController extends MultiActionController { private boolean hasSessionManager = false; private ISessionManagerGateway sessionManager; public ModelAndView screenCaptureHandler(HttpServletRequest request, HttpServletResponse response) throws Exception { String event = request.getParameterValues("event")[0]; int captureRequest = Integer.parseInt(event); if (0 == captureRequest) { handleCaptureStartRequest(request, response); } else if (1 == captureRequest) { handleCaptureUpdateRequest(request, response); if (isSharingStopped(request, response)) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } else if (2 == captureRequest) { handleCaptureEndRequest(request, response); } else if (3 == captureRequest) { handleUpdateMouseLocationRequest(request, response); } else { System.out.println("****Cannot handle screen capture event " + captureRequest); } return null; } private void handleUpdateMouseLocationRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String room = request.getParameterValues("room")[0]; String mouseX = request.getParameterValues("mousex")[0]; String mouseY = request.getParameterValues("mousey")[0]; String seqNum = request.getParameterValues("sequenceNumber")[0]; Point loc = new Point(Integer.parseInt(mouseX), Integer.parseInt(mouseY)); if (! hasSessionManager) { sessionManager = getSessionManager(); hasSessionManager = true; } sessionManager.updateMouseLocation(room, loc, Integer.parseInt(seqNum)); } private Boolean isSharingStopped(HttpServletRequest request, HttpServletResponse response) throws Exception { String room = request.getParameterValues("room")[0]; return sessionManager.isSharingStopped(room); } private void handleCaptureStartRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String room = request.getParameterValues("room")[0]; String seqNum = request.getParameterValues("sequenceNumber")[0]; String screenInfo = request.getParameterValues("screenInfo")[0]; String blockInfo = request.getParameterValues("blockInfo")[0]; String svc2Info = request.getParameterValues("svc2")[0]; String[] screen = screenInfo.split("x"); String[] block = blockInfo.split("x"); Dimension screenDim, blockDim; screenDim = new Dimension(Integer.parseInt(screen[0]), Integer.parseInt(screen[1])); blockDim = new Dimension(Integer.parseInt(block[0]), Integer.parseInt(block[1])); boolean useSVC2 = Boolean.parseBoolean(svc2Info); if (! hasSessionManager) { sessionManager = getSessionManager(); hasSessionManager = true; } sessionManager.createSession(room, screenDim, blockDim, Integer.parseInt(seqNum), useSVC2); } private void handleCaptureUpdateRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; String room = request.getParameterValues("room")[0]; String keyframe = "false"; // This data is never a keyframe //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Get the list of multipart files that are in this POST request. // Get the block info from each embedded file and send it to the // session manager to update the viewers. //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Iterator uploadedFilenames = multipartRequest.getFileNames(); while(uploadedFilenames.hasNext()) { // process each embedded upload-file (block) String uploadedFilename = (String)uploadedFilenames.next(); MultipartFile multipartFile = multipartRequest.getFile(uploadedFilename); // Parse the block info out of the upload file name // The file name is of format "blockgroup_<seqnum>_<position>". String[] uploadedFileInfo = uploadedFilename.split("[_]"); String seqNum = uploadedFileInfo[1]; String position = uploadedFileInfo[2]; // Update the viewers with the uploaded block data. sessionManager.updateBlock(room, Integer.valueOf(position), multipartFile.getBytes(), false, // This data is never a keyframe Integer.parseInt(seqNum)); } // process each embedded upload-file (block) /* // MultipartFile is a copy of file in memory, not in file system MultipartFile multipartFile = multipartRequest.getFile("blockdata"); long startRx = System.currentTimeMillis(); byte[] blockData = multipartFile.getBytes(); String room = request.getParameterValues("room")[0]; String seqNum = request.getParameterValues("sequenceNumber")[0]; String keyframe = request.getParameterValues("keyframe")[0]; String position = request.getParameterValues("position")[0]; if (! hasSessionManager) { sessionManager = getSessionManager(); hasSessionManager = true; } sessionManager.updateBlock(room, Integer.valueOf(position), blockData, Boolean.parseBoolean(keyframe), Integer.parseInt(seqNum)); */ } private void handleCaptureEndRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String room = request.getParameterValues("room")[0]; String seqNum = request.getParameterValues("sequenceNumber")[0]; if (! hasSessionManager) { sessionManager = getSessionManager(); hasSessionManager = true; } System.out.println("HttpTunnel: Received Capture Enfd Event."); sessionManager.removeSession(room, Integer.parseInt(seqNum)); } private ISessionManagerGateway getSessionManager() { //Get the servlet context ServletContext ctx = getServletContext(); //Grab a reference to the application context ApplicationContext appCtx = (ApplicationContext) ctx.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); //Get the bean holding the parameter ISessionManagerGateway manager = (ISessionManagerGateway) appCtx.getBean("sessionManagerGateway"); if (manager != null) { System.out.println("****Got the SessionManager context: *****"); } return manager; } }
41.721053
131
0.72928
b7301fdd15c6ceeffad3604f2e207d08db1db6d5
6,217
package com.tracelink.prodsec.plugin.jira; import com.tracelink.prodsec.plugin.jira.model.JiraThresholds; import com.tracelink.prodsec.plugin.jira.model.JiraVuln; import com.tracelink.prodsec.plugin.jira.service.JiraThresholdsService; import com.tracelink.prodsec.plugin.jira.service.JiraUpdateService; import com.tracelink.prodsec.plugin.jira.service.JiraVulnMetricsService; import com.tracelink.prodsec.synapse.auth.SynapseAdminAuthDictionary; import com.tracelink.prodsec.synapse.products.model.ProductLineModel; import com.tracelink.prodsec.synapse.scheduler.job.SchedulerJob; import com.tracelink.prodsec.synapse.scheduler.job.SimpleSchedulerJob; import com.tracelink.prodsec.synapse.scheduler.service.schedule.PeriodicSchedule; import com.tracelink.prodsec.synapse.scorecard.model.ScorecardColumn; import com.tracelink.prodsec.synapse.scorecard.model.ScorecardValue; import com.tracelink.prodsec.synapse.scorecard.model.SimpleScorecardColumn; import com.tracelink.prodsec.synapse.sidebar.model.SidebarLink; import com.tracelink.prodsec.synapse.sidebar.model.SimpleSidebarLink; import com.tracelink.prodsec.synapse.spi.PluginDisplayGroup; import com.tracelink.prodsec.synapse.spi.PluginWithDatabase; import com.tracelink.prodsec.synapse.spi.annotation.SynapsePluginDatabaseEnabled; import java.util.Collections; import org.springframework.beans.factory.annotation.Autowired; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; /** * The Jira Plugin allows for gathering information from a Jira Server. Using JQL * search phrases to query the client, this plugin displays metrics * from a team's scrum progress and gathers information on Jira issues, * in this case, issues regarding security vulnerabilities. * * @author bhoran */ @SynapsePluginDatabaseEnabled public class JiraPlugin extends PluginWithDatabase { /** * These fields are made public to share the schema definition with the model, * the privilege definition with the controller, and pagelinks with the controller */ public static final String SCHEMA = "jira"; public static final String PAGELINK = "/jira"; public static final String CONFIGURATIONS_PAGE = PAGELINK + "/configure"; public static final String VULN_PAGE = PAGELINK + "/vulns"; public static final String SCRUM_PAGE = PAGELINK + "/scrum"; public static final String MAPPINGS_PAGE = PAGELINK + "/mappings"; private final JiraUpdateService jiraUpdateService; private final JiraVulnMetricsService vulnService; private final JiraThresholdsService thresholdsService; /** * Creates the Jira plugin with three pre-configured services: the {@link * JiraUpdateService}, to regularly retrieve data from the Jira server; the {@link * JiraVulnMetricsService}, to parse and store data regarding vulnerable issues * and the {@link JiraThresholdsService}, to store and retrieve data * that defines a relative tolerance to issues. * * @param jiraUpdateService the Jira Update service * @param vulnService the Jira VulnMetrics Service * @param thresholdsService the risk tolerance thresholds service */ public JiraPlugin(@Autowired JiraUpdateService jiraUpdateService, @Autowired JiraVulnMetricsService vulnService, @Autowired JiraThresholdsService thresholdsService) { this.jiraUpdateService = jiraUpdateService; this.vulnService = vulnService; this.thresholdsService = thresholdsService; } @Override protected String getSchemaName() { return SCHEMA; } @Override protected String getMigrationsLocation() { return "db/jira/"; } @Override protected PluginDisplayGroup getPluginDisplayGroup() { return new PluginDisplayGroup("Jira Plugin", "stars"); } /** * {@inheritDoc} */ @Override protected List<SchedulerJob> getJobsForScheduler() { return Arrays.asList( new SimpleSchedulerJob("Fetch Jira Data").withJob(jiraUpdateService::syncAllData) .onSchedule(new PeriodicSchedule(1, TimeUnit.DAYS))); } /** * {@inheritDoc} */ @Override protected List<ScorecardColumn> getColumnsForScorecard() { return Arrays.asList( // Create the scorecard column for reporting new SimpleScorecardColumn("Jira Vulns").withPageLink(VULN_PAGE) .withProductLineCallback(this::getScorecardForProductLine)); } /** * {@inheritDoc} */ @Override protected List<SidebarLink> getLinksForSidebar() { // Vulnerabilities page SidebarLink vulnMetrics = new SimpleSidebarLink("Vulnerabilities") .withMaterialIcon("dashboard") .withPageLink(VULN_PAGE); // Scrum Metrics page SidebarLink scrumMetrics = new SimpleSidebarLink("Scrum Metrics") .withMaterialIcon("timeline") .withPageLink(SCRUM_PAGE); // Configurations page SidebarLink configurations = new SimpleSidebarLink("Configurations") .withMaterialIcon("settings_applications") .withPageLink(CONFIGURATIONS_PAGE) .withPrivileges(SynapseAdminAuthDictionary.ADMIN_PRIV); // Mappings page SidebarLink mappings = new SimpleSidebarLink("Mappings").withMaterialIcon("swap_horiz") .withPageLink(MAPPINGS_PAGE).withPrivileges(SynapseAdminAuthDictionary.ADMIN_PRIV); return Arrays.asList(vulnMetrics, scrumMetrics, configurations, mappings); } /** * {@inheritDoc} */ @Override protected List<String> getPrivileges() { return Collections.emptyList(); } private ScorecardValue getScorecardForProductLine(ProductLineModel productLine) { List<JiraVuln> issues = vulnService .getUnresolvedVulnsForProductLine(productLine); int numIssues = issues.size(); if (numIssues == 0) { return new ScorecardValue("No Data", ScorecardValue.TrafficLight.NONE); } return new ScorecardValue(numIssues + "", getTrafficLight(numIssues)); } private ScorecardValue.TrafficLight getTrafficLight(long score) { JiraThresholds thresholds = thresholdsService.getThresholds(); if (thresholds == null) { return ScorecardValue.TrafficLight.NONE; } else if (score < thresholds.getGreenYellow()) { return ScorecardValue.TrafficLight.GREEN; } else if (score >= thresholds.getGreenYellow() && score < thresholds.getYellowRed()) { return ScorecardValue.TrafficLight.YELLOW; } else { return ScorecardValue.TrafficLight.RED; } } }
34.538889
89
0.783175
440bdf1c534fc93c7a77cd58ba8740df761aa58d
312
package com.example.guestbook.helloworld.service; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; /** * */ import javax.enterprise.context.ApplicationScoped; /** * */ @ApplicationPath("/") @ApplicationScoped public class HelloworldserviceRestApplication extends Application { }
15.6
67
0.772436
8a07a663b0cbecb5d9976b42d0f9d437101fc7bf
1,143
package com.annotation.factory.config; import com.annotation.factory.annotation.MaskSensitiveData; import com.annotation.factory.introspector.MaskSensitiveDataAnnotationIntrospector; import com.fasterxml.jackson.databind.AnnotationIntrospector; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; @Configuration @ConditionalOnClass(MaskSensitiveData.class) public class MaskSensitiveDataObjectMapperConfig { @Primary @Autowired public void objectMapper(ObjectMapper objectMapper) { AnnotationIntrospector serializationAnnotationIntrospector = AnnotationIntrospector.pair(objectMapper.getSerializationConfig().getAnnotationIntrospector(), new MaskSensitiveDataAnnotationIntrospector()); objectMapper.setAnnotationIntrospectors(serializationAnnotationIntrospector, objectMapper.getDeserializationConfig().getAnnotationIntrospector()); } }
47.625
160
0.846019
33244012bad26ccb6332201f8b4c2ca90fd814c0
2,036
/* * Copyright 2021 Club Obsidian and 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 com.clubobsidian.dynamicgui.server; import com.clubobsidian.dynamicgui.entity.PlayerWrapper; import com.clubobsidian.dynamicgui.messaging.MessagingRunnable; import com.clubobsidian.dynamicgui.plugin.DynamicGuiPlugin; import com.clubobsidian.dynamicgui.scheduler.Scheduler; import com.clubobsidian.dynamicgui.world.WorldWrapper; import java.util.Collection; import java.util.UUID; public abstract class FakeServer { private final Scheduler scheduler; public FakeServer(Scheduler scheduler) { this.scheduler = scheduler; } public Scheduler getScheduler() { return this.scheduler; } public abstract void broadcastMessage(String message); public abstract void broadcastJsonMessage(String json); public abstract void dispatchServerCommand(String command); public abstract PlayerWrapper<?> getPlayer(UUID uuid); public abstract PlayerWrapper<?> getPlayer(String name); public abstract Collection<PlayerWrapper<?>> getOnlinePlayers(); public abstract int getGlobalPlayerCount(); public abstract ServerType getType(); public abstract void registerOutgoingPluginChannel(DynamicGuiPlugin plugin, String channel); public abstract void registerIncomingPluginChannel(DynamicGuiPlugin plugin, String channel, MessagingRunnable runnable); public abstract WorldWrapper<?> getWorld(String worldName); }
33.377049
124
0.761297
fe967ca6d7aad2cb8268e7685f4171615869b527
4,689
package com.viloma.jagoframework.sample; import java.sql.SQLException; import java.util.Date; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import com.viloma.jagoframework.JagoServer; /** * Your project main - needs to extend JagoServer which provides a full server-stack web-dev tools * * it provides * - a router * - an ORM with table generator * - and a dev time admin */ public class JagoFrameworkSample extends JagoServer { /** * In main - specify the port, location of your files, and configuration to use (can specify web.xml.dev / uat here for testing) */ public static void main(String[] args) throws Exception { startFromWar(8082, "war", "WEB-INF/web.xml"); } /** * Setup the system - using configuration. */ @Override public void init(ServletConfig config) throws ServletException { try { // setup the database - from config parameter DB or in code as in initDb("jdbc:h2:file:./data", "org.h2.Driver", null, null); initDb(config.getInitParameter("DB")); // the framework provides a dev time admin - init it here if specified in config initManager(config.getInitParameter("ADMIN_PAGE")); // mustache is the built in templating mechanism - it can be configured as such here mustache.setDefaultValue("-"); // optional if(config.getInitParameter("MODE") == "DEV") mustache.disableCaching(); // only for testing // Jago Framework provides a pure POJO ORM - where class can be linked to table by calling getDb().linkClassToTable(Greeting.class, "Greeting", "id", true); // last 3 params are Table name, PrimaryKey and If key is autogenerated // a call to this function - exposes the table as a Rest Service - details to come // exposeRestService("greetings", Greeting.class, "json", new String[]{"lang"}); testORM(); } catch (Exception e) { warn("Exception ", e); } // for Java 7 or earlier - you can register controller - using anonymous class // any url parameters to be extracted need to be specified - 2nd argument // a test string allows you to easily test the controller addController(GET, "/welcome/:lang", "lang=es;name=Jim;", new IController() { @Override public Response execute(Request req) throws Exception { // url params and query params can all be extracted as req.param(name) String greet = "es".equals(req.pathParam("lang")) ? "Hola" : "Hello"; // response is a Template - if name is null - raw text is returned return new TemplResponse(null, greet+ ' '+ req.param("name")); } }); // Java 8 and above can use lambda expressions or function pointers addController(GET, "/welcome1", "", (req) -> { // template can take mustache template - and add data to it as below return new TemplResponse(null, "{{> templates/first.tmpl}}" //"Mustache template {{greet.greeting}}" ).add("greet", new Greeting("en", "Hello!!!!")); }); // Java 8 + - this is the more convenient way of definiting controllers - just a pointer to a function addController(GET, "/welcome2/:lang", "lang=en;name=Jack;", this::showGreeting); } // model classes are just POCO - no annotations public static class Greeting{ public Greeting(){} // default constructor is required on model - if another constructor is specified public Greeting(String lang, String gr){this.lang = lang; this.greeting = gr; this.updateDate = new Date();} public String lang, greeting; public int id; public Date updateDate; } /** * In this test - we insert an object into the DB - retrieve it update it and print it. * Ofcourse - before this can be done - you have to create the table - which can be done on the admin page. */ private void testORM() throws SQLException { Greeting esHola = new Greeting("es", "hola"); getDb().insert(esHola); getDb().insert(new Greeting("en", "Hello")); esHola.greeting = "Hola!"; getDb().update(esHola); Greeting obj2 = getDb().getById(Greeting.class, esHola.id); System.out.println(obj2.greeting); } public Response showGreeting(Request req) throws SQLException{ String lang = ( req.pathParam("lang") == null ? "en" : req.pathParam("lang")); Greeting greet = getDb().readOne(Greeting.class, " lang = ? ", lang); return new TemplResponse("default", "Mustache template {{greet.greeting}}").add("greet", greet); } }
41.866071
140
0.645767
635a667aba803b97aac8fe3ef1591ceedd6decea
1,078
package com.hyty.cordova.mvp.ui.view; import android.content.Context; import android.support.annotation.AttrRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StyleRes; import android.util.AttributeSet; import android.widget.FrameLayout; /** * ================================================================ * 创建时间:2017/10/11 11:50 * 创建人:赵文贇 * 文件描述: * 看淡身边的虚伪,静心宁神做好自己。路那么长,无愧走好每一步。 * ================================================================ */ public class MyFL extends FrameLayout { public MyFL(@NonNull Context context) { super(context); } public MyFL(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public MyFL(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, widthMeasureSpec); } }
28.368421
100
0.639147
e93ceedc9ff6e133b3be34d8624190ef277b8947
1,886
/* * Copyright 2020 HiveMQ and the HiveMQ Community * * 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.hivemq.testcontainer.junit4; import com.hivemq.client.mqtt.datatypes.MqttQos; import com.hivemq.client.mqtt.exceptions.MqttSessionExpiredException; import com.hivemq.client.mqtt.mqtt5.Mqtt5BlockingClient; import com.hivemq.client.mqtt.mqtt5.Mqtt5Client; import org.junit.Test; import java.io.File; import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Yannick Weber */ public class ContainerWithCustomConfigIT { @Test(timeout = 200_000) public void test() { final HiveMQTestContainerRule rule = new HiveMQTestContainerRule("hivemq/hivemq4", "latest") .withHiveMQConfig(new File("src/test/resources/config.xml")); rule.start(); final Mqtt5BlockingClient publisher = Mqtt5Client.builder() .identifier("publisher") .serverPort(rule.getMqttPort()) .buildBlocking(); publisher.connect(); assertThrows(MqttSessionExpiredException.class, () -> { // this should fail since only QoS 0 is allowed by the configuration publisher.publishWith() .topic("test/topic") .qos(MqttQos.EXACTLY_ONCE) .send(); }); rule.stop(); } }
32.517241
100
0.679745
1cfc3703c71c63f2464d7119291759d975eb0f6a
25,360
/* Copyright 2017 Zutubi Pty Ltd * * 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.zutubi.pulse.core.scm.svn; import com.zutubi.pulse.core.scm.api.*; import com.zutubi.pulse.core.scm.patch.api.FileStatus; import com.zutubi.pulse.core.scm.patch.api.WorkingCopyStatus; import com.zutubi.pulse.core.scm.patch.api.WorkingCopyStatusBuilder; import com.zutubi.pulse.core.ui.api.UserInterface; import com.zutubi.util.config.Config; import com.zutubi.util.config.ConfigSupport; import org.tmatesoft.svn.core.*; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory; import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl; import org.tmatesoft.svn.core.internal.wc.DefaultSVNGNUDiffGenerator; import org.tmatesoft.svn.core.internal.wc.admin.SVNAdminAreaFactory; import org.tmatesoft.svn.core.wc.*; import java.io.File; import java.io.OutputStream; import java.util.EnumSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import static com.zutubi.pulse.core.scm.svn.SubversionConstants.*; /** */ public class SubversionWorkingCopy implements WorkingCopy, WorkingCopyStatusBuilder { public static final String PROPERTY_ALLOW_EXTERNALS = "svn.allow.externals"; static { // Initialise SVN library DAVRepositoryFactory.setup(); SVNRepositoryFactoryImpl.setup(); SVNAdminAreaFactory.setUpgradeEnabled(false); } private SVNClientManager getClientManager(WorkingCopyContext context, boolean addAuthenticationManager) { ISVNOptions options = SVNWCUtil.createDefaultOptions(true); SVNClientManager svnClientManager = SVNClientManager.newInstance(options); if (addAuthenticationManager) { svnClientManager = SVNClientManager.newInstance(options, getAuthenticationManager(context, svnClientManager)); } return svnClientManager; } private ISVNAuthenticationManager getAuthenticationManager(WorkingCopyContext context, SVNClientManager defaultClientManager) { ISVNAuthenticationManager authenticationManager; Config config = context.getConfig(); String user = config.getProperty(PROPERTY_USERNAME); if(user == null) { // See if there is a username specified in the working copy URL. try { SVNInfo info = defaultClientManager.getWCClient().doInfo(context.getBase(), null); user = info.getURL().getUserInfo(); } catch (SVNException e) { // Ignore this error, we can proceed. } } if(user == null) { authenticationManager = SVNWCUtil.createDefaultAuthenticationManager(); } else { authenticationManager = SVNWCUtil.createDefaultAuthenticationManager(user, getPassword(context.getUI(), config)); if(config.hasProperty(PROPERTY_KEYFILE)) { String privateKeyFile = config.getProperty(PROPERTY_KEYFILE); String passphrase = config.getProperty(PROPERTY_PASSPHRASE); authenticationManager.setAuthenticationProvider(new SVNSSHAuthenticationProvider(user, privateKeyFile, passphrase)); } } return authenticationManager; } public String getPassword(UserInterface ui, Config config) { String password = config.getProperty(PROPERTY_PASSWORD); if(password == null) { password = ui.passwordPrompt("Subversion password"); if(password == null) { password = ""; } } return password; } public Set<WorkingCopyCapability> getCapabilities() { return EnumSet.allOf(WorkingCopyCapability.class); } public boolean matchesLocation(WorkingCopyContext context, String location) throws ScmException { // We just check that the URL matches SVNURL serverURL; try { serverURL = SVNURL.parseURIEncoded(location); } catch (SVNException e) { // Not the personal-builder's problem return true; } try { SVNClientManager svnClientManager = getClientManager(context, false); SVNInfo info = svnClientManager.getWCClient().doInfo(context.getBase(), null); SVNURL wcUrl = info.getURL(); boolean eq = serverURL.getProtocol().equals(wcUrl.getProtocol()) && serverURL.hasPort() == wcUrl.hasPort() && serverURL.getPort() == wcUrl.getPort() && serverURL.getHost().equals(wcUrl.getHost()) && serverURL.getPath().equals(wcUrl.getPath()); if (eq) { return true; } else { context.getUI().warning("Working copy's repository URL '" + wcUrl + "' does not match Pulse project's repository URL '" + location + "'"); return false; } } catch (SVNException e) { throw convertException(e); } } public Revision getLatestRemoteRevision(WorkingCopyContext context) throws ScmException { SVNWCClient wcClient = getClientManager(context, true).getWCClient(); try { SVNInfo svnInfo = wcClient.doInfo(context.getBase(), SVNRevision.HEAD); return new Revision(svnInfo.getCommittedRevision().getNumber()); } catch (SVNException e) { throw convertException(e); } } public Revision guessLocalRevision(final WorkingCopyContext context) throws ScmException { // Note that there is no guarantee that the working copy is all updated // to a single revision. In this guess we assume the "normal" case, // that the user has updated everything from the base of the working // copy. SVNClientManager clientManager = getClientManager(context, true); GuessRevisionInfoHandler handler; try { SVNWCClient wcClient = clientManager.getWCClient(); SVNInfo info = wcClient.doInfo(context.getBase(), SVNRevision.WORKING); handler = new GuessRevisionInfoHandler(info.getRepositoryRootURL()); SVNStatusClient statusClient = clientManager.getStatusClient(); statusClient.doStatus(context.getBase(), SVNRevision.WORKING, SVNDepth.INFINITY, false, true, false, false, handler, null); } catch (SVNException e) { throw convertException(e); } return new Revision(handler.getRevision()); } public Revision update(WorkingCopyContext context, Revision revision) throws ScmException { SVNClientManager clientManager = getClientManager(context, true); SVNUpdateClient updateClient = clientManager.getUpdateClient(); updateClient.setEventHandler(new UpdateHandler(context.getUI())); try { SVNRevision svnRevision = revision == null ? SVNRevision.HEAD : SVNRevision.parse(revision.getRevisionString()); long rev = updateClient.doUpdate(context.getBase(), svnRevision, SVNDepth.INFINITY, false, false); return new Revision(Long.toString(rev)); } catch (SVNException e) { throw convertException(e); } } public WorkingCopyStatus getLocalStatus(WorkingCopyContext context, String... spec) throws ScmException { File base = context.getBase(); if(spec.length == 1 && spec[0].startsWith(":")) { String changelist = spec[0].substring(1); return getStatus(context, changelist, base); } else { File[] files = pathsToFiles(base, spec); if (files == null) { return getStatus(context, null, base); } else { return getStatus(context, null, files); } } } private WorkingCopyStatus getStatus(WorkingCopyContext context, String changelist, File... files) throws ScmException { SVNClientManager clientManager = getClientManager(context, false); StatusHandler handler = new StatusHandler(context, changelist); try { SVNStatusClient statusClient = clientManager.getStatusClient(); statusClient.setEventHandler(handler); for (File f : files) { statusClient.doStatus(f, SVNRevision.HEAD, SVNDepth.INFINITY, false, true, false, false, handler, null); } WorkingCopyStatus wcs = handler.getStatus(); String description = ""; if (files.length != 1 || files[0] != context.getBase()) { description = "the specified files in "; } if (changelist == null) { description += "the working copy"; } else { description += "the specified changelist"; } wcs.setSpecDescription(description); // Now find out if any changed files have an eol-style getProperties(clientManager, wcs, handler.propertyChangedPaths); return wcs; } catch (SVNException e) { throw convertException(e); } } private void getProperties(SVNClientManager clientManager, WorkingCopyStatus wcs, List<String> propertyChangedPaths) throws SVNException { SVNWCClient wcc = clientManager.getWCClient(); for (FileStatus fs : wcs.getFileStatuses()) { if (fs.getState().preferredPayloadType() != FileStatus.PayloadType.NONE) { SVNPropertyData property = wcc.doGetProperty(new File(wcs.getBase(), fs.getPath()), SVN_PROPERTY_EOL_STYLE, SVNRevision.WORKING, SVNRevision.WORKING); if (property != null) { fs.setProperty(FileStatus.PROPERTY_EOL_STYLE, convertEOLStyle(property.getValue().getString())); } } if (fs.getState() == FileStatus.State.ADDED) { // For new files, check for svn:executable SVNPropertyData property = wcc.doGetProperty(new File(wcs.getBase(), fs.getPath()), SVN_PROPERTY_EXECUTABLE, SVNRevision.WORKING, SVNRevision.WORKING); if (property != null) { fs.setProperty(FileStatus.PROPERTY_EXECUTABLE, "true"); } } } // For items with changed properties, check if the executable property has flipped for (String path : propertyChangedPaths) { FileStatus fs = wcs.getFileStatus(path); SVNPropertyData baseProperty = wcc.doGetProperty(new File(wcs.getBase(), path), SVN_PROPERTY_EXECUTABLE, SVNRevision.BASE, SVNRevision.BASE); SVNPropertyData workingProperty = wcc.doGetProperty(new File(wcs.getBase(), path), SVN_PROPERTY_EXECUTABLE, SVNRevision.WORKING, SVNRevision.WORKING); if (baseProperty == null) { if (workingProperty != null) { // Added svn:executable fs.setProperty(FileStatus.PROPERTY_EXECUTABLE, "true"); } } else { if (workingProperty == null) { // Removed svn:executable fs.setProperty(FileStatus.PROPERTY_EXECUTABLE, "false"); } } } } private String convertEOLStyle(String eol) { if (eol.equals("native")) { return EOLStyle.NATIVE.toString(); } else if (eol.equals("CR")) { return EOLStyle.CARRIAGE_RETURN.toString(); } else if (eol.equals("CRLF")) { return EOLStyle.CARRIAGE_RETURN_LINEFEED.toString(); } else if (eol.equals("LF")) { return EOLStyle.LINEFEED.toString(); } else { return EOLStyle.BINARY.toString(); } } public boolean canDiff(WorkingCopyContext context, String path) throws ScmException { SVNWCClient wcClient = getClientManager(context, false).getWCClient(); try { SVNPropertyData propertyData = wcClient.doGetProperty(new File(context.getBase(), path), SVNProperty.MIME_TYPE, SVNRevision.UNDEFINED, SVNRevision.WORKING); return propertyData == null || !SVNProperty.isBinaryMimeType(propertyData.getValue().getString()); } catch (SVNException e) { throw convertException(e); } } public void diff(WorkingCopyContext context, String path, OutputStream output) throws ScmException { SVNDiffClient diffClient = getClientManager(context, false).getDiffClient(); diffClient.setDiffGenerator(new DefaultSVNGNUDiffGenerator()); File f = new File(context.getBase(), path); try { diffClient.doDiff(f, SVNRevision.BASE, f, SVNRevision.WORKING, SVNDepth.EMPTY, false, output, null); } catch (SVNException e) { throw convertException(e); } } private File[] pathsToFiles(File base, String... spec) throws ScmException { if(spec.length == 0) { return null; } File[] result = new File[spec.length]; for(int i = 0; i < spec.length; i++) { result[i] = new File(base, spec[i]); if(!result[i].exists()) { throw new ScmException("File '" + spec[i] + "' does not exist"); } } return result; } private ScmException convertException(SVNException e) { return new ScmException(e.getMessage(), e); } private FileStatus convertStatus(File base, ConfigSupport configSupport, SVNStatus svnStatus, List<String> propertyChangedPaths) { SVNStatusType contentsStatus = svnStatus.getCombinedNodeAndContentsStatus(); String path = svnStatus.getFile().getPath(); boolean directory = svnStatus.getKind() == SVNNodeKind.DIR; if (path.startsWith(base.getPath())) { path = path.substring(base.getPath().length()); } if (path.startsWith("/") || path.startsWith(File.separator)) { path = path.substring(1); } FileStatus.State fileState; if (contentsStatus == SVNStatusType.STATUS_NORMAL) { // CIB-730: unchanged children of moved directories need to be // marked as added in our status. if(svnStatus.isCopied()) { fileState = FileStatus.State.ADDED; } else { fileState = FileStatus.State.UNCHANGED; } } else if (contentsStatus == SVNStatusType.STATUS_ADDED) { fileState = FileStatus.State.ADDED; } else if (contentsStatus == SVNStatusType.STATUS_CONFLICTED) { fileState = FileStatus.State.UNRESOLVED; } else if (contentsStatus == SVNStatusType.STATUS_DELETED) { fileState = FileStatus.State.DELETED; } else if (contentsStatus == SVNStatusType.STATUS_EXTERNAL) { if(configSupport.getBooleanProperty(PROPERTY_ALLOW_EXTERNALS, false)) { fileState = FileStatus.State.IGNORED; } else { fileState = FileStatus.State.UNSUPPORTED; } } else if (contentsStatus == SVNStatusType.STATUS_INCOMPLETE) { fileState = FileStatus.State.INCOMPLETE; } else if (contentsStatus == SVNStatusType.MERGED) { fileState = FileStatus.State.MERGED; } else if (contentsStatus == SVNStatusType.STATUS_MISSING) { fileState = FileStatus.State.MISSING; } else if (contentsStatus == SVNStatusType.STATUS_MODIFIED) { fileState = FileStatus.State.MODIFIED; } else if (contentsStatus == SVNStatusType.STATUS_OBSTRUCTED) { fileState = FileStatus.State.OBSTRUCTED; } else if (contentsStatus == SVNStatusType.STATUS_REPLACED) { fileState = FileStatus.State.REPLACED; } else { fileState = FileStatus.State.UNCHANGED; } SVNStatusType propertiesStatus = svnStatus.getPropertiesStatus(); if (propertiesStatus != SVNStatusType.STATUS_NONE && propertiesStatus != SVNStatusType.UNCHANGED && propertiesStatus != SVNStatusType.STATUS_NORMAL) { // if we record a property change path, we MUST have an interesting file // status to ensure that it is recorded. if (!fileState.isInteresting()) { fileState = FileStatus.State.METADATA_MODIFIED; } propertyChangedPaths.add(path); } return new FileStatus(path, fileState, directory); } private class StatusHandler implements ISVNEventHandler, ISVNStatusHandler { private WorkingCopyContext context; private String changelist; private ConfigSupport configSupport; private WorkingCopyStatus status; private List<String> propertyChangedPaths = new LinkedList<String>(); public StatusHandler(WorkingCopyContext context, String changelist) { this.context = context; this.changelist = changelist; configSupport = new ConfigSupport(context.getConfig()); status = new WorkingCopyStatus(context.getBase()); } public void handleEvent(SVNEvent event, double progress) { SVNEventAction action = event.getAction(); if (action == SVNEventAction.STATUS_COMPLETED) { context.getUI().status("Repository revision: " + event.getRevision()); } } public void checkCancelled() throws SVNCancelException { } public void handleStatus(SVNStatus svnStatus) { FileStatus fs = convertStatus(context.getBase(), configSupport, svnStatus, propertyChangedPaths); if (fs.isInteresting() && (changelist == null || changelist.equals(svnStatus.getChangelistName()))) { context.getUI().status(fs.toString()); status.addFileStatus(fs); } } public WorkingCopyStatus getStatus() { return status; } } private class UpdateHandler implements ISVNEventHandler { private UserInterface ui; private UpdateHandler(UserInterface ui) { this.ui = ui; } public void handleEvent(SVNEvent event, double progress) { SVNEventAction action = event.getAction(); String pathChangeType = " "; if (action == SVNEventAction.UPDATE_ADD) { pathChangeType = "A"; } else if (action == SVNEventAction.UPDATE_DELETE) { pathChangeType = "D"; } else if (action == SVNEventAction.UPDATE_UPDATE) { // Find out in detail what state the item is in (after having been // updated). SVNStatusType contentsStatus = event.getContentsStatus(); if (contentsStatus == SVNStatusType.CHANGED) { pathChangeType = "U"; } else if (contentsStatus == SVNStatusType.CONFLICTED) { pathChangeType = "C"; } else if (contentsStatus == SVNStatusType.MERGED) { pathChangeType = "G"; } } else if (action == SVNEventAction.UPDATE_EXTERNAL) { ui.status("Fetching external item into '" + event.getFile().getAbsolutePath() + "'"); ui.status("External at revision " + event.getRevision()); return; } else if (action == SVNEventAction.UPDATE_COMPLETED) { /* * Updating the working copy is completed. Prints out the revision. */ ui.status("Updated to revision " + event.getRevision()); return; } else if (action == SVNEventAction.ADD) { ui.status("A " + event.getFile().getPath()); return; } else if (action == SVNEventAction.DELETE) { ui.status("D " + event.getFile().getPath()); return; } else if (action == SVNEventAction.LOCKED) { ui.status("L " + event.getFile().getPath()); return; } else if (action == SVNEventAction.LOCK_FAILED) { ui.status("Failed to lock: " + event.getFile().getPath()); return; } // For added, delete or updated files, check the properties // status. SVNStatusType propertiesStatus = event.getPropertiesStatus(); String propertiesChangeType = " "; if (propertiesStatus == SVNStatusType.CHANGED) { propertiesChangeType = "U"; } else if (propertiesStatus == SVNStatusType.CONFLICTED) { propertiesChangeType = "C"; } else if (propertiesStatus == SVNStatusType.MERGED) { propertiesChangeType = "G"; } // Also get the loack status String lockLabel = " "; SVNStatusType lockType = event.getLockStatus(); if (lockType == SVNStatusType.LOCK_UNLOCKED) { lockLabel = "B"; } String message = pathChangeType + propertiesChangeType + lockLabel + " " + event.getFile().getPath(); if(message.trim().length() > 0) { ui.status(message); } } /* * Should be implemented to check if the current operation is cancelled. If * it is, this method should throw an SVNCancelException. */ public void checkCancelled() throws SVNCancelException { } } /** * A status handler that extracts the highest revision from all entries it * sees. */ private static class GuessRevisionInfoHandler implements ISVNStatusHandler { private long highestCommittedRevision = 0; private String rootURL; public GuessRevisionInfoHandler(SVNURL rootURL) { this.rootURL = rootURL.toDecodedString(); } public long getRevision() { return highestCommittedRevision; } public void handleStatus(SVNStatus svnStatus) throws SVNException { SVNURL url = svnStatus.getURL(); if (url != null && url.toDecodedString().startsWith(rootURL)) { long committed = svnStatus.getCommittedRevision().getNumber(); if (committed > highestCommittedRevision) { highestCommittedRevision = committed; } } } } }
35.418994
169
0.563565
10525c00fd8cb43e027c33791b3bba8e57c51c94
13,923
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ package org.netbeans.modules.subversion.remote.ui.search; import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.swing.JPanel; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionListener; import org.netbeans.modules.subversion.remote.RepositoryFile; import org.netbeans.modules.subversion.remote.Subversion; import org.netbeans.modules.subversion.remote.SvnModuleConfig; import org.netbeans.modules.subversion.remote.api.ISVNLogMessage; import org.netbeans.modules.subversion.remote.api.SVNClientException; import org.netbeans.modules.subversion.remote.api.SVNRevision; import org.netbeans.modules.subversion.remote.api.SVNUrl; import org.netbeans.modules.subversion.remote.client.SvnClient; import org.netbeans.modules.subversion.remote.client.SvnClientExceptionHandler; import org.netbeans.modules.subversion.remote.client.SvnProgressSupport; import org.netbeans.modules.subversion.remote.util.Context; import org.netbeans.modules.subversion.remote.util.SvnUtils; import org.netbeans.modules.versioning.core.api.VCSFileProxy; import org.netbeans.modules.versioning.util.NoContentPanel; import org.openide.util.NbBundle.Messages; import org.openide.util.RequestProcessor; import org.openide.util.Task; import org.openide.util.TaskListener; /** * Handles the UI for revision search. * * */ public class SvnSearch implements ActionListener, DocumentListener { public final static String SEACRH_HELP_ID_CHECKOUT = "org.netbeans.modules.subversion.ui.search.checkout"; //NOI18N public final static String SEACRH_HELP_ID_SWITCH = "org.netbeans.modules.subversion.ui.search.switch"; //NOI18N public final static String SEACRH_HELP_ID_COPY = "org.netbeans.modules.subversion.ui.search.copy"; //NOI18N public final static String SEACRH_HELP_ID_URL_PATTERN = "org.netbeans.modules.subversion.ui.search.urlpattern"; //NOI18N public final static String SEACRH_HELP_ID_MERGE = "org.netbeans.modules.subversion.ui.search.merge"; //NOI18N public final static String SEACRH_HELP_ID_REVERT = "org.netbeans.modules.subversion.ui.search.revert"; //NOI18N public final static String SEARCH_HELP_ID_UPDATE = "org.netbeans.modules.subversion.ui.search.update"; //NOI18N public final static String SEARCH_HELP_ID_SELECT_DIFF_TREE = "org.netbeans.modules.subversion.ui.search.selectdifftree"; //NOI18N private static final String DATE_FROM = "svnSearch.dateFrom"; // NOI18N private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); // NOI18N private final SvnSearchPanel panel; private final RepositoryFile[] repositoryFiles; private final SvnSearchView searchView; private SvnProgressSupport support; private final NoContentPanel noContentPanel; public SvnSearch(RepositoryFile ... repositoryFile) { this.repositoryFiles = repositoryFile; panel = new SvnSearchPanel(); panel.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(SvnSearch.class, "ACSN_SummaryView_Name")); // NOI18N panel.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(SvnSearch.class, "ACSD_SummaryView_Desc")); // NOI18N panel.listButton.addActionListener(this); panel.dateFromTextField.getDocument().addDocumentListener(this); String date = DATE_FORMAT.format(new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 7)); panel.dateFromTextField.setText(SvnModuleConfig.getDefault(repositoryFile[0].getFileSystem()).getPreferences().get(DATE_FROM, date)); searchView = new SvnSearchView(); panel.listPanel.setLayout(new BorderLayout()); panel.listPanel.add(searchView.getComponent()); noContentPanel = new NoContentPanel(); panel.noContentPanel.setLayout(new BorderLayout()); panel.noContentPanel.add(noContentPanel); noContentPanel.setLabel(org.openide.util.NbBundle.getMessage(SvnSearch.class, "LBL_NoResults_SearchNotPerformed")); // NOI18N panel.listPanel.setVisible(false); panel.noContentPanel.setVisible(true); } /** * Cancels all running tasks */ public void cancel() { if(support != null) { support.cancel(); } } @Messages({ "# {0} - resource URL", "MSG_SvnSearch.error.pathNotFound=Resource does not exist: {0}" }) private void listLogEntries() { noContentPanel.setLabel(org.openide.util.NbBundle.getMessage(SvnSearch.class, "LBL_NoResults_SearchInProgress")); // NOI18N panel.listPanel.setVisible(false); panel.noContentPanel.setVisible(true); final SVNRevision revisionFrom = getRevisionFrom(); final SVNUrl repositoryUrl = this.repositoryFiles[0].getRepositoryUrl(); if(revisionFrom instanceof SVNRevision.DateSpec) { SvnModuleConfig.getDefault(repositoryFiles[0].getFileSystem()).getPreferences().put(DATE_FROM, panel.dateFromTextField.getText().trim()); } final String[] paths = new String[repositoryFiles.length]; for(int i = 0; i < repositoryFiles.length; i++) { String[] segments = repositoryFiles[i].getPathSegments(); StringBuilder sb = new StringBuilder(); for(String segment : segments) { sb.append(segment); sb.append('/'); } paths[i] = sb.toString(); } RequestProcessor rp = Subversion.getInstance().getRequestProcessor(); support = new SvnProgressSupport(repositoryFiles[0].getFileSystem()) { @Override protected void perform() { ISVNLogMessage[] messageArray= null; try { SvnClient client = Subversion.getInstance().getClient(new Context(VCSFileProxy.createFileProxy(repositoryFiles[0].getFileSystem().getRoot())), repositoryUrl, this); messageArray = SvnUtils.getLogMessages(client, repositoryUrl, paths, null, SVNRevision.HEAD, revisionFrom, false, false, 0); } catch (SVNClientException ex) { if (SvnClientExceptionHandler.isFileNotFoundInRevision(ex.getMessage())) { for (int i=0; i < paths.length; ++i) { String path = paths[i]; while (path.endsWith("/")) { //NOI18N path = path.substring(0, path.length() - 1); } if (ex.getMessage().contains(path)) { noContentPanel.setLabel(Bundle.MSG_SvnSearch_error_pathNotFound(paths[i])); SvnClientExceptionHandler.notifyException(null, ex, false, false); return; } } } SvnClientExceptionHandler.notifyException(null, ex, true, true); } if(isCanceled()) { return; } if(messageArray == null) { return; } final List<ISVNLogMessage> messages = new ArrayList<>(); if(revisionFrom instanceof SVNRevision.DateSpec) { long timeFrom = ((SVNRevision.DateSpec) revisionFrom).getDate().getTime(); for(ISVNLogMessage lm : messageArray) { if(lm.getDate().getTime() >= timeFrom) { messages.add(lm); } } } else { long revision = ((SVNRevision.Number) revisionFrom).getNumber(); for(ISVNLogMessage lm : messageArray) { if(lm.getRevision().getNumber() >= revision) { messages.add(lm); } } } if(isCanceled()) { return; } EventQueue.invokeLater(new Runnable() { @Override public void run() { panel.listPanel.setVisible(true); panel.noContentPanel.setVisible(false); searchView.setResults(messages.toArray(new ISVNLogMessage[messages.size()])); } }); } }; support.start(rp, repositoryUrl, org.openide.util.NbBundle.getMessage(SvnSearch.class, "LBL_Search_Progress")).addTaskListener( // NOI18N new TaskListener(){ @Override public void taskFinished(Task task) { support = null; } } ); } public JPanel getSearchPanel() { return panel; } public SVNRevision getSelectedRevision() { return searchView.getSelectedValue(); } public void addListSelectionListener(ListSelectionListener listener) { searchView.addListSelectionListener(listener); } public void removeListSelectionListener(ListSelectionListener listener) { searchView.removeListSelectionListener(listener); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==panel.listButton) { listLogEntries(); } } private SVNRevision getRevisionFrom() { String value = panel.dateFromTextField.getText().trim(); if(value.equals("")) { //NOI18N return new SVNRevision.Number(1); } try { return new SVNRevision.DateSpec(DATE_FORMAT.parse(value)); } catch (ParseException ex) { return null; // should not happen } } @Override public void insertUpdate(DocumentEvent e) { validateUserInput(); } @Override public void removeUpdate(DocumentEvent e) { validateUserInput(); } @Override public void changedUpdate(DocumentEvent e) { validateUserInput(); } private void validateUserInput() { boolean isValid = false; String dateString = panel.dateFromTextField.getText(); if(dateString.equals("")) { // NOI18N isValid = true; } else { try { DATE_FORMAT.parse(panel.dateFromTextField.getText()); isValid = true; } catch (ParseException ex) { // ignore } } panel.listButton.setEnabled(isValid); } }
45.351792
209
0.618617
2edb297f7a0b715390d7c2d597c071fa5bb2025f
3,068
package org.neo4j.examples.imdb.web; import org.neo4j.examples.imdb.domain.Actor; import org.neo4j.examples.imdb.domain.ImdbService; import org.neo4j.examples.imdb.domain.Movie; import org.neo4j.examples.imdb.domain.Role; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import javax.servlet.ServletException; import java.util.*; public class ActorFindControllerDelegate implements FindControllerDelegate { @Autowired private ImdbService imdbService; public String getFieldName() { return "name"; } @Transactional public void getModel(final Object command, final Map<String, Object> model) throws ServletException { final String name = ((ActorForm) command).getName(); final Actor actor = imdbService.getActor(name); populateModel(model, actor); } private void populateModel(final Map<String, Object> model, final Actor actor) { if (actor == null) { model.put("actorName", "No actor found"); model.put("kevinBaconNumber", ""); model.put("movieTitles", Collections.emptyList()); } else { model.put("actorName", actor.getName()); final List<?> baconPathList = imdbService.getBaconPath(actor); model.put("kevinBaconNumber", baconPathList.size() / 2); final Collection<MovieInfo> movieInfo = new TreeSet<MovieInfo>(); for (Movie movie : actor.getMovies()) { movieInfo.add(new MovieInfo(movie, actor.getRole(movie))); } model.put("movieInfo", movieInfo); final List<String> baconPath = new LinkedList<String>(); for (Object actorOrMovie : baconPathList) { if (actorOrMovie instanceof Actor) { baconPath.add(((Actor) actorOrMovie).getName()); } else if (actorOrMovie instanceof Movie) { baconPath.add(((Movie) actorOrMovie).getTitle()); } } model.put("baconPath", baconPath); } } public static final class MovieInfo implements Comparable<MovieInfo> { private String title; private String role; MovieInfo(final Movie movie, final Role role) { setTitle(movie.getTitle()); if (role == null || role.getName() == null) { setRole("(unknown)"); } else { setRole(role.getName()); } } public final void setTitle(final String title) { this.title = title; } public String getTitle() { return title; } public final void setRole(final String role) { this.role = role; } public String getRole() { return role; } public int compareTo(final MovieInfo otherMovieInfo) { return getTitle().compareTo(otherMovieInfo.getTitle()); } } }
34.088889
79
0.596154
9c077fe499fb9a1b2871f5103e52456ca78429e4
250
package org.mockito.exceptions.misusing; import org.mockito.exceptions.base.MockitoException; public class CannotVerifyStubOnlyMock extends MockitoException { public CannotVerifyStubOnlyMock(String message) { super(message); } }
19.230769
64
0.776
e80733b3a84886bea33a81f304b1b9138a637d64
1,624
package io.github.sruby.concurrent.geek.completionservice; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; /** * @description: CompletionService test * @author: sruby * @create: 2020-06-16 18:01 */ @Slf4j public class CompletionServiceTest { @Test public void test() throws InterruptedException, ExecutionException { Executor executor = Executors.newFixedThreadPool(3); CompletionService<String> completionService = new ExecutorCompletionService(executor); List<Future<String>> futureList = new ArrayList<>(3); Future<String> query1 = completionService.submit(() -> { log.debug("query1"); return "query1"; }); Future<String> query2 = completionService.submit(() -> { log.debug("query2"); return "query2"; }); Future<String> query3 = completionService.submit(() -> { log.debug("query3"); return "query3"; }); futureList.add(query1); futureList.add(query2); futureList.add(query3); try { for (int i = 0; i < 3; i++){ String result = completionService.take().get(); log.debug("result:{}",result); if (StringUtils.isNotBlank(result)){ break; } } } finally { for (Future future:futureList){ future.cancel(true); } } } }
29.527273
94
0.578202
8dd8f6e2f1c6fcd44a073298997683172cbd5fb6
1,198
package appium; import io.appium.java_client.AppiumDriver; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.remote.MobileCapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import java.io.File; import java.net.MalformedURLException; import java.net.URL; public class BaseAndroid { private static AppiumDriver driver; public static AppiumDriver getDriver() { File srcDir = new File("src"); File app = new File(srcDir, "/test/resources/android/ApiDemos-debug.apk"); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Automation"); capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); capabilities.setCapability("appPackage", "io.appium.android.apis"); capabilities.setCapability("appActivity", "io.appium.android.apis.ApiDemos"); try { driver = new AndroidDriver( new URL("http://127.0.0.1:4723/wd/hub"), capabilities); } catch (MalformedURLException e) { e.printStackTrace(); } return driver; } }
31.526316
85
0.702003
29206ff72e9cf50436fd20b43f529f0f85786d78
10,644
package persistence; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import exceptions.ExceptionSearchId; import model.dao.OrderManager; import model.dao.OwnerManager; import model.dao.ProductManager; import model.dao.UserManager; import model.entity.AssignOrderToUser; import model.entity.AssignProductToOrder; import model.entity.AssignProductToOwner; import model.entity.Order; import model.entity.Owner; import model.entity.State; import model.entity.User; public class FileWrite { public void fileWriteAssignProductToOwnerOwner(ArrayList<AssignProductToOwner> ownerList) throws IOException{ File file=new File("src/data/AssignProductToOwner.json"); PrintWriter printWriter = new PrintWriter(new FileOutputStream(file, false)); JsonArray assignationsOwnerProduct = new JsonArray(); for (AssignProductToOwner owner : ownerList) { JsonObject assignProductToOrder = new JsonObject(); JsonObject ownerObject = new JsonObject(); ownerObject.addProperty(ConstantPersistence.OWNER_NAME, owner.getOwner().getName()); ownerObject.addProperty(ConstantPersistence.OWNER_PASSWORD, owner.getOwner().getPassword()); ownerObject.addProperty(ConstantPersistence.OWNER_IMAGE, owner.getOwner().getUrl()); JsonObject productsObjetc = new JsonObject(); productsObjetc.addProperty(ConstantPersistence.PRODUCT_NAME, owner.getProduct().getName()); productsObjetc.addProperty(ConstantPersistence.PRODUCT_DESCRIPTION, owner.getProduct().getDescription()); productsObjetc.addProperty(ConstantPersistence.PRODUCT_PRICE, owner.getProduct().getPrice()); productsObjetc.addProperty(ConstantPersistence.PRODUCT_IMAGE, owner.getProduct().getImg()); productsObjetc.addProperty(ConstantPersistence.PRODUCT_STATE, String.valueOf(owner.getProduct().getState())); assignProductToOrder.add(ConstantPersistence.OWNER, ownerObject); assignProductToOrder.add(ConstantPersistence.PRODUCT, productsObjetc); assignationsOwnerProduct.add(assignProductToOrder); } BufferedWriter bufferedWriter = new BufferedWriter(printWriter); bufferedWriter.write(assignationsOwnerProduct.toString()); bufferedWriter.close(); } public void fileWriteAssignProductToOrder(ArrayList<AssignProductToOrder> assignProductToOrderList) throws IOException{ // File fileFolder = new File(System.getProperty("user.dir")+"\\"+"Report"); File file=new File("src/data/assignProductToOrder.json"); // fileFolder.mkdirs(); PrintWriter printWriter = new PrintWriter(new FileOutputStream(file, true)); JsonArray restaurantObject = new JsonArray(); for (AssignProductToOrder assignProductToOrder : assignProductToOrderList) { JsonObject assignProductToOrderWriter= new JsonObject(); JsonObject orderObject = new JsonObject(); orderObject.addProperty(ConstantPersistence.ID_ORDER, String.valueOf(assignProductToOrder.getOrder().getId())); orderObject.addProperty(ConstantPersistence.ORDER_STATE, String.valueOf(assignProductToOrder.getOrder().getState())); orderObject.addProperty(ConstantPersistence.ORDER_DIRECTION, assignProductToOrder.getOrder().getDirection()); JsonObject productsObjetc = new JsonObject(); orderObject.add(ConstantPersistence.PRODUCT, productsObjetc); productsObjetc.addProperty(ConstantPersistence.PRODUCT_NAME, assignProductToOrder.getProduct().getName()); productsObjetc.addProperty(ConstantPersistence.PRODUCT_DESCRIPTION, assignProductToOrder.getProduct().getDescription()); productsObjetc.addProperty(ConstantPersistence.PRODUCT_PRICE, assignProductToOrder.getProduct().getPrice()); productsObjetc.addProperty(ConstantPersistence.PRODUCT_IMAGE, assignProductToOrder.getProduct().getImg()); productsObjetc.addProperty(ConstantPersistence.PRODUCT_STATE, String.valueOf(assignProductToOrder.getProduct().getState())); assignProductToOrderWriter.add(ConstantPersistence.PRODUCT, productsObjetc); assignProductToOrderWriter.add(ConstantPersistence.ORDER, orderObject); restaurantObject.add(assignProductToOrderWriter); } BufferedWriter bufferedWriter = new BufferedWriter(printWriter); bufferedWriter.write(restaurantObject.toString()); bufferedWriter.close(); } public void fileWritetAssignOrderToUser(ArrayList<AssignOrderToUser> assignOrderToUserList) throws IOException{ // File fileFolder = new File(System.getProperty("user.dir")+"\\"+"Report"); File file=new File("src/data/AssignOrderToUser.json"); // fileFolder.mkdirs(); System.out.println(file); PrintWriter printWriter = new PrintWriter(new FileOutputStream(file, false)); JsonArray assignOrderToUserListWriter = new JsonArray(); for (AssignOrderToUser assignOrderToUser : assignOrderToUserList) { JsonObject assignOrderToUserWriter = new JsonObject(); JsonObject userObject = new JsonObject(); userObject.addProperty(ConstantPersistence.USER_NAME, assignOrderToUser.getUser().getName()); userObject.addProperty(ConstantPersistence.USER_PASSWORD, assignOrderToUser.getUser().getPassword()); userObject.addProperty(ConstantPersistence.USER_STATE, assignOrderToUser.getUser().isState()); JsonObject orderObjetc = new JsonObject(); orderObjetc.addProperty(ConstantPersistence.ID_ORDER, String.valueOf(assignOrderToUser.getOrder().getId())); orderObjetc.addProperty(ConstantPersistence.ORDER_STATE, String.valueOf(assignOrderToUser.getOrder().getState())); orderObjetc.addProperty(ConstantPersistence.ORDER_DIRECTION, assignOrderToUser.getOrder().getDirection()); assignOrderToUserWriter.add(ConstantPersistence.USER, userObject); assignOrderToUserWriter.add(ConstantPersistence.ORDER,orderObjetc); assignOrderToUserListWriter.add(assignOrderToUserWriter); } BufferedWriter bufferedWriter = new BufferedWriter(printWriter); bufferedWriter.write(assignOrderToUserListWriter.toString()); bufferedWriter.close(); } public void saveOwner(ArrayList<Owner> ownerList) throws IOException { File file=new File("src/data/owners.json"); PrintWriter printWriter = new PrintWriter(new FileOutputStream(file, false)); BufferedWriter bufferedWriter = new BufferedWriter(printWriter); JsonArray ownerWriter = new JsonArray(); for (Owner owner : ownerList) { Gson gson = new Gson(); JsonObject ownerObject = new JsonObject(); ownerObject.add(ConstantPersistence.OWNER, gson.toJsonTree(owner)); ownerWriter.add(ownerObject); } bufferedWriter.write(ownerWriter.toString()); bufferedWriter.close(); } public void saveUser(ArrayList<User> userList) throws IOException { File file=new File("src/data/users.json"); PrintWriter printWriter = new PrintWriter(new FileOutputStream(file, false)); JsonArray users = new JsonArray(); for (User user : userList) { JsonObject userObject = new JsonObject(); Gson gson = new Gson(); JsonObject userWriter = new JsonObject(); userWriter.add(ConstantPersistence.USER, gson.toJsonTree(user)); users.add(userWriter); } BufferedWriter bufferedWriter = new BufferedWriter(printWriter); bufferedWriter.write(users.toString()); bufferedWriter.close(); } public static void main(String[] args) { OwnerManager ownerManager = new OwnerManager(); OrderManager orderManager = new OrderManager(); UserManager userManager = new UserManager(); ProductManager productManager = new ProductManager(); ownerManager .addOwner(OwnerManager.createOwner("Mc Donalds", "s", "src/image/mcDonalds.jpg")); ownerManager.addOwner(OwnerManager.createOwner("El Pirata", "z", "src/image/ElPirata.jpg")); ownerManager.addOwner(OwnerManager.createOwner("Al Toque", "z", "src/image/AlToque.png")); // userManager.addUser(UserManager.createUser("Juan", "X", null, true)); // userManager.addAssignOrderToUser(userManager.createAssignOrder(new Order(01, " ghh"), new User("love", "13", null, true))); productManager.addProduct(ProductManager.createProduct("Hamburguesa Dijon", "deliciosa", 3000, State.RECEIVED, "src/image/HamburguerProduct.png")); productManager.addProduct( ProductManager.createProduct("Gaseosa Manzana", "deliciosa", 3000, State.RECEIVED, "src/image/BebidaProducto.png")); productManager.addProduct( ProductManager.createProduct("Gaseosa Manzana", "deliciosa", 3000, State.RECEIVED, "src/image/BebidaProducto.png")); productManager.addProduct(ProductManager.createProduct("Hamburguesa Dijon", "deliciosa", 3000, State.RECEIVED, "src/image/HamburguerProduct.png")); try { ownerManager.addAssignProductoToOwner(ownerManager .createAssignProductoToOwner(productManager.searchProductById(0), ownerManager.searchOwner(1))); ownerManager.addAssignProductoToOwner(ownerManager .createAssignProductoToOwner(productManager.searchProductById(1), ownerManager.searchOwner(1))); ownerManager.addAssignProductoToOwner(ownerManager .createAssignProductoToOwner(productManager.searchProductById(2), ownerManager.searchOwner(1))); ownerManager.addAssignProductoToOwner(ownerManager .createAssignProductoToOwner(productManager.searchProductById(3), ownerManager.searchOwner(1))); } catch (ExceptionSearchId e) { e.printStackTrace(); } orderManager.addAssignProductoToOrder(new AssignProductToOrder(new Order(01, "fvhgh"), ProductManager.createProduct("Gaseosa Manzana", "deliciosa", 3000, State.RECEIVED, "src/image/BebidaProducto.png"))); orderManager.addAssignProductoToOrder(new AssignProductToOrder(new Order(01, "fvhgh"), ProductManager.createProduct("Gaseosa Manzana", "deliciosa", 3000, State.RECEIVED, "src/image/BebidaProducto.png"))); orderManager.addAssignProductoToOrder(new AssignProductToOrder(new Order(01, "fvhgh"), ProductManager.createProduct("Gaseosa Manzana", "deliciosa", 3000, State.RECEIVED, "src/image/BebidaProducto.png"))); FileWrite fileWrite = new FileWrite(); try { fileWrite.fileWritetAssignOrderToUser(userManager.getAssingOrderToUser()); // fileWrite.fileWriteAssignProductToOrder(orderManager.getProductsOfTheOrder()); fileWrite.fileWriteAssignProductToOwnerOwner(ownerManager.getAssignProductList()); // fileWrite.saveUser(userManager.getUsers()); fileWrite.saveOwner(ownerManager.getOwnerList()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
55.150259
207
0.780158
11df1729fa9f8ff045a691119f73f9e9d6b89057
1,056
package com.woshidaniu.socket.code; import java.nio.charset.Charset; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderAdapter; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.textline.LineDelimiter; public class DataEncoder extends ProtocolEncoderAdapter{ Charset charset = null; public DataEncoder(String encoding){ charset = Charset.forName(encoding); } @Override public void dispose(IoSession session) throws Exception { } public void encode(IoSession session, Object message, ProtocolEncoderOutput output) throws Exception { IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true); buf.putString(message.toString(), charset.newEncoder()); buf.putString(LineDelimiter.DEFAULT.getValue(), charset.newEncoder()); buf.flip(); output.write(buf); } }
29.333333
88
0.689394
308950a257f73cf8bc54a436be9f9f97fda897bb
16,914
package com.apakor; import java.util.Calendar; import android.app.Activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.app.TimePickerDialog; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.provider.Settings; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TimePicker; import android.widget.Toast; public class LapAwalBencanaAct_1 extends Activity implements LocationListener, OnClickListener{ public static final String myShared = "mySharedPreferences"; public static final int mode = Activity.MODE_PRIVATE; private SharedPreferences mySharedPreferences; private static final int DIALOG1 = 1; LocationManager locationManager; String locationProvider; Criteria criteria; Location currentLocation; Button setWaktu, setTanggal, setPosisi, lanjut, batal; Spinner spJenisKejadian; EditText edtxtTimBPBD, edtxtTimDinsos, edtxtTimDinkes, edtxtTimPU, edtxtIDBencana, edtxtIDPetugas; String jumlahTimBPBD, jumlahTimDinkes, jumlahTimDinsos, jumlahTimPU, jenisKejadianBencana, TanggalBencana, WaktuBencana, LatitudeBencana, LongitudeBencana, idBencana, idPetugas, tanggal = "", waktu = "", latitude = "", longitude = ""; Intent i; ImageView imgStatusTanggal, imgStatusWaktu, imgStatusLokasi; ProgressDialog progDialog; boolean flag = false; java.text.DateFormat formatDateTime = java.text.DateFormat.getDateTimeInstance(); Calendar dateAndTime = Calendar.getInstance(); DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() { //Set value datepicker public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // TODO Auto-generated method stub dateAndTime.set(Calendar.YEAR, year); dateAndTime.set(Calendar.MONTH, monthOfYear); dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth); tanggal = String.valueOf(year)+"-"+ String.valueOf(monthOfYear+1)+"-"+ String.valueOf(dayOfMonth) ; Toast.makeText(getBaseContext(), tanggal+ " berhasil diset", Toast.LENGTH_SHORT).show(); setStatusTanggal(); } }; TimePickerDialog.OnTimeSetListener time = new TimePickerDialog.OnTimeSetListener() { //Set value timepicker public void onTimeSet(TimePicker view, int hourOfDay, int minute) { // TODO Auto-generated method stub dateAndTime.set(Calendar.HOUR_OF_DAY, hourOfDay); dateAndTime.set(Calendar.MINUTE, minute); waktu = String.format("%02d:%02d", hourOfDay, minute); Toast.makeText(getBaseContext(), waktu + " berhasil diset", Toast.LENGTH_SHORT).show(); setStatusWaktu(); } }; private void setDate(){ //Method buat datepicker new DatePickerDialog(LapAwalBencanaAct_1.this, date, dateAndTime.get(Calendar.YEAR), dateAndTime.get(Calendar.MONTH), dateAndTime.get(Calendar.DAY_OF_MONTH)).show(); } private void setTime(){ //Method buat timepicker new TimePickerDialog(LapAwalBencanaAct_1.this, time, dateAndTime.get(Calendar.HOUR_OF_DAY), dateAndTime.get(Calendar.MINUTE), true).show(); } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_lap_awal_bencana_1); getActionBar().setTitle("Laporan Bencana"); initiateElement(); setUpGeoCurrentLocation(); loadPreferences(); } private void initiateElement() { setWaktu = (Button) findViewById(R.id.buttonSetWaktuBencana); setWaktu.setOnClickListener(this); setTanggal = (Button) findViewById(R.id.buttonSetTanggaBencana); setTanggal.setOnClickListener(this); setPosisi = (Button) findViewById(R.id.buttonSetPosisi); setPosisi.setOnClickListener(this); lanjut = (Button) findViewById(R.id.buttonLanjut); lanjut.setOnClickListener(this); batal = (Button) findViewById(R.id.buttonBatal); batal.setOnClickListener(this); spJenisKejadian = (Spinner) findViewById(R.id.spinnerJenisKejadian); edtxtTimBPBD = (EditText) findViewById(R.id.editTextTimBPBD); edtxtTimDinsos = (EditText) findViewById(R.id.editTextTimDinsos); edtxtTimDinkes = (EditText) findViewById(R.id.editTextTimDinkes); edtxtTimPU = (EditText) findViewById(R.id.editTextTimPU); edtxtIDBencana = (EditText)findViewById(R.id.editTextIDBencana); edtxtIDPetugas = (EditText)findViewById(R.id.editTextIDPetugas); imgStatusLokasi = (ImageView)findViewById(R.id.imageViewStatusLokasi); imgStatusTanggal = (ImageView)findViewById(R.id.imageViewStatusTanggal); imgStatusWaktu = (ImageView)findViewById(R.id.imageViewStatusWaktu); progDialog = new ProgressDialog(this); } private void loadPreferences() { // TODO Auto-generated method stub mySharedPreferences = getApplication().getSharedPreferences(myShared, mode); idPetugas = mySharedPreferences.getString("IDPetugas", ""); idBencana = mySharedPreferences.getString("IDBencana", ""); jumlahTimBPBD = mySharedPreferences.getString("JumlahTimBPBD", ""); jumlahTimDinkes = mySharedPreferences.getString("JumlahTimDinkes", ""); jumlahTimDinsos = mySharedPreferences.getString("JumlahTimDinsos", ""); jumlahTimPU = mySharedPreferences.getString("JumlahTimPU", ""); jenisKejadianBencana = mySharedPreferences.getString("JenisKejadianBencana", ""); tanggal= mySharedPreferences.getString("TanggalBencana", ""); waktu = mySharedPreferences.getString("WaktuBencana", ""); latitude = mySharedPreferences.getString("LatitudeBencana", ""); longitude = mySharedPreferences.getString("LongitudeBencana", ""); setElement(); } private void setElement() { edtxtIDPetugas.setText(idPetugas); edtxtIDBencana.setText(idBencana); edtxtTimBPBD.setText(jumlahTimBPBD); edtxtTimDinkes.setText(jumlahTimDinkes); edtxtTimDinsos.setText(jumlahTimDinsos); edtxtTimPU.setText(jumlahTimPU); if(!jenisKejadianBencana.equalsIgnoreCase("")) { ArrayAdapter myAdap = (ArrayAdapter) spJenisKejadian.getAdapter(); //cast to an ArrayAdapter int spinnerPosition = myAdap.getPosition(jenisKejadianBencana); spJenisKejadian.setSelection(spinnerPosition); } } private void clearPreferences() { // TODO Auto-generated method stub Editor editor = mySharedPreferences.edit(); editor.remove("IDPetugas"); editor.remove("IDBencana"); editor.remove("IDBencanaUpdate"); editor.remove("JumlahSubTim"); editor.remove("JumlahTimBPBD"); editor.remove("JumlahTimDinkes"); editor.remove("JumlahTimDinsos"); editor.remove("JumlahTimPU"); editor.remove("JenisKejadianBencana"); editor.remove("WaktuBencana"); editor.remove("TanggalBencana"); editor.remove("LatitudeBencana"); editor.remove("LongitudeBencana"); editor.remove("LokasiDusunBencana"); editor.remove("LokasiDesaBencana"); editor.remove("LokasiKecamatanBencana"); editor.remove("LokasiKabupatenBencana"); editor.remove("PenyebabBencana"); editor.remove("JumlahMeninggal"); editor.remove("JumlahLukaBerat"); editor.remove("JumlahLukaRingan"); editor.remove("JumlahHilang"); editor.remove("JumlahJiwaMengungsi"); editor.remove("JumlahKKMengungsi"); editor.remove("JumlahRumahRusak"); editor.remove("JumlahKantorRusak"); editor.remove("JumlahFasilitasKesehatanRusak"); editor.remove("JumlahFasilitasPendidikanRusak"); editor.remove("JumlahFasilitasUmumRusak"); editor.remove("JumlahSaranaIbadahRusak"); editor.remove("JumlahJembatanRusak"); editor.remove("JumlahJalanRusak"); editor.remove("JumlahTanggulRusak"); editor.remove("JumlahSawahRusak"); editor.remove("JumlahLahanRusak"); editor.remove("JumlahLainLainRusak"); editor.remove("WaktuPeninjauan"); editor.remove("TanggalPeninjauan"); editor.remove("MendirikanPosko"); editor.remove("MelakukanRapat"); editor.remove("MelaksanakanEvakuasi"); editor.remove("PelayananKesehatan"); editor.remove("DapurUmum"); editor.remove("BantuanMakanan"); editor.remove("PengarahanTenaga"); // editor.remove("SumberDaya"); // editor.remove("Kendala"); // editor.remove("Kebutuhan"); // editor.remove("RencanaTdkLanjut"); editor.commit(); } private void savePreferences() { // TODO Auto-generated method stub Editor editor = mySharedPreferences.edit(); editor.putString("IDPetugas", edtxtIDPetugas.getText().toString()); editor.putString("IDBencana", edtxtIDBencana.getText().toString()); editor.putString("JumlahTimBPBD", edtxtTimBPBD.getText().toString()); editor.putString("JumlahTimDinkes", edtxtTimDinkes.getText().toString()); editor.putString("JumlahTimDinsos", edtxtTimDinsos.getText().toString()); editor.putString("JumlahTimPU", edtxtTimPU.getText().toString()); editor.putString("JenisKejadianBencana", spJenisKejadian.getSelectedItem().toString()); editor.putString("TanggalBencana", tanggal); editor.putString("WaktuBencana", waktu); editor.putString("LatitudeBencana", latitude); editor.putString("LongitudeBencana", longitude); editor.commit(); } private void setUpGeoCurrentLocation() { // TODO Auto-generated method stub locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); criteria = new Criteria(); locationProvider = locationManager.getBestProvider(criteria, true); currentLocation = locationManager.getLastKnownLocation(locationProvider); locationManager.requestLocationUpdates(locationProvider, 5000, 10, this); isiPosisi(); } private void cekPosisi() { // TODO Auto-generated method stub if(currentLocation!=null) { Toast.makeText(getBaseContext(), "Data lokasi berhasil diset", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getBaseContext(), "Maaf data lokasi Belum tersedia", Toast.LENGTH_SHORT).show(); } setStatusLokasi(); } private void isiPosisi() { // TODO Auto-generated method stub if(currentLocation!=null) { latitude = String.valueOf(currentLocation.getLatitude()); longitude = String.valueOf(currentLocation.getLongitude()); if(progDialog.isShowing()) { progDialog.dismiss(); cekPosisi(); } } } public void onLocationChanged(Location location) { // TODO Auto-generated method stub currentLocation = location; isiPosisi(); // if(progDialog.isShowing()) // { // progDialog.dismiss(); // cekPosisi(); // } } public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } public void setStatusWaktu() { if(waktu.length()<=0||waktu.equalsIgnoreCase("")) { imgStatusWaktu.setVisibility(View.INVISIBLE); } else { imgStatusWaktu.setVisibility(View.VISIBLE); } } public void setStatusTanggal() { if(tanggal.length()<=0||tanggal.equalsIgnoreCase("")) { imgStatusTanggal.setVisibility(View.INVISIBLE); } else { imgStatusTanggal.setVisibility(View.VISIBLE); } } public void setStatusLokasi() { if(latitude.length()<=0||latitude.equalsIgnoreCase("")|| longitude.length()<=0||longitude.equalsIgnoreCase("")) { imgStatusLokasi.setVisibility(View.INVISIBLE); } else { imgStatusLokasi.setVisibility(View.VISIBLE); } } public boolean cekInputanData() { boolean cek = true; if(edtxtIDPetugas.getText().length()<=0|| edtxtIDPetugas.getText().toString().equalsIgnoreCase("")) { cek = false; Toast.makeText(getBaseContext(), "Isi Field ID Petugas!", Toast.LENGTH_SHORT).show(); } else if(edtxtIDBencana.getText().length()<=0|| edtxtIDBencana.getText().toString().equalsIgnoreCase("")) { cek = false; Toast.makeText(getBaseContext(), "Isi Field ID Bencana!", Toast.LENGTH_SHORT).show(); } else if(edtxtTimBPBD.getText().length()<=0|| edtxtTimBPBD.getText().toString().equalsIgnoreCase("")) { cek = false; Toast.makeText(getBaseContext(), "Isi Field Jumlah Tim BPBD!", Toast.LENGTH_SHORT).show(); } else if(edtxtTimDinsos.getText().length()<=0|| edtxtTimDinsos.getText().toString().equalsIgnoreCase("")) { cek = false; Toast.makeText(getBaseContext(), "Isi Field Jumlah Tim Dinas Sosial!", Toast.LENGTH_SHORT).show(); } else if(edtxtTimDinkes.getText().length()<=0|| edtxtTimDinkes.getText().toString().equalsIgnoreCase("")) { cek = false; Toast.makeText(getBaseContext(), "Isi Field Jumlah Tim Dinas Kesehatan!", Toast.LENGTH_SHORT).show(); } else if(edtxtTimPU.getText().length()<=0|| edtxtTimPU.getText().toString().equalsIgnoreCase("")) { cek = false; Toast.makeText(getBaseContext(), "Isi Field Jumlah Tim Perhubungan!", Toast.LENGTH_SHORT).show(); } else if(waktu.length()<=0||waktu.equalsIgnoreCase("")) { cek = false; Toast.makeText(getBaseContext(), "Atur Waktu Bencana!", Toast.LENGTH_SHORT).show(); } else if(tanggal.length()<=0||tanggal.equalsIgnoreCase("")) { cek = false; Toast.makeText(getBaseContext(), "Atur Tanggal Bencana!", Toast.LENGTH_SHORT).show(); } else if(latitude.length()<=0||latitude.equalsIgnoreCase("")|| longitude.length()<=0||longitude.equalsIgnoreCase("")) { cek = false; Toast.makeText(getBaseContext(), "Set Lokasi Dahulu!", Toast.LENGTH_SHORT).show(); } return cek; } private Dialog createDialog1(Context context){ AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Anda Yakin Batal Membuat Laporan?"); builder.setIcon(R.drawable.warning); builder.setPositiveButton("Iya", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub clearPreferences(); LapAwalBencanaAct_1.this.finish(); } }); builder.setNegativeButton("Tidak", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }); return builder.create(); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG1: return createDialog1(LapAwalBencanaAct_1.this); default: break; } return null; } public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.buttonSetWaktuBencana: //Set Waktu setTime(); break; case R.id.buttonSetTanggaBencana: //Set Tanggal setDate(); break; case R.id.buttonSetPosisi: // Set latitude longitude flag = displayGpsStatus(); if(flag) { progDialog.setMessage("Mencari data lokasi..."); progDialog.setTitle("Loading"); progDialog.setIcon(R.drawable.marker); progDialog.show(); // setUpGeoCurrentLocation(); locationManager.requestLocationUpdates(locationProvider, 5000, 10, this); } else { Toast.makeText(getApplicationContext(), "Tolong Aktifkan GPS Pada Perangkat Anda!", Toast.LENGTH_SHORT).show(); } break; case R.id.buttonLanjut: //Lanjutkan if(cekInputanData()==true) { savePreferences(); i = new Intent(LapAwalBencanaAct_1.this, LapAwalBencanaAct_2.class); startActivity(i); LapAwalBencanaAct_1.this.finish(); } break; case R.id.buttonBatal: //Batal showDialog(DIALOG1); break; default: break; } } private Boolean displayGpsStatus() { ContentResolver contentResolver = getBaseContext().getContentResolver(); boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver,LocationManager.GPS_PROVIDER); if (gpsStatus) { return true; } else { return false; } } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); locationManager.removeUpdates(this); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); locationManager.requestLocationUpdates(locationProvider, 5000, 10, this); setStatusLokasi(); setStatusTanggal(); setStatusWaktu(); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if(keyCode==KeyEvent.KEYCODE_BACK) { showDialog(DIALOG1); } return false; } }
30.978022
115
0.737141
4c977a558b0a89f1a6ec666fa66244b247fe1f89
311
package org.lexikos; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MorphoApplication { public static void main(String[] args) { SpringApplication.run(MorphoApplication.class, args); } }
23.923077
68
0.800643
0326b3084547645ac2a69cae1202e98063f40331
10,797
package jgame.platform; import jgame.*; import jgame.impl.JGameError; //import android.graphics.Bitmap; import android.graphics.*; import android.content.res.AssetManager; import java.io.IOException; import java.io.InputStream; import java.util.Hashtable; /** Image functionality */ class AndroidImage implements JGImage { //static Hashtable loadedimages = new Hashtable(); /* filenames => Images */ Bitmap img=null; //BitmapFactory.Options opaquebitmapopts = null; // colour which semi transparent pixels in scaled image should render to static JGColor bg_col=JGColor.black; // true means image is certainly opaque, false means image may be // transparent boolean is_opaque=false; /** Create new image and define any known settings. */ public AndroidImage (Bitmap img,JGColor bg_color,boolean is_opaque) { this.img=img; bg_col=bg_color; this.is_opaque=is_opaque; } /** Create new image */ public AndroidImage (Bitmap img) { this.img=img; } /** Create handle to image functions. */ public AndroidImage () { //opaquebitmapopts = new BitmapFactory.Options(); //opaquebitmapopts.inPreferredConfig = // getPreferredBitmapFormat(JGEngine.displayformat); } /* static in spirit*/ public JGImage loadImage(String imgfile) { return loadImage(JGEngine.assets,imgfile); } /** load image from assets directory * @param assets the assets manager used to load the file */ private AndroidImage loadImage(AssetManager assets, String filename) { Bitmap bitmap = null; if (assets!= null) { InputStream is; try { is = assets.open(filename); bitmap = BitmapFactory.decodeStream(is); is.close(); } catch (IOException e) { throw new Error("Asset '"+filename+"' not found"); } } return new AndroidImage(bitmap); } public void purgeImage(String imgfile) { //if (loadedimages.containsKey(imgfile)) loadedimages.remove(imgfile); } /* object-related methods */ JGPoint size=null; public JGPoint getSize() { if (size!=null) return size; size=new JGPoint(img.getWidth(),img.getHeight()); return size; } public boolean isOpaque(int alpha_thresh) { return is_opaque; } public JGImage rotate(int angle) { JGPoint size = getSize(); int [] buffer = new int [size.x * size.y]; img.getPixels(buffer, 0,size.x, 0,0, size.x,size.y); int [] rotate = new int [size.x * size.y]; int angletype = (angle/90) & 3; if (angletype==0) return this; if (angletype==1) { /* 1 2 3 4 9 5 1 * 5 6 7 8 => a 6 2 * 9 a b c b 7 3 * c 8 4 */ for(int y = 0; y < size.y; y++) { for(int x = 0; x < size.x; x++) { rotate[x*size.y + (size.y-1-y) ] = buffer[(y*size.x)+x]; } } return new AndroidImage( Bitmap.createBitmap(rotate,size.y,size.x,Bitmap.Config.ARGB_8888) ); } if (angletype==3) { /* 1 2 3 4 4 8 c * 5 6 7 8 => 3 7 b * 9 a b c 2 6 a * 1 5 9 */ for(int y = 0; y < size.y; y++) { for(int x = 0; x < size.x; x++) { rotate[(size.x-x-1)*size.y + y] = buffer[(y*size.x)+x]; } } return new AndroidImage( Bitmap.createBitmap(rotate,size.y,size.x,Bitmap.Config.ARGB_8888) ); } if (angletype==2) { /* 1 2 3 4 c b a 9 * 5 6 7 8 => 8 7 6 5 * 9 a b c 4 3 2 1 */ for(int y = 0; y < size.y; y++) { for(int x = 0; x < size.x; x++) { rotate[((size.y-y-1)*size.x)+(size.x-x-1)] = buffer[(y*size.x)+x]; } } } return new AndroidImage( Bitmap.createBitmap(rotate,size.x,size.y,Bitmap.Config.ARGB_8888) ); } public JGImage flip(boolean horiz,boolean vert) { if (!horiz && !vert) return this; JGPoint size = getSize(); int [] buffer = new int [size.x * size.y]; img.getPixels(buffer, 0,size.x, 0,0, size.x,size.y); int [] flipbuf = new int [size.x * size.y]; if (vert && !horiz) { for(int y = 0; y < size.y; y++) { for(int x = 0; x < size.x; x++) { flipbuf[(size.y-y-1)*size.x + x] = buffer[(y*size.x)+x]; } } } else if (horiz && !vert) { for(int y = 0; y < size.y; y++) { for(int x = 0; x < size.x; x++) { flipbuf[y*size.x + (size.x-x-1)] = buffer[(y*size.x)+x]; } } } else if (horiz && vert) { for(int y = 0; y < size.y; y++) { for(int x = 0; x < size.x; x++) { flipbuf[(size.y-y-1)*size.x + (size.x-x-1)] = buffer[(y*size.x)+x]; } } } return new AndroidImage( Bitmap.createBitmap(flipbuf,size.x,size.y,Bitmap.Config.ARGB_8888) ); } public JGImage scale(int width, int height) { return new AndroidImage(Bitmap.createScaledBitmap(img,width,height,true)); // int [] pix = new int [img.getWidth()*img.getHeight()]; // int srcwidth = img.getWidth(); // int srcheight = img.getHeight(); // img.getRGB(pix,0,srcwidth,0,0,srcwidth,srcheight); // int [] dstpix = new int[width*height]; // int dstidx=0; // int bg_pix=(((bg_col.r<<16) + (bg_col.g<<8) + bg_col.b)>>2)&0x3f3f3f3f; // double srcxinc = img.getWidth()/(double)width; // double srcyinc = img.getHeight()/(double)height; // double srcx,srcy=srcyinc*0.25; // double srcxround=srcxinc*0.5,srcyround=srcyinc*0.5; // for (int y=0; y<height; y++) { // srcx=srcxinc*0.25; // for (int x=0; x<width; x++) { // int pix1 = (pix[(int)srcx + srcwidth*(int)srcy] // >> 2) & 0x3f3f3f3f; // int pix2 = (pix[(int)(srcx+srcxround) + srcwidth*(int)srcy] // >> 2) & 0x3f3f3f3f; // int pix3 = (pix[(int)srcx + srcwidth*(int)(srcy+srcyround)] // >> 2) & 0x3f3f3f3f; // int pix4 = (pix[(int)(srcx+srcxround) + // srcwidth*(int)(srcy+srcyround)] // >> 2) & 0x3f3f3f3f; // // you might think that transparent pixels remember the // // colour you assigned to them, but on some phones // // (Sony Ericsson) they don't, and // // transparent pixels are always white. So we assign the bg // // color to them here. // if (pix1 <= 0xffffff) pix1 = bg_pix; // if (pix2 <= 0xffffff) pix2 = bg_pix; // if (pix3 <= 0xffffff) pix3 = bg_pix; // if (pix4 <= 0xffffff) pix4 = bg_pix; // int dp = pix1+pix2+pix3+pix4; // //if ((dp&0xff000000) != 0) dp |= 0xff000000; // if (((dp>>24)&0xff) > 0x60) dp |= 0xff000000; else dp = 0; // dstpix[dstidx++] = dp; // srcx += srcxinc; // } // srcy += srcyinc; // } // // clean up temp data before creating image to avoid peak memory use // pix = null; // return new AndroidImage( // Bitmap.createRGBImage(dstpix,width,height,!is_opaque), // bg_col,is_opaque); } public JGImage rotateAny(double angle) { return new AndroidImage(img); // int sw = img.getWidth(); // int sh = img.getHeight(); // int bg_pix=(((bg_col.r<<16) + (bg_col.g<<8) + bg_col.b)>>2)&0x3f3f3f3f; // // destination size is upper bound size. Upper bound is the max // // of the longest dimension and the figure's dimension at 45 degrees // // = sw*sin(45)+sh*cos(45) ~= 1.5*(sw+sh) // int dw = (int)Math.max( Math.max(sw,sh), 0.75*(sw+sh)); // int dh = dw; // // int[] srcData = new int[sw * sh]; // img.getRGB(srcData, 0, sw, 0, 0, sw, sh); // int[] dstData = new int[dw * dh]; // // float sa = (float) Math.sin(angle); // float ca = (float) Math.cos(angle); // int isa = (int) (256 * sa); // int ica = (int) (256 * ca); // // int my = - (dh >> 1); // for(int i = 0; i < dh; i++) { // int wpos = i * dw; // // int xacc = my * isa - (dw >> 1) * ica + ((sw >> 1) << 8); // int yacc = my * ica + (dw >> 1) * isa + ((sh >> 1) << 8); // // for(int j = 0; j < dw; j++) { // do { // int srcx1 = (xacc >> 8); // int srcy1 = (yacc >> 8); // int srcx2 = ((xacc+0x80) >> 8); // int srcy2 = ((yacc+0x80) >> 8); // // if (srcx1 < 0 || srcx1 >= sw) { // if (srcx2 < 0 || srcx2 >= sw) break; // srcx1 = srcx2; // } // if (srcy1 < 0 || srcy1 >= sh) { // if (srcy2 < 0 || srcy2 >= sh) break; // srcy1 = srcy2; // } // if (srcx2 < 0 || srcx2 >= sw) { // if (srcx1 < 0 || srcx1 >= sw) break; // srcx2 = srcx1; // } // if (srcy2 < 0 || srcy2 >= sh) { // if (srcy1 < 0 || srcy1 >= sh) break; // srcy2 = srcy1; // } // int pix1 = (srcData[srcx1 + srcy1 * sw]>>2)&0x3f3f3f3f; // int pix2 = (srcData[srcx2 + srcy1 * sw]>>2)&0x3f3f3f3f; // int pix3 = (srcData[srcx1 + srcy2 * sw]>>2)&0x3f3f3f3f; // int pix4 = (srcData[srcx2 + srcy2 * sw]>>2)&0x3f3f3f3f; // // see also scale() // /*int pixnr=0; // int dp=0; // if (pix1 > 0xffffff) { // dp += pix1; // pixnr++; // } // if (pix2 > 0xffffff) { // dp += pix2; // pixnr++; // } // if (pix3 > 0xffffff) { // dp += pix3; // pixnr++; // } // if (pix4 > 0xffffff) { // dp += pix4; // pixnr++; // } // if (pixnr<4) break; // if ((dp&0xff000000) != 0) dp |= 0xff000000; // dstData[wpos] = (dp/pixnr)<<2;*/ // if (pix1 <= 0xffffff) pix1 = bg_pix; // if (pix2 <= 0xffffff) pix2 = bg_pix; // if (pix3 <= 0xffffff) pix3 = bg_pix; // if (pix4 <= 0xffffff) pix4 = bg_pix; // int dp = pix1+pix2+pix3+pix4; // if (((dp>>24)&0xff) > 0x60) dp |= 0xff000000; else dp = 0; // dstData[wpos] = dp; // } while (false); // wpos++; // xacc += ica; // yacc -= isa; // } // my++; // } // // clean up temp data before creating image to avoid peak memory use // srcData = null; // return new AndroidImage(Bitmap.createRGBImage(dstData, dw, dh, !is_opaque)); } public JGImage crop(int x,int y, int width,int height) { return new AndroidImage(Bitmap.createBitmap(img, x, y, width, height, null, true) ); // return new AndroidImage(Bitmap.createImage(img, // x,y, width,height, Sprite.TRANS_NONE),bg_col,is_opaque); } public JGImage toDisplayCompatible(int thresh,JGColor bg_col, boolean fast,boolean bitmask) { return new AndroidImage(img); // this.bg_col=bg_col; // int [] pix = new int [img.getWidth()*img.getHeight()]; // int srcwidth = img.getWidth(); // int srcheight = img.getHeight(); // img.getRGB(pix,0,srcwidth,0,0,srcwidth,srcheight); // int srcidx=0; // int bg_pix = (bg_col.r<<16) + (bg_col.g<<8) + bg_col.b; // boolean is_transparent=false; // for (int i=0; i<srcwidth*srcheight; i++) { // int alpha = (pix[srcidx]>>24)&0xff; // if (alpha > thresh) { // pix[srcidx++] |= 0xff000000; // } else { // pix[srcidx++] = bg_pix; // is_transparent=true; // } // } // return new AndroidImage(Bitmap.createRGBImage(pix,srcwidth,srcheight, // is_transparent),bg_col,!is_transparent); } // not useful: cannot retrieve display format public static Bitmap.Config getPreferredBitmapFormat(int displayformat) { if (displayformat == PixelFormat.RGB_565) return Bitmap.Config.RGB_565; else return Bitmap.Config.ARGB_8888; } }
30.159218
80
0.580995
a2c35df278ea552de2879b5ad6f971ea133f8731
169
package com.study.tomcat.connector; /** * * @author dranawhite * @version $Id: Response.java, v 0.1 2019-03-09 17:44 dranawhite Exp $$ */ public class Response { }
16.9
72
0.674556