hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e0dc90df81d34783eb5fc37fb3cdf4bc964e19b
2,451
java
Java
protonj2-client-examples/src/main/java/org/apache/qpid/protonj2/client/examples/Request.java
tabish121/proton4j
225b7f35c545e73a3172d159bf4baec850009429
[ "Apache-2.0" ]
2
2019-04-28T20:38:32.000Z
2020-05-21T22:25:43.000Z
protonj2-client-examples/src/main/java/org/apache/qpid/protonj2/client/examples/Request.java
tabish121/protonj2
225b7f35c545e73a3172d159bf4baec850009429
[ "Apache-2.0" ]
null
null
null
protonj2-client-examples/src/main/java/org/apache/qpid/protonj2/client/examples/Request.java
tabish121/protonj2
225b7f35c545e73a3172d159bf4baec850009429
[ "Apache-2.0" ]
1
2018-04-05T18:51:10.000Z
2018-04-05T18:51:10.000Z
41.542373
97
0.71889
5,828
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.qpid.protonj2.client.examples; import java.util.concurrent.TimeUnit; import org.apache.qpid.protonj2.client.Client; import org.apache.qpid.protonj2.client.Connection; import org.apache.qpid.protonj2.client.Delivery; import org.apache.qpid.protonj2.client.Message; import org.apache.qpid.protonj2.client.Receiver; import org.apache.qpid.protonj2.client.Sender; import org.apache.qpid.protonj2.client.SenderOptions; /** * Sends a Request to a request Queue and awaits a response. */ public class Request { public static void main(String[] args) throws Exception { String serverHost = "localhost"; int serverPort = 5672; String address = "request-respond-example"; Client client = Client.create(); try (Connection connection = client.connect(serverHost, serverPort)) { Receiver dynamicReceiver = connection.openDynamicReceiver(); String dynamicAddress = dynamicReceiver.address(); System.out.println("Waiting for response to requests on address: " + dynamicAddress); SenderOptions senderOptions = new SenderOptions(); senderOptions.targetOptions().capabilities("queue"); Sender requestor = connection.openSender(address, senderOptions); Message<String> request = Message.create("Hello World").replyTo(dynamicAddress); requestor.send(request); Delivery response = dynamicReceiver.receive(30, TimeUnit.SECONDS); Message<String> received = response.message(); System.out.println("Received message with body: " + received.body()); } } }
3e0dc9299b662838c52f8db63c6e9c2e986e00f6
11,143
java
Java
server/src/test/java/io/crate/planner/SubQueryPlannerTest.java
Wiewiogr/crate
5651d8d4f6d149c496e329751af3e1fd28f8a5a8
[ "Apache-2.0" ]
3,066
2015-01-01T05:44:20.000Z
2022-03-31T19:33:32.000Z
server/src/test/java/io/crate/planner/SubQueryPlannerTest.java
Wiewiogr/crate
5651d8d4f6d149c496e329751af3e1fd28f8a5a8
[ "Apache-2.0" ]
7,255
2015-01-02T08:25:25.000Z
2022-03-31T21:05:43.000Z
server/src/test/java/io/crate/planner/SubQueryPlannerTest.java
Wiewiogr/crate
5651d8d4f6d149c496e329751af3e1fd28f8a5a8
[ "Apache-2.0" ]
563
2015-01-06T19:07:27.000Z
2022-03-25T03:03:36.000Z
44.572
117
0.627748
5,829
/* * Licensed to Crate.io GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.planner; import io.crate.execution.dsl.phases.CollectPhase; import io.crate.execution.dsl.phases.RoutedCollectPhase; import io.crate.execution.dsl.projection.AggregationProjection; import io.crate.execution.dsl.projection.EvalProjection; import io.crate.execution.dsl.projection.FetchProjection; import io.crate.execution.dsl.projection.FilterProjection; import io.crate.execution.dsl.projection.GroupProjection; import io.crate.execution.dsl.projection.OrderedTopNProjection; import io.crate.execution.dsl.projection.Projection; import io.crate.execution.dsl.projection.TopNProjection; import io.crate.planner.node.dql.Collect; import io.crate.planner.node.dql.QueryThenFetch; import io.crate.planner.node.dql.join.Join; import io.crate.test.integration.CrateDummyClusterServiceUnitTest; import io.crate.testing.SQLExecutor; import io.crate.testing.T3; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import java.util.List; import static io.crate.testing.ProjectionMatchers.isTopN; import static io.crate.testing.SymbolMatchers.isFunction; import static io.crate.testing.SymbolMatchers.isLiteral; import static io.crate.testing.SymbolMatchers.isReference; import static io.crate.testing.TestingHelpers.isSQL; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; public class SubQueryPlannerTest extends CrateDummyClusterServiceUnitTest { private SQLExecutor e; @Before public void setUpExecutor() throws Exception { e = SQLExecutor.builder(clusterService) .addTable(T3.T1_DEFINITION) .addTable(T3.T2_DEFINITION) .build(); } @Test public void testNestedSimpleSelectContainsFilterProjectionForWhereClause() throws Exception { QueryThenFetch qtf = e.plan( "select x, i from " + " (select x, i from t1 order by x asc limit 10) ti " + "where ti.x = 10 " + "order by x desc limit 3"); Collect collect = (Collect) qtf.subPlan(); List<Projection> projections = collect.collectPhase().projections(); assertThat(projections, Matchers.hasItem(instanceOf(FilterProjection.class))); } @Test public void testNestedSimpleSelectWithJoin() throws Exception { Join nl= e.plan("select t1x from (" + "select t1.x as t1x, t2.i as t2i from t1 as t1, t1 as t2 order by t1x asc limit 10" + ") t order by t1x desc limit 3"); List<Projection> projections = nl.joinPhase().projections(); assertThat(projections, Matchers.contains( instanceOf(EvalProjection.class), isTopN(10, 0), instanceOf(OrderedTopNProjection.class), instanceOf(EvalProjection.class), isTopN(3, 0) )); assertThat(projections.get(0).outputs(), isSQL("INPUT(1), INPUT(1)")); assertThat(projections.get(4).outputs(), isSQL("INPUT(0)")); } @Test public void testNestedSimpleSelectContainsGroupProjectionWithFunction() throws Exception { Collect collect = e.plan("select c + 100, max(max) from " + " (select x + 10::int as c, max(i) as max from t1 group by x + 10::int) t " + "group by c + 100 order by c + 100 " + "limit 100"); CollectPhase collectPhase = collect.collectPhase(); assertThat( collectPhase.toCollect(), contains( isReference("i"), isFunction("add", isReference("x"), isLiteral(10)) ) ); assertThat( collectPhase.projections(), contains( instanceOf(GroupProjection.class), instanceOf(GroupProjection.class), instanceOf(EvalProjection.class), instanceOf(GroupProjection.class), instanceOf(OrderedTopNProjection.class), instanceOf(TopNProjection.class) ) ); } @Test @SuppressWarnings("unchecked") public void testJoinOnSubSelectsWithLimitAndOffset() throws Exception { Join join = e.plan("select * from " + " (select i, a from t1 order by a limit 10 offset 2) t1 " + "join" + " (select i from t2 order by b limit 5 offset 5) t2 " + "on t1.i = t2.i"); assertThat(join.joinPhase().projections().size(), is(1)); assertThat(join.joinPhase().projections().get(0), instanceOf(EvalProjection.class)); QueryThenFetch leftQtf = (QueryThenFetch) join.left(); Collect left = (Collect) leftQtf.subPlan(); assertThat("1 node, otherwise mergePhases would be required", left.nodeIds().size(), is(1)); assertThat(left.orderBy(), isSQL("OrderByPositions{indices=[1], reverseFlags=[false], nullsFirst=[false]}")); assertThat(left.collectPhase().projections(), contains( isTopN(10, 2), instanceOf(FetchProjection.class) )); QueryThenFetch rightQtf = (QueryThenFetch) join.right(); Collect right = (Collect) rightQtf.subPlan(); assertThat("1 node, otherwise mergePhases would be required", right.nodeIds().size(), is(1)); assertThat(((RoutedCollectPhase) right.collectPhase()).orderBy(), isSQL("doc.t2.b")); assertThat(right.collectPhase().projections(), contains( isTopN(5, 5), instanceOf(FetchProjection.class), instanceOf(EvalProjection.class) // strips `b` used in order by from the outputs )); } @Test public void testJoinWithAggregationOnSubSelectsWithLimitAndOffset() throws Exception { Join join = e.plan("select t1.a, count(*) from " + " (select i, a from t1 order by a limit 10 offset 2) t1 " + "join" + " (select i from t2 order by i desc limit 5 offset 5) t2 " + "on t1.i = t2.i " + "group by t1.a"); QueryThenFetch qtf = (QueryThenFetch) join.left(); Collect left = (Collect) qtf.subPlan(); assertThat("1 node, otherwise mergePhases would be required", left.nodeIds().size(), is(1)); assertThat(((RoutedCollectPhase) left.collectPhase()).orderBy(), isSQL("doc.t1.a")); assertThat(left.collectPhase().projections(), contains( isTopN(10, 2), instanceOf(FetchProjection.class) )); assertThat(left.collectPhase().toCollect(), isSQL("doc.t1._fetchid, doc.t1.a")); Collect right = (Collect) join.right(); assertThat("1 node, otherwise mergePhases would be required", right.nodeIds().size(), is(1)); assertThat(((RoutedCollectPhase) right.collectPhase()).orderBy(), isSQL("doc.t2.i DESC")); assertThat(right.collectPhase().projections(), contains( isTopN(5, 5) )); List<Projection> nlProjections = join.joinPhase().projections(); assertThat(nlProjections, contains( instanceOf(EvalProjection.class), instanceOf(GroupProjection.class) )); } @Test public void testJoinWithGlobalAggregationOnSubSelectsWithLimitAndOffset() throws Exception { Join join = e.plan("select count(*) from " + " (select i, a from t1 order by a limit 10 offset 2) t1 " + "join" + " (select i from t2 order by i desc limit 5 offset 5) t2 " + "on t1.i = t2.i"); QueryThenFetch leftQtf = (QueryThenFetch) join.left(); Collect left = (Collect) leftQtf.subPlan(); assertThat("1 node, otherwise mergePhases would be required", left.nodeIds().size(), is(1)); assertThat(left.collectPhase().toCollect(), isSQL("doc.t1._fetchid, doc.t1.a")); assertThat(((RoutedCollectPhase) left.collectPhase()).orderBy(), isSQL("doc.t1.a")); assertThat(left.collectPhase().projections(), contains( isTopN(10, 2), instanceOf(FetchProjection.class) )); Collect right = (Collect) join.right(); assertThat("1 node, otherwise mergePhases would be required", right.nodeIds().size(), is(1)); assertThat(((RoutedCollectPhase) right.collectPhase()).orderBy(), isSQL("doc.t2.i DESC")); assertThat(right.collectPhase().projections(), contains( isTopN(5, 5) )); List<Projection> nlProjections = join.joinPhase().projections(); assertThat(nlProjections, contains( instanceOf(EvalProjection.class), instanceOf(AggregationProjection.class) )); } @Test public void testJoinWithAggregationOnSubSelectsWithAggregations() throws Exception { Join nl = e.plan("select t1.a, count(*) from " + " (select a, count(*) as cnt from t1 group by a) t1 " + "join" + " (select distinct i from t2) t2 " + "on t1.cnt = t2.i::long " + "group by t1.a"); assertThat(nl.joinPhase().projections(), contains( instanceOf(EvalProjection.class), instanceOf(GroupProjection.class) )); assertThat(nl.left(), instanceOf(Collect.class)); Collect leftPlan = (Collect) nl.left(); CollectPhase leftCollectPhase = leftPlan.collectPhase(); assertThat( leftCollectPhase.projections(), contains( instanceOf(GroupProjection.class), instanceOf(GroupProjection.class), instanceOf(EvalProjection.class) ) ); Collect rightPlan = (Collect) nl.right(); assertThat(rightPlan.collectPhase().projections(), contains( instanceOf(GroupProjection.class), instanceOf(GroupProjection.class) )); } }
3e0dc956a3e2312a86d27877daa8b805f16a6acd
529
java
Java
Data-Structures/Arrays/Cloning-of-one-dimensional-array.java
Pranit5895/Java-Programming
4203c899b4ce97e510e44fdade015fbf2da92fb3
[ "Apache-1.1" ]
1
2021-03-16T06:08:51.000Z
2021-03-16T06:08:51.000Z
Data-Structures/Arrays/Cloning-of-one-dimensional-array.java
Pranit5895/Java-Programming
4203c899b4ce97e510e44fdade015fbf2da92fb3
[ "Apache-1.1" ]
null
null
null
Data-Structures/Arrays/Cloning-of-one-dimensional-array.java
Pranit5895/Java-Programming
4203c899b4ce97e510e44fdade015fbf2da92fb3
[ "Apache-1.1" ]
null
null
null
25.190476
54
0.514178
5,830
// Java program to demonstrate // cloning of one-dimensional arrays class Test { public static void main(String args[]) { int intArray[] = {1,2,3}; int cloneArray[] = intArray.clone(); // will print false as deep copy is created // for one-dimensional array System.out.println(intArray == cloneArray); for (int i = 0; i < cloneArray.length; i++) { System.out.print(cloneArray[i]+" "); } } }
3e0dc9e0e0135ead15272d77ccaf35ef2eeed70d
2,143
java
Java
src/com/github/farhan3/jclickerquiz/model/DataUtil.java
farhan3/JClickerQuiz
ef510d8de01ec6479f566372be09c4b549c2712f
[ "Apache-2.0" ]
3
2017-09-25T00:30:01.000Z
2020-12-21T08:04:25.000Z
src/com/github/farhan3/jclickerquiz/model/DataUtil.java
farhan3/JClickerQuiz
ef510d8de01ec6479f566372be09c4b549c2712f
[ "Apache-2.0" ]
null
null
null
src/com/github/farhan3/jclickerquiz/model/DataUtil.java
farhan3/JClickerQuiz
ef510d8de01ec6479f566372be09c4b549c2712f
[ "Apache-2.0" ]
6
2017-06-05T03:59:26.000Z
2020-11-03T19:01:16.000Z
26.134146
79
0.664956
5,831
package com.github.farhan3.jclickerquiz.model; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; public class DataUtil { /** * Read a text file containing student number, one per line, and * return the list of student numbers. * @param studentNumFilePath the file path of the text file * @return list of student numbers obtained from the text file * @throws URISyntaxException if there was an issue with the given file path */ public static Collection<Integer> getStudentNumbers(String studentNumFilePath) throws URISyntaxException { if (studentNumFilePath == null) { return Collections.emptyList(); } Collection<Integer> studentNumber = new LinkedList<Integer>(); URL url = DataUtil.class.getResource(studentNumFilePath); if (url == null) { System.err.println(Thread.currentThread().getStackTrace()[1] + ": \n \t" + "The URL for the file <" + studentNumFilePath + "> was null. "); return null; } File file; try { file = new File(url.toURI()); } catch (URISyntaxException err) { err.printStackTrace(); return null; } if (file == null || !file.isFile()) { System.err.println(Thread.currentThread().getStackTrace()[1] + ": \n \t" + "The file <" + studentNumFilePath + "> is not a file. "); return null; } BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String line = null; while ((line = reader.readLine()) != null) { studentNumber.add(Integer.parseInt(line)); } } catch (FileNotFoundException err) { err.printStackTrace(); return null; } catch (IOException err) { err.printStackTrace(); return null; } finally { try { if (reader != null) { reader.close(); } } catch (IOException err2) { err2.printStackTrace(); } } return studentNumber; } }
3e0dca54ad1f196406ffa1a3efc264a730faf8cb
1,439
java
Java
airnet-data-service/src/main/java/com/marticles/airnet/dataservice/dao/RankDAO.java
Marticles/AirNet
c52542f8a488a4ccfcec205d09d15b4f460d5afb
[ "MIT" ]
26
2019-03-02T17:21:31.000Z
2022-02-26T16:31:15.000Z
airnet-data-service/src/main/java/com/marticles/airnet/dataservice/dao/RankDAO.java
znlccy/airnet
c52542f8a488a4ccfcec205d09d15b4f460d5afb
[ "MIT" ]
1
2020-02-28T07:45:38.000Z
2020-02-28T07:45:38.000Z
airnet-data-service/src/main/java/com/marticles/airnet/dataservice/dao/RankDAO.java
znlccy/airnet
c52542f8a488a4ccfcec205d09d15b4f460d5afb
[ "MIT" ]
9
2019-03-02T17:21:32.000Z
2020-11-13T01:55:10.000Z
44.96875
135
0.624739
5,832
package com.marticles.airnet.dataservice.dao; import com.marticles.airnet.dataservice.model.Rank; import org.apache.ibatis.annotations.*; import java.util.Date; import java.util.List; /** * @author Marticles * @description RankDAO * @date 2019/2/7 */ @Mapper public interface RankDAO { String FIELDS = "site,aqi,level,primaryPollutant,pm25,pm10,co,no2,ozone1hour,so2"; @Results({@Result(column = "ozone1hour", property = "oZone"), @Result(column = "primarypollutant", property = "primaryPollutant")}) @Select({"(select " + FIELDS + " from hongkou where time = #{time})" + "union all(select " + FIELDS + " from jingan where time = #{time})" + "union all(select " + FIELDS + " from pudongchuansha where time = #{time})" + "union all(select " + FIELDS + " from pudongxinqu where time = #{time})" + "union all(select " + FIELDS + " from pudongzhangjiang where time = #{time})" + "union all(select " + FIELDS + " from putuo where time = #{time})" + "union all(select " + FIELDS + " from qingpudianshanhu where time = #{time})" + "union all(select " + FIELDS + " from shiwuchang where time = #{time})" + "union all(select " + FIELDS + " from xuhuishangshida where time = #{time})" + "union all(select " + FIELDS + " from yangpusipiao where time = #{time})"}) List<Rank> getSiteRanks(@Param("time") Date time); }
3e0dcb17f7a9a46163b3005bf9cb286092c4367c
5,344
java
Java
src/pt/haslab/htapbench/core/TimeBucketIterator.java
faclc4/HTAPBench
0e64856a3906b65a077335fd10003b6af90e1ea6
[ "Apache-2.0" ]
15
2017-12-07T15:39:30.000Z
2022-02-18T02:28:56.000Z
src/pt/haslab/htapbench/core/TimeBucketIterator.java
faclc4/HTAPBench
0e64856a3906b65a077335fd10003b6af90e1ea6
[ "Apache-2.0" ]
5
2018-03-10T14:40:55.000Z
2019-11-25T17:03:02.000Z
src/pt/haslab/htapbench/core/TimeBucketIterator.java
faclc4/HTAPBench
0e64856a3906b65a077335fd10003b6af90e1ea6
[ "Apache-2.0" ]
10
2017-08-23T12:47:08.000Z
2022-02-18T02:57:12.000Z
40.484848
126
0.509918
5,833
/****************************************************************************** * Copyright 2015 by OLTPBenchmark Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * ****************************************************************************** /* * Copyright 2017 by INESC TEC * This work was based on the OLTPBenchmark Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pt.haslab.htapbench.core; import pt.haslab.htapbench.api.TransactionType; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; /** * * @author Fábio Coelho */ public final class TimeBucketIterator implements Iterator<DistributionStatistics> { private final Iterator<LatencyRecord.Sample> samples; private final int windowSizeSeconds; private final TransactionType txType; private LatencyRecord.Sample sample; private long nextStartNs; private DistributionStatistics next; /** * @param samples * @param windowSizeSeconds * @param txType * Allows to filter transactions by type */ public TimeBucketIterator(Iterator<LatencyRecord.Sample> samples, int windowSizeSeconds, TransactionType txType) { this.samples = samples; this.windowSizeSeconds = windowSizeSeconds; this.txType = txType; if (samples.hasNext()) { sample = samples.next(); // TODO: To be totally correct, we would want this to be the // timestamp of the start // of the measurement interval. In most cases this won't matter. nextStartNs = sample.startNs; calculateNext(); } } private void calculateNext() { assert next == null; assert sample != null; assert sample.startNs >= nextStartNs; // Collect all samples in the time window ArrayList<Integer> latencies = new ArrayList<Integer>(); long endNs = nextStartNs + windowSizeSeconds * 1000000000L; while (sample != null && sample.startNs < endNs) { // Check if a TX Type filter is set, in the default case, // INVALID TXType means all should be reported, if a filter is // set, only this specific transaction if (txType == TransactionType.INVALID || txType.getId() == sample.tranType) latencies.add(sample.latencyUs); if (samples.hasNext()) { sample = samples.next(); } else { sample = null; } } // Set up the next time window assert sample == null || endNs <= sample.startNs; nextStartNs = endNs; int[] l = new int[latencies.size()]; for (int i = 0; i < l.length; ++i) { l[i] = latencies.get(i); } next = DistributionStatistics.computeStatistics(l); } @Override public boolean hasNext() { return next != null; } @Override public DistributionStatistics next() { if (next == null) throw new NoSuchElementException(); DistributionStatistics out = next; next = null; if (sample != null) { calculateNext(); } return out; } @Override public void remove() { throw new UnsupportedOperationException("unsupported"); } }
3e0dcbbdd4faa83d92608e8741e897a3ce8805b2
633
java
Java
src/sk/uniza/fri/duracik2/gui/reflection/Funkcia.java
Unlink/Java-Simple-Service-GUI
fffb8c36554466331ed68cd3f808f7df16d03ae4
[ "MIT" ]
null
null
null
src/sk/uniza/fri/duracik2/gui/reflection/Funkcia.java
Unlink/Java-Simple-Service-GUI
fffb8c36554466331ed68cd3f808f7df16d03ae4
[ "MIT" ]
null
null
null
src/sk/uniza/fri/duracik2/gui/reflection/Funkcia.java
Unlink/Java-Simple-Service-GUI
fffb8c36554466331ed68cd3f808f7df16d03ae4
[ "MIT" ]
null
null
null
22.607143
79
0.742496
5,834
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sk.uniza.fri.duracik2.gui.reflection; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * * @author Unlink */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface Funkcia { int id() default -1; String name() default ""; String popis() default ""; String[] parametre() default {}; }
3e0dcd0f97cdd321b4eee2a6ad714db6c7ad4fd1
3,881
java
Java
icu/icu4j/main/classes/core/src/com/ibm/icu/impl/CharacterIteratorWrapper.java
OpenSource-Infinix/android_external_crcalc
e5bbf05e3a01b449f33cca14c5ce8048df45624b
[ "Unlicense" ]
7
2015-09-13T06:21:16.000Z
2021-07-13T02:12:50.000Z
icu/icu4j/main/classes/core/src/com/ibm/icu/impl/CharacterIteratorWrapper.java
OpenSource-Infinix/android_external_crcalc
e5bbf05e3a01b449f33cca14c5ce8048df45624b
[ "Unlicense" ]
null
null
null
icu/icu4j/main/classes/core/src/com/ibm/icu/impl/CharacterIteratorWrapper.java
OpenSource-Infinix/android_external_crcalc
e5bbf05e3a01b449f33cca14c5ce8048df45624b
[ "Unlicense" ]
6
2015-03-15T06:30:08.000Z
2021-03-15T18:05:56.000Z
26.04698
94
0.546766
5,835
/* ******************************************************************************* * Copyright (C) 1996-2010, International Business Machines Corporation and * * others. All Rights Reserved. * ******************************************************************************* */ package com.ibm.icu.impl; import java.text.CharacterIterator; import com.ibm.icu.text.UCharacterIterator; /** * This class is a wrapper around CharacterIterator and implements the * UCharacterIterator protocol * @author ram */ public class CharacterIteratorWrapper extends UCharacterIterator { private CharacterIterator iterator; public CharacterIteratorWrapper(CharacterIterator iter){ if(iter==null){ throw new IllegalArgumentException(); } iterator = iter; } /** * @see UCharacterIterator#current() */ public int current() { int c = iterator.current(); if(c==CharacterIterator.DONE){ return DONE; } return c; } /** * @see UCharacterIterator#getLength() */ public int getLength() { return (iterator.getEndIndex() - iterator.getBeginIndex()); } /** * @see UCharacterIterator#getIndex() */ public int getIndex() { return iterator.getIndex(); } /** * @see UCharacterIterator#next() */ public int next() { int i = iterator.current(); iterator.next(); if(i==CharacterIterator.DONE){ return DONE; } return i; } /** * @see UCharacterIterator#previous() */ public int previous() { int i = iterator.previous(); if(i==CharacterIterator.DONE){ return DONE; } return i; } /** * @see UCharacterIterator#setIndex(int) */ public void setIndex(int index) { try{ iterator.setIndex(index); }catch(IllegalArgumentException e){ throw new IndexOutOfBoundsException(); } } /** * @see UCharacterIterator#setToLimit() */ public void setToLimit() { iterator.setIndex(iterator.getEndIndex()); } /** * @see UCharacterIterator#getText(char[]) */ public int getText(char[] fillIn, int offset){ int length =iterator.getEndIndex() - iterator.getBeginIndex(); int currentIndex = iterator.getIndex(); if(offset < 0 || offset + length > fillIn.length){ throw new IndexOutOfBoundsException(Integer.toString(length)); } for (char ch = iterator.first(); ch != CharacterIterator.DONE; ch = iterator.next()) { fillIn[offset++] = ch; } iterator.setIndex(currentIndex); return length; } /** * Creates a clone of this iterator. Clones the underlying character iterator. * @see UCharacterIterator#clone() */ public Object clone(){ try { CharacterIteratorWrapper result = (CharacterIteratorWrapper) super.clone(); result.iterator = (CharacterIterator)this.iterator.clone(); return result; } catch (CloneNotSupportedException e) { return null; // only invoked if bad underlying character iterator } } public int moveIndex(int delta){ int length = iterator.getEndIndex() - iterator.getBeginIndex(); int idx = iterator.getIndex()+delta; if(idx < 0) { idx = 0; } else if(idx > length) { idx = length; } return iterator.setIndex(idx); } /** * @see UCharacterIterator#getCharacterIterator() */ public CharacterIterator getCharacterIterator(){ return (CharacterIterator)iterator.clone(); } }
3e0dcd8e2551e06480e4f2909d03854feb48341d
4,912
java
Java
googletoolbar/src/main/java/org/netbeans/modules/googletoolbar/GooglePanel.java
timboudreau/netbeans-contrib
e414495e8585df9911392d7e3b190153759ff6d3
[ "Apache-2.0" ]
2
2018-07-19T08:40:29.000Z
2019-12-07T19:37:03.000Z
googletoolbar/src/main/java/org/netbeans/modules/googletoolbar/GooglePanel.java
timboudreau/netbeans-contrib
e414495e8585df9911392d7e3b190153759ff6d3
[ "Apache-2.0" ]
4
2021-02-03T19:27:41.000Z
2021-08-02T17:04:13.000Z
googletoolbar/src/main/java/org/netbeans/modules/googletoolbar/GooglePanel.java
timboudreau/netbeans-contrib
e414495e8585df9911392d7e3b190153759ff6d3
[ "Apache-2.0" ]
2
2020-10-03T14:44:58.000Z
2022-01-13T22:03:24.000Z
42.713043
213
0.705822
5,836
/* * 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 * 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. 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): * * 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.googletoolbar; import org.openide.awt.HtmlBrowser.URLDisplayer; import java.net.URL; /** * * @author Ludovic Champenois */ public class GooglePanel extends javax.swing.JPanel { /** Creates new form GooglePanel */ public GooglePanel() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jLabel1.setText("Google:"); jTextField1.setText("Enter your search here..."); jTextField1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { jTextField1KeyTyped(evt); } }); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup() .add(jLabel1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jTextField1, 0, 160, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.BASELINE, jLabel1) .add(org.jdesktop.layout.GroupLayout.BASELINE, jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) ); }// </editor-fold>//GEN-END:initComponents private void jTextField1KeyTyped(java.awt.event.KeyEvent e) {//GEN-FIRST:event_jTextField1KeyTyped int i = e.getKeyChar(); if (i==10){//The ENTER KEY // we display the google url. try{ URLDisplayer.getDefault().showURL(new URL("http://www.google.com/search?hl=en&q="+jTextField1.getText()+"&btnG=Google+Search"));//NOI18N } catch (Exception eee){ return;//nothing much to do } } }//GEN-LAST:event_jTextField1KeyTyped // Variables declaration - do not modify//GEN-BEGIN:variables public javax.swing.JLabel jLabel1; public javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables public String getGoogleText(){ return jTextField1.getText(); } }
3e0dcd98e7d173f5637bc5b136d74a400bc3770b
10,323
java
Java
spring-xd-dirt/src/main/java/org/springframework/xd/dirt/module/ModuleDeployer.java
wwjiang007/spring-xd
ec106725c51d245109b2e5055d9f65e43228ecc1
[ "Apache-2.0" ]
332
2015-01-03T23:47:23.000Z
2022-02-06T17:09:21.000Z
spring-xd-dirt/src/main/java/org/springframework/xd/dirt/module/ModuleDeployer.java
wwjiang007/spring-xd
ec106725c51d245109b2e5055d9f65e43228ecc1
[ "Apache-2.0" ]
518
2015-01-01T16:41:07.000Z
2021-06-18T13:47:43.000Z
spring-xd-dirt/src/main/java/org/springframework/xd/dirt/module/ModuleDeployer.java
wwjiang007/spring-xd
ec106725c51d245109b2e5055d9f65e43228ecc1
[ "Apache-2.0" ]
229
2015-01-03T23:47:31.000Z
2022-02-25T06:30:35.000Z
30.272727
118
0.721399
5,837
/* * Copyright 2013-2014 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 org.springframework.xd.dirt.module; import java.beans.Introspector; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.concurrent.GuardedBy; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.OrderComparator; import org.springframework.util.Assert; import org.springframework.xd.module.ModuleDeploymentProperties; import org.springframework.xd.module.ModuleDescriptor; import org.springframework.xd.module.core.Module; import org.springframework.xd.module.core.ModuleFactory; import org.springframework.xd.module.core.Plugin; /** * Handles the creation, deployment, and un-deployment of {@link Module modules}. * Appropriate {@link Plugin} logic is applied throughout the deployment/ * un-deployment lifecycle. * <p> * In order to initialize modules with the correct application context, * this class maintains a reference to the global application context. * See <a href="http://docs.spring.io/autorepo/docs/spring-xd/current/reference/html/#XD-Spring-Application-Contexts"> * the reference documentation</a> for more details. * * @author Mark Fisher * @author Gary Russell * @author Ilayaperumal Gopinathan * @author David Turanski * @author Patrick Peralta */ public class ModuleDeployer implements ApplicationContextAware, InitializingBean { /** * Logger. */ private final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * The container application context. */ private volatile ApplicationContext context; /** * The global top level application context. This is used as the parent * application context for loaded modules. */ private volatile ApplicationContext globalContext; /** * Map of deployed modules. Key is the group/deployment unit name, * value is a map of module index to module. */ @GuardedBy("this") private final Map<String, Map<Integer, Module>> deployedModules = new HashMap<String, Map<Integer, Module>>(); /** * List of registered plugins. */ @GuardedBy("this") private final List<Plugin> plugins = new ArrayList<Plugin>(); /** * Module factory for creating new {@link Module} instances. */ private final ModuleFactory moduleFactory; /** * Construct a ModuleDeployer. * * @param moduleFactory module factory for creating new {@link Module} instances */ public ModuleDeployer(ModuleFactory moduleFactory) { this.moduleFactory = moduleFactory; } /** * {@inheritDoc} * * @param context the container application context */ @Override public void setApplicationContext(ApplicationContext context) { this.context = context; ApplicationContext global = null; try { // TODO: evaluate // The application context hierarchy is arranged as such: // // Global Context // ^ // Shared Server Context // ^ // Plugin Context // ^ // Container Context // // The global context is supposed to be the parent // context for deployed modules which means the // context should be obtained via // context.getParent().getParent().getParent(). // However this is causing shell test failures; // in particular NoSuchBeanDefinitionExceptions // for aggregateCounterRepository, fieldValueCounterRepository, // counterRepository, etc. This should be further evaluated. // global = context.getParent().getParent().getParent(); global = context.getParent().getParent(); } catch (NullPointerException e) { logger.trace("Exception looking up global application context", e); // npe handled by assert below } Assert.notNull(global, "Global application context not found"); this.globalContext = global; } @Override public synchronized void afterPropertiesSet() { if (!plugins.isEmpty()) { plugins.clear(); } plugins.addAll(this.context.getParent().getBeansOfType(Plugin.class).values()); OrderComparator.sort(this.plugins); } /** * Return a read-only map of deployed modules. Key is the group/deployment * unit name, value is a map of module index to module. * * @return map of deployed modules */ public synchronized Map<String, Map<Integer, Module>> getDeployedModules() { Map<String, Map<Integer, Module>> map = new HashMap<String, Map<Integer, Module>>(); for (Map.Entry<String, Map<Integer, Module>> entry : this.deployedModules.entrySet()) { map.put(entry.getKey(), Collections.unmodifiableMap(entry.getValue())); } return Collections.unmodifiableMap(map); } /** * Create a module based on the provided {@link ModuleDescriptor} and * {@link ModuleDeploymentProperties}. * * @param moduleDescriptor descriptor for the module * @param deploymentProperties deployment related properties for the module * * @return new module instance */ public Module createModule(ModuleDescriptor moduleDescriptor, ModuleDeploymentProperties deploymentProperties) { return moduleFactory.createModule(moduleDescriptor, deploymentProperties); } /** * Deploy the given module to this container. This action includes * <ul> * <li>applying the appropriate plugins</li> * <li>setting the parent application context</li> * <li>starting the module</li> * <li>registering the module with this container</li> * </ul> * * @param module the module to deploy * @param descriptor descriptor for the module instance */ public synchronized void deploy(Module module, ModuleDescriptor descriptor) { String group = descriptor.getGroup(); module.setParentContext(this.globalContext); doDeploy(module); logger.info("Deployed {}", module); Map<Integer, Module> modules = this.deployedModules.get(group); if (modules == null) { modules = new HashMap<Integer, Module>(); this.deployedModules.put(group, modules); } modules.put(descriptor.getIndex(), module); } /** * Apply plugins to the module and start it. * * @param module module to deploy */ private void doDeploy(Module module) { preProcessModule(module); module.initialize(); postProcessModule(module); module.start(); } /** * Allow plugins to contribute properties (e.g. "stream.name") * calling {@link Module#addProperties(java.util.Properties)}, etc. */ private void preProcessModule(Module module) { for (Plugin plugin : getSupportedPlugins(module)) { plugin.preProcessModule(module); } } /** * Allow plugins to perform other configuration after the module * is initialized but before it is started. */ private void postProcessModule(Module module) { for (Plugin plugin : getSupportedPlugins(module)) { plugin.postProcessModule(module); } } /** * Shut down the module indicated by {@code moduleDescriptor} * and remove its registration from the container. Lifecycle * plugins are applied during undeployment. * * @param moduleDescriptor descriptor for module to be undeployed */ public synchronized void undeploy(ModuleDescriptor moduleDescriptor) { Introspector.flushCaches(); // This is to prevent classloader leakage String group = moduleDescriptor.getGroup(); int index = moduleDescriptor.getIndex(); Map<Integer, Module> modules = deployedModules.get(group); if (modules != null) { Module module = modules.remove(index); if (modules.isEmpty()) { deployedModules.remove(group); } if (module != null) { destroyModule(module); } else { logger.debug("Ignoring undeploy - module with index {} from group {} is not deployed", index, group); } } else { logger.trace("Ignoring undeploy - group not deployed here: {}", group); } } /** * Apply lifecycle plugins and shut down the module. * * @param module module to shut down and destroy */ private void destroyModule(Module module) { logger.info("Removed {}", module); beforeShutdown(module); module.stop(); removeModule(module); module.destroy(); } /** * Apply shutdown lifecycle plugins for the given module. * * @param module module to shutdown */ private void beforeShutdown(Module module) { for (Plugin plugin : getSupportedPlugins(module)) { try { plugin.beforeShutdown(module); } catch (IllegalStateException e) { logger.warn("Failed to invoke plugin {} during shutdown: {}", plugin.getClass().getSimpleName(), e.getMessage()); logger.debug("Full stack trace", e); } } } /** * Apply remove lifecycle plugins for the given module. * * @param module module that has been shutdown */ private void removeModule(Module module) { for (Plugin plugin : getSupportedPlugins(module)) { plugin.removeModule(module); } } /** * Return an {@link Iterable} over the list of supported plugins for the given module. * * @param module the module for which to obtain supported plugins * @return iterable of supported plugins for a module */ private Iterable<Plugin> getSupportedPlugins(Module module) { return Iterables.filter(this.plugins, new ModulePluginPredicate(module)); } /** * Predicate used to determine if a plugin supports a module. */ private class ModulePluginPredicate implements Predicate<Plugin> { private final Module module; private ModulePluginPredicate(Module module) { this.module = module; } @Override public boolean apply(Plugin plugin) { return plugin.supports(this.module); } } }
3e0dcda6c0dd0731ceec6d70d4cd4030aa47715b
3,299
java
Java
schema-compiler/src/main/java/org/opentravel/schemacompiler/transform/symbols/JaxbLibraryPrefixResolver.java
OpenTravel/OTM-DE-Compiler
9b6e8f71649ae9a1ba8bd7ee0e04bea546d20256
[ "Apache-2.0" ]
6
2015-10-22T16:07:01.000Z
2020-07-30T18:00:30.000Z
schema-compiler/src/main/java/org/opentravel/schemacompiler/transform/symbols/JaxbLibraryPrefixResolver.java
OpenTravel/OTM-DE-Compiler
9b6e8f71649ae9a1ba8bd7ee0e04bea546d20256
[ "Apache-2.0" ]
65
2015-03-16T13:46:43.000Z
2021-12-16T23:28:49.000Z
schema-compiler/src/main/java/org/opentravel/schemacompiler/transform/symbols/JaxbLibraryPrefixResolver.java
OpenTravel/OTM-DE-Compiler
9b6e8f71649ae9a1ba8bd7ee0e04bea546d20256
[ "Apache-2.0" ]
3
2018-06-13T09:20:52.000Z
2020-06-28T07:30:12.000Z
35.117021
117
0.680097
5,838
/** * Copyright (C) 2014 OpenTravel Alliance (ychag@example.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opentravel.schemacompiler.transform.symbols; import org.opentravel.schemacompiler.loader.LibraryModuleImport; import org.opentravel.schemacompiler.loader.LibraryModuleInfo; import org.opentravel.schemacompiler.transform.AnonymousEntityFilter; import org.opentravel.schemacompiler.transform.PrefixResolver; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * Prefix resolver that obtains its prefix mappings from a JAXB Library instance. * * @author S. Livezey */ public class JaxbLibraryPrefixResolver implements PrefixResolver { private Map<String,String> prefixMappings = new HashMap<>(); private String localNamespace; /** * Constructor that specifies the underlying library that defines the prefix mappings. * * @param libraryInfo the JAXB library instance that defines the prefix mappings * @throws IllegalArgumentException thrown if the instance provided is not recognized as a supported JAXB library */ public JaxbLibraryPrefixResolver(LibraryModuleInfo<?> libraryInfo) { for (LibraryModuleImport nsImport : libraryInfo.getImports()) { String prefix = nsImport.getPrefix(); String namespace = nsImport.getNamespace(); if ((prefix != null) && (prefix.length() > 0) && (namespace != null) && (namespace.length() > 0)) { prefixMappings.put( prefix, namespace ); } } localNamespace = libraryInfo.getNamespace(); } /** * @see org.opentravel.schemacompiler.transform.PrefixResolver#getLocalNamespace() */ @Override public String getLocalNamespace() { return localNamespace; } /** * @see org.opentravel.schemacompiler.transform.PrefixResolver#resolveNamespaceFromPrefix(java.lang.String) */ @Override public String resolveNamespaceFromPrefix(String prefix) { return prefixMappings.get( prefix ); } /** * @see org.opentravel.schemacompiler.transform.PrefixResolver#getPrefixForNamespace(java.lang.String) */ @Override public String getPrefixForNamespace(String namespace) { String prefix = null; if ((namespace != null) && (namespace.equals( localNamespace ) || namespace.equals( AnonymousEntityFilter.ANONYMOUS_PSEUDO_NAMESPACE ))) { prefix = ""; } else { for (Entry<String,String> entry : prefixMappings.entrySet()) { if (entry.getValue().equals( namespace )) { prefix = entry.getKey(); break; } } } return prefix; } }
3e0dce51f7e7b41caa7ff5cad9f03e34de7bbbc2
529
java
Java
src/main/java/com/github/lemonj/jedismock/operations/RO_exists.java
24kpure/jedis-mock
11cb3ff2ddf0d891d9c64a1e1f41d02813d18328
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/lemonj/jedismock/operations/RO_exists.java
24kpure/jedis-mock
11cb3ff2ddf0d891d9c64a1e1f41d02813d18328
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/lemonj/jedismock/operations/RO_exists.java
24kpure/jedis-mock
11cb3ff2ddf0d891d9c64a1e1f41d02813d18328
[ "Apache-2.0" ]
null
null
null
25.190476
53
0.688091
5,839
package com.github.lemonj.jedismock.operations; import com.github.lemonj.jedismock.server.Response; import com.github.lemonj.jedismock.server.Slice; import com.github.lemonj.jedismock.storage.RedisBase; import java.util.List; class RO_exists extends AbstractRedisOperation { RO_exists(RedisBase base, List<Slice> params) { super(base, params); } Slice response() { if (base().exists(params().get(0))) { return Response.integer(1); } return Response.integer(0); } }
3e0dce742de57a6fec56bbee35eadf4afdfaf429
2,547
java
Java
xap-extensions/xap-hibernate-spring/src/main/java/org/openspaces/persistency/hibernate/ManagedEntitiesContainer.java
dm-tro/xap
9ab2cf43861bcc0ba759db1c9805e82e0b77a02c
[ "Apache-2.0" ]
90
2016-08-09T16:37:44.000Z
2022-03-30T10:33:17.000Z
xap-extensions/xap-hibernate-spring/src/main/java/org/openspaces/persistency/hibernate/ManagedEntitiesContainer.java
dm-tro/xap
9ab2cf43861bcc0ba759db1c9805e82e0b77a02c
[ "Apache-2.0" ]
33
2016-10-10T17:29:11.000Z
2022-03-17T07:27:48.000Z
xap-extensions/xap-hibernate-spring/src/main/java/org/openspaces/persistency/hibernate/ManagedEntitiesContainer.java
dm-tro/xap
9ab2cf43861bcc0ba759db1c9805e82e0b77a02c
[ "Apache-2.0" ]
48
2016-08-09T15:55:20.000Z
2022-03-31T12:21:50.000Z
34.418919
112
0.708677
5,840
/* * Copyright (c) 2008-2016, GigaSpaces Technologies, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openspaces.persistency.hibernate; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.Metamodel; import org.hibernate.SessionFactory; import java.util.HashSet; import java.util.Set; import javax.persistence.metamodel.EntityType; /** * An managed entities container which is used by {@link AbstractHibernateSpaceDataSource} and * {@link AbstractHibernateSpaceSynchronizationEndpoint} based implementations. * * @author eitany * @since 9.5 */ public class ManagedEntitiesContainer { protected static final Log logger = LogFactory.getLog(ManagedEntitiesContainer.class); private final Set<String> managedEntries; public ManagedEntitiesContainer(SessionFactory sessionFactory, Set<String> managedEntries) { this.managedEntries = createManagedEntries(managedEntries, sessionFactory); } private static Set<String> createManagedEntries(Set<String> managedEntries, SessionFactory sessionFactory) { if (managedEntries == null) { managedEntries = new HashSet<String>(); // try and derive the managedEntries Metamodel metamodel = sessionFactory.getMetamodel(); Set<EntityType<?>> entities = metamodel.getEntities(); for (EntityType entityType : entities ) { if (entityType.getJavaType() == null) continue; String typeName = entityType.getJavaType().getName(); managedEntries.add( typeName ); } } if (logger.isDebugEnabled()) { logger.debug("Using Hibernate managedEntries [" + managedEntries + "]"); } return managedEntries; } public boolean isManagedEntry(String entityName) { return managedEntries.contains(entityName); } public Iterable<String> getManagedEntries() { return managedEntries; } }
3e0dcf00d09f6742247b55cd1cc62c057486f127
5,723
java
Java
src/main/java/seedu/address/ui/PersonCard.java
angkoonhwee/tp
4525db1be2dccef45a31fb9900fe3a3be02200d3
[ "MIT" ]
null
null
null
src/main/java/seedu/address/ui/PersonCard.java
angkoonhwee/tp
4525db1be2dccef45a31fb9900fe3a3be02200d3
[ "MIT" ]
null
null
null
src/main/java/seedu/address/ui/PersonCard.java
angkoonhwee/tp
4525db1be2dccef45a31fb9900fe3a3be02200d3
[ "MIT" ]
null
null
null
30.121053
114
0.598812
5,841
package seedu.address.ui; import java.util.Comparator; import java.util.Set; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import seedu.address.model.lesson.Lesson; import seedu.address.model.person.Person; /** * An UI component that displays information of a {@code Person}. */ public class PersonCard extends UiPart<Region> { private static final String FXML = "PersonListCard.fxml"; private static final int CELL_HEIGHT = 105; /** * Note: Certain keywords such as "location" and "resources" are reserved keywords in JavaFX. * As a consequence, UI elements' variable names cannot be set to such keywords * or an exception will be thrown by JavaFX during runtime. * * @see <a href="https://github.com/se-edu/addressbook-level4/issues/336">The issue on AddressBook level 4</a> */ public final Person person; @FXML private HBox cardPane; @FXML private Label id; @FXML private Label name; @FXML private Label phone; @FXML private Label email; @FXML private Label parentPhone; @FXML private Label parentEmail; @FXML private Label address; @FXML private Label outstandingFee; @FXML private Label school; @FXML private Label acadStream; @FXML private Label acadLevel; @FXML private Label remark; @FXML private FlowPane tags; @FXML private ListView<Lesson> lessonListView; /** * Creates a {@code PersonCode} with the given {@code Person} and index to display. */ public PersonCard(Person person, int displayedIndex) { super(FXML); this.person = person; id.setText(displayedIndex + ". "); name.setText(person.getName().fullName); address.setText("Address: " + person.getAddress().value); if (person.getPhone().isEmpty()) { phone.setManaged(false); } else { phone.setText("Phone: " + person.getPhone().value); } if (person.getEmail().isEmpty()) { email.setManaged(false); } else { email.setText("Email: " + person.getEmail().value); } if (person.getParentPhone().isEmpty()) { parentPhone.setManaged(false); } else { parentPhone.setText("Parent Phone: " + person.getParentPhone().value); } if (person.getParentEmail().isEmpty()) { parentEmail.setManaged(false); } else { parentEmail.setText("Parent Email: " + person.getParentEmail().value); } if (person.getSchool().isEmpty()) { school.setManaged(false); } else { school.setText("School: " + person.getSchool().value); } if (person.getAcadStream().isEmpty()) { acadStream.setManaged(false); } else { acadStream.setText("Academic Stream: " + person.getAcadStream().value); } if (person.getAcadLevel().isEmpty()) { acadLevel.setVisible(false); acadLevel.setManaged(false); } else { acadLevel.setText("Academic Level: " + person.getAcadLevel().value); } if (person.getRemark().isEmpty()) { remark.setManaged(false); } else { remark.setText("Remark: " + person.getRemark().value); } if (person.getFee().isEmpty()) { outstandingFee.setManaged(false); } else { outstandingFee.setText("Outstanding Fees: $" + person.getFee().value); } if (person.getTags().isEmpty()) { tags.setManaged(false); } else { person.getTags().stream() .sorted(Comparator.comparing(tag -> tag.tagName)) .forEach(tag -> tags.getChildren().add(new Label(tag.tagName))); } if (person.getLessons().isEmpty()) { lessonListView.setManaged(false); } else { setLessonListView(person.getLessons()); } } private void setLessonListView(Set<Lesson> lessons) { ObservableList<Lesson> lessonList = FXCollections.observableArrayList(); lessons.forEach(lesson -> lessonList.add(lesson)); lessonListView.setItems(lessonList); lessonListView.setCellFactory(listView -> new LessonListViewCell()); lessonListView.setPrefHeight(lessonList.size() == 0 ? 0 : CELL_HEIGHT); } @Override public boolean equals(Object other) { // short circuit if same object if (other == this) { return true; } // instanceof handles nulls if (!(other instanceof PersonCard)) { return false; } // state check PersonCard card = (PersonCard) other; return id.getText().equals(card.id.getText()) && person.equals(card.person); } /** * Custom {@code ListCell} that displays the graphics of a {@code Lesson} using a {@code LessonCard}. */ class LessonListViewCell extends ListCell<Lesson> { @Override protected void updateItem(Lesson lesson, boolean empty) { super.updateItem(lesson, empty); if (empty || lesson == null) { setGraphic(null); setText(null); } else { setGraphic(new LessonCard(lesson, getIndex() + 1).getRoot()); } } } }
3e0dcf9f239f952cf188ee27e40ec0b22220b54b
203
java
Java
app/src/main/java/io/github/yzernik/squeakand/OfferWithSqueakServer.java
yzernik/SqueakAnd
e5c2f9751e0e30e6e66888c11b4fe3f89add182d
[ "MIT" ]
null
null
null
app/src/main/java/io/github/yzernik/squeakand/OfferWithSqueakServer.java
yzernik/SqueakAnd
e5c2f9751e0e30e6e66888c11b4fe3f89add182d
[ "MIT" ]
24
2020-05-20T20:48:20.000Z
2020-07-16T09:38:41.000Z
app/src/main/java/io/github/yzernik/squeakand/OfferWithSqueakServer.java
yzernik/SqueakAnd
e5c2f9751e0e30e6e66888c11b4fe3f89add182d
[ "MIT" ]
null
null
null
13.533333
37
0.743842
5,842
package io.github.yzernik.squeakand; import androidx.room.Embedded; public class OfferWithSqueakServer { @Embedded public Offer offer; @Embedded public SqueakServer squeakServer; }
3e0dcfc5b1daca74e7c749c12b58fc1e645fa88b
2,967
java
Java
src/main/java/org/launchcode/my401k/controllers/FormChoicesController.java
Judy2001/my401k
8240bc47b7b94d537334e8f68b8dec9c0ff02918
[ "MIT" ]
null
null
null
src/main/java/org/launchcode/my401k/controllers/FormChoicesController.java
Judy2001/my401k
8240bc47b7b94d537334e8f68b8dec9c0ff02918
[ "MIT" ]
null
null
null
src/main/java/org/launchcode/my401k/controllers/FormChoicesController.java
Judy2001/my401k
8240bc47b7b94d537334e8f68b8dec9c0ff02918
[ "MIT" ]
null
null
null
43
121
0.637681
5,843
package org.launchcode.my401k.controllers; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import java.util.ArrayList; @Controller @RequestMapping(value = "investment_choices") public class FormChoicesController { static ArrayList<String> assetAllocation = new ArrayList<>(); static ArrayList<String> bonds = new ArrayList<>(); static ArrayList<String> global = new ArrayList<>(); static ArrayList<String> largeCap = new ArrayList<>(); static ArrayList<String> midCap = new ArrayList<>(); static ArrayList<String> smallCap = new ArrayList<>(); static ArrayList<String> specialty = new ArrayList<>(); static ArrayList<String> stableValue = new ArrayList<>(); @RequestMapping(value = "display_form", method = RequestMethod.GET) public String displayInvestmentChoicesForm(Model model) { model.addAttribute("title", "My 401k"); model.addAttribute("assetAllocation", assetAllocation); model.addAttribute("bonds", bonds); model.addAttribute("global", global); model.addAttribute("largeCap", largeCap); model.addAttribute("midCap", midCap); model.addAttribute("smallCap", smallCap); model.addAttribute("specialty", specialty); model.addAttribute("stableValue", stableValue); return "investment_choices/display_form"; } @RequestMapping(value = "process_form", method = RequestMethod.POST) public String processInvestmentChoicesForm(@RequestParam int userId, @RequestParam ArrayList<String> assetAllocation, @RequestParam ArrayList<String> bonds, @RequestParam ArrayList<String> global, @RequestParam ArrayList<String> largeCap, @RequestParam ArrayList<String> midCap, @RequestParam ArrayList<String> smallCap, @RequestParam ArrayList<String> specialty, @RequestParam ArrayList<String> stableValue, Model model) { model.addAttribute("title", "My 401k"); model.addAttribute("assetAllocation", assetAllocation); model.addAttribute("bonds", bonds); model.addAttribute("global", global); model.addAttribute("largeCap", largeCap); model.addAttribute("midCap", midCap); model.addAttribute("smallCap", smallCap); model.addAttribute("specialty", specialty); model.addAttribute("stableValue", stableValue); return "investment_choices/process_form"; } }
3e0dcff5227e352d22a07d92153f171a0d08dbc4
1,879
java
Java
itf-examples/src/test/java/com/soebes/itf/examples/MavenProjectRootIT.java
filiphr/maven-it-extension
431d8a99f7af658f91cc523d445c32e4ae958600
[ "Apache-2.0" ]
51
2019-10-29T20:46:08.000Z
2022-03-23T20:45:38.000Z
itf-examples/src/test/java/com/soebes/itf/examples/MavenProjectRootIT.java
filiphr/maven-it-extension
431d8a99f7af658f91cc523d445c32e4ae958600
[ "Apache-2.0" ]
243
2019-10-30T19:01:46.000Z
2022-03-31T22:30:54.000Z
itf-examples/src/test/java/com/soebes/itf/examples/MavenProjectRootIT.java
filiphr/maven-it-extension
431d8a99f7af658f91cc523d445c32e4ae958600
[ "Apache-2.0" ]
20
2020-03-04T13:11:37.000Z
2022-03-10T10:53:49.000Z
32.396552
66
0.760511
5,844
package com.soebes.itf.examples; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.soebes.itf.jupiter.extension.MavenGoal; import com.soebes.itf.jupiter.extension.MavenJupiterExtension; import com.soebes.itf.jupiter.extension.MavenProject; import com.soebes.itf.jupiter.extension.MavenTest; import com.soebes.itf.jupiter.maven.MavenExecutionResult; import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.TestMethodOrder; @MavenJupiterExtension @MavenProject("test_project_root") @TestMethodOrder(OrderAnnotation.class) class MavenProjectRootIT { @MavenTest @MavenGoal("clean") @Order(10) void basic(MavenExecutionResult result) { System.out.println("(basic) result = " + result); } @MavenTest @MavenGoal("install") @Order(20) void packaging_includes(MavenExecutionResult result) { System.out.println("(packaging_includes) result = " + result); } @MavenTest @MavenGoal("verify") @Order(30) void a_third_part(MavenExecutionResult result) { System.out.println("(basic) result = " + result); } }
3e0dcff5f7a376f21c4c227ae5d7aef6710c4c61
366
java
Java
src/main/java/me/nithanim/gw2api/v2/api/traits/facttypes/ComboFieldFact.java
Nithanim/gw2api
e087992cb4b4e511a05f7784e93beed5e04fb134
[ "Apache-2.0" ]
10
2015-10-15T15:29:18.000Z
2020-08-11T22:10:55.000Z
src/main/java/me/nithanim/gw2api/v2/api/traits/facttypes/ComboFieldFact.java
Nithanim/gw2api
e087992cb4b4e511a05f7784e93beed5e04fb134
[ "Apache-2.0" ]
21
2015-10-15T15:40:46.000Z
2022-01-31T17:07:02.000Z
src/main/java/me/nithanim/gw2api/v2/api/traits/facttypes/ComboFieldFact.java
Nithanim/gw2api
e087992cb4b4e511a05f7784e93beed5e04fb134
[ "Apache-2.0" ]
8
2015-09-16T20:29:13.000Z
2022-01-28T23:03:06.000Z
24.4
79
0.751366
5,845
package me.nithanim.gw2api.v2.api.traits.facttypes; import me.nithanim.gw2api.v2.api.traits.FactBase; @lombok.NoArgsConstructor @lombok.Getter @lombok.ToString public class ComboFieldFact extends FactBase { private FieldType fieldType; public static enum FieldType { AIR, DARK, FIRE, ICE, LIGHT, LIGHTNING, POISON, SMOKE, ETHEREAL, WATER; } }
3e0dd03b5a9237554be22c1bd8dc53b74df95aaa
697
java
Java
src/main/java/com/snapscore/pipeline/textsearch/FullTextSearchableItem.java
snapscoregroup/pipeline
57f9f7a2adff8c75965f082c5fbba99ae99a7e67
[ "Apache-2.0" ]
null
null
null
src/main/java/com/snapscore/pipeline/textsearch/FullTextSearchableItem.java
snapscoregroup/pipeline
57f9f7a2adff8c75965f082c5fbba99ae99a7e67
[ "Apache-2.0" ]
3
2021-03-15T16:19:13.000Z
2021-10-15T12:47:15.000Z
src/main/java/com/snapscore/pipeline/textsearch/FullTextSearchableItem.java
snapscoregroup/pipeline
57f9f7a2adff8c75965f082c5fbba99ae99a7e67
[ "Apache-2.0" ]
1
2021-12-30T10:47:09.000Z
2021-12-30T10:47:09.000Z
34.85
166
0.710187
5,846
package com.snapscore.pipeline.textsearch; import java.util.Collection; public interface FullTextSearchableItem { /** * @return the name by which this item can be looked up; The user of this should not perform any splitting of the names by spaces. This is handled by the library. * Example: for the stage "UEFA" we might want to return a list like this ["UEFA", "UEFA Champions League"] */ Collection<String> getSearchableNames(); /** * @return unique item identifier by which the item can be identifier when it needs to be removed from the TrieBasedCache * IMPORTANT: can return null, client code needs to check !!! */ String getIdentifier(); }
3e0dd0721f75e58f9bc0d21f6067911dd2fdc5c3
693
java
Java
bizcore/WEB-INF/contact_core_src/com/doublechain/contact/iamservice/LoginTarget.java
golap-cn/contact-web-app
b50bf66a6852b8caceaf300d35aaa38761b491cc
[ "MIT" ]
null
null
null
bizcore/WEB-INF/contact_core_src/com/doublechain/contact/iamservice/LoginTarget.java
golap-cn/contact-web-app
b50bf66a6852b8caceaf300d35aaa38761b491cc
[ "MIT" ]
null
null
null
bizcore/WEB-INF/contact_core_src/com/doublechain/contact/iamservice/LoginTarget.java
golap-cn/contact-web-app
b50bf66a6852b8caceaf300d35aaa38761b491cc
[ "MIT" ]
null
null
null
14.744681
55
0.751804
5,847
package com.doublechain.contact.iamservice; import com.doublechain.contact.secuser.SecUser; import com.doublechain.contact.userapp.UserApp; public class LoginTarget { protected SecUser secUser; protected UserApp userApp; protected Object additionalInfo; public SecUser getSecUser() { return secUser; } public void setSecUser(SecUser secUser) { this.secUser = secUser; } public UserApp getUserApp() { return userApp; } public void setUserApp(UserApp userApp) { this.userApp = userApp; } public Object getAdditionalInfo() { return additionalInfo; } public void setAdditionalInfo(Object additionalInfo) { this.additionalInfo = additionalInfo; } }
3e0dd17078d90381588c3b35e96a9651c091c243
2,290
java
Java
api-boot-samples/api-boot-sample-integration/src/main/java/org/minbox/framework/knowledge/library/service/wx/controller/SmallProgramLoginController.java
sufann/api-boot
bda2b31a1aa1166e8b58db527123f03faa1f58ed
[ "Apache-2.0" ]
310
2019-03-13T09:38:37.000Z
2020-10-10T08:33:05.000Z
api-boot-samples/api-boot-sample-integration/src/main/java/org/minbox/framework/knowledge/library/service/wx/controller/SmallProgramLoginController.java
sufann/api-boot
bda2b31a1aa1166e8b58db527123f03faa1f58ed
[ "Apache-2.0" ]
34
2019-10-02T15:36:37.000Z
2021-04-22T09:16:53.000Z
api-boot-samples/api-boot-sample-integration/src/main/java/org/minbox/framework/knowledge/library/service/wx/controller/SmallProgramLoginController.java
sufann/api-boot
bda2b31a1aa1166e8b58db527123f03faa1f58ed
[ "Apache-2.0" ]
95
2019-03-14T01:41:34.000Z
2021-09-15T03:15:31.000Z
36.349206
114
0.760699
5,848
package org.minbox.framework.knowledge.library.service.wx.controller; import com.alibaba.fastjson.JSON; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import org.minbox.framework.api.boot.common.model.ApiBootResult; import org.minbox.framework.knowledge.library.common.tools.HttpClientTools; import org.minbox.framework.knowledge.library.service.constants.UrlPrefix; import org.minbox.framework.knowledge.library.service.wx.model.SmallProgramLoginResult; import org.minbox.framework.knowledge.library.service.wx.properties.SmallProgramProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * 小程序登录控制器 * * @author:恒宇少年 - 于起宇 * <p> * DateTime:2019-04-11 14:26 * Blog:http://blog.yuqiyu.com * WebSite:http://www.jianshu.com/u/092df3f77bca * Gitee:https://gitee.com/hengboy * GitHub:https://github.com/hengboy */ @RestController @RequestMapping(value = UrlPrefix.SMALL_PROGRAM_LOGIN) @Api(tags = "小程序登录信息") public class SmallProgramLoginController { /** * 小程序属性配置 */ @Autowired private SmallProgramProperties smallProgramProperties; /** * 通过JsCode兑换小程序用户信息 * * @param code jsCode * @return */ @GetMapping(value = "/{code}") @ApiOperation(value = "JsCode兑换OpenID", response = SmallProgramLoginResult.class) @ApiImplicitParam(name = "code", value = "JsCode") @ApiResponse(code = 200, message = "转换成功", response = SmallProgramLoginResult.class) public ApiBootResult getOpenId(@PathVariable String code) { // 格式化请求地址 String toSessionUrl = String.format(smallProgramProperties.getCodeToSessionUrl(), code); // 执行发送请求 String result = HttpClientTools.get(toSessionUrl); // 转换请求结果 SmallProgramLoginResult smallProgramLoginResult = JSON.parseObject(result, SmallProgramLoginResult.class); return ApiBootResult.builder().data(smallProgramLoginResult).build(); } }
3e0dd2068c4a93125ff34f0c894adc475d5c09d4
5,157
java
Java
src/lib_gen/TransitionDefinition.java
dgatto/LipiDex
13a71b0f34ec03bd5155231c055c80160ef25218
[ "MIT" ]
9
2018-01-26T22:46:30.000Z
2021-12-10T18:39:33.000Z
src/lib_gen/TransitionDefinition.java
dgatto/LipiDex
13a71b0f34ec03bd5155231c055c80160ef25218
[ "MIT" ]
4
2018-05-02T12:37:54.000Z
2019-09-06T14:19:54.000Z
src/lib_gen/TransitionDefinition.java
dgatto/LipiDex
13a71b0f34ec03bd5155231c055c80160ef25218
[ "MIT" ]
6
2018-05-10T06:50:56.000Z
2021-07-16T17:06:01.000Z
24.098131
145
0.69013
5,849
package lib_gen; //Represents a peak in the MS2 spectra public class TransitionDefinition extends Utilities implements Comparable<Transition> { Double mass; //Mass of fragment if applicable Double relativeIntensity; //Relative intensity scaled to 1000 String formula; //Elemental formula public String displayName; //Display name for Jtree display boolean isFormula; //Boolean if a formula was supplied Integer charge; //Charge on transition String massFormula; //String to store supplied mass/formula string String type; //String to store supplied type TransitionType typeObject; //Transition type object public TransitionDefinition(String massFormula, Double relIntensity, String displayName, String type, Integer charge, TransitionType typeObject) { //Initialize blank variables mass = -1.0; formula = ""; this.type = type; this.charge = 1; this.typeObject = typeObject; //Initialize paramaterized variables relativeIntensity = relIntensity; this.displayName = parseDisplayName(displayName); this.charge = charge; //Parse massFormula field parseMassFormula(massFormula); //Update mass and formula field if applicable updateMassFormula(); } public String getType() { return type; } public TransitionType getTypeObject() { return typeObject; } public void updateMassFormula() { //If a formula if (isFormula) { this.mass = calculateMassFromFormula(massFormula); this.formula = massFormula; } //If not a formula else { this.mass = Double.valueOf(massFormula); } } //Check mass formula for correct declaration @SuppressWarnings("unused") public void parseMassFormula(String massFormula) { boolean formula = false; for (int i=0; i<elements.length; i++) { if (massFormula.contains(elements[i])) formula = true; } if (massFormula.equals("-")) formula = true; //Check mass validity if (!formula) { try { this.isFormula = false; Double massDouble = Double.parseDouble(massFormula); this.massFormula = massFormula; } catch (Exception e) { CustomError e1 = new CustomError(massFormula+" is not a valid mass", null); } } //Check formula validity else { try { this.isFormula = true; validElementalFormula(massFormula); this.massFormula = massFormula; this.formula = massFormula; } catch(Exception e) { CustomError e1 = new CustomError(massFormula+" is not a valid elemental formula", null); } } } public void updateValues(Double relInt, String massFormula, String type, String charge) throws CustomException { try { //Update charge this.charge = Integer.valueOf(charge); //Parse massFormula field parseMassFormula(massFormula); //Update relative intensity this.relativeIntensity = relInt; //Update type this.type = type; //Reparse display name this.displayName = parseDisplayName(massFormula+","+relInt+","+charge+","+type); //Update mass and formula field if applicable updateMassFormula(); } catch (Exception e) { CustomError ce = new CustomError("Error updating entry. Please check formatting", null); } } //Format transition for display in tree public String parseDisplayName(String name) { String result = ""; String[] split; if (name.contains(",")) { split = name.split(","); if (split[0].contains(".")) split[0] = String.valueOf(Math.round (Double.valueOf(split[0]) * 10000.0) / 10000.0); result += String.format("%1$-" + 20 + "s", split[0]); result += String.format("%1$-" + 5 + "s", Math.round(relativeIntensity)); result += String.format("%1$-" + 3 + "s", charge); result += split[3]; } else { split = name.split(" +"); if (split[0].contains(".")) split[0] = String.valueOf(Math.round (Double.valueOf(split[0]) * 10000.0) / 10000.0); result += String.format("%1$-" + 20 + "s", split[0]); result += String.format("%1$-" + 5 + "s", Math.round(relativeIntensity)); result += String.format("%1$-" + 3 + "s", charge); result += split[3]; } return result; } //Adds elemental formula to transition public void addFormula(String formula) { this.formula = formula; } //Returns elemental formula public String getFormula() { return formula; } //Returns mass as double public Double getMass() { return mass; } //Returns relative intensity public Double getRelativeIntensity() { return relativeIntensity; } //Calculate elemental formula for transitions based on precursor formula public void calculateElementalComposition(String precursorFormula) { addFormula(annotateMassWithMZTolerance(mass, precursorFormula)); if (!formula.equals("")) mass = calculateMassFromFormula(formula); } //Returns string representation of transition public String toString() { String result = ""; result = massFormula+","+relativeIntensity+","+charge+","+type; return result; } //Comparator for sorting by intensity public int compareTo(Transition t2) { if (t2.getIntensity()>relativeIntensity) return 1; else if (t2.getIntensity()<relativeIntensity) return -1; return 0; } }
3e0dd269d60b7bbdafc5cd24cecc63f8dd1e968d
3,897
java
Java
tikv-client/src/main/java/com/pingcap/tikv/expression/PartitionPruner.java
purelind/tispark
7154ce36c5f0d320cf0657e49213334f6e64d049
[ "Apache-2.0" ]
834
2017-07-07T03:30:38.000Z
2022-03-28T03:39:13.000Z
tikv-client/src/main/java/com/pingcap/tikv/expression/PartitionPruner.java
purelind/tispark
7154ce36c5f0d320cf0657e49213334f6e64d049
[ "Apache-2.0" ]
1,738
2017-07-06T10:42:57.000Z
2022-03-31T10:32:18.000Z
tikv-client/src/main/java/com/pingcap/tikv/expression/PartitionPruner.java
purelind/tispark
7154ce36c5f0d320cf0657e49213334f6e64d049
[ "Apache-2.0" ]
241
2017-07-24T08:28:44.000Z
2022-03-29T07:31:31.000Z
36.420561
98
0.68078
5,850
/* * Copyright 2020 PingCAP, 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, * See the License for the specific language governing permissions and * limitations under the License. */ package com.pingcap.tikv.expression; import com.pingcap.tikv.meta.TiPartitionDef; import com.pingcap.tikv.meta.TiPartitionInfo; import com.pingcap.tikv.meta.TiPartitionInfo.PartitionType; import com.pingcap.tikv.meta.TiTableInfo; import com.pingcap.tikv.parser.TiParser; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class PartitionPruner { public static List<Expression> extractLogicalOrComparisonExpr(List<Expression> filters) { List<Expression> filteredFilters = new ArrayList<>(); for (Expression expr : filters) { if (expr instanceof LogicalBinaryExpression || expr instanceof ComparisonBinaryExpression) { filteredFilters.add(expr); } } return filteredFilters; } public static List<TiPartitionDef> prune(TiTableInfo tableInfo, List<Expression> filters) { PartitionType type = tableInfo.getPartitionInfo().getType(); if (!tableInfo.isPartitionEnabled()) { return tableInfo.getPartitionInfo().getDefs(); } boolean isRangeCol = Objects.requireNonNull(tableInfo.getPartitionInfo().getColumns()).size() > 0; switch (type) { case RangePartition: if (!isRangeCol) { // TiDB only supports partition pruning on range partition on single column // If we meet range partition on multiple columns, we simply return all parts. if (tableInfo.getPartitionInfo().getColumns().size() > 1) { return tableInfo.getPartitionInfo().getDefs(); } RangePartitionPruner prunner = new RangePartitionPruner(tableInfo); return prunner.prune(filters); } else { RangeColumnPartitionPruner pruner = new RangeColumnPartitionPruner(tableInfo); return pruner.prune(filters); } case ListPartition: case HashPartition: return tableInfo.getPartitionInfo().getDefs(); } throw new UnsupportedOperationException("cannot prune under invalid partition table"); } static void generateRangeExprs( TiPartitionInfo partInfo, List<Expression> partExprs, TiParser parser, String partExprStr, int lessThanIdx) { // partExprColRefs.addAll(PredicateUtils.extractColumnRefFromExpression(partExpr)); for (int i = 0; i < partInfo.getDefs().size(); i++) { TiPartitionDef pDef = partInfo.getDefs().get(i); String current = pDef.getLessThan().get(lessThanIdx); String leftHand; if (current.equals("MAXVALUE")) { leftHand = "true"; } else { leftHand = String.format("%s < %s", wrapColumnName(partExprStr), current); } if (i == 0) { partExprs.add(parser.parseExpression(leftHand)); } else { String previous = partInfo.getDefs().get(i - 1).getLessThan().get(lessThanIdx); String and = String.format("%s >= %s and %s", wrapColumnName(partExprStr), previous, leftHand); partExprs.add(parser.parseExpression(and)); } } } private static String wrapColumnName(String columnName) { if (columnName.startsWith("`") && columnName.endsWith("`")) { return columnName; } else if (columnName.contains("(") && columnName.contains(")")) { // function not column name, e.g. year(columnName) return columnName; } else { return String.format("`%s`", columnName); } } }
3e0dd27d077463f4f14f9711955b5bfb9f0d2f32
2,186
java
Java
asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerExceptionTest.java
sharmajiii/so
174f48bee127c51f98ec6054f72be7567e0d8073
[ "Apache-2.0" ]
16
2018-05-04T20:47:02.000Z
2021-10-15T15:01:14.000Z
asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerExceptionTest.java
sharmajiii/so
174f48bee127c51f98ec6054f72be7567e0d8073
[ "Apache-2.0" ]
4
2020-07-28T01:56:20.000Z
2021-02-10T09:01:46.000Z
asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerExceptionTest.java
sharmajiii/so
174f48bee127c51f98ec6054f72be7567e0d8073
[ "Apache-2.0" ]
22
2018-06-13T01:40:03.000Z
2022-03-22T10:06:08.000Z
42.862745
108
0.655078
5,851
/*- * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= */ package org.onap.so.asdc.client.exceptions; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import org.junit.Test; public class ArtifactInstallerExceptionTest { private String exceptionMessage = "test message for exception"; private String throwableMessage = "separate throwable that caused asdcDownloadException"; @Test public void asdcParametersExceptionTest() { ArtifactInstallerException asdcDownloadException = new ArtifactInstallerException(exceptionMessage); Exception expectedException = new Exception(exceptionMessage); assertThat(asdcDownloadException, sameBeanAs(expectedException)); } @Test public void asdcParametersExceptionThrowableTest() { Throwable throwableCause = new Throwable(throwableMessage); ArtifactInstallerException asdcDownloadException = new ArtifactInstallerException(exceptionMessage, throwableCause); Exception expectedException = new Exception(exceptionMessage, new Throwable(throwableMessage)); assertThat(asdcDownloadException, sameBeanAs(expectedException)); } }
3e0dd2886fbbb80682a2f611dc7921c6234b92b7
1,031
java
Java
src/main/java/ode/vertex/conf/helper/GraphInputOutputFactory.java
DrChainsaw/neuralODE4j
a7de829302a4c527ff49cb10fe4e90906956a9cc
[ "MIT" ]
7
2018-12-28T02:34:09.000Z
2019-04-22T08:06:28.000Z
src/main/java/ode/vertex/conf/helper/GraphInputOutputFactory.java
DrChainsaw/neuralODE4j
a7de829302a4c527ff49cb10fe4e90906956a9cc
[ "MIT" ]
10
2018-12-27T23:21:23.000Z
2019-04-24T21:41:37.000Z
src/main/java/ode/vertex/conf/helper/GraphInputOutputFactory.java
DrChainsaw/neuralODE4j
a7de829302a4c527ff49cb10fe4e90906956a9cc
[ "MIT" ]
1
2018-12-28T02:34:33.000Z
2018-12-28T02:34:33.000Z
31.242424
119
0.722599
5,852
package ode.vertex.conf.helper; import ode.vertex.impl.helper.GraphInputOutput; import org.deeplearning4j.nn.conf.inputs.InputType; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.shade.jackson.annotation.JsonTypeInfo; /** * Factory for {@link GraphInputOutput} * * @author Christian Skarby */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public interface GraphInputOutputFactory { /** * Create a new {@link GraphInputOutput} for the given input * * @param input input, typically activations from previous vertices * @return a new {@link GraphInputOutput} */ GraphInputOutput create(INDArray[] input); GraphInputOutputFactory clone(); /** * Returns the input types to the graph. Typically a matter of either adding one extra element for the time or not. * @param vertexInputs Inputs to vertex * @return InputTypes to use in graph */ InputType[] getInputType(InputType ... vertexInputs); }
3e0dd4b9b000b255b0c7dbf8171c30f1051b3258
11,218
java
Java
src/test/java/org/iq80/snappy/SnappyStreamTest.java
vsosrc/snappy
aff4f0dd2b9c19d0d103c1fae372e17da1e28a45
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/test/java/org/iq80/snappy/SnappyStreamTest.java
vsosrc/snappy
aff4f0dd2b9c19d0d103c1fae372e17da1e28a45
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/test/java/org/iq80/snappy/SnappyStreamTest.java
vsosrc/snappy
aff4f0dd2b9c19d0d103c1fae372e17da1e28a45
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
33.891239
126
0.643163
5,853
/* * Copyright (C) 2011 the original author or authors. * See the notice.md file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.iq80.snappy; import com.google.common.base.Charsets; import com.google.common.io.Files; import org.testng.annotations.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.Arrays; import static com.google.common.io.ByteStreams.toByteArray; import static com.google.common.primitives.UnsignedBytes.toInt; import static org.iq80.snappy.SnappyOutputStream.STREAM_HEADER; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class SnappyStreamTest { @Test public void testSimple() throws Exception { byte[] original = "aaaaaaaaaaaabbbbbbbaaaaaa".getBytes(Charsets.UTF_8); byte[] compressed = compress(original); byte[] uncompressed = uncompress(compressed); assertEquals(uncompressed, original); assertEquals(compressed.length, 33); // 7 byte stream header, 7 byte block header, 19 bytes compressed data assertEquals(Arrays.copyOf(compressed, 7), STREAM_HEADER); // stream header assertEquals(toInt(compressed[7]), 0x01); // flag: compressed assertEquals(toInt(compressed[8]), 0x00); // length: 19 = 0x0013 assertEquals(toInt(compressed[9]), 0x13); assertEquals(toInt(compressed[10]), 0x92); // crc32c: 0x9274cda8 assertEquals(toInt(compressed[11]), 0x74); assertEquals(toInt(compressed[12]), 0xCD); assertEquals(toInt(compressed[13]), 0xA8); } @Test public void testLargeWrites() throws Exception { byte[] random = getRandom(0.5, 500000); ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStream snappyOut = new SnappyOutputStream(out); // partially fill buffer int small = 1000; snappyOut.write(random, 0, small); // write more than the buffer size snappyOut.write(random, small, random.length - small); // get compressed data snappyOut.close(); byte[] compressed = out.toByteArray(); assertTrue(compressed.length < random.length); // decompress byte[] uncompressed = uncompress(compressed); assertEquals(uncompressed, random); // decompress byte at a time SnappyInputStream in = new SnappyInputStream(new ByteArrayInputStream(compressed)); int i = 0; int c; while ((c = in.read()) != -1) { uncompressed[i++] = (byte) c; } assertEquals(i, random.length); assertEquals(uncompressed, random); } @Test public void testSingleByteWrites() throws Exception { byte[] random = getRandom(0.5, 500000); ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStream snappyOut = new SnappyOutputStream(out); for (byte b : random) { snappyOut.write(b); } snappyOut.close(); byte[] compressed = out.toByteArray(); assertTrue(compressed.length < random.length); byte[] uncompressed = uncompress(compressed); assertEquals(uncompressed, random); } @Test public void testExtraFlushes() throws Exception { byte[] random = getRandom(0.5, 500000); ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStream snappyOut = new SnappyOutputStream(out); snappyOut.write(random); for (int i = 0; i < 10; i++) { snappyOut.flush(); } snappyOut.close(); byte[] compressed = out.toByteArray(); assertTrue(compressed.length < random.length); byte[] uncompressed = uncompress(compressed); assertEquals(uncompressed, random); } @Test public void testUncompressable() throws Exception { byte[] random = getRandom(1, 5000); int crc32c = Crc32C.maskedCrc32c(random); byte[] compressed = compress(random); byte[] uncompressed = uncompress(compressed); assertEquals(uncompressed, random); assertEquals(compressed.length, random.length + 7 + 7); assertEquals(toInt(compressed[7]), 0x00); // flag: uncompressed assertEquals(toInt(compressed[8]), 0x13); // length: 5000 = 0x1388 assertEquals(toInt(compressed[9]), 0x88); assertEquals(ByteBuffer.wrap(compressed, 10, 4).getInt(), crc32c); // crc: see above } @Test public void testUncompressableRange() throws Exception { int max = 35000; byte[] random = getRandom(1, max); for (int i = 1; i <= max; i++) { byte[] original = Arrays.copyOfRange(random, 0, i); byte[] compressed = compress(original); byte[] uncompressed = uncompress(compressed); // Stream header plus one or two blocks int overhead = 7 + ((i <= 32768) ? 7 : 14); assertEquals(uncompressed, original); assertEquals(compressed.length, original.length + overhead); } } @Test public void testByteForByteTestData() throws Exception { for (File testFile : SnappyTest.getTestFiles()) { byte[] original = Files.toByteArray(testFile); byte[] compressed = compress(original); byte[] uncompressed = uncompress(compressed); assertEquals(uncompressed, original); } } @Test public void testEmptyCompression() throws Exception { byte[] empty = new byte[0]; assertEquals(compress(empty), STREAM_HEADER); assertEquals(uncompress(STREAM_HEADER), empty); } @Test(expectedExceptions = EOFException.class, expectedExceptionsMessageRegExp = ".*stream header.*") public void testEmptyStream() throws Exception { uncompress(new byte[0]); } @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "invalid stream header") public void testInvalidStreamHeader() throws Exception { uncompress(new byte[] {'b', 0, 0, 'g', 'u', 's', 0}); } @Test(expectedExceptions = EOFException.class, expectedExceptionsMessageRegExp = ".*block header.*") public void testShortBlockHeader() throws Exception { uncompressBlock(new byte[]{0}); } @Test(expectedExceptions = EOFException.class, expectedExceptionsMessageRegExp = ".*block data.*") public void testShortBlockData() throws Exception { uncompressBlock(new byte[]{0, 0, 4, 0, 0, 0, 0, 'x', 'x'}); // flag = 0, size = 4, crc32c = 0, block data = [x, x] } @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "invalid compressed flag in header: 0x41") public void testInvalidBlockHeaderCompressedFlag() throws Exception { uncompressBlock(new byte[]{'A', 0, 1, 0, 0, 0, 0, 0}); // flag = 'A', block size = 1, crc32c = 0 } @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "invalid block size in header: 0") public void testInvalidBlockSizeZero() throws Exception { uncompressBlock(new byte[]{0, 0, 0, 0, 0, 0, 0}); // flag = '0', block size = 0, crc32c = 0 } @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "invalid block size in header: 55555") public void testInvalidBlockSizeLarge() throws Exception { uncompressBlock(new byte[]{0, (byte) 0xD9, 0x03, 0, 0, 0, 0}); // flag = 0, block size = 55555, crc32c = 0 } @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "Corrupt input: invalid checksum") public void testInvalidChecksum() throws Exception { uncompressBlock(new byte[]{0, 0, 1, 0, 0, 0, 0, 'a'}); // flag = 0, size = 4, crc32c = 0, block data = [a] } @Test public void testInvalidChecksumIgnoredWhenVerificationDisabled() throws Exception { byte[] block = {0, 0, 1, 0, 0, 0, 0, 'a'}; // flag = 0, size = 4, crc32c = 0, block data = [a] ByteArrayInputStream inputData = new ByteArrayInputStream(blockToStream(block)); assertEquals(toByteArray(new SnappyInputStream(inputData, false)), new byte[] {'a'}); } @Test public void testCloseIsIdempotent() throws Exception { byte[] random = getRandom(0.5, 500000); ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStream snappyOut = new SnappyOutputStream(out); snappyOut.write(random); snappyOut.close(); snappyOut.close(); byte[] compressed = out.toByteArray(); InputStream snappyIn = new SnappyInputStream(new ByteArrayInputStream(compressed)); byte[] uncompressed = toByteArray(snappyIn); assertEquals(uncompressed, random); snappyIn.close(); snappyIn.close(); } private static byte[] getRandom(double compressionRatio, int length) { SnappyTest.RandomGenerator gen = new SnappyTest.RandomGenerator(compressionRatio); gen.getNextPosition(length); byte[] random = Arrays.copyOf(gen.data, length); assertEquals(random.length, length); return random; } private static byte[] compress(byte[] original) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStream snappyOut = new SnappyOutputStream(out); snappyOut.write(original); snappyOut.close(); return out.toByteArray(); } private static byte[] uncompressBlock(byte[] block) throws IOException { return uncompress(blockToStream(block)); } private static byte[] blockToStream(byte[] block) { byte[] stream = new byte[STREAM_HEADER.length + block.length]; System.arraycopy(STREAM_HEADER, 0, stream, 0, STREAM_HEADER.length); System.arraycopy(block, 0, stream, STREAM_HEADER.length, block.length); return stream; } private static byte[] uncompress(byte[] compressed) throws IOException { return toByteArray(new SnappyInputStream(new ByteArrayInputStream(compressed))); } }
3e0dd5eb0ed6e49fa6eecfd0a10486e5fb2b0c24
11,313
java
Java
mahout/core/src/main/java/org/apache/mahout/math/hadoop/DistributedRowMatrix.java
Programming-Systems-Lab/kabu
652815e7b003d9899d68807632207147a1fd743f
[ "MIT" ]
15
2015-02-27T17:14:52.000Z
2018-03-27T10:13:24.000Z
core/src/main/java/org/apache/mahout/math/hadoop/DistributedRowMatrix.java
twitter-forks/mahout
16ea0f3d3b011d9a8f0565b238c26b2311925325
[ "Apache-2.0" ]
7
2020-06-30T23:10:31.000Z
2022-02-01T00:59:53.000Z
core/src/main/java/org/apache/mahout/math/hadoop/DistributedRowMatrix.java
twitter/mahout
16ea0f3d3b011d9a8f0565b238c26b2311925325
[ "Apache-2.0" ]
25
2015-01-07T16:00:14.000Z
2018-02-24T15:36:48.000Z
33.770149
116
0.621674
5,854
/** * 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.mahout.math.hadoop; import com.google.common.base.Function; import com.google.common.collect.Iterators; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.mahout.common.Pair; import org.apache.mahout.common.iterator.sequencefile.PathFilters; import org.apache.mahout.common.iterator.sequencefile.PathType; import org.apache.mahout.common.iterator.sequencefile.SequenceFileDirIterator; import org.apache.mahout.math.CardinalityException; import org.apache.mahout.math.MatrixSlice; import org.apache.mahout.math.Vector; import org.apache.mahout.math.VectorIterable; import org.apache.mahout.math.VectorWritable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Iterator; /** * DistributedRowMatrix is a FileSystem-backed VectorIterable in which the vectors live in a * SequenceFile<WritableComparable,VectorWritable>, and distributed operations are executed as M/R passes on * Hadoop. The usage is as follows: <p> * <p> * <pre> * // the path must already contain an already created SequenceFile! * DistributedRowMatrix m = new DistributedRowMatrix("path/to/vector/sequenceFile", "tmp/path", 10000000, 250000); * m.setConf(new Configuration()); * // now if we want to multiply a vector by this matrix, it's dimension must equal the row dimension of this * // matrix. If we want to timesSquared() a vector by this matrix, its dimension must equal the column dimension * // of the matrix. * Vector v = new DenseVector(250000); * // now the following operation will be done via a M/R pass via Hadoop. * Vector w = m.timesSquared(v); * </pre> * */ public class DistributedRowMatrix implements VectorIterable, Configurable { public static final String KEEP_TEMP_FILES = "DistributedMatrix.keep.temp.files"; private static final Logger log = LoggerFactory.getLogger(DistributedRowMatrix.class); private final Path inputPath; private final Path outputTmpPath; private Configuration conf; private Path rowPath; private Path outputTmpBasePath; private final int numRows; private final int numCols; private boolean keepTempFiles; public DistributedRowMatrix(Path inputPath, Path outputTmpPath, int numRows, int numCols) { this(inputPath, outputTmpPath, numRows, numCols, false); } public DistributedRowMatrix(Path inputPath, Path outputTmpPath, int numRows, int numCols, boolean keepTempFiles) { this.inputPath = inputPath; this.outputTmpPath = outputTmpPath; this.numRows = numRows; this.numCols = numCols; this.keepTempFiles = keepTempFiles; } @Override public Configuration getConf() { return conf; } @Override public void setConf(Configuration conf) { this.conf = conf; try { FileSystem fs = FileSystem.get(inputPath.toUri(), conf); rowPath = fs.makeQualified(inputPath); outputTmpBasePath = fs.makeQualified(outputTmpPath); keepTempFiles = conf.getBoolean(KEEP_TEMP_FILES, false); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } public Path getRowPath() { return rowPath; } public Path getOutputTempPath() { return outputTmpBasePath; } public void setOutputTempPathString(String outPathString) { try { outputTmpBasePath = FileSystem.get(conf).makeQualified(new Path(outPathString)); } catch (IOException ioe) { log.warn("Unable to set outputBasePath to {}, leaving as {}", outPathString, outputTmpBasePath); } } @Override public Iterator<MatrixSlice> iterateAll() { try { return Iterators.transform( new SequenceFileDirIterator<IntWritable,VectorWritable>(new Path(rowPath, "*"), PathType.GLOB, PathFilters.logsCRCFilter(), null, true, conf), new Function<Pair<IntWritable,VectorWritable>,MatrixSlice>() { @Override public MatrixSlice apply(Pair<IntWritable, VectorWritable> from) { return new MatrixSlice(from.getSecond().get(), from.getFirst().get()); } }); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } @Override public int numSlices() { return numRows(); } @Override public int numRows() { return numRows; } @Override public int numCols() { return numCols; } /** * This implements matrix this.transpose().times(other) * @param other a DistributedRowMatrix * @return a DistributedRowMatrix containing the product */ public DistributedRowMatrix times(DistributedRowMatrix other) throws IOException { if (numRows != other.numRows()) { throw new CardinalityException(numRows, other.numRows()); } Path outPath = new Path(outputTmpBasePath.getParent(), "productWith-" + (System.nanoTime() & 0xFF)); Configuration initialConf = getConf() == null ? new Configuration() : getConf(); Configuration conf = MatrixMultiplicationJob.createMatrixMultiplyJobConf(initialConf, rowPath, other.rowPath, outPath, other.numCols); JobClient.runJob(new JobConf(conf)); DistributedRowMatrix out = new DistributedRowMatrix(outPath, outputTmpPath, numCols, other.numCols()); out.setConf(conf); return out; } public DistributedRowMatrix transpose() throws IOException { Path outputPath = new Path(rowPath.getParent(), "transpose-" + (System.nanoTime() & 0xFF)); Configuration initialConf = getConf() == null ? new Configuration() : getConf(); Configuration conf = TransposeJob.buildTransposeJobConf(initialConf, rowPath, outputPath, numRows); JobClient.runJob(new JobConf(conf)); DistributedRowMatrix m = new DistributedRowMatrix(outputPath, outputTmpPath, numCols, numRows); m.setConf(this.conf); return m; } @Override public Vector times(Vector v) { try { Configuration initialConf = getConf() == null ? new Configuration() : getConf(); Path outputVectorTmpPath = new Path(outputTmpBasePath, new Path(Long.toString(System.nanoTime()))); Configuration conf = TimesSquaredJob.createTimesJobConf(initialConf, v, numRows, rowPath, outputVectorTmpPath); JobClient.runJob(new JobConf(conf)); Vector result = TimesSquaredJob.retrieveTimesSquaredOutputVector(conf); if (!keepTempFiles) { FileSystem fs = outputVectorTmpPath.getFileSystem(conf); fs.delete(outputVectorTmpPath, true); } return result; } catch (IOException ioe) { throw new IllegalStateException(ioe); } } @Override public Vector timesSquared(Vector v) { try { Configuration initialConf = getConf() == null ? new Configuration() : getConf(); Path outputVectorTmpPath = new Path(outputTmpBasePath, new Path(Long.toString(System.nanoTime()))); Configuration conf = TimesSquaredJob.createTimesSquaredJobConf(initialConf, v, rowPath, outputVectorTmpPath); JobClient.runJob(new JobConf(conf)); Vector result = TimesSquaredJob.retrieveTimesSquaredOutputVector(conf); if (!keepTempFiles) { FileSystem fs = outputVectorTmpPath.getFileSystem(conf); fs.delete(outputVectorTmpPath, true); } return result; } catch (IOException ioe) { throw new IllegalStateException(ioe); } } @Override public Iterator<MatrixSlice> iterator() { return iterateAll(); } public static class MatrixEntryWritable implements WritableComparable<MatrixEntryWritable> { private int row; private int col; private double val; public int getRow() { return row; } public void setRow(int row) { this.row = row; } public int getCol() { return col; } public void setCol(int col) { this.col = col; } public double getVal() { return val; } public void setVal(double val) { this.val = val; } @Override public int compareTo(MatrixEntryWritable o) { if (row > o.row) { return 1; } else if (row < o.row) { return -1; } else { if (col > o.col) { return 1; } else if (col < o.col) { return -1; } else { return 0; } } } @Override public boolean equals(Object o) { if (!(o instanceof MatrixEntryWritable)) { return false; } MatrixEntryWritable other = (MatrixEntryWritable) o; return row == other.row && col == other.col; } @Override public int hashCode() { return row + 31 * col; } @Override public void write(DataOutput out) throws IOException { out.writeInt(row); out.writeInt(col); out.writeDouble(val); } @Override public void readFields(DataInput in) throws IOException { row = in.readInt(); col = in.readInt(); val = in.readDouble(); } @Override public String toString() { return "(" + row + ',' + col + "):" + val; } } }
3e0dd760fefa02ea2999998a67ba89ef2663e38c
514
java
Java
modelos/acrescimos/bebidas/BebidaRefrigerante.java
arthurgregoryo/RamenShop
9cd081d2ba6952f5f6589c2d597589fc9c4d6e97
[ "MIT" ]
1
2020-08-07T14:19:12.000Z
2020-08-07T14:19:12.000Z
modelos/acrescimos/bebidas/BebidaRefrigerante.java
arthurgregoryo/RamenShop
9cd081d2ba6952f5f6589c2d597589fc9c4d6e97
[ "MIT" ]
null
null
null
modelos/acrescimos/bebidas/BebidaRefrigerante.java
arthurgregoryo/RamenShop
9cd081d2ba6952f5f6589c2d597589fc9c4d6e97
[ "MIT" ]
null
null
null
17.133333
53
0.714008
5,855
package modelos.acrescimos.bebidas; import modelos.Ramen; import modelos.acrescimos.Acrescimo; public class BebidaRefrigerante extends Acrescimo{ @SuppressWarnings("unused") private final Ramen ramen; public BebidaRefrigerante(Ramen ramen) { this.ramen = ramen; } @Override public String getNome() { return ramen.getNome() + ", Refrigerante ( 5.90 )"; } @Override public String getTipo() { return "BEBIDA"; } @Override public Double getPreco() { return ramen.getPreco() + 5.90; } }
3e0dd7f09d773908cb83025a166249c013b327e9
2,548
java
Java
src/main/java/com/exam/controllers/UserController.java
RavikantMorya/exam-portal-backendd
99f9722023e972d24177e8615362d9293cb18636
[ "Apache-2.0" ]
1
2022-02-24T02:34:13.000Z
2022-02-24T02:34:13.000Z
src/main/java/com/exam/controllers/UserController.java
RavikantMorya/exam-portal-backendd
99f9722023e972d24177e8615362d9293cb18636
[ "Apache-2.0" ]
null
null
null
src/main/java/com/exam/controllers/UserController.java
RavikantMorya/exam-portal-backendd
99f9722023e972d24177e8615362d9293cb18636
[ "Apache-2.0" ]
null
null
null
31.073171
96
0.690738
5,856
package com.exam.controllers; import com.exam.models.Role; import com.exam.models.User; import com.exam.models.UserRole; import com.exam.repo.UserRepository; import com.exam.services.impl.UserServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.HashSet; import java.util.Set; @RestController @RequestMapping("/user") @CrossOrigin("*") public class UserController { @Autowired private UserServiceImpl userService; @Autowired private UserRepository userRepository; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; //object user has all the data related to the user except its role // we want that the user should register as only normal user.We will manually add admin user @PostMapping("/") public User createUser(@RequestBody User user) throws Exception { user.setProfile("default.png"); user.setPassword(this.bCryptPasswordEncoder.encode(user.getPassword())); //createUser of service need two para user and a set of UserRole type //to create an object of userRole we need object of Role and User type //we already have User object in formal para and here we create object of Role Role role=new Role(); role.setRole_id(344); role.setRoleName("NORMAL"); System.out.println("Check1"); UserRole userRole=new UserRole(); userRole.setRole(role); userRole.setUser(user); Set<UserRole> userRoles=new HashSet<>(); userRoles.add(userRole); System.out.println("Check2"); User user1=this.userService.createUser(user,userRoles); System.out.println("Check3"); System.out.println(user1); return user1; } @RequestMapping("/{username}") public User getUser(@PathVariable("username") String username) { //this.userRepository.findByUsername(username); User user=this.userService.getUser(username); System.out.println(user.getUsername()+" "+user.getPassword()); return user; } @DeleteMapping("/{id}") public String deleteUser(@PathVariable("id") Long id) { this.userService.deleteUser(id); return "User deleted"; } @GetMapping("/test") public String get() { return "Hello! I am working fine\nI am backend API."; } }
3e0dd82c6ab9660fd3fc7643d766a7997c2a9f75
3,456
java
Java
java/org/kealinghornets/nxtdroid/app/ThreadDetailFragment.java
joonyeechuah/nxtdroid
d6ead2aa4671668143d70eeb1dcbf75cd67cc0a1
[ "MIT" ]
null
null
null
java/org/kealinghornets/nxtdroid/app/ThreadDetailFragment.java
joonyeechuah/nxtdroid
d6ead2aa4671668143d70eeb1dcbf75cd67cc0a1
[ "MIT" ]
null
null
null
java/org/kealinghornets/nxtdroid/app/ThreadDetailFragment.java
joonyeechuah/nxtdroid
d6ead2aa4671668143d70eeb1dcbf75cd67cc0a1
[ "MIT" ]
null
null
null
31.135135
188
0.680845
5,857
package org.kealinghornets.nxtdroid.app; import android.app.Fragment; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ScrollView; import android.widget.TextView; import org.kealinghornets.nxtdroid.NXT.NXTThread; import org.kealinghornets.nxtdroid.NXT.NXTThreadManager; import org.kealinghornets.nxtdroidproject.R; /** * A fragment representing a single NXTThread detail screen. This fragment is * either contained in a {@link org.kealinghornets.nxtdroid.app.ThreadListActivity} in two-pane mode (on * tablets) or a {@link org.kealinghornets.nxtdroid.app.ThreadDetailActivity} on handsets. */ public class ThreadDetailFragment extends Fragment { /** * The fragment argument representing the item ID that this fragment * represents. */ public static final String ARG_ITEM_ID = "item_id"; private View view = null; /** * The dummy content this fragment is presenting. */ private NXTThread mItem; private Handler mHandler; ThreadClickListener listener; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public ThreadDetailFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments().containsKey(ARG_ITEM_ID)) { // Load the dummy content specified by the fragment // arguments. In a real-world scenario, use a Loader // to load content from a content provider. mItem = NXTThreadManager.getThreadById(getArguments().getString(ARG_ITEM_ID)); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.thread_detail_layout, container, false); ImageView image = (ImageView)view.findViewById(R.id.thread_status_image); listener = new ThreadClickListener(mItem.getNXTThreadID()); image.setOnClickListener(listener); mHandler = new Handler() { public void handleMessage(Message msg) { post(new Runnable() { public void run() { updateThreadDetails(); } }); } }; NXTThreadManager.registerHandler(mHandler); // Show the dummy content as text in a TextView. if (mItem != null) { updateThreadDetails(); } return view; } private ScrollView scroll = null; public void updateThreadDetails() { if (mItem != null) { mItem = NXTThreadManager.getThreadById(mItem.getNXTThreadID()); listener.id = mItem.getNXTThreadID(); ThreadDisplayUpdate.updateView(view, mItem.getNXTThreadName() + (mItem.getNXT() != null ? (" on " + mItem.getNXT().deviceName) : " (disconnected)"), mItem.getNXTThreadState()); TextView log = (TextView) view.findViewById(R.id.thread_log); log.setText(Html.fromHtml(mItem.logString)); scroll = (ScrollView) view.findViewById(R.id.thread_log_scroller); scroll.post(new Runnable() { @Override public void run() { scroll.fullScroll(View.FOCUS_DOWN); } }); } } }
3e0dd8411ba88c631928fdaeca8061715451b102
7,652
java
Java
c5-replicator-util/src/main/java/c5db/log/EntryEncodingUtil.java
joshua-g/c5-replicator
22ea62f0f0244e2d0c06faa47c0a2188a5e5a8b1
[ "Apache-2.0" ]
null
null
null
c5-replicator-util/src/main/java/c5db/log/EntryEncodingUtil.java
joshua-g/c5-replicator
22ea62f0f0244e2d0c06faa47c0a2188a5e5a8b1
[ "Apache-2.0" ]
null
null
null
c5-replicator-util/src/main/java/c5db/log/EntryEncodingUtil.java
joshua-g/c5-replicator
22ea62f0f0244e2d0c06faa47c0a2188a5e5a8b1
[ "Apache-2.0" ]
null
null
null
38.646465
113
0.714584
5,858
/* * Copyright 2014 WANdisco * * WANdisco 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 c5db.log; import c5db.util.CrcInputStream; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.primitives.Ints; import io.protostuff.LinkBuffer; import io.protostuff.LowCopyProtobufOutput; import io.protostuff.ProtobufIOUtil; import io.protostuff.Schema; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Collection; import java.util.List; import java.util.zip.Adler32; import static com.google.common.math.IntMath.checkedAdd; /** * Contains methods used for encoding and decoding log entries */ public class EntryEncodingUtil { /** * Exception indicating that a CRC has been read which does not match up with * the CRC computed from the associated data. */ public static class CrcError extends RuntimeException { public CrcError(String s) { super(s); } } /** * Serialize a protostuff message object, prefixed with message length, and suffixed with a 4-byte CRC. * * @param schema Protostuff message schema * @param message Object to serialize * @param <T> Message type * @return A list of ByteBuffers containing a varInt length, followed by the message, followed by a 4-byte CRC. */ public static <T> List<ByteBuffer> encodeWithLengthAndCrc(Schema<T> schema, T message) { final LinkBuffer messageBuf = new LinkBuffer(); final LowCopyProtobufOutput lcpo = new LowCopyProtobufOutput(messageBuf); try { schema.writeTo(lcpo, message); final int length = Ints.checkedCast(lcpo.buffer.size()); final LinkBuffer lengthBuf = new LinkBuffer().writeVarInt32(length); return appendCrcToBufferList( Lists.newArrayList( Iterables.concat(lengthBuf.finish(), messageBuf.finish())) ); } catch (IOException e) { // This method performs no IO, so it should not actually be possible for an IOException to be thrown. // But just in case... throw new RuntimeException(e); } } /** * Decode a message from the passed input stream, and compute and verify its CRC. This method reads * data written by the method {@link EntryEncodingUtil#encodeWithLengthAndCrc}. * * @param inputStream Input stream, opened for reading and positioned just before the length-prepended header * @return The deserialized, constructed, validated message * @throws IOException if a problem is encountered while reading or parsing * @throws EntryEncodingUtil.CrcError if the recorded CRC of the message does not match its computed CRC. */ public static <T> T decodeAndCheckCrc(InputStream inputStream, Schema<T> schema) throws IOException, CrcError { // TODO this should check the length first and compare it with a passed-in maximum length final T message = schema.newMessage(); final CrcInputStream crcStream = new CrcInputStream(inputStream, new Adler32()); ProtobufIOUtil.mergeDelimitedFrom(crcStream, message, schema); final long computedCrc = crcStream.getValue(); final long diskCrc = readCrc(inputStream); if (diskCrc != computedCrc) { throw new CrcError("CRC mismatch on deserialized message " + message.toString()); } return message; } /** * Given a list of ByteBuffers, compute the combined CRC and then append it to the list as one or more * additional ByteBuffers. Return the entire resulting collection as a new list, including the original * ByteBuffers. * * @param content non-null list of ByteBuffers; no mutation will be performed on them. * @return New list of ByteBuffers, with the CRC appended to the original ByteBuffers */ public static List<ByteBuffer> appendCrcToBufferList(List<ByteBuffer> content) throws IOException { assert content != null; final Adler32 crc = new Adler32(); content.forEach((ByteBuffer buffer) -> crc.update(buffer.duplicate())); final LinkBuffer crcBuf = new LinkBuffer(8); putCrc(crcBuf, crc.getValue()); return Lists.newArrayList(Iterables.concat(content, crcBuf.finish())); } /** * Write a passed CRC to the passed buffer. The CRC is a 4-byte unsigned integer stored in a long; write it * as (fixed length) 4 bytes. * * @param writeTo Buffer to write to; exactly 4 bytes will be written. * @param crc CRC to write; caller guarantees that the code is within the range: * 0 <= CRC < 2^32 */ private static void putCrc(final LinkBuffer writeTo, final long crc) throws IOException { // To store the CRC in an int, we need to subtract to convert it from unsigned to signed. final long shiftedCrc = crc + Integer.MIN_VALUE; writeTo.writeInt32(Ints.checkedCast(shiftedCrc)); } private static long readCrc(InputStream inputStream) throws IOException { int shiftedCrc = (new DataInputStream(inputStream)).readInt(); return ((long) shiftedCrc) - Integer.MIN_VALUE; } /** * Read a specified number of bytes from the input stream (the "content"), then read one or more CRC codes and * check the validity of the data. * * @param inputStream Input stream, opened for reading and positioned just before the content * @param contentLength Length of data to read from inputStream, not including any trailing CRCs * @return The read content, as a ByteBuffer. * @throws IOException */ public static ByteBuffer getAndCheckContent(InputStream inputStream, int contentLength) throws IOException, CrcError { // TODO probably not the correct way to do this... should use IOUtils? final CrcInputStream crcStream = new CrcInputStream(inputStream, new Adler32()); final byte[] content = new byte[contentLength]; final int len = crcStream.read(content); if (len < contentLength) { // Data wasn't available that we expected to be throw new IllegalStateException("Reading a log entry's contents returned fewer than expected bytes"); } final long computedCrc = crcStream.getValue(); final long diskCrc = readCrc(inputStream); if (diskCrc != computedCrc) { throw new CrcError("CRC mismatch on log entry contents"); } return ByteBuffer.wrap(content); } public static void skip(InputStream inputStream, int numBytes) throws IOException { long actuallySkipped = inputStream.skip(numBytes); if (actuallySkipped < numBytes) { throw new IOException("Unable to skip requested number of bytes"); } } /** * Add up the lengths of the content of each buffer in the passed list, and return the sum of the lengths. * * @param buffers List of buffers; this method will not mutate them. * @return The sum of the remaining() bytes in each buffer. */ public static int sumRemaining(Collection<ByteBuffer> buffers) { int length = 0; if (buffers != null) { for (ByteBuffer b : buffers) { length = checkedAdd(length, b.remaining()); } } return length; } }
3e0dd919b80b08fceaf4a46dfb29c770d123f97d
413
java
Java
ModestUtils/src/main/java/com/myutils/utils/BusinessUtil.java
modest1927/modestUtils
a7bda1cae4a584a5c435622eee2bf75edfcb0c1d
[ "Apache-2.0" ]
null
null
null
ModestUtils/src/main/java/com/myutils/utils/BusinessUtil.java
modest1927/modestUtils
a7bda1cae4a584a5c435622eee2bf75edfcb0c1d
[ "Apache-2.0" ]
null
null
null
ModestUtils/src/main/java/com/myutils/utils/BusinessUtil.java
modest1927/modestUtils
a7bda1cae4a584a5c435622eee2bf75edfcb0c1d
[ "Apache-2.0" ]
null
null
null
16.52
76
0.634383
5,859
package com.myutils.utils; /** * 业务类 * */ public class BusinessUtil { /** * 将类的包名去掉 * 比如com.sgepit.frame.guideline.dao.SgccGuidelineInfo转换成SgccGuidelineInfo * @param beanName * @return **/ public static String getTableName(String beanName) { String table = beanName.indexOf(".") > -1 ? beanName.split("\\.")[beanName .split("\\.").length - 1] : beanName; return table; } }
3e0dd94c4b4ee1ab7c7fc548aca391d6fba48964
1,274
java
Java
addstation/src/data/addstation/Utilities.java
DarkbordermanModding/Starsector
f514c41d154b8615b1b4a54f8fb9439254489d0f
[ "BSD-2-Clause" ]
1
2021-03-29T09:58:25.000Z
2021-03-29T09:58:25.000Z
addstation/src/data/addstation/Utilities.java
DarkbordermanModding/Star-Sector
f514c41d154b8615b1b4a54f8fb9439254489d0f
[ "BSD-2-Clause" ]
null
null
null
addstation/src/data/addstation/Utilities.java
DarkbordermanModding/Star-Sector
f514c41d154b8615b1b4a54f8fb9439254489d0f
[ "BSD-2-Clause" ]
1
2021-07-19T03:59:35.000Z
2021-07-19T03:59:35.000Z
31.85
105
0.587127
5,860
package data.addstation; import com.fs.starfarer.api.Global; import com.fs.starfarer.api.campaign.*; import org.json.JSONObject; import java.util.*; public class Utilities { @SuppressWarnings("unchecked") public static Map<String, Number> getCost(String type){ Map<String, Number> costs = new HashMap<>(); try { JSONObject consumed = Global.getSettings().getJSONObject("addstation").getJSONObject(type); Iterator<String> keys = consumed.keys(); while(keys.hasNext()){ String key = keys.next(); costs.put(key, (float)consumed.getDouble(key)); } } catch (Exception e) {} return costs; } public static void setCostPanel(InteractionDialogAPI dialog, Object[] displays){ // Due to display limit, the display will cut each 3 display items(9 length array) int i = 0; while(i < displays.length){ if( i + 9 > displays.length){ dialog.getTextPanel().addCostPanel("", Arrays.copyOfRange(displays, i, displays.length)); } else{ dialog.getTextPanel().addCostPanel("", Arrays.copyOfRange(displays, i, i + 9)); } i += 9; } } }
3e0dd9d1827c923fce9fbec46cad276311f3fb58
4,757
java
Java
modules/designtime/src/main/java/org/shaolin/bmdp/designtime/andriod/datamodel/SearchView.java
akondasif/uimaster
9c083a1ffeb43c67ce95b163f14ab3d85e240758
[ "Apache-2.0" ]
null
null
null
modules/designtime/src/main/java/org/shaolin/bmdp/designtime/andriod/datamodel/SearchView.java
akondasif/uimaster
9c083a1ffeb43c67ce95b163f14ab3d85e240758
[ "Apache-2.0" ]
null
null
null
modules/designtime/src/main/java/org/shaolin/bmdp/designtime/andriod/datamodel/SearchView.java
akondasif/uimaster
9c083a1ffeb43c67ce95b163f14ab3d85e240758
[ "Apache-2.0" ]
null
null
null
26.281768
109
0.604373
5,861
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.08.28 at 04:10:22 PM CST // package org.shaolin.bmdp.designtime.andriod.datamodel; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for SearchView complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SearchView"> * &lt;complexContent> * &lt;extension base="{}LinearLayout"> * &lt;attribute ref="{http://schemas.android.com/apk/res/android}iconifiedByDefault"/> * &lt;attribute ref="{http://schemas.android.com/apk/res/android}imeOptions"/> * &lt;attribute ref="{http://schemas.android.com/apk/res/android}inputType"/> * &lt;attribute ref="{http://schemas.android.com/apk/res/android}maxWidth"/> * &lt;attribute ref="{http://schemas.android.com/apk/res/android}queryHint"/> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SearchView") @XmlRootElement(name = "SearchView") public class SearchView extends LinearLayout implements Serializable { private final static long serialVersionUID = 1L; @XmlAttribute(name = "iconifiedByDefault", namespace = "http://schemas.android.com/apk/res/android") protected String iconifiedByDefault; @XmlAttribute(name = "imeOptions", namespace = "http://schemas.android.com/apk/res/android") protected String imeOptions; @XmlAttribute(name = "inputType", namespace = "http://schemas.android.com/apk/res/android") protected String inputType; @XmlAttribute(name = "maxWidth", namespace = "http://schemas.android.com/apk/res/android") protected String maxWidth; @XmlAttribute(name = "queryHint", namespace = "http://schemas.android.com/apk/res/android") protected String queryHint; /** * Gets the value of the iconifiedByDefault property. * * @return * possible object is * {@link String } * */ public String getIconifiedByDefault() { return iconifiedByDefault; } /** * Sets the value of the iconifiedByDefault property. * * @param value * allowed object is * {@link String } * */ public void setIconifiedByDefault(String value) { this.iconifiedByDefault = value; } /** * Gets the value of the imeOptions property. * * @return * possible object is * {@link String } * */ public String getImeOptions() { return imeOptions; } /** * Sets the value of the imeOptions property. * * @param value * allowed object is * {@link String } * */ public void setImeOptions(String value) { this.imeOptions = value; } /** * Gets the value of the inputType property. * * @return * possible object is * {@link String } * */ public String getInputType() { return inputType; } /** * Sets the value of the inputType property. * * @param value * allowed object is * {@link String } * */ public void setInputType(String value) { this.inputType = value; } /** * Gets the value of the maxWidth property. * * @return * possible object is * {@link String } * */ public String getMaxWidth() { return maxWidth; } /** * Sets the value of the maxWidth property. * * @param value * allowed object is * {@link String } * */ public void setMaxWidth(String value) { this.maxWidth = value; } /** * Gets the value of the queryHint property. * * @return * possible object is * {@link String } * */ public String getQueryHint() { return queryHint; } /** * Sets the value of the queryHint property. * * @param value * allowed object is * {@link String } * */ public void setQueryHint(String value) { this.queryHint = value; } }
3e0dd9d662734d93cc0d2a67008b28ec0c539280
1,082
java
Java
sdk/mediaservices/azure-resourcemanager-mediaservices/src/samples/java/com/azure/resourcemanager/mediaservices/generated/MediaservicesSyncStorageKeysSamples.java
luisCavalcantiDev/azure-sdk-for-java
e4b9f41f4ba695fef58112401bc85ca64abd760f
[ "MIT" ]
1
2022-01-08T06:43:30.000Z
2022-01-08T06:43:30.000Z
sdk/mediaservices/azure-resourcemanager-mediaservices/src/samples/java/com/azure/resourcemanager/mediaservices/generated/MediaservicesSyncStorageKeysSamples.java
luisCavalcantiDev/azure-sdk-for-java
e4b9f41f4ba695fef58112401bc85ca64abd760f
[ "MIT" ]
null
null
null
sdk/mediaservices/azure-resourcemanager-mediaservices/src/samples/java/com/azure/resourcemanager/mediaservices/generated/MediaservicesSyncStorageKeysSamples.java
luisCavalcantiDev/azure-sdk-for-java
e4b9f41f4ba695fef58112401bc85ca64abd760f
[ "MIT" ]
null
null
null
38.642857
146
0.733826
5,862
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.mediaservices.generated; import com.azure.core.util.Context; import com.azure.resourcemanager.mediaservices.models.SyncStorageKeysInput; /** Samples for Mediaservices SyncStorageKeys. */ public final class MediaservicesSyncStorageKeysSamples { /* * x-ms-original-file: specification/mediaservices/resource-manager/Microsoft.Media/stable/2021-06-01/examples/accounts-sync-storage-keys.json */ /** * Sample code: Synchronizes Storage Account Keys. * * @param manager Entry point to MediaServicesManager. */ public static void synchronizesStorageAccountKeys( com.azure.resourcemanager.mediaservices.MediaServicesManager manager) { manager .mediaservices() .syncStorageKeysWithResponse( "contoso", "contososports", new SyncStorageKeysInput().withId("contososportsstore"), Context.NONE); } }
3e0dda22c2bcf343ee167d9ec0d607cdc4ad20f1
7,967
java
Java
app/src/main/java/com/liu/coolweather/bean/Weather.java
liuzicheng/coolweather
56218ecb93bdbd2338534006de7500bcab56e759
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/liu/coolweather/bean/Weather.java
liuzicheng/coolweather
56218ecb93bdbd2338534006de7500bcab56e759
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/liu/coolweather/bean/Weather.java
liuzicheng/coolweather
56218ecb93bdbd2338534006de7500bcab56e759
[ "Apache-2.0" ]
null
null
null
24.819315
173
0.397389
5,863
package com.liu.coolweather.bean; import org.litepal.crud.DataSupport; import java.util.List; /** * Created by LIUZICHENG on 2016/12/17. */ public class Weather extends DataSupport{ private List<HeWeather5Entity> HeWeather5; public List<HeWeather5Entity> getHeWeather5() { return HeWeather5; } public void setHeWeather5(List<HeWeather5Entity> HeWeather5) { this.HeWeather5 = HeWeather5; } public static class HeWeather5Entity { /** * basic : {"city":"北京","cnty":"中国","id":"CN101010100","lat":"39.904000","lon":"116.391000","prov":"北京","update":{"loc":"2016-08-31 11:52","utc":"2016-08-31 03:52"}} * now : {"cond":{"code":"104","txt":"阴"},"fl":"11","hum":"31","pcpn":"0","pres":"1025","tmp":"13","vis":"10","wind":{"deg":"40","dir":"东北风","sc":"4-5","spd":"24"}} * status : ok//接口状态 */ private BasicEntity basic; private NowEntity now; private String status;//接口状态 public BasicEntity getBasic() { return basic; } public void setBasic(BasicEntity basic) { this.basic = basic; } public NowEntity getNow() { return now; } public void setNow(NowEntity now) { this.now = now; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public static class BasicEntity { /** * city : 北京//城市名称 * cnty : 中国 //国家 * id : CN101010100 //城市ID * lat : 39.904000 //城市维度 * lon : 116.391000 //城市经度 * prov : 北京 //城市所属省份(仅限国内城市) * update : {"loc":"2016-08-31 11:52","utc":"2016-08-31 03:52"} */ private String city; private String cnty; private String id; private String lat; private String lon; private String prov; private UpdateEntity update; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCnty() { return cnty; } public void setCnty(String cnty) { this.cnty = cnty; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getLat() { return lat; } public void setLat(String lat) { this.lat = lat; } public String getLon() { return lon; } public void setLon(String lon) { this.lon = lon; } public String getProv() { return prov; } public void setProv(String prov) { this.prov = prov; } public UpdateEntity getUpdate() { return update; } public void setUpdate(UpdateEntity update) { this.update = update; } public static class UpdateEntity { /** * loc : 2016-08-31 11:52 //当地时间 * utc : 2016-08-31 03:52 //UTC时间 */ private String loc; private String utc; public String getLoc() { return loc; } public void setLoc(String loc) { this.loc = loc; } public String getUtc() { return utc; } public void setUtc(String utc) { this.utc = utc; } } } public static class NowEntity { /** * cond : {"code":"104","txt":"阴"} * fl : 11 //体感温度 * hum : 31 //相对湿度(%) * pcpn : 0 //降水量(mm) * pres : 1025 //气压 * tmp : 13 //温度 * vis : 10 //能见度(km) * wind : {"deg":"40","dir":"东北风","sc":"4-5","spd":"24"}//风力风向 */ private CondEntity cond; private String fl; private String hum; private String pcpn; private String pres; private String tmp; private String vis; private WindEntity wind; public CondEntity getCond() { return cond; } public void setCond(CondEntity cond) { this.cond = cond; } public String getFl() { return fl; } public void setFl(String fl) { this.fl = fl; } public String getHum() { return hum; } public void setHum(String hum) { this.hum = hum; } public String getPcpn() { return pcpn; } public void setPcpn(String pcpn) { this.pcpn = pcpn; } public String getPres() { return pres; } public void setPres(String pres) { this.pres = pres; } public String getTmp() { return tmp; } public void setTmp(String tmp) { this.tmp = tmp; } public String getVis() { return vis; } public void setVis(String vis) { this.vis = vis; } public WindEntity getWind() { return wind; } public void setWind(WindEntity wind) { this.wind = wind; } public static class CondEntity { /** * code : 104 //天气状况代码 * txt : 阴//天气状况描述 */ private String code; private String txt; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getTxt() { return txt; } public void setTxt(String txt) { this.txt = txt; } } public static class WindEntity { /** * deg : 40 //风向(360度) * dir : 东北风//风向 * sc : 4-5//风力 * spd : 24//风速(kmph) */ private String deg; private String dir; private String sc; private String spd; public String getDeg() { return deg; } public void setDeg(String deg) { this.deg = deg; } public String getDir() { return dir; } public void setDir(String dir) { this.dir = dir; } public String getSc() { return sc; } public void setSc(String sc) { this.sc = sc; } public String getSpd() { return spd; } public void setSpd(String spd) { this.spd = spd; } } } } }
3e0dda56563418bb2588c87cf99ee7e7d3d1fd36
2,464
java
Java
src/java/org/apache/fop/fo/expr/NearestSpecPropFunction.java
i14h/fop
e696ccbb98e7b8382d21c52232ca1fd1a143b771
[ "Apache-2.0" ]
1
2021-08-06T22:01:51.000Z
2021-08-06T22:01:51.000Z
src/java/org/apache/fop/fo/expr/NearestSpecPropFunction.java
i14h/fop
e696ccbb98e7b8382d21c52232ca1fd1a143b771
[ "Apache-2.0" ]
null
null
null
src/java/org/apache/fop/fo/expr/NearestSpecPropFunction.java
i14h/fop
e696ccbb98e7b8382d21c52232ca1fd1a143b771
[ "Apache-2.0" ]
null
null
null
34.222222
89
0.668831
5,864
/* * 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. */ /* $Id$ */ package org.apache.fop.fo.expr; import org.apache.fop.fo.FOPropertyMapping; import org.apache.fop.fo.properties.Property; /** * Class modelling the from-nearest-specified-value function. See Sec. 5.10.4 * of the XSL-FO standard. */ public class NearestSpecPropFunction extends FunctionBase { /** * @return 1 (maximum number of arguments for from-nearest-specified-value * function) */ public int nbArgs() { return 1; } /** * @return true (allow padding of arglist with property name) */ public boolean padArgsWithPropertyName() { return true; } /** * * @param args array of arguments for the function * @param pInfo PropertyInfo for the function * @return Property containing the nearest-specified-value * @throws PropertyException for invalid arguments to the function */ public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { String propName = args[0].getString(); if (propName == null) { throw new PropertyException( "Incorrect parameter to from-nearest-specified-value function"); } // NOTE: special cases for shorthand property // Should return COMPUTED VALUE int propId = FOPropertyMapping.getPropertyId(propName); if (propId < 0) { throw new PropertyException( "Unknown property name used with inherited-property-value function: " + propName); } return pInfo.getPropertyList().getNearestSpecified(propId); } }
3e0dda7973c78cb7c2f887e9968f195414dbcc3b
3,532
java
Java
jphp-runtime/src/php/runtime/lang/BaseException.java
Diffblue-benchmarks/Jphp-group-jphp
e0d00163a74d78adb72629d8309d1df3ffed7662
[ "Apache-2.0" ]
903
2015-01-02T18:49:24.000Z
2018-05-02T14:44:25.000Z
jphp-runtime/src/php/runtime/lang/BaseException.java
Diffblue-benchmarks/Jphp-group-jphp
e0d00163a74d78adb72629d8309d1df3ffed7662
[ "Apache-2.0" ]
137
2018-05-11T20:47:24.000Z
2022-02-24T23:21:21.000Z
jphp-runtime/src/php/runtime/lang/BaseException.java
Diffblue-benchmarks/Jphp-group-jphp
e0d00163a74d78adb72629d8309d1df3ffed7662
[ "Apache-2.0" ]
129
2015-01-06T06:34:03.000Z
2018-04-22T10:00:35.000Z
30.982456
108
0.655436
5,865
package php.runtime.lang; import php.runtime.Memory; import php.runtime.annotation.Reflection; import php.runtime.common.HintType; import php.runtime.common.Modifier; import php.runtime.env.CallStackItem; import php.runtime.env.Environment; import php.runtime.lang.exception.BaseBaseException; import php.runtime.lang.exception.BaseThrowable; import php.runtime.memory.StringMemory; import php.runtime.reflection.ClassEntity; import static php.runtime.annotation.Reflection.*; @BaseType @Name("Exception") @Reflection.Signature(root = true, value = { @Arg(value = "message", modifier = Modifier.PROTECTED, type = HintType.STRING), @Arg(value = "code", modifier = Modifier.PROTECTED, type = HintType.INT), @Arg(value = "previous", modifier = Modifier.PROTECTED, type = HintType.OBJECT), @Arg(value = "trace", modifier = Modifier.PROTECTED, type = HintType.ARRAY), @Arg(value = "file", modifier = Modifier.PROTECTED, type = HintType.STRING), @Arg(value = "line", modifier = Modifier.PROTECTED, type = HintType.INT), @Arg(value = "position", modifier = Modifier.PROTECTED, type = HintType.INT) }) public class BaseException extends BaseBaseException implements BaseThrowable { public BaseException(Environment env) { super(env); } public BaseException(Environment env, ClassEntity clazz) { super(env, clazz); } @Signature(value = { @Arg(value = "message", optional = @Optional(value = "")), @Arg(value = "code", optional = @Optional(value = "0")), @Arg(value = "previous", nativeType = BaseThrowable.class, optional = @Optional(value = "NULL")) }) public Memory __construct(Environment env, Memory... args) { clazz.refOfProperty(props, "message").assign(args[0].toString()); if (args.length > 1) { clazz.refOfProperty(props, "code").assign(args[1].toLong()); } if (args.length > 2) { clazz.refOfProperty(props, "previous").assign(args[2]); } return Memory.NULL; } @Override @Signature final public Memory getMessage(Environment env, Memory... args) { return super.getMessage(env, args); } @Override @Signature final public Memory getCode(Environment env, Memory... args) { return super.getCode(env, args); } @Override @Signature final public Memory getLine(Environment env, Memory... args) { return super.getLine(env, args); } @Override @Signature final public Memory getPosition(Environment env, Memory... args) { return super.getPosition(env, args); } @Override @Signature final public Memory getFile(Environment env, Memory... args) { return super.getFile(env, args); } @Override @Signature final public Memory getTrace(Environment env, Memory... args) { return super.getTrace(env, args); } @Override @Signature final public Memory getPrevious(Environment env, Memory... args) { return super.getPrevious(env, args); } @Override @Signature public Memory __toString(Environment env, Memory... args) { return super.__toString(env, args); } @Override @Signature final public Memory getTraceAsString(Environment env, Memory... args) { return super.getTraceAsString(env, args); } @Signature private Memory __clone(Environment env, Memory... args) { return Memory.NULL; } }
3e0ddaefd9d3e3152fa81e0e22693a5ef096e6b9
612
java
Java
springboot/src/main/java/com/camellibby/servlet/register/DemoSessionListener.java
camellibby/java_demo
bbe506168a9e4a076b9257ed7315eccde3d84e64
[ "Apache-2.0" ]
null
null
null
springboot/src/main/java/com/camellibby/servlet/register/DemoSessionListener.java
camellibby/java_demo
bbe506168a9e4a076b9257ed7315eccde3d84e64
[ "Apache-2.0" ]
null
null
null
springboot/src/main/java/com/camellibby/servlet/register/DemoSessionListener.java
camellibby/java_demo
bbe506168a9e4a076b9257ed7315eccde3d84e64
[ "Apache-2.0" ]
null
null
null
27.818182
69
0.74183
5,866
package com.camellibby.servlet.register; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class DemoSessionListener implements HttpSessionListener { public static long sessionCount = 0; @Override public void sessionCreated(HttpSessionEvent httpSessionEvent) { sessionCount++; System.out.println("创建session, 目前session数量为" + sessionCount); } @Override public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { sessionCount--; System.out.println("销毁session, 目前session数量为" + sessionCount); } }
3e0ddb0bd5f0e473f7548ac0a11fcfc59c1fcd4f
262
java
Java
server/src/main/java/com/lunchtime/security/TokenHistory.java
Andrii35/Lunch_Time
b28d91de17372224906f57d14b853b98d787757a
[ "MIT" ]
3
2020-02-29T18:31:20.000Z
2020-03-18T12:28:12.000Z
server/src/main/java/com/lunchtime/security/TokenHistory.java
Andrii35/Lunch_Time
b28d91de17372224906f57d14b853b98d787757a
[ "MIT" ]
64
2020-02-26T13:48:43.000Z
2021-12-09T22:19:44.000Z
server/src/main/java/com/lunchtime/security/TokenHistory.java
Andrii35/Lunch_Time
b28d91de17372224906f57d14b853b98d787757a
[ "MIT" ]
1
2020-05-15T15:15:12.000Z
2020-05-15T15:15:12.000Z
18.714286
55
0.782443
5,867
package com.lunchtime.security; import lombok.Getter; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; @Getter @Component public class TokenHistory { private List<String> tokenList = new ArrayList<>(); }
3e0ddb219455545237a0d0f887cb44b25baf40af
2,178
java
Java
java-multipleinheritance/src/mi/Dog.java
bantling/tools
6ec830bf05cbde6e3b360868f23268d3466ec751
[ "Apache-2.0" ]
2
2021-12-16T00:11:21.000Z
2022-01-31T12:43:52.000Z
java-multipleinheritance/src/mi/Dog.java
bantling/tools
6ec830bf05cbde6e3b360868f23268d3466ec751
[ "Apache-2.0" ]
null
null
null
java-multipleinheritance/src/mi/Dog.java
bantling/tools
6ec830bf05cbde6e3b360868f23268d3466ec751
[ "Apache-2.0" ]
null
null
null
26.888889
97
0.712121
5,868
package mi; import static java.time.temporal.ChronoField.DAY_OF_MONTH; import static java.time.temporal.ChronoField.HOUR_OF_DAY; import static java.time.temporal.ChronoField.MINUTE_OF_DAY; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.ChronoField.NANO_OF_SECOND; import static java.time.temporal.ChronoField.SECOND_OF_MINUTE; import static java.time.temporal.ChronoField.YEAR; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; /** * The fields of data that Foo needs to operate on */ class DogData { final String breed; final String name; final OffsetDateTime birthDate; DogData(String breed, String name, OffsetDateTime birthDate) { this.breed = breed; this.name = name; this.birthDate = birthDate; } } public interface Dog { /** * The method the class has to implement to return a DogData instance, from one its own fields. * * @return dog data */ DogData getDogData(); /** * Return the next time the dog should go to the vet for a checkup, * which is annually, one week after the dog's birthday. * * @return date of next checkup. */ default OffsetDateTime nextCheckup() { final OffsetDateTime now = OffsetDateTime.now(); final OffsetDateTime today = now. minusHours(now.get(HOUR_OF_DAY)). minusMinutes(now.get(MINUTE_OF_DAY)). minusSeconds(now.get(SECOND_OF_MINUTE)). minusSeconds(now.get(NANO_OF_SECOND)); final OffsetDateTime bday = getDogData().birthDate; final int thisYear = now.get(YEAR); final int bdayMonth = bday.get(MONTH_OF_YEAR); final int bdayDay = bday.get(DAY_OF_MONTH); OffsetDateTime nextCheckup = OffsetDateTime. of(thisYear, bdayMonth, bdayDay, 12, 0, 0, 0, ZoneOffset.UTC). plusDays(7); if (nextCheckup.isBefore(today)) { nextCheckup = nextCheckup.plusYears(1); } return nextCheckup; } default String getBreed() { return getDogData().breed; } default String getName() { return getDogData().name; } default OffsetDateTime getBirthDate() { return getDogData().birthDate; } }
3e0ddb88a143f5d7168884a3de02b156d93dd0c4
3,868
java
Java
spring-cloud-starter-stream-processor-httpclient-gateway/src/main/java/org/springframework/cloud/stream/app/httpclient/gateway/processor/ResourceLoaderSupport.java
queueing-theory/httpclient-gateway
31f89d48f7fb89ede89136efdebd25f2421b6745
[ "Apache-2.0" ]
null
null
null
spring-cloud-starter-stream-processor-httpclient-gateway/src/main/java/org/springframework/cloud/stream/app/httpclient/gateway/processor/ResourceLoaderSupport.java
queueing-theory/httpclient-gateway
31f89d48f7fb89ede89136efdebd25f2421b6745
[ "Apache-2.0" ]
null
null
null
spring-cloud-starter-stream-processor-httpclient-gateway/src/main/java/org/springframework/cloud/stream/app/httpclient/gateway/processor/ResourceLoaderSupport.java
queueing-theory/httpclient-gateway
31f89d48f7fb89ede89136efdebd25f2421b6745
[ "Apache-2.0" ]
1
2020-10-20T05:22:33.000Z
2020-10-20T05:22:33.000Z
42.505495
140
0.701655
5,869
package org.springframework.cloud.stream.app.httpclient.gateway.processor; import org.apache.commons.io.IOUtils; import org.apache.tika.mime.MimeTypeException; import org.apache.tika.mime.MimeTypes; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.WritableResource; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.http.MediaType; import org.springframework.util.Assert; import org.springframework.web.util.UriComponentsBuilder; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.time.LocalDateTime; import java.util.*; class ResourceLoaderSupport { private MimeTypes mimeTypes = MimeTypes.getDefaultMimeTypes(); private ResourceLoader resourceLoader; private String location; ResourceLoaderSupport(ResourceLoader resourceLoader, String location) { Assert.isTrue(location.endsWith("/") ^ (location.contains("{key}") && location.contains("{extension}")), "resourceLocationUri should either end with '/' or has a 'key' and 'extension' variable"); this.resourceLoader = resourceLoader; this.location = location; } private static Map<String, Object> createUriVariables(String name, String extension) { LocalDateTime localDateTime = LocalDateTime.now(); Map<String, Object> variables = new HashMap<>(); variables.put("key", Objects.requireNonNull(name)); variables.put("extension", Objects.requireNonNull(extension)); variables.put("yyyy", localDateTime.getYear()); variables.put("MM", String.format("%02d", localDateTime.getMonthValue())); variables.put("dd", String.format("%02d", localDateTime.getDayOfMonth())); variables.put("HH", String.format("%02d", localDateTime.getHour())); variables.put("mm", String.format("%02d", localDateTime.getMinute())); variables.put("ss", String.format("%02d", localDateTime.getSecond())); return Collections.unmodifiableMap(variables); } public String externalizeAsResource(String name, String continuationId, MediaType mediaType, DataBuffer dataBuffer) throws IOException { String extension = null; try { extension = mimeTypes.forName(mediaType.toString()).getExtension(); } catch (MimeTypeException e) { e.printStackTrace(); } String key = name + "/" + UUID.nameUUIDFromBytes(continuationId.getBytes()).toString(); String uriPath = uriPath(key, extension); Resource resource = createResource(uriPath); WritableResource writableResource = (WritableResource) resource; try (OutputStream outputStream = writableResource.getOutputStream(); InputStream inputStream = dataBuffer.asInputStream()) { IOUtils.copy(inputStream, outputStream); } return uriPath; } private String uriPath(String name, String extension) { UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(location); if (location.endsWith("/")) { uriComponentsBuilder.path(name + extension); } return uriComponentsBuilder.buildAndExpand(createUriVariables(name, extension)).toString(); } public Resource createResource(String uriPath) throws IOException { Resource resource = resourceLoader.getResource(uriPath); if (!resource.exists() && resource.isFile()) { if (!resource.getFile().getParentFile().exists()) { Files.createDirectories(resource.getFile().getParentFile().toPath()); } } return resource; } public Resource getResource(String location) { return resourceLoader.getResource(location); } }
3e0ddb968f68b4a7fa7b3ee24b168524599c8189
786
java
Java
me/zeroeightsix/kami/setting/impl/numerical/IntegerSetting.java
christallinqq/highland.cc
9111cfa71ce664b986cecdbb8e341ae33fb086f7
[ "Unlicense" ]
7
2021-07-27T20:07:33.000Z
2021-12-12T11:28:31.000Z
me/zeroeightsix/kami/setting/impl/numerical/IntegerSetting.java
christallinqq/highland.cc
9111cfa71ce664b986cecdbb8e341ae33fb086f7
[ "Unlicense" ]
null
null
null
me/zeroeightsix/kami/setting/impl/numerical/IntegerSetting.java
christallinqq/highland.cc
9111cfa71ce664b986cecdbb8e341ae33fb086f7
[ "Unlicense" ]
null
null
null
41.368421
191
0.805344
5,870
package me.zeroeightsix.kami.setting.impl.numerical; import java.util.function.BiConsumer; import java.util.function.Predicate; import me.zeroeightsix.kami.setting.converter.AbstractBoxedNumberConverter; import me.zeroeightsix.kami.setting.converter.BoxedIntegerConverter; public class IntegerSetting extends NumberSetting<Integer> { private static final BoxedIntegerConverter converter = new BoxedIntegerConverter(); public IntegerSetting(Integer value, Predicate<Integer> restriction, BiConsumer<Integer, Integer> consumer, String name, Predicate<Integer> visibilityPredicate, Integer min, Integer max) { super(value, restriction, consumer, name, visibilityPredicate, min, max); } public AbstractBoxedNumberConverter converter() { return converter; } }
3e0ddbca57a30e0e967124613da3576117cb41cb
12,745
java
Java
src/main/java/com/yqwl/pojo/User.java
liujiayii/OfficeBuilding
fd09103972d3f3b73ea412423231df0c4b38a967
[ "MIT" ]
null
null
null
src/main/java/com/yqwl/pojo/User.java
liujiayii/OfficeBuilding
fd09103972d3f3b73ea412423231df0c4b38a967
[ "MIT" ]
23
2020-06-16T03:59:56.000Z
2021-04-26T18:58:41.000Z
src/main/java/com/yqwl/pojo/User.java
liujiayii/OfficeBuilding
fd09103972d3f3b73ea412423231df0c4b38a967
[ "MIT" ]
null
null
null
33.806366
126
0.704747
5,871
package com.yqwl.pojo; import java.io.Serializable; import java.util.Date; public class User implements Serializable { /** * This field was generated by MyBatis Generator. This field corresponds to the database column t_user.id * @mbggenerated */ private Long id; /** * This field was generated by MyBatis Generator. This field corresponds to the database column t_user.category * @mbggenerated */ private Integer category; /** * This field was generated by MyBatis Generator. This field corresponds to the database column t_user.name * @mbggenerated */ private String name; /** * This field was generated by MyBatis Generator. This field corresponds to the database column t_user.address * @mbggenerated */ private String address; /** * This field was generated by MyBatis Generator. This field corresponds to the database column t_user.demand_acreage * @mbggenerated */ private Integer demand_acreage; /** * This field was generated by MyBatis Generator. This field corresponds to the database column t_user.demand_money * @mbggenerated */ private Integer demand_money; /** * This field was generated by MyBatis Generator. This field corresponds to the database column t_user.demand_address * @mbggenerated */ private String demand_address; /** * This field was generated by MyBatis Generator. This field corresponds to the database column t_user.time * @mbggenerated */ private Date time; /** * This field was generated by MyBatis Generator. This field corresponds to the database column t_user.broker_id * @mbggenerated */ private Long broker_id; /** * This field was generated by MyBatis Generator. This field corresponds to the database column t_user.region_id * @mbggenerated */ private Integer region_id; /** * This field was generated by MyBatis Generator. This field corresponds to the database column t_user.building_id * @mbggenerated */ private Long building_id; /** * This field was generated by MyBatis Generator. This field corresponds to the database column t_user.remark * @mbggenerated */ private String remark; /** * This field was generated by MyBatis Generator. This field corresponds to the database table t_user * @mbggenerated */ private static final long serialVersionUID = 1L; /** * This method was generated by MyBatis Generator. This method returns the value of the database column t_user.id * @return the value of t_user.id * @mbggenerated */ public Long getId() { return id; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column t_user.id * @param id the value for t_user.id * @mbggenerated */ public void setId(Long id) { this.id = id; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column t_user.category * @return the value of t_user.category * @mbggenerated */ public Integer getCategory() { return category; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column t_user.category * @param category the value for t_user.category * @mbggenerated */ public void setCategory(Integer category) { this.category = category; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column t_user.name * @return the value of t_user.name * @mbggenerated */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column t_user.name * @param name the value for t_user.name * @mbggenerated */ public void setName(String name) { this.name = name == null ? null : name.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value of the database column t_user.address * @return the value of t_user.address * @mbggenerated */ public String getAddress() { return address; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column t_user.address * @param address the value for t_user.address * @mbggenerated */ public void setAddress(String address) { this.address = address == null ? null : address.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value of the database column t_user.demand_acreage * @return the value of t_user.demand_acreage * @mbggenerated */ public Integer getDemand_acreage() { return demand_acreage; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column t_user.demand_acreage * @param demand_acreage the value for t_user.demand_acreage * @mbggenerated */ public void setDemand_acreage(Integer demand_acreage) { this.demand_acreage = demand_acreage; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column t_user.demand_money * @return the value of t_user.demand_money * @mbggenerated */ public Integer getDemand_money() { return demand_money; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column t_user.demand_money * @param demand_money the value for t_user.demand_money * @mbggenerated */ public void setDemand_money(Integer demand_money) { this.demand_money = demand_money; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column t_user.demand_address * @return the value of t_user.demand_address * @mbggenerated */ public String getDemand_address() { return demand_address; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column t_user.demand_address * @param demand_address the value for t_user.demand_address * @mbggenerated */ public void setDemand_address(String demand_address) { this.demand_address = demand_address == null ? null : demand_address.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value of the database column t_user.time * @return the value of t_user.time * @mbggenerated */ public Date getTime() { return time; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column t_user.time * @param time the value for t_user.time * @mbggenerated */ public void setTime(Date time) { this.time = time; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column t_user.broker_id * @return the value of t_user.broker_id * @mbggenerated */ public Long getBroker_id() { return broker_id; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column t_user.broker_id * @param broker_id the value for t_user.broker_id * @mbggenerated */ public void setBroker_id(Long broker_id) { this.broker_id = broker_id; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column t_user.region_id * @return the value of t_user.region_id * @mbggenerated */ public Integer getRegion_id() { return region_id; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column t_user.region_id * @param region_id the value for t_user.region_id * @mbggenerated */ public void setRegion_id(Integer region_id) { this.region_id = region_id; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column t_user.building_id * @return the value of t_user.building_id * @mbggenerated */ public Long getBuilding_id() { return building_id; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column t_user.building_id * @param building_id the value for t_user.building_id * @mbggenerated */ public void setBuilding_id(Long building_id) { this.building_id = building_id; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column t_user.remark * @return the value of t_user.remark * @mbggenerated */ public String getRemark() { return remark; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column t_user.remark * @param remark the value for t_user.remark * @mbggenerated */ public void setRemark(String remark) { this.remark = remark == null ? null : remark.trim(); } /** * This method was generated by MyBatis Generator. This method corresponds to the database table t_user * @mbggenerated */ @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } User other = (User) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getCategory() == null ? other.getCategory() == null : this.getCategory().equals(other.getCategory())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getAddress() == null ? other.getAddress() == null : this.getAddress().equals(other.getAddress())) && (this.getDemand_acreage() == null ? other.getDemand_acreage() == null : this.getDemand_acreage().equals(other.getDemand_acreage())) && (this.getDemand_money() == null ? other.getDemand_money() == null : this.getDemand_money().equals(other.getDemand_money())) && (this.getDemand_address() == null ? other.getDemand_address() == null : this.getDemand_address().equals(other.getDemand_address())) && (this.getTime() == null ? other.getTime() == null : this.getTime().equals(other.getTime())) && (this.getBroker_id() == null ? other.getBroker_id() == null : this.getBroker_id().equals(other.getBroker_id())) && (this.getRegion_id() == null ? other.getRegion_id() == null : this.getRegion_id().equals(other.getRegion_id())) && (this.getBuilding_id() == null ? other.getBuilding_id() == null : this.getBuilding_id().equals(other.getBuilding_id())) && (this.getRemark() == null ? other.getRemark() == null : this.getRemark().equals(other.getRemark())); } /** * This method was generated by MyBatis Generator. This method corresponds to the database table t_user * @mbggenerated */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getCategory() == null) ? 0 : getCategory().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getAddress() == null) ? 0 : getAddress().hashCode()); result = prime * result + ((getDemand_acreage() == null) ? 0 : getDemand_acreage().hashCode()); result = prime * result + ((getDemand_money() == null) ? 0 : getDemand_money().hashCode()); result = prime * result + ((getDemand_address() == null) ? 0 : getDemand_address().hashCode()); result = prime * result + ((getTime() == null) ? 0 : getTime().hashCode()); result = prime * result + ((getBroker_id() == null) ? 0 : getBroker_id().hashCode()); result = prime * result + ((getRegion_id() == null) ? 0 : getRegion_id().hashCode()); result = prime * result + ((getBuilding_id() == null) ? 0 : getBuilding_id().hashCode()); result = prime * result + ((getRemark() == null) ? 0 : getRemark().hashCode()); return result; } /** * This method was generated by MyBatis Generator. This method corresponds to the database table t_user * @mbggenerated */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", category=").append(category); sb.append(", name=").append(name); sb.append(", address=").append(address); sb.append(", demand_acreage=").append(demand_acreage); sb.append(", demand_money=").append(demand_money); sb.append(", demand_address=").append(demand_address); sb.append(", time=").append(time); sb.append(", broker_id=").append(broker_id); sb.append(", region_id=").append(region_id); sb.append(", building_id=").append(building_id); sb.append(", remark=").append(remark); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
3e0ddc0eabc56fa5d690fb000c84b471ef6ce8f9
35,076
java
Java
proto-google-cloud-monitoring-v3/src/main/java/com/google/monitoring/v3/ListGroupsResponse.java
googleapis/java-monitoring
e4b34fb8cd2b435a889fc972817f7b9b70ecb3df
[ "Apache-2.0" ]
11
2020-05-26T20:45:49.000Z
2021-11-04T04:13:50.000Z
proto-google-cloud-monitoring-v3/src/main/java/com/google/monitoring/v3/ListGroupsResponse.java
renovate-bot/java-monitoring
e4b34fb8cd2b435a889fc972817f7b9b70ecb3df
[ "Apache-2.0" ]
532
2019-10-30T15:00:48.000Z
2022-03-29T18:23:02.000Z
proto-google-cloud-monitoring-v3/src/main/java/com/google/monitoring/v3/ListGroupsResponse.java
renovate-bot/java-monitoring
e4b34fb8cd2b435a889fc972817f7b9b70ecb3df
[ "Apache-2.0" ]
18
2019-10-29T19:09:33.000Z
2021-10-07T04:54:51.000Z
30.903965
100
0.646168
5,872
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/monitoring/v3/group_service.proto package com.google.monitoring.v3; /** * * * <pre> * The `ListGroups` response. * </pre> * * Protobuf type {@code google.monitoring.v3.ListGroupsResponse} */ public final class ListGroupsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.monitoring.v3.ListGroupsResponse) ListGroupsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListGroupsResponse.newBuilder() to construct. private ListGroupsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListGroupsResponse() { group_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListGroupsResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ListGroupsResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { group_ = new java.util.ArrayList<com.google.monitoring.v3.Group>(); mutable_bitField0_ |= 0x00000001; } group_.add( input.readMessage(com.google.monitoring.v3.Group.parser(), extensionRegistry)); break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); nextPageToken_ = s; break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { group_ = java.util.Collections.unmodifiableList(group_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.monitoring.v3.GroupServiceProto .internal_static_google_monitoring_v3_ListGroupsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.monitoring.v3.GroupServiceProto .internal_static_google_monitoring_v3_ListGroupsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.monitoring.v3.ListGroupsResponse.class, com.google.monitoring.v3.ListGroupsResponse.Builder.class); } public static final int GROUP_FIELD_NUMBER = 1; private java.util.List<com.google.monitoring.v3.Group> group_; /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ @java.lang.Override public java.util.List<com.google.monitoring.v3.Group> getGroupList() { return group_; } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.monitoring.v3.GroupOrBuilder> getGroupOrBuilderList() { return group_; } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ @java.lang.Override public int getGroupCount() { return group_.size(); } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ @java.lang.Override public com.google.monitoring.v3.Group getGroup(int index) { return group_.get(index); } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ @java.lang.Override public com.google.monitoring.v3.GroupOrBuilder getGroupOrBuilder(int index) { return group_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; private volatile java.lang.Object nextPageToken_; /** * * * <pre> * If there are more results than have been returned, then this field is set * to a non-empty value. To see the additional results, * use that value as `page_token` in the next call to this method. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * If there are more results than have been returned, then this field is set * to a non-empty value. To see the additional results, * use that value as `page_token` in the next call to this method. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < group_.size(); i++) { output.writeMessage(1, group_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < group_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, group_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.monitoring.v3.ListGroupsResponse)) { return super.equals(obj); } com.google.monitoring.v3.ListGroupsResponse other = (com.google.monitoring.v3.ListGroupsResponse) obj; if (!getGroupList().equals(other.getGroupList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getGroupCount() > 0) { hash = (37 * hash) + GROUP_FIELD_NUMBER; hash = (53 * hash) + getGroupList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.monitoring.v3.ListGroupsResponse parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.monitoring.v3.ListGroupsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.monitoring.v3.ListGroupsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.monitoring.v3.ListGroupsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.monitoring.v3.ListGroupsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.monitoring.v3.ListGroupsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.monitoring.v3.ListGroupsResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.monitoring.v3.ListGroupsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.monitoring.v3.ListGroupsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.monitoring.v3.ListGroupsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.monitoring.v3.ListGroupsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.monitoring.v3.ListGroupsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.monitoring.v3.ListGroupsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The `ListGroups` response. * </pre> * * Protobuf type {@code google.monitoring.v3.ListGroupsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.monitoring.v3.ListGroupsResponse) com.google.monitoring.v3.ListGroupsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.monitoring.v3.GroupServiceProto .internal_static_google_monitoring_v3_ListGroupsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.monitoring.v3.GroupServiceProto .internal_static_google_monitoring_v3_ListGroupsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.monitoring.v3.ListGroupsResponse.class, com.google.monitoring.v3.ListGroupsResponse.Builder.class); } // Construct using com.google.monitoring.v3.ListGroupsResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getGroupFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); if (groupBuilder_ == null) { group_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { groupBuilder_.clear(); } nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.monitoring.v3.GroupServiceProto .internal_static_google_monitoring_v3_ListGroupsResponse_descriptor; } @java.lang.Override public com.google.monitoring.v3.ListGroupsResponse getDefaultInstanceForType() { return com.google.monitoring.v3.ListGroupsResponse.getDefaultInstance(); } @java.lang.Override public com.google.monitoring.v3.ListGroupsResponse build() { com.google.monitoring.v3.ListGroupsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.monitoring.v3.ListGroupsResponse buildPartial() { com.google.monitoring.v3.ListGroupsResponse result = new com.google.monitoring.v3.ListGroupsResponse(this); int from_bitField0_ = bitField0_; if (groupBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { group_ = java.util.Collections.unmodifiableList(group_); bitField0_ = (bitField0_ & ~0x00000001); } result.group_ = group_; } else { result.group_ = groupBuilder_.build(); } result.nextPageToken_ = nextPageToken_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.monitoring.v3.ListGroupsResponse) { return mergeFrom((com.google.monitoring.v3.ListGroupsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.monitoring.v3.ListGroupsResponse other) { if (other == com.google.monitoring.v3.ListGroupsResponse.getDefaultInstance()) return this; if (groupBuilder_ == null) { if (!other.group_.isEmpty()) { if (group_.isEmpty()) { group_ = other.group_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureGroupIsMutable(); group_.addAll(other.group_); } onChanged(); } } else { if (!other.group_.isEmpty()) { if (groupBuilder_.isEmpty()) { groupBuilder_.dispose(); groupBuilder_ = null; group_ = other.group_; bitField0_ = (bitField0_ & ~0x00000001); groupBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getGroupFieldBuilder() : null; } else { groupBuilder_.addAllMessages(other.group_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.monitoring.v3.ListGroupsResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.monitoring.v3.ListGroupsResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.util.List<com.google.monitoring.v3.Group> group_ = java.util.Collections.emptyList(); private void ensureGroupIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { group_ = new java.util.ArrayList<com.google.monitoring.v3.Group>(group_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.monitoring.v3.Group, com.google.monitoring.v3.Group.Builder, com.google.monitoring.v3.GroupOrBuilder> groupBuilder_; /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ public java.util.List<com.google.monitoring.v3.Group> getGroupList() { if (groupBuilder_ == null) { return java.util.Collections.unmodifiableList(group_); } else { return groupBuilder_.getMessageList(); } } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ public int getGroupCount() { if (groupBuilder_ == null) { return group_.size(); } else { return groupBuilder_.getCount(); } } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ public com.google.monitoring.v3.Group getGroup(int index) { if (groupBuilder_ == null) { return group_.get(index); } else { return groupBuilder_.getMessage(index); } } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ public Builder setGroup(int index, com.google.monitoring.v3.Group value) { if (groupBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureGroupIsMutable(); group_.set(index, value); onChanged(); } else { groupBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ public Builder setGroup(int index, com.google.monitoring.v3.Group.Builder builderForValue) { if (groupBuilder_ == null) { ensureGroupIsMutable(); group_.set(index, builderForValue.build()); onChanged(); } else { groupBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ public Builder addGroup(com.google.monitoring.v3.Group value) { if (groupBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureGroupIsMutable(); group_.add(value); onChanged(); } else { groupBuilder_.addMessage(value); } return this; } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ public Builder addGroup(int index, com.google.monitoring.v3.Group value) { if (groupBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureGroupIsMutable(); group_.add(index, value); onChanged(); } else { groupBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ public Builder addGroup(com.google.monitoring.v3.Group.Builder builderForValue) { if (groupBuilder_ == null) { ensureGroupIsMutable(); group_.add(builderForValue.build()); onChanged(); } else { groupBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ public Builder addGroup(int index, com.google.monitoring.v3.Group.Builder builderForValue) { if (groupBuilder_ == null) { ensureGroupIsMutable(); group_.add(index, builderForValue.build()); onChanged(); } else { groupBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ public Builder addAllGroup( java.lang.Iterable<? extends com.google.monitoring.v3.Group> values) { if (groupBuilder_ == null) { ensureGroupIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, group_); onChanged(); } else { groupBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ public Builder clearGroup() { if (groupBuilder_ == null) { group_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { groupBuilder_.clear(); } return this; } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ public Builder removeGroup(int index) { if (groupBuilder_ == null) { ensureGroupIsMutable(); group_.remove(index); onChanged(); } else { groupBuilder_.remove(index); } return this; } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ public com.google.monitoring.v3.Group.Builder getGroupBuilder(int index) { return getGroupFieldBuilder().getBuilder(index); } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ public com.google.monitoring.v3.GroupOrBuilder getGroupOrBuilder(int index) { if (groupBuilder_ == null) { return group_.get(index); } else { return groupBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ public java.util.List<? extends com.google.monitoring.v3.GroupOrBuilder> getGroupOrBuilderList() { if (groupBuilder_ != null) { return groupBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(group_); } } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ public com.google.monitoring.v3.Group.Builder addGroupBuilder() { return getGroupFieldBuilder().addBuilder(com.google.monitoring.v3.Group.getDefaultInstance()); } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ public com.google.monitoring.v3.Group.Builder addGroupBuilder(int index) { return getGroupFieldBuilder() .addBuilder(index, com.google.monitoring.v3.Group.getDefaultInstance()); } /** * * * <pre> * The groups that match the specified filters. * </pre> * * <code>repeated .google.monitoring.v3.Group group = 1;</code> */ public java.util.List<com.google.monitoring.v3.Group.Builder> getGroupBuilderList() { return getGroupFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.monitoring.v3.Group, com.google.monitoring.v3.Group.Builder, com.google.monitoring.v3.GroupOrBuilder> getGroupFieldBuilder() { if (groupBuilder_ == null) { groupBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.monitoring.v3.Group, com.google.monitoring.v3.Group.Builder, com.google.monitoring.v3.GroupOrBuilder>( group_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); group_ = null; } return groupBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * If there are more results than have been returned, then this field is set * to a non-empty value. To see the additional results, * use that value as `page_token` in the next call to this method. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * If there are more results than have been returned, then this field is set * to a non-empty value. To see the additional results, * use that value as `page_token` in the next call to this method. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * If there are more results than have been returned, then this field is set * to a non-empty value. To see the additional results, * use that value as `page_token` in the next call to this method. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; onChanged(); return this; } /** * * * <pre> * If there are more results than have been returned, then this field is set * to a non-empty value. To see the additional results, * use that value as `page_token` in the next call to this method. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); onChanged(); return this; } /** * * * <pre> * If there are more results than have been returned, then this field is set * to a non-empty value. To see the additional results, * use that value as `page_token` in the next call to this method. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.monitoring.v3.ListGroupsResponse) } // @@protoc_insertion_point(class_scope:google.monitoring.v3.ListGroupsResponse) private static final com.google.monitoring.v3.ListGroupsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.monitoring.v3.ListGroupsResponse(); } public static com.google.monitoring.v3.ListGroupsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListGroupsResponse> PARSER = new com.google.protobuf.AbstractParser<ListGroupsResponse>() { @java.lang.Override public ListGroupsResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ListGroupsResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ListGroupsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListGroupsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.monitoring.v3.ListGroupsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
3e0ddc3af8718a533545b1be5797b16ccc0b025d
1,216
java
Java
src/main/java/com/fly/imagehome/controller/feign/UserHomeFeign.java
dongzhanpeng/imagehome-service
e4d9397e10a6c61071530c14d788dc6838a570d4
[ "Apache-2.0" ]
null
null
null
src/main/java/com/fly/imagehome/controller/feign/UserHomeFeign.java
dongzhanpeng/imagehome-service
e4d9397e10a6c61071530c14d788dc6838a570d4
[ "Apache-2.0" ]
null
null
null
src/main/java/com/fly/imagehome/controller/feign/UserHomeFeign.java
dongzhanpeng/imagehome-service
e4d9397e10a6c61071530c14d788dc6838a570d4
[ "Apache-2.0" ]
null
null
null
32.864865
113
0.784539
5,873
package com.fly.imagehome.controller.feign; import com.fly.imagehome.pojo.UserHome; import com.fly.imagehome.service.userhome.UserHomeService; import com.fly.imagehome.utils.Result; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.validation.constraints.NotNull; /** * @Classname UserHomeFeign * @Description UserHomeFeign * @Date 2021/12/15 10:43 * @Author Fly * @Version 1.0 */ @Api(value = "userhome-feign", tags = {"userhome-feign"}) @RestController @RequestMapping(value = "/feign/imagehome") public class UserHomeFeign { @Autowired private UserHomeService userHomeService; @ApiOperation("根据用户uuid查询") @GetMapping("v1/getUserHomeByUuid") public Result<UserHome> getUserHomeByUuid(@RequestParam("uuid") @NotNull(message = "uuid不能为空") String uuid) { return Result.success(userHomeService.getUserHomeByUuid(uuid)); } }
3e0ddc4c0a962a034c28e94fb4943b808e027325
767
java
Java
src/main/java/org/apache/accumulo/storagehandler/predicate/compare/GreaterThanOrEqual.java
bfemiano/accumulo-hive-storage-manager
c46f735a4c4603b0a81c32f377b50562ff813360
[ "Apache-2.0" ]
3
2015-02-11T14:26:56.000Z
2015-09-08T09:28:35.000Z
src/main/java/org/apache/accumulo/storagehandler/predicate/compare/GreaterThanOrEqual.java
bfemiano/accumulo-hive-storage-manager
c46f735a4c4603b0a81c32f377b50562ff813360
[ "Apache-2.0" ]
2
2020-11-19T21:48:39.000Z
2020-11-19T21:48:52.000Z
src/main/java/org/apache/accumulo/storagehandler/predicate/compare/GreaterThanOrEqual.java
bfemiano/accumulo-hive-storage-manager
c46f735a4c4603b0a81c32f377b50562ff813360
[ "Apache-2.0" ]
3
2015-03-26T07:58:13.000Z
2022-03-24T11:23:14.000Z
22.558824
89
0.701434
5,874
package org.apache.accumulo.storagehandler.predicate.compare; /** * * Wraps call to greaterThanOrEqual over {@link PrimitiveCompare} instance. * * Used by {@link org.apache.accumulo.storagehandler.predicate.PrimitiveComparisonFilter} */ public class GreaterThanOrEqual implements CompareOp { private PrimitiveCompare comp; public GreaterThanOrEqual(){} public GreaterThanOrEqual(PrimitiveCompare comp) { this.comp = comp; } @Override public void setPrimitiveCompare(PrimitiveCompare comp) { this.comp = comp; } @Override public PrimitiveCompare getPrimitiveCompare() { return comp; } @Override public boolean accept(byte[] val) { return comp.greaterThanOrEqual(val); } }
3e0ddc722c28a3805234ac7b708c363bbd211f14
2,644
java
Java
egradle-plugin-main/src/test/java/de/jcup/egradle/core/text/IdentifierStringIdBuilderTest.java
BeckerFrank/egradle
7e521c0056e4c1138d6619121517d87522ad8707
[ "Apache-2.0" ]
30
2016-09-15T17:48:37.000Z
2022-03-27T17:29:16.000Z
egradle-plugin-main/src/test/java/de/jcup/egradle/core/text/IdentifierStringIdBuilderTest.java
BeckerFrank/egradle
7e521c0056e4c1138d6619121517d87522ad8707
[ "Apache-2.0" ]
407
2016-08-08T10:53:33.000Z
2022-03-19T00:51:11.000Z
egradle-plugin-main/src/test/java/de/jcup/egradle/core/text/IdentifierStringIdBuilderTest.java
BeckerFrank/egradle
7e521c0056e4c1138d6619121517d87522ad8707
[ "Apache-2.0" ]
5
2016-11-24T14:48:59.000Z
2022-01-16T19:27:28.000Z
27.831579
148
0.656203
5,875
/* * Copyright 2017 Albert Tregnaghi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions * and limitations under the License. * */ package de.jcup.egradle.core.text; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import de.jcup.egradle.core.text.DocumentIdentifier.IdentifierStringIdBuilder; public class IdentifierStringIdBuilderTest { private IdentifierStringIdBuilder builderToTest; @Before public void before() { builderToTest = DocumentIdentifier.createStringIdBuilder(); } @Test public void test_hallo_welt_created_as_array() { /* execute */ String[] created = builderToTest.add("hallo").add("welt").build(); /* test */ assertArrayEquals(new String[] { "hallo", "welt" }, created); } private enum DocumentTestidentifiers1 implements DocumentIdentifier { ALPHA, BETA,; @Override public String getId() { return name(); } } private enum DocumentTestidentifiers2 implements DocumentIdentifier { GAMMA, DELTA,; @Override public String getId() { return name(); } } @Test public void test_document_identifier1() { /* execute */ String[] created = builderToTest.addAll(DocumentTestidentifiers1.values()).build(); /* test */ assertArrayEquals(new String[] { "ALPHA", "BETA" }, created); } @Test public void test_document_identifier1_and_2() { /* execute */ String[] created = builderToTest.addAll(DocumentTestidentifiers1.values()).addAll(DocumentTestidentifiers2.values()).build(); /* test */ assertArrayEquals(new String[] { "ALPHA", "BETA", "GAMMA", "DELTA" }, created); } @Test public void test_default_and_document_identifier1_and_2() { /* execute */ String[] created = builderToTest.add("default").addAll(DocumentTestidentifiers1.values()).addAll(DocumentTestidentifiers2.values()).build(); /* test */ assertArrayEquals(new String[] { "default", "ALPHA", "BETA", "GAMMA", "DELTA" }, created); } }
3e0ddc83d33c934b6ebf478efbc248689efd67dc
2,250
java
Java
data/s3/src/main/java/org/teiid/spring/data/s3/S3Configuration.java
ozzioma/teiid-spring-boot
4a75369d3690096be200111ec18a5866b97e85e8
[ "Apache-2.0" ]
37
2017-09-19T13:19:33.000Z
2021-10-15T08:51:04.000Z
data/s3/src/main/java/org/teiid/spring/data/s3/S3Configuration.java
ozzioma/teiid-spring-boot
4a75369d3690096be200111ec18a5866b97e85e8
[ "Apache-2.0" ]
89
2017-05-22T09:32:52.000Z
2022-02-16T01:13:53.000Z
data/s3/src/main/java/org/teiid/spring/data/s3/S3Configuration.java
ozzioma/teiid-spring-boot
4a75369d3690096be200111ec18a5866b97e85e8
[ "Apache-2.0" ]
56
2017-05-12T08:07:46.000Z
2021-12-28T14:35:38.000Z
24.193548
75
0.666667
5,876
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * 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.teiid.spring.data.s3; public class S3Configuration implements org.teiid.s3.S3Configuration { private String accessKey; private String secretKey; private String bucket; private String region; private String sseAlgorithm = "AES256"; private String sseKey; // base64-encoded key private String endpoint; @Override public String getAccessKey() { return accessKey; } public void setAccessKey(String accessKey) { this.accessKey = accessKey; } @Override public String getSecretKey() { return secretKey; } public void setSecretKey(String secretKey) { this.secretKey = secretKey; } @Override public String getBucket() { return bucket; } public void setBucket(String bucket) { this.bucket = bucket; } @Override public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } @Override public String getSseAlgorithm() { return sseAlgorithm; } public void setSseAlgorithm(String sseAlgorithm) { this.sseAlgorithm = sseAlgorithm; } @Override public String getSseKey() { return sseKey; } public void setSseKey(String sseKey) { this.sseKey = sseKey; } @Override public String getEndpoint() { return endpoint; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } }
3e0ddd4b9acbcabd164a1d957d738cfe19f55544
7,697
java
Java
spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/DeprecatedRuntimeModulesController.java
pperalta/spring-cloud-dataflow
b323cefad8732d57dda8fa7f94fbb37f282a6716
[ "Apache-2.0" ]
null
null
null
spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/DeprecatedRuntimeModulesController.java
pperalta/spring-cloud-dataflow
b323cefad8732d57dda8fa7f94fbb37f282a6716
[ "Apache-2.0" ]
2
2015-08-03T22:30:43.000Z
2015-08-04T18:01:29.000Z
spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/DeprecatedRuntimeModulesController.java
pperalta/spring-cloud-dataflow
b323cefad8732d57dda8fa7f94fbb37f282a6716
[ "Apache-2.0" ]
null
null
null
39.270408
123
0.796544
5,877
/* * Copyright 2015-2016 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 org.springframework.cloud.dataflow.server.controller; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.dataflow.core.ModuleDeploymentId; import org.springframework.cloud.dataflow.module.ModuleInstanceStatus; import org.springframework.cloud.dataflow.module.ModuleStatus; import org.springframework.cloud.dataflow.module.deployer.ModuleDeployer; import org.springframework.cloud.dataflow.rest.resource.AppInstanceStatusResource; import org.springframework.cloud.dataflow.rest.resource.AppStatusResource; import org.springframework.data.domain.PageImpl; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.hateoas.ExposesResourceFor; import org.springframework.hateoas.PagedResources; import org.springframework.hateoas.ResourceAssembler; import org.springframework.hateoas.Resources; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; /** * Exposes runtime status of deployed modules. * * @author Eric Bottard */ @RestController @RequestMapping("/runtime/modules") @ExposesResourceFor(AppStatusResource.class) @Deprecated public class DeprecatedRuntimeModulesController { private static final Comparator<? super ModuleInstanceStatus> INSTANCE_SORTER = new Comparator<ModuleInstanceStatus>() { @Override public int compare(ModuleInstanceStatus i1, ModuleInstanceStatus i2) { return i1.getId().compareTo(i2.getId()); } }; private final Collection<ModuleDeployer> moduleDeployers; private final ResourceAssembler<ModuleStatus, AppStatusResource> statusAssembler = new Assembler(); @Autowired public DeprecatedRuntimeModulesController(Collection<ModuleDeployer> moduleDeployers) { this.moduleDeployers = new HashSet<>(moduleDeployers); } @RequestMapping public PagedResources<AppStatusResource> list(PagedResourcesAssembler<ModuleStatus> assembler) { List<ModuleStatus> values = new ArrayList<>(); for (ModuleDeployer moduleDeployer : moduleDeployers) { values.addAll(moduleDeployer.status().values()); } Collections.sort(values, new Comparator<ModuleStatus>() { @Override public int compare(ModuleStatus o1, ModuleStatus o2) { return o1.getModuleDeploymentId().toString().compareTo(o2.getModuleDeploymentId().toString()); } }); return assembler.toResource(new PageImpl<>(values), statusAssembler); } @RequestMapping("/{id}") public AppStatusResource display(@PathVariable String id) { ModuleDeploymentId moduleDeploymentId = ModuleDeploymentId.parse(id); for (ModuleDeployer moduleDeployer : moduleDeployers) { ModuleStatus status = moduleDeployer.status(moduleDeploymentId); if (status != null) { return statusAssembler.toResource(status); } } throw new ResourceNotFoundException(); } private class Assembler extends ResourceAssemblerSupport<ModuleStatus, AppStatusResource> { public Assembler() { super(DeprecatedRuntimeModulesController.class, AppStatusResource.class); } @Override public AppStatusResource toResource(ModuleStatus entity) { return createResourceWithId(entity.getModuleDeploymentId(), entity); } @Override protected AppStatusResource instantiateResource(ModuleStatus entity) { AppStatusResource resource = new AppStatusResource(entity.getModuleDeploymentId().toString(), entity.getState().name()); List<AppInstanceStatusResource> instanceStatusResources = new ArrayList<>(); InstanceAssembler instanceAssembler = new InstanceAssembler(entity); List<ModuleInstanceStatus> instanceStatuses = new ArrayList<>(entity.getInstances().values()); Collections.sort(instanceStatuses, INSTANCE_SORTER); for (ModuleInstanceStatus moduleInstanceStatus : instanceStatuses) { instanceStatusResources.add(instanceAssembler.toResource(moduleInstanceStatus)); } resource.setInstances(new Resources<>(instanceStatusResources)); return resource; } } @RestController @RequestMapping("/runtime/modules/{moduleId}/instances") @ExposesResourceFor(AppInstanceStatusResource.class) public static class DeprecatedInstanceController { private final Collection<ModuleDeployer> moduleDeployers; @Autowired public DeprecatedInstanceController(Collection<ModuleDeployer> moduleDeployers) { this.moduleDeployers = new HashSet<>(moduleDeployers); } @RequestMapping public PagedResources<AppInstanceStatusResource> list(@PathVariable String moduleId, PagedResourcesAssembler<ModuleInstanceStatus> assembler) { ModuleDeploymentId moduleDeploymentId = ModuleDeploymentId.parse(moduleId); for (ModuleDeployer moduleDeployer : moduleDeployers) { ModuleStatus status = moduleDeployer.status(moduleDeploymentId); if (status != null) { List<ModuleInstanceStatus> moduleInstanceStatuses = new ArrayList<>(status.getInstances().values()); Collections.sort(moduleInstanceStatuses, INSTANCE_SORTER); return assembler.toResource(new PageImpl<>(moduleInstanceStatuses), new InstanceAssembler(status)); } } throw new ResourceNotFoundException(); } @RequestMapping("/{instanceId}") public AppInstanceStatusResource display(@PathVariable String moduleId, @PathVariable String instanceId) { ModuleDeploymentId moduleDeploymentId = ModuleDeploymentId.parse(moduleId); for (ModuleDeployer moduleDeployer : moduleDeployers) { ModuleStatus status = moduleDeployer.status(moduleDeploymentId); if (status != null) { ModuleInstanceStatus moduleInstanceStatus = status.getInstances().get(instanceId); if (moduleInstanceStatus == null) { throw new ResourceNotFoundException(); } return new InstanceAssembler(status).toResource(moduleInstanceStatus); } } throw new ResourceNotFoundException(); } } @ResponseStatus(HttpStatus.NOT_FOUND) private static class ResourceNotFoundException extends RuntimeException { } private static class InstanceAssembler extends ResourceAssemblerSupport<ModuleInstanceStatus, AppInstanceStatusResource> { private final ModuleStatus owningModule; public InstanceAssembler(ModuleStatus owningModule) { super(DeprecatedInstanceController.class, AppInstanceStatusResource.class); this.owningModule = owningModule; } @Override public AppInstanceStatusResource toResource(ModuleInstanceStatus entity) { return createResourceWithId("/" + entity.getId(), entity, owningModule.getModuleDeploymentId().toString()); } @Override protected AppInstanceStatusResource instantiateResource(ModuleInstanceStatus entity) { return new AppInstanceStatusResource(entity.getId(), entity.getState().name(), entity.getAttributes()); } } }
3e0ddd7684eeb7fe04e3498542d1c52a60088835
672
java
Java
src/main/java/com/javaconcepts/networking/URLDemo.java
sumon-dey/JavaConcepts
3c532f682f14807e6280ace12827a79d365f5f01
[ "Apache-2.0" ]
44
2019-07-21T13:07:03.000Z
2022-03-20T19:54:05.000Z
src/main/java/com/javaconcepts/networking/URLDemo.java
SandeepDhamale19/Java.Concepts
6602eee763e30603566374fc1ebdfea303d4fd3c
[ "Apache-2.0" ]
null
null
null
src/main/java/com/javaconcepts/networking/URLDemo.java
SandeepDhamale19/Java.Concepts
6602eee763e30603566374fc1ebdfea303d4fd3c
[ "Apache-2.0" ]
17
2020-01-12T13:10:21.000Z
2021-11-27T09:52:08.000Z
32
101
0.703869
5,878
package com.javaconcepts.networking; import java.net.MalformedURLException; import java.net.URL; public class URLDemo { /* * The URL class provides a simple, concise API to access information across the * Internet using URLs */ public static void main(String[] args) throws MalformedURLException { URL url = new URL("https://www.linkedin.com/"); System.out.println("Protocol: " + url.getProtocol()); System.out.println("Port: " + url.getPort()); // -1 output means that a port was not explicitly set System.out.println("Host: " + url.getHost()); System.out.println("File: " + url.getFile()); System.out.println("Ext: " + url.toExternalForm()); } }
3e0dde2e09db8ea0191b54a8f85ef08ca4d045be
1,810
java
Java
src/LeetCode36.java
ldk123456/LeetCode
601ed347f75ac6a6fd084665cf9a89125d234c86
[ "Apache-2.0" ]
null
null
null
src/LeetCode36.java
ldk123456/LeetCode
601ed347f75ac6a6fd084665cf9a89125d234c86
[ "Apache-2.0" ]
null
null
null
src/LeetCode36.java
ldk123456/LeetCode
601ed347f75ac6a6fd084665cf9a89125d234c86
[ "Apache-2.0" ]
null
null
null
34.807692
64
0.261326
5,879
public class LeetCode36 { public static void main(String[] args) { char[][] nums=new char[][]{ {'5','3','.','.','7','.','.','.','.'}, {'6','.','.','1','9','5','.','.','.'}, {'.','9','8','.','.','.','.','6','.'}, {'8','.','.','.','6','.','.','.','3'}, {'4','.','.','8','.','3','.','.','1'}, {'7','.','.','.','2','.','.','.','6'}, {'.','6','.','.','.','.','2','8','.'}, {'.','.','.','4','1','9','.','.','5'}, {'.','.','.','.','8','.','.','7','9'} }; System.out.println(isValidSudoku(nums)); } //有效的数独 public static boolean isValidSudoku(char[][] board) { for(int i=0;i<9;i++){ int[] row=new int[9]; int[] col=new int[9]; int[] cude=new int[9]; for(int j=0;j<9;j++){ if(board[i][j]!='.'){ if(row[board[i][j]-'1']==1){ return false; }else { row[board[i][j]-'1']=1; } } if(board[j][i]!='.'){ if(col[board[j][i]-'1']==1){ return false; }else { col[board[j][i]-'1']=1; } } int rowIndex=3*(i/3)+j/3; int colIndex=3*(i%3)+j%3; if(board[rowIndex][colIndex]!='.'){ if (cude[board[rowIndex][colIndex]-'1']==1){ return false; }else { cude[board[rowIndex][colIndex]-'1']=1; } } } } return true; } }
3e0dde80bcb0af5cac14aaa152883fd41815257a
1,884
java
Java
src/main/java/cn/master/track/entity/SummaryItemRef.java
crazyone2one/issue-track-manage
8c4d776d4593c966c3a53a3532ded744afc5e9c7
[ "MIT" ]
1
2021-08-13T03:12:38.000Z
2021-08-13T03:12:38.000Z
src/main/java/cn/master/track/entity/SummaryItemRef.java
crazyone2one/issue-track-manage
8c4d776d4593c966c3a53a3532ded744afc5e9c7
[ "MIT" ]
1
2021-08-17T09:32:54.000Z
2021-08-18T03:12:48.000Z
src/main/java/cn/master/track/entity/SummaryItemRef.java
crazyone2one/issue-track-manage
8c4d776d4593c966c3a53a3532ded744afc5e9c7
[ "MIT" ]
1
2022-03-20T10:48:41.000Z
2022-03-20T10:48:41.000Z
20.478261
54
0.653928
5,880
package cn.master.track.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import java.io.Serializable; /** * <p> * * </p> * * @author 11's papa * @since 2021-08-04 */ @Data @EqualsAndHashCode(callSuper = false) @TableName("summary_item_ref") @Builder public class SummaryItemRef implements Serializable { private static final long serialVersionUID = 1L; /** * 主键id */ @TableId(value = "id",type = IdType.ASSIGN_UUID) private String id; /** * summary表主键id */ @TableField("summary_id") private String summaryId; /** * item表主键id */ @TableField("item_id") private String itemId; /** * 问题单时间 */ @TableField("issue_date") private String issueDate; /** * 新建轻微级别问题单数量 */ @TableField("create_bug_slight") private Integer createBugSlight; /** * 新建一般级别问题单数量 */ @TableField("create_bug_ordinary") private Integer createBugOrdinary; /** * 新建致命级别问题单数量 */ @TableField("create_bug_deadly") private Integer createBugDeadly; /** * 新建严重级别问题单数量 */ @TableField("create_bug_severity") private Integer createBugSeverity; /** * 回测轻微级别问题单数量 */ @TableField("review_bug_slight") private Integer reviewBugSlight; /** * 回测一般级别问题单数量 */ @TableField("review_bug_ordinary") private Integer reviewBugOrdinary; /** * 回测严重级别问题单数量 */ @TableField("review_bug_severity") private Integer reviewBugSeverity; /** * 回测致命级别问题单数量 */ @TableField("review_bug_deadly") private Integer reviewBugDeadly; }
3e0ddf436afbec39711cc8ce79825b9ff70a6e2d
9,616
java
Java
components/org.wso2.carbon.identity.sso.saml/src/main/java/org/wso2/carbon/identity/sso/saml/builders/encryption/DefaultSSOEncrypter.java
somindatommy/identity-inbound-auth-saml
f3731229a40b21022beaaca217a39ba083abc85f
[ "Apache-2.0" ]
3
2017-11-01T20:09:46.000Z
2020-03-27T03:01:50.000Z
components/org.wso2.carbon.identity.sso.saml/src/main/java/org/wso2/carbon/identity/sso/saml/builders/encryption/DefaultSSOEncrypter.java
somindatommy/identity-inbound-auth-saml
f3731229a40b21022beaaca217a39ba083abc85f
[ "Apache-2.0" ]
88
2016-03-31T10:38:12.000Z
2022-03-03T14:48:23.000Z
components/org.wso2.carbon.identity.sso.saml/src/main/java/org/wso2/carbon/identity/sso/saml/builders/encryption/DefaultSSOEncrypter.java
somindatommy/identity-inbound-auth-saml
f3731229a40b21022beaaca217a39ba083abc85f
[ "Apache-2.0" ]
137
2016-03-02T10:11:26.000Z
2022-02-23T05:36:01.000Z
46.009569
161
0.705491
5,881
/* * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.sso.saml.builders.encryption; import org.apache.xml.security.utils.Base64; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.saml.saml2.core.Assertion; import org.opensaml.saml.saml2.core.EncryptedAssertion; import org.opensaml.saml.saml2.encryption.Encrypter; import org.opensaml.core.xml.XMLObject; import org.opensaml.core.xml.XMLObjectBuilder; import org.opensaml.security.crypto.KeySupport; import org.opensaml.xmlsec.algorithm.AlgorithmSupport; import org.opensaml.xmlsec.encryption.EncryptedKey; import org.opensaml.xmlsec.encryption.support.DataEncryptionParameters; import org.opensaml.xmlsec.encryption.support.KeyEncryptionParameters; import org.opensaml.security.credential.CredentialSupport; import org.opensaml.security.credential.Credential; import org.opensaml.xmlsec.keyinfo.impl.StaticKeyInfoGenerator; import org.opensaml.security.x509.X509Credential; import org.opensaml.xmlsec.signature.KeyInfo; import org.opensaml.xmlsec.signature.X509Certificate; import org.opensaml.xmlsec.signature.X509Data; import net.shibboleth.utilities.java.support.xml.NamespaceSupport; import org.opensaml.xmlsec.signature.support.SignatureConstants; import org.wso2.carbon.identity.application.common.util.IdentityApplicationManagementUtil; import org.wso2.carbon.identity.base.IdentityException; import org.wso2.carbon.identity.sso.saml.builders.X509CredentialImpl; import javax.xml.namespace.QName; import java.security.cert.CertificateEncodingException; import java.util.List; public class DefaultSSOEncrypter implements SSOEncrypter { private static final String prefix = "ds"; @Override public void init() throws IdentityException { //Overridden method, no need to implement the body } @Override public EncryptedAssertion doEncryptedAssertion(Assertion assertion, X509Credential cred, String alias, String encryptionAlgorithm) throws IdentityException { try { String keyAlgorithm = AlgorithmSupport.getKeyAlgorithm(IdentityApplicationManagementUtil .getAssertionEncryptionAlgorithmURIByConfig()); Integer keyAlgorithmKeyLength = AlgorithmSupport.getKeyLength(IdentityApplicationManagementUtil .getAssertionEncryptionAlgorithmURIByConfig()); Credential symmetricCredential; if (keyAlgorithm != null && keyAlgorithmKeyLength != null) { symmetricCredential = CredentialSupport.getSimpleCredential( KeySupport.generateKey(keyAlgorithm, keyAlgorithmKeyLength, null)); } else { throw new IdentityException("Invalid assertion encryption algorithm"); } DataEncryptionParameters encParams = new DataEncryptionParameters(); encParams.setAlgorithm(IdentityApplicationManagementUtil .getAssertionEncryptionAlgorithmURIByConfig()); encParams.setEncryptionCredential(symmetricCredential); KeyEncryptionParameters keyEncryptionParameters = new KeyEncryptionParameters(); keyEncryptionParameters.setAlgorithm(IdentityApplicationManagementUtil .getKeyEncryptionAlgorithmURIByConfig()); keyEncryptionParameters.setEncryptionCredential(cred); Encrypter encrypter = new Encrypter(encParams, keyEncryptionParameters); encrypter.setKeyPlacement(Encrypter.KeyPlacement.INLINE); EncryptedAssertion encrypted = encrypter.encrypt(assertion); appendNamespaceDeclaration(encrypted); return encrypted; } catch (Exception e) { throw IdentityException.error("Error while Encrypting Assertion", e); } } @Override public EncryptedAssertion doEncryptedAssertion(Assertion assertion, X509Credential cred, String alias, String assertionEncryptionAlgorithm, String keyEncryptionAlgorithm) throws IdentityException { try { String keyAlgorithm = AlgorithmSupport.getKeyAlgorithm(assertionEncryptionAlgorithm); Integer keyAlgorithmKeyLength = AlgorithmSupport.getKeyLength(assertionEncryptionAlgorithm); Credential symmetricCredential; if (keyAlgorithm != null && keyAlgorithmKeyLength != null) { symmetricCredential = CredentialSupport.getSimpleCredential( KeySupport.generateKey(keyAlgorithm, keyAlgorithmKeyLength, null)); } else { throw new IdentityException("Invalid assertion encryption algorithm"); } DataEncryptionParameters encParams = new DataEncryptionParameters(); encParams.setAlgorithm(assertionEncryptionAlgorithm); encParams.setEncryptionCredential(symmetricCredential); KeyEncryptionParameters keyEncryptionParameters = new KeyEncryptionParameters(); keyEncryptionParameters.setAlgorithm(keyEncryptionAlgorithm); keyEncryptionParameters.setEncryptionCredential(cred); KeyInfo keyInfo = (KeyInfo) buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME); X509Data data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME); X509Certificate cert = (X509Certificate) buildXMLObject(X509Certificate.DEFAULT_ELEMENT_NAME); String value; try { value = Base64.encode(((X509CredentialImpl) cred).getSigningCert().getEncoded()); } catch (CertificateEncodingException e) { throw IdentityException.error("Error occurred while retrieving encoded cert", e); } cert.setValue(value); data.getX509Certificates().add(cert); keyInfo.getX509Datas().add(data); keyEncryptionParameters.setKeyInfoGenerator(new StaticKeyInfoGenerator(keyInfo)); Encrypter encrypter = new Encrypter(encParams, keyEncryptionParameters); encrypter.setKeyPlacement(Encrypter.KeyPlacement.INLINE); EncryptedAssertion encrypted = encrypter.encrypt(assertion); appendNamespaceDeclaration(encrypted); return encrypted; } catch (Exception e) { throw IdentityException.error("Error while Encrypting Assertion", e); } } /** * Builds SAML Elements * * @param objectQName * @return * @throws IdentityException */ private XMLObject buildXMLObject(QName objectQName) throws IdentityException { XMLObjectBuilder builder = XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(objectQName); if (builder == null) { throw IdentityException.error("Unable to retrieve builder for object QName " + objectQName); } return builder.buildObject(objectQName.getNamespaceURI(), objectQName.getLocalPart(), objectQName.getPrefix()); } /** * The process below will append a namespace declaration to the encrypted assertion. * This is executed due to the fact that one of the attributes required does not get * set automatically in OpenSAML 3 as in OpenSAML 2. If this process is skipped then * an error will be thrown when decrypting the assertion. * * @param encryptedAssertion The encrypted assertion. * @throws IdentityException If the namespace declaration cannot be set. */ private void appendNamespaceDeclaration(EncryptedAssertion encryptedAssertion) throws IdentityException { Boolean isNamespaceSet = false; String errorMessage = "Failed to set Namespace Declaration"; if (encryptedAssertion.getEncryptedData().getKeyInfo() != null && encryptedAssertion.getEncryptedData().getKeyInfo().getEncryptedKeys().size() > 0) { List<EncryptedKey> encryptedKeys = encryptedAssertion.getEncryptedData().getKeyInfo().getEncryptedKeys(); for (EncryptedKey encryptedKey : encryptedKeys) { if (encryptedKey.getEncryptionMethod() != null && encryptedKey.getEncryptionMethod().hasChildren()) { for (XMLObject encryptedKeyChildElement : encryptedKey.getEncryptionMethod().getOrderedChildren()) { if (encryptedKeyChildElement.getElementQName().getLocalPart().equals("DigestMethod")) { if (encryptedKeyChildElement.getDOM() != null) { NamespaceSupport.appendNamespaceDeclaration(encryptedKeyChildElement.getDOM(), SignatureConstants.XMLSIG_NS, prefix); isNamespaceSet = true; } } } } } if (!isNamespaceSet) { throw new IdentityException(errorMessage); } } else { throw new IdentityException(errorMessage); } } }
3e0ddfbd83af16000901118bdf3a4b7f3cafb8b8
1,879
java
Java
oap-server/server-storage-plugin/storage-jdbc-hikaricp-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/jdbc/mysql/MySQLStorageConfig.java
Conanjun/skywalking
955dc7c54bd6970801c40ccb7550c1d0cf69ec6f
[ "Apache-2.0" ]
13,111
2017-12-13T01:09:29.000Z
2022-03-31T11:39:37.000Z
oap-server/server-storage-plugin/storage-jdbc-hikaricp-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/jdbc/mysql/MySQLStorageConfig.java
Conanjun/skywalking
955dc7c54bd6970801c40ccb7550c1d0cf69ec6f
[ "Apache-2.0" ]
5,145
2019-04-20T01:55:01.000Z
2022-03-31T08:07:26.000Z
oap-server/server-storage-plugin/storage-jdbc-hikaricp-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/jdbc/mysql/MySQLStorageConfig.java
Conanjun/skywalking
955dc7c54bd6970801c40ccb7550c1d0cf69ec6f
[ "Apache-2.0" ]
4,259
2019-04-20T12:02:37.000Z
2022-03-31T10:55:45.000Z
33.553571
132
0.716871
5,882
/* * 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.skywalking.oap.server.storage.plugin.jdbc.mysql; import java.util.Properties; import lombok.Getter; import lombok.Setter; import org.apache.skywalking.oap.server.library.module.ModuleConfig; @Setter @Getter public class MySQLStorageConfig extends ModuleConfig { private int metadataQueryMaxSize = 5000; /** * Inherit from {@link org.apache.skywalking.oap.server.storage.plugin.jdbc.h2.H2StorageConfig#getMaxSizeOfArrayColumn()} * * @since 8.2.0 */ private int maxSizeOfArrayColumn = 20; /** * Inherit from {@link org.apache.skywalking.oap.server.storage.plugin.jdbc.h2.H2StorageConfig#getNumOfSearchableValuesPerTag()} * * @since 8.2.0 */ private int numOfSearchableValuesPerTag = 2; /** * The maximum size of batch size of SQL execution * * @since 8.8.0 */ private int maxSizeOfBatchSql = 2000; /** * async batch execute pool size * * @since 8.8.0 */ private int asyncBatchPersistentPoolSize = 4; private Properties properties; }
3e0de15719f451999b2d841e8e30f0a0e2f72733
4,293
java
Java
spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RequestMappingEndpointTests.java
ooroor/spring-boot
20bb9c030504a24187ca72ade3285d86350b8cc0
[ "Apache-2.0" ]
1
2015-03-11T03:14:16.000Z
2015-03-11T03:14:16.000Z
spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RequestMappingEndpointTests.java
hwy1782/spring-boot
d9ca0869b527b1e202574cc82e9ccaa4d7b6088c
[ "Apache-2.0" ]
null
null
null
spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RequestMappingEndpointTests.java
hwy1782/spring-boot
d9ca0869b527b1e202574cc82e9ccaa4d7b6088c
[ "Apache-2.0" ]
null
null
null
39.75
80
0.77079
5,883
/* * Copyright 2012-2013 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 org.springframework.boot.actuate.endpoint; import java.util.Arrays; import java.util.Collections; import java.util.Map; import org.junit.Test; import org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping; import org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter; import org.springframework.context.support.StaticApplicationContext; import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping; import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping; import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author Dave Syer */ public class RequestMappingEndpointTests { private RequestMappingEndpoint endpoint = new RequestMappingEndpoint(); @Test public void concreteUrlMappings() { SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setUrlMap(Collections.singletonMap("/foo", new Object())); mapping.setApplicationContext(new StaticApplicationContext()); mapping.initApplicationContext(); this.endpoint.setHandlerMappings(Collections .<AbstractUrlHandlerMapping> singletonList(mapping)); Map<String, Object> result = this.endpoint.invoke(); assertEquals(1, result.size()); @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) result.get("/foo"); assertEquals("java.lang.Object", map.get("type")); } @Test public void beanUrlMappings() { StaticApplicationContext context = new StaticApplicationContext(); SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setUrlMap(Collections.singletonMap("/foo", new Object())); mapping.setApplicationContext(context); mapping.initApplicationContext(); context.getDefaultListableBeanFactory().registerSingleton("mapping", mapping); this.endpoint.setApplicationContext(context); Map<String, Object> result = this.endpoint.invoke(); assertEquals(1, result.size()); @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) result.get("/foo"); assertEquals("mapping", map.get("bean")); } @Test public void beanMethodMappings() { StaticApplicationContext context = new StaticApplicationContext(); EndpointHandlerMapping mapping = new EndpointHandlerMapping( Arrays.asList(new EndpointMvcAdapter(new DumpEndpoint()))); mapping.setApplicationContext(new StaticApplicationContext()); mapping.afterPropertiesSet(); context.getDefaultListableBeanFactory().registerSingleton("mapping", mapping); this.endpoint.setApplicationContext(context); Map<String, Object> result = this.endpoint.invoke(); assertEquals(1, result.size()); assertTrue(result.keySet().iterator().next().contains("/dump")); @SuppressWarnings("unchecked") Map<String, Object> handler = (Map<String, Object>) result.values().iterator() .next(); assertTrue(handler.containsKey("method")); } @Test public void concreteMethodMappings() { EndpointHandlerMapping mapping = new EndpointHandlerMapping( Arrays.asList(new EndpointMvcAdapter(new DumpEndpoint()))); mapping.setApplicationContext(new StaticApplicationContext()); mapping.afterPropertiesSet(); this.endpoint.setMethodMappings(Collections .<AbstractHandlerMethodMapping<?>> singletonList(mapping)); Map<String, Object> result = this.endpoint.invoke(); assertEquals(1, result.size()); assertTrue(result.keySet().iterator().next().contains("/dump")); @SuppressWarnings("unchecked") Map<String, Object> handler = (Map<String, Object>) result.values().iterator() .next(); assertTrue(handler.containsKey("method")); } }
3e0de43bf69c7abd57c9b236a3b2bf8d6721c94a
1,117
java
Java
src/lec3/threadJava.java
MaxMls/KotlinLsns
5b88d19ba8e8abc6bc4adf0c51a1946d26b44996
[ "MIT" ]
2
2020-09-26T02:35:21.000Z
2021-09-22T13:54:16.000Z
src/lec3/threadJava.java
MaxMls/KotlinLsns
5b88d19ba8e8abc6bc4adf0c51a1946d26b44996
[ "MIT" ]
null
null
null
src/lec3/threadJava.java
MaxMls/KotlinLsns
5b88d19ba8e8abc6bc4adf0c51a1946d26b44996
[ "MIT" ]
7
2019-10-02T22:45:37.000Z
2020-12-18T02:25:27.000Z
20.309091
87
0.589078
5,884
package lec3; class SomeThread implements Runnable { public void run() { System.out.println("Other thread"); } } class MyThread extends Thread { @Override public void run() { System.out.println("My thread!"); } } public class threadJava { //static MyThread myThread; public static void main(String[] args) { SomeThread t = new SomeThread(); Thread thread = new Thread(t); thread.start(); //Thread thread2 = new Thread(new Runnable() { // public void run() // { // System.out.println("thread 2!"); // } //}); //thread2.start(); //myThread = new MyThread(); //Создание потока //myThread.start(); System.out.println("Main finish"); } } //Thread.sleep() //Thread.yield() заставляет процессор переключиться на обработку других потоков системы /* while(!smth) //Пока в очереди нет сообщений { Thread.yield(); //Передать управление другим потокам } //Thread.join() ждет другой поток */ //Thread.stop() Thread.suspend() Thread.resume(),
3e0de55158e9fdbe29a557844697dfe379dcb1df
676
java
Java
divconq.core/src/main/java/divconq/db/rocks/keyquery/KeyLevel.java
Gadreel/divconq
28520b38cc77f77ef26ca74228a5cbf535960b31
[ "Apache-2.0" ]
12
2015-02-14T07:41:42.000Z
2021-02-09T06:11:26.000Z
divconq.core/src/main/java/divconq/db/rocks/keyquery/KeyLevel.java
Gadreel/divconq
28520b38cc77f77ef26ca74228a5cbf535960b31
[ "Apache-2.0" ]
76
2015-01-06T13:50:46.000Z
2016-05-17T00:50:39.000Z
divconq.core/src/main/java/divconq/db/rocks/keyquery/KeyLevel.java
Gadreel/divconq
28520b38cc77f77ef26ca74228a5cbf535960b31
[ "Apache-2.0" ]
7
2015-09-11T04:14:47.000Z
2020-12-20T21:27:07.000Z
24.142857
91
0.711538
5,885
package divconq.db.rocks.keyquery; import divconq.lang.Memory; abstract public class KeyLevel { protected KeyLevel next = null; public boolean contains(byte[] key, boolean browseMode, Memory browseKey) { return this.compare(key, 0, browseMode, browseKey) == 0; } public byte[] next() { //if (!this.nextSeek()) // return null; Memory key = new Memory(2048); this.buildSeek(key); return key.toArray(); } // return 0 if does not contain, N past offset when does contain abstract public int compare(byte[] key, int offset, boolean browseMode, Memory browseKey); abstract public void buildSeek(Memory mem); abstract public void resetLast(); }
3e0de682d86747fb4521e565a955f386d8f97c31
794
java
Java
MapReduceExcercises/src/main/java/com/theprogrammersbook/mapreduce/wordcount/WCMapper.java
theprogrammersbook/hadoopTutorial
bc26bea2d741e63d20d93d4c02795c84c614d2f6
[ "Apache-2.0" ]
null
null
null
MapReduceExcercises/src/main/java/com/theprogrammersbook/mapreduce/wordcount/WCMapper.java
theprogrammersbook/hadoopTutorial
bc26bea2d741e63d20d93d4c02795c84c614d2f6
[ "Apache-2.0" ]
null
null
null
MapReduceExcercises/src/main/java/com/theprogrammersbook/mapreduce/wordcount/WCMapper.java
theprogrammersbook/hadoopTutorial
bc26bea2d741e63d20d93d4c02795c84c614d2f6
[ "Apache-2.0" ]
null
null
null
36.090909
116
0.760705
5,886
package com.theprogrammersbook.mapreduce.wordcount; import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class WCMapper extends Mapper<LongWritable, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { StringTokenizer tokenizer = new StringTokenizer(value.toString().replaceAll("\\p{Punct}|\\d", "").toLowerCase()); while (tokenizer.hasMoreTokens()) { word.set(tokenizer.nextToken()); context.write(word, one); } } }
3e0de71d2d3f256e46e20af0b5d9e7f68a6ebb94
2,545
java
Java
test/src/test/java/issueTracker/StepDefinitions/CreateIssueStepDefs.java
KodstarBootcamp/issue-tracker-2020-3
e3364ac8f8e6f8963ca646ea71847c43f191e311
[ "MIT" ]
null
null
null
test/src/test/java/issueTracker/StepDefinitions/CreateIssueStepDefs.java
KodstarBootcamp/issue-tracker-2020-3
e3364ac8f8e6f8963ca646ea71847c43f191e311
[ "MIT" ]
77
2020-12-19T21:46:35.000Z
2021-01-21T00:21:34.000Z
test/src/test/java/issueTracker/StepDefinitions/CreateIssueStepDefs.java
KodstarBootcamp/issue-tracker-2020-3
e3364ac8f8e6f8963ca646ea71847c43f191e311
[ "MIT" ]
3
2021-02-24T09:53:21.000Z
2021-11-22T20:36:40.000Z
34.391892
133
0.674263
5,887
package issueTracker.StepDefinitions; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import issueTracker.Utilities.ConfigReader; import issueTracker.Utilities.Driver; import issueTracker.Utilities.Pages; import javafx.beans.value.WeakChangeListener; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import java.util.ArrayList; import java.util.List; public class CreateIssueStepDefs { Pages pages = new Pages(); @Given("user on the homepage") public void user_on_the_homepage() { Driver.getDriver().get(ConfigReader.getProperty("homepage")); } @Given("user clicks on add new button") public void user_clicks_on_add_new_button() { pages.homePage().addNewButton.click(); } @Given("user is directed to {string} page") public void user_is_directed_to_page(String string) { Assert.assertTrue(pages.addNewPage().text.isDisplayed()); } @Given("user enters {string}") public void user_enters(String title) { pages.addNewPage().title.sendKeys(title); } @Given("user enters description") public void user_enters_description() { pages.addNewPage().description.sendKeys("test desc"); } @Given("user enters labels") public void user_enters_labels() { pages.addNewPage().labels.sendKeys("labels test"); } @Given("user clicks on create new issue button") public void user_clicks_on_create_new_issue_button() { pages.addNewPage().createButton.click(); } @Then("verify that issue list has {string}") public void verify_that_issue_list_has(String title) { List<String> rowText= new ArrayList<>(); for (int i=0;i<pages.issueListPage().rows.size();i++){ rowText.add(pages.issueListPage().rows.get(i).getText()); System.out.println(pages.issueListPage().rows.get(i).getText()); if(pages.issueListPage().rows.get(i).getText().equals(title)){ JavascriptExecutor js = (JavascriptExecutor)Driver.getDriver(); int row = i+1; WebElement actualTitle = Driver.getDriver().findElement(By.xpath("//tbody//tr["+row+"]")); js.executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid green;');", actualTitle); System.out.println(i); } } Assert.assertTrue("Creation failure", rowText.contains(title)); } }
3e0de7f47c86064a1ee0137e19ad9894c75fe50e
53,883
java
Java
app/src/main/java/project/java/tbusdriver/Controller/Travel.java
orItach/TbusDriver
f73bf38f5b21bbcd34517f8210c61f71f25cec98
[ "Apache-2.0" ]
null
null
null
app/src/main/java/project/java/tbusdriver/Controller/Travel.java
orItach/TbusDriver
f73bf38f5b21bbcd34517f8210c61f71f25cec98
[ "Apache-2.0" ]
3
2019-05-31T11:36:06.000Z
2019-08-19T20:05:40.000Z
app/src/main/java/project/java/tbusdriver/Controller/Travel.java
orItach/TbusDriver
f73bf38f5b21bbcd34517f8210c61f71f25cec98
[ "Apache-2.0" ]
null
null
null
39.625
154
0.58792
5,888
package project.java.tbusdriver.Controller; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.ClipData; import android.content.ClipDescription; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.ColorStateList; import android.graphics.Color; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.design.widget.FloatingActionButton; import android.support.percent.PercentRelativeLayout; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.content.ContextCompat; import android.util.DisplayMetrics; import android.util.Log; import android.view.DragEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationResult; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.places.Places; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import project.java.tbusdriver.Const; import project.java.tbusdriver.Controller.Adapter.StationsAdapter; import project.java.tbusdriver.Database.Factory; import project.java.tbusdriver.Database.ListDsManager; import project.java.tbusdriver.Entities.MyLocation; import project.java.tbusdriver.Entities.Ride; import project.java.tbusdriver.R; import project.java.tbusdriver.Service.updateLocationService; import project.java.tbusdriver.usefulFunctions; import static android.content.Context.LOCATION_SERVICE; import static java.lang.Math.pow; import static project.java.tbusdriver.Const.AvailableRidesListName; import static project.java.tbusdriver.usefulFunctions.POST; public class Travel extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, View.OnClickListener , com.google.android.gms.location.LocationListener { //GoogleApiClient.ConnectionCallbacks, //GoogleApiClient.OnConnectionFailedListener, //LocationListener { //region Variable // default zoom on the map private static int DEFAULT_ZOOM = 10; private GoogleApiClient mGoogleApiClient; // the map as object private GoogleMap mMap; // not in use boolean mRequestingLocationUpdates = true; // the client to get the current location FusedLocationProviderClient mFusedLocationClient; LocationCallback mLocationCallback; LocationRequest mLocationRequest; // bool that say if the location premmsion is granted private boolean mLocationPermissionGranted = false; // the last known location, not have to be the current private Location mLastKnownLocation = null; // same as above but the previous private Location mPreviousLastKnownLocation = null; // some const to req location premission private final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1; private LatLng mDefaultLocation; private CameraPosition mCameraPosition; public static final String TAG = Travel.class.getSimpleName(); View myView; FragmentActivity myActivity; private OnFragmentInteractionListener mListener; Button availableButton; Button busyButton; FloatingActionButton myFloating; // the map fragment as a object SupportMapFragment mapFragment; private MapView mMapView; public static Travel instance; LocationManager locationManager; Marker mPositionMarker; boolean doZoom; ListDsManager listDsManager; Ride ride; // bool say if we in ride public boolean inRoute; // bool say if we want to show the station list boolean showStations; ///SHOWSTATIONS ListView stationsList; ArrayList<MyLocation> stations; StationsAdapter stationsAdapter; TextView DragbleText; //endregion public Travel() { // Required empty public constructor } // implement the singleton pattern public static Travel newInstance() { if (instance == null) { instance = new Travel(); } else { return instance; } return instance; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); myActivity = getActivity(); doZoom = true; SharedPreferences sharedPref = myActivity.getPreferences(Context.MODE_PRIVATE); //boolean busySharedPreferences = getResources().getBoolean(Const.BusySharedPreferences); boolean busySharedPreferences = sharedPref.getBoolean(Const.BusySharedPreferences, false); usefulFunctions.busy =busySharedPreferences; locationManager = (LocationManager) myActivity.getSystemService(LOCATION_SERVICE); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) myActivity.getSupportFragmentManager() .findFragmentById(R.id.map); listDsManager = (ListDsManager) new Factory(getActivity()).getInstance(); //mapFragment.getMapAsync(this); // Do other setup activities here too, as described elsewhere in this tutorial. // Build the Play services client for use by the Fused Location Provider and the Places API. // Use the addApi() method to request the Google Places API and the Fused Location Provider. // define some parameter of the client location mFusedLocationClient = LocationServices.getFusedLocationProviderClient(myActivity); mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(3000000); mLocationRequest.setFastestInterval(5000); mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); // define what happen when we get the location mLocationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { for (Location location : locationResult.getLocations()) { if (mPreviousLastKnownLocation != null) { double LKLLo = mPreviousLastKnownLocation.getLongitude(); double LKLLa = mPreviousLastKnownLocation.getLatitude(); double LLo = location.getLongitude(); double LLa = location.getLatitude(); double deviation = 0.01; if (pow(deviation, 2) < pow((LKLLa - LLa), 2) + pow((LKLLo - LLo), 2)) usefulFunctions.showAlert(myActivity, "the location change"); } } } }; // define some parameter of the googleApiClient if (mGoogleApiClient == null || !mGoogleApiClient.isConnected()) { mGoogleApiClient = new GoogleApiClient.Builder(myActivity) .enableAutoManage(myActivity /* FragmentActivity */, this /* OnConnectionFailedListener */) .addConnectionCallbacks(this) //.addOnConnectionFailedListener(this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addApi(Places.PLACE_DETECTION_API) .build(); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment myView = inflater.inflate(R.layout.fragment_travel, container, false); availableButton = (Button) myView.findViewById(R.id.available); // you have to use rootview object.. availableButton.setOnClickListener(this); busyButton = (Button) myView.findViewById(R.id.busy); // you have to use rootview object.. busyButton.setOnClickListener(this); // define some view od the floating button myFloating = (FloatingActionButton) myView.findViewById(R.id.getMyLocation); // you have to use rootview object.. myFloating.bringToFront(); myFloating.setClickable(true); myFloating.setOnClickListener(this); myFloating.setBackgroundTintList(ColorStateList.valueOf(Color.RED)); mapFragment = (SupportMapFragment) myActivity.getSupportFragmentManager() .findFragmentById(R.id.map); mMapView = (MapView) myActivity.findViewById(R.id.map); PercentRelativeLayout allInstruction = (PercentRelativeLayout) myActivity.findViewById(R.id.allInstruction); allInstruction.bringToFront(); //stationsList =(ListView) myView.findViewById(R.id.DragbleText); //stationsList.setOnDragListener(new View.OnDragListener() stationsList = (ListView) myView.findViewById(R.id.stationList); DragbleText = (TextView) myView.findViewById(R.id.Test); // define what happen when hold the TextView DragbleText.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { ClipData.Item item = new ClipData.Item((CharSequence) v.getTag()); String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN}; //ClipData dragData = new ClipData(v.getTag().toString(),mimeTypes, item); View.DragShadowBuilder myShadow = new View.DragShadowBuilder(DragbleText); v.startDrag(null, myShadow, null, 0); return true; } }); // define what happen when drag the TextView DragbleText.setOnDragListener(new View.OnDragListener() { @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1) @Override public boolean onDrag(View v, DragEvent event) { int action = event.getAction(); PercentRelativeLayout.LayoutParams layoutParams = (PercentRelativeLayout.LayoutParams) v.getLayoutParams(); DisplayMetrics displayMetrics = myActivity.getResources().getDisplayMetrics(); // dpWidth is the 100% ? float dpWidth = displayMetrics.widthPixels / displayMetrics.density; switch (action) { case DragEvent.ACTION_DRAG_STARTED: //where its now int x_cord = (int) event.getX(); int y_cord = (int) event.getY(); v.invalidate(); // Invalidate the view to force a redraw in the new tint // returns true to indicate that the View can accept the dragged data. return true; case DragEvent.ACTION_DRAG_ENTERED: x_cord = (int) event.getX(); y_cord = (int) event.getY(); ShowListStations(); //usefulFunctions.showAlert(myActivity, "ACTION_DRAG_ENTERED x: " +x_cord + "y: " + y_cord); // Invalidate the view to force a redraw in the new tint v.invalidate(); return true; case DragEvent.ACTION_DRAG_LOCATION: x_cord = (int) event.getX(); y_cord = (int) event.getY(); //usefulFunctions.showAlert(myActivity, "ACTION_DRAG_LOCATION x: " +x_cord + "y: " + y_cord); //layoutParams.leftMargin = x_cord; //layoutParams.topMargin = y_cord; //v.setLayoutParams(layoutParams); // Ignore the event // return true; case DragEvent.ACTION_DRAG_EXITED: x_cord = (int) event.getX(); y_cord = (int) event.getY(); //usefulFunctions.showAlert(myActivity, "ACTION_DRAG_EXITED x: " +x_cord + "y: " + y_cord); // Invalidate the view to force a redraw in the new tint v.invalidate(); return true; case DragEvent.ACTION_DROP: //x_cord = (int) event.getX(); //y_cord = (int) event.getY(); // Invalidates the view to force a redraw v.invalidate(); // Returns true. DragEvent.getResult() will return true. return true; case DragEvent.ACTION_DRAG_ENDED: x_cord = (int) event.getX(); y_cord = (int) event.getY(); // Invalidates the view to force a redraw v.invalidate(); // returns true; the value is ignored. return true; // An unknown action type was received. default: Log.e("DragDrop Example", "Unknown action type received by OnDragListener."); break; } return true; } }); if(usefulFunctions.busy){ drawBusy(); } else { drawAvailable(); } return myView; } @Override public void onAttach(Context context) { super.onAttach(context); //onMapReady(); if (mMap != null) { //// Get the current location of the device and set the position of the map. DEFAULT_ZOOM = 16; getDeviceLocation(); //updateLocationUI(); } if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } if (getActivity() != null) { myActivity = getActivity(); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onStart() { super.onStart(); mGoogleApiClient.connect(); } //* This interface must be implemented by activities that contain this //* fragment to allow an interaction in this fragment to be communicated //* to the activity and potentially other fragments contained in that //* activity. //* <p> //* See the Android Training lesson <a href= //* "http://developer.android.com/training/basics/fragments/communicating.html" //* >Communicating with Other Fragments</a> for more information. //*/ public interface OnFragmentInteractionListener { void onFragmentInteraction(Uri uri); } /** * Builds the map when the Google Play services client is successfully connected. */ //region Connection Handler @Override public void onConnected(Bundle connectionHint) { Log.v(TAG, "onConnected"); if (mMap != null) { //// Get the current location of the device and set the position of the map. DEFAULT_ZOOM = 16; getDeviceLocation(); updateLocationUI(); } //mapFragment = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)); ////mapFragment = (SupportMapFragment) myActivity.getSupportFragmentManager() //// .findFragmentById(R.id.map); //if (mapFragment!=null){ // mapFragment.getMapAsync(this); // checkGPSEnable(); //} } @Override public void onConnectionSuspended(int i) { Log.v(TAG, "onConnectionSuspended"); //super.onConnectionSuspended(i); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Log.v(TAG, "onConnectionFailed"); //super.onConnectionFailed(connectionResult); } //endregion /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ //@Override //public void onMapReady(GoogleMap googleMap) { // mMap = googleMap; // // Add a marker in Sydney and move the camera // LatLng sydney = new LatLng(-34, 151); // mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney")); // mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); //} /** * Manipulates the map when it's available. * This callback is triggered when the map is ready to be used. */ // define what happen when we get the map object from google @SuppressLint("NewApi") @Override public void onMapReady(GoogleMap map) { mMap = map; //// Get the current location of the device and set the position of the map. if (mMap != null) { //// Get the current location of the device and set the position of the map. DEFAULT_ZOOM = 16; getDeviceLocation(); updateLocationUI(); } // define what happen when we are in route, e.g. draw route if (ride != null && inRoute) { drawMap(); drawStation(ride.getRoute().getLocations()); stations = ride.getRoute().getLocations(); if (showStations) { ShowListStations(); } drawRoute(ride.getRoute().getLocations()); DEFAULT_ZOOM = 13; if (mLastKnownLocation != null) { mMap.moveCamera(CameraUpdateFactory.newLatLngZoom( new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), DEFAULT_ZOOM)); } if (mLastKnownLocation == null && ride != null && ride.getRoute() != null) { MyLocation firstLocation = ride.getRoute().getLocations().get(0); LatLng newMapLocation = new LatLng(firstLocation.getMyLocation().getLatitude(), firstLocation.getMyLocation().getLongitude()); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom( newMapLocation, DEFAULT_ZOOM)); } } else { try { RemoveListStations(); } catch (Exception e) { Log.e("error", e.toString()); } } } //region Button Handler public void busy(View v) { myActivity.startService(new Intent(myActivity, updateLocationService.class)); if (mListener != null) { //mListener.onFragmentInteraction(uri); drawBusy(); usefulFunctions.busy = true; SharedPreferences sharedPref = myActivity.getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putBoolean(Const.BusySharedPreferences,true ); editor.commit(); //drawNavigationInstruction(); //setBigInstruction("left"); //setSmallInstructionP("right"); //drawStation(ride.getRoute().getLocations()); Double[] LatLng = new Double[2]; LatLng[0] = null; LatLng[1] = null; new Travel.UpdateLocation().execute(LatLng); } } // update the server with the current driver location static class UpdateLocation extends AsyncTask<Double, String, String> { @Override protected String doInBackground(Double... params) { //user[0]=Phone user[1]=User Name String toReturn = ""; try { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("lat", params[0]); parameters.put("lng", params[1]); toReturn = POST(Const.UPDATE_LOCATION_URI.toString(), parameters); String httpResult = new JSONObject(toReturn).getString("status"); if (httpResult.compareTo("OK") == 0) { //listDsManager.updateMyRides(toReturn); publishProgress(""); toReturn = ""; } else { publishProgress("something get wrong " + toReturn); } } catch (Exception e) { publishProgress(e.getMessage()); } return toReturn; } @Override protected void onPostExecute(String result) { if (result.equals("")) { //every thing is okay //mListener.onFragmentInteraction(""); } } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(String... values) { //user[0]=Phone user[1]=User Name //check if have any error if (values[0].length() > 1) { //showAlert(myActivity,values[0]); } else { //showAlert(myActivity,"נסיעה נלקחה בהצלחה"); //mCallBack.OnLoginFragmentInteractionListener(1); } } } public void available(View v) { if (mListener != null) { //mListener.onFragmentInteraction(uri); drawAvailable(); usefulFunctions.busy = false; SharedPreferences sharedPref = myActivity.getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putBoolean(Const.BusySharedPreferences,false ); editor.commit(); drawMap(); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.available: available(v); //myFloating.setDrawingCacheBackgroundColor(323); break; case R.id.busy: busy(v); break; case R.id.getMyLocation: if (mMap != null) { // Check to ensure coordinates aren't null, probably a better way of doing this... ///DEFAULT_ZOOM =14; // good for view nibgerood if (doZoom) { DEFAULT_ZOOM = 16; doZoom = false; } else { DEFAULT_ZOOM = 14; doZoom = true; } getDeviceLocation(); updateLocationUI(); } break; default: break; } } private void drawBusy(){ myFloating.setBackgroundTintList(ColorStateList.valueOf(Color.RED)); busyButton.setBackgroundResource(R.drawable.busy); availableButton.setBackgroundResource(R.drawable.start); } private void drawAvailable(){ myFloating.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); busyButton.setBackgroundResource(R.drawable.start); availableButton.setBackgroundResource(R.drawable.available); } //endregion //maybe here the problem, look good and work just one time private void getDeviceLocation() { boolean mLocationPermissionGranted = false; //permission handler if (ContextCompat.checkSelfPermission(myActivity.getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mLocationPermissionGranted = true; } else { ActivityCompat.requestPermissions(myActivity, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); } if (mLocationPermissionGranted) { mPreviousLastKnownLocation = mLastKnownLocation; mLastKnownLocation = LocationServices.FusedLocationApi .getLastLocation(mGoogleApiClient); //mFusedLocationClient.getLastLocation() // .addOnSuccessListener((Executor) myActivity, new OnSuccessListener<Location>() { // @Override // public void onSuccess(Location location) { // // Got last known location. In some rare situations this can be null. // if (location != null) { // // ... // } // } // }); } // Set the map's camera position to the current location of the device. //look like the problem is here if (mCameraPosition != null) { mMap.moveCamera(CameraUpdateFactory.newCameraPosition(mCameraPosition)); } else if (mLastKnownLocation != null) { mMap.moveCamera(CameraUpdateFactory.newLatLngZoom( new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), DEFAULT_ZOOM)); //mMap.getUiSettings().setMyLocationButtonEnabled(false); } else { LatLng jerusalem = new LatLng(31.75, 35.2); mMap.moveCamera(CameraUpdateFactory.newLatLng(jerusalem)); mMap.animateCamera(CameraUpdateFactory.zoomTo(DEFAULT_ZOOM)); Log.v(TAG, "Current location is null. Using defaults."); //the problem, probably DEFAULT_ZOOM initialize to something wrong //mMap.moveCamera(CameraUpdateFactory.newLatLn3. // gZoom(mDefaultLocation, DEFAULT_ZOOM)); //mMap.getUiSettings().setMyLocationButtonEnabled(false); } // A step later in the tutorial adds the code to get the device location. } // define what happen when we get the permission req result @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { mLocationPermissionGranted = false; switch (requestCode) { case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { mLocationPermissionGranted = true; } } } updateLocationUI(); } private void updateLocationUI() { if (mMap == null) { return; } /* * Request location permission, so that we can get the location of the * device. The result of the permission request is handled by a callback, * onRequestPermissionsResult. */ if (ContextCompat.checkSelfPermission(myActivity.getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mLocationPermissionGranted = true; } else { if (Build.VERSION.SDK_INT >= 23) { ActivityCompat.requestPermissions(myActivity, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); } else /////////////////////////check maybe need to be false mLocationPermissionGranted = true; } if (mLocationPermissionGranted) { mMap.setMyLocationEnabled(true); mMap.getUiSettings().setMyLocationButtonEnabled(true); mMap.getUiSettings().setMapToolbarEnabled(true); } else { mMap.setMyLocationEnabled(false); mMap.getUiSettings().setMapToolbarEnabled(false); mMap.getUiSettings().setMyLocationButtonEnabled(false); mLastKnownLocation = null;//? } } //region GPS Enable? private void checkGPSEnable() { if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { //Toast.makeText(myActivity, "GPS is Enabled in your device", Toast.LENGTH_SHORT).show(); } else { showGPSDisabledAlertToUser(); } } private void showGPSDisabledAlertToUser() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(myActivity); alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?") .setCancelable(false) .setPositiveButton("Goto Settings Page To Enable GPS", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent callGPSSettingIntent = new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(callGPSSettingIntent); } }); alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = alertDialogBuilder.create(); alert.show(); } //endregion @Override public void onResume() { super.onResume(); //if (mRequestingLocationUpdates) { // startLocationUpdates(); // //getDeviceLocation(); //} if (mMap != null) { //// Get the current location of the device and set the position of the map. DEFAULT_ZOOM = 16; //startLocationUpdates(); getDeviceLocation(); //updateLocationUI(); } if (!isHidden()) { int rideId; int index; myActivity = getActivity(); Bundle bundle = this.getArguments(); if (bundle != null) { boolean haveInMyRide =true; rideId = bundle.getInt("RIDEID", 0); index = ListDsManager.convertGroupIdToIndex("MyRide", rideId); if( index == -1){ index = ListDsManager.convertGroupIdToIndex(AvailableRidesListName,rideId); haveInMyRide = false; } if (haveInMyRide){ ride = ListDsManager.getMyRide().get(index); } else { ride = ListDsManager.getAvailableRides().get(index); } boolean showRide = bundle.getBoolean("SHOWSTATIONS"); ///SHOWRIDE if (showRide) { showStations = true; } inRoute = true; } //else //{ // try { // RemoveListStations(); // } catch (Exception e) { // Log.e("error", e.toString()); // } //} myActivity.setTitle("נסיעה"); mapFragment = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)); mapFragment.getMapAsync(this); } } private void startLocationUpdates() { if (ContextCompat.checkSelfPermission(myActivity.getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mLocationPermissionGranted = true; } else { ActivityCompat.requestPermissions(myActivity, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); } if (mLocationPermissionGranted) { mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null /* Looper */); } } @Override public void onPause() { super.onPause(); drawMap(); } //region NavigationInstruction private void drawNavigationInstruction() { if (getActivity() != null) { myActivity = getActivity(); RelativeLayout allInstruction = (RelativeLayout) myActivity.findViewById(R.id.allInstruction); allInstruction.setVisibility(View.VISIBLE); } //ins.invalidate(); } private void drawMap() { if (getActivity() != null) { myActivity = getActivity(); //PercentRelativeLayout allTravel=(PercentRelativeLayout)myActivity.findViewById(R.id.allTravel); //allTravel.bringToFront(); //allTravel.invalidate(); RelativeLayout allInstruction = (RelativeLayout) myActivity.findViewById(R.id.allInstruction); allInstruction.setVisibility(View.GONE); } } private void setBigInstruction(String direction) { ImageView imageFirstInstruction = (ImageView) myActivity.findViewById(R.id.imageFirstInstruction); TextView textFirstInstruction = (TextView) myActivity.findViewById(R.id.textFirstInstruction); switch (direction) { case "left": imageFirstInstruction.setImageResource(R.drawable.left); textFirstInstruction.setText("turn left"); break; case "right": textFirstInstruction.setText("turn right"); break; case "straight": break; case "left U-turn": break; } } private void setSmallInstructionP(String direction) { ImageView imageSecondInstruction = (ImageView) myActivity.findViewById(R.id.imageSecondInstruction); switch (direction) { case "left": break; case "right": imageSecondInstruction.setImageResource(R.drawable.rigth); break; case "straight": break; case "left U-turn": break; } } //endregion //region custom marker - currently not in use public void mLocationCallback(Location location) { if (location == null) return; //if (mPositionMarker == null) { // mPositionMarker = mMap.addMarker(new MarkerOptions() // .flat(false) // .anchor(0.5f, 0.5f) // .icon(BitmapDescriptorFactory // .fromResource(R.drawable.taxi)) // .position( // new LatLng(location.getLatitude(), location // .getLongitude()))); //} //animateMarker(mPositionMarker, location); // Helper method for smooth // animation //mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(location // .getLatitude(), location.getLongitude()))); } public void animateMarker(final Marker marker, final Location location) { final Handler handler = new Handler(); final long start = SystemClock.uptimeMillis(); final LatLng startLatLng = marker.getPosition(); final double startRotation = marker.getRotation(); final long duration = 500; final Interpolator interpolator = new LinearInterpolator(); handler.post(new Runnable() { @Override public void run() { long elapsed = SystemClock.uptimeMillis() - start; float t = interpolator.getInterpolation((float) elapsed / duration); double lng = t * location.getLongitude() + (1 - t) * startLatLng.longitude; double lat = t * location.getLatitude() + (1 - t) * startLatLng.latitude; float rotation = (float) (t * location.getBearing() + (1 - t) * startRotation); marker.setPosition(new LatLng(lat, lng)); marker.setRotation(rotation); if (t < 1.0) { // Post again 16ms later. handler.postDelayed(this, 16); } } }); } //end region //region routeAndDraw private void drawStation(@NonNull ArrayList<MyLocation> station) { for (int i = 1; i < station.size(); i++) { mMap.addMarker(new MarkerOptions() .position(new LatLng( station.get(i).getMyLocation().getLatitude(), station.get(i).getMyLocation().getLongitude())) .title("station " + i) ).showInfoWindow(); } } private void drawRoute(@NonNull ArrayList<MyLocation> station) { int numberOfStation = station.size() - 1; if (numberOfStation < 1) { usefulFunctions.showAlert(myActivity, "אין תחנות בנסיעה זאת, אנא פנה אלינו בהקדם"); return; } LatLng first = new LatLng(station.get(0).getMyLocation().getLatitude(), station.get(0).getMyLocation().getLongitude()); LatLng last = new LatLng(station.get(numberOfStation).getMyLocation().getLatitude(), station.get(numberOfStation).getMyLocation().getLongitude()); DragbleText.setVisibility(View.VISIBLE); myView.invalidate(); String url = getDirectionsUrl(first, last); // Start downloading json data from Google Directions API new Travel.DownloadTask().execute(url); //for (int i=0; i< station.size()-1; i++) //{ // mMap.addPolygon(new PolygonOptions() // .add(new LatLng( // station.get(i).getMyLocation().getLatitude(), // station.get(i).getMyLocation().getLongitude())) // .add(new LatLng( // station.get(i+1).getMyLocation().getLatitude(), // station.get(i+1).getMyLocation().getLongitude()) // ) // ); //} } private String getDirectionsUrl(@NonNull LatLng origin,@NonNull LatLng dest) { String str_origin = "origin=" + origin.latitude + "," + origin.longitude; String str_dest = "destination=" + dest.latitude + "," + dest.longitude; String sensor = "sensor=false"; // Building the parameters to the web service String parameters = str_origin + "&" + str_dest + "&" + sensor; // Output format String output = "json"; String keyParam = "key="+"caf86f4uutaoxfysmf7anj01xl6sv3ps"; // Building the url to the web service String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters + "&" + keyParam; return url; } private String downloadUrl(String strUrl) throws IOException { String data = ""; try { HttpURLConnection urlConnection = null; URL url = new URL(strUrl); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.connect(); try (InputStream iStream = urlConnection.getInputStream()) { // Creating an http connection to communicate with url // Connecting to url // Reading data from url BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); StringBuffer sb = new StringBuffer(); String line = ""; while ((line = br.readLine()) != null) { sb.append(line); } data = sb.toString(); br.close(); } catch (Exception e) { Log.d("Exception url", e.toString()); } finally { urlConnection.disconnect(); } } catch (Exception e){ Log.d("Exception url", e.toString()); } return data; } // req the route from google api private class DownloadTask extends AsyncTask<String, Void, String> { // Downloading data in non-ui thread @Override protected String doInBackground(String... url) { // For storing data from web service String data = ""; try { // Fetching the data from web service data = downloadUrl(url[0]); } catch (Exception e) { Log.d("Background Task", e.toString()); } return data; } // Executes in UI thread, after the execution of // doInBackground() @Override protected void onPostExecute(String result) { super.onPostExecute(result); ParserTask parserTask = new ParserTask(); // Invokes the thread for parsing the JSON data parserTask.execute(result); } } /** * A class to parse the Google Places in JSON format */ private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> { // Parsing the data in non-ui thread @Override protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) { JSONObject jObject; List<List<HashMap<String, String>>> routes = null; try { jObject = new JSONObject(jsonData[0]); //DirectionsJSONParser parser = new DirectionsJSONParser(); // Starts parsing data routes = parse(jObject); } catch (Exception e) { e.printStackTrace(); } return routes; } // Executes in UI thread, after the parsing process @Override protected void onPostExecute(List<List<HashMap<String, String>>> result) { ArrayList<LatLng> points = null; PolylineOptions lineOptions = new PolylineOptions(); MarkerOptions markerOptions = new MarkerOptions(); // Traversing through all the routes for (int i = 0; result != null && i < result.size(); i++) { points = new ArrayList<LatLng>(); lineOptions = new PolylineOptions(); // Fetching i-th route List<HashMap<String, String>> path = result.get(i); // Fetching all the points in i-th route for (int j = 0; j < path.size(); j++) { HashMap<String, String> point = path.get(j); double lat = Double.parseDouble(point.get("lat")); double lng = Double.parseDouble(point.get("lng")); LatLng position = new LatLng(lat, lng); points.add(position); } // Adding all the points in the route to LineOptions lineOptions.addAll(points); lineOptions.width(15); lineOptions.color(Color.BLUE); } // Drawing polyline in the Google Map for the i-th route mMap.addPolyline(lineOptions); } } public List<List<HashMap<String, String>>> parse(JSONObject jObject) { List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>(); JSONArray jRoutes = null; JSONArray jLegs = null; JSONArray jSteps = null; try { jRoutes = jObject.getJSONArray("routes"); /** Traversing all routes */ for (int i = 0; i < jRoutes.length(); i++) { jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs"); List path = new ArrayList<HashMap<String, String>>(); /** Traversing all legs */ for (int j = 0; j < jLegs.length(); j++) { jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps"); /** Traversing all steps */ for (int k = 0; k < jSteps.length(); k++) { String polyline = ""; polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points"); List<LatLng> list = decodePoly(polyline); /** Traversing all points */ for (int l = 0; l < list.size(); l++) { HashMap<String, String> hm = new HashMap<String, String>(); hm.put("lat", Double.toString(((LatLng) list.get(l)).latitude)); hm.put("lng", Double.toString(((LatLng) list.get(l)).longitude)); path.add(hm); } } routes.add(path); } } } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { } return routes; } private List<LatLng> decodePoly(@NonNull String encoded) { List<LatLng> poly = new ArrayList<LatLng>(); int index = 0, len = encoded.length(); int lat = 0, lng = 0; while (index < len) { int b, shift = 0, result = 0; do { b = encoded.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lat += dlat; shift = 0; result = 0; do { b = encoded.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lng += dlng; LatLng p = new LatLng((((double) lat / 1E5)), (((double) lng / 1E5))); poly.add(p); } return poly; } //end region public Location getmLastKnownLocation() { return mLastKnownLocation; } public void startRide(int rideId) { int index = ListDsManager.convertRideIdToIndex("MyRide", rideId); ride = ListDsManager.getMyRide().get(index); inRoute = true; } //Location update region // define what happen when the driver change is location private void handleNewLocation(Location location) { Log.d(TAG, location.toString()); double currentLatitude = location.getLatitude(); double currentLongitude = location.getLongitude(); LatLng latLng = new LatLng(currentLatitude, currentLongitude); int speed = (int) (location.getSpeed() * 2.2369); // send location data to server Intent myUpdateLocationServiceIntent = new Intent(getActivity(), updateLocationService.class); myUpdateLocationServiceIntent.putExtra("Lat", currentLatitude); myUpdateLocationServiceIntent.putExtra("Lng", currentLongitude); try { getContext().startService(myUpdateLocationServiceIntent); } catch (Exception e) { int x = 5; } //if (isSubscribed) { // JSONObject json = new JSONObject(); // try { // json.put("lat", currentLatitude); // json.put("long", currentLongitude); // json.put("time", location.getTime()); // json.put("accuracy", location.getAccuracy()); // json.put("speed", speed); // json.put("latLng", latLng); // mChannel.trigger("client-location-changed", json.toString()); // } catch (JSONException e) { // Log.e(TAG, "Problem adding JSON"); // } //} } @Override public void onLocationChanged(Location location) { handleNewLocation(location); } @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1) private void ShowListStations() { float dpHeight = getDpHeight(); availableButton.setVisibility(View.GONE); busyButton.setVisibility(View.GONE); myFloating.setVisibility(View.GONE); if (mapFragment.getView() != null) { ViewGroup.LayoutParams mapFragmentParams = mapFragment.getView().getLayoutParams(); mapFragmentParams.height = (int) (dpHeight * 1.50); mapFragment.getView().setLayoutParams(mapFragmentParams); } ViewGroup.LayoutParams stationsListParams = stationsList.getLayoutParams(); stationsListParams.height = (int) (dpHeight * 0.20); stationsList.setLayoutParams(stationsListParams); stationsList.setVisibility(View.VISIBLE); stationsAdapter = new StationsAdapter(myActivity, R.layout.item_station, stations); stationsList.setAdapter(stationsAdapter); RelativeLayout.LayoutParams draggableLayoutParams = (RelativeLayout.LayoutParams) DragbleText.getLayoutParams(); draggableLayoutParams.removeRule(RelativeLayout.ABOVE); draggableLayoutParams.addRule(RelativeLayout.ABOVE, R.id.stationList); DragbleText.setText("אתה בנסיעה עם תחנות, גרור למטה על מנת להעלימן"); stationsList.invalidateViews(); } @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1) private void RemoveListStations() { DisplayMetrics displayMetrics = myActivity.getResources().getDisplayMetrics(); float dpHeight = getDpHeight(); availableButton.setVisibility(View.VISIBLE); busyButton.setVisibility(View.VISIBLE); myFloating.setVisibility(View.VISIBLE); if (mapFragment != null && mapFragment.getView() != null) { ViewGroup.LayoutParams mapFragmentParams = mapFragment.getView().getLayoutParams(); mapFragmentParams.height = (int) (displayMetrics.heightPixels); mapFragment.getView().setLayoutParams(mapFragmentParams); } ViewGroup.LayoutParams stationsListParams = stationsList.getLayoutParams(); stationsListParams.height = (int) (0); stationsList.setLayoutParams(stationsListParams); stationsList.setVisibility(View.GONE); //stationsAdapter = new StationsAdapter(myActivity,R.layout.item_station,stations); //stationsList.setAdapter(stationsAdapter); RelativeLayout.LayoutParams draggableLayoutParams = (RelativeLayout.LayoutParams) DragbleText.getLayoutParams(); draggableLayoutParams.removeRule(RelativeLayout.BELOW); draggableLayoutParams.addRule(RelativeLayout.BELOW, R.id.stationList); DragbleText.setText("אתה בנסיעה עם תחנות, גרור למטה על מנת להעלימן"); stationsList.invalidateViews(); } private float getDpHeight() { DisplayMetrics displayMetrics = myActivity.getResources().getDisplayMetrics(); // dpHeight is the 100% ? float dpHeight = displayMetrics.heightPixels / displayMetrics.density; return dpHeight; } public void setInRoute(boolean inRoute) { this.inRoute = inRoute; } }
3e0de82335924e3d1461a4d5386cbc9a98c5f7a1
1,143
java
Java
src/com/booksaw/betterTeams/commands/teama/score/RemoveScore.java
megargayu/BetterTeams
6e550b93bbc2b8b87dc8fa6dd9c7fe7b2878bf76
[ "MIT" ]
22
2020-07-12T10:42:39.000Z
2022-03-14T03:20:35.000Z
src/com/booksaw/betterTeams/commands/teama/score/RemoveScore.java
megargayu/BetterTeams
6e550b93bbc2b8b87dc8fa6dd9c7fe7b2878bf76
[ "MIT" ]
306
2020-06-05T04:52:06.000Z
2022-03-29T13:09:13.000Z
src/com/booksaw/betterTeams/commands/teama/score/RemoveScore.java
megargayu/BetterTeams
6e550b93bbc2b8b87dc8fa6dd9c7fe7b2878bf76
[ "MIT" ]
29
2020-10-06T16:56:59.000Z
2022-03-03T19:13:32.000Z
23.326531
101
0.734908
5,889
package com.booksaw.betterTeams.commands.teama.score; import com.booksaw.betterTeams.CommandResponse; import com.booksaw.betterTeams.Team; import com.booksaw.betterTeams.commands.presets.ScoreSubCommand; import org.bukkit.command.CommandSender; import java.util.List; public class RemoveScore extends ScoreSubCommand { @Override public CommandResponse onCommand(CommandSender sender, Team team, int change) { team.setScore(Math.max(team.getScore() - change, 0)); return new CommandResponse("admin.score.success"); } @Override public String getCommand() { return "remove"; } @Override public String getNode() { return "admin.score.remove"; } @Override public String getHelp() { return "Remove the specified amount from that players score"; } @Override public String getArguments() { return "<player/team> <score>"; } @Override public void onTabComplete(List<String> options, CommandSender sender, String label, String[] args) { if (args.length == 1) { addTeamStringList(options, args[0]); addPlayerStringList(options, args[0]); } else if (args.length == 2) { options.add("<score>"); } } }
3e0de8b3bdac2f212ed14a62261bb4b29cc26d86
8,427
java
Java
app/src/main/java/domainapp/app/services/export/PublishContributionsForOrder.java
sudhi001/radrace2015
96e6b4440768ef9855118ed67d8a99073fe3a3c0
[ "Apache-2.0" ]
2
2015-12-10T13:54:12.000Z
2021-02-24T14:38:14.000Z
app/src/main/java/domainapp/app/services/export/PublishContributionsForOrder.java
yourfrienddhruv/radrace2015
96e6b4440768ef9855118ed67d8a99073fe3a3c0
[ "Apache-2.0" ]
null
null
null
app/src/main/java/domainapp/app/services/export/PublishContributionsForOrder.java
yourfrienddhruv/radrace2015
96e6b4440768ef9855118ed67d8a99073fe3a3c0
[ "Apache-2.0" ]
3
2016-03-05T03:39:13.000Z
2021-02-24T14:38:07.000Z
32.041825
119
0.680669
5,890
/* * Copyright 2013~2014 Dan Haywood * * 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 domainapp.app.services.export; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigDecimal; import com.google.common.base.Function; import com.google.common.io.Resources; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.output.DOMOutputter; import org.apache.isis.applib.DomainObjectContainer; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.Contributed; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.MemberOrder; import org.apache.isis.applib.annotation.NatureOfService; import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.services.clock.ClockService; import org.apache.isis.applib.value.Blob; import org.isisaddons.module.docx.dom.DocxService; import org.isisaddons.module.docx.dom.LoadTemplateException; import org.isisaddons.module.docx.dom.MergeException; import domainapp.dom.event.EventRepository; import domainapp.dom.ingredient.IngredientRepository; import domainapp.dom.menuitem.MenuItem; import domainapp.dom.order.Order; import domainapp.dom.orderitem.OrderItem; import domainapp.dom.quick.QuickObjectMenu; import domainapp.dom.supplierreport.SupplierReportCreator; @DomainService( nature = NatureOfService.VIEW_CONTRIBUTIONS_ONLY ) public class PublishContributionsForOrder { //region > publish (action) @Action( semantics = SemanticsOf.SAFE ) @ActionLayout( cssClassFa = "fa-download", contributed = Contributed.AS_ACTION ) @MemberOrder(sequence = "10") public Blob print(final Order order) throws IOException, JDOMException, MergeException { return exportToWordDocCatchExceptions(order); } //endregion //region > exportToWordDoc (programmatic) private Blob exportToWordDocCatchExceptions(final Order order) { final org.w3c.dom.Document w3cDocument; try { w3cDocument = asInputW3cDocument(order); final ByteArrayOutputStream docxTarget = new ByteArrayOutputStream(); docxService.merge(w3cDocument, getWordprocessingMLPackage(), docxTarget, DocxService.MatchingPolicy.LAX); final String blobName = order.getEvent().getName() + "-" + timestamp() + ".docx"; final String blobMimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; final byte[] blobBytes = docxTarget.toByteArray(); return new Blob(blobName, blobMimeType, blobBytes); } catch (JDOMException | MergeException e) { throw new RuntimeException(e); } } private org.w3c.dom.Document asInputW3cDocument(final Order order) throws JDOMException { final Document jdomDoc = asInputDocument(order); final DOMOutputter domOutputter = new DOMOutputter(); return domOutputter.output(jdomDoc); } //endregion ( private String timestamp() { return clockService.nowAsLocalDateTime().toString("yyyyMMdd'_'HHmmss"); } private Document asInputDocument(final Order order) { final Element html = new Element("html"); final Document document = new Document(html); final Element body = new Element("body"); html.addContent(body); addPara(body, "EventName", "rich", order.getEvent().getName()); final String personName = order.getPerson().getFirstName() + order.getPerson().getLastName(); addPara(body, "PersonName", "rich", personName); addPara(body, "ExportedOn", "date", clockService.nowAsLocalDateTime().toString("dd-MMM-yyyy")); final Element table = addTable(body, "Ingredients"); addTableRow(table, new String[] { "", ""}); for(final OrderItem orderItem: order.getItems()) { final MenuItem menuItem = orderItem.getMenuItem(); final int quantity = orderItem.getQuantity(); final BigDecimal memberPrice = menuItem.getMemberPrice(); final String quantityOfMenuItem = "" + quantity + " x " + container.titleOf(menuItem); final BigDecimal cost = memberPrice.multiply(BigDecimal.valueOf(quantity)); addTableRow(table, new String[] { quantityOfMenuItem, cost.toString() }); } addTableRow(table, new String[] { "", "", "" }); return document; } //endregion ( //region > helper: getWordprocessingMLPackage private WordprocessingMLPackage wordprocessingMLPackage; // lazily initialized to speed up bootstrapping (at cost of not failing fast). private WordprocessingMLPackage getWordprocessingMLPackage() { initializeIfNecessary(); return wordprocessingMLPackage; } private void initializeIfNecessary() { if(wordprocessingMLPackage == null) { try { final byte[] bytes = Resources.toByteArray(Resources.getResource(this.getClass(), "OrderReport.docx")); wordprocessingMLPackage = docxService.loadPackage(new ByteArrayInputStream(bytes)); } catch (IOException | LoadTemplateException e) { throw new RuntimeException(e); } } } //endregion //region > helpers private static final Function<String, String> TRIM = new Function<String, String>() { @Override public String apply(final String input) { return input.trim(); } }; private static void addPara(final Element body, final String id, final String clazz, final String text) { final Element p = new Element("p"); body.addContent(p); p.setAttribute("id", id); p.setAttribute("class", clazz); p.setText(text); } private static Element addList(final Element body, final String id) { final Element ul = new Element("ul"); body.addContent(ul); ul.setAttribute("id", id); return ul; } private static Element addListItem(final Element ul, final String... paras) { final Element li = new Element("li"); ul.addContent(li); for (final String para : paras) { addPara(li, para); } return ul; } private static void addPara(final Element li, final String text) { if(text == null) { return; } final Element p = new Element("p"); li.addContent(p); p.setText(text); } private static Element addTable(final Element body, final String id) { final Element table = new Element("table"); body.addContent(table); table.setAttribute("id", id); return table; } private static void addTableRow(final Element table, final String[] cells) { final Element tr = new Element("tr"); table.addContent(tr); for (final String columnName : cells) { final Element td = new Element("td"); tr.addContent(td); td.setText(columnName); } } //endregion //region > injected services @javax.inject.Inject DomainObjectContainer container; @javax.inject.Inject private DocxService docxService; @javax.inject.Inject private EventRepository eventRepository; @javax.inject.Inject private IngredientRepository ingredientRepository; @javax.inject.Inject private QuickObjectMenu quickObjectMenu; @javax.inject.Inject private ClockService clockService; @javax.inject.Inject SupplierReportCreator supplierReportCreator; //endregion }
3e0de8cd1bce3ed9ef614b8645e7690f6ff0d176
780
java
Java
crowdFunding-Admin-2-component/src/main/java/com/zero/mapper/MenuMapper.java
zero6996/CrowdFunding
cfeb3d4673816596447e8a4e3dbc830a855367dc
[ "MIT" ]
1
2020-01-29T04:54:00.000Z
2020-01-29T04:54:00.000Z
crowdFunding-Admin-2-component/src/main/java/com/zero/mapper/MenuMapper.java
zero6996/CrowdFunding
cfeb3d4673816596447e8a4e3dbc830a855367dc
[ "MIT" ]
4
2020-03-05T00:01:39.000Z
2021-12-09T21:49:52.000Z
crowdFunding-Admin-2-component/src/main/java/com/zero/mapper/MenuMapper.java
zero6996/CrowdFunding
cfeb3d4673816596447e8a4e3dbc830a855367dc
[ "MIT" ]
null
null
null
26
102
0.757692
5,891
package com.zero.mapper; import com.zero.entity.Menu; import com.zero.entity.MenuExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface MenuMapper { int countByExample(MenuExample example); int deleteByExample(MenuExample example); int deleteByPrimaryKey(Integer id); int insert(Menu record); int insertSelective(Menu record); List<Menu> selectByExample(MenuExample example); Menu selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") Menu record, @Param("example") MenuExample example); int updateByExample(@Param("record") Menu record, @Param("example") MenuExample example); int updateByPrimaryKeySelective(Menu record); int updateByPrimaryKey(Menu record); }
3e0de8d51a403713ed0d1a747f6111ae44a4ca3f
549
java
Java
cp3-file/cp3-file-biz/src/main/java/com/cp3/cloud/file/strategy/FileStrategy.java
huhua1990/cp3-cloud
c6050a1ce8767a104181cbdb5916c51a3458deb7
[ "Apache-2.0" ]
2
2021-08-12T02:48:00.000Z
2021-12-13T10:12:35.000Z
cp3-file/cp3-file-biz/src/main/java/com/cp3/cloud/file/strategy/FileStrategy.java
huhua1990/cp3-cloud
c6050a1ce8767a104181cbdb5916c51a3458deb7
[ "Apache-2.0" ]
null
null
null
cp3-file/cp3-file-biz/src/main/java/com/cp3/cloud/file/strategy/FileStrategy.java
huhua1990/cp3-cloud
c6050a1ce8767a104181cbdb5916c51a3458deb7
[ "Apache-2.0" ]
1
2020-11-25T11:25:16.000Z
2020-11-25T11:25:16.000Z
16.636364
55
0.632058
5,892
package com.cp3.cloud.file.strategy; import com.cp3.cloud.file.domain.FileDeleteDO; import com.cp3.cloud.file.entity.Attachment; import org.springframework.web.multipart.MultipartFile; import java.util.List; /** * 文件策略接口 * * @author zuihou * @date 2019/06/17 */ public interface FileStrategy { /** * 文件上传 * * @param file 文件 * @return 文件对象 */ Attachment upload(MultipartFile file); /** * 删除源文件 * * @param list 列表 * @return 是否成功 */ boolean delete(List<FileDeleteDO> list); }
3e0de92381ca5403207149c33d078be1fe905db8
4,315
java
Java
src/main/java/com/bsptechs/main/bean/ui/panel/PanelObjectMain.java
goshgarmirzayev/speedup
8c57835eb0bd9beda1d225a7dba3a46c10feb88d
[ "Apache-2.0" ]
1
2021-04-10T07:10:22.000Z
2021-04-10T07:10:22.000Z
src/main/java/com/bsptechs/main/bean/ui/panel/PanelObjectMain.java
goshgarmirzayev/speedup
8c57835eb0bd9beda1d225a7dba3a46c10feb88d
[ "Apache-2.0" ]
null
null
null
src/main/java/com/bsptechs/main/bean/ui/panel/PanelObjectMain.java
goshgarmirzayev/speedup
8c57835eb0bd9beda1d225a7dba3a46c10feb88d
[ "Apache-2.0" ]
null
null
null
38.185841
157
0.695713
5,893
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.bsptechs.main.bean.ui.panel; import com.bsptechs.main.bean.SUArrayList; import com.bsptechs.main.bean.ui.button.SUAbstractButton; import com.bsptechs.main.bean.ui.tree.server.SUAbstractServerTreeNode; import com.bsptechs.main.bean.ui.tree.server.SUServerTree; import java.awt.Color; import javax.swing.BorderFactory; import javax.swing.JButton; /** * * @author sarkhanrasullu */ public class PanelObjectMain extends javax.swing.JPanel { public PanelObjectMain() { initComponents(); } public void refresh(SUAbstractServerTreeNode treeNode) { if (treeNode == null) { return; } addAllButton(treeNode.getObjectControlButtons()); getTreeData().removeAllCustomTreeNodes(); getTreeData().fillTreeAsRoot(treeNode.getObjectData()); } public void addAllButton(SUArrayList<SUAbstractButton> btns) { if (btns == null) { return; } pnlButtons.removeAll(); for (SUAbstractButton btn : btns) { pnlButtons.add(btn); } pnlButtons.revalidate(); } private void addButton(SUAbstractButton btn) { pnlButtons.add(btn); pnlButtons.revalidate(); } public void btnenter(JButton btn) { btn.setBorder(BorderFactory.createBevelBorder(1, Color.lightGray, Color.white)); } public void btnexit(JButton btn) { btn.setBorder(null); } private SUServerTree getTreeData() { return (SUServerTree) treeData; } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { pnlButtons = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); treeData = new SUServerTree(); pnlButtons.setBackground(new java.awt.Color(204, 204, 204)); jScrollPane1.setViewportView(treeData); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 618, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 384, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pnlButtons, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(pnlButtons, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JPanel pnlButtons; private javax.swing.JTree treeData; // End of variables declaration//GEN-END:variables }
3e0de9987dd3902813cf73c94b278c4379170177
303
java
Java
common/src/main/java/org/propagate/common/dao/CrudOperations.java
lunar-logan/propagate
ac770f0df76ef2735c342a5089d460af71655861
[ "Apache-2.0" ]
null
null
null
common/src/main/java/org/propagate/common/dao/CrudOperations.java
lunar-logan/propagate
ac770f0df76ef2735c342a5089d460af71655861
[ "Apache-2.0" ]
1
2021-02-27T18:30:44.000Z
2021-02-27T18:30:44.000Z
common/src/main/java/org/propagate/common/dao/CrudOperations.java
lunar-logan/propagate
ac770f0df76ef2735c342a5089d460af71655861
[ "Apache-2.0" ]
1
2021-07-01T09:29:06.000Z
2021-07-01T09:29:06.000Z
21.642857
40
0.679868
5,894
package org.propagate.common.dao; import java.util.List; import java.util.Optional; public interface CrudOperations<T, ID> { T save(T entity); Optional<T> findById(ID id); List<T> findAll(); List<T> findAll(int page, int size); void delete(T entity); void deleteById(ID id); }
3e0dea84b3e8c601e5e79010b06be31360391484
247
java
Java
Defining Classes/RawData/src/Tyre.java
NikolaVodenicharov/Java-OOP-Basic
63492e9083855cc09e7f6d6c01783641c8d8be42
[ "MIT" ]
null
null
null
Defining Classes/RawData/src/Tyre.java
NikolaVodenicharov/Java-OOP-Basic
63492e9083855cc09e7f6d6c01783641c8d8be42
[ "MIT" ]
null
null
null
Defining Classes/RawData/src/Tyre.java
NikolaVodenicharov/Java-OOP-Basic
63492e9083855cc09e7f6d6c01783641c8d8be42
[ "MIT" ]
null
null
null
17.642857
43
0.591093
5,895
public class Tyre { private double pressure; private int age; public Tyre(double pressure, int age) { this.pressure = pressure; this.age = age; } public double getPressure() { return pressure; } }
3e0dea9817ea34ae4e2f9dc0b318d053f093af38
1,327
java
Java
src/main/java/stanhebben/zenscript/expression/ExpressionArrayList.java
eutropius225/ZenScript
beb7f7528fbb0494706ac6b05e072966510c0d11
[ "MIT" ]
47
2018-02-20T05:31:16.000Z
2022-02-22T19:21:53.000Z
src/main/java/stanhebben/zenscript/expression/ExpressionArrayList.java
eutropius225/ZenScript
beb7f7528fbb0494706ac6b05e072966510c0d11
[ "MIT" ]
17
2018-03-04T08:39:07.000Z
2021-10-31T01:43:47.000Z
src/main/java/stanhebben/zenscript/expression/ExpressionArrayList.java
eutropius225/ZenScript
beb7f7528fbb0494706ac6b05e072966510c0d11
[ "MIT" ]
26
2018-03-01T17:09:25.000Z
2022-02-22T19:21:56.000Z
31.595238
128
0.66315
5,896
package stanhebben.zenscript.expression; import stanhebben.zenscript.compiler.IEnvironmentMethod; import stanhebben.zenscript.type.*; import stanhebben.zenscript.util.*; import java.util.*; public class ExpressionArrayList extends Expression { private final Expression[] contents; private final ZenTypeArrayList type; public ExpressionArrayList(ZenPosition position, ZenTypeArrayList type, Expression[] contents) { super(position); this.contents = contents; this.type = type; } @Override public void compile(boolean result, IEnvironmentMethod environment) { if(!result) return; final MethodOutput methodOutput = environment.getOutput(); methodOutput.newObject(ArrayList.class); methodOutput.dup(); methodOutput.invokeSpecial("java/util/ArrayList", "<init>", "()V"); for(Expression content : contents) { methodOutput.dup(); content.cast(getPosition(), environment, ZenTypeUtil.checkPrimitive(content.getType())).compile(true, environment); methodOutput.invokeInterface(Collection.class, "add", boolean.class, Object.class); methodOutput.pop(); } } @Override public ZenType getType() { return type; } }
3e0decf008104ea83475c3ccca312ca544dbb1c9
1,241
java
Java
iextrading4j-acceptance/src/test/java/pl/zankowski/iextrading4j/test/acceptance/v1/DataPointsAcceptanceTest.java
10shibu/iextrading4j
4150ae5dd4712e886dbbce5c0af656d20561557b
[ "Apache-2.0" ]
1
2020-06-11T13:24:09.000Z
2020-06-11T13:24:09.000Z
iextrading4j-acceptance/src/test/java/pl/zankowski/iextrading4j/test/acceptance/v1/DataPointsAcceptanceTest.java
10shibu/iextrading4j
4150ae5dd4712e886dbbce5c0af656d20561557b
[ "Apache-2.0" ]
null
null
null
iextrading4j-acceptance/src/test/java/pl/zankowski/iextrading4j/test/acceptance/v1/DataPointsAcceptanceTest.java
10shibu/iextrading4j
4150ae5dd4712e886dbbce5c0af656d20561557b
[ "Apache-2.0" ]
null
null
null
31.025
92
0.706688
5,897
package pl.zankowski.iextrading4j.test.acceptance.v1; import org.junit.Ignore; import org.junit.Test; import pl.zankowski.iextrading4j.api.datapoint.DataPoint; import pl.zankowski.iextrading4j.client.rest.manager.RestRequest; import pl.zankowski.iextrading4j.client.rest.request.datapoint.DataPointsRequestBuilder; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class DataPointsAcceptanceTest extends IEXCloudV1AcceptanceTestBase { @Test public void dataPointsTest() { final RestRequest<List<DataPoint>> request = new DataPointsRequestBuilder() .withSymbol("AAPL") .build(); final List<DataPoint> dataPoints = cloudClient.executeRequest(request); assertThat(dataPoints).isNotNull(); } @Ignore // The requested data requires a Scale account and granted permission to access. @Test public void keyDataPointTest() { final RestRequest<String> request = new DataPointsRequestBuilder() .withSymbol("AAPL") .withKey("QUOTE-CLOSE") .build(); final String response = cloudClient.executeRequest(request); assertThat(response).isNotNull(); } }
3e0decfdb8769deda78b2cda8cb621be7d87da67
5,615
java
Java
src/main/java/io/renren/modules/test/entity/StressTestHistoryResourceDetailEntity.java
vi2233m/stressTestPlatform
6fdd6c0f3864f8ccf3a2510b935affbdbfd4276f
[ "Apache-2.0" ]
null
null
null
src/main/java/io/renren/modules/test/entity/StressTestHistoryResourceDetailEntity.java
vi2233m/stressTestPlatform
6fdd6c0f3864f8ccf3a2510b935affbdbfd4276f
[ "Apache-2.0" ]
null
null
null
src/main/java/io/renren/modules/test/entity/StressTestHistoryResourceDetailEntity.java
vi2233m/stressTestPlatform
6fdd6c0f3864f8ccf3a2510b935affbdbfd4276f
[ "Apache-2.0" ]
null
null
null
17.768987
57
0.508459
5,898
package io.renren.modules.test.entity; import java.util.Date; /** * 展示文件ID的 */ public class StressTestHistoryResourceDetailEntity { private static final long serialVersionUID = 1L; /** * 主键id */ private Long id; /** * 报告ID */ private Long reportId; /** * 版本号 */ private String version; /** * 文件ID */ private Long fileId; /** * 文件名称 */ private String fileName; /** * 应用名称 */ private String appName; /** * 应用IP */ private String appIp; /** * 用户CPU% */ private float cpuUser; /** * 系统CPU% */ private float cpuSys; /** * 等待CPU% */ private float cpuWait; /** * 空闲内存 */ private float memFree; /** * 活跃内存 */ private float memActive; /** * 总内存 */ private float memTotal; /** * 带宽read(KB/s) */ private float netRead; /** * 带宽write(KB/s) */ private float netWrite; /** * 磁盘读(KB/s) */ private float diskRead; /** * 磁盘写(KB/s) */ private float diskWrite; /** * 提交的用户 */ private String addBy; /** * 修改的用户 */ private String updateBy; /** * 提交的时间 */ private Date addTime; /** * 更新的时间 */ private Date updateTime; public static long getSerialVersionUID() { return serialVersionUID; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getReportId() { return reportId; } public void setReportId(Long reportId) { this.reportId = reportId; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public Long getFileId() { return fileId; } public void setFileId(Long fileId) { this.fileId = fileId; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getAppIp() { return appIp; } public void setAppIp(String appIp) { this.appIp = appIp; } public float getCpuUser() { return cpuUser; } public void setCpuUser(float cpuUser) { this.cpuUser = cpuUser; } public float getCpuSys() { return cpuSys; } public void setCpuSys(float cpuSys) { this.cpuSys = cpuSys; } public float getCpuWait() { return cpuWait; } public void setCpuWait(float cpuWait) { this.cpuWait = cpuWait; } public float getMemFree() { return memFree; } public void setMemFree(float memFree) { this.memFree = memFree; } public float getMemActive() { return memActive; } public void setMemActive(float memActive) { this.memActive = memActive; } public float getMemTotal() { return memTotal; } public void setMemTotal(float memTotal) { this.memTotal = memTotal; } public float getNetRead() { return netRead; } public void setNetRead(float netRead) { this.netRead = netRead; } public float getNetWrite() { return netWrite; } public void setNetWrite(float netWrite) { this.netWrite = netWrite; } public float getDiskRead() { return diskRead; } public void setDiskRead(float diskRead) { this.diskRead = diskRead; } public float getDiskWrite() { return diskWrite; } public void setDiskWrite(float diskWrite) { this.diskWrite = diskWrite; } public String getAddBy() { return addBy; } public void setAddBy(String addBy) { this.addBy = addBy; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } public Date getAddTime() { return addTime; } public void setAddTime(Date addTime) { this.addTime = addTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "StressTestHistoryResourceDetailEntity{" + "id=" + id + ", reportId=" + reportId + ", version='" + version + '\'' + ", fileId=" + fileId + ", fileName='" + fileName + '\'' + ", appName='" + appName + '\'' + ", appIp='" + appIp + '\'' + ", cpuUser=" + cpuUser + ", cpuSys=" + cpuSys + ", cpuWait=" + cpuWait + ", memFree=" + memFree + ", memActive=" + memActive + ", memTotal=" + memTotal + ", netRead=" + netRead + ", netWrite=" + netWrite + ", diskRead=" + diskRead + ", diskWrite=" + diskWrite + ", addBy='" + addBy + '\'' + ", updateBy='" + updateBy + '\'' + ", addTime=" + addTime + ", updateTime=" + updateTime + '}'; } }
3e0ded2638436cbe749bc95fe36090c94bdb7043
27,723
java
Java
device/nfc/android/junit/src/org/chromium/device/nfc/NFCTest.java
Cela-Inc/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
device/nfc/android/junit/src/org/chromium/device/nfc/NFCTest.java
Cela-Inc/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
device/nfc/android/junit/src/org/chromium/device/nfc/NFCTest.java
Cela-Inc/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
43.796209
96
0.702341
5,899
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.device.nfc; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.nfc.FormatException; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.NfcAdapter.ReaderCallback; import android.nfc.NfcManager; import android.os.Bundle; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.annotation.Config; import org.chromium.base.test.util.Feature; import org.chromium.device.nfc.mojom.Nfc.CancelAllWatchesResponse; import org.chromium.device.nfc.mojom.Nfc.CancelPushResponse; import org.chromium.device.nfc.mojom.Nfc.CancelWatchResponse; import org.chromium.device.nfc.mojom.Nfc.PushResponse; import org.chromium.device.nfc.mojom.Nfc.WatchResponse; import org.chromium.device.nfc.mojom.NfcClient; import org.chromium.device.nfc.mojom.NfcError; import org.chromium.device.nfc.mojom.NfcErrorType; import org.chromium.device.nfc.mojom.NfcMessage; import org.chromium.device.nfc.mojom.NfcPushOptions; import org.chromium.device.nfc.mojom.NfcPushTarget; import org.chromium.device.nfc.mojom.NfcRecord; import org.chromium.device.nfc.mojom.NfcRecordType; import org.chromium.device.nfc.mojom.NfcRecordTypeFilter; import org.chromium.device.nfc.mojom.NfcWatchMode; import org.chromium.device.nfc.mojom.NfcWatchOptions; import org.chromium.testing.local.LocalRobolectricTestRunner; import java.io.IOException; import java.io.UnsupportedEncodingException; /** * Unit tests for NfcImpl and NfcTypeConverter classes. */ @RunWith(LocalRobolectricTestRunner.class) @Config(manifest = Config.NONE) public class NFCTest { @Mock private Context mContext; @Mock private NfcManager mNfcManager; @Mock private NfcAdapter mNfcAdapter; @Mock private Activity mActivity; @Mock private NfcClient mNfcClient; @Mock private NfcTagHandler mNfcTagHandler; @Captor private ArgumentCaptor<NfcError> mErrorCaptor; @Captor private ArgumentCaptor<Integer> mWatchCaptor; @Captor private ArgumentCaptor<int[]> mOnWatchCallbackCaptor; // Constants used for the test. private static final String TEST_TEXT = "test"; private static final String TEST_URL = "https://google.com"; private static final String TEST_JSON = "{\"key1\":\"value1\",\"key2\":2}"; private static final String DOMAIN = "w3.org"; private static final String TYPE = "webnfc"; private static final String TEXT_MIME = "text/plain"; private static final String JSON_MIME = "application/json"; private static final String CHARSET_UTF8 = ";charset=UTF-8"; private static final String CHARSET_UTF16 = ";charset=UTF-16"; private static final String LANG_EN_US = "en-US"; /** * Class that is used test NfcImpl implementation */ private static class TestNfcImpl extends NfcImpl { public TestNfcImpl(Context context) { super(context); } public void setActivityForTesting(Activity activity) { super.setActivity(activity); } public void processPendingOperationsForTesting(NfcTagHandler handler) { super.processPendingOperations(handler); } } @Before public void setUp() { MockitoAnnotations.initMocks(this); doReturn(mNfcManager).when(mContext).getSystemService(Context.NFC_SERVICE); doReturn(mNfcAdapter).when(mNfcManager).getDefaultAdapter(); doReturn(true).when(mNfcAdapter).isEnabled(); doReturn(PackageManager.PERMISSION_GRANTED) .when(mContext) .checkPermission(anyString(), anyInt(), anyInt()); doNothing() .when(mNfcAdapter) .enableReaderMode(any(Activity.class), any(ReaderCallback.class), anyInt(), (Bundle) isNull()); doNothing().when(mNfcAdapter).disableReaderMode(any(Activity.class)); // Tag handler overrides used to mock connected tag. doReturn(true).when(mNfcTagHandler).isConnected(); doReturn(false).when(mNfcTagHandler).isTagOutOfRange(); try { doNothing().when(mNfcTagHandler).connect(); doNothing().when(mNfcTagHandler).write(any(NdefMessage.class)); doReturn(createUrlWebNFCNdefMessage()).when(mNfcTagHandler).read(); doNothing().when(mNfcTagHandler).close(); } catch (IOException | FormatException e) { } } /** * Test that error with type NOT_SUPPORTED is returned if NFC is not supported. */ @Test @Feature({"NFCTest"}) public void testNFCNotSupported() { doReturn(null).when(mNfcManager).getDefaultAdapter(); TestNfcImpl nfc = new TestNfcImpl(mContext); nfc.setActivityForTesting(mActivity); CancelAllWatchesResponse mockCallback = mock(CancelAllWatchesResponse.class); nfc.cancelAllWatches(mockCallback); verify(mockCallback).call(mErrorCaptor.capture()); assertEquals(NfcErrorType.NOT_SUPPORTED, mErrorCaptor.getValue().errorType); } /** * Test that error with type SECURITY is returned if permission to use NFC is not granted. */ @Test @Feature({"NFCTest"}) public void testNFCIsNotPermitted() { doReturn(PackageManager.PERMISSION_DENIED) .when(mContext) .checkPermission(anyString(), anyInt(), anyInt()); TestNfcImpl nfc = new TestNfcImpl(mContext); CancelAllWatchesResponse mockCallback = mock(CancelAllWatchesResponse.class); nfc.cancelAllWatches(mockCallback); verify(mockCallback).call(mErrorCaptor.capture()); assertEquals(NfcErrorType.SECURITY, mErrorCaptor.getValue().errorType); } /** * Test that method can be invoked successfully if NFC is supported and adapter is enabled. */ @Test @Feature({"NFCTest"}) public void testNFCIsSupported() { TestNfcImpl nfc = new TestNfcImpl(mContext); nfc.setActivityForTesting(mActivity); WatchResponse mockCallback = mock(WatchResponse.class); nfc.watch(createNfcWatchOptions(), mockCallback); verify(mockCallback).call(anyInt(), mErrorCaptor.capture()); assertNull(mErrorCaptor.getValue()); } /** * Test conversion from NdefMessage to mojo NfcMessage. */ @Test @Feature({"NFCTest"}) public void testNdefToMojoConversion() throws UnsupportedEncodingException { // Test EMPTY record conversion. NdefMessage emptyNdefMessage = new NdefMessage(new NdefRecord(NdefRecord.TNF_EMPTY, null, null, null)); NfcMessage emptyNfcMessage = NfcTypeConverter.toNfcMessage(emptyNdefMessage); assertNull(emptyNfcMessage.url); assertEquals(1, emptyNfcMessage.data.length); assertEquals(NfcRecordType.EMPTY, emptyNfcMessage.data[0].recordType); assertEquals(true, emptyNfcMessage.data[0].mediaType.isEmpty()); assertEquals(0, emptyNfcMessage.data[0].data.length); // Test URL record conversion. NdefMessage urlNdefMessage = new NdefMessage(NdefRecord.createUri(TEST_URL)); NfcMessage urlNfcMessage = NfcTypeConverter.toNfcMessage(urlNdefMessage); assertNull(urlNfcMessage.url); assertEquals(1, urlNfcMessage.data.length); assertEquals(NfcRecordType.URL, urlNfcMessage.data[0].recordType); assertEquals(TEXT_MIME, urlNfcMessage.data[0].mediaType); assertEquals(TEST_URL, new String(urlNfcMessage.data[0].data)); // Test TEXT record conversion. NdefMessage textNdefMessage = new NdefMessage(NdefRecord.createTextRecord(LANG_EN_US, TEST_TEXT)); NfcMessage textNfcMessage = NfcTypeConverter.toNfcMessage(textNdefMessage); assertNull(textNfcMessage.url); assertEquals(1, textNfcMessage.data.length); assertEquals(NfcRecordType.TEXT, textNfcMessage.data[0].recordType); assertEquals(TEXT_MIME, textNfcMessage.data[0].mediaType); assertEquals(TEST_TEXT, new String(textNfcMessage.data[0].data)); // Test MIME record conversion. NdefMessage mimeNdefMessage = new NdefMessage(NdefRecord.createMime(TEXT_MIME, TEST_TEXT.getBytes())); NfcMessage mimeNfcMessage = NfcTypeConverter.toNfcMessage(mimeNdefMessage); assertNull(mimeNfcMessage.url); assertEquals(1, mimeNfcMessage.data.length); assertEquals(NfcRecordType.OPAQUE_RECORD, mimeNfcMessage.data[0].recordType); assertEquals(TEXT_MIME, textNfcMessage.data[0].mediaType); assertEquals(TEST_TEXT, new String(textNfcMessage.data[0].data)); // Test JSON record conversion. NdefMessage jsonNdefMessage = new NdefMessage(NdefRecord.createMime(JSON_MIME, TEST_JSON.getBytes())); NfcMessage jsonNfcMessage = NfcTypeConverter.toNfcMessage(jsonNdefMessage); assertNull(jsonNfcMessage.url); assertEquals(1, jsonNfcMessage.data.length); assertEquals(NfcRecordType.JSON, jsonNfcMessage.data[0].recordType); assertEquals(JSON_MIME, jsonNfcMessage.data[0].mediaType); assertEquals(TEST_JSON, new String(jsonNfcMessage.data[0].data)); // Test NfcMessage with WebNFC external type. NdefRecord jsonNdefRecord = NdefRecord.createMime(JSON_MIME, TEST_JSON.getBytes()); NdefRecord extNdefRecord = NdefRecord.createExternal(DOMAIN, TYPE, TEST_URL.getBytes()); NdefMessage webNdefMessage = new NdefMessage(jsonNdefRecord, extNdefRecord); NfcMessage webNfcMessage = NfcTypeConverter.toNfcMessage(webNdefMessage); assertEquals(TEST_URL, webNfcMessage.url); assertEquals(1, webNfcMessage.data.length); assertEquals(NfcRecordType.JSON, webNfcMessage.data[0].recordType); assertEquals(JSON_MIME, webNfcMessage.data[0].mediaType); assertEquals(TEST_JSON, new String(webNfcMessage.data[0].data)); } /** * Test conversion from mojo NfcMessage to android NdefMessage. */ @Test @Feature({"NFCTest"}) public void testMojoToNdefConversion() throws InvalidNfcMessageException { // Test URL record conversion. NdefMessage urlNdefMessage = createUrlWebNFCNdefMessage(); assertEquals(2, urlNdefMessage.getRecords().length); assertEquals(NdefRecord.TNF_WELL_KNOWN, urlNdefMessage.getRecords()[0].getTnf()); assertEquals(TEST_URL, urlNdefMessage.getRecords()[0].toUri().toString()); assertEquals(NdefRecord.TNF_EXTERNAL_TYPE, urlNdefMessage.getRecords()[1].getTnf()); assertEquals(DOMAIN + ":" + TYPE, new String(urlNdefMessage.getRecords()[1].getType())); // Test TEXT record conversion. NfcRecord textNfcRecord = new NfcRecord(); textNfcRecord.recordType = NfcRecordType.TEXT; textNfcRecord.mediaType = TEXT_MIME; textNfcRecord.data = TEST_TEXT.getBytes(); NfcMessage textNfcMessage = createNfcMessage(TEST_URL, textNfcRecord); NdefMessage textNdefMessage = NfcTypeConverter.toNdefMessage(textNfcMessage); assertEquals(2, textNdefMessage.getRecords().length); short tnf = textNdefMessage.getRecords()[0].getTnf(); boolean isWellKnownOrMime = (tnf == NdefRecord.TNF_WELL_KNOWN || tnf == NdefRecord.TNF_MIME_MEDIA); assertEquals(true, isWellKnownOrMime); assertEquals(NdefRecord.TNF_EXTERNAL_TYPE, textNdefMessage.getRecords()[1].getTnf()); // Test MIME record conversion. NfcRecord mimeNfcRecord = new NfcRecord(); mimeNfcRecord.recordType = NfcRecordType.OPAQUE_RECORD; mimeNfcRecord.mediaType = TEXT_MIME; mimeNfcRecord.data = TEST_TEXT.getBytes(); NfcMessage mimeNfcMessage = createNfcMessage(TEST_URL, mimeNfcRecord); NdefMessage mimeNdefMessage = NfcTypeConverter.toNdefMessage(mimeNfcMessage); assertEquals(2, mimeNdefMessage.getRecords().length); assertEquals(NdefRecord.TNF_MIME_MEDIA, mimeNdefMessage.getRecords()[0].getTnf()); assertEquals(TEXT_MIME, mimeNdefMessage.getRecords()[0].toMimeType()); assertEquals(TEST_TEXT, new String(mimeNdefMessage.getRecords()[0].getPayload())); assertEquals(NdefRecord.TNF_EXTERNAL_TYPE, mimeNdefMessage.getRecords()[1].getTnf()); // Test JSON record conversion. NfcRecord jsonNfcRecord = new NfcRecord(); jsonNfcRecord.recordType = NfcRecordType.OPAQUE_RECORD; jsonNfcRecord.mediaType = JSON_MIME; jsonNfcRecord.data = TEST_JSON.getBytes(); NfcMessage jsonNfcMessage = createNfcMessage(TEST_URL, jsonNfcRecord); NdefMessage jsonNdefMessage = NfcTypeConverter.toNdefMessage(jsonNfcMessage); assertEquals(2, jsonNdefMessage.getRecords().length); assertEquals(NdefRecord.TNF_MIME_MEDIA, jsonNdefMessage.getRecords()[0].getTnf()); assertEquals(JSON_MIME, jsonNdefMessage.getRecords()[0].toMimeType()); assertEquals(TEST_JSON, new String(jsonNdefMessage.getRecords()[0].getPayload())); assertEquals(NdefRecord.TNF_EXTERNAL_TYPE, jsonNdefMessage.getRecords()[1].getTnf()); } /** * Test that invalid NfcMessage is rejected with INVALID_MESSAGE error code. */ @Test @Feature({"NFCTest"}) public void testInvalidNfcMessage() { TestNfcImpl nfc = new TestNfcImpl(mContext); nfc.setActivityForTesting(mActivity); PushResponse mockCallback = mock(PushResponse.class); nfc.push(new NfcMessage(), createNfcPushOptions(), mockCallback); nfc.processPendingOperationsForTesting(mNfcTagHandler); verify(mockCallback).call(mErrorCaptor.capture()); assertEquals(NfcErrorType.INVALID_MESSAGE, mErrorCaptor.getValue().errorType); } /** * Test that Nfc.suspendNfcOperations() and Nfc.resumeNfcOperations() work correctly. */ @Test @Feature({"NFCTest"}) public void testResumeSuspend() { TestNfcImpl nfc = new TestNfcImpl(mContext); // No activity / client or active pending operations nfc.suspendNfcOperations(); nfc.resumeNfcOperations(); nfc.setActivityForTesting(mActivity); nfc.setClient(mNfcClient); WatchResponse mockCallback = mock(WatchResponse.class); nfc.watch(createNfcWatchOptions(), mockCallback); nfc.suspendNfcOperations(); verify(mNfcAdapter, times(1)).disableReaderMode(mActivity); nfc.resumeNfcOperations(); // 1. Enable after watch is called, 2. after resumeNfcOperations is called. verify(mNfcAdapter, times(2)) .enableReaderMode(any(Activity.class), any(ReaderCallback.class), anyInt(), (Bundle) isNull()); nfc.processPendingOperationsForTesting(mNfcTagHandler); // Check that watch request was completed successfully. verify(mockCallback).call(mWatchCaptor.capture(), mErrorCaptor.capture()); assertNull(mErrorCaptor.getValue()); // Check that client was notified and watch with correct id was triggered. verify(mNfcClient, times(1)) .onWatch(mOnWatchCallbackCaptor.capture(), any(NfcMessage.class)); assertEquals(mWatchCaptor.getValue().intValue(), mOnWatchCallbackCaptor.getValue()[0]); } /** * Test that Nfc.push() successful when NFC tag is connected. */ @Test @Feature({"NFCTest"}) public void testPush() { TestNfcImpl nfc = new TestNfcImpl(mContext); nfc.setActivityForTesting(mActivity); PushResponse mockCallback = mock(PushResponse.class); nfc.push(createNfcMessage(), createNfcPushOptions(), mockCallback); nfc.processPendingOperationsForTesting(mNfcTagHandler); verify(mockCallback).call(mErrorCaptor.capture()); assertNull(mErrorCaptor.getValue()); } /** * Test that Nfc.cancelPush() cancels pending push opration and completes successfully. */ @Test @Feature({"NFCTest"}) public void testCancelPush() { TestNfcImpl nfc = new TestNfcImpl(mContext); nfc.setActivityForTesting(mActivity); PushResponse mockPushCallback = mock(PushResponse.class); CancelPushResponse mockCancelPushCallback = mock(CancelPushResponse.class); nfc.push(createNfcMessage(), createNfcPushOptions(), mockPushCallback); nfc.cancelPush(NfcPushTarget.ANY, mockCancelPushCallback); // Check that push request was cancelled with OPERATION_CANCELLED. verify(mockPushCallback).call(mErrorCaptor.capture()); assertEquals(NfcErrorType.OPERATION_CANCELLED, mErrorCaptor.getValue().errorType); // Check that cancel request was successfuly completed. verify(mockCancelPushCallback).call(mErrorCaptor.capture()); assertNull(mErrorCaptor.getValue()); } /** * Test that Nfc.watch() works correctly and client is notified. */ @Test @Feature({"NFCTest"}) public void testWatch() { TestNfcImpl nfc = new TestNfcImpl(mContext); nfc.setActivityForTesting(mActivity); nfc.setClient(mNfcClient); WatchResponse mockWatchCallback1 = mock(WatchResponse.class); nfc.watch(createNfcWatchOptions(), mockWatchCallback1); // Check that watch requests were completed successfully. verify(mockWatchCallback1).call(mWatchCaptor.capture(), mErrorCaptor.capture()); assertNull(mErrorCaptor.getValue()); int watchId1 = mWatchCaptor.getValue().intValue(); WatchResponse mockWatchCallback2 = mock(WatchResponse.class); nfc.watch(createNfcWatchOptions(), mockWatchCallback2); verify(mockWatchCallback2).call(mWatchCaptor.capture(), mErrorCaptor.capture()); assertNull(mErrorCaptor.getValue()); int watchId2 = mWatchCaptor.getValue().intValue(); // Check that each watch operation is associated with unique id. assertNotEquals(watchId1, watchId2); // Mocks 'NFC tag found' event. nfc.processPendingOperationsForTesting(mNfcTagHandler); // Check that client was notified and correct watch ids were provided. verify(mNfcClient, times(1)) .onWatch(mOnWatchCallbackCaptor.capture(), any(NfcMessage.class)); assertEquals(watchId1, mOnWatchCallbackCaptor.getValue()[0]); assertEquals(watchId2, mOnWatchCallbackCaptor.getValue()[1]); } /** * Test that Nfc.watch() matching function works correctly. */ @Test @Feature({"NFCTest"}) public void testlWatchMatching() { TestNfcImpl nfc = new TestNfcImpl(mContext); nfc.setActivityForTesting(mActivity); nfc.setClient(mNfcClient); // Should match by WebNFC Id. NfcWatchOptions options1 = createNfcWatchOptions(); options1.mode = NfcWatchMode.WEBNFC_ONLY; options1.url = TEST_URL; WatchResponse mockWatchCallback1 = mock(WatchResponse.class); nfc.watch(options1, mockWatchCallback1); verify(mockWatchCallback1).call(mWatchCaptor.capture(), mErrorCaptor.capture()); assertNull(mErrorCaptor.getValue()); int watchId1 = mWatchCaptor.getValue().intValue(); // Should match by media type. NfcWatchOptions options2 = createNfcWatchOptions(); options2.mode = NfcWatchMode.ANY; options2.mediaType = TEXT_MIME; WatchResponse mockWatchCallback2 = mock(WatchResponse.class); nfc.watch(options2, mockWatchCallback2); verify(mockWatchCallback2).call(mWatchCaptor.capture(), mErrorCaptor.capture()); assertNull(mErrorCaptor.getValue()); int watchId2 = mWatchCaptor.getValue().intValue(); // Should match by record type. NfcWatchOptions options3 = createNfcWatchOptions(); options3.mode = NfcWatchMode.ANY; NfcRecordTypeFilter typeFilter = new NfcRecordTypeFilter(); typeFilter.recordType = NfcRecordType.URL; options3.recordFilter = typeFilter; WatchResponse mockWatchCallback3 = mock(WatchResponse.class); nfc.watch(options3, mockWatchCallback3); verify(mockWatchCallback3).call(mWatchCaptor.capture(), mErrorCaptor.capture()); assertNull(mErrorCaptor.getValue()); int watchId3 = mWatchCaptor.getValue().intValue(); // Should not match NfcWatchOptions options4 = createNfcWatchOptions(); options4.mode = NfcWatchMode.WEBNFC_ONLY; options4.url = DOMAIN; WatchResponse mockWatchCallback4 = mock(WatchResponse.class); nfc.watch(options4, mockWatchCallback4); verify(mockWatchCallback4).call(mWatchCaptor.capture(), mErrorCaptor.capture()); assertNull(mErrorCaptor.getValue()); int watchId4 = mWatchCaptor.getValue().intValue(); nfc.processPendingOperationsForTesting(mNfcTagHandler); // Check that client was notified and watch with correct id was triggered. verify(mNfcClient, times(1)) .onWatch(mOnWatchCallbackCaptor.capture(), any(NfcMessage.class)); assertEquals(3, mOnWatchCallbackCaptor.getValue().length); assertEquals(watchId1, mOnWatchCallbackCaptor.getValue()[0]); assertEquals(watchId2, mOnWatchCallbackCaptor.getValue()[1]); assertEquals(watchId3, mOnWatchCallbackCaptor.getValue()[2]); } /** * Test that Nfc.watch() can be cancelled with Nfc.cancelWatch(). */ @Test @Feature({"NFCTest"}) public void testCancelWatch() { TestNfcImpl nfc = new TestNfcImpl(mContext); nfc.setActivityForTesting(mActivity); WatchResponse mockWatchCallback = mock(WatchResponse.class); nfc.watch(createNfcWatchOptions(), mockWatchCallback); verify(mockWatchCallback).call(mWatchCaptor.capture(), mErrorCaptor.capture()); assertNull(mErrorCaptor.getValue()); CancelWatchResponse mockCancelWatchCallback = mock(CancelWatchResponse.class); nfc.cancelWatch(mWatchCaptor.getValue().intValue(), mockCancelWatchCallback); // Check that cancel request was successfuly completed. verify(mockCancelWatchCallback).call(mErrorCaptor.capture()); assertNull(mErrorCaptor.getValue()); // Check that watch is not triggered when NFC tag is in proximity. nfc.processPendingOperationsForTesting(mNfcTagHandler); verify(mNfcClient, times(0)).onWatch(any(int[].class), any(NfcMessage.class)); } /** * Test that Nfc.cancelAllWatches() cancels all pending watch operations. */ @Test @Feature({"NFCTest"}) public void testCancelAllWatches() { TestNfcImpl nfc = new TestNfcImpl(mContext); nfc.setActivityForTesting(mActivity); WatchResponse mockWatchCallback1 = mock(WatchResponse.class); WatchResponse mockWatchCallback2 = mock(WatchResponse.class); nfc.watch(createNfcWatchOptions(), mockWatchCallback1); verify(mockWatchCallback1).call(mWatchCaptor.capture(), mErrorCaptor.capture()); assertNull(mErrorCaptor.getValue()); nfc.watch(createNfcWatchOptions(), mockWatchCallback2); verify(mockWatchCallback2).call(mWatchCaptor.capture(), mErrorCaptor.capture()); assertNull(mErrorCaptor.getValue()); CancelAllWatchesResponse mockCallback = mock(CancelAllWatchesResponse.class); nfc.cancelAllWatches(mockCallback); // Check that cancel request was successfuly completed. verify(mockCallback).call(mErrorCaptor.capture()); assertNull(mErrorCaptor.getValue()); } /** * Test that Nfc.cancelWatch() with invalid id is failing with NOT_FOUND error. */ @Test @Feature({"NFCTest"}) public void testCancelWatchInvalidId() { TestNfcImpl nfc = new TestNfcImpl(mContext); nfc.setActivityForTesting(mActivity); WatchResponse mockWatchCallback = mock(WatchResponse.class); nfc.watch(createNfcWatchOptions(), mockWatchCallback); verify(mockWatchCallback).call(mWatchCaptor.capture(), mErrorCaptor.capture()); assertNull(mErrorCaptor.getValue()); CancelWatchResponse mockCancelWatchCallback = mock(CancelWatchResponse.class); nfc.cancelWatch(mWatchCaptor.getValue().intValue() + 1, mockCancelWatchCallback); verify(mockCancelWatchCallback).call(mErrorCaptor.capture()); assertEquals(NfcErrorType.NOT_FOUND, mErrorCaptor.getValue().errorType); } /** * Test that Nfc.cancelAllWatches() is failing with NOT_FOUND error if there are no active * watch opeartions. */ @Test @Feature({"NFCTest"}) public void testCancelAllWatchesWithNoWathcers() { TestNfcImpl nfc = new TestNfcImpl(mContext); nfc.setActivityForTesting(mActivity); CancelAllWatchesResponse mockCallback = mock(CancelAllWatchesResponse.class); nfc.cancelAllWatches(mockCallback); verify(mockCallback).call(mErrorCaptor.capture()); assertEquals(NfcErrorType.NOT_FOUND, mErrorCaptor.getValue().errorType); } private NfcPushOptions createNfcPushOptions() { NfcPushOptions pushOptions = new NfcPushOptions(); pushOptions.target = NfcPushTarget.ANY; pushOptions.timeout = 0; pushOptions.ignoreRead = false; return pushOptions; } private NfcWatchOptions createNfcWatchOptions() { NfcWatchOptions options = new NfcWatchOptions(); options.url = ""; options.mediaType = ""; options.mode = NfcWatchMode.ANY; options.recordFilter = null; return options; } private NfcMessage createNfcMessage() { NfcMessage message = new NfcMessage(); message.url = ""; message.data = new NfcRecord[1]; NfcRecord nfcRecord = new NfcRecord(); nfcRecord.recordType = NfcRecordType.TEXT; nfcRecord.mediaType = TEXT_MIME; nfcRecord.data = TEST_TEXT.getBytes(); message.data[0] = nfcRecord; return message; } private NfcMessage createNfcMessage(String url, NfcRecord record) { NfcMessage message = new NfcMessage(); message.url = url; message.data = new NfcRecord[1]; message.data[0] = record; return message; } private NdefMessage createUrlWebNFCNdefMessage() { NfcRecord urlNfcRecord = new NfcRecord(); urlNfcRecord.recordType = NfcRecordType.URL; urlNfcRecord.mediaType = TEXT_MIME; urlNfcRecord.data = TEST_URL.getBytes(); NfcMessage urlNfcMessage = createNfcMessage(TEST_URL, urlNfcRecord); try { return NfcTypeConverter.toNdefMessage(urlNfcMessage); } catch (InvalidNfcMessageException e) { return null; } } }
3e0dedb08643ea01788e5e3b3fe6127852e54bb1
1,101
java
Java
src/main/java/ex01/pyrmont/Hello.java
robin2017/how_tomcat_work
64adc932925280d4b3fc0cf326aa3ad0fed6feb7
[ "Apache-1.1" ]
null
null
null
src/main/java/ex01/pyrmont/Hello.java
robin2017/how_tomcat_work
64adc932925280d4b3fc0cf326aa3ad0fed6feb7
[ "Apache-1.1" ]
null
null
null
src/main/java/ex01/pyrmont/Hello.java
robin2017/how_tomcat_work
64adc932925280d4b3fc0cf326aa3ad0fed6feb7
[ "Apache-1.1" ]
null
null
null
26.214286
76
0.533152
5,900
package ex01.pyrmont; import java.io.*; import java.net.Socket; /** * Created by robin on 2017/8/17. */ public class Hello { public void test() throws IOException, InterruptedException { Socket socket=new Socket("127.0.0.1",80); OutputStream os=socket.getOutputStream(); boolean autoflush=true; PrintWriter out=new PrintWriter(socket.getOutputStream(),autoflush); BufferedReader in=new BufferedReader( new InputStreamReader( socket.getInputStream())); out.println("GET /index.jsp HTTP/1.1"); out.println("Host:localhost:8080"); out.println("Connection:Close"); out.println(); boolean loop=true; StringBuffer sb=new StringBuffer(8096); while(loop){ if(in.ready()){ int i=0; while (i!=-1){ i=in.read(); sb.append((char)i); } loop=false; } Thread.currentThread().sleep(50); } socket.close(); } }
3e0dedcbcb068a559a057ae19f90a2adc1b5a8ae
4,017
java
Java
app/src/main/java/tk/winpooh32/omxrpicontroller/SettingsActivity.java
WinPooh32/OmxRPiController
d5c034a1050f0876e8494425771e0fa5a75bdca9
[ "MIT" ]
null
null
null
app/src/main/java/tk/winpooh32/omxrpicontroller/SettingsActivity.java
WinPooh32/OmxRPiController
d5c034a1050f0876e8494425771e0fa5a75bdca9
[ "MIT" ]
null
null
null
app/src/main/java/tk/winpooh32/omxrpicontroller/SettingsActivity.java
WinPooh32/OmxRPiController
d5c034a1050f0876e8494425771e0fa5a75bdca9
[ "MIT" ]
null
null
null
40.17
117
0.608912
5,901
package tk.winpooh32.omxrpicontroller; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.util.Log; public class SettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.activity_settings); //addPreferencesFromResource(R.xml.preferences); // Display the fragment as the main content. getFragmentManager().beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .commit(); setTitle("Settings"); } public static class SettingsFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.preferences); final ControllerApp app = (ControllerApp) this.getActivity().getApplicationContext(); final Preference ip = findPreference("ip"); final Preference port = findPreference("port"); final Preference path = findPreference("path"); final Preference connections = findPreference("connections"); final Preference uploads = findPreference("uploads"); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(app); ip.setSummary(app.serverIp); port.setSummary(app.serverPort); path.setSummary(prefs.getString("path","")); connections.setSummary(prefs.getString("connections","")); uploads.setSummary(prefs.getString("uploads","")); prefs.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if(key.equals("ip")){ app.serverIp = app.settings.getIp(); ip.setSummary(app.serverIp); } else if(key.equals("port")){ app.serverPort = app.settings.getPort(); port.setSummary(app.serverPort); } else if(key.equals("connections")){ connections.setSummary(sharedPreferences.getString("connections","")); } else if(key.equals("uploads")){ uploads.setSummary(sharedPreferences.getString("uploads","")); } else if(key.equals("path")){ path.setSummary(sharedPreferences.getString("path","")); } } }); } } // public static class SettingsFragment extends PreferenceFragment { // // private void setPreferencesFromResource(int preferences, String rootKey) { // setPreferencesFromResource(R.xml.preferences, rootKey); // } // //// @Override //// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //// //// mListPreference = (ListPreference) getPreferenceManager().findPreference("preference_key"); //// mListPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { //// @Override //// public boolean onPreferenceChange(Preference preference, Object newValue) { //// // your code here //// } //// } //// //// return inflater.inflate(R.layout.fragment_settings, container, false); //// } // } }
3e0deeab9aa1c16c30d99483563b419d9ed5f318
1,080
java
Java
jumi-core/src/main/java/fi/jumi/core/util/MemoryBarrier.java
orfjackal/jumi
18815c499b770f51cdb58cc6720dca4f254b2019
[ "Apache-2.0" ]
29
2015-01-18T13:09:54.000Z
2018-04-24T06:38:14.000Z
jumi-core/src/main/java/fi/jumi/core/util/MemoryBarrier.java
orfjackal/jumi
18815c499b770f51cdb58cc6720dca4f254b2019
[ "Apache-2.0" ]
null
null
null
jumi-core/src/main/java/fi/jumi/core/util/MemoryBarrier.java
orfjackal/jumi
18815c499b770f51cdb58cc6720dca4f254b2019
[ "Apache-2.0" ]
7
2015-04-09T20:12:26.000Z
2017-01-09T18:38:28.000Z
30
167
0.682407
5,902
// Copyright © 2011-2013, Esko Luontola <www.orfjackal.net> // This software is released under the Apache License 2.0. // The license text is at http://www.apache.org/licenses/LICENSE-2.0 package fi.jumi.core.util; import javax.annotation.concurrent.ThreadSafe; import java.util.concurrent.atomic.AtomicBoolean; /** * Operations for creating memory barriers. More information: * <ul> * <li><a href="http://g.oswego.edu/dl/jmm/cookbook.html">The JSR-133 Cookbook for Compiler Writers</a></li> * <li><a href="http://psy-lob-saw.blogspot.com/2012/12/atomiclazyset-is-performance-win-for.html">Atomic*.lazySet is a performance win for single writers</a></li> * <li><a href="http://brooker.co.za/blog/2012/09/10/volatile.html">Are volatile reads really free?</a></li> * </ul> */ @ThreadSafe public class MemoryBarrier { private final AtomicBoolean var = new AtomicBoolean(); public void storeStore() { var.lazySet(true); } public void storeLoad() { var.set(true); } public void loadLoad() { var.get(); } }
3e0df0521e947bbb7a1e58ed8858297be993d7fb
383
java
Java
src/build/android/incremental_install/java/org/chromium/incrementalinstall/SecondInstrumentation.java
tang88888888/naiveproxy
8bbb7526b927cbaa82870a4c81a08ccf5e8e9c1d
[ "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
src/build/android/incremental_install/java/org/chromium/incrementalinstall/SecondInstrumentation.java
tang88888888/naiveproxy
8bbb7526b927cbaa82870a4c81a08ccf5e8e9c1d
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
src/build/android/incremental_install/java/org/chromium/incrementalinstall/SecondInstrumentation.java
tang88888888/naiveproxy
8bbb7526b927cbaa82870a4c81a08ccf5e8e9c1d
[ "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
29.461538
73
0.785901
5,903
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.incrementalinstall; import android.app.Instrumentation; /** * Exists to support an app having multiple instrumentations. */ public final class SecondInstrumentation extends Instrumentation {}
3e0df0ed1f3c4f8b67701528ec2931725f1eef90
120
java
Java
src/rero/client/user/ClientCommand.java
pwillemann/jircii
b2c099059587a412eafaa99d465998e92ceccd4d
[ "Artistic-1.0" ]
10
2015-06-27T16:40:06.000Z
2022-02-28T11:22:02.000Z
src/rero/client/user/ClientCommand.java
pwillemann/jircii
b2c099059587a412eafaa99d465998e92ceccd4d
[ "Artistic-1.0" ]
2
2016-04-14T09:08:43.000Z
2016-07-31T08:31:18.000Z
src/rero/client/user/ClientCommand.java
pwillemann/jircii
b2c099059587a412eafaa99d465998e92ceccd4d
[ "Artistic-1.0" ]
4
2019-04-14T01:43:12.000Z
2021-12-30T19:43:37.000Z
17.142857
57
0.775
5,904
package rero.client.user; public interface ClientCommand { public void runAlias(String name, String parameters); }
3e0df16b73abce762e5832037b01b5c6ee7e8b68
326
java
Java
src/test/java/testListener/Main.java
lemonlulu/MyTest
8ef520776f5b0f72cca5ad292c27f02493842515
[ "Apache-2.0" ]
null
null
null
src/test/java/testListener/Main.java
lemonlulu/MyTest
8ef520776f5b0f72cca5ad292c27f02493842515
[ "Apache-2.0" ]
null
null
null
src/test/java/testListener/Main.java
lemonlulu/MyTest
8ef520776f5b0f72cca5ad292c27f02493842515
[ "Apache-2.0" ]
null
null
null
20.375
62
0.736196
5,905
package testListener; /** * Created by lemon on 2015/1/22. */ import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class Main { public static void main(String args[]){ // ServletContextEvent sce = new ServletContextEvent(); } }
3e0df25adc42bfb7eff8b1b24c2807631efc5414
16,054
java
Java
javaee-persistence-api/src/main/java/com/intellij/persistence/util/PersistenceCommonUtil.java
consulo-trash/consulo-hibernate
3f5a7247c6bfc7ee88923634bf2d698dcbe62efa
[ "Apache-2.0" ]
null
null
null
javaee-persistence-api/src/main/java/com/intellij/persistence/util/PersistenceCommonUtil.java
consulo-trash/consulo-hibernate
3f5a7247c6bfc7ee88923634bf2d698dcbe62efa
[ "Apache-2.0" ]
null
null
null
javaee-persistence-api/src/main/java/com/intellij/persistence/util/PersistenceCommonUtil.java
consulo-trash/consulo-hibernate
3f5a7247c6bfc7ee88923634bf2d698dcbe62efa
[ "Apache-2.0" ]
null
null
null
37.334884
195
0.773203
5,906
/* * Copyright 2000-2007 JetBrains s.r.o. * * 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.intellij.persistence.util; import gnu.trove.THashSet; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.jetbrains.annotations.NonNls; import com.intellij.jam.model.util.JamCommonUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.persistence.PersistenceHelper; import com.intellij.persistence.facet.PersistenceFacetBase; import com.intellij.persistence.model.PersistenceMappings; import com.intellij.persistence.model.PersistencePackage; import com.intellij.persistence.model.PersistenceQuery; import com.intellij.persistence.model.PersistentEmbeddedAttribute; import com.intellij.persistence.model.PersistentObject; import com.intellij.persistence.model.PersistentRelationshipAttribute; import com.intellij.persistence.model.TableInfoProvider; import com.intellij.persistence.roles.PersistenceClassRole; import com.intellij.persistence.roles.PersistenceClassRoleEnum; import com.intellij.persistence.roles.PersistenceRoleHolder; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiArrayType; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiClassType; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiMember; import com.intellij.psi.PsiType; import com.intellij.psi.PsiTypeParameter; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.ProjectScope; import com.intellij.psi.util.CachedValue; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PropertyUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtilBase; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.util.ExecutorsQuery; import com.intellij.util.Function; import com.intellij.util.Processor; import com.intellij.util.Query; import com.intellij.util.QueryExecutor; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xml.DomElement; import com.intellij.util.xml.DomUtil; import com.intellij.util.xml.GenericValue; import consulo.java.persistence.module.extension.PersistenceModuleExtension; import consulo.module.extension.ModuleExtension; /** * @author Gregory.Shrago */ public class PersistenceCommonUtil { @NonNls public static final String PERSISTENCE_FRAMEWORK_GROUP_ID = "persistence"; private PersistenceCommonUtil() { } @Nonnull public static List<PersistenceModuleExtension<?, ?>> getAllPersistenceFacets(@Nonnull final Project project) { final List<PersistenceModuleExtension<?, ?>> result = new ArrayList<>(); for(Module module : ModuleManager.getInstance(project).getModules()) { result.addAll(getAllPersistenceFacets(module)); } return result; } @Nonnull public static List<PersistenceModuleExtension<?, ?>> getAllPersistenceFacets(@Nonnull final Module module) { final List<PersistenceModuleExtension<?, ?>> result = new ArrayList<>(); ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); for(ModuleExtension extension : moduleRootManager.getExtensions()) { if(extension instanceof PersistenceModuleExtension) { result.add((PersistenceModuleExtension<?, ?>) extension); } } return result; } private static Key<CachedValue<List<PersistenceModuleExtension<?, ?>>>> MODULE_PERSISTENCE_FACETS = Key.create("MODULE_PERSISTENCE_FACETS"); @Nonnull public static List<PersistenceModuleExtension<?, ?>> getAllPersistenceFacetsWithDependencies(@Nonnull final Module module) { CachedValue<List<PersistenceModuleExtension<?, ?>>> cachedValue = module.getUserData(MODULE_PERSISTENCE_FACETS); if(cachedValue == null) { cachedValue = CachedValuesManager.getManager(module.getProject()).createCachedValue(() -> { final Set<Module> modules = new THashSet<>(); modules.addAll(Arrays.asList(JamCommonUtil.getAllDependentModules(module))); modules.addAll(Arrays.asList(JamCommonUtil.getAllModuleDependencies(module))); final Set<PersistenceModuleExtension<?, ?>> facets = new THashSet<>(); for(Module depModule : modules) { facets.addAll(getAllPersistenceFacets(depModule)); } return new CachedValueProvider.Result<>(new ArrayList<>(facets), ProjectRootManager.getInstance(module.getProject())); }, false); module.putUserData(MODULE_PERSISTENCE_FACETS, cachedValue); } return cachedValue.getValue(); } public static PersistenceModelBrowser createSameUnitsModelBrowser(@Nullable final PsiElement sourceElement) { final PsiClass sourceClass; final Set<PersistencePackage> unitSet; if(sourceElement == null || (sourceClass = PsiTreeUtil.getParentOfType(sourceElement, PsiClass.class, false)) == null) { unitSet = null; } else { unitSet = getAllPersistenceUnits(sourceClass, new THashSet<PersistencePackage>()); } return createUnitsAndTypeMapper(unitSet); } public static PersistenceModelBrowser createSameUnitsModelBrowser(@Nullable final DomElement sourceDom) { final Set<PersistencePackage> unitSet; final DomElement rootElement; if(sourceDom == null || !((rootElement = DomUtil.getRoot(sourceDom)) instanceof PersistenceMappings)) { unitSet = null; } else { unitSet = new THashSet<>(PersistenceHelper.getHelper().getSharedModelBrowser().getPersistenceUnits((PersistenceMappings) rootElement)); } return createUnitsAndTypeMapper(unitSet); } public static PersistenceModelBrowser createUnitsAndTypeMapper(@Nullable final Set<PersistencePackage> unitSet) { return PersistenceHelper.getHelper().createModelBrowser().setRoleFilter(new Condition<PersistenceClassRole>() { public boolean value(final PersistenceClassRole role) { final PersistentObject object = role.getPersistentObject(); final PersistenceClassRoleEnum roleType = role.getType(); return roleType != PersistenceClassRoleEnum.ENTITY_LISTENER && object != null && (unitSet == null || unitSet.contains(role.getPersistenceUnit())); } }); } public static PersistenceModelBrowser createFacetAndUnitModelBrowser(final PersistenceFacetBase facet, final PersistencePackage unit, final PersistenceClassRoleEnum type) { return PersistenceHelper.getHelper().createModelBrowser().setRoleFilter(new Condition<PersistenceClassRole>() { public boolean value(final PersistenceClassRole role) { final PersistentObject object = role.getPersistentObject(); return object != null && (type == null || role.getType() == type) && (unit == null || unit.equals(role.getPersistenceUnit())) && (facet == null || facet.equals(role.getFacet())); } }); } @Nullable public static PsiType getTargetEntityType(final PsiMember psiMember) { return getTargetEntityType(PropertyUtil.getPropertyType(psiMember)); } @Nullable public static PsiType getTargetEntityType(final PsiType type) { final Pair<JavaContainerType, PsiType> containerType = getContainerType(type); return containerType.getSecond(); } public static <T extends Collection<PersistencePackage>> T getAllPersistenceUnits(@Nullable final PsiClass sourceClass, @Nonnull final T result) { for(PersistenceClassRole role : getPersistenceRoles(sourceClass)) { ContainerUtil.addIfNotNull(role.getPersistenceUnit(), result); } return result; } @Nonnull public static PersistenceClassRole[] getPersistenceRoles(@Nullable final PsiClass aClass) { if(aClass == null || !aClass.isValid()) { return PersistenceClassRole.EMPTY_ARRAY; } return PersistenceRoleHolder.getInstance(aClass.getProject()).getRoles(aClass); } @Nonnull public static <T extends PersistencePackage, V extends PersistenceMappings> Collection<V> getDomEntityMappings(final Class<V> mappingsClass, final T unit, final PersistenceFacetBase<?, T> facet) { final THashSet<V> result = new THashSet<>(); for(PersistenceMappings mappings : facet.getDefaultEntityMappings(unit)) { if(mappingsClass.isAssignableFrom(mappings.getClass())) { result.add((V) mappings); } } for(GenericValue<V> value : unit.getModelHelper().getMappingFiles(mappingsClass)) { ContainerUtil.addIfNotNull(value.getValue(), result); } return result; } public static boolean isSameTable(final TableInfoProvider table1, final TableInfoProvider table2) { if(table1 == null || table2 == null) { return false; } final String name1 = table1.getTableName().getValue(); return StringUtil.isNotEmpty(name1) && Comparing.equal(name1, table2.getTableName().getValue()) && Comparing.equal(table1.getSchema().getValue(), table2.getSchema().getValue()) && Comparing .equal(table1.getCatalog().getValue(), table2.getCatalog().getValue()); } public static String getUniqueId(final PsiElement psiElement) { final VirtualFile virtualFile = psiElement == null ? null : PsiUtilBase.getVirtualFile(psiElement); return virtualFile == null ? "" : virtualFile.getUrl(); } public static String getMultiplicityString(final boolean optional, final boolean many) { final String first = (optional ? "0" : "1"); final String last = (many ? "*" : "1"); return first.equals(last) ? first : first + ".." + last; } public static <T, V extends Collection<T>> V mapPersistenceRoles(final V result, final Project project, final PersistenceModuleExtension<?, ?> facet, final PersistencePackage unit, final Function<PersistenceClassRole, T> mapper) { final Collection<PersistenceClassRole> allRoles = PersistenceRoleHolder.getInstance(project).getClassRoleManager().getUserData(PersistenceRoleHolder.PERSISTENCE_CLASS_ROLES_KEY, PersistenceRoleHolder.PERSISTENCE_ALL_ROLES_DATA_KEY); if(allRoles != null) { for(PersistenceClassRole role : allRoles) { if((facet == null || facet == role.getFacet()) && (unit == null || unit == role.getPersistenceUnit())) { ContainerUtil.addIfNotNull(mapper.fun(role), result); } } } return result; } public static boolean haveCorrespondingMultiplicity(final PersistentRelationshipAttribute a1, final PersistentRelationshipAttribute a2) { return a1.getAttributeModelHelper().getRelationshipType().corresponds(a2.getAttributeModelHelper().getRelationshipType()); } public static <T extends PersistencePackage> boolean processNamedQueries(final PersistenceModuleExtension<?, ?> facet, final boolean nativeQueries, final Processor<PersistenceQuery> processor) { return processNamedQueries(nativeQueries ? PersistenceRoleHolder.PERSISTENCE_ALL_NATIVE_QUERIES_DATA_KEY : PersistenceRoleHolder.PERSISTENCE_ALL_QUERIES_DATA_KEY, facet, processor); } private static <T extends PersistencePackage> boolean processNamedQueries(final Key<Map<PersistenceModuleExtension<?, ?>, Collection<PersistenceQuery>>> queriesDataKey, final PersistenceModuleExtension<?, T> facet, final Processor<PersistenceQuery> processor) { final Map<PersistenceModuleExtension<?, ?>, Collection<PersistenceQuery>> namedQueriesMap = PersistenceRoleHolder.getInstance(facet.getModule().getProject()).getClassRoleManager().getUserData (PersistenceRoleHolder.PERSISTENCE_CLASS_ROLES_KEY, queriesDataKey); if(namedQueriesMap != null) { final Collection<PersistenceQuery> queries = namedQueriesMap.get(facet); if(queries != null && !ContainerUtil.process(queries, processor)) { return false; } } return true; } @Nonnull public static Pair<JavaContainerType, PsiType> getContainerType(final PsiType type) { if(type instanceof PsiArrayType) { return Pair.create(JavaContainerType.ARRAY, ((PsiArrayType) type).getComponentType()); } final PsiClassType.ClassResolveResult classResolveResult = type instanceof PsiClassType ? ((PsiClassType) type).resolveGenerics() : null; if(classResolveResult == null) { return Pair.create(null, type); } final PsiClass psiClass = classResolveResult.getElement(); if(psiClass == null) { return Pair.create(null, type); } final PsiManager manager = psiClass.getManager(); final GlobalSearchScope scope = ProjectScope.getAllScope(manager.getProject()); for(JavaContainerType collectionType : JavaContainerType.values()) { if(collectionType == JavaContainerType.ARRAY) { continue; } final PsiClass aClass = JavaPsiFacade.getInstance(manager.getProject()).findClass(collectionType.getJavaBaseClassName(), scope); if(aClass != null && (manager.areElementsEquivalent(aClass, psiClass) || psiClass.isInheritor(aClass, true))) { final PsiTypeParameter[] typeParameters = aClass.getTypeParameters(); final PsiType entityType; if(typeParameters.length > 0) { entityType = TypeConversionUtil.getSuperClassSubstitutor(aClass, psiClass, classResolveResult.getSubstitutor()).substitute(typeParameters[typeParameters.length - 1]); } else { entityType = PsiType.getJavaLangObject(manager, scope); } return Pair.create(collectionType, entityType); } } return Pair.create(null, type); } public static Query<PersistentObject> queryPersistentObjects(final PersistenceMappings mappings) { return new ExecutorsQuery<>(mappings, Collections.<QueryExecutor<PersistentObject, PersistenceMappings>>singletonList(new QueryExecutor<PersistentObject, PersistenceMappings>() { public boolean execute(PersistenceMappings queryParameters, Processor<PersistentObject> consumer) { if(!ContainerUtil.process(queryParameters.getModelHelper().getPersistentEntities(), consumer)) { return false; } if(!ContainerUtil.process(queryParameters.getModelHelper().getPersistentSuperclasses(), consumer)) { return false; } if(!ContainerUtil.process(queryParameters.getModelHelper().getPersistentEmbeddables(), consumer)) { return false; } return true; } })); } @Nullable public static PsiClass getTargetClass(final PersistentRelationshipAttribute attribute) { final GenericValue<PsiClass> classValue = attribute.getTargetEntityClass(); final PsiClass targetClass; if(classValue.getStringValue() != null) { targetClass = classValue.getValue(); } else { final PsiType entityType = getTargetEntityType(attribute.getPsiMember()); targetClass = entityType instanceof PsiClassType ? ((PsiClassType) entityType).resolve() : null; } return targetClass; } @Nullable public static PsiClass getTargetClass(final PersistentEmbeddedAttribute attribute) { final GenericValue<PsiClass> classValue = attribute.getTargetEmbeddableClass(); final PsiClass targetClass; if(classValue.getStringValue() != null) { targetClass = classValue.getValue(); } else { final PsiType entityType = PropertyUtil.getPropertyType(attribute.getPsiMember()); targetClass = entityType instanceof PsiClassType ? ((PsiClassType) entityType).resolve() : null; } return targetClass; } }
3e0df2d6704c7f5efeab95974e6245458935b9cb
1,868
java
Java
src/main/java/com/simibubi/create/lib/mixin/client/FogRendererMixin.java
EcoBuilder13/Create-Refabricated
0f15b62d5ec2dfbbaeff600ab1cf7de9a0caf26c
[ "MIT" ]
null
null
null
src/main/java/com/simibubi/create/lib/mixin/client/FogRendererMixin.java
EcoBuilder13/Create-Refabricated
0f15b62d5ec2dfbbaeff600ab1cf7de9a0caf26c
[ "MIT" ]
null
null
null
src/main/java/com/simibubi/create/lib/mixin/client/FogRendererMixin.java
EcoBuilder13/Create-Refabricated
0f15b62d5ec2dfbbaeff600ab1cf7de9a0caf26c
[ "MIT" ]
null
null
null
35.923077
123
0.760707
5,907
package com.simibubi.create.lib.mixin.client; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import com.mojang.blaze3d.systems.RenderSystem; import com.simibubi.create.lib.event.FogEvents; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.Camera; import net.minecraft.client.renderer.FogRenderer; @Environment(EnvType.CLIENT) @Mixin(FogRenderer.class) public abstract class FogRendererMixin { @Shadow private static float fogRed; @Shadow private static float fogGreen; @Shadow private static float fogBlue; //TODO: Move this idk where // @Inject(at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/RenderSystem;clearColor(FFFF)V"), // method = "render(Lnet/minecraft/client/renderer/ActiveRenderInfo;FLnet/minecraft/client/world/ClientWorld;IF)V") // private static void render(Camera activeRenderInfo, float f, ClientLevel clientWorld, int i, float g, CallbackInfo ci) { // Vector3f color = FogEvents.SET_COLOR.invoker().setColor(activeRenderInfo, new Vector3f(red, green, blue)); // red = color.x(); // green = color.y(); // blue = color.z(); // } @Inject(at = @At("HEAD"), method = "setupFog", cancellable = true) private static void setupFog(Camera activeRenderInfo, FogRenderer.FogMode fogType, float f, boolean bl, CallbackInfo ci) { float density = FogEvents.SET_DENSITY.invoker().setDensity(activeRenderInfo, 0.1f); if (density != 0.1f) { //I am not 100% sure this is the same as RenderSystem.fogDensity(density) ¯\_(ツ)_/¯ RenderSystem.setShaderFogColor(fogRed, fogGreen, fogBlue, density); //RenderSystem.fogDensity(density); ci.cancel(); } } }
3e0df36a11509a94b048e8f3c00b7b5bf8a5bf40
468
java
Java
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/VdsInstallStages.java
jbeecham/ovirt-engine
3e76a8d3b970a963cedd84bcb3c7425b8484cf26
[ "Apache-2.0" ]
3
2019-01-12T06:47:09.000Z
2019-02-22T21:32:26.000Z
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/VdsInstallStages.java
jbeecham/ovirt-engine
3e76a8d3b970a963cedd84bcb3c7425b8484cf26
[ "Apache-2.0" ]
null
null
null
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/VdsInstallStages.java
jbeecham/ovirt-engine
3e76a8d3b970a963cedd84bcb3c7425b8484cf26
[ "Apache-2.0" ]
2
2015-01-15T19:06:01.000Z
2015-04-29T08:15:29.000Z
18
56
0.65812
5,908
package org.ovirt.engine.core.bll; public enum VdsInstallStages { None, Start, ConnectToServer, CheckUniqueVds, UploadScript, RunScript, DownloadCertificateRequest, SignCertificateRequest, UploadSignedCertificate, UploadCA, FinishCommand, End, Error; public int getValue() { return this.ordinal(); } public static VdsInstallStages forValue(int value) { return values()[value]; } }
3e0df38e0de57ac265e5a9efbba2a00345013427
580
java
Java
src/main/java/model/products/ProductProperties.java
ismael094/SatelliteImagesApplication
592f1d3b598947d3c374f7532e0cd6c72aaf8bea
[ "CC-BY-4.0" ]
null
null
null
src/main/java/model/products/ProductProperties.java
ismael094/SatelliteImagesApplication
592f1d3b598947d3c374f7532e0cd6c72aaf8bea
[ "CC-BY-4.0" ]
7
2021-01-21T01:40:01.000Z
2022-01-04T16:48:50.000Z
src/main/java/model/products/ProductProperties.java
ismael094/SatelliteImagesApplication
592f1d3b598947d3c374f7532e0cd6c72aaf8bea
[ "CC-BY-4.0" ]
null
null
null
21.481481
61
0.684483
5,909
package model.products; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class ProductProperties { private String name; @JsonProperty("content") private Object content; public String getName() { return name; } public void setName(String name) { this.name = name; } public Object getContent() { return content; } public void setContent(Object content) { this.content = content; } }
3e0df3f6973767d1f3722c3a74b03176b72a113c
2,031
java
Java
svalbard/xmlbeans/src/main/java/org/n52/svalbard/encode/AbstractLogValueTypeEncoder.java
52North/arctic-sea
2adb4a423db9efd2350920af264f761c29b2604f
[ "Apache-2.0" ]
19
2017-01-13T13:30:32.000Z
2021-11-27T16:21:42.000Z
svalbard/xmlbeans/src/main/java/org/n52/svalbard/encode/AbstractLogValueTypeEncoder.java
52North/arctic-sea
2adb4a423db9efd2350920af264f761c29b2604f
[ "Apache-2.0" ]
81
2017-12-19T15:47:04.000Z
2022-03-30T04:00:52.000Z
svalbard/xmlbeans/src/main/java/org/n52/svalbard/encode/AbstractLogValueTypeEncoder.java
52North/arctic-sea
2adb4a423db9efd2350920af264f761c29b2604f
[ "Apache-2.0" ]
32
2017-12-21T14:32:29.000Z
2022-03-02T15:04:52.000Z
39.823529
108
0.733629
5,910
/* * Copyright (C) 2015-2021 52°North Spatial Information Research GmbH * * 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.n52.svalbard.encode; import org.n52.shetland.ogc.om.values.ProfileLevel; import org.n52.svalbard.encode.exception.EncodingException; import net.opengis.gwmlWell.x22.LogValueType; public abstract class AbstractLogValueTypeEncoder<T> extends AbstractGroundWaterMLEncoder<T, ProfileLevel> { protected LogValueType encodeLogValue(ProfileLevel profileLevel) throws EncodingException { LogValueType lvt = LogValueType.Factory.newInstance(); setFromDepth(lvt, profileLevel); setToDepth(lvt, profileLevel); setValue(lvt, profileLevel); return lvt; } private void setFromDepth(LogValueType lvt, ProfileLevel profileLevel) throws EncodingException { if (profileLevel.isSetLevelStart()) { lvt.addNewFromDepth().addNewQuantity().set(encodeSweCommon(profileLevel.getLevelStart())); } } private void setToDepth(LogValueType lvt, ProfileLevel profileLevel) throws EncodingException { if (profileLevel.isSetLevelEnd()) { lvt.addNewToDepth().addNewQuantity().set(encodeSweCommon(profileLevel.getLevelEnd())); } } private void setValue(LogValueType lvt, ProfileLevel profileLevel) throws EncodingException { if (profileLevel.isSetValue()) { lvt.addNewValue().addNewDataRecord().set(encodeSweCommon(profileLevel.valueAsDataRecord())); } } }
3e0df475ff8da48770be1e4d938f65645d297b8c
4,530
java
Java
flink/src/main/java/org/apache/iceberg/flink/IcebergTableSource.java
dmgcodevil/iceberg
7001d95b8635d58f54795e1ec4c588697e86f47d
[ "Apache-2.0" ]
1
2021-01-04T11:22:52.000Z
2021-01-04T11:22:52.000Z
flink/src/main/java/org/apache/iceberg/flink/IcebergTableSource.java
dmgcodevil/iceberg
7001d95b8635d58f54795e1ec4c588697e86f47d
[ "Apache-2.0" ]
2
2022-01-28T20:37:58.000Z
2022-02-11T22:28:29.000Z
flink/src/main/java/org/apache/iceberg/flink/IcebergTableSource.java
dmgcodevil/iceberg
7001d95b8635d58f54795e1ec4c588697e86f47d
[ "Apache-2.0" ]
1
2020-12-22T17:15:15.000Z
2020-12-22T17:15:15.000Z
35.390625
111
0.742826
5,911
/* * 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.iceberg.flink; import java.util.Arrays; import java.util.Map; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.table.api.TableSchema; import org.apache.flink.table.data.RowData; import org.apache.flink.table.sources.FilterableTableSource; import org.apache.flink.table.sources.LimitableTableSource; import org.apache.flink.table.sources.ProjectableTableSource; import org.apache.flink.table.sources.StreamTableSource; import org.apache.flink.table.sources.TableSource; import org.apache.flink.table.types.DataType; import org.apache.flink.table.utils.TableConnectorUtils; import org.apache.iceberg.flink.source.FlinkSource; /** * Flink Iceberg table source. * TODO: Implement {@link FilterableTableSource} */ public class IcebergTableSource implements StreamTableSource<RowData>, ProjectableTableSource<RowData>, LimitableTableSource<RowData> { private final TableLoader loader; private final TableSchema schema; private final Map<String, String> properties; private final int[] projectedFields; private final boolean isLimitPushDown; private final long limit; public IcebergTableSource(TableLoader loader, TableSchema schema, Map<String, String> properties) { this(loader, schema, properties, null, false, -1); } private IcebergTableSource(TableLoader loader, TableSchema schema, Map<String, String> properties, int[] projectedFields, boolean isLimitPushDown, long limit) { this.loader = loader; this.schema = schema; this.properties = properties; this.projectedFields = projectedFields; this.isLimitPushDown = isLimitPushDown; this.limit = limit; } @Override public boolean isBounded() { return FlinkSource.isBounded(properties); } @Override public TableSource<RowData> projectFields(int[] fields) { return new IcebergTableSource(loader, schema, properties, fields, isLimitPushDown, limit); } @Override public DataStream<RowData> getDataStream(StreamExecutionEnvironment execEnv) { return FlinkSource.forRowData().env(execEnv).tableLoader(loader).project(getProjectedSchema()).limit(limit) .properties(properties).build(); } @Override public TableSchema getTableSchema() { return schema; } @Override public DataType getProducedDataType() { return getProjectedSchema().toRowDataType().bridgedTo(RowData.class); } private TableSchema getProjectedSchema() { TableSchema fullSchema = getTableSchema(); if (projectedFields == null) { return fullSchema; } else { String[] fullNames = fullSchema.getFieldNames(); DataType[] fullTypes = fullSchema.getFieldDataTypes(); return TableSchema.builder().fields( Arrays.stream(projectedFields).mapToObj(i -> fullNames[i]).toArray(String[]::new), Arrays.stream(projectedFields).mapToObj(i -> fullTypes[i]).toArray(DataType[]::new)).build(); } } @Override public String explainSource() { String explain = "Iceberg table: " + loader.toString(); if (projectedFields != null) { explain += ", ProjectedFields: " + Arrays.toString(projectedFields); } if (isLimitPushDown) { explain += String.format(", LimitPushDown : %d", limit); } return TableConnectorUtils.generateRuntimeName(getClass(), getTableSchema().getFieldNames()) + explain; } @Override public boolean isLimitPushedDown() { return isLimitPushDown; } @Override public TableSource<RowData> applyLimit(long newLimit) { return new IcebergTableSource(loader, schema, properties, projectedFields, true, newLimit); } }
3e0df4aa025006f0ff531e650748a244b9c70497
1,650
java
Java
luna-commons-common/src/main/java/com/luna/common/entity/Ztree.java
DAQ121/luna-commons
889110e845a5df3f481a180a405ebde425a7de06
[ "Apache-2.0" ]
1
2020-08-10T16:46:48.000Z
2020-08-10T16:46:48.000Z
luna-commons-common/src/main/java/com/luna/common/entity/Ztree.java
DAQ121/luna-commons
889110e845a5df3f481a180a405ebde425a7de06
[ "Apache-2.0" ]
null
null
null
luna-commons-common/src/main/java/com/luna/common/entity/Ztree.java
DAQ121/luna-commons
889110e845a5df3f481a180a405ebde425a7de06
[ "Apache-2.0" ]
null
null
null
15.865385
55
0.492121
5,912
package com.luna.common.entity; import java.io.Serializable; /** * Ztree树结构实体类 * * @author ruoyi */ public class Ztree implements Serializable { private static final long serialVersionUID = 1L; /** * 节点ID */ private Long id; /** * 节点父ID */ private Long pId; /** * 节点名称 */ private String name; /** * 节点标题 */ private String title; /** * 是否勾选 */ private boolean checked = false; /** * 是否展开 */ private boolean open = false; /** * 是否能勾选 */ private boolean nocheck = false; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getpId() { return pId; } public void setpId(Long pId) { this.pId = pId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } public boolean isOpen() { return open; } public void setOpen(boolean open) { this.open = open; } public boolean isNocheck() { return nocheck; } public void setNocheck(boolean nocheck) { this.nocheck = nocheck; } }
3e0df60befa0c2781cb9843d14e697a59be0199b
7,143
java
Java
src/test/testdatageneration/AbstractJUnitTest.java
ducanhnguyen/cft4cpp-for-dummy
d7599f95e688943f52f6a9a0b729f16011997eb8
[ "Apache-2.0" ]
null
null
null
src/test/testdatageneration/AbstractJUnitTest.java
ducanhnguyen/cft4cpp-for-dummy
d7599f95e688943f52f6a9a0b729f16011997eb8
[ "Apache-2.0" ]
null
null
null
src/test/testdatageneration/AbstractJUnitTest.java
ducanhnguyen/cft4cpp-for-dummy
d7599f95e688943f52f6a9a0b729f16011997eb8
[ "Apache-2.0" ]
null
null
null
45.788462
116
0.747585
5,913
package test.testdatageneration; import com.console.Console; import com.console.ConsoleOutput; import com.fit.config.*; import com.fit.testdatagen.ITestdataGeneration; import com.fit.testdatagen.htmlreport.ITestReport; import com.fit.utils.Utils; import org.apache.log4j.Logger; import javax.sound.sampled.LineUnavailableException; import java.io.File; import java.io.IOException; import java.util.List; public abstract class AbstractJUnitTest { final static Logger logger = Logger.getLogger(AbstractJUnitTest.class); public static Logger getLogger() { return logger; } public boolean generateTestdata(String originalProjectPath, String methodName, EO expectedOutput, int coverageType, ITestReport testReport) throws LineUnavailableException { // Create file for storing function String folderTestPath = ""; try { folderTestPath = new File(Settingv2.settingPath).getParentFile().getCanonicalPath() + File.separator; } catch (IOException e) { e.printStackTrace(); } String inputPath = folderTestPath + "test.txt"; methodName = (methodName.startsWith(File.separator) ? "" : File.separator) + methodName; Utils.writeContentToFile(methodName, inputPath); // Create setting.properties String configurePath = folderTestPath + "setting.properties"; Settingv2.create(); Settingv2.setValue(ISettingv2.DEFAULT_CHARACTER_LOWER_BOUND, 32); Settingv2.setValue(ISettingv2.DEFAULT_CHARACTER_UPPER_BOUND, 126); Settingv2.setValue(ISettingv2.DEFAULT_NUMBER_LOWER_BOUND, -95); Settingv2.setValue(ISettingv2.DEFAULT_NUMBER_UPPER_BOUND, 193); Settingv2.setValue(ISettingv2.DEFAULT_TEST_ARRAY_SIZE, 12); Settingv2.setValue(ISettingv2.MAX_ITERATION_FOR_EACH_LOOP, 11); AbstractSetting.setValue(ISettingv2.IN_TEST_MODE, "true"); Settingv2.setValue(ISettingv2.TESTDATA_STRATEGY, ITestdataGeneration.TESTDATA_GENERATION_STRATEGIES.FAST_MARS); Settingv2.setValue(ISettingv2.SMT_LIB_FILE_PATH, folderTestPath + "constraints.smt2"); if (coverageType == IFunctionConfig.BRANCH_COVERAGE) Settingv2.setValue(ISettingv2.COVERAGE, ISettingv2.SUPPORT_COVERAGE_CRITERIA[0]); else if (coverageType == IFunctionConfig.STATEMENT_COVERAGE) Settingv2.setValue(ISettingv2.COVERAGE, ISettingv2.SUPPORT_COVERAGE_CRITERIA[1]); else if (coverageType == IFunctionConfig.SUBCONDITION) Settingv2.setValue(ISettingv2.COVERAGE, ISettingv2.SUPPORT_COVERAGE_CRITERIA[2]); Settingv2.setValue(ISettingv2.SELECTED_SOLVING_STRATEGY, ISettingv2.SUPPORT_SOLVING_STRATEGIES[0]); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } // Paths.CURRENT_PROJECT.ORIGINAL_PROJECT_PATH = originalProjectPath; AbstractSetting.setValue(ISettingv2.INPUT_PROJECT_PATH, Paths.CURRENT_PROJECT.ORIGINAL_PROJECT_PATH); logger.debug("original project: " + Paths.CURRENT_PROJECT.ORIGINAL_PROJECT_PATH); Paths.CURRENT_PROJECT.TYPE_OF_PROJECT = Utils.getTypeOfProject(Paths.CURRENT_PROJECT.ORIGINAL_PROJECT_PATH); expectedOutput = expectedOutput == null ? new EO(EO.UNSPECIFIED_NUM_OF_TEST_PATH, EO.MAXIMUM_COVERAGE) : expectedOutput; // Generate test data String[] args = new String[] { Console.LOAD_PROJECT, Paths.CURRENT_PROJECT.ORIGINAL_PROJECT_PATH, Console.TESTED_FUNCTIONS, inputPath, Console.CONFIG, configurePath, Console.LOG4J_LEVEL, "debug" }; Console console = new Console(args); // Display output List<ConsoleOutput> outputList = console.getOutput(); boolean reachCoverageObjective = false; for (ConsoleOutput outputItem : outputList) { // logger.info("Original function: " + // outputItem.getFunctionNode().getAST().getRawSignature()); long totalRunningTime = outputItem.getRunningTime() - outputItem.getMacroNormalizationTime(); logger.info(""); logger.info("|--SUMMARY - not include macro normalization-----|"); logger.info("| Total time = " + totalRunningTime + "ms (~" + totalRunningTime / 1000 + "s)"); logger.info("| Execution time = " + outputItem.getExecutionTime() + "ms (" + outputItem.getExecutionTime() * 1.0 / totalRunningTime * 100 + "%)"); logger.info("| Solver running time = " + outputItem.getSolverRunningTime() + "ms (" + outputItem.getSolverRunningTime() * 1.0 / totalRunningTime * 100 + "%)"); logger.info("| Make file running time = " + outputItem.getMakeCommandRunningTime() + "ms (" + outputItem.getMakeCommandRunningTime() * 1.0 / totalRunningTime * 100 + "%) (" + outputItem.getMakeCommandRunningNumber() + "/" + outputItem.getNumOfExecutions() + " makes)"); logger.info("| Normalization time = " + (outputItem.getNormalizationTime() - outputItem.getMacroNormalizationTime()) + "ms (" + (outputItem.getNormalizationTime() - outputItem.getMacroNormalizationTime()) * 1.0 / totalRunningTime * 100 + "%)"); logger.info("| Symbolic execution time = " + outputItem.getSymbolicExecutionTime() + "ms (" + outputItem.getSymbolicExecutionTime() * 1.0 / totalRunningTime * 100 + "%)"); logger.info("| Num of effective solver calls = " + (outputItem.getNumOfSolverCalls() - outputItem.getNumOfSolverCallsbutCannotSolve()) + "/" + outputItem.getNumOfSolverCalls() + " times (Num of error Solver calls = " + outputItem.getNumOfSolverCallsbutCannotSolve() + "/" + outputItem.getNumOfSolverCalls() + ")"); logger.info("| Num of no change to coverage iteration = " + outputItem.getNumOfNoChangeToCoverage()); logger.info("| Num of symbolic executions = " + outputItem.getNumOfSymbolicExecutions() + " times"); logger.info("| Num of symbolic statements = " + outputItem.getNumOfSymbolicStatements() + " times"); logger.info("| Num of executions = " + outputItem.getNumOfExecutions() + " times"); logger.info("| Reached coverage = " + outputItem.getCoverge() + "% (Expected coverage = " + expectedOutput.getExpectedCoverage() + "%)"); logger.info("|--END SUMMARY - not include macro normalization-----|"); logger.info("| Macro normalization time = " + outputItem.getMacroNormalizationTime() / 1000 + " seconds"); logger.info(""); logger.info(""); // Compare the actual output and expected output reachCoverageObjective = outputItem.getCoverge() >= expectedOutput.getExpectedCoverage() ? true : false; } console.exportToHtml(new File(JUNIT_REPORT), methodName); Settingv2.setValue(ISettingv2.IN_TEST_MODE, "false"); return reachCoverageObjective; } protected class EO { public static final int UNSPECIFIED_NUM_OF_TEST_PATH = -1; public static final float MAXIMUM_COVERAGE = 100f; int nTestPath; float reachCoverage; public EO(int nTestPath, float reachCoverage) { super(); this.nTestPath = nTestPath; this.reachCoverage = reachCoverage; } public int getnTestPath() { return nTestPath; } public float getExpectedCoverage() { return reachCoverage; } } // Most of functions do not contain macro, so that we do not perform macro // normalization to reduce the test data generation time. public static boolean ENABLE_MACRO_NORMALIZATION = false; // default value public static String JUNIT_REPORT = "C:\\Users\\ducanhnguyen\\Desktop\\test.html"; }
3e0df62fb721034d22f94ff069dc01c4603f3d76
2,786
java
Java
src/main/java/io/github/haykam821/extracauldrons/LavaCauldronBlock.java
haykam821/Extra-Cauldrons
b380d3eb4ab4cc710eb346ef915a1ec695667217
[ "MIT" ]
null
null
null
src/main/java/io/github/haykam821/extracauldrons/LavaCauldronBlock.java
haykam821/Extra-Cauldrons
b380d3eb4ab4cc710eb346ef915a1ec695667217
[ "MIT" ]
null
null
null
src/main/java/io/github/haykam821/extracauldrons/LavaCauldronBlock.java
haykam821/Extra-Cauldrons
b380d3eb4ab4cc710eb346ef915a1ec695667217
[ "MIT" ]
null
null
null
35.265823
152
0.734386
5,914
package io.github.haykam821.extracauldrons; import net.minecraft.block.BlockState; import net.minecraft.block.CauldronBlock; import net.minecraft.entity.Entity; import net.minecraft.entity.damage.DamageSource; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvents; import net.minecraft.stat.Stats; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class LavaCauldronBlock extends CauldronBlock { public LavaCauldronBlock(Settings settings) { super(settings); } public ActionResult onUse(BlockState blockState, World world, BlockPos blockPos, PlayerEntity playerEntity, Hand hand, BlockHitResult blockHitResult) { ItemStack itemStack = playerEntity.getStackInHand(hand); if (itemStack.isEmpty()) { return ActionResult.PASS; } else { int level = (Integer)blockState.get(LEVEL); Item item = itemStack.getItem(); if (item == Items.LAVA_BUCKET) { if (level < 3 && !world.isClient) { if (!playerEntity.abilities.creativeMode) { playerEntity.setStackInHand(hand, new ItemStack(Items.BUCKET)); } playerEntity.incrementStat(Stats.FILL_CAULDRON); this.setLevel(world, blockPos, blockState, 3); world.playSound((PlayerEntity) null, blockPos, SoundEvents.ITEM_BUCKET_EMPTY_LAVA, SoundCategory.BLOCKS, 1.0F, 1.0F); } return ActionResult.SUCCESS; } else if (item == Items.BUCKET) { if (level == 3 && !world.isClient) { if (!playerEntity.abilities.creativeMode) { itemStack.decrement(1); if (itemStack.isEmpty()) { playerEntity.setStackInHand(hand, new ItemStack(Items.LAVA_BUCKET)); } else if (!playerEntity.inventory.insertStack(new ItemStack(Items.LAVA_BUCKET))) { playerEntity.dropItem(new ItemStack(Items.LAVA_BUCKET), false); } } playerEntity.incrementStat(Stats.USE_CAULDRON); this.setLevel(world, blockPos, blockState, 0); world.playSound((PlayerEntity)null, blockPos, SoundEvents.ITEM_BUCKET_FILL_LAVA, SoundCategory.BLOCKS, 1.0F, 1.0F); } return ActionResult.SUCCESS; } } return ActionResult.PASS; } public void onEntityCollision(BlockState blockState, World world, BlockPos blockPos, Entity entity) { int level = blockState.get(LEVEL); float liquidY = ((level * 3) + 6.0F) / 16.0F + blockPos.getY(); if (!world.isClient && level > 0 && entity.getY() <= (double) liquidY) { if (!entity.isFireImmune()) { entity.damage(DamageSource.LAVA, 4.0F); entity.setOnFireFor(15); } } } }
3e0df69f92782114f6ead7780009304a9415114e
4,442
java
Java
helpdesk-maker-checker-service/src/main/java/org/symphonyoss/symphony/bots/helpdesk/makerchecker/message/MakerCheckerMessageBuilder.java
symphonyoss/GroupID
ad69bd0f378f02c8c4bce017e5ddf1f3c319cd3b
[ "Apache-2.0" ]
null
null
null
helpdesk-maker-checker-service/src/main/java/org/symphonyoss/symphony/bots/helpdesk/makerchecker/message/MakerCheckerMessageBuilder.java
symphonyoss/GroupID
ad69bd0f378f02c8c4bce017e5ddf1f3c319cd3b
[ "Apache-2.0" ]
3
2018-03-01T19:25:02.000Z
2018-03-16T19:00:26.000Z
helpdesk-maker-checker-service/src/main/java/org/symphonyoss/symphony/bots/helpdesk/makerchecker/message/MakerCheckerMessageBuilder.java
symphonyoss/GroupID
ad69bd0f378f02c8c4bce017e5ddf1f3c319cd3b
[ "Apache-2.0" ]
4
2018-04-20T17:18:07.000Z
2020-12-16T11:45:23.000Z
27.7625
107
0.742683
5,915
package org.symphonyoss.symphony.bots.helpdesk.makerchecker.message; import com.fasterxml.jackson.core.JsonProcessingException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.symphonyoss.symphony.bots.utility.message.EntityBuilder; import org.symphonyoss.symphony.bots.utility.message.SymMessageBuilder; import org.symphonyoss.symphony.clients.model.SymMessage; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** * Created by rsanchez on 01/12/17. */ public class MakerCheckerMessageBuilder { private static final Logger LOGGER = LoggerFactory.getLogger(MakerCheckerMessageBuilder.class); private static final String BASE_EVENT = "com.symphony.bots.helpdesk.event.makerchecker"; private static final String VERSION = "1.0"; private static final String MAKER_CHECKER_MESSAGE_TEMPLATE = "makerCheckerMessage.xml"; private static String message; private final SymMessageBuilder messageBuilder; private String botHost; private String serviceHost; private Long makerId; private String streamId; private List<String> proxyToStreamIds = new ArrayList<>(); private Long timestamp; private String messageId; private String groupId; private String makerCheckerId; private String attachmentId; public MakerCheckerMessageBuilder() { if (StringUtils.isEmpty(message)) { message = parseTemplate(); } this.messageBuilder = SymMessageBuilder.message(message); } private String parseTemplate() { StringBuilder message = new StringBuilder(); InputStream resource = getClass().getClassLoader().getResourceAsStream(MAKER_CHECKER_MESSAGE_TEMPLATE); try (BufferedReader buffer = new BufferedReader(new InputStreamReader(resource))) { buffer.lines().forEach(message::append); } catch (IOException e) { LOGGER.error("Fail to parse maker checker message template"); } return message.toString(); } public MakerCheckerMessageBuilder botHost(String host) { this.botHost = host; return this; } public MakerCheckerMessageBuilder serviceHost(String host) { this.serviceHost = host; return this; } public MakerCheckerMessageBuilder makerId(Long makerId) { this.makerId = makerId; return this; } public MakerCheckerMessageBuilder streamId(String streamId) { this.streamId = streamId; return this; } public MakerCheckerMessageBuilder addProxyToStreamId(String streamId) { this.proxyToStreamIds.add(streamId); return this; } public MakerCheckerMessageBuilder timestamp(Long timestamp) { this.timestamp = timestamp; return this; } public MakerCheckerMessageBuilder messageId(String messageId) { this.messageId = messageId; return this; } public MakerCheckerMessageBuilder groupId(String groupId) { this.groupId = groupId; return this; } public MakerCheckerMessageBuilder makerCheckerId(String makerCheckerId) { this.makerCheckerId = makerCheckerId; return this; } public MakerCheckerMessageBuilder attachmentId(String attachmentId) { this.attachmentId = attachmentId; return this; } public SymMessage build() { if (messageBuilder == null) { return null; } try { EntityBuilder bodyBuilder = EntityBuilder.createEntity(BASE_EVENT, VERSION); String attachmentUrl = String.format("%s/v1/makerchecker/%s", serviceHost, makerCheckerId); bodyBuilder.addField("attachmentUrl", attachmentUrl); String approveUrl = String.format("%s/v1/makerchecker/%s/approve", botHost, makerCheckerId); bodyBuilder.addField("approveUrl", approveUrl); String denyUrl = String.format("%s/v1/makerchecker/%s/deny", botHost, makerCheckerId); bodyBuilder.addField("denyUrl", denyUrl); bodyBuilder.addField("makerCheckerId", makerCheckerId); bodyBuilder.addField("streamId", streamId); bodyBuilder.addField("makerId", makerId); EntityBuilder builder = EntityBuilder.createEntity(); builder.addField("makerchecker", bodyBuilder.toObject()); String entityData = builder.build(); return messageBuilder.entityData(entityData).build(); } catch (JsonProcessingException e) { LOGGER.error("Fail to create entity data"); return null; } } }
3e0df7071c841e9c0831b0b00ad3911d88951c04
1,201
java
Java
robozonky-api/src/test/java/com/github/robozonky/internal/util/json/AbstractDeserializerTest.java
LukeLaz/robozonky
84be394c815c95a7bd6b8c719c31df5b0d4513c9
[ "Apache-2.0" ]
null
null
null
robozonky-api/src/test/java/com/github/robozonky/internal/util/json/AbstractDeserializerTest.java
LukeLaz/robozonky
84be394c815c95a7bd6b8c719c31df5b0d4513c9
[ "Apache-2.0" ]
null
null
null
robozonky-api/src/test/java/com/github/robozonky/internal/util/json/AbstractDeserializerTest.java
LukeLaz/robozonky
84be394c815c95a7bd6b8c719c31df5b0d4513c9
[ "Apache-2.0" ]
null
null
null
29.292683
93
0.717735
5,916
/* * Copyright 2020 The RoboZonky Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.robozonky.internal.util.json; import static org.assertj.core.api.Assertions.*; import java.util.UUID; import javax.json.bind.Jsonb; import javax.json.bind.JsonbBuilder; import org.junit.jupiter.api.Test; import com.github.robozonky.api.remote.enums.Country; class AbstractDeserializerTest { @Test void defaultValue() throws Exception { try (Jsonb jsonb = JsonbBuilder.create()) { Country country = jsonb.fromJson("\"" + UUID.randomUUID() + "\"", Country.class); assertThat(country).isEqualTo(Country.UNKNOWN); } } }
3e0df775e79d8b3b0f99f1466cfa3ca35f1026f5
967
java
Java
main/java/com/example/farahnaz/myapplication/common/Helper/Model/Weather.java
internet-project/src
34d636e2462fcd992315e32b191bce1c024530c0
[ "MIT" ]
null
null
null
main/java/com/example/farahnaz/myapplication/common/Helper/Model/Weather.java
internet-project/src
34d636e2462fcd992315e32b191bce1c024530c0
[ "MIT" ]
null
null
null
main/java/com/example/farahnaz/myapplication/common/Helper/Model/Weather.java
internet-project/src
34d636e2462fcd992315e32b191bce1c024530c0
[ "MIT" ]
null
null
null
18.596154
70
0.598759
5,917
package com.example.farahnaz.myapplication.common.Helper.Model; /** * Created by Farahnaz on 22/06/2019. */ public class Weather { private int id; private String main; private String description; private String icon; public Weather(int id,String main,String description,String icon){ this.id=id; this.main=main; this.description=description; this.icon=icon; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getMain() { return main; } public void setMain(String main) { this.main = main; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } }
3e0df7e981ff83cc686e4b00d2e21a1fe96ca19d
342
java
Java
src/test/java/com/william/code/RestApp/RestAppApplicationTests.java
ChrisWongAtCUHK/restApp
804f5a5c9b19d17cac0a84b189ad25cc10841f6e
[ "MIT" ]
null
null
null
src/test/java/com/william/code/RestApp/RestAppApplicationTests.java
ChrisWongAtCUHK/restApp
804f5a5c9b19d17cac0a84b189ad25cc10841f6e
[ "MIT" ]
null
null
null
src/test/java/com/william/code/RestApp/RestAppApplicationTests.java
ChrisWongAtCUHK/restApp
804f5a5c9b19d17cac0a84b189ad25cc10841f6e
[ "MIT" ]
2
2018-07-24T10:23:32.000Z
2019-10-10T14:34:09.000Z
20.117647
60
0.809942
5,918
package com.william.code.RestApp; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class RestAppApplicationTests { @Test public void contextLoads() { } }
3e0df817464175456ee140763f0999a46c2b6a5e
2,469
java
Java
sources/b/j/a/c/s.java
tonioshikanlu/tubman-hack
8277e47c058174ca4411965ed67d05d2aba1c7fc
[ "MIT" ]
2
2021-03-20T07:33:30.000Z
2021-06-29T18:50:21.000Z
sources/b/j/a/c/s.java
tonioshikanlu/tubman-hack
8277e47c058174ca4411965ed67d05d2aba1c7fc
[ "MIT" ]
null
null
null
sources/b/j/a/c/s.java
tonioshikanlu/tubman-hack
8277e47c058174ca4411965ed67d05d2aba1c7fc
[ "MIT" ]
2
2021-03-20T15:56:20.000Z
2021-03-21T02:06:29.000Z
35.782609
186
0.626164
5,919
package b.j.a.c; import b.j.a.a.h0; import b.j.a.c.e0.h; import java.io.Serializable; public class s implements Serializable { /* renamed from: o reason: collision with root package name */ public static final s f2292o = new s(Boolean.TRUE, (String) null, (Integer) null, (String) null, (a) null, (h0) null, (h0) null); /* renamed from: p reason: collision with root package name */ public static final s f2293p = new s(Boolean.FALSE, (String) null, (Integer) null, (String) null, (a) null, (h0) null, (h0) null); /* renamed from: q reason: collision with root package name */ public static final s f2294q = new s((Boolean) null, (String) null, (Integer) null, (String) null, (a) null, (h0) null, (h0) null); /* renamed from: h reason: collision with root package name */ public final Boolean f2295h; /* renamed from: i reason: collision with root package name */ public final String f2296i; /* renamed from: j reason: collision with root package name */ public final Integer f2297j; /* renamed from: k reason: collision with root package name */ public final String f2298k; /* renamed from: l reason: collision with root package name */ public final transient a f2299l; /* renamed from: m reason: collision with root package name */ public h0 f2300m; /* renamed from: n reason: collision with root package name */ public h0 f2301n; public static final class a { public final h a; /* renamed from: b reason: collision with root package name */ public final boolean f2302b; public a(h hVar, boolean z) { this.a = hVar; this.f2302b = z; } } public s(Boolean bool, String str, Integer num, String str2, a aVar, h0 h0Var, h0 h0Var2) { this.f2295h = bool; this.f2296i = str; this.f2297j = num; this.f2298k = (str2 == null || str2.isEmpty()) ? null : str2; this.f2299l = aVar; this.f2300m = h0Var; this.f2301n = h0Var2; } public static s a(Boolean bool, String str, Integer num, String str2) { return (str == null && num == null && str2 == null) ? bool == null ? f2294q : bool.booleanValue() ? f2292o : f2293p : new s(bool, str, num, str2, (a) null, (h0) null, (h0) null); } public s b(a aVar) { return new s(this.f2295h, this.f2296i, this.f2297j, this.f2298k, aVar, this.f2300m, this.f2301n); } }
3e0df899d46a3f3574597fd387769c37e60ee30f
5,128
java
Java
projectMonitoringBE/src/main/java/com/pfe/projectMonitoringBE/services/ProjectService.java
kabilJbeli/PfeProjectMonitoring
0e87d3db318e659f6dc8b9363e5deaf4a6ec2fb0
[ "MIT" ]
null
null
null
projectMonitoringBE/src/main/java/com/pfe/projectMonitoringBE/services/ProjectService.java
kabilJbeli/PfeProjectMonitoring
0e87d3db318e659f6dc8b9363e5deaf4a6ec2fb0
[ "MIT" ]
null
null
null
projectMonitoringBE/src/main/java/com/pfe/projectMonitoringBE/services/ProjectService.java
kabilJbeli/PfeProjectMonitoring
0e87d3db318e659f6dc8b9363e5deaf4a6ec2fb0
[ "MIT" ]
null
null
null
38.556391
108
0.809672
5,920
package com.pfe.projectMonitoringBE.services; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.pfe.projectMonitoringBE.Enums.ProjectStatus; import com.pfe.projectMonitoringBE.entities.Member; import com.pfe.projectMonitoringBE.entities.Project; import com.pfe.projectMonitoringBE.interfaces.IProject; import com.pfe.projectMonitoringBE.models.ProjectStats; import com.pfe.projectMonitoringBE.repositories.ProjectRepository; @Service public class ProjectService implements IProject { @Autowired private ProjectRepository repository; @Override public void createOrUpdateProject(Project project) { repository.save(project); } @Override public Project findProject(int idProject) { return repository.findById(idProject).get(); } @Override public List<Project> getAllProject() { return repository.findAll(); } @Override public void deleteProject(Project project) { repository.delete(project); } @Override public List<Project> getManagerProjects(Member member) { return repository.findByProjectmanager(member); } @Override public List<Project> findByMember(String email) { return repository.findByMember(email); } @Override public List<Project> findByClient(String email) { return repository.findByClient(email); } @Override public List<Member> findProjectMembers(Integer id) { return repository.findProjectMembers(id); } @Override public List<ProjectStats> getProjectsStats() { List<ProjectStats> projectsta = new ArrayList<ProjectStats>(); projectsta.add( calculation(repository.findByProjectStatus(ProjectStatus.Created), ProjectStatus.Created.toString())); projectsta.add( calculation(repository.findByProjectStatus(ProjectStatus.Finished), ProjectStatus.Finished.toString())); projectsta.add(calculation(repository.findByProjectStatus(ProjectStatus.InMaintenance), ProjectStatus.InMaintenance.toString())); projectsta.add(calculation(repository.findByProjectStatus(ProjectStatus.InProgress), ProjectStatus.InProgress.toString())); projectsta.add( calculation(repository.findByProjectStatus(ProjectStatus.Released), ProjectStatus.Released.toString())); return projectsta; } @Override public List<ProjectStats> getNumberClientPerProject(Member client) { List<ProjectStats> projectsta = new ArrayList<ProjectStats>(); projectsta.add(calculation(repository.findProjectClientperstatut(ProjectStatus.Created, client), ProjectStatus.Created.toString())); projectsta.add(calculation(repository.findProjectClientperstatut(ProjectStatus.Finished, client), ProjectStatus.Finished.toString())); projectsta.add(calculation(repository.findProjectClientperstatut(ProjectStatus.InMaintenance, client), ProjectStatus.InMaintenance.toString())); projectsta.add(calculation(repository.findProjectClientperstatut(ProjectStatus.InProgress, client), ProjectStatus.InProgress.toString())); projectsta.add(calculation(repository.findProjectClientperstatut(ProjectStatus.Released, client), ProjectStatus.Released.toString())); return projectsta; } @Override public List<ProjectStats> getNumberEmployeePerProject(Member employee) { List<ProjectStats> projectsta = new ArrayList<ProjectStats>(); projectsta.add(calculation(repository.findProjectEmployeeperstatut(ProjectStatus.Created, employee), ProjectStatus.Created.toString())); projectsta.add(calculation(repository.findProjectEmployeeperstatut(ProjectStatus.Finished, employee), ProjectStatus.Finished.toString())); projectsta.add(calculation(repository.findProjectEmployeeperstatut(ProjectStatus.InMaintenance, employee), ProjectStatus.InMaintenance.toString())); projectsta.add(calculation(repository.findProjectEmployeeperstatut(ProjectStatus.InProgress, employee), ProjectStatus.InProgress.toString())); projectsta.add(calculation(repository.findProjectEmployeeperstatut(ProjectStatus.Released, employee), ProjectStatus.Released.toString())); return projectsta; } @Override public List<ProjectStats> getNumberManagerPerProject(Member employee) { List<ProjectStats> projectsta = new ArrayList<ProjectStats>(); projectsta.add(calculation(repository.findProjectManagerperstatut(ProjectStatus.Created, employee), ProjectStatus.Created.toString())); projectsta.add(calculation(repository.findProjectManagerperstatut(ProjectStatus.Finished, employee), ProjectStatus.Finished.toString())); projectsta.add(calculation(repository.findProjectManagerperstatut(ProjectStatus.InMaintenance, employee), ProjectStatus.InMaintenance.toString())); projectsta.add(calculation(repository.findProjectManagerperstatut(ProjectStatus.InProgress, employee), ProjectStatus.InProgress.toString())); projectsta.add(calculation(repository.findProjectManagerperstatut(ProjectStatus.Released, employee), ProjectStatus.Released.toString())); return projectsta; } public ProjectStats calculation(List<Project> projects, String statut) { return new ProjectStats(statut, projects.size()); } }
3e0df8bffc034a17648c988761e8a3d57b75e5d2
731
java
Java
src/main/java/de/muspellheim/commons/sql/DatabaseConfiguration.java
falkoschumann/java-muspellheim-commons
c9aee793fdd065fb2851e2c4db79be69bfa1109a
[ "MIT" ]
null
null
null
src/main/java/de/muspellheim/commons/sql/DatabaseConfiguration.java
falkoschumann/java-muspellheim-commons
c9aee793fdd065fb2851e2c4db79be69bfa1109a
[ "MIT" ]
9
2019-10-23T08:39:31.000Z
2020-01-07T20:15:32.000Z
src/main/java/de/muspellheim/commons/sql/DatabaseConfiguration.java
falkoschumann/java-muspellheim-commons
c9aee793fdd065fb2851e2c4db79be69bfa1109a
[ "MIT" ]
null
null
null
14.057692
53
0.618331
5,921
/* * Muspellheim Commons * Copyright (c) 2019 Falko Schumann */ package de.muspellheim.commons.sql; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.Value; /** Collect information for a database connection. */ @Value @RequiredArgsConstructor(staticName = "of") public class DatabaseConfiguration { /** * Host ip or hostname. * * @return the host */ String host; /** * Port. * * @return the port */ int port; /** * Username. * * @return the user */ @NonNull String user; /** * User password. * * @return the passwors */ String password; /** * Database name. * * @return the database */ @NonNull String database; }
3e0df9b52f2afa27e85d8f9f82de9692d17f7762
1,510
java
Java
starter/critter/src/main/java/com/udacity/jdnd/course3/critter/user/service/CustomerMapper.java
chrwolff/nd035-c3-data-stores-and-persistence-project-starter
ca2dfea7a8e4cba9c2e57d92effd05bc96fd0b12
[ "MIT" ]
null
null
null
starter/critter/src/main/java/com/udacity/jdnd/course3/critter/user/service/CustomerMapper.java
chrwolff/nd035-c3-data-stores-and-persistence-project-starter
ca2dfea7a8e4cba9c2e57d92effd05bc96fd0b12
[ "MIT" ]
null
null
null
starter/critter/src/main/java/com/udacity/jdnd/course3/critter/user/service/CustomerMapper.java
chrwolff/nd035-c3-data-stores-and-persistence-project-starter
ca2dfea7a8e4cba9c2e57d92effd05bc96fd0b12
[ "MIT" ]
null
null
null
31.458333
102
0.708609
5,922
package com.udacity.jdnd.course3.critter.user.service; import com.udacity.jdnd.course3.critter.EntityDTOMapper; import com.udacity.jdnd.course3.critter.pet.model.PetEntity; import com.udacity.jdnd.course3.critter.pet.service.PetService; import com.udacity.jdnd.course3.critter.user.controller.CustomerDTO; import com.udacity.jdnd.course3.critter.user.model.CustomerEntity; import org.springframework.stereotype.Service; import java.util.stream.Collectors; @Service public class CustomerMapper extends EntityDTOMapper<CustomerEntity, CustomerDTO> { private final PetService petService; public CustomerMapper(PetService petService) { this.petService = petService; } @Override public CustomerDTO convertEntityToDto(CustomerEntity customerEntity, CustomerDTO customerDTO) { super.convertEntityToDto(customerEntity, customerDTO); customerDTO.setPetIds( customerEntity.getPets() .stream() .map(PetEntity::getId) .collect(Collectors.toList()) ); return customerDTO; } @Override public CustomerEntity convertDtoToEntity(CustomerDTO customerDTO, CustomerEntity customerEntity) { super.convertDtoToEntity(customerDTO, customerEntity); if (customerDTO.getPetIds() != null) { customerDTO.getPetIds().stream() .map(this.petService::get) .forEach(customerEntity::addPet); } return customerEntity; } }
3e0df9d57da2a7ce0da29a5ef0f2b28ee57a329c
527
java
Java
oo4j-core/src/test/java/com/tyutyutyu/oo4j/core/template/FreemarkerApiTest.java
tyutyutyu/oo4j
e2dab9b24f5c05b99d7c66e5a62fb75449621915
[ "MIT" ]
null
null
null
oo4j-core/src/test/java/com/tyutyutyu/oo4j/core/template/FreemarkerApiTest.java
tyutyutyu/oo4j
e2dab9b24f5c05b99d7c66e5a62fb75449621915
[ "MIT" ]
89
2021-01-31T23:18:01.000Z
2022-03-31T17:51:36.000Z
oo4j-core/src/test/java/com/tyutyutyu/oo4j/core/template/FreemarkerApiTest.java
tyutyutyu/oo4j
e2dab9b24f5c05b99d7c66e5a62fb75449621915
[ "MIT" ]
1
2021-03-27T22:52:04.000Z
2021-03-27T22:52:04.000Z
20.269231
74
0.641366
5,923
package com.tyutyutyu.oo4j.core.template; import org.junit.jupiter.api.Test; import java.util.Map; import static org.assertj.core.api.Assertions.*; class FreemarkerApiTest { @Test void testGenerate() { // given String templateDir = "classpath:/test-templates/"; FreemarkerApi freemarkerApi = new FreemarkerApi(templateDir); // when String actual = freemarkerApi.generate("test1", Map.of("a", "b")); // then assertThat(actual).isEqualTo("a = b"); } }
3e0dfbd4a9db5f6819416c4ed4ef136cabf05d27
4,255
java
Java
familyhelper-assets-impl/src/main/java/com/dwarfeng/familyhelper/assets/impl/cache/ItemTypeIndicatorCacheImpl.java
DwArFeng/familyhelper-assets
fcd5b1cfcb18a5fa339f3b0e1b2ab0ef510239d8
[ "Apache-2.0" ]
null
null
null
familyhelper-assets-impl/src/main/java/com/dwarfeng/familyhelper/assets/impl/cache/ItemTypeIndicatorCacheImpl.java
DwArFeng/familyhelper-assets
fcd5b1cfcb18a5fa339f3b0e1b2ab0ef510239d8
[ "Apache-2.0" ]
null
null
null
familyhelper-assets-impl/src/main/java/com/dwarfeng/familyhelper/assets/impl/cache/ItemTypeIndicatorCacheImpl.java
DwArFeng/familyhelper-assets
fcd5b1cfcb18a5fa339f3b0e1b2ab0ef510239d8
[ "Apache-2.0" ]
null
null
null
42.55
118
0.780729
5,924
package com.dwarfeng.familyhelper.assets.impl.cache; import com.dwarfeng.familyhelper.assets.sdk.bean.entity.FastJsonItemTypeIndicator; import com.dwarfeng.familyhelper.assets.stack.bean.entity.ItemTypeIndicator; import com.dwarfeng.familyhelper.assets.stack.cache.ItemTypeIndicatorCache; import com.dwarfeng.subgrade.impl.cache.RedisBatchBaseCache; import com.dwarfeng.subgrade.sdk.interceptor.analyse.BehaviorAnalyse; import com.dwarfeng.subgrade.sdk.interceptor.analyse.SkipRecord; import com.dwarfeng.subgrade.stack.bean.key.StringIdKey; import com.dwarfeng.subgrade.stack.exception.CacheException; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Repository public class ItemTypeIndicatorCacheImpl implements ItemTypeIndicatorCache { private final RedisBatchBaseCache<StringIdKey, ItemTypeIndicator, FastJsonItemTypeIndicator> itemTypeIndicatorBatchBaseDelegate; public ItemTypeIndicatorCacheImpl( RedisBatchBaseCache<StringIdKey, ItemTypeIndicator, FastJsonItemTypeIndicator> itemTypeIndicatorBatchBaseDelegate ) { this.itemTypeIndicatorBatchBaseDelegate = itemTypeIndicatorBatchBaseDelegate; } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", readOnly = true, rollbackFor = Exception.class) public boolean exists(StringIdKey key) throws CacheException { return itemTypeIndicatorBatchBaseDelegate.exists(key); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", readOnly = true, rollbackFor = Exception.class) public ItemTypeIndicator get(StringIdKey key) throws CacheException { return itemTypeIndicatorBatchBaseDelegate.get(key); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public void push(ItemTypeIndicator value, long timeout) throws CacheException { itemTypeIndicatorBatchBaseDelegate.push(value, timeout); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public void delete(StringIdKey key) throws CacheException { itemTypeIndicatorBatchBaseDelegate.delete(key); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public void clear() throws CacheException { itemTypeIndicatorBatchBaseDelegate.clear(); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", readOnly = true, rollbackFor = Exception.class) public boolean allExists(@SkipRecord List<StringIdKey> keys) throws CacheException { return itemTypeIndicatorBatchBaseDelegate.allExists(keys); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", readOnly = true, rollbackFor = Exception.class) public boolean nonExists(@SkipRecord List<StringIdKey> keys) throws CacheException { return itemTypeIndicatorBatchBaseDelegate.nonExists(keys); } @Override @BehaviorAnalyse @SkipRecord @Transactional(transactionManager = "hibernateTransactionManager", readOnly = true, rollbackFor = Exception.class) public List<ItemTypeIndicator> batchGet(@SkipRecord List<StringIdKey> keys) throws CacheException { return itemTypeIndicatorBatchBaseDelegate.batchGet(keys); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public void batchPush(@SkipRecord List<ItemTypeIndicator> entities, long timeout) throws CacheException { itemTypeIndicatorBatchBaseDelegate.batchPush(entities, timeout); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public void batchDelete(@SkipRecord List<StringIdKey> keys) throws CacheException { itemTypeIndicatorBatchBaseDelegate.batchDelete(keys); } }
3e0dfd54a520288f2afdf41c1c8ddb412520f267
4,966
java
Java
bundles/user/impl/src/main/java/org/sakaiproject/nakamura/user/search/JoinRequestIndexingHandler.java
jfederico/nakamura
2001c7cddc7d0ab53a2d09b5b6a0b4db38ac33f1
[ "Apache-2.0" ]
1
2016-12-11T12:03:13.000Z
2016-12-11T12:03:13.000Z
bundles/user/impl/src/main/java/org/sakaiproject/nakamura/user/search/JoinRequestIndexingHandler.java
jfederico/nakamura
2001c7cddc7d0ab53a2d09b5b6a0b4db38ac33f1
[ "Apache-2.0" ]
null
null
null
bundles/user/impl/src/main/java/org/sakaiproject/nakamura/user/search/JoinRequestIndexingHandler.java
jfederico/nakamura
2001c7cddc7d0ab53a2d09b5b6a0b4db38ac33f1
[ "Apache-2.0" ]
null
null
null
37.059701
131
0.740234
5,925
/** * Licensed to the Sakai Foundation (SF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The SF 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.sakaiproject.nakamura.user.search; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.commons.lang.StringUtils; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Reference; import org.apache.solr.client.solrj.util.ClientUtils; import org.apache.solr.common.SolrInputDocument; import org.osgi.service.event.Event; import org.sakaiproject.nakamura.api.lite.Session; import org.sakaiproject.nakamura.api.lite.StorageClientException; import org.sakaiproject.nakamura.api.lite.accesscontrol.AccessDeniedException; import org.sakaiproject.nakamura.api.lite.authorizable.User; import org.sakaiproject.nakamura.api.lite.content.Content; import org.sakaiproject.nakamura.api.lite.content.ContentManager; import org.sakaiproject.nakamura.api.solr.IndexingHandler; import org.sakaiproject.nakamura.api.solr.RepositorySession; import org.sakaiproject.nakamura.api.solr.ResourceIndexingService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; /** * */ @Component(immediate = true) public class JoinRequestIndexingHandler implements IndexingHandler { private static final Logger logger = LoggerFactory .getLogger(JoinRequestIndexingHandler.class); @Reference(target = "(type=sparse)") private ResourceIndexingService resourceIndexingService; private static final Set<String> CONTENT_TYPES = Sets.newHashSet("sakai/joinrequest"); @Activate public void activate(Map<String, Object> properties) throws Exception { for (String type : CONTENT_TYPES) { resourceIndexingService.addHandler(type, this); } } @Deactivate public void deactivate(Map<String, Object> properties) { for (String type : CONTENT_TYPES) { resourceIndexingService.removeHandler(type, this); } } /** * {@inheritDoc} * * @see org.sakaiproject.nakamura.api.solr.IndexingHandler#getDocuments(org.sakaiproject.nakamura.api.solr.RepositorySession, * org.osgi.service.event.Event) */ public Collection<SolrInputDocument> getDocuments(RepositorySession repositorySession, Event event) { String path = (String) event.getProperty(FIELD_PATH); List<SolrInputDocument> documents = Lists.newArrayList(); if (!StringUtils.isBlank(path)) { try { Session session = repositorySession.adaptTo(Session.class); ContentManager cm = session.getContentManager(); Content content = cm.get(path); if (content != null) { if (!CONTENT_TYPES.contains(content.getProperty("sling:resourceType"))) { return documents; } SolrInputDocument doc = new SolrInputDocument(); doc.addField(User.NAME_FIELD, content.getProperty(User.NAME_FIELD)); doc.addField(Content.CREATED_FIELD, content.getProperty(Content.CREATED_FIELD)); doc.addField(_DOC_SOURCE_OBJECT, content); documents.add(doc); } } catch (StorageClientException e) { logger.warn(e.getMessage(), e); } catch (AccessDeniedException e) { logger.warn(e.getMessage(), e); } } logger.debug("Got documents {} ", documents); return documents; } /** * {@inheritDoc} * * @see org.sakaiproject.nakamura.api.solr.IndexingHandler#getDeleteQueries(org.sakaiproject.nakamura.api.solr.RepositorySession, * org.osgi.service.event.Event) */ public Collection<String> getDeleteQueries(RepositorySession repositorySession, Event event) { List<String> retval = Collections.emptyList(); logger.debug("GetDelete for {} ", event); String path = (String) event.getProperty(FIELD_PATH); String resourceType = (String) event.getProperty("resourceType"); if (CONTENT_TYPES.contains(resourceType)) { retval = ImmutableList.of("id:" + ClientUtils.escapeQueryChars(path)); } return retval; } }
3e0dfda3119cc88347fdeac53f1107763b93184f
330
java
Java
src/main/java/dev/gutoleao/tutorial/sampleapi/SampleApiApplication.java
gut0leao/fully-dockerized-development-enviroment-with-spring-boot-and-vscode
8a7b5bb54b7f697a84fbd0d4135d9e6e4a8f0fe8
[ "MIT" ]
1
2021-07-01T10:00:07.000Z
2021-07-01T10:00:07.000Z
src/main/java/dev/gutoleao/tutorial/sampleapi/SampleApiApplication.java
gut0leao/fully-dockerized-development-enviroment-with-spring-boot-and-vscode
8a7b5bb54b7f697a84fbd0d4135d9e6e4a8f0fe8
[ "MIT" ]
null
null
null
src/main/java/dev/gutoleao/tutorial/sampleapi/SampleApiApplication.java
gut0leao/fully-dockerized-development-enviroment-with-spring-boot-and-vscode
8a7b5bb54b7f697a84fbd0d4135d9e6e4a8f0fe8
[ "MIT" ]
null
null
null
23.571429
68
0.827273
5,926
package dev.gutoleao.tutorial.sampleapi; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SampleApiApplication { public static void main(String[] args) { SpringApplication.run(SampleApiApplication.class, args); } }
3e0dfe5161d5733874baf16e9d3c92b4bcc4aa31
3,755
java
Java
core/src/main/java/com/adobe/people/ararat/datalayer/core/services/CustomPageNameProvider.java
araraty/aem-63-datalayer
bca55d927b915d72a03d3f397077bea75801e064
[ "Apache-2.0" ]
null
null
null
core/src/main/java/com/adobe/people/ararat/datalayer/core/services/CustomPageNameProvider.java
araraty/aem-63-datalayer
bca55d927b915d72a03d3f397077bea75801e064
[ "Apache-2.0" ]
1
2018-08-08T21:51:36.000Z
2018-08-08T21:51:36.000Z
core/src/main/java/com/adobe/people/ararat/datalayer/core/services/CustomPageNameProvider.java
araraty/aem-63-datalayer
bca55d927b915d72a03d3f397077bea75801e064
[ "Apache-2.0" ]
null
null
null
37.55
130
0.701465
5,927
package com.adobe.people.ararat.datalayer.core.services; import com.day.cq.analytics.sitecatalyst.AnalyticsPageNameContext; import com.day.cq.analytics.sitecatalyst.AnalyticsPageNameProvider; import com.day.cq.analytics.sitecatalyst.Framework; import com.day.cq.wcm.api.Page; import com.adobe.people.ararat.datalayer.core.utils.PageUtils; import org.apache.commons.lang.StringUtils; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.osgi.framework.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.day.cq.analytics.sitecatalyst.AnalyticsPageNameContext.S_PAGE_NAME; import static com.adobe.people.ararat.datalayer.core.utils.CONSTANTS.SITE_NAME; /** * Default implementation of {@link AnalyticsPageNameProvider} that resolves * page title, path or navTitle if mapped in {@link Framework}. */ @Service @Component(metatype = false) @Properties({ @Property(name = Constants.SERVICE_DESCRIPTION, value = "Custom Page Name Resolver implementation"), @Property(name = Constants.SERVICE_RANKING, intValue = 200, propertyPrivate = false) }) public class CustomPageNameProvider implements AnalyticsPageNameProvider { private static final Logger log = LoggerFactory.getLogger(CustomPageNameProvider.class); @Override public String getPageName(AnalyticsPageNameContext context) { String pageName = null; Framework framework = context.getFramework(); Resource resource = context.getResource(); Page page = null; if (resource != null && framework != null && framework.mapsSCVariable(S_PAGE_NAME)) { String cqVar = framework.getMapping(S_PAGE_NAME); page = resource.adaptTo(Page.class); log.info("CustomPageNameProvider:Starting Function getPageName for pageName {}", page.getName()); PageUtils pageUtils = new PageUtils(); if (page != null && cqVar.equals("pagedata.analyticsPageName")){ pageName= pageUtils.pageAnalyticsPathFromPage(page); } log.info("CustomPageNameProvider:getPageName found a pageName {}",pageName); } if(pageName !=null && pageName.contains("content:")) { pageName.replace("content:", ""); } else { log.info("CustomPageNameProvider:pageName is not analytics Enabled. will calculate based on path {}", page.getName()); if(page==null){ page = resource.adaptTo(Page.class); } pageName = page.getPath().substring(1).replace('/',':'); pageName = pageName.replace("content:", ""); } return SITE_NAME + pageName; } @Override public Resource getResource(AnalyticsPageNameContext context) { String pageName = context.getPageName(); log.info("CustomPageNameProvider:Starting Function getResource for pageName {}", pageName); ResourceResolver rr = context.getResourceResolver(); if ( ! pageName.startsWith("content")) { pageName = "content:" + pageName; } pageName = "/" + StringUtils.replace(pageName, ":", "/"); log.info("CustomPageNameProvider:getResource Search for page {}", pageName); Resource resource = rr.resolve(pageName); if ( resource.adaptTo(Page.class) != null) { log.info("CustomPageNameProvider:getResource Page found"); return resource; } else { log.info("CustomPageNameProvider:getResource Page not found"); } return null; } }