hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
93bb745fe8abac2674d1d70da72bff1c0c2ff30a
1,793
/* * Copyright 2022-present the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.gradle.maven; import java.io.File; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.publish.PublishingExtension; import org.gradle.api.publish.maven.plugins.MavenPublishPlugin; /** * Gradle Plugin used to publish all {@link Project} artifacts locally * under {@literal rootProject/buildDir/publications/repos}. * * This is useful for inspecting the generated {@link Project} artifacts to ensure they are correct * before publishing the {@link Project} artifacts to Artifactory or Maven Central. * * @author Rob Winch * @author John Blum * @see org.gradle.api.Plugin * @see org.gradle.api.Project * @since 2.0.0 */ public class PublishLocalPlugin implements Plugin<Project> { @Override public void apply(Project project) { project.getPlugins().withType(MavenPublishPlugin.class).all(mavenPublish -> { PublishingExtension publishing = project.getExtensions().getByType(PublishingExtension.class); publishing.getRepositories().maven(maven -> { maven.setName("local"); maven.setUrl(new File(project.getRootProject().getBuildDir(), "publications/repos")); }); }); } }
33.203704
99
0.749024
8a7c5ff11cf095e785846ec178629ace6a087ff8
139
package net.runelite.client.plugins.socket.packet; import lombok.AllArgsConstructor; @AllArgsConstructor public class SocketShutdown { }
15.444444
50
0.834532
57c2f517066cf86feec1d3261c47d0d8b42b9955
2,492
package com.linkedin.thirdeye.client; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.linkedin.thirdeye.api.DimensionKey; import com.linkedin.thirdeye.api.MetricSchema; import com.linkedin.thirdeye.api.MetricTimeSeries; import com.linkedin.thirdeye.api.MetricType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ThirdEyeRawResponse { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final TypeReference<List<String>> LIST_TYPE_REF = new TypeReference<List<String>>(){}; private List<String> metrics; private List<String> dimensions; private Map<String, Map<String, Number[]>> data; public ThirdEyeRawResponse() {} public List<String> getMetrics() { return metrics; } public void setMetrics(List<String> metrics) { this.metrics = metrics; } public List<String> getDimensions() { return dimensions; } public void setDimensions(List<String> dimensions) { this.dimensions = dimensions; } public Map<String, Map<String, Number[]>> getData() { return data; } public void setData(Map<String, Map<String, Number[]>> data) { this.data = data; } public Map<DimensionKey, MetricTimeSeries> convert(List<MetricType> metricTypes) throws Exception { MetricSchema metricSchema = new MetricSchema(metrics, metricTypes); // Convert raw data Map<DimensionKey, MetricTimeSeries> converted = new HashMap<>(); for (Map.Entry<String, Map<String, Number[]>> entry : data.entrySet()) { // Dimension String dimensionString = entry.getKey(); List<String> dimensionValues = OBJECT_MAPPER.readValue(dimensionString, LIST_TYPE_REF); String[] valueArray = new String[dimensionValues.size()]; dimensionValues.toArray(valueArray); DimensionKey dimensionKey = new DimensionKey(valueArray); // Metrics / time MetricTimeSeries timeSeries = new MetricTimeSeries(metricSchema); for (Map.Entry<String, Number[]> point : entry.getValue().entrySet()) { Long time = Long.valueOf(point.getKey()); for (int i = 0; i < metrics.size(); i++) { String metricName = metrics.get(i); Number metricValue = point.getValue()[i]; timeSeries.increment(time, metricName, metricValue); } } converted.put(dimensionKey, timeSeries); } return converted; } }
31.544304
103
0.709069
717fc061a05029779da6b4b8ae750f9f8207dd5d
450
package me.retrodaredevil.solarthing.actions.environment; import me.retrodaredevil.solarthing.actions.PacketGroupProvider; public class LatestPacketGroupEnvironment { private final PacketGroupProvider packetGroupProvider; public LatestPacketGroupEnvironment(PacketGroupProvider packetGroupProvider) { this.packetGroupProvider = packetGroupProvider; } public PacketGroupProvider getPacketGroupProvider() { return packetGroupProvider; } }
28.125
79
0.853333
1e3c42c79f4c390181fb6f510b66ccb49b68be62
3,377
/* * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig 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 the following location: * * 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.jasig.cas.support.oauth.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.constraints.NotNull; import org.apache.commons.lang.StringUtils; import org.jasig.cas.services.ServicesManager; import org.jasig.cas.ticket.registry.TicketRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; /** * This controller is the base controller for wrapping OAuth protocol in CAS. * It finds the right sub controller to call according to the url. * * @author Jerome Leleu * @since 3.5.0 */ public abstract class BaseOAuthWrapperController extends AbstractController { protected final Logger logger = LoggerFactory.getLogger(BaseOAuthWrapperController.class); @NotNull protected String loginUrl; @NotNull protected ServicesManager servicesManager; @NotNull protected TicketRegistry ticketRegistry; @NotNull protected long timeout; @Override protected ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final String method = getMethod(request); logger.debug("method : {}", method); return internalHandleRequest(method, request, response); } protected abstract ModelAndView internalHandleRequest(String method, HttpServletRequest request, HttpServletResponse response) throws Exception; /** * Return the method to call according to the url. * * @param request the incoming http request * @return the method to call according to the url */ private String getMethod(final HttpServletRequest request) { String method = request.getRequestURI(); if (method.indexOf("?") >= 0) { method = StringUtils.substringBefore(method, "?"); } final int pos = method.lastIndexOf("/"); if (pos >= 0) { method = method.substring(pos + 1); } return method; } public void setServicesManager(final ServicesManager servicesManager) { this.servicesManager = servicesManager; } public void setTicketRegistry(final TicketRegistry ticketRegistry) { this.ticketRegistry = ticketRegistry; } public void setLoginUrl(final String loginUrl) { this.loginUrl = loginUrl; } public void setTimeout(final long timeout) { this.timeout = timeout; } }
33.107843
118
0.722535
73a8cc3ba96410e82822f31c3483796e3db40b4e
6,834
/* * Copyright 2020 Yelp Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yelp.nrtsearch.server.luceneserver.field; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.google.type.LatLng; import com.yelp.nrtsearch.server.grpc.*; import com.yelp.nrtsearch.server.grpc.AddDocumentRequest.MultiValuedField; import com.yelp.nrtsearch.server.grpc.SearchResponse.Hit; import com.yelp.nrtsearch.server.luceneserver.ServerTestCase; import io.grpc.StatusRuntimeException; import io.grpc.testing.GrpcCleanupRule; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.ClassRule; import org.junit.Test; public class LatLonFieldDefTest extends ServerTestCase { @ClassRule public static final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); protected List<String> getIndices() { return Collections.singletonList(DEFAULT_TEST_INDEX); } protected FieldDefRequest getIndexDef(String name) throws IOException { return getFieldsFromResourceFile("/field/registerFieldsLatLon.json"); } protected void initIndex(String name) throws Exception { List<AddDocumentRequest> docs = new ArrayList<>(); // Business in Fremont AddDocumentRequest fremontDocRequest = AddDocumentRequest.newBuilder() .setIndexName(name) .putFields("doc_id", MultiValuedField.newBuilder().addValue("1").build()) .putFields( "lat_lon_multi", MultiValuedField.newBuilder() .addValue("37.476220") .addValue("-121.904404") .addValue("37.506900") .addValue("-121.933121") .build()) .build(); // Business in SF AddDocumentRequest sfDocRequest = AddDocumentRequest.newBuilder() .setIndexName(name) .putFields("doc_id", MultiValuedField.newBuilder().addValue("2").build()) .putFields( "lat_lon_multi", MultiValuedField.newBuilder().addValue("37.781158").addValue("-122.414011").build()) .build(); docs.add(fremontDocRequest); docs.add(sfDocRequest); addDocuments(docs.stream()); } @Test public void testGeoBoxQuery() { GeoBoundingBoxQuery fremontGeoBoundingBoxQuery = GeoBoundingBoxQuery.newBuilder() .setField("lat_lon_multi") .setTopLeft( LatLng.newBuilder().setLatitude(37.589207).setLongitude(-122.019474).build()) .setBottomRight( LatLng.newBuilder().setLatitude(37.419254).setLongitude(-121.836704).build()) .build(); geoBoundingBoxQueryAndVerifyIds(fremontGeoBoundingBoxQuery, "1"); GeoBoundingBoxQuery sfGeoBoundingBoxQuery = GeoBoundingBoxQuery.newBuilder() .setField("lat_lon_multi") .setTopLeft( LatLng.newBuilder().setLatitude(37.793321).setLongitude(-122.430808).build()) .setBottomRight( LatLng.newBuilder().setLatitude(37.759250).setLongitude(-122.383569).build()) .build(); geoBoundingBoxQueryAndVerifyIds(sfGeoBoundingBoxQuery, "2"); // No results in Mountain View GeoBoundingBoxQuery mountainViewGeoBoxQuery = GeoBoundingBoxQuery.newBuilder() .setField("lat_lon_multi") .setTopLeft( LatLng.newBuilder().setLatitude(37.409778).setLongitude(-122.116884).build()) .setBottomRight( LatLng.newBuilder().setLatitude(37.346484).setLongitude(-121.984961).build()) .build(); geoBoundingBoxQueryAndVerifyIds(mountainViewGeoBoxQuery); } @Test(expected = StatusRuntimeException.class) public void testGeoBoxQueryNotSearchable() { GeoBoundingBoxQuery fremontGeoBoundingBoxQuery = GeoBoundingBoxQuery.newBuilder() .setField("lat_lon_not_searchable") .setTopLeft( LatLng.newBuilder().setLatitude(37.589207).setLongitude(-122.019474).build()) .setBottomRight( LatLng.newBuilder().setLatitude(37.419254).setLongitude(-121.836704).build()) .build(); geoBoundingBoxQueryAndVerifyIds(fremontGeoBoundingBoxQuery); } @Test public void testGeoRadiusQuery() { GeoRadiusQuery sfGeoRadiusQuery = GeoRadiusQuery.newBuilder() .setField("lat_lon_multi") .setRadius("5 mi") .setCenter( LatLng.newBuilder().setLatitude(37.7789847).setLongitude(-122.4166709).build()) .build(); geoRadiusQueryAndVerifyIds(sfGeoRadiusQuery, "2"); GeoRadiusQuery fremontGeoRadiusQuery = GeoRadiusQuery.newBuilder() .setField("lat_lon_multi") .setRadius("5 mi") .setCenter( LatLng.newBuilder().setLatitude(37.4766153).setLongitude(-121.9124278).build()) .build(); geoRadiusQueryAndVerifyIds(fremontGeoRadiusQuery, "1"); } private void geoBoundingBoxQueryAndVerifyIds( GeoBoundingBoxQuery geoBoundingBoxQuery, String... expectedIds) { Query query = Query.newBuilder().setGeoBoundingBoxQuery(geoBoundingBoxQuery).build(); queryAndVerifyIds(query, expectedIds); } private void geoRadiusQueryAndVerifyIds(GeoRadiusQuery geoRadiusQuery, String... expectedIds) { Query query = Query.newBuilder().setGeoRadiusQuery(geoRadiusQuery).build(); queryAndVerifyIds(query, expectedIds); } private void queryAndVerifyIds(Query query, String... expectedIds) { SearchResponse response = getGrpcServer() .getBlockingStub() .search( SearchRequest.newBuilder() .setIndexName(DEFAULT_TEST_INDEX) .setStartHit(0) .setTopHits(10) .setQuery(query) .addRetrieveFields("doc_id") .build()); List<String> idList = Arrays.asList(expectedIds); assertEquals(idList.size(), response.getHitsCount()); for (Hit hit : response.getHitsList()) { assertTrue(idList.contains(hit.getFieldsOrThrow("doc_id").getFieldValue(0).getTextValue())); } } }
38.829545
100
0.666959
1369fb3e9766c6b88a9ca011bd6ef7be5490f941
151
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_2716 { }
18.875
52
0.827815
98ea2805d879f86ddf32e29019faee88309923b2
63,827
/* * This file was automatically generated by EvoSuite * Sun Nov 29 16:50:13 GMT 2020 */ package com.ib.client; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.runtime.EvoAssertions.*; import com.ib.client.Contract; import com.ib.client.ContractDetails; import com.ib.client.EWrapperMsgGenerator; import com.ib.client.Execution; import com.ib.client.Order; import com.ib.client.OrderState; import com.ib.client.TagValue; import com.ib.client.UnderComp; import java.util.LinkedList; import java.util.Vector; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true) public class EWrapperMsgGenerator_ESTest extends EWrapperMsgGenerator_ESTest_scaffolding { /** //Test case number: 0 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test000() throws Throwable { LinkedList<Integer> linkedList0 = new LinkedList<Integer>(); Vector<Object> vector0 = new Vector<Object>(linkedList0); Contract contract0 = new Contract(857, "0zi=bt&", "iG_f5BwC", "close", 857, (String) null, "UlLtt`O>", (String) null, "#yde-uOKz,t@';V^+", "WZ6sD.]YH1Z", vector0, "close", false, "'6?{!Q?4'0\fm]", "category = "); String string0 = EWrapperMsgGenerator.updatePortfolio(contract0, 0, 1730.8989, 0.0, 1566.5535485006171, 1.7976931348623157E308, 2128.39155014, "WZ6sD.]YH1Z"); assertEquals("updatePortfolio: conid = 857\nsymbol = 0zi=bt&\nsecType = iG_f5BwC\nexpiry = close\nstrike = 857.0\nright = null\nmultiplier = UlLtt`O>\nexchange = null\nprimaryExch = close\ncurrency = #yde-uOKz,t@';V^+\nlocalSymbol = WZ6sD.]YH1Z\n0 1730.8989 0.0 1566.5535485006171 1.7976931348623157E308 2128.39155014 WZ6sD.]YH1Z", string0); } /** //Test case number: 1 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test001() throws Throwable { Contract contract0 = new Contract((-3484), "$^MMGL", "id=739 bidOptComp=2146543035", "id=739 bidOptComp=2146543035", 1077.5214528, "fm[nh$we|V^XC`%", "91", "?tW`%=f'$F:nol8", " =============== end ===============", (String) null, (Vector) null, "id=13 unknown: basisPoints = 520.0/jJ[ impliedFuture = 2.146543035E9 holdDays = -1192 futureExpiry = $^MMGL dividendImpact = -1.0 dividends to expiry = -1192.0", false, "", "id=739 bidOptComp=2146543035"); String string0 = EWrapperMsgGenerator.updatePortfolio(contract0, (-3484), (-961.9412213501594), (-3484), (-1073741824), 0.0, (-961.9412213501594), "id=520 unknown=-1.0 canAutoExecute"); assertEquals("updatePortfolio: conid = -3484\nsymbol = $^MMGL\nsecType = id=739 bidOptComp=2146543035\nexpiry = id=739 bidOptComp=2146543035\nstrike = 1077.5214528\nright = fm[nh$we|V^XC`%\nmultiplier = 91\nexchange = ?tW`%=f'$F:nol8\nprimaryExch = id=13 unknown: basisPoints = 520.0/jJ[ impliedFuture = 2.146543035E9 holdDays = -1192 futureExpiry = $^MMGL dividendImpact = -1.0 dividends to expiry = -1192.0\ncurrency = =============== end ===============\nlocalSymbol = null\n-3484 -961.9412213501594 -3484.0 -1.073741824E9 0.0 -961.9412213501594 id=520 unknown=-1.0 canAutoExecute", string0); } /** //Test case number: 2 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test002() throws Throwable { ContractDetails contractDetails0 = new ContractDetails(); String string0 = EWrapperMsgGenerator.updatePortfolio(contractDetails0.m_summary, 0, (-310.0), 1.0, 1.7976931348623157E308, (-1.0), (-1236.27044425038), (String) null); assertEquals("updatePortfolio: conid = 0\nsymbol = null\nsecType = null\nexpiry = null\nstrike = 0.0\nright = null\nmultiplier = null\nexchange = null\nprimaryExch = null\ncurrency = null\nlocalSymbol = null\n0 -310.0 1.0 1.7976931348623157E308 -1.0 -1236.27044425038 null", string0); assertNotNull(string0); } /** //Test case number: 3 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test003() throws Throwable { Contract contract0 = new Contract(); String string0 = EWrapperMsgGenerator.updatePortfolio(contract0, 3, 1, (-2020.669423446566), 599.506212547139, 538.7801382408505, (-1786.7363), (String) null); assertEquals("updatePortfolio: conid = 0\nsymbol = null\nsecType = null\nexpiry = null\nstrike = 0.0\nright = null\nmultiplier = null\nexchange = null\nprimaryExch = null\ncurrency = null\nlocalSymbol = null\n3 1.0 -2020.669423446566 599.506212547139 538.7801382408505 -1786.7363 null", string0); assertNotNull(string0); } /** //Test case number: 4 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test004() throws Throwable { Vector<TagValue> vector0 = new Vector<TagValue>(); Contract contract0 = new Contract(0, "D)vXO4*Z1", "updateAccountValue: id=13 modelOptComp=-1.0 id=13 modelOptComp=-1.0 id=13 modelOptComp: vol = 1950.0 delta = N/A: modelPrice = N/A: pvDividend = 1773.6066743 id = 13 =============== end ===============", " It does not support Scale orders.", (-595.178393), "id=13 modelOptComp: vol = 1950.0 delta = N/A: modelPrice = N/A: pvDividend = 1773.6066743", "id=13 modelOptComp=-1.0", "jQ6~uDl", "updateAccountValue: id=13 modelOptComp=-1.0 id=13 modelOptComp=-1.0 id=13 modelOptComp: vol = 1950.0 delta = N/A: modelPrice = N/A: pvDividend = 1773.6066743 id = 13 =============== end ===============", "cN\"np.NYjK", vector0, "%", false, "j3p3Skkzf", "tH2Acx.0WhpR=I)lk<"); String string0 = EWrapperMsgGenerator.updatePortfolio(contract0, (-2147021759), 1012.40611, (-1.0), 0, (-441.15073536), (-1.0), "id=13 modelOptComp=-1.0"); assertEquals("updatePortfolio: conid = 0\nsymbol = D)vXO4*Z1\nsecType = updateAccountValue: id=13 modelOptComp=-1.0 id=13 modelOptComp=-1.0 id=13 modelOptComp: vol = 1950.0 delta = N/A: modelPrice = N/A: pvDividend = 1773.6066743 id = 13 =============== end ===============\nexpiry = It does not support Scale orders.\nstrike = -595.178393\nright = id=13 modelOptComp: vol = 1950.0 delta = N/A: modelPrice = N/A: pvDividend = 1773.6066743\nmultiplier = id=13 modelOptComp=-1.0\nexchange = jQ6~uDl\nprimaryExch = %\ncurrency = updateAccountValue: id=13 modelOptComp=-1.0 id=13 modelOptComp=-1.0 id=13 modelOptComp: vol = 1950.0 delta = N/A: modelPrice = N/A: pvDividend = 1773.6066743 id = 13 =============== end ===============\nlocalSymbol = cN\"np.NYjK\n-2147021759 1012.40611 -1.0 0.0 -441.15073536 -1.0 id=13 modelOptComp=-1.0", string0); } /** //Test case number: 5 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test005() throws Throwable { String string0 = EWrapperMsgGenerator.updateNewsBulletin((-358), 2515, "", ""); assertEquals("MsgId=-358 :: MsgType=2515 :: Origin= :: Message=", string0); } /** //Test case number: 6 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test006() throws Throwable { String string0 = EWrapperMsgGenerator.updateNewsBulletin(13, 0, (String) null, "l@q(Sf6(z5Gf"); assertEquals("MsgId=13 :: MsgType=0 :: Origin=l@q(Sf6(z5Gf :: Message=null", string0); } /** //Test case number: 7 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test007() throws Throwable { String string0 = EWrapperMsgGenerator.updateNewsBulletin(0, 1, (String) null, (String) null); assertEquals("MsgId=0 :: MsgType=1 :: Origin=null :: Message=null", string0); } /** //Test case number: 8 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test008() throws Throwable { String string0 = EWrapperMsgGenerator.updateNewsBulletin((-598), (-598), "^[", "^["); assertEquals("MsgId=-598 :: MsgType=-598 :: Origin=^[ :: Message=^[", string0); } /** //Test case number: 9 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test009() throws Throwable { String string0 = EWrapperMsgGenerator.updateMktDepthL2((-598), 13, "{?hAFx'U@S8", (-1), (-598), 2928.4623, (-2079)); assertEquals("updateMktDepth: -598 13 {?hAFx'U@S8 -1 -598 2928.4623 -2079", string0); } /** //Test case number: 10 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test010() throws Throwable { String string0 = EWrapperMsgGenerator.updateMktDepthL2(2451, (-1499), "mKI", (-3121), 816, 0, (-2017)); assertEquals("updateMktDepth: 2451 -1499 mKI -3121 816 0.0 -2017", string0); } /** //Test case number: 11 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test011() throws Throwable { String string0 = EWrapperMsgGenerator.updateMktDepthL2(880, 98, "%3GJ", 3, 475, 0, 167); assertEquals("updateMktDepth: 880 98 %3GJ 3 475 0.0 167", string0); } /** //Test case number: 12 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test012() throws Throwable { String string0 = EWrapperMsgGenerator.updateMktDepthL2(0, 0, "!)C6m1z?J7<aA{6$", 0, 0, (-740), 0); assertEquals("updateMktDepth: 0 0 !)C6m1z?J7<aA{6$ 0 0 -740.0 0", string0); } /** //Test case number: 13 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test013() throws Throwable { String string0 = EWrapperMsgGenerator.updateMktDepth(3896, 0, 0, 3896, (-2184), (-1)); assertEquals("updateMktDepth: 3896 0 0 3896 -2184.0 -1", string0); } /** //Test case number: 14 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test014() throws Throwable { String string0 = EWrapperMsgGenerator.updateMktDepth(10, 0, 39, 39, 39, 0); assertEquals("updateMktDepth: 10 0 39 39 39.0 0", string0); } /** //Test case number: 15 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test015() throws Throwable { String string0 = EWrapperMsgGenerator.updateMktDepth(10, (-2130214345), (-83), (-2130214345), (-3241.6501996), 739); assertEquals("updateMktDepth: 10 -2130214345 -83 -2130214345 -3241.6501996 739", string0); } /** //Test case number: 16 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test016() throws Throwable { String string0 = EWrapperMsgGenerator.updateMktDepth(0, 13, (-2184), 13, 0.0, (-1849)); assertEquals("updateMktDepth: 0 13 -2184 13 0.0 -1849", string0); } /** //Test case number: 17 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test017() throws Throwable { String string0 = EWrapperMsgGenerator.updateMktDepth((-2822), 1807, (-968), 1590, 1590, 1375); assertEquals("updateMktDepth: -2822 1807 -968 1590 1590.0 1375", string0); } /** //Test case number: 18 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test018() throws Throwable { String string0 = EWrapperMsgGenerator.updateAccountValue("NC~^[k*Q5PfVa", (String) null, "26WeekLow", (String) null); assertEquals("updateAccountValue: NC~^[k*Q5PfVa null 26WeekLow null", string0); } /** //Test case number: 19 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test019() throws Throwable { String string0 = EWrapperMsgGenerator.updateAccountValue("?QFR)f*Z:lr/EnP(0xd", (String) null, (String) null, ""); assertEquals("updateAccountValue: ?QFR)f*Z:lr/EnP(0xd null null ", string0); } /** //Test case number: 20 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test020() throws Throwable { String string0 = EWrapperMsgGenerator.updateAccountValue((String) null, " WAP=", (String) null, "Z!80~Sz?5"); assertEquals("updateAccountValue: null WAP= null Z!80~Sz?5", string0); } /** //Test case number: 21 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test021() throws Throwable { String string0 = EWrapperMsgGenerator.updateAccountValue("", "current time = 0 (Jan 1, 1970 12:00:00 AM)", "'JNZg#fQpBW('hhw", "PROFILES"); assertEquals("updateAccountValue: current time = 0 (Jan 1, 1970 12:00:00 AM) 'JNZg#fQpBW('hhw PROFILES", string0); } /** //Test case number: 22 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test022() throws Throwable { String string0 = EWrapperMsgGenerator.updateAccountTime((String) null); assertEquals("updateAccountTime: null", string0); } /** //Test case number: 23 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test023() throws Throwable { String string0 = EWrapperMsgGenerator.tickString((-2147483647), 0, (String) null); assertEquals("id=-2147483647 bidSize=null", string0); } /** //Test case number: 24 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test024() throws Throwable { String string0 = EWrapperMsgGenerator.tickString((-598), (-598), ")"); assertEquals("id=-598 unknown=)", string0); } /** //Test case number: 25 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test025() throws Throwable { String string0 = EWrapperMsgGenerator.tickString(0, 1787, "id = 0 =============== end ==============="); assertEquals("id=0 unknown=id = 0 =============== end ===============", string0); } /** //Test case number: 26 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test026() throws Throwable { String string0 = EWrapperMsgGenerator.tickSnapshotEnd(10); assertEquals("id=10 =============== end ===============", string0); } /** //Test case number: 27 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test027() throws Throwable { String string0 = EWrapperMsgGenerator.tickSnapshotEnd((-1)); assertEquals("id=-1 =============== end ===============", string0); } /** //Test case number: 28 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test028() throws Throwable { String string0 = EWrapperMsgGenerator.tickSize(Integer.MAX_VALUE, 1, 0); assertEquals("id=2147483647 bidPrice=0", string0); } /** //Test case number: 29 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test029() throws Throwable { String string0 = EWrapperMsgGenerator.tickSize(6096, 13, (-1849)); assertEquals("id=6096 modelOptComp=-1849", string0); } /** //Test case number: 30 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test030() throws Throwable { String string0 = EWrapperMsgGenerator.tickSize(495, 0, 2939); assertEquals("id=495 bidSize=2939", string0); } /** //Test case number: 31 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test031() throws Throwable { String string0 = EWrapperMsgGenerator.tickSize(0, (-1911516715), 13); assertEquals("id=0 unknown=13", string0); } /** //Test case number: 32 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test032() throws Throwable { String string0 = EWrapperMsgGenerator.tickPrice(520, 732, (-1.0), 732); assertEquals("id=520 unknown=-1.0 canAutoExecute", string0); } /** //Test case number: 33 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test033() throws Throwable { String string0 = EWrapperMsgGenerator.tickOptionComputation(Integer.MAX_VALUE, (-2621), 1.7976931348623157E308, 4938.117721, 0, 0); assertEquals("id=2147483647 unknown: vol = N/A delta = N/A", string0); } /** //Test case number: 34 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test034() throws Throwable { String string0 = EWrapperMsgGenerator.tickGeneric(0, 0, 0); assertEquals("id=0 bidSize=0.0", string0); } /** //Test case number: 35 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test035() throws Throwable { String string0 = EWrapperMsgGenerator.tickGeneric(0, Integer.MAX_VALUE, 0.0); assertEquals("id=0 unknown=0.0", string0); } /** //Test case number: 36 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test036() throws Throwable { String string0 = EWrapperMsgGenerator.tickGeneric((-856), (-364), 935.393863469); assertEquals("id=-856 unknown=935.393863469", string0); } /** //Test case number: 37 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test037() throws Throwable { String string0 = EWrapperMsgGenerator.tickEFP(966, 1725, 1273.76342, " whatIf=", 1725, 515, "", 515, 1.0); assertEquals("id=966 unknown: basisPoints = 1273.76342/ whatIf= impliedFuture = 1725.0 holdDays = 515 futureExpiry = dividendImpact = 515.0 dividends to expiry = 1.0", string0); } /** //Test case number: 38 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test038() throws Throwable { String string0 = EWrapperMsgGenerator.tickEFP(1241, (-998), 0, "Next Valid Order ID: 0", 0, 1833, "id=-2395 bidSize=0.0 noAutoExecute", 485, 0); assertEquals("id=1241 unknown: basisPoints = 0.0/Next Valid Order ID: 0 impliedFuture = 0.0 holdDays = 1833 futureExpiry = id=-2395 bidSize=0.0 noAutoExecute dividendImpact = 485.0 dividends to expiry = 0.0", string0); } /** //Test case number: 39 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test039() throws Throwable { String string0 = EWrapperMsgGenerator.tickEFP(301, 10, 1.7976931348623157E308, "", 10, 109, "SCANNER PARAMETERS:\n", 301, 301); assertEquals("id=301 bidOptComp: basisPoints = 1.7976931348623157E308/ impliedFuture = 10.0 holdDays = 109 futureExpiry = SCANNER PARAMETERS:\n dividendImpact = 301.0 dividends to expiry = 301.0", string0); } /** //Test case number: 40 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test040() throws Throwable { String string0 = EWrapperMsgGenerator.tickEFP(51, (-11), (-832.8096467004403), "id = 1872 =============== end ===============", (-11), 92, "id=0 bidSize=0.0", 0, (-1.0)); assertEquals("id=51 unknown: basisPoints = -832.8096467004403/id = 1872 =============== end =============== impliedFuture = -11.0 holdDays = 92 futureExpiry = id=0 bidSize=0.0 dividendImpact = 0.0 dividends to expiry = -1.0", string0); } /** //Test case number: 41 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test041() throws Throwable { String string0 = EWrapperMsgGenerator.tickEFP(0, Integer.MAX_VALUE, 0, (String) null, (-1851.074690981), 0, (String) null, (-1835.02822), 0); assertEquals("id=0 unknown: basisPoints = 0.0/null impliedFuture = -1851.074690981 holdDays = 0 futureExpiry = null dividendImpact = -1835.02822 dividends to expiry = 0.0", string0); } /** //Test case number: 42 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test042() throws Throwable { String string0 = EWrapperMsgGenerator.tickEFP((-1), 0, (-1.0), " commission=", 2382, (-2146324146), "executionExchange = ", (-1), 175.45041); assertEquals("id=-1 bidSize: basisPoints = -1.0/ commission= impliedFuture = 2382.0 holdDays = -2146324146 futureExpiry = executionExchange = dividendImpact = -1.0 dividends to expiry = 175.45041", string0); } /** //Test case number: 43 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test043() throws Throwable { String string0 = EWrapperMsgGenerator.scannerParameters("id=-598 unknown=)"); assertEquals("SCANNER PARAMETERS:\nid=-598 unknown=)", string0); } /** //Test case number: 44 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test044() throws Throwable { String string0 = EWrapperMsgGenerator.scannerParameters(""); assertEquals("SCANNER PARAMETERS:\n", string0); } /** //Test case number: 45 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test045() throws Throwable { String string0 = EWrapperMsgGenerator.scannerDataEnd(13); assertEquals("id = 13 =============== end ===============", string0); } /** //Test case number: 46 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test046() throws Throwable { String string0 = EWrapperMsgGenerator.scannerDataEnd((-2142990215)); assertEquals("id = -2142990215 =============== end ===============", string0); } /** //Test case number: 47 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test047() throws Throwable { Contract contract0 = new Contract(); ContractDetails contractDetails0 = new ContractDetails(contract0, "", (String) null, 10, "", "issueDate = ", 13, (String) null, "oD", "vVZe+p#(", (String) null, "6%$6B{kEc]|ah", "", "-* f|AA", "oD"); String string0 = EWrapperMsgGenerator.scannerData((-1), (-3549), contractDetails0, "tradingHours = ", "LXXn", (String) null, ""); assertEquals("id = -1 rank=-3549 symbol=null secType=null expiry=null strike=0.0 right=null exchange=null currency=null localSymbol=null marketName= tradingClass=null distance=tradingHours = benchmark=LXXn projection=null legsStr=", string0); } /** //Test case number: 48 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test048() throws Throwable { ContractDetails contractDetails0 = new ContractDetails(); String string0 = EWrapperMsgGenerator.scannerData(0, 2146500367, contractDetails0, "", "", "", "65>_&"); assertEquals("id = 0 rank=2146500367 symbol=null secType=null expiry=null strike=0.0 right=null exchange=null currency=null localSymbol=null marketName=null tradingClass=null distance= benchmark= projection= legsStr=65>_&", string0); } /** //Test case number: 49 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test049() throws Throwable { ContractDetails contractDetails0 = new ContractDetails(); String string0 = EWrapperMsgGenerator.scannerData(3109, (-646), contractDetails0, "?QFR)f*Z:lr/EnP(0xd", "'\"J ?iM+}@ UH(", (String) null, (String) null); assertEquals("id = 3109 rank=-646 symbol=null secType=null expiry=null strike=0.0 right=null exchange=null currency=null localSymbol=null marketName=null tradingClass=null distance=?QFR)f*Z:lr/EnP(0xd benchmark='\"J ?iM+}@ UH( projection=null legsStr=null", string0); } /** //Test case number: 50 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test050() throws Throwable { ContractDetails contractDetails0 = new ContractDetails(); String string0 = EWrapperMsgGenerator.scannerData((-1968), 152, contractDetails0, (String) null, (String) null, (String) null, "'slongName = "); assertEquals("id = -1968 rank=152 symbol=null secType=null expiry=null strike=0.0 right=null exchange=null currency=null localSymbol=null marketName=null tradingClass=null distance=null benchmark=null projection=null legsStr='slongName = ", string0); } /** //Test case number: 51 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test051() throws Throwable { String string0 = EWrapperMsgGenerator.receiveFA(1576, ""); assertEquals("FA: null ", string0); } /** //Test case number: 52 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test052() throws Throwable { String string0 = EWrapperMsgGenerator.receiveFA(Integer.MAX_VALUE, (String) null); assertEquals("FA: null null", string0); } /** //Test case number: 53 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test053() throws Throwable { String string0 = EWrapperMsgGenerator.receiveFA((-4613), "FA: null "); assertEquals("FA: null FA: null ", string0); } /** //Test case number: 54 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test054() throws Throwable { String string0 = EWrapperMsgGenerator.realtimeBar(964, 0L, 0.0, 0.0, 0L, (-769.25493), (-1961L), 964, (-1)); assertEquals("id=964 time = 0 open=0.0 high=0.0 low=0.0 close=-769.25493 volume=-1961 count=-1 WAP=964.0", string0); } /** //Test case number: 55 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test055() throws Throwable { String string0 = EWrapperMsgGenerator.realtimeBar(889, 889, 857.201569540318, (-3125.62922), 538.40307168, 538.40307168, 889, 869.2349366, (-1977)); assertEquals("id=889 time = 889 open=857.201569540318 high=-3125.62922 low=538.40307168 close=538.40307168 volume=889 count=-1977 WAP=869.2349366", string0); } /** //Test case number: 56 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test056() throws Throwable { String string0 = EWrapperMsgGenerator.realtimeBar(4826, (-1L), (-1L), 4826, (-1L), 2.147483647E9, (-1L), (-318.0), 4262); assertEquals("id=4826 time = -1 open=-1.0 high=4826.0 low=-1.0 close=2.147483647E9 volume=-1 count=4262 WAP=-318.0", string0); } /** //Test case number: 57 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test057() throws Throwable { String string0 = EWrapperMsgGenerator.realtimeBar(14, 14, 14, 0.0, (-1792), 2970, 0L, 0.0, 14); assertEquals("id=14 time = 14 open=14.0 high=0.0 low=-1792.0 close=2970.0 volume=0 count=14 WAP=0.0", string0); } /** //Test case number: 58 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test058() throws Throwable { String string0 = EWrapperMsgGenerator.realtimeBar(51, 0, 0, 2102.230301195631, (-3257L), (-110.4493724955), 3419, (-917.58247), 0); assertEquals("id=51 time = 0 open=0.0 high=2102.230301195631 low=-3257.0 close=-110.4493724955 volume=3419 count=0 WAP=-917.58247", string0); } /** //Test case number: 59 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test059() throws Throwable { String string0 = EWrapperMsgGenerator.realtimeBar((-882), (-203L), 809.0781, 732.0, 732.0, (-882), 0L, 0.0, 0); assertEquals("id=-882 time = -203 open=809.0781 high=732.0 low=732.0 close=-882.0 volume=0 count=0 WAP=0.0", string0); } /** //Test case number: 60 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test060() throws Throwable { String string0 = EWrapperMsgGenerator.orderStatus('f', " It does not support realtime bar data query cancellation.", 866, 0, 0, 39, 0, Integer.MAX_VALUE, Integer.MAX_VALUE, (String) null); assertEquals("order status: orderId=102 clientId=2147483647 permId=39 status= It does not support realtime bar data query cancellation. filled=866 remaining=0 avgFillPrice=0.0 lastFillPrice=2.147483647E9 parent Id=0 whyHeld=null", string0); } /** //Test case number: 61 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test061() throws Throwable { String string0 = EWrapperMsgGenerator.orderStatus(0, (String) null, 0, (-1604), 1.7976931348623157E308, 18, (-763), (-420.7889444535538), (-1009), "|_Sewl`'}G:NJ}"); assertEquals("order status: orderId=0 clientId=-1009 permId=18 status=null filled=0 remaining=-1604 avgFillPrice=1.7976931348623157E308 lastFillPrice=-420.7889444535538 parent Id=-763 whyHeld=|_Sewl`'}G:NJ}", string0); } /** //Test case number: 62 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test062() throws Throwable { String string0 = EWrapperMsgGenerator.orderStatus(2892, "", (-739), (-739), 2892, 0, 10, 10, (-1124), ""); assertEquals("order status: orderId=2892 clientId=-1124 permId=0 status= filled=-739 remaining=-739 avgFillPrice=2892.0 lastFillPrice=10.0 parent Id=10 whyHeld=", string0); } /** //Test case number: 63 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test063() throws Throwable { String string0 = EWrapperMsgGenerator.orderStatus(1, "id = 1872 =============== end ===============", 51, (-11), 967.9052572852312, 51, 1, 173.9, 0, "id=51 unknown: basisPoints = -832.8096467004403/id = 1872 =============== end =============== impliedFuture = -11.0 holdDays = 92 futureExpiry = id=0 bidSize=0.0 dividendImpact = 0.0 dividends to expiry = -1.0"); assertEquals("order status: orderId=1 clientId=0 permId=51 status=id = 1872 =============== end =============== filled=51 remaining=-11 avgFillPrice=967.9052572852312 lastFillPrice=173.9 parent Id=1 whyHeld=id=51 unknown: basisPoints = -832.8096467004403/id = 1872 =============== end =============== impliedFuture = -11.0 holdDays = 92 futureExpiry = id=0 bidSize=0.0 dividendImpact = 0.0 dividends to expiry = -1.0", string0); } /** //Test case number: 64 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test064() throws Throwable { String string0 = EWrapperMsgGenerator.orderStatus((-4418), "5", (-4418), 10, (-4418), (-2077), 10, (-2362.6660428), 10, "kl~G@"); assertEquals("order status: orderId=-4418 clientId=10 permId=-2077 status=5 filled=-4418 remaining=10 avgFillPrice=-4418.0 lastFillPrice=-2362.6660428 parent Id=10 whyHeld=kl~G@", string0); } /** //Test case number: 65 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test065() throws Throwable { Contract contract0 = new Contract(); Order order0 = new Order(); // Undeclared exception! try { EWrapperMsgGenerator.openOrder(3, contract0, order0, (OrderState) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.ib.client.EWrapperMsgGenerator", e); } } /** //Test case number: 66 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test066() throws Throwable { Contract contract0 = new Contract(); OrderState orderState0 = new OrderState(); // Undeclared exception! try { EWrapperMsgGenerator.openOrder(2244, contract0, (Order) null, orderState0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.ib.client.EWrapperMsgGenerator", e); } } /** //Test case number: 67 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test067() throws Throwable { Vector<TagValue> vector0 = new Vector<TagValue>(); Contract contract0 = new Contract(10, "D (Hv9|omaAkv-+G}mB", (String) null, (String) null, 0.0, "ciY[\rV", "h~/B*id{zZ'|A+~Vz)N", "?tW`%=f'$F:nol8", (String) null, "id = 648 len = 42\ncurrent time = 0 (Jan 1, 1970 12:00:00 AM)", vector0, ")cZnm{zWYV'W", true, "ciY[\rV", "qRbiSI<#F"); Order order0 = new Order(); OrderState orderState0 = new OrderState(); String string0 = EWrapperMsgGenerator.openOrder((-1968), contract0, order0, orderState0); assertNotNull(string0); } /** //Test case number: 68 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test068() throws Throwable { String string0 = EWrapperMsgGenerator.nextValidId(0); assertEquals("Next Valid Order ID: 0", string0); } /** //Test case number: 69 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test069() throws Throwable { String string0 = EWrapperMsgGenerator.nextValidId((-265)); assertEquals("Next Valid Order ID: -265", string0); } /** //Test case number: 70 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test070() throws Throwable { String string0 = EWrapperMsgGenerator.managedAccounts((String) null); assertEquals("Connected : The list of managed accounts are : [null]", string0); } /** //Test case number: 71 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test071() throws Throwable { String string0 = EWrapperMsgGenerator.managedAccounts(""); assertEquals("Connected : The list of managed accounts are : []", string0); } /** //Test case number: 72 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test072() throws Throwable { String string0 = EWrapperMsgGenerator.historicalData(2144565474, "id=13 modelOptComp=-1.0", 602.46927266903, 927.88412406879, (-595.178393), (-3895.4961), 858, 1100, 13, true); assertEquals("id=2144565474 date = id=13 modelOptComp=-1.0 open=602.46927266903 high=927.88412406879 low=-595.178393 close=-3895.4961 volume=858 count=1100 WAP=13.0 hasGaps=true", string0); } /** //Test case number: 73 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test073() throws Throwable { String string0 = EWrapperMsgGenerator.historicalData(0, (String) null, 'y', 2, 1, Integer.MAX_VALUE, 0, 0, 1.7976931348623157E308, false); assertEquals("id=0 date = null open=121.0 high=2.0 low=1.0 close=2.147483647E9 volume=0 count=0 WAP=1.7976931348623157E308 hasGaps=false", string0); } /** //Test case number: 74 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test074() throws Throwable { String string0 = EWrapperMsgGenerator.historicalData((-31), "", (-31), 0.0, (-31), 0.0, (-31), (-31), (-31), true); assertEquals("id=-31 date = open=-31.0 high=0.0 low=-31.0 close=0.0 volume=-31 count=-31 WAP=-31.0 hasGaps=true", string0); } /** //Test case number: 75 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test075() throws Throwable { String string0 = EWrapperMsgGenerator.historicalData(0, "6G7Eg(7", 1, Integer.MAX_VALUE, 0, 0, 10, (-19), 0, false); assertEquals("id=0 date = 6G7Eg(7 open=1.0 high=2.147483647E9 low=0.0 close=0.0 volume=10 count=-19 WAP=0.0 hasGaps=false", string0); } /** //Test case number: 76 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test076() throws Throwable { String string0 = EWrapperMsgGenerator.historicalData((-1911516715), "com.ib.client.Order", 0, (-1911516715), (-639), 0.0, 4448, (-1911516715), (-1911516715), false); assertEquals("id=-1911516715 date = com.ib.client.Order open=0.0 high=-1.911516715E9 low=-639.0 close=0.0 volume=4448 count=-1911516715 WAP=-1.911516715E9 hasGaps=false", string0); } /** //Test case number: 77 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test077() throws Throwable { String string0 = EWrapperMsgGenerator.fundamentalData((-358), ""); assertEquals("id = -358 len = 0\n", string0); } /** //Test case number: 78 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test078() throws Throwable { String string0 = EWrapperMsgGenerator.fundamentalData((-221), "OptionCallOpenInterest"); assertEquals("id = -221 len = 22\nOptionCallOpenInterest", string0); } /** //Test case number: 79 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test079() throws Throwable { String string0 = EWrapperMsgGenerator.execDetailsEnd(0); assertEquals("reqId = 0 =============== end ===============", string0); } /** //Test case number: 80 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test080() throws Throwable { String string0 = EWrapperMsgGenerator.execDetailsEnd((-221)); assertEquals("reqId = -221 =============== end ===============", string0); } /** //Test case number: 81 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test081() throws Throwable { Contract contract0 = new Contract(); // Undeclared exception! try { EWrapperMsgGenerator.execDetails(13, contract0, (Execution) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.ib.client.EWrapperMsgGenerator", e); } } /** //Test case number: 82 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test082() throws Throwable { Contract contract0 = new Contract(); Execution execution0 = new Execution(2591, 2396, (String) null, (String) null, "highEFP", "]j<AA;Ik4Ai-", "{Gv", (-3621), (-6578.65889229993), 99, 1019, (-3168), 845.4031954459203); String string0 = EWrapperMsgGenerator.execDetails(46, contract0, execution0); assertEquals(" ---- Execution Details begin ----\nreqId = 46\norderId = 2591\nclientId = 2396\nsymbol = null\nsecType = null\nexpiry = null\nstrike = 0.0\nright = null\ncontractExchange = null\ncurrency = null\nlocalSymbol = null\nexecId = null\ntime = null\nacctNumber = highEFP\nexecutionExchange = ]j<AA;Ik4Ai-\nside = {Gv\nshares = -3621\nprice = -6578.65889229993\npermId = 99\nliquidation = 1019\ncumQty = -3168\navgPrice = 845.4031954459203\n ---- Execution Details end ----\n", string0); } /** //Test case number: 83 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test083() throws Throwable { UnderComp underComp0 = new UnderComp(); String string0 = EWrapperMsgGenerator.deltaNeutralValidation((-1732), underComp0); assertEquals("id = -1732 underComp.conId =0 underComp.delta =0.0 underComp.price =0.0", string0); } /** //Test case number: 84 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test084() throws Throwable { Vector<Object> vector0 = new Vector<Object>(); Contract contract0 = new Contract(0, (String) null, "com.ib.client.Order", "}gYfGR5", (-2371.2254), "halted", "!Q^7&B]%1", "com.ib.client.TickType", " It does not support fundamental data requests.", "halted", vector0, "reqId = 4448 =============== end ===============", true, "com.ib.client.TickType", " expiry="); // Undeclared exception! try { EWrapperMsgGenerator.deltaNeutralValidation(0, contract0.m_underComp); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.ib.client.EWrapperMsgGenerator", e); } } /** //Test case number: 85 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test085() throws Throwable { Vector<Object> vector0 = new Vector<Object>(); Contract contract0 = new Contract((-1911516715), "com.ib.client.Order", "ZQXkD", (String) null, (-3528.7926823), "kbe&ks", "reqId = 4448 =============== end ===============", (String) null, (String) null, "Jb2^R]G", vector0, "reqId = 4448 =============== end ===============", false, "j%Nh%q&-(-&{VI", "b="); // Undeclared exception! try { EWrapperMsgGenerator.deltaNeutralValidation(2146460232, contract0.m_underComp); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.ib.client.EWrapperMsgGenerator", e); } } /** //Test case number: 86 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test086() throws Throwable { String string0 = EWrapperMsgGenerator.currentTime(5L); assertEquals("current time = 5 (Jan 1, 1970 12:00:05 AM)", string0); } /** //Test case number: 87 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test087() throws Throwable { String string0 = EWrapperMsgGenerator.currentTime((-3L)); assertEquals("current time = -3 (Dec 31, 1969 11:59:57 PM)", string0); } /** //Test case number: 88 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test088() throws Throwable { Vector<TagValue> vector0 = new Vector<TagValue>(); Contract contract0 = new Contract(10, "D (Hv9|omaAkv-+G}mB", (String) null, (String) null, 0.0, "ciY[\rV", "h~/B*id{zZ'|A+~Vz)N", "?tW`%=f'$F:nol8", (String) null, "id = 648 len = 42\ncurrent time = 0 (Jan 1, 1970 12:00:00 AM)", vector0, ")cZnm{zWYV'W", true, "ciY[\rV", "qRbiSI<#F"); String string0 = EWrapperMsgGenerator.contractMsg(contract0); assertEquals("conid = 10\nsymbol = D (Hv9|omaAkv-+G}mB\nsecType = null\nexpiry = null\nstrike = 0.0\nright = ciY[\rV\nmultiplier = h~/B*id{zZ'|A+~Vz)N\nexchange = ?tW`%=f'$F:nol8\nprimaryExch = )cZnm{zWYV'W\ncurrency = null\nlocalSymbol = id = 648 len = 42\ncurrent time = 0 (Jan 1, 1970 12:00:00 AM)\n", string0); } /** //Test case number: 89 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test089() throws Throwable { String string0 = EWrapperMsgGenerator.contractDetailsEnd(0); assertEquals("reqId = 0 =============== end ===============", string0); } /** //Test case number: 90 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test090() throws Throwable { String string0 = EWrapperMsgGenerator.contractDetailsEnd((-2147021759)); assertEquals("reqId = -2147021759 =============== end ===============", string0); } /** //Test case number: 91 /*Coverage entropy=1.0986122886681096 */ @Test(timeout = 4000) public void test091() throws Throwable { Contract contract0 = new Contract(); ContractDetails contractDetails0 = new ContractDetails(contract0, "p97N~[(", "", (-923.7197130073154), (String) null, "MsgId=", 102, "]z`m\"e5XvAOdOsB*Y", "", (String) null, "", "reqId = 1 =============== end ===============", (String) null, "p97N~[(", "a-!nG|1d"); String string0 = EWrapperMsgGenerator.contractDetails(1, contractDetails0); assertEquals("reqId = 1 ===================================\n ---- Contract Details begin ----\nconid = 0\nsymbol = null\nsecType = null\nexpiry = null\nstrike = 0.0\nright = null\nmultiplier = null\nexchange = null\nprimaryExch = null\ncurrency = null\nlocalSymbol = null\nmarketName = p97N~[(\ntradingClass = \nminTick = -923.7197130073154\nprice magnifier = 0\norderTypes = null\nvalidExchanges = MsgId=\nunderConId = 102\nlongName = ]z`m\"e5XvAOdOsB*Y\ncontractMonth = \nindustry = null\ncategory = \nsubcategory = reqId = 1 =============== end ===============\ntimeZoneId = null\ntradingHours = p97N~[(\nliquidHours = a-!nG|1d\n ---- Contract Details End ----\n", string0); } /** //Test case number: 92 /*Coverage entropy=1.0986122886681096 */ @Test(timeout = 4000) public void test092() throws Throwable { ContractDetails contractDetails0 = new ContractDetails(); String string0 = EWrapperMsgGenerator.contractDetails((-32), contractDetails0); assertEquals("reqId = -32 ===================================\n ---- Contract Details begin ----\nconid = 0\nsymbol = null\nsecType = null\nexpiry = null\nstrike = 0.0\nright = null\nmultiplier = null\nexchange = null\nprimaryExch = null\ncurrency = null\nlocalSymbol = null\nmarketName = null\ntradingClass = null\nminTick = 0.0\nprice magnifier = 0\norderTypes = null\nvalidExchanges = null\nunderConId = 0\nlongName = null\ncontractMonth = null\nindustry = null\ncategory = null\nsubcategory = null\ntimeZoneId = null\ntradingHours = null\nliquidHours = null\n ---- Contract Details End ----\n", string0); } /** //Test case number: 93 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test093() throws Throwable { Contract contract0 = new Contract(); ContractDetails contractDetails0 = new ContractDetails(contract0, (String) null, (String) null, (-5514.32854817), "$Q{9~l><37", (String) null, 1, (String) null, "", (String) null, "com.ib.client.UnderComp", (String) null, "com.ib.client.Execution", "com.ib.client.ContractDetails", (String) null); String string0 = EWrapperMsgGenerator.bondContractDetails(0, contractDetails0); assertEquals("reqId = 0 ===================================\n ---- Bond Contract Details begin ----\nsymbol = null\nsecType = null\ncusip = null\ncoupon = 0.0\nmaturity = null\nissueDate = null\nratings = null\nbondType = null\ncouponType = null\nconvertible = false\ncallable = false\nputable = false\ndescAppend = null\nexchange = null\ncurrency = null\nmarketName = null\ntradingClass = null\nconid = 0\nminTick = -5514.32854817\norderTypes = $Q{9~l><37\nvalidExchanges = null\nnextOptionDate = null\nnextOptionType = null\nnextOptionPartial = false\nnotes = null\nlongName = null\n ---- Bond Contract Details End ----\n", string0); } /** //Test case number: 94 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test094() throws Throwable { ContractDetails contractDetails0 = new ContractDetails(); String string0 = EWrapperMsgGenerator.bondContractDetails((-1), contractDetails0); assertEquals("reqId = -1 ===================================\n ---- Bond Contract Details begin ----\nsymbol = null\nsecType = null\ncusip = null\ncoupon = 0.0\nmaturity = null\nissueDate = null\nratings = null\nbondType = null\ncouponType = null\nconvertible = false\ncallable = false\nputable = false\ndescAppend = null\nexchange = null\ncurrency = null\nmarketName = null\ntradingClass = null\nconid = 0\nminTick = 0.0\norderTypes = null\nvalidExchanges = null\nnextOptionDate = null\nnextOptionType = null\nnextOptionPartial = false\nnotes = null\nlongName = null\n ---- Bond Contract Details End ----\n", string0); } /** //Test case number: 95 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test095() throws Throwable { String string0 = EWrapperMsgGenerator.accountDownloadEnd("6kI_xFGvbb:d"); assertEquals("accountDownloadEnd: 6kI_xFGvbb:d", string0); } /** //Test case number: 96 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test096() throws Throwable { String string0 = EWrapperMsgGenerator.accountDownloadEnd(""); assertEquals("accountDownloadEnd: ", string0); } /** //Test case number: 97 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test097() throws Throwable { // Undeclared exception! try { EWrapperMsgGenerator.scannerData(0, 0, (ContractDetails) null, (String) null, "", (String) null, (String) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.ib.client.EWrapperMsgGenerator", e); } } /** //Test case number: 98 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test098() throws Throwable { Order order0 = new Order(); OrderState orderState0 = new OrderState("", "auctionPrice", "KsL/^CwR/6", "notes = ", 148.4338500588, 4938.117721, (-2213.1791), (String) null, (String) null); // Undeclared exception! try { EWrapperMsgGenerator.openOrder('y', (Contract) null, order0, orderState0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.ib.client.EWrapperMsgGenerator", e); } } /** //Test case number: 99 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test099() throws Throwable { // Undeclared exception! try { EWrapperMsgGenerator.fundamentalData(0, (String) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.ib.client.EWrapperMsgGenerator", e); } } /** //Test case number: 100 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test100() throws Throwable { Execution execution0 = new Execution(); // Undeclared exception! try { EWrapperMsgGenerator.execDetails((-1214), (Contract) null, execution0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.ib.client.EWrapperMsgGenerator", e); } } /** //Test case number: 101 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test101() throws Throwable { // Undeclared exception! try { EWrapperMsgGenerator.contractMsg((Contract) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.ib.client.EWrapperMsgGenerator", e); } } /** //Test case number: 102 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test102() throws Throwable { // Undeclared exception! try { EWrapperMsgGenerator.bondContractDetails(22, (ContractDetails) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.ib.client.EWrapperMsgGenerator", e); } } /** //Test case number: 103 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test103() throws Throwable { Contract contract0 = new Contract(); Order order0 = new Order(); OrderState orderState0 = new OrderState(); String string0 = EWrapperMsgGenerator.openOrder(0, contract0, order0, orderState0); assertNotNull(string0); } /** //Test case number: 104 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test104() throws Throwable { String string0 = EWrapperMsgGenerator.tickOptionComputation((-763), 13, 0, 0.0, 0.0, 1.7976931348623157E308); assertEquals("id=-763 modelOptComp: vol = 0.0 delta = 0.0: modelPrice = 0.0: pvDividend = N/A", string0); } /** //Test case number: 105 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test105() throws Throwable { String string0 = EWrapperMsgGenerator.tickOptionComputation(13, 13, 1.7976931348623157E308, 13, 1.7976931348623157E308, 845.4031954459203); assertEquals("id=13 modelOptComp: vol = N/A delta = N/A: modelPrice = N/A: pvDividend = 845.4031954459203", string0); } /** //Test case number: 106 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test106() throws Throwable { String string0 = EWrapperMsgGenerator.tickOptionComputation(121, 13, 2283.2551009, 1.7976931348623157E308, (-4648.3544159002), 0); assertEquals("id=121 modelOptComp: vol = 2283.2551009 delta = N/A: modelPrice = N/A: pvDividend = 0.0", string0); } /** //Test case number: 107 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test107() throws Throwable { String string0 = EWrapperMsgGenerator.tickOptionComputation(0, 0, 0, 0, (-832.8096467004403), 0); assertEquals("id=0 bidSize: vol = 0.0 delta = 0.0", string0); } /** //Test case number: 108 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test108() throws Throwable { String string0 = EWrapperMsgGenerator.tickOptionComputation(1, Integer.MAX_VALUE, 1.7976931348623157E308, (-2928.4623), 1.7976931348623157E308, 13); assertEquals("id=1 unknown: vol = N/A delta = N/A", string0); } /** //Test case number: 109 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test109() throws Throwable { String string0 = EWrapperMsgGenerator.tickOptionComputation(0, 13, (-441.15073536), 1.0, 734.9, (-763)); assertEquals("id=0 modelOptComp: vol = N/A delta = 1.0: modelPrice = 734.9: pvDividend = N/A", string0); } /** //Test case number: 110 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test110() throws Throwable { String string0 = EWrapperMsgGenerator.tickPrice(39, (-2010), 1.7976931348623157E308, (-364)); assertEquals("id=39 unknown=1.7976931348623157E308 canAutoExecute", string0); } /** //Test case number: 111 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test111() throws Throwable { String string0 = EWrapperMsgGenerator.tickPrice((-1562), 0, 0.0, 0); assertEquals("id=-1562 bidSize=0.0 noAutoExecute", string0); } /** //Test case number: 112 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test112() throws Throwable { String string0 = EWrapperMsgGenerator.updateMktDepth('n', 2146904915, Integer.MAX_VALUE, 0, 1.7976931348623157E308, Integer.MAX_VALUE); assertEquals("updateMktDepth: 110 2146904915 2147483647 0 1.7976931348623157E308 2147483647", string0); } /** //Test case number: 113 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test113() throws Throwable { String string0 = EWrapperMsgGenerator.tickString(648, 648, "1M"); assertEquals("id=648 unknown=1M", string0); } /** //Test case number: 114 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test114() throws Throwable { String string0 = EWrapperMsgGenerator.fundamentalData(648, "current time = 0 (Jan 1, 1970 12:00:00 AM)"); assertEquals("id = 648 len = 42\ncurrent time = 0 (Jan 1, 1970 12:00:00 AM)", string0); } /** //Test case number: 115 /*Coverage entropy=1.0986122886681096 */ @Test(timeout = 4000) public void test115() throws Throwable { ContractDetails contractDetails0 = new ContractDetails(); String string0 = EWrapperMsgGenerator.contractDetails(0, contractDetails0); assertEquals("reqId = 0 ===================================\n ---- Contract Details begin ----\nconid = 0\nsymbol = null\nsecType = null\nexpiry = null\nstrike = 0.0\nright = null\nmultiplier = null\nexchange = null\nprimaryExch = null\ncurrency = null\nlocalSymbol = null\nmarketName = null\ntradingClass = null\nminTick = 0.0\nprice magnifier = 0\norderTypes = null\nvalidExchanges = null\nunderConId = 0\nlongName = null\ncontractMonth = null\nindustry = null\ncategory = null\nsubcategory = null\ntimeZoneId = null\ntradingHours = null\nliquidHours = null\n ---- Contract Details End ----\n", string0); } /** //Test case number: 116 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test116() throws Throwable { Contract contract0 = new Contract(); String string0 = EWrapperMsgGenerator.updatePortfolio(contract0, 0, 0.0, (-1.0), (-2371.2254), 1.7976931348623157E308, 0, ""); assertEquals("updatePortfolio: conid = 0\nsymbol = null\nsecType = null\nexpiry = null\nstrike = 0.0\nright = null\nmultiplier = null\nexchange = null\nprimaryExch = null\ncurrency = null\nlocalSymbol = null\n0 0.0 -1.0 -2371.2254 1.7976931348623157E308 0.0 ", string0); } /** //Test case number: 117 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test117() throws Throwable { String string0 = EWrapperMsgGenerator.updateAccountValue("p$KO^q", "lastEFP", "", "putable = "); assertEquals("updateAccountValue: p$KO^q lastEFP putable = ", string0); } /** //Test case number: 118 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test118() throws Throwable { String string0 = EWrapperMsgGenerator.receiveFA(0, "id=0 unknown: vol = 0.0 delta = N/A"); assertEquals("FA: null id=0 unknown: vol = 0.0 delta = N/A", string0); } /** //Test case number: 119 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test119() throws Throwable { String string0 = EWrapperMsgGenerator.contractDetailsEnd(47); assertEquals("reqId = 47 =============== end ===============", string0); } /** //Test case number: 120 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test120() throws Throwable { String string0 = EWrapperMsgGenerator.tickSnapshotEnd(0); assertEquals("id=0 =============== end ===============", string0); } /** //Test case number: 121 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test121() throws Throwable { String string0 = EWrapperMsgGenerator.orderStatus(0, "updateAccountValue: com.ib.client.Contract =============== end =============== =============== end =============== stockRangeUpper=", 10, 0, 0.0, 0, 0, 0, (-1562), ".wDe(i2QX(q,7c+Q"); assertEquals("order status: orderId=0 clientId=-1562 permId=0 status=updateAccountValue: com.ib.client.Contract =============== end =============== =============== end =============== stockRangeUpper= filled=10 remaining=0 avgFillPrice=0.0 lastFillPrice=0.0 parent Id=0 whyHeld=.wDe(i2QX(q,7c+Q", string0); } /** //Test case number: 122 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test122() throws Throwable { String string0 = EWrapperMsgGenerator.scannerDataEnd(0); assertEquals("id = 0 =============== end ===============", string0); } /** //Test case number: 123 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test123() throws Throwable { String string0 = EWrapperMsgGenerator.tickGeneric(13, 13, (-2371.2254)); assertEquals("id=13 modelOptComp=-2371.2254", string0); } /** //Test case number: 124 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test124() throws Throwable { String string0 = EWrapperMsgGenerator.managedAccounts("id=10 unknown: vol = 10.0 delta = N/A"); assertEquals("Connected : The list of managed accounts are : [id=10 unknown: vol = 10.0 delta = N/A]", string0); } /** //Test case number: 125 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test125() throws Throwable { EWrapperMsgGenerator eWrapperMsgGenerator0 = new EWrapperMsgGenerator(); assertEquals("Connection Closed", eWrapperMsgGenerator0.connectionClosed()); } /** //Test case number: 126 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test126() throws Throwable { // Undeclared exception! try { EWrapperMsgGenerator.contractDetails(0, (ContractDetails) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.ib.client.EWrapperMsgGenerator", e); } } /** //Test case number: 127 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test127() throws Throwable { String string0 = EWrapperMsgGenerator.accountDownloadEnd((String) null); assertEquals("accountDownloadEnd: null", string0); } /** //Test case number: 128 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test128() throws Throwable { String string0 = EWrapperMsgGenerator.updateMktDepthL2((-1), 0, (String) null, 0, 2920, 0.0, Integer.MAX_VALUE); assertEquals("updateMktDepth: -1 0 null 0 2920 0.0 2147483647", string0); } /** //Test case number: 129 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test129() throws Throwable { Contract contract0 = new Contract(); ContractDetails contractDetails0 = new ContractDetails(contract0, "", "", 'c', "O", (String) null, 0, " ---- Execution Details begin ----\nreqId = 0\norderId = 0\nclientId = 0\nsymbol = null\nsecType = null\nexpiry = null\nstrike = 0.0\nright = null\ncontractExchange = null\ncurrency = null\nlocalSymbol = null\nexecId = null\ntime = null\nacctNumber = null\nexecutionExchange = null\nside = null\nshares = 0\nprice = 0.0\npermId = 0\nliquidation = 0\ncumQty = 0\navgPrice = 0.0\n ---- Execution Details end ----\n", "", (String) null, (String) null, (String) null, (String) null, "#yde-uOKz,t@';V^+", ""); String string0 = EWrapperMsgGenerator.scannerData(0, (-1), contractDetails0, (String) null, "NX<0SAR]8Avuht", " tradingClass=", "b)"); assertEquals("id = 0 rank=-1 symbol=null secType=null expiry=null strike=0.0 right=null exchange=null currency=null localSymbol=null marketName= tradingClass= distance=null benchmark=NX<0SAR]8Avuht projection= tradingClass= legsStr=b)", string0); } /** //Test case number: 130 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test130() throws Throwable { String string0 = EWrapperMsgGenerator.realtimeBar(0, (-11), 1.7976931348623157E308, 3090.87, 2102.230301195631, 1.0, (-3257L), 0, 3419); assertEquals("id=0 time = -11 open=1.7976931348623157E308 high=3090.87 low=2102.230301195631 close=1.0 volume=-3257 count=3419 WAP=0.0", string0); } /** //Test case number: 131 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test131() throws Throwable { String string0 = EWrapperMsgGenerator.nextValidId(2094); assertEquals("Next Valid Order ID: 2094", string0); } /** //Test case number: 132 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test132() throws Throwable { String string0 = EWrapperMsgGenerator.execDetailsEnd(1604); assertEquals("reqId = 1604 =============== end ===============", string0); } /** //Test case number: 133 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test133() throws Throwable { String string0 = EWrapperMsgGenerator.currentTime(0L); assertEquals("current time = 0 (Jan 1, 1970 12:00:00 AM)", string0); } /** //Test case number: 134 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test134() throws Throwable { String string0 = EWrapperMsgGenerator.openOrderEnd(); assertEquals(" =============== end ===============", string0); } /** //Test case number: 135 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test135() throws Throwable { Contract contract0 = new Contract(); Execution execution0 = new Execution(); String string0 = EWrapperMsgGenerator.execDetails(0, contract0, execution0); assertEquals(" ---- Execution Details begin ----\nreqId = 0\norderId = 0\nclientId = 0\nsymbol = null\nsecType = null\nexpiry = null\nstrike = 0.0\nright = null\ncontractExchange = null\ncurrency = null\nlocalSymbol = null\nexecId = null\ntime = null\nacctNumber = null\nexecutionExchange = null\nside = null\nshares = 0\nprice = 0.0\npermId = 0\nliquidation = 0\ncumQty = 0\navgPrice = 0.0\n ---- Execution Details end ----\n", string0); } /** //Test case number: 136 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test136() throws Throwable { String string0 = EWrapperMsgGenerator.tickSize((-636), (-1950), 1133); assertEquals("id=-636 unknown=1133", string0); } /** //Test case number: 137 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test137() throws Throwable { String string0 = EWrapperMsgGenerator.scannerParameters((String) null); assertEquals("SCANNER PARAMETERS:\nnull", string0); } /** //Test case number: 138 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test138() throws Throwable { String string0 = EWrapperMsgGenerator.updateAccountTime(" status="); assertEquals("updateAccountTime: status=", string0); } }
40.473684
860
0.649051
3a30d2464806c441f8af02cfa1bc2b12569f83f5
356
package jpuppeteer.cdp.client.entity.domstorage; /** * experimental */ public class DomStorageItemsClearedEvent { /** */ public final jpuppeteer.cdp.client.entity.domstorage.StorageId storageId; public DomStorageItemsClearedEvent(jpuppeteer.cdp.client.entity.domstorage.StorageId storageId) { this.storageId = storageId; } }
22.25
101
0.741573
08dfecd843dedbefa126f804764e90072c674869
2,033
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.bpmn.model; /** * @author Tijs Rademakers * @author Joram Barrez */ public class ScriptTask extends Task { protected String scriptFormat; protected String script; protected String resultVariable; protected boolean autoStoreVariables = false; // see // https://activiti.atlassian.net/browse/ACT-1626 public String getScriptFormat() { return scriptFormat; } public void setScriptFormat(String scriptFormat) { this.scriptFormat = scriptFormat; } public String getScript() { return script; } public void setScript(String script) { this.script = script; } public String getResultVariable() { return resultVariable; } public void setResultVariable(String resultVariable) { this.resultVariable = resultVariable; } public boolean isAutoStoreVariables() { return autoStoreVariables; } public void setAutoStoreVariables(boolean autoStoreVariables) { this.autoStoreVariables = autoStoreVariables; } public ScriptTask clone() { ScriptTask clone = new ScriptTask(); clone.setValues(this); return clone; } public void setValues(ScriptTask otherElement) { super.setValues(otherElement); setScriptFormat(otherElement.getScriptFormat()); setScript(otherElement.getScript()); setResultVariable(otherElement.getResultVariable()); setAutoStoreVariables(otherElement.isAutoStoreVariables()); } }
27.849315
97
0.719134
93f9c145c9a8322573ad3cebade2a4473b7b4445
2,898
package ec.common.error; import lombok.extern.slf4j.Slf4j; import java.util.Arrays; import java.util.Optional; /** * @author zack <br> * @create 2020-10-06 11:34 <br> * @project project-ec <br> */ @Slf4j public enum ErrorMessageEnum { // common errors SYSTEM_ERROR(999999, "Internal Server Error"), BEAN_VALIDATION_ERROR(400400, "Validate bean property error"), ; private Integer errorCode; private String errorMsg; ErrorMessageEnum(Integer errorCode, String errorMsg) { this.errorCode = errorCode; this.errorMsg = errorMsg; } public Integer getErrorCode() { return errorCode; } public String getErrorMsg() { return errorMsg; } @Override public String toString() { return "ErrorMessages{" + "code=" + errorCode + ", errorMsg='" + errorMsg + '\'' + '}'; } /** * get ErrorMessage by error code. * * @param errorCode * @return ErrorMessage */ public static ErrorMessageEnum getByErrorCode(final Integer errorCode) { return Arrays.stream(values()) .filter(enumErrorCode -> enumErrorCode.getErrorCode().equals(errorCode)) .findFirst() .orElse(null); } /** * get ErrorMessage by enum name, such as UNKNOWN_EXCEPTION. * * @param enumName * @return ErrorMessage */ public static ErrorMessageEnum getByEnumName(final String enumName) { Optional<ErrorMessageEnum> errorCode = getValueOf(ErrorMessageEnum.class, enumName); return errorCode.isPresent() ? errorCode.get() : null; } public static String getMessageByCode(final String errorCode) { Optional<ErrorMessageEnum> errorMessage = Arrays.stream(values()) .filter(enumErrorCode -> enumErrorCode.getErrorCode().equals(errorCode)) .findFirst(); return errorMessage.isPresent() ? errorMessage.get().getErrorMsg() : null; } public static Integer getCodeByMessage(final String errorMessage) { Optional<ErrorMessageEnum> errorCode = Arrays.stream(ErrorMessageEnum.class.getEnumConstants()) .filter(enumErrorCode -> enumErrorCode.getErrorMsg().equals(errorMessage)) .findFirst(); return errorCode.isPresent() ? errorCode.get().getErrorCode() : null; } /** * Convert enum to Optional, and handle IllegalArgumentException. * * @param enumType * @param name * @return Optional<Enum> or Optional.empty() */ private static Optional<ErrorMessageEnum> getValueOf( Class<ErrorMessageEnum> enumType, String name) { ErrorMessageEnum enumValue; try { enumValue = Enum.valueOf(enumType, name); } catch (IllegalArgumentException ex) { log.info( "occurs IllegalArgumentException when get enum[{}] by enum name: {}, so return {}", enumType, name, Optional.empty()); return Optional.empty(); } return Optional.ofNullable(enumValue); } }
27.865385
93
0.674603
020fb38b6e3e7ddb911e9b3d5d52369985af224f
1,310
package com.dev.base.exception.errorcode; import java.io.IOException; import java.util.Map.Entry; import java.util.Properties; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.io.Resource; import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.PropertiesLoaderUtils; /** * * <p>Title: 错误码配置</p> * <p>Description: 描述(简要描述类的职责、实现方式、使用注意事项等)</p> * <p>CreateDate: 2015年8月21日下午2:08:43</p> */ public class ErrorCodePropertyConfigurer implements InitializingBean { private Resource[] locations; public ErrorCodePropertyConfigurer() { } public Resource[] getLocations() { return locations; } public void setLocations(Resource[] locations) { this.locations = locations; } @Override public void afterPropertiesSet() throws Exception { this.build(); } protected void build() { for (Resource location : this.locations) { if (location == null) { continue; } try { Properties prop = PropertiesLoaderUtils.loadProperties(new EncodedResource(location,"UTF-8")); for (Entry<Object, Object> entry : prop.entrySet()) { ErrorCodeTool.setProperty(entry.getKey().toString(), entry.getValue().toString()); } } catch (IOException e) { e.printStackTrace(); } } } }
24.259259
98
0.725191
b3cdad7c73551265e48e52d691443ec4a2257017
1,924
package com.northeastern.edu; public class question1 { //Definition for singly-linked list. public static class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummy = new ListNode(0); ListNode cur3 = dummy; int carry = 0; ListNode cur1 = l1; ListNode cur2 = l2; int tmp = 0; while (cur1 != null || cur2 != null) { if (cur1 == null) { tmp = 0 + cur2.val + carry; } else if (cur2 == null) { tmp = 0 + cur1.val + carry; } else { tmp = cur1.val + cur2.val + carry; } ListNode newNode = new ListNode(tmp % 10); cur3.next = newNode; cur3 = cur3.next; carry = tmp / 10; if (cur1 != null) { cur1 = cur1.next; } if (cur2 != null) { cur2 = cur2.next; } } if (carry > 0) { cur3.next = new ListNode(carry); } return dummy.next; } public static void main(String[] args) { ListNode node1 = new ListNode(1); ListNode node2 = new ListNode(2); ListNode node3 = new ListNode(8); node1.next = node2; node2.next = node3; ListNode node4 = new ListNode(2); ListNode node5 = new ListNode(2); ListNode node6 = new ListNode(7); node4.next = node5; node5.next = node6; ListNode ans = addTwoNumbers(node1, node4); while (ans != null) { System.out.println(ans.val); ans = ans.next; } } }
27.485714
68
0.474012
23e40cea09fcf55d0e5140f50c1df799f52041ed
458
package fmnavarretem.co.restproxyandroidjava.Model.Util; import retrofit2.http.DELETE; import retrofit2.http.PATCH; public class Constants { public static class EndPoints{ public static String URL_ROOT = "https://sports-decathlon.herokuapp.com/api/v1/"; public static String SWIMMING = "sports"; } public enum ServiceTag{ GET_SWIMMING } public enum HTTPMethod{ GET, PATCH, DELETE } }
22.9
89
0.668122
191374050de6b090c983bb4b5da62e45db694d09
2,287
/* * Copyright 2000-2017 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 org.intellij.lang.regexp.inspection; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.ElementManipulator; import com.intellij.psi.ElementManipulators; import com.intellij.psi.PsiElement; import com.intellij.psi.xml.XmlElement; import com.intellij.xml.util.XmlStringUtil; import org.intellij.lang.regexp.psi.RegExpElement; import org.intellij.lang.regexp.psi.impl.RegExpElementImpl; /** * @author Bas Leijdekkers */ public class RegExpReplacementUtil { private RegExpReplacementUtil() {} public static String escapeForContext(String text, RegExpElement element) { final PsiElement context = element.getContainingFile().getContext(); ElementManipulator<PsiElement> manipulator = context == null ? null : ElementManipulators.getManipulator(context); if (manipulator != null) { // use element manipulator to process escape sequences correctly for all supported languages PsiElement copy = context.copy(); // create a copy to avoid original element modifications PsiElement newElement = manipulator.handleContentChange(copy, text); String newElementText = newElement.getText(); TextRange newRange = manipulator.getRangeInElement(newElement); return newElementText.substring(newRange.getStartOffset(), newRange.getEndOffset()); } else if (RegExpElementImpl.isLiteralExpression(context)) { // otherwise, just pretend it is a Java-style string return StringUtil.escapeStringCharacters(text); } else if (context instanceof XmlElement) { return XmlStringUtil.escapeString(text); } else { return text; } } }
39.431034
118
0.755138
da3a1be9700516f08c04abb736a74fe51264a872
316
package de.wirvsvirus.testresult.backend.model; import org.springframework.data.mongodb.core.mapping.Document; import lombok.Data; @Document @Data public class TestResult { String id; Result status; String contact; boolean notified; public enum Result { POSITIVE, NEGATIVE, PENDING} }
16.631579
63
0.731013
77c0e014e545fd711bcb658192e2e3d1c1edc394
3,653
package com.muleinaction; import org.junit.BeforeClass; import org.junit.Test; import org.mockftpserver.fake.FakeFtpServer; import org.mockftpserver.fake.UserAccount; import org.mockftpserver.fake.filesystem.DirectoryEntry; import org.mockftpserver.fake.filesystem.FileSystem; import org.mockftpserver.fake.filesystem.UnixFakeFileSystem; import org.mule.api.context.notification.EndpointMessageNotificationListener; import org.mule.api.context.notification.ServerNotification; import org.mule.context.notification.EndpointMessageNotification; import org.mule.tck.junit4.FunctionalTestCase; import org.mule.util.FileUtils; import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; import java.io.File; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class JDBCOutboundFunctionalTestCase extends FunctionalTestCase { private FakeFtpServer fakeFtpServer; private CountDownLatch putFilesLatch; private JdbcTemplate template; @Override protected String getConfigResources() { return "src/main/app/jdbc-outbound-config.xml"; } @BeforeClass public static void setupDirectories() throws Exception { File dataDirectory = new File("./data"); if (dataDirectory.exists()) { FileUtils.deleteDirectory(dataDirectory); } dataDirectory.mkdirs(); } @Override protected void doSetUp() throws Exception { super.doSetUp(); startServer(); putFilesLatch = new CountDownLatch(1); muleContext.registerListener(new EndpointMessageNotificationListener() { public void onNotification(final ServerNotification notification) { EndpointMessageNotification messageNotification = (EndpointMessageNotification) notification; if (messageNotification.getEndpoint().contains("ftp") && "end dispatch".equals(notification.getActionName())) { putFilesLatch.countDown(); } } }); } @Override protected void doTearDown() throws Exception { stopServer(); } @Test public void testCanInsertProducts() throws Exception { FileUtils.copyFileToDirectory(new File("src/test/resources/product.csv"),new File("./data")); assertTrue(putFilesLatch.await(15, TimeUnit.SECONDS)); assertEquals(2, template.queryForList("SELECT * FROM products").size()); } void startServer() { fakeFtpServer = new FakeFtpServer(); fakeFtpServer.setServerControlPort(9879); fakeFtpServer.addUserAccount(new UserAccount("admin", "123456", "/")); FileSystem fileSystem = new UnixFakeFileSystem(); fileSystem.add(new DirectoryEntry("/data/prancingdonkey/catalog")); fakeFtpServer.setFileSystem(fileSystem); fakeFtpServer.start(); DataSource dataSource = muleContext.getRegistry().lookupObject("dataSource"); template = new JdbcTemplate(dataSource); createDatabase(); } void stopServer() { fakeFtpServer.stop(); } private void createDatabase() { try { template.update("DROP TABLE products"); } catch (BadSqlGrammarException ex) { logger.error(ex); } template.update("CREATE TABLE products " + "(id BIGINT NOT NULL, name VARCHAR(256), acv DOUBLE, cost DOUBLE, description VARCHAR(4096))"); } }
31.765217
111
0.696414
121927566e0d9194ebaba8b06cfb8dd557eac418
1,816
package com.aranaira.arcanearchives.items.unused; import com.aranaira.arcanearchives.items.templates.ItemMultistateTemplate; import net.minecraft.client.resources.I18n; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.item.ItemStack; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.List; public class SpiritOrbItem extends ItemMultistateTemplate { public static ItemStack EMPTY, CROWN_MOTE, CROWN_JUVE, CROWN_ELD, MATTER_MOTE, MATTER_JUVE, MATTER_ELD, POWER_MOTE, POWER_JUVE, POWER_ELD, SPACE_MOTE, SPACE_JUVE, SPACE_ELD, TIME_MOTE, TIME_JUVE, TIME_ELD; public SpiritOrbItem () { super("item_spiritorb"); EMPTY = addItem(0, "empty"); CROWN_MOTE = addItem(1, "crown_mote"); CROWN_JUVE = addItem(2, "crown_juve"); CROWN_ELD = addItem(3, "crown_eld"); MATTER_MOTE = addItem(4, "matter_mote"); MATTER_JUVE = addItem(5, "matter_juve"); MATTER_ELD = addItem(6, "matter_eld"); POWER_MOTE = addItem(7, "power_mote"); POWER_JUVE = addItem(8, "power_juve"); POWER_ELD = addItem(9, "power_eld"); SPACE_MOTE = addItem(10, "space_mote"); SPACE_JUVE = addItem(11, "space_juve"); SPACE_ELD = addItem(12, "space_eld"); TIME_MOTE = addItem(13, "time_mote"); TIME_JUVE = addItem(14, "time_juve"); TIME_ELD = addItem(15, "time_eld"); } @Override @SideOnly(Side.CLIENT) public void addInformation (ItemStack stack, World worldIn, List<String> tooltip, ITooltipFlag flagIn) { tooltip.add(TextFormatting.RED + "" + TextFormatting.BOLD + I18n.format("arcanearchives.tooltip.notimplemented1")); tooltip.add(TextFormatting.RED + "" + TextFormatting.ITALIC + I18n.format("arcanearchives.tooltip.notimplemented2")); } }
36.32
206
0.759361
d7ef38f0071b4c7743c8b29071f36752dea8541f
21,013
package gr.uom.java.xmi.decomposition; import com.intellij.psi.*; import gr.uom.java.xmi.Formatter; import gr.uom.java.xmi.LocationInfo; import gr.uom.java.xmi.LocationInfo.CodeElementType; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static gr.uom.java.xmi.decomposition.PsiUtils.isSuperConstructorInvocation; import static gr.uom.java.xmi.decomposition.PsiUtils.isThisConstructorInvocation; public class OperationBody { private final CompositeStatementObject compositeStatement; private List<String> stringRepresentation; private boolean containsAssertion; private Set<VariableDeclaration> activeVariableDeclarations; public OperationBody(PsiFile file, String filePath, PsiCodeBlock codeBlock) { this(file, filePath, codeBlock, Collections.emptyList()); } public OperationBody(PsiFile file, String filePath, PsiCodeBlock codeBlock, List<VariableDeclaration> parameters) { this.compositeStatement = new CompositeStatementObject(file, filePath, codeBlock, 0, CodeElementType.BLOCK); this.activeVariableDeclarations = new HashSet<>(parameters); PsiStatement[] statements = codeBlock.getStatements(); for (PsiStatement statement : statements) { processStatement(file, filePath, compositeStatement, statement); } for (OperationInvocation invocation : getAllOperationInvocations()) { if (invocation.getName().startsWith("assert")) { containsAssertion = true; break; } } this.activeVariableDeclarations = null; } public int statementCount() { return compositeStatement.statementCount(); } public CompositeStatementObject getCompositeStatement() { return compositeStatement; } public boolean containsAssertion() { return containsAssertion; } public List<OperationInvocation> getAllOperationInvocations() { List<OperationInvocation> invocations = new ArrayList<>(); Map<String, List<OperationInvocation>> invocationMap = compositeStatement.getAllMethodInvocations(); for (String key : invocationMap.keySet()) { invocations.addAll(invocationMap.get(key)); } return invocations; } public List<AnonymousClassDeclarationObject> getAllAnonymousClassDeclarations() { return new ArrayList<>(compositeStatement.getAllAnonymousClassDeclarations()); } public List<LambdaExpressionObject> getAllLambdas() { return new ArrayList<>(compositeStatement.getAllLambdas()); } public List<String> getAllVariables() { return new ArrayList<>(compositeStatement.getAllVariables()); } public List<VariableDeclaration> getAllVariableDeclarations() { return new ArrayList<>(compositeStatement.getAllVariableDeclarations()); } public List<VariableDeclaration> getVariableDeclarationsInScope(LocationInfo location) { return new ArrayList<>(compositeStatement.getVariableDeclarationsInScope(location)); } public VariableDeclaration getVariableDeclaration(String variableName) { return compositeStatement.getVariableDeclaration(variableName); } private void processStatement(PsiFile file, String filePath, CompositeStatementObject parent, PsiCodeBlock codeBlock) { CompositeStatementObject blockChild = new CompositeStatementObject(file, filePath, codeBlock, parent.getDepth() + 1, CodeElementType.BLOCK); parent.addStatement(blockChild); addStatementInVariableScopes(blockChild); PsiStatement[] blockStatements = codeBlock.getStatements(); for (PsiStatement blockStatement : blockStatements) { processStatement(file, filePath, blockChild, blockStatement); } } private CodeElementType getCodeElementType(PsiExpression expression) { if (expression instanceof PsiMethodCallExpression) { PsiMethodCallExpression callExpression = (PsiMethodCallExpression) expression; if (isThisConstructorInvocation(callExpression)) { return CodeElementType.CONSTRUCTOR_INVOCATION; } else if (isSuperConstructorInvocation(callExpression)) { return CodeElementType.SUPER_CONSTRUCTOR_INVOCATION; } } return CodeElementType.EXPRESSION_STATEMENT; } private void processStatement(PsiFile file, String filePath, CompositeStatementObject parent, PsiExpression expression) { StatementObject child = new StatementObject(file, filePath, (PsiExpressionStatement) expression.getParent(), parent.getDepth() + 1, getCodeElementType(expression)); parent.addStatement(child); addStatementInVariableScopes(child); } private void processStatement(PsiFile file, String filePath, CompositeStatementObject parent, PsiStatement statement) { if (statement instanceof PsiBlockStatement) { PsiCodeBlock codeBlock = ((PsiBlockStatement) statement).getCodeBlock(); processStatement(file, filePath, parent, codeBlock); } else if (statement instanceof PsiIfStatement) { PsiIfStatement ifStatement = (PsiIfStatement) statement; CompositeStatementObject child = new CompositeStatementObject(file, filePath, ifStatement, parent.getDepth() + 1, CodeElementType.IF_STATEMENT); parent.addStatement(child); AbstractExpression abstractExpression = new AbstractExpression(file, filePath, ifStatement.getCondition(), CodeElementType.IF_STATEMENT_CONDITION); child.addExpression(abstractExpression); addStatementInVariableScopes(child); processStatement(file, filePath, child, ifStatement.getThenBranch()); if (ifStatement.getElseBranch() != null) { processStatement(file, filePath, child, ifStatement.getElseBranch()); } } else if (statement instanceof PsiForStatement) { PsiForStatement forStatement = (PsiForStatement) statement; CompositeStatementObject child = new CompositeStatementObject(file, filePath, forStatement, parent.getDepth() + 1, CodeElementType.FOR_STATEMENT); parent.addStatement(child); PsiStatement initializer = forStatement.getInitialization(); if (initializer != null && !(initializer instanceof PsiEmptyStatement)) { child.addExpression(new AbstractExpression(file, filePath, initializer, CodeElementType.FOR_STATEMENT_INITIALIZER)); } PsiExpression expression = forStatement.getCondition(); if (expression != null) { child.addExpression(new AbstractExpression(file, filePath, expression, CodeElementType.FOR_STATEMENT_CONDITION)); } PsiStatement updater = forStatement.getUpdate(); if (updater != null) { child.addExpression(new AbstractExpression(file, filePath, updater, CodeElementType.FOR_STATEMENT_UPDATER)); } addStatementInVariableScopes(child); List<VariableDeclaration> variableDeclarations = child.getVariableDeclarations(); this.activeVariableDeclarations.addAll(variableDeclarations); processStatement(file, filePath, child, forStatement.getBody()); variableDeclarations.forEach(this.activeVariableDeclarations::remove); } else if (statement instanceof PsiForeachStatement) { PsiForeachStatement foreachStatement = (PsiForeachStatement) statement; CompositeStatementObject child = new CompositeStatementObject(file, filePath, foreachStatement, parent.getDepth() + 1, CodeElementType.ENHANCED_FOR_STATEMENT); parent.addStatement(child); PsiParameter variableDeclaration = foreachStatement.getIterationParameter(); VariableDeclaration vd = new VariableDeclaration(file, filePath, variableDeclaration); child.addVariableDeclaration(vd); AbstractExpression variableDeclarationName = new AbstractExpression(file, filePath, variableDeclaration.getNameIdentifier(), CodeElementType.ENHANCED_FOR_STATEMENT_PARAMETER_NAME); child.addExpression(variableDeclarationName); AbstractExpression abstractExpression = new AbstractExpression(file, filePath, foreachStatement.getIteratedValue(), CodeElementType.ENHANCED_FOR_STATEMENT_EXPRESSION); child.addExpression(abstractExpression); addStatementInVariableScopes(child); List<VariableDeclaration> variableDeclarations = child.getVariableDeclarations(); this.activeVariableDeclarations.addAll(variableDeclarations); processStatement(file, filePath, child, foreachStatement.getBody()); variableDeclarations.forEach(this.activeVariableDeclarations::remove); } else if (statement instanceof PsiWhileStatement) { PsiWhileStatement whileStatement = (PsiWhileStatement) statement; CompositeStatementObject child = new CompositeStatementObject(file, filePath, whileStatement, parent.getDepth() + 1, CodeElementType.WHILE_STATEMENT); parent.addStatement(child); AbstractExpression abstractExpression = new AbstractExpression(file, filePath, whileStatement.getCondition(), CodeElementType.WHILE_STATEMENT_CONDITION); child.addExpression(abstractExpression); addStatementInVariableScopes(child); processStatement(file, filePath, child, whileStatement.getBody()); } else if (statement instanceof PsiDoWhileStatement) { PsiDoWhileStatement doStatement = (PsiDoWhileStatement) statement; CompositeStatementObject child = new CompositeStatementObject(file, filePath, doStatement, parent.getDepth() + 1, CodeElementType.DO_STATEMENT); parent.addStatement(child); AbstractExpression abstractExpression = new AbstractExpression(file, filePath, doStatement.getCondition(), CodeElementType.DO_STATEMENT_CONDITION); child.addExpression(abstractExpression); addStatementInVariableScopes(child); processStatement(file, filePath, child, doStatement.getBody()); } else if (statement instanceof PsiSwitchStatement) { PsiSwitchStatement switchStatement = (PsiSwitchStatement) statement; CompositeStatementObject child = new CompositeStatementObject(file, filePath, switchStatement, parent.getDepth() + 1, CodeElementType.SWITCH_STATEMENT); parent.addStatement(child); AbstractExpression abstractExpression = new AbstractExpression(file, filePath, switchStatement.getExpression(), CodeElementType.SWITCH_STATEMENT_CONDITION); child.addExpression(abstractExpression); addStatementInVariableScopes(child); PsiStatement[] switchStatements = switchStatement.getBody().getStatements(); for (PsiStatement switchStatement2 : switchStatements) processStatement(file, filePath, child, switchStatement2); } else if (statement instanceof PsiSwitchLabelStatement) { PsiSwitchLabelStatement switchCase = (PsiSwitchLabelStatement) statement; StatementObject child = new StatementObject(file, filePath, switchCase, parent.getDepth() + 1, CodeElementType.SWITCH_CASE); parent.addStatement(child); addStatementInVariableScopes(child); } else if (statement instanceof PsiAssertStatement) { PsiAssertStatement assertStatement = (PsiAssertStatement) statement; StatementObject child = new StatementObject(file, filePath, assertStatement, parent.getDepth() + 1, CodeElementType.ASSERT_STATEMENT); parent.addStatement(child); addStatementInVariableScopes(child); } else if (statement instanceof PsiLabeledStatement) { PsiLabeledStatement labeledStatement = (PsiLabeledStatement) statement; CodeElementType elementType = CodeElementType.LABELED_STATEMENT.setName(Formatter.format(labeledStatement.getLabelIdentifier())); CompositeStatementObject child = new CompositeStatementObject(file, filePath, labeledStatement, parent.getDepth() + 1, elementType); parent.addStatement(child); addStatementInVariableScopes(child); processStatement(file, filePath, child, labeledStatement.getStatement()); } else if (statement instanceof PsiReturnStatement) { PsiReturnStatement returnStatement = (PsiReturnStatement) statement; StatementObject child = new StatementObject(file, filePath, returnStatement, parent.getDepth() + 1, CodeElementType.RETURN_STATEMENT); parent.addStatement(child); addStatementInVariableScopes(child); } else if (statement instanceof PsiSynchronizedStatement) { PsiSynchronizedStatement synchronizedStatement = (PsiSynchronizedStatement) statement; CompositeStatementObject child = new CompositeStatementObject(file, filePath, synchronizedStatement, parent.getDepth() + 1, CodeElementType.SYNCHRONIZED_STATEMENT); parent.addStatement(child); AbstractExpression abstractExpression = new AbstractExpression(file, filePath, synchronizedStatement.getLockExpression(), CodeElementType.SYNCHRONIZED_STATEMENT_EXPRESSION); child.addExpression(abstractExpression); addStatementInVariableScopes(child); processStatement(file, filePath, child, synchronizedStatement.getBody()); } else if (statement instanceof PsiThrowStatement) { PsiThrowStatement throwStatement = (PsiThrowStatement) statement; StatementObject child = new StatementObject(file, filePath, throwStatement, parent.getDepth() + 1, CodeElementType.THROW_STATEMENT); parent.addStatement(child); addStatementInVariableScopes(child); } else if (statement instanceof PsiTryStatement) { PsiTryStatement tryStatement = (PsiTryStatement) statement; TryStatementObject child = new TryStatementObject(file, filePath, tryStatement, parent.getDepth() + 1); parent.addStatement(child); PsiResourceList resources = tryStatement.getResourceList(); if (resources != null) { for (PsiResourceListElement resource : resources) { AbstractExpression expression = new AbstractExpression(file, filePath, resource, CodeElementType.TRY_STATEMENT_RESOURCE); child.addExpression(expression); } } addStatementInVariableScopes(child); List<VariableDeclaration> variableDeclarations = child.getVariableDeclarations(); this.activeVariableDeclarations.addAll(variableDeclarations); PsiStatement[] tryStatements = tryStatement.getTryBlock().getStatements(); for (PsiStatement blockStatement : tryStatements) { processStatement(file, filePath, child, blockStatement); } variableDeclarations.forEach(this.activeVariableDeclarations::remove); PsiCatchSection[] catchClauses = tryStatement.getCatchSections(); for (PsiCatchSection catchClause : catchClauses) { PsiParameter variableDeclaration = catchClause.getParameter(); CompositeStatementObject catchClauseStatementObject = new CompositeStatementObject(file, filePath, catchClause.getCatchBlock(), parent.getDepth() + 1, CodeElementType.CATCH_CLAUSE); child.addCatchClause(catchClauseStatementObject); parent.addStatement(catchClauseStatementObject); VariableDeclaration vd = new VariableDeclaration(file, filePath, variableDeclaration); catchClauseStatementObject.addVariableDeclaration(vd); AbstractExpression variableDeclarationName = new AbstractExpression(file, filePath, variableDeclaration.getNameIdentifier(), CodeElementType.CATCH_CLAUSE_EXCEPTION_NAME); catchClauseStatementObject.addExpression(variableDeclarationName); if (variableDeclaration.getInitializer() != null) { AbstractExpression variableDeclarationInitializer = new AbstractExpression(file, filePath, variableDeclaration.getInitializer(), CodeElementType.VARIABLE_DECLARATION_INITIALIZER); catchClauseStatementObject.addExpression(variableDeclarationInitializer); } addStatementInVariableScopes(catchClauseStatementObject); List<VariableDeclaration> catchClauseVariableDeclarations = catchClauseStatementObject.getVariableDeclarations(); this.activeVariableDeclarations.addAll(catchClauseVariableDeclarations); PsiStatement[] blockStatements = catchClause.getCatchBlock().getStatements(); for (PsiStatement blockStatement : blockStatements) { processStatement(file, filePath, catchClauseStatementObject, blockStatement); } catchClauseVariableDeclarations.forEach(this.activeVariableDeclarations::remove); } PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock(); if (finallyBlock != null) { CompositeStatementObject finallyClauseStatementObject = new CompositeStatementObject(file, filePath, finallyBlock, parent.getDepth() + 1, CodeElementType.FINALLY_BLOCK); child.setFinallyClause(finallyClauseStatementObject); parent.addStatement(finallyClauseStatementObject); addStatementInVariableScopes(finallyClauseStatementObject); PsiStatement[] blockStatements = finallyBlock.getStatements(); for (PsiStatement blockStatement : blockStatements) { processStatement(file, filePath, finallyClauseStatementObject, blockStatement); } } } else if (statement instanceof PsiDeclarationStatement) { PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement) statement; // Local classes are not yet supported if (declarationStatement.getDeclaredElements()[0] instanceof PsiVariable) { StatementObject child = new StatementObject(file, filePath, declarationStatement, parent.getDepth() + 1, CodeElementType.VARIABLE_DECLARATION_STATEMENT); parent.addStatement(child); addStatementInVariableScopes(child); this.activeVariableDeclarations.addAll(child.getVariableDeclarations()); } } else if (statement instanceof PsiBreakStatement) { PsiBreakStatement breakStatement = (PsiBreakStatement) statement; StatementObject child = new StatementObject(file, filePath, breakStatement, parent.getDepth() + 1, CodeElementType.BREAK_STATEMENT); parent.addStatement(child); addStatementInVariableScopes(child); } else if (statement instanceof PsiContinueStatement) { PsiContinueStatement continueStatement = (PsiContinueStatement) statement; StatementObject child = new StatementObject(file, filePath, continueStatement, parent.getDepth() + 1, CodeElementType.CONTINUE_STATEMENT); parent.addStatement(child); addStatementInVariableScopes(child); } else if (statement instanceof PsiEmptyStatement) { PsiEmptyStatement emptyStatement = (PsiEmptyStatement) statement; StatementObject child = new StatementObject(file, filePath, emptyStatement, parent.getDepth() + 1, CodeElementType.EMPTY_STATEMENT); parent.addStatement(child); addStatementInVariableScopes(child); } else if (statement instanceof PsiExpressionStatement) { PsiExpressionStatement expressionStatement = (PsiExpressionStatement) statement; processStatement(file, filePath, parent, expressionStatement.getExpression()); } } private void addStatementInVariableScopes(AbstractStatement statement) { for (VariableDeclaration variableDeclaration : activeVariableDeclarations) { variableDeclaration.addStatementInScope(statement); } } public Map<String, Set<String>> aliasedAttributes() { return compositeStatement.aliasedAttributes(); } public CompositeStatementObject loopWithVariables(String currentElementName, String collectionName) { return compositeStatement.loopWithVariables(currentElementName, collectionName); } public List<String> stringRepresentation() { if (stringRepresentation == null) { stringRepresentation = compositeStatement.stringRepresentation(); } return stringRepresentation; } }
62.353116
199
0.717461
b145361be49f01a7d0e08ce57ce33781cf471a23
4,975
package com.goldze.mvvmhabit.ui.info; import android.Manifest; import android.annotation.SuppressLint; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.ViewGroup; import com.goldze.mvvmhabit.BR; import com.goldze.mvvmhabit.R; import com.goldze.mvvmhabit.app.AppViewModelFactory; import com.goldze.mvvmhabit.databinding.FragmentInfoBinding; import com.goldze.mvvmhabit.utils.UriTool; import com.linchaolong.android.imagepicker.ImagePicker; import com.linchaolong.android.imagepicker.cropper.CropImage; import com.linchaolong.android.imagepicker.cropper.CropImageView; import com.tbruyelle.rxpermissions2.RxPermissions; import io.reactivex.functions.Consumer; import me.goldze.mvvmhabit.base.BaseFragment; import me.goldze.mvvmhabit.utils.ToastUtils; public class InfoFragment extends BaseFragment<FragmentInfoBinding, InfoViewModel> { @Override public int initContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return R.layout.fragment_info; } @Override public int initVariableId() { return BR.viewModel; } @Override public InfoViewModel initViewModel() { //使用自定义的ViewModelFactory来创建ViewModel,如果不重写该方法,则默认会调用NetWorkViewModel(@NonNull Application application)构造方法 AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication()); return ViewModelProviders.of(this, factory).get(InfoViewModel.class); } @Override public void initData() { //通过binding拿到toolbar控件, 设置给Activity ((AppCompatActivity) getActivity()).setSupportActionBar(binding.include.toolbar); //初始化标题 viewModel.initToolbar(); // 设置标题 imagePicker.setTitle("设置头像"); // 设置是否裁剪图片 imagePicker.setCropImage(true); } @Override public void initViewObservable() { viewModel.requestPermissions.observe(this, new Observer<Boolean>() { @Override public void onChanged(@Nullable Boolean aBoolean) { requestCameraPermissions(); } }); } @SuppressLint("CheckResult") private void requestCameraPermissions() { //请求打开相机权限 RxPermissions rxPermissions = new RxPermissions(getActivity()); rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE) .subscribe(new Consumer<Boolean>() { @Override public void accept(Boolean aBoolean) throws Exception { if (aBoolean) { startChooser(); } else { ToastUtils.showShort("权限被拒绝"); } } }); } private void startChooser() { // 启动图片选择器 imagePicker.startChooser(this, new ImagePicker.Callback() { // 选择图片回调 @Override public void onPickImage(Uri imageUri) { } // 裁剪图片回调 @Override public void onCropImage(Uri imageUri) { viewModel.initHead(UriTool.getFilePathByUri(getActivity(), imageUri)); } // 自定义裁剪配置 @Override public void cropConfig(CropImage.ActivityBuilder builder) { builder // 是否启动多点触摸 .setMultiTouchEnabled(false) // 设置网格显示模式 .setGuidelines(CropImageView.Guidelines.OFF) // 圆形/矩形 .setCropShape(CropImageView.CropShape.RECTANGLE) .setRequestedSize(640, 640) .setAspectRatio(5, 5); } // 用户拒绝授权回调 @Override public void onPermissionDenied(int requestCode, String[] permissions, int[] grantResults) { } }); } private ImagePicker imagePicker = new ImagePicker(); @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); imagePicker.onActivityResult(this, requestCode, resultCode, data); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); imagePicker.onRequestPermissionsResult(this, requestCode, permissions, grantResults); } }
35.035211
116
0.63799
5e8d8a79c400278e9ccd81fe101b07a3c0095ba5
8,822
package me.alpha432.oyvey.features.modules.combat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Map.Entry; import java.util.concurrent.ConcurrentLinkedQueue; import me.alpha432.oyvey.OyVey; import me.alpha432.oyvey.features.modules.Module; import me.alpha432.oyvey.features.setting.Setting; import me.alpha432.oyvey.util.InventoryUtil; import me.alpha432.oyvey.util.Timer; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.gui.inventory.GuiInventory; import net.minecraft.init.Items; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemExpBottle; import net.minecraft.item.ItemStack; public class AutoArmor extends Module { private final Setting<Integer> delay = this.register(new Setting("Delay", 50, 0, 500)); private final Setting<Boolean> curse = this.register(new Setting("Vanishing", false)); private final Setting<Boolean> mendingTakeOff = this.register(new Setting("AutoMend", false)); private final Setting<Integer> closestEnemy = this.register(new Setting("Enemy", 8, 1, 20, (v) -> { return (Boolean)this.mendingTakeOff.getValue(); })); private final Setting<Integer> repair = this.register(new Setting("Repair%", 80, 1, 100, (v) -> { return (Boolean)this.mendingTakeOff.getValue(); })); private final Setting<Integer> actions = this.register(new Setting("Packets", 3, 1, 12)); private final Timer timer = new Timer(); private final Queue<InventoryUtil.Task> taskList = new ConcurrentLinkedQueue(); private final List<Integer> doneSlots = new ArrayList(); boolean flag; public AutoArmor() { super("AutoArmor", "Puts Armor on for you.", Module.Category.COMBAT, true, false, false); } public void onLogin() { this.timer.reset(); } public void onDisable() { this.taskList.clear(); this.doneSlots.clear(); this.flag = false; } public void onLogout() { this.taskList.clear(); this.doneSlots.clear(); } public void onTick() { if (!fullNullCheck() && (!(mc.field_71462_r instanceof GuiContainer) || mc.field_71462_r instanceof GuiInventory)) { int slot; if (this.taskList.isEmpty()) { if ((Boolean)this.mendingTakeOff.getValue() && InventoryUtil.holdingItem(ItemExpBottle.class) && mc.field_71474_y.field_74313_G.func_151470_d() && mc.field_71441_e.field_73010_i.stream().noneMatch((e) -> { return e != mc.field_71439_g && !OyVey.friendManager.isFriend(e.func_70005_c_()) && mc.field_71439_g.func_70032_d(e) <= (float)(Integer)this.closestEnemy.getValue(); }) && !this.flag) { int takeOff = 0; Iterator var11 = this.getArmor().entrySet().iterator(); int dam; ItemStack itemStack3; float percent; while(var11.hasNext()) { Entry<Integer, ItemStack> armorSlot = (Entry)var11.next(); itemStack3 = (ItemStack)armorSlot.getValue(); percent = (float)(Integer)this.repair.getValue() / 100.0F; dam = Math.round((float)itemStack3.func_77958_k() * percent); if (dam < itemStack3.func_77958_k() - itemStack3.func_77952_i()) { ++takeOff; } } if (takeOff == 4) { this.flag = true; } if (!this.flag) { ItemStack itemStack1 = mc.field_71439_g.field_71069_bz.func_75139_a(5).func_75211_c(); if (!itemStack1.field_190928_g) { float percent = (float)(Integer)this.repair.getValue() / 100.0F; int dam2 = Math.round((float)itemStack1.func_77958_k() * percent); if (dam2 < itemStack1.func_77958_k() - itemStack1.func_77952_i()) { this.takeOffSlot(5); } } ItemStack itemStack2 = mc.field_71439_g.field_71069_bz.func_75139_a(6).func_75211_c(); if (!itemStack2.field_190928_g) { percent = (float)(Integer)this.repair.getValue() / 100.0F; int dam3 = Math.round((float)itemStack2.func_77958_k() * percent); if (dam3 < itemStack2.func_77958_k() - itemStack2.func_77952_i()) { this.takeOffSlot(6); } } itemStack3 = mc.field_71439_g.field_71069_bz.func_75139_a(7).func_75211_c(); if (!itemStack3.field_190928_g) { percent = (float)(Integer)this.repair.getValue() / 100.0F; dam = Math.round((float)itemStack3.func_77958_k() * percent); if (dam < itemStack3.func_77958_k() - itemStack3.func_77952_i()) { this.takeOffSlot(7); } } ItemStack itemStack4 = mc.field_71439_g.field_71069_bz.func_75139_a(8).func_75211_c(); if (!itemStack4.field_190928_g) { float percent = (float)(Integer)this.repair.getValue() / 100.0F; int dam4 = Math.round((float)itemStack4.func_77958_k() * percent); if (dam4 < itemStack4.func_77958_k() - itemStack4.func_77952_i()) { this.takeOffSlot(8); } } } return; } this.flag = false; ItemStack helm = mc.field_71439_g.field_71069_bz.func_75139_a(5).func_75211_c(); int slot4; if (helm.func_77973_b() == Items.field_190931_a && (slot4 = InventoryUtil.findArmorSlot(EntityEquipmentSlot.HEAD, (Boolean)this.curse.getValue(), true)) != -1) { this.getSlotOn(5, slot4); } int slot3; if (mc.field_71439_g.field_71069_bz.func_75139_a(6).func_75211_c().func_77973_b() == Items.field_190931_a && (slot3 = InventoryUtil.findArmorSlot(EntityEquipmentSlot.CHEST, (Boolean)this.curse.getValue(), true)) != -1) { this.getSlotOn(6, slot3); } int slot2; if (mc.field_71439_g.field_71069_bz.func_75139_a(7).func_75211_c().func_77973_b() == Items.field_190931_a && (slot2 = InventoryUtil.findArmorSlot(EntityEquipmentSlot.LEGS, (Boolean)this.curse.getValue(), true)) != -1) { this.getSlotOn(7, slot2); } if (mc.field_71439_g.field_71069_bz.func_75139_a(8).func_75211_c().func_77973_b() == Items.field_190931_a && (slot = InventoryUtil.findArmorSlot(EntityEquipmentSlot.FEET, (Boolean)this.curse.getValue(), true)) != -1) { this.getSlotOn(8, slot); } } if (this.timer.passedMs((long)((int)((float)(Integer)this.delay.getValue() * OyVey.serverManager.getTpsFactor())))) { if (!this.taskList.isEmpty()) { for(slot = 0; slot < (Integer)this.actions.getValue(); ++slot) { InventoryUtil.Task task = (InventoryUtil.Task)this.taskList.poll(); if (task != null) { task.run(); } } } this.timer.reset(); } } } private void takeOffSlot(int slot) { if (this.taskList.isEmpty()) { int target = -1; Iterator var3 = InventoryUtil.findEmptySlots(true).iterator(); while(var3.hasNext()) { int i = (Integer)var3.next(); if (!this.doneSlots.contains(target)) { target = i; this.doneSlots.add(i); } } if (target != -1) { this.taskList.add(new InventoryUtil.Task(slot)); this.taskList.add(new InventoryUtil.Task(target)); this.taskList.add(new InventoryUtil.Task()); } } } private void getSlotOn(int slot, int target) { if (this.taskList.isEmpty()) { this.doneSlots.remove(target); this.taskList.add(new InventoryUtil.Task(target)); this.taskList.add(new InventoryUtil.Task(slot)); this.taskList.add(new InventoryUtil.Task()); } } private Map<Integer, ItemStack> getArmor() { return this.getInventorySlots(5, 8); } private Map<Integer, ItemStack> getInventorySlots(int current, int last) { HashMap fullInventorySlots; for(fullInventorySlots = new HashMap(); current <= last; ++current) { fullInventorySlots.put(current, mc.field_71439_g.field_71069_bz.func_75138_a().get(current)); } return fullInventorySlots; } }
42.210526
232
0.592723
ac96f835142de1a554aac9893382e7343dbd7ac8
294
package com.riiablo.codec.excel; @Excel.Binned public class LowQualityItems extends Excel<LowQualityItems.Entry> { @Excel.Index public static class Entry extends Excel.Entry { @Override public String toString() { return Name; } @Column public String Name; } }
18.375
67
0.697279
588b290d9ab70f140a8ad3e9acf378519172ed56
153
package edgedb.exceptions.clientexception; import edgedb.exceptions.BaseException; public class ConstraintViolationException extends BaseException { }
21.857143
65
0.862745
8111c2fa011d738b71b116feed17f19e4942d9c7
1,479
package ru.sendto.gwt.client.util; import ru.sendto.gwt.client.util.Websocket.ConnectedEvent; import ru.sendto.gwt.client.util.Websocket.DisconnectedEvent; public class WebsocketNotificationUtils { static String iconConnected = "res/connected.png"; static String iconDisconected = "res/disconnected.png"; private WebsocketNotificationUtils() {} public static void init(){}; public static void setIconDisconected(String iconDisconected) { iconDisconected = iconDisconected; } public static void setIconConnected(String iconConnected) { iconConnected = iconConnected; } static{Bus.get().listen(ConnectedEvent.class, WebsocketNotificationUtils::reconnectNotification);} static void reconnectNotification(ConnectedEvent event) { if (Websocket.reconnectNotification != null) { Notifications.close(Websocket.reconnectNotification); Websocket.reconnectNotification = null; Notifications.show("reconnect", "Подключение активно", "Вы снова подключены", WebsocketNotificationUtils.iconConnected, 5000); } } static{Bus.get().listen(DisconnectedEvent.class, WebsocketNotificationUtils::disconnectedNotication);} static void disconnectedNotication(DisconnectedEvent event) { // TODO добавить картиночку для оповещения if (Websocket.reconnectNotification == null) { Websocket.reconnectNotification = Notifications.show("reconnect", "Подключение нарушено", "Переподключение...", WebsocketNotificationUtils.iconDisconected, 0); } } }
34.395349
162
0.790399
7858117659a1c1ae73240825f33167f54ddc0cec
3,937
package cloud.genesys.webmessaging.sdk.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import java.util.Objects; import java.io.IOException; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; /** * UploadFailureEvent */ public class UploadFailureEvent implements Serializable { private String attachmentId = null; private Integer errorCode = null; private String errorMessage = null; private String timestamp = null; /** **/ public UploadFailureEvent attachmentId(String attachmentId) { this.attachmentId = attachmentId; return this; } @ApiModelProperty(example = "null", required = true, value = "") @JsonProperty("attachmentId") public String getAttachmentId() { return attachmentId; } public void setAttachmentId(String attachmentId) { this.attachmentId = attachmentId; } /** **/ public UploadFailureEvent errorCode(Integer errorCode) { this.errorCode = errorCode; return this; } @ApiModelProperty(example = "null", required = true, value = "") @JsonProperty("errorCode") public Integer getErrorCode() { return errorCode; } public void setErrorCode(Integer errorCode) { this.errorCode = errorCode; } /** **/ public UploadFailureEvent errorMessage(String errorMessage) { this.errorMessage = errorMessage; return this; } @ApiModelProperty(example = "null", required = true, value = "") @JsonProperty("errorMessage") public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } /** **/ public UploadFailureEvent timestamp(String timestamp) { this.timestamp = timestamp; return this; } @ApiModelProperty(example = "null", required = true, value = "") @JsonProperty("timestamp") public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UploadFailureEvent uploadFailureEvent = (UploadFailureEvent) o; return Objects.equals(this.attachmentId, uploadFailureEvent.attachmentId) && Objects.equals(this.errorCode, uploadFailureEvent.errorCode) && Objects.equals(this.errorMessage, uploadFailureEvent.errorMessage) && Objects.equals(this.timestamp, uploadFailureEvent.timestamp); } @Override public int hashCode() { return Objects.hash(attachmentId, errorCode, errorMessage, timestamp); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class UploadFailureEvent {\n"); sb.append(" attachmentId: ").append(toIndentedString(attachmentId)).append("\n"); sb.append(" errorCode: ").append(toIndentedString(errorCode)).append("\n"); sb.append(" errorMessage: ").append(toIndentedString(errorMessage)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
27.531469
88
0.701295
14b4943c0e22b2b9389a95d71d7620064af27d8c
2,509
package us.ihmc.sensorProcessing.encoder.processors; import us.ihmc.yoVariables.listener.YoVariableChangedListener; import us.ihmc.yoVariables.registry.YoRegistry; import us.ihmc.yoVariables.variable.YoDouble; import us.ihmc.yoVariables.variable.YoInteger; import us.ihmc.yoVariables.variable.YoVariable; public abstract class AbstractEncoderProcessor implements EncoderProcessor { protected final YoRegistry registry; protected final YoInteger rawTicks; protected final YoDouble time; protected final YoDouble processedTicks; protected final YoDouble processedTickRate; private final YoDouble processedPosition; private final YoDouble processedVelocity; private final String name; public AbstractEncoderProcessor(String name, YoInteger rawTicks, YoDouble time, double distancePerTick, YoRegistry registry) { this.name = name; this.registry = registry; this.rawTicks = rawTicks; this.time = time; this.processedTicks = new YoDouble(name + "ProcTicks", registry); this.processedTickRate = new YoDouble(name + "ProcTickRate", registry); this.processedPosition = new YoDouble(name + "ProcPos", registry); this.processedVelocity = new YoDouble(name + "ProcVel", registry); processedTicks.addListener(new MultiplicationVariableChangedListener(processedPosition, distancePerTick)); processedTickRate.addListener(new MultiplicationVariableChangedListener(processedVelocity, distancePerTick)); } public final double getQ() { return processedPosition.getDoubleValue(); } public final double getQd() { return processedVelocity.getDoubleValue(); } public abstract void initialize(); public abstract void update(); private static final class MultiplicationVariableChangedListener implements YoVariableChangedListener { private final YoVariable output; private final double multiplicationFactor; public MultiplicationVariableChangedListener(YoVariable output, double multiplicationFactor) { this.output = output; this.multiplicationFactor = multiplicationFactor; } public void changed(YoVariable variable) { output.setValueFromDouble(variable.getValueAsDouble() * multiplicationFactor); } } public YoRegistry getYoRegistry() { return null; } public String getName() { return name; } public String getDescription() { return name; } }
29.174419
127
0.737744
acae55e370b429e575d11a01eaa5d8ba3f33408e
2,139
package org.apitooling.model.stats; public class Stats { private int paths = 0; private int operations = 0; private int getOperations = 0; private int postOperations = 0; private int putOperations = 0; private int deleteOperations = 0; private int patchOperations = 0; private int totPathParams = 0; private int totHeaderAttrs = 0; private int totQueryParams = 0; private int totExamples= 0; public Stats() { // TODO Auto-generated constructor stub } public int getPaths() { return paths; } public void incPaths() { this.paths++; } public int getOperations() { return operations; } public void incOperations(String method) { this.operations++; if ("GET".equalsIgnoreCase(method)) { this.getOperations++; } if ("POST".equalsIgnoreCase(method)) { this.postOperations++; } if ("PUT".equalsIgnoreCase(method)) { this.putOperations++; } if ("DELETE".equalsIgnoreCase(method)) { this.deleteOperations++; } if ("PATCH".equalsIgnoreCase(method)) { this.patchOperations++; } } public int getHttpGetOperations() { return getOperations; } public int getHttpPostOperations() { return postOperations; } public int getHttpPutOperations() { return putOperations; } public int getHttpDeleteOperations() { return deleteOperations; } public int getHttpPatchOperations() { return patchOperations; } public double getAvgPathParamsPerOperation() { return totPathParams / operations; } public void incPathParams() { this.totPathParams++; } public double getAvgHeaderAttrsPerOperation() { return totHeaderAttrs / operations; } public void incHeaderAttrs() { this.totHeaderAttrs++; } public double getAvgQueryParamsPerOperation() { return totQueryParams / operations; } public void incQueryParams() { this.totQueryParams++; } public double getAvgExamplesPerOperation() { return totExamples / operations; } public void incExamples() { this.totExamples++; } public void incExamples(int size) { this.totExamples += size; } }
20.371429
49
0.681159
d316ee0853aea85a1f355009cfdfeae97d5323e1
2,269
package it.mulders.futbolin.webapp.security; import lombok.extern.slf4j.Slf4j; import javax.inject.Inject; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.security.Principal; import java.util.HashMap; import java.util.Map; @Slf4j @WebFilter(urlPatterns = "/app/*") public class EnhancedPrincipalFilter extends HttpFilter { private final transient Map<Principal, FutbolinPrincipal> userCache = new HashMap<>(); @Inject FutbolinPrincipalExtractor extractor; @Override public void init(final FilterConfig filterConfig) { // Nothing to do here. } @Override protected void doFilter(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException { var originalPrincipal = request.getUserPrincipal(); if (originalPrincipal == null) { log.debug("Request does not have user principal, continuing"); chain.doFilter(request, response); return; } else if (originalPrincipal instanceof FutbolinPrincipal) { log.debug("Request user principal is already of expected type, continuing"); chain.doFilter(request, response); return; } userCache.computeIfAbsent(originalPrincipal, this::createFutbolinPrincipal); var replacedPrincipal = userCache.get(originalPrincipal); var wrappedRequest = new HttpServletRequestWrapper(request) { @Override public Principal getUserPrincipal() { return replacedPrincipal; } }; chain.doFilter(wrappedRequest, response); } private FutbolinPrincipal createFutbolinPrincipal(final Principal originalPrincipal) { return extractor.extractFutbolinPrincipal(); } @Override public void destroy() { this.userCache.clear(); } }
32.414286
91
0.699427
99d628ac33a63d78c4711772b7ca59c7d5f13509
6,143
package net.minecraft.client.renderer.tileentity; import java.nio.FloatBuffer; import java.util.Random; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ActiveRenderInfo; import net.minecraft.client.renderer.GLAllocation; import net.minecraft.client.renderer.Tessellator; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityEndPortal; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; public class RenderEndPortal extends TileEntitySpecialRenderer { private static final ResourceLocation field_147529_c = new ResourceLocation("textures/environment/end_sky.png"); private static final ResourceLocation field_147526_d = new ResourceLocation("textures/entity/end_portal.png"); private static final Random field_147527_e = new Random(31100L); FloatBuffer field_147528_b = GLAllocation.createDirectFloatBuffer(16); private static final String __OBFID = "CL_00000972"; public void renderTileEntityAt(TileEntityEndPortal p_147524_1_, double p_147524_2_, double p_147524_4_, double p_147524_6_, float p_147524_8_) { float var9 = (float)this.field_147501_a.field_147560_j; float var10 = (float)this.field_147501_a.field_147561_k; float var11 = (float)this.field_147501_a.field_147558_l; GL11.glDisable(GL11.GL_LIGHTING); field_147527_e.setSeed(31100L); float var12 = 0.75F; for (int var13 = 0; var13 < 16; ++var13) { GL11.glPushMatrix(); float var14 = (float)(16 - var13); float var15 = 0.0625F; float var16 = 1.0F / (var14 + 1.0F); if (var13 == 0) { this.bindTexture(field_147529_c); var16 = 0.1F; var14 = 65.0F; var15 = 0.125F; GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); } if (var13 == 1) { this.bindTexture(field_147526_d); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE); var15 = 0.5F; } float var17 = (float)(-(p_147524_4_ + (double)var12)); float var18 = var17 + ActiveRenderInfo.objectY; float var19 = var17 + var14 + ActiveRenderInfo.objectY; float var20 = var18 / var19; var20 += (float)(p_147524_4_ + (double)var12); GL11.glTranslatef(var9, var20, var11); GL11.glTexGeni(GL11.GL_S, GL11.GL_TEXTURE_GEN_MODE, GL11.GL_OBJECT_LINEAR); GL11.glTexGeni(GL11.GL_T, GL11.GL_TEXTURE_GEN_MODE, GL11.GL_OBJECT_LINEAR); GL11.glTexGeni(GL11.GL_R, GL11.GL_TEXTURE_GEN_MODE, GL11.GL_OBJECT_LINEAR); GL11.glTexGeni(GL11.GL_Q, GL11.GL_TEXTURE_GEN_MODE, GL11.GL_EYE_LINEAR); GL11.glTexGen(GL11.GL_S, GL11.GL_OBJECT_PLANE, this.func_147525_a(1.0F, 0.0F, 0.0F, 0.0F)); GL11.glTexGen(GL11.GL_T, GL11.GL_OBJECT_PLANE, this.func_147525_a(0.0F, 0.0F, 1.0F, 0.0F)); GL11.glTexGen(GL11.GL_R, GL11.GL_OBJECT_PLANE, this.func_147525_a(0.0F, 0.0F, 0.0F, 1.0F)); GL11.glTexGen(GL11.GL_Q, GL11.GL_EYE_PLANE, this.func_147525_a(0.0F, 1.0F, 0.0F, 0.0F)); GL11.glEnable(GL11.GL_TEXTURE_GEN_S); GL11.glEnable(GL11.GL_TEXTURE_GEN_T); GL11.glEnable(GL11.GL_TEXTURE_GEN_R); GL11.glEnable(GL11.GL_TEXTURE_GEN_Q); GL11.glPopMatrix(); GL11.glMatrixMode(GL11.GL_TEXTURE); GL11.glPushMatrix(); GL11.glLoadIdentity(); GL11.glTranslatef(0.0F, (float)(Minecraft.getSystemTime() % 700000L) / 700000.0F, 0.0F); GL11.glScalef(var15, var15, var15); GL11.glTranslatef(0.5F, 0.5F, 0.0F); GL11.glRotatef((float)(var13 * var13 * 4321 + var13 * 9) * 2.0F, 0.0F, 0.0F, 1.0F); GL11.glTranslatef(-0.5F, -0.5F, 0.0F); GL11.glTranslatef(-var9, -var11, -var10); var18 = var17 + ActiveRenderInfo.objectY; GL11.glTranslatef(ActiveRenderInfo.objectX * var14 / var18, ActiveRenderInfo.objectZ * var14 / var18, -var10); Tessellator var23 = Tessellator.instance; var23.startDrawingQuads(); var20 = field_147527_e.nextFloat() * 0.5F + 0.1F; float var21 = field_147527_e.nextFloat() * 0.5F + 0.4F; float var22 = field_147527_e.nextFloat() * 0.5F + 0.5F; if (var13 == 0) { var22 = 1.0F; var21 = 1.0F; var20 = 1.0F; } var23.setColorRGBA_F(var20 * var16, var21 * var16, var22 * var16, 1.0F); var23.addVertex(p_147524_2_, p_147524_4_ + (double)var12, p_147524_6_); var23.addVertex(p_147524_2_, p_147524_4_ + (double)var12, p_147524_6_ + 1.0D); var23.addVertex(p_147524_2_ + 1.0D, p_147524_4_ + (double)var12, p_147524_6_ + 1.0D); var23.addVertex(p_147524_2_ + 1.0D, p_147524_4_ + (double)var12, p_147524_6_); var23.draw(); GL11.glPopMatrix(); GL11.glMatrixMode(GL11.GL_MODELVIEW); } GL11.glDisable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_TEXTURE_GEN_S); GL11.glDisable(GL11.GL_TEXTURE_GEN_T); GL11.glDisable(GL11.GL_TEXTURE_GEN_R); GL11.glDisable(GL11.GL_TEXTURE_GEN_Q); GL11.glEnable(GL11.GL_LIGHTING); } private FloatBuffer func_147525_a(float p_147525_1_, float p_147525_2_, float p_147525_3_, float p_147525_4_) { this.field_147528_b.clear(); this.field_147528_b.put(p_147525_1_).put(p_147525_2_).put(p_147525_3_).put(p_147525_4_); this.field_147528_b.flip(); return this.field_147528_b; } public void renderTileEntityAt(TileEntity p_147500_1_, double p_147500_2_, double p_147500_4_, double p_147500_6_, float p_147500_8_) { this.renderTileEntityAt((TileEntityEndPortal)p_147500_1_, p_147500_2_, p_147500_4_, p_147500_6_, p_147500_8_); } }
47.253846
146
0.642357
5daa66d55dc8653bfb2e66b03c84b98b755ac5c5
321
// Temperature In C AND F import java.util.Scanner; public class Main { public static void main(String[] args) { System.out.print("Temperature in C : "); Scanner in = new Scanner(System.in); float temC= in.nextFloat(); float temF=(temC * 9/5) + 32 ; System.out.println("Temperature In F : " + temF); } }
21.4
51
0.654206
5bb783f933995e30ca2cfaf3e6aa7326b18f9797
395
package net.poollovernathan.brewery; public interface IEnergyItem { int insertEnergy(int amount, boolean dry); int extractEnergy(int amount, boolean dry); boolean insertEnergyBlock(int amount, boolean dry); boolean extractEnergyBlock(int amount, boolean dry); int transferEnergy(IEnergyItem destination, boolean dry); int peekEnergy(); int getMaxEnergy(); }
32.916667
62
0.736709
6cec19acf62833976fce27aa51085d9f205e3313
6,333
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.master.security.impl; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.AssertJUnit.assertEquals; import java.util.Collection; import javax.time.Instant; import org.testng.annotations.Test; import com.opengamma.DataNotFoundException; import com.opengamma.core.security.Security; import com.opengamma.id.ExternalId; import com.opengamma.id.ExternalIdBundle; import com.opengamma.id.ObjectId; import com.opengamma.id.UniqueId; import com.opengamma.id.VersionCorrection; import com.opengamma.master.security.ManageableSecurity; import com.opengamma.master.security.SecurityDocument; import com.opengamma.master.security.SecurityMaster; import com.opengamma.master.security.SecuritySearchRequest; import com.opengamma.master.security.SecuritySearchResult; /** * Test {@link MasterSecuritySource}. */ @Test public class MasterSecuritySourceTest { private static final ObjectId OID = ObjectId.of("A", "B"); private static final UniqueId UID = UniqueId.of("A", "B", "V"); private static final ExternalId ID1 = ExternalId.of("C", "D"); private static final ExternalId ID2 = ExternalId.of("E", "F"); private static final ExternalIdBundle BUNDLE = ExternalIdBundle.of(ID1, ID2); private static final Instant NOW = Instant.now(); private static final VersionCorrection VC = VersionCorrection.of(NOW.minusSeconds(2), NOW.minusSeconds(1)); @Test(expectedExceptions = IllegalArgumentException.class) public void test_constructor_1arg_nullMaster() throws Exception { new MasterSecuritySource(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void test_constructor_2arg_nullMaster() throws Exception { new MasterSecuritySource(null, null); } //------------------------------------------------------------------------- public void test_getSecurity_UniqueId_noOverride_found() throws Exception { SecurityMaster mock = mock(SecurityMaster.class); SecurityDocument doc = new SecurityDocument(example()); when(mock.get(UID)).thenReturn(doc); MasterSecuritySource test = new MasterSecuritySource(mock); Security testResult = test.getSecurity(UID); verify(mock, times(1)).get(UID); assertEquals(example(), testResult); } public void test_getSecurity_UniqueId_found() throws Exception { SecurityMaster mock = mock(SecurityMaster.class); SecurityDocument doc = new SecurityDocument(example()); when(mock.get(OID, VC)).thenReturn(doc); MasterSecuritySource test = new MasterSecuritySource(mock, VC); Security testResult = test.getSecurity(UID); verify(mock, times(1)).get(OID, VC); assertEquals(example(), testResult); } @Test(expectedExceptions = DataNotFoundException.class) public void test_getSecurity_UniqueId_notFound() throws Exception { SecurityMaster mock = mock(SecurityMaster.class); when(mock.get(OID, VC)).thenThrow(new DataNotFoundException("")); MasterSecuritySource test = new MasterSecuritySource(mock, VC); try { test.getSecurity(UID); } finally { verify(mock, times(1)).get(OID, VC); } } //------------------------------------------------------------------------- public void test_getSecurity_ObjectId_found() throws Exception { SecurityMaster mock = mock(SecurityMaster.class); SecurityDocument doc = new SecurityDocument(example()); when(mock.get(OID, VC)).thenReturn(doc); MasterSecuritySource test = new MasterSecuritySource(mock, VC); Security testResult = test.getSecurity(OID, VC); verify(mock, times(1)).get(OID, VC); assertEquals(example(), testResult); } @Test(expectedExceptions = DataNotFoundException.class) public void test_getSecurity_ObjectId_notFound() throws Exception { SecurityMaster mock = mock(SecurityMaster.class); when(mock.get(OID, VC)).thenThrow(new DataNotFoundException("")); MasterSecuritySource test = new MasterSecuritySource(mock, VC); try { test.getSecurity(OID, VC); } finally { verify(mock, times(1)).get(OID, VC); } } //------------------------------------------------------------------------- public void test_getSecuritiesByExternalIdBundle() throws Exception { SecurityMaster mock = mock(SecurityMaster.class); SecuritySearchRequest request = new SecuritySearchRequest(); request.addExternalId(ID1); request.addExternalId(ID2); request.setVersionCorrection(VC); ManageableSecurity security = example(); SecuritySearchResult result = new SecuritySearchResult(); result.getDocuments().add(new SecurityDocument(security)); when(mock.search(request)).thenReturn(result); MasterSecuritySource test = new MasterSecuritySource(mock, VC); Collection<Security> testResult = test.getSecurities(BUNDLE); verify(mock, times(1)).search(request); assertEquals(UID, testResult.iterator().next().getUniqueId()); assertEquals("Test", testResult.iterator().next().getName()); } //------------------------------------------------------------------------- public void test_getSecurity_ExternalId() throws Exception { SecurityMaster mock = mock(SecurityMaster.class); SecuritySearchRequest request = new SecuritySearchRequest(); request.addExternalId(ID1); request.addExternalId(ID2); request.setVersionCorrection(VC); ManageableSecurity security = example(); SecuritySearchResult result = new SecuritySearchResult(); result.getDocuments().add(new SecurityDocument(security)); when(mock.search(request)).thenReturn(result); MasterSecuritySource test = new MasterSecuritySource(mock, VC); Security testResult = test.getSecurity(BUNDLE); verify(mock, times(1)).search(request); assertEquals(UID, testResult.getUniqueId()); assertEquals("Test", testResult.getName()); } //------------------------------------------------------------------------- protected ManageableSecurity example() { return new ManageableSecurity(UID, "Test", "EQUITY", ExternalIdBundle.EMPTY); } }
37.922156
109
0.698563
5c7fc6ff8cc457b93d74e45fe0edf8b2010cdbbb
3,980
/* * 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 universistant.controllers; import java.sql.*; //import com.mysql.jdbc.PreparedStatement; import java.sql.PreparedStatement; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javax.swing.JOptionPane; /** * FXML Controller class * * @author USER */ public class LoginController implements Initializable { @FXML private Text Universistant; @FXML private ImageView Logo; @FXML private TextField Username_TextField; @FXML private PasswordField Password_TextField; @FXML private Button SignIn_Button; @FXML private AnchorPane background; Connection con; PreparedStatement pst; public static String CurrentUser= " "; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO } @FXML private void click_SignIn(ActionEvent event) throws IOException, ClassNotFoundException, SQLException { boolean flag=false; boolean flagx=false; String uname = Username_TextField.getText(); String pass = Password_TextField.getText(); if(uname.equals("") || pass.equals("")) { JOptionPane.showMessageDialog(null, "Username or Password blank"); flagx=true; } if(!flagx) { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost/universistantdb", "root","root"); Statement st = con.createStatement(); ResultSet res = st.executeQuery("SELECT * FROM login"); while(res.next()) { String name=res.getString("Name"); String passw=res.getString("Password"); int role=res.getInt("Role"); if(name.equals(uname) && passw.equals(pass)) { flag=true; CurrentUser=uname; if(role==1) { AnchorPane pane = FXMLLoader.load(getClass().getResource("/resources/fxml/admin_dashboard.fxml")); background.getChildren().setAll(pane); } else if(role==2) { AnchorPane pane = FXMLLoader.load(getClass().getResource("/resources/fxml/teacher_dashboard.fxml")); background.getChildren().setAll(pane); } else { AnchorPane pane = FXMLLoader.load(getClass().getResource("/resources/fxml/student_dashboard.fxml")); background.getChildren().setAll(pane); } } } } if(!flag && !flagx) { JOptionPane.showMessageDialog(null, "Wrong Username or Password"); } } }
30.615385
125
0.549246
4b171a0b759f9d0616d978da4fc1d68bfd650144
3,527
/* * The MIT License (MIT) * * Copyright (c) 2017: * Ethan Brooks (CalmBit), * and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.elytradev.ville.inventory; import com.elytradev.concrete.inventory.gui.ConcreteContainer; import com.elytradev.concrete.inventory.gui.widget.WItemSlot; import com.elytradev.concrete.inventory.gui.widget.WPlainPanel; import com.elytradev.ville.entity.IExtendedMerchant; import com.elytradev.ville.gui.WExtendedMerchantResultSlot; import com.elytradev.ville.gui.WItemImage; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; public class ContainerExtendedMerchant extends ConcreteContainer { private IExtendedMerchant merchant; private InventoryExtendedMerchant merchantInventory; private World world; public ContainerExtendedMerchant(InventoryPlayer playerInventory, IExtendedMerchant merchant, InventoryExtendedMerchant merchantInventory, World world) { super(playerInventory, merchantInventory); this.merchant = merchant; this.merchantInventory = merchantInventory; this.world = world; WPlainPanel panel = new WPlainPanel(); this.setRootPanel(panel); panel.add(WItemSlot.of(this.merchantInventory, 0), 36, 53); panel.add(WItemSlot.of(this.merchantInventory, 1), 62, 53); panel.add(new WExtendedMerchantResultSlot(merchant, merchantInventory, 2), 120, 53); panel.add(WItemSlot.ofPlayerStorage(playerInventory), 0, 84); panel.add(WItemSlot.of(playerInventory, 0, 9, 1), 0, 144); panel.add(new WItemImage(), 36, 24); panel.add(new WItemImage(), 62, 24); panel.add(new WItemImage(), 120, 24); } @Override public boolean canInteractWith(EntityPlayer playerIn) { return true; } public void onContainerClosed(EntityPlayer playerIn) { super.onContainerClosed(playerIn); this.merchant.setCustomer(null); if (!this.world.isRemote) { ItemStack itemStack = this.merchantInventory.removeStackFromSlot(0); if (!itemStack.isEmpty()) playerIn.dropItem(itemStack, false); itemStack = this.merchantInventory.removeStackFromSlot(1); if (!itemStack.isEmpty()) playerIn.dropItem(itemStack, false); } } }
37.924731
157
0.720726
df05f14bd1c3bfed7a2c8a3885dbacb7021e04e5
38,428
package com.mcgrady.xtitlebar; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Build; import androidx.annotation.NonNull; import android.text.TextUtils; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.mcgrady.xtitlebar.util.Utils; /** * Created by mcgrady on 2019/1/22. */ public class TitleBar extends RelativeLayout implements View.OnClickListener { private View viewStatusBarFill; // 状态栏填充视图 private View viewBottomLine; // 分隔线视图 private View viewBottomShadow; // 底部阴影 private RelativeLayout rlMain; // 主视图 private TextView tvLeft; // 左边TextView private ImageButton btnLeft; // 左边ImageButton private View viewCustomLeft; private TextView tvRight; // 右边TextView private ImageButton btnRight; // 右边ImageButton private View viewCustomRight; private LinearLayout llMainCenter; private TextView tvCenter; // 标题栏文字 private TextView tvCenterSub; // 副标题栏文字 private ProgressBar progressCenter; // 中间进度条,默认隐藏 private RelativeLayout rlMainCenterSearch; // 中间搜索框布局 private EditText etSearchHint; private ImageView ivSearch; private ImageView ivVoice; private View centerCustomView; // 中间自定义视图 private boolean fillStatusBar; // 是否撑起状态栏, true时,标题栏浸入状态栏 private int titleBarColor; // 标题栏背景颜色 private int titleBarHeight; // 标题栏高度 private int statusBarColor; // 状态栏颜色 private boolean showBottomLine; // 是否显示底部分割线 private int bottomLineColor; // 分割线颜色 private float bottomShadowHeight; // 底部阴影高度 private int leftType; // 左边视图类型 private String leftText; // 左边TextView文字 private int leftTextColor; // 左边TextView颜色 private float leftTextSize; // 左边TextView文字大小 private int leftDrawable; // 左边TextView drawableLeft资源 private float leftDrawablePadding; // 左边TextView drawablePadding private int leftImageResource; // 左边图片资源 private Drawable leftBackgroundDrawable; // 左边背景资源 private int leftCustomViewRes; // 左边自定义视图布局资源 private int rightType; // 右边视图类型 private String rightText; // 右边TextView文字 private int rightTextColor; // 右边TextView颜色 private float rightTextSize; // 右边TextView文字大小 private int rightImageResource; // 右边图片资源 private Drawable rightBackgroundDrawable; // 右边背景资源 private int rightCustomViewRes; // 右边自定义视图布局资源 private int centerType; // 中间视图类型 private String centerText; // 中间TextView文字 private int centerTextColor; // 中间TextView字体颜色 private float centerTextSize; // 中间TextView字体大小 private boolean centerTextMarquee; // 中间TextView字体是否显示跑马灯效果 private String centerSubText; // 中间subTextView文字 private int centerSubTextColor; // 中间subTextView字体颜色 private float centerSubTextSize; // 中间subTextView字体大小 private boolean centerSearchEditable; // 搜索框是否可输入 private int centerSearchBgResource; // 搜索框背景图片 private int centerSearchRightType; // 搜索框右边按钮类型 0: voice 1: delete private int centerCustomViewRes; // 中间自定义布局资源 private int PADDING_5; private int PADDING_12; private int MATCH_PARENT; private int WRAP_CONTENT; private OnTitleBarListener listener; private OnTitleBarDoubleClickListener doubleClickListener; private static final int TYPE_LEFT_NONE = 0; private static final int TYPE_LEFT_TEXTVIEW = 1; private static final int TYPE_LEFT_IMAGEBUTTON = 2; private static final int TYPE_LEFT_CUSTOM_VIEW = 3; private static final int TYPE_RIGHT_NONE = 0; private static final int TYPE_RIGHT_TEXTVIEW = 1; private static final int TYPE_RIGHT_IMAGEBUTTON = 2; private static final int TYPE_RIGHT_CUSTOM_VIEW = 3; private static final int TYPE_CENTER_NONE = 0; private static final int TYPE_CENTER_TEXTVIEW = 1; private static final int TYPE_CENTER_SEARCHVIEW = 2; private static final int TYPE_CENTER_CUSTOM_VIEW = 3; private static final int TYPE_CENTER_SEARCH_RIGHT_VOICE = 0; private static final int TYPE_CENTER_SEARCH_RIGHT_DELETE = 1; public TitleBar(Context context, AttributeSet attrs) { super(context, attrs); loadAttributes(context, attrs, 0); initGlobalViews(context); initMainViews(context); } public TitleBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); loadAttributes(context, attrs, defStyleAttr); initGlobalViews(context); initMainViews(context); } { PADDING_5 = Utils.dp2px(5.0f); PADDING_12 = Utils.dp2px(12.0f); MATCH_PARENT = ViewGroup.LayoutParams.MATCH_PARENT; WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT; } private void loadAttributes(Context context, AttributeSet attrs, int defStyleAttr) { TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.XTitleBar, defStyleAttr, R.style.TitleBarDefaultStyle); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // notice 未引入沉浸式标题栏之前,隐藏标题栏撑起布局 fillStatusBar = array.getBoolean(R.styleable.XTitleBar_fillStatusBar, false); } titleBarColor = array.getColor(R.styleable.XTitleBar_titleBarColor, 0); titleBarHeight = (int) array.getDimension(R.styleable.XTitleBar_titleBarHeight, Utils.dp2px(56)); statusBarColor = array.getColor(R.styleable.XTitleBar_statusBarColor, 0); showBottomLine = array.getBoolean(R.styleable.XTitleBar_showBottomLine, false); bottomLineColor = array.getColor(R.styleable.XTitleBar_bottomLineColor, 0); bottomShadowHeight = array.getDimension(R.styleable.XTitleBar_bottomShadowHeight, Utils.dp2px(0)); leftType = array.getInt(R.styleable.XTitleBar_leftType, TYPE_LEFT_NONE); if (leftType == TYPE_LEFT_TEXTVIEW) { leftText = array.getString(R.styleable.XTitleBar_leftText); leftTextColor = array.getColor(R.styleable.XTitleBar_leftTextColor, 0); leftTextSize = array.getDimension(R.styleable.XTitleBar_leftTextSize, 0); leftDrawable = array.getResourceId(R.styleable.XTitleBar_leftDrawable, 0); leftDrawablePadding = array.getDimension(R.styleable.XTitleBar_leftDrawablePadding, 5); leftBackgroundDrawable = array.getDrawable(R.styleable.XTitleBar_leftBackgroundDrawable); } else if (leftType == TYPE_LEFT_IMAGEBUTTON) { leftImageResource = array.getResourceId(R.styleable.XTitleBar_leftImageResource, 0); leftBackgroundDrawable = array.getDrawable(R.styleable.XTitleBar_leftBackgroundDrawable); } else if (leftType == TYPE_LEFT_CUSTOM_VIEW) { leftCustomViewRes = array.getResourceId(R.styleable.XTitleBar_leftCustomView, 0); } rightType = array.getInt(R.styleable.XTitleBar_rightType, TYPE_RIGHT_NONE); if (rightType == TYPE_RIGHT_TEXTVIEW) { rightText = array.getString(R.styleable.XTitleBar_rightText); rightTextColor = array.getColor(R.styleable.XTitleBar_rightTextColor, 0); rightTextSize = array.getDimension(R.styleable.XTitleBar_rightTextSize, 0); rightBackgroundDrawable = array.getDrawable(R.styleable.XTitleBar_rightBackgroundDrawable); } else if (rightType == TYPE_RIGHT_IMAGEBUTTON) { rightImageResource = array.getResourceId(R.styleable.XTitleBar_rightImageResource, 0); rightBackgroundDrawable = array.getDrawable(R.styleable.XTitleBar_rightBackgroundDrawable); } else if (rightType == TYPE_RIGHT_CUSTOM_VIEW) { rightCustomViewRes = array.getResourceId(R.styleable.XTitleBar_rightCustomView, 0); } centerType = array.getInt(R.styleable.XTitleBar_centerType, TYPE_CENTER_NONE); if (centerType == TYPE_CENTER_TEXTVIEW) { centerText = array.getString(R.styleable.XTitleBar_centerText); centerTextColor = array.getColor(R.styleable.XTitleBar_centerTextColor, 0); centerTextSize = array.getDimension(R.styleable.XTitleBar_centerTextSize, 0); centerTextMarquee = array.getBoolean(R.styleable.XTitleBar_centerTextMarquee, true); centerSubText = array.getString(R.styleable.XTitleBar_centerSubText); centerSubTextColor = array.getColor(R.styleable.XTitleBar_centerSubTextColor, 0); centerSubTextSize = array.getDimension(R.styleable.XTitleBar_centerSubTextSize, 0); } else if (centerType == TYPE_CENTER_SEARCHVIEW) { centerSearchEditable = array.getBoolean(R.styleable.XTitleBar_centerSearchEditable, true); centerSearchBgResource = array.getResourceId(R.styleable.XTitleBar_centerSearchBg, 0); centerSearchRightType = array.getInt(R.styleable.XTitleBar_centerSearchRightType, TYPE_CENTER_SEARCH_RIGHT_VOICE); } else if (centerType == TYPE_CENTER_CUSTOM_VIEW) { centerCustomViewRes = array.getResourceId(R.styleable.XTitleBar_centerCustomView, 0); } array.recycle(); } /** * 初始化全局视图 * * @param context 上下文 */ private void initGlobalViews(Context context) { ViewGroup.LayoutParams globalParams = new ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT); setLayoutParams(globalParams); boolean transparentStatusBar = Utils.supportTransparentStatusBar(); // 构建标题栏填充视图 if (fillStatusBar && transparentStatusBar) { int statusBarHeight = Utils.getStatusBarHeight(); viewStatusBarFill = ViewCore.newView(context); viewStatusBarFill.setBackgroundColor(statusBarColor); LayoutParams statusBarParams = new LayoutParams(MATCH_PARENT, statusBarHeight); statusBarParams.addRule(RelativeLayout.ALIGN_PARENT_TOP); addView(viewStatusBarFill, statusBarParams); } // 构建主视图 rlMain = ViewCore.newRelativeLayout(context); rlMain.setBackgroundColor(titleBarColor); LayoutParams mainParams = new LayoutParams(MATCH_PARENT, titleBarHeight); if (fillStatusBar && transparentStatusBar) { mainParams.addRule(RelativeLayout.BELOW, viewStatusBarFill.getId()); } else { mainParams.addRule(RelativeLayout.ALIGN_PARENT_TOP); } // 计算主布局高度 if (showBottomLine) { mainParams.height = titleBarHeight - Math.max(1, Utils.dp2px(0.4f)); } else { mainParams.height = titleBarHeight; } addView(rlMain, mainParams); // 构建分割线视图 if (showBottomLine) { // 已设置显示标题栏分隔线,5.0以下机型,显示分隔线 viewBottomLine = new View(context); viewBottomLine.setBackgroundColor(bottomLineColor); LayoutParams bottomLineParams = new LayoutParams(MATCH_PARENT, Math.max(1, Utils.dp2px(0.4f))); bottomLineParams.addRule(RelativeLayout.BELOW, rlMain.getId()); addView(viewBottomLine, bottomLineParams); } else if (bottomShadowHeight != 0) { viewBottomShadow = new View(context); viewBottomShadow.setBackgroundResource(R.drawable.xtitlebar_bottom_shadow); LayoutParams bottomShadowParams = new LayoutParams(MATCH_PARENT, Utils.dp2px(bottomShadowHeight)); bottomShadowParams.addRule(RelativeLayout.BELOW, rlMain.getId()); addView(viewBottomShadow, bottomShadowParams); } } /** * 初始化主视图 * * @param context 上下文 */ private void initMainViews(Context context) { if (leftType != TYPE_LEFT_NONE) { initMainLeftViews(context); } if (rightType != TYPE_RIGHT_NONE) { initMainRightViews(context); } if (centerType != TYPE_CENTER_NONE) { initMainCenterViews(context); } } /** * 初始化主视图左边部分 * -- add: adaptive RTL * @param context 上下文 */ private void initMainLeftViews(Context context) { LayoutParams leftInnerParams = new LayoutParams(WRAP_CONTENT, MATCH_PARENT); leftInnerParams.addRule(RelativeLayout.ALIGN_PARENT_START); leftInnerParams.addRule(RelativeLayout.CENTER_VERTICAL); if (leftType == TYPE_LEFT_TEXTVIEW) { // 初始化左边TextView tvLeft = ViewCore.newTextView(context); tvLeft.setText(leftText); tvLeft.setTextColor(leftTextColor); tvLeft.setTextSize(TypedValue.COMPLEX_UNIT_PX, leftTextSize); tvLeft.setGravity(Gravity.START | Gravity.CENTER_VERTICAL); tvLeft.setOnClickListener(this); // 设置DrawableLeft及DrawablePadding if (leftDrawable != 0) { tvLeft.setCompoundDrawablePadding((int) leftDrawablePadding); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { tvLeft.setCompoundDrawablesRelativeWithIntrinsicBounds(leftDrawable, 0, 0, 0); } else { tvLeft.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, 0, 0, 0); } } tvLeft.setPadding(PADDING_12, 0, PADDING_12, 0); ViewCore.setBackground(tvLeft, leftBackgroundDrawable); rlMain.addView(tvLeft, leftInnerParams); } else if (leftType == TYPE_LEFT_IMAGEBUTTON) { // 初始化左边ImageButton btnLeft = ViewCore.newImageButton(context); btnLeft.setImageResource(leftImageResource); btnLeft.setPadding(PADDING_12, 0, PADDING_12, 0); btnLeft.setOnClickListener(this); ViewCore.setBackground(btnLeft, leftBackgroundDrawable); rlMain.addView(btnLeft, leftInnerParams); } else if (leftType == TYPE_LEFT_CUSTOM_VIEW) { // 初始化自定义View viewCustomLeft = LayoutInflater.from(context).inflate(leftCustomViewRes, rlMain, false); if (viewCustomLeft.getId() == View.NO_ID) { //viewCustomLeft.setId(Utils.generateViewId()); viewCustomLeft.setId(ViewCore.generateViewId()); } rlMain.addView(viewCustomLeft, leftInnerParams); } } /** * 初始化主视图右边部分 * -- add: adaptive RTL * @param context 上下文 */ private void initMainRightViews(Context context) { LayoutParams rightInnerParams = new LayoutParams(WRAP_CONTENT, MATCH_PARENT); rightInnerParams.addRule(RelativeLayout.ALIGN_PARENT_END); rightInnerParams.addRule(RelativeLayout.CENTER_VERTICAL); if (rightType == TYPE_RIGHT_TEXTVIEW) { // 初始化右边TextView tvRight = ViewCore.newTextView(context); tvRight.setText(rightText); tvRight.setTextColor(rightTextColor); tvRight.setTextSize(TypedValue.COMPLEX_UNIT_PX, rightTextSize); tvRight.setGravity(Gravity.END | Gravity.CENTER_VERTICAL); tvRight.setPadding(PADDING_12, 0, PADDING_12, 0); tvRight.setOnClickListener(this); ViewCore.setBackground(tvRight, rightBackgroundDrawable); rlMain.addView(tvRight, rightInnerParams); } else if (rightType == TYPE_RIGHT_IMAGEBUTTON) { // 初始化右边ImageBtn btnRight = ViewCore.newImageButton(context); btnRight.setImageResource(rightImageResource); btnRight.setScaleType(ImageView.ScaleType.CENTER_INSIDE); btnRight.setPadding(PADDING_12, 0, PADDING_12, 0); btnRight.setOnClickListener(this); ViewCore.setBackground(btnRight, rightBackgroundDrawable); rlMain.addView(btnRight, rightInnerParams); } else if (rightType == TYPE_RIGHT_CUSTOM_VIEW) { // 初始化自定义view viewCustomRight = LayoutInflater.from(context).inflate(rightCustomViewRes, rlMain, false); if (viewCustomRight.getId() == View.NO_ID) { // viewCustomRight.setId(Utils.generateViewId()); viewCustomRight.setId(ViewCore.generateViewId()); } rlMain.addView(viewCustomRight, rightInnerParams); } } /** * 初始化主视图中间部分 * * @param context 上下文 */ private void initMainCenterViews(Context context) { if (centerType == TYPE_CENTER_TEXTVIEW) { // 初始化中间子布局 llMainCenter = ViewCore.newMainCenterViews(context); llMainCenter.setOnClickListener(this); LayoutParams centerParams = new LayoutParams(WRAP_CONTENT, MATCH_PARENT); centerParams.setMarginStart(PADDING_12); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { centerParams.setMarginEnd(PADDING_12); } centerParams.addRule(RelativeLayout.CENTER_IN_PARENT); rlMain.addView(llMainCenter, centerParams); // 初始化标题栏TextView tvCenter = ViewCore.newTextView(context); tvCenter.setText(centerText); tvCenter.setTextColor(centerTextColor); tvCenter.setTextSize(TypedValue.COMPLEX_UNIT_PX, centerTextSize); tvCenter.setGravity(Gravity.CENTER); // 设置跑马灯效果 tvCenter.setMaxWidth((int) (Utils.getScreenSize(context)[0] * 3 / 5.0)); if (centerTextMarquee){ tvCenter.setEllipsize(TextUtils.TruncateAt.MARQUEE); tvCenter.setMarqueeRepeatLimit(-1); tvCenter.requestFocus(); tvCenter.setSelected(true); } LinearLayout.LayoutParams centerTextParams = new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT); llMainCenter.addView(tvCenter, centerTextParams); // 初始化进度条, 显示于标题栏左边 progressCenter = new ProgressBar(context); progressCenter.setIndeterminateDrawable(getResources().getDrawable(R.drawable.xtitlebar_progress_draw)); progressCenter.setVisibility(View.GONE); int progressWidth = Utils.dp2px(18); LayoutParams progressParams = new LayoutParams(progressWidth, progressWidth); progressParams.addRule(RelativeLayout.CENTER_VERTICAL); progressParams.addRule(RelativeLayout.START_OF, llMainCenter.getId()); rlMain.addView(progressCenter, progressParams); // 初始化副标题栏 tvCenterSub = ViewCore.newTextView(context); tvCenterSub.setText(centerSubText); tvCenterSub.setTextColor(centerSubTextColor); tvCenterSub.setTextSize(TypedValue.COMPLEX_UNIT_PX, centerSubTextSize); tvCenterSub.setGravity(Gravity.CENTER); if (TextUtils.isEmpty(centerSubText)) { tvCenterSub.setVisibility(View.GONE); } LinearLayout.LayoutParams centerSubTextParams = new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT); llMainCenter.addView(tvCenterSub, centerSubTextParams); } /*else if (centerType == TYPE_CENTER_SEARCHVIEW) { // 初始化通用搜索框 rlMainCenterSearch = ViewCore.newRelativeLayout(context); rlMainCenterSearch.setBackgroundResource(centerSearchBgResource); LayoutParams centerParams = new LayoutParams(MATCH_PARENT, MATCH_PARENT); // 设置边距 centerParams.topMargin = Utils.dp2px(7); centerParams.bottomMargin = Utils.dp2px(7); // 根据左边的布局类型来设置边距,布局依赖规则 if (leftType == TYPE_LEFT_TEXTVIEW) { centerParams.addRule(RelativeLayout.END_OF, tvLeft.getId()); centerParams.setMarginStart(PADDING_5); } else if (leftType == TYPE_LEFT_IMAGEBUTTON) { centerParams.addRule(RelativeLayout.END_OF, btnLeft.getId()); centerParams.setMarginStart(PADDING_5); } else if (leftType == TYPE_LEFT_CUSTOM_VIEW) { centerParams.addRule(RelativeLayout.END_OF, viewCustomLeft.getId()); centerParams.setMarginStart(PADDING_5); } else { centerParams.setMarginStart(PADDING_12); } // 根据右边的布局类型来设置边距,布局依赖规则 if (rightType == TYPE_RIGHT_TEXTVIEW) { centerParams.addRule(RelativeLayout.START_OF, tvRight.getId()); centerParams.setMarginEnd(PADDING_5); } else if (rightType == TYPE_RIGHT_IMAGEBUTTON) { centerParams.addRule(RelativeLayout.START_OF, btnRight.getId()); centerParams.setMarginEnd(PADDING_5); } else if (rightType == TYPE_RIGHT_CUSTOM_VIEW) { centerParams.addRule(RelativeLayout.START_OF, viewCustomRight.getId()); centerParams.setMarginEnd(PADDING_5); } else { centerParams.setMarginEnd(PADDING_12); } rlMain.addView(rlMainCenterSearch, centerParams); // 初始化搜索框搜索ImageView ivSearch = ViewCore.newImageView(context); ivSearch.setOnClickListener(this); int searchIconWidth = Utils.dp2px(15); LayoutParams searchParams = new LayoutParams(searchIconWidth, searchIconWidth); searchParams.addRule(RelativeLayout.CENTER_VERTICAL); searchParams.addRule(RelativeLayout.ALIGN_PARENT_START); searchParams.setMarginStart(PADDING_12); rlMainCenterSearch.addView(ivSearch, searchParams); ivSearch.setImageResource(R.drawable.xtitlebar_search_normal); // 初始化搜索框语音ImageView ivVoice = ViewCore.newImageView(context); ivVoice.setOnClickListener(this); LayoutParams voiceParams = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT); voiceParams.addRule(RelativeLayout.CENTER_VERTICAL); voiceParams.addRule(RelativeLayout.ALIGN_PARENT_END); voiceParams.setMarginEnd(PADDING_12); rlMainCenterSearch.addView(ivVoice, voiceParams); if (centerSearchRightType == TYPE_CENTER_SEARCH_RIGHT_VOICE) { ivVoice.setImageResource(R.drawable.xtitlebar_voice); } else { ivVoice.setImageResource(R.drawable.xtitlebar_delete_normal); ivVoice.setVisibility(View.GONE); } // 初始化文字输入框 etSearchHint = new EditText(context); etSearchHint.setBackgroundColor(Color.TRANSPARENT); etSearchHint.setGravity(Gravity.START | Gravity.CENTER_VERTICAL); etSearchHint.setHint(getResources().getString(R.string.titlebar_search_hint)); etSearchHint.setTextColor(Color.parseColor("#666666")); etSearchHint.setHintTextColor(Color.parseColor("#999999")); etSearchHint.setTextSize(TypedValue.COMPLEX_UNIT_PX, Utils.dp2px(14)); etSearchHint.setPadding(PADDING_5, 0, PADDING_5, 0); if (!centerSearchEditable) { etSearchHint.setCursorVisible(false); etSearchHint.clearFocus(); etSearchHint.setFocusable(false); etSearchHint.setOnClickListener(this); } else { etSearchHint.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { etSearchHint.setCursorVisible(true); } }); } etSearchHint.setCursorVisible(false); etSearchHint.setSingleLine(true); etSearchHint.setEllipsize(TextUtils.TruncateAt.END); etSearchHint.setImeOptions(EditorInfo.IME_ACTION_SEARCH); etSearchHint.addTextChangedListener(centerSearchWatcher); etSearchHint.setOnFocusChangeListener(focusChangeListener); etSearchHint.setOnEditorActionListener(editorActionListener); LayoutParams searchHintParams = new LayoutParams(MATCH_PARENT, MATCH_PARENT); searchHintParams.addRule(RelativeLayout.END_OF, ivSearch.getId()); searchHintParams.addRule(RelativeLayout.START_OF, ivVoice.getId()); searchHintParams.addRule(RelativeLayout.CENTER_VERTICAL); searchHintParams.setMarginStart(PADDING_5); searchHintParams.setMarginEnd(PADDING_5); rlMainCenterSearch.addView(etSearchHint, searchHintParams); }*/ else if (centerType == TYPE_CENTER_CUSTOM_VIEW) { // 初始化中间自定义布局 centerCustomView = LayoutInflater.from(context).inflate(centerCustomViewRes, rlMain, false); if (centerCustomView.getId() == View.NO_ID) { centerCustomView.setId(ViewCore.generateViewId()); } LayoutParams centerCustomParams = new LayoutParams(WRAP_CONTENT, MATCH_PARENT); centerCustomParams.setMarginStart(PADDING_12); centerCustomParams.setMarginEnd(PADDING_12); centerCustomParams.addRule(RelativeLayout.CENTER_IN_PARENT); // if (leftType == TYPE_LEFT_TEXTVIEW) { // centerCustomParams.addRule(RelativeLayout.END_OF, tvLeft.getId()); // } else if (leftType == TYPE_LEFT_IMAGEBUTTON) { // centerCustomParams.addRule(RelativeLayout.END_OF, btnLeft.getId()); // } else if (leftType == TYPE_LEFT_CUSTOM_VIEW) { // centerCustomParams.addRule(RelativeLayout.END_OF, viewCustomLeft.getId()); // } // if (rightType == TYPE_RIGHT_TEXTVIEW) { // centerCustomParams.addRule(RelativeLayout.START_OF, tvRight.getId()); // } else if (rightType == TYPE_RIGHT_IMAGEBUTTON) { // centerCustomParams.addRule(RelativeLayout.START_OF, btnRight.getId()); // } else if (rightType == TYPE_RIGHT_CUSTOM_VIEW) { // centerCustomParams.addRule(RelativeLayout.START_OF, viewCustomRight.getId()); // } rlMain.addView(centerCustomView, centerCustomParams); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); //setUpImmersionTitleBar(); } // private void setUpImmersionTitleBar() { // Window window = getWindow(); // if (window == null) return; // // 设置状态栏背景透明 // Utils.transparentStatusBar(window); // // 设置图标主题 // if (statusBarMode == 0) { // Utils.setDarkMode(window); // } else { // Utils.setLightMode(window); // } // } private Window getWindow() { Context context = getContext(); Activity activity; if (context instanceof Activity) { activity = (Activity) context; } else { activity = (Activity) ((ContextWrapper) context).getBaseContext(); } if (activity != null) { return activity.getWindow(); } return null; } // private TextWatcher centerSearchWatcher = new TextWatcher() { // @Override // public void beforeTextChanged(CharSequence s, int start, int count, int after) { // } // // @Override // public void onTextChanged(CharSequence s, int start, int before, int count) { // } // // @Override // public void afterTextChanged(Editable s) { // if (centerSearchRightType == TYPE_CENTER_SEARCH_RIGHT_VOICE) { // if (TextUtils.isEmpty(s)) { // ivVoice.setImageResource(R.drawable.xtitlebar_voice); // } else { // ivVoice.setImageResource(R.drawable.xtitlebar_delete_normal); // } // } else { // if (TextUtils.isEmpty(s)) { // ivVoice.setVisibility(View.GONE); // } else { // ivVoice.setVisibility(View.VISIBLE); // } // } // } // }; // // private OnFocusChangeListener focusChangeListener = new OnFocusChangeListener() { // @Override // public void onFocusChange(View v, boolean hasFocus) { // if (centerSearchRightType == TYPE_CENTER_SEARCH_RIGHT_DELETE) { // String input = etSearchHint.getText().toString(); // if (hasFocus && !TextUtils.isEmpty(input)) { // ivVoice.setVisibility(View.VISIBLE); // } else { // ivVoice.setVisibility(View.GONE); // } // } // } // }; // // private TextView.OnEditorActionListener editorActionListener = new TextView.OnEditorActionListener() { // @Override // public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { // if (listener != null && actionId == EditorInfo.IME_ACTION_SEARCH) { // listener.onClicked(v, ACTION_SEARCH_SUBMIT, etSearchHint.getText().toString()); // } // return false; // } // }; private long lastClickMillis = 0; // 双击事件中,上次被点击时间 @Override public void onClick(View v) { if (listener == null) return; if (v.equals(llMainCenter) && doubleClickListener != null) { long currentClickMillis = System.currentTimeMillis(); if (currentClickMillis - lastClickMillis < 500) { doubleClickListener.onClicked(v); } lastClickMillis = currentClickMillis; } else if (v.equals(tvLeft)) { listener.onClicked(v, ACTION_LEFT_TEXT, null); } else if (v.equals(btnLeft)) { listener.onClicked(v, ACTION_LEFT_BUTTON, null); } else if (v.equals(tvRight)) { listener.onClicked(v, ACTION_RIGHT_TEXT, null); } else if (v.equals(btnRight)) { listener.onClicked(v, ACTION_RIGHT_BUTTON, null); } else if (v.equals(etSearchHint) || v.equals(ivSearch)) { listener.onClicked(v, ACTION_SEARCH, null); } else if (v.equals(ivVoice)) { if (centerSearchRightType == TYPE_CENTER_SEARCH_RIGHT_VOICE && TextUtils.isEmpty(etSearchHint.getText())) { // 语音按钮被点击 listener.onClicked(v, ACTION_SEARCH_VOICE, null); } else { etSearchHint.setText(""); listener.onClicked(v, ACTION_SEARCH_DELETE, null); } } else if (v.equals(tvCenter)) { listener.onClicked(v, ACTION_CENTER_TEXT, null); } } /** * 设置背景颜色 * * @param color */ @Override public void setBackgroundColor(int color) { rlMain.setBackgroundColor(color); } /** * 设置背景图片 * * @param resource */ @Override public void setBackgroundResource(int resource) { setBackgroundColor(Color.TRANSPARENT); super.setBackgroundResource(resource); } /** * 获取标题栏底部横线 * * @return */ public View getBottomLine() { return viewBottomLine; } /** * 获取标题栏左边TextView,对应leftType = textView * * @return */ public TextView getLeftTextView() { return tvLeft; } /** * 获取标题栏左边ImageButton,对应leftType = imageButton * * @return */ public ImageButton getLeftImageButton() { return btnLeft; } /** * 获取标题栏右边TextView,对应rightType = textView * * @return */ public TextView getRightTextView() { return tvRight; } /** * 获取标题栏右边ImageButton,对应rightType = imageButton * * @return */ public ImageButton getRightImageButton() { return btnRight; } public LinearLayout getCenterLayout() { return llMainCenter; } /** * 获取标题栏中间TextView,对应centerType = textView * * @return */ public TextView getCenterTextView() { return tvCenter; } public TextView getCenterSubTextView() { return tvCenterSub; } /** * 获取搜索框布局,对应centerType = searchView * * @return */ public RelativeLayout getCenterSearchView() { return rlMainCenterSearch; } /** * 获取搜索框内部输入框,对应centerType = searchView * * @return */ public EditText getCenterSearchEditText() { return etSearchHint; } /** * 获取搜索框右边图标ImageView,对应centerType = searchView * * @return */ public ImageView getCenterSearchRightImageView() { return ivVoice; } public ImageView getCenterSearchLeftImageView() { return ivSearch; } /** * 获取左边自定义布局 * * @return */ public View getLeftCustomView() { return viewCustomLeft; } /** * 获取右边自定义布局 * * @return */ public View getRightCustomView() { return viewCustomRight; } /** * 获取中间自定义布局视图 * * @return */ public View getCenterCustomView() { return centerCustomView; } /** * @param leftView */ public void setLeftView(View leftView) { if (leftView.getId() == View.NO_ID) { leftView.setId(ViewCore.generateViewId()); } LayoutParams leftInnerParams = new LayoutParams(WRAP_CONTENT, MATCH_PARENT); leftInnerParams.addRule(RelativeLayout.ALIGN_PARENT_START); leftInnerParams.addRule(RelativeLayout.CENTER_VERTICAL); rlMain.addView(leftView, leftInnerParams); } /** * @param centerView */ public void setCenterView(View centerView) { if (centerView.getId() == View.NO_ID) { centerView.setId(ViewCore.generateViewId()); } LayoutParams centerInnerParams = new LayoutParams(WRAP_CONTENT, MATCH_PARENT); centerInnerParams.addRule(RelativeLayout.CENTER_IN_PARENT); centerInnerParams.addRule(RelativeLayout.CENTER_VERTICAL); rlMain.addView(centerView, centerInnerParams); } /** * @param rightView */ public void setRightView(View rightView) { if (rightView.getId() == View.NO_ID) { rightView.setId(ViewCore.generateViewId()); } LayoutParams rightInnerParams = new LayoutParams(WRAP_CONTENT, MATCH_PARENT); rightInnerParams.addRule(RelativeLayout.ALIGN_PARENT_END); rightInnerParams.addRule(RelativeLayout.CENTER_VERTICAL); rlMain.addView(rightView, rightInnerParams); } /** * 显示中间进度条 */ public void showCenterProgress() { progressCenter.setVisibility(View.VISIBLE); } /** * 隐藏中间进度条 */ public void dismissCenterProgress() { progressCenter.setVisibility(View.GONE); } /** * 显示或隐藏输入法,centerType="searchView"模式下有效 * * @return */ public void showSoftInputKeyboard(boolean show) { if (centerSearchEditable && show) { etSearchHint.setFocusable(true); etSearchHint.setFocusableInTouchMode(true); etSearchHint.requestFocus(); Utils.showSoftInput(getContext(), etSearchHint); } else { Utils.hideSoftInput(getContext(), etSearchHint); } } /** * 设置搜索框右边图标 * * @param res */ public void setSearchRightImageResource(int res) { if (ivVoice != null) { ivVoice.setImageResource(res); } } /** * 获取SearchView输入结果 */ public String getSearchKey() { if (etSearchHint != null) { return etSearchHint.getText().toString(); } return ""; } /** * 设置点击事件监听 * * @param listener */ public void setListener(OnTitleBarListener listener) { this.listener = listener; } public void setDoubleClickListener(OnTitleBarDoubleClickListener doubleClickListener) { this.doubleClickListener = doubleClickListener; } /** * 设置双击监听 */ public static final int ACTION_LEFT_TEXT = 1; // 左边TextView被点击 public static final int ACTION_LEFT_BUTTON = 2; // 左边ImageBtn被点击 public static final int ACTION_RIGHT_TEXT = 3; // 右边TextView被点击 public static final int ACTION_RIGHT_BUTTON = 4; // 右边ImageBtn被点击 public static final int ACTION_SEARCH = 5; // 搜索框被点击,搜索框不可输入的状态下会被触发 public static final int ACTION_SEARCH_SUBMIT = 6; // 搜索框输入状态下,键盘提交触发 public static final int ACTION_SEARCH_VOICE = 7; // 语音按钮被点击 public static final int ACTION_SEARCH_DELETE = 8; // 搜索删除按钮被点击 public static final int ACTION_CENTER_TEXT = 9; // 中间文字点击 /** * 点击事件 */ public interface OnTitleBarListener { /** * @param v * @param action 对应ACTION_XXX, 如ACTION_LEFT_TEXT * @param extra 中间为搜索框时,如果可输入,点击键盘的搜索按钮,会返回输入关键词 */ void onClicked(View v, int action, String extra); } /** * 标题栏双击事件监听 */ public interface OnTitleBarDoubleClickListener { void onClicked(View v); } }
39.657379
132
0.629541
2c4d5b34b54cf8be7d84d750c96d4ff495892a34
42,187
/* * Copyright 2021 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. */ package com.google.cloud.essentialcontacts.v1; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutures; import com.google.api.core.BetaApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.paging.AbstractFixedSizeCollection; import com.google.api.gax.paging.AbstractPage; import com.google.api.gax.paging.AbstractPagedListResponse; import com.google.api.gax.rpc.PageContext; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.essentialcontacts.v1.stub.EssentialContactsServiceStub; import com.google.cloud.essentialcontacts.v1.stub.EssentialContactsServiceStubSettings; import com.google.common.util.concurrent.MoreExecutors; import com.google.protobuf.Empty; import com.google.protobuf.FieldMask; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Service Description: Manages contacts for important Google Cloud notifications. * * <p>This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * FolderName parent = FolderName.of("[FOLDER]"); * Contact contact = Contact.newBuilder().build(); * Contact response = essentialContactsServiceClient.createContact(parent, contact); * } * }</pre> * * <p>Note: close() needs to be called on the EssentialContactsServiceClient object to clean up * resources such as threads. In the example above, try-with-resources is used, which automatically * calls close(). * * <p>The surface of this class includes several types of Java methods for each of the API's * methods: * * <ol> * <li>A "flattened" method. With this type of method, the fields of the request type have been * converted into function parameters. It may be the case that not all fields are available as * parameters, and not every API method will have a flattened method entry point. * <li>A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. * <li>A "callable" method. This type of method takes no parameters and returns an immutable API * callable object, which can be used to initiate calls to the service. * </ol> * * <p>See the individual methods for example code. * * <p>Many parameters require resource names to be formatted in a particular way. To assist with * these names, this class includes a format method for each type of name, and additionally a parse * method to extract the individual identifiers contained within names that are returned. * * <p>This class can be customized by passing in a custom instance of * EssentialContactsServiceSettings to create(). For example: * * <p>To customize credentials: * * <pre>{@code * EssentialContactsServiceSettings essentialContactsServiceSettings = * EssentialContactsServiceSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create(essentialContactsServiceSettings); * }</pre> * * <p>To customize the endpoint: * * <pre>{@code * EssentialContactsServiceSettings essentialContactsServiceSettings = * EssentialContactsServiceSettings.newBuilder().setEndpoint(myEndpoint).build(); * EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create(essentialContactsServiceSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @Generated("by gapic-generator-java") public class EssentialContactsServiceClient implements BackgroundResource { private final EssentialContactsServiceSettings settings; private final EssentialContactsServiceStub stub; /** Constructs an instance of EssentialContactsServiceClient with default settings. */ public static final EssentialContactsServiceClient create() throws IOException { return create(EssentialContactsServiceSettings.newBuilder().build()); } /** * Constructs an instance of EssentialContactsServiceClient, using the given settings. The * channels are created based on the settings passed in, or defaults for any settings that are not * set. */ public static final EssentialContactsServiceClient create( EssentialContactsServiceSettings settings) throws IOException { return new EssentialContactsServiceClient(settings); } /** * Constructs an instance of EssentialContactsServiceClient, using the given stub for making * calls. This is for advanced usage - prefer using create(EssentialContactsServiceSettings). */ @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public static final EssentialContactsServiceClient create(EssentialContactsServiceStub stub) { return new EssentialContactsServiceClient(stub); } /** * Constructs an instance of EssentialContactsServiceClient, using the given settings. This is * protected so that it is easy to make a subclass, but otherwise, the static factory methods * should be preferred. */ protected EssentialContactsServiceClient(EssentialContactsServiceSettings settings) throws IOException { this.settings = settings; this.stub = ((EssentialContactsServiceStubSettings) settings.getStubSettings()).createStub(); } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") protected EssentialContactsServiceClient(EssentialContactsServiceStub stub) { this.settings = null; this.stub = stub; } public final EssentialContactsServiceSettings getSettings() { return settings; } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public EssentialContactsServiceStub getStub() { return stub; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Adds a new contact for a resource. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * FolderName parent = FolderName.of("[FOLDER]"); * Contact contact = Contact.newBuilder().build(); * Contact response = essentialContactsServiceClient.createContact(parent, contact); * } * }</pre> * * @param parent Required. The resource to save this contact for. Format: * organizations/{organization_id}, folders/{folder_id} or projects/{project_id} * @param contact Required. The contact to create. Must specify an email address and language tag. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Contact createContact(FolderName parent, Contact contact) { CreateContactRequest request = CreateContactRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .setContact(contact) .build(); return createContact(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Adds a new contact for a resource. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * OrganizationName parent = OrganizationName.of("[ORGANIZATION]"); * Contact contact = Contact.newBuilder().build(); * Contact response = essentialContactsServiceClient.createContact(parent, contact); * } * }</pre> * * @param parent Required. The resource to save this contact for. Format: * organizations/{organization_id}, folders/{folder_id} or projects/{project_id} * @param contact Required. The contact to create. Must specify an email address and language tag. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Contact createContact(OrganizationName parent, Contact contact) { CreateContactRequest request = CreateContactRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .setContact(contact) .build(); return createContact(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Adds a new contact for a resource. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * ProjectName parent = ProjectName.of("[PROJECT]"); * Contact contact = Contact.newBuilder().build(); * Contact response = essentialContactsServiceClient.createContact(parent, contact); * } * }</pre> * * @param parent Required. The resource to save this contact for. Format: * organizations/{organization_id}, folders/{folder_id} or projects/{project_id} * @param contact Required. The contact to create. Must specify an email address and language tag. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Contact createContact(ProjectName parent, Contact contact) { CreateContactRequest request = CreateContactRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .setContact(contact) .build(); return createContact(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Adds a new contact for a resource. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * String parent = ProjectName.of("[PROJECT]").toString(); * Contact contact = Contact.newBuilder().build(); * Contact response = essentialContactsServiceClient.createContact(parent, contact); * } * }</pre> * * @param parent Required. The resource to save this contact for. Format: * organizations/{organization_id}, folders/{folder_id} or projects/{project_id} * @param contact Required. The contact to create. Must specify an email address and language tag. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Contact createContact(String parent, Contact contact) { CreateContactRequest request = CreateContactRequest.newBuilder().setParent(parent).setContact(contact).build(); return createContact(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Adds a new contact for a resource. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * CreateContactRequest request = * CreateContactRequest.newBuilder() * .setParent(ProjectName.of("[PROJECT]").toString()) * .setContact(Contact.newBuilder().build()) * .build(); * Contact response = essentialContactsServiceClient.createContact(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Contact createContact(CreateContactRequest request) { return createContactCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Adds a new contact for a resource. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * CreateContactRequest request = * CreateContactRequest.newBuilder() * .setParent(ProjectName.of("[PROJECT]").toString()) * .setContact(Contact.newBuilder().build()) * .build(); * ApiFuture<Contact> future = * essentialContactsServiceClient.createContactCallable().futureCall(request); * // Do something. * Contact response = future.get(); * } * }</pre> */ public final UnaryCallable<CreateContactRequest, Contact> createContactCallable() { return stub.createContactCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Updates a contact. Note: A contact's email address cannot be changed. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * Contact contact = Contact.newBuilder().build(); * FieldMask updateMask = FieldMask.newBuilder().build(); * Contact response = essentialContactsServiceClient.updateContact(contact, updateMask); * } * }</pre> * * @param contact Required. The contact resource to replace the existing saved contact. Note: the * email address of the contact cannot be modified. * @param updateMask Optional. The update mask applied to the resource. For the `FieldMask` * definition, see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Contact updateContact(Contact contact, FieldMask updateMask) { UpdateContactRequest request = UpdateContactRequest.newBuilder().setContact(contact).setUpdateMask(updateMask).build(); return updateContact(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Updates a contact. Note: A contact's email address cannot be changed. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * UpdateContactRequest request = * UpdateContactRequest.newBuilder() * .setContact(Contact.newBuilder().build()) * .setUpdateMask(FieldMask.newBuilder().build()) * .build(); * Contact response = essentialContactsServiceClient.updateContact(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Contact updateContact(UpdateContactRequest request) { return updateContactCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Updates a contact. Note: A contact's email address cannot be changed. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * UpdateContactRequest request = * UpdateContactRequest.newBuilder() * .setContact(Contact.newBuilder().build()) * .setUpdateMask(FieldMask.newBuilder().build()) * .build(); * ApiFuture<Contact> future = * essentialContactsServiceClient.updateContactCallable().futureCall(request); * // Do something. * Contact response = future.get(); * } * }</pre> */ public final UnaryCallable<UpdateContactRequest, Contact> updateContactCallable() { return stub.updateContactCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists the contacts that have been set on a resource. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * FolderName parent = FolderName.of("[FOLDER]"); * for (Contact element : essentialContactsServiceClient.listContacts(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. The parent resource name. Format: organizations/{organization_id}, * folders/{folder_id} or projects/{project_id} * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListContactsPagedResponse listContacts(FolderName parent) { ListContactsRequest request = ListContactsRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .build(); return listContacts(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists the contacts that have been set on a resource. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * OrganizationName parent = OrganizationName.of("[ORGANIZATION]"); * for (Contact element : essentialContactsServiceClient.listContacts(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. The parent resource name. Format: organizations/{organization_id}, * folders/{folder_id} or projects/{project_id} * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListContactsPagedResponse listContacts(OrganizationName parent) { ListContactsRequest request = ListContactsRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .build(); return listContacts(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists the contacts that have been set on a resource. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * ProjectName parent = ProjectName.of("[PROJECT]"); * for (Contact element : essentialContactsServiceClient.listContacts(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. The parent resource name. Format: organizations/{organization_id}, * folders/{folder_id} or projects/{project_id} * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListContactsPagedResponse listContacts(ProjectName parent) { ListContactsRequest request = ListContactsRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .build(); return listContacts(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists the contacts that have been set on a resource. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * String parent = ProjectName.of("[PROJECT]").toString(); * for (Contact element : essentialContactsServiceClient.listContacts(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. The parent resource name. Format: organizations/{organization_id}, * folders/{folder_id} or projects/{project_id} * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListContactsPagedResponse listContacts(String parent) { ListContactsRequest request = ListContactsRequest.newBuilder().setParent(parent).build(); return listContacts(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists the contacts that have been set on a resource. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * ListContactsRequest request = * ListContactsRequest.newBuilder() * .setParent(ProjectName.of("[PROJECT]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * for (Contact element : essentialContactsServiceClient.listContacts(request).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListContactsPagedResponse listContacts(ListContactsRequest request) { return listContactsPagedCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists the contacts that have been set on a resource. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * ListContactsRequest request = * ListContactsRequest.newBuilder() * .setParent(ProjectName.of("[PROJECT]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * ApiFuture<Contact> future = * essentialContactsServiceClient.listContactsPagedCallable().futureCall(request); * // Do something. * for (Contact element : future.get().iterateAll()) { * // doThingsWith(element); * } * } * }</pre> */ public final UnaryCallable<ListContactsRequest, ListContactsPagedResponse> listContactsPagedCallable() { return stub.listContactsPagedCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists the contacts that have been set on a resource. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * ListContactsRequest request = * ListContactsRequest.newBuilder() * .setParent(ProjectName.of("[PROJECT]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * while (true) { * ListContactsResponse response = * essentialContactsServiceClient.listContactsCallable().call(request); * for (Contact element : response.getResponsesList()) { * // doThingsWith(element); * } * String nextPageToken = response.getNextPageToken(); * if (!Strings.isNullOrEmpty(nextPageToken)) { * request = request.toBuilder().setPageToken(nextPageToken).build(); * } else { * break; * } * } * } * }</pre> */ public final UnaryCallable<ListContactsRequest, ListContactsResponse> listContactsCallable() { return stub.listContactsCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets a single contact. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * ContactName name = ContactName.ofProjectContactName("[PROJECT]", "[CONTACT]"); * Contact response = essentialContactsServiceClient.getContact(name); * } * }</pre> * * @param name Required. The name of the contact to retrieve. Format: * organizations/{organization_id}/contacts/{contact_id}, * folders/{folder_id}/contacts/{contact_id} or projects/{project_id}/contacts/{contact_id} * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Contact getContact(ContactName name) { GetContactRequest request = GetContactRequest.newBuilder().setName(name == null ? null : name.toString()).build(); return getContact(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets a single contact. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * String name = ContactName.ofProjectContactName("[PROJECT]", "[CONTACT]").toString(); * Contact response = essentialContactsServiceClient.getContact(name); * } * }</pre> * * @param name Required. The name of the contact to retrieve. Format: * organizations/{organization_id}/contacts/{contact_id}, * folders/{folder_id}/contacts/{contact_id} or projects/{project_id}/contacts/{contact_id} * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Contact getContact(String name) { GetContactRequest request = GetContactRequest.newBuilder().setName(name).build(); return getContact(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets a single contact. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * GetContactRequest request = * GetContactRequest.newBuilder() * .setName(ContactName.ofProjectContactName("[PROJECT]", "[CONTACT]").toString()) * .build(); * Contact response = essentialContactsServiceClient.getContact(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Contact getContact(GetContactRequest request) { return getContactCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets a single contact. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * GetContactRequest request = * GetContactRequest.newBuilder() * .setName(ContactName.ofProjectContactName("[PROJECT]", "[CONTACT]").toString()) * .build(); * ApiFuture<Contact> future = * essentialContactsServiceClient.getContactCallable().futureCall(request); * // Do something. * Contact response = future.get(); * } * }</pre> */ public final UnaryCallable<GetContactRequest, Contact> getContactCallable() { return stub.getContactCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Deletes a contact. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * ContactName name = ContactName.ofProjectContactName("[PROJECT]", "[CONTACT]"); * essentialContactsServiceClient.deleteContact(name); * } * }</pre> * * @param name Required. The name of the contact to delete. Format: * organizations/{organization_id}/contacts/{contact_id}, * folders/{folder_id}/contacts/{contact_id} or projects/{project_id}/contacts/{contact_id} * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final void deleteContact(ContactName name) { DeleteContactRequest request = DeleteContactRequest.newBuilder().setName(name == null ? null : name.toString()).build(); deleteContact(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Deletes a contact. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * String name = ContactName.ofProjectContactName("[PROJECT]", "[CONTACT]").toString(); * essentialContactsServiceClient.deleteContact(name); * } * }</pre> * * @param name Required. The name of the contact to delete. Format: * organizations/{organization_id}/contacts/{contact_id}, * folders/{folder_id}/contacts/{contact_id} or projects/{project_id}/contacts/{contact_id} * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final void deleteContact(String name) { DeleteContactRequest request = DeleteContactRequest.newBuilder().setName(name).build(); deleteContact(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Deletes a contact. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * DeleteContactRequest request = * DeleteContactRequest.newBuilder() * .setName(ContactName.ofProjectContactName("[PROJECT]", "[CONTACT]").toString()) * .build(); * essentialContactsServiceClient.deleteContact(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final void deleteContact(DeleteContactRequest request) { deleteContactCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Deletes a contact. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * DeleteContactRequest request = * DeleteContactRequest.newBuilder() * .setName(ContactName.ofProjectContactName("[PROJECT]", "[CONTACT]").toString()) * .build(); * ApiFuture<Empty> future = * essentialContactsServiceClient.deleteContactCallable().futureCall(request); * // Do something. * future.get(); * } * }</pre> */ public final UnaryCallable<DeleteContactRequest, Empty> deleteContactCallable() { return stub.deleteContactCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists all contacts for the resource that are subscribed to the specified notification * categories, including contacts inherited from any parent resources. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * ComputeContactsRequest request = * ComputeContactsRequest.newBuilder() * .setParent(ProjectName.of("[PROJECT]").toString()) * .addAllNotificationCategories(new ArrayList<NotificationCategory>()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * for (Contact element : essentialContactsServiceClient.computeContacts(request).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ComputeContactsPagedResponse computeContacts(ComputeContactsRequest request) { return computeContactsPagedCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists all contacts for the resource that are subscribed to the specified notification * categories, including contacts inherited from any parent resources. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * ComputeContactsRequest request = * ComputeContactsRequest.newBuilder() * .setParent(ProjectName.of("[PROJECT]").toString()) * .addAllNotificationCategories(new ArrayList<NotificationCategory>()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * ApiFuture<Contact> future = * essentialContactsServiceClient.computeContactsPagedCallable().futureCall(request); * // Do something. * for (Contact element : future.get().iterateAll()) { * // doThingsWith(element); * } * } * }</pre> */ public final UnaryCallable<ComputeContactsRequest, ComputeContactsPagedResponse> computeContactsPagedCallable() { return stub.computeContactsPagedCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists all contacts for the resource that are subscribed to the specified notification * categories, including contacts inherited from any parent resources. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * ComputeContactsRequest request = * ComputeContactsRequest.newBuilder() * .setParent(ProjectName.of("[PROJECT]").toString()) * .addAllNotificationCategories(new ArrayList<NotificationCategory>()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * while (true) { * ComputeContactsResponse response = * essentialContactsServiceClient.computeContactsCallable().call(request); * for (Contact element : response.getResponsesList()) { * // doThingsWith(element); * } * String nextPageToken = response.getNextPageToken(); * if (!Strings.isNullOrEmpty(nextPageToken)) { * request = request.toBuilder().setPageToken(nextPageToken).build(); * } else { * break; * } * } * } * }</pre> */ public final UnaryCallable<ComputeContactsRequest, ComputeContactsResponse> computeContactsCallable() { return stub.computeContactsCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Allows a contact admin to send a test message to contact to verify that it has been configured * correctly. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * SendTestMessageRequest request = * SendTestMessageRequest.newBuilder() * .addAllContacts(new ArrayList<String>()) * .setResource(ProjectName.of("[PROJECT]").toString()) * .setNotificationCategory(NotificationCategory.forNumber(0)) * .build(); * essentialContactsServiceClient.sendTestMessage(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final void sendTestMessage(SendTestMessageRequest request) { sendTestMessageCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Allows a contact admin to send a test message to contact to verify that it has been configured * correctly. * * <p>Sample code: * * <pre>{@code * try (EssentialContactsServiceClient essentialContactsServiceClient = * EssentialContactsServiceClient.create()) { * SendTestMessageRequest request = * SendTestMessageRequest.newBuilder() * .addAllContacts(new ArrayList<String>()) * .setResource(ProjectName.of("[PROJECT]").toString()) * .setNotificationCategory(NotificationCategory.forNumber(0)) * .build(); * ApiFuture<Empty> future = * essentialContactsServiceClient.sendTestMessageCallable().futureCall(request); * // Do something. * future.get(); * } * }</pre> */ public final UnaryCallable<SendTestMessageRequest, Empty> sendTestMessageCallable() { return stub.sendTestMessageCallable(); } @Override public final void close() { stub.close(); } @Override public void shutdown() { stub.shutdown(); } @Override public boolean isShutdown() { return stub.isShutdown(); } @Override public boolean isTerminated() { return stub.isTerminated(); } @Override public void shutdownNow() { stub.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return stub.awaitTermination(duration, unit); } public static class ListContactsPagedResponse extends AbstractPagedListResponse< ListContactsRequest, ListContactsResponse, Contact, ListContactsPage, ListContactsFixedSizeCollection> { public static ApiFuture<ListContactsPagedResponse> createAsync( PageContext<ListContactsRequest, ListContactsResponse, Contact> context, ApiFuture<ListContactsResponse> futureResponse) { ApiFuture<ListContactsPage> futurePage = ListContactsPage.createEmptyPage().createPageAsync(context, futureResponse); return ApiFutures.transform( futurePage, input -> new ListContactsPagedResponse(input), MoreExecutors.directExecutor()); } private ListContactsPagedResponse(ListContactsPage page) { super(page, ListContactsFixedSizeCollection.createEmptyCollection()); } } public static class ListContactsPage extends AbstractPage<ListContactsRequest, ListContactsResponse, Contact, ListContactsPage> { private ListContactsPage( PageContext<ListContactsRequest, ListContactsResponse, Contact> context, ListContactsResponse response) { super(context, response); } private static ListContactsPage createEmptyPage() { return new ListContactsPage(null, null); } @Override protected ListContactsPage createPage( PageContext<ListContactsRequest, ListContactsResponse, Contact> context, ListContactsResponse response) { return new ListContactsPage(context, response); } @Override public ApiFuture<ListContactsPage> createPageAsync( PageContext<ListContactsRequest, ListContactsResponse, Contact> context, ApiFuture<ListContactsResponse> futureResponse) { return super.createPageAsync(context, futureResponse); } } public static class ListContactsFixedSizeCollection extends AbstractFixedSizeCollection< ListContactsRequest, ListContactsResponse, Contact, ListContactsPage, ListContactsFixedSizeCollection> { private ListContactsFixedSizeCollection(List<ListContactsPage> pages, int collectionSize) { super(pages, collectionSize); } private static ListContactsFixedSizeCollection createEmptyCollection() { return new ListContactsFixedSizeCollection(null, 0); } @Override protected ListContactsFixedSizeCollection createCollection( List<ListContactsPage> pages, int collectionSize) { return new ListContactsFixedSizeCollection(pages, collectionSize); } } public static class ComputeContactsPagedResponse extends AbstractPagedListResponse< ComputeContactsRequest, ComputeContactsResponse, Contact, ComputeContactsPage, ComputeContactsFixedSizeCollection> { public static ApiFuture<ComputeContactsPagedResponse> createAsync( PageContext<ComputeContactsRequest, ComputeContactsResponse, Contact> context, ApiFuture<ComputeContactsResponse> futureResponse) { ApiFuture<ComputeContactsPage> futurePage = ComputeContactsPage.createEmptyPage().createPageAsync(context, futureResponse); return ApiFutures.transform( futurePage, input -> new ComputeContactsPagedResponse(input), MoreExecutors.directExecutor()); } private ComputeContactsPagedResponse(ComputeContactsPage page) { super(page, ComputeContactsFixedSizeCollection.createEmptyCollection()); } } public static class ComputeContactsPage extends AbstractPage< ComputeContactsRequest, ComputeContactsResponse, Contact, ComputeContactsPage> { private ComputeContactsPage( PageContext<ComputeContactsRequest, ComputeContactsResponse, Contact> context, ComputeContactsResponse response) { super(context, response); } private static ComputeContactsPage createEmptyPage() { return new ComputeContactsPage(null, null); } @Override protected ComputeContactsPage createPage( PageContext<ComputeContactsRequest, ComputeContactsResponse, Contact> context, ComputeContactsResponse response) { return new ComputeContactsPage(context, response); } @Override public ApiFuture<ComputeContactsPage> createPageAsync( PageContext<ComputeContactsRequest, ComputeContactsResponse, Contact> context, ApiFuture<ComputeContactsResponse> futureResponse) { return super.createPageAsync(context, futureResponse); } } public static class ComputeContactsFixedSizeCollection extends AbstractFixedSizeCollection< ComputeContactsRequest, ComputeContactsResponse, Contact, ComputeContactsPage, ComputeContactsFixedSizeCollection> { private ComputeContactsFixedSizeCollection( List<ComputeContactsPage> pages, int collectionSize) { super(pages, collectionSize); } private static ComputeContactsFixedSizeCollection createEmptyCollection() { return new ComputeContactsFixedSizeCollection(null, 0); } @Override protected ComputeContactsFixedSizeCollection createCollection( List<ComputeContactsPage> pages, int collectionSize) { return new ComputeContactsFixedSizeCollection(pages, collectionSize); } } }
37.366696
101
0.695712
8404134acd0854ea33376e155d1a14cb289e19df
2,452
package cn.ucloud.udisk.model; import cn.ucloud.common.annotation.UcloudParam; import cn.ucloud.common.pojo.BaseRequestParam; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; /** * @description: 调整云硬盘 参数类 * @author: joshua * @E-mail: joshua.yin@ucloud.cn * @date: 2018/9/25 18:58 */ public class ResizeUDiskParam extends BaseRequestParam { /** * require region 地域,参见https://docs.ucloud.cn/api/summary/regionlist.html */ @NotEmpty(message = "region can not be empty") @UcloudParam("Region") private String region; /** * require zone 可用区,参见https://docs.ucloud.cn/api/summary/regionlist.html */ @NotEmpty(message = "zone can not be empty") @UcloudParam("Zone") private String zone; /** * require uDiskId UDisk Id */ @NotEmpty(message = "uDiskId can not be empty") @UcloudParam("UDiskId") private String uDiskId; /** * require size 调整后大小, 单位:GB, 范围[1~2000],权限位控制可达8000,若需要请申请开通相关权限。 */ @NotNull(message = "size can not be empty") @UcloudParam("Size") private Integer size ; /** * optional couponId 使用的代金券id */ @UcloudParam("CouponId") private String couponId; public ResizeUDiskParam(@NotEmpty(message = "region can not be empty") String region, @NotEmpty(message = "zone can not be empty") String zone, @NotEmpty(message = "uDiskId can not be empty") String uDiskId, @NotEmpty(message = "size can not be empty") Integer size) { super("ResizeUDisk"); this.region = region; this.zone = zone; this.uDiskId = uDiskId; this.size = size; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getZone() { return zone; } public void setZone(String zone) { this.zone = zone; } public String getuDiskId() { return uDiskId; } public void setuDiskId(String uDiskId) { this.uDiskId = uDiskId; } public Integer getSize() { return size; } public void setSize(Integer size) { this.size = size; } public String getCouponId() { return couponId; } public void setCouponId(String couponId) { this.couponId = couponId; } }
24.277228
91
0.609706
a7845d2c5786ae32d6356e3749e647d886b78a83
1,046
package com.speryans.saldobus.framework.classes.ui; import net.rim.device.api.ui.Field; public class FieldDimensionUtilities { private FieldDimensionUtilities() { } public static int getBorderWidth( Field field ) { int width = 0; width = field.getWidth() - field.getContentWidth() - field.getPaddingLeft() - field.getPaddingRight(); return width; } public static int getBorderHeight( Field field ) { int height = 0; height = field.getWidth() - field.getContentHeight() - field.getPaddingTop() - field.getPaddingBottom(); return height; } public static int getBorderAndPaddingWidth( Field field ) { int width = 0; width = field.getWidth() - field.getContentWidth(); return width; } public static int getBorderAndPaddingHeight( Field field ) { int height = 0; height = field.getHeight() - field.getContentHeight(); return height; } }
23.244444
113
0.605163
b5a3f072942177690bc948cc5f584064c1ae9553
4,075
/* * 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. */ package com.google.android.gnd.ui.editobservation; import android.app.Application; import android.net.Uri; import android.view.View; import androidx.annotation.Nullable; import androidx.lifecycle.LiveData; import androidx.lifecycle.LiveDataReactiveStreams; import androidx.lifecycle.MutableLiveData; import com.google.android.gnd.model.form.Field; import com.google.android.gnd.model.form.Field.Type; import com.google.android.gnd.model.observation.Response; import com.google.android.gnd.persistence.remote.RemoteStorageManager; import com.google.android.gnd.rx.annotations.Hot; import com.google.android.gnd.ui.util.FileUtil; import io.reactivex.Single; import io.reactivex.processors.BehaviorProcessor; import io.reactivex.processors.FlowableProcessor; import java8.util.Optional; import javax.inject.Inject; import timber.log.Timber; public class PhotoFieldViewModel extends AbstractFieldViewModel { private static final String EMPTY_PATH = ""; private final RemoteStorageManager remoteStorageManager; private final FileUtil fileUtil; @Hot(replays = true) private final FlowableProcessor<String> destinationPath = BehaviorProcessor.create(); private final LiveData<Uri> uri; public final LiveData<Boolean> isVisible; @Hot(replays = true) private final MutableLiveData<Field> showDialogClicks = new MutableLiveData<>(); @Hot(replays = true) private final MutableLiveData<Integer> clearButtonVisibility = new MutableLiveData<>(View.GONE); @Inject PhotoFieldViewModel( RemoteStorageManager remoteStorageManager, FileUtil fileUtil, Application application) { super(application); this.remoteStorageManager = remoteStorageManager; this.fileUtil = fileUtil; this.isVisible = LiveDataReactiveStreams.fromPublisher(destinationPath.map(path -> !path.isEmpty())); this.uri = LiveDataReactiveStreams.fromPublisher( destinationPath.switchMapSingle(this::getDownloadUrl)); } /** * Fetch url for the image from Firestore Storage. If the remote image is not available then * search for the file locally and return its uri. * * @param path Final destination path of the uploaded photo relative to Firestore */ @Hot(terminates = true) private Single<Uri> getDownloadUrl(String path) { return path.isEmpty() ? Single.just(Uri.EMPTY) : remoteStorageManager .getDownloadUrl(path) .onErrorReturn(throwable -> fileUtil.getFileUriFromRemotePath(path)); } public LiveData<Uri> getUri() { return uri; } @Override public void setResponse(Optional<Response> response) { super.setResponse(response); updateField(response.isPresent() ? response.get() : null, getField()); } public void updateField(@Nullable Response response, Field field) { if (field.getType() != Type.PHOTO) { Timber.e("Not a photo type field: %s", field.getType()); return; } if (response == null) { destinationPath.onNext(EMPTY_PATH); } else { destinationPath.onNext(response.getDetailsText(field)); } } public void onShowPhotoSelectorDialog() { showDialogClicks.setValue(getField()); } LiveData<Field> getShowDialogClicks() { return showDialogClicks; } public void setClearButtonVisible(boolean enabled) { clearButtonVisibility.postValue(enabled ? View.VISIBLE : View.GONE); } public LiveData<Integer> getClearButtonVisibility() { return clearButtonVisibility; } }
32.862903
98
0.745276
2ba23542e27ab5f29bcc1d2f086dfda5d8355d3d
1,361
package com.hyphenate.easeui.widget.presenter; import android.content.Context; import android.widget.BaseAdapter; import com.hyphenate.chat.EMClient; import com.hyphenate.chat.EMMessage; import com.hyphenate.chat.EMTextMessageBody; import com.hyphenate.easeui.widget.chatrow.EaseChatRow; import com.hyphenate.easeui.widget.chatrow.EaseChatRowCard; import com.hyphenate.exceptions.HyphenateException; /** * Created by zhangsong on 17-10-12. */ public class EaseChatCardPresenter extends EaseChatRowPresenter { private static final String TAG = "EaseChatFilePresenter"; @Override protected EaseChatRow onCreateChatRow(Context cxt, EMMessage message, int position, BaseAdapter adapter) { return new EaseChatRowCard(cxt, message, position, adapter); } @Override public void onBubbleClick(EMMessage message) { EMTextMessageBody fileMessageBody = (EMTextMessageBody) message.getBody(); if (message.direct() == EMMessage.Direct.RECEIVE && !message.isAcked() && message.getChatType() == EMMessage.ChatType.Chat) { try { EMClient.getInstance().chatManager().ackMessageRead(message.getFrom(), message.getMsgId()); } catch (HyphenateException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
35.815789
133
0.709772
777473fa7a4eb5cb5eeccbcfb16272367e1e9e28
9,355
package com.runescape.game.content.skills.slayer; import com.runescape.game.interaction.dialogues.Dialogue; import com.runescape.game.interaction.dialogues.impl.item.SimpleItemMessage; import com.runescape.game.interaction.dialogues.impl.misc.SimpleNPCMessage; import com.runescape.game.interaction.dialogues.impl.skills.VannakaD; import com.runescape.game.world.entity.npc.NPC; import com.runescape.game.world.entity.player.Player; import com.runescape.game.world.entity.player.Skills; import com.runescape.game.world.entity.player.achievements.AchievementHandler; import com.runescape.game.world.entity.player.achievements.hard.Hard_Slayer; import com.runescape.game.world.entity.player.achievements.medium.Journey_Man_Slayer; import com.runescape.game.world.entity.player.achievements.medium.Slayer_Hunter; import com.runescape.game.world.item.Item; import com.runescape.utility.Utils; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * @author Tyluur<itstyluur@gmail.com> * @since Apr 24, 2015 */ public class SlayerManagement { /** * Gives the player a random slayer task of a type * * @param player * The player to receive the task * @param type * The type of task the player wants */ public static void giveTask(Player player, SlayerTasks type) { List<String> names = SlayerTasks.getTasksNames(type); if (names == null) { noAvailableTasks(player); return; } // so only the monsters that npcs with no definitions or npcs with // a required lvl lower than the players slayer lvl can be given names = names.stream().filter(name -> { SlayerMonsters monster = SlayerMonsters.getMonster(name); return monster == null || player.getSkills().getLevelForXp(Skills.SLAYER) >= monster.getRequirement(); }).collect(Collectors.toList()); if (names.size() == 0) { noAvailableTasks(player); return; } Collections.shuffle(names); String randomName = names.get(0); int[] amounts = type.getAmounts(); int amount = Utils.random(amounts[0], amounts[1]); SlayerTask task = new SlayerTask(randomName, amount, type); player.getFacade().setSlayerTask(task); if (player.getFacade().getSlayerPartnerPlayer() != null) { player.getFacade().getSlayerPartnerPlayer().getFacade().setSlayerTask(task); } VannakaD.receivedNewTaskDialogue(player); } private static void noAvailableTasks(Player player) { player.getDialogueManager().startDialogue(SimpleItemMessage.class, 4155, "There are no tasks available for you", "at your current slayer level.", "Select a different type."); } /** * Invites a player to be a player's social slayer partner * * @param player * The player inviting * @param p2 * The player invited */ public static void invitePlayer(Player player, Player p2) { player.putAttribute("social_request", p2); player.getPackets().sendGameMessage("Sending " + p2.getDisplayName() + " an invitation..."); p2.getPackets().sendMessage(117, "You have received an invitation to join " + player.getDisplayName() + "'s social slayer group.", player); } /** * Views the invitation to be someones slayer partner * * @param player * The player * @param inviter * The inviter */ public static boolean viewInvite(Player player, Player inviter) { if (inviter.removeAttribute("social_request") == player) { String message = availableForPartnering(player, inviter); if (message != null) { player.getDialogueManager().startDialogue(SimpleItemMessage.class, 4155, message); inviter.getDialogueManager().startDialogue(SimpleItemMessage.class, 4155, message); return true; } player.getDialogueManager().startDialogue(new Dialogue() { @Override public void start() { sendOptionsDialogue("Be slayer partners with " + inviter.getDisplayName() + "?", "Yes", "No"); } @Override public void run(int interfaceId, int option) { if (option == FIRST) { String localMessage = availableForPartnering(player, inviter); if (localMessage != null) { sendItemDialogue(4155, 1, localMessage); inviter.getDialogueManager().startDialogue(SimpleItemMessage.class, 4155, localMessage); } else { inviter.getFacade().setSlayerPartner(player.getUsername()); inviter.getPackets().sendGameMessage("You have created a social group."); player.getFacade().setSlayerPartner(inviter.getUsername()); sendDialogue("You have just joined " + inviter.getDisplayName() + "'s social group."); } stage = -2; } else { end(); } } @Override public void finish() { } }); return true; } return false; } /** * Checks if the two players are available for partnering. If they aren't, the reason why is returned * * @param player * The player * @param inviter * The player inviting */ public static String availableForPartnering(Player player, Player inviter) { SlayerTask slayerTask = player.getFacade().getSlayerTask(); SlayerTask slayerTaskO = inviter.getFacade().getSlayerTask(); if (slayerTask != null && slayerTaskO != null && !slayerTask.equals(slayerTaskO)) { return player.getDisplayName() + " needs to complete their slayer task before joining."; } else if (slayerTaskO != null && slayerTask != null && !slayerTaskO.equals(slayerTask)) { return inviter.getDisplayName() + " needs to complete their slayer task before joining."; } else if (player.getFacade().getSlayerPartner() != null) { return player.getDisplayName() + " needs to leave their current partner before joining a social slayer group."; } else if (inviter.getFacade().getSlayerPartner() != null) { return inviter.getDisplayName() + " needs to leave their current partner before joining a social slayer group."; } return null; } /** * Reducing the task amount * * @param player * The player * @param npc * The monster that died */ public static void reduceTaskAmount(Player player, NPC npc) { Player partner = player.getFacade().getSlayerPartnerPlayer(); player.getFacade().getSlayerTask().deductTaskAmount(); if (partner != null && partner.withinDistance(player, 16) && partner.getFacade().hasSlayerTask() && partner.getFacade().getSlayerTask().equals(player.getFacade().getSlayerTask())) { partner.getFacade().getSlayerTask().deductTaskAmount(); partner.getSkills().addXp(Skills.SLAYER, npc.getMaxHitpoints() / (equippingSlayerHelm(partner) ? 7 : 10)); checkProgress(partner, npc); } player.getSkills().addXp(Skills.SLAYER, npc.getMaxHitpoints() / (equippingSlayerHelm(player) ? 7 : 10)); checkProgress(player, npc); } /** * Checks the progress of the slayer task * * @param player * The player * @param npc * The monster that died */ private static void checkProgress(Player player, NPC npc) { if (player.getFacade().hasSlayerTask() && player.getFacade().getSlayerTask().getAmountToKill() <= 0) { SlayerTasks task = player.getFacade().getSlayerTask().getTask(); if (task != null) { if (task.equals(SlayerTasks.MEDIUM)) { AchievementHandler.incrementProgress(player, Slayer_Hunter.class); AchievementHandler.incrementProgress(player, Journey_Man_Slayer.class); } else if (task.equals(SlayerTasks.HARD)) { AchievementHandler.incrementProgress(player, Hard_Slayer.class); } } int points = player.getFacade().getSlayerTask().getTask().getSlayerPointReward(); int[] coinLootData = player.getFacade().getSlayerTask().getTask().getCoinLoots(); npc.sendDrop(player, new Item(995, Utils.random(coinLootData[0], coinLootData[1])), false); player.getFacade().setSlayerPoints(player.getFacade().getSlayerPoints() + points); player.getDialogueManager().startDialogue(SimpleNPCMessage.class, 1597, "You have completed your Slayer task. Come back to me for a new one.", "You receive " + points + " slayer points for completing this task."); player.getFacade().removeSlayerTask(); } } /** * Removes social slayer for this player and for the target if they're in the world. * * @param player * The player */ public static void removeSocialSlayer(Player player) { Player partner = player.getFacade().getSlayerPartnerPlayer(); player.getFacade().setSlayerPartner(null); if (partner != null) { partner.getFacade().setSlayerPartner(null); partner.sendMessage("Your partner has just turned off social slayer."); } } /** * Checking if the player is equipping a slayer helm * * @param player * The player */ public static boolean equippingSlayerHelm(Player player) {return player.getEquipment().getHatId() == 15492;} /** * Checking if the player is equipping a black mask * * @param player * The player */ public static boolean equippingBlackMask(Player player) { int hatId = player.getEquipment().getHatId(); return hatId == 13263 || hatId == 14636 || hatId == 14637 || hatId == 15492 || hatId == 15496 || hatId == 15497 || hatId >= 8901 && hatId <= 8921; } /** * Checks if the npc is the player's task * * @param player * The player * @param npc * The npc */ public static boolean isTask(Player player, NPC npc) { return player.getFacade().hasSlayerTask() && npc.getName().toLowerCase().contains(player.getFacade().getSlayerTask().getName().toLowerCase()); } }
36.542969
216
0.710957
9cd4d0714c9b4a4f36f1ca5118a46075ea560ee8
1,719
package frc.robot.commands; import frc.robot.Drivetrain; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj2.command.CommandBase; public class AutonOption5 extends CommandBase { private final Timer timer; private final Drivetrain drive; public AutonOption5(Drivetrain drive) { timer = new Timer(); this.drive = drive; addRequirements(drive); timer.start(); } private void stop() { drive.swerveDrive(0, 0, 0, true); } @Override public void execute() { // timer.start(); double timerVal = timer.get(); if (timerVal < 2) { System.out.println("Moving Back"); drive.swerveDrive(-1, 0, 0, false); } else if (timerVal > 2 && timerVal < 3) { System.out.println("Stopping"); stop(); } // INGEST BALL // SHOOT TWO BALLS else if (timerVal > 3 && timerVal < 7) { System.out.println("Moving Back Towards Terminal"); drive.swerveDrive(-1, 0, 0, false); } else if (timerVal > 7 && timerVal < 8) { System.out.println("Stopping"); stop(); } // INGEST BALL // INGEST BALL FED FROM HUMAN PLAYER else if (timerVal > 8 && timerVal < 11) { System.out.println("Moving towards Central Hub"); drive.swerveDrive(1, 0, 0, false); } else if (timerVal > 11 && timerVal < 12) { System.out.println("Stopping"); stop(); } // SHOOT TWO BALLS else { System.out.println("Stopping"); stop(); } // timer.stop(); // timer.reset(); } }
29.135593
63
0.532286
05e97c2ffe77b16c59f07494f4aec239a89f17bc
3,582
package io.alehub.alehubwallet.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import org.apache.commons.validator.routines.EmailValidator; import io.alehub.alehubwallet.R; import io.alehub.alehubwallet.view.NotificationLayout; /** * Created by dima on 1/23/18. */ public class RegistrationFragment extends Fragment implements View.OnClickListener { private EditText edFullName, edEmail, edPhoneNumber, edPassword, edRetypePassword; private Button btCreate; private TextView tvLogIn; private Toolbar toolbar; private NotificationLayout nlNotify; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.registration_fragment, null); edEmail = (EditText) v.findViewById(R.id.ed_registration_email); edFullName = (EditText) v.findViewById(R.id.ed_registration_full_name); edPassword = (EditText) v.findViewById(R.id.ed_registration_password); edPhoneNumber = (EditText) v.findViewById(R.id.ed_registration_phone_number); edRetypePassword = (EditText) v.findViewById(R.id.ed_registration_retype_password); tvLogIn = (TextView) v.findViewById(R.id.tv_registration_log_in); btCreate = (Button) v.findViewById(R.id.bt_registration_create); toolbar = (Toolbar) v.findViewById(R.id.toolbar); nlNotify = (NotificationLayout) v.findViewById(R.id.notification); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getActivity().onBackPressed(); } }); btCreate.setOnClickListener(this); tvLogIn.setOnClickListener(this); ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); v.setLayoutParams(lp); return v; } @Override public void onClick(View view) { if (view.getId() == R.id.bt_registration_create) { String fullName = edFullName.getText().toString(); String email = edEmail.getText().toString(); String phone = edPhoneNumber.getText().toString(); String password = edPassword.getText().toString(); String password1 = edRetypePassword.getText().toString(); if (fullName.length() < 1) { nlNotify.show(getString(R.string.fullname_incorrect), R.color.text_white, R.color.red); } else if (email.length() < 4 || !EmailValidator.getInstance().isValid(email)) { nlNotify.show(getString(R.string.email_incorrect), R.color.text_white, R.color.red); } else if (phone.length() < 1) { nlNotify.show(getString(R.string.phone_incorrect), R.color.text_white, R.color.red); } else if (password.length() < 6 || !password.equals(password1)) { nlNotify.show(getString(R.string.password_incorrect), R.color.text_white, R.color.red); } else { getActivity().onBackPressed(); } } else if (view.getId() == R.id.tv_registration_log_in) { getActivity().onBackPressed(); } } }
41.651163
137
0.684813
4b3599e5a8251595b6ee50764fc130736cf30fa7
916
/** * Created by wyd on 2019/2/13 10:36:11. */ public class Test { @org.junit.Test public void s() { System.out.println(1 << 4); System.out.println(1 << 3); System.out.println(1 << 2); System.out.println(1 << 1); System.out.println(1 << 0); } @org.junit.Test public void ox() { System.out.println(0x00); System.out.println(0x01); System.out.println(0x02); System.out.println(0x04); System.out.println(0x05); } @org.junit.Test public void oxbyte() { byte d0 = 0x00; byte d5 = 0x05; byte d5a = 0x05 & 0xFFFF; byte[] bytes = new byte[]{0x05, 0x01}; System.out.println(bytes); System.out.println(0x61); System.out.println((byte) 0x61); System.out.println((char) 0x61); } }
21.809524
46
0.498908
9f5c68711ef1a048827d2d9bcde8f7638e3b0ad1
11,452
package org.rarefiedredis.adapter; import org.rarefiedredis.redis.IRedisClient; import org.rarefiedredis.redis.NoKeyException; import org.rarefiedredis.redis.WrongTypeException; import org.rarefiedredis.redis.NotImplementedException; import org.rarefiedredis.redis.IndexOutOfRangeException; import java.util.List; import java.util.Iterator; import java.util.ListIterator; import java.util.Collection; public final class RedisListAdapter implements List<String> { private IRedisClient client; private String key; public RedisListAdapter(IRedisClient client, String key) { this.client = client; this.key = key; } @Override public boolean add(String e) throws IllegalArgumentException, UnsupportedOperationException { try { client.rpush(key, e); } catch (WrongTypeException x) { throw new IllegalArgumentException(); } catch (NotImplementedException x) { throw new UnsupportedOperationException(); } return true; } @Override public void add(int index, String e) throws NullPointerException, IndexOutOfBoundsException, IllegalArgumentException, UnsupportedOperationException { if (e == null) { throw new NullPointerException(); } try { client.lset(key, (long)index, e); return; } catch (IndexOutOfRangeException x) { throw new IndexOutOfBoundsException(); } catch (NoKeyException x) { throw new IllegalArgumentException(); } catch (WrongTypeException x) { throw new IllegalArgumentException(); } catch (NotImplementedException x) { throw new UnsupportedOperationException(); } } @Override public boolean addAll(Collection<? extends String> c) { Iterator<? extends String> iter = c.iterator(); while (iter.hasNext()) { try { if (!add((String)iter.next())) { return false; } } catch (Exception e) { return false; } } return true; } @Override public boolean addAll(int index, Collection<? extends String> c) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void clear() throws UnsupportedOperationException { try { client.del(key); } catch (NotImplementedException e) { throw new UnsupportedOperationException(); } } @Override public boolean contains(Object o) throws NullPointerException, ClassCastException { if (o == null) { throw new NullPointerException(); } if (!(o instanceof String)) { throw new ClassCastException(); } String element = (String)o; try { Long atATime = 10L; Long start = 0L; Long stop = start + atATime - 1L; while (true) { List<String> range = client.lrange(key, start, stop); if (range.isEmpty()) { break; } if (range.contains(element)) { return true; } start = stop + 1L; stop = start + atATime - 1L; } } catch (WrongTypeException e) { return false; } catch (NotImplementedException e) { return false; } return false; } @Override public boolean containsAll(Collection<?> c) { Iterator<?> iter = c.iterator(); while (iter.hasNext()) { Object next = iter.next(); try { if (!contains(next)) { return false; } } catch (Exception e) { return false; } } return true; } @Override public String get(int index) { try { return client.lindex(key, (long)index); } catch (WrongTypeException e) { return null; } catch (NotImplementedException e) { return null; } } @Override public int indexOf(Object o) throws NullPointerException, ClassCastException { if (o == null) { throw new NullPointerException(); } if (!(o instanceof String)) { throw new ClassCastException(); } String element = (String)o; Long index = 0L; try { Long atATime = 10L; Long start = 0L; Long stop = start + atATime - 1L; while (true) { List<String> range = client.lrange(key, start, stop); if (range.isEmpty()) { break; } if (range.indexOf(element) != -1) { return (int)(index + (long)range.indexOf(element)); } start = stop + 1L; stop = start + atATime - 1L; } } catch (WrongTypeException e) { return -1; } catch (NotImplementedException e) { return -1; } return -1; } @Override public boolean isEmpty() { try { return (long)client.llen(key) == 0L; } catch (WrongTypeException e) { return true; } catch (NotImplementedException e) { return true; } } @Override public Iterator<String> iterator() { return new Iterator<String>() { private Long index = 0L; @Override public boolean hasNext() { try { return index < client.llen(key); } catch (Exception e) { return false; } } @Override public String next() { try { return client.lindex(key, index++); } catch (Exception e) { return null; } } @Override public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } }; } @Override public int lastIndexOf(Object o) throws NullPointerException, ClassCastException { if (o == null) { throw new NullPointerException(); } if (!(o instanceof String)) { throw new ClassCastException(); } String element = (String)o; Long index = 0L; try { Long atATime = 10L; Long start = 0L; Long stop = start + atATime - 1L; while (true) { List<String> range = client.lrange(key, start, stop); if (range.isEmpty()) { break; } if (range.indexOf(element) != -1) { index = index + (long)range.indexOf(element); } start = stop + 1L; stop = start + atATime - 1L; } } catch (WrongTypeException e) { return -1; } catch (NotImplementedException e) { return -1; } return index.intValue(); } @Override public ListIterator<String> listIterator() { return null; } @Override public ListIterator<String> listIterator(int index) { return null; } @Override public String remove(int index) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public boolean remove(Object o) throws NullPointerException, ClassCastException { if (o == null) { throw new NullPointerException(); } if (!(o instanceof String)) { throw new ClassCastException(); } String element = (String)o; try { Long llen = client.llen(key); client.lrem(key, 1L, element); return llen > client.llen(key); } catch (Exception e) { return false; } } @Override public boolean removeAll(Collection<?> c) { boolean changed = false; Iterator<?> iter = c.iterator(); while (iter.hasNext()) { Object o = iter.next(); try { if (remove(o)) { changed = true; } } catch (Exception e) { return false; } } return changed; } @Override public boolean retainAll(Collection<?> c) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public String set(int index, String element) throws NullPointerException, IndexOutOfBoundsException, IllegalArgumentException, UnsupportedOperationException { if (element == null) { throw new NullPointerException(); } try { String previous = client.lindex(key, (long)index); client.lset(key, (long)index, element); return previous; } catch (IndexOutOfRangeException e) { throw new IndexOutOfBoundsException(); } catch (NoKeyException e) { throw new IllegalArgumentException(); } catch (WrongTypeException e) { throw new IllegalArgumentException(); } catch (NotImplementedException e) { throw new UnsupportedOperationException(); } } @Override public int size() { try { return client.llen(key).intValue(); } catch (WrongTypeException e) { return 0; } catch (NotImplementedException e) { return 0; } } @Override public List<String> subList(int fromIndex, int toIndex) { try { return client.lrange(key, (long)fromIndex, (long)(toIndex + 1)); } catch (WrongTypeException e) { return null; } catch (NotImplementedException e) { return null; } } @Override public Object[] toArray() { Long llen; try { llen = client.llen(key); } catch (Exception e) { return null; } Object[] array = new Object[llen.intValue()]; int index = 0; try { Long atATime = 10L; Long start = 0L; Long stop = start + atATime - 1L; while (true) { List<String> range = client.lrange(key, start, stop); if (range.isEmpty()) { break; } for (int idx = 0; idx < range.size(); ++idx, ++index) { array[index] = range.get(idx); } start = stop + 1L; stop = start + atATime - 1L; } } catch (WrongTypeException e) { return null; } catch (NotImplementedException e) { return null; } return array; } @Override public <T> T[] toArray(T[] a) { return null; } }
29.364103
172
0.506986
954674d0424b19e34a323f07c1e19609bc307751
1,144
/* * 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 lab3_stephaniemartinez_y_brauliocalix; /** * * @author User */ public class Armas { private String nombre; private int alcance; private double precio; public Armas() { } public Armas(String nombre, int alcance, double precio) { this.nombre = nombre; this.alcance = alcance; this.precio = precio; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public int getAlcance() { return alcance; } public void setAlcance(int alcance) { this.alcance = alcance; } public double getPrecio() { return precio; } public void setPrecio(double precio) { this.precio = precio; } @Override public String toString() { return " Armas{" + "nombre = " + nombre + ", alcance = " + alcance + ", precio = " + precio + '}'; } }
20.428571
109
0.598776
2788709d4b608934ade3548d72ac52f7f31dc4a5
2,992
package uk.gov.dvsa.mot.reporting; import com.github.mkolisnyk.cucumber.reporting.CucumberDetailedResults; import com.github.mkolisnyk.cucumber.reporting.CucumberResultsOverview; /** * Reporting class used to generate HTML reports based on the Cucumber json report. */ public class CucumberReporting { /** * Called by the Gradle reporting task to generate the HTML reports. * @param args Command line arguments (unused) * @throws Exception Error producing the report */ public static void main(String[] args) throws Exception { String outputDirectory = "target/"; String sourceFile = "build/reports/selenium/selenium.json"; String outputName = "cucumber"; String screenShotLocation = "screenshots/"; generateOverviewReport(outputDirectory, sourceFile, outputName); generateFeatureReport(outputDirectory, sourceFile, outputName, screenShotLocation); } /** * Generate the HTML report on features, scenarios, and steps broken down by feature. * @param outputDirectory The directory to output the report to and the base directory for screenshots * @param sourceFile The json file used to generate the HTML reports * @param outputName The prefix given to the report * @param screenShotLocation The location from the outputDirectory to store screenshots for the report * @throws Exception Error producing the report */ private static void generateFeatureReport(String outputDirectory, String sourceFile, String outputName, String screenShotLocation) throws Exception { CucumberDetailedResults cucumberDetailedResults = new CucumberDetailedResults(); cucumberDetailedResults.setOutputDirectory(outputDirectory); cucumberDetailedResults.setOutputName(outputName); cucumberDetailedResults.setSourceFile(sourceFile); cucumberDetailedResults.setScreenShotLocation(screenShotLocation); cucumberDetailedResults.execute(true, new String[] {}); } /** * Generate the overview HTML report including pie chart, feature breakdown, and scenario breakdown. * @param outputDirectory The directory to output the report to * @param sourceFile The json file used to generate the HTML reports * @param outputName The prefix given to the report * @throws Exception Error producing the report */ private static void generateOverviewReport(String outputDirectory, String sourceFile, String outputName) throws Exception { CucumberResultsOverview cucumberResultsOverview = new CucumberResultsOverview(); cucumberResultsOverview.setOutputDirectory(outputDirectory); cucumberResultsOverview.setOutputName(outputName); cucumberResultsOverview.setSourceFile(sourceFile); cucumberResultsOverview.execute(); } }
49.04918
112
0.713235
7aed99513df59a2cd915e5e757b5e865d9e7315a
248
Class EvenorOdd{ public static void main(String args[]) { int i=45; if(i%2==0) { System.out.println("Prints! this is a Even Number"); } else { System.out.println("This is an odd number"); } System.out.println("Thank You"); } }
14.588235
52
0.625
eecc15ddb8a3917dc244cfafb9a195ded990c54d
2,895
package noppes.npcs.ai.pathfinder; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.pathfinding.PathPoint; import net.minecraft.util.EnumFacing; import net.minecraft.util.MathHelper; import net.minecraft.util.math.BlockPos; import noppes.npcs.entity.EntityNPCInterface; public class FlyNodeProcessor extends NodeProcessor{ public PathPoint getPathPointTo(Entity p_176161_1_) { return this.openPoint(MathHelper.floor_double(p_176161_1_.boundingBox.minX), MathHelper.floor_double(p_176161_1_.boundingBox.minY + 0.5D), MathHelper.floor_double(p_176161_1_.boundingBox.minZ)); } public PathPoint getPathPointToCoords(Entity p_176160_1_, double p_176160_2_, double p_176160_4_, double p_176160_6_) { return this.openPoint(MathHelper.floor_double(p_176160_2_ - (double)(p_176160_1_.width / 2.0F)), MathHelper.floor_double(p_176160_4_ + 0.5D), MathHelper.floor_double(p_176160_6_ - (double)(p_176160_1_.width / 2.0F))); } public int findPathOptions(PathPoint[] p_176164_1_, Entity p_176164_2_, PathPoint p_176164_3_, PathPoint p_176164_4_, float p_176164_5_) { int i = 0; EnumFacing[] aenumfacing = EnumFacing.values(); int j = aenumfacing.length; for (int k = 0; k < j; ++k) { EnumFacing enumfacing = aenumfacing[k]; PathPoint pathpoint2 = this.getSafePoint(p_176164_2_, p_176164_3_.xCoord + enumfacing.getFrontOffsetX(), p_176164_3_.yCoord + enumfacing.getFrontOffsetY(), p_176164_3_.zCoord + enumfacing.getFrontOffsetZ()); if (pathpoint2 != null && !pathpoint2.isFirst && pathpoint2.distanceTo(p_176164_4_) < p_176164_5_) { p_176164_1_[i++] = pathpoint2; } } return i; } private PathPoint getSafePoint(Entity p_176185_1_, int p_176185_2_, int p_176185_3_, int p_176185_4_) { int l = this.func_176186_b(p_176185_1_, p_176185_2_, p_176185_3_, p_176185_4_); return l == -1 ? this.openPoint(p_176185_2_, p_176185_3_, p_176185_4_) : null; } private int func_176186_b(Entity entityIn, int x, int y, int z) { for (int i = x; i < x + this.entitySizeX; ++i) { for (int j = y; j < y + this.entitySizeY; ++j) { for (int k = z; k < z + this.entitySizeZ; ++k) { Block block = this.blockaccess.getBlock(i, j, k); if(block.getMaterial() == Material.water && entityIn instanceof EntityNPCInterface && ((EntityNPCInterface)entityIn).ai.canSwim) continue; if (block.getMaterial() != Material.air) { return 0; } } } } return -1; } }
39.121622
225
0.642487
a6ef391ff1f7468feff5183414e6b9082eefccfc
1,373
import com.avaje.ebean.Ebean; import models.auth.Bind; import org.junit.Test; import javax.persistence.PersistenceException; import static play.test.Helpers.fakeApplication; import static play.test.Helpers.running; /** * Created by zjh on 15-1-10. */ public class BindTest { @Test public void isBindMac(){ running(fakeApplication(), new Runnable() { @Override public void run() { String mac = "00:ad:05:01:a6:85"; Bind bind = Ebean.find(Bind.class).where().eq("mac", mac).findUnique(); if (bind != null){ System.out.println("mac地址已经绑定账号了"); }else{ System.out.println("mac地址还没有绑定账号"); } } }); } @Test public void newBind(){ running(fakeApplication(), new Runnable() { @Override public void run() { try { long userid = 3; String mac = "01:ad:05:01:a6:85"; Bind bind = new Bind(userid, mac); bind.save(); System.out.println("insert id -> " + bind.getId()); }catch (PersistenceException e){ System.out.println("duplicate mac insert failed"); } } }); } }
28.020408
87
0.492353
d04410474db8e629785cba470bb9c36170373721
1,417
import javax.swing.*; import java.awt.*; import java.awt.geom.*; import java.util.ArrayList; public class Lattice { private int width, height; private int stick_thick; private int level; private int max_level; private ArrayList<Rectangle2D.Double> sticks; Color[] colors = { new Color(249, 65, 68), new Color(248, 150, 30), new Color(144, 190, 109), new Color(87, 117, 144) }; private boolean visible; public void level_up() { if(level==max_level) { sticks.clear(); level = 0; } level += 1; // each level introduces 1<<level sticks for(int t = 1; t < (1<<level); t += 2) { int v = (width*t)/(1<<level) - stick_thick/2; sticks.add(new Rectangle2D.Double(v,0,stick_thick,height)); sticks.add(new Rectangle2D.Double(0,v,width,stick_thick)); } } public Lattice(int width, int height, int max_level) { this.width = width; this.height = height; this.max_level = max_level; sticks = new ArrayList<Rectangle2D.Double>(); this.stick_thick = 6; this.level = 0; level_up(); this.visible = false; } public void draw(Graphics2D g2d) { if(!visible) return; int i = sticks.size()-1; for(int t = level; t >= 1; t--) { g2d.setColor(colors[t-1]); for(int k = 0; k < (1<<t); k++, i--) { // System.out.println(sticks.get(i)); g2d.fill(sticks.get(i)); } } } public void toggleVisibility() { visible = !visible; } }
18.644737
62
0.629499
8575ab1c60b302f9919c5a46481469a664a2cf6f
1,598
package com.sequenceiq.redbeams.filter; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.sequenceiq.redbeams.service.ThreadBasedRequestIdProvider; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mock; public class RequestIdFilterTest { private static final String REQUEST_ID = "requestId1"; private RequestIdFilter underTest; @Mock private ThreadBasedRequestIdProvider threadBasedRequestIdProvider; @Mock private HttpServletRequest request; @Mock private HttpServletResponse response; @Mock private FilterChain filterChain; @Before public void setUp() { initMocks(this); underTest = new RequestIdFilter(threadBasedRequestIdProvider); } @Test public void testDoFilterInternal() throws IOException, ServletException { when(request.getHeader("x-cdp-request-id")).thenReturn(REQUEST_ID); underTest.doFilterInternal(request, response, filterChain); InOrder inOrder = inOrder(threadBasedRequestIdProvider, filterChain); inOrder.verify(threadBasedRequestIdProvider).setRequestId(REQUEST_ID); inOrder.verify(filterChain).doFilter(request, response); inOrder.verify(threadBasedRequestIdProvider).removeRequestId(); } }
27.084746
78
0.767835
a45e11ff80a2c0f3ee802f135b9a84211df3ed77
2,015
package ru.job4j.chess.figures; import org.junit.Test; import ru.job4j.chess.Cell; import ru.job4j.chess.ImpossibleMoveException; import ru.job4j.chess.figures.Figure; import ru.job4j.chess.figures.King; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class KingTest { @Test public void whenKingCantReachDistanation() { King king = new King(new Cell(5, 3)); String result = "no exception"; try { king.way(king.position, new Cell(5, 5)); } catch (ImpossibleMoveException e) { result = "right exception"; } catch (RuntimeException e) { result = "wrong exception"; } assertThat(result, is("right exception")); } @Test public void whenKingCanReachDistanation() { King king = new King(new Cell(5, 3)); String result = "no exception"; try { king.way(king.position, new Cell(4, 2)); king.way(king.position, new Cell(5, 2)); king.way(king.position, new Cell(6, 2)); king.way(king.position, new Cell(6, 3)); king.way(king.position, new Cell(6, 4)); king.way(king.position, new Cell(5, 4)); king.way(king.position, new Cell(4, 4)); king.way(king.position, new Cell(4, 3)); } catch (ImpossibleMoveException e) { result = "right exception"; } catch (RuntimeException e) { result = "wrong exception"; } assertThat(result, is("no exception")); } @Test public void whenFigureCantStay() { String result = "no exception"; Figure figure = new King(new Cell(5, 3)); try { figure.way(figure.position, figure.position); } catch (ImpossibleMoveException e) { result = "right exception"; } catch (RuntimeException e) { result = "wrong exception"; } assertThat(result, is("right exception")); } }
32.5
57
0.584119
8475a70ae5741928a6d5c22c69d9df7566d126d0
5,506
package cn.justquiet.daoimpl; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import cn.justquiet.bean.Student; import cn.justquiet.bean.Teacher; import cn.justquiet.dao.PersonDAO; import cn.justquiet.db.DBConnection; import cn.justquiet.db.DBUtils; public class PersonDAOImpl implements PersonDAO{ /** * 判断学生用户名和密码是否正确,并返回相应准确的错误信息 * (用数字表示返回结果,3 用户名和密码正确、2 密码错误、1 用户名错误、0 用户名和密码都错误) * * @param id * @param password */ @SuppressWarnings("resource") @Override public int isStudent(String id, String password) { int flag = 0; Connection con = null; String sql = "select * from tb_student where sid = '"+id+"' and spassword = '"+password+"'"; Statement stmt = null; ResultSet rs = null; try { con = DBConnection.getConnection(); stmt = con.createStatement(); rs = stmt.executeQuery(sql); if(rs != null && rs.next()) { flag = 3; return flag; }else { sql = "select * from tb_student where sid = '"+id+"'"; stmt = con.prepareStatement(sql); rs = stmt.executeQuery(sql); if(rs != null && rs.next()) { flag = 2; return flag; }else { sql = "select * from tb_student where spassword = '"+password+"'"; stmt = con.prepareStatement(sql); rs = stmt.executeQuery(sql); if(rs != null && rs.next()) { flag = 1; return flag; } } } }catch(Exception e) { e.printStackTrace(); }finally { DBUtils.closeObject(rs, stmt, con); } return flag; } /** * 判断教师用户名和密码是否正确,并返回相应准确的错误信息 * (用数字表示返回结果,3 用户名和密码正确、2 密码错误、1 用户名错误、0 用户名和密码都错误) * * @param id * @param password */ @SuppressWarnings("resource") @Override public int isTeacher(String id, String password) { int flag = 0; Connection con = null; String sql = "select * from tb_teacher where taccount = '"+id+"' and tpassword = '"+password+"'"; Statement stmt = null; ResultSet rs = null; try { con = DBConnection.getConnection(); stmt = con.createStatement(); rs = stmt.executeQuery(sql); if(rs!=null&&rs.next()) { flag = 3; return flag; }else { sql = "select * from tb_teacher where taccount = '"+id+"'"; stmt = con.prepareStatement(sql); rs = stmt.executeQuery(sql); if(rs!=null&&rs.next()) { flag = 2; return flag; }else { sql = "select * from tb_teacher where tpassword = '"+password+"'"; stmt = con.prepareStatement(sql); rs = stmt.executeQuery(sql); if(rs!=null&&rs.next()) { flag = 1; return flag; } } } }catch(Exception e) { e.printStackTrace(); }finally { DBUtils.closeObject(rs, stmt, con); } return flag; } /** * 根据学生id查询学生信息 * * @param sql 数据库查询语句--查询指定学生信息 * @return List 返回结果--List类型 */ @Override public List<Student> executeQueryStuById(String sid) { List<Student> liststu = null; Connection con = null; String sql = "select * from tb_student where sid = '"+sid+"'"; Statement stmt = null; ResultSet rs = null; try { con = DBConnection.getConnection(); stmt = con.createStatement(); liststu = new ArrayList<Student>(); rs = stmt.executeQuery(sql); while (rs.next()) { Student stu = new Student(); int i = 1; stu.setSid(rs.getString(i++)); stu.setSpassword(rs.getString(i++)); stu.setSname(rs.getString(i++)); stu.setSnickname(rs.getString(i++)); stu.setCid(rs.getInt(i++)); stu.setSlevel(rs.getInt(i++)); stu.setSexperience(rs.getString(i++)); stu.setSactive(rs.getInt(i++)); liststu.add(stu);// 将结果加入到List中以便返回 } } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeObject(rs, stmt, con); } return liststu; } /** * 根据教师id查询教师信息 * * @param sql 数据库查询语句--查询指定教师信息 * @return List 返回结果--List类型 */ @Override public List<Teacher> executeQueryTeaById(String tid) { List<Teacher> listtea = null; Connection con = null; String sql = "select * from tb_teacher where taccount = '"+tid+"'"; Statement stmt = null; ResultSet rs = null; try { con = DBConnection.getConnection(); stmt = con.createStatement(); listtea = new ArrayList<Teacher>(); rs = stmt.executeQuery(sql); while (rs.next()) { Teacher tea = new Teacher(); int i = 1; tea.setTid(rs.getInt(i++)); tea.setTaccount(rs.getString(i++)); tea.setTpassword(rs.getString(i++)); tea.setTname(rs.getString(i++)); tea.setTnickname(rs.getString(i++)); tea.setTlevel(rs.getString(i++)); tea.setTexperience(rs.getString(i++)); tea.setTactive(rs.getInt(i++)); listtea.add(tea);// 将结果加入到List中以便返回 } } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeObject(rs, stmt, con); } return listtea; } /** * 根据班级id查询所有学生信息 */ @Override public List<Student> executeQueryStuByCid(int cid) { List<Student> liststu = null; Connection con = null; String sql = "select * from tb_student where cid = '"+cid+"'"; Statement stmt = null; ResultSet rs = null; try { con = DBConnection.getConnection(); stmt = con.createStatement(); liststu = new ArrayList<Student>(); rs = stmt.executeQuery(sql); while (rs.next()) { Student stu = new Student(); stu.setSid(rs.getString(1)); stu.setSname(rs.getString(3)); liststu.add(stu);// 将结果加入到List中以便返回 } } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.closeObject(rs, stmt, con); } return liststu; } }
24.801802
99
0.630948
fb24e96a9147cf683c8969e3cd9042608d17e3ba
2,300
package team.gutterteam123.ledanimation.devices; import io.github.splotycode.mosaik.domparsing.annotation.FileSystem; import io.github.splotycode.mosaik.domparsing.annotation.parsing.SerialisedEntryParser; import io.github.splotycode.mosaik.runtime.LinkBase; import io.github.splotycode.mosaik.runtime.Links; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import java.io.Serializable; import java.util.*; @Getter public class Scene implements Serializable { private static final long serialVersionUID = 1L; public static final FileSystem<Scene> FILE_SYSTEM = LinkBase.getInstance().getLink(Links.PARSING_FILEPROVIDER).provide("scenes", new SerialisedEntryParser()); public static Scene saveCurrent(String name) { Map<String, Map<ChannelType, Short>> values = new HashMap<>(); for (Controllable controllable : Controllable.FILE_SYSTEM.getEntries()) { Map<ChannelType, Short> channels = new HashMap<>(); for (ChannelType channel : controllable.getChannels()) { channels.put(channel, controllable.getValue(channel).getValue()); } values.put(controllable.displayName(), channels); } return new Scene(name, values); } private String name; private Map<String, Map<ChannelType, Short>> values; public Scene(String name, Map<String, Map<ChannelType, Short>> values) { this.name = name; this.values = values; } @Getter @Setter private boolean visible; public List<String> load() { List<String> failedDevices = null; for (Map.Entry<String, Map<ChannelType, Short>> device : values.entrySet()) { Controllable dev = Controllable.FILE_SYSTEM.getEntry(device.getKey()); if (dev == null) { if (failedDevices == null) { failedDevices = new ArrayList<>(); } failedDevices.add(device.getKey()); continue; } for (Map.Entry<ChannelType, Short> channel : device.getValue().entrySet()) { dev.setChannel(null, channel.getKey(), channel.getValue()); } } return failedDevices == null ? Collections.emptyList() : failedDevices; } }
35.384615
162
0.655652
43501b7d084ba0b6494605c6e3667bc651123a0f
2,593
package net.creeperhost.resourcefulcreepers.data; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import java.util.ArrayList; import java.util.List; public class CreeperType { private final String name; private final String displayName; private final int tier; private final int spawnEggColour1; private final int spawnEggColour2; private final boolean dropItemsOnDeath; private final int spawnWeight; private final boolean allowNaturalSpawns; private final double armourValue; private final List<ItemDrop> itemDrops; public CreeperType(String name, String displayName, int tier, int spawnEggColour1, int spawnEggColour2, boolean dropItemsOnDeath, int spawnWeight, boolean allowNaturalSpawns, double armourValue, List<ItemDrop> itemDrops) { this.name = name; this.displayName = displayName; this.tier = tier; this.spawnEggColour1 = spawnEggColour1; this.spawnEggColour2 = spawnEggColour2; this.dropItemsOnDeath = dropItemsOnDeath; this.spawnWeight = spawnWeight; this.allowNaturalSpawns = allowNaturalSpawns; this.armourValue = armourValue; this.itemDrops = itemDrops; } public String getName() { return name; } public String getDisplayName() { return displayName; } public int getSpawnEggColour1() { return spawnEggColour1; } public int getSpawnEggColour2() { return spawnEggColour2; } public int getTier() { return tier; } public boolean shouldDropItemsOnDeath() { return dropItemsOnDeath; } public int getSpawnWeight() { return spawnWeight; } public boolean allowNaturalSpawns() { return allowNaturalSpawns; } public double getArmourValue() { return armourValue; } public List<ItemDrop> getItemDrops() { return itemDrops; } public ArrayList<ItemStack> getItemDropsAsList() { ArrayList<ItemStack> itemStacks = new ArrayList<>(); for (ItemDrop itemDrop : getItemDrops()) { Item item = Registry.ITEM.get(new ResourceLocation(itemDrop.getName())); if(item != null && item != Items.AIR) { itemStacks.add(new ItemStack(item, itemDrop.getAmount())); } } return itemStacks; } }
25.174757
224
0.660239
6303a5d91c3c4dcacb8d6087d7d6252553cd7b57
248
package com.tekwill.learning.hw; public class ShowDivisibleNumbersDemo { public static void main(String[] args) { ShowDivisibleNumbers service = new ShowDivisibleNumbers(); service.printDivisibleNumbers(100, 1000, 10); } }
27.555556
66
0.721774
98cdfc115297f9b8a5fa11f12faf7b85968dbf61
1,478
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: provenance/attribute/v1/tx.proto package io.provenance.attribute.v1; public interface MsgDeleteAttributeRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:provenance.attribute.v1.MsgDeleteAttributeRequest) com.google.protobuf.MessageOrBuilder { /** * <pre> * The attribute name. * </pre> * * <code>string name = 1;</code> * @return The name. */ java.lang.String getName(); /** * <pre> * The attribute name. * </pre> * * <code>string name = 1;</code> * @return The bytes for name. */ com.google.protobuf.ByteString getNameBytes(); /** * <pre> * The account to add the attribute to. * </pre> * * <code>string account = 2;</code> * @return The account. */ java.lang.String getAccount(); /** * <pre> * The account to add the attribute to. * </pre> * * <code>string account = 2;</code> * @return The bytes for account. */ com.google.protobuf.ByteString getAccountBytes(); /** * <pre> * The address that the name must resolve to. * </pre> * * <code>string owner = 3;</code> * @return The owner. */ java.lang.String getOwner(); /** * <pre> * The address that the name must resolve to. * </pre> * * <code>string owner = 3;</code> * @return The bytes for owner. */ com.google.protobuf.ByteString getOwnerBytes(); }
21.114286
100
0.606901
0461abf20b216b6669526a9693a3aaaa60c64d79
709
package com.database.postservice; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.database.post.entity.Post; import com.database.post.repository.PostRepository; @Service public class PostService { @Autowired PostRepository postrepo; public List<Post> getAllPost(){ return postrepo.findAll(); } public Post SavePost(Post post) { return postrepo.save(post); } public Post getPostById(Long Id) { return postrepo.findById(Id).get(); } public void DeletePostById(Long id) { System.out.println("Pir sultan abdalim "+id); postrepo.deleteById(id); } }
18.179487
62
0.719323
62e29ce15dd3ffe37a3080867edb0b2103c9a5db
80,035
package org.jruby.util.io; import org.jcodings.Encoding; import org.jcodings.EncodingDB; import org.jcodings.Ptr; import org.jcodings.specific.ASCIIEncoding; import org.jcodings.specific.USASCIIEncoding; import org.jcodings.specific.UTF16BEEncoding; import org.jcodings.specific.UTF16LEEncoding; import org.jcodings.specific.UTF32BEEncoding; import org.jcodings.specific.UTF32LEEncoding; import org.jcodings.specific.UTF8Encoding; import org.jcodings.transcode.EConv; import org.jcodings.transcode.EConvFlags; import org.jcodings.transcode.EConvResult; import org.jcodings.transcode.Transcoder; import org.jcodings.transcode.TranscoderDB; import org.jcodings.transcode.Transcoding; import org.jcodings.unicode.UnicodeEncoding; import org.jcodings.util.CaseInsensitiveBytesHash; import org.jruby.Ruby; import org.jruby.RubyArray; import org.jruby.RubyBasicObject; import org.jruby.RubyConverter; import org.jruby.RubyEncoding; import org.jruby.RubyFixnum; import org.jruby.RubyHash; import org.jruby.RubyIO; import org.jruby.RubyInteger; import org.jruby.RubyMethod; import org.jruby.RubyNumeric; import org.jruby.RubyProc; import org.jruby.RubyString; import org.jruby.RubySymbol; import org.jruby.exceptions.RaiseException; import org.jruby.platform.Platform; import org.jruby.runtime.Block; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.runtime.encoding.EncodingCapable; import org.jruby.runtime.encoding.EncodingService; import org.jruby.util.ByteList; import org.jruby.util.ByteListHolder; import org.jruby.util.CodeRangeSupport; import org.jruby.util.CodeRangeable; import org.jruby.util.Sprintf; import org.jruby.util.StringSupport; import org.jruby.util.TypeConverter; import java.util.Arrays; public class EncodingUtils { public static final int ECONV_DEFAULT_NEWLINE_DECORATOR = Platform.IS_WINDOWS ? EConvFlags.UNIVERSAL_NEWLINE_DECORATOR : 0; public static final int DEFAULT_TEXTMODE = Platform.IS_WINDOWS ? OpenFile.TEXTMODE : 0; public static final int TEXTMODE_NEWLINE_DECORATOR_ON_WRITE = Platform.IS_WINDOWS ? EConvFlags.CRLF_NEWLINE_DECORATOR : 0; private static final byte[] NULL_BYTE_ARRAY = ByteList.NULL_ARRAY; // rb_to_encoding public static Encoding rbToEncoding(ThreadContext context, IRubyObject enc) { if (enc instanceof RubyEncoding) return ((RubyEncoding) enc).getEncoding(); return toEncoding(context, enc); } // to_encoding public static Encoding toEncoding(ThreadContext context, IRubyObject enc) { RubyString encStr = enc.convertToString(); if (!encStr.getEncoding().isAsciiCompatible()) { throw context.runtime.newArgumentError("invalid name encoding (non ASCII)"); } Encoding idx = context.runtime.getEncodingService().getEncodingFromObject(encStr); // check for missing encoding is in getEncodingFromObject return idx; } public static IRubyObject[] openArgsToArgs(Ruby runtime, IRubyObject firstElement, RubyHash options) { IRubyObject value = hashARef(runtime, options, "open_args"); if (value.isNil()) return new IRubyObject[] { firstElement, options }; RubyArray array = value.convertToArray(); IRubyObject[] openArgs = new IRubyObject[array.size()]; value.convertToArray().toArray(openArgs); IRubyObject[] args = new IRubyObject[openArgs.length + 1]; args[0] = firstElement; System.arraycopy(openArgs, 0, args, 1, openArgs.length); return args; } // FIXME: This could be smarter amount determining whether optionsArg is a RubyHash and !null (invariant) // mri: extract_binmode public static void extractBinmode(Ruby runtime, IRubyObject optionsArg, int[] fmode_p) { int fmodeMask = 0; IRubyObject v = hashARef(runtime, optionsArg, "textmode"); if (!v.isNil() && v.isTrue()) fmodeMask |= OpenFile.TEXTMODE; v = hashARef(runtime, optionsArg, "binmode"); if (!v.isNil() && v.isTrue()) fmodeMask |= OpenFile.BINMODE; if ((fmodeMask & OpenFile.BINMODE) != 0 && (fmodeMask & OpenFile.TEXTMODE) != 0) { throw runtime.newArgumentError("both textmode and binmode specified"); } fmode_p[0] |= fmodeMask; } private static IRubyObject hashARef(Ruby runtime, IRubyObject hash, String symbol) { if (hash == null || !(hash instanceof RubyHash)) return runtime.getNil(); IRubyObject value = ((RubyHash) hash).fastARef(runtime.newSymbol(symbol)); return value == null ? runtime.getNil() : value; } public static Encoding ascii8bitEncoding(Ruby runtime) { return runtime.getEncodingService().getAscii8bitEncoding(); } static final int VMODE = 0; static final int PERM = 1; public static Object vmodeVperm(IRubyObject vmode, IRubyObject vperm) { return new IRubyObject[] {vmode, vperm}; } public static IRubyObject vmode(Object vmodeVperm) { return ((IRubyObject[])vmodeVperm)[VMODE]; } public static void vmode(Object vmodeVperm, IRubyObject vmode) { ((IRubyObject[])vmodeVperm)[VMODE] = vmode; } public static IRubyObject vperm(Object vmodeVperm) { return ((IRubyObject[])vmodeVperm)[PERM]; } public static void vperm(Object vmodeVperm, IRubyObject vperm) { ((IRubyObject[])vmodeVperm)[PERM] = vperm; } public static final int MODE_BTMODE(int fmode, int a, int b, int c) { if ((fmode & OpenFile.BINMODE) != 0) { return b; } else if ((fmode & OpenFile.TEXTMODE) != 0) { return c; } return a; } public static int SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(Encoding enc2, int ecflags) { if (enc2 != null && (ecflags & ECONV_DEFAULT_NEWLINE_DECORATOR) != 0) { return ecflags | EConvFlags.UNIVERSAL_NEWLINE_DECORATOR; } return ecflags; } /* * This is a wacky method which is a very near port from MRI. pm passes in * a permissions value and a mode value. As a side-effect mode will get set * if this found any 'mode'-like stuff so the caller can know whether mode * has been handled yet. The same story for permission value. If it has * not been set then we know it needs to default permissions from the caller. */ // mri: rb_io_extract_modeenc public static void extractModeEncoding(ThreadContext context, IOEncodable ioEncodable, Object vmodeAndVperm_p, IRubyObject options, int[] oflags_p, int[] fmode_p) { Ruby runtime = context.runtime; int ecflags; IRubyObject[] ecopts_p = {context.nil}; boolean hasEnc = false, hasVmode = false; IRubyObject intmode; // Give default encodings ioExtIntToEncs(context, ioEncodable, null, null, 0); vmode_handle: do { if (vmode(vmodeAndVperm_p) == null || vmode(vmodeAndVperm_p).isNil()) { fmode_p[0] = OpenFile.READABLE; oflags_p[0] = ModeFlags.RDONLY; } else { intmode = TypeConverter.checkIntegerType(runtime, vmode(vmodeAndVperm_p), "to_int"); if (!intmode.isNil()) { vmode(vmodeAndVperm_p, intmode); oflags_p[0] = RubyNumeric.num2int(intmode); fmode_p[0] = ModeFlags.getOpenFileFlagsFor(oflags_p[0]); } else { String p = vmode(vmodeAndVperm_p).convertToString().asJavaString(); fmode_p[0] = OpenFile.ioModestrFmode(runtime, p); oflags_p[0] = OpenFile.ioFmodeOflags(fmode_p[0]); int colonSplit = p.indexOf(":"); if (colonSplit != -1) { hasEnc = true; parseModeEncoding(context, ioEncodable, p.substring(colonSplit + 1), fmode_p); } else { Encoding e = (fmode_p[0] & OpenFile.BINMODE) != 0 ? ascii8bitEncoding(runtime) : null; ioExtIntToEncs(context, ioEncodable, e, null, fmode_p[0]); } } } if (options == null || options.isNil()) { ecflags = (fmode_p[0] & OpenFile.READABLE) != 0 ? MODE_BTMODE(fmode_p[0], ECONV_DEFAULT_NEWLINE_DECORATOR, 0, EConvFlags.UNIVERSAL_NEWLINE_DECORATOR) : 0; if (TEXTMODE_NEWLINE_DECORATOR_ON_WRITE != 0) { ecflags |= (fmode_p[0] & OpenFile.WRITABLE) != 0 ? MODE_BTMODE(fmode_p[0], TEXTMODE_NEWLINE_DECORATOR_ON_WRITE, 0, TEXTMODE_NEWLINE_DECORATOR_ON_WRITE) : 0; } ecflags = SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(ioEncodable.getEnc2(), ecflags); ecopts_p[0] = context.nil; } else { if (!hasVmode) { IRubyObject v = ((RubyHash) options).op_aref(context, runtime.newSymbol("mode")); if (!v.isNil()) { if (vmode(vmodeAndVperm_p) != null && !vmode(vmodeAndVperm_p).isNil()) { throw runtime.newArgumentError("mode specified twice"); } hasVmode = true; vmode(vmodeAndVperm_p, v); continue vmode_handle; } } IRubyObject v = ((RubyHash) options).op_aref(context, runtime.newSymbol("flags")); if (!v.isNil()) { v = v.convertToInteger(); oflags_p[0] |= RubyNumeric.num2int(v); vmode(vmodeAndVperm_p, runtime.newFixnum(oflags_p[0])); fmode_p[0] = ModeFlags.getOpenFileFlagsFor(oflags_p[0]); } extractBinmode(runtime, options, fmode_p); // Differs from MRI but we open with ModeFlags if ((fmode_p[0] & OpenFile.BINMODE) != 0) { oflags_p[0] |= ModeFlags.BINARY; if (!hasEnc) { ioExtIntToEncs(context, ioEncodable, ascii8bitEncoding(runtime), null, fmode_p[0]); } } else if (DEFAULT_TEXTMODE != 0 && (vmode(vmodeAndVperm_p) == null || vmode(vmodeAndVperm_p).isNil())) { fmode_p[0] |= DEFAULT_TEXTMODE; } v = hashARef(runtime, options, "perm"); if (!v.isNil()) { if (vperm(vmodeAndVperm_p) != null) { if (!vperm(vmodeAndVperm_p).isNil()) throw runtime.newArgumentError("perm specified twice"); vperm(vmodeAndVperm_p, v); } } IRubyObject extraFlags = hashARef(runtime, options, "flags"); if (!extraFlags.isNil()) { oflags_p[0] |= extraFlags.convertToInteger().getIntValue(); } ecflags = (fmode_p[0] & OpenFile.READABLE) != 0 ? MODE_BTMODE(fmode_p[0], ECONV_DEFAULT_NEWLINE_DECORATOR, 0, EConvFlags.UNIVERSAL_NEWLINE_DECORATOR) : 0; if (TEXTMODE_NEWLINE_DECORATOR_ON_WRITE != -1) { ecflags |= (fmode_p[0] & OpenFile.WRITABLE) != 0 ? MODE_BTMODE(fmode_p[0], TEXTMODE_NEWLINE_DECORATOR_ON_WRITE, 0, TEXTMODE_NEWLINE_DECORATOR_ON_WRITE) : 0; } if (ioExtractEncodingOption(context, ioEncodable, options, fmode_p)) { if (hasEnc) throw runtime.newArgumentError("encoding specified twice"); } ecflags = SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(ioEncodable.getEnc2(), ecflags); ecflags = econvPrepareOptions(context, options, ecopts_p, ecflags); } EncodingUtils.validateEncodingBinmode(context, fmode_p, ecflags, ioEncodable); ioEncodable.setEcflags(ecflags); ioEncodable.setEcopts(ecopts_p[0]); return; } while (true); } // mri: rb_io_extract_encoding_option public static boolean ioExtractEncodingOption(ThreadContext context, IOEncodable ioEncodable, IRubyObject options, int[] fmode_p) { Ruby runtime = context.runtime; IRubyObject encoding = context.nil; IRubyObject extenc = null; IRubyObject intenc = null; IRubyObject tmp; boolean extracted = false; Encoding extencoding = null; Encoding intencoding = null; if (options != null && !options.isNil()) { RubyHash opts = (RubyHash) options; IRubyObject encodingOpt = opts.op_aref(context, runtime.newSymbol("encoding")); if (!encodingOpt.isNil()) encoding = encodingOpt; IRubyObject externalOpt = opts.op_aref(context, runtime.newSymbol("external_encoding")); if (!externalOpt.isNil()) extenc = externalOpt; IRubyObject internalOpt = opts.op_aref(context, runtime.newSymbol("internal_encoding")); if (!internalOpt.isNil()) intenc = internalOpt; } if ((extenc != null || intenc != null) && !encoding.isNil()) { if (runtime.isVerbose()) { runtime.getWarnings().warn("Ignoring encoding parameter '" + encoding + "': " + (extenc == null ? "internal" : "external") + "_encoding is used"); } encoding = context.nil; } if (extenc != null && !extenc.isNil()) { extencoding = rbToEncoding(context, extenc); } if (intenc != null) { if (intenc.isNil()) { intencoding = null; } else if (!(tmp = intenc.checkStringType19()).isNil()) { String p = tmp.toString(); if (p.equals("-")) { intencoding = null; } else { intencoding = rbToEncoding(context, intenc); } } else { intencoding = rbToEncoding(context, intenc); } if (extencoding == intencoding) { intencoding = null; } } if (!encoding.isNil()) { extracted = true; if (!(tmp = encoding.checkStringType19()).isNil()) { parseModeEncoding(context, ioEncodable, tmp.asJavaString(), fmode_p); } else { ioExtIntToEncs(context, ioEncodable, rbToEncoding(context, encoding), null, 0); } } else if (extenc != null || intenc != null) { extracted = true; ioExtIntToEncs(context, ioEncodable, extencoding, intencoding, 0); } return extracted; } // mri: rb_io_ext_int_to_encs public static void ioExtIntToEncs(ThreadContext context, IOEncodable encodable, Encoding external, Encoding internal, int fmode) { boolean defaultExternal = false; if (external == null) { external = context.runtime.getDefaultExternalEncoding(); defaultExternal = true; } if (external == ascii8bitEncoding(context.runtime)) { internal = null; } else if (internal == null) { internal = context.runtime.getDefaultInternalEncoding(); } if (internal == null || ((fmode & OpenFile.SETENC_BY_BOM) == 0 && internal == external)) { encodable.setEnc((defaultExternal && internal != external) ? null : external); encodable.setEnc2(null); } else { encodable.setEnc(internal); encodable.setEnc2(external); } } // mri: parse_mode_enc public static void parseModeEncoding(ThreadContext context, IOEncodable ioEncodable, String option, int[] fmode_p) { Ruby runtime = context.runtime; EncodingService service = runtime.getEncodingService(); Encoding idx2; Encoding intEnc, extEnc; if (fmode_p == null) fmode_p = new int[]{0}; String estr; String[] encs = option.split(":", 2); if (encs.length == 2) { estr = encs[0]; } else { estr = option; } if (estr.toLowerCase().startsWith("bom|")) { estr = estr.substring(4); if (estr.toLowerCase().startsWith("utf-")) { fmode_p[0] |= OpenFile.SETENC_BY_BOM; ioEncodable.setBOM(true); } else { runtime.getWarnings().warn("BOM with non-UTF encoding " + estr + " is nonsense"); fmode_p[0] &= ~OpenFile.SETENC_BY_BOM; } } Encoding idx = service.findEncodingNoError(new ByteList(estr.getBytes())); if (idx == null) { runtime.getWarnings().warn("Unsupported encoding " + estr + " ignored"); extEnc = null; } else { extEnc = idx; } intEnc = null; if (encs.length == 2) { if (encs[1].equals("-")) { intEnc = null; } else { idx2 = service.getEncodingFromString(encs[1]); if (idx2 == null) { context.runtime.getWarnings().warn("ignoring internal encoding " + idx2 + ": it is identical to external encoding " + idx); intEnc = null; } else { intEnc = idx2; } } } ioExtIntToEncs(context, ioEncodable, extEnc, intEnc, fmode_p[0]); } // rb_econv_str_convert public static ByteList econvStrConvert(ThreadContext context, EConv ec, ByteList src, int flags) { return econvSubstrAppend(context, ec, src, null, flags); } // rb_econv_substr_append public static ByteList econvSubstrAppend(ThreadContext context, EConv ec, ByteList src, ByteList dst, int flags) { return econvAppend(context, ec, src, dst, flags); } // rb_econv_append public static ByteList econvAppend(ThreadContext context, EConv ec, ByteList sByteList, ByteList dst, int flags) { int len = sByteList.getRealSize(); Ptr sp = new Ptr(0); int se = 0; int ds = 0; int ss = sByteList.getBegin(); byte[] dBytes; Ptr dp = new Ptr(0); int de = 0; EConvResult res; int maxOutput; if (dst == null) { dst = new ByteList(len); if (ec.destinationEncoding != null) { dst.setEncoding(ec.destinationEncoding); } } if (ec.lastTranscoding != null) { maxOutput = ec.lastTranscoding.transcoder.maxOutput; } else { maxOutput = 1; } do { int dlen = dst.getRealSize(); if ((dst.getUnsafeBytes().length - dst.getBegin()) - dlen < len + maxOutput) { long newCapa = dlen + len + maxOutput; if (Integer.MAX_VALUE < newCapa) { throw context.runtime.newArgumentError("too long string"); } dst.ensure((int)newCapa); dst.setRealSize(dlen); } sp.p = ss; se = sp.p + len; dBytes = dst.getUnsafeBytes(); ds = dst.getBegin(); de = dBytes.length; dp.p = ds += dlen; res = ec.convert(sByteList.getUnsafeBytes(), sp, se, dBytes, dp, de, flags); len -= sp.p - ss; ss = sp.p; dst.setRealSize(dlen + (dp.p - ds)); EncodingUtils.econvCheckError(context, ec); } while (res == EConvResult.DestinationBufferFull); return dst; } // rb_econv_check_error public static void econvCheckError(ThreadContext context, EConv ec) { RaiseException re = makeEconvException(context.runtime, ec); if (re != null) throw re; } // rb_econv_prepare_opts public static int econvPrepareOpts(ThreadContext context, IRubyObject opthash, IRubyObject[] opts) { return econvPrepareOptions(context, opthash, opts, 0); } // rb_econv_prepare_options public static int econvPrepareOptions(ThreadContext context, IRubyObject opthash, IRubyObject[] opts, int ecflags) { IRubyObject newhash = context.nil; IRubyObject v; if (opthash.isNil()) { opts[0] = context.nil; return ecflags; } RubyHash optHash2 = (RubyHash)opthash; ecflags = econvOpts(context, opthash, ecflags); v = optHash2.op_aref(context, context.runtime.newSymbol("replace")); if (!v.isNil()) { RubyString v_str = v.convertToString(); if (v_str.scanForCodeRange() == StringSupport.CR_BROKEN) { throw context.runtime.newArgumentError("replacement string is broken: " + v_str); } v = v_str.freeze(context); newhash = RubyHash.newHash(context.runtime); ((RubyHash)newhash).op_aset(context, context.runtime.newSymbol("replace"), v); } v = optHash2.op_aref(context, context.runtime.newSymbol("fallback")); if (!v.isNil()) { IRubyObject h = TypeConverter.checkHashType(context.runtime, v); boolean condition; if (h.isNil()) { condition = (v instanceof RubyProc || v instanceof RubyMethod || v.respondsTo("[]")); } else { v = h; condition = true; } if (condition) { if (newhash.isNil()) { newhash = RubyHash.newHash(context.runtime); } ((RubyHash)newhash).op_aset(context, context.runtime.newSymbol("fallback"), v); } } if (!newhash.isNil()) { newhash.setFrozen(true); } opts[0] = newhash; return ecflags; } // econv_opts public static int econvOpts(ThreadContext context, IRubyObject opt, int ecflags) { Ruby runtime = context.runtime; IRubyObject v; v = ((RubyHash)opt).op_aref(context, runtime.newSymbol("invalid")); if (v.isNil()) { } else if (v.toString().equals("replace")) { ecflags |= EConvFlags.INVALID_REPLACE; } else { throw runtime.newArgumentError("unknown value for invalid character option"); } v = ((RubyHash)opt).op_aref(context, runtime.newSymbol("undef")); if (v.isNil()) { } else if (v.toString().equals("replace")) { ecflags |= EConvFlags.UNDEF_REPLACE; } else { throw runtime.newArgumentError("unknown value for undefined character option"); } v = ((RubyHash)opt).op_aref(context, runtime.newSymbol("replace")); if (!v.isNil() && (ecflags & EConvFlags.INVALID_REPLACE) != 0) { ecflags |= EConvFlags.UNDEF_REPLACE; } v = ((RubyHash)opt).op_aref(context, runtime.newSymbol("xml")); if (!v.isNil()) { if (v.toString().equals("text")) { ecflags |= EConvFlags.XML_TEXT_DECORATOR | EConvFlags.UNDEF_HEX_CHARREF; } else if (v.toString().equals("attr")) { ecflags |= EConvFlags.XML_ATTR_CONTENT_DECORATOR | EConvFlags.XML_ATTR_QUOTE_DECORATOR | EConvFlags.UNDEF_HEX_CHARREF; } else { throw runtime.newArgumentError("unexpected value for xml option: " + v); } } v = ((RubyHash)opt).op_aref(context, runtime.newSymbol("newline")); if (!v.isNil()) { ecflags &= ~EConvFlags.NEWLINE_DECORATOR_MASK; if (v.toString().equals("universal")) { ecflags |= EConvFlags.UNIVERSAL_NEWLINE_DECORATOR; } else if (v.toString().equals("crlf")) { ecflags |= EConvFlags.CRLF_NEWLINE_DECORATOR; } else if (v.toString().equals("cr")) { ecflags |= EConvFlags.CR_NEWLINE_DECORATOR; } else if (v.toString().equals("lf")) { // ecflags |= ECONV_LF_NEWLINE_DECORATOR; } else if (v instanceof RubySymbol) { throw runtime.newArgumentError("unexpected value for newline option: " + ((RubySymbol) v).to_s(context).toString()); } else { throw runtime.newArgumentError("unexpected value for newline option"); } } int setflags = 0; boolean newlineflag = false; v = ((RubyHash)opt).op_aref(context, runtime.newSymbol("universal_newline")); if (v.isTrue()) { setflags |= EConvFlags.UNIVERSAL_NEWLINE_DECORATOR; } newlineflag |= !v.isNil(); v = ((RubyHash)opt).op_aref(context, runtime.newSymbol("crlf_newline")); if (v.isTrue()) { setflags |= EConvFlags.CRLF_NEWLINE_DECORATOR; } newlineflag |= !v.isNil(); v = ((RubyHash)opt).op_aref(context, runtime.newSymbol("cr_newline")); if (v.isTrue()) { setflags |= EConvFlags.CR_NEWLINE_DECORATOR; } newlineflag |= !v.isNil(); if (newlineflag) { ecflags &= ~EConvFlags.NEWLINE_DECORATOR_MASK; ecflags |= setflags; } return ecflags; } // rb_econv_open_opts public static EConv econvOpenOpts(ThreadContext context, byte[] sourceEncoding, byte[] destinationEncoding, int ecflags, IRubyObject opthash) { Ruby runtime = context.runtime; IRubyObject replacement; if (opthash == null || opthash.isNil()) { replacement = context.nil; } else { if (!(opthash instanceof RubyHash) || !opthash.isFrozen()) { throw runtime.newRuntimeError("bug: EncodingUtils.econvOpenOpts called with invalid opthash"); } replacement = ((RubyHash)opthash).op_aref(context, runtime.newSymbol("replace")); } EConv ec = TranscoderDB.open(sourceEncoding, destinationEncoding, ecflags); if (ec == null) return ec; if (!replacement.isNil()) { int ret; RubyString replStr = (RubyString)replacement; ByteList replBL = replStr.getByteList(); ec.makeReplacement(); ret = ec.setReplacement(replBL.getUnsafeBytes(), replBL.getBegin(), replBL.getRealSize(), replBL.getEncoding().getName()); if (ret == -1) { ec.close(); return null; } } return ec; } // rb_econv_open_exc public static RaiseException econvOpenExc(ThreadContext context, byte[] sourceEncoding, byte[] destinationEncoding, int ecflags) { String message = econvDescription(context, sourceEncoding, destinationEncoding, ecflags, "code converter not found (") + ")"; return context.runtime.newConverterNotFoundError(message); } // rb_econv_description public static String econvDescription(ThreadContext context, byte[] sourceEncoding, byte[] destinationEncoding, int ecflags, String message) { // limited port for now return message + new String(sourceEncoding) + " to " + new String(destinationEncoding); } // rb_econv_asciicompat_encoding // Missing proper logic from transcoding subsystem public static Encoding econvAsciicompatEncoding(Encoding enc) { return RubyConverter.NONASCII_TO_ASCII.get(enc); } // rb_enc_asciicompat public static boolean encAsciicompat(Encoding enc) { return encMbminlen(enc) == 1 && !encDummy(enc); } // rb_enc_ascget public static int encAscget(byte[] pBytes, int p, int e, int[] len, Encoding enc) { int c; int l; if (e <= p) { return -1; } if (encAsciicompat(enc)) { c = pBytes[p] & 0xFF; if (!Encoding.isAscii((byte)c)) { return -1; } if (len != null) len[0] = 1; return c; } l = StringSupport.preciseLength(enc, pBytes, p, e); if (!StringSupport.MBCLEN_CHARFOUND_P(l)) { return -1; } c = enc.mbcToCode(pBytes, p, e); if (!Encoding.isAscii(c)) { return -1; } if (len != null) len[0] = l; return c; } // rb_enc_mbminlen public static int encMbminlen(Encoding encoding) { return encoding.minLength(); } // rb_enc_dummy_p public static boolean encDummy(Encoding enc) { return enc.isDummy(); } // rb_enc_get public static Encoding encGet(ThreadContext context, IRubyObject obj) { if (obj instanceof EncodingCapable) { return ((EncodingCapable)obj).getEncoding(); } return context.runtime.getDefaultInternalEncoding(); } // encoding_equal public static boolean encodingEqual(byte[] enc1, byte[] enc2) { return new String(enc1).equalsIgnoreCase(new String(enc2)); } // enc_arg public static Encoding encArg(ThreadContext context, IRubyObject encval, byte[][] name_p, Encoding[] enc_p) { Encoding enc; if ((enc = toEncodingIndex(context, encval)) == null) { name_p[0] = encval.convertToString().getBytes(); } else { name_p[0] = enc.getName(); } return enc_p[0] = enc; } // rb_to_encoding_index public static Encoding toEncodingIndex(ThreadContext context, IRubyObject enc) { if (enc instanceof RubyEncoding) { return ((RubyEncoding)enc).getEncoding(); } else if ((enc = enc.checkStringType19()).isNil()) { return null; } if (!((RubyString)enc).getEncoding().isAsciiCompatible()) { return null; } return context.runtime.getEncodingService().getEncodingFromObjectNoError(enc); } // encoded_dup public static IRubyObject encodedDup(ThreadContext context, IRubyObject newstr, IRubyObject str, Encoding encindex) { if (encindex == null) return str.dup(); if (newstr == str) { newstr = str.dup(); } else { // set to same superclass ((RubyBasicObject)newstr).setMetaClass(str.getMetaClass()); } ((RubyString)newstr).modify19(); return strEncodeAssociate(context, newstr, encindex); } // str_encode_associate public static IRubyObject strEncodeAssociate(ThreadContext context, IRubyObject str, Encoding encidx) { encAssociateIndex(str, encidx); if (encAsciicompat(encidx)) { ((RubyString)str).scanForCodeRange(); } else { ((RubyString)str).setCodeRange(StringSupport.CR_VALID); } return str; } // rb_enc_associate_index public static IRubyObject encAssociateIndex(IRubyObject obj, Encoding encidx) { ((RubyBasicObject)obj).checkFrozen(); if (encidx == null) encidx = ASCIIEncoding.INSTANCE; if (((EncodingCapable)obj).getEncoding() == encidx) { return obj; } if (obj instanceof RubyString && ! CodeRangeSupport.isCodeRangeAsciiOnly((RubyString) obj) || encAsciicompat(encidx)) { ((RubyString)obj).clearCodeRange(); } ((EncodingCapable)obj).setEncoding(encidx); return obj; } // str_encode public static IRubyObject strEncode(ThreadContext context, IRubyObject str, IRubyObject... args) { IRubyObject[] newstr_p = {str}; Encoding dencindex = strTranscode(context, args, newstr_p); return encodedDup(context, newstr_p[0], str, dencindex); } // rb_str_encode public static IRubyObject rbStrEncode(ThreadContext context, IRubyObject str, IRubyObject to, int ecflags, IRubyObject ecopt) { IRubyObject[] newstr_p = {str}; Encoding dencindex = strTranscode0(context, 1, new IRubyObject[]{to}, newstr_p, ecflags, ecopt); return encodedDup(context, newstr_p[0], str, dencindex); } // str_transcode public static Encoding strTranscode(ThreadContext context, IRubyObject[] args, IRubyObject[] self_p) { int ecflags = 0; int argc = args.length; IRubyObject[] ecopts_p = {context.nil}; if (args.length >= 1) { IRubyObject tmp = TypeConverter.checkHashType(context.runtime, args[args.length - 1]); if (!tmp.isNil()) { argc--; ecflags = econvPrepareOpts(context, tmp, ecopts_p); } } return strTranscode0(context, argc, args, self_p, ecflags, ecopts_p[0]); } // str_transcode0 public static Encoding strTranscode0(ThreadContext context, int argc, IRubyObject[] args, IRubyObject[] self_p, int ecflags, IRubyObject ecopts) { Ruby runtime = context.runtime; IRubyObject str = self_p[0]; IRubyObject arg1, arg2; Encoding[] senc_p = {null}, denc_p = {null}; byte[][] sname_p = {null}, dname_p = {null}; Encoding dencindex; boolean explicitlyInvalidReplace = true; if (argc > 2) { throw context.runtime.newArgumentError(args.length, 2); } if (argc == 0) { arg1 = runtime.getEncodingService().getDefaultInternal(); if (arg1 == null || arg1.isNil()) { if (ecflags == 0) return null; arg1 = objEncoding(context, str); } if ((ecflags & EConvFlags.INVALID_MASK) == 0) { explicitlyInvalidReplace = false; } ecflags |= EConvFlags.INVALID_REPLACE | EConvFlags.UNDEF_REPLACE; } else { arg1 = args[0]; } arg2 = argc <= 1 ? context.nil : args[1]; dencindex = strTranscodeEncArgs(context, str, arg1, arg2, sname_p, senc_p, dname_p, denc_p); IRubyObject dest; if ((ecflags & (EConvFlags.NEWLINE_DECORATOR_MASK | EConvFlags.XML_TEXT_DECORATOR | EConvFlags.XML_ATTR_CONTENT_DECORATOR | EConvFlags.XML_ATTR_QUOTE_DECORATOR)) == 0) { if (senc_p[0] != null && senc_p[0] == denc_p[0]) { if ((ecflags & EConvFlags.INVALID_MASK) != 0 && explicitlyInvalidReplace) { IRubyObject rep = context.nil; if (!ecopts.isNil()) { rep = ((RubyHash)ecopts).op_aref(context, runtime.newSymbol("replace")); } dest = ((RubyString)str).scrub(context, rep, Block.NULL_BLOCK); if (dest.isNil()) dest = str; self_p[0] = dest; return dencindex; } return arg2.isNil() ? null : dencindex; } else if (senc_p[0] != null && denc_p[0] != null && senc_p[0].isAsciiCompatible() && denc_p[0].isAsciiCompatible()) { if (((RubyString)str).scanForCodeRange() == StringSupport.CR_7BIT) { return dencindex; } } if (encodingEqual(sname_p[0], dname_p[0])) { return arg2.isNil() ? null : dencindex; } } else { if (encodingEqual(sname_p[0], dname_p[0])) { sname_p[0] = NULL_BYTE_ARRAY; dname_p[0] = NULL_BYTE_ARRAY; } } ByteList sp = ((RubyString)str).getByteList(); ByteList fromp = sp; int slen = ((RubyString)str).size(); int blen = slen + 30; dest = RubyString.newStringLight(runtime, blen); ByteList destp = ((RubyString)dest).getByteList(); byte[] frompBytes = fromp.unsafeBytes(); byte[] destpBytes = destp.unsafeBytes(); Ptr frompPos = new Ptr(fromp.getBegin()); Ptr destpPos = new Ptr(destp.getBegin()); transcodeLoop(context, frompBytes, frompPos, destpBytes, destpPos, frompPos.p + slen, destpPos.p + blen, destp, strTranscodingResize, sname_p[0], dname_p[0], ecflags, ecopts); if (frompPos.p != sp.begin() + slen) { throw runtime.newArgumentError("not fully converted, " + (slen - frompPos.p) + " bytes left"); } destp.setRealSize(destpPos.p); if (denc_p[0] == null) { dencindex = defineDummyEncoding(context, dname_p[0]); } self_p[0] = dest; return dencindex; } // rb_obj_encoding public static IRubyObject objEncoding(ThreadContext context, IRubyObject obj) { Encoding enc = encGet(context, obj); if (enc == null) { throw context.runtime.newTypeError("unknown encoding"); } return context.runtime.getEncodingService().convertEncodingToRubyEncoding(enc); } public static Encoding strTranscodeEncArgs(ThreadContext context, IRubyObject str, IRubyObject arg1, IRubyObject arg2, byte[][] sname_p, Encoding[] senc_p, byte[][] dname_p, Encoding[] denc_p) { Encoding dencindex; dencindex = encArg(context, arg1, dname_p, denc_p); if (arg2.isNil()) { senc_p[0] = encGet(context, str); sname_p[0] = senc_p[0].getName(); } else { encArg(context, arg2, sname_p, senc_p); } return dencindex; } public static boolean encRegistered(byte[] name) { return EncodingDB.getEncodings().get(name) != null; } // enc_check_duplication public static void encCheckDuplication(ThreadContext context, byte[] name) { if (encRegistered(name)) { throw context.runtime.newArgumentError("encoding " + new String(name) + " is already registered"); } } // rb_enc_replicate public static Encoding encReplicate(ThreadContext context, byte[] name, Encoding encoding) { encCheckDuplication(context, name); EncodingDB.replicate(new String(name), new String(encoding.getName())); return EncodingDB.getEncodings().get(name).getEncoding(); } // rb_define_dummy_encoding public static Encoding defineDummyEncoding(ThreadContext context, byte[] name) { Encoding dummy = encReplicate(context, name, ascii8bitEncoding(context.runtime)); // TODO: set dummy on encoding; this probably should live in jcodings return dummy; } public static boolean DECORATOR_P(byte[] sname, byte[] dname) { return sname == null || sname.length == 0 || sname[0] == 0; } // TODO: Get rid of this and get consumers calling with existing RubyString public static ByteList strConvEncOpts(ThreadContext context, ByteList str, Encoding fromEncoding, Encoding toEncoding, int ecflags, IRubyObject ecopts) { return strConvEncOpts( context, RubyString.newString(context.runtime, str), fromEncoding, toEncoding, ecflags, ecopts).getByteList(); } /** * This will try and transcode the supplied ByteList to the supplied toEncoding. It will use * forceEncoding as its encoding if it is supplied; otherwise it will use the encoding it has * tucked away in the bytelist. This will return a new copy of a ByteList in the request * encoding or die trying (ConverterNotFound). * * c: rb_str_conv_enc_opts */ public static RubyString strConvEncOpts(ThreadContext context, RubyString str, Encoding fromEncoding, Encoding toEncoding, int ecflags, IRubyObject ecopts) { if (toEncoding == null) return str; if (fromEncoding == null) fromEncoding = str.getEncoding(); if (fromEncoding == toEncoding) return str; if ((toEncoding.isAsciiCompatible() && str.isAsciiOnly()) || toEncoding == ASCIIEncoding.INSTANCE) { if (str.getEncoding() != toEncoding) { str = (RubyString)str.dup(); str.setEncoding(toEncoding); } return str; } ByteList strByteList = str.getByteList(); int len = strByteList.getRealSize(); ByteList newStr = new ByteList(len); int olen = len; EConv ec = econvOpenOpts(context, fromEncoding.getName(), toEncoding.getName(), ecflags, ecopts); if (ec == null) return str; byte[] sbytes = strByteList.getUnsafeBytes(); Ptr sp = new Ptr(strByteList.getBegin()); int start = sp.p; byte[] destbytes; Ptr dp = new Ptr(0); EConvResult ret; int convertedOutput = 0; // these are in the while clause in MRI destbytes = newStr.getUnsafeBytes(); int dest = newStr.begin(); dp.p = dest + convertedOutput; ret = ec.convert(sbytes, sp, start + len, destbytes, dp, dest + olen, 0); while (ret == EConvResult.DestinationBufferFull) { int convertedInput = sp.p - start; int rest = len - convertedInput; convertedOutput = dp.p - dest; newStr.setRealSize(convertedOutput); if (convertedInput != 0 && convertedOutput != 0 && rest < (Integer.MAX_VALUE / convertedOutput)) { rest = (rest * convertedOutput) / convertedInput; } else { rest = olen; } olen += rest < 2 ? 2 : rest; newStr.ensure(olen); // these are the while clause in MRI destbytes = newStr.getUnsafeBytes(); dest = newStr.begin(); dp.p = dest + convertedOutput; ret = ec.convert(sbytes, sp, start + len, destbytes, dp, dest + olen, 0); } ec.close(); switch (ret) { case Finished: len = dp.p; newStr.setRealSize(len); newStr.setEncoding(toEncoding); return RubyString.newString(context.runtime, newStr); default: // some error, return original return str; } } // rb_str_conv_enc public static RubyString strConvEnc(ThreadContext context, RubyString value, Encoding fromEncoding, Encoding toEncoding) { return strConvEncOpts(context, value, fromEncoding, toEncoding, 0, context.nil); } public static ByteList strConvEnc(ThreadContext context, ByteList value, Encoding fromEncoding, Encoding toEncoding) { return strConvEncOpts(context, value, fromEncoding, toEncoding, 0, context.nil); } public static RubyString setStrBuf(Ruby runtime, final IRubyObject obj, final int len) { final RubyString str; if (obj == null || obj.isNil()) { str = RubyString.newStringLight(runtime, len); } else { str = obj.convertToString(); int clen = str.size(); if (clen >= len) { str.modify(); return str; } str.modifyExpand(len); } return str; } public interface ResizeFunction { /** * Resize the destination, returning the new begin offset. * * @param destination * @param len * @param new_len * @return */ int resize(ByteList destination, int len, int new_len); } public static final ResizeFunction strTranscodingResize = new ResizeFunction() { @Override public int resize(ByteList destination, int len, int new_len) { destination.setRealSize(len); destination.ensure(new_len); return destination.getBegin(); } }; public interface TranscodeFallback { IRubyObject call(ThreadContext context, IRubyObject fallback, IRubyObject c); } private static final TranscodeFallback HASH_FALLBACK = new TranscodeFallback() { @Override public IRubyObject call(ThreadContext context, IRubyObject fallback, IRubyObject c) { return ((RubyHash)fallback).op_aref(context, c); } }; private static final TranscodeFallback PROC_FALLBACK = new TranscodeFallback() { @Override public IRubyObject call(ThreadContext context, IRubyObject fallback, IRubyObject c) { return ((RubyProc)fallback).call(context, new IRubyObject[]{c}); } }; private static final TranscodeFallback METHOD_FALLBACK = new TranscodeFallback() { @Override public IRubyObject call(ThreadContext context, IRubyObject fallback, IRubyObject c) { return fallback.callMethod(context, "call", c); } }; private static final TranscodeFallback AREF_FALLBACK = new TranscodeFallback() { @Override public IRubyObject call(ThreadContext context, IRubyObject fallback, IRubyObject c) { return fallback.callMethod(context, "[]", c); } }; // transcode_loop public static void transcodeLoop(ThreadContext context, byte[] inBytes, Ptr inPos, byte[] outBytes, Ptr outPos, int inStop, int _outStop, ByteList destination, ResizeFunction resizeFunction, byte[] sname, byte[] dname, int ecflags, IRubyObject ecopts) { Ruby runtime = context.runtime; EConv ec; Ptr outStop = new Ptr(_outStop); IRubyObject fallback = context.nil; TranscodeFallback fallbackFunc = null; ec = econvOpenOpts(context, sname, dname, ecflags, ecopts); if (ec == null) { throw econvOpenExc(context, sname, dname, ecflags); } if (!ecopts.isNil() && ecopts instanceof RubyHash) { fallback = ((RubyHash)ecopts).op_aref(context, runtime.newSymbol("fallback")); if (fallback instanceof RubyHash) { fallbackFunc = HASH_FALLBACK; } else if (fallback instanceof RubyProc) { // not quite same check as MRI fallbackFunc = PROC_FALLBACK; } else if (fallback instanceof RubyMethod) { // not quite same check as MRI fallbackFunc = METHOD_FALLBACK; } else { fallbackFunc = AREF_FALLBACK; } } Transcoding lastTC = ec.lastTranscoding; int maxOutput = lastTC != null ? lastTC.transcoder.maxOutput : 1; Ptr outStart = new Ptr(outPos.p); // resume: while (true) { EConvResult ret = ec.convert(inBytes, inPos, inStop, outBytes, outPos, outStop.p, 0); if (!fallback.isNil() && ret == EConvResult.UndefinedConversion) { IRubyObject rep = RubyString.newStringNoCopy( runtime, new ByteList( ec.lastError.getErrorBytes(), ec.lastError.getErrorBytesP(), ec.lastError.getErrorBytesLength(), runtime.getEncodingService().findEncodingOrAliasEntry(ec.lastError.getSource()).getEncoding(), false) ); rep = fallbackFunc.call(context, fallback, rep); if (!rep.isNil()) { rep = rep.convertToString(); Encoding repEnc = ((RubyString)rep).getEncoding(); ByteList repByteList = ((RubyString)rep).getByteList(); ec.insertOutput(repByteList.getUnsafeBytes(), repByteList.begin(), repByteList.getRealSize(), repEnc.getName()); // TODO: check for too-large replacement continue; } } if (ret == EConvResult.InvalidByteSequence || ret == EConvResult.IncompleteInput || ret == EConvResult.UndefinedConversion) { RaiseException re = makeEconvException(runtime, ec); ec.close(); throw re; } if (ret == EConvResult.DestinationBufferFull) { moreOutputBuffer(destination, resizeFunction, maxOutput, outStart, outPos, outStop); outBytes = destination.getUnsafeBytes(); continue; } ec.close(); return; } } // make_econv_exception public static RaiseException makeEconvException(Ruby runtime, EConv ec) { final StringBuilder mesg = new StringBuilder(); RaiseException exc; final EConvResult result = ec.lastError.getResult(); if (result == EConvResult.InvalidByteSequence || result == EConvResult.IncompleteInput) { byte[] errBytes = ec.lastError.getErrorBytes(); int errBytesP = ec.lastError.getErrorBytesP(); int errorLen = ec.lastError.getErrorBytesLength(); ByteList _bytes = new ByteList(errBytes, errBytesP, errorLen - errBytesP); RubyString bytes = RubyString.newString(runtime, _bytes); RubyString dumped = (RubyString)bytes.dump(); int readagainLen = ec.lastError.getReadAgainLength(); IRubyObject bytes2 = runtime.getNil(); if (result == EConvResult.IncompleteInput) { mesg.append("incomplete ").append(dumped).append(" on ").append(new String(ec.lastError.getSource())); } else if (readagainLen != 0) { bytes2 = RubyString.newString(runtime, new ByteList(errBytes, errorLen + errBytesP, ec.lastError.getReadAgainLength())); IRubyObject dumped2 = ((RubyString) bytes2).dump(); mesg.append(dumped).append(" followed by ").append(dumped2).append(" on ").append( new String(ec.lastError.getSource()) ); } else { mesg.append(dumped).append(" on ").append( new String(ec.lastError.getSource()) ); } exc = runtime.newInvalidByteSequenceError(mesg.toString()); exc.getException().setInternalVariable("error_bytes", bytes); exc.getException().setInternalVariable("readagain_bytes", bytes2); exc.getException().setInternalVariable("incomplete_input", result == EConvResult.IncompleteInput ? runtime.getTrue() : runtime.getFalse()); return makeEConvExceptionSetEncs(exc, runtime, ec); } else if (result == EConvResult.UndefinedConversion) { byte[] errBytes = ec.lastError.getErrorBytes(); int errBytesP = ec.lastError.getErrorBytesP(); int errorLen = ec.lastError.getErrorBytesLength(); final byte[] errSource = ec.lastError.getSource(); if (Arrays.equals(errSource, "UTF-8".getBytes())) { // prepare dumped form } RubyString bytes = RubyString.newString(runtime, new ByteList(errBytes, errBytesP, errorLen - errBytesP)); RubyString dumped = (RubyString) bytes.dump(); if (Arrays.equals(errSource, ec.source) && Arrays.equals(ec.lastError.getDestination(), ec.destination)) { mesg.append(dumped).append(" from ").append( new String(errSource) ).append(" to ").append( new String(ec.lastError.getDestination()) ); } else { mesg.append(dumped).append(" to ").append( new String(ec.lastError.getDestination()) ).append(" in conversion from ").append( new String(ec.source) ); for (int i = 0; i < ec.numTranscoders; i++) { mesg.append(" to ").append( new String(ec.elements[i].transcoding.transcoder.getDestination()) ); } } exc = runtime.newUndefinedConversionError(mesg.toString()); EncodingDB.Entry entry = runtime.getEncodingService().findEncodingOrAliasEntry(errSource); if (entry != null) { bytes.setEncoding(entry.getEncoding()); exc.getException().setInternalVariable("error_char", bytes); } return makeEConvExceptionSetEncs(exc, runtime, ec); } return null; } private static RaiseException makeEConvExceptionSetEncs(RaiseException exc, Ruby runtime, EConv ec) { exc.getException().setInternalVariable("source_encoding_name", RubyString.newString(runtime, ec.lastError.getSource())); exc.getException().setInternalVariable("destination_encoding_name", RubyString.newString(runtime, ec.lastError.getDestination())); EncodingDB.Entry entry = runtime.getEncodingService().findEncodingOrAliasEntry(ec.lastError.getSource()); if (entry != null) { exc.getException().setInternalVariable("source_encoding", runtime.getEncodingService().convertEncodingToRubyEncoding(entry.getEncoding())); } entry = runtime.getEncodingService().findEncodingOrAliasEntry(ec.lastError.getDestination()); if (entry != null) { exc.getException().setInternalVariable("destination_encoding", runtime.getEncodingService().convertEncodingToRubyEncoding(entry.getEncoding())); } return exc; } // more_output_buffer static void moreOutputBuffer(ByteList destination, ResizeFunction resizeDestination, int maxOutput, Ptr outStart, Ptr outPos, Ptr outStop) { int len = outPos.p - outStart.p; int newLen = (len + maxOutput) * 2; outStart.p = resizeDestination.resize(destination, len, newLen); outPos.p = outStart.p + len; outStop.p = outStart.p + newLen; } // io_set_encoding_by_bom public static void ioSetEncodingByBOM(ThreadContext context, RubyIO io) { Ruby runtime = context.runtime; Encoding bomEncoding = ioStripBOM(context, io); if (bomEncoding != null) { // FIXME: Wonky that we acquire RubyEncoding to pass these encodings through IRubyObject theBom = runtime.getEncodingService().getEncoding(bomEncoding); IRubyObject theInternal = io.internal_encoding(context); io.setEncoding(runtime.getCurrentContext(), theBom, theInternal, context.nil); } else { io.setEnc2(null); } } // mri: io_strip_bom @Deprecated public static Encoding ioStripBOM(RubyIO io) { return ioStripBOM(io.getRuntime().getCurrentContext(), io); } public static Encoding ioStripBOM(ThreadContext context, RubyIO io) { IRubyObject b1, b2, b3, b4; if ((b1 = io.getbyte(context)).isNil()) return null; switch ((int)((RubyFixnum)b1).getLongValue()) { case 0xEF: if ((b2 = io.getbyte(context)).isNil()) break; if (b2 instanceof RubyFixnum && ((RubyFixnum)b2).getLongValue() == 0xBB && !(b3 = io.getbyte(context)).isNil()) { if (((RubyFixnum)b3).getLongValue() == 0xBF) { return UTF8Encoding.INSTANCE; } io.ungetbyte(context, b3); } io.ungetbyte(context, b2); break; case 0xFE: if ((b2 = io.getbyte(context)).isNil()) break; if (b2 instanceof RubyFixnum && ((RubyFixnum)b2).getLongValue() == 0xFF) { return UTF16BEEncoding.INSTANCE; } io.ungetbyte(context, b2); break; case 0xFF: if ((b2 = io.getbyte(context)).isNil()) break; if (b2 instanceof RubyFixnum && ((RubyFixnum)b2).getLongValue() == 0xFE) { b3 = io.getbyte(context); if (b3 instanceof RubyFixnum && ((RubyFixnum)b3).getLongValue() == 0 && !(b4 = io.getbyte(context)).isNil()) { if (((RubyFixnum)b4).getLongValue() == 0) { return UTF32LEEncoding.INSTANCE; } io.ungetbyte(context, b4); } else { io.ungetbyte(context, b3); return UTF16LEEncoding.INSTANCE; } io.ungetbyte(context, b3); } io.ungetbyte(context, b2); break; case 0: if ((b2 = io.getbyte(context)).isNil()) break; if (b2 instanceof RubyFixnum && ((RubyFixnum)b2).getLongValue() == 0 && !(b3 = io.getbyte(context)).isNil()) { if (b3 instanceof RubyFixnum && ((RubyFixnum)b3).getLongValue() == 0xFE && !(b4 = io.getbyte(context)).isNil()) { if (b4 instanceof RubyFixnum && ((RubyFixnum)b4).getLongValue() == 0xFF) { return UTF32BEEncoding.INSTANCE; } io.ungetbyte(context, b4); } io.ungetbyte(context, b3); } io.ungetbyte(context, b2); break; } io.ungetbyte(context, b1); return null; } // validate_enc_binmode public static void validateEncodingBinmode(ThreadContext context, int[] fmode_p, int ecflags, IOEncodable ioEncodable) { Ruby runtime = context.runtime; int fmode = fmode_p[0]; if ((fmode & OpenFile.READABLE) != 0 && ioEncodable.getEnc2() == null && (fmode & OpenFile.BINMODE) == 0 && !(ioEncodable.getEnc() != null ? ioEncodable.getEnc() : runtime.getDefaultExternalEncoding()).isAsciiCompatible()) { throw runtime.newArgumentError("ASCII incompatible encoding needs binmode"); } if ((fmode & OpenFile.BINMODE) == 0 && (EncodingUtils.DEFAULT_TEXTMODE != 0 || (ecflags & EConvFlags.NEWLINE_DECORATOR_MASK) != 0)) { fmode |= EncodingUtils.DEFAULT_TEXTMODE; fmode_p[0] = fmode; } else if (EncodingUtils.DEFAULT_TEXTMODE == 0 && (ecflags & EConvFlags.NEWLINE_DECORATOR_MASK) == 0) { fmode &= ~OpenFile.TEXTMODE; fmode_p[0] = fmode; } } // rb_enc_set_default_external public static void rbEncSetDefaultExternal(ThreadContext context, IRubyObject encoding) { if (encoding.isNil()) { throw context.runtime.newArgumentError("default external can not be nil"); } Encoding[] enc_p = {context.runtime.getDefaultExternalEncoding()}; encSetDefaultEncoding(context, enc_p, encoding, "external"); context.runtime.setDefaultExternalEncoding(enc_p[0]); } // rb_enc_set_default_internal public static void rbEncSetDefaultInternal(ThreadContext context, IRubyObject encoding) { Encoding[] enc_p = {context.runtime.getDefaultInternalEncoding()}; encSetDefaultEncoding(context, enc_p, encoding, "internal"); context.runtime.setDefaultInternalEncoding(enc_p[0]); } // enc_set_default_encoding public static boolean encSetDefaultEncoding(ThreadContext context, Encoding[] def_p, IRubyObject encoding, String name) { boolean overridden = false; if (def_p != null) { overridden = true; } if (encoding.isNil()) { def_p[0] = null; // don't set back into encoding table since it defers to us } else { def_p[0] = rbToEncoding(context, encoding); // don't set back into encoding table since it defers to us } if (name.equals("external")) { // TODO: set filesystem encoding } return overridden; } // rb_default_external_encoding public static Encoding defaultExternalEncoding(Ruby runtime) { if (runtime.getDefaultExternalEncoding() != null) return runtime.getDefaultExternalEncoding(); return runtime.getEncodingService().getLocaleEncoding(); } // rb_str_buf_cat public static void rbStrBufCat(Ruby runtime, RubyString str, ByteList ptr) { if (ptr.length() == 0) return; // negative length check here, we shouldn't need strBufCat(runtime, str, ptr); } public static void rbStrBufCat(Ruby runtime, ByteListHolder str, byte[] ptrBytes, int ptr, int len) { if (len == 0) return; // negative length check here, we shouldn't need strBufCat(runtime, str, ptrBytes, ptr, len); } public static void rbStrBufCat(Ruby runtime, ByteList str, byte[] ptrBytes, int ptr, int len) { if (len == 0) return; // negative length check here, we shouldn't need strBufCat(str, ptrBytes, ptr, len); } // str_buf_cat public static void strBufCat(Ruby runtime, RubyString str, ByteList ptr) { strBufCat(runtime, str, ptr.getUnsafeBytes(), ptr.getBegin(), ptr.getRealSize()); } public static void strBufCat(Ruby runtime, ByteListHolder str, byte[] ptrBytes, int ptr, int len) { str.modify(); strBufCat(str.getByteList(), ptrBytes, ptr, len); } public static void strBufCat(ByteList str, byte[] ptrBytes, int ptr, int len) { int total, off = -1; // termlen is not relevant since we have no termination sequence // missing: if ptr string is inside str, off = ptr start minus str start // str.modify(); if (len == 0) return; // much logic is missing here, since we don't manually manage the ByteList buffer total = str.getRealSize() + len; str.ensure(total); str.append(ptrBytes, ptr, len); } // rb_enc_str_buf_cat public static void encStrBufCat(Ruby runtime, RubyString str, ByteList ptr, Encoding enc) { encCrStrBufCat(runtime, str, ptr.getUnsafeBytes(), ptr.getBegin(), ptr.getRealSize(), enc, StringSupport.CR_UNKNOWN, null); } public static void encStrBufCat(Ruby runtime, RubyString str, byte[] ptrBytes, int ptr, int len, Encoding enc) { encCrStrBufCat(runtime, str, ptrBytes, ptr, len, enc, StringSupport.CR_UNKNOWN, null); } // rb_enc_cr_str_buf_cat public static void encCrStrBufCat(Ruby runtime, CodeRangeable str, ByteList ptr, Encoding ptrEnc, int ptr_cr, int[] ptr_cr_ret) { encCrStrBufCat(runtime, str, ptr.getUnsafeBytes(), ptr.getBegin(), ptr.getRealSize(), ptrEnc, ptr_cr, ptr_cr_ret); } public static void encCrStrBufCat(Ruby runtime, CodeRangeable str, byte[] ptrBytes, int ptr, int len, Encoding ptrEnc, int ptr_cr, int[] ptr_cr_ret) { Encoding strEnc = str.getByteList().getEncoding(); Encoding resEnc; int str_cr, res_cr; boolean incompatible = false; str_cr = str.getByteList().getRealSize() > 0 ? str.getCodeRange() : StringSupport.CR_7BIT; if (strEnc == ptrEnc) { if (str_cr == StringSupport.CR_UNKNOWN) { ptr_cr = StringSupport.CR_UNKNOWN; } else if (ptr_cr == StringSupport.CR_UNKNOWN) { ptr_cr = StringSupport.codeRangeScan(ptrEnc, ptrBytes, ptr, len); } } else { if (!EncodingUtils.encAsciicompat(strEnc) || !EncodingUtils.encAsciicompat(ptrEnc)) { if (len == 0) { return; } if (str.getByteList().getRealSize() == 0) { rbStrBufCat(runtime, str, ptrBytes, ptr, len); str.getByteList().setEncoding(ptrEnc); str.setCodeRange(ptr_cr); return; } incompatible = true; } if (!incompatible) { if (ptr_cr == StringSupport.CR_UNKNOWN) { ptr_cr = StringSupport.codeRangeScan(ptrEnc, ptrBytes, ptr, len); } if (str_cr == StringSupport.CR_UNKNOWN) { if (strEnc == ASCIIEncoding.INSTANCE || ptr_cr != StringSupport.CR_7BIT) { str_cr = str.scanForCodeRange(); } } } } if (ptr_cr_ret != null) { ptr_cr_ret[0] = ptr_cr; } if (incompatible || (strEnc != ptrEnc && str_cr != StringSupport.CR_7BIT && ptr_cr != StringSupport.CR_7BIT)) { throw runtime.newEncodingCompatibilityError("incompatible encodings: " + strEnc + " and " + ptrEnc); } if (str_cr == StringSupport.CR_UNKNOWN) { resEnc = strEnc; res_cr = StringSupport.CR_UNKNOWN; } else if (str_cr == StringSupport.CR_7BIT) { if (ptr_cr == StringSupport.CR_7BIT) { resEnc = strEnc; res_cr = StringSupport.CR_7BIT; } else { resEnc = ptrEnc; res_cr = ptr_cr; } } else if (str_cr == StringSupport.CR_VALID) { resEnc = strEnc; if (ptr_cr == StringSupport.CR_7BIT || ptr_cr == StringSupport.CR_VALID) { res_cr = str_cr; } else { res_cr = ptr_cr; } } else { // str_cr must be BROKEN at this point resEnc = strEnc; res_cr = str_cr; if (0 < len) res_cr = StringSupport.CR_UNKNOWN; } // MRI checks for len < 0 here, but I don't think that's possible for us strBufCat(runtime, str, ptrBytes, ptr, len); str.getByteList().setEncoding(resEnc); str.setCodeRange(res_cr); } // econv_args public static void econvArgs(ThreadContext context, IRubyObject[] args, byte[][] encNames, Encoding[] encs, int[] ecflags_p, IRubyObject[] ecopts_p) { Ruby runtime = context.runtime; IRubyObject snamev = context.nil; IRubyObject dnamev = context.nil; IRubyObject flags = context.nil; IRubyObject opt = context.nil; // scan args logic { switch (args.length) { case 3: flags = args[2]; case 2: dnamev = args[1]; case 1: snamev = args[0]; } IRubyObject tmp; if (!(tmp = TypeConverter.checkHashType(runtime, flags)).isNil()) { opt = tmp; flags = context.nil; } } if (!flags.isNil()) { if (!opt.isNil()) { throw runtime.newArgumentError(args.length, 3); } ecflags_p[0] = (int)flags.convertToInteger().getLongValue(); ecopts_p[0] = context.nil; } else if (!opt.isNil()) { ecflags_p[0] = EncodingUtils.econvPrepareOpts(context, opt, ecopts_p); } else { ecflags_p[0] = 0; ecopts_p[0] = context.nil; } encs[0] = runtime.getEncodingService().getEncodingFromObjectNoError(snamev); if (encs[0] == null) { snamev = snamev.convertToString(); } encs[1] = runtime.getEncodingService().getEncodingFromObjectNoError(dnamev); if (encs[1] == null) { dnamev = dnamev.convertToString(); } encNames[0] = encs[0] != null ? encs[0].getName() : ((RubyString)snamev).getBytes(); encNames[1] = encs[1] != null ? encs[1].getName() : ((RubyString)dnamev).getBytes(); return; } // rb_econv_init_by_convpath public static EConv econvInitByConvpath(ThreadContext context, IRubyObject convpath, byte[][] encNames, Encoding[] encs) { final Ruby runtime = context.runtime; final EConv ec = TranscoderDB.alloc(convpath.convertToArray().size()); IRubyObject[] sname_v = {context.nil}; IRubyObject[] dname_v = {context.nil}; byte[][] sname = {null}; byte[][] dname = {null}; Encoding[] senc = {null}; Encoding[] denc = {null}; boolean first = true; for (int i = 0; i < ((RubyArray)convpath).size(); i++) { IRubyObject elt = ((RubyArray)convpath).eltOk(i); IRubyObject pair; if (!(pair = elt.checkArrayType()).isNil()) { if (((RubyArray)pair).size() != 2) { throw context.runtime.newArgumentError("not a 2-element array in convpath"); } sname_v[0] = ((RubyArray)pair).eltOk(0); encArg(context, sname_v[0], sname, senc); dname_v[0] = ((RubyArray)pair).eltOk(1); encArg(context, dname_v[0], dname, denc); } else { sname[0] = NULL_BYTE_ARRAY; dname[0] = elt.convertToString().getBytes(); } if (DECORATOR_P(sname[0], dname[0])) { boolean ret = ec.addConverter(sname[0], dname[0], ec.numTranscoders); if (!ret) { throw runtime.newArgumentError("decoration failed: " + new String(dname[0])); } } else { int j = ec.numTranscoders; final int[] arg = {j,0}; int ret = TranscoderDB.searchPath(sname[0], dname[0], new TranscoderDB.SearchPathCallback() { @Override public void call(byte[] source, byte[] destination, int depth) { if (arg[1] == -1) return; arg[1] = ec.addConverter(source, destination, arg[0]) ? 0 : -1; } }); if (ret == -1 || arg[1] == -1) { throw runtime.newArgumentError("adding conversion failed: " + new String(sname[0]) + " to " + new String(dname[0])); } if (first) { first = false; encs[0] = senc[0]; encNames[0] = ec.elements[j].transcoding.transcoder.getSource(); } encs[1] = denc[0]; encNames[1] = ec.elements[ec.numTranscoders - 1].transcoding.transcoder.getDestination(); } } if (first) { encs[0] = null; encs[1] = null; encNames[0] = NULL_BYTE_ARRAY; encNames[1] = NULL_BYTE_ARRAY; } ec.source = encNames[0]; ec.destination = encNames[0]; return ec; } // decorate_convpath public static int decorateConvpath(ThreadContext context, IRubyObject convpath, int ecflags) { Ruby runtime = context.runtime; int num_decorators; byte[][] decorators = new byte[EConvFlags.MAX_ECFLAGS_DECORATORS][]; int i; int n, len; num_decorators = TranscoderDB.decoratorNames(ecflags, decorators); if (num_decorators == -1) return -1; len = n = ((RubyArray)convpath).size(); if (n != 0) { IRubyObject pair = ((RubyArray)convpath).eltOk(n - 1); if (pair instanceof RubyArray) { byte[] sname = runtime.getEncodingService().getEncodingFromObject(((RubyArray)pair).eltOk(0)).getName(); byte[] dname = runtime.getEncodingService().getEncodingFromObject(((RubyArray)pair).eltOk(1)).getName(); TranscoderDB.Entry entry = TranscoderDB.getEntry(sname, dname); Transcoder tr = entry.getTranscoder(); if (tr == null) return -1; if (!DECORATOR_P(tr.getSource(), tr.getDestination()) && tr.compatibility.isEncoder()) { n--; ((RubyArray)convpath).store(len + num_decorators - 1, pair); } } else { ((RubyArray)convpath).store(len + num_decorators - 1, pair); } } for (i = 0; i < num_decorators; i++) ((RubyArray)convpath).store(n + i, RubyString.newString(runtime, decorators[i])); return 0; } // io_enc_str public static IRubyObject ioEncStr(Ruby runtime, IRubyObject str, OpenFile fptr) { str.setTaint(true); ((RubyString)str).setEncoding(fptr.readEncoding(runtime)); return str; } // rb_enc_uint_chr public static IRubyObject encUintChr(ThreadContext context, int code, Encoding enc) { Ruby runtime = context.runtime; if (!Character.isValidCodePoint(code)) { // inefficient to create a fixnum for this return new RubyFixnum(runtime, code).chr19(context); } char[] chars = Character.toChars(code); RubyString str = RubyString.newString(runtime, new String(chars), enc); // ByteList strByteList = str.getByteList(); // if (StringSupport.preciseLength(enc, strByteList.unsafeBytes(), strByteList.getBegin(), strByteList.getBegin() + strByteList.getRealSize()) != n) { // rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc)); // } return str; } // rb_enc_mbcput public static void encMbcput(int c, byte[] buf, int p, Encoding enc) { enc.codeToMbc(c, buf, p); } // rb_enc_codepoint_len public static int encCodepointLength(Ruby runtime, byte[] pBytes, int p, int e, int[] len_p, Encoding enc) { int r; if (e <= p) throw runtime.newArgumentError("empty string"); r = StringSupport.preciseLength(enc, pBytes, p, e); if (!StringSupport.MBCLEN_CHARFOUND_P(r)) { throw runtime.newArgumentError("invalid byte sequence in " + enc); } if (len_p != null) len_p[0] = StringSupport.MBCLEN_CHARFOUND_LEN(r); return StringSupport.codePoint(runtime, enc, pBytes, p, e); } // MRI: str_compat_and_valid public static IRubyObject strCompatAndValid(ThreadContext context, IRubyObject _str, Encoding enc) { int cr; RubyString str = _str.convertToString(); cr = str.scanForCodeRange(); if (cr == StringSupport.CR_BROKEN) { throw context.runtime.newArgumentError("replacement must be valid byte sequence '" + str + "'"); } else { Encoding e = STR_ENC_GET(str); if (cr == StringSupport.CR_7BIT ? enc.minLength() != 1 : enc != e) { throw context.runtime.newEncodingCompatibilityError("incompatible character encodings: " + enc + " and " + e); } } return str; } // MRI: get_encoding public static Encoding getEncoding(ByteList str) { return getActualEncoding(str.getEncoding(), str); } private static final Encoding UTF16Dummy = EncodingDB.getEncodings().get("UTF-16".getBytes()).getEncoding(); private static final Encoding UTF32Dummy = EncodingDB.getEncodings().get("UTF-32".getBytes()).getEncoding(); // MRI: get_actual_encoding public static Encoding getActualEncoding(Encoding enc, ByteList byteList) { return getActualEncoding(enc, byteList.getUnsafeBytes(), byteList.begin(), byteList.begin() + byteList.realSize()); } public static Encoding getActualEncoding(Encoding enc, byte[] bytes, int p, int end) { if (enc.isDummy() && enc instanceof UnicodeEncoding) { // handle dummy UTF-16 and UTF-32 by scanning for BOM, as in MRI if (enc == UTF16Dummy && end - p >= 2) { int c0 = bytes[p] & 0xff; int c1 = bytes[p + 1] & 0xff; if (c0 == 0xFE && c1 == 0xFF) { return UTF16BEEncoding.INSTANCE; } else if (c0 == 0xFF && c1 == 0xFE) { return UTF16LEEncoding.INSTANCE; } return ASCIIEncoding.INSTANCE; } else if (enc == UTF32Dummy && end - p >= 4) { int c0 = bytes[p] & 0xff; int c1 = bytes[p + 1] & 0xff; int c2 = bytes[p + 2] & 0xff; int c3 = bytes[p + 3] & 0xff; if (c0 == 0 && c1 == 0 && c2 == 0xFE && c3 == 0xFF) { return UTF32BEEncoding.INSTANCE; } else if (c3 == 0 && c2 == 0 && c1 == 0xFE && c0 == 0xFF) { return UTF32LEEncoding.INSTANCE; } return ASCIIEncoding.INSTANCE; } } return enc; } public static Encoding STR_ENC_GET(ByteListHolder str) { return getEncoding(str.getByteList()); } public static RubyString rbStrEscape(Ruby runtime, RubyString str) { Encoding enc = str.getEncoding(); ByteList pByteList = str.getByteList(); byte[] pBytes = pByteList.unsafeBytes(); int p = pByteList.begin(); int pend = p + pByteList.realSize(); int prev = p; byte[] buf; RubyString result = RubyString.newEmptyString(runtime); boolean unicode_p = enc.isUnicode(); boolean asciicompat = enc.isAsciiCompatible(); while (p < pend) { long c, cc; int n = StringSupport.preciseLength(enc, pBytes, p, pend); if (!StringSupport.MBCLEN_CHARFOUND_P(n)) { if (p > prev) result.cat(pBytes, prev, p - prev); n = enc.minLength(); if (pend < p + n) n = (int) (pend - p); while ((n--) != 0) { buf = String.format("x%02X", pBytes[p] & 0377).getBytes(); result.cat(buf, 0, buf.length); prev = ++p; } continue; } n = StringSupport.MBCLEN_CHARFOUND_LEN(n); c = enc.mbcToCode(pBytes, p, pend); p += n; switch ((int)c) { case '\n': cc = 'n'; break; case '\r': cc = 'r'; break; case '\t': cc = 't'; break; case '\f': cc = 'f'; break; case '\013': cc = 'v'; break; case '\010': cc = 'b'; break; case '\007': cc = 'a'; break; case 033: cc = 'e'; break; default: cc = 0; break; } if (cc != 0) { if (p - n > prev) result.cat(pBytes, prev, p - n - prev); buf = new byte[] {(byte)'\\', (byte)cc}; result.cat(buf, 0, 2); prev = p; } else if (asciicompat && Encoding.isAscii((byte)c) && c > 31 /*ISPRINT(c)*/) { } else { if (p - n > prev) result.cat(pBytes, prev, p - n - prev); rbStrBufCatEscapedChar(result, c, unicode_p); prev = p; } } if (p > prev) result.cat(pBytes, prev, p - prev); result.setEncodingAndCodeRange(USASCIIEncoding.INSTANCE, StringSupport.CR_7BIT); result.setTaint(str.isTaint()); return result; } public static int rbStrBufCatEscapedChar(RubyString result, long c, boolean unicode_p) { // FIXME: inefficient byte[] buf; int l; c &= 0xffffffff; if (unicode_p) { if (c < 0x7F && c > 31 /*ISPRINT(c)*/) { buf = String.format("%c", (char)c).getBytes(); } else if (c < 0x10000) { buf = String.format("\\u%04X", c).getBytes(); } else { buf = String.format("\\u{%X}", c).getBytes(); } } else { if (c < 0x100) { buf = String.format("\\x{%02X}", c).getBytes(); } else { buf = String.format("\\x{%X}", c).getBytes(); } } result.cat(buf); return buf.length; } }
39.858068
257
0.573299
ec30595a4cd223eb25013d41a75cd8b90e400f3c
115
<T> void commit() throws IOException { bw.write(sb.toString()); bw.flush(); sb = new StringBuilder(); }
23
38
0.608696
ff94df176452e4af8de2666b6f864b34df83b068
900
package com.lin; import com.lin.datatype.DataType; import com.lin.faker.Faker; import com.lin.utils.DBTools; /** * 基本使用示范类 * @author lkmc2 * @since 1.0.0 */ public class Main { public static void main(String[] args) { // 更详细的使用例子参见 Example.java // 创建数据库连接 DBTools.url("jdbc:mysql://localhost:3306/facker") .username("root") .password("123456") .driverClassName("com.mysql.jdbc.Driver") .connect(); // 当数据库属性都等于默认值时,可只设置数据库名 // DBTools.dbName("facker").connect(); // 给user表的四个字段填充5条数据 Faker.tableName("user") .param("name", DataType.USERNAME) .param("age", DataType.AGE) .param("sex", DataType.SEX) .param("birthday", DataType.TIME) .insertCount(5) .execute(); } }
22.5
57
0.532222
1b1d9d4f4a299c6480990b2feb6897aad5116e59
3,599
package psidev.psi.mi.jami.xml.io.writer.elements.impl.extended; import psidev.psi.mi.jami.model.Experiment; import psidev.psi.mi.jami.model.ModelledInteraction; import psidev.psi.mi.jami.xml.cache.PsiXmlObjectCache; import psidev.psi.mi.jami.xml.io.writer.elements.PsiXmlExtendedInteractionWriter; import psidev.psi.mi.jami.xml.io.writer.elements.impl.extended.xml25.XmlExperimentWriter; import psidev.psi.mi.jami.xml.model.extension.PsiXmlInteraction; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import java.util.Collections; import java.util.List; /** * Abstract class for XML writers of modelled interaction * * @author Marine Dumousseau (marine@ebi.ac.uk) * @version $Id$ * @since <pre>18/11/13</pre> */ public abstract class AbstractXmlModelledInteractionWriter<I extends ModelledInteraction> extends psidev.psi.mi.jami.xml.io.writer.elements.impl.abstracts.AbstractXmlModelledInteractionWriter<I> implements PsiXmlExtendedInteractionWriter<I> { private List<Experiment> defaultExperiments; /** * <p>Constructor for AbstractXmlModelledInteractionWriter.</p> * * @param writer a {@link javax.xml.stream.XMLStreamWriter} object. * @param objectIndex a {@link psidev.psi.mi.jami.xml.cache.PsiXmlObjectCache} object. */ public AbstractXmlModelledInteractionWriter(XMLStreamWriter writer, PsiXmlObjectCache objectIndex) { super(writer, objectIndex); } /** {@inheritDoc} */ @Override public List<Experiment> getDefaultExperiments() { if (this.defaultExperiments == null || this.defaultExperiments.isEmpty()){ this.defaultExperiments = Collections.singletonList(getDefaultExperiment()); } return this.defaultExperiments; } /** {@inheritDoc} */ @Override public void setDefaultExperiments(List<Experiment> exp) { this.defaultExperiments = exp; if (this.defaultExperiments != null && !this.defaultExperiments.isEmpty()){ getParameterWriter().setDefaultExperiment(this.defaultExperiments.iterator().next()); } } /** {@inheritDoc} */ @Override protected void initialiseXrefWriter(){ super.setXrefWriter(new XmlDbXrefWriter(getStreamWriter())); } /** {@inheritDoc} */ @Override protected void initialiseInferredInteractionWriter() { super.setInferredInteractionWriter(new psidev.psi.mi.jami.xml.io.writer.elements.impl.XmlInferredInteractionWriter(getStreamWriter(), getObjectIndex())); } /** {@inheritDoc} */ @Override protected void initialiseInteractionTypeWriter() { super.setInteractionTypeWriter(new XmlCvTermWriter(getStreamWriter())); } /** {@inheritDoc} */ @Override protected void initialiseExperimentWriter(){ super.setExperimentWriter(new XmlExperimentWriter(getStreamWriter(), getObjectIndex())); } /** {@inheritDoc} */ @Override protected void writeIntraMolecular(I object) throws XMLStreamException { if (object instanceof PsiXmlInteraction){ PsiXmlInteraction xmlInteraction = (PsiXmlInteraction)object; if (xmlInteraction.isIntraMolecular()){ getStreamWriter().writeStartElement("intraMolecular"); getStreamWriter().writeCharacters(Boolean.toString(xmlInteraction.isIntraMolecular())); // write end intra molecular getStreamWriter().writeEndElement(); } } else{ super.writeIntraMolecular(object); } } }
36.72449
161
0.704918
f2f17eadb9ebb89ee3c2b1adda1e9045083db63f
803
import java.util.Scanner; public class A579 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); input.close(); double ans = Math.log(n)/Math.log(2); int integer_ans = (int)ans; int backs = 0; if(ans - integer_ans == 0){ System.out.println(1); }else{ int mid = n; while(n!=0 && n!=1 && integer_ans!=0){ mid-=Math.pow(2,integer_ans--); if(mid >= 0){ n = mid; backs++; }else{ mid = n; } } if(n == 1){ backs++; } System.out.println(backs); } } }
25.903226
50
0.39477
bd8d2f46f6a549c1dcac9bd9b896899faf3255cf
534
package ab; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/") public String index() { return "Greetings from Spring Boot!"; } // http://localhost:8080/hello?name=world @GetMapping("/hello") public String greeting(@RequestParam(value = "name", defaultValue = "world") String name) { return "hello " + name; } }
24.272727
93
0.735955
1a6034d7a3b00bcdfeca17ea9bdc762cc0926e3c
23,223
package com.gamechangers.android.asklocals; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.graphics.Color; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.speech.RecognizerIntent; import androidx.annotation.NonNull; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.viewpager.widget.ViewPager; import androidx.appcompat.app.ActionBar; import androidx.core.app.ActivityCompat; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.ContextCompat; import androidx.appcompat.widget.Toolbar; import android.text.Editable; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View.OnClickListener; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.gamechangers.android.asklocals.BottomSheetBehaviorGoogleMapsLike; import com.gamechangers.android.asklocals.EditTextWithDeleteButton.TextChangedListener; import com.gamechangers.android.asklocals.MergedAppBarLayoutBehavior; import com.gamechangers.android.asklocals.R; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.places.GeoDataClient; import com.google.android.gms.location.places.PlaceDetectionClient; import com.google.android.gms.location.places.Places; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.material.appbar.AppBarLayout; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, LocationListener { public final static String EXTRA_MESSAGE = "com.gamechangers.android.asklocals.MESSAGE"; private static final String TAG = MainActivity.class.getSimpleName(); private static final int REQUEST_CODE = 1234; protected View view; private GoogleMap mMap; private EditText word; private ListView wordsList; private Button bt_voiceinput; public double latitude; public double longitude; public LocationManager locationManager; public Criteria criteria; public String bestProvider; private TextView txtSpeechInput; private GoogleMap map; private static final int DEFAULT_ZOOM = 15; private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1; private boolean mLocationPermissionGranted; // The geographical location where the device is currently located. That is, the last-known // location retrieved by the Fused Location Provider. private Location mLastKnownLocation; // Keys for storing activity state. private static final String KEY_CAMERA_POSITION = "camera_position"; private static final String KEY_LOCATION = "location"; private static final long MIN_TIME = 400; private static final float MIN_DISTANCE = 1000; int[] mDrawables = { R.drawable.cheese_3, R.drawable.cheese_3, R.drawable.cheese_3, R.drawable.cheese_3, R.drawable.cheese_3, R.drawable.cheese_3 }; TextView bottomSheetTextView; private BottomSheetBehaviorGoogleMapsLike behavior; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setReference(); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setNavigationIcon(null); setSupportActionBar(toolbar); ImageButton speakButton = (ImageButton) findViewById(R.id.speak_button); speakButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { speakButtonClicked(v); } }); FloatingActionButton floatingButton = (FloatingActionButton) findViewById(R.id.floatingActionButton); floatingButton.setBackgroundResource(R.string.button_send); floatingButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { sendMessage(v); } }); ImageButton minimizeButton = (ImageButton) findViewById(R.id.sheet_minimize); minimizeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { minimizeSheet(v); } }); ImageButton closeButton = (ImageButton) findViewById(R.id.sheet_close); closeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeSheet(v); } }); wordsList = (ListView) findViewById(R.id.list); // Build the map. SupportMapFragment map = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); map.getMapAsync(this); // Get reference of widgets from XML layout final Spinner spinner = (Spinner) findViewById(R.id.spinner); // Initializing a String Array String[] categories = new String[]{ "Select a category...", "Transport", "Lodging", "Food", "Sightseeing", "Other" }; final List<String> categoryList = new ArrayList<>(Arrays.asList(categories)); /** * Disable button if no recognition service is present */ PackageManager pm = getPackageManager(); List<ResolveInfo> activities = pm.queryIntentActivities( new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); if (activities.size() == 0) { bt_voiceinput.setEnabled(false); } // Initializing an ArrayAdapter final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>( this,R.layout.spinner_item,categoryList){ @Override public boolean isEnabled(int position){ if(position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item); spinner.setAdapter(spinnerArrayAdapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String selectedItemText = (String) parent.getItemAtPosition(position); // If user change the default selection // First item is disable and it is used for hint if(position > 0){ // Notify the selected item text Toast.makeText (getApplicationContext(), "Selected : " + selectedItemText, Toast.LENGTH_SHORT) .show(); } } @Override public void onNothingSelected(AdapterView<?> parent) {} }); CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorlayout); View bottomSheet = coordinatorLayout.findViewById(R.id.bottom_sheet); BottomSheetBehaviorGoogleMapsLike behavior = BottomSheetBehaviorGoogleMapsLike.from(bottomSheet); behavior.setState(BottomSheetBehaviorGoogleMapsLike.STATE_COLLAPSED); } /** * Saves the state of the map when the activity is paused. */ @Override protected void onSaveInstanceState(Bundle outState) { if (map != null) { outState.putParcelable(KEY_CAMERA_POSITION, map.getCameraPosition()); outState.putParcelable(KEY_LOCATION, mLastKnownLocation); super.onSaveInstanceState(outState); } } public void sendMessage(View view) { //Intent startNewActivity = new Intent(this, DisplayMessageActivity.class); //EditText editText = (EditText) findViewById(R.id.editTextView); //String message = editText.getText().toString(); //startNewActivity.putExtra(EXTRA_MESSAGE, message); //startActivity(startNewActivity); /** * If we want to listen for states callback */ CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorlayout); View bottomSheet = coordinatorLayout.findViewById(R.id.bottom_sheet); final BottomSheetBehaviorGoogleMapsLike behavior = BottomSheetBehaviorGoogleMapsLike.from(bottomSheet); AppBarLayout mergedAppBarLayout = (AppBarLayout) findViewById(R.id.merged_appbarlayout); MergedAppBarLayoutBehavior mergedAppBarLayoutBehavior = MergedAppBarLayoutBehavior.from(mergedAppBarLayout); //mergedAppBarLayoutBehavior.setToolbarTitle("Local Advisor Name"); mergedAppBarLayoutBehavior.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { behavior.setState(BottomSheetBehaviorGoogleMapsLike.STATE_COLLAPSED); } }); bottomSheetTextView = (TextView) bottomSheet.findViewById(R.id.bottom_sheet_title); ItemPagerAdapter adapter = new ItemPagerAdapter(this,mDrawables); ViewPager viewPager = (ViewPager) findViewById(R.id.pager); viewPager.setAdapter(adapter); behavior.setState(BottomSheetBehaviorGoogleMapsLike.STATE_COLLAPSED); behavior.addBottomSheetCallback(new BottomSheetBehaviorGoogleMapsLike.BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) { switch (newState) { case BottomSheetBehaviorGoogleMapsLike.STATE_COLLAPSED: Log.d("bottomsheet-", "STATE_COLLAPSED"); break; case BottomSheetBehaviorGoogleMapsLike.STATE_DRAGGING: Log.d("bottomsheet-", "STATE_DRAGGING"); break; case BottomSheetBehaviorGoogleMapsLike.STATE_EXPANDED: Log.d("bottomsheet-", "STATE_EXPANDED"); break; case BottomSheetBehaviorGoogleMapsLike.STATE_ANCHOR_POINT: Log.d("bottomsheet-", "STATE_ANCHOR_POINT"); break; case BottomSheetBehaviorGoogleMapsLike.STATE_HIDDEN: Log.d("bottomsheet-", "STATE_HIDDEN"); break; default: Log.d("bottomsheet-", "STATE_SETTLING"); break; } } @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { } }); } public void minimizeSheet(View view) { CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorlayout); View bottomSheet = coordinatorLayout.findViewById(R.id.bottom_sheet); BottomSheetBehaviorGoogleMapsLike behavior = BottomSheetBehaviorGoogleMapsLike.from(bottomSheet); behavior.setState(BottomSheetBehaviorGoogleMapsLike.STATE_COLLAPSED); } public void closeSheet(View view) { CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorlayout); View bottomSheet = coordinatorLayout.findViewById(R.id.bottom_sheet); BottomSheetBehaviorGoogleMapsLike behavior = BottomSheetBehaviorGoogleMapsLike.from(bottomSheet); behavior.setState(BottomSheetBehaviorGoogleMapsLike.STATE_HIDDEN); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } /** * Handles a click on the menu option to get a place. * @param item The menu item to handle. * @return Boolean. */ @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.more_options) { // Do what you gotta do for Settings options here. } return true; } public void setReference() { ImageButton bt_voiceinput = (ImageButton) findViewById(R.id.speak_button); word = (EditText) findViewById(R.id.editTextView); } @Override public void onMapReady(GoogleMap map) { mMap = map; mMap.getUiSettings().setCompassEnabled(true); mMap.getUiSettings().setRotateGesturesEnabled(true); mMap.getUiSettings().setScrollGesturesEnabled(true); mMap.getUiSettings().setTiltGesturesEnabled(true); mMap.getUiSettings().setZoomControlsEnabled(true); //mMap.setMyLocationEnabled(true); // Prompt the user for permission. getLocationPermission(); // Turn on the My Location layer and the related control on the map. updateLocationUI(); // Get the current location of the device and set the position of the map. getDeviceLocation(); // Use a custom info window adapter to handle multiple lines of text in the // info window contents. mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() { @Override // Return null here, so that getInfoContents() is called next. public View getInfoWindow(Marker arg0) { return null; } @Override public View getInfoContents(Marker marker) { // Inflate the layouts for the info window, title and snippet. View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_contents, (FrameLayout) findViewById(R.id.map), false); TextView title = ((TextView) infoWindow.findViewById(R.id.title)); title.setText(marker.getTitle()); TextView snippet = ((TextView) infoWindow.findViewById(R.id.snippet)); snippet.setText(marker.getSnippet()); return infoWindow; } }); } protected void getLocationPermission() { /* * 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(this.getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mLocationPermissionGranted = true; } else { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); } } @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; } try { if (mLocationPermissionGranted) { mMap.setMyLocationEnabled(true); mMap.getUiSettings().setMyLocationButtonEnabled(true); } else { mMap.setMyLocationEnabled(false); mMap.getUiSettings().setMyLocationButtonEnabled(false); mLastKnownLocation = null; getLocationPermission(); } } catch (SecurityException e) { Log.e("Exception: %s", e.getMessage()); } } private void getDeviceLocation() { /* * Get the best and most recent location of the device, which may be null in rare * cases when a location is not available. */ try { if (mLocationPermissionGranted) { locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); criteria = new Criteria(); bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString(); try { Location location = locationManager.getLastKnownLocation(bestProvider); CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom( new LatLng(location.getLatitude(), location.getLongitude()), DEFAULT_ZOOM); mMap.animateCamera(cameraUpdate); } catch(Exception e) { CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom( new LatLng(28.6357600, 77.2244500), DEFAULT_ZOOM); mMap.animateCamera(cameraUpdate); } } } catch(Exception e) { //Log.e("Exception: %s", e.getMessage()); } } @Override protected void onPause() { super.onPause(); locationManager.removeUpdates(this); } @Override public void onLocationChanged(Location location) { //Hey, a non null location! Sweet! //remove location callback: locationManager.removeUpdates(this); //open the map: latitude = location.getLatitude(); longitude = location.getLongitude(); } @Override public void onStatusChanged(String provider, int status, Bundle extras) {} @Override public void onProviderEnabled(String provider) {} @Override public void onProviderDisabled(String provider) {} private TextChangedListener editTextChanged() { return new TextChangedListener() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }; } /** * Handle the action of the button being clicked */ public void speakButtonClicked(View v) { startVoiceRecognitionActivity(); } /** * Fire an intent to start the voice recognition activity. */ private void startVoiceRecognitionActivity() { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Ask your question..."); startActivityForResult(intent, REQUEST_CODE); } /** * Handle the results from the voice recognition activity. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) { // Populate the wordsList with the String values the recognition engine thought it heard ArrayList<String> matches = data.getStringArrayListExtra( RecognizerIntent.EXTRA_RESULTS); wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, matches)); String match = matches.get(0); //EditTextWithDeleteButton editTextWithDeleteButton = // (EditTextWithDeleteButton) findViewById(R.id.editTextView); //EditText editText = createEditText(this.getApplicationContext()); //editText.setText(match); } super.onActivityResult(requestCode, resultCode, data); } /* @SuppressLint("NewApi") private EditText createEditText(Context context) { EditText editText = new EditText(context); editText.setRawInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE); editText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); editText.setLayoutParams(new TableLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)); editText.setHorizontallyScrolling(false); editText.setVerticalScrollBarEnabled(true); editText.setGravity(Gravity.LEFT); editText.setBackground(null); return editText; }*/ }
39.09596
119
0.641002
b8273148523d973af387b2dc212341e0a1cb96ed
1,722
package com.anggito.ListViewActivity; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import java.util.ArrayList; public class RecyclerViewActivity extends AppCompatActivity { private MahasiswaAdapter mAdapter; private RecyclerView rvMahasiswa; private ArrayList<Mahasiswa> mahasiswaArrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recycler_view); addData(); rvMahasiswa = findViewById(R.id.rv_mahasiswa); mAdapter = new MahasiswaAdapter(mahasiswaArrayList); rvMahasiswa.setLayoutManager(new LinearLayoutManager(this)); rvMahasiswa.setAdapter(mAdapter); } private MahasiswaAdapter getmAdapter() { return mAdapter; } private void addData() { mahasiswaArrayList = new ArrayList<>(); mahasiswaArrayList.add(new Mahasiswa("Puteri", "E41190143", "123456789")); mahasiswaArrayList.add(new Mahasiswa("Ivon", "E41192408", "123456789")); mahasiswaArrayList.add(new Mahasiswa("Nidha", "E41190455", "123456789")); mahasiswaArrayList.add(new Mahasiswa("Dandi", "E41190142", "123456789")); mahasiswaArrayList.add(new Mahasiswa("Angga", "E41192098", "123456789")); mahasiswaArrayList.add(new Mahasiswa("Rifky", "E41192428", "123456789")); mahasiswaArrayList.add(new Mahasiswa("Anggito", "E41190255", "123456789")); }}
34.44
68
0.675377
22e2a97064f62ec3b650c247b2a785a256de34a6
12,501
package lf.com.android.blackfishdemo.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message; import android.support.design.widget.BottomSheetDialog; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.TabLayout; import android.text.SpannableString; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.view.SimpleDraweeView; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import lf.com.android.blackfishdemo.R; import lf.com.android.blackfishdemo.adapter.SimilarRecoAdapter; import lf.com.android.blackfishdemo.bean.GoodsDetailsInfo; import lf.com.android.blackfishdemo.bean.OptionalTypeInfo; import lf.com.android.blackfishdemo.bean.SimilarRecoInfo; import lf.com.android.blackfishdemo.bean.UrlInfoBean; import lf.com.android.blackfishdemo.listener.OnNetResultListener; import lf.com.android.blackfishdemo.listener.OnNumChangeListener; import lf.com.android.blackfishdemo.listener.OnRvBannerClickListener; import lf.com.android.blackfishdemo.listener.OnSwitchRvBannerListener; import lf.com.android.blackfishdemo.util.JsonUtil; import lf.com.android.blackfishdemo.util.OkHttpUtil; import lf.com.android.blackfishdemo.util.SpannableStringUtil; import lf.com.android.blackfishdemo.util.ToastUtil; import lf.com.android.blackfishdemo.view.AmountView; import lf.com.android.blackfishdemo.view.GridViewForScroll; import lf.com.android.blackfishdemo.view.RecyclerViewBanner; import lf.com.android.blackfishdemo.view.TagsLayout; public class GoodsDetailActivity extends BaseActivity { @BindView(R.id.iv_back) ImageView mIvBack; @BindView(R.id.tab_layout) TabLayout mTabLayout; @BindView(R.id.iv_more) ImageView mIvMore; @BindView(R.id.rvb_banner) RecyclerViewBanner mRvBanner; @BindView(R.id.tv_price) TextView mTvPrice; @BindView(R.id.tv_single_price) TextView mTvSinglePrice; @BindView(R.id.tv_desc) TextView mTvDesc; @BindView(R.id.tv_choose_type) TextView mTvChooseType; @BindView(R.id.iv_more_type) ImageView mIvMoreType; @BindView(R.id.tv_choose_address) TextView mTvChooseAddress; @BindView(R.id.iv_more_address) ImageView mIvMoreAddress; @BindView(R.id.gv_similar_reco) GridViewForScroll mGvSimilarReco; @BindView(R.id.coordinator_layout) CoordinatorLayout mCoordinatorLayout; @BindView(R.id.rl_dialog) RelativeLayout mRIDialog; @BindView(R.id.ll_period_info) LinearLayout mLinearPeriodInfo; @BindView(R.id.tv_fav) TextView mTextFav; @BindView(R.id.tv_imm_pay) TextView mTextImmPay; private Context context; private boolean isFav = false; private BottomSheetDialog mDialog; private List<GoodsDetailsInfo> mGoodsDetailsInfos; private Handler mHandler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { if (msg.what == 0x01) { final GoodsDetailsInfo detailsInfo = mGoodsDetailsInfos.get(0); final List<String> bannerList = detailsInfo.getmBannerList(); mRvBanner.setRvBannerData(bannerList); mRvBanner.setOnSwitchRvBannerListener(new OnSwitchRvBannerListener() { @Override public void switchBanner(int position, SimpleDraweeView draweeView) { draweeView.setImageURI(bannerList.get(position)); } }); mRvBanner.setListener(new OnRvBannerClickListener() { @Override public void OnClick(int position) { skipActivity(new Intent(context, ShowImageActivity.class)); } }); String totalPrice = "¥" + detailsInfo.getTotalPrice(); SpannableString spannableString = new SpannableStringUtil().setMallGoodsPrice(totalPrice, 0, totalPrice.length()); mTvPrice.setText(spannableString); String singlePrice = "月供 " + detailsInfo.getSinglePrice() + " 元起"; mTvSinglePrice.setText(singlePrice); mTvDesc.setText(detailsInfo.getDesc()); mTvChooseType.setText(detailsInfo.getDefaultType()); mTvChooseAddress.setText("上海市 浦东新区"); setDialogData(detailsInfo.getmOptionalTypeInfos()); List<SimilarRecoInfo> similarRecoInfos = detailsInfo.getmSimilarRecoInfos(); mGvSimilarReco.setAdapter(new SimilarRecoAdapter(context, similarRecoInfos)); } return false; } }); @Override public int getlayoutId() { return R.layout.activity_goods_detail_layout; } @Override public void initView() { Fresco.initialize(this); context = GoodsDetailActivity.this; mTabLayout.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { Toast.makeText( GoodsDetailActivity.this, "TabLayout" + tab.getPosition(), Toast.LENGTH_SHORT).show(); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); mIvBack.setOnClickListener(this); mIvMore.setOnClickListener(this); mIvMoreType.setOnClickListener(this); mIvMoreAddress.setOnClickListener(this); mRIDialog.setOnClickListener(this); mLinearPeriodInfo.setOnClickListener(this); mTextFav.setOnClickListener(this); mTextImmPay.setOnClickListener(this); } @Override public void intitdata() { mGoodsDetailsInfos = new ArrayList<>(); final JsonUtil jsonUtil = new JsonUtil(); OkHttpUtil.getInstance().startGet(UrlInfoBean.goodsDetailsUrl, new OnNetResultListener() { @Override public void OnSuccessListener(String result) { mGoodsDetailsInfos = jsonUtil.getDataFromJson(result, 4); Message message = mHandler.obtainMessage(0x01, mGoodsDetailsInfos); mHandler.sendMessage(message); } @Override public void OnFailureListener(String result) { } }); } @Override public void ClickListener(View view) { switch (view.getId()) { case R.id.iv_back: finish(); break; case R.id.iv_more: Toast toast = ToastUtil.setMyToast( this, ToastUtil.PROMPT, "更多", Toast.LENGTH_SHORT); toast.show(); break; case R.id.iv_more_type: mDialog.show(); break; case R.id.iv_more_address: Toast toast1 = ToastUtil.setMyToast( this, ToastUtil.PROMPT, "选择配送地址", Toast.LENGTH_SHORT); toast1.show(); break; case R.id.rl_dialog: showServiceDialog(); break; case R.id.ll_period_info: Toast toast2 = ToastUtil.setMyToast( this, ToastUtil.PROMPT, "月供详情", Toast.LENGTH_SHORT); toast2.show(); break; case R.id.tv_fav: Drawable[] drawables = mTextFav.getCompoundDrawables(); if (!isFav) { mTextFav.setText("已收藏"); Drawable drawable = getResources().getDrawable(R.drawable.icon_fav_checked); drawable.setBounds(0, 0, 50, 50); mTextFav.setCompoundDrawables(drawables[0], drawable, drawables[2], drawables[3]); isFav = true; } else { mTextFav.setText("收藏"); Drawable drawable = getResources().getDrawable(R.drawable.icon_fav_uncheck); drawable.setBounds(0, 0, 50, 50); mTextFav.setCompoundDrawables(drawables[0], drawable, drawables[2], drawables[3]); isFav = false; } break; case R.id.tv_imm_pay: mDialog.show(); break; default: break; } } private void showServiceDialog() { final Dialog dialog = new BottomSheetDialog(this); View view = LayoutInflater.from(this).inflate(R.layout.dialog_service_info_layout, null); view.findViewById(R.id.iv_close_dialog).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.setContentView(view); dialog.show(); } private void setDialogData(List<OptionalTypeInfo> typeInfos) { mDialog = new BottomSheetDialog(this); View view = LayoutInflater.from(this).inflate(R.layout.dialog_choose_type_layout, null); view.findViewById(R.id.iv_close_dialog).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDialog.dismiss(); } }); SimpleDraweeView draweeView = view.findViewById(R.id.iv_good); draweeView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { skipActivity(new Intent(context, ShowImageActivity.class)); } }); TextView textPrice = view.findViewById(R.id.tv_top_price); TextView textType = view.findViewById(R.id.tv_type); final TextView textAmount = view.findViewById(R.id.tv_num); final TextView textSingle = view.findViewById(R.id.tv_price_bottom); TextView textPay = view.findViewById(R.id.tv_diter_pay); textPay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDialog.dismiss(); skipActivity(new Intent(context, SubmitOrderActivity.class)); } }); TagsLayout tagsLayout = view.findViewById(R.id.labels_view); ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); for (int i = 0; i < typeInfos.size(); i++) { TextView textView = new TextView(context); textView.setPadding(10, 10, 10, 10); textView.setBackgroundColor(R.drawable.shape_search); String s = " " + typeInfos.get(i).getType() + " "; textView.setText(s); if (i == 1) { textView.setBackgroundColor(R.drawable.shape_selected_bg); textView.setTextColor(getResources().getColor(R.color.colorWhite)); } tagsLayout.addView(textView, lp); } OptionalTypeInfo typeInfo = typeInfos.get(2); String totalPrice = "¥" + typeInfo.getTotalPrice(); textPrice.setText(totalPrice); final double singlePrice = typeInfo.getSinglePrice(); setSpann(textSingle, singlePrice); AmountView amountView = view.findViewById(R.id.amount_view); amountView.setMaxNumber(100); amountView.setOnNumChangeListener(new OnNumChangeListener() { @Override public void onChange(int num) { String s = "数量: " + num; textAmount.setText(s); setSpann(textSingle, singlePrice * num); } }); mDialog.setContentView(view); } private void setSpann(TextView textView, double price) { String single = "月供 ¥" + price + " 起"; SpannableString spannableString = new SpannableStringUtil().setMallGoodsPrice(single, 3, 4 + String.valueOf(price).length()); textView.setText(spannableString); } }
38.943925
137
0.633629
664e1589988628beac39b24a5fd4a5a1a14fd0e8
444
package autograderutils; public class AutograderTestException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; private int pointsEarned = 0; public AutograderTestException() { super("Not implemented"); } public AutograderTestException(int pointsEarned, String message) { super(message); this.pointsEarned = pointsEarned; } public int getPointsEarned() { return pointsEarned; } }
19.304348
67
0.740991
638d4d5e2874d4ac726ffd709c3238fe255a1c23
2,473
package com.funsonli.bootan.module.base.controller; import com.funsonli.bootan.base.BaseResult; import com.funsonli.bootan.component.uploader.UploaderFactory; import com.funsonli.bootan.module.base.entity.File; import com.funsonli.bootan.module.base.service.FileService; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.InputStream; import java.util.UUID; @Slf4j @RestController @ApiModel("学生接口") @RequestMapping("/bootan/common") public class CommonController { @Autowired private UploaderFactory uploaderFactory; @Autowired private FileService fileService; @RequestMapping(value = "/upload",method = RequestMethod.POST) @ApiOperation(value = "文件上传") public BaseResult upload(@RequestParam(required = false) MultipartFile file, HttpServletRequest request) { String result = null; String key = rename(file.getOriginalFilename()); try { InputStream inputStream = file.getInputStream(); result = uploaderFactory.getUploader().uploadInputStream(inputStream, key); if (result != null) { File model = new File(); model.setName(file.getOriginalFilename()); model.setSize(file.getSize()); model.setFileKey(key); model.setUrl(result); model.setLocation(uploaderFactory.getType()); model.setContentType(file.getContentType()); fileService.save(model); } } catch (Exception e) { log.error(e.toString()); return BaseResult.error(e.toString()); } return BaseResult.success(result); } /** * 以UUID重命名 * * @param fileName 文件名 * @return String */ private String rename(String fileName) { String extName = fileName.substring(fileName.lastIndexOf(".")); return UUID.randomUUID().toString().replace("-", "") + extName; } }
34.347222
87
0.681359
e6d3d1b092d462c6d4b3a739c0d698ba9049a24c
5,032
package com.epam.rft.atsy.web.configuration; import com.epam.rft.atsy.service.configuration.ServiceConfiguration; import com.epam.rft.atsy.web.exceptionhandling.UncheckedExceptionResolver; import com.epam.rft.atsy.web.messageresolution.AtsyReloadableResourceBundleMessageSource; import com.epam.rft.atsy.web.messageresolution.MessageKeyResolver; import com.epam.rft.atsy.web.messageresolution.MessageKeyResolverImpl; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.CharEncoding; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.json.MappingJackson2JsonView; import java.io.File; import java.util.List; import java.util.Locale; import javax.annotation.PostConstruct; @Configuration @ComponentScan("com.epam.rft.atsy.web") @PropertySource("classpath:environment.properties") @Import({ServiceConfiguration.class}) public class WebConfiguration extends DelegatingWebMvcConfiguration { @Value("${upload_location_cv}") private String uploadLocation; @PostConstruct public void init() { File folder = new File(uploadLocation); if (!folder.exists()) { folder.mkdir(); } } @Bean public ViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/pages/"); viewResolver.setSuffix(".jsp"); return viewResolver; } @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } @Bean public ObjectMapper objectMapper() { return new ObjectMapper(); } @Bean public HttpMessageConverter jsonMessageConverter(ObjectMapper objectMapper) { return new MappingJackson2HttpMessageConverter(objectMapper); } @Bean public AtsyReloadableResourceBundleMessageSource atsyInternalMessageSource() { AtsyReloadableResourceBundleMessageSource source = new AtsyReloadableResourceBundleMessageSource(); source.setBasename("classpath:i18n/messages"); source.setDefaultEncoding(CharEncoding.UTF_8); source.setFallbackToSystemLocale(false); return source; } @Bean public MessageKeyResolver messageSource() { MessageKeyResolver messageKeyResolver = new MessageKeyResolverImpl(atsyInternalMessageSource()); return messageKeyResolver; } @Bean public LocaleResolver localeResolver() { CookieLocaleResolver resolver = new CookieLocaleResolver(); resolver.setDefaultLocale(Locale.forLanguageTag("HU")); return resolver; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("locale"); return localeChangeInterceptor; } @Bean public MappingJackson2JsonView mappingJackson2JsonView() { return new MappingJackson2JsonView(objectMapper()); } @Override protected void configureHandlerExceptionResolvers( List<HandlerExceptionResolver> exceptionResolvers) { addDefaultHandlerExceptionResolvers(exceptionResolvers); // The index is 1, in order to add it after the ExceptionHandlerExceptionResolver exceptionResolvers.add(1, new UncheckedExceptionResolver(mappingJackson2JsonView(), messageSource())); } @Bean public CommonsMultipartResolver multipartResolver() { return new CommonsMultipartResolver(); } //To resolve ${} in @Value @Bean public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() { return new PropertySourcesPlaceholderConfigurer(); } }
36.729927
106
0.809618
39edfd595a4e7f3ded0e2bfaf087b01ecd121b25
153
/** * Sample showing Query-by-Example related features of Spring Data JPA. * * @author Mark Paluch */ package example.springdata.jpa.querybyexample;
21.857143
71
0.745098
c4c48a59967062f39b2d83d69a92e9ce65ff033e
4,673
/* * Copyright 2016 Damian Terlecki. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.t3r1jj.gammaj.model.temperature; import io.github.t3r1jj.gammaj.model.Gamma; public class RgbTemperature { protected final double rgb[] = new double[3]; private final double temperature; private double xc; private double yc; private double y; private double x; private double z; private double u; private double v; public double[] getRgb() { return rgb; } public SrgbTemperature toSrgb() { return new SrgbTemperature(temperature); } /** * * @param temperature in Kelvin */ public RgbTemperature(double temperature) { this.temperature = temperature; if (temperature == Gamma.DEFAULT_TEMPERATURE) { for (int i = 0; i < rgb.length; i++) { rgb[i] = 1d; } return; } temperatureToXyy(); XyyToXyz(); XyzToRgb(); } private void temperatureToXyy() { calculateXc(); calculateYc(); } private void calculateXc() { if (temperature < 1667) { temperatureToCie1960Ucs(); } else if (temperature < 4000) { xc = -0.2661239 * (Math.pow(10, 9) / Math.pow(temperature, 3)) - 0.2343580 * (Math.pow(10, 6) / Math.pow(temperature, 2)) + 0.8776956 * (Math.pow(10, 3) / temperature) + 0.179910; } else if (temperature <= 25000) { xc = -3.0258469 * (Math.pow(10, 9) / Math.pow(temperature, 3)) + 2.1070379 * (Math.pow(10, 6) / Math.pow(temperature, 2)) + 0.2226347 * (Math.pow(10, 3) / temperature) + 0.240390; } } private void calculateYc() { if (temperature < 1667) { temperatureToCie1960Ucs(); } else if (temperature < 2222) { yc = -1.1063814 * Math.pow(xc, 3) - 1.34811020 * Math.pow(xc, 2) + 2.18555832 * xc - 0.20219683; } else if (temperature < 4000) { yc = -0.9549476 * Math.pow(xc, 3) - 1.37418593 * Math.pow(xc, 2) + 2.09137015 * xc - 0.16748867; } else if (temperature <= 25000) { yc = 3.0817580 * Math.pow(xc, 3) - 5.87338670 * Math.pow(xc, 2) + 3.75112997 * xc - 0.37001483; } } private void XyyToXyz() { y = (yc == 0) ? 0 : 1; x = (yc == 0) ? 0 : xc * y / yc; z = (yc == 0) ? 0 : ((1 - xc - yc) * y) / yc; } private void XyzToRgb() { calculateLinearRgb(); scale(); } private void calculateLinearRgb() { rgb[0] = 3.2406 * x - 1.5372 * y - 0.4986 * z; rgb[1] = -0.9689 * x + 1.8758 * y + 0.0415 * z; rgb[2] = 0.0557 * x - 0.2040 * y + 1.0570 * z; } private void scale() { double max = Math.max(rgb[0], Math.max(rgb[1], rgb[2])); if (max == 0) { for (int i = 0; i < rgb.length; i++) { rgb[i] = 0; } } for (int i = 0; i < rgb.length; i++) { rgb[i] /= max; } } private void temperatureToCie1960Ucs() { u = (0.860117757 + 1.54118254 * Math.pow(10, -4) * temperature + 1.28641212 * Math.pow(10, -7) * temperature * temperature) / (1 + 8.42420235 * Math.pow(10, -4) * temperature + 7.08145163 * Math.pow(10, -7) * temperature * temperature); v = (0.317398726 + 4.22806245 * Math.pow(10, -5) * temperature + 4.20481691 * Math.pow(10, -8) * temperature * temperature) / (1 - 2.89741816 * Math.pow(10, -5) * temperature + 1.61456053 * Math.pow(10, -7) * temperature * temperature); xc = 3d * u / (2d * u - 8d * v + 4d); yc = 2d * v / (2d * u - 8d * v + 4d); } public double getTemperature() { return temperature; } @Override public String toString() { return "rgb"; } }
31.789116
131
0.514873
0938c7f48527d4d7b96e1aa9349248743acbc06b
3,194
package at.favre.lib.crypto.singlestepkdf; import at.favre.lib.bytes.Bytes; import at.favre.lib.crypto.singlstepkdf.HFunction; import org.junit.Test; import javax.crypto.Mac; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import static org.junit.Assert.*; public class HFunctionTest { @Test public void testMessageDigestHmacSha256() throws NoSuchAlgorithmException { HFunction digest = new HFunction.MacHFunction(Mac.getInstance("HmacSHA256")); assertTrue(digest.requireInit()); assertEquals(32, digest.getHFuncOutputBytes()); assertEquals(64, digest.getHFuncInputBlockLengthBytes()); digest.init(new byte[32]); digest.update(new byte[0]); assertEquals("b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad", Bytes.wrap(digest.calculate()).encodeHex()); digest.reset(); } @Test public void testMessageDigestHmacSha512() throws NoSuchAlgorithmException { HFunction digest = new HFunction.MacHFunction(Mac.getInstance("HmacSHA512")); assertTrue(digest.requireInit()); assertEquals(64, digest.getHFuncOutputBytes()); assertEquals(128, digest.getHFuncInputBlockLengthBytes()); digest.init(new byte[64]); digest.update(new byte[0]); assertEquals("b936cee86c9f87aa5d3c6f2e84cb5a4239a5fe50480a6ec66b70ab5b1f4ac6730c6c515421b327ec1d69402e53dfb49ad7381eb067b338fd7b0cb22247225d47", Bytes.wrap(digest.calculate()).encodeHex()); digest.reset(); } @Test public void testMessageDigestSha256() throws NoSuchAlgorithmException { HFunction digest = new HFunction.MessageDigestHFunction(MessageDigest.getInstance("SHA-256")); assertFalse(digest.requireInit()); assertEquals(32, digest.getHFuncOutputBytes()); assertEquals(64, digest.getHFuncInputBlockLengthBytes()); digest.update(new byte[0]); assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", Bytes.wrap(digest.calculate()).encodeHex()); digest.reset(); } @Test public void testMessageDigestSha512() throws NoSuchAlgorithmException { HFunction digest = new HFunction.MessageDigestHFunction(MessageDigest.getInstance("SHA-512")); assertFalse(digest.requireInit()); assertEquals(64, digest.getHFuncOutputBytes()); assertEquals(128, digest.getHFuncInputBlockLengthBytes()); digest.update(new byte[0]); assertEquals("cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", Bytes.wrap(digest.calculate()).encodeHex()); digest.reset(); } @Test(expected = UnsupportedOperationException.class) public void testMessageDigestNotSupportInit() throws NoSuchAlgorithmException { new HFunction.MessageDigestHFunction(MessageDigest.getInstance("SHA-256")).init(new byte[32]); } @Test(expected = IllegalArgumentException.class) public void testMacInvalidKey() throws NoSuchAlgorithmException { new HFunction.MacHFunction(Mac.getInstance("HmacSha256")).init(new byte[0]); } }
40.43038
197
0.74139
fe7f8585983a801bbebb6508f7b935fc5b81c27e
1,264
package org.dicl.velox.mapreduce; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; public class Chunk implements Writable { public String fileName; public long size; //public long index; public int index; public long offset; public String host; public Chunk() { } /** * Constructor. */ //public Chunk(String fileName, long size, long index, long offset, String host) { public Chunk(String fileName, long size, int index, long offset, String host) { this.fileName = fileName; this.index = index; this.size = size; this.offset = offset; this.host = host; } @Override public void readFields(DataInput in) throws IOException { fileName = Text.readString(in); size = in.readLong(); //index = in.readLong(); index = in.readInt(); offset = in.readLong(); host = Text.readString(in); } @Override public void write(DataOutput out) throws IOException { Text.writeString(out, fileName); out.writeLong(size); //out.writeLong(index); out.writeInt(index); out.writeLong(offset); // Is it needed? Text.writeString(out, host); } }
24.307692
85
0.689873
10b8a6d2dbc160de219f93475e9c491f90aaf1c9
13,428
/***************************************************************** * 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.cayenne.conf; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import org.apache.cayenne.util.Util; import org.apache.cayenne.access.dbsync.SkipSchemaUpdateStrategy; import org.apache.cayenne.map.DataMap; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; /** * Class that performs runtime loading of Cayenne configuration. */ public class ConfigLoader { protected XMLReader parser; protected ConfigLoaderDelegate delegate; /** Creates new ConfigLoader. */ public ConfigLoader(ConfigLoaderDelegate delegate) throws Exception { if (delegate == null) { throw new IllegalArgumentException("Delegate must not be null."); } this.delegate = delegate; parser = Util.createXmlReader(); } /** * Returns the delegate. * * @return ConfigLoaderDelegate */ public ConfigLoaderDelegate getDelegate() { return delegate; } /** * Parses XML input, invoking delegate methods to interpret loaded XML. * * @param in * @return boolean */ public boolean loadDomains(InputStream in) { DefaultHandler handler = new RootHandler(); parser.setContentHandler(handler); parser.setErrorHandler(handler); try { delegate.startedLoading(); parser.parse(new InputSource(in)); delegate.finishedLoading(); } catch (IOException ioex) { getDelegate().loadError(ioex); } catch (SAXException saxex) { getDelegate().loadError(saxex); } // return true if no failures return !getDelegate().getStatus().hasFailures(); } // SAX handlers start below /** * Handler for the root element. Its only child must be the "domains" element. */ private class RootHandler extends DefaultHandler { /** * Handles the start of a datadomains element. A domains handler is created and * initialised with the element name and attributes. * * @exception SAXException if the tag given is not <code>"domains"</code> */ @Override public void startElement( String namespaceURI, String localName, String qName, Attributes attrs) throws SAXException { if (localName.equals("domains")) { delegate.shouldLoadProjectVersion(attrs.getValue("", "project-version")); new DomainsHandler(parser, this); } else { throw new SAXParseException("<domains> should be the root element. <" + localName + "> is unexpected.", null); } } } /** * Handler for the top level "project" element. */ private class DomainsHandler extends AbstractHandler { /** * Constructor which just delegates to the superconstructor. * * @param parentHandler The handler which should be restored to the parser at the * end of the element. Must not be <code>null</code>. */ public DomainsHandler(XMLReader parser, ContentHandler parentHandler) { super(parser, parentHandler); } /** * Handles the start of a top-level element within the project. An appropriate * handler is created and initialised with the details of the element. */ @Override public void startElement( String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { if (localName.equals("domain")) { new DomainHandler(getParser(), this).init(localName, atts); } else if (localName.equals("view")) { new ViewHandler(getParser(), this).init(atts); } else { String message = "<domain> or <view> are only valid children of <domains>. <" + localName + "> is unexpected."; throw new SAXParseException(message, null); } } } private class ViewHandler extends AbstractHandler { public ViewHandler(XMLReader parser, ContentHandler parentHandler) { super(parser, parentHandler); } public void init(Attributes attrs) { String name = attrs.getValue("", "name"); String location = attrs.getValue("", "location"); delegate.shouldRegisterDataView(name, location); } } /** * Handler for the "domain" element. */ private class DomainHandler extends AbstractHandler { private String domainName; private Map<String, String> properties; private Map<String, DataMap> mapLocations; public DomainHandler(XMLReader parser, ContentHandler parentHandler) { super(parser, parentHandler); } public void init(String name, Attributes attrs) { domainName = attrs.getValue("", "name"); mapLocations = new HashMap<String, DataMap>(); properties = new HashMap<String, String>(); delegate.shouldLoadDataDomain(domainName); } @Override public void startElement( String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { if (localName.equals("property")) { new PropertyHandler(getParser(), this).init(atts, properties); } else if (localName.equals("map")) { // "map" elements go after "property" elements // must flush properties if there are any loadProperties(); new MapHandler(getParser(), this).init( localName, atts, domainName, mapLocations); } else if (localName.equals("node")) { // "node" elements go after "map" elements // must flush maps if there are any loadMaps(); new NodeHandler(getParser(), this).init(localName, atts, domainName); } else { String message = "<node> or <map> should be the children of <domain>. <" + localName + "> is unexpected."; throw new SAXParseException(message, null); } } @Override protected void finished() { loadProperties(); loadMaps(); } private void loadProperties() { if (properties.size() > 0) { // load all properties delegate.shouldLoadDataDomainProperties(domainName, properties); // clean properties to avoid loading them twice properties.clear(); } } private void loadMaps() { if (mapLocations.size() > 0) { // load all maps delegate.shouldLoadDataMaps(domainName, mapLocations); // clean map locations to avoid loading maps twice mapLocations.clear(); } } } private class PropertyHandler extends AbstractHandler { public PropertyHandler(XMLReader parser, ContentHandler parentHandler) { super(parser, parentHandler); } public void init(Attributes attrs, Map<String, String> properties) { String name = attrs.getValue("", "name"); String value = attrs.getValue("", "value"); if (name != null && value != null) { properties.put(name, value); } } } private class MapHandler extends AbstractHandler { protected String domainName; protected String mapName; protected String location; private Map mapLocations; public MapHandler(XMLReader parser, ContentHandler parentHandler) { super(parser, parentHandler); } public void init( String name, Attributes attrs, String domainName, Map<String, DataMap> locations) { this.domainName = domainName; this.mapLocations = locations; mapName = attrs.getValue("", "name"); location = attrs.getValue("", "location"); } @Override public void startElement( String namespaceURI, String localName, String qName, Attributes attrs) throws SAXException { if (localName.equals("dep-map-ref")) { // this is no longer supported, but kept as noop // for backwards compatibility new DepMapRefHandler(getParser(), this).init(localName, attrs); } else { throw new SAXParseException( "<dep-map-ref> should be the only map child. <" + localName + "> is unexpected.", null); } } @Override protected void finished() { mapLocations.put(mapName, location); } } /** Handles processing of "node" element. */ private class NodeHandler extends AbstractHandler { protected String nodeName; protected String domainName; public NodeHandler(XMLReader parser, ContentHandler parentHandler) { super(parser, parentHandler); } public void init(String name, Attributes attrs, String domainName) { this.domainName = domainName; nodeName = attrs.getValue("", "name"); String dataSrcLocation = attrs.getValue("", "datasource"); String adapterClass = attrs.getValue("", "adapter"); String factoryName = attrs.getValue("", "factory"); String schemaUpdateStrategyName = attrs .getValue("", "schema-update-strategy"); if (schemaUpdateStrategyName == null) { schemaUpdateStrategyName = SkipSchemaUpdateStrategy.class.getName(); } delegate.shouldLoadDataNode( domainName, nodeName, dataSrcLocation, adapterClass, factoryName, schemaUpdateStrategyName); } @Override public void startElement( String namespaceURI, String localName, String qName, Attributes attrs) throws SAXException { if (localName.equals("map-ref")) { new MapRefHandler(getParser(), this).init( localName, attrs, domainName, nodeName); } else { throw new SAXParseException("<map-ref> should be the only node child. <" + localName + "> is unexpected.", null); } } } // this handler is deprecated, but is kept around for backwards compatibility private class DepMapRefHandler extends AbstractHandler { public DepMapRefHandler(XMLReader parser, ContentHandler parentHandler) { super(parser, parentHandler); } public void init(String name, Attributes attrs) { } } private class MapRefHandler extends AbstractHandler { public MapRefHandler(XMLReader parser, ContentHandler parentHandler) { super(parser, parentHandler); } public void init(String name, Attributes attrs, String domainName, String nodeName) { String mapName = attrs.getValue("", "name"); delegate.shouldLinkDataMap(domainName, nodeName, mapName); } } }
33.654135
93
0.557641
4682b5ccdb77f0c4787f559763eee489bb9c8cbc
3,630
package com.perunlabs.jsolid.d3; import static com.perunlabs.jsolid.JSolid.matrix; import static com.perunlabs.jsolid.JSolid.max; import static com.perunlabs.jsolid.JSolid.min; import static com.perunlabs.jsolid.JSolid.range; import com.perunlabs.jsolid.JSolid; import com.perunlabs.jsolid.d1.Angle; import com.perunlabs.jsolid.d1.Range; public abstract class Axis<A extends Axis<A>> extends Vector3 { public static final XAxis X = new XAxis(); public static final YAxis Y = new YAxis(); public static final ZAxis Z = new ZAxis(); private Axis(double x, double y, double z) { super(x, y, z); } public abstract double coordinate(Vector3 v); public abstract Vector3 v(double coordinate); public Range rangeOf(Solid solid) { return range(min().on(this).valueIn(solid), max().on(this).valueIn(solid)); } public double sizeOf(Solid solid) { return rangeOf(solid).size(); } public abstract Matrix4 rotateMatrix(Angle angle); public abstract Matrix4 mirrorMatrix(); public abstract Matrix4 scaleMatrix(double factor); public static class XAxis extends Axis<XAxis> { public XAxis() { super(1, 0, 0); } public double coordinate(Vector3 v) { return v.x; } public Vector3 v(double coordinate) { return JSolid.v(coordinate, 0, 0); } public Matrix4 rotateMatrix(Angle angle) { double sin = Math.sin(angle.radians()); double cos = Math.cos(angle.radians()); return matrix( 1, 0, 0, 0, 0, cos, -sin, 0, 0, sin, cos, 0, 0, 0, 0, 1); } public Matrix4 mirrorMatrix() { return new Matrix4( -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } public Matrix4 scaleMatrix(double factor) { return matrix( factor, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } } public static class YAxis extends Axis<YAxis> { public YAxis() { super(0, 1, 0); } public double coordinate(Vector3 v) { return v.y; } public Vector3 v(double coordinate) { return JSolid.v(0, coordinate, 0); } public Matrix4 rotateMatrix(Angle angle) { double sin = Math.sin(angle.radians()); double cos = Math.cos(angle.radians()); return matrix( cos, 0, sin, 0, 0, 1, 0, 0, -sin, 0, cos, 0, 0, 0, 0, 1); } public Matrix4 mirrorMatrix() { return new Matrix4( 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } public Matrix4 scaleMatrix(double factor) { return matrix( 1, 0, 0, 0, 0, factor, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } } public static class ZAxis extends Axis<ZAxis> { public ZAxis() { super(0, 0, 1); } public double coordinate(Vector3 v) { return v.z; } public Vector3 v(double coordinate) { return JSolid.v(0, 0, coordinate); } public Matrix4 rotateMatrix(Angle angle) { double sin = Math.sin(angle.radians()); double cos = Math.cos(angle.radians()); return matrix( cos, -sin, 0, 0, sin, cos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } public Matrix4 mirrorMatrix() { return new Matrix4( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1); } public Matrix4 scaleMatrix(double factor) { return matrix( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, factor, 0, 0, 0, 0, 1); } } }
22.6875
79
0.550689
b03f1ab4740b1cbb6d16dd8d3eeffe2e1a340ade
2,106
import com.nag.routines.X03.X03AA; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileNotFoundException; import java.io.IOException; /** * X03AAJ example program text. * @author willa * @since 27.1.0.0 */ public class X03AAJE{ /** * X03AAJ example main program. */ public static void main(String[] args){ int n = 3; double c1 = 0, c2 = 0, d1 = 0, d2 = 0; //placeholder int ifail, isizea, isizeb, istepa, istepb; boolean sw; double[] a, b; a = new double[n * n]; b = new double[n]; System.out.println("X03AAF Example Program Results"); System.out.println(); if(args.length != 1){ System.err.println("Please specify the path to the data file."); System.exit(-1); } String filename = args[0]; try{ BufferedReader reader = new BufferedReader(new FileReader(filename)); String line = reader.readLine(); //skip header //stored column wise //a = (-2, -3, 7) // ( 2, -5, 3) // (-9, 1, 0) for(int i = 0; i < n; i++){ line = reader.readLine(); String[] sVal = line.split("\\s+"); for(int j = 0; j < n; j++){ a[i + (j * n)] = Double.parseDouble(sVal[j + 1]); } } line = reader.readLine(); for(int i = 0; i < n; i++){ String[] sVal = line.split("\\s+"); b[i] = Double.parseDouble(sVal[i + 1]); } } catch(FileNotFoundException e){ System.err.println("***FATAL: Can't find " + filename); System.exit(-2); } catch(IOException e){ System.err.println("***FATAL: Can't read " + filename + "\n" + e.getMessage()); } c1 = 1; c2 = 0; isizea = n; isizeb = n; istepa = 1; istepb = 1; sw = true; ifail = 0; X03AA x03aa = new X03AA(a , isizea, b, isizeb, n, istepa, istepb, c1, c2, d1, d2, sw, ifail); x03aa.eval(); //update c1 = x03aa.getC1(); c2 = x03aa.getC2(); d1 = x03aa.getD1(); d2 = x03aa.getD2(); System.out.printf("D1 = %.1f D2 = %.1f\n", d1, d2); } }
23.931818
97
0.534663
1847a825a39d8cfee29bef79f42d4e7fca35126b
3,508
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.eventbridge.models; import com.aliyun.tea.*; /** * The response of create event streaming */ public class GetEventStreamingResponse extends TeaModel { @NameInMap("RequestId") @Validation(required = true) public String requestId; @NameInMap("ResourceOwnerAccountId") @Validation(required = true) public String resourceOwnerAccountId; @NameInMap("EventStreamingName") @Validation(required = true) public String eventStreamingName; @NameInMap("Description") @Validation(required = true) public String description; @NameInMap("Source") @Validation(required = true) public Source source; @NameInMap("FilterPattern") @Validation(required = true) public String filterPattern; @NameInMap("Sink") @Validation(required = true) public Sink sink; @NameInMap("RunOptions") @Validation(required = true) public RunOptions runOptions; @NameInMap("Tag") @Validation(required = true) public String tag; @NameInMap("Status") @Validation(required = true) public String status; public static GetEventStreamingResponse build(java.util.Map<String, ?> map) { GetEventStreamingResponse self = new GetEventStreamingResponse(); return TeaModel.build(map, self); } public GetEventStreamingResponse setRequestId(String requestId) { this.requestId = requestId; return this; } public String getRequestId() { return this.requestId; } public GetEventStreamingResponse setResourceOwnerAccountId(String resourceOwnerAccountId) { this.resourceOwnerAccountId = resourceOwnerAccountId; return this; } public String getResourceOwnerAccountId() { return this.resourceOwnerAccountId; } public GetEventStreamingResponse setEventStreamingName(String eventStreamingName) { this.eventStreamingName = eventStreamingName; return this; } public String getEventStreamingName() { return this.eventStreamingName; } public GetEventStreamingResponse setDescription(String description) { this.description = description; return this; } public String getDescription() { return this.description; } public GetEventStreamingResponse setSource(Source source) { this.source = source; return this; } public Source getSource() { return this.source; } public GetEventStreamingResponse setFilterPattern(String filterPattern) { this.filterPattern = filterPattern; return this; } public String getFilterPattern() { return this.filterPattern; } public GetEventStreamingResponse setSink(Sink sink) { this.sink = sink; return this; } public Sink getSink() { return this.sink; } public GetEventStreamingResponse setRunOptions(RunOptions runOptions) { this.runOptions = runOptions; return this; } public RunOptions getRunOptions() { return this.runOptions; } public GetEventStreamingResponse setTag(String tag) { this.tag = tag; return this; } public String getTag() { return this.tag; } public GetEventStreamingResponse setStatus(String status) { this.status = status; return this; } public String getStatus() { return this.status; } }
25.794118
95
0.673033
3e1c522653a463cf1fa72e113d20c9c7203e4494
3,127
package youngfriend.main_pnl.deleagte; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import youngfriend.exception.ParamValidateExcption; import youngfriend.main_pnl.utils.MainPnlUtil; import youngfriend.utils.PubUtil; import javax.swing.JButton; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Iterator; /** * Created by xiong on 9/2/16. */ public class OutParamTableDeletate { //出口参数表格index public static final int INDEX_OUTPARAMS_FIELD = 0; public static final int INDEX_OUTPARAMS_FIELD_DESC = 1; private final DefaultTableModel model; private JTable table; public OutParamTableDeletate(final JTable table, JButton addBtn, JButton delBtn) { this.table=table; model = (DefaultTableModel) table.getModel(); addBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { PubUtil.stopTabelCellEditor(table); int selectedRow = table.getSelectedRow(); selectedRow++; model.insertRow(selectedRow, new String[2]); PubUtil.tableSelect(table, selectedRow); } }); PubUtil.tableDelRow(delBtn, table); } public void clear() { MainPnlUtil.clearTable(table); } public void load(JsonObject inparamObj) { JsonArray outparam = PubUtil.getJsonObj(inparamObj, "outparam", JsonArray.class); if (outparam != null) { JsonArray outParams = PubUtil.getJsonObj(outparam.get(0).getAsJsonObject(), "outParams", JsonArray.class); if(outParams!=null){ Iterator<JsonElement> iterator = outParams.iterator(); while (iterator.hasNext()) { JsonObject fieldObj = iterator.next().getAsJsonObject(); model.addRow(new String[]{PubUtil.getProp(fieldObj, "name"), PubUtil.getProp(fieldObj, "label")}); } } } } public JsonArray getOutParamsLevel2() { PubUtil.stopTabelCellEditor(table); int rowCount_out = table.getRowCount(); JsonArray fieldoutParams = null; if (rowCount_out > 0) { fieldoutParams = new JsonArray(); for (int i = 0; i < rowCount_out; i++) { String fieldname = (String) table.getValueAt(i, INDEX_OUTPARAMS_FIELD); String fielddesc = (String) table.getValueAt(i, INDEX_OUTPARAMS_FIELD_DESC); if (PubUtil.existNull(fieldname, fielddesc)) { PubUtil.tableSelect(table, i); throw new ParamValidateExcption("出口参数设错误"); } JsonObject fieldObj = new JsonObject(); fieldObj.addProperty("name", fieldname); fieldObj.addProperty("label", fielddesc); fieldoutParams.add(fieldObj); } } return fieldoutParams; } }
36.360465
118
0.631276
30a9876824d9a78d8faebf1d7be62724bc267a04
176
package no.helgeby.inventory.domain.model; public interface Product { ProductCode getCode(); String getDescription(); ProductType getType(); Weight getNetWeight(); }
12.571429
42
0.75
7fca56bdba9e6ff60ede249a2c39d19bf7d1b988
2,559
package amten.ml.examples; import amten.ml.NNParams; import amten.ml.matrix.Matrix; import amten.ml.matrix.MatrixUtils; /** * Examples of using NeuralNetwork for regression. * * @author Johannes Amtén */ public class NNRegressionExample { /** * Performs regression on a dataset of car prices for cars with different features. * <br></br> * Uses file /example_data/Car_Prices.csv */ public static void runCarPricesRegression() throws Exception { System.out.println("Running regression on Car Prices dataset...\n"); // Read data from CSV-file int headerRows = 1; char separator = ','; Matrix data = MatrixUtils.readCSV("example_data/Car_Prices.csv", separator, headerRows); // Split data into training set and crossvalidation set. float crossValidationPercent = 33; Matrix[] split = MatrixUtils.split(data, crossValidationPercent, 0); Matrix dataTrain = split[0]; Matrix dataCV = split[1]; // 15:th column contains the correct price. The rest are the indata. Matrix xTrain = dataTrain.getColumns(0, 13); Matrix yTrain = dataTrain.getColumns(14, 14); Matrix xCV = dataCV.getColumns(0, 13); Matrix yCV = dataCV.getColumns(14, 14); // Use default parameters; single hidden layer with 100 units. NNParams params = new NNParams(); long startTime = System.currentTimeMillis(); amten.ml.NeuralNetwork nn = new amten.ml.NeuralNetwork(params); nn.train(xTrain, yTrain); System.out.println("\nTraining time: " + String.format("%.3g", (System.currentTimeMillis() - startTime) / 1000.0) + "s"); Matrix predictions = nn.getPredictions(xTrain); double error = 0; for (int i = 0; i < predictions.numRows(); i++) { error += Math.pow(predictions.get(i, 0) - yTrain.get(i, 0), 2); } error = Math.sqrt(error / predictions.numRows()); System.out.println("Training set root mean squared error: " + String.format("%.4g", error)); predictions = nn.getPredictions(xCV); error = 0; for (int i = 0; i < predictions.numRows(); i++) { error += Math.pow(predictions.get(i, 0) - yCV.get(i, 0), 2); } error = Math.sqrt(error / predictions.numRows()); System.out.println("Crossvalidation set root mean squared error: " + String.format("%.4g", error)); } public static void main(String[] args) throws Exception { runCarPricesRegression(); } }
37.632353
129
0.632669
3a4c03417d4a2ff6caf3a9f264558f74b13b87d3
344
package com.frame4j.base.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.NoRepositoryBean; /** * 通用repository * * @author MJ * * @param <T> * @param <ID> */ @NoRepositoryBean public interface BaseRepository<T, ID> extends JpaRepository<T, ID> { }
19.111111
70
0.706395
2cf61ca5b633335fb3aa04c20504f0f5e2dd95c8
922
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.resources.implementation; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.resourcemanager.resources.models.Tenants; import com.azure.resourcemanager.resources.fluent.inner.TenantIdDescriptionInner; import com.azure.resourcemanager.resources.fluent.TenantsClient; /** * Implementation for {@link Tenants}. */ public final class TenantsImpl implements Tenants { private final TenantsClient client; public TenantsImpl(final TenantsClient client) { this.client = client; } @Override public PagedIterable<TenantIdDescriptionInner> list() { return client.list(); } @Override public PagedFlux<TenantIdDescriptionInner> listAsync() { return client.listAsync(); } }
27.939394
81
0.747289
add5db9bf5a01e602e8b86a4c369c3e294b828d8
5,244
package com.server.controller; import java.net.URI; import java.util.Base64; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.bordercloud.sparql.Method; import com.bordercloud.sparql.MimeType; import com.bordercloud.sparql.SparqlResult; @RestController public class HTTPRequestController { private static final Logger log = LogManager.getLogger(HTTPRequestController.class); @SuppressWarnings({ "rawtypes", "unchecked" }) @RequestMapping(value = "/", method = { RequestMethod.GET, RequestMethod.POST }) public ResponseEntity<?> wikidata(@RequestParam(name = "endpoint", required = true) String endpointURI, @RequestParam(name = "query", required = true) String query, @RequestParam(name = "method", required = false) String httpMethod, @RequestParam(name = "default-graph-uri", required = false) String defaultGraphUri, @RequestParam(name = "format", required = false) String format) { try { // String decodedEndpoint = this.decodeBase64Content(endpointURI); // String decodedQuery = this.decodeBase64Content(query); String decodedEndpoint = endpointURI; String decodedQuery = query; log.info("Decoded URL: " + ((decodedEndpoint != null) ? decodedEndpoint : "null")); log.info("Decoded Query: " + ((decodedQuery != null) ? decodedQuery : "null")); log.info("method: " + ((httpMethod != null) ? httpMethod : "null")); log.info("format: " + ((format != null) ? format : "null")); log.info("default-graph-uri: " + ((defaultGraphUri != null) ? defaultGraphUri : "null")); if (decodedQuery == null || decodedQuery.equalsIgnoreCase("undefined")) { log.info("Recieved empty query := " + decodedQuery); return new ResponseEntity("Recieved query=undefined", HttpStatus.BAD_REQUEST); } URI endpoint = new URI(decodedEndpoint); String querySelect = decodedQuery; // querySelect = querySelect+"%26format="+format; MySparqlClient sc = new MySparqlClient(false); if (httpMethod != null && httpMethod.equalsIgnoreCase("POST")) { sc.setMethodHTTPRead(Method.POST); } else { sc.setMethodHTTPRead(Method.GET); } sc.setEndpointRead(endpoint); SparqlResult sr = null; if (format != null && format.equalsIgnoreCase("xml")) sr = sc.query(querySelect, MimeType.xml); else sr = sc.query(querySelect, MimeType.json); if (sr != null && sr.resultRaw != null) { log.info(sr.resultRaw); return new ResponseEntity(sr.resultRaw, HttpStatus.OK); } else { log.info("Recieved empty response"); return new ResponseEntity("{} ", HttpStatus.OK); } } catch (Exception e) { e.printStackTrace(); log.error(e); return new ResponseEntity(e.getMessage(), HttpStatus.BAD_REQUEST); } } private String decodeBase64Content(String value) { Base64.Decoder decoder = Base64.getDecoder(); String dStr = new String(decoder.decode(value)); return dStr; } /* * apache httpclient lib code * * @GetMapping("/proxy") public ResponseEntity<?> * getProxyResponse(@RequestParam(name = "endpoint", required = true) String * endpointURI, * * @RequestParam(name = "query", required = true) String query, * * @RequestParam(name = "method") String httpMethod) { * * CloseableHttpClient httpClient = * HttpClients.custom().disableContentCompression().build(); try { * * String decodedEndpoint = this.decodeBase64Content(endpointURI); String * decodedQuery = this.decodeBase64Content(query); String domainName = * this.getDomainName(decodedEndpoint); * * HttpUriRequest request = * RequestBuilder.get().setUri(decodedEndpoint).addParameter("query", * decodedQuery) .setHeader(HttpHeaders.CONTENT_TYPE, "application/json") * .setHeader(HttpHeaders.ACCEPT, * "application/json").setHeader(HttpHeaders.REFERER, domainName) // * .setHeader(HttpHeaders.HOST, domainName) .setHeader(HttpHeaders.USER_AGENT, * "SpringBoot API") .setHeader(HttpHeaders.CACHE_CONTROL, "no-cache").build(); * * HttpResponse response = httpClient.execute(request); StatusLine statusLine = * response.getStatusLine(); System.out.println(statusLine.getStatusCode() + " " * + statusLine.getReasonPhrase()); String responseBody = * EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); * System.out.println(responseBody); * * System.out.println(response); logger.info(response); return new * ResponseEntity(responseBody, HttpStatus.OK); } catch (Exception e) { * e.printStackTrace(); return new ResponseEntity(e.getMessage(), * HttpStatus.BAD_REQUEST); } finally { if (httpClient != null) { try { * httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } } */ /* * private String getDomainName(String url) throws URISyntaxException { URI uri * = new URI(url); String domain = uri.getHost(); return * domain.startsWith("www.") ? domain.substring(4) : domain; } */ }
39.727273
104
0.718345
7a1cc886100815fdc644d4d43bea13f3af8ee247
8,570
package de.adorsys.ledgers.postings.impl.service; import de.adorsys.ledgers.postings.api.domain.ChartOfAccountBO; import de.adorsys.ledgers.postings.api.domain.LedgerAccountBO; import de.adorsys.ledgers.postings.api.domain.LedgerBO; import de.adorsys.ledgers.postings.db.domain.ChartOfAccount; import de.adorsys.ledgers.postings.db.domain.Ledger; import de.adorsys.ledgers.postings.db.domain.LedgerAccount; import de.adorsys.ledgers.postings.db.repository.ChartOfAccountRepository; import de.adorsys.ledgers.postings.db.repository.LedgerAccountRepository; import de.adorsys.ledgers.postings.db.repository.LedgerRepository; import de.adorsys.ledgers.util.exception.PostingModuleException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.time.LocalDateTime; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class AbstractServiceImplTest { private static final String ACCOUNT_ID = "ledger account id"; private static final String ACCOUNT_NAME = "ledger account name"; private static final String LEDGER_ID = "ledger id"; private static final String LEDGER_NAME = "ledger name"; @InjectMocks AbstractServiceImpl service; @Mock private LedgerAccountRepository ledgerAccountRepository; @Mock private ChartOfAccountRepository chartOfAccountRepo; @Mock private LedgerRepository ledgerRepository; @Test void loadCoa() { // Given when(chartOfAccountRepo.findById(anyString())).thenReturn(Optional.of(getCoa())); // When ChartOfAccount result = service.loadCoa(getCoaBO("id", "name")); // Then assertEquals(new ChartOfAccount(), result); } @Test void loadCoa_id_not_present() { // Given when(chartOfAccountRepo.findOptionalByName(anyString())).thenReturn(Optional.of(getCoa())); // When ChartOfAccount result = service.loadCoa(getCoaBO(null, "name")); // Then assertEquals(new ChartOfAccount(), result); } @Test void loadCoa_no_identifier_present() { // Then assertThrows(PostingModuleException.class, () -> service.loadCoa(getCoaBO(null, null))); } @Test void loadCoa_by_id_not_found() { // Given when(chartOfAccountRepo.findById(anyString())).thenReturn(Optional.empty()); // Then assertThrows(PostingModuleException.class, () -> service.loadCoa(getCoaBO("id", "name"))); } @Test void loadCoa_by_name_not_found() { // Given when(chartOfAccountRepo.findOptionalByName(anyString())).thenReturn(Optional.empty()); // Then assertThrows(PostingModuleException.class, () -> service.loadCoa(getCoaBO(null, "name"))); } @Test void loadCoa_null_body() { // Then assertThrows(PostingModuleException.class, () -> service.loadCoa(null)); } @Test void loadLedgerAccountBO() { // Given when(ledgerAccountRepository.findById(anyString())).thenReturn(Optional.of(new LedgerAccount())); LedgerBO ledger = getLedger(LEDGER_ID, LEDGER_NAME); // When LedgerAccount result = service.loadLedgerAccountBO(getLedgerAccountBO(ACCOUNT_ID, ACCOUNT_NAME, ledger)); // Then assertEquals(new LedgerAccount(), result); } @Test void loadLedgerAccountBO_by_name_n_ledger_id() { // Given when(ledgerRepository.findById(anyString())).thenReturn(Optional.of(new Ledger())); when(ledgerAccountRepository.findOptionalByLedgerAndName(any(), anyString())).thenReturn(Optional.of(new LedgerAccount())); LedgerBO ledger = getLedger(LEDGER_ID, LEDGER_NAME); // When LedgerAccount result = service.loadLedgerAccountBO(getLedgerAccountBO(null, ACCOUNT_NAME, ledger)); // Then assertEquals(new LedgerAccount(), result); } @Test void loadLedgerAccountBO_by_name_n_ledger_name() { // Given when(ledgerRepository.findOptionalByName(anyString())).thenReturn(Optional.of(new Ledger())); when(ledgerAccountRepository.findOptionalByLedgerAndName(any(), anyString())).thenReturn(Optional.of(new LedgerAccount())); LedgerBO ledger = getLedger(null, LEDGER_NAME); // When LedgerAccount result = service.loadLedgerAccountBO(getLedgerAccountBO(null, ACCOUNT_NAME, ledger)); // Then assertEquals(new LedgerAccount(), result); } @Test void loadLedgerAccountBO_by_name_n_ledger_insufficient_ledger_info() { // Given LedgerBO ledger = getLedger(null, null); // Then assertThrows(PostingModuleException.class, () -> { LedgerAccount result = service.loadLedgerAccountBO(getLedgerAccountBO(null, ACCOUNT_NAME, ledger)); assertEquals(new LedgerAccount(), result); }); } @Test void loadLedgerAccountBO_by_id_nf() { // Given when(ledgerAccountRepository.findById(anyString())).thenReturn(Optional.empty()); LedgerBO ledger = getLedger(null, null); // Then assertThrows(PostingModuleException.class, () -> { LedgerAccount result = service.loadLedgerAccountBO(getLedgerAccountBO(ACCOUNT_ID, ACCOUNT_NAME, ledger)); assertEquals(new LedgerAccount(), result); }); } @Test void loadLedgerAccountBO_by_name_nf() { // Given when(ledgerRepository.findById(anyString())).thenReturn(Optional.of(new Ledger())); when(ledgerAccountRepository.findOptionalByLedgerAndName(any(), anyString())).thenReturn(Optional.empty()); LedgerBO ledger = getLedger(LEDGER_ID, null); // Then assertThrows(PostingModuleException.class, () -> { LedgerAccount result = service.loadLedgerAccountBO(getLedgerAccountBO(null, ACCOUNT_NAME, ledger)); assertEquals(new LedgerAccount(), result); }); } @Test void loadLedgerAccountBO_null() { // Then assertThrows(PostingModuleException.class, () -> { LedgerAccount result = service.loadLedgerAccountBO(null); assertEquals(new LedgerAccount(), result); }); } @Test void loadLedgerAccountBO_null_info() { // Given LedgerBO ledger = getLedger(LEDGER_ID, null); // Then assertThrows(PostingModuleException.class, () -> { LedgerAccount result = service.loadLedgerAccountBO(getLedgerAccountBO(null, null, ledger)); assertEquals(new LedgerAccount(), result); }); } @Test void loadLedger() { // Then assertThrows(PostingModuleException.class, () -> service.loadLedger((LedgerBO) null)); } @Test void loadLedger_id_nf() { // Given when(ledgerRepository.findById(anyString())).thenReturn(Optional.empty()); // Then assertThrows(PostingModuleException.class, () -> service.loadLedger(getLedger(LEDGER_ID, LEDGER_NAME))); } @Test void loadLedger_name_nf() { // Given when(ledgerRepository.findOptionalByName(anyString())).thenReturn(Optional.empty()); // Then assertThrows(PostingModuleException.class, () -> service.loadLedger(getLedger(null, LEDGER_NAME))); } @Test void loadLedger_null() { // Then assertThrows(PostingModuleException.class, () -> service.loadLedger((Ledger) null)); } private ChartOfAccount getCoa() { return new ChartOfAccount(); } private ChartOfAccountBO getCoaBO(String id, String name) { return new ChartOfAccountBO(name, id, LocalDateTime.now(), "details", "short descr", "long desc"); } private LedgerAccountBO getLedgerAccountBO(String id, String name, LedgerBO ledger) { LedgerAccountBO account = new LedgerAccountBO(); account.setId(id); account.setName(name); account.setLedger(ledger); return account; } private LedgerBO getLedger(String id, String name) { LedgerBO ledger = new LedgerBO(); ledger.setId(id); ledger.setName(name); return ledger; } }
33.873518
131
0.680397
ece0937840c60fa9297c9bcb68be83c4053a6b7e
1,020
package com.alexstyl.touchcontrol.ui.widget; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.widget.ImageView; import com.alexstyl.touchcontrol.R; /** * A view... that is a circle * <p>Created by alexstyl on 12/03/15.</p> */ public class CircleView extends ImageView{ public CircleView(Context context) { super(context); init(); } public CircleView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public CircleView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public CircleView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private void init() { setImageResource(R.mipmap.ic_target); } }
23.72093
95
0.683333
75bbf760ef308f9121aec276aad692a3b7bd4157
11,200
/* * @(#)ODGView.java * * Copyright (c) 1996-2010 by the original authors of JHotDraw and all its * contributors. All rights reserved. * * You may not use, copy or modify this file, except in compliance with the * license agreement you entered into with the copyright holders. For details * see accompanying license terms. * */ package org.jhotdraw.samples.odg; import org.jhotdraw.app.action.edit.RedoAction; import org.jhotdraw.app.action.edit.UndoAction; import org.jhotdraw.draw.io.TextInputFormat; import org.jhotdraw.draw.io.OutputFormat; import org.jhotdraw.draw.io.InputFormat; import org.jhotdraw.draw.io.ImageOutputFormat; import org.jhotdraw.draw.io.ImageInputFormat; import org.jhotdraw.draw.print.DrawingPageable; import java.awt.image.BufferedImage; import java.awt.print.Pageable; import java.util.HashMap; import java.util.LinkedList; import org.jhotdraw.gui.*; import org.jhotdraw.samples.odg.io.ODGInputFormat; import org.jhotdraw.samples.svg.figures.*; import org.jhotdraw.samples.svg.io.*; import org.jhotdraw.undo.*; import org.jhotdraw.util.*; import java.awt.*; import java.beans.*; import java.io.File; import java.io.IOException; import java.lang.reflect.*; import java.net.URI; import javax.swing.*; import javax.swing.border.*; import javax.swing.filechooser.FileFilter; import org.jhotdraw.app.*; import org.jhotdraw.draw.*; import org.jhotdraw.draw.action.*; import org.jhotdraw.gui.JFileURIChooser; import org.jhotdraw.gui.URIChooser; /** * A view for ODG drawings. * * @author Werner Randelshofer * @version $Id: ODGView.java 717 2010-11-21 12:30:57Z rawcoder $ */ public class ODGView extends AbstractView { public final static String GRID_VISIBLE_PROPERTY = "gridVisible"; protected JFileURIChooser exportChooser; /** * Each ODGView uses its own undo redo manager. * This allows for undoing and redoing actions per view. */ private UndoRedoManager undo; /** * Depending on the type of an application, there may be one editor per * view, or a single shared editor for all views. */ private DrawingEditor editor; private GridConstrainer visibleConstrainer = new GridConstrainer(10, 10); private GridConstrainer invisibleConstrainer = new GridConstrainer(1, 1); /** * Creates a new view. */ public ODGView() { initComponents(); scrollPane.setLayout(new PlacardScrollPaneLayout()); scrollPane.setBorder(new EmptyBorder(0, 0, 0, 0)); setEditor(new DefaultDrawingEditor()); undo = new UndoRedoManager(); view.setDrawing(createDrawing()); view.getDrawing().addUndoableEditListener(undo); initActions(); undo.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { setHasUnsavedChanges(undo.hasSignificantEdits()); } }); ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.draw.Labels"); JPanel placardPanel = new JPanel(new BorderLayout()); javax.swing.AbstractButton pButton; pButton = ButtonFactory.createZoomButton(view); pButton.putClientProperty("Quaqua.Button.style", "placard"); pButton.putClientProperty("Quaqua.Component.visualMargin", new Insets(0, 0, 0, 0)); pButton.setFont(UIManager.getFont("SmallSystemFont")); placardPanel.add(pButton, BorderLayout.WEST); pButton = ButtonFactory.createToggleGridButton(view); pButton.putClientProperty("Quaqua.Button.style", "placard"); pButton.putClientProperty("Quaqua.Component.visualMargin", new Insets(0, 0, 0, 0)); pButton.setFont(UIManager.getFont("SmallSystemFont")); labels.configureToolBarButton(pButton, "view.toggleGrid.placard"); placardPanel.add(pButton, BorderLayout.EAST); scrollPane.add(placardPanel, JScrollPane.LOWER_LEFT_CORNER); propertiesPanel.setVisible(preferences.getBoolean("propertiesPanelVisible", false)); propertiesPanel.setView(view); } /** * Creates a new Drawing for this view. */ protected Drawing createDrawing() { Drawing drawing = new ODGDrawing(); LinkedList<InputFormat> inputFormats = new LinkedList<InputFormat>(); inputFormats.add(new ODGInputFormat()); inputFormats.add(new ImageInputFormat(new SVGImageFigure())); inputFormats.add(new TextInputFormat(new SVGTextFigure())); drawing.setInputFormats(inputFormats); LinkedList<OutputFormat> outputFormats = new LinkedList<OutputFormat>(); outputFormats.add(new SVGOutputFormat()); outputFormats.add(new SVGZOutputFormat()); outputFormats.add(new ImageOutputFormat()); outputFormats.add(new ImageOutputFormat("JPG", "Joint Photographics Experts Group (JPEG)", "jpg", BufferedImage.TYPE_INT_RGB)); outputFormats.add(new ImageOutputFormat("BMP", "Windows Bitmap (BMP)", "bmp", BufferedImage.TYPE_BYTE_INDEXED)); outputFormats.add(new ImageMapOutputFormat()); drawing.setOutputFormats(outputFormats); return drawing; } /** * Creates a Pageable object for printing the view. */ public Pageable createPageable() { return new DrawingPageable(view.getDrawing()); } public DrawingEditor getEditor() { return editor; } public void setEditor(DrawingEditor newValue) { DrawingEditor oldValue = editor; if (oldValue != null) { oldValue.remove(view); } editor = newValue; propertiesPanel.setEditor(editor); if (newValue != null) { newValue.add(view); } } /** * Initializes view specific actions. */ private void initActions() { getActionMap().put(UndoAction.ID, undo.getUndoAction()); getActionMap().put(RedoAction.ID, undo.getRedoAction()); } @Override protected void setHasUnsavedChanges(boolean newValue) { super.setHasUnsavedChanges(newValue); undo.setHasSignificantEdits(newValue); } /** * Writes the view to the specified uri. */ @Override public void write(URI f, URIChooser fc) throws IOException { new SVGOutputFormat().write(new File(f), view.getDrawing()); } /** * Reads the view from the specified uri. */ @SuppressWarnings("unchecked") @Override public void read(URI f, URIChooser fc) throws IOException { try { final Drawing drawing = createDrawing(); HashMap<FileFilter, InputFormat> fileFilterInputFormatMap = (HashMap<FileFilter, InputFormat>) ((JFileURIChooser) fc).getClientProperty("ffInputFormatMap"); InputFormat sf = fileFilterInputFormatMap.get(((JFileURIChooser) fc).getFileFilter()); if (sf == null) { sf = drawing.getInputFormats().get(0); } sf.read(f, drawing, true); System.out.println("ODCView read(" + f + ") drawing.childCount=" + drawing.getChildCount()); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { view.getDrawing().removeUndoableEditListener(undo); view.setDrawing(drawing); view.getDrawing().addUndoableEditListener(undo); undo.discardAllEdits(); } }); } catch (InterruptedException e) { InternalError error = new InternalError(); e.initCause(e); throw error; } catch (InvocationTargetException e) { InternalError error = new InternalError(); error.initCause(e); throw error; } } public Drawing getDrawing() { return view.getDrawing(); } @Override public void setEnabled(boolean newValue) { view.setEnabled(newValue); super.setEnabled(newValue); } public void setPropertiesPanelVisible(boolean newValue) { boolean oldValue = propertiesPanel.isVisible(); propertiesPanel.setVisible(newValue); firePropertyChange("propertiesPanelVisible", oldValue, newValue); preferences.putBoolean("propertiesPanelVisible", newValue); validate(); } public boolean isPropertiesPanelVisible() { return propertiesPanel.isVisible(); } public boolean isGridVisible() { return view.isConstrainerVisible(); } public void setGridVisible(boolean newValue) { boolean oldValue = isGridVisible(); view.setConstrainerVisible(newValue); firePropertyChange(GRID_VISIBLE_PROPERTY, oldValue, newValue); } public double getScaleFactor() { return view.getScaleFactor(); } public void setScaleFactor(double newValue) { double oldValue = getScaleFactor(); view.setScaleFactor(newValue); firePropertyChange("scaleFactor", oldValue, newValue); } /** * Clears the view. */ @Override public void clear() { final Drawing newDrawing = createDrawing(); try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { view.getDrawing().removeUndoableEditListener(undo); view.setDrawing(newDrawing); view.getDrawing().addUndoableEditListener(undo); undo.discardAllEdits(); } }); } catch (InvocationTargetException ex) { ex.printStackTrace(); } catch (InterruptedException ex) { ex.printStackTrace(); } } @Override public boolean canSaveTo(URI uri) { return uri.getPath().endsWith(".odg"); } /** 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() { scrollPane = new javax.swing.JScrollPane(); view = new org.jhotdraw.draw.DefaultDrawingView(); propertiesPanel = new org.jhotdraw.samples.odg.ODGPropertiesPanel(); setLayout(new java.awt.BorderLayout()); scrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); scrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setViewportView(view); add(scrollPane, java.awt.BorderLayout.CENTER); add(propertiesPanel, java.awt.BorderLayout.SOUTH); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private org.jhotdraw.samples.odg.ODGPropertiesPanel propertiesPanel; private javax.swing.JScrollPane scrollPane; private org.jhotdraw.draw.DefaultDrawingView view; // End of variables declaration//GEN-END:variables }
35.33123
168
0.665089
0c74cfa8cd4fb968575b22fc518073acc43bdf05
4,844
package com.algolia.search.integration.dictionary; import static org.assertj.core.api.Assertions.assertThat; import com.algolia.search.SearchClientDictionary; import com.algolia.search.models.dictionary.Compound; import com.algolia.search.models.dictionary.Dictionary; import com.algolia.search.models.dictionary.DictionaryEntry; import com.algolia.search.models.dictionary.DictionarySettings; import com.algolia.search.models.dictionary.DisableStandardEntries; import com.algolia.search.models.dictionary.Plural; import com.algolia.search.models.dictionary.Stopword; import com.algolia.search.models.indexing.Query; import com.algolia.search.models.indexing.SearchResult; import java.util.Arrays; import java.util.Collections; import java.util.UUID; import org.junit.jupiter.api.Test; public abstract class DictionaryTest { private final SearchClientDictionary searchClient; protected DictionaryTest(SearchClientDictionary searchClient) { this.searchClient = searchClient; } @Test void testStopwordsDictionaries() { String objectID = UUID.randomUUID().toString(); Query query = new Query(objectID); Dictionary dictionary = Dictionary.STOPWORDS; // Search non-existent. SearchResult<Stopword> search = searchClient.searchDictionaryEntries(dictionary, query, null); assertThat(search.getNbHits()).isZero(); Stopword stopword = DictionaryEntry.stopword(objectID, "en", "upper", "enabled"); // Save entry searchClient.saveDictionaryEntries(dictionary, Collections.singletonList(stopword)).waitTask(); search = searchClient.searchDictionaryEntries(dictionary, query); assertThat(search.getNbHits()).isEqualTo(1); assertThat(search.getHits().get(0)).isEqualTo(stopword); // Replace entry stopword.setWord("uppercase"); searchClient .replaceDictionaryEntries(dictionary, Collections.singletonList(stopword)) .waitTask(); search = searchClient.searchDictionaryEntries(dictionary, query); assertThat(search.getNbHits()).isEqualTo(1); assertThat(search.getHits().get(0)).isEqualTo(stopword); assertThat(search.getHits().get(0).getWord()).isEqualTo(stopword.getWord()); // Delete entry searchClient .deleteDictionaryEntries(dictionary, Collections.singletonList(objectID)) .waitTask(); search = searchClient.searchDictionaryEntries(dictionary, query); assertThat(search.getNbHits()).isZero(); } @Test void testPluralsDictionaries() { String objectID = UUID.randomUUID().toString(); Query query = new Query(objectID); Dictionary dictionary = Dictionary.PLURALS; // Search non-existent. SearchResult<Plural> search = searchClient.searchDictionaryEntries(dictionary, query, null); assertThat(search.getNbHits()).isZero(); Plural plural = DictionaryEntry.plural(objectID, "en", Arrays.asList("cheval", "chevaux")); // Save searchClient.saveDictionaryEntries(dictionary, Collections.singletonList(plural)).waitTask(); search = searchClient.searchDictionaryEntries(dictionary, query); assertThat(search.getNbHits()).isEqualTo(1); assertThat(search.getHits().get(0)).isEqualTo(plural); // Delete searchClient .deleteDictionaryEntries(dictionary, Collections.singletonList(objectID)) .waitTask(); search = searchClient.searchDictionaryEntries(dictionary, query); assertThat(search.getNbHits()).isZero(); } @Test void testCompoundsDictionary() { String objectID = UUID.randomUUID().toString(); Query query = new Query(objectID); Dictionary dictionary = Dictionary.COMPOUNDS; SearchResult<Compound> search = searchClient.searchDictionaryEntries(dictionary, query, null); assertThat(search.getNbHits()).isZero(); Compound compound = DictionaryEntry.compound( objectID, "nl", "kopfschmerztablette", Arrays.asList("kopf", "schmerz", "tablette")); // Save searchClient.saveDictionaryEntries(dictionary, Collections.singletonList(compound)).waitTask(); search = searchClient.searchDictionaryEntries(dictionary, query); assertThat(search.getNbHits()).isEqualTo(1); assertThat(search.getHits().get(0)).isEqualTo(compound); // Delete searchClient .deleteDictionaryEntries(dictionary, Collections.singletonList(objectID)) .waitTask(); search = searchClient.searchDictionaryEntries(dictionary, query); assertThat(search.getNbHits()).isZero(); } @Test void testSettings() { DictionarySettings settings = new DictionarySettings() .setDisableStandardEntries( new DisableStandardEntries().setStopwords(Collections.singletonMap("en", true))); searchClient.setDictionarySettings(settings).waitTask(); assertThat(searchClient.getDictionarySettings()).isEqualTo(settings); } }
37.84375
99
0.745458
14017eb78f3e6cd06c7c146db3e29a5513c54b4c
897
package com.oseevol; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import com.oseevol.controller.ActorController; import com.oseevol.controller.GenreController; import com.oseevol.controller.MovieController; import com.oseevol.service.LibraryService; @SpringBootTest class ApplicationTests { @Autowired private LibraryService libraryService; @Autowired private MovieController movieController; @Autowired private GenreController genreController; @Autowired private ActorController actorController; @Test void contextLoads() { assertThat(libraryService).isNotNull(); assertThat(movieController).isNotNull(); assertThat(genreController).isNotNull(); assertThat(actorController).isNotNull(); } }
23.605263
62
0.818283
9dbacd100afcc731b17cf19d26355bf370e6dfd5
1,666
package io.kubernetes.client.openapi.models; import com.google.gson.annotations.SerializedName; import io.kubernetes.client.fluent.Fluent; import io.kubernetes.client.custom.Quantity; import java.lang.String; import java.lang.Boolean; import java.util.Map; import java.util.LinkedHashMap; public interface V1ResourceRequirementsFluent<A extends io.kubernetes.client.openapi.models.V1ResourceRequirementsFluent<A>> extends io.kubernetes.client.fluent.Fluent<A> { public A addToLimits(java.lang.String key,io.kubernetes.client.custom.Quantity value); public A addToLimits(java.util.Map<java.lang.String,io.kubernetes.client.custom.Quantity> map); public A removeFromLimits(java.lang.String key); public A removeFromLimits(java.util.Map<java.lang.String,io.kubernetes.client.custom.Quantity> map); public java.util.Map<java.lang.String,io.kubernetes.client.custom.Quantity> getLimits(); public <K,V>A withLimits(java.util.Map<java.lang.String,io.kubernetes.client.custom.Quantity> limits); public java.lang.Boolean hasLimits(); public A addToRequests(java.lang.String key,io.kubernetes.client.custom.Quantity value); public A addToRequests(java.util.Map<java.lang.String,io.kubernetes.client.custom.Quantity> map); public A removeFromRequests(java.lang.String key); public A removeFromRequests(java.util.Map<java.lang.String,io.kubernetes.client.custom.Quantity> map); public java.util.Map<java.lang.String,io.kubernetes.client.custom.Quantity> getRequests(); public <K,V>A withRequests(java.util.Map<java.lang.String,io.kubernetes.client.custom.Quantity> requests); public java.lang.Boolean hasRequests(); }
57.448276
172
0.792317
90472bb45803d9928634ae8ee413e3431217727d
2,810
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.server.deploymentoverlay; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT_OVERLAY; import static org.jboss.as.server.deploymentoverlay.DeploymentOverlayModel.DEPLOYMENT_OVERRIDE_DEPLOYMENT_PATH; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.descriptions.common.ControllerResolver; import org.jboss.as.controller.registry.ManagementResourceRegistration; /** * Links a deployment overlay to a deployment * * @author Stuart Douglas */ public class DeploymentOverlayDeploymentDefinition extends SimpleResourceDefinition { private static final AttributeDefinition[] ATTRIBUTES = {}; public static AttributeDefinition[] attributes() { return ATTRIBUTES.clone(); } public DeploymentOverlayDeploymentDefinition() { super(new Parameters(DEPLOYMENT_OVERRIDE_DEPLOYMENT_PATH, ControllerResolver.getResolver(DEPLOYMENT_OVERLAY + '.' + DEPLOYMENT)) .setAddHandler(new DeploymentOverlayDeploymentAdd())); } @Override public void registerAttributes(final ManagementResourceRegistration resourceRegistration) { for (AttributeDefinition attr : ATTRIBUTES) { resourceRegistration.registerReadOnlyAttribute(attr, null); } } @Override public void registerOperations(ManagementResourceRegistration resourceRegistration) { super.registerOperations(resourceRegistration); resourceRegistration.registerOperationHandler(DeploymentOverlayDeploymentRemoveHandler.REMOVE_DEFINITION, DeploymentOverlayDeploymentRemoveHandler.INSTANCE); } }
43.90625
165
0.780783
780a749b8eb68af2528b0e76e4a81dcf2540680d
16,801
/* * Copyright 2000-2020 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 jetbrains.buildServer.artifacts.s3; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.AmazonS3Exception; import com.amazonaws.services.s3.transfer.Transfer; import com.amazonaws.services.s3.transfer.TransferManagerConfiguration; import com.intellij.openapi.diagnostic.Logger; import java.io.File; import java.lang.reflect.Method; import java.net.URLConnection; import java.security.KeyStore; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.SSLContext; import jetbrains.buildServer.artifacts.ArtifactListData; import jetbrains.buildServer.serverSide.TeamCityProperties; import jetbrains.buildServer.util.ExceptionUtil; import jetbrains.buildServer.util.FileUtil; import jetbrains.buildServer.util.StringUtil; import jetbrains.buildServer.util.amazon.AWSClients; import jetbrains.buildServer.util.amazon.AWSCommonParams; import jetbrains.buildServer.util.amazon.S3Util.WithTransferManager; import jetbrains.buildServer.util.ssl.SSLContextUtil; import jetbrains.buildServer.util.ssl.TrustStoreIO; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import static jetbrains.buildServer.artifacts.s3.S3Constants.*; import static jetbrains.buildServer.util.amazon.AWSCommonParams.REGION_NAME_PARAM; import static jetbrains.buildServer.util.amazon.AWSCommonParams.SSL_CERT_DIRECTORY_PARAM; /** * Created by Nikita.Skvortsov date: 02.08.2016. */ public class S3Util { @NotNull private static final Pattern OUR_OBJECT_KEY_PATTERN = Pattern.compile("^[a-zA-Z0-9!/\\-_.*'()]+$"); private static final int OUT_MAX_PREFIX_LENGTH = 127; @NotNull private static final Logger LOGGER = Logger.getInstance(S3Util.class.getName()); @NotNull private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream"; @NotNull private static final Method PROBE_CONTENT_TYPE_METHOD = getProbeContentTypeMethod(); @NotNull private static final Method FILE_TO_PATH_METHOD = getFileToPathMethod(); @NotNull private static final String V4_SIGNER_TYPE = "AWSS3V4SignerType"; @NotNull private static final Long DEFAULT_DOWNLOAD_CHUNK_SIZE = Long.valueOf(5 * 1024 * 1024); @NotNull private static final Long DEFAULT_MULTIPART_THRESHOLD = Long.valueOf(16 * 1024 * 1024); @NotNull private static final Double DEFAULT_MINIMUM_CHUNK_TO_THRESHOLD_RATIO = 1.0 * DEFAULT_MULTIPART_THRESHOLD / DEFAULT_DOWNLOAD_CHUNK_SIZE; @NotNull public static Map<String, String> validateParameters(@NotNull final Map<String, String> params, final boolean acceptReferences) { final Map<String, String> commonErrors = AWSCommonParams.validate(params, acceptReferences); if (!commonErrors.isEmpty()) { return commonErrors; } final Map<String, String> invalids = new HashMap<>(); if (StringUtil.isEmptyOrSpaces(getBucketName(params))) { invalids.put(beanPropertyNameForBucketName(), "S3 bucket name must not be empty"); } final String pathPrefix = params.getOrDefault(S3_PATH_PREFIX_SETTING, ""); if (TeamCityProperties.getBooleanOrTrue("teamcity.internal.storage.s3.bucket.prefix.enable") && !StringUtil.isEmptyOrSpaces(pathPrefix)) { if (pathPrefix.length() > OUT_MAX_PREFIX_LENGTH) { invalids.put(S3_PATH_PREFIX_SETTING, "Should be less than " + OUT_MAX_PREFIX_LENGTH + " characters"); } if (!OUR_OBJECT_KEY_PATTERN.matcher(pathPrefix).matches()) { invalids.put(S3_PATH_PREFIX_SETTING, "Should match the regexp [" + OUR_OBJECT_KEY_PATTERN.pattern() + "]"); } } return invalids; } @NotNull public static Map<String, String> validateParameters(@NotNull final Map<String, String> params) throws IllegalArgumentException { final Map<String, String> invalids = validateParameters(params, false); if (!invalids.isEmpty()) { throw new InvalidSettingsException(invalids); } return params; } @NotNull public static String beanPropertyNameForBucketName() { return S3_BUCKET_NAME; } @Nullable public static String getBucketName(@NotNull final Map<String, String> params) { return params.get(beanPropertyNameForBucketName()); } @Nullable public static String getPathPrefix(@NotNull final ArtifactListData artifactsInfo) { return getPathPrefix(artifactsInfo.getCommonProperties()); } @Nullable public static String getPathPrefix(@NotNull final Map<String, String> properties) { return properties.get(S3Constants.S3_PATH_PREFIX_ATTR); } public static boolean usePreSignedUrls(@NotNull final Map<String, String> properties) { return Boolean.parseBoolean(properties.get(S3Constants.S3_USE_PRE_SIGNED_URL_FOR_UPLOAD)); } public static boolean disableParallelUploads(@NotNull Map<String, String> properties) { return Boolean.parseBoolean(properties.get(S3CONFIG_DISABLE_PARALLEL_DOWNLOADS)); } public static Long minimumUploadPartSize(@NotNull Map<String, String> properties) { if (properties.containsKey(S3CONFIG_MINIMUM_UPLOAD_PART_SIZE)) { try { return parseAny(properties.get(S3CONFIG_MINIMUM_UPLOAD_PART_SIZE)); } catch (Exception e) { LOGGER.warn(String.format("String {} does not parse as a 'long'. Using default instead.", properties.get(S3CONFIG_MINIMUM_UPLOAD_PART_SIZE))); } } return DEFAULT_DOWNLOAD_CHUNK_SIZE; } public static Long multipartUploadThreshold(@NotNull Map<String, String> properties) { Long result = null; if (properties.containsKey(S3CONFIG_MULTIPART_UPLOAD_THRESHOLD)) { try { result = parseAny(properties.get(S3CONFIG_MULTIPART_UPLOAD_THRESHOLD)); } catch (Exception e) { LOGGER.warn(String.format("String {} does not parse as a 'long'. Using default instead.", properties.get(S3CONFIG_MULTIPART_UPLOAD_THRESHOLD))); } } if (result != null) { if (result < Math.round(DEFAULT_MINIMUM_CHUNK_TO_THRESHOLD_RATIO * minimumUploadPartSize(properties))) { result = Math.round(DEFAULT_MINIMUM_CHUNK_TO_THRESHOLD_RATIO * minimumUploadPartSize(properties)); } } else { result = DEFAULT_MULTIPART_THRESHOLD; } return result; } public static int getNumberOfRetries(@NotNull final Map<String, String> configurationParameters) { try { final int nRetries = Integer.parseInt(configurationParameters.get(S3_NUMBER_OF_RETRIES_ON_ERROR)); return nRetries >= 0 ? nRetries : DEFAULT_S3_NUMBER_OF_RETRIES_ON_ERROR; } catch (NumberFormatException e) { return DEFAULT_S3_NUMBER_OF_RETRIES_ON_ERROR; } } public static int getRetryDelayInMs(@NotNull final Map<String, String> configurationParameters) { try { final int delay = Integer.parseInt(configurationParameters.get(S3_RETRY_DELAY_MS_ON_ERROR)); return delay >= 0 ? delay : DEFAULT_S3_RETRY_DELAY_ON_ERROR_MS; } catch (NumberFormatException e) { return DEFAULT_S3_RETRY_DELAY_ON_ERROR_MS; } } private static boolean useSignatureVersion4(@NotNull final Map<String, String> properties) { return Boolean.parseBoolean(properties.get(S3_USE_SIGNATURE_V4)); } private static boolean disablePathStyleAccess(@NotNull Map<String, String> properties) { final String fromSettings = properties.get(S3_FORCE_VIRTUAL_HOST_ADDRESSING); if (fromSettings != null) { return Boolean.parseBoolean(fromSettings); } else { return TeamCityProperties.getBoolean("teamcity.internal." + S3_FORCE_VIRTUAL_HOST_ADDRESSING); } } private static String units = "BKMGTPEZY"; /** @return index of pattern in s or -1, if not found */ private static int indexOf(Pattern pattern, String s) { Matcher matcher = pattern.matcher(s); return matcher.find() ? matcher.start() : -1; } private static long parseAny(String arg0) { int index = indexOf(Pattern.compile("[A-Za-z]"), arg0); double ret = Double.parseDouble(arg0.substring(0, index)); String unitString = arg0.substring(index); int unitChar = unitString.charAt(0); int power = units.indexOf(unitChar); boolean isSi = unitString.indexOf('i') != -1; int factor = 1024; if (isSi) { factor = 1000; } return new Double(ret * Math.pow(factor, power)).longValue(); } @Nullable private static KeyStore trustStore(@Nullable final String directory) { if (directory == null) { return null; } return TrustStoreIO.readTrustStoreFromDirectory(directory); } @Nullable private static ConnectionSocketFactory socketFactory(@NotNull final Map<String, String> params) { final String certDirectory = params.get(SSL_CERT_DIRECTORY_PARAM); if (certDirectory == null) { return null; } final KeyStore trustStore = trustStore(certDirectory); if (trustStore == null) { return null; } final SSLContext sslContext = SSLContextUtil.createUserSSLContext(trustStore); if (sslContext == null) { return null; } return new SSLConnectionSocketFactory(sslContext); } public static <T, E extends Throwable> T withS3ClientShuttingDownImmediately(@NotNull final Map<String, String> params, @NotNull final WithS3<T, E> withClient) throws E { return withS3Client(params, withClient, true); } public static <T, E extends Throwable> T withS3Client(@NotNull final Map<String, String> params, @NotNull final WithS3<T, E> withClient) throws E { return withS3Client(params, withClient, false); } private static <T, E extends Throwable> T withS3Client(@NotNull final Map<String, String> params, @NotNull final WithS3<T, E> withClient, boolean shutdownImmediately) throws E { return AWSCommonParams.withAWSClients(params, clients -> { if (useSignatureVersion4(params)) { clients.setS3SignerType(V4_SIGNER_TYPE); } clients.setDisablePathStyleAccess(disablePathStyleAccess(params)); patchAWSClientsSsl(clients, params); final AmazonS3 s3Client = clients.createS3Client(); try { return withClient.run(s3Client); } finally { if (shutdownImmediately) { s3Client.shutdown(); } } }); } @SuppressWarnings("UnusedReturnValue") public static <T extends Transfer> Collection<T> withTransferManagerCorrectingRegion( @NotNull final Map<String, String> s3Settings, @NotNull final WithTransferManager<T> withTransferManager) throws Throwable { return withTransferManagerCorrectingRegion(s3Settings, null, withTransferManager); } @SuppressWarnings("UnusedReturnValue") public static <T extends Transfer> Collection<T> withTransferManagerCorrectingRegion( @NotNull final Map<String, String> s3Settings, TransferManagerConfiguration config, @NotNull final WithTransferManager<T> withTransferManager) throws Throwable { try { return withTransferManager(s3Settings, config, withTransferManager); } catch (RuntimeException e) { final String correctRegion = extractCorrectedRegion(e); if (correctRegion != null) { LOGGER.debug("Running operation with corrected S3 region [" + correctRegion + "]", e); s3Settings.put(REGION_NAME_PARAM, correctRegion); return withTransferManager(s3Settings, config, withTransferManager); } else { throw e; } } } private static <T extends Transfer> Collection<T> withTransferManager(@NotNull final Map<String, String> s3Settings, @NotNull final TransferManagerConfiguration config, @NotNull final WithTransferManager<T> withTransferManager) throws Throwable { return AWSCommonParams.withAWSClients(s3Settings, clients -> { patchAWSClientsSsl(clients, s3Settings); return jetbrains.buildServer.util.amazon.S3Util.withTransferManager(clients.createS3Client(), true, withTransferManager); }); } private static void patchAWSClientsSsl(@NotNull final AWSClients clients, @NotNull final Map<String, String> params) { final ConnectionSocketFactory socketFactory = socketFactory(params); if (socketFactory != null) { clients.getClientConfiguration().getApacheHttpClientConfig().withSslSocketFactory(socketFactory); } } public static String getContentType(final File file) { String contentType = URLConnection.guessContentTypeFromName(file.getName()); if (StringUtil.isNotEmpty(contentType)) { return contentType; } if (PROBE_CONTENT_TYPE_METHOD != null && FILE_TO_PATH_METHOD != null) { try { final Object result = PROBE_CONTENT_TYPE_METHOD.invoke(null, FILE_TO_PATH_METHOD.invoke(file)); if (result instanceof String) { contentType = (String) result; } } catch (Exception ignored) { } } return StringUtil.notEmpty(contentType, DEFAULT_CONTENT_TYPE); } public static String normalizeArtifactPath(final String path, final File file) { if (StringUtil.isEmpty(path)) { return file.getName(); } else { return FileUtil.normalizeRelativePath(String.format("%s/%s", path, file.getName())); } } private static Method getProbeContentTypeMethod() { try { final Class<?> filesClass = Class.forName("java.nio.file.Files"); final Class<?> pathClass = Class.forName("java.nio.file.Path"); if (filesClass != null && pathClass != null) { return filesClass.getMethod("probeContentType", pathClass); } } catch (Exception ignored) { } return null; } private static Method getFileToPathMethod() { try { return File.class.getMethod("toPath"); } catch (Exception ignored) { } return null; } public static <T> T withClientCorrectingRegion(@NotNull final AmazonS3 s3Client, @NotNull final Map<String, String> settings, @NotNull final WithS3<T, AmazonS3Exception> withCorrectedClient) { try { return withCorrectedClient.run(s3Client); } catch (AmazonS3Exception awsException) { final String correctRegion = extractCorrectedRegion(awsException); if (correctRegion != null) { LOGGER.debug("Running operation with corrected S3 region [" + correctRegion + "]", awsException); final HashMap<String, String> correctedSettings = new HashMap<>(settings); correctedSettings.put(REGION_NAME_PARAM, correctRegion); return withS3ClientShuttingDownImmediately(correctedSettings, withCorrectedClient); } else { throw awsException; } } } @Nullable private static String extractCorrectedRegion(@NotNull final Throwable e) { @Nullable final AmazonS3Exception awsException = e instanceof AmazonS3Exception ? (AmazonS3Exception) e : ExceptionUtil.getCause(e, AmazonS3Exception.class); if (awsException != null && TeamCityProperties.getBooleanOrTrue("teamcity.internal.storage.s3.autoCorrectRegion") && awsException.getAdditionalDetails() != null) { final String correctRegion = awsException.getAdditionalDetails().get("Region"); if (correctRegion != null) { return correctRegion; } else { return awsException.getAdditionalDetails().get("x-amz-bucket-region"); } } else { return null; } } public interface WithS3<T, E extends Throwable> { @Nullable T run(@NotNull AmazonS3 client) throws E; } public static class InvalidSettingsException extends RuntimeException { private final Map<String, String> myInvalids; public InvalidSettingsException(@NotNull final Map<String, String> invalids) { myInvalids = new HashMap<>(invalids); } @Override public String getMessage() { return StringUtil.join("\n", myInvalids.values()); } @NotNull public Map<String, String> getInvalids() { return myInvalids; } } }
39.907363
172
0.720969
6f47bcb48ce8afdac7d966e042b6b8c104e22a66
1,864
package Layers; import Layers.Layer; import javafx.scene.image.Image; import static UI.UIValues.WINDOW_HEIGHT; import static UI.UIValues.WINDOW_WIDTH; /** * Created by Akihiro on 2017/02/27. */ public class ImageLayer extends Layer { private Image image; private String image_path; private double bairitsu; public ImageLayer(double width, double height){ super(width, height); bairitsu = 1.0; } public void SetImage(Image image){ this.image = image; } public Image getImage() { return image; } public double getBairitsu(){ return this.bairitsu; } public void DrawImageNormal(final Image image, double x, double y){ this.image = image; graphicsContext.clearRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); graphicsContext.drawImage(image, x, y); } public void DrawImageWithResize(final Image image, double x, double y, double width, double height, double bairitsu){ this.image = image; this.bairitsu = bairitsu; graphicsContext.clearRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); graphicsContext.drawImage(image, x, y, width * bairitsu, height * bairitsu); } public void MoveImage(double x, double y){ graphicsContext.clearRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); graphicsContext.drawImage(image, x, y, image.getWidth() * bairitsu, image.getHeight() * bairitsu); } public void Redraw(double x, double y){ graphicsContext.clearRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); graphicsContext.drawImage(image, x, y); } public void setImagePath(String path){ this.image_path = path; } public String getImagePath(){ return image_path; } public void clear(){ graphicsContext.clearRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); } }
27.411765
121
0.664163
95430c7954a77fd2b67669ffe6f31cb6b1e878de
3,402
package leetcode.problems; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** 288. Unique Word Abbreviation * The abbreviation of a word is a concatenation of its first letter, the number of characters between the first and last letter, and its last letter. If a word has only two characters, then it is an abbreviation of itself. * For example: * dog --> d1g because there is one letter between the first letter 'd' and the last letter 'g'. * internationalization --> i18n because there are 18 letters between the first letter 'i' and the last letter 'n'. * it --> it because any word with only two characters is an abbreviation of itself. * Implement the ValidWordAbbr class: * ValidWordAbbr(String[] dictionary) Initializes the object with a dictionary of words. * boolean isUnique(string word) Returns true if either of the following conditions are met (otherwise returns false): * There is no word in dictionary whose abbreviation is equal to word's abbreviation. * For any word in dictionary whose abbreviation is equal to word's abbreviation, that word and word are the same. * Example 1: * Input * ["ValidWordAbbr", "isUnique", "isUnique", "isUnique", "isUnique", "isUnique"] * [[["deer", "door", "cake", "card"]], ["dear"], ["cart"], ["cane"], ["make"], ["cake"]] * Output * [null, false, true, false, true, true] * * Explanation * ValidWordAbbr validWordAbbr = new ValidWordAbbr(["deer", "door", "cake", "card"]); * validWordAbbr.isUnique("dear"); // return false, dictionary word "deer" and word "dear" have the same abbreviation "d2r" but are not the same. * validWordAbbr.isUnique("cart"); // return true, no words in the dictionary have the abbreviation "c2t". * validWordAbbr.isUnique("cane"); // return false, dictionary word "cake" and word "cane" have the same abbreviation "c2e" but are not the same. * validWordAbbr.isUnique("make"); // return true, no words in the dictionary have the abbreviation "m2e". * validWordAbbr.isUnique("cake"); // return true, because "cake" is already in the dictionary and no other word in the dictionary has "c2e" abbreviation. * * Constraints: * 1 <= dictionary.length <= 3 * 10^4 * 1 <= dictionary[i].length <= 20 * dictionary[i] consists of lowercase English letters. * 1 <= word.length <= 20 * word consists of lowercase English letters. * At most 5000 calls will be made to isUnique. */ public class _288UniqueWordAbbreviation { } class ValidWordAbbr { private Map<String, Set<String>> dict = new HashMap<>(); public ValidWordAbbr(String[] dictionary) { for(String s : dictionary){ String key = buildKey(s); if(dict.containsKey(key)){ dict.get(key).add(s); }else{ Set<String> t = new HashSet<>(); t.add(s); dict.put(key, t); } } } private String buildKey(String s){ if(s.length() <= 2 ) return s; else return s.charAt(0) + Integer.toString(s.length()-2) + s.charAt(s.length()-1); } public boolean isUnique(String word) { String key = buildKey(word); if(!dict.containsKey(key)){ return true; }else{ return dict.get(key).contains(word) && dict.get(key).size() <=1; } } }
45.972973
223
0.654321
f71b3dd1a41a3b5269f7f15ea71beeec0c4907c0
1,657
package AmazonLocker.PackageManger; import AmazonLocker.LogisticsManager.LogisticsManager; import java.util.Queue; public class ProxyPackageTracker implements Observer{ private Package mPackage; private ITracker mTracker; private Queue<PackageFacility> mPackageFacilities; private Subject subject; public ProxyPackageTracker(Package pack, Queue<PackageFacility> packageFacilities, ITracker tracker){ mPackage = pack; mTracker = tracker; mPackageFacilities = packageFacilities; processQueue(); } /* We are using observer pattern here. We are doing this because we want independent processing from Package Facility. It gives us better control for processing. Processing Package at 101 Processing Package at 102 Processing Package at 103 Done History: 101 102 103 */ public void processQueue(){ Observer observer = this; if (!mPackageFacilities.isEmpty()){ PackageFacility packageFacility = mPackageFacilities.poll(); subject = packageFacility; mTracker.updateHistory(packageFacility.getPinCode()); packageFacility.register(observer); packageFacility.addPackageToFacility(mPackage); packageFacility.processPackage(); }else{ System.out.println("Done"); LogisticsManager.getInstance().hasReachedEndFacility(mPackage); } } @Override public void update() { processQueue(); } @Override public void setSubject(Subject subject) { this.subject = subject; } }
28.568966
166
0.668075
03704a8aa4bb127f123eafa711ffb37c49055b73
2,273
/* * Copyright 2014-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.spring.gradle.dependencymanagement.internal; /** * An exclusion of an artifact by group ID and artifact ID. * * @author Andy Wilkinson */ public class Exclusion { private final String groupId; private final String artifactId; /** * Creates a new {@code Exclusion} using the given {@code groupId} and {@code artifactId}. * * @param groupId group ID * @param artifactId artifact ID */ public Exclusion(String groupId, String artifactId) { this.groupId = (groupId != null) ? groupId : ""; this.artifactId = (artifactId != null) ? artifactId : ""; } /** * Returns the group ID that is excluded. * @return the group ID */ public String getGroupId() { return groupId; } /** * Returns the artifact ID that is excluded. * @return the artifact ID */ public String getArtifactId() { return artifactId; } @Override public int hashCode() { int result = 1; result = 31 * result + artifactId.hashCode(); result = 31 * result + groupId.hashCode(); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Exclusion other = (Exclusion) obj; if (!artifactId.equals(other.artifactId)) { return false; } if (!groupId.equals(other.groupId)) { return false; } return true; } }
26.126437
94
0.604927
39b124e65e0e2533aea9f228f2eb9c0987bb0f3f
13,361
package com.dev.theblueorb.gsheetjavaapisample; import android.*; import android.accounts.AccountManager; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.api.client.googleapis.extensions.android.gms.auth.GooglePlayServicesAvailabilityIOException; import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.ExponentialBackOff; import com.google.api.services.sheets.v4.Sheets; import com.google.api.services.sheets.v4.SheetsScopes; import com.google.api.services.sheets.v4.model.AppendValuesResponse; import com.google.api.services.sheets.v4.model.ValueRange; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import pub.devrel.easypermissions.AfterPermissionGranted; import pub.devrel.easypermissions.EasyPermissions; public class appendToSheetActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks{ GoogleAccountCredential mCredential; private static final String[] SCOPES = { SheetsScopes.SPREADSHEETS }; static final int REQUEST_ACCOUNT_PICKER = 1000; static final int REQUEST_AUTHORIZATION = 1001; static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002; static final int REQUEST_PERMISSION_GET_ACCOUNTS = 1003; private static final String BUTTON_TEXT = "Call Google Sheets API"; private static final String PREF_ACCOUNT_NAME = "accountName"; private ProgressBar mProgressBar; private TextView mTextView; private Button appendToSheetBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_append_to_sheet); mTextView = findViewById(R.id.status); mProgressBar = findViewById(R.id.progress_bar); mCredential = GoogleAccountCredential.usingOAuth2( getApplicationContext(), Arrays.asList(SCOPES)) .setBackOff(new ExponentialBackOff()); appendToSheetBtn = (Button) findViewById(R.id.append_to_sheet_btn); appendToSheetBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getResultsFromApi(); //checks if play services is available, device is online and if everything is ok performs the append to sheet operation } }); } public void getResultsFromApi() { if (! isGooglePlayServicesAvailable()) { acquireGooglePlayServices(); } else if (mCredential.getSelectedAccountName() == null) { chooseAccount(); } else if (! isDeviceOnline()) { Log.e(this.toString(),"No network connection available."); } else { new appendToSheetActivity.MakeRequestTask(mCredential,this).execute(); } } @AfterPermissionGranted(REQUEST_PERMISSION_GET_ACCOUNTS) private void chooseAccount() { if (EasyPermissions.hasPermissions( this, android.Manifest.permission.GET_ACCOUNTS)) { String accountName = getPreferences(Context.MODE_PRIVATE) .getString(PREF_ACCOUNT_NAME, null); if (accountName != null) { mCredential.setSelectedAccountName(accountName); getResultsFromApi(); } else { // Start a dialog from which the user can choose an account startActivityForResult( mCredential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER); } } else { // Request the GET_ACCOUNTS permission via a user dialog EasyPermissions.requestPermissions( this, "This app needs to access your Google account (via Contacts).", REQUEST_PERMISSION_GET_ACCOUNTS, android.Manifest.permission.GET_ACCOUNTS); } } @Override protected void onActivityResult( int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case REQUEST_GOOGLE_PLAY_SERVICES: if (resultCode != RESULT_OK) { Log.e(this.toString(),"This app requires Google Play Services. Please install " + "Google Play Services on your device and relaunch this app."); } else { getResultsFromApi(); } break; case REQUEST_ACCOUNT_PICKER: if (resultCode == RESULT_OK && data != null && data.getExtras() != null) { String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME); if (accountName != null) { SharedPreferences settings = getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putString(PREF_ACCOUNT_NAME, accountName); editor.apply(); mCredential.setSelectedAccountName(accountName); getResultsFromApi(); } } break; case REQUEST_AUTHORIZATION: if (resultCode == RESULT_OK) { getResultsFromApi(); } break; } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); EasyPermissions.onRequestPermissionsResult( requestCode, permissions, grantResults, this); } @Override public void onPermissionsGranted(int requestCode, List<String> list) { // Do nothing. } @Override public void onPermissionsDenied(int requestCode, List<String> list) { // Do nothing. } private boolean isDeviceOnline() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); return (networkInfo != null && networkInfo.isConnected()); } private boolean isGooglePlayServicesAvailable() { GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); final int connectionStatusCode = apiAvailability.isGooglePlayServicesAvailable(this); return connectionStatusCode == ConnectionResult.SUCCESS; } private void acquireGooglePlayServices() { GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); final int connectionStatusCode = apiAvailability.isGooglePlayServicesAvailable(this); if (apiAvailability.isUserResolvableError(connectionStatusCode)) { showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode); } } void showGooglePlayServicesAvailabilityErrorDialog( final int connectionStatusCode) { GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); Dialog dialog = apiAvailability.getErrorDialog( appendToSheetActivity.this, connectionStatusCode, REQUEST_GOOGLE_PLAY_SERVICES); dialog.show(); } private class MakeRequestTask extends AsyncTask<Void, Void, Void> { private com.google.api.services.sheets.v4.Sheets mService = null; private Exception mLastError = null; private Context mContext; MakeRequestTask(GoogleAccountCredential credential,Context context) { mContext = context; HttpTransport transport = AndroidHttp.newCompatibleTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); mService = new com.google.api.services.sheets.v4.Sheets.Builder( transport, jsonFactory, credential) .setApplicationName("GSheetJavaApiSample") .build(); } /** * Background task to call Google Sheets API. * @param params no parameters needed for this task. */ @Override protected Void doInBackground(Void... params) { try { writeToSheetUsingApi(); } catch (Exception e) { mLastError = e; if (mLastError instanceof GooglePlayServicesAvailabilityIOException) { showGooglePlayServicesAvailabilityErrorDialog( ((GooglePlayServicesAvailabilityIOException) mLastError) .getConnectionStatusCode()); } else if (mLastError instanceof UserRecoverableAuthIOException) { startActivityForResult( ((UserRecoverableAuthIOException) mLastError).getIntent(), appendToSheetActivity.REQUEST_AUTHORIZATION); } else { Log.e(this.toString(),"The following error occurred:\n"+ mLastError.getMessage()); } Log.e(this.toString(),e+""); } return null; } @Override protected void onPreExecute() { mTextView.setText("Calling Api"); appendToSheetBtn.setVisibility(View.INVISIBLE); mProgressBar.setVisibility(View.VISIBLE); } @Override protected void onPostExecute(Void aVoid) { mProgressBar.setVisibility(View.GONE); mTextView.setText("Task Completed."); } @Override protected void onCancelled() { mProgressBar.setVisibility(View.GONE); if (mLastError != null) { if (mLastError instanceof GooglePlayServicesAvailabilityIOException) { showGooglePlayServicesAvailabilityErrorDialog( ((GooglePlayServicesAvailabilityIOException) mLastError) .getConnectionStatusCode()); } else if (mLastError instanceof UserRecoverableAuthIOException) { startActivityForResult( ((UserRecoverableAuthIOException) mLastError).getIntent(), appendToSheetActivity.REQUEST_AUTHORIZATION); } else { mTextView.setText("The following error occurred:\n"+ mLastError.getMessage()); } } else { mTextView.setText("Request cancelled."); } } private void writeToSheetUsingApi() throws IOException, GeneralSecurityException { String spreadsheetId = "your_spreadsheet_id_here"; //TODO update the spreadSheet Id to your spreadSheet ID String range = "A1:X1"; //TODO update the value of the cell range String valueInputOption = "USER_ENTERED"; ValueRange requestBody = new ValueRange(); List<Object> data1 = new ArrayList<>(); // TODO change the value1, value2 etc to the value that you wish to append to the sheet data1.add("value1"); data1.add("value2"); data1.add("value3"); data1.add("value4"); data1.add("value5"); List<List<Object>> requestBodyData = new ArrayList<>(); requestBodyData.add(data1); requestBody.setValues(requestBodyData); Sheets.Spreadsheets.Values.Append request = mService.spreadsheets().values().append(spreadsheetId, range, requestBody); request.setValueInputOption(valueInputOption); AppendValuesResponse response = request.execute(); Log.e(this.toString(),response.toString()); } } }
38.727536
135
0.624429
c895e7989ff8b69847d5bff12af85faaccb44938
2,408
package com.demo; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; @Component public class ZullRedirectFilter extends ZuulFilter { @Value("${Authorities}") String Authorities; @Override public boolean shouldFilter() { return true; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); String token = request.getHeader("application-token"); // if request is to public service String[] urlParts = request.getServletPath().split("/"); System.out.println("**************************URLParts:" + request.getServletPath()); String serviceUrl = urlParts[1]; System.out.println("************************Service Url:" + serviceUrl); JSONParser parser = new JSONParser(); JSONObject json = null; try { json = (JSONObject) parser.parse(Authorities); System.out.println(Authorities); } catch (ParseException e3) { return HttpServletResponse.SC_FORBIDDEN; // e3.printStackTrace(); } String services = (String) json.get("User"); String[] servicess = services.split(","); System.out.println("*****************Services:" + services); for (String service : servicess) { if (serviceUrl.equals(service)) { // then let go return HttpServletResponse.SC_OK; } } if(request.getServletPath().equals("/hello-service/v2/api-docs")) return HttpServletResponse.SC_OK; // if private have token let it go if (token.equals("none") || token.equals("")) { //token is null and service-name!=login redirect to error page or login page return HttpServletResponse.SC_FORBIDDEN; } return null; } @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 1; } }
33.915493
93
0.622924
210cfb154c2b44c5eeb4f39a13145c0a8ab7ab54
2,086
package com.ad.thepool.scenes; import java.util.ArrayList; import com.ad.thepool.GObject; import com.ad.thepool.Game; import com.ad.thepool.Map; import com.ad.thepool.Scene; import com.ad.thepool.components.CameraComponent; import com.ad.thepool.components.RenderImageComponent; import com.ad.thepool.components.RenderTextComponent; import com.ad.thepool.objects.Player; import com.ad.thepool.objects.TextBox; import com.ad.thepool.wrapper.GraphicsWrapper; import com.ad.thepool.wrapper.KeyEventWrapper; public class SceneDarknight extends Scene { /** * */ private static final long serialVersionUID = 5344022726663482828L; TextBox help; public SceneDarknight(int order, Game game) { super(order, game); ; } @Override public void init() { super.init(); clearScene(); Map map = new Map("maps/darknight.lvl", null); addMap(map); addImageBox(0, 0, GObject.Z_BACKGROUND, 25, 15, "back_stars.png", RenderImageComponent.POS_PARALLAX_SLOW, false); help = addTextBox(1, 1, 20, 13, "In the darkest night,\nafter endless falling,\nmy dream was captured by a breeze\ncaptured from infinity.\n\nThe pain is long forgotten,\nJust remembrance,\nquite remembrance", GraphicsWrapper.COLOR_RED, true, RenderTextComponent.POS_LEFT_UP, false, null, null); // addImageBox(0, 0, GObject.Z_BACKGROUND, 25, 15, "back_stars.png", RenderImageComponent.POS_PARALLAX, false); ArrayList<GObject> players = searchGObjectByTag("player"); Player player = (Player) players.get(0); CameraComponent cam = player.getCameraComponent(); cam.setType(CameraComponent.TYPE_FIX); saveCheckPoint(true); // addImageBox(0, 0, GObject.Z_BACK, 25, 15, // "graphics/back_universe.bmp", RenderImageComponent.POS_SCALE, false, // false); } @Override public void keyDown(int key) { if (key == KeyEventWrapper.KEY_ENTER) { setNewScene(-1); } } @Override public void receiveMessage(GObject source, GObject dest, String tag, String sendkey) { super.receiveMessage(source, dest, tag, sendkey); if (sendkey.equals("mouse.click.enter")) { setNewScene(-1); } } }
30.676471
297
0.748802