hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
923941cad803a240bcebe205924ca45c1f8dd787 | 922 | java | Java | src/test/java/com/backbase/ct/bbfuel/service/factory/ProductGroupSeedFactory.java | MarcelHeemskerk/bb-fuel | 6a18fddb8cf23fdcb89fc8d62db8da649299762c | [
"Unlicense"
] | null | null | null | src/test/java/com/backbase/ct/bbfuel/service/factory/ProductGroupSeedFactory.java | MarcelHeemskerk/bb-fuel | 6a18fddb8cf23fdcb89fc8d62db8da649299762c | [
"Unlicense"
] | 1 | 2020-08-25T11:45:35.000Z | 2020-08-25T11:49:30.000Z | src/test/java/com/backbase/ct/bbfuel/service/factory/ProductGroupSeedFactory.java | reCeLR/bb-fuel | 5a6b635a2f22b63d6815c77856b352be75def587 | [
"Unlicense"
] | null | null | null | 32.928571 | 98 | 0.747289 | 998,761 | package com.backbase.ct.bbfuel.service.factory;
import com.backbase.ct.bbfuel.dto.entitlement.ProductGroupSeed;
import java.util.ArrayList;
import java.util.List;
/**
* Factory of {@link ProductGroupSeed}.
*/
public class ProductGroupSeedFactory {
public static final String PRODUCT_GROUP_NAME_INTTRADE = "International Trade";
public static final String PRODUCT_GROUP_NAME_PAYROLL = "Payroll";
public static List<ProductGroupSeed> createProductGroupSeeds(List<String> productGroupNames) {
List<ProductGroupSeed> productGroupSeeds = new ArrayList<>();
productGroupNames.forEach(name -> productGroupSeeds.add(createProductGroupSeed(name)));
return productGroupSeeds;
}
public static ProductGroupSeed createProductGroupSeed(String productGroupName) {
return ProductGroupSeed.builder()
.productGroupName(productGroupName)
.build();
}
}
|
923941e8ad5698505a43473945c659b932aec731 | 1,195 | java | Java | web/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/admin/DiagnosticsCommand.java | NCIP/psc | 3f4b0be4cec4062f592ee16f059a079167e4e359 | [
"BSD-3-Clause"
] | 2 | 2015-01-22T06:14:35.000Z | 2021-09-24T20:27:40.000Z | web/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/admin/DiagnosticsCommand.java | NCIP/psc | 3f4b0be4cec4062f592ee16f059a079167e4e359 | [
"BSD-3-Clause"
] | null | null | null | web/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/admin/DiagnosticsCommand.java | NCIP/psc | 3f4b0be4cec4062f592ee16f059a079167e4e359 | [
"BSD-3-Clause"
] | null | null | null | 26.555556 | 81 | 0.746444 | 998,762 | /*L
* Copyright Northwestern University.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.io/psc/LICENSE.txt for details.
*/
package edu.northwestern.bioinformatics.studycalendar.web.admin;
import edu.northwestern.bioinformatics.studycalendar.configuration.Configuration;
//import gov.nih.nci.ccts.grid.smoketest.client.SmokeTestServiceClient;
/**
* @author Saurabh Agrawal
*/
public class DiagnosticsCommand extends ConfigurationCommand {
private String smtpException;
private String smokeTestServiceException;
public DiagnosticsCommand(Configuration configuration) {
super(configuration);
}
public BindableConfiguration getConfiguration() {
return getConf();
}
public void setSmtpException(String smtpException) {
this.smtpException = smtpException;
}
public String getSmtpException() {
return smtpException;
}
public String getSmokeTestServiceException() {
return smokeTestServiceException;
}
public void setSmokeTestServiceException(String smokeTestServiceException) {
this.smokeTestServiceException = smokeTestServiceException;
}
}
|
9239423349c5958d0e684068be97699871b1f3c3 | 3,367 | java | Java | doyto-query-integration-test/src/test/java/win/doyto/query/web/demo/module/auth/LoginControllerTest.java | f0rb/doyto-query | 3337571773b4144e8715a04fd3ff4bfa444ecd39 | [
"Apache-2.0"
] | 15 | 2019-05-13T09:33:37.000Z | 2021-06-19T08:26:30.000Z | doyto-query-integration-test/src/test/java/win/doyto/query/web/demo/module/auth/LoginControllerTest.java | f0rb/doyto-query | 3337571773b4144e8715a04fd3ff4bfa444ecd39 | [
"Apache-2.0"
] | 1 | 2020-09-08T09:07:19.000Z | 2020-09-08T09:25:06.000Z | doyto-query-integration-test/src/test/java/win/doyto/query/web/demo/module/auth/LoginControllerTest.java | doytowin/doyto-query | 8b6d59fc2d984b5f489bc7d8047d0ba3b1a5ddb4 | [
"Apache-2.0"
] | 7 | 2019-05-28T06:38:02.000Z | 2020-09-08T09:10:33.000Z | 30.288288 | 76 | 0.657049 | 998,763 | /*
* Copyright © 2019-2022 Forb Yuan
*
* 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 win.doyto.query.web.demo.module.auth;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import win.doyto.query.web.demo.module.user.UserData;
import win.doyto.query.web.demo.module.user.UserResponse;
import javax.servlet.http.HttpServletRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
/**
* LoginControllerTest
*
* @author f0rb
*/
@Slf4j
class LoginControllerTest {
LoginController loginController;
HttpServletRequest httpRequest;
@BeforeEach
void setUp() {
loginController = new LoginController(UserData.getUserController());
httpRequest = new MockHttpServletRequest();
}
@Test
void login() {
LoginRequest loginRequest = new LoginRequest();
loginRequest.setAccount("f0rb");
loginRequest.setPassword("123456");
try {
loginController.login(loginRequest, httpRequest);
} catch (Exception e) {
fail("Login failed", e);
}
UserResponse userResponse = loginController.account(httpRequest);
assertEquals("自在", userResponse.getNickname());
}
@Test
void notLogin() {
try {
loginController.account(httpRequest);
} catch (Exception e) {
assertEquals("会话过期", e.getMessage());
}
}
@Test
void loginWithWrongAccount() {
LoginRequest loginRequest = new LoginRequest();
loginRequest.setAccount("none");
loginRequest.setPassword("123456");
try {
loginController.login(loginRequest, httpRequest);
fail("Login with wrong account should fail");
} catch (Exception e) {
assertEquals("账号不存在", e.getMessage());
}
}
@Test
void loginWithWrongPassword() {
LoginRequest loginRequest = new LoginRequest();
loginRequest.setAccount("anpch@example.com");
loginRequest.setPassword("12345678");
try {
loginController.login(loginRequest, httpRequest);
fail("Login with wrong password should fail");
} catch (Exception e) {
assertEquals("密码错误", e.getMessage());
}
}
@Test
void loginWithWrongInvalid() {
LoginRequest loginRequest = new LoginRequest();
loginRequest.setAccount("17778888881");
loginRequest.setPassword("123456");
try {
loginController.login(loginRequest, httpRequest);
fail("Login with wrong password should fail");
} catch (Exception e) {
assertEquals("账号被禁用", e.getMessage());
}
}
} |
923942bab68b96c3b0a9ea0121bacc924021ebb0 | 339 | java | Java | software/src/java/gov/nih/nci/cadsr/common/Constants.java | NCIP/cadsr-sentinel | 236e5a6c2b30cf016455adcef8fce024d135b327 | [
"BSD-3-Clause"
] | null | null | null | software/src/java/gov/nih/nci/cadsr/common/Constants.java | NCIP/cadsr-sentinel | 236e5a6c2b30cf016455adcef8fce024d135b327 | [
"BSD-3-Clause"
] | null | null | null | software/src/java/gov/nih/nci/cadsr/common/Constants.java | NCIP/cadsr-sentinel | 236e5a6c2b30cf016455adcef8fce024d135b327 | [
"BSD-3-Clause"
] | 1 | 2018-07-20T14:18:23.000Z | 2018-07-20T14:18:23.000Z | 24.214286 | 69 | 0.737463 | 998,764 | /*L
* Copyright ScenPro Inc, SAIC-F
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cadsr-sentinal/LICENSE.txt for details.
*/
package gov.nih.nci.cadsr.common;
public class Constants {
public static final String DEFAULT_CONTEXT = "NCIP";
public static final String BUILD_TAG = "b003";
}
|
9239436270d19405ebcacb1572f901e5de700b0f | 5,886 | java | Java | CrawlerSystem/src/com/syntun/etl/tools/ConnectSqlUtil.java | RLP0815/Syntun | 3d608755f9d370b211c4722d2e932caf47ccbd0c | [
"Apache-2.0"
] | null | null | null | CrawlerSystem/src/com/syntun/etl/tools/ConnectSqlUtil.java | RLP0815/Syntun | 3d608755f9d370b211c4722d2e932caf47ccbd0c | [
"Apache-2.0"
] | null | null | null | CrawlerSystem/src/com/syntun/etl/tools/ConnectSqlUtil.java | RLP0815/Syntun | 3d608755f9d370b211c4722d2e932caf47ccbd0c | [
"Apache-2.0"
] | null | null | null | 27.764151 | 109 | 0.614509 | 998,765 | package com.syntun.etl.tools;
import java.sql.*;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConnectSqlUtil {
private final static Logger LOGGER = LoggerFactory.getLogger(ConnectSqlUtil.class);
private static final int CONN_TIME_OUT = 288000;
public static String sqlName = "wgdata";
public static String sqlPassWord = "syntun-000";
public static String sqlDbName = "crawler";
public static String sqlHost = "192.168.0.144:3306";// 原来124
private static String sqlConStr = null;
private static LinkedList<Connection> liConn = new LinkedList<Connection>();
private static LinkedList<String> sqlCache = new LinkedList<String>();
private static LinkedList<Statement> bacthStmt = new LinkedList<Statement>();
private static int connCreterNum = 0;
private static int maxConnNum = 10;
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
private synchronized static void connCreaterNumChange(int num) {
System.err.println("+++++++++connCreterNum=" + connCreterNum + " liConnLength = " + liConn.size());
connCreterNum += num;
if (connCreterNum < 0)
connCreterNum = 0;
}
/**
* 获取数据库连接
*
* @return
*/
public static Connection getConnection(String URL,String userName,String passWord) {
Connection conn = null;
try {
conn = DriverManager.getConnection(URL, userName, passWord);
} catch (SQLException e) {
LOGGER.error("get connection failure", e);
}
return conn;
}
/**
* 关闭数据库连接
* @param conn
*/
public static void closeConnection(Connection conn) {
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
LOGGER.error("close connection failure", e);
}
}
}
/**
* 获取数据库链接
*
* @return
*
*/
public static Connection getConn(String dataIP,String databaseName) {
synchronized (liConn) {
//if (sqlConStr == null) {
// if(dataIP.equals("192.168.0.132")){
// sqlName = "xitong";
// sqlPassWord = "xitong001";
// }
sqlConStr = "jdbc:mysql://" + dataIP + ":3306/" + databaseName + "?user=" + sqlName + "&password="
+ sqlPassWord
+ "&seUnicode=true&characterEncoding=UTF8&autoReconnect=true&failOverReadOnly=false&maxReconnects=100";
//}
Connection conn = null;
try {
if (liConn.isEmpty() || liConn.size() == 0) {
if (connCreterNum < maxConnNum) {
liConn.add(DriverManager.getConnection(sqlConStr));
connCreaterNumChange(1);
} else {
while (liConn.size() == 0 || connCreterNum < maxConnNum) {
System.out.println("达到最大连接数,休眠等待");
Thread.sleep(300);
}
}
}
conn = (Connection) liConn.pollFirst();
// 判断链接是否有效
if (conn.isClosed() || !conn.isValid(CONN_TIME_OUT)) {
connCreterNum--;
return getConn(dataIP, databaseName);
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("connection db error!!!");
System.exit(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
return conn;
}
}
public static void push(Connection conn) {
synchronized (liConn) {
if (connCreterNum < maxConnNum) {
try {
if (!conn.isClosed()) {
if (!conn.getAutoCommit()) {
conn.commit();
conn.setAutoCommit(true);
}
conn.clearWarnings();
} else
conn = DriverManager.getConnection(sqlConStr);
liConn.add(conn);
} catch (SQLException e1) {
e1.printStackTrace();
}
} else {
try {
conn.close();
connCreaterNumChange(-1);
} catch (Exception e) {
conn = null;
}
}
}
}
public static synchronized void addStmt(Statement stmt) {
int s = ConnectSqlUtil.bacthStmt.indexOf(stmt);
if (s == -1)
ConnectSqlUtil.bacthStmt.add(stmt);
}
public static synchronized void removeStmt(Statement stmt) {
int s = ConnectSqlUtil.bacthStmt.indexOf(stmt);
if (s != -1)
ConnectSqlUtil.bacthStmt.remove(s);
}
public static synchronized int exeAllBacth() throws SQLException {
int sNum = 0;
while (ConnectSqlUtil.bacthStmt.size() > 0) {
sNum += ConnectSqlUtil.bacthStmt.remove(0).executeBatch().length;
}
return sNum;
}
public static synchronized void cacheInserSql(String sql, Statement stmt) {
if (ConnectSqlUtil.sqlCache.size() >= 50) {
try {
for (int i = 0; i < ConnectSqlUtil.sqlCache.size(); i++)
stmt.addBatch(ConnectSqlUtil.sqlCache.get(i));
stmt.executeBatch();
stmt.clearBatch();
stmt.clearWarnings();
} catch (Exception e) {
System.out.println("执行缓存sql错误");
System.exit(0);
}
ConnectSqlUtil.sqlCache.clear();
ConnectSqlUtil.sqlCache = new LinkedList<String>();
}
ConnectSqlUtil.sqlCache.add(sql);
}
/**
* 获取数据库下的所有库名
*/
public static List<String> getDatabaseNames(String dataIP, String userName, String passWord) {
List<String> databaseNames = new ArrayList<>();
Connection conn = getConn(dataIP,"crawler");
//Connection conn = getConnection(URL, userName, passWord);
ResultSet rs = null;
try {
//获取数据库的元数据
DatabaseMetaData db = conn.getMetaData();
rs = db.getCatalogs();
while(rs.next()){
String string = rs.getString(1);
databaseNames.add(string);
}
} catch (SQLException e) {
LOGGER.error("getTableNames failure", e);
} finally {
try {
rs.close();
push(conn);
closeConnection(conn);
} catch (SQLException e) {
LOGGER.error("close ResultSet failure", e);
}
}
return databaseNames;
}
}
|
923943aeca92e6704cc9e710ba58b80b373d4839 | 15,345 | java | Java | autobot/src/intTest/java/com/jdpgrailsdev/oasis/timeline/EndToEndIntegrationTests.java | jdpgrailsdev/oasis-timeline | 420d558e9010b26b9529a7be1118f82bb96f602c | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | autobot/src/intTest/java/com/jdpgrailsdev/oasis/timeline/EndToEndIntegrationTests.java | jdpgrailsdev/oasis-timeline | 420d558e9010b26b9529a7be1118f82bb96f602c | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2019-01-18T16:34:54.000Z | 2021-11-25T17:51:55.000Z | autobot/src/intTest/java/com/jdpgrailsdev/oasis/timeline/EndToEndIntegrationTests.java | jdpgrailsdev/oasis-timeline | 420d558e9010b26b9529a7be1118f82bb96f602c | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 44.221902 | 100 | 0.713848 | 998,766 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.jdpgrailsdev.oasis.timeline;
import static com.github.tomakehurst.wiremock.client.WireMock.getAllServeEvents;
import static com.github.tomakehurst.wiremock.client.WireMock.okJson;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.stubbing.ServeEvent;
import com.github.tomakehurst.wiremock.verification.LoggedRequest;
import com.jdpgrailsdev.oasis.timeline.config.IntegrationTestConfiguration;
import com.jdpgrailsdev.oasis.timeline.data.TimelineDataType;
import com.jdpgrailsdev.oasis.timeline.data.Tweet;
import com.jdpgrailsdev.oasis.timeline.mocks.MockDateUtils;
import com.jdpgrailsdev.oasis.timeline.schedule.TwitterTimelineEventScheduler;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.TextStyle;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import twitter4j.GeoLocation;
@ActiveProfiles("test")
@SpringBootTest(classes = {IntegrationTestConfiguration.class})
@ContextConfiguration(initializers = {WireMockInitializer.class})
class EndToEndIntegrationTests {
private static final String SIZE_ASSERTION_MESSAGE = "expected number of tweets produced";
private static final String TWEET_BODY_MESSAGE = "expected tweet message body";
private static final String TWEET_LOCATION_MESSAGE = "expected tweet location";
private static final String TWITTER_RESPONSE_FILE = "/twitter_response.json";
private static final String TWITTER_URI = "/statuses/update.json";
@Autowired private TwitterTimelineEventScheduler scheduler;
@Autowired private MockDateUtils dateUtils;
@Autowired private WireMockServer wireMockServer;
@BeforeAll
static void setup() {
WireMock.configureFor("localhost", 9091);
}
@AfterEach
void cleanup() {
dateUtils.reset();
wireMockServer.resetAll();
}
@Test
@DisplayName(
"test that when the scheduler is invoked for a date with timeline events, the events are"
+ " published to Twitter")
void testSchedulingTweets() throws IOException, URISyntaxException {
final String twitterResponse =
new String(
Files.readAllBytes(new ClassPathResource(TWITTER_RESPONSE_FILE).getFile().toPath()));
stubFor(post(urlEqualTo(TWITTER_URI)).willReturn(okJson(twitterResponse)));
dateUtils.setToday("October 2");
scheduler.publishTimelineTweet();
verify(3, postRequestedFor(urlEqualTo(TWITTER_URI)));
final List<ServeEvent> serveEventList = getAllServeEvents();
assertEquals(3, serveEventList.size(), SIZE_ASSERTION_MESSAGE);
final String tweet1 =
TimelineDataType.RELEASES.getEmoji()
+ " #OnThisDay in 1995, @Oasis release '(What's the Story) Morning Glory?', their "
+ "second studio album, on Creation Records. The album would propel the band to a "
+ "worldwide fame, selling over 12 million copies around the world."
+ "\n\n@creationrecords #Oasis #OTD #TodayInMusic #britpop";
validateTweet(tweet1, serveEventList.get(2).getRequest());
final String tweet2 =
TimelineDataType.NOTEWORTHY.getEmoji()
+ " #OnThisDay in 2016, '@Oasis: Supersonic' premieres at the Manchester Odeon "
+ "Printworks in Manchester, UK. The event is attended by Liam Gallagher, Paul "
+ "\"Bonehead\" Arthurs and director Mat Whitecross. Liam, Bonehead and Mat take "
+ "part in a Q&A with the audience after...";
validateTweet(tweet2, serveEventList.get(1).getRequest());
final String tweet3 =
"... the screening of the film."
+ "\n\n@boneheadspage @liamGallagher @matwhitecross #Oasis #OTD #TodayInMusic #britpop";
validateTweet(tweet3, serveEventList.get(0).getRequest());
}
@Test
@DisplayName(
"test that when the scheduler is invoked for a date with timeline events and the generated"
+ " tweet exceeds the size limit, the event is split and published to Twitter")
void testSchedulingTweetsExceedingTheLimit() throws IOException, URISyntaxException {
final String twitterResponse =
new String(
Files.readAllBytes(new ClassPathResource(TWITTER_RESPONSE_FILE).getFile().toPath()));
stubFor(post(urlEqualTo(TWITTER_URI)).willReturn(okJson(twitterResponse)));
dateUtils.setToday("April 24");
scheduler.publishTimelineTweet();
verify(3, postRequestedFor(urlEqualTo(TWITTER_URI)));
final List<ServeEvent> serveEventList = getAllServeEvents();
assertEquals(3, serveEventList.size(), SIZE_ASSERTION_MESSAGE);
final String tweet1 =
TimelineDataType.RELEASES.getEmoji()
+ " #OnThisDay in 1995, @Oasis release 'Some Might Say', the first single from "
+ "the forthcoming album '(What's The Story) Morning Glory?', on Creation "
+ "Records. It would go on to become @Oasis' first number one single and is "
+ "the last recording to...";
validateTweet(tweet1, serveEventList.get(2).getRequest());
final String tweet2 =
"... feature the original lineup. The single "
+ "includes the b-sides 'Talk Tonight', 'Acquiesce' and 'Headshrinker'."
+ "\n\n@creationrecords #Oasis #OTD #TodayInMusic #britpop";
validateTweet(tweet2, serveEventList.get(1).getRequest());
final String tweet3 =
TimelineDataType.VIDEOS.getEmoji()
+ " #OnThisDay in 1995, @Oasis release the music video for 'Some Might Say'. "
+ "The video is directed by Stuart Fryer."
+ "\n\n#Oasis #OTD #TodayInMusic #britpop";
validateTweet(tweet3, serveEventList.get(0).getRequest());
}
@Test
@DisplayName(
"test that when the scheduler is invoked for a date with timeline events that should include"
+ " mentions, the events are published to Twitter with the mentions included")
void testSchedulingTweetsWithMentions() throws IOException, URISyntaxException {
final String twitterResponse =
new String(
Files.readAllBytes(new ClassPathResource(TWITTER_RESPONSE_FILE).getFile().toPath()));
stubFor(post(urlEqualTo(TWITTER_URI)).willReturn(okJson(twitterResponse)));
dateUtils.setToday("August 18");
scheduler.publishTimelineTweet();
verify(8, postRequestedFor(urlEqualTo(TWITTER_URI)));
final List<ServeEvent> serveEventList = getAllServeEvents();
assertEquals(8, serveEventList.size(), SIZE_ASSERTION_MESSAGE);
final String tweet1 =
TimelineDataType.GIGS.getEmoji()
+ " #OnThisDay in 1991, @Oasis perform their first gig under the name \"@Oasis\" "
+ "at The Boardwalk in Manchester, UK. At this point, the band is a 4-piece made "
+ "up of Liam Gallagher, Paul \"Bonehead\" Arthurs, Paul \"Guigsy\" McGuigan and "
+ "Tony McCarroll.";
validateTweet(tweet1, serveEventList.get(7).getRequest());
final String tweet2 =
"The Inspiral Carpets are in attendance, "
+ "accompanied by roadie Noel Gallagher, who sees his brother's band perform live "
+ "for the first time.\n\n@boneheadspage @liamGallagher @noelgallagher "
+ "@TonyMcCarrolls #Oasis #OTD #TodayInMusic #britpop";
validateTweet(tweet2, serveEventList.get(6).getRequest());
final String tweet3 =
TimelineDataType.NOTEWORTHY.getEmoji()
+ " #OnThisDay in 1994, Noel Gallagher, Liam Gallagher and Paul \"Bonehead\" "
+ "Arthurs appear on MTV's Most Wanted to promote the release of their upcoming "
+ "debut album 'Definitely Maybe' and a live show later that evening at the "
+ "Kentish Town Forum in...";
validateTweet(tweet3, serveEventList.get(5).getRequest());
final String tweet4 =
"... London, UK. After a short "
+ "interview with host Davina McCall, the trio perform 'Whatever' and 'Live "
+ "Forever'. The performance is notable as Bonehead accompanies Noel and Liam on "
+ "the piano instead of his customary rhythm guitar.\n\n@boneheadspage...";
validateTweet(tweet4, serveEventList.get(4).getRequest());
final String tweet5 =
"... @liamGallagher @noelgallagher " + "@ThisisDavina #Oasis #OTD #TodayInMusic #britpop";
validateTweet(tweet5, serveEventList.get(3).getRequest());
final String tweet6 =
TimelineDataType.NOTEWORTHY.getEmoji()
+ " #OnThisDay in 1996, Noel Gallagher joins Paul Weller and Jools Holland on "
+ "stage at the first V Festival in Hylands Park, Chelmsford, UK to play 'Eye of "
+ "the Storm'. During the song, Noel asks the crowd to \"show your appreciation\" "
+ "and informs...";
validateTweet(tweet6, serveEventList.get(2).getRequest());
final String tweet7 =
"... the crowd that \"Alan White's "
+ "brother\" (Steve White) is on drums. Paul Weller returns the favor "
+ "by thanking \"Mr. Liam Gallagher\" after the jam. It would be another "
+ "nine years before @Oasis would finally appear at the festival in...";
validateTweet(tweet7, serveEventList.get(1).getRequest());
final String tweet8 =
"... 2005.\n\n@drummerwhitey "
+ "@liamGallagher @noelgallagher #Oasis #OTD #TodayInMusic #britpop";
validateTweet(tweet8, serveEventList.get(0).getRequest());
}
@Test
@DisplayName(
"test that when the scheduled task is invoked for each date on the calendar, the task is"
+ " executed")
void testSchedulingSpecificDate() throws IOException {
final String twitterResponse =
new String(
Files.readAllBytes(new ClassPathResource(TWITTER_RESPONSE_FILE).getFile().toPath()));
stubFor(post(urlEqualTo(TWITTER_URI)).willReturn(okJson(twitterResponse)));
final LocalDate end = LocalDate.of(2021, 1, 1);
for (LocalDate date = LocalDate.of(2020, 1, 1); date.isBefore(end); date = date.plusDays(1)) {
final ZonedDateTime localDate = date.atStartOfDay(ZoneId.systemDefault());
final String today =
localDate.getMonth().getDisplayName(TextStyle.FULL, Locale.ENGLISH)
+ " "
+ localDate.getDayOfMonth();
dateUtils.setToday(today);
scheduler.publishTimelineTweet();
}
verify(postRequestedFor(urlEqualTo(TWITTER_URI)));
final List<ServeEvent> serveEventList = getAllServeEvents();
serveEventList.forEach(
event -> {
try {
assertTrue(
decodeTweet(event.getRequest()).length() <= Tweet.TWEET_LIMIT,
SIZE_ASSERTION_MESSAGE);
} catch (URISyntaxException e) {
fail(e);
}
});
}
@Test
@DisplayName("test that Twitter handle replacement works for names that end with an apostrophe")
void testTwitterHandleReplacement() throws IOException, URISyntaxException {
final String twitterResponse =
new String(
Files.readAllBytes(new ClassPathResource(TWITTER_RESPONSE_FILE).getFile().toPath()));
stubFor(post(urlEqualTo(TWITTER_URI)).willReturn(okJson(twitterResponse)));
dateUtils.setToday("May 7");
scheduler.publishTimelineTweet();
verify(1, postRequestedFor(urlEqualTo(TWITTER_URI)));
final List<ServeEvent> serveEventList = getAllServeEvents();
assertEquals(1, serveEventList.size(), SIZE_ASSERTION_MESSAGE);
final String tweet =
TimelineDataType.NOTEWORTHY.getEmoji()
+ " #OnThisDay in 1996, @Oasis appear on Chris Evans' Radio 1 Breakfast Show and "
+ "announce that they will be playing two nights at Knebworth in August."
+ "\n\n@achrisevans #Oasis #OTD #TodayInMusic #britpop";
validateTweet(tweet, serveEventList.get(0).getRequest());
}
private void validateTweet(final String tweet, final LoggedRequest loggedRequest)
throws URISyntaxException {
final String request = decodeTweet(loggedRequest);
final GeoLocation location = decodeLocation(loggedRequest);
assertEquals(tweet, request, TWEET_BODY_MESSAGE);
assertEquals(Tweet.LOCATION, location, TWEET_LOCATION_MESSAGE);
}
private String decodeTweet(final LoggedRequest request) throws URISyntaxException {
final Map<String, Object> params = decodeRequest(request);
return params.getOrDefault("status", null).toString();
}
private GeoLocation decodeLocation(final LoggedRequest request) throws URISyntaxException {
final Map<String, Object> params = decodeRequest(request);
final Double latitude = Double.valueOf(params.getOrDefault("lat", "0.0").toString());
final Double longitude = Double.valueOf(params.getOrDefault("long", "0.0").toString());
return new GeoLocation(latitude, longitude);
}
private Map<String, Object> decodeRequest(final LoggedRequest request) throws URISyntaxException {
final List<NameValuePair> params =
URLEncodedUtils.parse(
new URI(request.getUrl() + "?" + request.getBodyAsString()), StandardCharsets.UTF_8);
return params.stream()
.collect(Collectors.toMap(NameValuePair::getName, NameValuePair::getValue));
}
}
|
9239444aa7e1517ad2b64829c8f5ddb26262ffd6 | 143 | java | Java | specs/gollgot/project/src/Main.java | gollgot/Teaching-HEIGVD-RES-2020-Exercise-Protocol-Design | cf4a30fe3e5795924f27b9fe5177baacafb0a588 | [
"MIT"
] | null | null | null | specs/gollgot/project/src/Main.java | gollgot/Teaching-HEIGVD-RES-2020-Exercise-Protocol-Design | cf4a30fe3e5795924f27b9fe5177baacafb0a588 | [
"MIT"
] | null | null | null | specs/gollgot/project/src/Main.java | gollgot/Teaching-HEIGVD-RES-2020-Exercise-Protocol-Design | cf4a30fe3e5795924f27b9fe5177baacafb0a588 | [
"MIT"
] | null | null | null | 15.888889 | 44 | 0.622378 | 998,767 | public class Main {
public static void main(String[] args) {
Server server = new Server(12000);
server.serveClients();
}
}
|
9239460b0e173bcadaec9090babd9d2fa9a32ebc | 598 | java | Java | src/main/java/com/dobo/modules/cms/service/ArticleDataService.java | 249910119/dobo | 56e42bd03fc1a78c80bdad72a062affdaf1e1213 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/dobo/modules/cms/service/ArticleDataService.java | 249910119/dobo | 56e42bd03fc1a78c80bdad72a062affdaf1e1213 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/dobo/modules/cms/service/ArticleDataService.java | 249910119/dobo | 56e42bd03fc1a78c80bdad72a062affdaf1e1213 | [
"Apache-2.0"
] | null | null | null | 26 | 105 | 0.779264 | 998,768 | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">dobo</a> All rights reserved.
*/
package com.dobo.modules.cms.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dobo.common.service.CrudService;
import com.dobo.modules.cms.dao.ArticleDataDao;
import com.dobo.modules.cms.entity.ArticleData;
/**
* 站点Service
* @author ThinkGem
* @version 2013-01-15
*/
@Service
@Transactional(readOnly = true)
public class ArticleDataService extends CrudService<ArticleDataDao, ArticleData> {
}
|
9239467952a91a50d5ec057fc496dc410fe1721f | 6,187 | java | Java | src/main/java/com/t3c/anchel/core/domain/entities/GenericStatistic.java | t3ctechnologies/Anchel_Core | 6c3f9c5787d181453dbebfdeb98aa8e5669a85ee | [
"MIT"
] | null | null | null | src/main/java/com/t3c/anchel/core/domain/entities/GenericStatistic.java | t3ctechnologies/Anchel_Core | 6c3f9c5787d181453dbebfdeb98aa8e5669a85ee | [
"MIT"
] | null | null | null | src/main/java/com/t3c/anchel/core/domain/entities/GenericStatistic.java | t3ctechnologies/Anchel_Core | 6c3f9c5787d181453dbebfdeb98aa8e5669a85ee | [
"MIT"
] | null | null | null | 29.745192 | 111 | 0.770163 | 998,769 | /*
* LinShare is an open source filesharing software, part of the LinPKI software
* suite, developed by Linagora.
*
* Copyright (C) 2015 LINAGORA
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any
* later version, provided you comply with the Additional Terms applicable for
* LinShare software by Linagora pursuant to Section 7 of the GNU Affero General
* Public License, subsections (b), (c), and (e), pursuant to which you must
* notably (i) retain the display of the “LinShare™” trademark/logo at the top
* of the interface window, the display of the “You are using the Open Source
* and free version of LinShare™, powered by Linagora © 2009–2015. Contribute to
* Linshare R&D by subscribing to an Enterprise offer!” infobox and in the
* e-mails sent with the Program, (ii) retain all hypertext links between
* LinShare and t3c.io, between linagora.com and Linagora, and (iii)
* refrain from infringing Linagora intellectual property rights over its
* trademarks and commercial brands. Other Additional Terms apply, see
* <http://www.linagora.com/licenses/> for more details.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License and
* its applicable Additional Terms for LinShare along with this program. If not,
* see <http://www.gnu.org/licenses/> for the GNU Affero General Public License
* version 3 and <http://www.linagora.com/licenses/> for the Additional Terms
* applicable to LinShare software.
*/
package com.t3c.anchel.core.domain.entities;
import java.util.Date;
import com.t3c.anchel.core.domain.constants.StatisticType;
public abstract class GenericStatistic {
protected Long id;
protected Account account;
protected AbstractDomain domain;
protected AbstractDomain parentDomain;
protected Long actualOperationSum;
protected Date creationDate;
protected Date statisticDate;
protected Long operationCount;
protected Long deleteOperationCount;
protected Long createOperationCount;
protected Long createOperationSum;
protected Long deleteOperationSum;
protected Long diffOperationSum;
protected StatisticType statisticType;
public GenericStatistic() {
}
public GenericStatistic(Account account, AbstractDomain domain, AbstractDomain parentDomain,
Long actualOperationSum, Long operationCount, Long deleteOperationCount, Long createOperationCount,
Long createOperationSum, Long deleteOperationSum, Long diffOperationSum, StatisticType statisticType) {
this.domain = domain;
this.parentDomain = parentDomain;
this.account = account;
this.actualOperationSum = actualOperationSum;
this.operationCount = operationCount;
this.deleteOperationCount = deleteOperationCount;
this.createOperationCount = createOperationCount;
this.createOperationSum = createOperationSum;
this.deleteOperationSum = deleteOperationSum;
this.diffOperationSum = diffOperationSum;
this.statisticType = statisticType;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public AbstractDomain getDomain() {
return domain;
}
public void setDomain(AbstractDomain domain) {
this.domain = domain;
}
public AbstractDomain getParentDomain() {
return parentDomain;
}
public void setParentDomain(AbstractDomain parentDomain) {
this.parentDomain = parentDomain;
}
public Long getActualOperationSum() {
return actualOperationSum;
}
public void setActualOperationSum(Long actualOperationSum) {
this.actualOperationSum = actualOperationSum;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Long getOperationCount() {
return operationCount;
}
public void setOperationCount(Long operationCount) {
this.operationCount = operationCount;
}
public Long getDeleteOperationCount() {
return deleteOperationCount;
}
public void setDeleteOperationCount(Long deleteOperationCount) {
this.deleteOperationCount = deleteOperationCount;
}
public Long getCreateOperationCount() {
return createOperationCount;
}
public void setCreateOperationCount(Long createOperationCount) {
this.createOperationCount = createOperationCount;
}
public Long getCreateOperationSum() {
return createOperationSum;
}
public void setCreateOperationSum(Long createOperationSum) {
this.createOperationSum = createOperationSum;
}
public Long getDeleteOperationSum() {
return deleteOperationSum;
}
public void setDeleteOperationSum(Long deleteOperationSum) {
this.deleteOperationSum = deleteOperationSum;
}
public Long getDiffOperationSum() {
return diffOperationSum;
}
public void setDiffOperationSum(Long diffOperationSum) {
this.diffOperationSum = diffOperationSum;
}
public abstract StatisticType getStatisticType();
public void setStatisticType(StatisticType statisticType) {
this.statisticType = statisticType;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public Date getStatisticDate() {
return statisticDate;
}
public void setStatisticDate(Date statisticDate) {
this.statisticDate = statisticDate;
}
@Override
public String toString() {
return "GenericStatistic [id=" + id + ", account=" + account + ", domain=" + domain + ", actualOperationSum="
+ actualOperationSum + ", creationDate=" + creationDate + ", operationCount=" + operationCount
+ ", deleteOperationCount=" + deleteOperationCount + ", createOperationCount=" + createOperationCount
+ ", createOperationSum=" + createOperationSum + ", deleteOperationSum=" + deleteOperationSum
+ ", diffOperationSum=" + diffOperationSum + ", statisticType=" + statisticType + "]";
}
}
|
923946ca0d3b16b58b4b75a03c571a7469898e0f | 6,568 | java | Java | server/nswy-api-dev/nswy-member-service/src/main/java/com/ovit/nswy/member/service/impl/StandardServiceImpl.java | tracy4262/zhenxingxiangcun | ea7f947814e4fc46ae872bb3477a5fa263c0a7a6 | [
"MIT"
] | 2 | 2020-10-26T04:34:07.000Z | 2021-02-24T03:02:36.000Z | server/nswy-api-dev/nswy-member-service/src/main/java/com/ovit/nswy/member/service/impl/StandardServiceImpl.java | tracy4262/zhenxingxiangcun | ea7f947814e4fc46ae872bb3477a5fa263c0a7a6 | [
"MIT"
] | 18 | 2020-09-09T19:49:32.000Z | 2022-03-02T08:04:17.000Z | server/nswy-api-dev/nswy-member-service/src/main/java/com/ovit/nswy/member/service/impl/StandardServiceImpl.java | tracy4262/zhenxingxiangcun | ea7f947814e4fc46ae872bb3477a5fa263c0a7a6 | [
"MIT"
] | 3 | 2019-09-25T07:05:35.000Z | 2021-01-17T08:06:39.000Z | 38.409357 | 112 | 0.63718 | 998,770 | package com.ovit.nswy.member.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.ovit.nswy.member.mapper.LoginUserMapper;
import com.ovit.nswy.member.mapper.StandardMapper;
import com.ovit.nswy.member.model.StandardComment;
import com.ovit.nswy.member.service.StandardService;
import com.ovit.nswy.member.util.PageUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 标准service层
*
* @author haoWen
* @create 2018-03-12 15:38
**/
@Service
@Transactional
public class StandardServiceImpl implements StandardService {
@Autowired
private StandardMapper standardMapper;
@Autowired
private LoginUserMapper loginUserMapper;
@Override
public int insertStandard(Map<String, Object> params) {
int index = -1;
int detail = standardMapper.insertStandardDetail(params);
int base = standardMapper.insertStandardBase(params);
if (detail != -1 && base != -1) {
index = detail;
}
return index;
}
@Override
public PageInfo<Map<String, Object>> queryForMemberCenter(Map<String, Object> params) {
PageUtils.initPage(params);
List<Map<String,Object>> list = standardMapper.queryForMemberCenter(params);
return new PageInfo<>(list);
}
@Override
public Map<String, Object> queryStandardDetail(Map<String, Object> params) {
Map<String, Object> detailMap = standardMapper.queryStandardDetail(params);
//查询当前ID的下一条数据
Map<String, Object> nextStandardInfo = standardMapper.queryNext(params);
//查询当前ID的上一条数据
Map<String, Object> previousStandardInfo = standardMapper.queryPrevious(params);
detailMap.put("nextMap",nextStandardInfo);
detailMap.put("previousMap",previousStandardInfo);
return detailMap;
}
@Override
public PageInfo<Map<String,Object>> queryStandardComment(Map<String, Object> params) {
PageHelper.startPage(MapUtils.getInteger(params,"pageNum"), 10);
String account = MapUtils.getString(params,"account");
Map<String,Object> maps = new HashMap<String,Object>();
List<Map<String,Object>> list = standardMapper.queryStandardComment(params);
for(int i=0;i<list.size();i++){
Map<String,Object> info = list.get(i);
String userAccount = String.valueOf(info.get("user_account"));
if(StringUtil.isNotEmpty(account)){
if(account.equals(userAccount)){
info.put("isReply",true);
}else{
info.put("isReply",false);
}
}else{
info.put("isReply",false);
}
info.put("replyBoxShow",false);
maps.put("account",userAccount);
List<Map<String, Object>> loginusers= loginUserMapper.listLoginUser(maps);
info.put("author",loginusers.get(0));
Map<String,Object> replyfindmap = new HashMap<String,Object>();
replyfindmap.put("id",info.get("id").toString());
List<Map<String, Object>> replyAuthor = standardMapper.findCommentHF(replyfindmap);
if(replyAuthor.size()>0){
for(int j=0;j<replyAuthor.size();j++){
Map<String,Object> replymap = new HashMap<String,Object>();
Map<String,Object> reply = replyAuthor.get(j);
String accounts = String.valueOf(reply.get("user_account"));
if(StringUtil.isNotEmpty(account)){
if(account.equals(accounts)){
info.put("isReply",true);
}else{
info.put("isReply",false);
}
}else{
info.put("isReply",false);
}
reply.put("replyBoxShow",false);
replymap.put("account",accounts);
List<Map<String, Object>> loginuser= loginUserMapper.listLoginUser(replymap);
reply.put("author",loginuser.get(0));
Map<String,Object> replyfindmaps = new HashMap<String,Object>();
replyfindmaps.put("id",info.get("id").toString());
List<Map<String, Object>> replyAuthors = standardMapper.findCommentHFDetail(replyfindmaps);
reply.put("replyAuthor",replyAuthors.get(0));
list.add(reply);
}
}
}
return new PageInfo<Map<String,Object>>(list);
}
@Override
public void deleteMyComment(Map<String, Object> params){
standardMapper.deleteMyComment(params);
}
@Override
public int queryStandardCommentCount(Map<String, Object> params) {
return standardMapper.queryStandardCommentCount(params);
}
@Override
public int publishComment(Map<String, Object> params) {
return standardMapper.publishComment(params);
}
@Override
public int updateBrowseNumber(Map<String, Object> params) {
return standardMapper.updateBrowseNumber(params);
}
@Override
public int queryThumbNumByDetailId(Map<String, Object> params) {
return standardMapper.queryThumbNumByDetailId(params);
}
@Override
public PageInfo<Map<String, Object>> queryDetailCommentReply(Map<String, Object> params) {
PageUtils.initPage(params);
List<Map<String, Object>> list = standardMapper.queryDetailCommentReply(params);
return new PageInfo<>(list);
}
@Override
public PageInfo<Map<String, Object>> queryForNswyNavigation(Map<String, Object> params) {
PageUtils.initPage(params);
List<Map<String, Object>> list = standardMapper.queryForNswyNavigation(params);
return new PageInfo<>(list);
}
@Override
public PageInfo<Map<String, Object>> queryForNswyHome(Map<String, Object> params) {
PageUtils.initPage(params);
List<Map<String, Object>> list = standardMapper.queryForNswyHome(params);
return new PageInfo<>(list);
}
}
|
92394709601e996a3a70517e2e140c7f196d9b48 | 1,462 | java | Java | src/main/java/com/zz/leecode/stringz/ConvertStringToZString.java | Zzij/leecode | 499202da332b4d776aa5f8defca78f9ab4b627b3 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/zz/leecode/stringz/ConvertStringToZString.java | Zzij/leecode | 499202da332b4d776aa5f8defca78f9ab4b627b3 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/zz/leecode/stringz/ConvertStringToZString.java | Zzij/leecode | 499202da332b4d776aa5f8defca78f9ab4b627b3 | [
"Apache-2.0"
] | null | null | null | 27.074074 | 88 | 0.595075 | 998,771 | package com.zz.leecode.stringz;
import java.util.HashMap;
/**
* @author zzj
* @className ConvertStringToZString
* @description TODO
* 将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
* <p>
* 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
* <p>
* L C I R
* E T O E S I I G
* E D H N
* 之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。
* @date 2020/11/9
*/
public class ConvertStringToZString {
public String convert(String s, int numRows) {
int length = s.length();
HashMap<Integer, StringBuilder> hashMap = new HashMap<>();
for (int i = 0; i < length; i++) {
int index = i % numRows;
if (hashMap.containsKey(index)) {
hashMap.get(index).append(s.charAt(i));
} else {
StringBuilder sb = new StringBuilder();
hashMap.put(index, sb);
sb.append(s.charAt(i));
}
}
StringBuilder currentSb = new StringBuilder(length);
for (int j = 0; j < numRows; j++) {
StringBuilder stringBuilder = hashMap.get(j);
currentSb.append(stringBuilder);
}
return currentSb.toString();
}
public static void main(String[] args) {
ConvertStringToZString convertStringToZString = new ConvertStringToZString();
String leetcodeishiring = convertStringToZString.convert("LEETCODEISHIRING", 3);
System.out.println(leetcodeishiring);
}
}
|
92394809a4d2dea736050a9f1ab54588a3f9bb44 | 447 | java | Java | az-center/src/main/java/com/wantdo/security/center/CenterBootstrap.java | luanx/az-security | 6466ab4fbc8bbd437039ddeab4b391171220e864 | [
"Apache-2.0"
] | null | null | null | az-center/src/main/java/com/wantdo/security/center/CenterBootstrap.java | luanx/az-security | 6466ab4fbc8bbd437039ddeab4b391171220e864 | [
"Apache-2.0"
] | null | null | null | az-center/src/main/java/com/wantdo/security/center/CenterBootstrap.java | luanx/az-security | 6466ab4fbc8bbd437039ddeab4b391171220e864 | [
"Apache-2.0"
] | null | null | null | 23.526316 | 74 | 0.789709 | 998,772 | package com.wantdo.security.center;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* @author luanx
*/
@SpringBootApplication
@EnableEurekaServer
public class CenterBootstrap {
public static void main(String[] args) {
SpringApplication.run(CenterBootstrap.class, args);
}
}
|
92394a95cabcf061d46c46c0eb52f56620dcb779 | 932 | java | Java | yeb-server/src/main/java/com/zj/server/mapper/EmployeeMapper.java | love-zj/yeb_project | 7dcd8ec66ab60da319242ac5fa187eb6df50d5c6 | [
"Apache-2.0"
] | null | null | null | yeb-server/src/main/java/com/zj/server/mapper/EmployeeMapper.java | love-zj/yeb_project | 7dcd8ec66ab60da319242ac5fa187eb6df50d5c6 | [
"Apache-2.0"
] | null | null | null | yeb-server/src/main/java/com/zj/server/mapper/EmployeeMapper.java | love-zj/yeb_project | 7dcd8ec66ab60da319242ac5fa187eb6df50d5c6 | [
"Apache-2.0"
] | null | null | null | 23.897436 | 103 | 0.669528 | 998,773 | package com.zj.server.mapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zj.server.pojo.Employee;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.web.bind.annotation.RequestParam;
import java.time.LocalDate;
import java.util.List;
/**
* <p>
* Mapper 接口
* </p>
*
* @author zhoujian
* @since 2021-07-08
*/
public interface EmployeeMapper extends BaseMapper<Employee> {
/**
* 查询所有员工(分页)
* @param page
* @param employee
* @param beginDateScope
* @return
*/
IPage<Employee> getEmployeeByPage(Page<Employee> page, @RequestParam("employee") Employee employee,
@RequestParam("beginDateScope") LocalDate[] beginDateScope);
/**
* 查询员工
* @param id
* @return
*/
List<Employee> getEmployee(Integer id);
}
|
92394a9e25615d9d8bdcfe4a7ce414afa1367675 | 6,466 | java | Java | kubernetes/src/test/java/io/kubernetes/java/apis/Certificates_v1alpha1ApiTest.java | mbohlool/client-java | bf231ada499e2abbf95d2410fec65569b4f2cffe | [
"Apache-2.0"
] | 1 | 2021-11-08T08:09:51.000Z | 2021-11-08T08:09:51.000Z | kubernetes/src/test/java/io/kubernetes/java/apis/Certificates_v1alpha1ApiTest.java | mbohlool/client-java | bf231ada499e2abbf95d2410fec65569b4f2cffe | [
"Apache-2.0"
] | null | null | null | kubernetes/src/test/java/io/kubernetes/java/apis/Certificates_v1alpha1ApiTest.java | mbohlool/client-java | bf231ada499e2abbf95d2410fec65569b4f2cffe | [
"Apache-2.0"
] | null | null | null | 28.610619 | 169 | 0.658985 | 998,774 | /*
* Kubernetes
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: v1.5.1-660c2a2
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.kubernetes.java.apis;
import io.kubernetes.java.ApiException;
import io.kubernetes.java.models.UnversionedAPIResourceList;
import io.kubernetes.java.models.UnversionedPatch;
import io.kubernetes.java.models.UnversionedStatus;
import io.kubernetes.java.models.V1DeleteOptions;
import io.kubernetes.java.models.V1alpha1CertificateSigningRequest;
import io.kubernetes.java.models.V1alpha1CertificateSigningRequestList;
import org.junit.Test;
import org.junit.Ignore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* API tests for Certificates_v1alpha1Api
*/
@Ignore
public class Certificates_v1alpha1ApiTest {
private final Certificates_v1alpha1Api api = new Certificates_v1alpha1Api();
/**
*
*
* create a CertificateSigningRequest
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void createCertificateSigningRequestTest() throws ApiException {
V1alpha1CertificateSigningRequest body = null;
String pretty = null;
V1alpha1CertificateSigningRequest response = api.createCertificateSigningRequest(body, pretty);
// TODO: test validations
}
/**
*
*
* delete a CertificateSigningRequest
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void deleteCertificateSigningRequestTest() throws ApiException {
String name = null;
V1DeleteOptions body = null;
String pretty = null;
Integer gracePeriodSeconds = null;
Boolean orphanDependents = null;
UnversionedStatus response = api.deleteCertificateSigningRequest(name, body, pretty, gracePeriodSeconds, orphanDependents);
// TODO: test validations
}
/**
*
*
* delete collection of CertificateSigningRequest
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void deleteCollectionCertificateSigningRequestTest() throws ApiException {
String pretty = null;
String fieldSelector = null;
String labelSelector = null;
String resourceVersion = null;
Integer timeoutSeconds = null;
Boolean watch = null;
UnversionedStatus response = api.deleteCollectionCertificateSigningRequest(pretty, fieldSelector, labelSelector, resourceVersion, timeoutSeconds, watch);
// TODO: test validations
}
/**
*
*
* get available resources
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getAPIResourcesTest() throws ApiException {
UnversionedAPIResourceList response = api.getAPIResources();
// TODO: test validations
}
/**
*
*
* list or watch objects of kind CertificateSigningRequest
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void listCertificateSigningRequestTest() throws ApiException {
String pretty = null;
String fieldSelector = null;
String labelSelector = null;
String resourceVersion = null;
Integer timeoutSeconds = null;
Boolean watch = null;
V1alpha1CertificateSigningRequestList response = api.listCertificateSigningRequest(pretty, fieldSelector, labelSelector, resourceVersion, timeoutSeconds, watch);
// TODO: test validations
}
/**
*
*
* partially update the specified CertificateSigningRequest
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void patchCertificateSigningRequestTest() throws ApiException {
String name = null;
UnversionedPatch body = null;
String pretty = null;
V1alpha1CertificateSigningRequest response = api.patchCertificateSigningRequest(name, body, pretty);
// TODO: test validations
}
/**
*
*
* read the specified CertificateSigningRequest
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void readCertificateSigningRequestTest() throws ApiException {
String name = null;
String pretty = null;
Boolean exact = null;
Boolean export = null;
V1alpha1CertificateSigningRequest response = api.readCertificateSigningRequest(name, pretty, exact, export);
// TODO: test validations
}
/**
*
*
* replace the specified CertificateSigningRequest
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void replaceCertificateSigningRequestTest() throws ApiException {
String name = null;
V1alpha1CertificateSigningRequest body = null;
String pretty = null;
V1alpha1CertificateSigningRequest response = api.replaceCertificateSigningRequest(name, body, pretty);
// TODO: test validations
}
/**
*
*
* replace approval of the specified CertificateSigningRequest
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void replaceCertificateSigningRequestApprovalTest() throws ApiException {
V1alpha1CertificateSigningRequest body = null;
String name = null;
String pretty = null;
V1alpha1CertificateSigningRequest response = api.replaceCertificateSigningRequestApproval(body, name, pretty);
// TODO: test validations
}
/**
*
*
* replace status of the specified CertificateSigningRequest
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void replaceCertificateSigningRequestStatusTest() throws ApiException {
V1alpha1CertificateSigningRequest body = null;
String name = null;
String pretty = null;
V1alpha1CertificateSigningRequest response = api.replaceCertificateSigningRequestStatus(body, name, pretty);
// TODO: test validations
}
}
|
92394affbbd98de3e4440a846f8b523b7af207e9 | 2,857 | java | Java | dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/IfModifiedSinceSelector.java | bireme/DSpace-6-FUNASA | fd29e3eda4be65e8ee217efae98c43187b419d17 | [
"BSD-3-Clause"
] | 10 | 2015-08-26T14:22:21.000Z | 2019-07-02T14:18:09.000Z | dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/IfModifiedSinceSelector.java | bireme/DSpace-6-FUNASA | fd29e3eda4be65e8ee217efae98c43187b419d17 | [
"BSD-3-Clause"
] | 690 | 2015-07-16T20:44:35.000Z | 2022-03-14T17:42:44.000Z | dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/IfModifiedSinceSelector.java | Sergio-strazzacappa/Dspace | 2aaa2aa526058b122637e8cc4400e47ea5499cd4 | [
"BSD-3-Clause"
] | 16 | 2017-01-12T09:30:45.000Z | 2019-04-18T20:51:12.000Z | 31.395604 | 86 | 0.635282 | 998,775 | /**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.general;
import java.util.Map;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.selection.Selector;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.Constants;
/**
* This simple selector looks for the If-Modified-Since header, and
* returns true if the Item in the request has not been modified since that
* date. The expression is ignored since the test is inherent in the request.
*
* <p>Typical sitemap usage:
*
* <pre>
* {@code
* <map:match type="HandleTypeMatcher" pattern="item">
* <map:select type="IfModifiedSinceSelector">
* <map:when test="true">
* <map:act type="NotModifiedAction"/>
* <map:serialize/>
* </map:when>
* <map:otherwise>
* <map:transform type="ItemViewer"/>
* <map:serialize type="xml"/>
* </map:otherwise>
* </map:select>
* </map:match>
* }
* </pre>
*
* @author Larry Stone
*/
public class IfModifiedSinceSelector implements Selector
{
private static final Logger log = Logger.getLogger(IfModifiedSinceSelector.class);
/**
* Check for If-Modified-Since header on request,
* and returns true if the Item should *not* be sent, i.e.
* if the response status should be 304 (HttpServletResponse.SC_NOT_MODIFIED).
*
* @param expression is ignored
* @param objectModel
* environment passed through via Cocoon.
* @param parameters
* sitemap parameters.
* @return null or map containing value of sitemap parameter 'pattern'
*/
@Override
public boolean select(String expression, Map objectModel,
Parameters parameters)
{
try
{
Request request = ObjectModelHelper.getRequest(objectModel);
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso.getType() == Constants.ITEM)
{
Item item = (Item) dso;
long modSince = request.getDateHeader("If-Modified-Since");
if (modSince != -1 && item.getLastModified().getTime() < modSince)
{
return true;
}
}
return false;
}
catch (Exception e)
{
log.error("Error selecting based on If-Modified-Since: "+e.toString());
return false;
}
}
}
|
92394d5805b66266295ce027257cc4cf518066f9 | 1,278 | java | Java | leetcode/algorithm/src/main/java/com/alison/sort/BubbleSort.java | GavinAlison/advanceJava | 93766361c7bb934d0c0abbf3eca87a5beb463cee | [
"Apache-2.0"
] | null | null | null | leetcode/algorithm/src/main/java/com/alison/sort/BubbleSort.java | GavinAlison/advanceJava | 93766361c7bb934d0c0abbf3eca87a5beb463cee | [
"Apache-2.0"
] | 2 | 2019-10-19T13:49:01.000Z | 2019-12-10T08:25:58.000Z | leetcode/algorithm/src/main/java/com/alison/sort/BubbleSort.java | GavinAlison/advanceJava | 93766361c7bb934d0c0abbf3eca87a5beb463cee | [
"Apache-2.0"
] | null | null | null | 26.625 | 67 | 0.408451 | 998,776 | package com.alison.sort;
import java.util.Arrays;
/**
* @Author alison
* @Date 2019/8/10 18:26
* @Version 1.0
* @Description
*/
public class BubbleSort implements IArraySort {
@Override
public int[] sort(int[] sourceArray) {
// 对arr进行拷贝, 不改变参数内容
int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = tmp;
}
}
}
return arr;
}
public int[] sort2(int[] sourceArray) {
// 对arr进行拷贝, 不改变参数内容
int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
for (int i = 1; i < arr.length; i++) {
boolean flag = true;
for (int j = 0; j < arr.length - i; j++) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = tmp;
flag = false;
}
}
if (flag) {
break;
}
}
return arr;
}
}
|
92394d78f72f6095c282d2e5fbffde3cf499c87e | 1,073 | java | Java | gradle/src/testing-jvm/org/gradle/api/internal/tasks/testing/detection/TestFrameworkDetector.java | HenryHarper/Acquire-Reboot | ed7d8e3ce1953d7cf0b7e8313a9ee7ad9948bc34 | [
"MIT"
] | 158 | 2015-04-18T23:39:02.000Z | 2021-07-01T18:28:29.000Z | gradle/src/testing-jvm/org/gradle/api/internal/tasks/testing/detection/TestFrameworkDetector.java | HenryHarper/Acquire-Reboot | ed7d8e3ce1953d7cf0b7e8313a9ee7ad9948bc34 | [
"MIT"
] | 31 | 2015-04-29T18:52:40.000Z | 2020-06-29T19:25:24.000Z | gradle/src/testing-jvm/org/gradle/api/internal/tasks/testing/detection/TestFrameworkDetector.java | HenryHarper/Acquire-Reboot | ed7d8e3ce1953d7cf0b7e8313a9ee7ad9948bc34 | [
"MIT"
] | 32 | 2016-01-05T21:58:24.000Z | 2021-06-21T21:56:34.000Z | 33.53125 | 75 | 0.7726 | 998,777 | /*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.tasks.testing.detection;
import org.gradle.api.file.FileCollection;
import org.gradle.api.internal.tasks.testing.TestClassProcessor;
import java.io.File;
public interface TestFrameworkDetector {
void startDetection(TestClassProcessor testClassProcessor);
boolean processTestClass(File testClassFile);
void setTestClassesDirectory(File testClassesDir);
void setTestClasspath(FileCollection classpath);
}
|
92394e7ce222734cd92e0e03bf47412fea2f330e | 504 | java | Java | checker/tests/aggregate/NullnessAndRegex.java | twistedsquare/checker-framework | 35b682c252a390924fefe3e12f5dcc57971cf9eb | [
"MIT"
] | 877 | 2015-07-04T19:51:28.000Z | 2022-03-25T07:40:52.000Z | checker/tests/aggregate/NullnessAndRegex.java | smonteiro/checker-framework | 967490a52d69c4658b8cc2461c5dce06a016f1e7 | [
"MIT"
] | 2,468 | 2015-07-06T18:17:19.000Z | 2022-03-31T16:56:39.000Z | checker/tests/aggregate/NullnessAndRegex.java | smonteiro/checker-framework | 967490a52d69c4658b8cc2461c5dce06a016f1e7 | [
"MIT"
] | 427 | 2015-07-07T15:52:48.000Z | 2022-03-20T21:52:22.000Z | 24 | 63 | 0.668651 | 998,778 | // Make sure that we actually receive errors from sub-checkers.
import org.checkerframework.checker.i18n.qual.Localized;
import org.checkerframework.checker.regex.qual.Regex;
public class NullnessAndRegex {
// :: error: (assignment)
@Regex String s1 = "De(mo";
// :: error: (assignment)
Object f = null;
// :: error: (assignment)
@Regex String s2 = "De(mo";
void localized(@Localized String s) {}
void method() {
// :: error: (argument)
localized("ldskjfldj"); // error
}
}
|
92394e972bd47091d8d5ca7a95bf118c0bd12a89 | 1,715 | java | Java | checkstyle/src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/javadocmethod/InputJavadocMethodSetterGetter.java | spoole167/java-static-analysis-samples | 880f9b394e531d8c03af425b1b4e5a95302a3359 | [
"Apache-2.0"
] | null | null | null | checkstyle/src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/javadocmethod/InputJavadocMethodSetterGetter.java | spoole167/java-static-analysis-samples | 880f9b394e531d8c03af425b1b4e5a95302a3359 | [
"Apache-2.0"
] | null | null | null | checkstyle/src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/javadocmethod/InputJavadocMethodSetterGetter.java | spoole167/java-static-analysis-samples | 880f9b394e531d8c03af425b1b4e5a95302a3359 | [
"Apache-2.0"
] | 1 | 2021-09-15T05:49:41.000Z | 2021-09-15T05:49:41.000Z | 19.055556 | 82 | 0.627405 | 998,779 | /*
JavadocMethod
allowedAnnotations = (default)Override
validateThrows = (default)false
accessModifiers = (default)public, protected, package, private
allowMissingParamTags = (default)false
allowMissingReturnTag = (default)false
tokens = (default)METHOD_DEF, CTOR_DEF, ANNOTATION_FIELD_DEF, COMPACT_CTOR_DEF
*/
package com.puppycrawl.tools.checkstyle.checks.javadoc.javadocmethod;
public class InputJavadocMethodSetterGetter
{
private int mNumber; // ok
public void setNumber(final int number) // ok
{
mNumber = number;
}
public int getNumber() // ok
{
return mNumber;
}
public void setNumber1() // ok
{
mNumber = mNumber;
}
public void setNumber2(int number) // ok
{
mNumber = number;
firePropertyChanged();
}
public void getNumber2() // ok
{
}
public int getCost1(int forMe) // ok
{
return 666;
}
public int getCost2() // ok
{
mNumber = 4;
return 666;
}
public int getCost3() throws Exception // ok
{
return 666;
}
public boolean isSomething() // ok
{
return false;
}
private void firePropertyChanged(){} // ok
Object setObject(Object object) { // ok
return new Object();
}
Object getNext() { // ok
throw new UnsupportedOperationException();
}
public void setWithoutAssignment(Object object) { // ok
object.notify();
}
InputJavadocMethodSetterGetter() {} // ok
public InputJavadocMethodSetterGetter(Object object) throws Exception {} // ok
}
interface TestInterface { // ok
void setObject(Object object);
Object getObject();
}
|
92394eac4abb9213cd955aa1b63d6144f6ae3176 | 152 | java | Java | CH21_Genrics/src/hierarchy/Mammal.java | EGParkk/java-study | 5684fce40889388b7a3f2c1df87ea2b59057dfc0 | [
"MIT"
] | 1 | 2021-11-17T06:23:40.000Z | 2021-11-17T06:23:40.000Z | CH21_Genrics/src/hierarchy/Mammal.java | EGParkk/java-study | 5684fce40889388b7a3f2c1df87ea2b59057dfc0 | [
"MIT"
] | null | null | null | CH21_Genrics/src/hierarchy/Mammal.java | EGParkk/java-study | 5684fce40889388b7a3f2c1df87ea2b59057dfc0 | [
"MIT"
] | null | null | null | 15.2 | 55 | 0.717105 | 998,780 | package hierarchy;
public class Mammal extends Creature {
public Mammal(String name) {
super(name); // 부모 클래스 Creature를 생성할때 이름(name)이 입력되야함
}
}
|
92394f32db067cbdb32c89070be4c09a3c0f0229 | 3,674 | java | Java | src/main/java/slimebound/events/WorldOfGoopSlimebound.java | tldyl/EvilWithin | 2a713787ccd7e1228d59f0946db76a689bda6b89 | [
"MIT"
] | 12 | 2020-08-27T16:35:17.000Z | 2022-03-26T17:57:00.000Z | src/main/java/slimebound/events/WorldOfGoopSlimebound.java | tldyl/EvilWithin | 2a713787ccd7e1228d59f0946db76a689bda6b89 | [
"MIT"
] | 1 | 2021-04-02T21:05:12.000Z | 2021-04-02T21:05:12.000Z | src/main/java/slimebound/events/WorldOfGoopSlimebound.java | tldyl/EvilWithin | 2a713787ccd7e1228d59f0946db76a689bda6b89 | [
"MIT"
] | 23 | 2020-06-28T19:57:13.000Z | 2022-03-27T08:07:50.000Z | 35.326923 | 174 | 0.627382 | 998,781 | //
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package slimebound.events;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.core.Settings;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.events.AbstractImageEvent;
import com.megacrit.cardcrawl.helpers.RelicLibrary;
import com.megacrit.cardcrawl.localization.EventStrings;
import com.megacrit.cardcrawl.vfx.RainingGoldEffect;
import slimebound.relics.GreedOozeRelic;
public class WorldOfGoopSlimebound extends AbstractImageEvent {
public static final String ID = "Slimebound:WorldofGoop";
public static final String NAME;
public static final String[] DESCRIPTIONS;
public static final String[] OPTIONS;
private static final EventStrings eventStrings;
private static final String DIALOG_1;
private static final String GOLD_DIALOG;
private static final String LEAVE_DIALOG;
static {
eventStrings = CardCrawlGame.languagePack.getEventString("Slimebound:WorldofGoop");
NAME = eventStrings.NAME;
DESCRIPTIONS = eventStrings.DESCRIPTIONS;
OPTIONS = eventStrings.OPTIONS;
DIALOG_1 = DESCRIPTIONS[0];
GOLD_DIALOG = DESCRIPTIONS[1];
LEAVE_DIALOG = DESCRIPTIONS[2];
}
private WorldOfGoopSlimebound.CurScreen screen;
private int damage;
private int gold;
private int goldLoss;
public WorldOfGoopSlimebound() {
super(NAME, DIALOG_1, "images/events/goopPuddle.jpg");
this.screen = WorldOfGoopSlimebound.CurScreen.INTRO;
this.damage = 11;
this.gold = 75;
this.imageEventText.setDialogOption(OPTIONS[0]);
if (this.gold <= AbstractDungeon.player.gold) {
this.imageEventText.setDialogOption( OPTIONS[1], new GreedOozeRelic());
} else {
this.imageEventText.setDialogOption( OPTIONS[3], true);
}
}
public void onEnterRoom() {
if (Settings.AMBIANCE_ON) {
CardCrawlGame.sound.play("EVENT_SPIRITS");
}
}
protected void buttonEffect(int buttonPressed) {
switch (this.screen) {
case INTRO:
switch (buttonPressed) {
case 0:
this.imageEventText.updateBodyText(GOLD_DIALOG);
this.imageEventText.clearAllDialogs();
this.imageEventText.setDialogOption(OPTIONS[2]);
AbstractDungeon.effectList.add(new RainingGoldEffect(this.gold));
AbstractDungeon.player.gainGold(this.gold);
imageEventText.updateBodyText(GOLD_DIALOG);
this.screen = WorldOfGoopSlimebound.CurScreen.RESULT;
return;
case 1:
imageEventText.updateBodyText(LEAVE_DIALOG);
this.imageEventText.clearAllDialogs();
this.imageEventText.setDialogOption(OPTIONS[2]);
AbstractDungeon.getCurrRoom().spawnRelicAndObtain(Settings.WIDTH / 2.0f, Settings.HEIGHT / 2.0f, RelicLibrary.getRelic(GreedOozeRelic.ID).makeCopy());
AbstractDungeon.player.loseGold(this.gold);
this.screen = WorldOfGoopSlimebound.CurScreen.RESULT;
return;
default:
return;
}
default:
this.openMap();
}
}
private enum CurScreen {
INTRO,
RESULT;
CurScreen() {
}
}
}
|
923950c07da2eeaea88a092827c7d667f2eff3e8 | 4,351 | java | Java | graalvm/transactions/fork/narayana/ArjunaJTS/jts/classes/com/arjuna/ats/internal/jts/interposition/ServerControlWrapper.java | nmcl/wfswarm-example-arjuna-old | c2344f4780cd59caf37dd806e492efe1973ad2ff | [
"Apache-2.0"
] | 1 | 2019-05-23T18:19:26.000Z | 2019-05-23T18:19:26.000Z | graalvm/transactions/fork/narayana/ArjunaJTS/jts/classes/com/arjuna/ats/internal/jts/interposition/ServerControlWrapper.java | nmcl/scratch | 2a068fa6eb2f14c5338a332d3b624d5c91c42c07 | [
"Apache-2.0"
] | 65 | 2016-01-24T19:44:46.000Z | 2022-02-09T01:00:07.000Z | graalvm/transactions/fork/narayana/ArjunaJTS/jts/classes/com/arjuna/ats/internal/jts/interposition/ServerControlWrapper.java | nmcl/wfswarm-example-arjuna | c2344f4780cd59caf37dd806e492efe1973ad2ff | [
"Apache-2.0"
] | 1 | 2019-05-02T14:23:43.000Z | 2019-05-02T14:23:43.000Z | 27.745223 | 123 | 0.737833 | 998,782 | /*
* JBoss, Home of Professional Open Source
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* (C) 2005-2006,
* @author JBoss Inc.
*/
/*
* Copyright (C) 2004,
*
* Arjuna Technologies Ltd,
* Newcastle upon Tyne,
* Tyne and Wear,
* UK.
*
* $Id: ServerControlWrapper.java 2342 2006-03-30 13:06:17Z $
*/
package com.arjuna.ats.internal.jts.interposition;
import org.omg.CORBA.CompletionStatus;
import org.omg.CORBA.INVALID_TRANSACTION;
import org.omg.CORBA.SystemException;
import org.omg.CosTransactions.Control;
import org.omg.CosTransactions.Coordinator;
import org.omg.CosTransactions.Inactive;
import org.omg.CosTransactions.NoTransaction;
import org.omg.CosTransactions.SubtransactionsUnavailable;
import org.omg.CosTransactions.Unavailable;
import com.arjuna.ats.arjuna.common.Uid;
import com.arjuna.ats.arjuna.coordinator.ActionStatus;
import com.arjuna.ats.internal.jts.ControlWrapper;
import com.arjuna.ats.internal.jts.interposition.resources.arjuna.Interposition;
import com.arjuna.ats.internal.jts.orbspecific.ControlImple;
import com.arjuna.ats.jts.exceptions.ExceptionCodes;
import com.arjuna.ats.jts.logging.jtsLogger;
/**
* This class attempts to mask the local/remote control issue. We try to use
* local controls directly as much as possible and not register them with the
* ORB until the last minute. This improves performance *significantly*. At
* present we only do this for top-level transactions, but extending for nested
* transactions is straightforward.
*
* It also acts as a convenience class for ease of use. Therefore, some
* Coordinator and Terminator methods may be found directly on this class.
* Because of the way in which the implementation works, however, some of their
* signatures may be slightly different.
*
* @author Mark Little (ychag@example.com)
* @version $Id: ServerControlWrapper.java 2342 2006-03-30 13:06:17Z $
* @since JTS 3.3.
*/
/*
* We create and destroy instances of this class regularly simply because
* otherwise we would never know.
*/
public class ServerControlWrapper extends ControlWrapper
{
public ServerControlWrapper (Control c)
{
super(c);
}
public ServerControlWrapper (ControlImple impl)
{
super(impl);
}
public ServerControlWrapper (Control c, ControlImple impl)
{
super(c, impl);
}
public ServerControlWrapper (Control c, Uid u)
{
super(c, u);
}
/*
* Override some Reapable methods.
*/
public int cancel ()
{
try
{
Interposition.destroy(super.get_uid());
rollback();
return ActionStatus.ABORTED;
}
catch (Unavailable ex)
{
return ActionStatus.INVALID;
}
catch (NoTransaction ex)
{
return ActionStatus.NO_ACTION;
}
catch (Exception ex) {
jtsLogger.i18NLogger.warn_interposition_cwabort(ex);
return ActionStatus.INVALID;
}
}
public ControlWrapper create_subtransaction () throws Unavailable,
Inactive, SubtransactionsUnavailable, SystemException
{
Coordinator coord = null;
try
{
coord = get_coordinator();
}
catch (SystemException e)
{
coord = null;
}
if (coord != null)
{
return new ServerControlWrapper(coord.create_subtransaction());
}
else
{
if (jtsLogger.logger.isTraceEnabled()) {
jtsLogger.logger.trace("ServerControlWrapper::create_subtransaction - subtransaction parent is inactive.");
}
throw new INVALID_TRANSACTION(
ExceptionCodes.UNAVAILABLE_COORDINATOR,
CompletionStatus.COMPLETED_NO);
}
}
}
|
9239517b0f5c81cd93bcf23eda6f18bebfa97149 | 7,226 | java | Java | chapter_009/src/main/java/ru/job4j/fin/repository/UserRepository.java | wamdue/agorbunov | da072c01c4205442582864e3c14ad38d0c166aef | [
"Apache-2.0"
] | null | null | null | chapter_009/src/main/java/ru/job4j/fin/repository/UserRepository.java | wamdue/agorbunov | da072c01c4205442582864e3c14ad38d0c166aef | [
"Apache-2.0"
] | null | null | null | chapter_009/src/main/java/ru/job4j/fin/repository/UserRepository.java | wamdue/agorbunov | da072c01c4205442582864e3c14ad38d0c166aef | [
"Apache-2.0"
] | null | null | null | 32.845455 | 138 | 0.588431 | 998,783 | package ru.job4j.fin.repository;
import org.apache.log4j.Logger;
import ru.job4j.fin.dao.AddressDao;
import ru.job4j.fin.dao.MusicTypeDao;
import ru.job4j.fin.dao.RoleDao;
import ru.job4j.fin.dao.UserDao;
import ru.job4j.fin.entity.Address;
import ru.job4j.fin.entity.MusicType;
import ru.job4j.fin.entity.Role;
import ru.job4j.fin.entity.User;
import ru.job4j.fin.util.SearchType;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
/**
* Created on 22.11.17.
* User repository pattern realisation.
* @author Wamdue
* @version 1.0
*/
public class UserRepository extends UserDao {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(RoleRepository.class);
/**
* Role dao copy.
*/
private RoleDao roleDao;
/**
* MusicType dao copy.
*/
private MusicTypeDao musicTypeDao;
/**
* Address dao copy.
*/
private AddressDao addressDao;
/**
* Dispatch pattern, for search type.
*/
private final Map<String, Function<SearchType, List<User>>> search = new HashMap<>();
/**
* Main constructor.
* @param connection - connection to db.
*/
public UserRepository(Connection connection) {
super(connection);
this.roleDao = new RoleDao(this.getConnection());
this.musicTypeDao = new MusicTypeDao(this.getConnection());
this.addressDao = new AddressDao(this.getConnection());
this.fillSearch();
}
/**
* Fill dispatch map.
*/
private void fillSearch() {
this.search.put("address", this.addressSearch());
this.search.put("role", this.roleSearch());
this.search.put("type", this.musicTypeSearch());
}
/**
* Find user and all entities for him by id.
* @param id - user id.
* @return - full user information.
*/
public User getUserById(int id) {
User user = this.findById(id);
Address address = this.addressDao.findById(id);
if (address != null && address.getId() != -1) {
user.setAddress(address);
}
try (PreparedStatement statement = this.getConnection().prepareStatement(this.getProps().getProperty("select_user_roles"))) {
statement.setInt(1, user.getId());
try (ResultSet set = statement.executeQuery()) {
while (set.next()) {
int i = set.getInt("role_id");
user.addRole(this.roleDao.findById(i));
}
}
} catch (SQLException e) {
LOGGER.error("Cannot load user roles from DB.", e);
}
try (PreparedStatement statement = this.getConnection().prepareStatement(this.getProps().getProperty("select_user_music"))) {
statement.setInt(1, user.getId());
try (ResultSet set = statement.executeQuery()) {
while (set.next()) {
int i = (set.getInt("type_id"));
user.addMusicType(this.musicTypeDao.findById(i));
}
}
} catch (SQLException e) {
LOGGER.error("Cannot load user music types from DB.", e);
}
return user;
}
/**
* Adding new user to db.
* @param user - user to add.
* @return - user id in db.
*/
public int createUser(User user) {
int userId = this.add(user);
Address address = new Address();
address.setId(userId);
address.setAddress(user.getAddress().getAddress());
this.addressDao.add(address);
if (userId > 0) {
for (Role role : user.getRoles()) {
try (PreparedStatement statement = this.getConnection().prepareStatement(this.getProps().getProperty("add_role2user"))) {
statement.setInt(1, userId);
statement.setInt(2, role.getId());
statement.executeUpdate();
} catch (SQLException e) {
LOGGER.error("Cannot insert user roles in DB.", e);
}
}
for (MusicType musicType : user.getMusicTypes()) {
try (PreparedStatement statement = this.getConnection().prepareStatement(this.getProps().getProperty("add_music2user"))) {
statement.setInt(1, userId);
statement.setInt(2, musicType.getId());
statement.executeUpdate();
} catch (SQLException e) {
LOGGER.error("Cannot insert user music types in DB.", e);
}
}
LOGGER.info(String.format("New user id# %d add to db.", userId));
}
return userId;
}
/**
* Get list of users by search string.
* @param searchString - address to search.
* @param sql - sql statement.
* @return - list of users.
*/
private List<User> getUsersBySearchString(String searchString, String sql) {
List<User> users = new ArrayList<>();
try (PreparedStatement statement = this.getConnection().prepareStatement(sql)) {
StringBuilder sb = new StringBuilder();
sb.append("%").append(searchString).append("%");
statement.setString(1, sb.toString());
users = this.fillListOfUsers(statement.executeQuery());
} catch (SQLException e) {
LOGGER.error("Cannot load list of users by Search string", e);
}
return users;
}
/**
* Internal method, to work with result set.
* @param set - source set.
* @return - filled user list.
*/
private List<User> fillListOfUsers(ResultSet set) {
List<User> users = new ArrayList<>();
try (ResultSet s = set) {
while (s.next()) {
users.add(this.getUserById(s.getInt("user_id")));
}
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
/**
* Search by address string.
* @return - list of users.
*/
private Function<SearchType, List<User>> addressSearch() {
return type-> this.getUsersBySearchString(type.getVal(), this.getProps().getProperty("find_users_by_address"));
}
/**
* Search by role.
* @return - list of users.
*/
private Function<SearchType, List<User>> roleSearch() {
return type-> this.getUsersBySearchString(type.getVal(), this.getProps().getProperty("find_users_by_role"));
}
/**
* Search by music type.
* @return - list of users.
*/
private Function<SearchType, List<User>> musicTypeSearch() {
return type-> this.getUsersBySearchString(type.getVal(), this.getProps().getProperty("find_users_by_music_type"));
}
/**
* Main search methos.
* @param searchType - search string with type.
* @return - filled list of users.
*/
public List<User> searchMethod(SearchType searchType) {
return this.search.get(searchType.getType()).apply(searchType);
}
} |
9239519a975e9956d32ea6739ed09a2739fc2b30 | 941 | java | Java | app/src/main/java/lee/todo/Util/LogUtil.java | LeeReindeer/SimpleNote | 80d8d931dd95a9cfcbad7258fdd0e27bb9bdd2aa | [
"Apache-2.0"
] | 1 | 2021-04-07T16:52:02.000Z | 2021-04-07T16:52:02.000Z | app/src/main/java/lee/todo/Util/LogUtil.java | LeeReindeer/Todo | 80d8d931dd95a9cfcbad7258fdd0e27bb9bdd2aa | [
"Apache-2.0"
] | 1 | 2017-08-14T11:33:04.000Z | 2017-08-15T13:10:11.000Z | app/src/main/java/lee/todo/Util/LogUtil.java | LeeReindeer/SimpleNote | 80d8d931dd95a9cfcbad7258fdd0e27bb9bdd2aa | [
"Apache-2.0"
] | null | null | null | 21.386364 | 48 | 0.590861 | 998,784 | package lee.todo.Util;
import android.util.Log;
/**
* @Author lee
* @Time 6/26/17.
*/
public class LogUtil {
private final static int NOTHING=6;
private final static int VERBOSE=1;
private final static int DEBUG=2;
private final static int INFO=3;
private final static int WARN=4;
private final static int ERROR=5;
private final static int level=VERBOSE;
public static void v(String TAG,String msg){
if (level<=VERBOSE)
Log.v(TAG,msg);
}
public static void d(String TAG,String msg){
if (level<=DEBUG)
Log.d(TAG,msg);
}
public static void i(String TAG,String msg){
if (level<=INFO)
Log.i(TAG,msg);
}
public static void w(String TAG,String msg){
if (level<=WARN)
Log.w(TAG,msg);
}
public static void e(String TAG,String msg){
if (level<=ERROR)
Log.e(TAG,msg);
}
}
|
923952537fb267c79417acbe471e97565312d61b | 2,063 | java | Java | common/src/cube/common/state/FileProcessorStateCode.java | shixincube/cube-server | d9828a9399e9d80c6d63aa8b7e1d80b9d22c4465 | [
"MIT"
] | 3 | 2021-01-06T00:42:05.000Z | 2021-11-29T08:10:37.000Z | common/src/cube/common/state/FileProcessorStateCode.java | shixincube/cube-server | d9828a9399e9d80c6d63aa8b7e1d80b9d22c4465 | [
"MIT"
] | null | null | null | common/src/cube/common/state/FileProcessorStateCode.java | shixincube/cube-server | d9828a9399e9d80c6d63aa8b7e1d80b9d22c4465 | [
"MIT"
] | 1 | 2021-02-25T05:25:47.000Z | 2021-02-25T05:25:47.000Z | 22.67033 | 81 | 0.630635 | 998,785 | /*
* This source file is part of Cube.
*
* The MIT License (MIT)
*
* Copyright (c) 2020-2021 Shixin Cube Team.
*
* 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 cube.common.state;
/**
* 文件处理状态码。
*/
public enum FileProcessorStateCode {
/**
* 成功。
*/
Ok(0),
/**
* 无效参数。
*/
InvalidParameter(5),
/**
* 遇到故障。
*/
Failure(9),
/**
* 无效域信息。
*/
InvalidDomain(11),
/**
* 操作超时。
*/
OptTimeout(12),
/**
* 与 CV 服务器无连接。
*/
NoCVConnection(21),
/**
* 无文件。
*/
NoFile(110),
/**
* 未知的状态。
*/
Unknown(99)
;
public final int code;
FileProcessorStateCode(int code) {
this.code = code;
}
public static FileProcessorStateCode parse(int code) {
for (FileProcessorStateCode sc : FileProcessorStateCode.values()) {
if (sc.code == code) {
return sc;
}
}
return FileProcessorStateCode.Unknown;
}
}
|
92395402c6bf4e9b0d1c6401f3bf0193a3c1ae90 | 6,893 | java | Java | calenday/src/main/java/com/erikzuo/calendaylib/view/MonthView.java | SilverEnd/Calenday | 8c42cd9699552f34ede36d7071f6f471261db2b2 | [
"Apache-2.0"
] | 1 | 2018-02-25T05:09:06.000Z | 2018-02-25T05:09:06.000Z | calenday/src/main/java/com/erikzuo/calendaylib/view/MonthView.java | SilverEnd/Calenday | 8c42cd9699552f34ede36d7071f6f471261db2b2 | [
"Apache-2.0"
] | null | null | null | calenday/src/main/java/com/erikzuo/calendaylib/view/MonthView.java | SilverEnd/Calenday | 8c42cd9699552f34ede36d7071f6f471261db2b2 | [
"Apache-2.0"
] | null | null | null | 37.05914 | 118 | 0.696068 | 998,786 | package com.erikzuo.calendaylib.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.erikzuo.calendaylib.listener.AddEventListener;
import com.erikzuo.calendaylib.utility.Constants;
import com.erikzuo.calendaylib.listener.EventClickListener;
import com.erikzuo.calendaylib.R;
import com.erikzuo.calendaylib.model.Event;
import java.util.ArrayList;
import java.util.Calendar;
/**
* Created by YifanZuo on 31/08/2016.
*/
public class MonthView extends FrameLayout {
private Context mContext;
// General attributes
private int mAxisColor;
private int mWeekdayBgColor;
private int mMonthCellColor;
private int mMonthTextColor;
private int mOtherMonthCellColor;
private int mOtherMonthTextColor;
private int mTodayColor;
private int mEventColor;
private int mCurrentTimeColor;
private int mAddEventBtnResId;
private Calendar mStartDate;
private ViewPager mViewPager;
private ArrayList<Event> mEventList;
private ArrayList<SingleMonthPage> mMonthFragmentList;
private AddEventListener mAddEventListener;
private EventClickListener mEventClickListener;
public MonthView(Context context) {
this(context, null);
}
public MonthView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MonthView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
LayoutInflater inflater = (LayoutInflater) context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.month_view, this);
// Get the attribute values (if any).
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MonthView);
try {
mAxisColor = a.getColor(R.styleable.MonthView_monthAxisColor, Color.parseColor("#bbbbbb"));
mWeekdayBgColor = a.getColor(R.styleable.MonthView_monthWeekdayBackground, Color.parseColor("#f0f0f0"));
mMonthCellColor = a.getColor(R.styleable.MonthView_monthCellColor, Color.parseColor("#eeeeee"));
mMonthTextColor = a.getColor(R.styleable.MonthView_monthTextColor, Color.parseColor("#eeeeee"));
mOtherMonthCellColor = a.getColor(R.styleable.MonthView_otherMonthCellColor, Color.parseColor("#000000"));
mOtherMonthTextColor = a.getColor(R.styleable.MonthView_otherMonthTextColor, Color.parseColor("#aaaaaa"));
mTodayColor = a.getColor(R.styleable.MonthView_monthTodayColor, Color.parseColor("#fffdd0"));
mEventColor = a.getColor(R.styleable.MonthView_monthEventColor, Color.parseColor("#ff0000"));
mCurrentTimeColor = a.getColor(R.styleable.MonthView_monthCurrentTimeColor, Color.parseColor("#0000ff"));
mAddEventBtnResId = a.getResourceId(R.styleable.MonthView_monthAddEventBtn, R.drawable.ic_add_white);
} finally {
a.recycle();
}
init();
}
private void init() {
mStartDate = Calendar.getInstance();
mStartDate.set(Calendar.DAY_OF_MONTH, 1);
mMonthFragmentList = new ArrayList<>();
for (int i = 0; i < Constants.MAX_PAGE_NUMBER; i++) {
mMonthFragmentList.add(i, null);
}
mViewPager = (ViewPager) findViewById(R.id.week_view_pager);
MonthPagerAdapter mPagerAdapter = new MonthPagerAdapter();
mViewPager.setAdapter(mPagerAdapter);
mViewPager.setCurrentItem(Constants.MAX_PAGE_NUMBER / 2, false);
}
public void setEventList(ArrayList<Event> eventList) {
this.mEventList = eventList;
}
public void refresh() {
SingleMonthPage fragment = mMonthFragmentList.get(mViewPager.getCurrentItem());
if (fragment != null) {
fragment.refresh();
}
}
public void setEventClickListener(EventClickListener eventClickListener) {
this.mEventClickListener = eventClickListener;
}
public void setAddEventListener(AddEventListener addEventListener) {
this.mAddEventListener = addEventListener;
}
public void goToToday() {
mViewPager.setCurrentItem(Constants.MAX_PAGE_NUMBER / 2, true);
}
private class MonthPagerAdapter extends PagerAdapter {
@Override
public int getCount() {
return mMonthFragmentList.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
SingleMonthPage page = new SingleMonthPage(mContext);
Calendar startOfMonth = (Calendar) mStartDate.clone();
startOfMonth.add(Calendar.MONTH, (position - Constants.MAX_PAGE_NUMBER / 2));
startOfMonth.set(Calendar.DAY_OF_MONTH, 1);
if (startOfMonth.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
int dayGap = startOfMonth.get(Calendar.DAY_OF_WEEK) - Calendar.MONDAY;
dayGap = dayGap < 0 ? 7 + dayGap: dayGap;
startOfMonth.add(Calendar.DAY_OF_YEAR, -dayGap);
}
Bundle bundle = new Bundle();
bundle.putSerializable(Constants.KEY_START_DATE, startOfMonth);
bundle.putParcelableArrayList(Constants.KEY_EVENT_LIST, mEventList);
bundle.putInt(Constants.KEY_AXIS_COLOR, mAxisColor);
bundle.putInt(Constants.KEY_WEEKDAY_BG_COLOR, mWeekdayBgColor);
bundle.putInt(Constants.KEY_MONTH_CELL_COLOR, mMonthCellColor);
bundle.putInt(Constants.KEY_MONTH_TEXT_COLOR, mMonthTextColor);
bundle.putInt(Constants.KEY_OTHER_MONTH_CELL_COLOR, mOtherMonthCellColor);
bundle.putInt(Constants.KEY_OTHER_MONTH_CELL_TEXT_COLOR, mOtherMonthTextColor);
bundle.putInt(Constants.KEY_TODAY_COLOR, mTodayColor);
bundle.putInt(Constants.KEY_EVENT_COLOR, mEventColor);
bundle.putInt(Constants.KEY_CURREENT_TIME_COLOR, mCurrentTimeColor);
bundle.putInt(Constants.KEY_ADD_EVENT_BTN_RES_ID, mAddEventBtnResId);
page.init(bundle, mAddEventListener, mEventClickListener);
mMonthFragmentList.set(position, page);
container.addView(page);
return page;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(mMonthFragmentList.get(position));
}
}
}
|
9239547d214b43cbb40da3135f4bd186d4248c6d | 81 | java | Java | jevents-cg/src/test/java/net/davidtanzer/jevents/DoSomething.java | sempmessaging/semp | ae0807c95cbc6dbacd38f68f29e3a1d5b9df5ffb | [
"Apache-2.0"
] | null | null | null | jevents-cg/src/test/java/net/davidtanzer/jevents/DoSomething.java | sempmessaging/semp | ae0807c95cbc6dbacd38f68f29e3a1d5b9df5ffb | [
"Apache-2.0"
] | null | null | null | jevents-cg/src/test/java/net/davidtanzer/jevents/DoSomething.java | sempmessaging/semp | ae0807c95cbc6dbacd38f68f29e3a1d5b9df5ffb | [
"Apache-2.0"
] | null | null | null | 13.5 | 32 | 0.765432 | 998,787 | package net.davidtanzer.jevents;
public interface DoSomething {
void doIt();
}
|
9239562d108626a00691c2263fff113ad93f6bdf | 904 | java | Java | src/main/java/ffffffff0x/beryenigma/App/View/Modules/Tools/TextEdit/TextReplace/TextReplaceController.java | istoliving/BerylEnigma | 02dd3d13b238b89a64d121dace9683fc392b1ed9 | [
"MIT"
] | 259 | 2021-01-27T13:15:47.000Z | 2022-03-29T06:32:20.000Z | src/main/java/ffffffff0x/beryenigma/App/View/Modules/Tools/TextEdit/TextReplace/TextReplaceController.java | istoliving/BerylEnigma | 02dd3d13b238b89a64d121dace9683fc392b1ed9 | [
"MIT"
] | 8 | 2021-02-01T07:19:24.000Z | 2021-12-30T08:16:15.000Z | src/main/java/ffffffff0x/beryenigma/App/View/Modules/Tools/TextEdit/TextReplace/TextReplaceController.java | AlexRogalskiy/BerylEnigma | d40e8885c825f4f140fbf99491e0710e72d65a3d | [
"MIT"
] | 46 | 2021-04-13T13:56:29.000Z | 2022-03-26T06:21:29.000Z | 32.285714 | 129 | 0.740044 | 998,788 | package ffffffff0x.beryenigma.App.View.Modules.Tools.TextEdit.TextReplace;
import ffffffff0x.beryenigma.Kit.Utils.ViewUtils;
import ffffffff0x.beryenigma.App.Controller.Tools.TextEdit.TextReplace.TextEdit_TextReplace;
import ffffffff0x.beryenigma.App.View.Viewobj.ViewController;
import com.jfoenix.controls.JFXTextArea;
import javafx.fxml.FXML;
public class TextReplaceController extends ViewController {
@FXML private JFXTextArea JTA_oldString;
@FXML private JFXTextArea JTA_newString;
@Override
protected void initialize() {
super.initialize();
}
@Override
public void ONClickConfirm() {
super.ONClickConfirm();
try {
JTA_dst.setText(TextEdit_TextReplace.TextReplace(JTA_src.getText(),JTA_oldString.getText(),JTA_newString.getText()));
}catch (Exception e){
ViewUtils.textAreaValidate(JTA_dst);
}
}
}
|
9239563d9e9e371a63f8a170fe899f1ffbc5e3f0 | 3,988 | java | Java | dspace-api/src/main/java/org/dspace/identifier/doi/DOIConnector.java | clairtonluz/DSpace | 1db8e382d574234d0444ab90b4a02d34917ec12f | [
"BSD-3-Clause"
] | 541 | 2015-01-08T17:28:08.000Z | 2022-03-28T07:16:48.000Z | dspace-api/src/main/java/org/dspace/identifier/doi/DOIConnector.java | clairtonluz/DSpace | 1db8e382d574234d0444ab90b4a02d34917ec12f | [
"BSD-3-Clause"
] | 2,364 | 2015-01-02T16:39:38.000Z | 2022-03-31T21:04:54.000Z | dspace-api/src/main/java/org/dspace/identifier/doi/DOIConnector.java | clairtonluz/DSpace | 1db8e382d574234d0444ab90b4a02d34917ec12f | [
"BSD-3-Clause"
] | 973 | 2015-01-09T15:12:13.000Z | 2022-03-29T23:41:13.000Z | 40.282828 | 110 | 0.710883 | 998,789 | /**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.identifier.doi;
import org.dspace.content.DSpaceObject;
import org.dspace.core.Context;
/**
* A DOIConnector handles all calls to the API of your DOI registry.
*
* A DOIConnector should care about rules of the registration agency. For
* example, if the registration agency wants us to reserve a DOI before we can
* register it, the DOIConnector should check if a DOI is reserved. Use a
* {@link org.dspace.identifier.doi.DOIIdentifierException#DOIIdentifierException DOIIdentifierException}.
* and set its error code in case of any errors.
* For the given example you should use
* {@code DOIIdentifierException.RESERVE_FIRST} as error code.
*
* @author Pascal-Nicolas Becker
*/
public interface DOIConnector {
public boolean isDOIReserved(Context context, String doi)
throws DOIIdentifierException;
public boolean isDOIRegistered(Context context, String doi)
throws DOIIdentifierException;
/**
* Sends the DELETE-Request to the DOI registry.
*
* <p>This method sends a request to "delete" a DOI. As DOIs are persistent
* identifiers they should never be deleted. For example, if you send a HTTP
* DELETE request to the DataCite Metadata API directly, it will set the DOI
* to inactive.</p>
*
* @param context The relevant DSpace Context.
* @param doi DOI string to "delete"
* @throws DOIIdentifierException if DOI error
*/
public void deleteDOI(Context context, String doi)
throws DOIIdentifierException;
/**
* Sends a request to the DOI registry to reserve a DOI.
*
* The DOIConnector should check weather this DOI is reserved for another
* object already. In this case it should throw an
* {@link org.dspace.identifier.doi.DOIIdentifierException#DOIIdentifierException DOIIdentifierException}.
* DOIIdentifierException} and set the error code to {@code
* DOIIdentifierException.DOI_ALREADY_EXISTS}.
*
* @param context The relevant DSpace Context.
* @param dso DSpace object to associate to the DOI
* @param doi DOI string to reserve
* @throws DOIIdentifierException if DOI error
*/
public void reserveDOI(Context context, DSpaceObject dso, String doi)
throws DOIIdentifierException;
/**
* Sends a request to the DOI registry to register a DOI.
*
* The DOIConnector ensures compliance with the workflow of the registration
* agency. For example, if a DOI has to be reserved before it can be
* registered the DOIConnector has to check if it is reserved. In this case
* you can throw an
* {@link org.dspace.identifier.doi.DOIIdentifierException#DOIIdentifierException DOIIdentifierException}.
* and set the error code to
* {@code DOIIdentifierException.RESERVE_FIRST}.
*
* @param context The relevant DSpace Context.
* @param dso DSpace object to associate to the DOI
* @param doi DOI string to register
* @throws DOIIdentifierException if DOI error
*/
public void registerDOI(Context context, DSpaceObject dso, String doi)
throws DOIIdentifierException;
/**
* Sends a request to the DOI registry to update metadata for a DOI.
*
* The DOIConnector should check weather the DOI is reserved or registered
* for the specified DSpace Object before it sends the metadata update.
*
* @param context The relevant DSpace Context.
* @param dso DSpace object associated to the DOI
* @param doi DOI string to update (metadata)
* @throws DOIIdentifierException if DOI error
*/
public void updateMetadata(Context context, DSpaceObject dso, String doi)
throws DOIIdentifierException;
}
|
923956a83dcf64fb62fa6248d1263cb141e60473 | 595 | java | Java | src/main/java/com/lgmrszd/compressedcreativity/index/CCCommonUpgradeHandlers.java | Lgmrszd/CompressedCreativity | c66802f6e76375f0c02c7514b7ea8b321c5f24b9 | [
"MIT"
] | 4 | 2021-12-15T19:35:04.000Z | 2022-03-07T01:09:18.000Z | src/main/java/com/lgmrszd/compressedcreativity/index/CCCommonUpgradeHandlers.java | Lgmrszd/CompressedCreativity | c66802f6e76375f0c02c7514b7ea8b321c5f24b9 | [
"MIT"
] | 2 | 2021-11-23T01:33:44.000Z | 2021-11-25T09:35:50.000Z | src/main/java/com/lgmrszd/compressedcreativity/index/CCCommonUpgradeHandlers.java | Lgmrszd/CompressedCreativity | c66802f6e76375f0c02c7514b7ea8b321c5f24b9 | [
"MIT"
] | null | null | null | 37.1875 | 92 | 0.815126 | 998,790 | package com.lgmrszd.compressedcreativity.index;
import com.lgmrszd.compressedcreativity.upgrades.MechanicalVisorHandler;
// TODO use API
import me.desht.pneumaticcraft.api.PneumaticRegistry;
import me.desht.pneumaticcraft.api.pneumatic_armor.ICommonArmorRegistry;
public class CCCommonUpgradeHandlers {
public static MechanicalVisorHandler mechanicalVisorHandler;
public static void init() {
ICommonArmorRegistry reg = PneumaticRegistry.getInstance().getCommonArmorRegistry();
mechanicalVisorHandler = reg.registerUpgradeHandler(new MechanicalVisorHandler());
}
}
|
923956f02319e858476756fc1c5a4ef92d7f798b | 2,595 | java | Java | support/cas-server-support-passwordless-mongo/src/main/java/org/apereo/cas/config/MongoDbPasswordlessAuthenticationConfiguration.java | qxo/cas | 044f30b460d4125f98e5fa58294cd824786ed42f | [
"Apache-2.0"
] | 8,772 | 2016-05-08T04:44:50.000Z | 2022-03-31T06:02:13.000Z | support/cas-server-support-passwordless-mongo/src/main/java/org/apereo/cas/config/MongoDbPasswordlessAuthenticationConfiguration.java | qxo/cas | 044f30b460d4125f98e5fa58294cd824786ed42f | [
"Apache-2.0"
] | 2,911 | 2016-05-07T23:07:52.000Z | 2022-03-31T15:09:08.000Z | support/cas-server-support-passwordless-mongo/src/main/java/org/apereo/cas/config/MongoDbPasswordlessAuthenticationConfiguration.java | jasonjxsu/cas | 4a86423ca2f4e658ce1b2af35b246da24ac55cec | [
"Apache-2.0"
] | 3,675 | 2016-05-08T04:45:46.000Z | 2022-03-31T09:34:54.000Z | 47.181818 | 120 | 0.813487 | 998,791 | package org.apereo.cas.config;
import org.apereo.cas.api.PasswordlessUserAccountStore;
import org.apereo.cas.authentication.CasSSLContext;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.impl.account.MongoDbPasswordlessUserAccountStore;
import org.apereo.cas.mongo.MongoDbConnectionFactory;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.data.mongodb.core.MongoTemplate;
/**
* This is {@link MongoDbPasswordlessAuthenticationConfiguration}.
*
* @author Misagh Moayyed
* @since 6.2.0
*/
@Configuration(value = "mongoDbPasswordlessAuthenticationConfiguration", proxyBeanMethods = false)
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class MongoDbPasswordlessAuthenticationConfiguration {
@ConditionalOnMissingBean(name = "mongoDbPasswordlessAuthenticationTemplate")
@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
@Autowired
public MongoTemplate mongoDbPasswordlessAuthenticationTemplate(
final CasConfigurationProperties casProperties,
@Qualifier("casSslContext")
final CasSSLContext casSslContext) {
val mongo = casProperties.getAuthn().getPasswordless().getAccounts().getMongo();
val factory = new MongoDbConnectionFactory(casSslContext.getSslContext());
val mongoTemplate = factory.buildMongoTemplate(mongo);
MongoDbConnectionFactory.createCollection(mongoTemplate, mongo.getCollection(), mongo.isDropCollection());
return mongoTemplate;
}
@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
@Autowired
public PasswordlessUserAccountStore passwordlessUserAccountStore(
@Qualifier("mongoDbPasswordlessAuthenticationTemplate")
final MongoTemplate mongoDbPasswordlessAuthenticationTemplate, final CasConfigurationProperties casProperties) {
val accounts = casProperties.getAuthn().getPasswordless().getAccounts();
return new MongoDbPasswordlessUserAccountStore(mongoDbPasswordlessAuthenticationTemplate, accounts.getMongo());
}
}
|
92395784ba342f1b855bc999af213646f0cba4a3 | 1,409 | java | Java | integration-tests/cse-v1/provider/src/main/java/com/huaweicloud/samples/ProviderController.java | hujinming178/spring-cloud-huawei | 53aa3bcf32a960d05d975312e3d5e4803ea3cb05 | [
"Apache-2.0"
] | null | null | null | integration-tests/cse-v1/provider/src/main/java/com/huaweicloud/samples/ProviderController.java | hujinming178/spring-cloud-huawei | 53aa3bcf32a960d05d975312e3d5e4803ea3cb05 | [
"Apache-2.0"
] | null | null | null | integration-tests/cse-v1/provider/src/main/java/com/huaweicloud/samples/ProviderController.java | hujinming178/spring-cloud-huawei | 53aa3bcf32a960d05d975312e3d5e4803ea3cb05 | [
"Apache-2.0"
] | null | null | null | 33.547619 | 78 | 0.738822 | 998,792 | /*
* Copyright (C) 2020-2022 Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.huaweicloud.samples;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProviderController {
// a very simple service to echo the request parameter
@GetMapping("/sayHello")
public String sayHello(@RequestParam("name") String name) {
return "Hello " + name;
}
@GetMapping("/sayHelloCanary")
public String sayHelloCanary(@RequestParam("name") String name) {
return "Hello Canary " + name;
}
@GetMapping("/gateway/sayHelloCanary")
public String gatewaySayHelloCanary(@RequestParam("name") String name) {
return "Hello Gateway Canary " + name;
}
}
|
9239582cddcda8ba2c509d4f01675650d15895ac | 1,506 | java | Java | subdomains/excel/fixture/src/main/java/org/apache/isis/subdomains/excel/fixtures/demoapp/demomodule/contributions/ExcelDemoToDoItem_export.java | h2000/isis | 0606b7fcdfe83910e17b3cd143e8397f1ccf12c5 | [
"Apache-2.0"
] | null | null | null | subdomains/excel/fixture/src/main/java/org/apache/isis/subdomains/excel/fixtures/demoapp/demomodule/contributions/ExcelDemoToDoItem_export.java | h2000/isis | 0606b7fcdfe83910e17b3cd143e8397f1ccf12c5 | [
"Apache-2.0"
] | null | null | null | subdomains/excel/fixture/src/main/java/org/apache/isis/subdomains/excel/fixtures/demoapp/demomodule/contributions/ExcelDemoToDoItem_export.java | h2000/isis | 0606b7fcdfe83910e17b3cd143e8397f1ccf12c5 | [
"Apache-2.0"
] | null | null | null | 36.731707 | 137 | 0.747012 | 998,793 | package org.apache.isis.subdomains.excel.fixtures.demoapp.demomodule.contributions;
import javax.inject.Inject;
import org.apache.isis.applib.annotation.Action;
import org.apache.isis.applib.annotation.ActionLayout;
import org.apache.isis.applib.annotation.Contributed;
import org.apache.isis.applib.annotation.Mixin;
import org.apache.isis.applib.value.Blob;
import org.apache.isis.subdomains.excel.applib.dom.ExcelService;
import org.apache.isis.subdomains.excel.fixtures.demoapp.todomodule.dom.ExcelDemoToDoItem;
import org.apache.isis.subdomains.excel.fixtures.demoapp.todomodule.dom.ExcelDemoToDoItemMenu;
@Mixin(method = "act")
public class ExcelDemoToDoItem_export {
private final ExcelDemoToDoItem toDoItem;
public ExcelDemoToDoItem_export(final ExcelDemoToDoItem toDoItem) {
this.toDoItem = toDoItem;
}
@Action
@ActionLayout(contributed = Contributed.AS_ACTION)
@SuppressWarnings({ "unchecked", "rawtypes" })
public Blob act() {
throw new UnsupportedOperationException();
// if(actionInvocationContext.isLast()) {
// // ie current object only
// final List toDoItems = actionInvocationContext.getDomainObjects();
// return excelService.toExcel(toDoItems, ExcelDemoToDoItem.class, ExcelDemoToDoItem.class.getSimpleName(), "toDoItems.xlsx");
// } else {
// return null;
// }
}
@Inject ExcelService excelService;
@Inject ExcelDemoToDoItemMenu excelModuleDemoToDoItems;
}
|
923958c3a6d9b087e76c1d75eccdd152c84d63b0 | 49,347 | java | Java | EvaluatorMVC/APKDecompile/jd-core/sample/android/support/v4/app/BackStackRecord.java | neerajmathur/UMETRIX | cea997db250152d843d8d0adc8e20df2c25023d4 | [
"Apache-2.0"
] | 1 | 2021-05-17T15:36:26.000Z | 2021-05-17T15:36:26.000Z | EvaluatorMVC/APKDecompile/jd-core/sample/android/support/v4/app/BackStackRecord.java | neerajmathur/UMETRIX | cea997db250152d843d8d0adc8e20df2c25023d4 | [
"Apache-2.0"
] | null | null | null | EvaluatorMVC/APKDecompile/jd-core/sample/android/support/v4/app/BackStackRecord.java | neerajmathur/UMETRIX | cea997db250152d843d8d0adc8e20df2c25023d4 | [
"Apache-2.0"
] | 2 | 2018-05-27T14:52:14.000Z | 2019-05-16T06:04:03.000Z | 33.275118 | 393 | 0.661925 | 998,794 | package android.support.v4.app;
import android.content.Context;
import android.os.Build.VERSION;
import android.support.v4.util.ArrayMap;
import android.support.v4.util.LogWriter;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
final class BackStackRecord
extends FragmentTransaction
implements FragmentManager.BackStackEntry, Runnable
{
static final int OP_ADD = 1;
static final int OP_ATTACH = 7;
static final int OP_DETACH = 6;
static final int OP_HIDE = 4;
static final int OP_NULL = 0;
static final int OP_REMOVE = 3;
static final int OP_REPLACE = 2;
static final int OP_SHOW = 5;
static final boolean SUPPORTS_TRANSITIONS;
static final String TAG = "FragmentManager";
boolean mAddToBackStack;
boolean mAllowAddToBackStack = true;
int mBreadCrumbShortTitleRes;
CharSequence mBreadCrumbShortTitleText;
int mBreadCrumbTitleRes;
CharSequence mBreadCrumbTitleText;
boolean mCommitted;
int mEnterAnim;
int mExitAnim;
Op mHead;
int mIndex = -1;
final FragmentManagerImpl mManager;
String mName;
int mNumOp;
int mPopEnterAnim;
int mPopExitAnim;
ArrayList<String> mSharedElementSourceNames;
ArrayList<String> mSharedElementTargetNames;
Op mTail;
int mTransition;
int mTransitionStyle;
static
{
if (Build.VERSION.SDK_INT >= 21) {}
for (boolean bool = true;; bool = false)
{
SUPPORTS_TRANSITIONS = bool;
return;
}
}
public BackStackRecord(FragmentManagerImpl paramFragmentManagerImpl)
{
this.mManager = paramFragmentManagerImpl;
}
private TransitionState beginTransition(SparseArray<Fragment> paramSparseArray1, SparseArray<Fragment> paramSparseArray2, boolean paramBoolean)
{
TransitionState localTransitionState = new TransitionState();
localTransitionState.nonExistentView = new View(this.mManager.mHost.getContext());
int i = 0;
int j = 0;
while (j < paramSparseArray1.size())
{
if (configureTransitions(paramSparseArray1.keyAt(j), localTransitionState, paramBoolean, paramSparseArray1, paramSparseArray2)) {
i = 1;
}
j += 1;
}
j = 0;
while (j < paramSparseArray2.size())
{
int m = paramSparseArray2.keyAt(j);
int k = i;
if (paramSparseArray1.get(m) == null)
{
k = i;
if (configureTransitions(m, localTransitionState, paramBoolean, paramSparseArray1, paramSparseArray2)) {
k = 1;
}
}
j += 1;
i = k;
}
paramSparseArray1 = localTransitionState;
if (i == 0) {
paramSparseArray1 = null;
}
return paramSparseArray1;
}
private void calculateFragments(SparseArray<Fragment> paramSparseArray1, SparseArray<Fragment> paramSparseArray2)
{
if (!this.mManager.mContainer.onHasView()) {}
Op localOp;
do
{
return;
localOp = this.mHead;
} while (localOp == null);
switch (localOp.cmd)
{
}
for (;;)
{
localOp = localOp.next;
break;
setLastIn(paramSparseArray1, paramSparseArray2, localOp.fragment);
continue;
Object localObject1 = localOp.fragment;
if (this.mManager.mAdded != null)
{
int i = 0;
if (i < this.mManager.mAdded.size())
{
Fragment localFragment = (Fragment)this.mManager.mAdded.get(i);
Object localObject2;
if (localObject1 != null)
{
localObject2 = localObject1;
if (localFragment.mContainerId != ((Fragment)localObject1).mContainerId) {}
}
else
{
if (localFragment != localObject1) {
break label197;
}
localObject2 = null;
paramSparseArray2.remove(localFragment.mContainerId);
}
for (;;)
{
i += 1;
localObject1 = localObject2;
break;
label197:
setFirstOut(paramSparseArray1, paramSparseArray2, localFragment);
localObject2 = localObject1;
}
}
}
setLastIn(paramSparseArray1, paramSparseArray2, localOp.fragment);
continue;
setFirstOut(paramSparseArray1, paramSparseArray2, localOp.fragment);
continue;
setFirstOut(paramSparseArray1, paramSparseArray2, localOp.fragment);
continue;
setLastIn(paramSparseArray1, paramSparseArray2, localOp.fragment);
continue;
setFirstOut(paramSparseArray1, paramSparseArray2, localOp.fragment);
continue;
setLastIn(paramSparseArray1, paramSparseArray2, localOp.fragment);
}
}
private void callSharedElementEnd(TransitionState paramTransitionState, Fragment paramFragment1, Fragment paramFragment2, boolean paramBoolean, ArrayMap<String, View> paramArrayMap)
{
if (paramBoolean) {}
for (paramTransitionState = paramFragment2.mEnterTransitionCallback;; paramTransitionState = paramFragment1.mEnterTransitionCallback)
{
if (paramTransitionState != null) {
paramTransitionState.onSharedElementEnd(new ArrayList(paramArrayMap.keySet()), new ArrayList(paramArrayMap.values()), null);
}
return;
}
}
private static Object captureExitingViews(Object paramObject, Fragment paramFragment, ArrayList<View> paramArrayList, ArrayMap<String, View> paramArrayMap, View paramView)
{
Object localObject = paramObject;
if (paramObject != null) {
localObject = FragmentTransitionCompat21.captureExitingViews(paramObject, paramFragment.getView(), paramArrayList, paramArrayMap, paramView);
}
return localObject;
}
private boolean configureTransitions(int paramInt, TransitionState paramTransitionState, boolean paramBoolean, SparseArray<Fragment> paramSparseArray1, SparseArray<Fragment> paramSparseArray2)
{
ViewGroup localViewGroup = (ViewGroup)this.mManager.mContainer.onFindViewById(paramInt);
if (localViewGroup == null) {
return false;
}
Object localObject3 = (Fragment)paramSparseArray2.get(paramInt);
Object localObject5 = (Fragment)paramSparseArray1.get(paramInt);
Object localObject4 = getEnterTransition((Fragment)localObject3, paramBoolean);
Object localObject1 = getSharedElementTransition((Fragment)localObject3, (Fragment)localObject5, paramBoolean);
Object localObject6 = getExitTransition((Fragment)localObject5, paramBoolean);
paramSparseArray1 = null;
ArrayList localArrayList = new ArrayList();
paramSparseArray2 = (SparseArray<Fragment>)localObject1;
if (localObject1 != null)
{
localObject2 = remapSharedElements(paramTransitionState, (Fragment)localObject5, paramBoolean);
if (((ArrayMap)localObject2).isEmpty())
{
paramSparseArray2 = null;
paramSparseArray1 = null;
}
}
else
{
if ((localObject4 != null) || (paramSparseArray2 != null) || (localObject6 != null)) {
break label220;
}
return false;
}
if (paramBoolean) {}
for (paramSparseArray1 = ((Fragment)localObject5).mEnterTransitionCallback;; paramSparseArray1 = ((Fragment)localObject3).mEnterTransitionCallback)
{
if (paramSparseArray1 != null) {
paramSparseArray1.onSharedElementStart(new ArrayList(((ArrayMap)localObject2).keySet()), new ArrayList(((ArrayMap)localObject2).values()), null);
}
prepareSharedElementTransition(paramTransitionState, localViewGroup, localObject1, (Fragment)localObject3, (Fragment)localObject5, paramBoolean, localArrayList, localObject4, localObject6);
paramSparseArray2 = (SparseArray<Fragment>)localObject1;
paramSparseArray1 = (SparseArray<Fragment>)localObject2;
break;
}
label220:
localObject1 = new ArrayList();
Object localObject2 = captureExitingViews(localObject6, (Fragment)localObject5, (ArrayList)localObject1, paramSparseArray1, paramTransitionState.nonExistentView);
if ((this.mSharedElementTargetNames != null) && (paramSparseArray1 != null))
{
localObject5 = (View)paramSparseArray1.get(this.mSharedElementTargetNames.get(0));
if (localObject5 != null)
{
if (localObject2 != null) {
FragmentTransitionCompat21.setEpicenter(localObject2, (View)localObject5);
}
if (paramSparseArray2 != null) {
FragmentTransitionCompat21.setEpicenter(paramSparseArray2, (View)localObject5);
}
}
}
localObject5 = new FragmentTransitionCompat21.ViewRetriever()
{
public View getView()
{
return this.val$inFragment.getView();
}
};
localObject6 = new ArrayList();
ArrayMap localArrayMap = new ArrayMap();
boolean bool = true;
if (localObject3 != null) {
if (!paramBoolean) {
break label478;
}
}
label478:
for (bool = ((Fragment)localObject3).getAllowReturnTransitionOverlap();; bool = ((Fragment)localObject3).getAllowEnterTransitionOverlap())
{
localObject3 = FragmentTransitionCompat21.mergeTransitions(localObject4, localObject2, paramSparseArray2, bool);
if (localObject3 != null)
{
FragmentTransitionCompat21.addTransitionTargets(localObject4, paramSparseArray2, localObject2, localViewGroup, (FragmentTransitionCompat21.ViewRetriever)localObject5, paramTransitionState.nonExistentView, paramTransitionState.enteringEpicenterView, paramTransitionState.nameOverrides, (ArrayList)localObject6, (ArrayList)localObject1, paramSparseArray1, localArrayMap, localArrayList);
excludeHiddenFragmentsAfterEnter(localViewGroup, paramTransitionState, paramInt, localObject3);
FragmentTransitionCompat21.excludeTarget(localObject3, paramTransitionState.nonExistentView, true);
excludeHiddenFragments(paramTransitionState, paramInt, localObject3);
FragmentTransitionCompat21.beginDelayedTransition(localViewGroup, localObject3);
FragmentTransitionCompat21.cleanupTransitions(localViewGroup, paramTransitionState.nonExistentView, localObject4, (ArrayList)localObject6, localObject2, (ArrayList)localObject1, paramSparseArray2, localArrayList, localObject3, paramTransitionState.hiddenFragmentViews, localArrayMap);
}
if (localObject3 == null) {
break;
}
return true;
}
return false;
}
private void doAddOp(int paramInt1, Fragment paramFragment, String paramString, int paramInt2)
{
Class localClass = paramFragment.getClass();
int i = localClass.getModifiers();
if ((localClass.isAnonymousClass()) || (!Modifier.isPublic(i)) || ((localClass.isMemberClass()) && (!Modifier.isStatic(i)))) {
throw new IllegalStateException("Fragment " + localClass.getCanonicalName() + " must be a public static class to be properly recreated from" + " instance state.");
}
paramFragment.mFragmentManager = this.mManager;
if (paramString != null)
{
if ((paramFragment.mTag != null) && (!paramString.equals(paramFragment.mTag))) {
throw new IllegalStateException("Can't change tag of fragment " + paramFragment + ": was " + paramFragment.mTag + " now " + paramString);
}
paramFragment.mTag = paramString;
}
if (paramInt1 != 0)
{
if (paramInt1 == -1) {
throw new IllegalArgumentException("Can't add fragment " + paramFragment + " with tag " + paramString + " to container view with no id");
}
if ((paramFragment.mFragmentId != 0) && (paramFragment.mFragmentId != paramInt1)) {
throw new IllegalStateException("Can't change container ID of fragment " + paramFragment + ": was " + paramFragment.mFragmentId + " now " + paramInt1);
}
paramFragment.mFragmentId = paramInt1;
paramFragment.mContainerId = paramInt1;
}
paramString = new Op();
paramString.cmd = paramInt2;
paramString.fragment = paramFragment;
addOp(paramString);
}
private void excludeHiddenFragments(TransitionState paramTransitionState, int paramInt, Object paramObject)
{
if (this.mManager.mAdded != null)
{
int i = 0;
if (i < this.mManager.mAdded.size())
{
Fragment localFragment = (Fragment)this.mManager.mAdded.get(i);
if ((localFragment.mView != null) && (localFragment.mContainer != null) && (localFragment.mContainerId == paramInt))
{
if (!localFragment.mHidden) {
break label125;
}
if (!paramTransitionState.hiddenFragmentViews.contains(localFragment.mView))
{
FragmentTransitionCompat21.excludeTarget(paramObject, localFragment.mView, true);
paramTransitionState.hiddenFragmentViews.add(localFragment.mView);
}
}
for (;;)
{
i += 1;
break;
label125:
FragmentTransitionCompat21.excludeTarget(paramObject, localFragment.mView, false);
paramTransitionState.hiddenFragmentViews.remove(localFragment.mView);
}
}
}
}
private void excludeHiddenFragmentsAfterEnter(final View paramView, final TransitionState paramTransitionState, final int paramInt, final Object paramObject)
{
paramView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
{
public boolean onPreDraw()
{
paramView.getViewTreeObserver().removeOnPreDrawListener(this);
BackStackRecord.this.excludeHiddenFragments(paramTransitionState, paramInt, paramObject);
return true;
}
});
}
private static Object getEnterTransition(Fragment paramFragment, boolean paramBoolean)
{
if (paramFragment == null) {
return null;
}
if (paramBoolean) {}
for (paramFragment = paramFragment.getReenterTransition();; paramFragment = paramFragment.getEnterTransition()) {
return FragmentTransitionCompat21.cloneTransition(paramFragment);
}
}
private static Object getExitTransition(Fragment paramFragment, boolean paramBoolean)
{
if (paramFragment == null) {
return null;
}
if (paramBoolean) {}
for (paramFragment = paramFragment.getReturnTransition();; paramFragment = paramFragment.getExitTransition()) {
return FragmentTransitionCompat21.cloneTransition(paramFragment);
}
}
private static Object getSharedElementTransition(Fragment paramFragment1, Fragment paramFragment2, boolean paramBoolean)
{
if ((paramFragment1 == null) || (paramFragment2 == null)) {
return null;
}
if (paramBoolean) {}
for (paramFragment1 = paramFragment2.getSharedElementReturnTransition();; paramFragment1 = paramFragment1.getSharedElementEnterTransition()) {
return FragmentTransitionCompat21.wrapSharedElementTransition(paramFragment1);
}
}
private ArrayMap<String, View> mapEnteringSharedElements(TransitionState paramTransitionState, Fragment paramFragment, boolean paramBoolean)
{
ArrayMap localArrayMap = new ArrayMap();
paramFragment = paramFragment.getView();
paramTransitionState = localArrayMap;
if (paramFragment != null)
{
paramTransitionState = localArrayMap;
if (this.mSharedElementSourceNames != null)
{
FragmentTransitionCompat21.findNamedViews(localArrayMap, paramFragment);
if (!paramBoolean) {
break label57;
}
paramTransitionState = remapNames(this.mSharedElementSourceNames, this.mSharedElementTargetNames, localArrayMap);
}
}
return paramTransitionState;
label57:
localArrayMap.retainAll(this.mSharedElementTargetNames);
return localArrayMap;
}
private ArrayMap<String, View> mapSharedElementsIn(TransitionState paramTransitionState, boolean paramBoolean, Fragment paramFragment)
{
ArrayMap localArrayMap = mapEnteringSharedElements(paramTransitionState, paramFragment, paramBoolean);
if (paramBoolean)
{
if (paramFragment.mExitTransitionCallback != null) {
paramFragment.mExitTransitionCallback.onMapSharedElements(this.mSharedElementTargetNames, localArrayMap);
}
setBackNameOverrides(paramTransitionState, localArrayMap, true);
return localArrayMap;
}
if (paramFragment.mEnterTransitionCallback != null) {
paramFragment.mEnterTransitionCallback.onMapSharedElements(this.mSharedElementTargetNames, localArrayMap);
}
setNameOverrides(paramTransitionState, localArrayMap, true);
return localArrayMap;
}
private void prepareSharedElementTransition(final TransitionState paramTransitionState, final View paramView, final Object paramObject1, final Fragment paramFragment1, final Fragment paramFragment2, final boolean paramBoolean, final ArrayList<View> paramArrayList, final Object paramObject2, final Object paramObject3)
{
if (paramObject1 != null) {
paramView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
{
public boolean onPreDraw()
{
paramView.getViewTreeObserver().removeOnPreDrawListener(this);
FragmentTransitionCompat21.removeTargets(paramObject1, paramArrayList);
paramArrayList.remove(paramTransitionState.nonExistentView);
FragmentTransitionCompat21.excludeSharedElementViews(paramObject2, paramObject3, paramObject1, paramArrayList, false);
paramArrayList.clear();
ArrayMap localArrayMap = BackStackRecord.this.mapSharedElementsIn(paramTransitionState, paramBoolean, paramFragment1);
FragmentTransitionCompat21.setSharedElementTargets(paramObject1, paramTransitionState.nonExistentView, localArrayMap, paramArrayList);
BackStackRecord.this.setEpicenterIn(localArrayMap, paramTransitionState);
BackStackRecord.this.callSharedElementEnd(paramTransitionState, paramFragment1, paramFragment2, paramBoolean, localArrayMap);
FragmentTransitionCompat21.excludeSharedElementViews(paramObject2, paramObject3, paramObject1, paramArrayList, true);
return true;
}
});
}
}
private static ArrayMap<String, View> remapNames(ArrayList<String> paramArrayList1, ArrayList<String> paramArrayList2, ArrayMap<String, View> paramArrayMap)
{
if (paramArrayMap.isEmpty()) {
return paramArrayMap;
}
ArrayMap localArrayMap = new ArrayMap();
int j = paramArrayList1.size();
int i = 0;
while (i < j)
{
View localView = (View)paramArrayMap.get(paramArrayList1.get(i));
if (localView != null) {
localArrayMap.put(paramArrayList2.get(i), localView);
}
i += 1;
}
return localArrayMap;
}
private ArrayMap<String, View> remapSharedElements(TransitionState paramTransitionState, Fragment paramFragment, boolean paramBoolean)
{
ArrayMap localArrayMap2 = new ArrayMap();
ArrayMap localArrayMap1 = localArrayMap2;
if (this.mSharedElementSourceNames != null)
{
FragmentTransitionCompat21.findNamedViews(localArrayMap2, paramFragment.getView());
if (!paramBoolean) {
break label82;
}
localArrayMap2.retainAll(this.mSharedElementTargetNames);
}
label82:
for (localArrayMap1 = localArrayMap2; paramBoolean; localArrayMap1 = remapNames(this.mSharedElementSourceNames, this.mSharedElementTargetNames, localArrayMap2))
{
if (paramFragment.mEnterTransitionCallback != null) {
paramFragment.mEnterTransitionCallback.onMapSharedElements(this.mSharedElementTargetNames, localArrayMap1);
}
setBackNameOverrides(paramTransitionState, localArrayMap1, false);
return localArrayMap1;
}
if (paramFragment.mExitTransitionCallback != null) {
paramFragment.mExitTransitionCallback.onMapSharedElements(this.mSharedElementTargetNames, localArrayMap1);
}
setNameOverrides(paramTransitionState, localArrayMap1, false);
return localArrayMap1;
}
private void setBackNameOverrides(TransitionState paramTransitionState, ArrayMap<String, View> paramArrayMap, boolean paramBoolean)
{
int i;
int j;
label13:
String str;
Object localObject;
if (this.mSharedElementTargetNames == null)
{
i = 0;
j = 0;
if (j >= i) {
return;
}
str = (String)this.mSharedElementSourceNames.get(j);
localObject = (View)paramArrayMap.get((String)this.mSharedElementTargetNames.get(j));
if (localObject != null)
{
localObject = FragmentTransitionCompat21.getTransitionName((View)localObject);
if (!paramBoolean) {
break label103;
}
setNameOverride(paramTransitionState.nameOverrides, str, (String)localObject);
}
}
for (;;)
{
j += 1;
break label13;
i = this.mSharedElementTargetNames.size();
break;
label103:
setNameOverride(paramTransitionState.nameOverrides, (String)localObject, str);
}
}
private void setEpicenterIn(ArrayMap<String, View> paramArrayMap, TransitionState paramTransitionState)
{
if ((this.mSharedElementTargetNames != null) && (!paramArrayMap.isEmpty()))
{
paramArrayMap = (View)paramArrayMap.get(this.mSharedElementTargetNames.get(0));
if (paramArrayMap != null) {
paramTransitionState.enteringEpicenterView.epicenter = paramArrayMap;
}
}
}
private static void setFirstOut(SparseArray<Fragment> paramSparseArray1, SparseArray<Fragment> paramSparseArray2, Fragment paramFragment)
{
if (paramFragment != null)
{
int i = paramFragment.mContainerId;
if ((i != 0) && (!paramFragment.isHidden()))
{
if ((paramFragment.isAdded()) && (paramFragment.getView() != null) && (paramSparseArray1.get(i) == null)) {
paramSparseArray1.put(i, paramFragment);
}
if (paramSparseArray2.get(i) == paramFragment) {
paramSparseArray2.remove(i);
}
}
}
}
private void setLastIn(SparseArray<Fragment> paramSparseArray1, SparseArray<Fragment> paramSparseArray2, Fragment paramFragment)
{
if (paramFragment != null)
{
int i = paramFragment.mContainerId;
if (i != 0)
{
if (!paramFragment.isAdded()) {
paramSparseArray2.put(i, paramFragment);
}
if (paramSparseArray1.get(i) == paramFragment) {
paramSparseArray1.remove(i);
}
}
if ((paramFragment.mState < 1) && (this.mManager.mCurState >= 1))
{
this.mManager.makeActive(paramFragment);
this.mManager.moveToState(paramFragment, 1, 0, 0, false);
}
}
}
private static void setNameOverride(ArrayMap<String, String> paramArrayMap, String paramString1, String paramString2)
{
int i;
if ((paramString1 != null) && (paramString2 != null)) {
i = 0;
}
while (i < paramArrayMap.size())
{
if (paramString1.equals(paramArrayMap.valueAt(i)))
{
paramArrayMap.setValueAt(i, paramString2);
return;
}
i += 1;
}
paramArrayMap.put(paramString1, paramString2);
}
private void setNameOverrides(TransitionState paramTransitionState, ArrayMap<String, View> paramArrayMap, boolean paramBoolean)
{
int j = paramArrayMap.size();
int i = 0;
if (i < j)
{
String str1 = (String)paramArrayMap.keyAt(i);
String str2 = FragmentTransitionCompat21.getTransitionName((View)paramArrayMap.valueAt(i));
if (paramBoolean) {
setNameOverride(paramTransitionState.nameOverrides, str1, str2);
}
for (;;)
{
i += 1;
break;
setNameOverride(paramTransitionState.nameOverrides, str2, str1);
}
}
}
private static void setNameOverrides(TransitionState paramTransitionState, ArrayList<String> paramArrayList1, ArrayList<String> paramArrayList2)
{
if (paramArrayList1 != null)
{
int i = 0;
while (i < paramArrayList1.size())
{
String str1 = (String)paramArrayList1.get(i);
String str2 = (String)paramArrayList2.get(i);
setNameOverride(paramTransitionState.nameOverrides, str1, str2);
i += 1;
}
}
}
public FragmentTransaction add(int paramInt, Fragment paramFragment)
{
doAddOp(paramInt, paramFragment, null, 1);
return this;
}
public FragmentTransaction add(int paramInt, Fragment paramFragment, String paramString)
{
doAddOp(paramInt, paramFragment, paramString, 1);
return this;
}
public FragmentTransaction add(Fragment paramFragment, String paramString)
{
doAddOp(0, paramFragment, paramString, 1);
return this;
}
void addOp(Op paramOp)
{
if (this.mHead == null)
{
this.mTail = paramOp;
this.mHead = paramOp;
}
for (;;)
{
paramOp.enterAnim = this.mEnterAnim;
paramOp.exitAnim = this.mExitAnim;
paramOp.popEnterAnim = this.mPopEnterAnim;
paramOp.popExitAnim = this.mPopExitAnim;
this.mNumOp += 1;
return;
paramOp.prev = this.mTail;
this.mTail.next = paramOp;
this.mTail = paramOp;
}
}
public FragmentTransaction addSharedElement(View paramView, String paramString)
{
if (SUPPORTS_TRANSITIONS)
{
paramView = FragmentTransitionCompat21.getTransitionName(paramView);
if (paramView == null) {
throw new IllegalArgumentException("Unique transitionNames are required for all sharedElements");
}
if (this.mSharedElementSourceNames == null)
{
this.mSharedElementSourceNames = new ArrayList();
this.mSharedElementTargetNames = new ArrayList();
}
this.mSharedElementSourceNames.add(paramView);
this.mSharedElementTargetNames.add(paramString);
}
return this;
}
public FragmentTransaction addToBackStack(String paramString)
{
if (!this.mAllowAddToBackStack) {
throw new IllegalStateException("This FragmentTransaction is not allowed to be added to the back stack.");
}
this.mAddToBackStack = true;
this.mName = paramString;
return this;
}
public FragmentTransaction attach(Fragment paramFragment)
{
Op localOp = new Op();
localOp.cmd = 7;
localOp.fragment = paramFragment;
addOp(localOp);
return this;
}
void bumpBackStackNesting(int paramInt)
{
if (!this.mAddToBackStack) {}
for (;;)
{
return;
if (FragmentManagerImpl.DEBUG) {
Log.v("FragmentManager", "Bump nesting in " + this + " by " + paramInt);
}
for (Op localOp = this.mHead; localOp != null; localOp = localOp.next)
{
Fragment localFragment;
if (localOp.fragment != null)
{
localFragment = localOp.fragment;
localFragment.mBackStackNesting += paramInt;
if (FragmentManagerImpl.DEBUG) {
Log.v("FragmentManager", "Bump nesting of " + localOp.fragment + " to " + localOp.fragment.mBackStackNesting);
}
}
if (localOp.removed != null)
{
int i = localOp.removed.size() - 1;
while (i >= 0)
{
localFragment = (Fragment)localOp.removed.get(i);
localFragment.mBackStackNesting += paramInt;
if (FragmentManagerImpl.DEBUG) {
Log.v("FragmentManager", "Bump nesting of " + localFragment + " to " + localFragment.mBackStackNesting);
}
i -= 1;
}
}
}
}
}
public void calculateBackFragments(SparseArray<Fragment> paramSparseArray1, SparseArray<Fragment> paramSparseArray2)
{
if (!this.mManager.mContainer.onHasView()) {}
Op localOp;
do
{
return;
localOp = this.mTail;
} while (localOp == null);
switch (localOp.cmd)
{
}
for (;;)
{
localOp = localOp.prev;
break;
setFirstOut(paramSparseArray1, paramSparseArray2, localOp.fragment);
continue;
if (localOp.removed != null)
{
int i = localOp.removed.size() - 1;
while (i >= 0)
{
setLastIn(paramSparseArray1, paramSparseArray2, (Fragment)localOp.removed.get(i));
i -= 1;
}
}
setFirstOut(paramSparseArray1, paramSparseArray2, localOp.fragment);
continue;
setLastIn(paramSparseArray1, paramSparseArray2, localOp.fragment);
continue;
setLastIn(paramSparseArray1, paramSparseArray2, localOp.fragment);
continue;
setFirstOut(paramSparseArray1, paramSparseArray2, localOp.fragment);
continue;
setLastIn(paramSparseArray1, paramSparseArray2, localOp.fragment);
continue;
setFirstOut(paramSparseArray1, paramSparseArray2, localOp.fragment);
}
}
public int commit()
{
return commitInternal(false);
}
public int commitAllowingStateLoss()
{
return commitInternal(true);
}
int commitInternal(boolean paramBoolean)
{
if (this.mCommitted) {
throw new IllegalStateException("commit already called");
}
if (FragmentManagerImpl.DEBUG)
{
Log.v("FragmentManager", "Commit: " + this);
dump(" ", null, new PrintWriter(new LogWriter("FragmentManager")), null);
}
this.mCommitted = true;
if (this.mAddToBackStack) {}
for (this.mIndex = this.mManager.allocBackStackIndex(this);; this.mIndex = -1)
{
this.mManager.enqueueAction(this, paramBoolean);
return this.mIndex;
}
}
public void commitNow()
{
disallowAddToBackStack();
this.mManager.execSingleAction(this, false);
}
public void commitNowAllowingStateLoss()
{
disallowAddToBackStack();
this.mManager.execSingleAction(this, true);
}
public FragmentTransaction detach(Fragment paramFragment)
{
Op localOp = new Op();
localOp.cmd = 6;
localOp.fragment = paramFragment;
addOp(localOp);
return this;
}
public FragmentTransaction disallowAddToBackStack()
{
if (this.mAddToBackStack) {
throw new IllegalStateException("This transaction is already being added to the back stack");
}
this.mAllowAddToBackStack = false;
return this;
}
public void dump(String paramString, FileDescriptor paramFileDescriptor, PrintWriter paramPrintWriter, String[] paramArrayOfString)
{
dump(paramString, paramPrintWriter, true);
}
public void dump(String paramString, PrintWriter paramPrintWriter, boolean paramBoolean)
{
if (paramBoolean)
{
paramPrintWriter.print(paramString);
paramPrintWriter.print("mName=");
paramPrintWriter.print(this.mName);
paramPrintWriter.print(" mIndex=");
paramPrintWriter.print(this.mIndex);
paramPrintWriter.print(" mCommitted=");
paramPrintWriter.println(this.mCommitted);
if (this.mTransition != 0)
{
paramPrintWriter.print(paramString);
paramPrintWriter.print("mTransition=#");
paramPrintWriter.print(Integer.toHexString(this.mTransition));
paramPrintWriter.print(" mTransitionStyle=#");
paramPrintWriter.println(Integer.toHexString(this.mTransitionStyle));
}
if ((this.mEnterAnim != 0) || (this.mExitAnim != 0))
{
paramPrintWriter.print(paramString);
paramPrintWriter.print("mEnterAnim=#");
paramPrintWriter.print(Integer.toHexString(this.mEnterAnim));
paramPrintWriter.print(" mExitAnim=#");
paramPrintWriter.println(Integer.toHexString(this.mExitAnim));
}
if ((this.mPopEnterAnim != 0) || (this.mPopExitAnim != 0))
{
paramPrintWriter.print(paramString);
paramPrintWriter.print("mPopEnterAnim=#");
paramPrintWriter.print(Integer.toHexString(this.mPopEnterAnim));
paramPrintWriter.print(" mPopExitAnim=#");
paramPrintWriter.println(Integer.toHexString(this.mPopExitAnim));
}
if ((this.mBreadCrumbTitleRes != 0) || (this.mBreadCrumbTitleText != null))
{
paramPrintWriter.print(paramString);
paramPrintWriter.print("mBreadCrumbTitleRes=#");
paramPrintWriter.print(Integer.toHexString(this.mBreadCrumbTitleRes));
paramPrintWriter.print(" mBreadCrumbTitleText=");
paramPrintWriter.println(this.mBreadCrumbTitleText);
}
if ((this.mBreadCrumbShortTitleRes != 0) || (this.mBreadCrumbShortTitleText != null))
{
paramPrintWriter.print(paramString);
paramPrintWriter.print("mBreadCrumbShortTitleRes=#");
paramPrintWriter.print(Integer.toHexString(this.mBreadCrumbShortTitleRes));
paramPrintWriter.print(" mBreadCrumbShortTitleText=");
paramPrintWriter.println(this.mBreadCrumbShortTitleText);
}
}
if (this.mHead != null)
{
paramPrintWriter.print(paramString);
paramPrintWriter.println("Operations:");
String str2 = paramString + " ";
Op localOp = this.mHead;
int i = 0;
while (localOp != null)
{
String str1;
int j;
switch (localOp.cmd)
{
default:
str1 = "cmd=" + localOp.cmd;
paramPrintWriter.print(paramString);
paramPrintWriter.print(" Op #");
paramPrintWriter.print(i);
paramPrintWriter.print(": ");
paramPrintWriter.print(str1);
paramPrintWriter.print(" ");
paramPrintWriter.println(localOp.fragment);
if (paramBoolean)
{
if ((localOp.enterAnim != 0) || (localOp.exitAnim != 0))
{
paramPrintWriter.print(paramString);
paramPrintWriter.print("enterAnim=#");
paramPrintWriter.print(Integer.toHexString(localOp.enterAnim));
paramPrintWriter.print(" exitAnim=#");
paramPrintWriter.println(Integer.toHexString(localOp.exitAnim));
}
if ((localOp.popEnterAnim != 0) || (localOp.popExitAnim != 0))
{
paramPrintWriter.print(paramString);
paramPrintWriter.print("popEnterAnim=#");
paramPrintWriter.print(Integer.toHexString(localOp.popEnterAnim));
paramPrintWriter.print(" popExitAnim=#");
paramPrintWriter.println(Integer.toHexString(localOp.popExitAnim));
}
}
if ((localOp.removed == null) || (localOp.removed.size() <= 0)) {
break label807;
}
j = 0;
label641:
if (j >= localOp.removed.size()) {
break label807;
}
paramPrintWriter.print(str2);
if (localOp.removed.size() == 1) {
paramPrintWriter.print("Removed: ");
}
break;
}
for (;;)
{
paramPrintWriter.println(localOp.removed.get(j));
j += 1;
break label641;
str1 = "NULL";
break;
str1 = "ADD";
break;
str1 = "REPLACE";
break;
str1 = "REMOVE";
break;
str1 = "HIDE";
break;
str1 = "SHOW";
break;
str1 = "DETACH";
break;
str1 = "ATTACH";
break;
if (j == 0) {
paramPrintWriter.println("Removed:");
}
paramPrintWriter.print(str2);
paramPrintWriter.print(" #");
paramPrintWriter.print(j);
paramPrintWriter.print(": ");
}
label807:
localOp = localOp.next;
i += 1;
}
}
}
public CharSequence getBreadCrumbShortTitle()
{
if (this.mBreadCrumbShortTitleRes != 0) {
return this.mManager.mHost.getContext().getText(this.mBreadCrumbShortTitleRes);
}
return this.mBreadCrumbShortTitleText;
}
public int getBreadCrumbShortTitleRes()
{
return this.mBreadCrumbShortTitleRes;
}
public CharSequence getBreadCrumbTitle()
{
if (this.mBreadCrumbTitleRes != 0) {
return this.mManager.mHost.getContext().getText(this.mBreadCrumbTitleRes);
}
return this.mBreadCrumbTitleText;
}
public int getBreadCrumbTitleRes()
{
return this.mBreadCrumbTitleRes;
}
public int getId()
{
return this.mIndex;
}
public String getName()
{
return this.mName;
}
public int getTransition()
{
return this.mTransition;
}
public int getTransitionStyle()
{
return this.mTransitionStyle;
}
public FragmentTransaction hide(Fragment paramFragment)
{
Op localOp = new Op();
localOp.cmd = 4;
localOp.fragment = paramFragment;
addOp(localOp);
return this;
}
public boolean isAddToBackStackAllowed()
{
return this.mAllowAddToBackStack;
}
public boolean isEmpty()
{
return this.mNumOp == 0;
}
public TransitionState popFromBackStack(boolean paramBoolean, TransitionState paramTransitionState, SparseArray<Fragment> paramSparseArray1, SparseArray<Fragment> paramSparseArray2)
{
if (FragmentManagerImpl.DEBUG)
{
Log.v("FragmentManager", "popFromBackStack: " + this);
dump(" ", null, new PrintWriter(new LogWriter("FragmentManager")), null);
}
TransitionState localTransitionState = paramTransitionState;
if (SUPPORTS_TRANSITIONS)
{
localTransitionState = paramTransitionState;
if (this.mManager.mCurState >= 1)
{
if (paramTransitionState != null) {
break label235;
}
if (paramSparseArray1.size() == 0)
{
localTransitionState = paramTransitionState;
if (paramSparseArray2.size() == 0) {}
}
else
{
localTransitionState = beginTransition(paramSparseArray1, paramSparseArray2, true);
}
}
}
label112:
bumpBackStackNesting(-1);
int i;
label125:
int j;
label133:
int k;
if (localTransitionState != null)
{
i = 0;
if (localTransitionState == null) {
break label269;
}
j = 0;
paramTransitionState = this.mTail;
if (paramTransitionState == null) {
break label558;
}
if (localTransitionState == null) {
break label278;
}
k = 0;
label150:
if (localTransitionState == null) {
break label287;
}
}
label235:
label269:
label278:
label287:
for (int m = 0;; m = paramTransitionState.popExitAnim) {
switch (paramTransitionState.cmd)
{
default:
throw new IllegalArgumentException("Unknown cmd: " + paramTransitionState.cmd);
localTransitionState = paramTransitionState;
if (paramBoolean) {
break label112;
}
setNameOverrides(paramTransitionState, this.mSharedElementTargetNames, this.mSharedElementSourceNames);
localTransitionState = paramTransitionState;
break label112;
i = this.mTransitionStyle;
break label125;
j = this.mTransition;
break label133;
k = paramTransitionState.popEnterAnim;
break label150;
}
}
paramSparseArray1 = paramTransitionState.fragment;
paramSparseArray1.mNextAnim = m;
this.mManager.removeFragment(paramSparseArray1, FragmentManagerImpl.reverseTransit(j), i);
for (;;)
{
paramTransitionState = paramTransitionState.prev;
break;
paramSparseArray1 = paramTransitionState.fragment;
if (paramSparseArray1 != null)
{
paramSparseArray1.mNextAnim = m;
this.mManager.removeFragment(paramSparseArray1, FragmentManagerImpl.reverseTransit(j), i);
}
if (paramTransitionState.removed != null)
{
m = 0;
while (m < paramTransitionState.removed.size())
{
paramSparseArray1 = (Fragment)paramTransitionState.removed.get(m);
paramSparseArray1.mNextAnim = k;
this.mManager.addFragment(paramSparseArray1, false);
m += 1;
}
paramSparseArray1 = paramTransitionState.fragment;
paramSparseArray1.mNextAnim = k;
this.mManager.addFragment(paramSparseArray1, false);
continue;
paramSparseArray1 = paramTransitionState.fragment;
paramSparseArray1.mNextAnim = k;
this.mManager.showFragment(paramSparseArray1, FragmentManagerImpl.reverseTransit(j), i);
continue;
paramSparseArray1 = paramTransitionState.fragment;
paramSparseArray1.mNextAnim = m;
this.mManager.hideFragment(paramSparseArray1, FragmentManagerImpl.reverseTransit(j), i);
continue;
paramSparseArray1 = paramTransitionState.fragment;
paramSparseArray1.mNextAnim = k;
this.mManager.attachFragment(paramSparseArray1, FragmentManagerImpl.reverseTransit(j), i);
continue;
paramSparseArray1 = paramTransitionState.fragment;
paramSparseArray1.mNextAnim = k;
this.mManager.detachFragment(paramSparseArray1, FragmentManagerImpl.reverseTransit(j), i);
}
}
label558:
if (paramBoolean)
{
this.mManager.moveToState(this.mManager.mCurState, FragmentManagerImpl.reverseTransit(j), i, true);
localTransitionState = null;
}
if (this.mIndex >= 0)
{
this.mManager.freeBackStackIndex(this.mIndex);
this.mIndex = -1;
}
return localTransitionState;
}
public FragmentTransaction remove(Fragment paramFragment)
{
Op localOp = new Op();
localOp.cmd = 3;
localOp.fragment = paramFragment;
addOp(localOp);
return this;
}
public FragmentTransaction replace(int paramInt, Fragment paramFragment)
{
return replace(paramInt, paramFragment, null);
}
public FragmentTransaction replace(int paramInt, Fragment paramFragment, String paramString)
{
if (paramInt == 0) {
throw new IllegalArgumentException("Must use non-zero containerViewId");
}
doAddOp(paramInt, paramFragment, paramString, 2);
return this;
}
public void run()
{
if (FragmentManagerImpl.DEBUG) {
Log.v("FragmentManager", "Run: " + this);
}
if ((this.mAddToBackStack) && (this.mIndex < 0)) {
throw new IllegalStateException("addToBackStack() called after commit()");
}
bumpBackStackNesting(1);
Object localObject1 = null;
Object localObject2 = localObject1;
if (SUPPORTS_TRANSITIONS)
{
localObject2 = localObject1;
if (this.mManager.mCurState >= 1)
{
localObject1 = new SparseArray();
localObject2 = new SparseArray();
calculateFragments((SparseArray)localObject1, (SparseArray)localObject2);
localObject2 = beginTransition((SparseArray)localObject1, (SparseArray)localObject2, false);
}
}
int i;
label134:
int j;
label141:
Op localOp;
int k;
if (localObject2 != null)
{
i = 0;
if (localObject2 == null) {
break label256;
}
j = 0;
localOp = this.mHead;
if (localOp == null) {
break label755;
}
if (localObject2 == null) {
break label264;
}
k = 0;
label159:
if (localObject2 == null) {
break label273;
}
}
label256:
label264:
label273:
for (int m = 0;; m = localOp.exitAnim) {
switch (localOp.cmd)
{
default:
throw new IllegalArgumentException("Unknown cmd: " + localOp.cmd);
i = this.mTransitionStyle;
break label134;
j = this.mTransition;
break label141;
k = localOp.enterAnim;
break label159;
}
}
localObject1 = localOp.fragment;
((Fragment)localObject1).mNextAnim = k;
this.mManager.addFragment((Fragment)localObject1, false);
for (;;)
{
localOp = localOp.next;
break;
localObject1 = localOp.fragment;
int i1 = ((Fragment)localObject1).mContainerId;
Object localObject3 = localObject1;
if (this.mManager.mAdded != null)
{
int n = this.mManager.mAdded.size() - 1;
localObject3 = localObject1;
if (n >= 0)
{
Fragment localFragment = (Fragment)this.mManager.mAdded.get(n);
if (FragmentManagerImpl.DEBUG) {
Log.v("FragmentManager", "OP_REPLACE: adding=" + localObject1 + " old=" + localFragment);
}
localObject3 = localObject1;
if (localFragment.mContainerId == i1)
{
if (localFragment != localObject1) {
break label471;
}
localObject3 = null;
localOp.fragment = null;
}
for (;;)
{
n -= 1;
localObject1 = localObject3;
break;
label471:
if (localOp.removed == null) {
localOp.removed = new ArrayList();
}
localOp.removed.add(localFragment);
localFragment.mNextAnim = m;
if (this.mAddToBackStack)
{
localFragment.mBackStackNesting += 1;
if (FragmentManagerImpl.DEBUG) {
Log.v("FragmentManager", "Bump nesting of " + localFragment + " to " + localFragment.mBackStackNesting);
}
}
this.mManager.removeFragment(localFragment, j, i);
localObject3 = localObject1;
}
}
}
if (localObject3 != null)
{
localObject3.mNextAnim = k;
this.mManager.addFragment(localObject3, false);
continue;
localObject1 = localOp.fragment;
((Fragment)localObject1).mNextAnim = m;
this.mManager.removeFragment((Fragment)localObject1, j, i);
continue;
localObject1 = localOp.fragment;
((Fragment)localObject1).mNextAnim = m;
this.mManager.hideFragment((Fragment)localObject1, j, i);
continue;
localObject1 = localOp.fragment;
((Fragment)localObject1).mNextAnim = k;
this.mManager.showFragment((Fragment)localObject1, j, i);
continue;
localObject1 = localOp.fragment;
((Fragment)localObject1).mNextAnim = m;
this.mManager.detachFragment((Fragment)localObject1, j, i);
continue;
localObject1 = localOp.fragment;
((Fragment)localObject1).mNextAnim = k;
this.mManager.attachFragment((Fragment)localObject1, j, i);
}
}
label755:
this.mManager.moveToState(this.mManager.mCurState, j, i, true);
if (this.mAddToBackStack) {
this.mManager.addBackStackState(this);
}
}
public FragmentTransaction setBreadCrumbShortTitle(int paramInt)
{
this.mBreadCrumbShortTitleRes = paramInt;
this.mBreadCrumbShortTitleText = null;
return this;
}
public FragmentTransaction setBreadCrumbShortTitle(CharSequence paramCharSequence)
{
this.mBreadCrumbShortTitleRes = 0;
this.mBreadCrumbShortTitleText = paramCharSequence;
return this;
}
public FragmentTransaction setBreadCrumbTitle(int paramInt)
{
this.mBreadCrumbTitleRes = paramInt;
this.mBreadCrumbTitleText = null;
return this;
}
public FragmentTransaction setBreadCrumbTitle(CharSequence paramCharSequence)
{
this.mBreadCrumbTitleRes = 0;
this.mBreadCrumbTitleText = paramCharSequence;
return this;
}
public FragmentTransaction setCustomAnimations(int paramInt1, int paramInt2)
{
return setCustomAnimations(paramInt1, paramInt2, 0, 0);
}
public FragmentTransaction setCustomAnimations(int paramInt1, int paramInt2, int paramInt3, int paramInt4)
{
this.mEnterAnim = paramInt1;
this.mExitAnim = paramInt2;
this.mPopEnterAnim = paramInt3;
this.mPopExitAnim = paramInt4;
return this;
}
public FragmentTransaction setTransition(int paramInt)
{
this.mTransition = paramInt;
return this;
}
public FragmentTransaction setTransitionStyle(int paramInt)
{
this.mTransitionStyle = paramInt;
return this;
}
public FragmentTransaction show(Fragment paramFragment)
{
Op localOp = new Op();
localOp.cmd = 5;
localOp.fragment = paramFragment;
addOp(localOp);
return this;
}
public String toString()
{
StringBuilder localStringBuilder = new StringBuilder(128);
localStringBuilder.append("BackStackEntry{");
localStringBuilder.append(Integer.toHexString(System.identityHashCode(this)));
if (this.mIndex >= 0)
{
localStringBuilder.append(" #");
localStringBuilder.append(this.mIndex);
}
if (this.mName != null)
{
localStringBuilder.append(" ");
localStringBuilder.append(this.mName);
}
localStringBuilder.append("}");
return localStringBuilder.toString();
}
static final class Op
{
int cmd;
int enterAnim;
int exitAnim;
Fragment fragment;
Op next;
int popEnterAnim;
int popExitAnim;
Op prev;
ArrayList<Fragment> removed;
Op() {}
}
public class TransitionState
{
public FragmentTransitionCompat21.EpicenterView enteringEpicenterView = new FragmentTransitionCompat21.EpicenterView();
public ArrayList<View> hiddenFragmentViews = new ArrayList();
public ArrayMap<String, String> nameOverrides = new ArrayMap();
public View nonExistentView;
public TransitionState() {}
}
}
|
9239597577edff6952c4ac9c86663ac837bf7c5d | 258 | java | Java | domain/src/main/java/nf/co/emilianku/domain/processors/ResponseProcessor.java | emilioschiavi/european-football | 38dd522ec0a1123d3a40353c2569e7be104d3819 | [
"MIT"
] | null | null | null | domain/src/main/java/nf/co/emilianku/domain/processors/ResponseProcessor.java | emilioschiavi/european-football | 38dd522ec0a1123d3a40353c2569e7be104d3819 | [
"MIT"
] | 3 | 2017-05-05T21:07:42.000Z | 2017-05-06T19:20:34.000Z | domain/src/main/java/nf/co/emilianku/domain/processors/ResponseProcessor.java | emilioschiavi/european-football | 38dd522ec0a1123d3a40353c2569e7be104d3819 | [
"MIT"
] | null | null | null | 19.846154 | 78 | 0.763566 | 998,795 | package nf.co.emilianku.domain.processors;
import nf.co.emilianku.domain.model.DataContainer;
/**
* Created by emilio on 28.04.17.
*/
public interface ResponseProcessor {
boolean process(DataContainer container, String url, String responseBody);
}
|
92395b0e1c7ae3835ff6679cb9f34fdeb48d135e | 5,523 | java | Java | src/main/java/com/twilio/twiml/voice/Sms.java | duttonw/twilio-java | 87e51c729aa882926eeb59114be3488423d750ad | [
"MIT"
] | 295 | 2015-01-04T17:00:48.000Z | 2022-03-29T21:51:49.000Z | src/main/java/com/twilio/twiml/voice/Sms.java | duttonw/twilio-java | 87e51c729aa882926eeb59114be3488423d750ad | [
"MIT"
] | 349 | 2015-01-14T19:08:16.000Z | 2022-03-09T15:50:13.000Z | src/main/java/com/twilio/twiml/voice/Sms.java | duttonw/twilio-java | 87e51c729aa882926eeb59114be3488423d750ad | [
"MIT"
] | 376 | 2015-01-03T22:31:01.000Z | 2022-03-31T08:23:17.000Z | 23.303797 | 77 | 0.524896 | 998,796 | /**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
package com.twilio.twiml.voice;
import com.twilio.converter.Promoter;
import com.twilio.http.HttpMethod;
import com.twilio.twiml.TwiML;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
/**
* TwiML wrapper for {@code <Sms>}
*/
public class Sms extends TwiML {
private final com.twilio.type.PhoneNumber to;
private final com.twilio.type.PhoneNumber from;
private final URI action;
private final HttpMethod method;
private final URI statusCallback;
private final String message;
/**
* For XML Serialization/Deserialization
*/
private Sms() {
this(new Builder((String) null));
}
/**
* Create a new {@code <Sms>} element
*/
private Sms(Builder b) {
super("Sms", b);
this.to = b.to;
this.from = b.from;
this.action = b.action;
this.method = b.method;
this.statusCallback = b.statusCallback;
this.message = b.message;
}
/**
* The body of the TwiML element
*
* @return Element body as a string if present else null
*/
protected String getElementBody() {
return this.getMessage() == null ? null : this.getMessage();
}
/**
* Attributes to set on the generated XML element
*
* @return A Map of attribute keys to values
*/
protected Map<String, String> getElementAttributes() {
// Preserve order of attributes
Map<String, String> attrs = new HashMap<>();
if (this.getTo() != null) {
attrs.put("to", this.getTo().toString());
}
if (this.getFrom() != null) {
attrs.put("from", this.getFrom().toString());
}
if (this.getAction() != null) {
attrs.put("action", this.getAction().toString());
}
if (this.getMethod() != null) {
attrs.put("method", this.getMethod().toString());
}
if (this.getStatusCallback() != null) {
attrs.put("statusCallback", this.getStatusCallback().toString());
}
return attrs;
}
/**
* Number to send message to
*
* @return Number to send message to
*/
public com.twilio.type.PhoneNumber getTo() {
return to;
}
/**
* Number to send message from
*
* @return Number to send message from
*/
public com.twilio.type.PhoneNumber getFrom() {
return from;
}
/**
* Action URL
*
* @return Action URL
*/
public URI getAction() {
return action;
}
/**
* Action URL method
*
* @return Action URL method
*/
public HttpMethod getMethod() {
return method;
}
/**
* Status callback URL
*
* @return Status callback URL
*/
public URI getStatusCallback() {
return statusCallback;
}
/**
* Message body
*
* @return Message body
*/
public String getMessage() {
return message;
}
/**
* Create a new {@code <Sms>} element
*/
public static class Builder extends TwiML.Builder<Builder> {
private com.twilio.type.PhoneNumber to;
private com.twilio.type.PhoneNumber from;
private URI action;
private HttpMethod method;
private URI statusCallback;
private String message;
/**
* Create a {@code <Sms>} with message
*/
public Builder(String message) {
this.message = message;
}
/**
* Number to send message to
*/
public Builder to(com.twilio.type.PhoneNumber to) {
this.to = to;
return this;
}
/**
* Number to send message to
*/
public Builder to(String to) {
this.to = Promoter.phoneNumberFromString(to);
return this;
}
/**
* Number to send message from
*/
public Builder from(com.twilio.type.PhoneNumber from) {
this.from = from;
return this;
}
/**
* Number to send message from
*/
public Builder from(String from) {
this.from = Promoter.phoneNumberFromString(from);
return this;
}
/**
* Action URL
*/
public Builder action(URI action) {
this.action = action;
return this;
}
/**
* Action URL
*/
public Builder action(String action) {
this.action = Promoter.uriFromString(action);
return this;
}
/**
* Action URL method
*/
public Builder method(HttpMethod method) {
this.method = method;
return this;
}
/**
* Status callback URL
*/
public Builder statusCallback(URI statusCallback) {
this.statusCallback = statusCallback;
return this;
}
/**
* Status callback URL
*/
public Builder statusCallback(String statusCallback) {
this.statusCallback = Promoter.uriFromString(statusCallback);
return this;
}
/**
* Create and return resulting {@code <Sms>} element
*/
public Sms build() {
return new Sms(this);
}
}
} |
92395bab586a5f7d5186c1a1f38459ae44fb2109 | 6,866 | java | Java | flink-formats/flink-avro/src/test/java/org/apache/flink/formats/avro/typeutils/BackwardsCompatibleAvroSerializerTest.java | senorcarbone/incubator-flink | 72bc31e55882537caf77c4749cc808b3fcb5d51b | [
"BSD-2-Clause",
"Apache-2.0"
] | 13 | 2018-03-05T23:10:08.000Z | 2021-02-07T02:00:51.000Z | flink-formats/flink-avro/src/test/java/org/apache/flink/formats/avro/typeutils/BackwardsCompatibleAvroSerializerTest.java | senorcarbone/incubator-flink | 72bc31e55882537caf77c4749cc808b3fcb5d51b | [
"BSD-2-Clause",
"Apache-2.0"
] | 7 | 2018-01-08T11:59:49.000Z | 2022-03-25T09:08:48.000Z | flink-formats/flink-avro/src/test/java/org/apache/flink/formats/avro/typeutils/BackwardsCompatibleAvroSerializerTest.java | senorcarbone/incubator-flink | 72bc31e55882537caf77c4749cc808b3fcb5d51b | [
"BSD-2-Clause",
"Apache-2.0"
] | 7 | 2017-01-30T15:28:26.000Z | 2018-04-03T12:38:07.000Z | 40.869048 | 148 | 0.782552 | 998,797 | /*
* 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.flink.formats.avro.typeutils;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.common.typeutils.TypeSerializerConfigSnapshot;
import org.apache.flink.api.common.typeutils.TypeSerializerSerializationUtil;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.typeutils.runtime.PojoSerializer;
import org.apache.flink.api.java.typeutils.runtime.PojoSerializer.PojoSerializerConfigSnapshot;
import org.apache.flink.core.memory.DataInputViewStreamWrapper;
import org.apache.flink.formats.avro.generated.User;
import org.apache.flink.formats.avro.utils.TestDataGenerator;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Random;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* This test ensures that state and state configuration created by Flink 1.3 Avro types
* that used the PojoSerializer still works.
*
* <p><b>Important:</b> Since Avro itself broke class compatibility between 1.7.7 (used in Flink 1.3)
* and 1.8.2 (used in Flink 1.4), the Avro by Pojo compatibility is broken through Avro already.
* This test only tests that the Avro serializer change (switching from Pojo to Avro for Avro types)
* works properly.
*
* <p>This test can be dropped once we drop backwards compatibility with Flink 1.3 snapshots.
*/
public class BackwardsCompatibleAvroSerializerTest {
private static final String SNAPSHOT_RESOURCE = "flink-1.3-avro-type-serializer-snapshot";
private static final String DATA_RESOURCE = "flink-1.3-avro-type-serialized-data";
@SuppressWarnings("unused")
private static final String SNAPSHOT_RESOURCE_WRITER = "/data/repositories/flink/flink-formats/flink-avro/src/test/resources/" + SNAPSHOT_RESOURCE;
@SuppressWarnings("unused")
private static final String DATA_RESOURCE_WRITER = "/data/repositories/flink/flink-formats/flink-avro/src/test/resources/" + DATA_RESOURCE;
private static final long RANDOM_SEED = 143065108437678L;
private static final int NUM_DATA_ENTRIES = 20;
@Test
public void testCompatibilityWithFlink_1_3() throws Exception {
// retrieve the old config snapshot
final TypeSerializer<User> serializer;
final TypeSerializerConfigSnapshot configSnapshot;
try (InputStream in = getClass().getClassLoader().getResourceAsStream(SNAPSHOT_RESOURCE)) {
DataInputViewStreamWrapper inView = new DataInputViewStreamWrapper(in);
List<Tuple2<TypeSerializer<?>, TypeSerializerConfigSnapshot>> deserialized =
TypeSerializerSerializationUtil.readSerializersAndConfigsWithResilience(
inView, getClass().getClassLoader());
assertEquals(1, deserialized.size());
@SuppressWarnings("unchecked")
final TypeSerializer<User> typedSerializer = (TypeSerializer<User>) deserialized.get(0).f0;
serializer = typedSerializer;
configSnapshot = deserialized.get(0).f1;
}
assertNotNull(serializer);
assertNotNull(configSnapshot);
assertTrue(serializer instanceof PojoSerializer);
assertTrue(configSnapshot instanceof PojoSerializerConfigSnapshot);
// sanity check for the test: check that the test data works with the original serializer
validateDeserialization(serializer);
// sanity check for the test: check that a PoJoSerializer and the original serializer work together
assertFalse(serializer.ensureCompatibility(configSnapshot).isRequiresMigration());
final TypeSerializer<User> newSerializer = new AvroTypeInfo<>(User.class, true).createSerializer(new ExecutionConfig());
assertFalse(newSerializer.ensureCompatibility(configSnapshot).isRequiresMigration());
// deserialize the data and make sure this still works
validateDeserialization(newSerializer);
TypeSerializerConfigSnapshot nextSnapshot = newSerializer.snapshotConfiguration();
final TypeSerializer<User> nextSerializer = new AvroTypeInfo<>(User.class, true).createSerializer(new ExecutionConfig());
assertFalse(nextSerializer.ensureCompatibility(nextSnapshot).isRequiresMigration());
// deserialize the data and make sure this still works
validateDeserialization(nextSerializer);
}
private static void validateDeserialization(TypeSerializer<User> serializer) throws IOException {
final Random rnd = new Random(RANDOM_SEED);
try (InputStream in = BackwardsCompatibleAvroSerializerTest.class.getClassLoader()
.getResourceAsStream(DATA_RESOURCE)) {
final DataInputViewStreamWrapper inView = new DataInputViewStreamWrapper(in);
for (int i = 0; i < NUM_DATA_ENTRIES; i++) {
final User deserialized = serializer.deserialize(inView);
// deterministically generate a reference record
final User reference = TestDataGenerator.generateRandomUser(rnd);
assertEquals(reference, deserialized);
}
}
}
// run this code on a 1.3 (or earlier) branch to generate the test data
// public static void main(String[] args) throws Exception {
//
// AvroTypeInfo<User> typeInfo = new AvroTypeInfo<>(User.class);
//
// TypeSerializer<User> serializer = typeInfo.createPojoSerializer(new ExecutionConfig());
// TypeSerializerConfigSnapshot confSnapshot = serializer.snapshotConfiguration();
//
// try (FileOutputStream fos = new FileOutputStream(SNAPSHOT_RESOURCE_WRITER)) {
// DataOutputViewStreamWrapper out = new DataOutputViewStreamWrapper(fos);
//
// TypeSerializerSerializationUtil.writeSerializersAndConfigsWithResilience(
// out,
// Collections.singletonList(
// new Tuple2<>(serializer, confSnapshot)));
// }
//
// try (FileOutputStream fos = new FileOutputStream(DATA_RESOURCE_WRITER)) {
// final DataOutputViewStreamWrapper out = new DataOutputViewStreamWrapper(fos);
// final Random rnd = new Random(RANDOM_SEED);
//
// for (int i = 0; i < NUM_DATA_ENTRIES; i++) {
// serializer.serialize(TestDataGenerator.generateRandomUser(rnd), out);
// }
// }
// }
}
|
92395c2b02b04127d14b8171a8a238330772963d | 267,715 | java | Java | constraintlayout/constraintlayout/src/main/java/androidx/constraintlayout/widget/ConstraintSet.java | xtuzy/constraintlayout | 0821c4ee57d2535d3404086ec76f55b57b69fb5a | [
"Apache-2.0"
] | 927 | 2020-07-24T07:24:54.000Z | 2022-03-31T10:01:37.000Z | constraintlayout/constraintlayout/src/main/java/androidx/constraintlayout/widget/ConstraintSet.java | xtuzy/constraintlayout | 0821c4ee57d2535d3404086ec76f55b57b69fb5a | [
"Apache-2.0"
] | 183 | 2020-09-07T17:45:12.000Z | 2022-03-31T14:56:38.000Z | constraintlayout/constraintlayout/src/main/java/androidx/constraintlayout/widget/ConstraintSet.java | xtuzy/constraintlayout | 0821c4ee57d2535d3404086ec76f55b57b69fb5a | [
"Apache-2.0"
] | 135 | 2020-08-28T02:33:08.000Z | 2022-03-26T01:19:59.000Z | 45.260355 | 165 | 0.575078 | 998,798 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.constraintlayout.widget;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.graphics.Color;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.util.TypedValue;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import androidx.constraintlayout.core.widgets.ConstraintWidget;
import androidx.constraintlayout.core.widgets.HelperWidget;
import androidx.constraintlayout.core.motion.utils.Easing;
import androidx.constraintlayout.motion.widget.Debug;
import androidx.constraintlayout.motion.widget.MotionLayout;
import androidx.constraintlayout.motion.widget.MotionScene;
import androidx.constraintlayout.widget.ConstraintAttribute.AttributeType;
import androidx.constraintlayout.widget.ConstraintLayout.LayoutParams;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
/**
* This class allows you to define programmatically a set of constraints to be used with {@link ConstraintLayout}.
* <p>
* For details about Constraint behaviour see {@link ConstraintLayout}.
* It lets you create and save constraints, and apply them to an existing ConstraintLayout. ConstraintsSet can be created in various ways:
* <ul>
* <li>
* Manually <br> {@code c = new ConstraintSet(); c.connect(....);}
* </li>
* <li>
* from a R.layout.* object <br> {@code c.clone(context, R.layout.layout1);}
* </li>
* <li>
* from a ConstraintLayout <br> {@code c.clone(constraintLayout);}
* </li>
* </ul><p>
* Example code:<br>
* {@sample resources/examples/ExampleConstraintSet.java Example}
*/
public class ConstraintSet {
private static final String TAG = "ConstraintSet";
private static final String ERROR_MESSAGE = "XML parser error must be within a Constraint ";
private static final int INTERNAL_MATCH_PARENT = -1;
private static final int INTERNAL_WRAP_CONTENT = -2;
private static final int INTERNAL_MATCH_CONSTRAINT = -3;
private static final int INTERNAL_WRAP_CONTENT_CONSTRAINED = -4;
private boolean mValidate;
public String mIdString;
public String derivedState = "";
public static final int ROTATE_NONE = 0;
public static final int ROTATE_PORTRATE_OF_RIGHT = 1;
public static final int ROTATE_PORTRATE_OF_LEFT = 2;
public static final int ROTATE_RIGHT_OF_PORTRATE = 3;
public static final int ROTATE_LEFT_OF_PORTRATE = 4;
public int mRotate = 0;
private HashMap<String, ConstraintAttribute> mSavedAttributes = new HashMap<>();
/**
* require that all views have IDs to function
*/
private boolean mForceId = true;
/**
* Used to indicate a parameter is cleared or not set
*/
public static final int UNSET = LayoutParams.UNSET;
/**
* Dimension will be controlled by constraints
*/
public static final int MATCH_CONSTRAINT = ConstraintLayout.LayoutParams.MATCH_CONSTRAINT;
/**
* Dimension will set by the view's content
*/
public static final int WRAP_CONTENT = ConstraintLayout.LayoutParams.WRAP_CONTENT;
/**
* How to calculate the size of a view in 0 dp by using its wrap_content size
*/
public static final int MATCH_CONSTRAINT_WRAP = ConstraintLayout.LayoutParams.MATCH_CONSTRAINT_WRAP;
/**
* Calculate the size of a view in 0 dp by reducing the constrains gaps as much as possible
*/
public static final int MATCH_CONSTRAINT_SPREAD = ConstraintLayout.LayoutParams.MATCH_CONSTRAINT_SPREAD;
public static final int MATCH_CONSTRAINT_PERCENT = ConstraintLayout.LayoutParams.MATCH_CONSTRAINT_PERCENT;
/**
* References the id of the parent.
* Used in:
* <ul>
* <li>{@link #connect(int, int, int, int, int)}</li>
* <li>{@link #center(int, int, int, int, int, int, int, float)}</li>
* </ul>
*/
public static final int PARENT_ID = ConstraintLayout.LayoutParams.PARENT_ID;
/**
* The horizontal orientation.
*/
public static final int HORIZONTAL = ConstraintLayout.LayoutParams.HORIZONTAL;
/**
* The vertical orientation.
*/
public static final int VERTICAL = ConstraintLayout.LayoutParams.VERTICAL;
/**
* Used to create a horizontal create guidelines.
*/
public static final int HORIZONTAL_GUIDELINE = 0;
/**
* Used to create a vertical create guidelines.
* see {@link #create(int, int)}
*/
public static final int VERTICAL_GUIDELINE = 1;
/**
* This view is visible.
* Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
* android:visibility}.
*/
public static final int VISIBLE = View.VISIBLE;
/**
* This view is invisible, but it still takes up space for layout purposes.
* Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
* android:visibility}.
*/
public static final int INVISIBLE = View.INVISIBLE;
/**
* This view is gone, and will not take any space for layout
* purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
* android:visibility}.
*/
public static final int GONE = View.GONE;
/**
* The left side of a view.
*/
public static final int LEFT = ConstraintLayout.LayoutParams.LEFT;
/**
* The right side of a view.
*/
public static final int RIGHT = ConstraintLayout.LayoutParams.RIGHT;
/**
* The top of a view.
*/
public static final int TOP = ConstraintLayout.LayoutParams.TOP;
/**
* The bottom side of a view.
*/
public static final int BOTTOM = ConstraintLayout.LayoutParams.BOTTOM;
/**
* The baseline of the text in a view.
*/
public static final int BASELINE = ConstraintLayout.LayoutParams.BASELINE;
/**
* The left side of a view in left to right languages.
* In right to left languages it corresponds to the right side of the view
*/
public static final int START = ConstraintLayout.LayoutParams.START;
/**
* The right side of a view in right to left languages.
* In right to left languages it corresponds to the left side of the view
*/
public static final int END = ConstraintLayout.LayoutParams.END;
/**
* Circle reference from a view.
*/
public static final int CIRCLE_REFERENCE = ConstraintLayout.LayoutParams.CIRCLE;
/**
* Chain spread style
*/
public static final int CHAIN_SPREAD = ConstraintLayout.LayoutParams.CHAIN_SPREAD;
/**
* Chain spread inside style
*/
public static final int CHAIN_SPREAD_INSIDE = ConstraintLayout.LayoutParams.CHAIN_SPREAD_INSIDE;
public static final int VISIBILITY_MODE_NORMAL = 0;
public static final int VISIBILITY_MODE_IGNORE = 1;
/**
* Chain packed style
*/
public static final int CHAIN_PACKED = ConstraintLayout.LayoutParams.CHAIN_PACKED;
private static final boolean DEBUG = false;
private static final int[] VISIBILITY_FLAGS = new int[]{VISIBLE, INVISIBLE, GONE};
private static final int BARRIER_TYPE = 1;
private HashMap<Integer, Constraint> mConstraints = new HashMap<Integer, Constraint>();
private static SparseIntArray mapToConstant = new SparseIntArray();
private static SparseIntArray overrideMapToConstant = new SparseIntArray();
private static final int BASELINE_TO_BASELINE = 1;
private static final int BOTTOM_MARGIN = 2;
private static final int BOTTOM_TO_BOTTOM = 3;
private static final int BOTTOM_TO_TOP = 4;
private static final int DIMENSION_RATIO = 5;
private static final int EDITOR_ABSOLUTE_X = 6;
private static final int EDITOR_ABSOLUTE_Y = 7;
private static final int END_MARGIN = 8;
private static final int END_TO_END = 9;
private static final int END_TO_START = 10;
private static final int GONE_BOTTOM_MARGIN = 11;
private static final int GONE_END_MARGIN = 12;
private static final int GONE_LEFT_MARGIN = 13;
private static final int GONE_RIGHT_MARGIN = 14;
private static final int GONE_START_MARGIN = 15;
private static final int GONE_TOP_MARGIN = 16;
private static final int GUIDE_BEGIN = 17;
private static final int GUIDE_END = 18;
private static final int GUIDE_PERCENT = 19;
private static final int HORIZONTAL_BIAS = 20;
private static final int LAYOUT_HEIGHT = 21;
private static final int LAYOUT_VISIBILITY = 22;
private static final int LAYOUT_WIDTH = 23;
private static final int LEFT_MARGIN = 24;
private static final int LEFT_TO_LEFT = 25;
private static final int LEFT_TO_RIGHT = 26;
private static final int ORIENTATION = 27;
private static final int RIGHT_MARGIN = 28;
private static final int RIGHT_TO_LEFT = 29;
private static final int RIGHT_TO_RIGHT = 30;
private static final int START_MARGIN = 31;
private static final int START_TO_END = 32;
private static final int START_TO_START = 33;
private static final int TOP_MARGIN = 34;
private static final int TOP_TO_BOTTOM = 35;
private static final int TOP_TO_TOP = 36;
private static final int VERTICAL_BIAS = 37;
private static final int VIEW_ID = 38;
private static final int HORIZONTAL_WEIGHT = 39;
private static final int VERTICAL_WEIGHT = 40;
private static final int HORIZONTAL_STYLE = 41;
private static final int VERTICAL_STYLE = 42;
private static final int ALPHA = 43;
private static final int ELEVATION = 44;
private static final int ROTATION_X = 45;
private static final int ROTATION_Y = 46;
private static final int SCALE_X = 47;
private static final int SCALE_Y = 48;
private static final int TRANSFORM_PIVOT_X = 49;
private static final int TRANSFORM_PIVOT_Y = 50;
private static final int TRANSLATION_X = 51;
private static final int TRANSLATION_Y = 52;
private static final int TRANSLATION_Z = 53;
private static final int WIDTH_DEFAULT = 54;
private static final int HEIGHT_DEFAULT = 55;
private static final int WIDTH_MAX = 56;
private static final int HEIGHT_MAX = 57;
private static final int WIDTH_MIN = 58;
private static final int HEIGHT_MIN = 59;
private static final int ROTATION = 60;
private static final int CIRCLE = 61;
private static final int CIRCLE_RADIUS = 62;
private static final int CIRCLE_ANGLE = 63;
private static final int ANIMATE_RELATIVE_TO = 64;
private static final int TRANSITION_EASING = 65;
private static final int DRAW_PATH = 66;
private static final int TRANSITION_PATH_ROTATE = 67;
private static final int PROGRESS = 68;
private static final int WIDTH_PERCENT = 69;
private static final int HEIGHT_PERCENT = 70;
private static final int CHAIN_USE_RTL = 71;
private static final int BARRIER_DIRECTION = 72;
private static final int BARRIER_MARGIN = 73;
private static final int CONSTRAINT_REFERENCED_IDS = 74;
private static final int BARRIER_ALLOWS_GONE_WIDGETS = 75;
private static final int PATH_MOTION_ARC = 76;
private static final int CONSTRAINT_TAG = 77;
private static final int VISIBILITY_MODE = 78;
private static final int MOTION_STAGGER = 79;
private static final int CONSTRAINED_WIDTH = 80;
private static final int CONSTRAINED_HEIGHT = 81;
private static final int ANIMATE_CIRCLE_ANGLE_TO = 82;
private static final int TRANSFORM_PIVOT_TARGET = 83;
private static final int QUANTIZE_MOTION_STEPS = 84;
private static final int QUANTIZE_MOTION_PHASE = 85;
private static final int QUANTIZE_MOTION_INTERPOLATOR = 86;
private static final int UNUSED = 87;
private static final int QUANTIZE_MOTION_INTERPOLATOR_TYPE = 88;
private static final int QUANTIZE_MOTION_INTERPOLATOR_ID = 89;
private static final int QUANTIZE_MOTION_INTERPOLATOR_STR = 90;
private static final int BASELINE_TO_TOP = 91;
private static final int BASELINE_TO_BOTTOM = 92;
private static final int BASELINE_MARGIN = 93;
private static final int GONE_BASELINE_MARGIN = 94;
private static final int LAYOUT_CONSTRAINT_WIDTH = 95;
private static final int LAYOUT_CONSTRAINT_HEIGHT = 96;
private static final int LAYOUT_WRAP_BEHAVIOR = 97;
private static final int MOTION_TARGET = 98;
private static final String KEY_WEIGHT = "weight";
private static final String KEY_RATIO = "ratio";
private static final String KEY_PERCENT_PARENT = "parent";
static {
mapToConstant.append(R.styleable.Constraint_layout_constraintLeft_toLeftOf, LEFT_TO_LEFT);
mapToConstant.append(R.styleable.Constraint_layout_constraintLeft_toRightOf, LEFT_TO_RIGHT);
mapToConstant.append(R.styleable.Constraint_layout_constraintRight_toLeftOf, RIGHT_TO_LEFT);
mapToConstant.append(R.styleable.Constraint_layout_constraintRight_toRightOf, RIGHT_TO_RIGHT);
mapToConstant.append(R.styleable.Constraint_layout_constraintTop_toTopOf, TOP_TO_TOP);
mapToConstant.append(R.styleable.Constraint_layout_constraintTop_toBottomOf, TOP_TO_BOTTOM);
mapToConstant.append(R.styleable.Constraint_layout_constraintBottom_toTopOf, BOTTOM_TO_TOP);
mapToConstant.append(R.styleable.Constraint_layout_constraintBottom_toBottomOf, BOTTOM_TO_BOTTOM);
mapToConstant.append(R.styleable.Constraint_layout_constraintBaseline_toBaselineOf, BASELINE_TO_BASELINE);
mapToConstant.append(R.styleable.Constraint_layout_constraintBaseline_toTopOf, BASELINE_TO_TOP);
mapToConstant.append(R.styleable.Constraint_layout_constraintBaseline_toBottomOf, BASELINE_TO_BOTTOM);
mapToConstant.append(R.styleable.Constraint_layout_editor_absoluteX, EDITOR_ABSOLUTE_X);
mapToConstant.append(R.styleable.Constraint_layout_editor_absoluteY, EDITOR_ABSOLUTE_Y);
mapToConstant.append(R.styleable.Constraint_layout_constraintGuide_begin, GUIDE_BEGIN);
mapToConstant.append(R.styleable.Constraint_layout_constraintGuide_end, GUIDE_END);
mapToConstant.append(R.styleable.Constraint_layout_constraintGuide_percent, GUIDE_PERCENT);
mapToConstant.append(R.styleable.Constraint_android_orientation, ORIENTATION);
mapToConstant.append(R.styleable.Constraint_layout_constraintStart_toEndOf, START_TO_END);
mapToConstant.append(R.styleable.Constraint_layout_constraintStart_toStartOf, START_TO_START);
mapToConstant.append(R.styleable.Constraint_layout_constraintEnd_toStartOf, END_TO_START);
mapToConstant.append(R.styleable.Constraint_layout_constraintEnd_toEndOf, END_TO_END);
mapToConstant.append(R.styleable.Constraint_layout_goneMarginLeft, GONE_LEFT_MARGIN);
mapToConstant.append(R.styleable.Constraint_layout_goneMarginTop, GONE_TOP_MARGIN);
mapToConstant.append(R.styleable.Constraint_layout_goneMarginRight, GONE_RIGHT_MARGIN);
mapToConstant.append(R.styleable.Constraint_layout_goneMarginBottom, GONE_BOTTOM_MARGIN);
mapToConstant.append(R.styleable.Constraint_layout_goneMarginStart, GONE_START_MARGIN);
mapToConstant.append(R.styleable.Constraint_layout_goneMarginEnd, GONE_END_MARGIN);
mapToConstant.append(R.styleable.Constraint_layout_constraintVertical_weight, VERTICAL_WEIGHT);
mapToConstant.append(R.styleable.Constraint_layout_constraintHorizontal_weight, HORIZONTAL_WEIGHT);
mapToConstant.append(R.styleable.Constraint_layout_constraintHorizontal_chainStyle, HORIZONTAL_STYLE);
mapToConstant.append(R.styleable.Constraint_layout_constraintVertical_chainStyle, VERTICAL_STYLE);
mapToConstant.append(R.styleable.Constraint_layout_constraintHorizontal_bias, HORIZONTAL_BIAS);
mapToConstant.append(R.styleable.Constraint_layout_constraintVertical_bias, VERTICAL_BIAS);
mapToConstant.append(R.styleable.Constraint_layout_constraintDimensionRatio, DIMENSION_RATIO);
mapToConstant.append(R.styleable.Constraint_layout_constraintLeft_creator, UNUSED);
mapToConstant.append(R.styleable.Constraint_layout_constraintTop_creator, UNUSED);
mapToConstant.append(R.styleable.Constraint_layout_constraintRight_creator, UNUSED);
mapToConstant.append(R.styleable.Constraint_layout_constraintBottom_creator, UNUSED);
mapToConstant.append(R.styleable.Constraint_layout_constraintBaseline_creator, UNUSED);
mapToConstant.append(R.styleable.Constraint_android_layout_marginLeft, LEFT_MARGIN);
mapToConstant.append(R.styleable.Constraint_android_layout_marginRight, RIGHT_MARGIN);
mapToConstant.append(R.styleable.Constraint_android_layout_marginStart, START_MARGIN);
mapToConstant.append(R.styleable.Constraint_android_layout_marginEnd, END_MARGIN);
mapToConstant.append(R.styleable.Constraint_android_layout_marginTop, TOP_MARGIN);
mapToConstant.append(R.styleable.Constraint_android_layout_marginBottom, BOTTOM_MARGIN);
mapToConstant.append(R.styleable.Constraint_android_layout_width, LAYOUT_WIDTH);
mapToConstant.append(R.styleable.Constraint_android_layout_height, LAYOUT_HEIGHT);
mapToConstant.append(R.styleable.Constraint_layout_constraintWidth, LAYOUT_CONSTRAINT_WIDTH);
mapToConstant.append(R.styleable.Constraint_layout_constraintHeight, LAYOUT_CONSTRAINT_HEIGHT);
mapToConstant.append(R.styleable.Constraint_android_visibility, LAYOUT_VISIBILITY);
mapToConstant.append(R.styleable.Constraint_android_alpha, ALPHA);
mapToConstant.append(R.styleable.Constraint_android_elevation, ELEVATION);
mapToConstant.append(R.styleable.Constraint_android_rotationX, ROTATION_X);
mapToConstant.append(R.styleable.Constraint_android_rotationY, ROTATION_Y);
mapToConstant.append(R.styleable.Constraint_android_rotation, ROTATION);
mapToConstant.append(R.styleable.Constraint_android_scaleX, SCALE_X);
mapToConstant.append(R.styleable.Constraint_android_scaleY, SCALE_Y);
mapToConstant.append(R.styleable.Constraint_android_transformPivotX, TRANSFORM_PIVOT_X);
mapToConstant.append(R.styleable.Constraint_android_transformPivotY, TRANSFORM_PIVOT_Y);
mapToConstant.append(R.styleable.Constraint_android_translationX, TRANSLATION_X);
mapToConstant.append(R.styleable.Constraint_android_translationY, TRANSLATION_Y);
mapToConstant.append(R.styleable.Constraint_android_translationZ, TRANSLATION_Z);
mapToConstant.append(R.styleable.Constraint_layout_constraintWidth_default, WIDTH_DEFAULT);
mapToConstant.append(R.styleable.Constraint_layout_constraintHeight_default, HEIGHT_DEFAULT);
mapToConstant.append(R.styleable.Constraint_layout_constraintWidth_max, WIDTH_MAX);
mapToConstant.append(R.styleable.Constraint_layout_constraintHeight_max, HEIGHT_MAX);
mapToConstant.append(R.styleable.Constraint_layout_constraintWidth_min, WIDTH_MIN);
mapToConstant.append(R.styleable.Constraint_layout_constraintHeight_min, HEIGHT_MIN);
mapToConstant.append(R.styleable.Constraint_layout_constraintCircle, CIRCLE);
mapToConstant.append(R.styleable.Constraint_layout_constraintCircleRadius, CIRCLE_RADIUS);
mapToConstant.append(R.styleable.Constraint_layout_constraintCircleAngle, CIRCLE_ANGLE);
mapToConstant.append(R.styleable.Constraint_animateRelativeTo, ANIMATE_RELATIVE_TO);
mapToConstant.append(R.styleable.Constraint_transitionEasing, TRANSITION_EASING);
mapToConstant.append(R.styleable.Constraint_drawPath, DRAW_PATH);
mapToConstant.append(R.styleable.Constraint_transitionPathRotate, TRANSITION_PATH_ROTATE);
mapToConstant.append(R.styleable.Constraint_motionStagger, MOTION_STAGGER);
mapToConstant.append(R.styleable.Constraint_android_id, VIEW_ID);
mapToConstant.append(R.styleable.Constraint_motionProgress, PROGRESS);
mapToConstant.append(R.styleable.Constraint_layout_constraintWidth_percent, WIDTH_PERCENT);
mapToConstant.append(R.styleable.Constraint_layout_constraintHeight_percent, HEIGHT_PERCENT);
mapToConstant.append(R.styleable.Constraint_layout_wrapBehaviorInParent, LAYOUT_WRAP_BEHAVIOR);
mapToConstant.append(R.styleable.Constraint_chainUseRtl, CHAIN_USE_RTL);
mapToConstant.append(R.styleable.Constraint_barrierDirection, BARRIER_DIRECTION);
mapToConstant.append(R.styleable.Constraint_barrierMargin, BARRIER_MARGIN);
mapToConstant.append(R.styleable.Constraint_constraint_referenced_ids, CONSTRAINT_REFERENCED_IDS);
mapToConstant.append(R.styleable.Constraint_barrierAllowsGoneWidgets, BARRIER_ALLOWS_GONE_WIDGETS);
mapToConstant.append(R.styleable.Constraint_pathMotionArc, PATH_MOTION_ARC);
mapToConstant.append(R.styleable.Constraint_layout_constraintTag, CONSTRAINT_TAG);
mapToConstant.append(R.styleable.Constraint_visibilityMode, VISIBILITY_MODE);
mapToConstant.append(R.styleable.Constraint_layout_constrainedWidth, CONSTRAINED_WIDTH);
mapToConstant.append(R.styleable.Constraint_layout_constrainedHeight, CONSTRAINED_HEIGHT);
mapToConstant.append(R.styleable.Constraint_polarRelativeTo, ANIMATE_CIRCLE_ANGLE_TO);
mapToConstant.append(R.styleable.Constraint_transformPivotTarget, TRANSFORM_PIVOT_TARGET);
mapToConstant.append(R.styleable.Constraint_quantizeMotionSteps, QUANTIZE_MOTION_STEPS);
mapToConstant.append(R.styleable.Constraint_quantizeMotionPhase, QUANTIZE_MOTION_PHASE);
mapToConstant.append(R.styleable.Constraint_quantizeMotionInterpolator, QUANTIZE_MOTION_INTERPOLATOR);
/*
The tags not available in constraintOverride
Left here to help with documentation and understanding
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintLeft_toLeftOf, LEFT_TO_LEFT);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintLeft_toRightOf, LEFT_TO_RIGHT);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintRight_toLeftOf, RIGHT_TO_LEFT);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintRight_toRightOf, RIGHT_TO_RIGHT);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintTop_toTopOf, TOP_TO_TOP);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintTop_toBottomOf, TOP_TO_BOTTOM);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintBottom_toTopOf, BOTTOM_TO_TOP);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintBottom_toBottomOf, BOTTOM_TO_BOTTOM);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintBaseline_toBaselineOf, BASELINE_TO_BASELINE);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintGuide_begin, GUIDE_BEGIN);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintGuide_end, GUIDE_END);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintGuide_percent, GUIDE_PERCENT);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintStart_toEndOf, START_TO_END);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintStart_toStartOf, START_TO_START);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintEnd_toStartOf, END_TO_START);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintEnd_toEndOf, END_TO_END);
*/
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_editor_absoluteY, EDITOR_ABSOLUTE_X);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_editor_absoluteY, EDITOR_ABSOLUTE_Y);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_orientation, ORIENTATION);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_goneMarginLeft, GONE_LEFT_MARGIN);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_goneMarginTop, GONE_TOP_MARGIN);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_goneMarginRight, GONE_RIGHT_MARGIN);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_goneMarginBottom, GONE_BOTTOM_MARGIN);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_goneMarginStart, GONE_START_MARGIN);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_goneMarginEnd, GONE_END_MARGIN);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintVertical_weight, VERTICAL_WEIGHT);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintHorizontal_weight, HORIZONTAL_WEIGHT);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintHorizontal_chainStyle, HORIZONTAL_STYLE);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintVertical_chainStyle, VERTICAL_STYLE);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintHorizontal_bias, HORIZONTAL_BIAS);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintVertical_bias, VERTICAL_BIAS);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintDimensionRatio, DIMENSION_RATIO);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintLeft_creator, UNUSED);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintTop_creator, UNUSED);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintRight_creator, UNUSED);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintBottom_creator, UNUSED);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintBaseline_creator, UNUSED);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_layout_marginLeft, LEFT_MARGIN);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_layout_marginRight, RIGHT_MARGIN);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_layout_marginStart, START_MARGIN);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_layout_marginEnd, END_MARGIN);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_layout_marginTop, TOP_MARGIN);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_layout_marginBottom, BOTTOM_MARGIN);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_layout_width, LAYOUT_WIDTH);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_layout_height, LAYOUT_HEIGHT);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintWidth, LAYOUT_CONSTRAINT_WIDTH);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintHeight, LAYOUT_CONSTRAINT_HEIGHT);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_visibility, LAYOUT_VISIBILITY);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_alpha, ALPHA);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_elevation, ELEVATION);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_rotationX, ROTATION_X);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_rotationY, ROTATION_Y);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_rotation, ROTATION);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_scaleX, SCALE_X);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_scaleY, SCALE_Y);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_transformPivotX, TRANSFORM_PIVOT_X);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_transformPivotY, TRANSFORM_PIVOT_Y);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_translationX, TRANSLATION_X);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_translationY, TRANSLATION_Y);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_translationZ, TRANSLATION_Z);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintWidth_default, WIDTH_DEFAULT);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintHeight_default, HEIGHT_DEFAULT);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintWidth_max, WIDTH_MAX);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintHeight_max, HEIGHT_MAX);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintWidth_min, WIDTH_MIN);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintHeight_min, HEIGHT_MIN);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintCircleRadius, CIRCLE_RADIUS);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintCircleAngle, CIRCLE_ANGLE);
overrideMapToConstant.append(R.styleable.ConstraintOverride_animateRelativeTo, ANIMATE_RELATIVE_TO);
overrideMapToConstant.append(R.styleable.ConstraintOverride_transitionEasing, TRANSITION_EASING);
overrideMapToConstant.append(R.styleable.ConstraintOverride_drawPath, DRAW_PATH);
overrideMapToConstant.append(R.styleable.ConstraintOverride_transitionPathRotate, TRANSITION_PATH_ROTATE);
overrideMapToConstant.append(R.styleable.ConstraintOverride_motionStagger, MOTION_STAGGER);
overrideMapToConstant.append(R.styleable.ConstraintOverride_android_id, VIEW_ID);
overrideMapToConstant.append(R.styleable.ConstraintOverride_motionTarget, MOTION_TARGET);
overrideMapToConstant.append(R.styleable.ConstraintOverride_motionProgress, PROGRESS);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintWidth_percent, WIDTH_PERCENT);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintHeight_percent, HEIGHT_PERCENT);
overrideMapToConstant.append(R.styleable.ConstraintOverride_chainUseRtl, CHAIN_USE_RTL);
overrideMapToConstant.append(R.styleable.ConstraintOverride_barrierDirection, BARRIER_DIRECTION);
overrideMapToConstant.append(R.styleable.ConstraintOverride_barrierMargin, BARRIER_MARGIN);
overrideMapToConstant.append(R.styleable.ConstraintOverride_constraint_referenced_ids, CONSTRAINT_REFERENCED_IDS);
overrideMapToConstant.append(R.styleable.ConstraintOverride_barrierAllowsGoneWidgets, BARRIER_ALLOWS_GONE_WIDGETS);
overrideMapToConstant.append(R.styleable.ConstraintOverride_pathMotionArc, PATH_MOTION_ARC);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constraintTag, CONSTRAINT_TAG);
overrideMapToConstant.append(R.styleable.ConstraintOverride_visibilityMode, VISIBILITY_MODE);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constrainedWidth, CONSTRAINED_WIDTH);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_constrainedHeight, CONSTRAINED_HEIGHT);
overrideMapToConstant.append(R.styleable.ConstraintOverride_polarRelativeTo, ANIMATE_CIRCLE_ANGLE_TO);
overrideMapToConstant.append(R.styleable.ConstraintOverride_transformPivotTarget, TRANSFORM_PIVOT_TARGET);
overrideMapToConstant.append(R.styleable.ConstraintOverride_quantizeMotionSteps, QUANTIZE_MOTION_STEPS);
overrideMapToConstant.append(R.styleable.ConstraintOverride_quantizeMotionPhase, QUANTIZE_MOTION_PHASE);
overrideMapToConstant.append(R.styleable.ConstraintOverride_quantizeMotionInterpolator, QUANTIZE_MOTION_INTERPOLATOR);
overrideMapToConstant.append(R.styleable.ConstraintOverride_layout_wrapBehaviorInParent, LAYOUT_WRAP_BEHAVIOR);
}
public HashMap<String, ConstraintAttribute> getCustomAttributeSet() {
return mSavedAttributes;
}
public Constraint getParameters(int mId) {
return get(mId);
}
/**
* This will copy Constraints from the ConstraintSet
*
* @param set
*/
public void readFallback(ConstraintSet set) {
for (Integer key : set.mConstraints.keySet()) {
int id = key;
Constraint parent = set.mConstraints.get(key);
if (!mConstraints.containsKey(id)) {
mConstraints.put(id, new Constraint());
}
Constraint constraint = mConstraints.get(id);
if (constraint == null) {
continue;
}
if (!constraint.layout.mApply) {
constraint.layout.copyFrom(parent.layout);
}
if (!constraint.propertySet.mApply) {
constraint.propertySet.copyFrom(parent.propertySet);
}
if (!constraint.transform.mApply) {
constraint.transform.copyFrom(parent.transform);
}
if (!constraint.motion.mApply) {
constraint.motion.copyFrom(parent.motion);
}
for (String s : parent.mCustomConstraints.keySet()) {
if (!constraint.mCustomConstraints.containsKey(s)) {
constraint.mCustomConstraints.put(s, parent.mCustomConstraints.get(s));
}
}
}
}
/**
* This will copy Constraints from the ConstraintLayout if it does not have parameters
*
* @param constraintLayout
*/
public void readFallback(ConstraintLayout constraintLayout) {
int count = constraintLayout.getChildCount();
for (int i = 0; i < count; i++) {
View view = constraintLayout.getChildAt(i);
ConstraintLayout.LayoutParams param = (ConstraintLayout.LayoutParams) view.getLayoutParams();
int id = view.getId();
if (mForceId && id == -1) {
throw new RuntimeException("All children of ConstraintLayout must have ids to use ConstraintSet");
}
if (!mConstraints.containsKey(id)) {
mConstraints.put(id, new Constraint());
}
Constraint constraint = mConstraints.get(id);
if (constraint == null) {
continue;
}
if (!constraint.layout.mApply) {
constraint.fillFrom(id, param);
if (view instanceof ConstraintHelper) {
constraint.layout.mReferenceIds = ((ConstraintHelper) view).getReferencedIds();
if (view instanceof Barrier) {
Barrier barrier = (Barrier) view;
constraint.layout.mBarrierAllowsGoneWidgets = barrier.getAllowsGoneWidget();
constraint.layout.mBarrierDirection = barrier.getType();
constraint.layout.mBarrierMargin = barrier.getMargin();
}
}
constraint.layout.mApply = true;
}
if (!constraint.propertySet.mApply) {
constraint.propertySet.visibility = view.getVisibility();
constraint.propertySet.alpha = view.getAlpha();
constraint.propertySet.mApply = true;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (!constraint.transform.mApply) {
constraint.transform.mApply = true;
constraint.transform.rotation = view.getRotation();
constraint.transform.rotationX = view.getRotationX();
constraint.transform.rotationY = view.getRotationY();
constraint.transform.scaleX = view.getScaleX();
constraint.transform.scaleY = view.getScaleY();
float pivotX = view.getPivotX(); // we assume it is not set if set to 0.0
float pivotY = view.getPivotY(); // we assume it is not set if set to 0.0
if (pivotX != 0.0 || pivotY != 0.0) {
constraint.transform.transformPivotX = pivotX;
constraint.transform.transformPivotY = pivotY;
}
constraint.transform.translationX = view.getTranslationX();
constraint.transform.translationY = view.getTranslationY();
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
constraint.transform.translationZ = view.getTranslationZ();
if (constraint.transform.applyElevation) {
constraint.transform.elevation = view.getElevation();
}
}
}
}
}
}
public void applyDeltaFrom(ConstraintSet cs) {
for (Constraint from : cs.mConstraints.values()) {
if (from.mDelta != null) {
if (from.mTargetString != null) {
int count = 0;
for (int key : mConstraints.keySet()) {
Constraint potential = getConstraint(key);
if (potential.layout.mConstraintTag != null) {
if (from.mTargetString.matches(potential.layout.mConstraintTag)) {
from.mDelta.applyDelta(potential);
potential.mCustomConstraints.putAll((HashMap)from.mCustomConstraints.clone());
}
}
}
} else {
Constraint constraint = getConstraint(from.mViewId);
from.mDelta.applyDelta(constraint);
}
}
}
}
/**
* Parse the constraint dimension attribute
*
* @param a
* @param attr
* @param orientation
*/
static void parseDimensionConstraints(Object data, TypedArray a, int attr, int orientation) {
if (data == null) {
return;
}
// data can be of:
//
// ConstraintLayout.LayoutParams
// ConstraintSet.Layout
// Constraint.Delta
TypedValue v = a.peekValue(attr);
int type = v.type;
int finalValue = 0;
boolean finalConstrained = false;
switch (type) {
case TypedValue.TYPE_DIMENSION: {
finalValue = a.getDimensionPixelSize(attr, 0);
}
break;
case TypedValue.TYPE_STRING: {
String value = a.getString(attr);
parseDimensionConstraintsString(data, value, orientation);
return;
}
default: {
int value = a.getInt(attr, 0);
switch (value) {
case INTERNAL_WRAP_CONTENT:
case INTERNAL_MATCH_PARENT: {
finalValue = value;
}
break;
case INTERNAL_MATCH_CONSTRAINT: {
finalValue = MATCH_CONSTRAINT;
}
break;
case INTERNAL_WRAP_CONTENT_CONSTRAINED: {
finalValue = WRAP_CONTENT;
finalConstrained = true;
}
break;
}
}
}
if (data instanceof ConstraintLayout.LayoutParams) {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) data;
if (orientation == HORIZONTAL) {
params.width = finalValue;
params.constrainedWidth = finalConstrained;
} else {
params.height = finalValue;
params.constrainedHeight = finalConstrained;
}
} else if (data instanceof Layout) {
Layout params = (Layout) data;
if (orientation == HORIZONTAL) {
params.mWidth = finalValue;
params.constrainedWidth = finalConstrained;
} else {
params.mHeight = finalValue;
params.constrainedHeight = finalConstrained;
}
} else if (data instanceof Constraint.Delta) {
Constraint.Delta params = (Constraint.Delta) data;
if (orientation == HORIZONTAL) {
params.add(LAYOUT_WIDTH, finalValue);
params.add(CONSTRAINED_WIDTH, finalConstrained);
} else {
params.add(LAYOUT_HEIGHT, finalValue);
params.add(CONSTRAINED_HEIGHT, finalConstrained);
}
}
}
/**
* Parse the dimension ratio string
*
* @param value
*/
static void parseDimensionRatioString(ConstraintLayout.LayoutParams params, String value) {
String dimensionRatio = value;
float dimensionRatioValue = Float.NaN;
int dimensionRatioSide = UNSET;
if (dimensionRatio != null) {
int len = dimensionRatio.length();
int commaIndex = dimensionRatio.indexOf(',');
if (commaIndex > 0 && commaIndex < len - 1) {
String dimension = dimensionRatio.substring(0, commaIndex);
if (dimension.equalsIgnoreCase("W")) {
dimensionRatioSide = HORIZONTAL;
} else if (dimension.equalsIgnoreCase("H")) {
dimensionRatioSide = VERTICAL;
}
commaIndex++;
} else {
commaIndex = 0;
}
int colonIndex = dimensionRatio.indexOf(':');
if (colonIndex >= 0 && colonIndex < len - 1) {
String nominator = dimensionRatio.substring(commaIndex, colonIndex);
String denominator = dimensionRatio.substring(colonIndex + 1);
if (nominator.length() > 0 && denominator.length() > 0) {
try {
float nominatorValue = Float.parseFloat(nominator);
float denominatorValue = Float.parseFloat(denominator);
if (nominatorValue > 0 && denominatorValue > 0) {
if (dimensionRatioSide == VERTICAL) {
dimensionRatioValue = Math.abs(denominatorValue / nominatorValue);
} else {
dimensionRatioValue = Math.abs(nominatorValue / denominatorValue);
}
}
} catch (NumberFormatException e) {
// Ignore
}
}
} else {
String r = dimensionRatio.substring(commaIndex);
if (r.length() > 0) {
try {
dimensionRatioValue = Float.parseFloat(r);
} catch (NumberFormatException e) {
// Ignore
}
}
}
}
params.dimensionRatio = dimensionRatio;
params.dimensionRatioValue = dimensionRatioValue;
params.dimensionRatioSide = dimensionRatioSide;
}
/**
* Parse the constraints string dimension
*
* @param value
* @param orientation
*/
static void parseDimensionConstraintsString(Object data, String value, int orientation) {
// data can be of:
//
// ConstraintLayout.LayoutParams
// ConstraintSet.Layout
// Constraint.Delta
// String should be of the form
//
// "<Key>=<Value>"
// supported Keys are:
// "weight=<value>"
// "ratio=<value>"
// "parent=<value>"
if (value == null) {
return;
}
int equalIndex = value.indexOf('=');
int len = value.length();
if (equalIndex > 0 && equalIndex < len - 1) {
String key = value.substring(0, equalIndex);
String val = value.substring(equalIndex + 1);
if (val.length() > 0) {
key = key.trim();
val = val.trim();
if (KEY_RATIO.equalsIgnoreCase(key)) {
if (data instanceof ConstraintLayout.LayoutParams) {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) data;
if (orientation == HORIZONTAL) {
params.width = MATCH_CONSTRAINT;
} else {
params.height = MATCH_CONSTRAINT;
}
parseDimensionRatioString(params, val);
} else if (data instanceof Layout) {
Layout params = (Layout) data;
params.dimensionRatio = val;
} else if (data instanceof Constraint.Delta) {
Constraint.Delta params = (Constraint.Delta) data;
params.add(DIMENSION_RATIO, val);
}
} else if (KEY_WEIGHT.equalsIgnoreCase(key)) {
try {
float weight = Float.parseFloat(val);
if (data instanceof ConstraintLayout.LayoutParams) {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) data;
if (orientation == HORIZONTAL) {
params.width = MATCH_CONSTRAINT;
params.horizontalWeight = weight;
} else {
params.height = MATCH_CONSTRAINT;
params.verticalWeight = weight;
}
} else if (data instanceof Layout) {
Layout params = (Layout) data;
if (orientation == HORIZONTAL) {
params.mWidth = MATCH_CONSTRAINT;
params.horizontalWeight = weight;
} else {
params.mHeight = MATCH_CONSTRAINT;
params.verticalWeight = weight;
}
} else if (data instanceof Constraint.Delta) {
Constraint.Delta params = (Constraint.Delta) data;
if (orientation == HORIZONTAL) {
params.add(LAYOUT_WIDTH, MATCH_CONSTRAINT);
params.add(HORIZONTAL_WEIGHT, weight);
} else {
params.add(LAYOUT_HEIGHT, MATCH_CONSTRAINT);
params.add(VERTICAL_WEIGHT, weight);
}
}
} catch (NumberFormatException e) {
// nothing
}
} else if (KEY_PERCENT_PARENT.equalsIgnoreCase(key)) {
try {
float percent = Math.min(1, Float.parseFloat(val));
percent = Math.max(0, percent);
if (data instanceof ConstraintLayout.LayoutParams) {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) data;
if (orientation == HORIZONTAL) {
params.width = MATCH_CONSTRAINT;
params.matchConstraintPercentWidth = percent;
params.matchConstraintDefaultWidth = MATCH_CONSTRAINT_PERCENT;
} else {
params.height = MATCH_CONSTRAINT;
params.matchConstraintPercentHeight = percent;
params.matchConstraintDefaultHeight = MATCH_CONSTRAINT_PERCENT;
}
} else if (data instanceof Layout) {
Layout params = (Layout) data;
if (orientation == HORIZONTAL) {
params.mWidth = MATCH_CONSTRAINT;
params.widthPercent = percent;
params.widthDefault = MATCH_CONSTRAINT_PERCENT;
} else {
params.mHeight = MATCH_CONSTRAINT;
params.heightPercent = percent;
params.heightDefault = MATCH_CONSTRAINT_PERCENT;
}
} else if (data instanceof Constraint.Delta) {
Constraint.Delta params = (Constraint.Delta) data;
if (orientation == HORIZONTAL) {
params.add(LAYOUT_WIDTH, MATCH_CONSTRAINT);
params.add(WIDTH_DEFAULT, MATCH_CONSTRAINT_PERCENT);
} else {
params.add(LAYOUT_HEIGHT, MATCH_CONSTRAINT);
params.add(HEIGHT_DEFAULT, MATCH_CONSTRAINT_PERCENT);
}
}
} catch (NumberFormatException e) {
// nothing
}
}
}
}
}
/**
* @suppress
*/
public static class Layout {
public boolean mIsGuideline = false;
public boolean mApply = false;
public boolean mOverride = false;
public int mWidth;
public int mHeight;
public static final int UNSET = ConstraintSet.UNSET;
public static final int UNSET_GONE_MARGIN = Integer.MIN_VALUE;
public int guideBegin = UNSET;
public int guideEnd = UNSET;
public float guidePercent = UNSET;
public int leftToLeft = UNSET;
public int leftToRight = UNSET;
public int rightToLeft = UNSET;
public int rightToRight = UNSET;
public int topToTop = UNSET;
public int topToBottom = UNSET;
public int bottomToTop = UNSET;
public int bottomToBottom = UNSET;
public int baselineToBaseline = UNSET;
public int baselineToTop = UNSET;
public int baselineToBottom = UNSET;
public int startToEnd = UNSET;
public int startToStart = UNSET;
public int endToStart = UNSET;
public int endToEnd = UNSET;
public float horizontalBias = 0.5f;
public float verticalBias = 0.5f;
public String dimensionRatio = null;
public int circleConstraint = UNSET;
public int circleRadius = 0;
public float circleAngle = 0;
public int editorAbsoluteX = UNSET;
public int editorAbsoluteY = UNSET;
public int orientation = UNSET;
public int leftMargin = 0;
public int rightMargin = 0;
public int topMargin = 0;
public int bottomMargin = 0;
public int endMargin = 0;
public int startMargin = 0;
public int baselineMargin = 0;
public int goneLeftMargin = UNSET_GONE_MARGIN;
public int goneTopMargin = UNSET_GONE_MARGIN;
public int goneRightMargin = UNSET_GONE_MARGIN;
public int goneBottomMargin = UNSET_GONE_MARGIN;
public int goneEndMargin = UNSET_GONE_MARGIN;
public int goneStartMargin = UNSET_GONE_MARGIN;
public int goneBaselineMargin = UNSET_GONE_MARGIN;
public float verticalWeight = UNSET;
public float horizontalWeight = UNSET;
public int horizontalChainStyle = CHAIN_SPREAD;
public int verticalChainStyle = CHAIN_SPREAD;
public int widthDefault = ConstraintWidget.MATCH_CONSTRAINT_SPREAD;
public int heightDefault = ConstraintWidget.MATCH_CONSTRAINT_SPREAD;
public int widthMax = 0;
public int heightMax = 0;
public int widthMin = 0;
public int heightMin = 0;
public float widthPercent = 1;
public float heightPercent = 1;
public int mBarrierDirection = UNSET;
public int mBarrierMargin = 0;
public int mHelperType = UNSET;
public int[] mReferenceIds;
public String mReferenceIdString;
public String mConstraintTag;
public boolean constrainedWidth = false;
public boolean constrainedHeight = false;
// TODO public boolean mChainUseRtl = false;
public boolean mBarrierAllowsGoneWidgets = true;
public int mWrapBehavior = ConstraintWidget.WRAP_BEHAVIOR_INCLUDED;
public void copyFrom(Layout src) {
mIsGuideline = src.mIsGuideline;
mWidth = src.mWidth;
mApply = src.mApply;
mHeight = src.mHeight;
guideBegin = src.guideBegin;
guideEnd = src.guideEnd;
guidePercent = src.guidePercent;
leftToLeft = src.leftToLeft;
leftToRight = src.leftToRight;
rightToLeft = src.rightToLeft;
rightToRight = src.rightToRight;
topToTop = src.topToTop;
topToBottom = src.topToBottom;
bottomToTop = src.bottomToTop;
bottomToBottom = src.bottomToBottom;
baselineToBaseline = src.baselineToBaseline;
baselineToTop = src.baselineToTop;
baselineToBottom = src.baselineToBottom;
startToEnd = src.startToEnd;
startToStart = src.startToStart;
endToStart = src.endToStart;
endToEnd = src.endToEnd;
horizontalBias = src.horizontalBias;
verticalBias = src.verticalBias;
dimensionRatio = src.dimensionRatio;
circleConstraint = src.circleConstraint;
circleRadius = src.circleRadius;
circleAngle = src.circleAngle;
editorAbsoluteX = src.editorAbsoluteX;
editorAbsoluteY = src.editorAbsoluteY;
orientation = src.orientation;
leftMargin = src.leftMargin;
rightMargin = src.rightMargin;
topMargin = src.topMargin;
bottomMargin = src.bottomMargin;
endMargin = src.endMargin;
startMargin = src.startMargin;
baselineMargin = src.baselineMargin;
goneLeftMargin = src.goneLeftMargin;
goneTopMargin = src.goneTopMargin;
goneRightMargin = src.goneRightMargin;
goneBottomMargin = src.goneBottomMargin;
goneEndMargin = src.goneEndMargin;
goneStartMargin = src.goneStartMargin;
goneBaselineMargin = src.goneBaselineMargin;
verticalWeight = src.verticalWeight;
horizontalWeight = src.horizontalWeight;
horizontalChainStyle = src.horizontalChainStyle;
verticalChainStyle = src.verticalChainStyle;
widthDefault = src.widthDefault;
heightDefault = src.heightDefault;
widthMax = src.widthMax;
heightMax = src.heightMax;
widthMin = src.widthMin;
heightMin = src.heightMin;
widthPercent = src.widthPercent;
heightPercent = src.heightPercent;
mBarrierDirection = src.mBarrierDirection;
mBarrierMargin = src.mBarrierMargin;
mHelperType = src.mHelperType;
mConstraintTag = src.mConstraintTag;
if (src.mReferenceIds != null && src.mReferenceIdString == null) {
mReferenceIds = Arrays.copyOf(src.mReferenceIds, src.mReferenceIds.length);
} else {
mReferenceIds = null;
}
mReferenceIdString = src.mReferenceIdString;
constrainedWidth = src.constrainedWidth;
constrainedHeight = src.constrainedHeight;
// TODO mChainUseRtl = t.mChainUseRtl;
mBarrierAllowsGoneWidgets = src.mBarrierAllowsGoneWidgets;
mWrapBehavior = src.mWrapBehavior;
}
private static SparseIntArray mapToConstant = new SparseIntArray();
private static final int BASELINE_TO_BASELINE = 1;
private static final int BOTTOM_MARGIN = 2;
private static final int BOTTOM_TO_BOTTOM = 3;
private static final int BOTTOM_TO_TOP = 4;
private static final int DIMENSION_RATIO = 5;
private static final int EDITOR_ABSOLUTE_X = 6;
private static final int EDITOR_ABSOLUTE_Y = 7;
private static final int END_MARGIN = 8;
private static final int END_TO_END = 9;
private static final int END_TO_START = 10;
private static final int GONE_BOTTOM_MARGIN = 11;
private static final int GONE_END_MARGIN = 12;
private static final int GONE_LEFT_MARGIN = 13;
private static final int GONE_RIGHT_MARGIN = 14;
private static final int GONE_START_MARGIN = 15;
private static final int GONE_TOP_MARGIN = 16;
private static final int GUIDE_BEGIN = 17;
private static final int GUIDE_END = 18;
private static final int GUIDE_PERCENT = 19;
private static final int HORIZONTAL_BIAS = 20;
private static final int LAYOUT_HEIGHT = 21;
private static final int LAYOUT_WIDTH = 22;
private static final int LEFT_MARGIN = 23;
private static final int LEFT_TO_LEFT = 24;
private static final int LEFT_TO_RIGHT = 25;
private static final int ORIENTATION = 26;
private static final int RIGHT_MARGIN = 27;
private static final int RIGHT_TO_LEFT = 28;
private static final int RIGHT_TO_RIGHT = 29;
private static final int START_MARGIN = 30;
private static final int START_TO_END = 31;
private static final int START_TO_START = 32;
private static final int TOP_MARGIN = 33;
private static final int TOP_TO_BOTTOM = 34;
private static final int TOP_TO_TOP = 35;
private static final int VERTICAL_BIAS = 36;
private static final int HORIZONTAL_WEIGHT = 37;
private static final int VERTICAL_WEIGHT = 38;
private static final int HORIZONTAL_STYLE = 39;
private static final int VERTICAL_STYLE = 40;
private static final int LAYOUT_CONSTRAINT_WIDTH = 41;
private static final int LAYOUT_CONSTRAINT_HEIGHT = 42;
private static final int CIRCLE = 61;
private static final int CIRCLE_RADIUS = 62;
private static final int CIRCLE_ANGLE = 63;
private static final int WIDTH_PERCENT = 69;
private static final int HEIGHT_PERCENT = 70;
private static final int CHAIN_USE_RTL = 71;
private static final int BARRIER_DIRECTION = 72;
private static final int BARRIER_MARGIN = 73;
private static final int CONSTRAINT_REFERENCED_IDS = 74;
private static final int BARRIER_ALLOWS_GONE_WIDGETS = 75;
private static final int UNUSED = 76;
static {
mapToConstant.append(R.styleable.Layout_layout_constraintLeft_toLeftOf, LEFT_TO_LEFT);
mapToConstant.append(R.styleable.Layout_layout_constraintLeft_toRightOf, LEFT_TO_RIGHT);
mapToConstant.append(R.styleable.Layout_layout_constraintRight_toLeftOf, RIGHT_TO_LEFT);
mapToConstant.append(R.styleable.Layout_layout_constraintRight_toRightOf, RIGHT_TO_RIGHT);
mapToConstant.append(R.styleable.Layout_layout_constraintTop_toTopOf, TOP_TO_TOP);
mapToConstant.append(R.styleable.Layout_layout_constraintTop_toBottomOf, TOP_TO_BOTTOM);
mapToConstant.append(R.styleable.Layout_layout_constraintBottom_toTopOf, BOTTOM_TO_TOP);
mapToConstant.append(R.styleable.Layout_layout_constraintBottom_toBottomOf, BOTTOM_TO_BOTTOM);
mapToConstant.append(R.styleable.Layout_layout_constraintBaseline_toBaselineOf, BASELINE_TO_BASELINE);
mapToConstant.append(R.styleable.Layout_layout_editor_absoluteX, EDITOR_ABSOLUTE_X);
mapToConstant.append(R.styleable.Layout_layout_editor_absoluteY, EDITOR_ABSOLUTE_Y);
mapToConstant.append(R.styleable.Layout_layout_constraintGuide_begin, GUIDE_BEGIN);
mapToConstant.append(R.styleable.Layout_layout_constraintGuide_end, GUIDE_END);
mapToConstant.append(R.styleable.Layout_layout_constraintGuide_percent, GUIDE_PERCENT);
mapToConstant.append(R.styleable.Layout_android_orientation, ORIENTATION);
mapToConstant.append(R.styleable.Layout_layout_constraintStart_toEndOf, START_TO_END);
mapToConstant.append(R.styleable.Layout_layout_constraintStart_toStartOf, START_TO_START);
mapToConstant.append(R.styleable.Layout_layout_constraintEnd_toStartOf, END_TO_START);
mapToConstant.append(R.styleable.Layout_layout_constraintEnd_toEndOf, END_TO_END);
mapToConstant.append(R.styleable.Layout_layout_goneMarginLeft, GONE_LEFT_MARGIN);
mapToConstant.append(R.styleable.Layout_layout_goneMarginTop, GONE_TOP_MARGIN);
mapToConstant.append(R.styleable.Layout_layout_goneMarginRight, GONE_RIGHT_MARGIN);
mapToConstant.append(R.styleable.Layout_layout_goneMarginBottom, GONE_BOTTOM_MARGIN);
mapToConstant.append(R.styleable.Layout_layout_goneMarginStart, GONE_START_MARGIN);
mapToConstant.append(R.styleable.Layout_layout_goneMarginEnd, GONE_END_MARGIN);
mapToConstant.append(R.styleable.Layout_layout_constraintVertical_weight, VERTICAL_WEIGHT);
mapToConstant.append(R.styleable.Layout_layout_constraintHorizontal_weight, HORIZONTAL_WEIGHT);
mapToConstant.append(R.styleable.Layout_layout_constraintHorizontal_chainStyle, HORIZONTAL_STYLE);
mapToConstant.append(R.styleable.Layout_layout_constraintVertical_chainStyle, VERTICAL_STYLE);
mapToConstant.append(R.styleable.Layout_layout_constraintHorizontal_bias, HORIZONTAL_BIAS);
mapToConstant.append(R.styleable.Layout_layout_constraintVertical_bias, VERTICAL_BIAS);
mapToConstant.append(R.styleable.Layout_layout_constraintDimensionRatio, DIMENSION_RATIO);
mapToConstant.append(R.styleable.Layout_layout_constraintLeft_creator, UNUSED);
mapToConstant.append(R.styleable.Layout_layout_constraintTop_creator, UNUSED);
mapToConstant.append(R.styleable.Layout_layout_constraintRight_creator, UNUSED);
mapToConstant.append(R.styleable.Layout_layout_constraintBottom_creator, UNUSED);
mapToConstant.append(R.styleable.Layout_layout_constraintBaseline_creator, UNUSED);
mapToConstant.append(R.styleable.Layout_android_layout_marginLeft, LEFT_MARGIN);
mapToConstant.append(R.styleable.Layout_android_layout_marginRight, RIGHT_MARGIN);
mapToConstant.append(R.styleable.Layout_android_layout_marginStart, START_MARGIN);
mapToConstant.append(R.styleable.Layout_android_layout_marginEnd, END_MARGIN);
mapToConstant.append(R.styleable.Layout_android_layout_marginTop, TOP_MARGIN);
mapToConstant.append(R.styleable.Layout_android_layout_marginBottom, BOTTOM_MARGIN);
mapToConstant.append(R.styleable.Layout_android_layout_width, LAYOUT_WIDTH);
mapToConstant.append(R.styleable.Layout_android_layout_height, LAYOUT_HEIGHT);
mapToConstant.append(R.styleable.Layout_layout_constraintWidth, LAYOUT_CONSTRAINT_WIDTH);
mapToConstant.append(R.styleable.Layout_layout_constraintHeight, LAYOUT_CONSTRAINT_HEIGHT);
mapToConstant.append(R.styleable.Layout_layout_constrainedWidth, LAYOUT_CONSTRAINT_WIDTH);
mapToConstant.append(R.styleable.Layout_layout_constrainedHeight, LAYOUT_CONSTRAINT_HEIGHT);
mapToConstant.append(R.styleable.Layout_layout_wrapBehaviorInParent, LAYOUT_WRAP_BEHAVIOR);
mapToConstant.append(R.styleable.Layout_layout_constraintCircle, CIRCLE);
mapToConstant.append(R.styleable.Layout_layout_constraintCircleRadius, CIRCLE_RADIUS);
mapToConstant.append(R.styleable.Layout_layout_constraintCircleAngle, CIRCLE_ANGLE);
mapToConstant.append(R.styleable.Layout_layout_constraintWidth_percent, WIDTH_PERCENT);
mapToConstant.append(R.styleable.Layout_layout_constraintHeight_percent, HEIGHT_PERCENT);
mapToConstant.append(R.styleable.Layout_chainUseRtl, CHAIN_USE_RTL);
mapToConstant.append(R.styleable.Layout_barrierDirection, BARRIER_DIRECTION);
mapToConstant.append(R.styleable.Layout_barrierMargin, BARRIER_MARGIN);
mapToConstant.append(R.styleable.Layout_constraint_referenced_ids, CONSTRAINT_REFERENCED_IDS);
mapToConstant.append(R.styleable.Layout_barrierAllowsGoneWidgets, BARRIER_ALLOWS_GONE_WIDGETS);
}
void fillFromAttributeList(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Layout);
mApply = true;
final int N = a.getIndexCount();
for (int i = 0; i < N; i++) {
int attr = a.getIndex(i);
switch (mapToConstant.get(attr)) {
case LEFT_TO_LEFT:
leftToLeft = lookupID(a, attr, leftToLeft);
break;
case LEFT_TO_RIGHT:
leftToRight = lookupID(a, attr, leftToRight);
break;
case RIGHT_TO_LEFT:
rightToLeft = lookupID(a, attr, rightToLeft);
break;
case RIGHT_TO_RIGHT:
rightToRight = lookupID(a, attr, rightToRight);
break;
case TOP_TO_TOP:
topToTop = lookupID(a, attr, topToTop);
break;
case TOP_TO_BOTTOM:
topToBottom = lookupID(a, attr, topToBottom);
break;
case BOTTOM_TO_TOP:
bottomToTop = lookupID(a, attr, bottomToTop);
break;
case BOTTOM_TO_BOTTOM:
bottomToBottom = lookupID(a, attr, bottomToBottom);
break;
case BASELINE_TO_BASELINE:
baselineToBaseline = lookupID(a, attr, baselineToBaseline);
break;
case BASELINE_TO_TOP:
baselineToTop = lookupID(a, attr, baselineToTop);
break;
case BASELINE_TO_BOTTOM:
baselineToBottom = lookupID(a, attr, baselineToBottom);
break;
case EDITOR_ABSOLUTE_X:
editorAbsoluteX = a.getDimensionPixelOffset(attr, editorAbsoluteX);
break;
case EDITOR_ABSOLUTE_Y:
editorAbsoluteY = a.getDimensionPixelOffset(attr, editorAbsoluteY);
break;
case GUIDE_BEGIN:
guideBegin = a.getDimensionPixelOffset(attr, guideBegin);
break;
case GUIDE_END:
guideEnd = a.getDimensionPixelOffset(attr, guideEnd);
break;
case GUIDE_PERCENT:
guidePercent = a.getFloat(attr, guidePercent);
break;
case ORIENTATION:
orientation = a.getInt(attr, orientation);
break;
case START_TO_END:
startToEnd = lookupID(a, attr, startToEnd);
break;
case START_TO_START:
startToStart = lookupID(a, attr, startToStart);
break;
case END_TO_START:
endToStart = lookupID(a, attr, endToStart);
break;
case END_TO_END:
endToEnd = lookupID(a, attr, endToEnd);
break;
case CIRCLE:
circleConstraint = lookupID(a, attr, circleConstraint);
break;
case CIRCLE_RADIUS:
circleRadius = a.getDimensionPixelSize(attr, circleRadius);
break;
case CIRCLE_ANGLE:
circleAngle = a.getFloat(attr, circleAngle);
break;
case GONE_LEFT_MARGIN:
goneLeftMargin = a.getDimensionPixelSize(attr, goneLeftMargin);
break;
case GONE_TOP_MARGIN:
goneTopMargin = a.getDimensionPixelSize(attr, goneTopMargin);
break;
case GONE_RIGHT_MARGIN:
goneRightMargin = a.getDimensionPixelSize(attr, goneRightMargin);
break;
case GONE_BOTTOM_MARGIN:
goneBottomMargin = a.getDimensionPixelSize(attr, goneBottomMargin);
break;
case GONE_START_MARGIN:
goneStartMargin = a.getDimensionPixelSize(attr, goneStartMargin);
break;
case GONE_END_MARGIN:
goneEndMargin = a.getDimensionPixelSize(attr, goneEndMargin);
break;
case GONE_BASELINE_MARGIN:
goneBaselineMargin = a.getDimensionPixelSize(attr, goneBaselineMargin);
break;
case HORIZONTAL_BIAS:
horizontalBias = a.getFloat(attr, horizontalBias);
break;
case VERTICAL_BIAS:
verticalBias = a.getFloat(attr, verticalBias);
break;
case LEFT_MARGIN:
leftMargin = a.getDimensionPixelSize(attr, leftMargin);
break;
case RIGHT_MARGIN:
rightMargin = a.getDimensionPixelSize(attr, rightMargin);
break;
case START_MARGIN:
if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) {
startMargin = a.getDimensionPixelSize(attr, startMargin);
}
break;
case END_MARGIN:
if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) {
endMargin = a.getDimensionPixelSize(attr, endMargin);
}
break;
case TOP_MARGIN:
topMargin = a.getDimensionPixelSize(attr, topMargin);
break;
case BOTTOM_MARGIN:
bottomMargin = a.getDimensionPixelSize(attr, bottomMargin);
break;
case BASELINE_MARGIN:
baselineMargin = a.getDimensionPixelSize(attr, baselineMargin);
break;
case LAYOUT_WIDTH:
mWidth = a.getLayoutDimension(attr, mWidth);
break;
case LAYOUT_HEIGHT:
mHeight = a.getLayoutDimension(attr, mHeight);
break;
case LAYOUT_CONSTRAINT_WIDTH:
ConstraintSet.parseDimensionConstraints(this, a, attr, HORIZONTAL);
break;
case LAYOUT_CONSTRAINT_HEIGHT:
ConstraintSet.parseDimensionConstraints(this, a, attr, VERTICAL);
break;
case WIDTH_DEFAULT:
widthDefault = a.getInt(attr, widthDefault);
break;
case HEIGHT_DEFAULT:
heightDefault = a.getInt(attr, heightDefault);
break;
case VERTICAL_WEIGHT:
verticalWeight = a.getFloat(attr, verticalWeight);
break;
case HORIZONTAL_WEIGHT:
horizontalWeight = a.getFloat(attr, horizontalWeight);
break;
case VERTICAL_STYLE:
verticalChainStyle = a.getInt(attr, verticalChainStyle);
break;
case HORIZONTAL_STYLE:
horizontalChainStyle = a.getInt(attr, horizontalChainStyle);
break;
case DIMENSION_RATIO:
dimensionRatio = a.getString(attr);
break;
case HEIGHT_MAX:
heightMax = a.getDimensionPixelSize(attr, heightMax);
break;
case WIDTH_MAX:
widthMax = a.getDimensionPixelSize(attr, widthMax);
break;
case HEIGHT_MIN:
heightMin = a.getDimensionPixelSize(attr, heightMin);
break;
case WIDTH_MIN:
widthMin = a.getDimensionPixelSize(attr, widthMin);
break;
case WIDTH_PERCENT:
widthPercent = a.getFloat(attr, 1);
break;
case HEIGHT_PERCENT:
heightPercent = a.getFloat(attr, 1);
break;
case CONSTRAINED_WIDTH:
constrainedWidth = a.getBoolean(attr, constrainedWidth);
break;
case CONSTRAINED_HEIGHT:
constrainedHeight = a.getBoolean(attr, constrainedHeight);
break;
case CHAIN_USE_RTL:
Log.e(TAG, "CURRENTLY UNSUPPORTED"); // TODO add support or remove
// TODO add support or remove c.mChainUseRtl = a.getBoolean(attr,c.mChainUseRtl);
break;
case BARRIER_DIRECTION:
mBarrierDirection = a.getInt(attr, mBarrierDirection);
break;
case LAYOUT_WRAP_BEHAVIOR:
mWrapBehavior = a.getInt(attr, mWrapBehavior);
break;
case BARRIER_MARGIN:
mBarrierMargin = a.getDimensionPixelSize(attr, mBarrierMargin);
break;
case CONSTRAINT_REFERENCED_IDS:
mReferenceIdString = a.getString(attr);
break;
case BARRIER_ALLOWS_GONE_WIDGETS:
mBarrierAllowsGoneWidgets = a.getBoolean(attr, mBarrierAllowsGoneWidgets);
break;
case CONSTRAINT_TAG:
mConstraintTag = a.getString(attr);
break;
case UNUSED:
Log.w(TAG,
"unused attribute 0x" + Integer.toHexString(attr) + " " + mapToConstant.get(attr));
break;
default:
Log.w(TAG,
"Unknown attribute 0x" + Integer.toHexString(attr) + " " + mapToConstant.get(attr));
}
}
a.recycle();
}
public void dump(MotionScene scene, StringBuilder stringBuilder) {
Field[] fields = this.getClass().getDeclaredFields();
stringBuilder.append("\n");
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
String name = field.getName();
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
// if (!field.isAccessible()) {
// continue;
// } if (!field.isAccessible()) {
// continue;
// }
try {
Object value = field.get(this);
Class<?> type = field.getType();
if (type == Integer.TYPE) {
Integer iValue = (Integer) value;
if (iValue != UNSET) {
String stringId = scene.lookUpConstraintName(iValue);
stringBuilder.append(" ");
stringBuilder.append(name);
stringBuilder.append(" = \"");
stringBuilder.append((stringId == null) ? iValue : stringId);
stringBuilder.append("\"\n");
}
} else if (type == Float.TYPE) {
Float fValue = (Float) value;
if (fValue != UNSET) {
stringBuilder.append(" ");
stringBuilder.append(name);
stringBuilder.append(" = \"");
stringBuilder.append(fValue);
stringBuilder.append("\"\n");
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
/**
* @suppress
*/
public static class Transform {
public boolean mApply = false;
public float rotation = 0;
public float rotationX = 0;
public float rotationY = 0;
public float scaleX = 1;
public float scaleY = 1;
public float transformPivotX = Float.NaN;
public float transformPivotY = Float.NaN;
public int transformPivotTarget = UNSET;
public float translationX = 0;
public float translationY = 0;
public float translationZ = 0;
public boolean applyElevation = false;
public float elevation = 0;
public void copyFrom(Transform src) {
mApply = src.mApply;
rotation = src.rotation;
rotationX = src.rotationX;
rotationY = src.rotationY;
scaleX = src.scaleX;
scaleY = src.scaleY;
transformPivotX = src.transformPivotX;
transformPivotY = src.transformPivotY;
transformPivotTarget = src.transformPivotTarget;
translationX = src.translationX;
translationY = src.translationY;
translationZ = src.translationZ;
applyElevation = src.applyElevation;
elevation = src.elevation;
}
private static SparseIntArray mapToConstant = new SparseIntArray();
private static final int ROTATION = 1;
private static final int ROTATION_X = 2;
private static final int ROTATION_Y = 3;
private static final int SCALE_X = 4;
private static final int SCALE_Y = 5;
private static final int TRANSFORM_PIVOT_X = 6;
private static final int TRANSFORM_PIVOT_Y = 7;
private static final int TRANSLATION_X = 8;
private static final int TRANSLATION_Y = 9;
private static final int TRANSLATION_Z = 10;
private static final int ELEVATION = 11;
private static final int TRANSFORM_PIVOT_TARGET = 12;
static {
mapToConstant.append(R.styleable.Transform_android_rotation, ROTATION);
mapToConstant.append(R.styleable.Transform_android_rotationX, ROTATION_X);
mapToConstant.append(R.styleable.Transform_android_rotationY, ROTATION_Y);
mapToConstant.append(R.styleable.Transform_android_scaleX, SCALE_X);
mapToConstant.append(R.styleable.Transform_android_scaleY, SCALE_Y);
mapToConstant.append(R.styleable.Transform_android_transformPivotX, TRANSFORM_PIVOT_X);
mapToConstant.append(R.styleable.Transform_android_transformPivotY, TRANSFORM_PIVOT_Y);
mapToConstant.append(R.styleable.Transform_android_translationX, TRANSLATION_X);
mapToConstant.append(R.styleable.Transform_android_translationY, TRANSLATION_Y);
mapToConstant.append(R.styleable.Transform_android_translationZ, TRANSLATION_Z);
mapToConstant.append(R.styleable.Transform_android_elevation, ELEVATION);
mapToConstant.append(R.styleable.Transform_transformPivotTarget, TRANSFORM_PIVOT_TARGET);
}
void fillFromAttributeList(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Transform);
mApply = true;
final int N = a.getIndexCount();
for (int i = 0; i < N; i++) {
int attr = a.getIndex(i);
switch (mapToConstant.get(attr)) {
case ROTATION:
rotation = a.getFloat(attr, rotation);
break;
case ROTATION_X:
rotationX = a.getFloat(attr, rotationX);
break;
case ROTATION_Y:
rotationY = a.getFloat(attr, rotationY);
break;
case SCALE_X:
scaleX = a.getFloat(attr, scaleX);
break;
case SCALE_Y:
scaleY = a.getFloat(attr, scaleY);
break;
case TRANSFORM_PIVOT_X:
transformPivotX = a.getDimension(attr, transformPivotX);
break;
case TRANSFORM_PIVOT_Y:
transformPivotY = a.getDimension(attr, transformPivotY);
break;
case TRANSFORM_PIVOT_TARGET:
transformPivotTarget = lookupID(a, attr, transformPivotTarget);
break;
case TRANSLATION_X:
translationX = a.getDimension(attr, translationX);
break;
case TRANSLATION_Y:
translationY = a.getDimension(attr, translationY);
break;
case TRANSLATION_Z:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
translationZ = a.getDimension(attr, translationZ);
}
break;
case ELEVATION:
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
applyElevation = true;
elevation = a.getDimension(attr, elevation);
}
break;
}
}
a.recycle();
}
}
/**
* @suppress
*/
public static class PropertySet {
public boolean mApply = false;
public int visibility = View.VISIBLE;
public int mVisibilityMode = VISIBILITY_MODE_NORMAL;
public float alpha = 1;
public float mProgress = Float.NaN;
public void copyFrom(PropertySet src) {
mApply = src.mApply;
visibility = src.visibility;
alpha = src.alpha;
mProgress = src.mProgress;
mVisibilityMode = src.mVisibilityMode;
}
void fillFromAttributeList(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PropertySet);
mApply = true;
final int N = a.getIndexCount();
for (int i = 0; i < N; i++) {
int attr = a.getIndex(i);
if (attr == R.styleable.PropertySet_android_alpha) {
alpha = a.getFloat(attr, alpha);
} else if (attr == R.styleable.PropertySet_android_visibility) {
visibility = a.getInt(attr, visibility);
visibility = VISIBILITY_FLAGS[visibility];
} else if (attr == R.styleable.PropertySet_visibilityMode) {
mVisibilityMode = a.getInt(attr, mVisibilityMode);
} else if (attr == R.styleable.PropertySet_motionProgress) {
mProgress = a.getFloat(attr, mProgress);
}
}
a.recycle();
}
}
/**
* @suppress
*/
public static class Motion {
public boolean mApply = false;
public int mAnimateRelativeTo = Layout.UNSET;
public int mAnimateCircleAngleTo = 0;
public String mTransitionEasing = null;
public int mPathMotionArc = Layout.UNSET;
public int mDrawPath = 0;
public float mMotionStagger = Float.NaN;
public int mPolarRelativeTo = Layout.UNSET;
public float mPathRotate = Float.NaN;
public float mQuantizeMotionPhase = Float.NaN;
public int mQuantizeMotionSteps = Layout.UNSET;
public String mQuantizeInterpolatorString = null;
public int mQuantizeInterpolatorType = INTERPOLATOR_UNDEFINED; // undefined
public int mQuantizeInterpolatorID = -1;
private static final int INTERPOLATOR_REFERENCE_ID = -2;
private static final int SPLINE_STRING = -1;
private static final int INTERPOLATOR_UNDEFINED = -3;
public void copyFrom(Motion src) {
mApply = src.mApply;
mAnimateRelativeTo = src.mAnimateRelativeTo;
mTransitionEasing = src.mTransitionEasing;
mPathMotionArc = src.mPathMotionArc;
mDrawPath = src.mDrawPath;
mPathRotate = src.mPathRotate;
mMotionStagger = src.mMotionStagger;
mPolarRelativeTo = src.mPolarRelativeTo;
}
private static SparseIntArray mapToConstant = new SparseIntArray();
private static final int TRANSITION_PATH_ROTATE = 1;
private static final int PATH_MOTION_ARC = 2;
private static final int TRANSITION_EASING = 3;
private static final int MOTION_DRAW_PATH = 4;
private static final int ANIMATE_RELATIVE_TO = 5;
private static final int ANIMATE_CIRCLE_ANGLE_TO = 6;
private static final int MOTION_STAGGER = 7;
private static final int QUANTIZE_MOTION_STEPS = 8;
private static final int QUANTIZE_MOTION_PHASE = 9;
private static final int QUANTIZE_MOTION_INTERPOLATOR = 10;
static {
mapToConstant.append(R.styleable.Motion_motionPathRotate, TRANSITION_PATH_ROTATE);
mapToConstant.append(R.styleable.Motion_pathMotionArc, PATH_MOTION_ARC);
mapToConstant.append(R.styleable.Motion_transitionEasing, TRANSITION_EASING);
mapToConstant.append(R.styleable.Motion_drawPath, MOTION_DRAW_PATH);
mapToConstant.append(R.styleable.Motion_animateRelativeTo, ANIMATE_RELATIVE_TO);
mapToConstant.append(R.styleable.Motion_animateCircleAngleTo, ANIMATE_CIRCLE_ANGLE_TO);
mapToConstant.append(R.styleable.Motion_motionStagger, MOTION_STAGGER);
mapToConstant.append(R.styleable.Motion_quantizeMotionSteps, QUANTIZE_MOTION_STEPS);
mapToConstant.append(R.styleable.Motion_quantizeMotionPhase, QUANTIZE_MOTION_PHASE);
mapToConstant.append(R.styleable.Motion_quantizeMotionInterpolator, QUANTIZE_MOTION_INTERPOLATOR);
}
void fillFromAttributeList(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Motion);
mApply = true;
final int N = a.getIndexCount();
for (int i = 0; i < N; i++) {
int attr = a.getIndex(i);
switch (mapToConstant.get(attr)) {
case TRANSITION_PATH_ROTATE:
mPathRotate = a.getFloat(attr, mPathRotate);
break;
case PATH_MOTION_ARC:
mPathMotionArc = a.getInt(attr, mPathMotionArc);
break;
case TRANSITION_EASING:
TypedValue type = a.peekValue(attr);
if (type.type == TypedValue.TYPE_STRING) {
mTransitionEasing = a.getString(attr);
} else {
mTransitionEasing = Easing.NAMED_EASING[a.getInteger(attr, 0)];
}
break;
case MOTION_DRAW_PATH:
mDrawPath = a.getInt(attr, 0);
break;
case ANIMATE_RELATIVE_TO:
mAnimateRelativeTo = lookupID(a, attr, mAnimateRelativeTo);
break;
case ANIMATE_CIRCLE_ANGLE_TO:
mAnimateCircleAngleTo = a.getInteger(attr, mAnimateCircleAngleTo);
break;
case MOTION_STAGGER:
mMotionStagger = a.getFloat(attr, mMotionStagger);
break;
case QUANTIZE_MOTION_STEPS:
mQuantizeMotionSteps = a.getInteger(attr, mQuantizeMotionSteps);
break;
case QUANTIZE_MOTION_PHASE:
mQuantizeMotionPhase = a.getFloat(attr, mQuantizeMotionPhase);
break;
case QUANTIZE_MOTION_INTERPOLATOR:
type = a.peekValue(attr);
if (type.type == TypedValue.TYPE_REFERENCE) {
mQuantizeInterpolatorID = a.getResourceId(attr, -1);
if (mQuantizeInterpolatorID != -1) {
mQuantizeInterpolatorType = INTERPOLATOR_REFERENCE_ID;
}
} else if (type.type == TypedValue.TYPE_STRING) {
mQuantizeInterpolatorString = a.getString(attr);
if (mQuantizeInterpolatorString.indexOf("/") > 0) {
mQuantizeInterpolatorID = a.getResourceId(attr, -1);
mQuantizeInterpolatorType = INTERPOLATOR_REFERENCE_ID;
} else {
mQuantizeInterpolatorType = SPLINE_STRING;
}
} else {
mQuantizeInterpolatorType = a.getInteger(attr, mQuantizeInterpolatorID);
}
break;
}
}
a.recycle();
}
}
/**
* @suppress
*/
public static class Constraint {
int mViewId;
String mTargetString;
public final PropertySet propertySet = new PropertySet();
public final Motion motion = new Motion();
public final Layout layout = new Layout();
public final Transform transform = new Transform();
public HashMap<String, ConstraintAttribute> mCustomConstraints = new HashMap<>();
Delta mDelta;
static class Delta {
private static final int INITIAL_BOOLEAN = 4;
private static final int INITIAL_INT = 10;
private static final int INITIAL_FLOAT = 10;
private static final int INITIAL_STRING = 5;
int[] mTypeInt = new int[INITIAL_INT];
int[] mValueInt = new int[INITIAL_INT];
int mCountInt = 0;
void add(int type, int value) {
if (mCountInt >= mTypeInt.length) {
mTypeInt = Arrays.copyOf(mTypeInt, mTypeInt.length * 2);
mValueInt = Arrays.copyOf(mValueInt, mValueInt.length * 2);
}
mTypeInt[mCountInt] = type;
mValueInt[mCountInt++] = value;
}
int[] mTypeFloat = new int[INITIAL_FLOAT];
float[] mValueFloat = new float[INITIAL_FLOAT];
int mCountFloat = 0;
void add(int type, float value) {
if (mCountFloat >= mTypeFloat.length) {
mTypeFloat = Arrays.copyOf(mTypeFloat, mTypeFloat.length * 2);
mValueFloat = Arrays.copyOf(mValueFloat, mValueFloat.length * 2);
}
mTypeFloat[mCountFloat] = type;
mValueFloat[mCountFloat++] = value;
}
int[] mTypeString = new int[INITIAL_STRING];
String[] mValueString = new String[INITIAL_STRING];
int mCountString = 0;
void add(int type, String value) {
if (mCountString >= mTypeString.length) {
mTypeString = Arrays.copyOf(mTypeString, mTypeString.length * 2);
mValueString = Arrays.copyOf(mValueString, mValueString.length * 2);
}
mTypeString[mCountString] = type;
mValueString[mCountString++] = value;
}
int[] mTypeBoolean = new int[INITIAL_BOOLEAN];
boolean[] mValueBoolean = new boolean[INITIAL_BOOLEAN];
int mCountBoolean = 0;
void add(int type, boolean value) {
if (mCountBoolean >= mTypeBoolean.length) {
mTypeBoolean = Arrays.copyOf(mTypeBoolean, mTypeBoolean.length * 2);
mValueBoolean = Arrays.copyOf(mValueBoolean, mValueBoolean.length * 2);
}
mTypeBoolean[mCountBoolean] = type;
mValueBoolean[mCountBoolean++] = value;
}
void applyDelta(Constraint c) {
for (int i = 0; i < mCountInt; i++) {
setDeltaValue(c, mTypeInt[i], mValueInt[i]);
}
for (int i = 0; i < mCountFloat; i++) {
setDeltaValue(c, mTypeFloat[i], mValueFloat[i]);
}
for (int i = 0; i < mCountString; i++) {
setDeltaValue(c, mTypeString[i], mValueString[i]);
}
for (int i = 0; i < mCountBoolean; i++) {
setDeltaValue(c, mTypeBoolean[i], mValueBoolean[i]);
}
}
@SuppressLint("LogConditional")
void printDelta(String tag) {
Log.v(tag, "int");
for (int i = 0; i < mCountInt; i++) {
Log.v(tag, mTypeInt[i] + " = " + mValueInt[i]);
}
Log.v(tag, "float");
for (int i = 0; i < mCountFloat; i++) {
Log.v(tag, mTypeFloat[i] + " = " + mValueFloat[i]);
}
Log.v(tag, "strings");
for (int i = 0; i < mCountString; i++) {
Log.v(tag, mTypeString[i] + " = " + mValueString[i]);
}
Log.v(tag, "boolean");
for (int i = 0; i < mCountBoolean; i++) {
Log.v(tag, mTypeBoolean[i] + " = " + mValueBoolean[i]);
}
}
}
public void applyDelta(Constraint c) {
if (mDelta != null) {
mDelta.applyDelta(c);
}
}
public void printDelta(String tag) {
if (mDelta != null) {
mDelta.printDelta(tag);
} else {
Log.v(tag, "DELTA IS NULL");
}
}
private ConstraintAttribute get(String attributeName, AttributeType attributeType) {
ConstraintAttribute ret;
if (mCustomConstraints.containsKey(attributeName)) {
ret = mCustomConstraints.get(attributeName);
if (ret.getType() != attributeType) {
throw new IllegalArgumentException(
"ConstraintAttribute is already a " + ret.getType().name());
}
} else {
ret = new ConstraintAttribute(attributeName, attributeType);
mCustomConstraints.put(attributeName, ret);
}
return ret;
}
private void setStringValue(String attributeName, String value) {
get(attributeName, AttributeType.STRING_TYPE).setStringValue(value);
}
private void setFloatValue(String attributeName, float value) {
get(attributeName, AttributeType.FLOAT_TYPE).setFloatValue(value);
}
private void setIntValue(String attributeName, int value) {
get(attributeName, AttributeType.INT_TYPE).setIntValue(value);
}
private void setColorValue(String attributeName, int value) {
get(attributeName, AttributeType.COLOR_TYPE).setColorValue(value);
}
public Constraint clone() {
Constraint clone = new Constraint();
clone.layout.copyFrom(layout);
clone.motion.copyFrom(motion);
clone.propertySet.copyFrom(propertySet);
clone.transform.copyFrom(transform);
clone.mViewId = mViewId;
clone.mDelta = mDelta;
return clone;
}
private void fillFromConstraints(ConstraintHelper helper, int viewId, Constraints.LayoutParams param) {
fillFromConstraints(viewId, param);
if (helper instanceof Barrier) {
layout.mHelperType = BARRIER_TYPE;
Barrier barrier = (Barrier) helper;
layout.mBarrierDirection = barrier.getType();
layout.mReferenceIds = barrier.getReferencedIds();
layout.mBarrierMargin = barrier.getMargin();
}
}
private void fillFromConstraints(int viewId, Constraints.LayoutParams param) {
fillFrom(viewId, param);
propertySet.alpha = param.alpha;
transform.rotation = param.rotation;
transform.rotationX = param.rotationX;
transform.rotationY = param.rotationY;
transform.scaleX = param.scaleX;
transform.scaleY = param.scaleY;
transform.transformPivotX = param.transformPivotX;
transform.transformPivotY = param.transformPivotY;
transform.translationX = param.translationX;
transform.translationY = param.translationY;
transform.translationZ = param.translationZ;
transform.elevation = param.elevation;
transform.applyElevation = param.applyElevation;
}
private void fillFrom(int viewId, ConstraintLayout.LayoutParams param) {
mViewId = viewId;
layout.leftToLeft = param.leftToLeft;
layout.leftToRight = param.leftToRight;
layout.rightToLeft = param.rightToLeft;
layout.rightToRight = param.rightToRight;
layout.topToTop = param.topToTop;
layout.topToBottom = param.topToBottom;
layout.bottomToTop = param.bottomToTop;
layout.bottomToBottom = param.bottomToBottom;
layout.baselineToBaseline = param.baselineToBaseline;
layout.baselineToTop = param.baselineToTop;
layout.baselineToBottom = param.baselineToBottom;
layout.startToEnd = param.startToEnd;
layout.startToStart = param.startToStart;
layout.endToStart = param.endToStart;
layout.endToEnd = param.endToEnd;
layout.horizontalBias = param.horizontalBias;
layout.verticalBias = param.verticalBias;
layout.dimensionRatio = param.dimensionRatio;
layout.circleConstraint = param.circleConstraint;
layout.circleRadius = param.circleRadius;
layout.circleAngle = param.circleAngle;
layout.editorAbsoluteX = param.editorAbsoluteX;
layout.editorAbsoluteY = param.editorAbsoluteY;
layout.orientation = param.orientation;
layout.guidePercent = param.guidePercent;
layout.guideBegin = param.guideBegin;
layout.guideEnd = param.guideEnd;
layout.mWidth = param.width;
layout.mHeight = param.height;
layout.leftMargin = param.leftMargin;
layout.rightMargin = param.rightMargin;
layout.topMargin = param.topMargin;
layout.bottomMargin = param.bottomMargin;
layout.baselineMargin = param.baselineMargin;
layout.verticalWeight = param.verticalWeight;
layout.horizontalWeight = param.horizontalWeight;
layout.verticalChainStyle = param.verticalChainStyle;
layout.horizontalChainStyle = param.horizontalChainStyle;
layout.constrainedWidth = param.constrainedWidth;
layout.constrainedHeight = param.constrainedHeight;
layout.widthDefault = param.matchConstraintDefaultWidth;
layout.heightDefault = param.matchConstraintDefaultHeight;
layout.widthMax = param.matchConstraintMaxWidth;
layout.heightMax = param.matchConstraintMaxHeight;
layout.widthMin = param.matchConstraintMinWidth;
layout.heightMin = param.matchConstraintMinHeight;
layout.widthPercent = param.matchConstraintPercentWidth;
layout.heightPercent = param.matchConstraintPercentHeight;
layout.mConstraintTag = param.constraintTag;
layout.goneTopMargin = param.goneTopMargin;
layout.goneBottomMargin = param.goneBottomMargin;
layout.goneLeftMargin = param.goneLeftMargin;
layout.goneRightMargin = param.goneRightMargin;
layout.goneStartMargin = param.goneStartMargin;
layout.goneEndMargin = param.goneEndMargin;
layout.goneBaselineMargin = param.goneBaselineMargin;
layout.mWrapBehavior = param.wrapBehaviorInParent;
int currentApiVersion = android.os.Build.VERSION.SDK_INT;
if (currentApiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
layout.endMargin = param.getMarginEnd();
layout.startMargin = param.getMarginStart();
}
}
public void applyTo(ConstraintLayout.LayoutParams param) {
param.leftToLeft = layout.leftToLeft;
param.leftToRight = layout.leftToRight;
param.rightToLeft = layout.rightToLeft;
param.rightToRight = layout.rightToRight;
param.topToTop = layout.topToTop;
param.topToBottom = layout.topToBottom;
param.bottomToTop = layout.bottomToTop;
param.bottomToBottom = layout.bottomToBottom;
param.baselineToBaseline = layout.baselineToBaseline;
param.baselineToTop = layout.baselineToTop;
param.baselineToBottom = layout.baselineToBottom;
param.startToEnd = layout.startToEnd;
param.startToStart = layout.startToStart;
param.endToStart = layout.endToStart;
param.endToEnd = layout.endToEnd;
param.leftMargin = layout.leftMargin;
param.rightMargin = layout.rightMargin;
param.topMargin = layout.topMargin;
param.bottomMargin = layout.bottomMargin;
param.goneStartMargin = layout.goneStartMargin;
param.goneEndMargin = layout.goneEndMargin;
param.goneTopMargin = layout.goneTopMargin;
param.goneBottomMargin = layout.goneBottomMargin;
param.horizontalBias = layout.horizontalBias;
param.verticalBias = layout.verticalBias;
param.circleConstraint = layout.circleConstraint;
param.circleRadius = layout.circleRadius;
param.circleAngle = layout.circleAngle;
param.dimensionRatio = layout.dimensionRatio;
param.editorAbsoluteX = layout.editorAbsoluteX;
param.editorAbsoluteY = layout.editorAbsoluteY;
param.verticalWeight = layout.verticalWeight;
param.horizontalWeight = layout.horizontalWeight;
param.verticalChainStyle = layout.verticalChainStyle;
param.horizontalChainStyle = layout.horizontalChainStyle;
param.constrainedWidth = layout.constrainedWidth;
param.constrainedHeight = layout.constrainedHeight;
param.matchConstraintDefaultWidth = layout.widthDefault;
param.matchConstraintDefaultHeight = layout.heightDefault;
param.matchConstraintMaxWidth = layout.widthMax;
param.matchConstraintMaxHeight = layout.heightMax;
param.matchConstraintMinWidth = layout.widthMin;
param.matchConstraintMinHeight = layout.heightMin;
param.matchConstraintPercentWidth = layout.widthPercent;
param.matchConstraintPercentHeight = layout.heightPercent;
param.orientation = layout.orientation;
param.guidePercent = layout.guidePercent;
param.guideBegin = layout.guideBegin;
param.guideEnd = layout.guideEnd;
param.width = layout.mWidth;
param.height = layout.mHeight;
if (layout.mConstraintTag != null) {
param.constraintTag = layout.mConstraintTag;
}
param.wrapBehaviorInParent = layout.mWrapBehavior;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
param.setMarginStart(layout.startMargin);
param.setMarginEnd(layout.endMargin);
}
param.validate();
}
}
/**
* Copy the constraints from a layout.
*
* @param context the context for the layout inflation
* @param constraintLayoutId the id of the layout file
*/
public void clone(Context context, int constraintLayoutId) {
clone((ConstraintLayout) LayoutInflater.from(context).inflate(constraintLayoutId, null));
}
/**
* Copy the constraints from a layout.
*
* @param set constraint set to copy
*/
public void clone(ConstraintSet set) {
mConstraints.clear();
for (Integer key : set.mConstraints.keySet()) {
Constraint constraint = set.mConstraints.get(key);
if (constraint == null) {
continue;
}
mConstraints.put(key, constraint.clone());
}
}
/**
* Copy the layout parameters of a ConstraintLayout.
*
* @param constraintLayout The ConstraintLayout to be copied
*/
public void clone(ConstraintLayout constraintLayout) {
int count = constraintLayout.getChildCount();
mConstraints.clear();
for (int i = 0; i < count; i++) {
View view = constraintLayout.getChildAt(i);
ConstraintLayout.LayoutParams param = (ConstraintLayout.LayoutParams) view.getLayoutParams();
int id = view.getId();
if (mForceId && id == -1) {
throw new RuntimeException("All children of ConstraintLayout must have ids to use ConstraintSet");
}
if (!mConstraints.containsKey(id)) {
mConstraints.put(id, new Constraint());
}
Constraint constraint = mConstraints.get(id);
if (constraint == null) {
continue;
}
constraint.mCustomConstraints = ConstraintAttribute.extractAttributes(mSavedAttributes, view);
constraint.fillFrom(id, param);
constraint.propertySet.visibility = view.getVisibility();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
constraint.propertySet.alpha = view.getAlpha();
constraint.transform.rotation = view.getRotation();
constraint.transform.rotationX = view.getRotationX();
constraint.transform.rotationY = view.getRotationY();
constraint.transform.scaleX = view.getScaleX();
constraint.transform.scaleY = view.getScaleY();
float pivotX = view.getPivotX(); // we assume it is not set if set to 0.0
float pivotY = view.getPivotY(); // we assume it is not set if set to 0.0
if (pivotX != 0.0 || pivotY != 0.0) {
constraint.transform.transformPivotX = pivotX;
constraint.transform.transformPivotY = pivotY;
}
constraint.transform.translationX = view.getTranslationX();
constraint.transform.translationY = view.getTranslationY();
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
constraint.transform.translationZ = view.getTranslationZ();
if (constraint.transform.applyElevation) {
constraint.transform.elevation = view.getElevation();
}
}
}
if (view instanceof Barrier) {
Barrier barrier = ((Barrier) view);
constraint.layout.mBarrierAllowsGoneWidgets = barrier.getAllowsGoneWidget();
constraint.layout.mReferenceIds = barrier.getReferencedIds();
constraint.layout.mBarrierDirection = barrier.getType();
constraint.layout.mBarrierMargin = barrier.getMargin();
}
}
}
/**
* Copy the layout parameters of a ConstraintLayout.
*
* @param constraints The ConstraintLayout to be copied
*/
public void clone(Constraints constraints) {
int count = constraints.getChildCount();
mConstraints.clear();
for (int i = 0; i < count; i++) {
View view = constraints.getChildAt(i);
Constraints.LayoutParams param = (Constraints.LayoutParams) view.getLayoutParams();
int id = view.getId();
if (mForceId && id == -1) {
throw new RuntimeException("All children of ConstraintLayout must have ids to use ConstraintSet");
}
if (!mConstraints.containsKey(id)) {
mConstraints.put(id, new Constraint());
}
Constraint constraint = mConstraints.get(id);
if (constraint == null) {
continue;
}
if (view instanceof ConstraintHelper) {
ConstraintHelper helper = (ConstraintHelper) view;
constraint.fillFromConstraints(helper, id, param);
}
constraint.fillFromConstraints(id, param);
}
}
/**
* Apply the constraints to a ConstraintLayout.
*
* @param constraintLayout to be modified
*/
public void applyTo(ConstraintLayout constraintLayout) {
applyToInternal(constraintLayout, true);
constraintLayout.setConstraintSet(null);
constraintLayout.requestLayout();
}
/**
* Apply the constraints to a ConstraintLayout.
*
* @param constraintLayout to be modified
*/
public void applyToWithoutCustom(ConstraintLayout constraintLayout) {
applyToInternal(constraintLayout, false);
constraintLayout.setConstraintSet(null);
}
/**
* Apply custom attributes alone
*
* @param constraintLayout
*/
public void applyCustomAttributes(ConstraintLayout constraintLayout) {
int count = constraintLayout.getChildCount();
for (int i = 0; i < count; i++) {
View view = constraintLayout.getChildAt(i);
int id = view.getId();
if (!mConstraints.containsKey(id)) {
Log.w(TAG, "id unknown " + Debug.getName(view));
continue;
}
if (mForceId && id == -1) {
throw new RuntimeException("All children of ConstraintLayout must have ids to use ConstraintSet");
}
if (mConstraints.containsKey(id)) {
Constraint constraint = mConstraints.get(id);
if (constraint == null) {
continue;
}
ConstraintAttribute.setAttributes(view, constraint.mCustomConstraints);
}
}
}
/**
* Apply Layout to Helper widget
*
* @param helper
* @param child
* @param layoutParams
* @param mapIdToWidget
*/
public void applyToHelper(ConstraintHelper helper, ConstraintWidget child, LayoutParams layoutParams, SparseArray<ConstraintWidget> mapIdToWidget) {
int id = helper.getId();
if (mConstraints.containsKey(id)) {
Constraint constraint = mConstraints.get(id);
if (constraint != null && child instanceof HelperWidget) {
HelperWidget helperWidget = (HelperWidget) child;
helper.loadParameters(constraint, helperWidget, layoutParams, mapIdToWidget);
}
}
}
/**
* Fill in a ConstraintLayout LayoutParam based on the id.
*
* @param id Id of the view
* @param layoutParams LayoutParams to be filled
*/
public void applyToLayoutParams(int id, ConstraintLayout.LayoutParams layoutParams) {
if (mConstraints.containsKey(id)) {
Constraint constraint = mConstraints.get(id);
if (constraint != null) {
constraint.applyTo(layoutParams);
}
}
}
/**
* Used to set constraints when used by constraint layout
*/
void applyToInternal(ConstraintLayout constraintLayout, boolean applyPostLayout) {
int count = constraintLayout.getChildCount();
HashSet<Integer> used = new HashSet<Integer>(mConstraints.keySet());
for (int i = 0; i < count; i++) {
View view = constraintLayout.getChildAt(i);
int id = view.getId();
if (!mConstraints.containsKey(id)) {
Log.w(TAG, "id unknown " + Debug.getName(view));
continue;
}
if (mForceId && id == -1) {
throw new RuntimeException("All children of ConstraintLayout must have ids to use ConstraintSet");
}
if (id == -1) {
continue;
}
if (mConstraints.containsKey(id)) {
used.remove(id);
Constraint constraint = mConstraints.get(id);
if (constraint == null) {
continue;
}
if (view instanceof Barrier) {
constraint.layout.mHelperType = BARRIER_TYPE;
Barrier barrier = (Barrier) view;
barrier.setId(id);
barrier.setType(constraint.layout.mBarrierDirection);
barrier.setMargin(constraint.layout.mBarrierMargin);
barrier.setAllowsGoneWidget(constraint.layout.mBarrierAllowsGoneWidgets);
if (constraint.layout.mReferenceIds != null) {
barrier.setReferencedIds(constraint.layout.mReferenceIds);
} else if (constraint.layout.mReferenceIdString != null) {
constraint.layout.mReferenceIds = convertReferenceString(barrier,
constraint.layout.mReferenceIdString);
barrier.setReferencedIds(constraint.layout.mReferenceIds);
}
}
ConstraintLayout.LayoutParams param = (ConstraintLayout.LayoutParams) view
.getLayoutParams();
param.validate();
constraint.applyTo(param);
if (applyPostLayout) {
ConstraintAttribute.setAttributes(view, constraint.mCustomConstraints);
}
view.setLayoutParams(param);
if (constraint.propertySet.mVisibilityMode == VISIBILITY_MODE_NORMAL) {
view.setVisibility(constraint.propertySet.visibility);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
view.setAlpha(constraint.propertySet.alpha);
view.setRotation(constraint.transform.rotation);
view.setRotationX(constraint.transform.rotationX);
view.setRotationY(constraint.transform.rotationY);
view.setScaleX(constraint.transform.scaleX);
view.setScaleY(constraint.transform.scaleY);
if (constraint.transform.transformPivotTarget != UNSET) {
View layout = (View) view.getParent();
View center = layout.findViewById(constraint.transform.transformPivotTarget);
if (center != null) {
float cy = (center.getTop() + center.getBottom()) / 2.0f;
float cx = (center.getLeft() + center.getRight()) / 2.0f;
if (view.getRight() - view.getLeft() > 0 && view.getBottom() - view.getTop() > 0) {
float px = (cx - view.getLeft());
float py = (cy - view.getTop());
view.setPivotX(px);
view.setPivotY(py);
}
}
} else {
if (!Float.isNaN(constraint.transform.transformPivotX)) {
view.setPivotX(constraint.transform.transformPivotX);
}
if (!Float.isNaN(constraint.transform.transformPivotY)) {
view.setPivotY(constraint.transform.transformPivotY);
}
}
view.setTranslationX(constraint.transform.translationX);
view.setTranslationY(constraint.transform.translationY);
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
view.setTranslationZ(constraint.transform.translationZ);
if (constraint.transform.applyElevation) {
view.setElevation(constraint.transform.elevation);
}
}
}
} else {
Log.v(TAG, "WARNING NO CONSTRAINTS for view " + id);
}
}
for (Integer id : used) {
Constraint constraint = mConstraints.get(id);
if (constraint == null) {
continue;
}
if (constraint.layout.mHelperType == BARRIER_TYPE) {
Barrier barrier = new Barrier(constraintLayout.getContext());
barrier.setId(id);
if (constraint.layout.mReferenceIds != null) {
barrier.setReferencedIds(constraint.layout.mReferenceIds);
} else if (constraint.layout.mReferenceIdString != null) {
constraint.layout.mReferenceIds = convertReferenceString(barrier,
constraint.layout.mReferenceIdString);
barrier.setReferencedIds(constraint.layout.mReferenceIds);
}
barrier.setType(constraint.layout.mBarrierDirection);
barrier.setMargin(constraint.layout.mBarrierMargin);
LayoutParams param = constraintLayout
.generateDefaultLayoutParams();
barrier.validateParams();
constraint.applyTo(param);
constraintLayout.addView(barrier, param);
}
if (constraint.layout.mIsGuideline) {
Guideline g = new Guideline(constraintLayout.getContext());
g.setId(id);
ConstraintLayout.LayoutParams param = constraintLayout.generateDefaultLayoutParams();
constraint.applyTo(param);
constraintLayout.addView(g, param);
}
}
for (int i = 0; i < count; i++) {
View view = constraintLayout.getChildAt(i);
if (view instanceof ConstraintHelper) {
ConstraintHelper constraintHelper = (ConstraintHelper) view;
constraintHelper.applyLayoutFeaturesInConstraintSet(constraintLayout);
}
}
}
/**
* Center widget between the other two widgets.
* (for sides see: {@link #TOP, {@link #BOTTOM}, {@link #START, {@link #END}, {@link #LEFT, {@link #RIGHT})
* Note, sides must be all vertical or horizontal sides.
*
* @param centerID ID of the widget to be centered
* @param firstID ID of the first widget to connect the left or top of the widget to
* @param firstSide the side of the widget to connect to
* @param firstMargin the connection margin
* @param secondId the ID of the second widget to connect to right or top of the widget to
* @param secondSide the side of the widget to connect to
* @param secondMargin the connection margin
* @param bias the ratio between two connections
*/
public void center(int centerID,
int firstID, int firstSide, int firstMargin,
int secondId, int secondSide, int secondMargin,
float bias) {
// Error checking
if (firstMargin < 0) {
throw new IllegalArgumentException("margin must be > 0");
}
if (secondMargin < 0) {
throw new IllegalArgumentException("margin must be > 0");
}
if (bias <= 0 || bias > 1) {
throw new IllegalArgumentException("bias must be between 0 and 1 inclusive");
}
if (firstSide == LEFT || firstSide == RIGHT) {
connect(centerID, LEFT, firstID, firstSide, firstMargin);
connect(centerID, RIGHT, secondId, secondSide, secondMargin);
Constraint constraint = mConstraints.get(centerID);
if (constraint != null) {
constraint.layout.horizontalBias = bias;
}
} else if (firstSide == START || firstSide == END) {
connect(centerID, START, firstID, firstSide, firstMargin);
connect(centerID, END, secondId, secondSide, secondMargin);
Constraint constraint = mConstraints.get(centerID);
if (constraint != null) {
constraint.layout.horizontalBias = bias;
}
} else {
connect(centerID, TOP, firstID, firstSide, firstMargin);
connect(centerID, BOTTOM, secondId, secondSide, secondMargin);
Constraint constraint = mConstraints.get(centerID);
if (constraint != null) {
constraint.layout.verticalBias = bias;
}
}
}
/**
* Centers the widget horizontally to the left and right side on another widgets sides.
* (for sides see: {@link #START, {@link #END}, {@link #LEFT, {@link #RIGHT})
*
* @param centerID ID of widget to be centered
* @param leftId The Id of the widget on the left side
* @param leftSide The side of the leftId widget to connect to
* @param leftMargin The margin on the left side
* @param rightId The Id of the widget on the right side
* @param rightSide The side of the rightId widget to connect to
* @param rightMargin The margin on the right side
* @param bias The ratio of the space on the left vs. right sides 0.5 is centered (default)
*/
public void centerHorizontally(int centerID, int leftId, int leftSide, int leftMargin,
int rightId, int rightSide, int rightMargin, float bias) {
connect(centerID, LEFT, leftId, leftSide, leftMargin);
connect(centerID, RIGHT, rightId, rightSide, rightMargin);
Constraint constraint = mConstraints.get(centerID);
if (constraint != null) {
constraint.layout.horizontalBias = bias;
}
}
/**
* Centers the widgets horizontally to the left and right side on another widgets sides.
* (for sides see: {@link #START}, {@link #END},
* {@link #LEFT}, {@link #RIGHT})
*
* @param centerID ID of widget to be centered
* @param startId The Id of the widget on the start side (left in non rtl languages)
* @param startSide The side of the startId widget to connect to
* @param startMargin The margin on the start side
* @param endId The Id of the widget on the start side (left in non rtl languages)
* @param endSide The side of the endId widget to connect to
* @param endMargin The margin on the end side
* @param bias The ratio of the space on the start vs end side 0.5 is centered (default)
*/
public void centerHorizontallyRtl(int centerID, int startId, int startSide, int startMargin,
int endId, int endSide, int endMargin, float bias) {
connect(centerID, START, startId, startSide, startMargin);
connect(centerID, END, endId, endSide, endMargin);
Constraint constraint = mConstraints.get(centerID);
if (constraint != null) {
constraint.layout.horizontalBias = bias;
}
}
/**
* Centers the widgets vertically to the top and bottom side on another widgets sides.
* (for sides see: {@link #TOP, {@link #BOTTOM})
*
* @param centerID ID of widget to be centered
* @param topId The Id of the widget on the top side
* @param topSide The side of the leftId widget to connect to
* @param topMargin The margin on the top side
* @param bottomId The Id of the widget on the bottom side
* @param bottomSide The side of the bottomId widget to connect to
* @param bottomMargin The margin on the bottom side
* @param bias The ratio of the space on the top vs. bottom sides 0.5 is centered (default)
*/
public void centerVertically(int centerID, int topId, int topSide, int topMargin, int bottomId,
int bottomSide, int bottomMargin, float bias) {
connect(centerID, TOP, topId, topSide, topMargin);
connect(centerID, BOTTOM, bottomId, bottomSide, bottomMargin);
Constraint constraint = mConstraints.get(centerID);
if (constraint != null) {
constraint.layout.verticalBias = bias;
}
}
/**
* Spaces a set of widgets vertically between the view topId and bottomId.
* Widgets can be spaced with weights.
* This operation sets all the related margins to 0.
* <p>
* (for sides see: {@link #TOP, {@link #BOTTOM})
*
* @param topId The id of the widget to connect to or PARENT_ID
* @param topSide the side of the start to connect to
* @param bottomId The id of the widget to connect to or PARENT_ID
* @param bottomSide the side of the right to connect to
* @param chainIds widgets to use as a chain
* @param weights can be null
* @param style set the style of the chain
*/
public void createVerticalChain(int topId, int topSide, int bottomId, int bottomSide, int[] chainIds, float[] weights,
int style) {
if (chainIds.length < 2) {
throw new IllegalArgumentException("must have 2 or more widgets in a chain");
}
if (weights != null && weights.length != chainIds.length) {
throw new IllegalArgumentException("must have 2 or more widgets in a chain");
}
if (weights != null) {
get(chainIds[0]).layout.verticalWeight = weights[0];
}
get(chainIds[0]).layout.verticalChainStyle = style;
connect(chainIds[0], TOP, topId, topSide, 0);
for (int i = 1; i < chainIds.length; i++) {
int chainId = chainIds[i];
connect(chainIds[i], TOP, chainIds[i - 1], BOTTOM, 0);
connect(chainIds[i - 1], BOTTOM, chainIds[i], TOP, 0);
if (weights != null) {
get(chainIds[i]).layout.verticalWeight = weights[i];
}
}
connect(chainIds[chainIds.length - 1], BOTTOM, bottomId, bottomSide, 0);
}
/**
* Spaces a set of widgets horizontally between the view startID and endId.
* Widgets can be spaced with weights.
* This operation sets all the related margins to 0.
* <p>
* (for sides see: {@link #START, {@link #END},
* {@link #LEFT, {@link #RIGHT}
*
* @param leftId The id of the widget to connect to or PARENT_ID
* @param leftSide the side of the start to connect to
* @param rightId The id of the widget to connect to or PARENT_ID
* @param rightSide the side of the right to connect to
* @param chainIds The widgets in the chain
* @param weights The weight to assign to each element in the chain or null
* @param style The type of chain
*/
public void createHorizontalChain(int leftId, int leftSide, int rightId, int rightSide, int[] chainIds, float[] weights,
int style) {
createHorizontalChain(leftId, leftSide, rightId, rightSide, chainIds, weights, style, LEFT, RIGHT);
}
/**
* Spaces a set of widgets horizontal between the view startID and endId.
* Widgets can be spaced with weights.
* (for sides see: {@link #START, {@link #END},
* {@link #LEFT, {@link #RIGHT})
*
* @param startId The id of the widget to connect to or PARENT_ID
* @param startSide the side of the start to connect to
* @param endId The id of the widget to connect to or PARENT_ID
* @param endSide the side of the end to connect to
* @param chainIds The widgets in the chain
* @param weights The weight to assign to each element in the chain or null
* @param style The type of chain
*/
public void createHorizontalChainRtl(int startId, int startSide, int endId, int endSide, int[] chainIds, float[] weights,
int style) {
createHorizontalChain(startId, startSide, endId, endSide, chainIds, weights, style, START, END);
}
private void createHorizontalChain(int leftId, int leftSide, int rightId, int rightSide, int[] chainIds, float[] weights,
int style, int left, int right) {
if (chainIds.length < 2) {
throw new IllegalArgumentException("must have 2 or more widgets in a chain");
}
if (weights != null && weights.length != chainIds.length) {
throw new IllegalArgumentException("must have 2 or more widgets in a chain");
}
if (weights != null) {
get(chainIds[0]).layout.horizontalWeight = weights[0];
}
get(chainIds[0]).layout.horizontalChainStyle = style;
connect(chainIds[0], left, leftId, leftSide, UNSET);
for (int i = 1; i < chainIds.length; i++) {
int chainId = chainIds[i];
connect(chainIds[i], left, chainIds[i - 1], right, UNSET);
connect(chainIds[i - 1], right, chainIds[i], left, UNSET);
if (weights != null) {
get(chainIds[i]).layout.horizontalWeight = weights[i];
}
}
connect(chainIds[chainIds.length - 1], right, rightId, rightSide,
UNSET);
}
/**
* Create a constraint between two widgets.
* (for sides see: {@link #TOP, {@link #BOTTOM}, {@link #START, {@link #END},
* {@link #LEFT, {@link #RIGHT}, {@link #BASELINE})
*
* @param startID the ID of the widget to be constrained
* @param startSide the side of the widget to constrain
* @param endID the id of the widget to constrain to
* @param endSide the side of widget to constrain to
* @param margin the margin to constrain (margin must be positive)
*/
public void connect(int startID, int startSide, int endID, int endSide, int margin) {
if (!mConstraints.containsKey(startID)) {
mConstraints.put(startID, new Constraint());
}
Constraint constraint = mConstraints.get(startID);
if (constraint == null) {
return;
}
switch (startSide) {
case LEFT:
if (endSide == LEFT) {
constraint.layout.leftToLeft = endID;
constraint.layout.leftToRight = Layout.UNSET;
} else if (endSide == RIGHT) {
constraint.layout.leftToRight = endID;
constraint.layout.leftToLeft = Layout.UNSET;
} else {
throw new IllegalArgumentException("Left to " + sideToString(endSide) + " undefined");
}
constraint.layout.leftMargin = margin;
break;
case RIGHT:
if (endSide == LEFT) {
constraint.layout.rightToLeft = endID;
constraint.layout.rightToRight = Layout.UNSET;
} else if (endSide == RIGHT) {
constraint.layout.rightToRight = endID;
constraint.layout.rightToLeft = Layout.UNSET;
} else {
throw new IllegalArgumentException("right to " + sideToString(endSide) + " undefined");
}
constraint.layout.rightMargin = margin;
break;
case TOP:
if (endSide == TOP) {
constraint.layout.topToTop = endID;
constraint.layout.topToBottom = Layout.UNSET;
constraint.layout.baselineToBaseline = Layout.UNSET;
constraint.layout.baselineToTop = Layout.UNSET;
constraint.layout.baselineToBottom = Layout.UNSET;
} else if (endSide == BOTTOM) {
constraint.layout.topToBottom = endID;
constraint.layout.topToTop = Layout.UNSET;
constraint.layout.baselineToBaseline = Layout.UNSET;
constraint.layout.baselineToTop = Layout.UNSET;
constraint.layout.baselineToBottom = Layout.UNSET;
} else {
throw new IllegalArgumentException("right to " + sideToString(endSide) + " undefined");
}
constraint.layout.topMargin = margin;
break;
case BOTTOM:
if (endSide == BOTTOM) {
constraint.layout.bottomToBottom = endID;
constraint.layout.bottomToTop = Layout.UNSET;
constraint.layout.baselineToBaseline = Layout.UNSET;
constraint.layout.baselineToTop = Layout.UNSET;
constraint.layout.baselineToBottom = Layout.UNSET;
} else if (endSide == TOP) {
constraint.layout.bottomToTop = endID;
constraint.layout.bottomToBottom = Layout.UNSET;
constraint.layout.baselineToBaseline = Layout.UNSET;
constraint.layout.baselineToTop = Layout.UNSET;
constraint.layout.baselineToBottom = Layout.UNSET;
} else {
throw new IllegalArgumentException("right to " + sideToString(endSide) + " undefined");
}
constraint.layout.bottomMargin = margin;
break;
case BASELINE:
if (endSide == BASELINE) {
constraint.layout.baselineToBaseline = endID;
constraint.layout.bottomToBottom = Layout.UNSET;
constraint.layout.bottomToTop = Layout.UNSET;
constraint.layout.topToTop = Layout.UNSET;
constraint.layout.topToBottom = Layout.UNSET;
} else if (endSide == TOP) {
constraint.layout.baselineToTop = endID;
constraint.layout.bottomToBottom = Layout.UNSET;
constraint.layout.bottomToTop = Layout.UNSET;
constraint.layout.topToTop = Layout.UNSET;
constraint.layout.topToBottom = Layout.UNSET;
} else if (endSide == BOTTOM) {
constraint.layout.baselineToBottom = endID;
constraint.layout.bottomToBottom = Layout.UNSET;
constraint.layout.bottomToTop = Layout.UNSET;
constraint.layout.topToTop = Layout.UNSET;
constraint.layout.topToBottom = Layout.UNSET;
} else {
throw new IllegalArgumentException("right to " + sideToString(endSide) + " undefined");
}
break;
case START:
if (endSide == START) {
constraint.layout.startToStart = endID;
constraint.layout.startToEnd = Layout.UNSET;
} else if (endSide == END) {
constraint.layout.startToEnd = endID;
constraint.layout.startToStart = Layout.UNSET;
} else {
throw new IllegalArgumentException("right to " + sideToString(endSide) + " undefined");
}
constraint.layout.startMargin = margin;
break;
case END:
if (endSide == END) {
constraint.layout.endToEnd = endID;
constraint.layout.endToStart = Layout.UNSET;
} else if (endSide == START) {
constraint.layout.endToStart = endID;
constraint.layout.endToEnd = Layout.UNSET;
} else {
throw new IllegalArgumentException("right to " + sideToString(endSide) + " undefined");
}
constraint.layout.endMargin = margin;
break;
default:
throw new IllegalArgumentException(
sideToString(startSide) + " to " + sideToString(endSide) + " unknown");
}
}
/**
* Create a constraint between two widgets.
* (for sides see: {@link #TOP, {@link #BOTTOM}, {@link #START, {@link #END}, {@link #LEFT, {@link #RIGHT}, {@link #BASELINE})
*
* @param startID the ID of the widget to be constrained
* @param startSide the side of the widget to constrain
* @param endID the id of the widget to constrain to
* @param endSide the side of widget to constrain to
*/
public void connect(int startID, int startSide, int endID, int endSide) {
if (!mConstraints.containsKey(startID)) {
mConstraints.put(startID, new Constraint());
}
Constraint constraint = mConstraints.get(startID);
if (constraint == null) {
return;
}
switch (startSide) {
case LEFT:
if (endSide == LEFT) {
constraint.layout.leftToLeft = endID;
constraint.layout.leftToRight = Layout.UNSET;
} else if (endSide == RIGHT) {
constraint.layout.leftToRight = endID;
constraint.layout.leftToLeft = Layout.UNSET;
} else {
throw new IllegalArgumentException("left to " + sideToString(endSide) + " undefined");
}
break;
case RIGHT:
if (endSide == LEFT) {
constraint.layout.rightToLeft = endID;
constraint.layout.rightToRight = Layout.UNSET;
} else if (endSide == RIGHT) {
constraint.layout.rightToRight = endID;
constraint.layout.rightToLeft = Layout.UNSET;
} else {
throw new IllegalArgumentException("right to " + sideToString(endSide) + " undefined");
}
break;
case TOP:
if (endSide == TOP) {
constraint.layout.topToTop = endID;
constraint.layout.topToBottom = Layout.UNSET;
constraint.layout.baselineToBaseline = Layout.UNSET;
constraint.layout.baselineToTop = Layout.UNSET;
constraint.layout.baselineToBottom = Layout.UNSET;
} else if (endSide == BOTTOM) {
constraint.layout.topToBottom = endID;
constraint.layout.topToTop = Layout.UNSET;
constraint.layout.baselineToBaseline = Layout.UNSET;
constraint.layout.baselineToTop = Layout.UNSET;
constraint.layout.baselineToBottom = Layout.UNSET;
} else {
throw new IllegalArgumentException("right to " + sideToString(endSide) + " undefined");
}
break;
case BOTTOM:
if (endSide == BOTTOM) {
constraint.layout.bottomToBottom = endID;
constraint.layout.bottomToTop = Layout.UNSET;
constraint.layout.baselineToBaseline = Layout.UNSET;
constraint.layout.baselineToTop = Layout.UNSET;
constraint.layout.baselineToBottom = Layout.UNSET;
} else if (endSide == TOP) {
constraint.layout.bottomToTop = endID;
constraint.layout.bottomToBottom = Layout.UNSET;
constraint.layout.baselineToBaseline = Layout.UNSET;
constraint.layout.baselineToTop = Layout.UNSET;
constraint.layout.baselineToBottom = Layout.UNSET;
} else {
throw new IllegalArgumentException("right to " + sideToString(endSide) + " undefined");
}
break;
case BASELINE:
if (endSide == BASELINE) {
constraint.layout.baselineToBaseline = endID;
constraint.layout.bottomToBottom = Layout.UNSET;
constraint.layout.bottomToTop = Layout.UNSET;
constraint.layout.topToTop = Layout.UNSET;
constraint.layout.topToBottom = Layout.UNSET;
} else if (endSide == TOP) {
constraint.layout.baselineToTop = endID;
constraint.layout.bottomToBottom = Layout.UNSET;
constraint.layout.bottomToTop = Layout.UNSET;
constraint.layout.topToTop = Layout.UNSET;
constraint.layout.topToBottom = Layout.UNSET;
} else if (endSide == BOTTOM) {
constraint.layout.baselineToBottom = endID;
constraint.layout.bottomToBottom = Layout.UNSET;
constraint.layout.bottomToTop = Layout.UNSET;
constraint.layout.topToTop = Layout.UNSET;
constraint.layout.topToBottom = Layout.UNSET;
} else {
throw new IllegalArgumentException("right to " + sideToString(endSide) + " undefined");
}
break;
case START:
if (endSide == START) {
constraint.layout.startToStart = endID;
constraint.layout.startToEnd = Layout.UNSET;
} else if (endSide == END) {
constraint.layout.startToEnd = endID;
constraint.layout.startToStart = Layout.UNSET;
} else {
throw new IllegalArgumentException("right to " + sideToString(endSide) + " undefined");
}
break;
case END:
if (endSide == END) {
constraint.layout.endToEnd = endID;
constraint.layout.endToStart = Layout.UNSET;
} else if (endSide == START) {
constraint.layout.endToStart = endID;
constraint.layout.endToEnd = Layout.UNSET;
} else {
throw new IllegalArgumentException("right to " + sideToString(endSide) + " undefined");
}
break;
default:
throw new IllegalArgumentException(
sideToString(startSide) + " to " + sideToString(endSide) + " unknown");
}
}
/**
* Centers the view horizontally relative to toView's position.
*
* @param viewId ID of view to center Horizontally
* @param toView ID of view to center on (or in)
*/
public void centerHorizontally(int viewId, int toView) {
if (toView == PARENT_ID) {
center(viewId, PARENT_ID, ConstraintSet.LEFT, 0, PARENT_ID, ConstraintSet.RIGHT, 0, 0.5f);
} else {
center(viewId, toView, ConstraintSet.RIGHT, 0, toView, ConstraintSet.LEFT, 0, 0.5f);
}
}
/**
* Centers the view horizontally relative to toView's position.
*
* @param viewId ID of view to center Horizontally
* @param toView ID of view to center on (or in)
*/
public void centerHorizontallyRtl(int viewId, int toView) {
if (toView == PARENT_ID) {
center(viewId, PARENT_ID, ConstraintSet.START, 0, PARENT_ID, ConstraintSet.END, 0, 0.5f);
} else {
center(viewId, toView, ConstraintSet.END, 0, toView, ConstraintSet.START, 0, 0.5f);
}
}
/**
* Centers the view vertically relative to toView's position.
*
* @param viewId ID of view to center Horizontally
* @param toView ID of view to center on (or in)
*/
public void centerVertically(int viewId, int toView) {
if (toView == PARENT_ID) {
center(viewId, PARENT_ID, ConstraintSet.TOP, 0, PARENT_ID, ConstraintSet.BOTTOM, 0, 0.5f);
} else {
center(viewId, toView, ConstraintSet.BOTTOM, 0, toView, ConstraintSet.TOP, 0, 0.5f);
}
}
/**
* Remove all constraints from this view.
*
* @param viewId ID of view to remove all connections to
*/
public void clear(int viewId) {
mConstraints.remove(viewId);
}
/**
* Remove a constraint from this view.
*
* @param viewId ID of view to center on (or in)
* @param anchor the Anchor to remove constraint from
*/
public void clear(int viewId, int anchor) {
if (mConstraints.containsKey(viewId)) {
Constraint constraint = mConstraints.get(viewId);
if (constraint == null) {
return;
}
switch (anchor) {
case LEFT:
constraint.layout.leftToRight = Layout.UNSET;
constraint.layout.leftToLeft = Layout.UNSET;
constraint.layout.leftMargin = Layout.UNSET;
constraint.layout.goneLeftMargin = Layout.UNSET_GONE_MARGIN;
break;
case RIGHT:
constraint.layout.rightToRight = Layout.UNSET;
constraint.layout.rightToLeft = Layout.UNSET;
constraint.layout.rightMargin = Layout.UNSET;
constraint.layout.goneRightMargin = Layout.UNSET_GONE_MARGIN;
break;
case TOP:
constraint.layout.topToBottom = Layout.UNSET;
constraint.layout.topToTop = Layout.UNSET;
constraint.layout.topMargin = 0;
constraint.layout.goneTopMargin = Layout.UNSET_GONE_MARGIN;
break;
case BOTTOM:
constraint.layout.bottomToTop = Layout.UNSET;
constraint.layout.bottomToBottom = Layout.UNSET;
constraint.layout.bottomMargin = 0;
constraint.layout.goneBottomMargin = Layout.UNSET_GONE_MARGIN;
break;
case BASELINE:
constraint.layout.baselineToBaseline = Layout.UNSET;
constraint.layout.baselineToTop = Layout.UNSET;
constraint.layout.baselineToBottom = Layout.UNSET;
constraint.layout.baselineMargin = 0;
constraint.layout.goneBaselineMargin = Layout.UNSET_GONE_MARGIN;
break;
case START:
constraint.layout.startToEnd = Layout.UNSET;
constraint.layout.startToStart = Layout.UNSET;
constraint.layout.startMargin = 0;
constraint.layout.goneStartMargin = Layout.UNSET_GONE_MARGIN;
break;
case END:
constraint.layout.endToStart = Layout.UNSET;
constraint.layout.endToEnd = Layout.UNSET;
constraint.layout.endMargin = 0;
constraint.layout.goneEndMargin = Layout.UNSET_GONE_MARGIN;
break;
case CIRCLE_REFERENCE:
constraint.layout.circleAngle = Layout.UNSET;
constraint.layout.circleRadius = Layout.UNSET;
constraint.layout.circleConstraint = Layout.UNSET;
break;
default:
throw new IllegalArgumentException("unknown constraint");
}
}
}
/**
* Sets the margin.
*
* @param viewId ID of view to adjust the margin on
* @param anchor The side to adjust the margin on
* @param value The new value for the margin
*/
public void setMargin(int viewId, int anchor, int value) {
Constraint constraint = get(viewId);
switch (anchor) {
case LEFT:
constraint.layout.leftMargin = value;
break;
case RIGHT:
constraint.layout.rightMargin = value;
break;
case TOP:
constraint.layout.topMargin = value;
break;
case BOTTOM:
constraint.layout.bottomMargin = value;
break;
case BASELINE:
constraint.layout.baselineMargin = value;
break;
case START:
constraint.layout.startMargin = value;
break;
case END:
constraint.layout.endMargin = value;
break;
default:
throw new IllegalArgumentException("unknown constraint");
}
}
/**
* Sets the gone margin.
*
* @param viewId ID of view to adjust the margin on
* @param anchor The side to adjust the margin on
* @param value The new value for the margin
*/
public void setGoneMargin(int viewId, int anchor, int value) {
Constraint constraint = get(viewId);
switch (anchor) {
case LEFT:
constraint.layout.goneLeftMargin = value;
break;
case RIGHT:
constraint.layout.goneRightMargin = value;
break;
case TOP:
constraint.layout.goneTopMargin = value;
break;
case BOTTOM:
constraint.layout.goneBottomMargin = value;
break;
case BASELINE:
constraint.layout.goneBaselineMargin = value;
break;
case START:
constraint.layout.goneStartMargin = value;
break;
case END:
constraint.layout.goneEndMargin = value;
break;
default:
throw new IllegalArgumentException("unknown constraint");
}
}
/**
* Adjust the horizontal bias of the view (used with views constrained on left and right).
*
* @param viewId ID of view to adjust the horizontal
* @param bias the new bias 0.5 is in the middle
*/
public void setHorizontalBias(int viewId, float bias) {
get(viewId).layout.horizontalBias = bias;
}
/**
* Adjust the vertical bias of the view (used with views constrained on left and right).
*
* @param viewId ID of view to adjust the vertical
* @param bias the new bias 0.5 is in the middle
*/
public void setVerticalBias(int viewId, float bias) {
get(viewId).layout.verticalBias = bias;
}
/**
* Constrains the views aspect ratio.
* For Example a HD screen is 16 by 9 = 16/(float)9 = 1.777f.
*
* @param viewId ID of view to constrain
* @param ratio The ratio of the width to height (width / height)
*/
public void setDimensionRatio(int viewId, String ratio) {
get(viewId).layout.dimensionRatio = ratio;
}
/**
* Adjust the visibility of a view.
*
* @param viewId ID of view to adjust the vertical
* @param visibility the visibility
*/
public void setVisibility(int viewId, int visibility) {
get(viewId).propertySet.visibility = visibility;
}
/**
* ConstraintSet will not setVisibility. {@link #VISIBILITY_MODE_IGNORE} or {@link
* #VISIBILITY_MODE_NORMAL}.
*
* @param viewId ID of view
* @param visibilityMode
*/
public void setVisibilityMode(int viewId, int visibilityMode) {
get(viewId).propertySet.mVisibilityMode = visibilityMode;
}
/**
* ConstraintSet will not setVisibility. {@link #VISIBILITY_MODE_IGNORE} or {@link
* #VISIBILITY_MODE_NORMAL}.
*
* @param viewId ID of view
*/
public int getVisibilityMode(int viewId) {
return get(viewId).propertySet.mVisibilityMode;
}
/**
* Get the visibility flag set in this view
*
* @param viewId the id of the view
* @return the visibility constraint for the view
*/
public int getVisibility(int viewId) {
return get(viewId).propertySet.visibility;
}
/**
* Get the height set in the view
*
* @param viewId the id of the view
* @return return the height constraint of the view
*/
public int getHeight(int viewId) {
return get(viewId).layout.mHeight;
}
/**
* Get the width set in the view
*
* @param viewId the id of the view
* @return return the width constraint of the view
*/
public int getWidth(int viewId) {
return get(viewId).layout.mWidth;
}
/**
* Adjust the alpha of a view.
*
* @param viewId ID of view to adjust the vertical
* @param alpha the alpha
*/
public void setAlpha(int viewId, float alpha) {
get(viewId).propertySet.alpha = alpha;
}
/**
* return with the constraint set will apply elevation for the specified view.
*
* @return true if the elevation will be set on this view (default is false)
*/
public boolean getApplyElevation(int viewId) {
return get(viewId).transform.applyElevation;
}
/**
* set if elevation will be applied to the view.
* Elevation logic is based on style and animation. By default it is not used because it would
* lead to unexpected results.
*
* @param apply true if this constraint set applies elevation to this view
*/
public void setApplyElevation(int viewId, boolean apply) {
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
get(viewId).transform.applyElevation = apply;
}
}
/**
* Adjust the elevation of a view.
*
* @param viewId ID of view to adjust the elevation
* @param elevation the elevation
*/
public void setElevation(int viewId, float elevation) {
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
get(viewId).transform.elevation = elevation;
get(viewId).transform.applyElevation = true;
}
}
/**
* Adjust the post-layout rotation about the Z axis of a view.
*
* @param viewId ID of view to adjust th Z rotation
* @param rotation the rotation about the X axis
*/
public void setRotation(int viewId, float rotation) {
get(viewId).transform.rotation = rotation;
}
/**
* Adjust the post-layout rotation about the X axis of a view.
*
* @param viewId ID of view to adjust th X rotation
* @param rotationX the rotation about the X axis
*/
public void setRotationX(int viewId, float rotationX) {
get(viewId).transform.rotationX = rotationX;
}
/**
* Adjust the post-layout rotation about the Y axis of a view.
*
* @param viewId ID of view to adjust the Y rotation
* @param rotationY the rotationY
*/
public void setRotationY(int viewId, float rotationY) {
get(viewId).transform.rotationY = rotationY;
}
/**
* Adjust the post-layout scale in X of a view.
*
* @param viewId ID of view to adjust the scale in X
* @param scaleX the scale in X
*/
public void setScaleX(int viewId, float scaleX) {
get(viewId).transform.scaleX = scaleX;
}
/**
* Adjust the post-layout scale in Y of a view.
*
* @param viewId ID of view to adjust the scale in Y
* @param scaleY the scale in Y
*/
public void setScaleY(int viewId, float scaleY) {
get(viewId).transform.scaleY = scaleY;
}
/**
* Set X location of the pivot point around which the view will rotate and scale.
* use Float.NaN to clear the pivot value.
* Note: once an actual View has had its pivot set it cannot be cleared.
*
* @param viewId ID of view to adjust the transforms pivot point about X
* @param transformPivotX X location of the pivot point.
*/
public void setTransformPivotX(int viewId, float transformPivotX) {
get(viewId).transform.transformPivotX = transformPivotX;
}
/**
* Set Y location of the pivot point around which the view will rotate and scale.
* use Float.NaN to clear the pivot value.
* Note: once an actual View has had its pivot set it cannot be cleared.
*
* @param viewId ID of view to adjust the transforms pivot point about Y
* @param transformPivotY Y location of the pivot point.
*/
public void setTransformPivotY(int viewId, float transformPivotY) {
get(viewId).transform.transformPivotY = transformPivotY;
}
/**
* Set X,Y location of the pivot point around which the view will rotate and scale.
* use Float.NaN to clear the pivot value.
* Note: once an actual View has had its pivot set it cannot be cleared.
*
* @param viewId ID of view to adjust the transforms pivot point
* @param transformPivotX X location of the pivot point.
* @param transformPivotY Y location of the pivot point.
*/
public void setTransformPivot(int viewId, float transformPivotX, float transformPivotY) {
Constraint constraint = get(viewId);
constraint.transform.transformPivotY = transformPivotY;
constraint.transform.transformPivotX = transformPivotX;
}
/**
* Adjust the post-layout X translation of a view.
*
* @param viewId ID of view to translate in X
* @param translationX the translation in X
*/
public void setTranslationX(int viewId, float translationX) {
get(viewId).transform.translationX = translationX;
}
/**
* Adjust the post-layout Y translation of a view.
*
* @param viewId ID of view to to translate in Y
* @param translationY the translation in Y
*/
public void setTranslationY(int viewId, float translationY) {
get(viewId).transform.translationY = translationY;
}
/**
* Adjust the post-layout translation of a view.
*
* @param viewId ID of view to adjust its translation in X & Y
* @param translationX the translation in X
* @param translationY the translation in Y
*/
public void setTranslation(int viewId, float translationX, float translationY) {
Constraint constraint = get(viewId);
constraint.transform.translationX = translationX;
constraint.transform.translationY = translationY;
}
/**
* Adjust the translation in Z of a view.
*
* @param viewId ID of view to adjust
* @param translationZ the translationZ
*/
public void setTranslationZ(int viewId, float translationZ) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
get(viewId).transform.translationZ = translationZ;
}
}
/**
* @suppress
*/
public void setEditorAbsoluteX(int viewId, int position) {
get(viewId).layout.editorAbsoluteX = position;
}
/**
* @suppress
*/
public void setEditorAbsoluteY(int viewId, int position) {
get(viewId).layout.editorAbsoluteY = position;
}
/**
* Sets the wrap behavior of the widget in the parent's wrap computation
*/
public void setLayoutWrapBehavior(int viewId, int behavior) {
if (behavior >= 0 && behavior <= ConstraintWidget.WRAP_BEHAVIOR_SKIPPED) {
get(viewId).layout.mWrapBehavior = behavior;
}
}
/**
* Sets the height of the view. It can be a dimension, {@link #WRAP_CONTENT} or {@link
* #MATCH_CONSTRAINT}.
*
* @param viewId ID of view to adjust its height
* @param height the height of the view
* @since 1.1
*/
public void constrainHeight(int viewId, int height) {
get(viewId).layout.mHeight = height;
}
/**
* Sets the width of the view. It can be a dimension, {@link #WRAP_CONTENT} or {@link
* #MATCH_CONSTRAINT}.
*
* @param viewId ID of view to adjust its width
* @param width the width of the view
* @since 1.1
*/
public void constrainWidth(int viewId, int width) {
get(viewId).layout.mWidth = width;
}
/**
* Constrain the view on a circle constraint
*
* @param viewId ID of the view we constrain
* @param id ID of the view we constrain relative to
* @param radius the radius of the circle in degrees
* @param angle the angle
* @since 1.1
*/
public void constrainCircle(int viewId, int id, int radius, float angle) {
Constraint constraint = get(viewId);
constraint.layout.circleConstraint = id;
constraint.layout.circleRadius = radius;
constraint.layout.circleAngle = angle;
}
/**
* Sets the maximum height of the view. It is a dimension, It is only applicable if height is
* #MATCH_CONSTRAINT}.
*
* @param viewId ID of view to adjust it height
* @param height the maximum height of the constraint
* @since 1.1
*/
public void constrainMaxHeight(int viewId, int height) {
get(viewId).layout.heightMax = height;
}
/**
* Sets the maximum width of the view. It is a dimension, It is only applicable if width is
* #MATCH_CONSTRAINT}.
*
* @param viewId ID of view to adjust its max height
* @param width the maximum width of the view
* @since 1.1
*/
public void constrainMaxWidth(int viewId, int width) {
get(viewId).layout.widthMax = width;
}
/**
* Sets the height of the view. It is a dimension, It is only applicable if height is
* #MATCH_CONSTRAINT}.
*
* @param viewId ID of view to adjust its min height
* @param height the minimum height of the view
* @since 1.1
*/
public void constrainMinHeight(int viewId, int height) {
get(viewId).layout.heightMin = height;
}
/**
* Sets the width of the view. It is a dimension, It is only applicable if width is
* #MATCH_CONSTRAINT}.
*
* @param viewId ID of view to adjust its min height
* @param width the minimum width of the view
* @since 1.1
*/
public void constrainMinWidth(int viewId, int width) {
get(viewId).layout.widthMin = width;
}
/**
* Sets the width of the view as a percentage of the parent.
*
* @param viewId
* @param percent
* @since 1.1
*/
public void constrainPercentWidth(int viewId, float percent) {
get(viewId).layout.widthPercent = percent;
}
/**
* Sets the height of the view as a percentage of the parent.
*
* @param viewId
* @param percent
* @since 1.1
*/
public void constrainPercentHeight(int viewId, float percent) {
get(viewId).layout.heightPercent = percent;
}
/**
* Sets how the height is calculated ether MATCH_CONSTRAINT_WRAP or MATCH_CONSTRAINT_SPREAD.
* Default is spread.
*
* @param viewId ID of view to adjust its matchConstraintDefaultHeight
* @param height MATCH_CONSTRAINT_WRAP or MATCH_CONSTRAINT_SPREAD
* @since 1.1
*/
public void constrainDefaultHeight(int viewId, int height) {
get(viewId).layout.heightDefault = height;
}
/**
* Sets how the width is calculated ether MATCH_CONSTRAINT_WRAP or MATCH_CONSTRAINT_SPREAD.
* Default is spread.
*
* @param viewId ID of view to adjust its matchConstraintDefaultWidth
* @param constrained if true with will be constrained
* @since 1.1
*/
public void constrainedWidth(int viewId, boolean constrained) {
get(viewId).layout.constrainedWidth = constrained;
}
/**
* Sets how the height is calculated ether MATCH_CONSTRAINT_WRAP or MATCH_CONSTRAINT_SPREAD.
* Default is spread.
*
* @param viewId ID of view to adjust its matchConstraintDefaultHeight
* @param constrained if true height will be constrained
* @since 1.1
*/
public void constrainedHeight(int viewId, boolean constrained) {
get(viewId).layout.constrainedHeight = constrained;
}
/**
* Sets how the width is calculated ether MATCH_CONSTRAINT_WRAP or MATCH_CONSTRAINT_SPREAD.
* Default is spread.
*
* @param viewId ID of view to adjust its matchConstraintDefaultWidth
* @param width SPREAD or WRAP
* @since 1.1
*/
public void constrainDefaultWidth(int viewId, int width) {
get(viewId).layout.widthDefault = width;
}
/**
* The child's weight that we can use to distribute the available horizontal space
* in a chain, if the dimension behaviour is set to MATCH_CONSTRAINT
*
* @param viewId ID of view to adjust its HorizontalWeight
* @param weight the weight that we can use to distribute the horizontal space
*/
public void setHorizontalWeight(int viewId, float weight) {
get(viewId).layout.horizontalWeight = weight;
}
/**
* The child's weight that we can use to distribute the available vertical space
* in a chain, if the dimension behaviour is set to MATCH_CONSTRAINT
*
* @param viewId ID of view to adjust its VerticalWeight
* @param weight the weight that we can use to distribute the vertical space
*/
public void setVerticalWeight(int viewId, float weight) {
get(viewId).layout.verticalWeight = weight;
}
/**
* How the elements of the horizontal chain will be positioned. if the dimension
* behaviour is set to MATCH_CONSTRAINT. The possible values are:
*
* <ul>
* <li>{@link #CHAIN_SPREAD} -- the elements will be spread out</li>
* <li>{@link #CHAIN_SPREAD_INSIDE} -- similar, but the endpoints of the chain will not
* be spread out</li>
* <li>{@link #CHAIN_PACKED} -- the elements of the chain will be packed together. The
* horizontal bias attribute of the child will then affect the positioning of the packed
* elements</li>
* </ul>
*
* @param viewId ID of view to adjust its HorizontalChainStyle
* @param chainStyle the weight that we can use to distribute the horizontal space
*/
public void setHorizontalChainStyle(int viewId, int chainStyle) {
get(viewId).layout.horizontalChainStyle = chainStyle;
}
/**
* How the elements of the vertical chain will be positioned. in a chain, if the dimension
* behaviour is set to MATCH_CONSTRAINT
*
* <ul>
* <li>{@link #CHAIN_SPREAD} -- the elements will be spread out</li>
* <li>{@link #CHAIN_SPREAD_INSIDE} -- similar, but the endpoints of the chain will not
* be spread out</li>
* <li>{@link #CHAIN_PACKED} -- the elements of the chain will be packed together. The
* vertical bias attribute of the child will then affect the positioning of the packed
* elements</li>
* </ul>
*
* @param viewId ID of view to adjust its VerticalChainStyle
* @param chainStyle the weight that we can use to distribute the horizontal space
*/
public void setVerticalChainStyle(int viewId, int chainStyle) {
get(viewId).layout.verticalChainStyle = chainStyle;
}
/**
* Adds a view to a horizontal chain.
*
* @param viewId view to add
* @param leftId view in chain to the left
* @param rightId view in chain to the right
*/
public void addToHorizontalChain(int viewId, int leftId, int rightId) {
connect(viewId, LEFT, leftId, (leftId == PARENT_ID) ? LEFT : RIGHT, 0);
connect(viewId, RIGHT, rightId, (rightId == PARENT_ID) ? RIGHT : LEFT, 0);
if (leftId != PARENT_ID) {
connect(leftId, RIGHT, viewId, LEFT, 0);
}
if (rightId != PARENT_ID) {
connect(rightId, LEFT, viewId, RIGHT, 0);
}
}
/**
* Adds a view to a horizontal chain.
*
* @param viewId view to add
* @param leftId view to the start side
* @param rightId view to the end side
*/
public void addToHorizontalChainRTL(int viewId, int leftId, int rightId) {
connect(viewId, START, leftId, (leftId == PARENT_ID) ? START : END, 0);
connect(viewId, END, rightId, (rightId == PARENT_ID) ? END : START, 0);
if (leftId != PARENT_ID) {
connect(leftId, END, viewId, START, 0);
}
if (rightId != PARENT_ID) {
connect(rightId, START, viewId, END, 0);
}
}
/**
* Adds a view to a vertical chain.
*
* @param viewId view to add to a vertical chain
* @param topId view above.
* @param bottomId view below
*/
public void addToVerticalChain(int viewId, int topId, int bottomId) {
connect(viewId, TOP, topId, (topId == PARENT_ID) ? TOP : BOTTOM, 0);
connect(viewId, BOTTOM, bottomId, (bottomId == PARENT_ID) ? BOTTOM : TOP, 0);
if (topId != PARENT_ID) {
connect(topId, BOTTOM, viewId, TOP, 0);
}
if (bottomId != PARENT_ID) {
connect(bottomId, TOP, viewId, BOTTOM, 0);
}
}
/**
* Removes a view from a vertical chain.
* This assumes the view is connected to a vertical chain.
* Its behaviour is undefined if not part of a vertical chain.
*
* @param viewId the view to be removed
*/
public void removeFromVerticalChain(int viewId) {
if (mConstraints.containsKey(viewId)) {
Constraint constraint = mConstraints.get(viewId);
if (constraint == null) {
return;
}
int topId = constraint.layout.topToBottom;
int bottomId = constraint.layout.bottomToTop;
if (topId != Layout.UNSET || bottomId != Layout.UNSET) {
if (topId != Layout.UNSET && bottomId != Layout.UNSET) {
// top and bottom connected to views
connect(topId, BOTTOM, bottomId, TOP, 0);
connect(bottomId, TOP, topId, BOTTOM, 0);
} else if (constraint.layout.bottomToBottom != Layout.UNSET) {
// top connected to view. Bottom connected to parent
connect(topId, BOTTOM, constraint.layout.bottomToBottom, BOTTOM, 0);
} else if (constraint.layout.topToTop != Layout.UNSET) {
// bottom connected to view. Top connected to parent
connect(bottomId, TOP, constraint.layout.topToTop, TOP, 0);
}
}
}
clear(viewId, TOP);
clear(viewId, BOTTOM);
}
/**
* Removes a view from a horizontal chain.
* This assumes the view is connected to a horizontal chain.
* Its behaviour is undefined if not part of a horizontal chain.
*
* @param viewId the view to be removed
*/
public void removeFromHorizontalChain(int viewId) {
if (mConstraints.containsKey(viewId)) {
Constraint constraint = mConstraints.get(viewId);
if (constraint == null) {
return;
}
int leftId = constraint.layout.leftToRight;
int rightId = constraint.layout.rightToLeft;
if (leftId != Layout.UNSET || rightId != Layout.UNSET) {
if (leftId != Layout.UNSET && rightId != Layout.UNSET) {
// left and right connected to views
connect(leftId, RIGHT, rightId, LEFT, 0);
connect(rightId, LEFT, leftId, RIGHT, 0);
} else if (constraint.layout.rightToRight != Layout.UNSET) {
// left connected to view. right connected to parent
connect(leftId, RIGHT, constraint.layout.rightToRight, RIGHT, 0);
} else if (constraint.layout.leftToLeft != Layout.UNSET) {
// right connected to view. left connected to parent
connect(rightId, LEFT, constraint.layout.leftToLeft, LEFT, 0);
}
clear(viewId, LEFT);
clear(viewId, RIGHT);
} else {
int startId = constraint.layout.startToEnd;
int endId = constraint.layout.endToStart;
if (startId != Layout.UNSET || endId != Layout.UNSET) {
if (startId != Layout.UNSET && endId != Layout.UNSET) {
// start and end connected to views
connect(startId, END, endId, START, 0);
connect(endId, START, leftId, END, 0);
} else if (endId != Layout.UNSET) {
if (constraint.layout.rightToRight != Layout.UNSET) {
// left connected to view. right connected to parent
connect(leftId, END, constraint.layout.rightToRight, END, 0);
} else if (constraint.layout.leftToLeft != Layout.UNSET) {
// right connected to view. left connected to parent
connect(endId, START, constraint.layout.leftToLeft, START, 0);
}
}
}
clear(viewId, START);
clear(viewId, END);
}
}
}
/**
* Creates a ConstraintLayout virtual object. Currently only horizontal or vertical GuideLines.
*
* @param guidelineID ID of guideline to create
* @param orientation the Orientation of the guideline
*/
public void create(int guidelineID, int orientation) {
Constraint constraint = get(guidelineID);
constraint.layout.mIsGuideline = true;
constraint.layout.orientation = orientation;
}
/**
* Creates a ConstraintLayout Barrier object.
*
* @param id
* @param direction Barrier.{LEFT,RIGHT,TOP,BOTTOM,START,END}
* @param referenced
* @since 1.1
*/
public void createBarrier(int id, int direction, int margin, int... referenced) {
Constraint constraint = get(id);
constraint.layout.mHelperType = BARRIER_TYPE;
constraint.layout.mBarrierDirection = direction;
constraint.layout.mBarrierMargin = margin;
constraint.layout.mIsGuideline = false;
constraint.layout.mReferenceIds = referenced;
}
/**
* Set the guideline's distance form the top or left edge.
*
* @param guidelineID ID of the guideline
* @param margin the distance to the top or left edge
*/
public void setGuidelineBegin(int guidelineID, int margin) {
get(guidelineID).layout.guideBegin = margin;
get(guidelineID).layout.guideEnd = Layout.UNSET;
get(guidelineID).layout.guidePercent = Layout.UNSET;
}
/**
* Set a guideline's distance to end.
*
* @param guidelineID ID of the guideline
* @param margin the margin to the right or bottom side of container
*/
public void setGuidelineEnd(int guidelineID, int margin) {
get(guidelineID).layout.guideEnd = margin;
get(guidelineID).layout.guideBegin = Layout.UNSET;
get(guidelineID).layout.guidePercent = Layout.UNSET;
}
/**
* Set a Guideline's percent.
*
* @param guidelineID ID of the guideline
* @param ratio the ratio between the gap on the left and right 0.0 is top/left 0.5 is middle
*/
public void setGuidelinePercent(int guidelineID, float ratio) {
get(guidelineID).layout.guidePercent = ratio;
get(guidelineID).layout.guideEnd = Layout.UNSET;
get(guidelineID).layout.guideBegin = Layout.UNSET;
}
/**
* get the reference id's of a helper.
*
* @param id
* @return array of id's
*/
public int[] getReferencedIds(int id) {
Constraint constraint = get(id);
if (constraint.layout.mReferenceIds == null) {
return new int[0];
}
return Arrays.copyOf(constraint.layout.mReferenceIds, constraint.layout.mReferenceIds.length);
}
/**
* sets the reference id's of a barrier.
*
* @param id
* @param referenced
* @since 2.0
*/
public void setReferencedIds(int id, int... referenced) {
Constraint constraint = get(id);
constraint.layout.mReferenceIds = referenced;
}
public void setBarrierType(int id, int type) {
Constraint constraint = get(id);
constraint.layout.mHelperType = type;
}
public void removeAttribute(String attributeName) {
mSavedAttributes.remove(attributeName);
}
public void setIntValue(int viewId, String attributeName, int value) {
get(viewId).setIntValue(attributeName, value);
}
public void setColorValue(int viewId, String attributeName, int value) {
get(viewId).setColorValue(attributeName, value);
}
public void setFloatValue(int viewId, String attributeName, float value) {
get(viewId).setFloatValue(attributeName, value);
}
public void setStringValue(int viewId, String attributeName, String value) {
get(viewId).setStringValue(attributeName, value);
}
private void addAttributes(AttributeType attributeType, String... attributeName) {
ConstraintAttribute constraintAttribute = null;
for (int i = 0; i < attributeName.length; i++) {
if (mSavedAttributes.containsKey(attributeName[i])) {
constraintAttribute = mSavedAttributes.get(attributeName[i]);
if (constraintAttribute == null) {
continue;
}
if (constraintAttribute.getType() != attributeType) {
throw new IllegalArgumentException(
"ConstraintAttribute is already a " + constraintAttribute.getType().name());
}
} else {
constraintAttribute = new ConstraintAttribute(attributeName[i], attributeType);
mSavedAttributes.put(attributeName[i], constraintAttribute);
}
}
}
public void parseIntAttributes(Constraint set, String attributes) {
String[] sp = attributes.split(",");
for (int i = 0; i < sp.length; i++) {
String[] attr = sp[i].split("=");
if (attr.length != 2) {
Log.w(TAG, " Unable to parse " + sp[i]);
} else {
set.setFloatValue(attr[0], Integer.decode(attr[1]));
}
}
}
public void parseColorAttributes(Constraint set, String attributes) {
String[] sp = attributes.split(",");
for (int i = 0; i < sp.length; i++) {
String[] attr = sp[i].split("=");
if (attr.length != 2) {
Log.w(TAG, " Unable to parse " + sp[i]);
} else {
set.setColorValue(attr[0], Color.parseColor(attr[1]));
}
}
}
public void parseFloatAttributes(Constraint set, String attributes) {
String[] sp = attributes.split(",");
for (int i = 0; i < sp.length; i++) {
String[] attr = sp[i].split("=");
if (attr.length != 2) {
Log.w(TAG, " Unable to parse " + sp[i]);
} else {
set.setFloatValue(attr[0], Float.parseFloat(attr[1]));
}
}
}
public void parseStringAttributes(Constraint set, String attributes) {
String[] sp = splitString(attributes);
for (int i = 0; i < sp.length; i++) {
String[] attr = sp[i].split("=");
Log.w(TAG, " Unable to parse " + sp[i]);
set.setStringValue(attr[0], attr[1]);
}
}
private static String[] splitString(String str) {
char[] chars = str.toCharArray();
ArrayList<String> list = new ArrayList<>();
boolean inDouble = false;
int start = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == ',' && !inDouble) {
list.add(new String(chars, start, i - start));
start = i + 1;
} else if (chars[i] == '"') {
inDouble = !inDouble;
}
}
list.add(new String(chars, start, chars.length - start));
return list.toArray(new String[list.size()]);
}
public void addIntAttributes(String... attributeName) {
addAttributes(AttributeType.INT_TYPE, attributeName);
}
public void addColorAttributes(String... attributeName) {
addAttributes(AttributeType.COLOR_TYPE, attributeName);
}
public void addFloatAttributes(String... attributeName) {
addAttributes(AttributeType.FLOAT_TYPE, attributeName);
}
public void addStringAttributes(String... attributeName) {
addAttributes(AttributeType.STRING_TYPE, attributeName);
}
private Constraint get(int id) {
if (!mConstraints.containsKey(id)) {
mConstraints.put(id, new Constraint());
}
return mConstraints.get(id);
}
private String sideToString(int side) {
switch (side) {
case LEFT:
return "left";
case RIGHT:
return "right";
case TOP:
return "top";
case BOTTOM:
return "bottom";
case BASELINE:
return "baseline";
case START:
return "start";
case END:
return "end";
}
return "undefined";
}
/**
* Load a constraint set from a constraintSet.xml file.
* Note. Do NOT use this to load a layout file.
* It will fail silently as there is no efficient way to differentiate.
*
* @param context the context for the inflation
* @param resourceId id of xml file in res/xml/
*/
public void load(Context context, int resourceId) {
Resources res = context.getResources();
XmlPullParser parser = res.getXml(resourceId);
String document = null;
String tagName = null;
try {
for (int eventType = parser.getEventType();
eventType != XmlResourceParser.END_DOCUMENT;
eventType = parser.next()) {
switch (eventType) {
case XmlResourceParser.START_DOCUMENT:
document = parser.getName();
break;
case XmlResourceParser.START_TAG:
tagName = parser.getName();
Constraint constraint = fillFromAttributeList(context, Xml.asAttributeSet(parser), false);
if (tagName.equalsIgnoreCase("Guideline")) {
constraint.layout.mIsGuideline = true;
}
if (DEBUG) {
Log.v(TAG, Debug.getLoc() + " cache " + Debug.getName(context, constraint.mViewId) + " " + constraint.mViewId);
}
mConstraints.put(constraint.mViewId, constraint);
break;
case XmlResourceParser.END_TAG:
tagName = null;
break;
case XmlResourceParser.TEXT:
break;
}
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Load a constraint set from a constraintSet.xml file
*
* @param context the context for the inflation
* @param parser id of xml file in res/xml/
*/
public void load(Context context, XmlPullParser parser) {
String tagName = null;
try {
Constraint constraint = null;
for (int eventType = parser.getEventType();
eventType != XmlResourceParser.END_DOCUMENT;
eventType = parser.next()) {
switch (eventType) {
case XmlResourceParser.START_DOCUMENT:
String document = parser.getName();
break;
case XmlResourceParser.START_TAG:
tagName = parser.getName();
if (DEBUG) {
Log.v(TAG, Debug.getLoc() + " view .... tagName=" + tagName);
}
switch (tagName) {
case "Constraint":
constraint = fillFromAttributeList(context, Xml.asAttributeSet(parser), false);
break;
case "ConstraintOverride":
constraint = fillFromAttributeList(context, Xml.asAttributeSet(parser), true);
break;
case "Guideline":
constraint = fillFromAttributeList(context, Xml.asAttributeSet(parser), false);
constraint.layout.mIsGuideline = true;
constraint.layout.mApply = true;
break;
case "Barrier":
constraint = fillFromAttributeList(context, Xml.asAttributeSet(parser), false);
constraint.layout.mHelperType = BARRIER_TYPE;
break;
case "PropertySet":
if (constraint == null) {
throw new RuntimeException(ERROR_MESSAGE + parser.getLineNumber());
}
constraint.propertySet.fillFromAttributeList(context, Xml.asAttributeSet(parser));
break;
case "Transform":
if (constraint == null) {
throw new RuntimeException(ERROR_MESSAGE + parser.getLineNumber());
}
constraint.transform.fillFromAttributeList(context, Xml.asAttributeSet(parser));
break;
case "Layout":
if (constraint == null) {
throw new RuntimeException(ERROR_MESSAGE + parser.getLineNumber());
}
constraint.layout.fillFromAttributeList(context, Xml.asAttributeSet(parser));
break;
case "Motion":
if (constraint == null) {
throw new RuntimeException(ERROR_MESSAGE + parser.getLineNumber());
}
constraint.motion.fillFromAttributeList(context, Xml.asAttributeSet(parser));
break;
case "CustomAttribute":
case "CustomMethod":
if (constraint == null) {
throw new RuntimeException(ERROR_MESSAGE + parser.getLineNumber());
}
ConstraintAttribute.parse(context, parser, constraint.mCustomConstraints);
break;
}
// if (tagName.equalsIgnoreCase("Constraint")) {
// constraint = fillFromAttributeList(context, Xml.asAttributeSet(parser));
// } else if (tagName.equalsIgnoreCase("Guideline")) {
// constraint = fillFromAttributeList(context, Xml.asAttributeSet(parser));
// constraint.layout.mIsGuideline = true;
// } else if (tagName.equalsIgnoreCase("CustomAttribute")) {
// ConstraintAttribute.parse(context, parser, constraint.mCustomConstraints);
// }
break;
case XmlResourceParser.END_TAG:
tagName = parser.getName();
switch (tagName.toLowerCase(Locale.ROOT)) {
case "constraintset":
return;
case "constraint":
case "constraintoverride":
case "guideline":
mConstraints.put(constraint.mViewId, constraint);
constraint = null;
}
tagName = null;
break;
case XmlResourceParser.TEXT:
break;
}
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static int lookupID(TypedArray a, int index, int def) {
int ret = a.getResourceId(index, def);
if (ret == Layout.UNSET) {
ret = a.getInt(index, Layout.UNSET);
}
return ret;
}
private Constraint fillFromAttributeList(Context context, AttributeSet attrs, boolean override) {
Constraint c = new Constraint();
TypedArray a = context.obtainStyledAttributes(attrs, override ? R.styleable.ConstraintOverride : R.styleable.Constraint);
populateConstraint(context, c, a, override);
a.recycle();
return c;
}
/**
* Used to read a ConstraintDelta
*
* @param context
* @param parser
* @return
*/
public static Constraint buildDelta(Context context, XmlPullParser parser) {
AttributeSet attrs = Xml.asAttributeSet(parser);
Constraint c = new Constraint();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ConstraintOverride);
populateOverride(context, c, a);
a.recycle();
return c;
}
private static void populateOverride(Context ctx, Constraint c, TypedArray a) {
final int N = a.getIndexCount();
TypedValue type;
Constraint.Delta delta = new Constraint.Delta();
c.mDelta = delta;
c.motion.mApply = false;
c.layout.mApply = false;
c.propertySet.mApply = false;
c.transform.mApply = false;
for (int i = 0; i < N; i++) {
int attr = a.getIndex(i);
int attrType = overrideMapToConstant.get(attr);
if (DEBUG) {
Log.v(TAG, Debug.getLoc() + " > " + attrType + " " + getDebugName(attrType));
}
switch (attrType) {
case EDITOR_ABSOLUTE_X:
delta.add(EDITOR_ABSOLUTE_X, a.getDimensionPixelOffset(attr, c.layout.editorAbsoluteX));
break;
case EDITOR_ABSOLUTE_Y:
delta.add(EDITOR_ABSOLUTE_Y, a.getDimensionPixelOffset(attr, c.layout.editorAbsoluteY));
break;
case GUIDE_BEGIN:
delta.add(GUIDE_BEGIN, a.getDimensionPixelOffset(attr, c.layout.guideBegin));
break;
case GUIDE_END:
delta.add(GUIDE_END, a.getDimensionPixelOffset(attr, c.layout.guideEnd));
break;
case GUIDE_PERCENT:
delta.add(GUIDE_PERCENT, a.getFloat(attr, c.layout.guidePercent));
break;
case ORIENTATION:
delta.add(ORIENTATION, a.getInt(attr, c.layout.orientation));
break;
case CIRCLE_RADIUS:
delta.add(CIRCLE_RADIUS, a.getDimensionPixelSize(attr, c.layout.circleRadius));
break;
case CIRCLE_ANGLE:
delta.add(CIRCLE_ANGLE, a.getFloat(attr, c.layout.circleAngle));
break;
case GONE_LEFT_MARGIN:
delta.add(GONE_LEFT_MARGIN, a.getDimensionPixelSize(attr, c.layout.goneLeftMargin));
break;
case GONE_TOP_MARGIN:
delta.add(GONE_TOP_MARGIN, a.getDimensionPixelSize(attr, c.layout.goneTopMargin));
break;
case GONE_RIGHT_MARGIN:
delta.add(GONE_RIGHT_MARGIN, a.getDimensionPixelSize(attr, c.layout.goneRightMargin));
break;
case GONE_BOTTOM_MARGIN:
delta.add(GONE_BOTTOM_MARGIN, a.getDimensionPixelSize(attr, c.layout.goneBottomMargin));
break;
case GONE_START_MARGIN:
delta.add(GONE_START_MARGIN, a.getDimensionPixelSize(attr, c.layout.goneStartMargin));
break;
case GONE_END_MARGIN:
delta.add(GONE_END_MARGIN, a.getDimensionPixelSize(attr, c.layout.goneEndMargin));
break;
case GONE_BASELINE_MARGIN:
delta.add(GONE_BASELINE_MARGIN, a.getDimensionPixelSize(attr, c.layout.goneBaselineMargin));
break;
case HORIZONTAL_BIAS:
delta.add(HORIZONTAL_BIAS, a.getFloat(attr, c.layout.horizontalBias));
break;
case VERTICAL_BIAS:
delta.add(VERTICAL_BIAS, a.getFloat(attr, c.layout.verticalBias));
break;
case LEFT_MARGIN:
delta.add(LEFT_MARGIN, a.getDimensionPixelSize(attr, c.layout.leftMargin));
break;
case RIGHT_MARGIN:
delta.add(RIGHT_MARGIN, a.getDimensionPixelSize(attr, c.layout.rightMargin));
break;
case START_MARGIN:
if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) {
delta.add(START_MARGIN, a.getDimensionPixelSize(attr, c.layout.startMargin));
}
break;
case END_MARGIN:
if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) {
delta.add(END_MARGIN, a.getDimensionPixelSize(attr, c.layout.endMargin));
}
break;
case TOP_MARGIN:
delta.add(TOP_MARGIN, a.getDimensionPixelSize(attr, c.layout.topMargin));
break;
case BOTTOM_MARGIN:
delta.add(BOTTOM_MARGIN, a.getDimensionPixelSize(attr, c.layout.bottomMargin));
break;
case BASELINE_MARGIN:
delta.add(BASELINE_MARGIN, a.getDimensionPixelSize(attr, c.layout.baselineMargin));
break;
case LAYOUT_WIDTH:
delta.add(LAYOUT_WIDTH, a.getLayoutDimension(attr, c.layout.mWidth));
break;
case LAYOUT_HEIGHT:
delta.add(LAYOUT_HEIGHT, a.getLayoutDimension(attr, c.layout.mHeight));
break;
case LAYOUT_CONSTRAINT_WIDTH:
ConstraintSet.parseDimensionConstraints(delta, a, attr, HORIZONTAL);
break;
case LAYOUT_CONSTRAINT_HEIGHT:
ConstraintSet.parseDimensionConstraints(delta, a, attr, VERTICAL);
break;
case LAYOUT_WRAP_BEHAVIOR:
delta.add(LAYOUT_WRAP_BEHAVIOR, a.getInt(attr, c.layout.mWrapBehavior));
break;
case WIDTH_DEFAULT:
delta.add(WIDTH_DEFAULT, a.getInt(attr, c.layout.widthDefault));
break;
case HEIGHT_DEFAULT:
delta.add(HEIGHT_DEFAULT, a.getInt(attr, c.layout.heightDefault));
break;
case HEIGHT_MAX:
delta.add(HEIGHT_MAX, a.getDimensionPixelSize(attr, c.layout.heightMax));
break;
case WIDTH_MAX:
delta.add(WIDTH_MAX, a.getDimensionPixelSize(attr, c.layout.widthMax));
break;
case HEIGHT_MIN:
delta.add(HEIGHT_MIN, a.getDimensionPixelSize(attr, c.layout.heightMin));
break;
case WIDTH_MIN:
delta.add(WIDTH_MIN, a.getDimensionPixelSize(attr, c.layout.widthMin));
break;
case CONSTRAINED_WIDTH:
delta.add(CONSTRAINED_WIDTH, a.getBoolean(attr, c.layout.constrainedWidth));
break;
case CONSTRAINED_HEIGHT:
delta.add(CONSTRAINED_HEIGHT, a.getBoolean(attr, c.layout.constrainedHeight));
break;
case LAYOUT_VISIBILITY:
delta.add(LAYOUT_VISIBILITY, VISIBILITY_FLAGS[a.getInt(attr, c.propertySet.visibility)]);
break;
case VISIBILITY_MODE:
delta.add(VISIBILITY_MODE, a.getInt(attr, c.propertySet.mVisibilityMode));
break;
case ALPHA:
delta.add(ALPHA, a.getFloat(attr, c.propertySet.alpha));
break;
case ELEVATION:
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
delta.add(ELEVATION, true);
delta.add(ELEVATION, a.getDimension(attr, c.transform.elevation));
}
break;
case ROTATION:
delta.add(ROTATION, a.getFloat(attr, c.transform.rotation));
break;
case ROTATION_X:
delta.add(ROTATION_X, a.getFloat(attr, c.transform.rotationX));
break;
case ROTATION_Y:
delta.add(ROTATION_Y, a.getFloat(attr, c.transform.rotationY));
break;
case SCALE_X:
delta.add(SCALE_X, a.getFloat(attr, c.transform.scaleX));
break;
case SCALE_Y:
delta.add(SCALE_Y, a.getFloat(attr, c.transform.scaleY));
break;
case TRANSFORM_PIVOT_X:
delta.add(TRANSFORM_PIVOT_X, a.getDimension(attr, c.transform.transformPivotX));
break;
case TRANSFORM_PIVOT_Y:
delta.add(TRANSFORM_PIVOT_Y, a.getDimension(attr, c.transform.transformPivotY));
break;
case TRANSLATION_X:
delta.add(TRANSLATION_X, a.getDimension(attr, c.transform.translationX));
break;
case TRANSLATION_Y:
delta.add(TRANSLATION_Y, a.getDimension(attr, c.transform.translationY));
break;
case TRANSLATION_Z:
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
delta.add(TRANSLATION_Z, a.getDimension(attr, c.transform.translationZ));
}
break;
case TRANSFORM_PIVOT_TARGET:
delta.add(TRANSFORM_PIVOT_TARGET, lookupID(a, attr, c.transform.transformPivotTarget));
break;
case VERTICAL_WEIGHT:
delta.add(VERTICAL_WEIGHT, a.getFloat(attr, c.layout.verticalWeight));
break;
case HORIZONTAL_WEIGHT:
delta.add(HORIZONTAL_WEIGHT, a.getFloat(attr, c.layout.horizontalWeight));
break;
case VERTICAL_STYLE:
delta.add(VERTICAL_STYLE, a.getInt(attr, c.layout.verticalChainStyle));
break;
case HORIZONTAL_STYLE:
delta.add(HORIZONTAL_STYLE, a.getInt(attr, c.layout.horizontalChainStyle));
break;
case VIEW_ID:
c.mViewId = a.getResourceId(attr, c.mViewId);
delta.add(VIEW_ID, c.mViewId);
break;
case MOTION_TARGET:
if (MotionLayout.IS_IN_EDIT_MODE) {
c.mViewId = a.getResourceId(attr, c.mViewId);
if (c.mViewId == -1) {
c.mTargetString = a.getString(attr);
}
} else {
if (a.peekValue(attr).type == TypedValue.TYPE_STRING) {
c.mTargetString = a.getString(attr);
} else {
c.mViewId = a.getResourceId(attr, c.mViewId);
}
}
break;
case DIMENSION_RATIO:
delta.add(DIMENSION_RATIO, a.getString(attr));
break;
case WIDTH_PERCENT:
delta.add(WIDTH_PERCENT, a.getFloat(attr, 1));
break;
case HEIGHT_PERCENT:
delta.add(HEIGHT_PERCENT, a.getFloat(attr, 1));
break;
case PROGRESS:
delta.add(PROGRESS, a.getFloat(attr, c.propertySet.mProgress));
break;
case ANIMATE_RELATIVE_TO:
delta.add(ANIMATE_RELATIVE_TO, lookupID(a, attr, c.motion.mAnimateRelativeTo));
break;
case ANIMATE_CIRCLE_ANGLE_TO:
delta.add(ANIMATE_CIRCLE_ANGLE_TO, a.getInteger(attr, c.motion.mAnimateCircleAngleTo));
break;
case TRANSITION_EASING:
type = a.peekValue(attr);
if (type.type == TypedValue.TYPE_STRING) {
delta.add(TRANSITION_EASING, a.getString(attr));
} else {
delta.add(TRANSITION_EASING, Easing.NAMED_EASING[a.getInteger(attr, 0)]);
}
break;
case PATH_MOTION_ARC:
delta.add(PATH_MOTION_ARC, a.getInt(attr, c.motion.mPathMotionArc));
break;
case TRANSITION_PATH_ROTATE:
delta.add(TRANSITION_PATH_ROTATE, a.getFloat(attr, c.motion.mPathRotate));
break;
case MOTION_STAGGER:
delta.add(MOTION_STAGGER, a.getFloat(attr, c.motion.mMotionStagger));
break;
case QUANTIZE_MOTION_STEPS:
delta.add(QUANTIZE_MOTION_STEPS, a.getInteger(attr, c.motion.mQuantizeMotionSteps));
break;
case QUANTIZE_MOTION_PHASE:
delta.add(QUANTIZE_MOTION_PHASE, a.getFloat(attr, c.motion.mQuantizeMotionPhase));
break;
case QUANTIZE_MOTION_INTERPOLATOR:
type = a.peekValue(attr);
if (type.type == TypedValue.TYPE_REFERENCE) {
c.motion.mQuantizeInterpolatorID = a.getResourceId(attr, -1);
delta.add(QUANTIZE_MOTION_INTERPOLATOR_ID, c.motion.mQuantizeInterpolatorID);
if (c.motion.mQuantizeInterpolatorID != -1) {
c.motion.mQuantizeInterpolatorType = Motion.INTERPOLATOR_REFERENCE_ID;
delta.add(QUANTIZE_MOTION_INTERPOLATOR_TYPE, c.motion.mQuantizeInterpolatorType);
}
} else if (type.type == TypedValue.TYPE_STRING) {
c.motion.mQuantizeInterpolatorString = a.getString(attr);
delta.add(QUANTIZE_MOTION_INTERPOLATOR_STR, c.motion.mQuantizeInterpolatorString);
if (c.motion.mQuantizeInterpolatorString.indexOf("/") > 0) {
c.motion.mQuantizeInterpolatorID = a.getResourceId(attr, -1);
delta.add(QUANTIZE_MOTION_INTERPOLATOR_ID, c.motion.mQuantizeInterpolatorID);
c.motion.mQuantizeInterpolatorType = Motion.INTERPOLATOR_REFERENCE_ID;
delta.add(QUANTIZE_MOTION_INTERPOLATOR_TYPE, c.motion.mQuantizeInterpolatorType);
} else {
c.motion.mQuantizeInterpolatorType = Motion.SPLINE_STRING;
delta.add(QUANTIZE_MOTION_INTERPOLATOR_TYPE, c.motion.mQuantizeInterpolatorType);
}
} else {
c.motion.mQuantizeInterpolatorType = a.getInteger(attr, c.motion.mQuantizeInterpolatorID);
delta.add(QUANTIZE_MOTION_INTERPOLATOR_TYPE, c.motion.mQuantizeInterpolatorType);
}
break;
case DRAW_PATH:
delta.add(DRAW_PATH, a.getInt(attr, 0));
break;
case CHAIN_USE_RTL:
Log.e(TAG, "CURRENTLY UNSUPPORTED"); // TODO add support or remove
// TODO add support or remove c.mChainUseRtl = a.getBoolean(attr,c.mChainUseRtl);
break;
case BARRIER_DIRECTION:
delta.add(BARRIER_DIRECTION, a.getInt(attr, c.layout.mBarrierDirection));
break;
case BARRIER_MARGIN:
delta.add(BARRIER_MARGIN, a.getDimensionPixelSize(attr, c.layout.mBarrierMargin));
break;
case CONSTRAINT_REFERENCED_IDS:
delta.add(CONSTRAINT_REFERENCED_IDS, a.getString(attr));
break;
case CONSTRAINT_TAG:
delta.add(CONSTRAINT_TAG, a.getString(attr));
break;
case BARRIER_ALLOWS_GONE_WIDGETS:
delta.add(BARRIER_ALLOWS_GONE_WIDGETS, a.getBoolean(attr, c.layout.mBarrierAllowsGoneWidgets));
break;
case UNUSED:
Log.w(TAG,
"unused attribute 0x" + Integer.toHexString(attr) + " " + mapToConstant.get(attr));
break;
default:
Log.w(TAG,
"Unknown attribute 0x" + Integer.toHexString(attr) + " " + mapToConstant.get(attr));
}
}
}
private static void setDeltaValue(Constraint c, int type, float value) {
switch (type) {
case GUIDE_PERCENT:
c.layout.guidePercent = value;
break;
case CIRCLE_ANGLE:
c.layout.circleAngle = value;
break;
case HORIZONTAL_BIAS:
c.layout.horizontalBias = value;
break;
case VERTICAL_BIAS:
c.layout.verticalBias = value;
break;
case ALPHA:
c.propertySet.alpha = value;
break;
case ELEVATION:
c.transform.elevation = value;
c.transform.applyElevation = true;
break;
case ROTATION:
c.transform.rotation = value;
break;
case ROTATION_X:
c.transform.rotationX = value;
break;
case ROTATION_Y:
c.transform.rotationY = value;
break;
case SCALE_X:
c.transform.scaleX = value;
break;
case SCALE_Y:
c.transform.scaleY = value;
break;
case TRANSFORM_PIVOT_X:
c.transform.transformPivotX = value;
break;
case TRANSFORM_PIVOT_Y:
c.transform.transformPivotY = value;
break;
case TRANSLATION_X:
c.transform.translationX = value;
break;
case TRANSLATION_Y:
c.transform.translationY = value;
break;
case TRANSLATION_Z:
c.transform.translationZ = value;
break;
case VERTICAL_WEIGHT:
c.layout.verticalWeight = value;
break;
case HORIZONTAL_WEIGHT:
c.layout.horizontalWeight = value;
break;
case WIDTH_PERCENT:
c.layout.widthPercent = value;
break;
case HEIGHT_PERCENT:
c.layout.heightPercent = value;
break;
case PROGRESS:
c.propertySet.mProgress = value;
break;
case TRANSITION_PATH_ROTATE:
c.motion.mPathRotate = value;
break;
case MOTION_STAGGER:
c.motion.mMotionStagger = value;
break;
case QUANTIZE_MOTION_PHASE:
c.motion.mQuantizeMotionPhase = value;
break;
case UNUSED:
break;
default:
Log.w(TAG,
"Unknown attribute 0x");
}
}
private static void setDeltaValue(Constraint c, int type, int value) {
switch (type) {
case EDITOR_ABSOLUTE_X:
c.layout.editorAbsoluteX = value;
break;
case EDITOR_ABSOLUTE_Y:
c.layout.editorAbsoluteY = value;
break;
case LAYOUT_WRAP_BEHAVIOR:
c.layout.mWrapBehavior = value;
break;
case GUIDE_BEGIN:
c.layout.guideBegin = value;
break;
case GUIDE_END:
c.layout.guideEnd = value;
break;
case ORIENTATION:
c.layout.orientation = value;
break;
case CIRCLE:
c.layout.circleConstraint = value;
break;
case CIRCLE_RADIUS:
c.layout.circleRadius = value;
break;
case GONE_LEFT_MARGIN:
c.layout.goneLeftMargin = value;
break;
case GONE_TOP_MARGIN:
c.layout.goneTopMargin = value;
break;
case GONE_RIGHT_MARGIN:
c.layout.goneRightMargin = value;
break;
case GONE_BOTTOM_MARGIN:
c.layout.goneBottomMargin = value;
break;
case GONE_START_MARGIN:
c.layout.goneStartMargin = value;
break;
case GONE_END_MARGIN:
c.layout.goneEndMargin = value;
break;
case GONE_BASELINE_MARGIN:
c.layout.goneBaselineMargin = value;
break;
case LEFT_MARGIN:
c.layout.leftMargin = value;
break;
case RIGHT_MARGIN:
c.layout.rightMargin = value;
break;
case START_MARGIN:
c.layout.startMargin = value;
break;
case END_MARGIN:
c.layout.endMargin = value;
break;
case TOP_MARGIN:
c.layout.topMargin = value;
break;
case BOTTOM_MARGIN:
c.layout.bottomMargin = value;
break;
case BASELINE_MARGIN:
c.layout.baselineMargin = value;
break;
case LAYOUT_WIDTH:
c.layout.mWidth = value;
break;
case LAYOUT_HEIGHT:
c.layout.mHeight = value;
break;
case WIDTH_DEFAULT:
c.layout.widthDefault = value;
break;
case HEIGHT_DEFAULT:
c.layout.heightDefault = value;
break;
case HEIGHT_MAX:
c.layout.heightMax = value;
break;
case WIDTH_MAX:
c.layout.widthMax = value;
break;
case HEIGHT_MIN:
c.layout.heightMin = value;
break;
case WIDTH_MIN:
c.layout.widthMin = value;
break;
case LAYOUT_VISIBILITY:
c.propertySet.visibility = value;
break;
case VISIBILITY_MODE:
c.propertySet.mVisibilityMode = value;
break;
case TRANSFORM_PIVOT_TARGET:
c.transform.transformPivotTarget = value;
break;
case VERTICAL_STYLE:
c.layout.verticalChainStyle = value;
break;
case HORIZONTAL_STYLE:
c.layout.horizontalChainStyle = value;
break;
case VIEW_ID:
c.mViewId = value;
break;
case ANIMATE_RELATIVE_TO:
c.motion.mAnimateRelativeTo = value;
break;
case ANIMATE_CIRCLE_ANGLE_TO:
c.motion.mAnimateCircleAngleTo = value;
break;
case PATH_MOTION_ARC:
c.motion.mPathMotionArc = value;
break;
case QUANTIZE_MOTION_STEPS:
c.motion.mQuantizeMotionSteps = value;
break;
case QUANTIZE_MOTION_INTERPOLATOR_TYPE:
c.motion.mQuantizeInterpolatorType = value;
break;
case QUANTIZE_MOTION_INTERPOLATOR_ID:
c.motion.mQuantizeInterpolatorID = value;
break;
case DRAW_PATH:
c.motion.mDrawPath = value;
break;
case BARRIER_DIRECTION:
c.layout.mBarrierDirection = value;
break;
case BARRIER_MARGIN:
c.layout.mBarrierMargin = value;
break;
case UNUSED:
break;
default:
Log.w(TAG,
"Unknown attribute 0x");
}
}
private static void setDeltaValue(Constraint c, int type, String value) {
switch (type) {
case DIMENSION_RATIO:
c.layout.dimensionRatio = value;
break;
case TRANSITION_EASING:
c.motion.mTransitionEasing = value;
break;
case QUANTIZE_MOTION_INTERPOLATOR_STR:
c.motion.mQuantizeInterpolatorString = value;
break;
case CONSTRAINT_REFERENCED_IDS:
c.layout.mReferenceIdString = value;
// If a string is defined, clear up the reference ids array
c.layout.mReferenceIds = null;
break;
case CONSTRAINT_TAG:
c.layout.mConstraintTag = value;
break;
case UNUSED:
break;
default:
Log.w(TAG,
"Unknown attribute 0x");
}
}
private static void setDeltaValue(Constraint c, int type, boolean value) {
switch (type) {
case CONSTRAINED_WIDTH:
c.layout.constrainedWidth = value;
break;
case CONSTRAINED_HEIGHT:
c.layout.constrainedHeight = value;
break;
case ELEVATION:
c.transform.applyElevation = value;
break;
case BARRIER_ALLOWS_GONE_WIDGETS:
c.layout.mBarrierAllowsGoneWidgets = value;
break;
case UNUSED:
break;
default:
Log.w(TAG, "Unknown attribute 0x");
}
}
private void populateConstraint(Context ctx, Constraint c, TypedArray a, boolean override) {
if (override) {
populateOverride(ctx, c, a);
return;
}
final int N = a.getIndexCount();
for (int i = 0; i < N; i++) {
int attr = a.getIndex(i);
if (DEBUG) { // USEFUL when adding features to track tags being parsed
try {
Field[] campos = R.styleable.class.getFields();
boolean found = false;
for (Field f : campos) {
try {
if (f.getType().isPrimitive() && attr == f.getInt(null) && f.getName()
.contains("Constraint_")) {
found = true;
if (DEBUG) {
Log.v(TAG, "L id " + f.getName() + " #" + attr);
}
break;
}
} catch (Exception e) {
}
}
if (!found) {
campos = android.R.attr.class.getFields();
for (Field f : campos) {
try {
if (f.getType().isPrimitive() && attr == f.getInt(null) && f.getName()
.contains("Constraint_")) {
found = false;
if (DEBUG) {
Log.v(TAG, "x id " + f.getName());
}
break;
}
} catch (Exception e) {
}
}
}
if (!found) {
Log.v(TAG, " ? " + attr);
}
} catch (Exception e) {
Log.v(TAG, " " + e.toString());
}
}
if (attr != R.styleable.Constraint_android_id &&
R.styleable.Constraint_android_layout_marginStart != attr &&
R.styleable.Constraint_android_layout_marginEnd != attr) {
c.motion.mApply = true;
c.layout.mApply = true;
c.propertySet.mApply = true;
c.transform.mApply = true;
}
switch (mapToConstant.get(attr)) {
case LEFT_TO_LEFT:
c.layout.leftToLeft = lookupID(a, attr, c.layout.leftToLeft);
break;
case LEFT_TO_RIGHT:
c.layout.leftToRight = lookupID(a, attr, c.layout.leftToRight);
break;
case RIGHT_TO_LEFT:
c.layout.rightToLeft = lookupID(a, attr, c.layout.rightToLeft);
break;
case RIGHT_TO_RIGHT:
c.layout.rightToRight = lookupID(a, attr, c.layout.rightToRight);
break;
case TOP_TO_TOP:
c.layout.topToTop = lookupID(a, attr, c.layout.topToTop);
break;
case TOP_TO_BOTTOM:
c.layout.topToBottom = lookupID(a, attr, c.layout.topToBottom);
break;
case BOTTOM_TO_TOP:
c.layout.bottomToTop = lookupID(a, attr, c.layout.bottomToTop);
break;
case BOTTOM_TO_BOTTOM:
c.layout.bottomToBottom = lookupID(a, attr, c.layout.bottomToBottom);
break;
case BASELINE_TO_BASELINE:
c.layout.baselineToBaseline = lookupID(a, attr, c.layout.baselineToBaseline);
break;
case BASELINE_TO_TOP:
c.layout.baselineToTop = lookupID(a, attr, c.layout.baselineToTop);
break;
case BASELINE_TO_BOTTOM:
c.layout.baselineToBottom = lookupID(a, attr, c.layout.baselineToBottom);
break;
case EDITOR_ABSOLUTE_X:
c.layout.editorAbsoluteX = a.getDimensionPixelOffset(attr, c.layout.editorAbsoluteX);
break;
case EDITOR_ABSOLUTE_Y:
c.layout.editorAbsoluteY = a.getDimensionPixelOffset(attr, c.layout.editorAbsoluteY);
break;
case GUIDE_BEGIN:
c.layout.guideBegin = a.getDimensionPixelOffset(attr, c.layout.guideBegin);
break;
case GUIDE_END:
c.layout.guideEnd = a.getDimensionPixelOffset(attr, c.layout.guideEnd);
break;
case GUIDE_PERCENT:
c.layout.guidePercent = a.getFloat(attr, c.layout.guidePercent);
break;
case ORIENTATION:
c.layout.orientation = a.getInt(attr, c.layout.orientation);
break;
case START_TO_END:
c.layout.startToEnd = lookupID(a, attr, c.layout.startToEnd);
break;
case START_TO_START:
c.layout.startToStart = lookupID(a, attr, c.layout.startToStart);
break;
case END_TO_START:
c.layout.endToStart = lookupID(a, attr, c.layout.endToStart);
break;
case END_TO_END:
c.layout.endToEnd = lookupID(a, attr, c.layout.endToEnd);
break;
case CIRCLE:
c.layout.circleConstraint = lookupID(a, attr, c.layout.circleConstraint);
break;
case CIRCLE_RADIUS:
c.layout.circleRadius = a.getDimensionPixelSize(attr, c.layout.circleRadius);
break;
case CIRCLE_ANGLE:
c.layout.circleAngle = a.getFloat(attr, c.layout.circleAngle);
break;
case GONE_LEFT_MARGIN:
c.layout.goneLeftMargin = a.getDimensionPixelSize(attr, c.layout.goneLeftMargin);
break;
case GONE_TOP_MARGIN:
c.layout.goneTopMargin = a.getDimensionPixelSize(attr, c.layout.goneTopMargin);
break;
case GONE_RIGHT_MARGIN:
c.layout.goneRightMargin = a.getDimensionPixelSize(attr, c.layout.goneRightMargin);
break;
case GONE_BOTTOM_MARGIN:
c.layout.goneBottomMargin = a.getDimensionPixelSize(attr, c.layout.goneBottomMargin);
break;
case GONE_START_MARGIN:
c.layout.goneStartMargin = a.getDimensionPixelSize(attr, c.layout.goneStartMargin);
break;
case GONE_END_MARGIN:
c.layout.goneEndMargin = a.getDimensionPixelSize(attr, c.layout.goneEndMargin);
break;
case GONE_BASELINE_MARGIN:
c.layout.goneBaselineMargin = a.getDimensionPixelSize(attr, c.layout.goneBaselineMargin);
break;
case HORIZONTAL_BIAS:
c.layout.horizontalBias = a.getFloat(attr, c.layout.horizontalBias);
break;
case VERTICAL_BIAS:
c.layout.verticalBias = a.getFloat(attr, c.layout.verticalBias);
break;
case LEFT_MARGIN:
c.layout.leftMargin = a.getDimensionPixelSize(attr, c.layout.leftMargin);
break;
case RIGHT_MARGIN:
c.layout.rightMargin = a.getDimensionPixelSize(attr, c.layout.rightMargin);
break;
case START_MARGIN:
if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) {
c.layout.startMargin = a.getDimensionPixelSize(attr, c.layout.startMargin);
}
break;
case END_MARGIN:
if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) {
c.layout.endMargin = a.getDimensionPixelSize(attr, c.layout.endMargin);
}
break;
case TOP_MARGIN:
c.layout.topMargin = a.getDimensionPixelSize(attr, c.layout.topMargin);
break;
case BOTTOM_MARGIN:
c.layout.bottomMargin = a.getDimensionPixelSize(attr, c.layout.bottomMargin);
break;
case BASELINE_MARGIN:
c.layout.baselineMargin = a.getDimensionPixelSize(attr, c.layout.baselineMargin);
break;
case LAYOUT_WIDTH:
c.layout.mWidth = a.getLayoutDimension(attr, c.layout.mWidth);
break;
case LAYOUT_HEIGHT:
c.layout.mHeight = a.getLayoutDimension(attr, c.layout.mHeight);
break;
case LAYOUT_CONSTRAINT_WIDTH:
ConstraintSet.parseDimensionConstraints(c.layout, a, attr, HORIZONTAL);
break;
case LAYOUT_CONSTRAINT_HEIGHT:
ConstraintSet.parseDimensionConstraints(c.layout, a, attr, VERTICAL);
break;
case LAYOUT_WRAP_BEHAVIOR:
c.layout.mWrapBehavior = a.getInt(attr, c.layout.mWrapBehavior);
break;
case WIDTH_DEFAULT:
c.layout.widthDefault = a.getInt(attr, c.layout.widthDefault);
break;
case HEIGHT_DEFAULT:
c.layout.heightDefault = a.getInt(attr, c.layout.heightDefault);
break;
case HEIGHT_MAX:
c.layout.heightMax = a.getDimensionPixelSize(attr, c.layout.heightMax);
break;
case WIDTH_MAX:
c.layout.widthMax = a.getDimensionPixelSize(attr, c.layout.widthMax);
break;
case HEIGHT_MIN:
c.layout.heightMin = a.getDimensionPixelSize(attr, c.layout.heightMin);
break;
case WIDTH_MIN:
c.layout.widthMin = a.getDimensionPixelSize(attr, c.layout.widthMin);
break;
case CONSTRAINED_WIDTH:
c.layout.constrainedWidth = a.getBoolean(attr, c.layout.constrainedWidth);
break;
case CONSTRAINED_HEIGHT:
c.layout.constrainedHeight = a.getBoolean(attr, c.layout.constrainedHeight);
break;
case LAYOUT_VISIBILITY:
c.propertySet.visibility = a.getInt(attr, c.propertySet.visibility);
c.propertySet.visibility = VISIBILITY_FLAGS[c.propertySet.visibility];
break;
case VISIBILITY_MODE:
c.propertySet.mVisibilityMode = a.getInt(attr, c.propertySet.mVisibilityMode);
break;
case ALPHA:
c.propertySet.alpha = a.getFloat(attr, c.propertySet.alpha);
break;
case ELEVATION:
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
c.transform.applyElevation = true;
c.transform.elevation = a.getDimension(attr, c.transform.elevation);
}
break;
case ROTATION:
c.transform.rotation = a.getFloat(attr, c.transform.rotation);
break;
case ROTATION_X:
c.transform.rotationX = a.getFloat(attr, c.transform.rotationX);
break;
case ROTATION_Y:
c.transform.rotationY = a.getFloat(attr, c.transform.rotationY);
break;
case SCALE_X:
c.transform.scaleX = a.getFloat(attr, c.transform.scaleX);
break;
case SCALE_Y:
c.transform.scaleY = a.getFloat(attr, c.transform.scaleY);
break;
case TRANSFORM_PIVOT_X:
c.transform.transformPivotX = a.getDimension(attr, c.transform.transformPivotX);
break;
case TRANSFORM_PIVOT_Y:
c.transform.transformPivotY = a.getDimension(attr, c.transform.transformPivotY);
break;
case TRANSLATION_X:
c.transform.translationX = a.getDimension(attr, c.transform.translationX);
break;
case TRANSLATION_Y:
c.transform.translationY = a.getDimension(attr, c.transform.translationY);
break;
case TRANSLATION_Z:
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
c.transform.translationZ = a.getDimension(attr, c.transform.translationZ);
}
break;
case TRANSFORM_PIVOT_TARGET:
c.transform.transformPivotTarget = lookupID(a, attr, c.transform.transformPivotTarget);
break;
case VERTICAL_WEIGHT:
c.layout.verticalWeight = a.getFloat(attr, c.layout.verticalWeight);
break;
case HORIZONTAL_WEIGHT:
c.layout.horizontalWeight = a.getFloat(attr, c.layout.horizontalWeight);
break;
case VERTICAL_STYLE:
c.layout.verticalChainStyle = a.getInt(attr, c.layout.verticalChainStyle);
break;
case HORIZONTAL_STYLE:
c.layout.horizontalChainStyle = a.getInt(attr, c.layout.horizontalChainStyle);
break;
case VIEW_ID:
c.mViewId = a.getResourceId(attr, c.mViewId);
break;
case DIMENSION_RATIO:
c.layout.dimensionRatio = a.getString(attr);
break;
case WIDTH_PERCENT:
c.layout.widthPercent = a.getFloat(attr, 1);
break;
case HEIGHT_PERCENT:
c.layout.heightPercent = a.getFloat(attr, 1);
break;
case PROGRESS:
c.propertySet.mProgress = a.getFloat(attr, c.propertySet.mProgress);
break;
case ANIMATE_RELATIVE_TO:
c.motion.mAnimateRelativeTo = lookupID(a, attr, c.motion.mAnimateRelativeTo);
break;
case ANIMATE_CIRCLE_ANGLE_TO:
c.motion.mAnimateCircleAngleTo = a.getInteger(attr, c.motion.mAnimateCircleAngleTo);
break;
case TRANSITION_EASING:
TypedValue type = a.peekValue(attr);
if (type.type == TypedValue.TYPE_STRING) {
c.motion.mTransitionEasing = a.getString(attr);
} else {
c.motion.mTransitionEasing = Easing.NAMED_EASING[a.getInteger(attr, 0)];
}
break;
case PATH_MOTION_ARC:
c.motion.mPathMotionArc = a.getInt(attr, c.motion.mPathMotionArc);
break;
case TRANSITION_PATH_ROTATE:
c.motion.mPathRotate = a.getFloat(attr, c.motion.mPathRotate);
break;
case MOTION_STAGGER:
c.motion.mMotionStagger = a.getFloat(attr, c.motion.mMotionStagger);
break;
case QUANTIZE_MOTION_STEPS:
c.motion.mQuantizeMotionSteps = a.getInteger(attr, c.motion.mQuantizeMotionSteps);
break;
case QUANTIZE_MOTION_PHASE:
c.motion.mQuantizeMotionPhase = a.getFloat(attr, c.motion.mQuantizeMotionPhase);
break;
case QUANTIZE_MOTION_INTERPOLATOR:
type = a.peekValue(attr);
if (type.type == TypedValue.TYPE_REFERENCE) {
c.motion.mQuantizeInterpolatorID = a.getResourceId(attr, -1);
if (c.motion.mQuantizeInterpolatorID != -1) {
c.motion.mQuantizeInterpolatorType = Motion.INTERPOLATOR_REFERENCE_ID;
}
} else if (type.type == TypedValue.TYPE_STRING) {
c.motion.mQuantizeInterpolatorString = a.getString(attr);
if (c.motion.mQuantizeInterpolatorString.indexOf("/") > 0) {
c.motion.mQuantizeInterpolatorID = a.getResourceId(attr, -1);
c.motion.mQuantizeInterpolatorType = Motion.INTERPOLATOR_REFERENCE_ID;
} else {
c.motion.mQuantizeInterpolatorType = Motion.SPLINE_STRING;
}
} else {
c.motion.mQuantizeInterpolatorType = a.getInteger(attr, c.motion.mQuantizeInterpolatorID);
}
break;
case DRAW_PATH:
c.motion.mDrawPath = a.getInt(attr, 0);
break;
case CHAIN_USE_RTL:
Log.e(TAG, "CURRENTLY UNSUPPORTED"); // TODO add support or remove
// TODO add support or remove c.mChainUseRtl = a.getBoolean(attr,c.mChainUseRtl);
break;
case BARRIER_DIRECTION:
c.layout.mBarrierDirection = a.getInt(attr, c.layout.mBarrierDirection);
break;
case BARRIER_MARGIN:
c.layout.mBarrierMargin = a.getDimensionPixelSize(attr, c.layout.mBarrierMargin);
break;
case CONSTRAINT_REFERENCED_IDS:
c.layout.mReferenceIdString = a.getString(attr);
break;
case CONSTRAINT_TAG:
c.layout.mConstraintTag = a.getString(attr);
break;
case BARRIER_ALLOWS_GONE_WIDGETS:
c.layout.mBarrierAllowsGoneWidgets = a.getBoolean(attr, c.layout.mBarrierAllowsGoneWidgets);
break;
case UNUSED:
Log.w(TAG,
"unused attribute 0x" + Integer.toHexString(attr) + " " + mapToConstant.get(attr));
break;
default:
Log.w(TAG,
"Unknown attribute 0x" + Integer.toHexString(attr) + " " + mapToConstant.get(attr));
}
}
if (c.layout.mReferenceIdString != null) {
// in case the strings are set, make sure to clear up the cached ids
c.layout.mReferenceIds = null;
};
}
private int[] convertReferenceString(View view, String referenceIdString) {
String[] split = referenceIdString.split(",");
Context context = view.getContext();
int[] tags = new int[split.length];
int count = 0;
for (int i = 0; i < split.length; i++) {
String idString = split[i];
idString = idString.trim();
int tag = 0;
try {
Class res = R.id.class;
Field field = res.getField(idString);
tag = field.getInt(null);
} catch (Exception e) {
// Do nothing
}
if (tag == 0) {
tag = context.getResources().getIdentifier(idString, "id",
context.getPackageName());
}
if (tag == 0 && view.isInEditMode() && view.getParent() instanceof ConstraintLayout) {
ConstraintLayout constraintLayout = (ConstraintLayout) view.getParent();
Object value = constraintLayout.getDesignInformation(0, idString);
if (value != null && value instanceof Integer) {
tag = (Integer) value;
}
}
tags[count++] = tag;
}
if (count != split.length) {
tags = Arrays.copyOf(tags, count);
}
return tags;
}
/**
* @suppress
*/
public Constraint getConstraint(int id) {
if (mConstraints.containsKey(id)) {
return mConstraints.get(id);
}
return null;
}
/**
* @suppress
*/
public int[] getKnownIds() {
Integer[] arr = mConstraints.keySet().toArray(new Integer[0]);
int[] array = new int[arr.length];
for (int i = 0; i < array.length; i++) {
array[i] = arr[i];
}
return array;
}
/**
* Enforce id are required for all ConstraintLayout children to use ConstraintSet.
* default = true;
*/
public boolean isForceId() {
return mForceId;
}
/**
* Enforce id are required for all ConstraintLayout children to use ConstraintSet.
* default = true;
*
* @param forceId
*/
public void setForceId(boolean forceId) {
this.mForceId = forceId;
}
/**
* If true perform validation checks when parsing ConstraintSets
* This will slow down parsing and should only be used for debugging
*
* @param validate
*/
public void setValidateOnParse(boolean validate) {
mValidate = validate;
}
/**
* Dump the contents
*
* @param scene
* @param ids
*/
public void dump(MotionScene scene, int... ids) {
Set<Integer> keys = mConstraints.keySet();
HashSet<Integer> set;
if (ids.length != 0) {
set = new HashSet<Integer>();
for (int id : ids) {
set.add(id);
}
} else {
set = new HashSet<>(keys);
}
System.out.println(set.size() + " constraints");
StringBuilder stringBuilder = new StringBuilder();
for (Integer id : set.toArray(new Integer[0])) {
Constraint constraint = mConstraints.get(id);
if (constraint == null) {
continue;
}
stringBuilder.append("<Constraint id=");
stringBuilder.append(id);
stringBuilder.append(" \n");
constraint.layout.dump(scene, stringBuilder);
stringBuilder.append("/>\n");
}
System.out.println(stringBuilder.toString());
}
/**
* Construct a user friendly error string
*
* @param context the context
* @param resourceId the xml being parsed
* @param pullParser the XML parser
* @return
*/
static String getLine(Context context, int resourceId, XmlPullParser pullParser) {
return ".(" + Debug.getName(context, resourceId) + ".xml:" + pullParser.getLineNumber() +
") \"" + pullParser.getName() + "\"";
}
static String getDebugName(int v) {
for (Field field : ConstraintSet.class.getDeclaredFields()) {
if (field.getName().contains("_") &&
field.getType() == int.class &&
java.lang.reflect.Modifier.isStatic(field.getModifiers()) &&
java.lang.reflect.Modifier.isFinal(field.getModifiers())) {
int val = 0;
try {
val = field.getInt(null);
if (val == v) {
return field.getName();
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return "UNKNOWN";
}
public void writeState(Writer writer, ConstraintLayout layout, int flags) throws IOException {
writer.write("\n---------------------------------------------\n");
if ((flags & 1) == 1) {
new WriteXmlEngine(writer, layout, flags).writeLayout();
} else {
new WriteJsonEngine(writer, layout, flags).writeLayout();
}
writer.write("\n---------------------------------------------\n");
}
class WriteXmlEngine {
Writer writer;
ConstraintLayout layout;
Context context;
int flags;
int unknownCount = 0;
final String LEFT = "'left'";
final String RIGHT = "'right'";
final String BASELINE = "'baseline'";
final String BOTTOM = "'bottom'";
final String TOP = "'top'";
final String START = "'start'";
final String END = "'end'";
WriteXmlEngine(Writer writer, ConstraintLayout layout, int flags) throws IOException {
this.writer = writer;
this.layout = layout;
this.context = layout.getContext();
this.flags = flags;
}
void writeLayout() throws IOException {
writer.write("\n<ConstraintSet>\n");
for (Integer id : mConstraints.keySet()) {
Constraint c = mConstraints.get(id);
String idName = getName(id);
writer.write(" <Constraint");
writer.write(SPACE + "android:id" + "=\"" + idName + "\"");
Layout l = c.layout;
writeBaseDimension("android:layout_width", l.mWidth, -5); // nodefault
writeBaseDimension("android:layout_height", l.mHeight, -5);// nodefault
writeVariable("app:layout_constraintGuide_begin", l.guideBegin, UNSET);
writeVariable("app:layout_constraintGuide_end", l.guideEnd, UNSET);
writeVariable("app:layout_constraintGuide_percent", l.guidePercent, UNSET);
writeVariable("app:layout_constraintHorizontal_bias", l.horizontalBias, 0.5f);
writeVariable("app:layout_constraintVertical_bias", l.verticalBias, 0.5f);
writeVariable("app:layout_constraintDimensionRatio", l.dimensionRatio, null);
writeXmlConstraint("app:layout_constraintCircle", l.circleConstraint);
writeVariable("app:layout_constraintCircleRadius", l.circleRadius, 0);
writeVariable("app:layout_constraintCircleAngle", l.circleAngle, 0);
writeVariable("android:orientation", l.orientation, UNSET);
writeVariable("app:layout_constraintVertical_weight", l.verticalWeight, UNSET);
writeVariable("app:layout_constraintHorizontal_weight", l.horizontalWeight, UNSET);
writeVariable("app:layout_constraintHorizontal_chainStyle", l.horizontalChainStyle, CHAIN_SPREAD);
writeVariable("app:layout_constraintVertical_chainStyle", l.verticalChainStyle, CHAIN_SPREAD);
writeVariable("app:barrierDirection", l.mBarrierDirection, UNSET);
writeVariable("app:barrierMargin", l.mBarrierMargin, 0);
writeDimension("app:layout_marginLeft", l.leftMargin, 0);
writeDimension("app:layout_goneMarginLeft", l.goneLeftMargin, Layout.UNSET_GONE_MARGIN);
writeDimension("app:layout_marginRight", l.rightMargin, 0);
writeDimension("app:layout_goneMarginRight", l.goneRightMargin, Layout.UNSET_GONE_MARGIN);
writeDimension("app:layout_marginStart", l.startMargin, 0);
writeDimension("app:layout_goneMarginStart", l.goneStartMargin, Layout.UNSET_GONE_MARGIN);
writeDimension("app:layout_marginEnd", l.endMargin, 0);
writeDimension("app:layout_goneMarginEnd", l.goneEndMargin, Layout.UNSET_GONE_MARGIN);
writeDimension("app:layout_marginTop", l.topMargin, 0);
writeDimension("app:layout_goneMarginTop", l.goneTopMargin, Layout.UNSET_GONE_MARGIN);
writeDimension("app:layout_marginBottom", l.bottomMargin, 0);
writeDimension("app:layout_goneMarginBottom", l.goneBottomMargin, Layout.UNSET_GONE_MARGIN);
writeDimension("app:goneBaselineMargin", l.goneBaselineMargin, Layout.UNSET_GONE_MARGIN);
writeDimension("app:baselineMargin", l.baselineMargin, 0);
writeBoolen("app:layout_constrainedWidth", l.constrainedWidth, false);
writeBoolen("app:layout_constrainedHeight", l.constrainedHeight, false);
writeBoolen("app:barrierAllowsGoneWidgets", l.mBarrierAllowsGoneWidgets, true);
writeVariable("app:layout_wrapBehaviorInParent", l.mWrapBehavior, ConstraintWidget.WRAP_BEHAVIOR_INCLUDED);
writeXmlConstraint("app:baselineToBaseline", l.baselineToBaseline);
writeXmlConstraint("app:baselineToBottom", l.baselineToBottom);
writeXmlConstraint("app:baselineToTop", l.baselineToTop);
writeXmlConstraint("app:layout_constraintBottom_toBottomOf", l.bottomToBottom);
writeXmlConstraint("app:layout_constraintBottom_toTopOf", l.bottomToTop);
writeXmlConstraint("app:layout_constraintEnd_toEndOf", l.endToEnd);
writeXmlConstraint("app:layout_constraintEnd_toStartOf", l.endToStart);
writeXmlConstraint("app:layout_constraintLeft_toLeftOf", l.leftToLeft);
writeXmlConstraint("app:layout_constraintLeft_toRightOf", l.leftToRight);
writeXmlConstraint("app:layout_constraintRight_toLeftOf", l.rightToLeft);
writeXmlConstraint("app:layout_constraintRight_toRightOf", l.rightToRight);
writeXmlConstraint("app:layout_constraintStart_toEndOf", l.startToEnd);
writeXmlConstraint("app:layout_constraintStart_toStartOf", l.startToStart);
writeXmlConstraint("app:layout_constraintTop_toBottomOf", l.topToBottom);
writeXmlConstraint("app:layout_constraintTop_toTopOf", l.topToTop);
String[] typesConstraintDefault = {"spread", "wrap", "percent"};
writeEnum("app:layout_constraintHeight_default", l.heightDefault, typesConstraintDefault, ConstraintWidget.MATCH_CONSTRAINT_SPREAD);
writeVariable("app:layout_constraintHeight_percent", l.heightPercent, 1);
writeDimension("app:layout_constraintHeight_min", l.heightMin, 0);
writeDimension("app:layout_constraintHeight_max", l.heightMax, 0);
writeBoolen("android:layout_constrainedHeight", l.constrainedHeight, false);
writeEnum("app:layout_constraintWidth_default", l.widthDefault, typesConstraintDefault, ConstraintWidget.MATCH_CONSTRAINT_SPREAD);
writeVariable("app:layout_constraintWidth_percent", l.widthPercent, 1);
writeDimension("app:layout_constraintWidth_min", l.widthMin, 0);
writeDimension("app:layout_constraintWidth_max", l.widthMax, 0);
writeBoolen("android:layout_constrainedWidth", l.constrainedWidth, false);
writeVariable("app:layout_constraintVertical_weight", l.verticalWeight, UNSET);
writeVariable("app:layout_constraintHorizontal_weight", l.horizontalWeight, UNSET);
writeVariable("app:layout_constraintHorizontal_chainStyle", l.horizontalChainStyle);
writeVariable("app:layout_constraintVertical_chainStyle", l.verticalChainStyle);
String[] barrierDir = {"left", "right", "top", "bottom", "start", "end"};
writeEnum("app:barrierDirection", l.mBarrierDirection, barrierDir, UNSET);
writeVariable("app:layout_constraintTag", l.mConstraintTag, null);
if (l.mReferenceIds != null) {
writeVariable("'ReferenceIds'", l.mReferenceIds);
}
writer.write(" />\n");
}
writer.write("</ConstraintSet>\n");
}
private static final String SPACE = "\n ";
private void writeBoolen(String dimString, boolean val, boolean def) throws IOException {
if (val != def)
writer.write(SPACE + dimString + "=\"" + val + "dp\"");
}
private void writeEnum(String dimString, int val, String[] types, int def) throws IOException {
if (val != def)
writer.write(SPACE + dimString + "=\"" + types[val] + "\"");
}
private void writeDimension(String dimString, int dim, int def) throws IOException {
if (dim != def)
writer.write(SPACE + dimString + "=\"" + dim + "dp\"");
}
private void writeBaseDimension(String dimString, int dim, int def) throws IOException {
if (dim != def) {
if (dim == -2) {
writer.write(SPACE + dimString + "=\"wrap_content\"");
} else if (dim == -1) {
writer.write(SPACE + dimString + "=\"match_parent\"");
} else {
writer.write(SPACE + dimString + "=\"" + dim + "dp\"");
}
}
}
HashMap<Integer, String> idMap = new HashMap<>();
String getName(int id) {
if (idMap.containsKey(id)) {
return "@+id/" + idMap.get(id) + "";
}
if (id == 0) {
return "parent";
}
String name = lookup(id);
idMap.put(id, name);
return "@+id/" + name + "";
}
String lookup(int id) {
try {
if (id != -1) {
return context.getResources().getResourceEntryName(id);
} else {
return "unknown" + (++unknownCount);
}
} catch (Exception ex) {
return "unknown" + (++unknownCount);
}
}
void writeXmlConstraint(String str, int leftToLeft) throws IOException {
if (leftToLeft == UNSET) {
return;
}
writer.write(SPACE + str);
writer.write("=\"" + getName(leftToLeft) + "\"");
}
void writeConstraint(String my, int leftToLeft, String other, int margin, int goneMargin) throws IOException {
if (leftToLeft == UNSET) {
return;
}
writer.write(SPACE + my);
writer.write(":[");
writer.write(getName(leftToLeft));
writer.write(" , ");
writer.write(other);
if (margin != 0) {
writer.write(" , " + margin);
}
writer.write("],\n");
}
void writeCircle(int circleConstraint, float circleAngle, int circleRadius) throws IOException {
if (circleConstraint == UNSET) {
return;
}
writer.write("circle");
writer.write(":[");
writer.write(getName(circleConstraint));
writer.write(", " + circleAngle);
writer.write(circleRadius + "]");
}
void writeVariable(String name, int value) throws IOException {
if (value == 0 || value == -1) {
return;
}
writer.write(SPACE + name + "=\"" + value + "\"\n");
}
void writeVariable(String name, float value, float def) throws IOException {
if (value == def) {
return;
}
writer.write(SPACE + name);
writer.write("=\"" + value + "\"");
}
void writeVariable(String name, String value, String def) throws IOException {
if (value == null || value.equals(def)) {
return;
}
writer.write(SPACE + name);
writer.write("=\"" + value + "\"");
}
void writeVariable(String name, int[] value) throws IOException {
if (value == null) {
return;
}
writer.write(SPACE + name);
writer.write(":");
for (int i = 0; i < value.length; i++) {
writer.write(((i == 0) ? "[" : ", ") + getName(value[i]));
}
writer.write("],\n");
}
void writeVariable(String name, String value) throws IOException {
if (value == null) {
return;
}
writer.write(name);
writer.write(":");
writer.write(", " + value);
writer.write("\n");
}
}
// ================================== JSON ===============================================
class WriteJsonEngine {
Writer writer;
ConstraintLayout layout;
Context context;
int flags;
int unknownCount = 0;
final String LEFT = "'left'";
final String RIGHT = "'right'";
final String BASELINE = "'baseline'";
final String BOTTOM = "'bottom'";
final String TOP = "'top'";
final String START = "'start'";
final String END = "'end'";
private static final String SPACE = " ";
WriteJsonEngine(Writer writer, ConstraintLayout layout, int flags) throws IOException {
this.writer = writer;
this.layout = layout;
this.context = layout.getContext();
this.flags = flags;
}
void writeLayout() throws IOException {
writer.write("\n\'ConstraintSet\':{\n");
for (Integer id : mConstraints.keySet()) {
Constraint c = mConstraints.get(id);
String idName = getName(id);
writer.write(idName + ":{\n");
Layout l = c.layout;
writeDimension("height", l.mHeight, l.heightDefault, l.heightPercent, l.heightMin, l.heightMax, l.constrainedHeight);
writeDimension("width", l.mWidth, l.widthDefault, l.widthPercent, l.widthMin, l.widthMax, l.constrainedWidth);
writeConstraint(LEFT, l.leftToLeft, LEFT, l.leftMargin, l.goneLeftMargin);
writeConstraint(LEFT, l.leftToRight, RIGHT, l.leftMargin, l.goneLeftMargin);
writeConstraint(RIGHT, l.rightToLeft, LEFT, l.rightMargin, l.goneRightMargin);
writeConstraint(RIGHT, l.rightToRight, RIGHT, l.rightMargin, l.goneRightMargin);
writeConstraint(BASELINE, l.baselineToBaseline, BASELINE, UNSET, l.goneBaselineMargin);
writeConstraint(BASELINE, l.baselineToTop, TOP, UNSET, l.goneBaselineMargin);
writeConstraint(BASELINE, l.baselineToBottom, BOTTOM, UNSET, l.goneBaselineMargin);
writeConstraint(TOP, l.topToBottom, BOTTOM, l.topMargin, l.goneTopMargin);
writeConstraint(TOP, l.topToTop, TOP, l.topMargin, l.goneTopMargin);
writeConstraint(BOTTOM, l.bottomToBottom, BOTTOM, l.bottomMargin, l.goneBottomMargin);
writeConstraint(BOTTOM, l.bottomToTop, TOP, l.bottomMargin, l.goneBottomMargin);
writeConstraint(START, l.startToStart, START, l.startMargin, l.goneStartMargin);
writeConstraint(START, l.startToEnd, END, l.startMargin, l.goneStartMargin);
writeConstraint(END, l.endToStart, START, l.endMargin, l.goneEndMargin);
writeConstraint(END, l.endToEnd, END, l.endMargin, l.goneEndMargin);
writeVariable("'horizontalBias'", l.horizontalBias, 0.5f);
writeVariable("'verticalBias'", l.verticalBias, 0.5f);
writeCircle(l.circleConstraint, l.circleAngle, l.circleRadius);
writeGuideline(l.orientation, l.guideBegin, l.guideEnd, l.guidePercent);
writeVariable("'dimensionRatio'", l.dimensionRatio);
writeVariable("'barrierMargin'", l.mBarrierMargin);
writeVariable("'type'", l.mHelperType);
writeVariable("'ReferenceId'", l.mReferenceIdString);
writeVariable("'mBarrierAllowsGoneWidgets'", l.mBarrierAllowsGoneWidgets ,true );
writeVariable("'WrapBehavior'", l.mWrapBehavior);
writeVariable("'verticalWeight'", l.verticalWeight);
writeVariable("'horizontalWeight'", l.horizontalWeight);
writeVariable("'horizontalChainStyle'", l.horizontalChainStyle);
writeVariable("'verticalChainStyle'", l.verticalChainStyle);
writeVariable("'barrierDirection'", l.mBarrierDirection);
if (l.mReferenceIds != null) {
writeVariable("'ReferenceIds'", l.mReferenceIds);
}
writer.write("}\n");
}
writer.write("}\n");
}
private void writeGuideline(int orientation, int guideBegin, int guideEnd, float guidePercent) {
}
private void writeDimension(String dimString, int dim, int dimDefault, float dimPercent, int dimMin, int dimMax, boolean constrainedDim) throws IOException {
if ( dim == 0 ) {
if (dimMax != UNSET || dimMin != UNSET) {
switch (dimDefault) {
case 0: // spread
writer.write(SPACE + dimString + ": {'spread' ," +dimMin +", "+dimMax+"}\n");
break;
case 1: // wrap
writer.write(SPACE + dimString + ": {'wrap' ," +dimMin +", "+dimMax+"}\n");
return;
case 2: // percent
writer.write(SPACE + dimString + ": {'"+dimPercent+"'% ," +dimMin +", "+dimMax+"}\n");
return;
}
return;
}
switch (dimDefault) {
case 0: // spread is the default
break;
case 1: // wrap
writer.write(SPACE + dimString + ": '???????????',\n");
return;
case 2: // percent
writer.write(SPACE + dimString + ": '"+dimPercent+"%',\n");
return;
}
} else if ( dim == -2 ) {
writer.write(SPACE + dimString + ": 'wrap'\n");
} else if ( dim == -1 ) {
writer.write(SPACE + dimString + ": 'parent'\n");
} else {
writer.write(SPACE + dimString + ": "+dim+",\n");
}
}
HashMap<Integer, String> idMap = new HashMap<>();
String getName(int id) {
if (idMap.containsKey(id)) {
return "\'" + idMap.get(id) + "\'";
}
if (id == 0) {
return "'parent'";
}
String name = lookup(id);
idMap.put(id, name);
return "\'" + name + "\'";
}
String lookup(int id) {
try {
if (id != -1) {
return context.getResources().getResourceEntryName(id);
} else {
return "unknown" + (++unknownCount);
}
} catch (Exception ex) {
return "unknown" + (++unknownCount);
}
}
void writeConstraint(String my, int leftToLeft, String other, int margin, int goneMargin) throws IOException {
if (leftToLeft == UNSET) {
return;
}
writer.write(SPACE + my);
writer.write(":[");
writer.write(getName(leftToLeft));
writer.write(" , ");
writer.write(other);
if (margin != 0) {
writer.write(" , " + margin);
}
writer.write("],\n");
}
void writeCircle(int circleConstraint, float circleAngle, int circleRadius) throws IOException {
if (circleConstraint == UNSET) {
return;
}
writer.write(SPACE + "circle");
writer.write(":[");
writer.write(getName(circleConstraint));
writer.write(", " + circleAngle);
writer.write(circleRadius + "]");
}
void writeVariable(String name, int value) throws IOException {
if (value == 0 || value == -1) {
return;
}
writer.write(SPACE + name);
writer.write(":");
writer.write(", " + value);
writer.write("\n");
}
void writeVariable(String name, float value) throws IOException {
if (value == UNSET) {
return;
}
writer.write(SPACE + name);
writer.write(": " + value);
writer.write(",\n");
}
void writeVariable(String name, float value, float def) throws IOException {
if (value == def) {
return;
}
writer.write(SPACE + name);
writer.write(": " + value);
writer.write(",\n");
}
void writeVariable(String name, boolean value) throws IOException {
if (value == false) {
return;
}
writer.write(SPACE + name);
writer.write(": " + value);
writer.write(",\n");
}
void writeVariable(String name, boolean value , boolean def) throws IOException {
if (value == def) {
return;
}
writer.write(SPACE + name);
writer.write(": " + value);
writer.write(",\n");
}
void writeVariable(String name, int[] value) throws IOException {
if (value == null) {
return;
}
writer.write(SPACE + name);
writer.write(": ");
for (int i = 0; i < value.length; i++) {
writer.write(((i == 0) ? "[" : ", ") + getName(value[i]));
}
writer.write("],\n");
}
void writeVariable(String name, String value) throws IOException {
if (value == null) {
return;
}
writer.write(SPACE + name);
writer.write(":");
writer.write(", " + value);
writer.write("\n");
}
}
}
|
92395d8d8619f287f63d5d445ca9833327c0e9f2 | 1,034 | java | Java | Fundamentals-2.0/JavaFundamentals/ExamProblems/ExamPractice/src/org/softuni/RageQuit.java | sholev/SoftUni | 0d5f4b26fa20e5442b91a515f775e80ae6994834 | [
"MIT"
] | 1 | 2019-01-22T21:16:45.000Z | 2019-01-22T21:16:45.000Z | Fundamentals-2.0/JavaFundamentals/ExamProblems/ExamPractice/src/org/softuni/RageQuit.java | sholev/SoftUni | 0d5f4b26fa20e5442b91a515f775e80ae6994834 | [
"MIT"
] | null | null | null | Fundamentals-2.0/JavaFundamentals/ExamProblems/ExamPractice/src/org/softuni/RageQuit.java | sholev/SoftUni | 0d5f4b26fa20e5442b91a515f775e80ae6994834 | [
"MIT"
] | null | null | null | 29.542857 | 75 | 0.598646 | 998,799 | package org.softuni;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// Advanced C# Exam 19 July 2015
public class RageQuit {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input = in.nextLine().toUpperCase();
Matcher rageBuddy = Pattern.compile("(\\D+)(\\d+)").matcher(input);
StringBuilder result = new StringBuilder();
while (rageBuddy.find()) {
String forRepeat = rageBuddy.group(1);
int repetitions = Integer.parseInt(rageBuddy.group(2));
for (int i = 0; i < repetitions; i++) {
result.append(forRepeat);
}
}
Set<Character> counter = new HashSet<>();
for (char c : result.toString().toCharArray()) {
counter.add(c);
}
System.out.println("Unique symbols used: " + counter.size());
System.out.println(result.toString());
}
}
|
92395f069e797589f7ac53f2af7137d4d964f1bb | 3,589 | java | Java | src/main/java/com/hotels/mutantswarm/model/MutantSwarmScript.java | HotelsDotCom/mutant-swarm | ebd72f667a07d72a588b2e5a31b32ab80b288f32 | [
"Apache-2.0"
] | 23 | 2019-02-27T15:24:57.000Z | 2020-12-20T21:56:33.000Z | src/main/java/com/hotels/mutantswarm/model/MutantSwarmScript.java | HiveRunner/mutant-swarm | ebd72f667a07d72a588b2e5a31b32ab80b288f32 | [
"Apache-2.0"
] | 10 | 2019-03-13T15:49:19.000Z | 2021-02-01T16:59:01.000Z | src/main/java/com/hotels/mutantswarm/model/MutantSwarmScript.java | HiveRunner/mutant-swarm | ebd72f667a07d72a588b2e5a31b32ab80b288f32 | [
"Apache-2.0"
] | 6 | 2019-03-22T10:13:06.000Z | 2020-09-28T12:39:16.000Z | 26.389706 | 129 | 0.623015 | 998,800 | /*
* Copyright (C) 2018-2021 Expedia, Inc.
* Copyright (C) 2021 The HiveRunner Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hotels.mutantswarm.model;
import static java.util.Collections.unmodifiableList;
import java.nio.file.Path;
import java.util.List;
import com.klarna.hiverunner.builder.Script;
/**
* A script file under test; a collection of statements. Using an interface so can easily decorate in exec package.
*/
public interface MutantSwarmScript extends Script {
/**
* Script file name.
*/
String getFileName();
/**
* The statements which make up the script.
*/
List<MutantSwarmStatement> getStatements();
/**
* Concrete implementation.
*/
static public class Impl implements MutantSwarmScript {
private final int index;
private final String name;
private final List<MutantSwarmStatement> statements;
private Path path;
public Impl(int index, Path path, List<MutantSwarmStatement> statements) {
this.index = index;
this.path = path;
this.name = path.getFileName().toString();
this.statements = unmodifiableList(statements);
}
@Override
public int getIndex() {
return index;
}
@Override
public String getFileName() {
return name;
}
@Override
public List<MutantSwarmStatement> getStatements() {
return statements;
}
@Override
public String getSql(){
String sql = "";
for (MutantSwarmStatement statement : statements) {
sql += statement.getSql() + ";\n";
}
return sql;
}
@Override
public Path getPath() {
return path;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + index;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((path == null) ? 0 : path.hashCode());
result = prime * result + ((statements == null) ? 0 : statements.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;
MutantSwarmScript.Impl other = (MutantSwarmScript.Impl) obj;
if (index != other.index)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (path == null) {
if (other.path != null)
return false;
} else if (!path.equals(other.path))
return false;
if (statements == null) {
if (other.statements != null)
return false;
} else if (!statements.equals(other.statements))
return false;
return true;
}
@Override
public String toString() {
return "MutantSwarmScript.Impl [index=" + index + ", name=" + name + ", statements=" + statements + ", path=" + path + "]";
}
}
}
|
92395f3ea6c27848109db4976cc9ab6121f2db9a | 649 | java | Java | src/main/java/otmui/utils/Arrow.java | ggomes/otm-ui | 42b92c282cd6c37ea23b925030fa8ea2e319181f | [
"BSD-3-Clause"
] | null | null | null | src/main/java/otmui/utils/Arrow.java | ggomes/otm-ui | 42b92c282cd6c37ea23b925030fa8ea2e319181f | [
"BSD-3-Clause"
] | null | null | null | src/main/java/otmui/utils/Arrow.java | ggomes/otm-ui | 42b92c282cd6c37ea23b925030fa8ea2e319181f | [
"BSD-3-Clause"
] | null | null | null | 34.157895 | 78 | 0.653313 | 998,801 | package otmui.utils;
public class Arrow implements Comparable<Arrow>{
public double position; // distance along the midline
public Vector start; // coordinates of the point
public Vector direction; // lateral/outward direction
public double distance_to_next; // position of next - position of this
public Arrow(double position,Vector start,Vector direction){
this.position = position;
this.start = start;
this.direction = direction;
}
@Override
public int compareTo(Arrow that) {
return Double.compare(this.position,that.position);
}
}
|
9239601b5e60ef0ea6e2dd09a3c4ea34e10dddb7 | 1,124 | java | Java | examples/praphic_test_01/build-tmp/source/praphic_test_01.java | videoalchemy/portal-control | 81550b16364dcf17f68d9f48585afb5c1b4b513a | [
"MIT"
] | null | null | null | examples/praphic_test_01/build-tmp/source/praphic_test_01.java | videoalchemy/portal-control | 81550b16364dcf17f68d9f48585afb5c1b4b513a | [
"MIT"
] | null | null | null | examples/praphic_test_01/build-tmp/source/praphic_test_01.java | videoalchemy/portal-control | 81550b16364dcf17f68d9f48585afb5c1b4b513a | [
"MIT"
] | null | null | null | 20.436364 | 68 | 0.708185 | 998,802 | import processing.core.*;
import processing.data.*;
import processing.event.*;
import processing.opengl.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.File;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class praphic_test_01 extends PApplet {
/* jstephens - pgraphics practice - 2015-03
Create two pgraphics layers and draw them into the processing screen
*/
PGraphics top;
PGraphics bottom;
public void setup() {
size(640, 480);
top = createGraphics(width, height);
bottom = createGraphics(width, height);
}
public void draw(){
top.beginDraw();
top.fill(255,0,0,150);
//top.translate(width/2, height/2);
top.translate(mouseX,mouseY);
top.ellipse(0, 0, 100, 100);
top.endDraw();
image(top,0, 0,width, height);
}
static public void main(String[] passedArgs) {
String[] appletArgs = new String[] { "praphic_test_01" };
if (passedArgs != null) {
PApplet.main(concat(appletArgs, passedArgs));
} else {
PApplet.main(appletArgs);
}
}
}
|
923961188b35b8fd38dfbb53343e5573404f951d | 2,025 | java | Java | java/timebase/server/src/main/java/com/epam/deltix/qsrv/hf/tickdb/impl/HierarchicalTypeFilter.java | mcleo-d/TimeBase-CE | ecbe6fd28161c19bbafee6fd90b728655f34956e | [
"Apache-2.0"
] | 23 | 2021-08-19T12:26:37.000Z | 2022-03-22T14:58:54.000Z | java/timebase/server/src/main/java/com/epam/deltix/qsrv/hf/tickdb/impl/HierarchicalTypeFilter.java | mcleo-d/TimeBase-CE | ecbe6fd28161c19bbafee6fd90b728655f34956e | [
"Apache-2.0"
] | 173 | 2021-05-13T11:04:42.000Z | 2021-07-07T13:25:15.000Z | java/timebase/server/src/main/java/com/epam/deltix/qsrv/hf/tickdb/impl/HierarchicalTypeFilter.java | mcleo-d/TimeBase-CE | ecbe6fd28161c19bbafee6fd90b728655f34956e | [
"Apache-2.0"
] | 5 | 2021-07-14T19:08:50.000Z | 2022-03-18T13:48:06.000Z | 30.681818 | 80 | 0.634568 | 998,803 | /*
* Copyright 2021 EPAM Systems, Inc
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.epam.deltix.qsrv.hf.tickdb.impl;
import com.epam.deltix.qsrv.hf.tickdb.pub.query.*;
import java.util.*;
/**
* Common utility for filtering types. Requires external synchronization.
*/
public class HierarchicalTypeFilter implements TypeSubscriptionController {
private Set <String> allowedNames = null;
private BitSet allowedTypes = null;
public boolean accept (StreamMessageSource info) {
throw new RuntimeException ();
}
public void addTypes (String... names) {
if (allowedNames == null)
allowedNames = new HashSet <String> ();
for (String s : names) {
allowedNames.add (s);
}
}
@Override
public void setTypes(String... names) {
if (allowedNames == null)
allowedNames = new HashSet <String> ();
else
allowedNames.clear();
allowedNames.addAll(Arrays.asList(names));
}
public void removeTypes (String... names) {
if (allowedNames == null)
allowedNames = new HashSet <String> ();
else {
for (String s : names) {
allowedNames.remove (s);
}
}
}
public void subscribeToAllTypes () {
allowedNames = null;
}
}
|
923961c7785cabf2c8f7dac950dd3d4dc3a8f00a | 4,241 | java | Java | app/src/main/java/nl/lxtreme/binutils/hex/AbstractReader.java | ron-a20/Android-Disassembler | c0d0520126bf95ad0fe54e0ce69ef88d2484cf45 | [
"MIT"
] | 395 | 2018-10-01T00:59:17.000Z | 2022-03-28T04:34:37.000Z | app/src/main/java/nl/lxtreme/binutils/hex/AbstractReader.java | ron-a20/Android-Disassembler | c0d0520126bf95ad0fe54e0ce69ef88d2484cf45 | [
"MIT"
] | 460 | 2018-09-30T14:59:13.000Z | 2022-03-30T21:34:39.000Z | app/src/main/java/nl/lxtreme/binutils/hex/AbstractReader.java | ron-a20/Android-Disassembler | c0d0520126bf95ad0fe54e0ce69ef88d2484cf45 | [
"MIT"
] | 75 | 2018-10-24T22:15:41.000Z | 2022-03-28T04:49:13.000Z | 27.934211 | 115 | 0.598446 | 998,804 | /*
* BinUtils - access various binary formats from Java
*
* (C) Copyright 2017 - JaWi - nnheo@example.com
*
* Licensed under Apache License v2.
*/
package nl.lxtreme.binutils.hex;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.ByteOrder;
import nl.lxtreme.binutils.hex.util.ByteOrderUtils;
/**
* Base implementation for interpreting hex-based data files.
*/
public abstract class AbstractReader {
// VARIABLES
protected final Reader reader;
// CONSTRUCTORS
/**
* Creates a new AbstractReader instance.
*/
public AbstractReader(Reader aReader) {
this.reader = (aReader instanceof BufferedReader) ? (BufferedReader) aReader : new BufferedReader(aReader);
}
// METHODS
/**
* Closes this instruction stream.
*
* @throws IOException in case of stream I/O problems.
*/
public void close() throws IOException {
this.reader.close();
}
/**
* @return the current address location, or <tt>-1</tt> if no address is
* known.
* @throws IOException in case of I/O problems.
*/
public abstract long getAddress() throws IOException;
/**
* Reads a single byte from the underlying stream.
*
* @return the next byte, can be <code>-1</code> in case an end-of-stream was
* encountered.
* @throws IOException in case of stream I/O problems;
*/
public abstract int readByte() throws IOException;
/**
* Reads a long word (4 bytes) from the underlying stream.
*
* @return the next long word, can be <code>-1</code> in case an end-of-stream
* was encountered.
* @throws IOException in case of stream I/O problems;
*/
public int readLongWord() throws IOException {
final byte[] data = readBytes(4);
if (data == null) {
return -1;
}
return (int) ByteOrderUtils.decode(getByteOrder(), data);
}
/**
* Reads a word (2 bytes) from the underlying stream.
*
* @return the next word, can be <code>-1</code> in case an end-of-stream was
* encountered.
* @throws IOException in case of stream I/O problems;
*/
public int readWord() throws IOException {
final byte[] data = readBytes(2);
if (data == null) {
return -1;
}
return (int) ByteOrderUtils.decode(ByteOrder.LITTLE_ENDIAN, data);
}
/**
* Returns the byte order in which this data provider reads its data.
*
* @return a byte order, never <code>null</code>.
*/
protected abstract ByteOrder getByteOrder();
/**
* Convenience method to read a number of bytes.
*
* @param aCount the number of bytes to read, should be > 0.
* @return a byte array with the read bytes, can be <code>null</code> in case
* an EOF was found.
* @throws IOException in case of I/O problems;
* @throws IllegalArgumentException in case the given count was <= 0.
*/
protected final byte[] readBytes(final int aCount) throws IOException, IllegalArgumentException {
if (aCount <= 0) {
throw new IllegalArgumentException("Count cannot be less or equal to zero!");
}
final byte[] result = new byte[aCount];
for (int i = 0; i < aCount; i++) {
int readByte = readByte();
if (readByte == -1) {
return null;
}
result[i] = (byte) readByte;
}
return result;
}
protected final char[] readChars(final int aCount) throws IOException, IllegalArgumentException {
if (aCount <= 0) {
throw new IllegalArgumentException("Invalid count!");
}
final char[] buf = new char[aCount];
if (this.reader.read(buf) != aCount) {
throw new IOException("Unexpected end of stream!");
}
return buf;
}
/**
* Skips until the end-of-line is found.
*/
protected final int readSingleByte() throws IOException {
int ch;
do {
ch = this.reader.read();
}
while ((ch != -1) && Character.isWhitespace(ch));
return ch;
}
}
|
9239620944f2d38757e858d648a853d28cefd8e1 | 651 | java | Java | src/S1388PizzaWith3nSlices.java | camelcc/leetcode | 0ba37f7fd47ed3e893525988ce803ce805001ba7 | [
"CECILL-B"
] | 4 | 2021-11-30T20:28:14.000Z | 2022-01-04T04:01:32.000Z | src/S1388PizzaWith3nSlices.java | camelcc/leetcode | 0ba37f7fd47ed3e893525988ce803ce805001ba7 | [
"CECILL-B"
] | null | null | null | src/S1388PizzaWith3nSlices.java | camelcc/leetcode | 0ba37f7fd47ed3e893525988ce803ce805001ba7 | [
"CECILL-B"
] | 1 | 2021-11-30T23:33:51.000Z | 2021-11-30T23:33:51.000Z | 32.55 | 80 | 0.442396 | 998,805 | public class S1388PizzaWith3nSlices {
public int maxSizeSlices(int[] slices) {
int M = slices.length;
int N = M/3;
return Math.max(findMax(slices, 0, M-2, N), findMax(slices, 1, M-1, N));
}
private int findMax(int[] slices, int lo, int hi, int N) {
int[][] dp = new int[hi-lo+1][N+1];
for (int i = 0; i <= hi-lo; i++) {
for (int k = 1; k <= N; k++) {
int pick = (i >= 2) ? dp[i-2][k-1] : 0;
int skip = (i >= 1) ? dp[i-1][k] : 0;
dp[i][k] = Math.max(skip, pick + slices[i+lo]);
}
}
return dp[hi-lo][N];
}
}
|
923962a6462571eba712d0baf5003ceaf3bece39 | 960 | java | Java | Mage.Sets/src/mage/cards/f/FieldOfDreams.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,444 | 2015-01-02T00:25:38.000Z | 2022-03-31T13:57:18.000Z | Mage.Sets/src/mage/cards/f/FieldOfDreams.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 6,180 | 2015-01-02T19:10:09.000Z | 2022-03-31T21:10:44.000Z | Mage.Sets/src/mage/cards/f/FieldOfDreams.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,001 | 2015-01-01T01:15:20.000Z | 2022-03-30T20:23:04.000Z | 26.666667 | 111 | 0.7375 | 998,806 |
package mage.cards.f;
import java.util.UUID;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.effects.common.continuous.PlayWithTheTopCardRevealedEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SuperType;
import mage.constants.Zone;
/**
*
* @author LoneFox
*/
public final class FieldOfDreams extends CardImpl {
public FieldOfDreams(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT},"{U}");
addSuperType(SuperType.WORLD);
// Players play with the top card of their libraries revealed.
this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new PlayWithTheTopCardRevealedEffect(true)));
}
private FieldOfDreams(final FieldOfDreams card) {
super(card);
}
@Override
public FieldOfDreams copy() {
return new FieldOfDreams(this);
}
}
|
923963c3ba0cc2a7b359d8ae67855b56419f70d2 | 978 | java | Java | src/Controller/ClienteController.java | TallesVictor/Loja | 30113ff6342d9e024e3b6ecf8393ba5743f0262e | [
"Apache-2.0"
] | null | null | null | src/Controller/ClienteController.java | TallesVictor/Loja | 30113ff6342d9e024e3b6ecf8393ba5743f0262e | [
"Apache-2.0"
] | null | null | null | src/Controller/ClienteController.java | TallesVictor/Loja | 30113ff6342d9e024e3b6ecf8393ba5743f0262e | [
"Apache-2.0"
] | null | null | null | 22.744186 | 80 | 0.601227 | 998,807 | /*
* 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 Controller;
import Model.Cliente;
import Model.ClienteDao;
import java.util.ArrayList;
/**
*
* @author Dcxz
*/
public class ClienteController {
ClienteDao dao;
public ArrayList<Cliente> buscarTodos() {
dao = new ClienteDao();
return dao.buscarTodos();
}
public boolean Cadastrar(Cliente f) {
dao = new ClienteDao();
return dao.cadastrar(f);
}
public Cliente buscaID(int id) {
dao = new ClienteDao();
return dao.buscarporid(id);
}
public void atualizarCliente(Cliente f) {
dao = new ClienteDao();
dao.atualizar(f);
}
public void excluirCliente(Integer id) {
dao = new ClienteDao();
dao.excluir(id);
}
}
|
92396452002573feaf44e1dca046f1dee013140d | 3,336 | java | Java | src/test/java/seedu/foodlog/logic/commands/RangeCommandTest.java | yhtMinceraft1010X/FoodLog3.5 | e4542c5a411aa3dca1fa31f4fe9b1ef9f1be2a07 | [
"MIT"
] | null | null | null | src/test/java/seedu/foodlog/logic/commands/RangeCommandTest.java | yhtMinceraft1010X/FoodLog3.5 | e4542c5a411aa3dca1fa31f4fe9b1ef9f1be2a07 | [
"MIT"
] | 5 | 2021-06-11T04:59:45.000Z | 2021-12-27T22:09:54.000Z | src/test/java/seedu/foodlog/logic/commands/RangeCommandTest.java | yhtMinceraft1010X/FoodLog3.5 | e4542c5a411aa3dca1fa31f4fe9b1ef9f1be2a07 | [
"MIT"
] | null | null | null | 40.192771 | 97 | 0.752698 | 998,808 | package seedu.foodlog.logic.commands;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.foodlog.commons.core.Messages.MESSAGE_FOOD_ENTRIES_LISTED_OVERVIEW;
import static seedu.foodlog.logic.commands.CommandTestUtil.assertCommandSuccess;
import static seedu.foodlog.testutil.TypicalFoodEntries.getEditedDateTimesModel;
import static seedu.foodlog.testutil.TypicalFoodEntries.getTypicalFoodLog;
import java.util.Collections;
import org.junit.jupiter.api.Test;
import seedu.foodlog.model.Model;
import seedu.foodlog.model.ModelManager;
import seedu.foodlog.model.UserPrefs;
import seedu.foodlog.model.foodentry.DateRangePredicate;
/**
* Contains integration tests (interaction with the Model) for {@code RangeCommand}.
*/
public class RangeCommandTest {
private Model model = new ModelManager(getTypicalFoodLog(), new UserPrefs());
private Model expectedModel = new ModelManager(getTypicalFoodLog(), new UserPrefs());
@Test
public void equals() {
DateRangePredicate firstPredicate =
new DateRangePredicate(1);
DateRangePredicate secondPredicate =
new DateRangePredicate(2);
RangeCommand rangeFirstCommand = new RangeCommand(firstPredicate);
RangeCommand rangeSecondCommand = new RangeCommand(secondPredicate);
// same object -> returns true
assertTrue(rangeFirstCommand.equals(rangeFirstCommand));
// same values -> returns true
RangeCommand rangeFirstCommandCopy = new RangeCommand(firstPredicate);
assertTrue(rangeFirstCommand.equals(rangeFirstCommandCopy));
// different types -> returns false
assertFalse(rangeFirstCommand.equals(1));
// null -> returns false
assertFalse(rangeFirstCommand.equals(null));
// different foodEntry -> returns false
assertFalse(rangeFirstCommand.equals(rangeSecondCommand));
}
@Test
public void execute_beyondRange_noFoodEntryFound() {
model = getEditedDateTimesModel(model, 2);
expectedModel = getEditedDateTimesModel(expectedModel, 2);
String expectedMessage = String.format(MESSAGE_FOOD_ENTRIES_LISTED_OVERVIEW, 0);
DateRangePredicate predicate = new DateRangePredicate(1);
RangeCommand command = new RangeCommand(predicate);
expectedModel.updateFilteredFoodEntryList(predicate);
assertCommandSuccess(command, model, expectedMessage, expectedModel);
assertEquals(Collections.emptyList(), model.getFilteredFoodEntryList());
}
@Test
public void execute_multipleKeywords_multipleFoodEntriesFound() {
model = getEditedDateTimesModel(model, 0);
expectedModel = getEditedDateTimesModel(expectedModel, 0);
String expectedMessage = String.format(MESSAGE_FOOD_ENTRIES_LISTED_OVERVIEW, 2);
DateRangePredicate predicate = new DateRangePredicate(2);
RangeCommand command = new RangeCommand(predicate);
expectedModel.updateFilteredFoodEntryList(predicate);
assertCommandSuccess(command, model, expectedMessage, expectedModel);
assertEquals(expectedModel.getFilteredFoodEntryList(), model.getFilteredFoodEntryList());
}
}
|
92396581e74cb19732143b72c195dac595b43731 | 1,573 | java | Java | app/src/main/java/com/yurkiv/unote/adapter/HashtagAdapter.java | yurkiv/MaterialNotes | 73454084c12e0d75cf4de84bd066ed95d03dba08 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/yurkiv/unote/adapter/HashtagAdapter.java | yurkiv/MaterialNotes | 73454084c12e0d75cf4de84bd066ed95d03dba08 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/yurkiv/unote/adapter/HashtagAdapter.java | yurkiv/MaterialNotes | 73454084c12e0d75cf4de84bd066ed95d03dba08 | [
"Apache-2.0"
] | null | null | null | 24.968254 | 109 | 0.661157 | 998,809 | package com.yurkiv.unote.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.yurkiv.unote.R;
import java.util.List;
/**
* Created by poliveira on 24/10/2014.
*/
public class HashtagAdapter extends BaseAdapter {
private List<String> hashtags;
public HashtagAdapter(List<String> data) {
hashtags = data;
}
@Override
public int getCount() {
return hashtags.size();
}
@Override
public Object getItem(int position) {
return hashtags.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView==null){
convertView=LayoutInflater.from(parent.getContext()).inflate(R.layout.drawer_row, parent, false);
holder=new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder= (ViewHolder) convertView.getTag();
}
holder.textView.setText(hashtags.get(position));
return convertView;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView textView;
public ViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.item_name);
}
}
}
|
923965863f4a13b9c730303db9369ff7fc390ead | 1,049 | java | Java | random/src/main/java/de/slothsoft/random/types/LocalTimeRandomField.java | slothsoft/random-framework | cede7bc8a3f56c6972e90accc07c2921d4150774 | [
"MIT"
] | 2 | 2019-02-23T17:35:34.000Z | 2019-02-23T17:35:37.000Z | random/src/main/java/de/slothsoft/random/types/LocalTimeRandomField.java | slothsoft/framework-random | cede7bc8a3f56c6972e90accc07c2921d4150774 | [
"MIT"
] | 28 | 2019-02-22T22:05:24.000Z | 2020-02-05T19:21:34.000Z | random/src/main/java/de/slothsoft/random/types/LocalTimeRandomField.java | slothsoft/random-framework | cede7bc8a3f56c6972e90accc07c2921d4150774 | [
"MIT"
] | null | null | null | 21.854167 | 90 | 0.734986 | 998,810 | package de.slothsoft.random.types;
import java.time.LocalTime;
import java.time.temporal.ChronoField;
import de.slothsoft.random.RandomField;
/**
* A {@link RandomField} representing a {@link LocalTime} between 0:00 and 24:00 o'clock.
*
* @author Stef Schulz
* @since 2.1.0
*/
public class LocalTimeRandomField extends AbstractChronoRandomField<LocalTime> {
@Override
LocalTime createDefaultStartValue() {
return LocalTime.MIN;
}
@Override
LocalTime createDefaultEndValue() {
return LocalTime.MAX;
}
@Override
long toLongValue(LocalTime value) {
return value.getLong(ChronoField.NANO_OF_DAY);
}
@Override
LocalTime fromLongValue(long date) {
return LocalTime.ofNanoOfDay(date);
}
@Override
public LocalTimeRandomField endValue(LocalTime newEndValue) {
return (LocalTimeRandomField) super.endValue(newEndValue);
}
@Override
public LocalTimeRandomField startValue(LocalTime newStartValue) {
return (LocalTimeRandomField) super.startValue(newStartValue);
}
}
|
9239676181b18d7018270b5837f81c59c2805b84 | 1,336 | java | Java | src/pt/iscte/dcti/poo/sokoban/starter/Ice.java | Roguezilla/ISCTE_POO_Sokoban | f16cf45ed23f31cb1314f69ba1f06c830a4bf8cb | [
"MIT"
] | null | null | null | src/pt/iscte/dcti/poo/sokoban/starter/Ice.java | Roguezilla/ISCTE_POO_Sokoban | f16cf45ed23f31cb1314f69ba1f06c830a4bf8cb | [
"MIT"
] | null | null | null | src/pt/iscte/dcti/poo/sokoban/starter/Ice.java | Roguezilla/ISCTE_POO_Sokoban | f16cf45ed23f31cb1314f69ba1f06c830a4bf8cb | [
"MIT"
] | null | null | null | 40.484848 | 164 | 0.66991 | 998,811 | package pt.iscte.dcti.poo.sokoban.starter;
import pt.iul.ista.poo.utils.Direction;
import pt.iul.ista.poo.utils.Point2D;
public class Ice extends SokobanObject implements ActiveObject {
public Ice(Point2D position, String imageName) {
super(2, position, imageName);
}
@Override
public void interactWith(SokobanObject object) {
//anything that can touch ice is a movable object so this cast is safe
MovableObject movableObject = (MovableObject)object;
//objects are moved in the direction the player is moving
Direction playerDir = Sokoban.getInstance().getPlayer().getDirection();
/*
2 bugs are fixed here:
1. fixes the player and the movable object being moved to the same spot after the player tries moving it from when its on ice due to a previous collision
2. fixes objects getting moved twice
*/
SokobanObject onIce = Sokoban.getInstance().selectObject(sokobanObject -> sokobanObject.isAt(this.getPosition()) && sokobanObject instanceof MovableObject);
if (onIce != null) {
if (movableObject instanceof Player) {
movableObject.move(playerDir);
}
((MovableObject)onIce).move(playerDir);
} else {
movableObject.move(playerDir);
}
}
}
|
9239677addb2e51a250feffe7798557e9f77de35 | 1,327 | java | Java | aliyun-java-sdk-xtrace/src/main/java/com/aliyuncs/xtrace/transform/v20190808/GetTagValResponseUnmarshaller.java | cctvzd7/aliyun-openapi-java-sdk | b8e4dce2a61ca968615c9b910bedebaea71781ae | [
"Apache-2.0"
] | 3 | 2020-04-26T09:15:45.000Z | 2020-05-09T03:10:26.000Z | aliyun-java-sdk-xtrace/src/main/java/com/aliyuncs/xtrace/transform/v20190808/GetTagValResponseUnmarshaller.java | cctvzd7/aliyun-openapi-java-sdk | b8e4dce2a61ca968615c9b910bedebaea71781ae | [
"Apache-2.0"
] | 27 | 2021-06-11T21:08:40.000Z | 2022-03-11T21:25:09.000Z | aliyun-java-sdk-xtrace/src/main/java/com/aliyuncs/xtrace/transform/v20190808/GetTagValResponseUnmarshaller.java | cctvzd7/aliyun-openapi-java-sdk | b8e4dce2a61ca968615c9b910bedebaea71781ae | [
"Apache-2.0"
] | 1 | 2020-03-05T07:30:16.000Z | 2020-03-05T07:30:16.000Z | 34.921053 | 108 | 0.763376 | 998,812 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.xtrace.transform.v20190808;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.xtrace.model.v20190808.GetTagValResponse;
import com.aliyuncs.transform.UnmarshallerContext;
public class GetTagValResponseUnmarshaller {
public static GetTagValResponse unmarshall(GetTagValResponse getTagValResponse, UnmarshallerContext _ctx) {
getTagValResponse.setRequestId(_ctx.stringValue("GetTagValResponse.RequestId"));
List<String> tagValues = new ArrayList<String>();
for (int i = 0; i < _ctx.lengthValue("GetTagValResponse.TagValues.Length"); i++) {
tagValues.add(_ctx.stringValue("GetTagValResponse.TagValues["+ i +"]"));
}
getTagValResponse.setTagValues(tagValues);
return getTagValResponse;
}
} |
92396a407433dd021f23d4d5b3e3794a7fbda4e1 | 1,086 | java | Java | hazelcast-sql/src/main/java/com/hazelcast/jet/sql/impl/expression/Range.java | ldziedziul-gh-tests/hazelcast | 3a7382ac8164bc17836fc9b1f852b2667e7bef96 | [
"ECL-2.0",
"Apache-2.0"
] | 4,283 | 2015-01-02T03:56:10.000Z | 2022-03-29T23:07:45.000Z | hazelcast-sql/src/main/java/com/hazelcast/jet/sql/impl/expression/Range.java | ldziedziul-gh-tests/hazelcast | 3a7382ac8164bc17836fc9b1f852b2667e7bef96 | [
"ECL-2.0",
"Apache-2.0"
] | 14,014 | 2015-01-01T04:29:38.000Z | 2022-03-31T21:47:55.000Z | hazelcast-sql/src/main/java/com/hazelcast/jet/sql/impl/expression/Range.java | ldziedziul-gh-tests/hazelcast | 3a7382ac8164bc17836fc9b1f852b2667e7bef96 | [
"ECL-2.0",
"Apache-2.0"
] | 1,608 | 2015-01-04T09:57:08.000Z | 2022-03-31T12:05:26.000Z | 28.578947 | 84 | 0.734807 | 998,813 | /*
* Copyright 2021 Hazelcast Inc.
*
* Licensed under the Hazelcast Community License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://hazelcast.com/hazelcast-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.sql.impl.expression;
import com.google.common.collect.RangeSet;
import com.hazelcast.sql.impl.expression.Searchable;
import java.io.Serializable;
@SuppressWarnings("UnstableApiUsage")
public class Range<C extends Comparable<C>> implements Searchable<C>, Serializable {
private final RangeSet<C> set;
public Range(RangeSet<C> set) {
this.set = set;
}
@Override
public boolean contains(C value) {
return set.contains(value);
}
}
|
92396abf1fb3847b08fe6a5f0f0cb7abc9f3bfaf | 13,487 | java | Java | src/test/java/org/elasticsearch/test/unit/index/search/nested/NestedFieldComparatorTests.java | egaumer/elasticsearch | bd75b731c654f4c845f0781306b8055704706585 | [
"Apache-2.0"
] | null | null | null | src/test/java/org/elasticsearch/test/unit/index/search/nested/NestedFieldComparatorTests.java | egaumer/elasticsearch | bd75b731c654f4c845f0781306b8055704706585 | [
"Apache-2.0"
] | null | null | null | src/test/java/org/elasticsearch/test/unit/index/search/nested/NestedFieldComparatorTests.java | egaumer/elasticsearch | bd75b731c654f4c845f0781306b8055704706585 | [
"Apache-2.0"
] | 1 | 2020-08-27T14:40:01.000Z | 2020-08-27T14:40:01.000Z | 51.087121 | 180 | 0.66071 | 998,814 | package org.elasticsearch.test.unit.index.search.nested;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.apache.lucene.search.join.ScoreMode;
import org.apache.lucene.search.join.ToParentBlockJoinQuery;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.lucene.search.AndFilter;
import org.elasticsearch.common.lucene.search.NotFilter;
import org.elasticsearch.common.lucene.search.TermFilter;
import org.elasticsearch.common.lucene.search.XFilteredQuery;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.index.fielddata.FieldDataType;
import org.elasticsearch.index.fielddata.fieldcomparator.BytesRefFieldComparatorSource;
import org.elasticsearch.index.fielddata.fieldcomparator.SortMode;
import org.elasticsearch.index.fielddata.plain.PagedBytesIndexFieldData;
import org.elasticsearch.index.search.nested.NestedFieldComparatorSource;
import org.elasticsearch.test.unit.index.fielddata.AbstractFieldDataTests;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
/**
*/
public class NestedFieldComparatorTests extends AbstractFieldDataTests {
@Override
protected FieldDataType getFieldDataType() {
return new FieldDataType("string", ImmutableSettings.builder().put("format", "paged_bytes"));
}
@Test
public void testNestedSorting() throws Exception {
List<Document> docs = new ArrayList<Document>();
Document document = new Document();
document.add(new StringField("field2", "a", Field.Store.NO));
document.add(new StringField("filter_1", "T", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("field2", "b", Field.Store.NO));
document.add(new StringField("filter_1", "T", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("field2", "c", Field.Store.NO));
document.add(new StringField("filter_1", "T", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("__type", "parent", Field.Store.NO));
document.add(new StringField("field1", "a", Field.Store.NO));
docs.add(document);
writer.addDocuments(docs);
writer.commit();
docs.clear();
document = new Document();
document.add(new StringField("field2", "c", Field.Store.NO));
document.add(new StringField("filter_1", "T", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("field2", "d", Field.Store.NO));
document.add(new StringField("filter_1", "T", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("field2", "e", Field.Store.NO));
document.add(new StringField("filter_1", "T", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("__type", "parent", Field.Store.NO));
document.add(new StringField("field1", "b", Field.Store.NO));
docs.add(document);
writer.addDocuments(docs);
docs.clear();
document = new Document();
document.add(new StringField("field2", "e", Field.Store.NO));
document.add(new StringField("filter_1", "T", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("field2", "f", Field.Store.NO));
document.add(new StringField("filter_1", "T", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("field2", "g", Field.Store.NO));
document.add(new StringField("filter_1", "T", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("__type", "parent", Field.Store.NO));
document.add(new StringField("field1", "c", Field.Store.NO));
docs.add(document);
writer.addDocuments(docs);
docs.clear();
document = new Document();
document.add(new StringField("field2", "g", Field.Store.NO));
document.add(new StringField("filter_1", "T", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("field2", "h", Field.Store.NO));
document.add(new StringField("filter_1", "F", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("field2", "i", Field.Store.NO));
document.add(new StringField("filter_1", "F", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("__type", "parent", Field.Store.NO));
document.add(new StringField("field1", "d", Field.Store.NO));
docs.add(document);
writer.addDocuments(docs);
writer.commit();
docs.clear();
document = new Document();
document.add(new StringField("field2", "i", Field.Store.NO));
document.add(new StringField("filter_1", "F", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("field2", "j", Field.Store.NO));
document.add(new StringField("filter_1", "F", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("field2", "k", Field.Store.NO));
document.add(new StringField("filter_1", "F", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("__type", "parent", Field.Store.NO));
document.add(new StringField("field1", "f", Field.Store.NO));
docs.add(document);
writer.addDocuments(docs);
docs.clear();
document = new Document();
document.add(new StringField("field2", "k", Field.Store.NO));
document.add(new StringField("filter_1", "T", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("field2", "l", Field.Store.NO));
document.add(new StringField("filter_1", "T", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("field2", "m", Field.Store.NO));
document.add(new StringField("filter_1", "T", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("__type", "parent", Field.Store.NO));
document.add(new StringField("field1", "g", Field.Store.NO));
docs.add(document);
writer.addDocuments(docs);
// This doc will not be included, because it doesn't have nested docs
document = new Document();
document.add(new StringField("__type", "parent", Field.Store.NO));
document.add(new StringField("field1", "h", Field.Store.NO));
writer.addDocument(document);
docs.clear();
document = new Document();
document.add(new StringField("field2", "m", Field.Store.NO));
document.add(new StringField("filter_1", "T", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("field2", "n", Field.Store.NO));
document.add(new StringField("filter_1", "F", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("field2", "o", Field.Store.NO));
document.add(new StringField("filter_1", "F", Field.Store.NO));
docs.add(document);
document = new Document();
document.add(new StringField("__type", "parent", Field.Store.NO));
document.add(new StringField("field1", "i", Field.Store.NO));
docs.add(document);
writer.addDocuments(docs);
writer.commit();
// Some garbage docs, just to check if the NestedFieldComparator can deal with this.
document = new Document();
document.add(new StringField("fieldXXX", "x", Field.Store.NO));
writer.addDocument(document);
document = new Document();
document.add(new StringField("fieldXXX", "x", Field.Store.NO));
writer.addDocument(document);
document = new Document();
document.add(new StringField("fieldXXX", "x", Field.Store.NO));
writer.addDocument(document);
SortMode sortMode = SortMode.MIN;
IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(writer, false));
PagedBytesIndexFieldData indexFieldData = getForField("field2");
BytesRefFieldComparatorSource innerSource = new BytesRefFieldComparatorSource(indexFieldData, sortMode);
Filter parentFilter = new TermFilter(new Term("__type", "parent"));
Filter childFilter = new NotFilter(parentFilter);
NestedFieldComparatorSource nestedComparatorSource = new NestedFieldComparatorSource(sortMode, innerSource, parentFilter, childFilter);
ToParentBlockJoinQuery query = new ToParentBlockJoinQuery(new XFilteredQuery(new MatchAllDocsQuery(), childFilter), new CachingWrapperFilter(parentFilter), ScoreMode.None);
Sort sort = new Sort(new SortField("field2", nestedComparatorSource));
TopFieldDocs topDocs = searcher.search(query, 5, sort);
assertThat(topDocs.totalHits, equalTo(7));
assertThat(topDocs.scoreDocs.length, equalTo(5));
assertThat(topDocs.scoreDocs[0].doc, equalTo(3));
assertThat(((BytesRef) ((FieldDoc) topDocs.scoreDocs[0]).fields[0]).utf8ToString(), equalTo("a"));
assertThat(topDocs.scoreDocs[1].doc, equalTo(7));
assertThat(((BytesRef) ((FieldDoc) topDocs.scoreDocs[1]).fields[0]).utf8ToString(), equalTo("c"));
assertThat(topDocs.scoreDocs[2].doc, equalTo(11));
assertThat(((BytesRef) ((FieldDoc) topDocs.scoreDocs[2]).fields[0]).utf8ToString(), equalTo("e"));
assertThat(topDocs.scoreDocs[3].doc, equalTo(15));
assertThat(((BytesRef) ((FieldDoc) topDocs.scoreDocs[3]).fields[0]).utf8ToString(), equalTo("g"));
assertThat(topDocs.scoreDocs[4].doc, equalTo(19));
assertThat(((BytesRef) ((FieldDoc) topDocs.scoreDocs[4]).fields[0]).utf8ToString(), equalTo("i"));
sortMode = SortMode.MAX;
nestedComparatorSource = new NestedFieldComparatorSource(sortMode, innerSource, parentFilter, childFilter);
sort = new Sort(new SortField("field2", nestedComparatorSource, true));
topDocs = searcher.search(query, 5, sort);
assertThat(topDocs.totalHits, equalTo(7));
assertThat(topDocs.scoreDocs.length, equalTo(5));
assertThat(topDocs.scoreDocs[0].doc, equalTo(28));
assertThat(((BytesRef) ((FieldDoc) topDocs.scoreDocs[0]).fields[0]).utf8ToString(), equalTo("o"));
assertThat(topDocs.scoreDocs[1].doc, equalTo(23));
assertThat(((BytesRef) ((FieldDoc) topDocs.scoreDocs[1]).fields[0]).utf8ToString(), equalTo("m"));
assertThat(topDocs.scoreDocs[2].doc, equalTo(19));
assertThat(((BytesRef) ((FieldDoc) topDocs.scoreDocs[2]).fields[0]).utf8ToString(), equalTo("k"));
assertThat(topDocs.scoreDocs[3].doc, equalTo(15));
assertThat(((BytesRef) ((FieldDoc) topDocs.scoreDocs[3]).fields[0]).utf8ToString(), equalTo("i"));
assertThat(topDocs.scoreDocs[4].doc, equalTo(11));
assertThat(((BytesRef) ((FieldDoc) topDocs.scoreDocs[4]).fields[0]).utf8ToString(), equalTo("g"));
childFilter = new AndFilter(Arrays.asList(new NotFilter(parentFilter), new TermFilter(new Term("filter_1", "T"))));
nestedComparatorSource = new NestedFieldComparatorSource(sortMode, innerSource, parentFilter, childFilter);
query = new ToParentBlockJoinQuery(
new XFilteredQuery(new MatchAllDocsQuery(), childFilter),
new CachingWrapperFilter(parentFilter),
ScoreMode.None
);
sort = new Sort(new SortField("field2", nestedComparatorSource, true));
topDocs = searcher.search(query, 5, sort);
assertThat(topDocs.totalHits, equalTo(6));
assertThat(topDocs.scoreDocs.length, equalTo(5));
assertThat(topDocs.scoreDocs[0].doc, equalTo(23));
assertThat(((BytesRef) ((FieldDoc) topDocs.scoreDocs[0]).fields[0]).utf8ToString(), equalTo("m"));
assertThat(topDocs.scoreDocs[1].doc, equalTo(28));
assertThat(((BytesRef) ((FieldDoc) topDocs.scoreDocs[1]).fields[0]).utf8ToString(), equalTo("m"));
assertThat(topDocs.scoreDocs[2].doc, equalTo(11));
assertThat(((BytesRef) ((FieldDoc) topDocs.scoreDocs[2]).fields[0]).utf8ToString(), equalTo("g"));
assertThat(topDocs.scoreDocs[3].doc, equalTo(15));
assertThat(((BytesRef) ((FieldDoc) topDocs.scoreDocs[3]).fields[0]).utf8ToString(), equalTo("g"));
assertThat(topDocs.scoreDocs[4].doc, equalTo(7));
assertThat(((BytesRef) ((FieldDoc) topDocs.scoreDocs[4]).fields[0]).utf8ToString(), equalTo("e"));
searcher.getIndexReader().close();
}
}
|
92396ac472605d901a9a0fefc0fc162e95484fe3 | 528 | java | Java | app/src/main/java/br/com/androidpro/bollyfilmes/sync/FilmesAuthenticatosService.java | androidaccelerate/BollyFilmes | 00ed455017ef2c10dd36c9e3900f1a125cc9a9db | [
"Apache-2.0"
] | 8 | 2016-09-07T17:00:43.000Z | 2021-02-09T02:03:08.000Z | app/src/main/java/br/com/androidpro/bollyfilmes/sync/FilmesAuthenticatosService.java | androidaccelerate/BollyFilmes | 00ed455017ef2c10dd36c9e3900f1a125cc9a9db | [
"Apache-2.0"
] | null | null | null | app/src/main/java/br/com/androidpro/bollyfilmes/sync/FilmesAuthenticatosService.java | androidaccelerate/BollyFilmes | 00ed455017ef2c10dd36c9e3900f1a125cc9a9db | [
"Apache-2.0"
] | 8 | 2017-07-02T13:30:28.000Z | 2020-11-04T23:10:04.000Z | 22.956522 | 60 | 0.748106 | 998,815 | package br.com.androidpro.bollyfilmes.sync;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
public class FilmesAuthenticatosService extends Service {
private FilmesAuthenticator filmesAuthenticator;
@Override
public void onCreate() {
filmesAuthenticator = new FilmesAuthenticator(this);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return filmesAuthenticator.getIBinder();
}
}
|
92396ac7f55e115656c722aa6c420ed2a1758116 | 2,481 | java | Java | xmall-admin/src/main/java/com/yzsunlei/xmall/admin/service/impl/UmsRoleServiceImpl.java | npmmirror/xmall | bb6ba9ba38d5dfb0940debd8d2d6e88f3f2b6bda | [
"MIT"
] | 302 | 2019-04-28T03:56:20.000Z | 2022-03-29T01:38:00.000Z | xmall-admin/src/main/java/com/yzsunlei/xmall/admin/service/impl/UmsRoleServiceImpl.java | npmmirror/xmall | bb6ba9ba38d5dfb0940debd8d2d6e88f3f2b6bda | [
"MIT"
] | 3 | 2019-10-22T01:48:43.000Z | 2021-06-09T10:39:56.000Z | xmall-admin/src/main/java/com/yzsunlei/xmall/admin/service/impl/UmsRoleServiceImpl.java | npmmirror/xmall | bb6ba9ba38d5dfb0940debd8d2d6e88f3f2b6bda | [
"MIT"
] | 135 | 2019-04-07T16:05:48.000Z | 2022-03-19T13:05:58.000Z | 32.644737 | 88 | 0.720274 | 998,816 | package com.yzsunlei.xmall.admin.service.impl;
import com.yzsunlei.xmall.admin.dao.UmsRolePermissionRelationDao;
import com.yzsunlei.xmall.db.mapper.UmsRoleMapper;
import com.yzsunlei.xmall.db.mapper.UmsRolePermissionRelationMapper;
import com.yzsunlei.xmall.admin.service.UmsRoleService;
import com.yzsunlei.xmall.db.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* 后台角色管理Service实现类
* Created by macro on 2018/9/30.
*/
@Service
public class UmsRoleServiceImpl implements UmsRoleService {
@Autowired
private UmsRoleMapper roleMapper;
@Autowired
private UmsRolePermissionRelationMapper rolePermissionRelationMapper;
@Autowired
private UmsRolePermissionRelationDao rolePermissionRelationDao;
@Override
public int create(UmsRole role) {
role.setCreateTime(new Date());
role.setStatus(1);
role.setAdminCount(0);
role.setSort(0);
return roleMapper.insert(role);
}
@Override
public int update(Long id, UmsRole role) {
role.setId(id);
return roleMapper.updateByPrimaryKey(role);
}
@Override
public int delete(List<Long> ids) {
UmsRoleExample example = new UmsRoleExample();
example.createCriteria().andIdIn(ids);
return roleMapper.deleteByExample(example);
}
@Override
public List<UmsPermission> getPermissionList(Long roleId) {
return rolePermissionRelationDao.getPermissionList(roleId);
}
@Override
public int updatePermission(Long roleId, List<Long> permissionIds) {
//先删除原有关系
UmsRolePermissionRelationExample example=new UmsRolePermissionRelationExample();
example.createCriteria().andRoleIdEqualTo(roleId);
rolePermissionRelationMapper.deleteByExample(example);
//批量插入新关系
List<UmsRolePermissionRelation> relationList = new ArrayList<>();
for (Long permissionId : permissionIds) {
UmsRolePermissionRelation relation = new UmsRolePermissionRelation();
relation.setRoleId(roleId);
relation.setPermissionId(permissionId);
relationList.add(relation);
}
return rolePermissionRelationDao.insertList(relationList);
}
@Override
public List<UmsRole> list() {
return roleMapper.selectByExample(new UmsRoleExample());
}
}
|
92396ba53adff8bdc7d1da31ec62f02f4e1311c3 | 2,801 | java | Java | sample/src/main/java/com/capitalone/easyscreenshots/sample/TrueFalseQuestionFragment.java | nickcapurso/easy-screenshots | 75db271ac64d6d4ebb6fdf00b4d0b2086ecf059b | [
"Apache-2.0"
] | 23 | 2018-01-21T00:54:13.000Z | 2020-10-01T23:19:26.000Z | sample/src/main/java/com/capitalone/easyscreenshots/sample/TrueFalseQuestionFragment.java | nickcapurso/easy-screenshots | 75db271ac64d6d4ebb6fdf00b4d0b2086ecf059b | [
"Apache-2.0"
] | 10 | 2018-01-17T17:50:23.000Z | 2020-11-23T17:32:55.000Z | sample/src/main/java/com/capitalone/easyscreenshots/sample/TrueFalseQuestionFragment.java | nickcapurso/easy-screenshots | 75db271ac64d6d4ebb6fdf00b4d0b2086ecf059b | [
"Apache-2.0"
] | 7 | 2018-10-17T09:14:41.000Z | 2021-08-14T20:52:04.000Z | 33.746988 | 103 | 0.670118 | 998,817 | /**
* SPDX-Copyright: Copyright (c) Capital One Services, LLC
* SPDX-License-Identifier: Apache-2.0
* Copyright 2017 Capital One Services, 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
*
* 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.capitalone.easyscreenshots.sample;
import android.os.Bundle;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatTextView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.capitalone.easyscreenshots.sample.model.TrueFalseQuestion;
import timber.log.Timber;
public class TrueFalseQuestionFragment extends QuestionFragment {
private TrueFalseQuestion question;
private AppCompatButton positiveButton;
private AppCompatButton negativeButton;
private AppCompatTextView questionText;
public TrueFalseQuestionFragment() {
super();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
question = (TrueFalseQuestion) getQuestion();
View rootView = inflater.inflate(R.layout.true_false_question, container, false);
questionText = (AppCompatTextView) rootView.findViewById(R.id.question_text);
positiveButton = (AppCompatButton) rootView.findViewById(R.id.positive_button);
negativeButton = (AppCompatButton) rootView.findViewById(R.id.negative_button);
questionText.setText(question.getQuestion());
positiveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Timber.d("TRUE clicked, Answer: " + question.getBooleanAnswer());
if (question.getBooleanAnswer() == true) {
correct();
} else {
incorrect();
}
}
});
negativeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Timber.d("FALSE clicked, Answer: " + question.getBooleanAnswer());
if (question.getBooleanAnswer() == false) {
correct();
} else {
incorrect();
}
}
});
return rootView;
}
}
|
92396bbc7a7f445927874b96a478784894b6e7e4 | 26,383 | java | Java | core/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/InstallationService.java | cquoss/servicemix3 | a4ce3148916c940fa204b713795bb21e8d0cd42e | [
"Apache-2.0"
] | 2 | 2015-07-29T22:58:57.000Z | 2021-11-10T19:04:24.000Z | core/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/InstallationService.java | cquoss/servicemix3 | a4ce3148916c940fa204b713795bb21e8d0cd42e | [
"Apache-2.0"
] | null | null | null | core/servicemix-core/src/main/java/org/apache/servicemix/jbi/framework/InstallationService.java | cquoss/servicemix3 | a4ce3148916c940fa204b713795bb21e8d0cd42e | [
"Apache-2.0"
] | 12 | 2015-10-05T13:32:39.000Z | 2021-11-10T19:04:18.000Z | 45.803819 | 136 | 0.613653 | 998,818 | /*
* 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.servicemix.jbi.framework;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import javax.jbi.JBIException;
import javax.jbi.management.DeploymentException;
import javax.jbi.management.InstallationServiceMBean;
import javax.jbi.management.InstallerMBean;
import javax.management.Attribute;
import javax.management.JMException;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.servicemix.jbi.container.ComponentEnvironment;
import org.apache.servicemix.jbi.container.EnvironmentContext;
import org.apache.servicemix.jbi.container.JBIContainer;
import org.apache.servicemix.jbi.deployment.Component;
import org.apache.servicemix.jbi.deployment.Descriptor;
import org.apache.servicemix.jbi.deployment.DescriptorFactory;
import org.apache.servicemix.jbi.deployment.SharedLibrary;
import org.apache.servicemix.jbi.management.BaseSystemService;
import org.apache.servicemix.jbi.management.ManagementContext;
import org.apache.servicemix.jbi.management.OperationInfoHelper;
import org.apache.servicemix.jbi.management.ParameterHelper;
import org.apache.servicemix.jbi.util.FileUtil;
import org.apache.servicemix.jbi.util.FileVersionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Installation Service - installs/uninstalls archives
*
* @version $Revision$
*/
public class InstallationService extends BaseSystemService implements InstallationServiceMBean {
private static final transient Logger LOGGER = LoggerFactory.getLogger(InstallationService.class);
private EnvironmentContext environmentContext;
private ManagementContext managementContext;
private Map<String, InstallerMBeanImpl> installers = new ConcurrentHashMap<String, InstallerMBeanImpl>();
private Map<String, InstallerMBeanImpl> nonLoadedInstallers = new ConcurrentHashMap<String, InstallerMBeanImpl>();
/**
* Get Description
*
* @return description of this item
*/
public String getDescription() {
return "installs/uninstalls Components";
}
/**
* Load the installer for a new component from a component installation
* package.
*
* @param installJarURL -
* URL locating a jar file containing a JBI Installable
* Component.
* @return - the JMX ObjectName of the InstallerMBean loaded from
* installJarURL.
*/
public synchronized ObjectName loadNewInstaller(String installJarURL) {
try {
ObjectName result = null;
LOGGER.debug("Loading new installer from {}", installJarURL);
File tmpDir = AutoDeploymentService.unpackLocation(environmentContext.getTmpDir(), installJarURL);
if (tmpDir == null) {
throw new RuntimeException("loation " + installJarURL + " isn't valid");
}
Descriptor root = DescriptorFactory.buildDescriptor(tmpDir);
if (root == null || root.getComponent() == null) {
throw new RuntimeException("Could not find Component from " + installJarURL);
}
String componentName = root.getComponent().getIdentification().getName();
if (installers.containsKey(componentName)) {
throw new RuntimeException("An installer already exists for " + componentName);
}
InstallerMBeanImpl installer = doInstallArchive(tmpDir, root);
if (installer != null) {
result = installer.getObjectName();
LOGGER.debug("Registering installer as loaded for component {}", componentName);
installers.put(componentName, installer);
}
return result;
} catch (Throwable t) {
LOGGER.error("Deployment failed", t);
if (t instanceof Error) {
throw (Error) t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new RuntimeException("Deployment failed: " + t.getMessage());
}
}
}
/**
* Load the InstallerMBean for a previously installed component.
*
* @param aComponentName -
* the component name identifying the installer to load.
* @return - the JMX ObjectName of the InstallerMBean loaded from an
* existing installation context.
*/
public ObjectName loadInstaller(String aComponentName) {
LOGGER.debug("Going to load installer for component {}", aComponentName);
InstallerMBeanImpl installer = installers.get(aComponentName);
LOGGER.debug("Found installer for component {}", aComponentName);
if (installer == null) {
LOGGER.debug("Loaded installer for component {} was not found. Trying non-loaded installers", aComponentName);
installer = nonLoadedInstallers.get(aComponentName);
if (installer != null) {
LOGGER.debug("Found non-loaded installer for component {}", aComponentName);
try {
// create an MBean for the installer
ObjectName objectName = managementContext.createCustomComponentMBeanName("Installer", aComponentName);
installer.setObjectName(objectName);
managementContext.registerMBean(objectName, installer, InstallerMBean.class,
"standard installation controls for a Component");
} catch (Exception e) {
throw new RuntimeException("Could not load installer", e);
}
return installer.getObjectName();
} else {
LOGGER.debug("Did not found any installer for component " + aComponentName);
}
}
return null;
}
private InstallerMBeanImpl createInstaller(String componentName) throws IOException, DeploymentException {
File installationDir = environmentContext.getComponentInstallationDir(componentName);
Descriptor root = DescriptorFactory.buildDescriptor(installationDir);
Component descriptor = root.getComponent();
InstallationContextImpl installationContext = new InstallationContextImpl(descriptor);
installationContext.setInstall(false);
installationContext.setInstallRoot(installationDir);
// now build the ComponentContext
File componentRoot = environmentContext.getComponentRootDir(componentName);
ComponentContextImpl context = buildComponentContext(componentRoot, installationDir, componentName);
installationContext.setContext(context);
return new InstallerMBeanImpl(container, installationContext);
}
/**
* Unload a JBI Installable Component installer.
*
* @param componentName -
* the component name identifying the installer to unload.
* @param isToBeDeleted -
* true if the component is to be deleted as well.
* @return - true if the operation was successful, otherwise false.
*/
public boolean unloadInstaller(String componentName, boolean isToBeDeleted) {
LOGGER.debug("Going to unload installer for component {}", componentName);
boolean result = false;
try {
InstallerMBeanImpl installer = installers.remove(componentName);
result = installer != null;
if (result) {
LOGGER.debug("Found installer for component {}", componentName);
container.getManagementContext().unregisterMBean(installer);
if (isToBeDeleted) {
LOGGER.debug("Uninstalling component {}", componentName);
installer.uninstall();
} else {
LOGGER.debug("Registering installer as non-loaded for component {}", componentName);
nonLoadedInstallers.put(componentName, installer);
}
} else {
LOGGER.debug("Did not found installer for component {}", componentName);
}
} catch (JBIException e) {
String errStr = "Problem unloading installer for component " + componentName;
LOGGER.error(errStr, e);
}
return result;
}
/**
* Install a shared library jar.
*
* @param aSharedLibURI -
* URI locating a jar file containing a shared library.
* @return - the name of the shared library loaded from aSharedLibURI.
*/
public String installSharedLibrary(String aSharedLibURI) {
String result = "";
try {
File tmpDir = AutoDeploymentService.unpackLocation(environmentContext.getTmpDir(), aSharedLibURI);
if (tmpDir != null) {
Descriptor root = DescriptorFactory.buildDescriptor(tmpDir);
if (root == null) {
throw new DeploymentException("Could not find JBI descriptor");
}
SharedLibrary sl = root.getSharedLibrary();
if (sl != null) {
result = doInstallSharedLibrary(tmpDir, sl);
} else {
throw new DeploymentException("JBI descriptor is not a SharedLibrary descriptor");
}
} else {
throw new DeploymentException("Could not find JBI descriptor");
}
} catch (DeploymentException e) {
LOGGER.error("Deployment failed", e);
}
return result;
}
/**
* Uninstall a shared library.
*
* @param aSharedLibName -
* the name of the shared library to uninstall.
* @return - true iff the uninstall was successful.
*/
public boolean uninstallSharedLibrary(String aSharedLibName) {
// TODO: should check existence of shared library
// and that it is not currently in use
container.getRegistry().unregisterSharedLibrary(aSharedLibName);
environmentContext.removeSharedLibraryDirectory(aSharedLibName);
return true;
}
/**
* Initialize the Service
*
* @param container
* @throws JBIException
* @throws DeploymentException
*/
public void init(JBIContainer container) throws JBIException {
super.init(container);
this.environmentContext = container.getEnvironmentContext();
this.managementContext = container.getManagementContext();
buildState();
}
protected Class getServiceMBean() {
return InstallationServiceMBean.class;
}
/**
* Install an archive
*
* @param location
* @param props
* @param autoStart
* @throws DeploymentException
*/
public void install(String location, Properties props, boolean autoStart) throws DeploymentException {
File tmpDir = AutoDeploymentService.unpackLocation(environmentContext.getTmpDir(), location);
if (tmpDir != null) {
Descriptor root = DescriptorFactory.buildDescriptor(tmpDir);
if (root != null) {
if (root.getComponent() == null) {
throw new DeploymentException("JBI descriptor is not a component descriptor");
}
install(tmpDir, props, root, autoStart);
} else {
throw new DeploymentException("Could not find JBI descriptor");
}
} else {
throw new DeploymentException("Could not find JBI descriptor");
}
}
/**
* Install an archive
*
* @param tmpDir
* @param root
* @param autoStart
* @throws DeploymentException
*/
protected void install(File tmpDir, Properties props, Descriptor root, boolean autoStart) throws DeploymentException {
LOGGER.debug("Going to install component from {}", tmpDir.getPath());
if (root.getComponent() != null) {
String componentName = root.getComponent().getIdentification().getName();
if (installers.containsKey(componentName)) {
throw new DeploymentException("Component " + componentName + " is already installed");
}
InstallerMBeanImpl installer = doInstallArchive(tmpDir, root);
if (installer != null) {
try {
if (props != null && props.size() > 0) {
ObjectName on = installer.getInstallerConfigurationMBean();
if (on == null) {
LOGGER.warn("Could not find installation configuration MBean. Installation properties will be ignored.");
} else {
MBeanServer mbs = managementContext.getMBeanServer();
for (Iterator it = props.keySet().iterator(); it.hasNext();) {
String key = (String) it.next();
String val = props.getProperty(key);
try {
mbs.setAttribute(on, new Attribute(key, val));
} catch (JMException e) {
throw new DeploymentException("Could not set installation property: (" + key + " = " + val, e);
}
}
}
}
installer.install();
} catch (JBIException e) {
throw new DeploymentException(e);
}
if (autoStart) {
try {
ComponentMBeanImpl lcc = container.getComponent(componentName);
if (lcc != null) {
lcc.start();
} else {
LOGGER.warn("No ComponentConnector found for Component {}", componentName);
}
} catch (JBIException e) {
String errStr = "Failed to start Component: " + componentName;
LOGGER.error(errStr, e);
throw new DeploymentException(e);
}
}
LOGGER.debug("Registering installer as loaded for component {}", componentName);
installers.put(componentName, installer);
}
}
}
/**
* Get an array of MBeanOperationInfo
*
* @return array of OperationInfos
* @throws JMException
*/
public MBeanOperationInfo[] getOperationInfos() throws JMException {
OperationInfoHelper helper = new OperationInfoHelper();
ParameterHelper ph = helper.addOperation(getObjectToManage(), "loadNewInstaller", 1, "load a new Installer ");
ph.setDescription(0, "installJarURL", "URL locating the install Jar");
ph = helper.addOperation(getObjectToManage(), "loadInstaller", 1, "load installer for a previously installed component");
ph.setDescription(0, "componentName", "Name of the Component");
ph = helper.addOperation(getObjectToManage(), "unloadInstaller", 2, "unload an installer");
ph.setDescription(0, "componentName", "Name of the Component");
ph.setDescription(1, "isToBeDeleted", "true if component is to be deleted");
ph = helper.addOperation(getObjectToManage(), "installSharedLibrary", 1, "Install a shared library jar");
ph.setDescription(0, "sharedLibURI", "URI for the jar to be installed");
ph = helper.addOperation(getObjectToManage(), "uninstallSharedLibrary", 1, "Uninstall a shared library jar");
ph.setDescription(0, "sharedLibName", "name of the shared library");
ph = helper.addOperation(getObjectToManage(), "install", 1, "install and deplot an archive");
ph.setDescription(0, "location", "location of archive");
ph = helper.addOperation(getObjectToManage(), "install", 2, "install and deplot an archive");
ph.setDescription(0, "location", "location of archive");
ph.setDescription(1, "autostart", "automatically start the Component");
return OperationInfoHelper.join(super.getOperationInfos(), helper.getOperationInfos());
}
protected InstallerMBeanImpl doInstallArchive(File tmpDirectory, Descriptor descriptor) throws DeploymentException {
InstallerMBeanImpl installer = null;
Component component = descriptor.getComponent();
if (component != null) {
installer = doInstallComponent(tmpDirectory, component);
}
return installer;
}
protected String doInstallSharedLibrary(File tmpDirectory, SharedLibrary descriptor) throws DeploymentException {
String result = null;
if (descriptor != null) {
File installationDir = null;
try {
result = descriptor.getIdentification().getName();
File rootDir = environmentContext.createSharedLibraryDirectory(result);
installationDir = FileVersionUtil.getNewVersionDirectory(rootDir);
if (!tmpDirectory.renameTo(installationDir)) {
throw new DeploymentException("Unable to rename " + tmpDirectory + " to " + installationDir);
}
LOGGER.debug("Moved {} to {}", tmpDirectory, installationDir);
container.getRegistry().registerSharedLibrary(descriptor, installationDir);
} catch (Exception e) {
LOGGER.error("Deployment of Shared Library failed", e);
// remove any files created for installation
FileUtil.deleteFile(installationDir);
throw new DeploymentException(e);
} finally {
FileUtil.deleteFile(tmpDirectory);
}
}
return result;
}
protected InstallerMBeanImpl doInstallComponent(File tmpDirectory, Component descriptor) throws DeploymentException {
// move archive to Component directory
InstallerMBeanImpl result = null;
String name = descriptor.getIdentification().getName();
try {
File oldInstallationDir = environmentContext.getComponentInstallationDir(name);
// try and delete the old version ? - maybe should leave around ??
if (!FileUtil.deleteFile(oldInstallationDir)) {
LOGGER.warn("Failed to delete old installation directory: {}", oldInstallationDir.getPath());
}
File componentRoot = environmentContext.createComponentRootDir(name);
// this will get the new one
File installationDir = environmentContext.getNewComponentInstallationDir(name);
tmpDirectory.renameTo(installationDir);
LOGGER.debug("Moved {} to {}", tmpDirectory, installationDir);
result = initializeInstaller(installationDir, componentRoot, descriptor);
return result;
} catch (IOException e) {
throw new DeploymentException(e);
}
}
private InstallerMBeanImpl initializeInstaller(File installationDir, File componentRoot,
Component descriptor) throws DeploymentException {
InstallerMBeanImpl result = null;
try {
String name = descriptor.getIdentification().getName();
InstallationContextImpl installationContext = new InstallationContextImpl(descriptor);
installationContext.setInstall(true);
installationContext.setInstallRoot(installationDir);
// now build the ComponentContext
ComponentContextImpl context = buildComponentContext(componentRoot, installationDir, name);
installationContext.setContext(context);
result = new InstallerMBeanImpl(container, installationContext);
// create an MBean for the installer
ObjectName objectName = managementContext.createCustomComponentMBeanName("Installer", name);
result.setObjectName(objectName);
managementContext.registerMBean(objectName, result, InstallerMBean.class, "standard installation controls for a Component");
} catch (Throwable e) {
LOGGER.error("Deployment of Component failed", e);
// remove any files created for installation
environmentContext.removeComponentRootDirectory(descriptor.getIdentification().getName());
throw new DeploymentException(e);
}
return result;
}
protected void buildState() {
buildSharedLibs();
buildComponents();
}
/**
* returns true if a shared library is already installed
*
* @param name
* @return true/false
*/
protected boolean containsSharedLibrary(String name) {
return container.getRegistry().getSharedLibrary(name) != null;
}
protected void buildSharedLibs() {
// walk through shared libaries and add then to the ClassLoaderService
File top = environmentContext.getSharedLibDir();
if (top != null && top.exists() && top.isDirectory()) {
// directory structure is sharedlibraries/<lib name>/version_x/stuff
// ...
File[] files = top.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (!files[i].isDirectory()) {
continue;
}
File dir = FileVersionUtil.getLatestVersionDirectory(files[i]);
if (dir == null) {
continue;
}
Descriptor root = DescriptorFactory.buildDescriptor(dir);
if (root == null) {
continue;
}
SharedLibrary sl = root.getSharedLibrary();
if (sl == null) {
continue;
}
try {
container.getRegistry().registerSharedLibrary(sl, dir);
} catch (Exception e) {
LOGGER.error("Failed to initialize sharted library", e);
}
}
}
}
}
protected void buildComponents() {
// walk through components and add then to the ClassLoaderService
File top = environmentContext.getComponentsDir();
if (top != null && top.exists() && top.isDirectory()) {
// directory structure is components/<component name>/installation
// ...
File[] files = top.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (!files[i].isDirectory()) {
continue;
}
final File directory = files[i];
try {
buildComponent(directory);
} catch (DeploymentException e) {
LOGGER.error("Could not build Component: {}", directory.getName(), e);
LOGGER.warn("Deleting Component directory: {}", directory);
FileUtil.deleteFile(directory);
}
}
}
}
}
protected void buildComponent(File componentDirectory) throws DeploymentException {
LOGGER.debug("Building component from directory {}" + componentDirectory.getPath());
try {
String componentName = componentDirectory.getName();
ComponentEnvironment env = container.getEnvironmentContext().getComponentEnvironment(componentName);
if (!env.getStateFile().exists()) {
LOGGER.debug("Removing directory {} as component has not been installed (there is not state file)",
componentDirectory.getPath());
// An installer has been created but the component has not been
// installed
// So remove it
FileUtil.deleteFile(componentDirectory);
} else {
InstallerMBeanImpl installer = createInstaller(componentName);
installer.activateComponent();
nonLoadedInstallers.put(componentName, installer);
LOGGER.debug("Registering installer as loaded for component {}", componentName);
}
} catch (Throwable e) {
LOGGER.error("Failed to deploy component: {}", componentDirectory.getName(), e);
throw new DeploymentException(e);
}
}
protected ComponentContextImpl buildComponentContext(File componentRoot, File installRoot, String name) throws IOException {
ComponentNameSpace cns = new ComponentNameSpace(container.getName(), name);
ComponentContextImpl context = new ComponentContextImpl(container, cns);
ComponentEnvironment env = new ComponentEnvironment();
FileUtil.buildDirectory(componentRoot);
File privateWorkspace = environmentContext.createWorkspaceDirectory(name);
env.setWorkspaceRoot(privateWorkspace);
env.setComponentRoot(componentRoot);
env.setInstallRoot(installRoot);
context.setEnvironment(env);
return context;
}
}
|
92396bf5b7a66687da65e0831ad1fed7fef14467 | 850 | java | Java | app/src/main/java/com/example/nikhil/studentregistrationsystem/databaseModel/DbQueriesInterface.java | TechOnLabs/Student-Registration-System | 7c331bf55075afd32aedf0338972381d6371abab | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/nikhil/studentregistrationsystem/databaseModel/DbQueriesInterface.java | TechOnLabs/Student-Registration-System | 7c331bf55075afd32aedf0338972381d6371abab | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/nikhil/studentregistrationsystem/databaseModel/DbQueriesInterface.java | TechOnLabs/Student-Registration-System | 7c331bf55075afd32aedf0338972381d6371abab | [
"Apache-2.0"
] | null | null | null | 25.757576 | 89 | 0.8 | 998,819 | package com.example.nikhil.studentregistrationsystem.databaseModel;
import com.example.nikhil.studentregistrationsystem.allStudentActivtiy.AllStudentListRef;
import java.util.ArrayList;
/**
* Created by nikhil on 5/9/17.
*/
public interface DbQueriesInterface {
void truncateDb(String depId);
void addStudentDetails(StudentDetailsRef studentDetailsRef, String depId);
void updateStudentDetails(StudentDetailsRef studentDetailsRef, String depId);
ArrayList<StudentDetailsRef> getStudentList(String depName);
DepartmentDetailsRef getDepartmentsDetails(String departmentName);
ArrayList<String> getDepartmentsNamesList();
ArrayList<DepartmentDetailsRef> getDepartmentDetailsList();
void deleteOneEntry(String reg_num);
ArrayList<AllStudentListRef> getAllStudentList();
void truncateAllTables();
}
|
92396cd8f2020378e67eeace767f67f08a30864e | 9,341 | java | Java | src/main/java/malte0811/recipebuffers/impl/RecipeListSerializer.java | malte0811/RecipeBuffers | 2d48f812517c91b271af8fdcd956b42ae42c1a49 | [
"MIT"
] | 2 | 2021-09-11T20:11:48.000Z | 2021-10-02T01:51:24.000Z | src/main/java/malte0811/recipebuffers/impl/RecipeListSerializer.java | malte0811/RecipeBuffers | 2d48f812517c91b271af8fdcd956b42ae42c1a49 | [
"MIT"
] | 3 | 2020-11-27T22:55:27.000Z | 2021-01-15T14:30:12.000Z | src/main/java/malte0811/recipebuffers/impl/RecipeListSerializer.java | malte0811/RecipeBuffers | 2d48f812517c91b271af8fdcd956b42ae42c1a49 | [
"MIT"
] | null | null | null | 45.34466 | 121 | 0.625415 | 998,820 | package malte0811.recipebuffers.impl;
import com.google.common.collect.Lists;
import io.netty.buffer.ByteBufUtil;
import malte0811.recipebuffers.Config;
import malte0811.recipebuffers.RBRecipeSerializers;
import malte0811.recipebuffers.RecipeBuffers;
import malte0811.recipebuffers.util.IngredientSerializer;
import malte0811.recipebuffers.util.StateStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.IRecipeSerializer;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistries;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
/**
* Differences from vanilla implementation:
* - Uses {@link OptimizedPacketBuffer} for everything
* - Does not send the serializer ID for every recipe, instead sorts by ID and sends each ID once
*/
public class RecipeListSerializer {
public static final Logger WRITE_LOGGER = LogManager.getLogger(RecipeBuffers.MODID + " - WRITE");
public static final Logger READ_LOGGER = LogManager.getLogger(RecipeBuffers.MODID + " - READ");
public static void writeRecipes(List<IRecipe<?>> recipes, PacketBuffer bufIn) throws IOException {
final int debugLevel = Config.debugLogLevel.get();
final boolean writeLength = Config.writeRecipeLength.get();
byte configByte = 0;
if (writeLength) {
configByte |= ConfigMasks.RECIPE_LENGTH;
}
bufIn.writeByte(configByte);
final StateStack.Entry computeLists = StateStack.push("Compute recipe lists");
OptimizedPacketBuffer buf = new OptimizedPacketBuffer(bufIn, false);
Map<IRecipeSerializer<?>, List<IRecipe<?>>> bySerializer = new IdentityHashMap<>();
for (IRecipe<?> recipe : recipes) {
bySerializer.computeIfAbsent(recipe.getSerializer(), ser -> new ArrayList<>())
.add(recipe);
}
computeLists.pop();
IngredientSerializer ingredientSerializer = new IngredientSerializer(buf, false);
buf.writeVarInt(bySerializer.size());
if (debugLevel > 0) {
WRITE_LOGGER.debug("Number of serializers: {}", bySerializer.size());
}
for (Map.Entry<IRecipeSerializer<?>, List<IRecipe<?>>> entry : bySerializer.entrySet()) {
final StateStack.Entry serializerEntry = StateStack.push(
"Writing recipes for serializer " + entry.getKey().getRegistryName()
);
if (debugLevel > 0) {
WRITE_LOGGER.debug(
"Writing {} recipes for serializer {}",
entry.getValue().size(), entry.getKey().getRegistryName()
);
}
buf.writeRegistryIdUnsafe(ForgeRegistries.RECIPE_SERIALIZERS, entry.getKey());
IRecipeSerializer<?> serializerToUse = RBRecipeSerializers.getSerializer(entry.getKey());
buf.writeVarInt(entry.getValue().size());
for (IRecipe<?> recipe : entry.getValue()) {
final StateStack.Entry recipeEntry = StateStack.push(
"Writing recipe " + recipe.getId()
);
if (debugLevel > 1) {
WRITE_LOGGER.debug("Writing recipe {} (name: {})", recipe, recipe.getId());
}
final int oldWriteIndex = buf.writerIndex();
writeRecipe(recipe, buf, serializerToUse, ingredientSerializer, writeLength);
if (debugLevel > 1) {
WRITE_LOGGER.debug("Wrote recipe, takes {} bytes", buf.writerIndex() - oldWriteIndex);
}
recipeEntry.pop();
}
serializerEntry.pop();
}
if (Config.dumpPacket.get()) {
try (FileOutputStream out = new FileOutputStream("written_recipes.dmp")) {
out.write(ByteBufUtil.getBytes(buf.copy()));
}
}
if (Config.logPacketStats.get()) {
WRITE_LOGGER.info("Recipe packet size: {}", buf.readableBytes());
WRITE_LOGGER.info("Item stack bytes: {}", buf.itemStackBytes);
WRITE_LOGGER.info("RL path bytes: {}", buf.resourceLocationSerializer.rlPathBytes);
WRITE_LOGGER.info("Ingredient cache size: {}", ingredientSerializer.cacheSize());
WRITE_LOGGER.info("Ingredient cache hits: {}", ingredientSerializer.cacheHits());
}
}
public static List<IRecipe<?>> readRecipes(PacketBuffer bufIn) throws IOException {
if (Config.dumpPacket.get()) {
try (FileOutputStream out = new FileOutputStream("read_recipes.dmp")) {
out.write(ByteBufUtil.getBytes(bufIn.copy()));
}
}
final int debugLevel = Config.debugLogLevel.get();
OptimizedPacketBuffer buf = new OptimizedPacketBuffer(bufIn, true);
final byte configByte = buf.readByte();
final boolean includesLengthPrefix = (configByte & ConfigMasks.RECIPE_LENGTH) != 0;
List<IRecipe<?>> recipes = Lists.newArrayList();
IngredientSerializer ingredientSerializer = new IngredientSerializer(buf, true);
final int numSerializer = buf.readVarInt();
if (debugLevel > 0) {
READ_LOGGER.debug("Number of serializers: {}", numSerializer);
}
for (int serId = 0; serId < numSerializer; ++serId) {
IRecipeSerializer<?> serializer = buf.readRegistryIdUnsafe(ForgeRegistries.RECIPE_SERIALIZERS);
final StateStack.Entry serializerEntry = StateStack.push(
"Reading recipes for serializer " + serializer.getRegistryName()
);
final int numRecipes = buf.readVarInt();
if (debugLevel > 0) {
READ_LOGGER.debug("Reading {} recipes for serializer {}", numRecipes, serializer.getRegistryName());
}
serializer = RBRecipeSerializers.getSerializer(serializer);
for (int recId = 0; recId < numRecipes; ++recId) {
final int oldReadIndex = buf.readerIndex();
IRecipe<?> readRecipe = readRecipe(buf, serializer, ingredientSerializer, includesLengthPrefix);
recipes.add(readRecipe);
if (debugLevel > 1) {
READ_LOGGER.debug(
"Read recipe {} (name {}), bytes read: {}",
readRecipe, readRecipe.getId(), buf.readerIndex() - oldReadIndex
);
}
}
serializerEntry.pop();
}
return recipes;
}
public static <R extends IRecipe<?>> R readRecipe(
OptimizedPacketBuffer buffer,
IRecipeSerializer<R> serializer,
IngredientSerializer ingredientSerializer,
boolean readLength
) {
final int expectedLength;
if (readLength) {
expectedLength = buffer.readVarInt();
} else {
expectedLength = -1;
}
final int oldReadIndex = buffer.readerIndex();
ResourceLocation name = buffer.readResourceLocation();
StateStack.Entry recipeEntry = StateStack.push("Reading recipe " + name);
R result;
if (serializer instanceof IRecurringRecipeSerializer<?>)
result = ((IRecurringRecipeSerializer<R>) serializer).read(name, buffer, ingredientSerializer);
else
result = serializer.read(name, buffer);
final int recipeLength = buffer.readerIndex() - oldReadIndex;
if (readLength && expectedLength != recipeLength) {
throw new IllegalStateException(
"Recipe read " + recipeLength + " bytes, but wrote " + expectedLength + " bytes, see log for details"
);
} else {
recipeEntry.pop();
return result;
}
}
public static <T extends IRecipe<?>> void writeRecipe(
T recipe,
OptimizedPacketBuffer buffer,
IRecipeSerializer<?> serializer,
IngredientSerializer ingredientSerializer,
boolean writeLength
) {
final int writerIndexBefore = buffer.writerIndex();
buffer.writeResourceLocation(recipe.getId());
if (serializer instanceof IRecurringRecipeSerializer<?>)
((IRecurringRecipeSerializer<T>) serializer).write(buffer, recipe, ingredientSerializer);
else
((IRecipeSerializer<T>) serializer).write(buffer, recipe);
if (writeLength) {
final int readerIndexBefore = buffer.readerIndex();
final int bytesWritten = buffer.writerIndex() - writerIndexBefore;
buffer.readerIndex(writerIndexBefore);
byte[] recipeBytes = new byte[bytesWritten];
buffer.readBytes(recipeBytes);
buffer.readerIndex(readerIndexBefore);
buffer.writerIndex(writerIndexBefore);
buffer.writeVarInt(bytesWritten);
buffer.writeBytes(recipeBytes);
}
}
private static class ConfigMasks {
public static final byte RECIPE_LENGTH = 1;
}
}
|
92396e43767a80bd5cd2d35a862c6bef0b346b2a | 217 | java | Java | java/java.hints/test/unit/data/javahints/TestShortErrorsMethodInvocation1.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,056 | 2019-04-25T20:00:35.000Z | 2022-03-30T04:46:14.000Z | java/java.hints/test/unit/data/javahints/TestShortErrorsMethodInvocation1.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,846 | 2019-04-25T20:50:05.000Z | 2022-03-31T23:40:41.000Z | java/java.hints/test/unit/data/javahints/TestShortErrorsMethodInvocation1.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 550 | 2019-04-25T20:04:33.000Z | 2022-03-25T17:43:01.000Z | 16.692308 | 47 | 0.608295 | 998,821 | package javahints;
public class TestShortErrorsMethodInvocation1 {
public TestShortErrorsMethodInvocation1() {
Object o = 1;
test(o);
}
public void test(Integer i) {}
}
|
92396eadd00cf20f80751c8d0c56d932e9d9299b | 6,898 | java | Java | src/main/java/org/o3project/odenos/component/slicer/SliceConditionTable.java | o3project/odenos | 837d0d3d3c37482e843c40c5eeeac10646e68c65 | [
"Apache-2.0"
] | 26 | 2015-02-18T10:22:50.000Z | 2020-06-18T05:07:54.000Z | src/main/java/org/o3project/odenos/component/slicer/SliceConditionTable.java | o3project/odenos | 837d0d3d3c37482e843c40c5eeeac10646e68c65 | [
"Apache-2.0"
] | 45 | 2015-02-20T00:40:45.000Z | 2021-12-14T21:07:57.000Z | src/main/java/org/o3project/odenos/component/slicer/SliceConditionTable.java | o3project/odenos | 837d0d3d3c37482e843c40c5eeeac10646e68c65 | [
"Apache-2.0"
] | 30 | 2015-02-19T02:00:35.000Z | 2017-02-18T15:28:09.000Z | 26.328244 | 94 | 0.685996 | 998,822 | /*
* Copyright 2015 NEC Corporation.
*
* 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.o3project.odenos.component.slicer;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.o3project.odenos.core.logging.message.LogMessage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
/**
* SliceConditionTable for managing the order of priority SliceCondition.
*
*/
public class SliceConditionTable {
private static final Logger log = LogManager.getLogger(SliceConditionTable.class);
/**
* Constructor.
*/
public SliceConditionTable() {
}
/**
* priority tables.
* <pre>
* {@literal
* key :priority
* value :conditionIdList ["10":["slice001","slice002"] "20":["slice003","slice004"] ..]
* }
* </pre>
*/
private TreeMap<String, List<String>> priorityTables =
new TreeMap<String, List<String>>();
/**
* map of condition.
* <pre>
* {@literal
* key :conndition_id
* value : Object SliceCondition.class ["Slicer1":<matchObject>, "Slice2":<match Object>...]
* }
* </pre>
*/
private Map<String, SliceCondition> sliceConditionObjects =
new HashMap<String, SliceCondition>();
/**
* key :connection_id value :conndition_id connections["c0":["slice001",
* "slice002"], "c1":["slice003"] ..]
*/
private Map<String, List<String>> connectionTables =
new HashMap<String, List<String>>();
// priorityTables
/**
* Returns a priority table.
* @return priority table.
*/
public TreeMap<String, List<String>>
getPriorityTables() {
return priorityTables;
}
/**
* Returns list of string.
* @param priority key of the priority table.
* @return list of string.
*/
public List<String>
getConditionIdList(final String priority) {
return priorityTables.get(priority);
}
// sliceConditionObjects
/**
* Returns a slice conditions.
* @param conditionId condition ID.
* @return slice conditions.
*/
public SliceCondition
getSliceConditionObject(final String conditionId) {
return sliceConditionObjects.get(conditionId);
}
/**
* Returns condition ids.
* @param connectionId connection id.
* @return list of condition id.
*/
public List<String>
getSliceConditionIds(final String connectionId) {
List<String> conditionIds = connectionTables.get(connectionId);
if (conditionIds == null) {
conditionIds = new ArrayList<String>();
}
return conditionIds;
}
// connectionTables
protected String
getConnectionId(final String conditionId) {
SliceCondition condition = sliceConditionObjects.get(conditionId);
return condition.getConnection();
}
// Entry
/**
* add priority.
* @param priority string of priority.
* @return true if priority added.
*/
public boolean addEntryToPriorityTable(final String priority) {
if (priorityTables.containsKey(priority)) {
return false;
}
ArrayList<String> conditionList = new ArrayList<String>();
priorityTables.put(priority, conditionList);
return true;
}
/**
* add condition.
* @param priority string of priority.
* @param condition the condition to register
*/
public void addEntryToSliceCondition(
final String priority,
SliceCondition condition) {
final String conditionId = getUniqueId();
condition.setId(conditionId);
addEntryToSliceCondition(priority, conditionId, condition);
}
/**
* add condition.
* @param priority string of priority.
* @param conditionId condition ID.
* @param condition the condition to register.
*/
public void addEntryToSliceCondition(
final String priority,
final String conditionId,
final SliceCondition condition) {
final String connectionId = condition.getConnection();
if (!StringUtils.equals(conditionId, condition.getId())) {
log.warn("set condition ID: {}", conditionId);
condition.setId(connectionId);
}
// update sliceConditionObjects
sliceConditionObjects.put(conditionId, condition);
// update priorityTables
List<String> conditionIds = priorityTables.get(priority);
if (conditionIds == null) {
conditionIds = new ArrayList<String>();
priorityTables.put(priority, conditionIds);
}
conditionIds.add(conditionId);
// update connectionTables
List<String> connIds = connectionTables.get(connectionId);
if (connIds == null) {
connIds = new ArrayList<String>();
connectionTables.put(connectionId, connIds);
}
connIds.add(conditionId);
}
// Delete
/**
* Delete a condition.
* @param conditionId ID for condition.
*/
public void
deleteSliceCondition(final String conditionId) {
for (List<String> conditionIds : priorityTables.values()) {
conditionIds.remove(conditionId);
}
for (List<String> conditionIds : connectionTables.values()) {
conditionIds.remove(conditionId);
}
sliceConditionObjects.remove(conditionId);
}
/**
* Delete conditions.
* @param priority string of priority (0 - 65535: max)
*/
public void deleteSliceConditionTable(String priority) {
if (priority == null) {
throw new IllegalArgumentException("priority is null");
}
Map<String, List<String>> priorityTable = getPriorityTables();
List<String> conditionIds = new ArrayList<String>(
priorityTable.get(priority));
for (String conditionId : conditionIds) {
deleteSliceCondition(conditionId);
}
priorityTables.remove(priority);
}
/**
* Method for assigned generating UUID to ComponentConnectionID.
*
* @return id ComponentConnectionID.
*/
protected final String getUniqueId() {
String id;
do {
id = UUID.randomUUID().toString();
} while (connectionTables.containsKey(id));
return id;
}
@Override
public String toString() {
ToStringBuilder sb = new ToStringBuilder(this);
sb.append("priorityTables", priorityTables);
sb.append("connectionTables", connectionTables);
sb.append("sliceConditionObjects", sliceConditionObjects);
return sb.toString();
}
}
|
92396f55543f042236433166735a56b4d2f76899 | 2,161 | java | Java | uberfire-showcase/uberfire-webapp/src/main/java/org/uberfire/backend/server/impl/FileExplorerRootServiceImpl.java | mswiderski/uberfire | fbecc8222d7e922c43c0c8bd9490e400c289af9d | [
"Apache-2.0"
] | null | null | null | uberfire-showcase/uberfire-webapp/src/main/java/org/uberfire/backend/server/impl/FileExplorerRootServiceImpl.java | mswiderski/uberfire | fbecc8222d7e922c43c0c8bd9490e400c289af9d | [
"Apache-2.0"
] | null | null | null | uberfire-showcase/uberfire-webapp/src/main/java/org/uberfire/backend/server/impl/FileExplorerRootServiceImpl.java | mswiderski/uberfire | fbecc8222d7e922c43c0c8bd9490e400c289af9d | [
"Apache-2.0"
] | null | null | null | 26.679012 | 101 | 0.711708 | 998,823 | /*
* Copyright 2012 JBoss 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 org.uberfire.backend.server.impl;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.jboss.errai.bus.server.annotations.Service;
import org.uberfire.backend.FileExplorerRootService;
import org.uberfire.backend.Root;
import org.uberfire.backend.vfs.ActiveFileSystems;
import org.uberfire.backend.vfs.Path;
import org.uberfire.shared.mvp.impl.PathPlaceRequest;
import static java.util.Collections.*;
@Service
@ApplicationScoped
public class FileExplorerRootServiceImpl
implements
FileExplorerRootService {
protected final Set<Root> roots = new HashSet<Root>();
@Inject
@Named("fs")
private ActiveFileSystems fileSystems;
@PostConstruct
protected void init() {
setupGitRepos();
}
private void setupGitRepos() {
final Path rootPath = fileSystems.getBootstrapFileSystem().getRootDirectories().get( 0 );
final Root root = new Root( rootPath, new PathPlaceRequest( rootPath, "RepositoryEditor" ) );
roots.add( root );
}
@Override
public Collection<Root> listRoots() {
return unmodifiableSet( roots );
}
@Override
public void addRoot( final Root root ) {
roots.add( root );
}
@Override
public void removeRoot( final Root root ) {
roots.remove( root );
}
@Override
public void clear() {
roots.clear();
}
}
|
92396fd6605d3e4046f200d592a55d295d465787 | 3,432 | java | Java | src/main/java/igrad/ui/HelpWindow.java | yjskrs/main | f55ff17ef07ad824ca90a4c565ad42f8a497837a | [
"MIT"
] | null | null | null | src/main/java/igrad/ui/HelpWindow.java | yjskrs/main | f55ff17ef07ad824ca90a4c565ad42f8a497837a | [
"MIT"
] | null | null | null | src/main/java/igrad/ui/HelpWindow.java | yjskrs/main | f55ff17ef07ad824ca90a4c565ad42f8a497837a | [
"MIT"
] | null | null | null | 27.677419 | 115 | 0.535839 | 998,824 | package igrad.ui;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.logging.Logger;
import igrad.commons.core.LogsCenter;
import javafx.fxml.FXML;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.stage.Stage;
/**
* Controller for a help page.
*/
public class HelpWindow extends UiPart<Stage> {
public static final String USERGUIDE_URL = "https://ay1920s2-cs2103t-f09-3.github.io/main/";
public static final String USER_GUIDE_TITLE = "User Guide Link:";
private static final Logger logger = LogsCenter.getLogger(HelpWindow.class);
private static final String FXML = "HelpWindow.fxml";
@FXML
private Hyperlink hyperlink;
@FXML
private Label userGuide;
/**
* Creates a new HelpWindow.
*
* @param root Stage to use as the root of the HelpWindow.
*/
public HelpWindow(Stage root) {
super(FXML, root);
userGuide.setText(USER_GUIDE_TITLE);
hyperlink.setText("iGrad UG");
}
/**
* Creates a new HelpWindow.
*/
public HelpWindow() {
this(new Stage());
}
/**
* Shows the help window.
*
* @throws IllegalStateException <ul>
* <li>
* if this method is called on a thread other than the JavaFX Application Thread.
* </li>
* <li>
* if this method is called during animation or layout processing.
* </li>
* <li>
* if this method is called on the primary stage.
* </li>
* <li>
* if {@code dialogStage} is already showing.
* </li>
* </ul>
*/
public void show() {
logger.fine("Showing help page about the application.");
getRoot().show();
getRoot().centerOnScreen();
}
/**
* Returns true if the help window is currently being shown.
*/
public boolean isShowing() {
return getRoot().isShowing();
}
/**
* Hides the help window.
*/
public void hide() {
getRoot().hide();
}
/**
* Focuses on the help window.
*/
public void focus() {
getRoot().requestFocus();
}
/**
* Opens the iGrad User Guide in the user's default browser.
*/
public void openUserGuide() {
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().browse(new URI(USERGUIDE_URL));
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
}
/**
* Copies the URL to the user guide to the clipboard.
*/
@FXML
private void copyUrl() {
final Clipboard clipboard = Clipboard.getSystemClipboard();
final ClipboardContent url = new ClipboardContent();
url.putString(USERGUIDE_URL);
clipboard.setContent(url);
}
}
|
9239708a55d08864637aab1c776b5408041a734f | 3,608 | java | Java | app/src/main/java/com/priyankanandiraju/teleprompter/widget/TeleprompterWidget.java | komelio/Teleprompter-5 | 1060fa5f3258975716f68fd03b7a4dc51f402ed3 | [
"Apache-2.0"
] | 1 | 2018-08-08T22:10:09.000Z | 2018-08-08T22:10:09.000Z | app/src/main/java/com/priyankanandiraju/teleprompter/widget/TeleprompterWidget.java | komelio/Teleprompter-5 | 1060fa5f3258975716f68fd03b7a4dc51f402ed3 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/priyankanandiraju/teleprompter/widget/TeleprompterWidget.java | komelio/Teleprompter-5 | 1060fa5f3258975716f68fd03b7a4dc51f402ed3 | [
"Apache-2.0"
] | 3 | 2019-01-08T05:32:47.000Z | 2021-03-23T08:35:00.000Z | 40.088889 | 100 | 0.700665 | 998,825 | package com.priyankanandiraju.teleprompter.widget;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.preference.PreferenceManager;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import com.google.gson.Gson;
import com.priyankanandiraju.teleprompter.R;
import com.priyankanandiraju.teleprompter.utils.TeleprompterFile;
import static com.priyankanandiraju.teleprompter.utils.Constants.IMAGE_DATA;
import static com.priyankanandiraju.teleprompter.utils.Constants.SHARED_PREF_FILE;
/**
* Implementation of App Widget functionality.
*/
public class TeleprompterWidget extends AppWidgetProvider {
private static final String TAG = TeleprompterWidget.class.getSimpleName();
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
CharSequence widgetText = context.getString(R.string.app_name);
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.teleprompter_widget);
views.setTextViewText(R.id.appwidget_text, widgetText);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
if (sharedPref.contains(SHARED_PREF_FILE)) {
views.setViewVisibility(R.id.ll_content, View.VISIBLE);
views.setViewVisibility(R.id.tv_empty, View.GONE);
String jsonPrefFile = sharedPref.getString(SHARED_PREF_FILE, null);
Gson gson = new Gson();
TeleprompterFile teleprompterFile = gson.fromJson(jsonPrefFile, TeleprompterFile.class);
views.setTextViewText(R.id.file_title, teleprompterFile.getTitle());
views.setTextViewText(R.id.file_content, teleprompterFile.getContent());
String imageFileName = IMAGE_DATA + teleprompterFile.getTitle();
if (sharedPref.contains(imageFileName)) {
String previouslyEncodedImage = sharedPref.getString(imageFileName, "");
if (!previouslyEncodedImage.equalsIgnoreCase("")) {
byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
views.setImageViewBitmap(R.id.file_icon, bitmap);
} else {
views.setImageViewBitmap(R.id.file_icon, null);
}
}
} else {
Log.v(TAG, "No data");
views.setViewVisibility(R.id.ll_content, View.GONE);
views.setViewVisibility(R.id.tv_empty, View.VISIBLE);
}
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
@Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
@Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
}
|
923971faae61d2159f647bdb0b5cece201026461 | 4,181 | java | Java | servlet/mapping/src/test/java/org/javaee8/servlet/mapping/ServletMappingTest.java | SeanHayesLai/javaee8-samples | 6a688fe5a95b732c4b1f24e0d4371be1729d647b | [
"MIT"
] | 384 | 2015-01-10T19:26:51.000Z | 2022-02-21T13:14:42.000Z | servlet/mapping/src/test/java/org/javaee8/servlet/mapping/ServletMappingTest.java | SeanHayesLai/javaee8-samples | 6a688fe5a95b732c4b1f24e0d4371be1729d647b | [
"MIT"
] | 30 | 2017-08-17T11:27:10.000Z | 2022-01-21T23:22:14.000Z | servlet/mapping/src/test/java/org/javaee8/servlet/mapping/ServletMappingTest.java | SeanHayesLai/javaee8-samples | 6a688fe5a95b732c4b1f24e0d4371be1729d647b | [
"MIT"
] | 250 | 2015-01-03T13:13:46.000Z | 2022-03-31T21:58:13.000Z | 32.410853 | 102 | 0.631667 | 998,826 | package org.javaee8.servlet.mapping;
import static org.jboss.shrinkwrap.api.ShrinkWrap.create;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.URL;
import javax.servlet.http.MappingMatch;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.gargoylesoftware.htmlunit.TextPage;
import com.gargoylesoftware.htmlunit.WebClient;
/**
* @author Arjan Tijms
*/
@RunWith(Arquillian.class)
public class ServletMappingTest {
@ArquillianResource
private URL base;
private WebClient webClient;
@Deployment
public static WebArchive createDeployment() {
return create(WebArchive.class)
.addClass(Servlet.class);
}
@Before
public void setup() {
webClient = new WebClient();
}
@After
public void teardown() {
webClient.close();
}
@Test
@RunAsClient
public void testPath() throws IOException {
// Test Servet is mapped to /path/*, so name after "/path/*" can be anything
TextPage page = webClient.getPage(base + "path/foo");
String content = page.getContent();
System.out.println("\nContent for `"+ base + "path/foo" + "` :\n" + content + "\n");
assertTrue(content.contains("Mapping match:" + MappingMatch.PATH.name()));
assertTrue(content.contains("Match value:'foo'"));
assertTrue(content.contains("Pattern:'/path/*'"));
}
@Test
@RunAsClient
public void testExtension() throws IOException {
// Test Servet is mapped to *.ext, so name before ".ext" can be anything
TextPage page = webClient.getPage(base + "foo.ext");
String content = page.getContent();
System.out.println("\nContent for `"+ base + "foo.ext" + "` :\n" + content + "\n");
assertTrue(content.contains("Mapping match:" + MappingMatch.EXTENSION.name()));
assertTrue(content.contains("Match value:'foo'"));
assertTrue(content.contains("Pattern:'*.ext'"));
}
@Test
@RunAsClient
public void testRoot() throws IOException {
// Test Servet is mapped to the root of the web application
TextPage page = webClient.getPage(base);
String content = page.getContent();
System.out.println("\nContent for `"+ base + "` :\n" + content + "\n");
assertTrue(content.contains("Mapping match:" + MappingMatch.CONTEXT_ROOT.name()));
assertTrue(content.contains("Match value:''"));
assertTrue(content.contains("Pattern:''"));
}
@Test
@RunAsClient
public void testDefault() throws IOException {
// Test Servet is mapped to the "default", which is a fallback if nothing else matches
TextPage page = webClient.getPage(base + "doesnotexist");
String content = page.getContent();
System.out.println("\nContent for `"+ base + "doesnotexist" + "` :\n" + content + "\n");
assertTrue(content.contains("Mapping match:" + MappingMatch.DEFAULT.name()));
assertTrue(content.contains("Match value:''"));
assertTrue(content.contains("Pattern:'/'"));
}
@Test
@RunAsClient
public void testExact() throws IOException {
// Test Servet is mapped to an exact name ("/exact"), which is thus not a wildcard of any kind
TextPage page = webClient.getPage(base + "exact");
String content = page.getContent();
System.out.println("\nContent for `"+ base + "exact" + "` :\n" + content + "\n");
assertTrue(content.contains("Mapping match:" + MappingMatch.EXACT.name()));
assertTrue(content.contains("Match value:'exact'"));
assertTrue(content.contains("Pattern:'/exact'"));
}
}
|
92397365744524eb8acb433ec85d50d4c97dec7b | 245 | java | Java | payhelper/src/main/java/com/littleyellow/payhelper/alipay/PayIntercept.java | cunmin/PayHelperDemo | bf0f9b08af9dd72281d2f5acdbbf8ca258954160 | [
"Apache-2.0"
] | 1 | 2019-03-20T03:35:18.000Z | 2019-03-20T03:35:18.000Z | payhelper/src/main/java/com/littleyellow/payhelper/alipay/PayIntercept.java | cunmin/PayHelperDemo | bf0f9b08af9dd72281d2f5acdbbf8ca258954160 | [
"Apache-2.0"
] | null | null | null | payhelper/src/main/java/com/littleyellow/payhelper/alipay/PayIntercept.java | cunmin/PayHelperDemo | bf0f9b08af9dd72281d2f5acdbbf8ca258954160 | [
"Apache-2.0"
] | null | null | null | 15.3125 | 50 | 0.710204 | 998,827 | package com.littleyellow.payhelper.alipay;
import java.util.Map;
/**
* Created by 小黄 on 2018/4/13.
*/
public interface PayIntercept {
void onBuildParam(Map<String, String> params);
void onPayResult(Map<String, String> result);
}
|
923973d5c9e042e2bc46250c2efe50b053d8f819 | 146 | java | Java | app/src/main/java/com/zdd/td/mine/Interface/HomeHqZiXuanListener.java | uniapp10/DrawCorners | 0c0c5726ce77535b3363381c937b8df3bb7e8948 | [
"MIT"
] | null | null | null | app/src/main/java/com/zdd/td/mine/Interface/HomeHqZiXuanListener.java | uniapp10/DrawCorners | 0c0c5726ce77535b3363381c937b8df3bb7e8948 | [
"MIT"
] | null | null | null | app/src/main/java/com/zdd/td/mine/Interface/HomeHqZiXuanListener.java | uniapp10/DrawCorners | 0c0c5726ce77535b3363381c937b8df3bb7e8948 | [
"MIT"
] | null | null | null | 14.6 | 39 | 0.69863 | 998,828 | package com.zdd.td.mine.Interface;
/**
* Created by zhudongdong on 2018/7/4.
*/
public interface HomeHqZiXuanListener {
void onClick();
}
|
923974c29cc5c2e901d3eb9d9e90610774a209bc | 3,330 | java | Java | web/json/query/src/main/java/org/smallmind/web/json/query/SortField.java | zenbones/SmallMind | 3cb676e6ba1039dde69d499f2f5f197fdcffd051 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2016-03-31T04:24:49.000Z | 2022-03-20T10:07:09.000Z | web/json/query/src/main/java/org/smallmind/web/json/query/SortField.java | zenbones/SmallMind | 3cb676e6ba1039dde69d499f2f5f197fdcffd051 | [
"ECL-2.0",
"Apache-2.0"
] | 22 | 2019-11-13T03:14:55.000Z | 2022-01-04T16:43:55.000Z | web/json/query/src/main/java/org/smallmind/web/json/query/SortField.java | zenbones/SmallMind | 3cb676e6ba1039dde69d499f2f5f197fdcffd051 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2016-03-31T04:26:46.000Z | 2019-05-08T05:56:19.000Z | 27.520661 | 113 | 0.705105 | 998,829 | /*
* Copyright (c) 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 David Berkman
*
* This file is part of the SmallMind Code Project.
*
* The SmallMind Code Project is free software, you can redistribute
* it and/or modify it under either, at your discretion...
*
* 1) The terms of GNU Affero General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* ...or...
*
* 2) The terms of the Apache License, Version 2.0.
*
* The SmallMind Code Project is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License or Apache License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* and the Apache License along with the SmallMind Code Project. If not, see
* <http://www.gnu.org/licenses/> or <http://www.apache.org/licenses/LICENSE-2.0>.
*
* Additional permission under the GNU Affero GPL version 3 section 7
* ------------------------------------------------------------------
* If you modify this Program, or any covered work, by linking or
* combining it with other code, such other code is not for that reason
* alone subject to any of the requirements of the GNU Affero GPL
* version 3.
*/
package org.smallmind.web.json.query;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement(name = "field", namespace = "http://org.smallmind/web/json/query")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class SortField {
private SortDirection direction;
private String entity;
private String name;
public SortField () {
}
public SortField (String name, SortDirection direction) {
this.name = name;
this.direction = direction;
}
public SortField (String entity, String name, SortDirection direction) {
this(name, direction);
this.entity = entity;
}
public static SortField instance (String name, SortDirection direction) {
return new SortField(name, direction);
}
public static SortField instance (String entity, String name, SortDirection direction) {
return new SortField(entity, name, direction);
}
@XmlElement(name = "entity")
public String getEntity () {
return entity;
}
public void setEntity (String entity) {
this.entity = entity;
}
@XmlElement(name = "name", required = true)
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
@XmlElement(name = "direction", required = true)
@XmlJavaTypeAdapter(SortDirectionEnumXmlAdapter.class)
public SortDirection getDirection () {
return direction;
}
public void setDirection (SortDirection direction) {
this.direction = direction;
}
@Override
public int hashCode () {
return name.hashCode();
}
@Override
public boolean equals (Object obj) {
return (obj instanceof SortField) && ((SortField)obj).getName().equals(name);
}
} |
923974d1e391595eb9a3994c9c00c9bdcce3fd67 | 1,942 | java | Java | ExtraUtilitiesBuilder/src/main/java/com/rwtema/extrautils/tileentity/transfernodes/pipes/PipeEnergy.java | Robotia/ExtraUtilities | 40e8594e8c4d2f6505e86270d196059b2b06a373 | [
"MIT"
] | 6 | 2016-04-17T00:18:51.000Z | 2017-03-31T14:49:37.000Z | ExtraUtilitiesBuilder/src/main/java/com/rwtema/extrautils/tileentity/transfernodes/pipes/PipeEnergy.java | Robotia/ExtraUtilities | 40e8594e8c4d2f6505e86270d196059b2b06a373 | [
"MIT"
] | 7 | 2016-04-17T00:28:01.000Z | 2016-07-25T11:00:31.000Z | ExtraUtilitiesBuilder/src/main/java/com/rwtema/extrautils/tileentity/transfernodes/pipes/PipeEnergy.java | sameer/ExtraUtilities | 40e8594e8c4d2f6505e86270d196059b2b06a373 | [
"MIT"
] | 10 | 2017-06-30T04:48:32.000Z | 2021-09-20T11:09:17.000Z | 31.836066 | 131 | 0.694645 | 998,830 | //
// ExtraUtilities decompiled and fixed by Robotia https://github.com/Robotia
//
package com.rwtema.extrautils.tileentity.transfernodes.pipes;
import com.rwtema.extrautils.tileentity.transfernodes.BlockTransferPipe;
import net.minecraft.util.IIcon;
import net.minecraft.tileentity.TileEntity;
import com.rwtema.extrautils.tileentity.transfernodes.TNHelper;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraft.world.IBlockAccess;
public class PipeEnergy extends PipeBase
{
public PipeEnergy() {
super("Energy");
}
public PipeEnergy(final String type) {
super(type);
}
@Override
public boolean shouldConnectToTile(final IBlockAccess world, final int x, final int y, final int z, final ForgeDirection dir) {
if (TNHelper.getPipe(world, x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ) != null) {
return false;
}
final TileEntity tile = world.getTileEntity(x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ);
return TNHelper.isRFEnergy(tile, dir.getOpposite());
}
@Override
public boolean canInput(final IBlockAccess world, final int x, final int y, final int z, final ForgeDirection dir) {
final IPipe pipe = TNHelper.getPipe(world, x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ);
return pipe != null && pipe.getPipeType().startsWith("Energy");
}
@Override
public IIcon socketTexture(final ForgeDirection dir) {
return BlockTransferPipe.pipes_nozzle_energy;
}
@Override
public IIcon baseTexture() {
return BlockTransferPipe.pipes_energy;
}
@Override
public IIcon pipeTexture(final ForgeDirection dir, final boolean blocked) {
return BlockTransferPipe.pipes_energy;
}
@Override
public IIcon invPipeTexture(final ForgeDirection dir) {
return BlockTransferPipe.pipes_energy;
}
}
|
923974d4d02c127339abdce85903f191b1255188 | 1,389 | java | Java | app/src/main/java/ch/swissonid/design_lib_sample/Data.java | piyurabadiya/android-design-support-lib-sample | 01917461597cbfa46e298108ef88408b7943f51e | [
"Apache-2.0"
] | 954 | 2015-05-30T14:43:58.000Z | 2021-04-08T20:22:49.000Z | app/src/main/java/ch/swissonid/design_lib_sample/Data.java | piyurabadiya/android-design-support-lib-sample | 01917461597cbfa46e298108ef88408b7943f51e | [
"Apache-2.0"
] | 22 | 2015-06-03T01:13:11.000Z | 2016-06-18T22:36:53.000Z | app/src/main/java/ch/swissonid/design_lib_sample/Data.java | piyurabadiya/android-design-support-lib-sample | 01917461597cbfa46e298108ef88408b7943f51e | [
"Apache-2.0"
] | 160 | 2015-06-06T16:56:05.000Z | 2019-05-03T00:15:58.000Z | 29.553191 | 95 | 0.525558 | 998,831 | package ch.swissonid.design_lib_sample;
import android.support.annotation.DrawableRes;
/**
* Created by pmueller on 19.9.15.
*/
public class Data {
public static final @DrawableRes
int[] ROOT_DATA = {
R.drawable.car,
R.drawable.cross,
R.drawable.doll,
R.drawable.desert,
R.drawable.fantastic,
R.drawable.girl,
R.drawable.glass,
R.drawable.jump,
R.drawable.mens,
R.drawable.plunge,
R.drawable.shadow,
R.drawable.wall,
R.drawable.baseball,
R.drawable.beach_with_hair,
R.drawable.cat_window,
R.drawable.crying,
R.drawable.food,
R.drawable.map,
R.drawable.mini_food,
R.drawable.mirror,
R.drawable.soup
};
public static @DrawableRes int[] getData( final int amountOfImgs){
return getData(0, amountOfImgs);
}
public static @DrawableRes int[] getData(final int startPoint, final int amountOfImgs){
@DrawableRes int[] data = new int[amountOfImgs];
int j=0;
for(int i=startPoint; i<(startPoint+amountOfImgs);++i){
data[j++] = Data.ROOT_DATA[i];
}
return data;
}
}
|
9239750fc85cff5ed1c57d0453af0d45d38f2f08 | 3,419 | java | Java | zipkin-storage/cassandra/src/main/java/zipkin2/storage/cassandra/InsertTraceByServiceRemoteService.java | arioko/zipkin | 17e7a73436bb6c48fdab4f1db2aea4513ce806e4 | [
"Apache-2.0"
] | 2 | 2021-05-14T13:20:48.000Z | 2021-05-14T13:20:54.000Z | zipkin-storage/cassandra/src/main/java/zipkin2/storage/cassandra/InsertTraceByServiceRemoteService.java | arioko/zipkin | 17e7a73436bb6c48fdab4f1db2aea4513ce806e4 | [
"Apache-2.0"
] | 2 | 2020-08-01T11:40:33.000Z | 2020-08-01T11:48:12.000Z | zipkin-storage/cassandra/src/main/java/zipkin2/storage/cassandra/InsertTraceByServiceRemoteService.java | arioko/zipkin | 17e7a73436bb6c48fdab4f1db2aea4513ce806e4 | [
"Apache-2.0"
] | 1 | 2020-12-29T03:41:41.000Z | 2020-12-29T03:41:41.000Z | 33.519608 | 100 | 0.730038 | 998,832 | /*
* Copyright 2015-2019 The OpenZipkin Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package zipkin2.storage.cassandra;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.ResultSetFuture;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.google.auto.value.AutoValue;
import java.util.UUID;
import zipkin2.Call;
import zipkin2.storage.cassandra.internal.call.ResultSetFutureCall;
import static zipkin2.storage.cassandra.Schema.TABLE_TRACE_BY_SERVICE_REMOTE_SERVICE;
final class InsertTraceByServiceRemoteService extends ResultSetFutureCall<Void> {
@AutoValue abstract static class Input {
abstract String service();
abstract String remote_service();
abstract int bucket();
abstract UUID ts();
abstract String trace_id();
}
static class Factory {
final Session session;
final PreparedStatement preparedStatement;
final boolean strictTraceId;
Factory(Session session, boolean strictTraceId) {
this.session = session;
this.preparedStatement =
session.prepare(QueryBuilder.insertInto(TABLE_TRACE_BY_SERVICE_REMOTE_SERVICE)
.value("service", QueryBuilder.bindMarker("service"))
.value("remote_service", QueryBuilder.bindMarker("remote_service"))
.value("bucket", QueryBuilder.bindMarker("bucket"))
.value("ts", QueryBuilder.bindMarker("ts"))
.value("trace_id", QueryBuilder.bindMarker("trace_id")));
this.strictTraceId = strictTraceId;
}
Input newInput(String service, String remote_service, int bucket, UUID ts, String trace_id) {
return new AutoValue_InsertTraceByServiceRemoteService_Input(
service,
remote_service,
bucket,
ts,
!strictTraceId && trace_id.length() == 32 ? trace_id.substring(16) : trace_id);
}
Call<Void> create(Input input) {
return new InsertTraceByServiceRemoteService(this, input);
}
}
final Factory factory;
final Input input;
InsertTraceByServiceRemoteService(Factory factory, Input input) {
this.factory = factory;
this.input = input;
}
@Override protected ResultSetFuture newFuture() {
return factory.session.executeAsync(factory.preparedStatement.bind()
.setString("service", input.service())
.setString("remote_service", input.remote_service())
.setInt("bucket", input.bucket())
.setUUID("ts", input.ts())
.setString("trace_id", input.trace_id()));
}
@Override public Void map(ResultSet input) {
return null;
}
@Override public String toString() {
return input.toString().replace("Input", "InsertTraceByServiceRemoteService");
}
@Override public InsertTraceByServiceRemoteService clone() {
return new InsertTraceByServiceRemoteService(factory, input);
}
}
|
9239763ef0e4e741846f02a44c0b257e0d945bdd | 2,465 | java | Java | flume-websocket/src/main/java/com/sequenceiq/samples/flume/server/JettyWebSocketServer.java | sequenceiq/sequenceiq-samples | 228b9f01dc12ab679d52fbae0a2104a6cfea6415 | [
"Apache-2.0"
] | 92 | 2015-01-10T08:47:17.000Z | 2021-03-07T10:47:23.000Z | flume-websocket/src/main/java/com/sequenceiq/samples/flume/server/JettyWebSocketServer.java | sequenceiq/sequenceiq-samples | 228b9f01dc12ab679d52fbae0a2104a6cfea6415 | [
"Apache-2.0"
] | 2 | 2015-04-16T12:50:32.000Z | 2015-08-31T20:14:42.000Z | flume-websocket/src/main/java/com/sequenceiq/samples/flume/server/JettyWebSocketServer.java | sequenceiq/sequenceiq-samples | 228b9f01dc12ab679d52fbae0a2104a6cfea6415 | [
"Apache-2.0"
] | 46 | 2015-01-13T12:01:31.000Z | 2018-07-10T12:50:52.000Z | 34.71831 | 111 | 0.708316 | 998,833 | package com.sequenceiq.samples.flume.server;
import org.apache.flume.channel.ChannelProcessor;
import org.eclipse.jetty.server.*;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.ssl.SslContextFactory;
/**
* @author keyki
*/
public class JettyWebSocketServer implements WebSocketServer {
private final String host;
private final int port;
private final String path;
private final ChannelProcessor channelProcessor;
public JettyWebSocketServer(String host, int port, String path, ChannelProcessor channelProcessor) {
this.host = host;
this.port = port;
this.path = path;
this.channelProcessor = channelProcessor;
}
@Override
public void start() throws Exception {
Server server = new Server();
ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(new HttpConfiguration()));
http.setHost(host);
http.setPort(port);
server.setConnectors(new Connector[]{http});
configureContextHandler(server);
startServer(server);
}
private void configureContextHandler(Server server) {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.addServlet(new ServletHolder(new JettyWebSocketServlet(channelProcessor)), path);
context.setContextPath("/");
server.setHandler(context);
}
@Override
public void startSSL(String keyStoreLocation, String keyStorePassword) throws Exception {
Server server = new Server();
HttpConfiguration httpsConfig = new HttpConfiguration();
httpsConfig.addCustomizer(new SecureRequestCustomizer());
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(keyStoreLocation);
sslContextFactory.setKeyStorePassword(keyStorePassword);
ServerConnector https = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory, "http/1.1"),
new HttpConnectionFactory(httpsConfig));
https.setHost(host);
https.setPort(port);
server.setConnectors(new Connector[]{https});
configureContextHandler(server);
startServer(server);
}
private void startServer(Server server) throws Exception {
server.start();
server.join();
}
}
|
923976aa80de4b40dbe403db6fb725cfd4b7dc31 | 2,673 | java | Java | src/main/java/at/ac/ait/lablink/core/connection/dispatching/IRootDispatcher.java | AIT-Lablink/lablink-core-java | 6d18cb405e6b05ebb3c2fdecd4910c82eee0e17b | [
"BSD-3-Clause"
] | null | null | null | src/main/java/at/ac/ait/lablink/core/connection/dispatching/IRootDispatcher.java | AIT-Lablink/lablink-core-java | 6d18cb405e6b05ebb3c2fdecd4910c82eee0e17b | [
"BSD-3-Clause"
] | 1 | 2021-03-30T11:30:36.000Z | 2021-04-07T16:28:23.000Z | src/main/java/at/ac/ait/lablink/core/connection/dispatching/IRootDispatcher.java | AIT-Lablink/lablink-core-java | 6d18cb405e6b05ebb3c2fdecd4910c82eee0e17b | [
"BSD-3-Clause"
] | null | null | null | 37.647887 | 99 | 0.742237 | 998,834 | //
// Copyright (c) AIT Austrian Institute of Technology GmbH.
// Distributed under the terms of the Modified BSD License.
//
package at.ac.ait.lablink.core.connection.dispatching;
import at.ac.ait.lablink.core.connection.mqtt.IMqttConnectionListener;
import at.ac.ait.lablink.core.connection.mqtt.IMqttReceiverCallback;
import at.ac.ait.lablink.core.connection.mqtt.IMqttSubscriber;
import java.util.List;
/**
* Interface for a root dispatcher.
*
* <p>The root dispatcher is used to manage other dispatcher units. It should also implement the
* connection to the low level Mqtt communication. Therefore it must implement the
* {@link IMqttReceiverCallback} and {@link IMqttConnectionListener} interfaces. The Mqtt client
* will use these interfaces to inform the Root Dispatcher about connection changes or received
* messages. The root dispatcher can also use a {@link IMqttSubscriber} to subscribe or unsubscribe
* topics to/from the Mqtt broker.
*/
public interface IRootDispatcher extends IMqttReceiverCallback, IMqttConnectionListener {
/**
* Add a dispatcher to the IRootDispatcher.
*
* @param subscription List of topic elements that points to the requested dispatcher to be
* add.
* @param node Dispatcher to be added
*/
void addDispatcher(List<String> subscription, IDispatcherInterface node);
/**
* Remove a dispatcher from the IRootDispatcher.
*
* @param subscription List of topic elements that points to the requested dispatcher to be
* deleted.
*/
void removeDispatcher(List<String> subscription);
/**
* Check if the IRootDispatcher contains a registered dispatcher with the given full dispatcher
* name.
*
* @param dispatcherName List of topic elements that points to the requested dispatcher.
* @return true if a dispatcher is already registered
*/
boolean hasDispatcher(List<String> dispatcherName);
/**
* Get an already registered dispatcher from the IRootDispatcher.
*
* <p>If no dispatcher with the given name is registered in the IRootDispatcher the method will
* return null.
*
* @param dispatcherName List of topic elements that points to the requested dispatcher.
* @return The method will return a registered dispatcher, if it exists.
*/
IDispatcherInterface getDispatcher(List<String> dispatcherName);
/**
* Add a IMqttSubscriber to the root dispatcher. This subscriber will be used to subscribe and
* unsubscribe topics to/from the MQTT broker.
*
* @param mqttSubscriber to be stored in the IRootDispatcher.
*/
void setMqttSubscriber(IMqttSubscriber mqttSubscriber);
}
|
923976e93592d57feea6c526f5340ced3f67aae4 | 186 | java | Java | common-library/src/main/java/com/common/api/core/InitViews.java | SavorGit/Hotspot-Operation | 58e53b11321cae69bd7ca93cd6cbe46a9f53e79a | [
"Apache-2.0"
] | 3 | 2017-08-23T01:39:02.000Z | 2020-08-06T14:05:25.000Z | common-library/src/main/java/com/common/api/core/InitViews.java | SavorGit/Hotspot-Operation | 58e53b11321cae69bd7ca93cd6cbe46a9f53e79a | [
"Apache-2.0"
] | null | null | null | common-library/src/main/java/com/common/api/core/InitViews.java | SavorGit/Hotspot-Operation | 58e53b11321cae69bd7ca93cd6cbe46a9f53e79a | [
"Apache-2.0"
] | null | null | null | 16.909091 | 28 | 0.672043 | 998,835 | package com.common.api.core;
/**初始化页面*/
public interface InitViews {
/**关联控件*/
public void getViews();
/**初始化控件*/
public void setViews();
/**设置监听事件*/
public void setListeners();
}
|
923976f986196d9d860bbfad34c2a80b565c10d4 | 565 | java | Java | mureng-core/src/main/java/net/mureng/core/member/entity/FcmToken.java | YAPP-18th/Android-Team-1-Backend | 0bd9348522ced1fb443fbee756518b99756d438a | [
"Apache-2.0"
] | 11 | 2021-03-26T06:36:37.000Z | 2021-12-14T14:52:47.000Z | mureng-core/src/main/java/net/mureng/core/member/entity/FcmToken.java | YAPP-18th/Android-Team-1-Backend | 0bd9348522ced1fb443fbee756518b99756d438a | [
"Apache-2.0"
] | 124 | 2021-04-06T15:43:19.000Z | 2021-12-18T10:02:50.000Z | mureng-core/src/main/java/net/mureng/core/member/entity/FcmToken.java | YAPP-18th/Android-Team-1-Backend | 0bd9348522ced1fb443fbee756518b99756d438a | [
"Apache-2.0"
] | 2 | 2021-03-26T13:26:11.000Z | 2021-04-08T07:30:08.000Z | 20.178571 | 55 | 0.711504 | 998,836 | package net.mureng.core.member.entity;
import lombok.*;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Getter @Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "fcm_token")
public class FcmToken {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "idx", nullable = false)
private Long idx;
@OneToOne
@JoinColumn(name = "member_id", unique = true)
private Member member;
@NotNull
@Column(nullable = false, unique = true)
private String token;
}
|
923977614ee09804476ede37b7f8199a6826472f | 3,714 | java | Java | geronimo-jaxrpc_1.1_spec/src/main/java/javax/xml/rpc/handler/HandlerInfo.java | christopher-johnson/geronimo-specs | 4ca1c22f158aa2de15daf4281409694e47f84178 | [
"Apache-2.0"
] | 16 | 2015-02-04T03:40:21.000Z | 2022-01-05T02:48:32.000Z | geronimo-jaxrpc_1.1_spec/src/main/java/javax/xml/rpc/handler/HandlerInfo.java | christopher-johnson/geronimo-specs | 4ca1c22f158aa2de15daf4281409694e47f84178 | [
"Apache-2.0"
] | 10 | 2015-01-04T19:18:46.000Z | 2020-10-15T10:34:43.000Z | geronimo-jaxrpc_1.1_spec/src/main/java/javax/xml/rpc/handler/HandlerInfo.java | christopher-johnson/geronimo-specs | 4ca1c22f158aa2de15daf4281409694e47f84178 | [
"Apache-2.0"
] | 34 | 2015-02-04T12:46:04.000Z | 2022-03-09T14:42:19.000Z | 29.244094 | 73 | 0.645934 | 998,837 | /*
* 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 javax.xml.rpc.handler;
import javax.xml.namespace.QName;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* The <code>javax.xml.rpc.handler.HandlerInfo</code> represents
* information about a handler in the HandlerChain. A HandlerInfo
* instance is passed in the <code>Handler.init</code> method to
* initialize a <code>Handler</code> instance.
*
* @version $Rev$ $Date$
* @see HandlerChain
*/
public class HandlerInfo implements Serializable {
/** Default constructor. */
public HandlerInfo() {
handlerClass = null;
config = new HashMap();
}
/**
* Constructor for HandlerInfo.
*
* @param handlerClass Java Class for the Handler
* @param config Handler Configuration as a java.util.Map
* @param headers QNames for the header blocks processed
* by this Handler. QName is the qualified name
* of the outermost element of a header block
*/
public HandlerInfo(Class handlerClass, Map config, QName[] headers) {
this.handlerClass = handlerClass;
this.config = config;
this.headers = headers;
}
/**
* Sets the Handler class.
*
* @param handlerClass Class for the Handler
*/
public void setHandlerClass(Class handlerClass) {
this.handlerClass = handlerClass;
}
/**
* Gets the Handler class.
*
* @return Returns null if no Handler class has been
* set; otherwise the set handler class
*/
public Class getHandlerClass() {
return handlerClass;
}
/**
* Sets the Handler configuration as <code>java.util.Map</code>
* @param config Configuration map
*/
public void setHandlerConfig(Map config) {
this.config = config;
}
/**
* Gets the Handler configuration.
*
* @return Returns empty Map if no configuration map
* has been set; otherwise returns the set configuration map
*/
public Map getHandlerConfig() {
return config;
}
/**
* Sets the header blocks processed by this Handler.
* @param headers QNames of the header blocks. QName
* is the qualified name of the outermost
* element of the SOAP header block
*/
public void setHeaders(QName[] headers) {
this.headers = headers;
}
/**
* Gets the header blocks processed by this Handler.
* @return Array of QNames for the header blocks. Returns
* <code>null</code> if no header blocks have been
* set using the <code>setHeaders</code> method.
*/
public QName[] getHeaders() {
return headers;
}
/** Handler Class. */
private Class handlerClass;
/** Configuration Map. */
private Map config;
/** Headers. */
private QName[] headers;
}
|
9239785e2c1201652581678d0e8abd15cd525b47 | 2,224 | java | Java | token_lib/src/main/java/com/wallet/tokenlib/common/crypto/SCryptParams.java | xinshuhao/Btc-Eth-Wicc-Wallet | d7d1871e44b13f0eeb6352b80cb16b73f54cc03e | [
"Apache-2.0"
] | null | null | null | token_lib/src/main/java/com/wallet/tokenlib/common/crypto/SCryptParams.java | xinshuhao/Btc-Eth-Wicc-Wallet | d7d1871e44b13f0eeb6352b80cb16b73f54cc03e | [
"Apache-2.0"
] | null | null | null | token_lib/src/main/java/com/wallet/tokenlib/common/crypto/SCryptParams.java | xinshuhao/Btc-Eth-Wicc-Wallet | d7d1871e44b13f0eeb6352b80cb16b73f54cc03e | [
"Apache-2.0"
] | null | null | null | 19.681416 | 83 | 0.602968 | 998,838 | package com.wallet.tokenlib.common.crypto;
import com.google.common.base.Strings;
import com.wallet.tokenlib.common.exception.Messages;
import com.wallet.tokenlib.common.exception.TokenException;
public class SCryptParams implements KDFParams {
static final int COST_FACTOR = 8192;
static final int BLOCK_SIZE_FACTOR = 8;
static final int PARALLELIZATION_FACTOR = 1;
private int dklen = 0;
private int n = 0;
private int p = 0;
private int r = 0;
private String salt;
public SCryptParams() {
}
public static SCryptParams createSCryptParams() {
SCryptParams params = new SCryptParams();
params.dklen = DK_LEN;
params.n = COST_FACTOR;
params.p = PARALLELIZATION_FACTOR;
params.r = BLOCK_SIZE_FACTOR;
return params;
}
public int getDklen() {
return dklen;
}
public void setDklen(int dklen) {
this.dklen = dklen;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
public int getP() {
return p;
}
public void setP(int p) {
this.p = p;
}
public int getR() {
return r;
}
public void setR(int r) {
this.r = r;
}
public String getSalt() {
return salt;
}
@Override
public void validate() {
if (n == 0 || dklen == 0 || p == 0 || r == 0 || Strings.isNullOrEmpty(salt)) {
throw new TokenException(Messages.KDF_PARAMS_INVALID);
}
}
public void setSalt(String salt) {
this.salt = salt;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof SCryptParams)) {
return false;
}
SCryptParams that = (SCryptParams) o;
if (dklen != that.dklen) {
return false;
}
if (n != that.n) {
return false;
}
if (p != that.p) {
return false;
}
if (r != that.r) {
return false;
}
return getSalt() != null
? getSalt().equals(that.getSalt()) : that.getSalt() == null;
}
@Override
public int hashCode() {
int result = dklen;
result = 31 * result + n;
result = 31 * result + p;
result = 31 * result + r;
result = 31 * result + (getSalt() != null ? getSalt().hashCode() : 0);
return result;
}
}
|
9239788e80a0475f7542dc7ffed68f0108836f3c | 6,224 | java | Java | modules/yardstick/src/main/java/org/apache/ignite/yardstick/sql/IgniteInlineIndexBenchmark.java | liyuj/gridgain | 9505c0cfd7235210993b2871b17f15acf7d3dcd4 | [
"CC0-1.0"
] | 218 | 2015-01-04T13:20:55.000Z | 2022-03-28T05:28:55.000Z | modules/yardstick/src/main/java/org/apache/ignite/yardstick/sql/IgniteInlineIndexBenchmark.java | liyuj/gridgain | 9505c0cfd7235210993b2871b17f15acf7d3dcd4 | [
"CC0-1.0"
] | 175 | 2015-02-04T23:16:56.000Z | 2022-03-28T18:34:24.000Z | modules/yardstick/src/main/java/org/apache/ignite/yardstick/sql/IgniteInlineIndexBenchmark.java | liyuj/gridgain | 9505c0cfd7235210993b2871b17f15acf7d3dcd4 | [
"CC0-1.0"
] | 93 | 2015-01-06T20:54:23.000Z | 2022-03-31T08:09:00.000Z | 31.593909 | 112 | 0.595276 | 998,839 | /*
* Copyright 2019 GridGain Systems, Inc. and Contributors.
*
* Licensed under the GridGain Community Edition License (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.gridgain.com/products/software/community-edition/gridgain-community-edition-license
*
* 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.ignite.yardstick.sql;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.ignite.IgniteDataStreamer;
import org.apache.ignite.IgniteSemaphore;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.yardstick.IgniteAbstractBenchmark;
import org.yardstickframework.BenchmarkConfiguration;
import static org.yardstickframework.BenchmarkUtils.println;
/**
* Ignite benchmark that performs query operations with joins.
*/
public class IgniteInlineIndexBenchmark extends IgniteAbstractBenchmark {
/**
* Enum of key types possible for testing
*/
private enum TestedType {
/** */
JAVA_OBJECT,
/** */
PRIMITIVE,
/** */
DECIMAL,
/** */
LARGE_DECIMAL,
/** */
SMALL_DECIMAL
}
/* List of double keys generated before execution */
private final List<Double> doubleKeys = new ArrayList<>();
/** Cache name for benchmark. */
private String cacheName;
/** */
private Class<?> keyCls;
/** How many entries should be preloaded and within which range. */
private int range;
/** Type of the key object for the test */
private TestedType testedType;
/** {@inheritDoc} */
@Override public void setUp(BenchmarkConfiguration cfg) throws Exception {
super.setUp(cfg);
range = args.range();
testedType = TestedType.valueOf(args.getStringParameter("testedType", TestedType.PRIMITIVE.toString()));
switch (testedType) {
case JAVA_OBJECT:
cacheName = "CACHE_POJO";
keyCls = TestKey.class;
break;
case PRIMITIVE:
cacheName = "CACHE_LONG";
keyCls = Integer.class;
break;
case DECIMAL:
generateDoublekeys(doubleKeys);
cacheName = "CACHE_DECIMAL";
keyCls = BigDecimal.class;
break;
case LARGE_DECIMAL:
generateDoublekeys(doubleKeys);
cacheName = "CACHE_LARGE_DECIMAL";
keyCls = BigDecimal.class;
break;
case SMALL_DECIMAL:
generateDoublekeys(doubleKeys);
cacheName = "CACHE_SMALL_DECIMAL";
keyCls = BigDecimal.class;
break;
default:
throw new Exception(testedType + "is not expected type");
}
printParameters();
IgniteSemaphore sem = ignite().semaphore("setup", 1, true, true);
try {
if (sem.tryAcquire()) {
println(cfg, "Create tables...");
init();
}
else {
// Acquire (wait setup by other client) and immediately release/
println(cfg, "Waits for setup...");
sem.acquire();
}
}
finally {
sem.release();
}
}
private void generateDoublekeys(List<Double> keys) {
while (keys.size() < range)
keys.add(ThreadLocalRandom.current().nextDouble(range));
}
/**
*
*/
private void init() {
ignite().createCache(
new CacheConfiguration<Object, Integer>(cacheName)
.setIndexedTypes(keyCls, Integer.class)
);
println(cfg, "Populate cache: " + cacheName + ", range: " + range);
try (IgniteDataStreamer<Object, Integer> stream = ignite().dataStreamer(cacheName)) {
stream.allowOverwrite(false);
for (long k = 0; k < range; ++k)
stream.addData(nextKey(), ThreadLocalRandom.current().nextInt());
}
println(cfg, "Cache populated: " + cacheName);
}
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
ignite().<Object, Integer>cache(cacheName).put(nextKey(), ThreadLocalRandom.current().nextInt());
return true;
}
/** Creates next random key. */
private Object nextKey() {
switch (testedType) {
case JAVA_OBJECT:
return new TestKey(ThreadLocalRandom.current().nextInt(range));
case PRIMITIVE:
return ThreadLocalRandom.current().nextInt(range);
case DECIMAL:
return BigDecimal.valueOf(doubleKeys.get(ThreadLocalRandom.current().nextInt(range)));
case LARGE_DECIMAL:
return BigDecimal.valueOf(doubleKeys.get(ThreadLocalRandom.current().nextInt(range))).pow(3);
case SMALL_DECIMAL:
// low enough to use intCompact of BigDecimal
return BigDecimal.valueOf(doubleKeys.get(ThreadLocalRandom.current().nextInt(range))).
divide(BigDecimal.TEN, RoundingMode.HALF_DOWN).setScale(2, RoundingMode.HALF_UP);
default:
return null;
}
}
/** */
private void printParameters() {
println("Benchmark parameter:");
println(" range: " + range);
println(" testedType: " + testedType);
}
/** Pojo that used as key value for object's inlining benchmark. */
static class TestKey {
/** */
private final int id;
/** */
public TestKey(int id) {
this.id = id;
}
}
}
|
923978b65d4ce05c2deaf86bb3cb133253a6ddd6 | 8,237 | java | Java | src/main/java/ru/org/linux/search/SearchController.java | BALURAM1226/lorsource | e2243d32c02a2327e5a747e9558b0ef467d8f183 | [
"Apache-2.0"
] | 141 | 2015-01-02T21:54:40.000Z | 2022-03-27T10:21:07.000Z | src/main/java/ru/org/linux/search/SearchController.java | BALURAM1226/lorsource | e2243d32c02a2327e5a747e9558b0ef467d8f183 | [
"Apache-2.0"
] | 225 | 2015-01-19T21:15:27.000Z | 2022-03-31T09:35:41.000Z | src/main/java/ru/org/linux/search/SearchController.java | BALURAM1226/lorsource | e2243d32c02a2327e5a747e9558b0ef467d8f183 | [
"Apache-2.0"
] | 156 | 2015-03-31T21:36:18.000Z | 2022-02-24T20:51:07.000Z | 34.320833 | 138 | 0.690178 | 998,840 | /*
* Copyright 1998-2019 Linux.org.ru
* 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 ru.org.linux.search;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.ImmutableSortedMap;
import com.sksamuel.elastic4s.http.ElasticClient;
import com.sksamuel.elastic4s.http.search.FilterAggregationResult;
import com.sksamuel.elastic4s.http.search.SearchResponse;
import com.sksamuel.elastic4s.http.search.TermBucket;
import com.sksamuel.elastic4s.http.search.TermsAggResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import ru.org.linux.group.Group;
import ru.org.linux.group.GroupDao;
import ru.org.linux.search.SearchEnums.SearchInterval;
import ru.org.linux.search.SearchEnums.SearchRange;
import ru.org.linux.section.Section;
import ru.org.linux.section.SectionService;
import ru.org.linux.user.User;
import ru.org.linux.user.UserPropertyEditor;
import ru.org.linux.user.UserService;
import ru.org.linux.util.ExceptionBindingErrorProcessor;
import scala.None$;
import scala.Option;
import scala.Tuple2;
import java.beans.PropertyEditorSupport;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
@Controller
public class SearchController {
@Autowired
private SectionService sectionService;
@Autowired
private UserService userService;
@Autowired
private GroupDao groupDao;
@Autowired
private ElasticClient client;
@Autowired
private SearchResultsService resultsService;
@ModelAttribute("sorts")
public static Map<String, String> getSorts() {
Builder<String, String> builder = ImmutableMap.builder(); // preserves order!
for (SearchOrder value : SearchOrder$.MODULE$.jvalues()) {
builder.put(value.id(), value.name());
}
return builder.build();
}
@ModelAttribute("intervals")
public static Map<SearchInterval, String> getIntervals() {
Builder<SearchInterval, String> builder = ImmutableSortedMap.naturalOrder();
for (SearchInterval value : SearchInterval.values()) {
builder.put(value, value.getTitle());
}
return builder.build();
}
@ModelAttribute("ranges")
public static Map<SearchRange, String> getRanges() {
Builder<SearchRange, String> builder = ImmutableSortedMap.naturalOrder();
for (SearchRange value : SearchRange.values()) {
builder.put(value, value.getTitle());
}
return builder.build();
}
@RequestMapping(value = "/search.jsp", method = {RequestMethod.GET, RequestMethod.HEAD})
public String search(
Model model,
@ModelAttribute("query") SearchRequest query,
BindingResult bindingResult
) {
Map<String, Object> params = model.asMap();
if (!query.isInitial() && !bindingResult.hasErrors()) {
sanitizeQuery(query);
SearchViewer sv = new SearchViewer(query, client);
SearchResponse response = sv.performSearch();
long current = System.currentTimeMillis();
Collection<SearchItem> res = resultsService.prepareAll(Arrays.asList(response.hits().hits()));
if (response.aggregations() != null) {
FilterAggregationResult countFacet = response.aggregations().filter("sections");
TermsAggResult sectionsFacet = countFacet.terms("sections");
if (sectionsFacet.getBuckets().size()>1 || !Strings.isNullOrEmpty(query.getSection())) {
params.put("sectionFacet", resultsService.buildSectionFacet(countFacet, Option.apply(Strings.emptyToNull(query.getSection()))));
if (!Strings.isNullOrEmpty(query.getSection())) {
Option<TermBucket> selectedSection = sectionsFacet.bucketOpt(query.getSection());
if (!Strings.isNullOrEmpty(query.getGroup())) {
params.put("groupFacet", resultsService.buildGroupFacet(
selectedSection, Option.apply(Tuple2.apply(query.getSection(), query.getGroup()))
));
} else {
params.put("groupFacet", resultsService.buildGroupFacet(selectedSection, None$.empty()));
}
}
} else if (Strings.isNullOrEmpty(query.getSection()) && sectionsFacet.buckets().size()==1) {
TermBucket onlySection = sectionsFacet.buckets().head();
query.setSection(onlySection.key());
params.put("groupFacet", resultsService.buildGroupFacet(Option.apply(onlySection), None$.empty()));
}
params.put("tags", resultsService.foundTags(response.aggregations()));
}
long time = System.currentTimeMillis() - current;
params.put("result", res);
params.put("searchTime", response.took());
params.put("numFound", response.totalHits());
if (response.totalHits() > query.getOffset() + SearchViewer.SearchRows()) {
params.put("nextLink", "/search.jsp?" + query.getQuery(query.getOffset() + SearchViewer.SearchRows()));
}
if (query.getOffset() - SearchViewer.SearchRows() >= 0) {
params.put("prevLink", "/search.jsp?" + query.getQuery(query.getOffset() - SearchViewer.SearchRows()));
}
params.put("time", time);
}
return "search";
}
private void sanitizeQuery(SearchRequest query) {
if (!Strings.isNullOrEmpty(query.getSection())) {
Option<Section> section = sectionService.fuzzyNameToSection().get(query.getSection());
if (section.isDefined()) {
query.setSection(section.get().getUrlName());
if (!Strings.isNullOrEmpty(query.getGroup())) {
Optional<Group> group = groupDao.getGroupOpt(section.get(), query.getGroup(), true);
if (group.isEmpty()) {
query.setGroup("");
} else {
query.setGroup(group.get().getUrlName());
}
} else {
query.setGroup("");
}
} else {
query.setSection("");
query.setGroup("");
}
} else {
query.setGroup("");
query.setSection("");
}
}
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(SearchOrder.class, new PropertyEditorSupport() {
@Override
public void setAsText(String s) throws IllegalArgumentException {
switch (s) {
case "1": // for old links
setValue(SearchOrder.Relevance$.MODULE$);
break;
case "2":
setValue(SearchOrder.Date$.MODULE$);
break;
default:
setValue(SearchOrder$.MODULE$.valueOf(s));
break;
}
}
});
binder.registerCustomEditor(SearchInterval.class, new PropertyEditorSupport() {
@Override
public void setAsText(String s) throws IllegalArgumentException {
setValue(SearchInterval.valueOf(s.toUpperCase()));
}
});
binder.registerCustomEditor(SearchRange.class, new PropertyEditorSupport() {
@Override
public void setAsText(String s) throws IllegalArgumentException {
setValue(SearchRange.valueOf(s.toUpperCase()));
}
});
binder.registerCustomEditor(User.class, new UserPropertyEditor(userService));
binder.setBindingErrorProcessor(new ExceptionBindingErrorProcessor());
}
}
|
92397900ae4a281fdea508093d6a44a5210a914d | 2,494 | java | Java | puree/src/main/java/com/mercari/puree/outputs/PureeOutput.java | mercari/puree-android | 500874bd42eebb6dea495824951734a9faeeffd1 | [
"MIT"
] | 2 | 2019-03-09T01:00:13.000Z | 2019-05-20T10:14:48.000Z | puree/src/main/java/com/mercari/puree/outputs/PureeOutput.java | mercari/puree-android | 500874bd42eebb6dea495824951734a9faeeffd1 | [
"MIT"
] | 1 | 2019-06-06T07:52:55.000Z | 2019-06-12T04:49:05.000Z | puree/src/main/java/com/mercari/puree/outputs/PureeOutput.java | mercari/puree-android | 500874bd42eebb6dea495824951734a9faeeffd1 | [
"MIT"
] | null | null | null | 26.531915 | 85 | 0.683641 | 998,841 | package com.mercari.puree.outputs;
import com.mercari.puree.PureeFilter;
import com.google.gson.JsonObject;
import com.mercari.puree.PureeLogger;
import com.mercari.puree.TagPattern;
import com.mercari.puree.storage.PureeStorage;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
@ParametersAreNonnullByDefault
public abstract class PureeOutput {
protected OutputConfiguration conf;
protected PureeStorage storage;
protected List<PureeFilter> filters = new ArrayList<>();
public void registerFilter(PureeFilter filter) {
filters.add(filter);
}
public PureeOutput withFilters(PureeFilter... filters) {
Collections.addAll(this.filters, filters);
return this;
}
public PureeOutput withFilters(Collection<PureeFilter> filters) {
this.filters.addAll(filters);
return this;
}
public List<PureeFilter> getFilters() {
return filters;
}
public void initialize(PureeLogger logger) {
this.storage = logger.getStorage();
OutputConfiguration defaultConfiguration = new OutputConfiguration();
this.conf = configure(defaultConfiguration);
}
public void receive(JsonObject jsonLog) {
final JsonObject filteredLog = applyFilters(jsonLog);
if (filteredLog == null) {
return;
}
emit(filteredLog);
}
/**
* Override this method in order to provide your own TagPattern.
* Please use {@link com.mercari.puree.TagPattern#fromString(String)} to generate
* a proper tag pattern.
*/
@Nonnull
public TagPattern getTagPattern() {
return TagPattern.getDefaultInstance();
}
@Nullable
protected JsonObject applyFilters(JsonObject jsonLog) {
JsonObject filteredLog = jsonLog;
for (PureeFilter filter : filters) {
filteredLog = filter.apply(filteredLog);
if (filteredLog == null) {
return null;
}
}
return filteredLog;
}
public void flush() {
// do nothing because PureeOutput don't have any buffers.
}
@Nonnull
public abstract String type();
@Nonnull
public abstract OutputConfiguration configure(OutputConfiguration conf);
public abstract void emit(JsonObject jsonLog);
}
|
923979306649021d83066882512396157ca9a1ce | 3,051 | java | Java | modules/rank-eval/src/main/java/org/elasticsearch/index/rankeval/RankEvalNamedXContentProvider.java | diwasjoshi/elasticsearch | 58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f | [
"Apache-2.0"
] | null | null | null | modules/rank-eval/src/main/java/org/elasticsearch/index/rankeval/RankEvalNamedXContentProvider.java | diwasjoshi/elasticsearch | 58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f | [
"Apache-2.0"
] | null | null | null | modules/rank-eval/src/main/java/org/elasticsearch/index/rankeval/RankEvalNamedXContentProvider.java | diwasjoshi/elasticsearch | 58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f | [
"Apache-2.0"
] | null | null | null | 38.620253 | 140 | 0.654539 | 998,842 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.index.rankeval;
import org.elasticsearch.plugins.spi.NamedXContentProvider;
import org.elasticsearch.xcontent.NamedXContentRegistry;
import org.elasticsearch.xcontent.ParseField;
import java.util.ArrayList;
import java.util.List;
public class RankEvalNamedXContentProvider implements NamedXContentProvider {
@Override
public List<NamedXContentRegistry.Entry> getNamedXContentParsers() {
List<NamedXContentRegistry.Entry> namedXContent = new ArrayList<>();
namedXContent.add(
new NamedXContentRegistry.Entry(EvaluationMetric.class, new ParseField(PrecisionAtK.NAME), PrecisionAtK::fromXContent)
);
namedXContent.add(new NamedXContentRegistry.Entry(EvaluationMetric.class, new ParseField(RecallAtK.NAME), RecallAtK::fromXContent));
namedXContent.add(
new NamedXContentRegistry.Entry(
EvaluationMetric.class,
new ParseField(MeanReciprocalRank.NAME),
MeanReciprocalRank::fromXContent
)
);
namedXContent.add(
new NamedXContentRegistry.Entry(
EvaluationMetric.class,
new ParseField(DiscountedCumulativeGain.NAME),
DiscountedCumulativeGain::fromXContent
)
);
namedXContent.add(
new NamedXContentRegistry.Entry(
EvaluationMetric.class,
new ParseField(ExpectedReciprocalRank.NAME),
ExpectedReciprocalRank::fromXContent
)
);
namedXContent.add(
new NamedXContentRegistry.Entry(MetricDetail.class, new ParseField(PrecisionAtK.NAME), PrecisionAtK.Detail::fromXContent)
);
namedXContent.add(
new NamedXContentRegistry.Entry(MetricDetail.class, new ParseField(RecallAtK.NAME), RecallAtK.Detail::fromXContent)
);
namedXContent.add(
new NamedXContentRegistry.Entry(
MetricDetail.class,
new ParseField(MeanReciprocalRank.NAME),
MeanReciprocalRank.Detail::fromXContent
)
);
namedXContent.add(
new NamedXContentRegistry.Entry(
MetricDetail.class,
new ParseField(DiscountedCumulativeGain.NAME),
DiscountedCumulativeGain.Detail::fromXContent
)
);
namedXContent.add(
new NamedXContentRegistry.Entry(
MetricDetail.class,
new ParseField(ExpectedReciprocalRank.NAME),
ExpectedReciprocalRank.Detail::fromXContent
)
);
return namedXContent;
}
}
|
92397be8820f5ff610d41a5836beecdba44088a2 | 76 | java | Java | src/com/coolweather/app/util/package-info.java | jwjw111qq/coolWeather | e575eb869bcb9e4f27fcaa3186d27901c3f8ad7f | [
"Apache-2.0"
] | null | null | null | src/com/coolweather/app/util/package-info.java | jwjw111qq/coolWeather | e575eb869bcb9e4f27fcaa3186d27901c3f8ad7f | [
"Apache-2.0"
] | null | null | null | src/com/coolweather/app/util/package-info.java | jwjw111qq/coolWeather | e575eb869bcb9e4f27fcaa3186d27901c3f8ad7f | [
"Apache-2.0"
] | null | null | null | 9.5 | 33 | 0.552632 | 998,843 | /**
*
*/
/**
* @author jiangwei
*
*/
package com.coolweather.app.util; |
92397c36130883f4131c588db9013d88d3cc2977 | 996 | java | Java | violin-test/src/main/java/com/wolf/test/jackson/test3/Teacher.java | liyork/violin | 4f99d5461796df9debf33838d2ea7a16c1cb63c3 | [
"Apache-2.0"
] | null | null | null | violin-test/src/main/java/com/wolf/test/jackson/test3/Teacher.java | liyork/violin | 4f99d5461796df9debf33838d2ea7a16c1cb63c3 | [
"Apache-2.0"
] | 24 | 2020-03-04T22:07:41.000Z | 2022-01-21T23:50:53.000Z | violin-test/src/main/java/com/wolf/test/jackson/test3/Teacher.java | liyork/violin | 4f99d5461796df9debf33838d2ea7a16c1cb63c3 | [
"Apache-2.0"
] | 1 | 2017-06-27T09:15:50.000Z | 2017-06-27T09:15:50.000Z | 19.92 | 74 | 0.640562 | 998,844 | package com.wolf.test.jackson.test3;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
/**
* Description:
* Created on 2021/3/31 9:59 AM
*
* @author 李超
* @version 0.0.1
*/
public class Teacher {
@JacksonXmlProperty(localName = "TypeCode")
private TeacherType teacherTypeCode;
private String name;
private String gender;
private String age;
public TeacherType getTeacherTypeCode() {
return teacherTypeCode;
}
public void setTeacherTypeCode(TeacherType teacherTypeCode) {
this.teacherTypeCode = teacherTypeCode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
} |
92397c412d37691f468b45346fddef42e58e4533 | 1,210 | java | Java | src/main/java/io/voucherify/client/model/promotion/response/CreatePromotionCampaignResponse.java | mabdullah12/voucherify-java-sdk | a4dab181fb248164f466d008305771d7ff3685cb | [
"MIT"
] | 12 | 2017-09-27T08:20:00.000Z | 2021-11-09T14:08:33.000Z | src/main/java/io/voucherify/client/model/promotion/response/CreatePromotionCampaignResponse.java | mabdullah12/voucherify-java-sdk | a4dab181fb248164f466d008305771d7ff3685cb | [
"MIT"
] | 28 | 2018-01-09T13:57:14.000Z | 2022-02-22T07:01:30.000Z | src/main/java/io/voucherify/client/model/promotion/response/CreatePromotionCampaignResponse.java | mabdullah12/voucherify-java-sdk | a4dab181fb248164f466d008305771d7ff3685cb | [
"MIT"
] | 17 | 2017-10-24T13:33:14.000Z | 2022-01-13T05:58:37.000Z | 23.269231 | 67 | 0.812397 | 998,845 | package io.voucherify.client.model.promotion.response;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.voucherify.client.model.campaign.CampaignType;
import io.voucherify.client.model.voucher.GenerationStatus;
import io.voucherify.client.model.voucher.response.VoucherResponse;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.Date;
import java.util.Map;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
@ToString
public class CreatePromotionCampaignResponse {
private String id;
private String name;
private String object;
private CampaignType type;
@JsonProperty("campaign_type")
private String campaignType;
private String description;
@JsonProperty("start_date")
private Date startDate;
@JsonProperty("expiration_date")
private Date expirationDate;
private Map<String, Object> metadata;
private Long vouchersCount;
@JsonProperty("vouchers_generation_status")
private GenerationStatus generationStatus;
private VoucherResponse voucher;
private PromotionResponse promotion;
}
|
92397c86cd8a66a95232955392ae009779acae38 | 965 | java | Java | tourismwork-master/src/apps/manage/src/main/java/com/opentravelsoft/json/PinyinAction.java | xiaosongdeyx001/shujuku-----123 | a0a009a732d74bf601f9d4ebccfb8d42c8a9b7d9 | [
"Apache-2.0"
] | 3 | 2019-06-18T16:12:33.000Z | 2021-12-09T07:39:15.000Z | tourismwork-master/src/apps/manage/src/main/java/com/opentravelsoft/json/PinyinAction.java | xiaosongdeyx001/shujuku-----123 | a0a009a732d74bf601f9d4ebccfb8d42c8a9b7d9 | [
"Apache-2.0"
] | 12 | 2020-11-16T20:38:06.000Z | 2022-03-31T20:10:58.000Z | tourismwork-master/src/apps/manage/src/main/java/com/opentravelsoft/json/PinyinAction.java | xiaosongdeyx001/shujuku-----123 | a0a009a732d74bf601f9d4ebccfb8d42c8a9b7d9 | [
"Apache-2.0"
] | 1 | 2019-06-21T07:44:03.000Z | 2019-06-21T07:44:03.000Z | 21.043478 | 69 | 0.72624 | 998,846 | package com.opentravelsoft.json;
import org.springframework.beans.factory.annotation.Autowired;
import com.opensymphony.xwork2.Action;
import com.opentravelsoft.action.ManageAction;
import com.opentravelsoft.providers.PinyinDao;
/**
*
* @author <a herf="mailto:hzdkv@example.com">Steven Zhang</a>
* @version $Revision: 1.1 $ $Date: 2009/03/01 16:24:16 $
*/
public class PinyinAction extends ManageAction {
private static final long serialVersionUID = -5840178415466047565L;
private String pinyin;
private String name;
private PinyinDao pinyinDao;
@Autowired
public void setPinyinDao(PinyinDao pinyinDao) {
this.pinyinDao = pinyinDao;
}
public String execute() {
pinyin = pinyinDao.getPinyinByName(name);
return Action.SUCCESS;
}
public String getPinyin() {
return pinyin;
}
public void setPinyin(String pinyin) {
this.pinyin = pinyin;
}
public void setName(String name) {
this.name = name;
}
}
|
92397cef3e5137fdf4c0878e6f168f9b2328231a | 8,680 | java | Java | gapic/src/main/com/google/gapid/glviewer/Viewer.java | ben-clayton/gapid | 90c1e9bf5391d723699cb1ff248102b62f1d2ec0 | [
"Apache-2.0"
] | null | null | null | gapic/src/main/com/google/gapid/glviewer/Viewer.java | ben-clayton/gapid | 90c1e9bf5391d723699cb1ff248102b62f1d2ec0 | [
"Apache-2.0"
] | 25 | 2017-04-25T20:39:25.000Z | 2018-06-14T17:10:48.000Z | gapic/src/main/com/google/gapid/glviewer/Viewer.java | ben-clayton/gapid | 90c1e9bf5391d723699cb1ff248102b62f1d2ec0 | [
"Apache-2.0"
] | 1 | 2017-07-28T03:00:42.000Z | 2017-07-28T03:00:42.000Z | 26.30303 | 97 | 0.634217 | 998,847 | /*
* Copyright (C) 2017 Google 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.google.gapid.glviewer;
import static java.util.logging.Level.FINE;
import com.google.gapid.glviewer.gl.Shader;
import com.google.gapid.util.MouseAdapter;
import com.google.gapid.widgets.GlComposite;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import java.util.logging.Logger;
/**
* Renders a {@link Renderable} and handles user interactions with the given {@link CameraModel}.
* This is the main entry point of the GL model viewer.
*/
public class Viewer implements GlComposite.Listener {
private static final Logger LOG = Logger.getLogger(Viewer.class.getName());
private final CameraModel camera;
private Shaders shaders;
private Renderable renderable;
private Renderable newRenderable;
private Shading shading = Shading.LIT;
private Winding winding = Winding.CCW;
private Culling culling = Culling.OFF;
public Viewer(CameraModel camera) {
this.camera = camera;
}
/**
* Hooks up the mouse handling event listener to the given canvas.
*/
public void addMouseListeners(GlComposite canvas) {
MouseHandler handler = new MouseHandler(camera, canvas);
canvas.getControl().addMouseListener(handler);
canvas.getControl().addMouseMoveListener(handler);
canvas.getControl().addMouseWheelListener(handler);
}
public void setRenderable(Renderable renderable) {
if (this.renderable != renderable) {
newRenderable = renderable;
} else {
newRenderable = null;
}
}
public Shading getShading() {
return shading;
}
public Culling getCulling() {
return culling;
}
public Winding getWinding() {
return winding;
}
public void setShading(Shading shading) {
this.shading = shading;
}
public void setCulling(Culling culling) {
this.culling = culling;
}
public Culling toggleCulling() {
culling = culling.toggle();
return culling;
}
public void setWinding(Winding winding) {
this.winding = winding;
}
public Winding toggleWinding() {
winding = winding.toggle();
return winding;
}
@Override
public void init() {
float[] background = new float[] { .2f, .2f, .2f, 1f };
LOG.log(FINE, "GL Version: " + GL11.glGetString(GL11.GL_VERSION));
LOG.log(FINE, "GLSL Version: " + GL11.glGetString(GL20.GL_SHADING_LANGUAGE_VERSION));
shaders = Shaders.init();
if (renderable != null) {
renderable.init();
}
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glClearColor(background[0], background[1], background[2], background[3]);
GL11.glPointSize(4);
GL30.glBindVertexArray(GL30.glGenVertexArrays());
}
@Override
public void reshape(int x, int y, int width, int height) {
GL11.glViewport(x, y, width, height);
camera.updateViewport(width, height);
}
@Override
public void display() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
if (newRenderable != null) {
if (renderable != null) {
renderable.dispose();
}
renderable = newRenderable;
renderable.init();
newRenderable = null;
}
if (renderable != null) {
Renderable.State state = shading.getState(shaders, winding.invertNormals);
culling.apply();
winding.apply();
state.transform.setProjection(camera.getProjection());
state.transform.setModelView(camera.getViewTransform());
renderable.render(state);
}
}
@Override
public void dispose() {
shaders.delete();
if (renderable != null) {
renderable.dispose();
}
}
/**
* Back-face culling mode.
*/
public static enum Culling {
OFF() {
@Override
public void apply() {
GL11.glDisable(GL11.GL_CULL_FACE);
}
},
ON() {
@Override
public void apply() {
GL11.glEnable(GL11.GL_CULL_FACE);
}
};
public abstract void apply();
public Culling toggle() {
return (this == OFF) ? ON : OFF;
}
}
/**
* Triangle winding mode.
*/
public static enum Winding {
CCW(false) {
@Override
public void apply() {
GL11.glFrontFace(GL11.GL_CCW);
}
},
CW(true) {
@Override
public void apply() {
GL11.glFrontFace(GL11.GL_CW);
}
};
public final boolean invertNormals;
Winding(boolean invertNormals) {
this.invertNormals = invertNormals;
}
public abstract void apply();
public Winding toggle() {
return (this == CCW) ? CW : CCW;
}
}
/**
* Different shading options to use when rendering.
*/
public static enum Shading {
LIT() {
@Override
public Renderable.State getState(Shaders shaders, boolean invertNormals) {
Renderable.State state = new Renderable.State(shaders.litShader, invertNormals);
state.shader.bind();
state.shader.setUniform("uLightDir", new float[] {
0, -0.707f, -0.707f,
0, 0.707f, -0.707f,
-0.707f, 0, 0.707f,
0.707f, 0, 0.707f
});
state.shader.setUniform("uLightColor", new float[] {
0.2f, 0.2f, 0.2f,
0.4f, 0.4f, 0.4f,
0.5f, 0.5f, 0.5f,
1.0f, 1.0f, 1.0f
});
state.shader.setUniform("uLightSpecColor", new float[] {
0.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
1.0f, 1.0f, 1.0f
});
state.shader.setUniform("uLightSize", new float[] {
0f, 0.05f, 0.05f, 0f
});
state.shader.setUniform("uDiffuseColor",
new float[] { 0.37868f, 0.56050f, 0.03703f }); // #A4C639 in linear.
state.shader.setUniform("uSpecularColor", new float[] { 0.3f, 0.3f, 0.3f });
state.shader.setUniform("uRoughness", 0.25f);
return state;
}
},
FLAT() {
@Override
public Renderable.State getState(Shaders shaders, boolean invertNormals) {
Renderable.State state = new Renderable.State(shaders.flatShader, false);
state.shader.bind();
state.shader.setUniform("uDiffuseColor",
new float[] { 0.640625f, 0.7734375f, 0.22265625f }); // #A4C639 in sRGB.
return state;
}
},
NORMALS() {
@Override
public Renderable.State getState(Shaders shaders, boolean invertNormals) {
Renderable.State state = new Renderable.State(shaders.normalShader, invertNormals);
state.shader.bind();
return state;
}
};
public abstract Renderable.State getState(Shaders shaders, boolean invertNormals);
}
private static class MouseHandler extends MouseAdapter {
private final CameraModel camera;
private final GlComposite canvas;
private int lastX, lastY;
public MouseHandler(CameraModel camera, GlComposite canvas) {
this.camera = camera;
this.canvas = canvas;
}
@Override
public void mouseScrolled(MouseEvent e) {
camera.onZoom(-e.count / 18.0f);
canvas.paint();
}
@Override
public void mouseDown(MouseEvent e) {
lastX = e.x;
lastY = e.y;
}
@Override
public void mouseMove(MouseEvent e) {
if ((e.stateMask & SWT.BUTTON1) != 0) {
camera.onDrag(e.x - lastX, e.y - lastY);
canvas.paint();
}
lastX = e.x;
lastY = e.y;
}
}
private static class Shaders {
public final Shader litShader;
public final Shader flatShader;
public final Shader normalShader;
private Shaders(Shader litShader, Shader flatShader, Shader normalShader) {
this.litShader = litShader;
this.flatShader = flatShader;
this.normalShader = normalShader;
}
public static Shaders init() {
return new Shaders(
ShaderSource.loadShader("lit"),
ShaderSource.loadShader("flat"),
ShaderSource.loadShader("normals"));
}
public void delete() {
litShader.delete();
flatShader.delete();
normalShader.delete();
}
}
}
|
92397d4856089a0fdcd4df1a5b826a20b6f76995 | 4,704 | java | Java | docker/src/main/java/org/apache/karaf/docker/ContainerConfig.java | mhus/karaf | b92dd7e4d6fab3b98e534e661ae5a4ec3c1b9084 | [
"Apache-2.0"
] | 531 | 2015-01-05T22:33:44.000Z | 2022-03-23T13:35:40.000Z | docker/src/main/java/org/apache/karaf/docker/ContainerConfig.java | mhus/karaf | b92dd7e4d6fab3b98e534e661ae5a4ec3c1b9084 | [
"Apache-2.0"
] | 638 | 2015-01-27T10:11:40.000Z | 2022-03-30T10:57:48.000Z | docker/src/main/java/org/apache/karaf/docker/ContainerConfig.java | mhus/karaf | b92dd7e4d6fab3b98e534e661ae5a4ec3c1b9084 | [
"Apache-2.0"
] | 691 | 2015-02-04T00:04:32.000Z | 2022-03-28T08:17:32.000Z | 22.724638 | 80 | 0.663478 | 998,848 | /*
* 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.karaf.docker;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
/**
* Represents configuration of a Docker Container.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class ContainerConfig {
@JsonProperty("Hostname")
private String hostname;
@JsonProperty("User")
private String user;
@JsonProperty("AttachStdin")
private boolean attachStdin;
@JsonProperty("AttachStdout")
private boolean attachStdout;
@JsonProperty("AttachStderr")
private boolean attachStderr;
@JsonProperty("PortSpecs")
private String portSpecs;
@JsonProperty("Tty")
private boolean tty;
@JsonProperty("OpenStdin")
private boolean openStdin;
@JsonProperty("StdinOnce")
private boolean stdinOnce;
@JsonProperty("Env")
private String env;
@JsonProperty("Cmd")
private String[] cmd;
@JsonProperty("Image")
private String image;
@JsonProperty("WorkingDir")
private String workingDir;
@JsonProperty("NetworkDisabled")
private boolean networkDisabled;
@JsonProperty("ExposedPorts")
private Map<String, Map<String, String>> exposedPorts;
@JsonProperty("HostConfig")
private HostConfig hostConfig;
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public boolean isAttachStdin() {
return attachStdin;
}
public void setAttachStdin(boolean attachStdin) {
this.attachStdin = attachStdin;
}
public boolean isAttachStdout() {
return attachStdout;
}
public void setAttachStdout(boolean attachStdout) {
this.attachStdout = attachStdout;
}
public boolean isAttachStderr() {
return attachStderr;
}
public void setAttachStderr(boolean attachStderr) {
this.attachStderr = attachStderr;
}
public String getPortSpecs() {
return portSpecs;
}
public void setPortSpecs(String portSpecs) {
this.portSpecs = portSpecs;
}
public boolean isTty() {
return tty;
}
public void setTty(boolean tty) {
this.tty = tty;
}
public boolean isOpenStdin() {
return openStdin;
}
public void setOpenStdin(boolean openStdin) {
this.openStdin = openStdin;
}
public boolean isStdinOnce() {
return stdinOnce;
}
public void setStdinOnce(boolean stdinOnce) {
this.stdinOnce = stdinOnce;
}
public String getEnv() {
return env;
}
public void setEnv(String env) {
this.env = env;
}
public String[] getCmd() {
return cmd;
}
public void setCmd(String[] cmd) {
this.cmd = cmd;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getWorkingDir() {
return workingDir;
}
public void setWorkingDir(String workingDir) {
this.workingDir = workingDir;
}
public boolean isNetworkDisabled() {
return networkDisabled;
}
public void setNetworkDisabled(boolean networkDisabled) {
this.networkDisabled = networkDisabled;
}
public Map<String, Map<String, String>> getExposedPorts() {
return exposedPorts;
}
public void setExposedPorts(Map<String, Map<String, String>> exposedPorts) {
this.exposedPorts = exposedPorts;
}
public HostConfig getHostConfig() {
return hostConfig;
}
public void setHostConfig(HostConfig hostConfig) {
this.hostConfig = hostConfig;
}
}
|
92397d5112b41f0341f1e1f704d1b193c45a2137 | 733 | java | Java | app/src/main/java/com/kaige/cniao/bean/Tab.java | zhou1401/Cniao | 9e8af9b5c3bfe7452fd3169a67dfdb9648797209 | [
"Apache-2.0"
] | 2 | 2017-09-06T10:09:07.000Z | 2019-04-09T03:19:57.000Z | app/src/main/java/com/kaige/cniao/bean/Tab.java | zhou1401/Cniao | 9e8af9b5c3bfe7452fd3169a67dfdb9648797209 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/kaige/cniao/bean/Tab.java | zhou1401/Cniao | 9e8af9b5c3bfe7452fd3169a67dfdb9648797209 | [
"Apache-2.0"
] | null | null | null | 17.046512 | 52 | 0.574352 | 998,849 | package com.kaige.cniao.bean;
/**
* Created by Administrator on 2017/7/18.
*/
public class Tab {
private int title;
private int icon;
private Class fragment;
public Tab(Class fragment,int title, int icon) {
this.title = title;
this.icon = icon;
this.fragment = fragment;
}
public int getTitle() {
return title;
}
public void setTitle(int title) {
this.title = title;
}
public int getIcon() {
return icon;
}
public void setIcon(int icon) {
this.icon = icon;
}
public Class getFragment() {
return fragment;
}
public void setFragment(Class fragment) {
this.fragment = fragment;
}
}
|
92397e1ace697128549e6e5c87cf7c46e1ef5294 | 1,343 | java | Java | src/kujiin/ui/dialogs/SelectDate.java | calebtrahan/KujiIn_Java | 962e5b1c5f60328fd317067bb24146b46f35f15f | [
"MIT"
] | null | null | null | src/kujiin/ui/dialogs/SelectDate.java | calebtrahan/KujiIn_Java | 962e5b1c5f60328fd317067bb24146b46f35f15f | [
"MIT"
] | null | null | null | src/kujiin/ui/dialogs/SelectDate.java | calebtrahan/KujiIn_Java | 962e5b1c5f60328fd317067bb24146b46f35f15f | [
"MIT"
] | null | null | null | 29.844444 | 112 | 0.623232 | 998,850 | package kujiin.ui.dialogs;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.util.Duration;
import kujiin.ui.boilerplate.StyledStage;
import kujiin.xml.SoundFile;
import java.io.IOException;
import java.time.LocalDate;
public class SelectDate extends StyledStage {
public DatePicker DateSelector;
public Button AcceptButton;
public Button CancelButton;
private boolean Accepted;
public SelectDate(String title) {
try {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../../assets/fxml/SelectDate.fxml"));
fxmlLoader.setController(this);
Scene defaultscene = new Scene(fxmlLoader.load());
setScene(defaultscene);
setResizable(false);
setTitle(title);
Accepted = false;
DateSelector.setValue(LocalDate.now());
AcceptButton.setOnAction(event -> {
Accepted = true;
close();
});
CancelButton.setOnAction(event -> {
Accepted = false;
close();
});
} catch (IOException e) {e.printStackTrace();}
}
public LocalDate getDate() {return DateSelector.getValue();}
public boolean isAccepted() {
return Accepted;
}
} |
9239815276691681045c7fefeaa32e5196bfdc83 | 543 | java | Java | android/src/com/gultendogan/survivorbird/AndroidLauncher.java | gulten27/SurvivorBird | 6384552bcf5a303bdc2d7428b951620d4dfcc828 | [
"MIT"
] | null | null | null | android/src/com/gultendogan/survivorbird/AndroidLauncher.java | gulten27/SurvivorBird | 6384552bcf5a303bdc2d7428b951620d4dfcc828 | [
"MIT"
] | null | null | null | android/src/com/gultendogan/survivorbird/AndroidLauncher.java | gulten27/SurvivorBird | 6384552bcf5a303bdc2d7428b951620d4dfcc828 | [
"MIT"
] | null | null | null | 31.941176 | 81 | 0.836096 | 998,851 | package com.gultendogan.survivorbird;
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.gultendogan.survivorbird.SurvivorBird;
public class AndroidLauncher extends AndroidApplication {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
initialize(new SurvivorBird(), config);
}
}
|
92398352480a4a7c795121ab72092cbba8fd5407 | 2,335 | java | Java | src/main/java/one/digitalinnovation/citiesapididi/entity/PointType.java | didifive/cities-api-digital_innovation_one | e421482748f551245364555b737e35ded3c101dc | [
"MIT"
] | null | null | null | src/main/java/one/digitalinnovation/citiesapididi/entity/PointType.java | didifive/cities-api-digital_innovation_one | e421482748f551245364555b737e35ded3c101dc | [
"MIT"
] | null | null | null | src/main/java/one/digitalinnovation/citiesapididi/entity/PointType.java | didifive/cities-api-digital_innovation_one | e421482748f551245364555b737e35ded3c101dc | [
"MIT"
] | null | null | null | 26.534091 | 101 | 0.670236 | 998,852 | package one.digitalinnovation.citiesapididi.entity;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
import org.springframework.data.geo.Point;
import org.postgresql.geometric.PGpoint;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class PointType implements UserType {
@Override
public int[] sqlTypes() {
return new int[] {java.sql.Types.OTHER};
}
@Override
public Class returnedClass() {
return Point.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
return false;
}
@Override
public int hashCode(Object x) throws HibernateException {
return 0;
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session,
Object owner) throws HibernateException, SQLException {
/* 1st */
/*Object object = rs.getObject(names[0]);
Double[] points = StringLocationUtils.transform(object.toString());
return new Point(points[0], points[1]);*/
/* 2nd */
/*PGpoint value = (PGpoint) rs.getObject(names[0]);
return new Point(value.x, value.y);*/
/* 3rd */
Object object = rs.getObject(names[0]);
PGpoint point = new PGpoint(object.toString());
return new Point(point.x, point.y);
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index,
SharedSessionContractImplementor session)
throws HibernateException, SQLException {
}
@Override
public Object deepCopy(Object value) throws HibernateException {
return null;
}
@Override
public boolean isMutable() {
return false;
}
@Override
public Serializable disassemble(Object value) throws HibernateException {
return null;
}
@Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return null;
}
@Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return null;
}
}
|
923983947f8d7aea709e507ef1a12ac7b8d13d53 | 3,494 | java | Java | test-clients/src/main/java/com/hedera/services/bdd/suites/misc/KeyExport.java | tinker-michaelj/hedera-services | 60c4aa6d4d6746b23528e487aa5b87ae0b8fd723 | [
"Apache-2.0"
] | null | null | null | test-clients/src/main/java/com/hedera/services/bdd/suites/misc/KeyExport.java | tinker-michaelj/hedera-services | 60c4aa6d4d6746b23528e487aa5b87ae0b8fd723 | [
"Apache-2.0"
] | null | null | null | test-clients/src/main/java/com/hedera/services/bdd/suites/misc/KeyExport.java | tinker-michaelj/hedera-services | 60c4aa6d4d6746b23528e487aa5b87ae0b8fd723 | [
"Apache-2.0"
] | null | null | null | 31.763636 | 104 | 0.734402 | 998,853 | package com.hedera.services.bdd.suites.misc;
/*-
*
* Hedera Services Test Clients
*
* Copyright (C) 2018 - 2020 Hedera Hashgraph, 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import com.hedera.services.bdd.spec.HapiApiSpec;
import com.hedera.services.bdd.spec.keys.KeyFactory;
import com.hedera.services.bdd.spec.keys.KeyShape;
import com.hedera.services.bdd.suites.HapiApiSuite;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static com.hedera.services.bdd.spec.HapiApiSpec.defaultHapiSpec;
import static com.hedera.services.bdd.spec.keys.KeyShape.listOf;
import static com.hedera.services.bdd.spec.transactions.TxnVerbs.fileCreate;
import static com.hedera.services.bdd.spec.utilops.UtilVerbs.keyFromPem;
import static com.hedera.services.bdd.spec.utilops.UtilVerbs.newKeyNamed;
import static com.hedera.services.bdd.spec.utilops.UtilVerbs.withOpContext;
public class KeyExport extends HapiApiSuite {
private static final Logger log = LogManager.getLogger(KeyExport.class);
private static final String PEM_FILE_NAME = "previewTestnet.pem";
public static void main(String... args) throws Exception {
new KeyExport().runSuiteSync();
}
@Override
protected List<HapiApiSpec> getSpecsInSuite() {
return List.of(new HapiApiSpec[] {
exportCurrentTreasuryKey(),
// exportGenesisKey(),
// validateNewKey(),
}
);
}
private HapiApiSpec validateNewKey() {
return defaultHapiSpec("validateNewKey").given(
keyFromPem(PEM_FILE_NAME)
.name("newKey")
.passphrase("P1WUX2Xla2wFslpoPTN39avz")
.simpleWacl()
).when().then(
fileCreate("testFile").key("newKey")
);
}
private HapiApiSpec exportCurrentTreasuryKey() {
KeyFactory.PEM_PASSPHRASE = "passphrase";
return defaultHapiSpec("ExportCurrentTreasuryKeyAsPem")
.given( ).when( ).then(
withOpContext((spec, opLog) -> {
spec.keys().exportSimpleWacl("devGenesisKeypair.pem", GENESIS);
})
);
}
private HapiApiSpec exportGenesisKey() {
final var r = new Random();
final int passphraseLength = 24;
final char[] choices = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
final KeyShape listOfSizeOne = listOf(1);
KeyFactory.PEM_PASSPHRASE = IntStream.range(0, passphraseLength)
.map(ignore -> r.nextInt(choices.length))
.mapToObj(i -> Character.valueOf(choices[i]).toString())
.collect(Collectors.joining(""));
return defaultHapiSpec("ExportGenesisKey")
.given(
newKeyNamed("ab-initio").shape(listOfSizeOne)
).when( ).then(
withOpContext((spec, opLog) -> {
opLog.info("Passphrase is: {}", KeyFactory.PEM_PASSPHRASE);
spec.keys().exportSimpleWacl(PEM_FILE_NAME, "ab-initio");
})
);
}
@Override
protected Logger getResultsLogger() {
return log;
}
}
|
9239839e1d0498d88444c2539d92ecf941b4c839 | 778 | java | Java | src/main/java/com/hellosatish/generator/engine/rendering/metadata/PropertiesRendererMetadata.java | hellosatish/magic-code | dc1c17b5dda2f80b8b3dd2ba7ff1be0f3b07b280 | [
"MIT"
] | null | null | null | src/main/java/com/hellosatish/generator/engine/rendering/metadata/PropertiesRendererMetadata.java | hellosatish/magic-code | dc1c17b5dda2f80b8b3dd2ba7ff1be0f3b07b280 | [
"MIT"
] | null | null | null | src/main/java/com/hellosatish/generator/engine/rendering/metadata/PropertiesRendererMetadata.java | hellosatish/magic-code | dc1c17b5dda2f80b8b3dd2ba7ff1be0f3b07b280 | [
"MIT"
] | null | null | null | 25.096774 | 82 | 0.845758 | 998,854 | package com.hellosatish.generator.engine.rendering.metadata;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PropertiesRendererMetadata implements GeneratorMetadata {
private String projectName;
private int portnumber;
protected boolean loadBalancingEnabled;
protected boolean cloudconfigEnabled;
protected boolean serviceRegistrationEnabled;
protected boolean securityEnabled;
protected boolean actuatorEnabled;
private boolean renderH2Properties;
private boolean renderMySQLProerties;
private boolean cloudDependencyEnabled;
public boolean isCloudDependencyEnabled(){
return loadBalancingEnabled || cloudconfigEnabled || serviceRegistrationEnabled;
}
}
|
92398404891772eabb770b5fd293c86ff942078c | 1,641 | java | Java | src/main/java/cn/ms/neural/moduler/Moduler.java | vwyuheng/neural | 2073e34475f34d0cf9d7cec934315f1543751f3e | [
"MIT"
] | null | null | null | src/main/java/cn/ms/neural/moduler/Moduler.java | vwyuheng/neural | 2073e34475f34d0cf9d7cec934315f1543751f3e | [
"MIT"
] | null | null | null | src/main/java/cn/ms/neural/moduler/Moduler.java | vwyuheng/neural | 2073e34475f34d0cf9d7cec934315f1543751f3e | [
"MIT"
] | 2 | 2018-04-09T15:32:03.000Z | 2018-12-12T03:43:36.000Z | 26.901639 | 138 | 0.766606 | 998,855 | package cn.ms.neural.moduler;
import cn.ms.neural.common.Constants;
import cn.ms.neural.common.URL;
import cn.ms.neural.common.spi.ExtensionLoader;
import cn.ms.neural.common.utils.NetUtils;
import cn.ms.neural.moduler.extension.blackwhite.IBlackWhite;
import cn.ms.neural.moduler.extension.gracestop.IGraceStop;
import cn.ms.neural.moduler.extension.pipescaling.IPipeScaling;
public class Moduler<REQ, RES> {
/**
* 统一配置资源
*/
URL url=new URL(Constants.DEFAULT_PROTOCOL_VALUE, NetUtils.getLocalHostName(), Constants.DEFAULT_PORT_VALUE, this.getClass().getName());
/**
* 优雅停机
*/
@SuppressWarnings("unchecked")
IGraceStop<REQ, RES> graceStop=ExtensionLoader.getExtensionLoader(IGraceStop.class).getAdaptiveExtension();
@SuppressWarnings("unchecked")
IBlackWhite<REQ, RES> blackWhite=ExtensionLoader.getExtensionLoader(IBlackWhite.class).getAdaptiveExtension();
@SuppressWarnings("unchecked")
IPipeScaling<REQ, RES> pipeScaling=ExtensionLoader.getExtensionLoader(IPipeScaling.class).getAdaptiveExtension();
public URL getUrl() {
return url;
}
public void setUrl(URL url) {
this.url = url;
}
public IGraceStop<REQ, RES> getGraceStop() {
return graceStop;
}
public void setGraceStop(IGraceStop<REQ, RES> graceStop) {
this.graceStop = graceStop;
}
public IBlackWhite<REQ, RES> getBlackWhite() {
return blackWhite;
}
public void setBlackWhite(IBlackWhite<REQ, RES> blackWhite) {
this.blackWhite = blackWhite;
}
public IPipeScaling<REQ, RES> getPipeScaling() {
return pipeScaling;
}
public void setPipeScaling(IPipeScaling<REQ, RES> pipeScaling) {
this.pipeScaling = pipeScaling;
}
}
|
92398462ee47bd3a69c866fb31055087cd99af36 | 406 | java | Java | src/test/java8Test/Java8InAction/chap9/Resizable.java | leoeco2000/TestJava8 | fa96dc043aea3263bb5ee0ef78fd03b6a05c7d28 | [
"MIT"
] | null | null | null | src/test/java8Test/Java8InAction/chap9/Resizable.java | leoeco2000/TestJava8 | fa96dc043aea3263bb5ee0ef78fd03b6a05c7d28 | [
"MIT"
] | null | null | null | src/test/java8Test/Java8InAction/chap9/Resizable.java | leoeco2000/TestJava8 | fa96dc043aea3263bb5ee0ef78fd03b6a05c7d28 | [
"MIT"
] | null | null | null | 31.230769 | 69 | 0.746305 | 998,856 | package test.java8Test.Java8InAction.chap9;
public interface Resizable extends Drawable{
public int getWidth();
public int getHeight();
public void setWidth(int width);
public void setHeight(int height);
public void setAbsoluteSize(int width, int height);
//TODO: uncomment, read the README for instructions
//public void setRelativeSize(int widthFactor, int heightFactor);
}
|
923984b60f0c5f6180b432fb624727c238360f5d | 444 | java | Java | app/src/main/java/wannabit/io/cosmostaion/utils/WLog.java | imversed/imversed-wallet-android | 093d53e16d44014cc3f045c696f15dc53dceb9d3 | [
"MIT"
] | null | null | null | app/src/main/java/wannabit/io/cosmostaion/utils/WLog.java | imversed/imversed-wallet-android | 093d53e16d44014cc3f045c696f15dc53dceb9d3 | [
"MIT"
] | null | null | null | app/src/main/java/wannabit/io/cosmostaion/utils/WLog.java | imversed/imversed-wallet-android | 093d53e16d44014cc3f045c696f15dc53dceb9d3 | [
"MIT"
] | null | null | null | 20.181818 | 52 | 0.59009 | 998,857 | package wannabit.io.cosmostaion.utils;
import android.util.Log;
import wannabit.io.cosmostaion.BuildConfig;
public class WLog {
public final static String LOG_TAG = "FDWallet";
public static void e(String msg) {
if (BuildConfig.DEBUG) {
Log.e(LOG_TAG, msg + "\n");
}
}
public static void w(String msg) {
if (BuildConfig.DEBUG) {
Log.w(LOG_TAG, msg + "\n");
}
}
}
|
9239883e2a269d68026b0c2348b53271331f48b1 | 17,043 | java | Java | Android/app/src/main/java/com/harvard/usermodule/LoginCallbackActivity.java | JudeAlexis111/alexistudies | 226b617fd79db81c8ca42a96b231815d9fe01591 | [
"MIT"
] | 43 | 2020-12-18T02:43:00.000Z | 2022-03-30T03:03:03.000Z | Android/app/src/main/java/com/harvard/usermodule/LoginCallbackActivity.java | JudeAlexis111/alexistudies | 226b617fd79db81c8ca42a96b231815d9fe01591 | [
"MIT"
] | 1,472 | 2020-12-18T07:19:53.000Z | 2022-03-31T15:34:27.000Z | Android/app/src/main/java/com/harvard/usermodule/LoginCallbackActivity.java | JudeAlexis111/alexistudies | 226b617fd79db81c8ca42a96b231815d9fe01591 | [
"MIT"
] | 49 | 2020-12-20T16:57:07.000Z | 2022-02-23T15:53:43.000Z | 41.568293 | 101 | 0.684387 | 998,858 | /*
* Copyright 2020-2021 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
package com.harvard.usermodule;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.google.firebase.iid.FirebaseInstanceId;
import com.harvard.AppConfig;
import com.harvard.BuildConfig;
import com.harvard.FdaApplication;
import com.harvard.R;
import com.harvard.notificationmodule.NotificationModuleSubscriber;
import com.harvard.storagemodule.DbServiceSubscriber;
import com.harvard.studyappmodule.ChangePasswordActivity;
import com.harvard.studyappmodule.StandaloneActivity;
import com.harvard.studyappmodule.StudyActivity;
import com.harvard.studyappmodule.StudyInfoActivity;
import com.harvard.usermodule.event.GetUserProfileEvent;
import com.harvard.usermodule.event.LoginEvent;
import com.harvard.usermodule.event.UpdateUserProfileEvent;
import com.harvard.usermodule.webservicemodel.TokenData;
import com.harvard.usermodule.webservicemodel.UpdateUserProfileData;
import com.harvard.usermodule.webservicemodel.UserProfileData;
import com.harvard.utils.AppController;
import com.harvard.utils.Logger;
import com.harvard.utils.SharedPreferenceHelper;
import com.harvard.utils.Urls;
import com.harvard.webservicemodule.apihelper.ApiCall;
import com.harvard.webservicemodule.events.AuthServerConfigEvent;
import com.harvard.webservicemodule.events.ParticipantDatastoreConfigEvent;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginCallbackActivity extends AppCompatActivity
implements ApiCall.OnAsyncRequestComplete {
private static final int TOKENS_REQUEST = 100;
private static final int UPDATE_USER_PROFILE = 101;
private static final int USER_PROFILE_REQUEST = 102;
private String userId;
private String userAuth;
private String code;
private String accountStatus;
private String emailId;
UserProfileData userProfileData;
private static final int PASSCODE_RESPONSE = 103;
private static final int STUDYINFO_REQUEST = 100;
private static final int CHANGE_PASSWORD_RESPONSE = 104;
private static final String PASSWORD_RESET_STATUS = "3";
private static final String ACCOUNT_LOCKED_STATUS = "2";
private static final String INTENT_SIGNIN = "signin";
private static final String INTENT_FLOW = "login_callback";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_standalone);
handleIntent(getIntent());
}
public void handleIntent(Intent intent) {
String appLinkAction = intent.getAction();
Uri appLinkData = intent.getData();
if (Intent.ACTION_VIEW.equals(appLinkAction) && appLinkData != null) {
Uri uri = intent.getData();
Map<String, String> urlParams = AppController.decodeUrl(uri.getEncodedQuery());
if (uri != null && urlParams!=null) {
userId = urlParams.get("userId");
emailId = urlParams.get("email");
if (uri.getPath().equalsIgnoreCase(Urls.DEEPLINK_CALLBACK)) {
code = urlParams.get("code");
accountStatus = urlParams.get("accountStatus");
AppController.getHelperProgressDialog().showProgress(this, "", "", false);
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
headers.put("correlationId", FdaApplication.getRandomString());
headers.put("appId", BuildConfig.APP_ID);
headers.put("mobilePlatform", "ANDROID");
HashMap<String, String> params = new HashMap<>();
params.put("grant_type", "authorization_code");
params.put("scope", "openid offline");
params.put("redirect_uri", Urls.AUTH_SERVER_REDIRECT_URL);
params.put("code_verifier", FdaApplication.getRandomString());
params.put("code", code);
params.put("userId", userId);
AuthServerConfigEvent authServerConfigEvent =
new AuthServerConfigEvent(
"post",
Urls.TOKENS,
TOKENS_REQUEST,
this,
TokenData.class,
params,
headers,
null,
false,
this);
LoginEvent loginEvent = new LoginEvent();
loginEvent.setAuthServerConfigEvent(authServerConfigEvent);
UserModulePresenter userModulePresenter = new UserModulePresenter();
userModulePresenter.performLogin(loginEvent);
} else if (uri.getPath().equalsIgnoreCase(Urls.DEEPLINK_ACTIVATION)) {
emailId = urlParams.get("email");
Intent verificationIntent =
new Intent(LoginCallbackActivity.this, VerificationStepActivity.class);
verificationIntent.putExtra("email", urlParams.get("email"));
verificationIntent.putExtra("type", INTENT_SIGNIN);
startActivity(verificationIntent);
finish();
}
}
}
}
@Override
public <T> void asyncResponse(T response, int responseCode) {
if (responseCode == TOKENS_REQUEST) {
TokenData tokenData = (TokenData) response;
// FilterActivity Screen json object clearing
AppController.getHelperSharedPreference()
.writePreference(LoginCallbackActivity.this, getString(R.string.json_object_filter), "");
userAuth = tokenData.getAccess_token();
AppController.getHelperSharedPreference()
.writePreference(
LoginCallbackActivity.this,
getString(R.string.refreshToken),
tokenData.getRefresh_token());
if (accountStatus != null
&& (accountStatus.equalsIgnoreCase(PASSWORD_RESET_STATUS)
|| accountStatus.equalsIgnoreCase(ACCOUNT_LOCKED_STATUS))) {
AppController.getHelperProgressDialog().dismissDialog();
Intent changePasswordIntent =
new Intent(LoginCallbackActivity.this, ChangePasswordActivity.class);
changePasswordIntent.putExtra("from", "signin");
changePasswordIntent.putExtra("userid", userId);
changePasswordIntent.putExtra("auth", userAuth);
changePasswordIntent.putExtra("email", emailId);
startActivityForResult(changePasswordIntent, CHANGE_PASSWORD_RESPONSE);
} else {
new GetFcmRefreshToken().execute();
}
} else if (responseCode == UPDATE_USER_PROFILE) {
UpdateUserProfileData updateUserProfileData = (UpdateUserProfileData) response;
if (updateUserProfileData != null) {
callUserProfileWebService();
} else {
Toast.makeText(
this, getResources().getString(R.string.not_able_to_login), Toast.LENGTH_SHORT)
.show();
finish();
}
} else if (responseCode == USER_PROFILE_REQUEST) {
userProfileData = (UserProfileData) response;
if (userProfileData != null) {
if (userProfileData.getSettings().isPasscode()) {
AppController.getHelperProgressDialog().dismissDialog();
AppController.getHelperSharedPreference()
.writePreference(
LoginCallbackActivity.this, getString(R.string.initialpasscodeset), "no");
AppController.getHelperSharedPreference()
.writePreference(LoginCallbackActivity.this, getString(R.string.userid), "" + userId);
AppController.getHelperSharedPreference()
.writePreference(LoginCallbackActivity.this, getString(R.string.auth), "" + userAuth);
AppController.getHelperSharedPreference()
.writePreference(LoginCallbackActivity.this, getString(R.string.verified), "true");
AppController.getHelperSharedPreference()
.writePreference(
LoginCallbackActivity.this,
getString(R.string.email),
"" + userProfileData.getProfile().getEmailId());
Intent intent = new Intent(LoginCallbackActivity.this, NewPasscodeSetupActivity.class);
intent.putExtra("from", INTENT_SIGNIN);
startActivityForResult(intent, PASSCODE_RESPONSE);
} else {
login();
}
} else {
Toast.makeText(
this, getResources().getString(R.string.not_able_to_login), Toast.LENGTH_SHORT)
.show();
finish();
}
}
}
private void login() {
AppController.getHelperProgressDialog().dismissDialog();
AppController.getHelperSharedPreference()
.writePreference(LoginCallbackActivity.this, getString(R.string.userid), "" + userId);
AppController.getHelperSharedPreference()
.writePreference(LoginCallbackActivity.this, getString(R.string.auth), "" + userAuth);
AppController.getHelperSharedPreference()
.writePreference(
LoginCallbackActivity.this,
getString(R.string.email),
"" + userProfileData.getProfile().getEmailId());
AppController.getHelperSharedPreference()
.writePreference(LoginCallbackActivity.this, getString(R.string.verified), "true");
DbServiceSubscriber dbServiceSubscriber = new DbServiceSubscriber();
dbServiceSubscriber.saveUserProfileData(LoginCallbackActivity.this, userProfileData);
if (userProfileData != null
&& (!userProfileData.getSettings().isLocalNotifications()
|| userProfileData.getSettings().isRemoteNotifications())) {
NotificationModuleSubscriber notificationModuleSubscriber =
new NotificationModuleSubscriber(null, null);
notificationModuleSubscriber.generateNotificationTurnOffNotification(
Calendar.getInstance().getTime(), LoginCallbackActivity.this);
}
if (SharedPreferenceHelper.readPreference(
LoginCallbackActivity.this, getString(R.string.loginflow), "")
.equalsIgnoreCase("StudyInfo")) {
Intent intent = new Intent(LoginCallbackActivity.this, StudyInfoActivity.class);
intent.putExtra("flow", INTENT_FLOW);
intent.putExtra(
"studyId",
SharedPreferenceHelper.readPreference(
LoginCallbackActivity.this, getString(R.string.login_studyinfo_studyId), ""));
intent.putExtra(
"title",
SharedPreferenceHelper.readPreference(
LoginCallbackActivity.this, getString(R.string.login_studyinfo_title), ""));
intent.putExtra(
"bookmark",
Boolean.parseBoolean(
SharedPreferenceHelper.readPreference(
LoginCallbackActivity.this, getString(R.string.login_studyinfo_bookmark), "")));
intent.putExtra(
"status",
SharedPreferenceHelper.readPreference(
LoginCallbackActivity.this, getString(R.string.login_studyinfo_status), ""));
intent.putExtra(
"studyStatus",
SharedPreferenceHelper.readPreference(
LoginCallbackActivity.this, getString(R.string.login_studyinfo_studyStatus), ""));
intent.putExtra(
"position",
SharedPreferenceHelper.readPreference(
LoginCallbackActivity.this, getString(R.string.login_studyinfo_position), ""));
intent.putExtra(
"enroll",
SharedPreferenceHelper.readPreference(
LoginCallbackActivity.this, getString(R.string.login_studyinfo_enroll), ""));
startActivity(intent);
} else {
if (AppConfig.AppType.equalsIgnoreCase(getString(R.string.app_gateway))) {
Intent intent = new Intent(LoginCallbackActivity.this, StudyActivity.class);
ComponentName cn = intent.getComponent();
Intent mainIntent = Intent.makeRestartActivityTask(cn);
startActivity(mainIntent);
finish();
} else {
Intent intent = new Intent(LoginCallbackActivity.this, StandaloneActivity.class);
ComponentName cn = intent.getComponent();
Intent mainIntent = Intent.makeRestartActivityTask(cn);
mainIntent.putExtra("flow", INTENT_FLOW);
startActivity(mainIntent);
finish();
}
}
}
@Override
public void asyncResponseFailure(int responseCode, String errormsg, String statusCode) {
AppController.getHelperProgressDialog().dismissDialog();
Toast.makeText(this, errormsg, Toast.LENGTH_SHORT).show();
finish();
}
private class GetFcmRefreshToken extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
String token = "";
if (FirebaseInstanceId.getInstance().getToken() == null
|| FirebaseInstanceId.getInstance().getToken().isEmpty()) {
boolean regIdStatus = false;
while (!regIdStatus) {
token =
AppController.getHelperSharedPreference()
.readPreference(LoginCallbackActivity.this, "deviceToken", "");
if (!token.isEmpty()) {
regIdStatus = true;
}
}
} else {
AppController.getHelperSharedPreference()
.writePreference(
LoginCallbackActivity.this,
"deviceToken",
FirebaseInstanceId.getInstance().getToken());
token =
AppController.getHelperSharedPreference()
.readPreference(LoginCallbackActivity.this, "deviceToken", "");
}
return token;
}
@Override
protected void onPostExecute(String token) {
callUpdateProfileWebService(token);
}
@Override
protected void onPreExecute() {
AppController.getHelperProgressDialog()
.showProgress(LoginCallbackActivity.this, "", "", false);
}
}
private void callUpdateProfileWebService(String deviceToken) {
AppController.getHelperProgressDialog().showProgress(LoginCallbackActivity.this, "", "", false);
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + userAuth);
headers.put("userId", userId);
JSONObject jsonObjBody = new JSONObject();
JSONObject infoJson = new JSONObject();
try {
infoJson.put("os", "android");
infoJson.put("appVersion", BuildConfig.VERSION_NAME + "." + BuildConfig.VERSION_CODE);
infoJson.put("deviceToken", deviceToken);
jsonObjBody.put("info", infoJson);
} catch (JSONException e) {
Logger.log(e);
}
if (SharedPreferenceHelper.readPreference(LoginCallbackActivity.this, "logintype", "")
.equalsIgnoreCase("signUp")) {
JSONObject settingJson = new JSONObject();
try {
settingJson.put("passcode", true);
settingJson.put("remoteNotifications", true);
settingJson.put("localNotifications", true);
jsonObjBody.put("settings", settingJson);
} catch (JSONException e) {
Logger.log(e);
}
}
ParticipantDatastoreConfigEvent participantDatastoreConfigEvent =
new ParticipantDatastoreConfigEvent(
"post_object",
Urls.UPDATE_USER_PROFILE,
UPDATE_USER_PROFILE,
this,
UpdateUserProfileData.class,
null,
headers,
jsonObjBody,
false,
this);
UpdateUserProfileEvent updateUserProfileEvent = new UpdateUserProfileEvent();
updateUserProfileEvent.setParticipantDatastoreConfigEvent(participantDatastoreConfigEvent);
UserModulePresenter userModulePresenter = new UserModulePresenter();
userModulePresenter.performUpdateUserProfile(updateUserProfileEvent);
}
private void callUserProfileWebService() {
HashMap<String, String> header = new HashMap<>();
header.put("Authorization", "Bearer " + userAuth);
header.put("userId", userId);
GetUserProfileEvent getUserProfileEvent = new GetUserProfileEvent();
ParticipantDatastoreConfigEvent participantDatastoreConfigEvent =
new ParticipantDatastoreConfigEvent(
"get",
Urls.GET_USER_PROFILE,
USER_PROFILE_REQUEST,
LoginCallbackActivity.this,
UserProfileData.class,
null,
header,
null,
false,
this);
getUserProfileEvent.setParticipantDatastoreConfigEvent(participantDatastoreConfigEvent);
UserModulePresenter userModulePresenter = new UserModulePresenter();
userModulePresenter.performGetUserProfile(getUserProfileEvent);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PASSCODE_RESPONSE) {
login();
} else if (requestCode == CHANGE_PASSWORD_RESPONSE && resultCode == RESULT_OK) {
new GetFcmRefreshToken().execute();
}
}
}
|
92398862f11a1659ead42799fb207511793d6151 | 423 | java | Java | JAVA-BEGINNERS-PROGRAMS/tutorial13/src/App.java | harshen/Java-Programs | 2914add7452c979798da3f5602808c20fbdac0d7 | [
"MIT"
] | null | null | null | JAVA-BEGINNERS-PROGRAMS/tutorial13/src/App.java | harshen/Java-Programs | 2914add7452c979798da3f5602808c20fbdac0d7 | [
"MIT"
] | null | null | null | JAVA-BEGINNERS-PROGRAMS/tutorial13/src/App.java | harshen/Java-Programs | 2914add7452c979798da3f5602808c20fbdac0d7 | [
"MIT"
] | null | null | null | 16.92 | 41 | 0.652482 | 998,859 | class Person {
// Instance variables (data or "state")
String name;
int age;
// Classes can contain
// 1. Data
// 2. Subroutines (methods)
}
public class App {
public static void main(String[] args) {
Person person1 = new Person();
person1.name = "Joe Bloggs";
person1.age = 37;
Person person2 = new Person();
person2.name = "Sarah Smith";
person2.age = 20;
System.out.println(person1.name);
}
}
|
92398873b656d654b7c72357420e33b0f1d17a2f | 518 | java | Java | spring/src/main/java/org/wrl/spring/jdbc/model/InsertUserModel.java | wangruiling/samples | 4d11763cbbcf34a0651d9319164a72c166018eb3 | [
"Apache-2.0"
] | null | null | null | spring/src/main/java/org/wrl/spring/jdbc/model/InsertUserModel.java | wangruiling/samples | 4d11763cbbcf34a0651d9319164a72c166018eb3 | [
"Apache-2.0"
] | 1 | 2015-07-03T15:48:58.000Z | 2015-07-05T01:54:31.000Z | spring/src/main/java/org/wrl/spring/jdbc/model/InsertUserModel.java | wangruiling/samples | 4d11763cbbcf34a0651d9319164a72c166018eb3 | [
"Apache-2.0"
] | null | null | null | 28.777778 | 64 | 0.745174 | 998,860 | package org.wrl.spring.jdbc.model;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.SqlUpdate;
import java.sql.Types;
public class InsertUserModel extends SqlUpdate {
public InsertUserModel(JdbcTemplate jdbcTemplate) {
super.setJdbcTemplate(jdbcTemplate);
super.setSql("insert into test(name) values(?)");
super.declareParameter(new SqlParameter(Types.VARCHAR));
compile();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.