hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
c5b08a37162109e2d4debfaa78a44bb636376030 | 4,557 | package lectureNotes.lesson3.rule3;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import org.junit.Test;
public class FixedDesignFlaw1 {
// Engine control unit
static class ECU {
public static final String ACTIVATE_FAN_UNIT = "Activate Fan unit";
public static final String ACTIVATE_EGR = "Activate EGR";
private final BSI bsi;
public ECU(BSI bsi) {
this.bsi = bsi;
}
boolean dispatchEngineParam(String engineParam) {
boolean everyCommandProcessed = true;
// ...
if (engineParam.equals("Engine too hot")) {
String answer = bsi.sendMessage("CoolingSystemId", ACTIVATE_FAN_UNIT);
// process answer
everyCommandProcessed &= answer.equals(BSI.NO_ACTION_PERFORMED);
}
if (engineParam.equals("EGR filter full")) {
String answer = bsi.sendMessage("EGRSystemId", ACTIVATE_EGR);
// process answer
everyCommandProcessed &= answer.equals(BSI.NO_ACTION_PERFORMED);
}
// ...
return everyCommandProcessed;
}
}
// It is still valid to want an unique instance for BSI, using singleton for this is not a good
// option.
// The wiring part has to manage that:
// Factories or dependency injection framework
static class BSI {
public static final String NO_ACTION_PERFORMED = "No action performed";
// With a constructor with visibility package, we almost only allow the BSI factory
// to instantiate BSI class
BSI() {
}
String sendMessage(String ecuId, String message) {
// ...
if (message.equals(ECU.ACTIVATE_FAN_UNIT)) {
// Prevent over heating of engine since generate heat (may be an unrealistic
// automotive behavior: it's just a sample)
inhibitEGRMessage();
return "Fan activated";
// ...
} else if (message.equals(ECU.ACTIVATE_EGR) && !isInhibitedEGRMessage()) {
return "EGR Activated";
}
// ...
return NO_ACTION_PERFORMED;
}
private void inhibitEGRMessage() { // ...
}
private boolean isInhibitedEGRMessage() { // ...
return true; // or false
}
}
// BSI factory manages to create only BSI instance
public static class BSIFactory {
private static BSI bsi;
public BSI build() {
if (bsi == null) {
bsi = new BSI();
}
return bsi;
}
}
public static class ECUTest {
@Test
public void testActivateFanUnit() {
// Setup
// -----
BSI fakableBsi = mock(BSI.class);
ECU ecu = new ECU(fakableBsi);
// Exercise SUT (software under test)
// ----------------------------------
// A side effect is produced by this tests in BSI: EGR message are inhibited
// But it does not matter since tests are run in isolation and current instance of BSI
// will be garbage collected
boolean actualEveryCommandProcessed = ecu.dispatchEngineParam("Engine too hot");
// Verify
// ------
boolean expectedEveryCommandProcessed = true;
assertEquals("...", expectedEveryCommandProcessed, actualEveryCommandProcessed);
}
@Test
public void testActivateEGR() {
// Setup
// -----
BSI fakableBsi = mock(BSI.class);
ECU ecu = new ECU(fakableBsi);
// Exercise SUT (software under test)
// ----------------------------------
// This test does not depend on the execution of the previous one, we have a fresh
// instance of BSI. Tests are run in isolation
boolean actualEveryCommandProcessed = ecu.dispatchEngineParam("EGR filter full");
// Verify
// ------
// Test succeeds
boolean expectedEveryCommandProcessed = true;
assertEquals("...", expectedEveryCommandProcessed, actualEveryCommandProcessed);
}
}
}
| 33.507353 | 99 | 0.530832 |
9a7286655090677254558f8309875207353b66ee | 773 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.pfc.soriano.ws.test.util.enums;
/**
*
* @author NACHO
*/
public enum EModelAPI {
CATEGORIAS("categorias"),
CATEGORIA("categoria"),
SUBCATEGORIAS("subcategorias"),
SUBCATEGORIA("subcategoria"),
TRUEQUES("trueques"),
TRUEQUE("trueque"),
USUARIOS("usuarios"),
USUARIO("usuario"),
VALORACIONES("valoraciones"),
VALORACION("valoracion");
private final String path;
private EModelAPI(String path) {
this.path = path;
}
public String getPath() {
return path;
}
}
| 21.472222 | 80 | 0.624838 |
0970566f418bcadbe2369d6b8602d6f1d55304e8 | 375 | package xyz.rexlin600.rabbitmq.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.lang.reflect.Method;
/**
* Amqp invoke
*
* @author hekunlin
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AmqpInvoke {
/**
* Methods
*/
public Method[] methods;
/**
* Object
*/
public Object object;
} | 12.931034 | 38 | 0.717333 |
6062b24b0e2db91b2068fe7b48f9ef9022877e16 | 5,169 | package de.rakuten.cloud.service.productserver.controllers;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import de.rakuten.cloud.service.productapi.exceptions.InvalidProductTypeException;
import de.rakuten.cloud.service.productserver.datatransferobjects.ErrorResponse;
import de.rakuten.cloud.service.productserver.exceptions.CategoryNotFoundException;
import de.rakuten.cloud.service.productserver.exceptions.InvalidCategoryException;
import de.rakuten.cloud.service.productserver.exceptions.InvalidCurrencyException;
import de.rakuten.cloud.service.productserver.exceptions.ProductNotFoundException;
import de.rakuten.cloud.service.productserver.exceptions.ProductServiceException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@ControllerAdvice
public class BaseController {
@ExceptionHandler(CategoryNotFoundException.class)
public ResponseEntity<ErrorResponse> categoryNotFoundException(CategoryNotFoundException exec,
HttpServletRequest request, HttpServletResponse response) {
ErrorResponse errorResponse = new ErrorResponse(new Date().toString(), HttpStatus.NOT_FOUND.name(),
HttpStatus.NOT_FOUND.value(), exec.getMessage(), null, request.getRequestURI());
log.warn(errorResponse.getMessage(), exec);
return new ResponseEntity<>(errorResponse, new HttpHeaders(),
HttpStatus.valueOf(errorResponse.getHttpStatusCode()));
}
@ExceptionHandler(ProductNotFoundException.class)
public ResponseEntity<ErrorResponse> productNotFoundException(ProductNotFoundException exec,
HttpServletRequest request, HttpServletResponse response) {
ErrorResponse errorResponse = new ErrorResponse(new Date().toString(), HttpStatus.NOT_FOUND.name(),
HttpStatus.NOT_FOUND.value(), exec.getMessage(), null, request.getRequestURI());
log.warn(errorResponse.getMessage(), exec);
return new ResponseEntity<>(errorResponse, new HttpHeaders(),
HttpStatus.valueOf(errorResponse.getHttpStatusCode()));
}
@ExceptionHandler(InvalidProductTypeException.class)
public ResponseEntity<ErrorResponse> invalidProductTypeException(InvalidProductTypeException exec,
HttpServletRequest request, HttpServletResponse response) {
ErrorResponse errorResponse = new ErrorResponse(new Date().toString(), HttpStatus.UNPROCESSABLE_ENTITY.name(),
HttpStatus.UNPROCESSABLE_ENTITY.value(), exec.getMessage(), null, request.getRequestURI());
log.warn(errorResponse.getMessage(), exec);
return new ResponseEntity<>(errorResponse, new HttpHeaders(),
HttpStatus.valueOf(errorResponse.getHttpStatusCode()));
}
@ExceptionHandler(InvalidCategoryException.class)
public ResponseEntity<ErrorResponse> invalidCategoryException(InvalidCategoryException exec,
HttpServletRequest request, HttpServletResponse response) {
ErrorResponse errorResponse = new ErrorResponse(new Date().toString(), HttpStatus.UNPROCESSABLE_ENTITY.name(),
HttpStatus.UNPROCESSABLE_ENTITY.value(), exec.getMessage(), null, request.getRequestURI());
log.warn(errorResponse.getMessage(), exec);
return new ResponseEntity<>(errorResponse, new HttpHeaders(),
HttpStatus.valueOf(errorResponse.getHttpStatusCode()));
}
@ExceptionHandler(InvalidCurrencyException.class)
public ResponseEntity<ErrorResponse> invalidCurrencyException(InvalidCurrencyException exec,
HttpServletRequest request, HttpServletResponse response) {
ErrorResponse errorResponse = new ErrorResponse(new Date().toString(), HttpStatus.UNPROCESSABLE_ENTITY.name(),
HttpStatus.UNPROCESSABLE_ENTITY.value(), exec.getMessage(), null, request.getRequestURI());
log.warn(errorResponse.getMessage(), exec);
return new ResponseEntity<>(errorResponse, new HttpHeaders(),
HttpStatus.valueOf(errorResponse.getHttpStatusCode()));
}
@ExceptionHandler(ProductServiceException.class)
public ResponseEntity<ErrorResponse> productServiceException(ProductServiceException exec,
HttpServletRequest request, HttpServletResponse response) {
ErrorResponse errorResponse = new ErrorResponse(new Date().toString(), HttpStatus.UNPROCESSABLE_ENTITY.name(),
HttpStatus.UNPROCESSABLE_ENTITY.value(), exec.getMessage(), null, request.getRequestURI());
log.warn(errorResponse.getMessage(), exec);
return new ResponseEntity<>(errorResponse, new HttpHeaders(),
HttpStatus.valueOf(errorResponse.getHttpStatusCode()));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> generic(Exception exec, HttpServletRequest request,
HttpServletResponse response) {
ErrorResponse errorResponse = new ErrorResponse(new Date().toString(), HttpStatus.BAD_REQUEST.name(),
HttpStatus.BAD_REQUEST.value(), exec.getMessage(), null, request.getRequestURI());
log.warn(errorResponse.getMessage(), exec);
return new ResponseEntity<>(errorResponse, new HttpHeaders(),
HttpStatus.valueOf(errorResponse.getHttpStatusCode()));
}
} | 46.567568 | 112 | 0.815051 |
c91703157b2d66544fbadfd4bdeb0d23df7c035a | 20,977 | package net.es.maddash.notifications;
import net.es.jsnow.ServiceNowClient;
import net.es.jsnow.oauth.OAuth2Details;
import net.es.jsnow.parameters.TableQueryParams;
import net.es.maddash.NetLogger;
import net.es.maddash.checks.TemplateVariableMap;
import org.apache.log4j.Logger;
import org.ho.yaml.Yaml;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.StringReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Creates records in ServiceNow (https://www.service-now.com) based on configuration provided
*/
public class ServiceNowNotification extends BaseNotification{
private Logger log = Logger.getLogger(ServiceNowNotification.class);
private Logger netlogger = Logger.getLogger("netlogger");
private String snowInstanceName;
private String clientId;
private String clientSecret;
private String username;
private String password;
private String recordTable;
private JsonObject recordFields;
private String dashboardUrl;
private JsonObject duplicateRules;
private JsonObject resolveFields;
final public static String PROP_SNOW_INSTANCE_NAME = "instance";
final public static String PROP_OAUTH_FILE = "oauthFile";
final public static String PROP_CLIENT_ID = "clientID";
final public static String PROP_CLIENT_SECRET = "clientSecret";
final public static String PROP_USERNAME = "username";
final public static String PROP_PASSWORD = "password";
final public static String PROP_RECORD_TABLE = "recordTable";
final public static String PROP_RECORD_FIELDS = "recordFields";
final public static String PROP_DASHBOARDURL = "dashboardUrl";
final public static String PROP_DUPLICATERULES = "duplicateRules";
final public static String PROP_DUPLICATERULES_RULES = "rules";
final public static String PROP_RULES_IDENTITYFIELDS = "identityFields";
final public static String PROP_RULES_EQUALSFIELDS = "equalsFields";
final public static String PROP_RULES_LTFIELDS = "ltFields";
final public static String PROP_RULES_GTFIELDS = "gtFields";
final public static String PROP_RULES_UPDATEFIELDS = "updateFields";
final public static String PROP_RESOLVEFIELDS = "resolveFields";
/**
* Initializes ServiceNow client based on configuration
* @param name name of the notification
* @param params configuration options
*/
public void init(String name, JsonObject params) {
NetLogger netLog = NetLogger.getTlogger();
netlogger.info(netLog.start("maddash.ServiceNowNotification.init"));
//get required properties
if(params.containsKey(PROP_SNOW_INSTANCE_NAME) && !params.isNull(PROP_SNOW_INSTANCE_NAME) ){
this.snowInstanceName = params.getString(PROP_SNOW_INSTANCE_NAME);
}else{
throw new RuntimeException("The property " + PROP_SNOW_INSTANCE_NAME + " must be specified");
}
if(params.containsKey(PROP_RECORD_TABLE) && !params.isNull(PROP_RECORD_TABLE) ){
this.recordTable = params.getString(PROP_RECORD_TABLE);
}else{
throw new RuntimeException("The property " + PROP_RECORD_TABLE + " must be specified");
}
if(params.containsKey(PROP_RECORD_FIELDS) && !params.isNull(PROP_RECORD_FIELDS) ){
this.recordFields = params.getJsonObject(PROP_RECORD_FIELDS);
}else{
throw new RuntimeException("The property " + PROP_RECORD_FIELDS + " must be specified");
}
//get oauth props from file
this.clientId = null;
this.clientSecret = null;
if(params.containsKey(PROP_OAUTH_FILE) && !params.isNull(PROP_OAUTH_FILE) ){
this.loadOAuthFile(params.getString(PROP_OAUTH_FILE));
}
//get OAuth properties - overrides file props
if(params.containsKey(PROP_USERNAME) && !params.isNull(PROP_USERNAME) ){
this.username = params.getString(PROP_USERNAME);
}else if(this.username == null){
//if not set by property or OAuth file, then error
throw new RuntimeException("The property " + PROP_USERNAME + " must be specified");
}
if(params.containsKey(PROP_PASSWORD) && !params.isNull(PROP_PASSWORD) ){
this.password = params.getString(PROP_PASSWORD);
}else if(this.password == null){
//if not set by property or OAuth file, then error
throw new RuntimeException("The property " + PROP_PASSWORD + " must be specified");
}
if(params.containsKey(PROP_CLIENT_ID) && !params.isNull(PROP_CLIENT_ID) ){
this.clientId = params.getString(PROP_CLIENT_ID);
}
if(params.containsKey(PROP_CLIENT_SECRET) && !params.isNull(PROP_CLIENT_SECRET) ){
this.clientSecret= params.getString(PROP_CLIENT_SECRET);
}
if(params.containsKey(PROP_DASHBOARDURL) && !params.isNull(PROP_DASHBOARDURL) ){
this.dashboardUrl= params.getString(PROP_DASHBOARDURL);
}else{
this.dashboardUrl = null;
}
if(params.containsKey(PROP_DUPLICATERULES) && !params.isNull(PROP_DUPLICATERULES) ){
this.duplicateRules = params.getJsonObject(PROP_DUPLICATERULES);
}else{
this.duplicateRules = null;
}
if(params.containsKey(PROP_RESOLVEFIELDS) && !params.isNull(PROP_RESOLVEFIELDS) ){
this.resolveFields = params.getJsonObject(PROP_RESOLVEFIELDS);
}else{
this.resolveFields = null;
}
netlogger.info(netLog.end("maddash.ServiceNowNotification.init"));
}
private void loadOAuthFile(String file){
NetLogger netLog = NetLogger.getTlogger();
netlogger.info(netLog.start("maddash.ServiceNowNotification.loadOAuthFile"));
//read file
Map oauthConfig = null;
try {
oauthConfig = (Map) Yaml.load(new File(file));
} catch (FileNotFoundException e) {
netlogger.error(netLog.error("maddash.ServiceNowNotification.loadOAuthFile", "Unable to find file " + file + ": " + e.getMessage()));
return;
}
if(oauthConfig == null){
//should not happen, but just to be safe
return;
}
//get parameters
if(oauthConfig.containsKey(PROP_CLIENT_ID) && oauthConfig.get(PROP_CLIENT_ID) != null){
this.clientId = oauthConfig.get(PROP_CLIENT_ID) + "";
}
if(oauthConfig.containsKey(PROP_CLIENT_SECRET) && oauthConfig.get(PROP_CLIENT_SECRET) != null){
this.clientSecret = oauthConfig.get(PROP_CLIENT_SECRET) + "";
}
if(oauthConfig.containsKey(PROP_USERNAME) && oauthConfig.get(PROP_USERNAME) != null){
this.username = oauthConfig.get(PROP_USERNAME) + "";
}
if(oauthConfig.containsKey(PROP_PASSWORD) && oauthConfig.get(PROP_PASSWORD) != null){
this.password = oauthConfig.get(PROP_PASSWORD) + "";
}
netlogger.info(netLog.end("maddash.ServiceNowNotification.loadOAuthFile"));
}
/**
* Creates or updates ServiceNow records given a list of problems
*
* @param problems the problems from which to create notifications
*/
public void send(int notificationId, List<NotifyProblem> problems, List<String> resolvedData) {
NetLogger netLog = NetLogger.getTlogger();
HashMap<String,String> netLogParams = new HashMap<String,String>();
netlogger.info(netLog.start("maddash.ServiceNowNotification.send"));
//don't send anything if no problems
if(problems.isEmpty()){
netlogger.info(netLog.end("maddash.ServiceNowNotification.send", "No problems found so no records created"));
return;
}
try {
//Setup oauth2 details
OAuth2Details oauth2Details = new OAuth2Details();
oauth2Details.setClientId(this.clientId);
oauth2Details.setClientSecret(this.clientSecret);
oauth2Details.setUsername(this.username);
oauth2Details.setPassword(this.password);
//Build client
ServiceNowClient snowclient = new ServiceNowClient(this.snowInstanceName, oauth2Details);
//iterate through problems
for (NotifyProblem p : problems) {
this.handleProblem(notificationId, snowclient, p);
}
//resolve issues
for (String sysId: resolvedData) {
this.handleResolve(snowclient, sysId);
}
netlogger.info(netLog.end("maddash.ServiceNowNotification.send", "Operation completed", null, netLogParams));
}catch(Exception e){
e.printStackTrace();
netlogger.info(netLog.error("maddash.ServiceNowNotification.send", e.getMessage(), null, netLogParams));
}
}
private void handleResolve(ServiceNowClient snowclient, String sysId){
//init logging
NetLogger netLog = NetLogger.getTlogger();
HashMap<String,String> netLogParams = new HashMap<String,String>();
netLogParams.put("sysid", sysId);
String netLogMsg = "";
netlogger.info(netLog.start("maddash.ServiceNowNotification.handleResolve", null, null, netLogParams));
//update record, but ignore errors if fails
try {
snowclient.updateRecord(this.recordTable, sysId, this.resolveFields);
}catch(Exception e){
netlogger.info(netLog.end("maddash.ServiceNowNotification.handleResolve", e.getMessage(), null, netLogParams));
}
netlogger.info(netLog.end("maddash.ServiceNowNotification.handleResolve", null, null, netLogParams));
}
private void handleProblem(int notificationId, ServiceNowClient snowclient, NotifyProblem p){
//init logging
NetLogger netLog = NetLogger.getTlogger();
HashMap<String,String> netLogParams = new HashMap<String,String>();
String netLogMsg = "";
netlogger.info(netLog.start("maddash.ServiceNowNotification.handleProblem"));
//don't send anything if no problems
if(p == null || p.getProblem() == null){
netlogger.info(netLog.end("maddash.ServiceNowNotification.handleProblem", "Problems null, so nothing to do"));
return;
}
//load some logging fields
netLogParams.put("problemGrid", p.getGridName());
netLogParams.put("problemSite", p.getSiteName());
netLogParams.put("problemName", p.getProblem().getName());
netLogParams.put("problemCat", p.getProblem().getCategory());
netLogParams.put("problemSeverity", p.getProblem().getSeverity()+"");
//expand record template
JsonObject expandedRecordField = this.expandRecordFields(p, this.recordFields);
//check for duplicate record
String duplicateRecordId = this.handleDuplicateRecord(snowclient, expandedRecordField, p);
if (duplicateRecordId != null) {
netLogParams.put("action", "update");
//update happened in handleDuplicateRecord
this.updateAppData(notificationId, p, duplicateRecordId);
} else {
netLogParams.put("action", "create");
JsonObject response = snowclient.createRecord(this.recordTable, expandedRecordField);
netLogParams.put("snowResponse", response+"");
String sys_id = this.parseSysId(response);
if(sys_id != null){
this.updateAppData(notificationId, p, sys_id);
}
netLogMsg = "Created record from problem";
}
netlogger.info(netLog.end("maddash.ServiceNowNotification.handleProblem", netLogMsg, null, netLogParams));
}
private String parseSysId(JsonObject response) {
if (response == null) {
return null;
}
JsonObject result = response.getJsonObject("result");
if(result == null){
return null;
}
if(result.containsKey("sys_id") && !result.isNull("sys_id")){
return result.getString("sys_id");
}
return null;
}
private String handleDuplicateRecord(ServiceNowClient snowclient, JsonObject expandedRecordField, NotifyProblem p) {
//Logger initialization
NetLogger netLog = NetLogger.getTlogger();
String netLogMsg = "";
HashMap<String,String> netLogParams = new HashMap<String,String>();
netlogger.debug(netLog.start("maddash.ServiceNowNotification.handleDuplicateRecord"));
//no duplicate rules then nothing to check
if(this.duplicateRules == null){
netlogger.debug(netLog.end("maddash.ServiceNowNotification.handleDuplicateRecord", "No duplicate rules so nothing to check"));
return null;
}
//get id fields
List<String> idQuery = new ArrayList<String>();
if(this.duplicateRules.containsKey(PROP_RULES_IDENTITYFIELDS) &&
!this.duplicateRules.isNull(PROP_RULES_IDENTITYFIELDS)){
JsonArray idFields = this.duplicateRules.getJsonArray(PROP_RULES_IDENTITYFIELDS);
for(int i = 0; i < idFields.size(); i++) {
String idField = idFields.getString(i);
if(expandedRecordField.containsKey(idField)) {
idQuery.add(idField + "=" + expandedRecordField.getString(idField + ""));
}else{
String errMsg = "In the " + PROP_DUPLICATERULES +
" section of your configuration, an invalid " +
PROP_RULES_EQUALSFIELDS + "entry is given";
netlogger.debug(netLog.error("maddash.ServiceNowNotification.handleDuplicateRecord", errMsg));
throw new RuntimeException(errMsg);
}
}
}
//if no rules, then nothing to do
if(!this.duplicateRules.containsKey(PROP_DUPLICATERULES_RULES) ||
this.duplicateRules.isNull(PROP_DUPLICATERULES_RULES)) {
netlogger.info(netLog.end("maddash.ServiceNowNotification.handleDuplicateRecord", netLogMsg, null, netLogParams));
return null;
}
//loop through rules until find the first one that matches something
JsonArray rules = this.duplicateRules.getJsonArray(PROP_DUPLICATERULES_RULES);
for(int i = 0; i < rules.size(); i++) {
JsonObject rule = rules.getJsonObject(i);
List<String> snowQuery = new ArrayList<String>();
snowQuery.addAll(idQuery);
//get equals fields
if (rule.containsKey(PROP_RULES_EQUALSFIELDS) && !rule.isNull(PROP_RULES_EQUALSFIELDS)) {
JsonObject eqFields = rule.getJsonObject(PROP_RULES_EQUALSFIELDS);
for (String eqField : eqFields.keySet()) {
snowQuery.add(eqField + "=" + eqFields.get(eqField));
}
}
//get lt fields
if (rule.containsKey(PROP_RULES_LTFIELDS) && !rule.isNull(PROP_RULES_LTFIELDS)) {
JsonObject ltFields = rule.getJsonObject(PROP_RULES_LTFIELDS);
for (String ltField : ltFields.keySet()) {
snowQuery.add(ltField + "<" + ltFields.get(ltField));
}
}
//get gt fields
if (rule.containsKey(PROP_RULES_GTFIELDS) && !rule.isNull(PROP_RULES_GTFIELDS)) {
JsonObject gtFields = rule.getJsonObject(PROP_RULES_GTFIELDS);
for (String gtField : gtFields.keySet()) {
snowQuery.add(gtField + ">" + gtFields.get(gtField));
}
}
//build query string
String snowQueryString = String.join("^", snowQuery);
TableQueryParams queryParams = new TableQueryParams();
queryParams.setQuery(snowQueryString);
netLogParams.put("getParams", queryParams.toGetParams());
//perform query
JsonObject duplicateResults = snowclient.queryTable(this.recordTable, queryParams);
if (duplicateResults.containsKey("result") && !duplicateResults.isNull("result")) {
netLogParams.put("dupCount", duplicateResults.size() + "");
if (!duplicateResults.getJsonArray("result").isEmpty()) {
//only grab the first result
JsonObject record = duplicateResults.getJsonArray("result").getJsonObject(0);
if (record.containsKey("sys_id") && !record.isNull("sys_id")) {
String duplicateRecordId = record.getString("sys_id");
netLogParams.put("duplicateRecordId", duplicateRecordId);
//check if we want to update the duplicate or do nothing
if (rule.containsKey(PROP_RULES_UPDATEFIELDS) && !rule.isNull(PROP_RULES_UPDATEFIELDS)) {
netLogParams.put("action", "update");
JsonObject updateObject = this.expandRecordFields(p, rule.getJsonObject(PROP_RULES_UPDATEFIELDS));
snowclient.updateRecord(this.recordTable, duplicateRecordId, updateObject);
netLogParams.put("duplicateRecordId", duplicateRecordId);
netLogMsg = "Updated record";
} else {
netLogParams.put("action", "none");
netLogMsg = "UpdateFields not configured so not updating duplicate record";
}
netlogger.info(netLog.end("maddash.ServiceNowNotification.handleDuplicateRecord", netLogMsg, null, netLogParams));
return duplicateRecordId;
}
}
}
}
netlogger.info(netLog.end("maddash.ServiceNowNotification.handleDuplicateRecord", netLogMsg, null, netLogParams));
return null;
}
private JsonObject expandRecordFields(NotifyProblem p, JsonObject record) {
NetLogger netLog = NetLogger.getTlogger();
netlogger.debug(netLog.start("maddash.ServiceNowNotification.expandRecordFields"));
HashMap<String,String> netLogParams = new HashMap<String,String>();
//convert to string
TemplateVariableMap templateVars = new TemplateVariableMap();
String str = record + "";
templateVars.put("%br", "\\\\n");
if(p.getSiteName() != null) {
templateVars.put("%problemEntity", p.getSiteName() + "");
}else if(p.getGridName() != null){
templateVars.put("%problemEntity", p.getGridName() + "");
}else{
templateVars.put("%problemEntity", "Unknown");
}
if(p.getGridName() != null && this.dashboardUrl != null){
String gridUrl = this.dashboardUrl;
if(!gridUrl.endsWith("/")){
gridUrl += "/";
}
try {
gridUrl += "index.cgi?grid=" + URLEncoder.encode(p.getGridName(), "UTF-8");
}catch(Exception e){}
templateVars.put("%gridUrl", gridUrl);
String gridLink = "[code]<a href=\\\\\"" + gridUrl + "\\\\\" target=\\\\\"_blank\\\\\">View Grid</a>[/code]";
templateVars.put("%gridLink", gridLink);
}
templateVars.put("%siteName", p.getSiteName() + "");
templateVars.put("%gridName", p.getGridName()+ "");
templateVars.put("%isGlobal", p.isGlobal() + "");
templateVars.put("%severity", p.getProblem().getSeverity() + "");
templateVars.put("%category", p.getProblem().getCategory()+ "");
StringBuilder solutions = new StringBuilder();
if(p.getProblem().getSolutions() != null && !p.getProblem().getSolutions().isEmpty()){
for(String solution : p.getProblem().getSolutions()){
solutions.append(" - ").append(solution).append("\\\\n");
}
}else{
solutions.append(" - None available").append("\\\\n");
}
templateVars.put("%solutions", solutions.toString());
templateVars.put("%name", p.getProblem().getName()+ "");
//replace variables
for(String var: templateVars.keySet()){
String val = templateVars.get(var);
if(val == null || val.toLowerCase().equals("null")) {
val = "n/a";
}
str = str.replaceAll(var, val);
}
//create object
JsonObject jsonResult = Json.createReader(new StringReader(str)).readObject();
netLogParams.put("expandedJson", jsonResult + "");
netlogger.debug(netLog.end("maddash.ServiceNowNotification.expandRecordFields",null,null, netLogParams));
return jsonResult;
}
}
| 47.139326 | 145 | 0.632121 |
00302347ac015d7bc9c00d918ad730fd5fbb42f0 | 1,546 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.cam.ceb.como.chem.filemgmt.gaussian.parser.geometry.util;
import java.io.Serializable;
/**
*
* @author pb556
*/
public class ChemCompound implements Serializable {
protected Object compound = null;
protected Object pos = null; //HashMap<Atom, Point3>
protected String path = null;
protected String id = null;
protected int multiplicity = 0;
protected int formalCharge = 0;
public void setCompound(Object compound) {
this.compound = compound;
}
public void setPath(String path) {
this.path = path;
}
public void setID(String id) {
this.id = id;
}
public void setPosition(Object pos) {
this.pos = pos;
}
public void setSpinMultiplicity(int multiplicity) {
this.multiplicity = multiplicity;
}
public void setFormalCharge(int charge) {
this.formalCharge = charge;
}
public Object getCompound(){
return this.compound;
}
public String getPath() {
return this.path;
}
public String getID() {
return this.id;
}
public Object getPosition() {
return this.pos;
}
public int getSpinMultiplicity() {
return this.multiplicity;
}
public int getFormalCharge() {
return this.formalCharge;
}
}
| 21.774648 | 70 | 0.578913 |
7d799cd8d9de6ac57303776938340c5c3b820555 | 1,510 | package com.leif.knowme.service;
import com.leif.knowme.base.BaseContext;
import com.leif.knowme.exception.AppException;
import com.leif.knowme.factory.ScheduleFactory;
import com.leif.knowme.dto.ScheduleDto;
import com.leif.knowme.dto.TodoDto;
import com.leif.knowme.repository.ScheduleRepository;
import com.leif.knowme.repository.TodoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
@Service
public class ScheduleService {
@Autowired
ScheduleRepository scheduleRepo;
@Autowired
TodoRepository todoRepo;
@Transactional(rollbackFor = Exception.class)
public int createSchedule(ScheduleDto scheduleDto, List<String> todoIds) throws AppException {
List<TodoDto> todoDtos = todoRepo.getTodosByIds(scheduleDto.getAccountId(), todoIds);
ScheduleFactory.assembleTodos(scheduleDto, todoDtos);
return scheduleRepo.saveSchedule(scheduleDto);
}
public ScheduleDto previewSchedule(BaseContext context, Date planStartTime, List<String> todoIds) throws
AppException {
List<TodoDto> todoDtos = todoRepo.getTodosByIds(context.getAccountId(), todoIds);
return ScheduleFactory.buildFromTodos(planStartTime, todoDtos);
}
public ScheduleDto getLatestSchedule(String accountId) {
return scheduleRepo.getLatestSchedule(accountId);
}
}
| 35.952381 | 108 | 0.781457 |
cf31b95851a3b3ec81873714225bd444a0085be1 | 822 | package org.tlh.springcloud.config.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import java.util.List;
import java.util.Map;
/**
* @author huping
* @desc
* @date 18/10/7
*/
@Data
@RefreshScope
@ConfigurationProperties(prefix = NestingProperty.SCC_PREFIX)
public class NestingProperty {
public static final String SCC_PREFIX="scc.config.client";
private String secret;
private Long expire;
private RateLimit rateLimit;
private Map<String,Item> docket;
@Data
static class RateLimit{
private Long rate;
private Long remaining;
List<Item> items;
}
@Data
static class Item{
private String name;
}
}
| 18.681818 | 75 | 0.714112 |
c3c31b93b70c10318153d243d10c59d66f071dc2 | 2,585 | package net.degrendel.gui;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
public class AboutDialog extends JDialog {
private static final long serialVersionUID = 8103133740529042448L;
private final JPanel contentPanel = new JPanel();
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
AboutDialog dialog = new AboutDialog();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public AboutDialog() {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("notice");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer text = new StringBuffer();
String ligne;
try {
while ((ligne = reader.readLine()) != null) {
text.append(ligne + "\n");
}
} catch (IOException e1) {
e1.printStackTrace();
}
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setAlwaysOnTop(true);
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new BorderLayout(0, 0));
{
JScrollPane scrollPane = new JScrollPane();
contentPanel.add(scrollPane, BorderLayout.CENTER);
{
JTextArea textArea = new JTextArea();
scrollPane.setViewportView(textArea);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setText(text.toString());
textArea.setEditable(false);
}
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.setActionCommand("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
}
}
}
| 27.210526 | 92 | 0.697872 |
588400dba2deab3a2bac892fc555317210899e99 | 9,284 | /*
* Copyright 2018 Google LLC. 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.google.cloud.tools.maven.deploy;
import static org.junit.Assert.fail;
import com.google.cloud.tools.appengine.AppEngineException;
import com.google.cloud.tools.appengine.configuration.DeployConfiguration;
import com.google.cloud.tools.appengine.configuration.DeployProjectConfigurationConfiguration;
import com.google.cloud.tools.appengine.operations.Deployment;
import com.google.cloud.tools.maven.cloudsdk.CloudSdkAppEngineFactory;
import com.google.cloud.tools.maven.deploy.AppDeployer.ConfigBuilder;
import com.google.cloud.tools.maven.stage.Stager;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class AppDeployerTest {
@Rule public TemporaryFolder tempFolder = new TemporaryFolder();
@Mock private ConfigBuilder configBuilder;
@Mock private Stager stager;
@Mock private AbstractDeployMojo deployMojo;
private Path stagingDirectory;
private Path appengineDirectory;
@Mock private CloudSdkAppEngineFactory appEngineFactory;
@Mock private Deployment appEngineDeployment;
@Mock private DeployConfiguration deployConfiguration;
@Mock private DeployProjectConfigurationConfiguration deployProjectConfigurationConfiguration;
@Mock private Log mockLog;
private AppDeployer testDeployer;
@Before
public void setup() throws IOException {
stagingDirectory = tempFolder.newFolder("staging").toPath();
appengineDirectory = tempFolder.newFolder("appengine").toPath();
testDeployer = new AppDeployer(deployMojo, stager, configBuilder, appengineDirectory);
Mockito.when(deployMojo.getStagingDirectory()).thenReturn(stagingDirectory);
Mockito.when(deployMojo.getAppEngineFactory()).thenReturn(appEngineFactory);
Mockito.when(appEngineFactory.deployment()).thenReturn(appEngineDeployment);
Mockito.when(configBuilder.buildDeployProjectConfigurationConfiguration(appengineDirectory))
.thenReturn(deployProjectConfigurationConfiguration);
Mockito.when(deployMojo.getLog()).thenReturn(mockLog);
}
@Test
public void testDeploy() throws MojoExecutionException, AppEngineException {
Mockito.when(configBuilder.buildDeployConfiguration(ImmutableList.of(stagingDirectory)))
.thenReturn(deployConfiguration);
testDeployer.deploy();
Mockito.verify(stager).stage();
Mockito.verify(appEngineDeployment).deploy(deployConfiguration);
}
private List<Path> createStagedYamls(String... names) throws IOException {
List<Path> createdFiles = new ArrayList<>();
for (String name : names) {
createdFiles.add(Files.createFile(appengineDirectory.resolve(name + ".yaml")));
}
return createdFiles;
}
private Path createAppYaml() throws IOException {
return Files.createFile(stagingDirectory.resolve("app.yaml"));
}
@Test
public void testDeployAll_allYamls()
throws MojoExecutionException, AppEngineException, IOException {
List<Path> files =
ImmutableList.<Path>builder()
.add(createAppYaml())
.addAll(createStagedYamls("cron", "dispatch", "dos", "index", "queue"))
.build();
// also create a file we'll ignore
Files.createFile(appengineDirectory.resolve("ignored"));
Mockito.when(configBuilder.buildDeployConfiguration(Mockito.eq(files)))
.thenReturn(deployConfiguration);
testDeployer.deployAll();
Mockito.verify(stager).stage();
Mockito.verify(appEngineDeployment).deploy(deployConfiguration);
}
@Test
public void testDeployAll_someYamls()
throws MojoExecutionException, AppEngineException, IOException {
List<Path> files =
ImmutableList.<Path>builder()
.add(createAppYaml())
.addAll(createStagedYamls("dispatch", "dos", "queue"))
.build();
// also create a file we'll ignore
Files.createFile(appengineDirectory.resolve("ignored"));
Mockito.when(configBuilder.buildDeployConfiguration(Mockito.eq(files)))
.thenReturn(deployConfiguration);
testDeployer.deployAll();
Mockito.verify(stager).stage();
Mockito.verify(configBuilder).buildDeployConfiguration(files);
Mockito.verify(appEngineDeployment).deploy(deployConfiguration);
}
@Test
public void testDeployAll_noAppYaml() throws IOException {
createStagedYamls("dos", "cron");
try {
testDeployer.deployAll();
fail();
} catch (MojoExecutionException ex) {
Assert.assertEquals("Failed to deploy all: could not find app.yaml.", ex.getMessage());
}
}
@Test
public void testDeployCron() throws MojoExecutionException, AppEngineException {
testDeployer.deployCron();
Mockito.verify(stager).stage();
Mockito.verify(configBuilder).buildDeployProjectConfigurationConfiguration(appengineDirectory);
Mockito.verify(appEngineDeployment).deployCron(deployProjectConfigurationConfiguration);
}
@Test
public void testDeployDos() throws MojoExecutionException, AppEngineException {
testDeployer.deployDos();
Mockito.verify(stager).stage();
Mockito.verify(configBuilder).buildDeployProjectConfigurationConfiguration(appengineDirectory);
Mockito.verify(appEngineDeployment).deployDos(deployProjectConfigurationConfiguration);
}
@Test
public void testDeployDispatch() throws MojoExecutionException, AppEngineException {
testDeployer.deployDispatch();
Mockito.verify(stager).stage();
Mockito.verify(configBuilder).buildDeployProjectConfigurationConfiguration(appengineDirectory);
Mockito.verify(appEngineDeployment).deployDispatch(deployProjectConfigurationConfiguration);
}
@Test
public void testDeployIndex() throws MojoExecutionException, AppEngineException {
testDeployer.deployIndex();
Mockito.verify(stager).stage();
Mockito.verify(configBuilder).buildDeployProjectConfigurationConfiguration(appengineDirectory);
Mockito.verify(appEngineDeployment).deployIndex(deployProjectConfigurationConfiguration);
}
@Test
public void testDeployQueue() throws MojoExecutionException, AppEngineException {
testDeployer.deployQueue();
Mockito.verify(stager).stage();
Mockito.verify(configBuilder).buildDeployProjectConfigurationConfiguration(appengineDirectory);
Mockito.verify(appEngineDeployment).deployQueue(deployProjectConfigurationConfiguration);
}
@Test
public void testBuildDeployConfiguration() {
AbstractDeployMojo deployMojo = Mockito.mock(AbstractDeployMojo.class);
Mockito.when(deployMojo.getBucket()).thenReturn("testBucket");
Mockito.when(deployMojo.getGcloudMode()).thenReturn("beta");
Mockito.when(deployMojo.getImageUrl()).thenReturn("testImageUrl");
Mockito.when(deployMojo.getProjectId()).thenReturn("testProjectId");
Mockito.when(deployMojo.getPromote()).thenReturn(false);
Mockito.when(deployMojo.getStopPreviousVersion()).thenReturn(false);
Mockito.when(deployMojo.getServer()).thenReturn("testServer");
Mockito.when(deployMojo.getVersion()).thenReturn("testVersion");
ConfigProcessor configProcessor = Mockito.mock(ConfigProcessor.class);
Mockito.when(configProcessor.processProjectId("testProjectId"))
.thenReturn("processedTestProjectId");
Mockito.when(configProcessor.processVersion("testVersion")).thenReturn("processedTestVersion");
List<Path> deployables = ImmutableList.of(Paths.get("some/path"), Paths.get("some/other/path"));
DeployConfiguration deployConfig =
new ConfigBuilder(deployMojo, configProcessor).buildDeployConfiguration(deployables);
Assert.assertEquals(deployables, deployConfig.getDeployables());
Assert.assertEquals("beta", deployConfig.getGcloudMode());
Assert.assertEquals("testBucket", deployConfig.getBucket());
Assert.assertEquals("testImageUrl", deployConfig.getImageUrl());
Assert.assertEquals("processedTestProjectId", deployConfig.getProjectId());
Assert.assertEquals(Boolean.FALSE, deployConfig.getPromote());
Assert.assertEquals(Boolean.FALSE, deployConfig.getStopPreviousVersion());
Assert.assertEquals("testServer", deployConfig.getServer());
Assert.assertEquals("processedTestVersion", deployConfig.getVersion());
}
}
| 41.262222 | 100 | 0.771435 |
cbb0279e86ac5da8e956d4240a77346a52d7c483 | 4,251 | package com.lotus.dao.gmapper;
import com.lotus.dao.pojo.Content;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.type.JdbcType;
public interface ContentMapper {
@Delete({
"delete from co_content",
"where id = #{id,jdbcType=INTEGER}"
})
int deleteByPrimaryKey(Integer id);
@Insert({
"insert into co_content (taxonomy_id, title, ",
"text, summary, thumbnail, ",
"is_stick, is_published, ",
"sort_num, source, ",
"source_href, created, ",
"modified, icon)",
"values (#{taxonomyId,jdbcType=INTEGER}, #{title,jdbcType=VARCHAR}, ",
"#{text,jdbcType=VARCHAR}, #{summary,jdbcType=VARCHAR}, #{thumbnail,jdbcType=VARCHAR}, ",
"#{isStick,jdbcType=INTEGER}, #{isPublished,jdbcType=INTEGER}, ",
"#{sortNum,jdbcType=INTEGER}, #{source,jdbcType=VARCHAR}, ",
"#{sourceHref,jdbcType=VARCHAR}, #{created,jdbcType=TIMESTAMP}, ",
"#{modified,jdbcType=TIMESTAMP}, #{icon,jdbcType=VARCHAR})"
})
@SelectKey(statement="SELECT LAST_INSERT_ID()", keyProperty="id", before=false, resultType=Integer.class)
int insert(Content record);
@InsertProvider(type=ContentSqlProvider.class, method="insertSelective")
@SelectKey(statement="SELECT LAST_INSERT_ID()", keyProperty="id", before=false, resultType=Integer.class)
int insertSelective(Content record);
@Select({
"select",
"id, taxonomy_id, title, text, summary, thumbnail, is_stick, is_published, sort_num, ",
"source, source_href, created, modified, icon",
"from co_content",
"where id = #{id,jdbcType=INTEGER}"
})
@Results({
@Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="taxonomy_id", property="taxonomyId", jdbcType=JdbcType.INTEGER),
@Result(column="title", property="title", jdbcType=JdbcType.VARCHAR),
@Result(column="text", property="text", jdbcType=JdbcType.VARCHAR),
@Result(column="summary", property="summary", jdbcType=JdbcType.VARCHAR),
@Result(column="thumbnail", property="thumbnail", jdbcType=JdbcType.VARCHAR),
@Result(column="is_stick", property="isStick", jdbcType=JdbcType.INTEGER),
@Result(column="is_published", property="isPublished", jdbcType=JdbcType.INTEGER),
@Result(column="sort_num", property="sortNum", jdbcType=JdbcType.INTEGER),
@Result(column="source", property="source", jdbcType=JdbcType.VARCHAR),
@Result(column="source_href", property="sourceHref", jdbcType=JdbcType.VARCHAR),
@Result(column="created", property="created", jdbcType=JdbcType.TIMESTAMP),
@Result(column="modified", property="modified", jdbcType=JdbcType.TIMESTAMP),
@Result(column="icon", property="icon", jdbcType=JdbcType.VARCHAR)
})
Content selectByPrimaryKey(Integer id);
@UpdateProvider(type=ContentSqlProvider.class, method="updateByPrimaryKeySelective")
int updateByPrimaryKeySelective(Content record);
@Update({
"update co_content",
"set taxonomy_id = #{taxonomyId,jdbcType=INTEGER},",
"title = #{title,jdbcType=VARCHAR},",
"text = #{text,jdbcType=VARCHAR},",
"summary = #{summary,jdbcType=VARCHAR},",
"thumbnail = #{thumbnail,jdbcType=VARCHAR},",
"is_stick = #{isStick,jdbcType=INTEGER},",
"is_published = #{isPublished,jdbcType=INTEGER},",
"sort_num = #{sortNum,jdbcType=INTEGER},",
"source = #{source,jdbcType=VARCHAR},",
"source_href = #{sourceHref,jdbcType=VARCHAR},",
"created = #{created,jdbcType=TIMESTAMP},",
"modified = #{modified,jdbcType=TIMESTAMP},",
"icon = #{icon,jdbcType=VARCHAR}",
"where id = #{id,jdbcType=INTEGER}"
})
int updateByPrimaryKey(Content record);
} | 47.764045 | 109 | 0.673489 |
be9837dd8378b9c4d2bd0baaf225ba92a6080659 | 1,638 | package com.tz.core;
import java.util.Properties;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
//@Intercepts({ @Signature(type = Executor.class, method = "update", args = {
//MappedStatement.class, Object.class }) })
@Intercepts({ @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }),
@Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class })
})
public class ExamplePlugin implements Interceptor {
public Object intercept(Invocation invocation) throws Throwable {
System.out.println("=================="+invocation);
System.out.println("=================="+invocation.getTarget().getClass().getName());
System.out.println("=================="+invocation.getMethod());
System.out.println("=================="+invocation.getArgs());
MappedStatement statement = (MappedStatement) invocation.getArgs()[0];
System.out.println(statement.getId());
return invocation.proceed();
}
public Object plugin(Object target) {
System.out.println("**********************"+target);
return Plugin.wrap(target, this);
}
public void setProperties(Properties properties) {
System.out.println("333333333333333333333333"+properties);
}
} | 39.95122 | 152 | 0.717338 |
be8b2fd3afc8fa0e04a024fab298125d1806832c | 1,542 | package br.com.mpssolutions.bookmarkapp.entities;
import java.util.Arrays;
import br.com.mpssolutions.bookmarkapp.constants.MovieGenre;
public class Movie extends Bookmark {
private int releaseYear;
private String[] cast;
private String[] directors;
private MovieGenre genre;
private double imdbRating;
public int getReleaseYear() {
return releaseYear;
}
public void setReleaseYear(int releaseYear) {
this.releaseYear = releaseYear;
}
public String[] getCast() {
return cast;
}
public void setCast(String[] cast) {
this.cast = cast;
}
public String[] getDirectors() {
return directors;
}
public void setDirectors(String[] directors) {
this.directors = directors;
}
public MovieGenre getGenre() {
return genre;
}
public void setGenre(MovieGenre genre) {
this.genre = genre;
}
public double getImdbRating() {
return imdbRating;
}
public void setImdbRating(double imdbRating) {
this.imdbRating = imdbRating;
}
@Override
public String toString() {
return String.format(
"Movie ID: %s%nTitle: %s%nRelease Year: %d%nCast: %s%nDiretor(s): %s%n"
+ "Genre: %s%nIMDB Rating: %.1f%nProfile URL: %s%n%n",
this.getId(), this.getTitle(), releaseYear, Arrays.deepToString(cast), Arrays.deepToString(directors),
genre, imdbRating, this.getProfileUrl());
}
@Override
public boolean isKidFriendlyEligible() {
if (genre.equals(MovieGenre.HORROR) || genre.equals(MovieGenre.THRILLERS)
|| genre.equals(MovieGenre.FOREGIN_THRILLERS))
return false;
return true;
}
}
| 21.123288 | 106 | 0.716602 |
0a6278497edd64b920c1ed98343e0492e212e14b | 5,433 | package com.bulbinc.nick;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
public class FragmentSettings extends Fragment {
Switch news, jam, music, concert;
SharedPreferences settings;
Boolean news_b,jam_b,music_b,concert_b;
private OnFragmentInteractionListener mListener;
Button sign_out;
TextView user_name,user_email;
public FragmentSettings() {
// Required empty public constructor
}
public static FragmentSettings newInstance(String param1, String param2) {
FragmentSettings fragment = new FragmentSettings();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_settings, container, false);
news = (Switch) view.findViewById(R.id.switch_news);
jam = (Switch) view.findViewById(R.id.switch_new_jamming_video);
music = (Switch) view.findViewById(R.id.switch_new_music_video);
concert = (Switch) view.findViewById(R.id.switch_nearest_concert);
settings = getActivity().getSharedPreferences("LEL", 0);
news_b = settings.getBoolean("noti_news_settings", true);
jam_b = settings.getBoolean("noti_jam_settings", true);
music_b = settings.getBoolean("noti_music_settings", true);
concert_b = settings.getBoolean("noti_concert_settings", true);
user_name = (TextView) view.findViewById(R.id.user_name);
user_email = (TextView) view.findViewById(R.id.user_email);
user_email.setText(settings.getString("user_email", "User email"));
user_name.setText(settings.getString("user_name", "User Name"));
sign_out = (Button) view.findViewById(R.id.sign_out_button);
sign_out.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences settings = getActivity().getSharedPreferences("LEL", 0);
SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.commit();
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
getActivity().finish();
}
});
SharedPreferences.Editor editor = settings.edit();
editor.putString("fragment_name", "settings");
editor.commit();
news.setChecked(news_b);
jam.setChecked(jam_b);
music.setChecked(music_b);
concert.setChecked(concert_b);
final SharedPreferences.Editor edit = settings.edit();
news.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
edit.putBoolean("noti_news_settings",isChecked);
edit.commit();
}
});
jam.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
edit.putBoolean("noti_jam_settings",isChecked);
edit.commit();
}
});
music.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
edit.putBoolean("noti_music_settings",isChecked);
edit.commit();
}
});
concert.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
edit.putBoolean("noti_concert_settings",isChecked);
edit.commit();
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction_settings(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction_settings(Uri uri);
}
}
| 34.826923 | 90 | 0.65323 |
3873ac982ae4d7be8b414db75e8f0e4bb395919f | 245 | package llh.circular;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class B {
@Autowired
private A a;
public void doB(){
System.err.println("do B...");
}
}
| 16.333333 | 62 | 0.746939 |
ff6a2494b26556b8a3b1081ee82117990da6315e | 3,755 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
package com.google.cloud.compute.v1;
public interface TargetPoolsAddInstanceRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.TargetPoolsAddInstanceRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name
* </pre>
*
* <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code>
*/
java.util.List<com.google.cloud.compute.v1.InstanceReference> getInstancesList();
/**
*
*
* <pre>
* A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name
* </pre>
*
* <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code>
*/
com.google.cloud.compute.v1.InstanceReference getInstances(int index);
/**
*
*
* <pre>
* A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name
* </pre>
*
* <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code>
*/
int getInstancesCount();
/**
*
*
* <pre>
* A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name
* </pre>
*
* <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code>
*/
java.util.List<? extends com.google.cloud.compute.v1.InstanceReferenceOrBuilder>
getInstancesOrBuilderList();
/**
*
*
* <pre>
* A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name
* </pre>
*
* <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code>
*/
com.google.cloud.compute.v1.InstanceReferenceOrBuilder getInstancesOrBuilder(int index);
}
| 48.141026 | 337 | 0.732889 |
c03642a65a232520e80b668953fb21105689ecfa | 1,322 | package com.github.miginmrs.jlogic.terms;
import com.github.miginmrs.jlogic.values.IntegerValue;
import com.github.miginmrs.jlogic.values.Value;
import java.util.Objects;
public class ConstInteger implements IntegerTerm {
private final IntegerValue a;
public ConstInteger(int a) {
this.a = new IntegerValue(a);
}
@Override
public IntegerValue getValue(Value[] vars) {
return a;
}
@Override
public boolean setValue(Value[] vars, IntegerValue value) {
return Objects.equals(value, a);
}
@Override
public boolean isVariable() {
return false;
}
@Override
public boolean isVariable(Value[] vars) {
return false;
}
@Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + Objects.hashCode(this.a);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof ConstInteger)) {
return false;
}
final ConstInteger other = (ConstInteger) obj;
return Objects.equals(this.a, other.a);
}
@Override
public String toString() {
return a.toString();
}
@Override
public String toString(String[] varNames, int priority) {
return a.toString();
}
}
| 21.672131 | 63 | 0.612708 |
67b741d441f0deaacbadcb12d7a3b2b73b463c49 | 397 | package com.kosho.ssql.elasticsearch.sharding.condition;
import com.kosho.ssql.core.dsl.semantic.Ssql;
/**
* 分片条件解析器工厂
*
* @author Kosho
* @since 2021-08-27
*/
public class ShardingConditionParserFactory {
public static ShardingConditionParser<Ssql> getSsqlConditionParser(Ssql ssql) {
// where condition parser
return SsqlQueryShardingConditionParser.INSTANCE;
}
}
| 23.352941 | 83 | 0.743073 |
cf2864dfbc448a0453770b87815c0ec19ecc3358 | 3,540 | /*
* This class extracts the result predicted by CRF++ pipeline
* in category of Location, Organization, Person, MISC
* refer to NE-ExtractorFormat as example output
* @author Hao Zhang
*/
package nlp.opennlp;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class NEextractor {
private static final String OUTPUT_PATH = "../NE-Extractor-Result.txt";
private static final String INPUT_PATH = "../tagged.txt";
static HashMap<String, Integer> loc = new HashMap<String, Integer>();
static HashMap<String, Integer> org = new HashMap<String, Integer>();
static HashMap<String, Integer> per = new HashMap<String, Integer>();
static HashMap<String, Integer> misc = new HashMap<String, Integer>();
static String last_word = "";
static String last_tag = "";
static String last_type = "";
public static void main(String[] args) throws IOException {
File fileI = new File(INPUT_PATH);
BufferedReader bufferR = new BufferedReader(new FileReader(fileI));
File fileO = new File(OUTPUT_PATH);
BufferedWriter bufferW = new BufferedWriter(new FileWriter(fileO));
// read from CRF++ predicated result
String s = bufferR.readLine();
while (s != null) {
process(s);
s = bufferR.readLine();
}
bufferR.close();
System.out.println(loc);
System.out.println(org);
System.out.println(per);
System.out.println(misc);
outputResult("LOCATION", loc, bufferW);
outputResult("ORGANIZATION", org, bufferW);
outputResult("PERSON", per, bufferW);
outputResult("MISC", misc, bufferW);
bufferW.close();
}
// process the results of crf_test to hash maps of different entity categories
private static void process(String s) {
StringTokenizer st = new StringTokenizer(s);
int i = 0;
String word = "";
String full_tag = "";
String tag = "";
while (st.hasMoreTokens()) {
i++;
if (i == 1) {
word = st.nextToken();
} else if (i == 3) {
full_tag = st.nextToken();
} else {
st.nextToken();
}
}
//System.out.println(word + "\t" + tag);
int index = full_tag.indexOf("-");
if (index != -1) {
tag = full_tag.substring(index+1, full_tag.length());
if (last_type.equals("B") && tag.equals(last_tag)) {
last_word += " " + word;
} else {
if (last_word != "" && !tag.equals(last_tag)) {
classifyWord(last_word, last_tag);
}
classifyWord(word, tag);
last_word = word;
last_tag = tag;
last_type = full_tag.substring(0, index);
}
}
}
private static void classifyWord(String word, String tag) {
if (tag.equals("ORG")) {
addToMap(word, org);
} else if (tag.equals("LOC")) {
addToMap(word, loc);
} else if (tag.equals("PER")) {
addToMap(word, per);
} else if (tag.equals("MISC")) {
addToMap(word, misc);
}
}
private static void addToMap(String word, HashMap<String, Integer> map) {
if (map.containsKey(word)) {
map.put(word, map.get(word)+1);
} else {
map.put(word, 1);
}
}
// output the result in the required format to a file
private static void outputResult(String s, HashMap<String, Integer> hm, BufferedWriter bw) throws IOException {
bw.write(s + "\n");
for (Map.Entry<String, Integer> entry : hm.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
bw.write("\t" + key + "\t" + value + "\n");
}
bw.write("\n");
}
}
| 26.818182 | 112 | 0.663277 |
0352f71d04aa199092d1d605e7a45f52495fa916 | 1,885 | /*
package io.github.vampirestudios.raa_dimension;
import com.mojang.datafixers.Dynamic;
import com.mojang.datafixers.types.DynamicOps;
import com.mojang.serialization.Codec;
import com.mojang.serialization.Lifecycle;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import io.github.vampirestudios.raa.RandomlyAddingAnything;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.source.BiomeLayerSampler;
import net.minecraft.world.biome.source.BiomeSource;
import net.minecraft.world.biome.source.BiomeSourceType;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class DimensionalBiomeSource extends BiomeSource {
private static List<Biome> BIOMES;
private final BiomeLayerSampler noiseLayer;
private final long seed;
public static final Codec<DimensionalBiomeSource> CODEC = RecordCodecBuilder.create((instance) -> {
return instance.group(Codec.LONG.fieldOf("seed").stable().forGetter((vanillaLayeredBiomeSource) -> {
return vanillaLayeredBiomeSource.seed;
})).apply(instance, instance.stable(DimensionalBiomeSource::new));
});
public DimensionalBiomeSource(long seed) {
super(BIOMES);
this.seed = seed;
BIOMES = biomes;
Set<Biome> biomes1 = new java.util.HashSet<>(biomes);
this.noiseLayer = DimensionalBiomeLayers.build(seed, biomes1);
}
@Override
public Biome getBiomeForNoiseGen(int biomeX, int biomeY, int biomeZ) {
return this.noiseLayer.sample(biomeX, biomeZ);
}
@Override
protected Codec<? extends BiomeSource> method_28442() {
return null;
}
@Override
public BiomeSource withSeed(long seed) {
return RAADimensionAddon.DIMENSIONAL_BIOMES;
}
@Override
public List<Biome> getSpawnBiomes() {
return new ArrayList<>(BIOMES);
}
}
*/
| 31.949153 | 108 | 0.732095 |
b49618db5f657e4b1c3053fa648ac44d527adefe | 2,298 | package org.quickstart.spring.security.oauth2.redis.oauth2.controller;
import com.alibaba.fastjson.JSON;
import org.quickstart.spring.security.oauth2.redis.oauth2.service.RedisClientDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/client")
@RestController
public class ClientController {
@Autowired
RedisClientDetailsService redisClientDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
@RequestMapping(path = "/get/{clientId}")
ResponseEntity get(@PathVariable("clientId") String clientId) {
ClientDetails clientDetails = redisClientDetailsService.loadClientByClientId(clientId);
if (null == clientDetails)
return new ResponseEntity(HttpStatus.NOT_FOUND);
return new ResponseEntity<String>(JSON.toJSONString(clientDetails), HttpStatus.OK);
}
@PostMapping(value = {"/add"})
ResponseEntity add(@RequestBody BaseClientDetails clientDetails) {
clientDetails.setClientSecret(passwordEncoder.encode(clientDetails.getClientSecret()));
redisClientDetailsService.storeClientDetails(clientDetails);
return ResponseEntity.ok().build();
}
@PostMapping(value = {"/update"})
ResponseEntity update(@RequestBody BaseClientDetails clientDetails) {
clientDetails.setClientSecret(passwordEncoder.encode(clientDetails.getClientSecret()));
redisClientDetailsService.updateClientDetails(clientDetails);
return ResponseEntity.ok().build();
}
@RequestMapping(path = "/delete/{clientId}")
ResponseEntity delete(@PathVariable("clientId") String clientId) {
redisClientDetailsService.deleteClientDetails(clientId);
return ResponseEntity.ok().build();
}
}
| 41.035714 | 92 | 0.81114 |
4107134d660b226740ba2fc670d4834138eded09 | 100,890 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package io.rong.recognizer;
public final class R {
public static final class array {
public static int rc_audio_file_suffix=0x7f0a0000;
public static int rc_emoji_code=0x7f0a0001;
public static int rc_emoji_res=0x7f0a0002;
public static int rc_excel_file_suffix=0x7f0a0003;
public static int rc_file_file_suffix=0x7f0a0004;
public static int rc_image_file_suffix=0x7f0a0005;
public static int rc_other_file_suffix=0x7f0a0006;
public static int rc_pdf_file_suffix=0x7f0a0007;
public static int rc_ppt_file_suffix=0x7f0a0008;
public static int rc_reconnect_interval=0x7f0a0009;
public static int rc_video_file_suffix=0x7f0a000a;
public static int rc_word_file_suffix=0x7f0a000b;
}
public static final class attr {
/** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static int RCCornerRadius=0x7f010001;
/** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static int RCDefDrawable=0x7f010004;
/** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static int RCMask=0x7f010002;
/** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static int RCMaxWidth=0x7f010005;
/** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static int RCMinShortSideSize=0x7f010000;
/** <p>Must be one or more (separated by '|') of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>square</code></td><td>0</td><td></td></tr>
<tr><td><code>circle</code></td><td>1</td><td></td></tr>
</table>
*/
public static int RCShape=0x7f010003;
/** <p>Must be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>SCE</code></td><td>0x123</td><td></td></tr>
<tr><td><code>SC</code></td><td>0x120</td><td></td></tr>
<tr><td><code>EC</code></td><td>0x320</td><td></td></tr>
<tr><td><code>CE</code></td><td>0x023</td><td></td></tr>
<tr><td><code>C</code></td><td>0x020</td><td></td></tr>
</table>
*/
public static int RCStyle=0x7f01000f;
/** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static int font=0x7f01000d;
/** <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static int fontProviderAuthority=0x7f010006;
/** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static int fontProviderCerts=0x7f010009;
/** <p>Must be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>blocking</code></td><td>0</td><td></td></tr>
<tr><td><code>async</code></td><td>1</td><td></td></tr>
</table>
*/
public static int fontProviderFetchStrategy=0x7f01000a;
/** <p>May be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
<p>May be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>forever</code></td><td>-1</td><td></td></tr>
</table>
*/
public static int fontProviderFetchTimeout=0x7f01000b;
/** <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static int fontProviderPackage=0x7f010007;
/** <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static int fontProviderQuery=0x7f010008;
/** <p>Must be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>normal</code></td><td>0</td><td></td></tr>
<tr><td><code>italic</code></td><td>1</td><td></td></tr>
</table>
*/
public static int fontStyle=0x7f01000c;
/** <p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static int fontWeight=0x7f01000e;
}
public static final class bool {
public static int abc_action_bar_embed_tabs=0x7f060000;
public static int rc_enable_mentioned_message=0x7f060001;
public static int rc_enable_message_recall=0x7f060002;
public static int rc_enable_sync_read_status=0x7f060003;
public static int rc_extension_history=0x7f060004;
public static int rc_is_show_warning_notification=0x7f060005;
public static int rc_play_audio_continuous=0x7f060006;
public static int rc_read_receipt=0x7f060007;
public static int rc_stop_custom_service_when_quit=0x7f060008;
public static int rc_typing_status=0x7f060009;
}
public static final class color {
public static int notification_action_color_filter=0x7f080000;
public static int notification_icon_bg_color=0x7f080001;
public static int notification_material_background_media_default_color=0x7f080002;
public static int primary_text_default_material_dark=0x7f080003;
public static int rc_ad_file_list_no_select_file_text_state=0x7f080004;
public static int rc_ad_file_list_select_file_text_state=0x7f080005;
public static int rc_bg_speech_tv_bottom_normal=0x7f080006;
public static int rc_bg_speech_tv_bottom_pressed=0x7f080007;
public static int rc_btn_file_list_send=0x7f08003e;
public static int rc_conversation_list_divider_color=0x7f080008;
public static int rc_conversation_top_bg=0x7f080009;
public static int rc_divider_color=0x7f08000a;
public static int rc_divider_line=0x7f08000b;
public static int rc_draft_color=0x7f08000c;
public static int rc_emoji_grid_item_bg=0x7f08000d;
public static int rc_extension_normal=0x7f08000e;
public static int rc_gray=0x7f08000f;
public static int rc_input_bg=0x7f080010;
public static int rc_input_gap_color=0x7f080011;
public static int rc_location_text=0x7f080012;
public static int rc_main_theme=0x7f080013;
public static int rc_mentioned_color=0x7f080014;
public static int rc_message_user_name=0x7f080015;
public static int rc_normal_bg=0x7f080016;
public static int rc_notice_normal=0x7f080017;
public static int rc_notice_text=0x7f080018;
public static int rc_notice_warning=0x7f080019;
public static int rc_notification_bg=0x7f08001a;
public static int rc_picprev_toolbar_transparent=0x7f08001b;
public static int rc_picsel_catalog_shadow=0x7f08001c;
public static int rc_picsel_grid_mask=0x7f08001d;
public static int rc_picsel_grid_mask_pressed=0x7f08001e;
public static int rc_picsel_toolbar=0x7f08001f;
public static int rc_picsel_toolbar_send_disable=0x7f080020;
public static int rc_picsel_toolbar_send_normal=0x7f080021;
public static int rc_picsel_toolbar_send_pressed=0x7f080022;
public static int rc_picsel_toolbar_send_text_disable=0x7f080023;
public static int rc_picsel_toolbar_send_text_normal=0x7f080024;
public static int rc_picsel_toolbar_transparent=0x7f080025;
public static int rc_plugins_bg=0x7f080026;
public static int rc_popup_dialog_list_divider_color=0x7f080027;
public static int rc_popup_dialog_prompt_cancel_color=0x7f080028;
public static int rc_popup_dialog_prompt_clear_color=0x7f080029;
public static int rc_popup_dialog_prompt_ok_color=0x7f08002a;
public static int rc_popup_dialog_text_color=0x7f08002b;
public static int rc_read_receipt_status=0x7f08002c;
public static int rc_recognizerview_bg_normal=0x7f08002d;
public static int rc_rich_content=0x7f08002e;
public static int rc_rich_title=0x7f08002f;
public static int rc_speech_tv=0x7f080030;
public static int rc_text_color_primary=0x7f080031;
public static int rc_text_color_primary_inverse=0x7f080032;
public static int rc_text_color_secondary=0x7f080033;
public static int rc_text_color_tertiary=0x7f080034;
public static int rc_text_voice=0x7f080035;
public static int rc_voice_cancel=0x7f080036;
public static int rc_voice_color=0x7f080037;
public static int rc_voice_color_left=0x7f080038;
public static int rc_voice_color_right=0x7f080039;
public static int rc_web_progress_bar=0x7f08003a;
public static int ripple_material_light=0x7f08003b;
public static int secondary_text_default_material_dark=0x7f08003c;
public static int secondary_text_default_material_light=0x7f08003d;
}
public static final class dimen {
public static int compat_button_inset_horizontal_material=0x7f070004;
public static int compat_button_inset_vertical_material=0x7f070005;
public static int compat_button_padding_horizontal_material=0x7f070006;
public static int compat_button_padding_vertical_material=0x7f070007;
public static int compat_control_corner_material=0x7f070008;
public static int notification_action_icon_size=0x7f070009;
public static int notification_action_text_size=0x7f07000a;
public static int notification_big_circle_margin=0x7f07000b;
public static int notification_content_margin_start=0x7f070001;
public static int notification_large_icon_height=0x7f07000c;
public static int notification_large_icon_width=0x7f07000d;
public static int notification_main_column_padding_top=0x7f070002;
public static int notification_media_narrow_margin=0x7f070003;
public static int notification_right_icon_size=0x7f07000e;
public static int notification_right_side_padding_top=0x7f070000;
public static int notification_small_icon_background_padding=0x7f07000f;
public static int notification_small_icon_size_as_large=0x7f070010;
public static int notification_subtext_size=0x7f070011;
public static int notification_top_pad=0x7f070012;
public static int notification_top_pad_large_text=0x7f070013;
public static int rc_conversation_item_data_size=0x7f070014;
public static int rc_conversation_item_name_size=0x7f070015;
public static int rc_conversation_item_time_size=0x7f070016;
public static int rc_dimen_size_18=0x7f070017;
public static int rc_dimen_size_24=0x7f070018;
public static int rc_dimen_size_3=0x7f070019;
public static int rc_dimen_size_40=0x7f07001a;
public static int rc_dimen_size_44=0x7f07001b;
public static int rc_dimen_size_5=0x7f07001c;
public static int rc_dimen_size_50=0x7f07001d;
public static int rc_dimen_size_7=0x7f07001e;
public static int rc_dimen_size_9=0x7f07001f;
public static int rc_extension_board_height=0x7f070020;
public static int rc_popup_dialog_distance_to_edge=0x7f070021;
}
public static final class drawable {
public static int notification_action_background=0x7f020000;
public static int notification_bg=0x7f020001;
public static int notification_bg_low=0x7f020002;
public static int notification_bg_low_normal=0x7f020003;
public static int notification_bg_low_pressed=0x7f020004;
public static int notification_bg_normal=0x7f020005;
public static int notification_bg_normal_pressed=0x7f020006;
public static int notification_icon_background=0x7f020007;
public static int notification_template_icon_bg=0x7f0201c8;
public static int notification_template_icon_low_bg=0x7f0201c9;
public static int notification_tile_bg=0x7f020008;
public static int notify_panel_notification_icon_bg=0x7f020009;
public static int rc_ac_audio_file_icon=0x7f02000a;
public static int rc_ac_btn_file_download_open_button=0x7f02000b;
public static int rc_ac_file_preview=0x7f02000c;
public static int rc_ac_other_file_icon=0x7f02000d;
public static int rc_ac_ram_icon=0x7f02000e;
public static int rc_ac_sd_card_icon=0x7f02000f;
public static int rc_ac_text_file_icon=0x7f020010;
public static int rc_ac_video_file_icon=0x7f020011;
public static int rc_ad_list_audio_icon=0x7f020012;
public static int rc_ad_list_file_checked=0x7f020013;
public static int rc_ad_list_file_icon=0x7f020014;
public static int rc_ad_list_file_unchecked=0x7f020015;
public static int rc_ad_list_folder_icon=0x7f020016;
public static int rc_ad_list_other_icon=0x7f020017;
public static int rc_ad_list_pdf_icon=0x7f020018;
public static int rc_ad_list_ppt_icon=0x7f020019;
public static int rc_ad_list_video_icon=0x7f02001a;
public static int rc_add_people=0x7f02001b;
public static int rc_an_voice_receive=0x7f02001c;
public static int rc_an_voice_sent=0x7f02001d;
public static int rc_anim_speech_end=0x7f02001e;
public static int rc_anim_speech_start=0x7f02001f;
public static int rc_audio_toggle=0x7f020020;
public static int rc_audio_toggle_hover=0x7f020021;
public static int rc_back_icon=0x7f020022;
public static int rc_bg_item=0x7f020023;
public static int rc_bg_mentionlist_item=0x7f020024;
public static int rc_bg_menu=0x7f020025;
public static int rc_bg_sidebar=0x7f020026;
public static int rc_bg_speech_tv_bottom=0x7f020027;
public static int rc_bg_toast=0x7f020028;
public static int rc_bg_voice_popup=0x7f020029;
public static int rc_btn_download_cancel=0x7f02002a;
public static int rc_btn_input=0x7f02002b;
public static int rc_btn_open_file_normal=0x7f02002c;
public static int rc_btn_open_file_selected=0x7f02002d;
public static int rc_btn_pub_service_enter_hover=0x7f02002e;
public static int rc_btn_pub_service_enter_normal=0x7f02002f;
public static int rc_btn_pub_service_follow_hover=0x7f020030;
public static int rc_btn_pub_service_follow_normal=0x7f020031;
public static int rc_btn_public_service_enter_selector=0x7f020032;
public static int rc_btn_public_service_unfollow_selector=0x7f020033;
public static int rc_btn_send=0x7f020034;
public static int rc_btn_send_hover=0x7f020035;
public static int rc_btn_send_normal=0x7f020036;
public static int rc_btn_voice=0x7f020037;
public static int rc_btn_voice_hover=0x7f020038;
public static int rc_btn_voice_normal=0x7f020039;
public static int rc_complete=0x7f02003a;
public static int rc_complete_hover=0x7f02003b;
public static int rc_conversation_list_empty=0x7f02003c;
public static int rc_conversation_list_msg_send_failure=0x7f02003d;
public static int rc_conversation_list_msg_sending=0x7f02003e;
public static int rc_conversation_newmsg=0x7f02003f;
public static int rc_corner_location_style=0x7f020040;
public static int rc_corner_popup_dialog_style=0x7f020041;
public static int rc_corner_style=0x7f020042;
public static int rc_corner_voice_style=0x7f020043;
public static int rc_cs_admin=0x7f020044;
public static int rc_cs_admin_hover=0x7f020045;
public static int rc_cs_admin_selector=0x7f020046;
public static int rc_cs_back_icon=0x7f020047;
public static int rc_cs_back_press=0x7f020048;
public static int rc_cs_back_selector=0x7f020049;
public static int rc_cs_button_bg=0x7f02004a;
public static int rc_cs_button_bg_hover=0x7f02004b;
public static int rc_cs_close=0x7f02004c;
public static int rc_cs_comment_bg=0x7f02004d;
public static int rc_cs_corner_single_check_style=0x7f02004e;
public static int rc_cs_default_portrait=0x7f02004f;
public static int rc_cs_delete=0x7f020050;
public static int rc_cs_evaluate_plugin=0x7f020051;
public static int rc_cs_evaluate_plugin_hover=0x7f020052;
public static int rc_cs_evaluate_selector=0x7f020053;
public static int rc_cs_follow=0x7f020054;
public static int rc_cs_follow_hover=0x7f020055;
public static int rc_cs_group_cancel_normal=0x7f020056;
public static int rc_cs_group_cancel_pressed=0x7f020057;
public static int rc_cs_group_check=0x7f020058;
public static int rc_cs_group_checkbox_selector=0x7f020059;
public static int rc_cs_group_dialog_cancel_selector=0x7f02005a;
public static int rc_cs_group_dialog_ok_selector=0x7f02005b;
public static int rc_cs_group_list_divide_line=0x7f02005c;
public static int rc_cs_group_ok_disabled=0x7f02005d;
public static int rc_cs_group_ok_normal=0x7f02005e;
public static int rc_cs_group_ok_pressed=0x7f02005f;
public static int rc_cs_group_ok_text_selector=0x7f020060;
public static int rc_cs_group_uncheck=0x7f020061;
public static int rc_cs_leave_message_bg=0x7f020062;
public static int rc_cs_leave_message_bg_hover=0x7f020063;
public static int rc_cs_leave_message_btn=0x7f020064;
public static int rc_cs_list_divider_style=0x7f020065;
public static int rc_cs_ratingbar=0x7f020066;
public static int rc_cs_resolved=0x7f020067;
public static int rc_cs_resolved_hover=0x7f020068;
public static int rc_cs_star=0x7f020069;
public static int rc_cs_star_hover=0x7f02006a;
public static int rc_cs_submit_comment=0x7f02006b;
public static int rc_cs_unresolved=0x7f02006c;
public static int rc_cs_unresolved_hover=0x7f02006d;
public static int rc_default_discussion_portrait=0x7f02006e;
public static int rc_default_group_portrait=0x7f02006f;
public static int rc_default_portrait=0x7f020070;
public static int rc_ed_pub_service_search_hover=0x7f020071;
public static int rc_ed_pub_service_search_normal=0x7f020072;
public static int rc_ed_public_service_search_selector=0x7f020073;
public static int rc_edit_text_background=0x7f020074;
public static int rc_edit_text_background_hover=0x7f020075;
public static int rc_edit_text_background_selector=0x7f020076;
public static int rc_emoji_grid_item_selector=0x7f020077;
public static int rc_emotion_toggle=0x7f020078;
public static int rc_emotion_toggle_hover=0x7f020079;
public static int rc_emotion_toggle_selector=0x7f02007a;
public static int rc_ext_indicator=0x7f02007b;
public static int rc_ext_indicator_hover=0x7f02007c;
public static int rc_ext_location_marker=0x7f02007d;
public static int rc_ext_location_tip=0x7f02007e;
public static int rc_ext_locator=0x7f02007f;
public static int rc_ext_my_locator=0x7f020080;
public static int rc_ext_plugin_image=0x7f020081;
public static int rc_ext_plugin_image_pressed=0x7f020082;
public static int rc_ext_plugin_image_selector=0x7f020083;
public static int rc_ext_plugin_location=0x7f020084;
public static int rc_ext_plugin_location_pressed=0x7f020085;
public static int rc_ext_plugin_location_selector=0x7f020086;
public static int rc_ext_plugin_toggle=0x7f020087;
public static int rc_ext_plugin_toggle_hover=0x7f020088;
public static int rc_ext_realtime_default_avatar=0x7f020089;
public static int rc_ext_tab_add=0x7f02008a;
public static int rc_ext_voice_btn_hover=0x7f02008b;
public static int rc_ext_voice_btn_normal=0x7f02008c;
public static int rc_file_icon_audio=0x7f02008d;
public static int rc_file_icon_cancel=0x7f02008e;
public static int rc_file_icon_else=0x7f02008f;
public static int rc_file_icon_excel=0x7f020090;
public static int rc_file_icon_file=0x7f020091;
public static int rc_file_icon_pdf=0x7f020092;
public static int rc_file_icon_picture=0x7f020093;
public static int rc_file_icon_ppt=0x7f020094;
public static int rc_file_icon_video=0x7f020095;
public static int rc_file_icon_word=0x7f020096;
public static int rc_fr_file_list_ad_icon_file=0x7f020097;
public static int rc_fr_file_list_ad_icon_folder=0x7f020098;
public static int rc_grid_camera=0x7f020099;
public static int rc_grid_image_default=0x7f02009a;
public static int rc_ic_bubble_left=0x7f02009b;
public static int rc_ic_bubble_left_file=0x7f02009c;
public static int rc_ic_bubble_no_left=0x7f02009d;
public static int rc_ic_bubble_no_right=0x7f02009e;
public static int rc_ic_bubble_right=0x7f02009f;
public static int rc_ic_bubble_right_file=0x7f0200a0;
public static int rc_ic_bubble_white=0x7f0200a1;
public static int rc_ic_checkbox_full=0x7f0200a2;
public static int rc_ic_checkbox_none=0x7f0200a3;
public static int rc_ic_def_coversation_portrait=0x7f0200a4;
public static int rc_ic_def_msg_portrait=0x7f0200a5;
public static int rc_ic_def_rich_content=0x7f0200a6;
public static int rc_ic_emoji_block=0x7f0200a7;
public static int rc_ic_files_normal=0x7f0200a8;
public static int rc_ic_files_pressed=0x7f0200a9;
public static int rc_ic_files_selector=0x7f0200aa;
public static int rc_ic_location=0x7f0200ab;
public static int rc_ic_location_item_default=0x7f0200ac;
public static int rc_ic_location_normal=0x7f0200ad;
public static int rc_ic_location_pressed=0x7f0200ae;
public static int rc_ic_message_block=0x7f0200af;
public static int rc_ic_no=0x7f0200b0;
public static int rc_ic_no_hover=0x7f0200b1;
public static int rc_ic_no_selector=0x7f0200b2;
public static int rc_ic_notice_loading=0x7f0200b3;
public static int rc_ic_notice_point=0x7f0200b4;
public static int rc_ic_notice_wraning=0x7f0200b5;
public static int rc_ic_phone_normal=0x7f0200b6;
public static int rc_ic_phone_pressed=0x7f0200b7;
public static int rc_ic_phone_selector=0x7f0200b8;
public static int rc_ic_setting_friends_add=0x7f0200b9;
public static int rc_ic_setting_friends_delete=0x7f0200ba;
public static int rc_ic_star=0x7f0200bb;
public static int rc_ic_star_hover=0x7f0200bc;
public static int rc_ic_star_selector=0x7f0200bd;
public static int rc_ic_voice_receive=0x7f0200be;
public static int rc_ic_voice_receive_play1=0x7f0200bf;
public static int rc_ic_voice_receive_play2=0x7f0200c0;
public static int rc_ic_voice_receive_play3=0x7f0200c1;
public static int rc_ic_voice_sent=0x7f0200c2;
public static int rc_ic_voice_sent_play1=0x7f0200c3;
public static int rc_ic_voice_sent_play2=0x7f0200c4;
public static int rc_ic_voice_sent_play3=0x7f0200c5;
public static int rc_ic_volume_0=0x7f0200c6;
public static int rc_ic_volume_1=0x7f0200c7;
public static int rc_ic_volume_2=0x7f0200c8;
public static int rc_ic_volume_3=0x7f0200c9;
public static int rc_ic_volume_4=0x7f0200ca;
public static int rc_ic_volume_5=0x7f0200cb;
public static int rc_ic_volume_6=0x7f0200cc;
public static int rc_ic_volume_7=0x7f0200cd;
public static int rc_ic_volume_8=0x7f0200ce;
public static int rc_ic_volume_cancel=0x7f0200cf;
public static int rc_ic_volume_wraning=0x7f0200d0;
public static int rc_ic_warning=0x7f0200d1;
public static int rc_ic_yes=0x7f0200d2;
public static int rc_ic_yes_hover=0x7f0200d3;
public static int rc_ic_yes_selector=0x7f0200d4;
public static int rc_icon_admin=0x7f0200d5;
public static int rc_icon_admin_hover=0x7f0200d6;
public static int rc_icon_emoji_delete=0x7f0200d7;
public static int rc_icon_rt_message_left=0x7f0200d8;
public static int rc_icon_rt_message_right=0x7f0200d9;
public static int rc_image_default=0x7f0200da;
public static int rc_image_error=0x7f0200db;
public static int rc_img_camera=0x7f0200dc;
public static int rc_input_sub_menu_bg=0x7f0200dd;
public static int rc_item_list_selector=0x7f0200de;
public static int rc_item_top_list_selector=0x7f0200df;
public static int rc_keyboard=0x7f0200e0;
public static int rc_keyboard_hover=0x7f0200e1;
public static int rc_keyboard_selector=0x7f0200e2;
public static int rc_loading=0x7f0200e3;
public static int rc_mebmer_delete=0x7f0200e4;
public static int rc_menu_background_selector=0x7f0200e5;
public static int rc_menu_keyboard=0x7f0200e6;
public static int rc_menu_keyboard_hover=0x7f0200e7;
public static int rc_menu_keyboard_selector=0x7f0200e8;
public static int rc_menu_text=0x7f0200e9;
public static int rc_menu_text_hover=0x7f0200ea;
public static int rc_menu_text_selector=0x7f0200eb;
public static int rc_menu_trangle=0x7f0200ec;
public static int rc_message_checkbox=0x7f0200ed;
public static int rc_no=0x7f0200ee;
public static int rc_no_hover=0x7f0200ef;
public static int rc_notification_connecting=0x7f0200f0;
public static int rc_notification_connecting_animated=0x7f0200f1;
public static int rc_notification_network_available=0x7f0200f2;
public static int rc_origin_check_nor=0x7f0200f3;
public static int rc_origin_check_sel=0x7f0200f4;
public static int rc_pb_file_download_progress=0x7f0200f5;
public static int rc_pb_file_download_progress_background=0x7f0200f6;
public static int rc_pb_file_download_progress_progress=0x7f0200f7;
public static int rc_picsel_back_normal=0x7f0200f8;
public static int rc_picsel_back_pressed=0x7f0200f9;
public static int rc_picsel_catalog_pic_shadow=0x7f0200fa;
public static int rc_picsel_catalog_selected=0x7f0200fb;
public static int rc_picsel_empty_pic=0x7f0200fc;
public static int rc_picsel_pictype_normal=0x7f0200fd;
public static int rc_plugin_default=0x7f0200fe;
public static int rc_plugin_toggle_selector=0x7f0200ff;
public static int rc_praise=0x7f020100;
public static int rc_praise_hover=0x7f020101;
public static int rc_progress_sending_style=0x7f020102;
public static int rc_public_service_menu_bg=0x7f020103;
public static int rc_radio_button_off=0x7f020104;
public static int rc_radio_button_on=0x7f020105;
public static int rc_read_receipt=0x7f020106;
public static int rc_read_receipt_request=0x7f020107;
public static int rc_read_receipt_request_button=0x7f020108;
public static int rc_read_receipt_request_hover=0x7f020109;
public static int rc_real_time_location_exit=0x7f02010a;
public static int rc_real_time_location_hide=0x7f02010b;
public static int rc_receive_voice_one=0x7f02010c;
public static int rc_receive_voice_three=0x7f02010d;
public static int rc_receive_voice_two=0x7f02010e;
public static int rc_recognize_bg_mic=0x7f02010f;
public static int rc_recognize_disable=0x7f020110;
public static int rc_recognize_volume_01=0x7f020111;
public static int rc_recognize_volume_02=0x7f020112;
public static int rc_recognize_volume_03=0x7f020113;
public static int rc_recognize_volume_04=0x7f020114;
public static int rc_recognize_volume_05=0x7f020115;
public static int rc_recognize_volume_06=0x7f020116;
public static int rc_recognize_volume_07=0x7f020117;
public static int rc_recognize_volume_08=0x7f020118;
public static int rc_recognize_volume_09=0x7f020119;
public static int rc_recognize_volume_10=0x7f02011a;
public static int rc_recognize_volume_11=0x7f02011b;
public static int rc_recognize_volume_12=0x7f02011c;
public static int rc_recognize_volume_13=0x7f02011d;
public static int rc_recognize_volume_14=0x7f02011e;
public static int rc_recognize_volume_blue=0x7f02011f;
public static int rc_recognize_volume_grey=0x7f020120;
public static int rc_recognizer_voice=0x7f020121;
public static int rc_recognizer_voice_hover=0x7f020122;
public static int rc_recognizer_voice_selector=0x7f020123;
public static int rc_rt_loc_myself=0x7f020124;
public static int rc_rt_loc_other=0x7f020125;
public static int rc_rt_location_arrow=0x7f020126;
public static int rc_rt_location_bar=0x7f020127;
public static int rc_sel_picsel_toolbar_back=0x7f020128;
public static int rc_sel_picsel_toolbar_send=0x7f020129;
public static int rc_select_check_nor=0x7f02012a;
public static int rc_select_check_sel=0x7f02012b;
public static int rc_selector_grid_camera_mask=0x7f02012c;
public static int rc_selector_title_back_press=0x7f02012d;
public static int rc_selector_title_pic_back_press=0x7f02012e;
public static int rc_send_toggle=0x7f02012f;
public static int rc_send_toggle_hover=0x7f020130;
public static int rc_send_toggle_selector=0x7f020131;
public static int rc_send_voice_one=0x7f020132;
public static int rc_send_voice_three=0x7f020133;
public static int rc_send_voice_two=0x7f020134;
public static int rc_sp_grid_mask=0x7f020135;
public static int rc_switch_btn=0x7f020136;
public static int rc_tab_emoji=0x7f020137;
public static int rc_unread_count_bg=0x7f020138;
public static int rc_unread_msg_arrow=0x7f020139;
public static int rc_unread_msg_bg_style=0x7f02013a;
public static int rc_unread_remind_list_count=0x7f02013b;
public static int rc_unread_remind_without_count=0x7f02013c;
public static int rc_voice_icon_left=0x7f02013d;
public static int rc_voice_icon_right=0x7f02013e;
public static int rc_voice_input_selector=0x7f02013f;
public static int rc_voice_input_toggle=0x7f020140;
public static int rc_voice_input_toggle_hover=0x7f020141;
public static int rc_voice_toggle_selector=0x7f020142;
public static int rc_voice_unread=0x7f020143;
public static int rc_voide_message_unread=0x7f020144;
public static int rc_white_bg_shape=0x7f020145;
public static int u1f004=0x7f020146;
public static int u1f30f=0x7f020147;
public static int u1f319=0x7f020148;
public static int u1f332=0x7f020149;
public static int u1f339=0x7f02014a;
public static int u1f33b=0x7f02014b;
public static int u1f349=0x7f02014c;
public static int u1f356=0x7f02014d;
public static int u1f35a=0x7f02014e;
public static int u1f366=0x7f02014f;
public static int u1f36b=0x7f020150;
public static int u1f377=0x7f020151;
public static int u1f37b=0x7f020152;
public static int u1f381=0x7f020153;
public static int u1f382=0x7f020154;
public static int u1f384=0x7f020155;
public static int u1f389=0x7f020156;
public static int u1f393=0x7f020157;
public static int u1f3a4=0x7f020158;
public static int u1f3b2=0x7f020159;
public static int u1f3b5=0x7f02015a;
public static int u1f3c0=0x7f02015b;
public static int u1f3c2=0x7f02015c;
public static int u1f3e1=0x7f02015d;
public static int u1f434=0x7f02015e;
public static int u1f436=0x7f02015f;
public static int u1f437=0x7f020160;
public static int u1f44a=0x7f020161;
public static int u1f44c=0x7f020162;
public static int u1f44d=0x7f020163;
public static int u1f44e=0x7f020164;
public static int u1f44f=0x7f020165;
public static int u1f451=0x7f020166;
public static int u1f46a=0x7f020167;
public static int u1f46b=0x7f020168;
public static int u1f47b=0x7f020169;
public static int u1f47c=0x7f02016a;
public static int u1f47d=0x7f02016b;
public static int u1f47f=0x7f02016c;
public static int u1f484=0x7f02016d;
public static int u1f48a=0x7f02016e;
public static int u1f48b=0x7f02016f;
public static int u1f48d=0x7f020170;
public static int u1f494=0x7f020171;
public static int u1f4a1=0x7f020172;
public static int u1f4a2=0x7f020173;
public static int u1f4a3=0x7f020174;
public static int u1f4a4=0x7f020175;
public static int u1f4a9=0x7f020176;
public static int u1f4aa=0x7f020177;
public static int u1f4b0=0x7f020178;
public static int u1f4da=0x7f020179;
public static int u1f4de=0x7f02017a;
public static int u1f4e2=0x7f02017b;
public static int u1f525=0x7f02017c;
public static int u1f52b=0x7f02017d;
public static int u1f556=0x7f02017e;
public static int u1f600=0x7f02017f;
public static int u1f601=0x7f020180;
public static int u1f602=0x7f020181;
public static int u1f603=0x7f020182;
public static int u1f605=0x7f020183;
public static int u1f606=0x7f020184;
public static int u1f607=0x7f020185;
public static int u1f608=0x7f020186;
public static int u1f609=0x7f020187;
public static int u1f60a=0x7f020188;
public static int u1f60b=0x7f020189;
public static int u1f60c=0x7f02018a;
public static int u1f60d=0x7f02018b;
public static int u1f60e=0x7f02018c;
public static int u1f60f=0x7f02018d;
public static int u1f611=0x7f02018e;
public static int u1f612=0x7f02018f;
public static int u1f613=0x7f020190;
public static int u1f614=0x7f020191;
public static int u1f615=0x7f020192;
public static int u1f616=0x7f020193;
public static int u1f618=0x7f020194;
public static int u1f61a=0x7f020195;
public static int u1f61c=0x7f020196;
public static int u1f61d=0x7f020197;
public static int u1f61e=0x7f020198;
public static int u1f61f=0x7f020199;
public static int u1f621=0x7f02019a;
public static int u1f622=0x7f02019b;
public static int u1f623=0x7f02019c;
public static int u1f624=0x7f02019d;
public static int u1f628=0x7f02019e;
public static int u1f629=0x7f02019f;
public static int u1f62a=0x7f0201a0;
public static int u1f62b=0x7f0201a1;
public static int u1f62c=0x7f0201a2;
public static int u1f62d=0x7f0201a3;
public static int u1f62e=0x7f0201a4;
public static int u1f62f=0x7f0201a5;
public static int u1f630=0x7f0201a6;
public static int u1f631=0x7f0201a7;
public static int u1f632=0x7f0201a8;
public static int u1f633=0x7f0201a9;
public static int u1f634=0x7f0201aa;
public static int u1f635=0x7f0201ab;
public static int u1f636=0x7f0201ac;
public static int u1f637=0x7f0201ad;
public static int u1f648=0x7f0201ae;
public static int u1f649=0x7f0201af;
public static int u1f64a=0x7f0201b0;
public static int u1f64f=0x7f0201b1;
public static int u1f680=0x7f0201b2;
public static int u1f6ab=0x7f0201b3;
public static int u1f6b2=0x7f0201b4;
public static int u1f6bf=0x7f0201b5;
public static int u23f0=0x7f0201b6;
public static int u23f3=0x7f0201b7;
public static int u2600=0x7f0201b8;
public static int u2601=0x7f0201b9;
public static int u2614=0x7f0201ba;
public static int u2615=0x7f0201bb;
public static int u261d=0x7f0201bc;
public static int u263a=0x7f0201bd;
public static int u26a1=0x7f0201be;
public static int u26bd=0x7f0201bf;
public static int u26c4=0x7f0201c0;
public static int u26c5=0x7f0201c1;
public static int u270a=0x7f0201c2;
public static int u270b=0x7f0201c3;
public static int u270c=0x7f0201c4;
public static int u270f=0x7f0201c5;
public static int u2744=0x7f0201c6;
public static int u2b50=0x7f0201c7;
}
public static final class id {
public static int C=0x7f0b0043;
public static int CE=0x7f0b0044;
public static int EC=0x7f0b0045;
public static int SC=0x7f0b0046;
public static int SCE=0x7f0b0047;
public static int account=0x7f0b00d1;
public static int action0=0x7f0b004b;
public static int action_container=0x7f0b0048;
public static int action_divider=0x7f0b004f;
public static int action_image=0x7f0b0049;
public static int action_text=0x7f0b004a;
public static int actions=0x7f0b0059;
public static int async=0x7f0b003e;
public static int back=0x7f0b0106;
public static int blocking=0x7f0b003f;
public static int btn_clear=0x7f0b0120;
public static int camera_mask=0x7f0b0119;
public static int cancel_action=0x7f0b004c;
public static int catalog_listview=0x7f0b010f;
public static int catalog_window=0x7f0b010e;
public static int checkbox=0x7f0b011b;
public static int chronometer=0x7f0b0054;
public static int circle=0x7f0b003c;
public static int description=0x7f0b00d4;
public static int end_padder=0x7f0b005b;
public static int enter=0x7f0b00d5;
public static int evaluate_text=0x7f0b00ed;
public static int ext_main_bar=0x7f0b00a6;
public static int follow=0x7f0b00d6;
public static int forever=0x7f0b0040;
public static int func=0x7f0b00d3;
public static int gridlist=0x7f0b010d;
public static int icon=0x7f0b0056;
public static int icon_group=0x7f0b005a;
public static int image=0x7f0b010b;
public static int image_layout=0x7f0b0115;
public static int img_mic=0x7f0b0123;
public static int index_total=0x7f0b0107;
public static int info=0x7f0b0055;
public static int introduction=0x7f0b00eb;
public static int italic=0x7f0b0041;
public static int iv_complete=0x7f0b00f1;
public static int iv_no=0x7f0b00f4;
public static int iv_yes=0x7f0b00f3;
public static int layout_head=0x7f0b008c;
public static int layout_praise=0x7f0b00ee;
public static int layout_praise_area=0x7f0b00f0;
public static int letter=0x7f0b00fc;
public static int line1=0x7f0b0000;
public static int line3=0x7f0b0001;
public static int line_split=0x7f0b0121;
public static int ll_message_check=0x7f0b00e7;
public static int mask=0x7f0b011a;
public static int media_actions=0x7f0b004e;
public static int memberItem=0x7f0b00fd;
public static int message_check=0x7f0b00e8;
public static int name=0x7f0b00d0;
public static int normal=0x7f0b0042;
public static int notification_background=0x7f0b0058;
public static int notification_main_column=0x7f0b0051;
public static int notification_main_column_container=0x7f0b0050;
public static int number=0x7f0b0116;
public static int origin_check=0x7f0b010a;
public static int pic_camera=0x7f0b0118;
public static int pic_type=0x7f0b0110;
public static int popup_dialog_button_cancel=0x7f0b009d;
public static int popup_dialog_button_ok=0x7f0b009e;
public static int popup_dialog_message=0x7f0b009b;
public static int popup_dialog_prompt_button=0x7f0b009c;
public static int popup_dialog_title=0x7f0b0099;
public static int portrait=0x7f0b00cf;
public static int preview=0x7f0b0113;
public static int preview_text=0x7f0b0114;
public static int rc_ac_btn_download_button=0x7f0b006d;
public static int rc_ac_fl_storage_folder_list_fragment=0x7f0b005d;
public static int rc_ac_iv_file_type_image=0x7f0b006a;
public static int rc_ac_ll_base_title=0x7f0b0074;
public static int rc_ac_ll_content_container=0x7f0b005c;
public static int rc_ac_ll_download_file_detail_info=0x7f0b0069;
public static int rc_ac_ll_progress_view=0x7f0b006e;
public static int rc_ac_ll_sd_card=0x7f0b0063;
public static int rc_ac_ll_sd_card_one=0x7f0b0065;
public static int rc_ac_ll_sd_card_two=0x7f0b0067;
public static int rc_ac_pb_download_progress=0x7f0b006f;
public static int rc_ac_tv_download_progress=0x7f0b0070;
public static int rc_ac_tv_file_manager_SD_card=0x7f0b0064;
public static int rc_ac_tv_file_manager_SD_card_one=0x7f0b0066;
public static int rc_ac_tv_file_manager_SD_card_two=0x7f0b0068;
public static int rc_ac_tv_file_manager_audio=0x7f0b0060;
public static int rc_ac_tv_file_manager_file=0x7f0b005e;
public static int rc_ac_tv_file_manager_mobile_memory=0x7f0b0062;
public static int rc_ac_tv_file_manager_picture=0x7f0b0061;
public static int rc_ac_tv_file_manager_video=0x7f0b005f;
public static int rc_ac_tv_file_name=0x7f0b006b;
public static int rc_ac_tv_file_size=0x7f0b006c;
public static int rc_action_bar_back=0x7f0b0075;
public static int rc_action_bar_ok=0x7f0b0077;
public static int rc_action_bar_title=0x7f0b0076;
public static int rc_actionbar=0x7f0b0002;
public static int rc_ad_iv_file_list_go_back=0x7f0b00c0;
public static int rc_ad_ll_file_list_title=0x7f0b00bf;
public static int rc_ad_tv_file_list_select_state=0x7f0b00c2;
public static int rc_ad_tv_file_list_title=0x7f0b00c1;
public static int rc_audio_input_toggle=0x7f0b00b8;
public static int rc_audio_state_image=0x7f0b0128;
public static int rc_audio_state_text=0x7f0b012a;
public static int rc_audio_timer=0x7f0b0129;
public static int rc_back=0x7f0b0003;
public static int rc_base_container=0x7f0b0078;
public static int rc_btn_cancel=0x7f0b0004;
public static int rc_btn_ok=0x7f0b0005;
public static int rc_checkbox=0x7f0b0006;
public static int rc_close_button=0x7f0b0080;
public static int rc_container_layout=0x7f0b00ab;
public static int rc_content=0x7f0b0007;
public static int rc_conversation_content=0x7f0b0008;
public static int rc_conversation_list_empty_layout=0x7f0b00bd;
public static int rc_conversation_msg_block=0x7f0b0009;
public static int rc_conversation_notification_container=0x7f0b0079;
public static int rc_conversation_notification_textView=0x7f0b007a;
public static int rc_conversation_status=0x7f0b000a;
public static int rc_conversation_time=0x7f0b000b;
public static int rc_conversation_title=0x7f0b000c;
public static int rc_cs_btn_cancel=0x7f0b0093;
public static int rc_cs_btn_ok=0x7f0b0094;
public static int rc_cs_btn_select=0x7f0b0092;
public static int rc_cs_evaluate_content=0x7f0b0088;
public static int rc_cs_group_checkBox=0x7f0b008b;
public static int rc_cs_group_dialog_listView=0x7f0b0095;
public static int rc_cs_msg=0x7f0b007d;
public static int rc_cs_resolved=0x7f0b0085;
public static int rc_cs_resolved_or_not=0x7f0b0083;
public static int rc_cs_resolving=0x7f0b0086;
public static int rc_cs_rootView=0x7f0b008f;
public static int rc_cs_stars=0x7f0b007b;
public static int rc_cs_tv_divide=0x7f0b0091;
public static int rc_cs_tv_group_name=0x7f0b008a;
public static int rc_cs_tv_title=0x7f0b0090;
public static int rc_cs_unresolved=0x7f0b0087;
public static int rc_cs_yes_no=0x7f0b007c;
public static int rc_description=0x7f0b00ec;
public static int rc_dialog_popup_item_name=0x7f0b0097;
public static int rc_edit_text=0x7f0b000d;
public static int rc_emoticon_tab_add=0x7f0b00a3;
public static int rc_emoticon_tab_iv=0x7f0b00a5;
public static int rc_emoticon_toggle=0x7f0b00ae;
public static int rc_emotion_scroll_tab=0x7f0b00a4;
public static int rc_emotion_tab_bar=0x7f0b00a2;
public static int rc_empty_tv=0x7f0b00be;
public static int rc_evaluate_level=0x7f0b0082;
public static int rc_ext_amap=0x7f0b00f6;
public static int rc_ext_emoji_item=0x7f0b009f;
public static int rc_ext_location_marker=0x7f0b011c;
public static int rc_ext_my_location=0x7f0b011d;
public static int rc_ext_plugin_icon=0x7f0b00b2;
public static int rc_ext_plugin_title=0x7f0b00b3;
public static int rc_extension=0x7f0b00b9;
public static int rc_fm_ll_storage_folder_list_load=0x7f0b00c4;
public static int rc_fm_lv_storage_folder_list_files=0x7f0b00c3;
public static int rc_fm_pb_storage_folder_list_load_progress=0x7f0b00c5;
public static int rc_fm_tv_no_file_message=0x7f0b00c7;
public static int rc_fm_tv_storage_folder_list_load_message=0x7f0b00c6;
public static int rc_fragment=0x7f0b000e;
public static int rc_frame=0x7f0b000f;
public static int rc_icon=0x7f0b0010;
public static int rc_img=0x7f0b0011;
public static int rc_indicator=0x7f0b00a1;
public static int rc_input_extension=0x7f0b0012;
public static int rc_input_main=0x7f0b0013;
public static int rc_input_switch=0x7f0b0014;
public static int rc_item0=0x7f0b0015;
public static int rc_item1=0x7f0b0016;
public static int rc_item2=0x7f0b0017;
public static int rc_item3=0x7f0b0018;
public static int rc_item4=0x7f0b0019;
public static int rc_item5=0x7f0b001a;
public static int rc_item6=0x7f0b001b;
public static int rc_item7=0x7f0b001c;
public static int rc_item8=0x7f0b001d;
public static int rc_item9=0x7f0b001e;
public static int rc_item_conversation=0x7f0b001f;
public static int rc_layout=0x7f0b0020;
public static int rc_layout_item_message=0x7f0b00e6;
public static int rc_layout_msg_list=0x7f0b0021;
public static int rc_left=0x7f0b0022;
public static int rc_list=0x7f0b0023;
public static int rc_list_dialog_popup_options=0x7f0b0096;
public static int rc_logo=0x7f0b0024;
public static int rc_menu_bar=0x7f0b00b0;
public static int rc_menu_icon=0x7f0b00b5;
public static int rc_menu_item_text=0x7f0b00e9;
public static int rc_menu_line=0x7f0b00ea;
public static int rc_menu_title=0x7f0b00b4;
public static int rc_message=0x7f0b00e0;
public static int rc_message_send_failed=0x7f0b0025;
public static int rc_msg=0x7f0b0026;
public static int rc_msg_canceled=0x7f0b00e4;
public static int rc_msg_iv_file_type_image=0x7f0b00e1;
public static int rc_msg_pb_file_upload_progress=0x7f0b00e5;
public static int rc_msg_tv_file_name=0x7f0b00e2;
public static int rc_msg_tv_file_size=0x7f0b00e3;
public static int rc_new=0x7f0b0027;
public static int rc_new_message_count=0x7f0b00cb;
public static int rc_new_message_number=0x7f0b00cc;
public static int rc_notification_container=0x7f0b00cd;
public static int rc_pager=0x7f0b0028;
public static int rc_pager_fragment=0x7f0b0071;
public static int rc_photoView=0x7f0b00c8;
public static int rc_plugin_layout=0x7f0b00ac;
public static int rc_plugin_toggle=0x7f0b00ad;
public static int rc_popup_bg=0x7f0b0100;
public static int rc_portrait=0x7f0b0029;
public static int rc_portrait_right=0x7f0b002a;
public static int rc_progress=0x7f0b002b;
public static int rc_rating_bar=0x7f0b0081;
public static int rc_read_receipt=0x7f0b002c;
public static int rc_read_receipt_request=0x7f0b002d;
public static int rc_read_receipt_status=0x7f0b002e;
public static int rc_resolve_progress=0x7f0b0084;
public static int rc_right=0x7f0b002f;
public static int rc_scroll=0x7f0b007e;
public static int rc_scroll_item=0x7f0b007f;
public static int rc_search_btn=0x7f0b00d9;
public static int rc_search_ed=0x7f0b00d8;
public static int rc_search_list=0x7f0b00da;
public static int rc_send=0x7f0b0030;
public static int rc_send_toggle=0x7f0b00af;
public static int rc_sent_status=0x7f0b0031;
public static int rc_setting_item=0x7f0b00db;
public static int rc_sidebar=0x7f0b0101;
public static int rc_status_bar=0x7f0b00ba;
public static int rc_status_bar_image=0x7f0b00bb;
public static int rc_status_bar_text=0x7f0b00bc;
public static int rc_sub_menu_divider_line=0x7f0b00b7;
public static int rc_sub_menu_title=0x7f0b00b6;
public static int rc_submit_button=0x7f0b0089;
public static int rc_submit_message=0x7f0b008e;
public static int rc_switch_divider=0x7f0b00a9;
public static int rc_switch_layout=0x7f0b00a7;
public static int rc_switch_to_keyboard=0x7f0b00b1;
public static int rc_switch_to_menu=0x7f0b00a8;
public static int rc_time=0x7f0b0032;
public static int rc_title=0x7f0b0033;
public static int rc_title_layout=0x7f0b0034;
public static int rc_toolbar=0x7f0b00f7;
public static int rc_toolbar_close=0x7f0b00f8;
public static int rc_toolbar_hide=0x7f0b00fa;
public static int rc_txt=0x7f0b0035;
public static int rc_unread_message=0x7f0b0036;
public static int rc_unread_message_count=0x7f0b00ca;
public static int rc_unread_message_icon=0x7f0b00dd;
public static int rc_unread_message_icon_right=0x7f0b00df;
public static int rc_unread_message_layout=0x7f0b00c9;
public static int rc_unread_message_right=0x7f0b0037;
public static int rc_unread_view_left=0x7f0b00dc;
public static int rc_unread_view_right=0x7f0b00de;
public static int rc_user_icons=0x7f0b00f9;
public static int rc_user_name=0x7f0b00ff;
public static int rc_user_portrait=0x7f0b00fe;
public static int rc_user_text=0x7f0b00fb;
public static int rc_view_pager=0x7f0b00a0;
public static int rc_voice_toggle=0x7f0b00aa;
public static int rc_voice_unread=0x7f0b00f5;
public static int rc_warning=0x7f0b0038;
public static int rc_web_progressbar=0x7f0b0072;
public static int rc_webview=0x7f0b0073;
public static int rc_wi_ad_iv_file_check_state=0x7f0b0127;
public static int rc_wi_ad_iv_file_icon=0x7f0b0124;
public static int rc_wi_ad_tv_file_details=0x7f0b0126;
public static int rc_wi_ad_tv_file_name=0x7f0b0125;
public static int real_time_location_bar=0x7f0b0102;
public static int real_time_location_text=0x7f0b0103;
public static int refresh_loading_indicator=0x7f0b011e;
public static int rel_group_intro=0x7f0b00d2;
public static int right_icon=0x7f0b0057;
public static int right_side=0x7f0b0052;
public static int rl_bottom=0x7f0b011f;
public static int rl_mic=0x7f0b0122;
public static int rl_popup_dialog_prompt_message=0x7f0b009a;
public static int rl_popup_dialog_title=0x7f0b0098;
public static int select_check=0x7f0b010c;
public static int selected=0x7f0b0117;
public static int send=0x7f0b0108;
public static int square=0x7f0b003d;
public static int status_bar_latest_event_content=0x7f0b004d;
public static int text=0x7f0b0039;
public static int text2=0x7f0b003a;
public static int time=0x7f0b0053;
public static int title=0x7f0b003b;
public static int toolbar_bottom=0x7f0b0109;
public static int toolbar_top=0x7f0b0105;
public static int tv_line=0x7f0b00ef;
public static int tv_prompt=0x7f0b00f2;
public static int tv_title=0x7f0b008d;
public static int type_image=0x7f0b0112;
public static int type_text=0x7f0b0111;
public static int unfollow=0x7f0b00d7;
public static int viewpager=0x7f0b00ce;
public static int volume_animation=0x7f0b012b;
public static int whole_layout=0x7f0b0104;
}
public static final class integer {
public static int cancel_button_image_alpha=0x7f0c0000;
public static int rc_audio_encoding_bit_rate=0x7f0c0001;
public static int rc_chatroom_first_pull_message_count=0x7f0c0002;
public static int rc_custom_service_evaluation_interval=0x7f0c0003;
public static int rc_extension_emoji_count_per_page=0x7f0c0004;
public static int rc_extension_plugin_count_per_page=0x7f0c0005;
public static int rc_image_quality=0x7f0c0006;
public static int rc_image_size=0x7f0c0007;
public static int rc_message_recall_interval=0x7f0c0008;
public static int rc_read_receipt_request_interval=0x7f0c0009;
public static int status_bar_notification_info_maxnum=0x7f0c000a;
}
public static final class layout {
public static int notification_action=0x7f030000;
public static int notification_action_tombstone=0x7f030001;
public static int notification_media_action=0x7f030002;
public static int notification_media_cancel_action=0x7f030003;
public static int notification_template_big_media=0x7f030004;
public static int notification_template_big_media_custom=0x7f030005;
public static int notification_template_big_media_narrow=0x7f030006;
public static int notification_template_big_media_narrow_custom=0x7f030007;
public static int notification_template_custom_big=0x7f030008;
public static int notification_template_icon_group=0x7f030009;
public static int notification_template_lines_media=0x7f03000a;
public static int notification_template_media=0x7f03000b;
public static int notification_template_media_custom=0x7f03000c;
public static int notification_template_part_chronometer=0x7f03000d;
public static int notification_template_part_time=0x7f03000e;
public static int rc_ac_albums=0x7f03000f;
public static int rc_ac_camera=0x7f030010;
public static int rc_ac_file_download=0x7f030011;
public static int rc_ac_file_list=0x7f030012;
public static int rc_ac_file_manager=0x7f030013;
public static int rc_ac_file_preview_content=0x7f030014;
public static int rc_ac_picture_pager=0x7f030015;
public static int rc_ac_webview=0x7f030016;
public static int rc_base_activity_layout=0x7f030017;
public static int rc_camera=0x7f030018;
public static int rc_conversation_notification_container=0x7f030019;
public static int rc_cs_alert_human_evaluation=0x7f03001a;
public static int rc_cs_alert_robot_evaluation=0x7f03001b;
public static int rc_cs_alert_warning=0x7f03001c;
public static int rc_cs_evaluate=0x7f03001d;
public static int rc_cs_item_single_choice=0x7f03001e;
public static int rc_cs_leave_message=0x7f03001f;
public static int rc_cs_single_choice_layout=0x7f030020;
public static int rc_dialog_popup_options=0x7f030021;
public static int rc_dialog_popup_options_item=0x7f030022;
public static int rc_dialog_popup_prompt=0x7f030023;
public static int rc_dialog_popup_prompt_warning=0x7f030024;
public static int rc_ext_emoji_grid_view=0x7f030025;
public static int rc_ext_emoji_item=0x7f030026;
public static int rc_ext_emoji_pager=0x7f030027;
public static int rc_ext_emoticon_tab_container=0x7f030028;
public static int rc_ext_emoticon_tab_item=0x7f030029;
public static int rc_ext_extension_bar=0x7f03002a;
public static int rc_ext_indicator=0x7f03002b;
public static int rc_ext_input_edit_text=0x7f03002c;
public static int rc_ext_menu_container=0x7f03002d;
public static int rc_ext_plugin_grid_view=0x7f03002e;
public static int rc_ext_plugin_item=0x7f03002f;
public static int rc_ext_plugin_pager=0x7f030030;
public static int rc_ext_root_menu_item=0x7f030031;
public static int rc_ext_sub_menu_container=0x7f030032;
public static int rc_ext_sub_menu_item=0x7f030033;
public static int rc_ext_voice_input=0x7f030034;
public static int rc_fr_conversation=0x7f030035;
public static int rc_fr_conversation_member_list=0x7f030036;
public static int rc_fr_conversationlist=0x7f030037;
public static int rc_fr_dialog_alter=0x7f030038;
public static int rc_fr_file_list=0x7f030039;
public static int rc_fr_image=0x7f03003a;
public static int rc_fr_messagelist=0x7f03003b;
public static int rc_fr_photo=0x7f03003c;
public static int rc_fr_public_service_inf=0x7f03003d;
public static int rc_fr_public_service_search=0x7f03003e;
public static int rc_fr_public_service_sub_list=0x7f03003f;
public static int rc_fragment_base_setting=0x7f030040;
public static int rc_icon_rt_location_marker=0x7f030041;
public static int rc_input_pager_layout=0x7f030042;
public static int rc_item_app_service_conversation=0x7f030043;
public static int rc_item_base_conversation=0x7f030044;
public static int rc_item_conversation=0x7f030045;
public static int rc_item_conversation_member=0x7f030046;
public static int rc_item_discussion_conversation=0x7f030047;
public static int rc_item_discussion_notification_message=0x7f030048;
public static int rc_item_file_message=0x7f030049;
public static int rc_item_group_conversation=0x7f03004a;
public static int rc_item_group_information_notification_message=0x7f03004b;
public static int rc_item_image_message=0x7f03004c;
public static int rc_item_information_notification_message=0x7f03004d;
public static int rc_item_location_message=0x7f03004e;
public static int rc_item_message=0x7f03004f;
public static int rc_item_preview_fragment=0x7f030050;
public static int rc_item_progress=0x7f030051;
public static int rc_item_public_service_conversation=0x7f030052;
public static int rc_item_public_service_input_menu=0x7f030053;
public static int rc_item_public_service_input_menu_item=0x7f030054;
public static int rc_item_public_service_input_menus=0x7f030055;
public static int rc_item_public_service_list=0x7f030056;
public static int rc_item_public_service_message=0x7f030057;
public static int rc_item_public_service_multi_rich_content_message=0x7f030058;
public static int rc_item_public_service_rich_content_message=0x7f030059;
public static int rc_item_public_service_search=0x7f03005a;
public static int rc_item_rich_content_message=0x7f03005b;
public static int rc_item_system_conversation=0x7f03005c;
public static int rc_item_text_message=0x7f03005d;
public static int rc_item_text_message_evaluate=0x7f03005e;
public static int rc_item_voice_message=0x7f03005f;
public static int rc_location_preview_activity=0x7f030060;
public static int rc_location_real_time_activity=0x7f030061;
public static int rc_mention_list_item=0x7f030062;
public static int rc_mention_members=0x7f030063;
public static int rc_notification_realtime_location=0x7f030064;
public static int rc_pic_popup_window=0x7f030065;
public static int rc_picprev_activity=0x7f030066;
public static int rc_picsel_activity=0x7f030067;
public static int rc_picsel_catalog_listview=0x7f030068;
public static int rc_picsel_grid_camera=0x7f030069;
public static int rc_picsel_grid_item=0x7f03006a;
public static int rc_picsel_original=0x7f03006b;
public static int rc_picsel_preview=0x7f03006c;
public static int rc_plugin_location_activity=0x7f03006d;
public static int rc_refresh_list_view=0x7f03006e;
public static int rc_share_location_message=0x7f03006f;
public static int rc_view_recognizer=0x7f030070;
public static int rc_wi_block=0x7f030071;
public static int rc_wi_block_popup=0x7f030072;
public static int rc_wi_file_list_adapter=0x7f030073;
public static int rc_wi_notice=0x7f030074;
public static int rc_wi_vo_popup=0x7f030075;
}
public static final class string {
public static int rc_ac_file_download_btn=0x7f050001;
public static int rc_ac_file_download_open_file_btn=0x7f050002;
public static int rc_ac_file_download_preview=0x7f050003;
public static int rc_ac_file_download_progress_tv=0x7f050004;
public static int rc_ac_file_download_request_permission=0x7f050005;
public static int rc_ac_file_download_request_permission_cancel=0x7f050006;
public static int rc_ac_file_download_request_permission_sure=0x7f050007;
public static int rc_ac_file_manager_SD_card=0x7f050008;
public static int rc_ac_file_manager_SD_card_one=0x7f050009;
public static int rc_ac_file_manager_SD_card_two=0x7f05000a;
public static int rc_ac_file_manager_category_audio=0x7f05000b;
public static int rc_ac_file_manager_category_file=0x7f05000c;
public static int rc_ac_file_manager_category_picture=0x7f05000d;
public static int rc_ac_file_manager_category_title=0x7f05000e;
public static int rc_ac_file_manager_category_video=0x7f05000f;
public static int rc_ac_file_manager_dir_title=0x7f050010;
public static int rc_ac_file_manager_mobile_memory=0x7f050011;
public static int rc_ac_file_preview_begin_download=0x7f050012;
public static int rc_ac_file_preview_can_not_open_file=0x7f050013;
public static int rc_ac_file_preview_deleted=0x7f050014;
public static int rc_ac_file_preview_download_cancel=0x7f050015;
public static int rc_ac_file_preview_download_error=0x7f050016;
public static int rc_ac_file_preview_downloaded=0x7f050017;
public static int rc_ac_file_send_preview=0x7f050018;
public static int rc_action_bar_back=0x7f050019;
public static int rc_action_bar_ok=0x7f05001a;
public static int rc_ad_file_size=0x7f05001b;
public static int rc_ad_folder_files_number=0x7f05001c;
public static int rc_ad_folder_no_files=0x7f05001d;
public static int rc_ad_send_file_no_select_file=0x7f05001e;
public static int rc_ad_send_file_select_file=0x7f05001f;
public static int rc_afternoon_format=0x7f050020;
public static int rc_android_permission_ACCESS_COARSE_LOCATION=0x7f050021;
public static int rc_android_permission_ACCESS_FINE_LOCATION=0x7f050022;
public static int rc_android_permission_CAMERA=0x7f050023;
public static int rc_android_permission_PROCESS_OUTGOING_CALLS=0x7f050024;
public static int rc_android_permission_READ_EXTERNAL_STORAGE=0x7f050025;
public static int rc_android_permission_READ_PHONE_STATE=0x7f050026;
public static int rc_android_permission_RECORD_AUDIO=0x7f050027;
public static int rc_android_permission_WRITE_EXTERNAL_STORAGE=0x7f050028;
public static int rc_android_settings_action_MANAGE_OVERLAY_PERMISSION=0x7f050029;
public static int rc_audio_input=0x7f05002a;
public static int rc_audio_input_hover=0x7f05002b;
public static int rc_authorities_fileprovider=0x7f0500fc;
public static int rc_blacklist_prompt=0x7f05002c;
public static int rc_called_accept=0x7f05002d;
public static int rc_called_is_calling=0x7f05002e;
public static int rc_called_not_accept=0x7f05002f;
public static int rc_called_on_hook=0x7f050030;
public static int rc_cancel=0x7f050031;
public static int rc_choose_members=0x7f050032;
public static int rc_confirm=0x7f050033;
public static int rc_conversation_List_operation_failure=0x7f050034;
public static int rc_conversation_list_app_public_service=0x7f050035;
public static int rc_conversation_list_default_discussion_name=0x7f050036;
public static int rc_conversation_list_dialog_cancel_top=0x7f050037;
public static int rc_conversation_list_dialog_remove=0x7f050038;
public static int rc_conversation_list_dialog_set_top=0x7f050039;
public static int rc_conversation_list_empty_prompt=0x7f05003a;
public static int rc_conversation_list_my_chatroom=0x7f05003b;
public static int rc_conversation_list_my_customer_service=0x7f05003c;
public static int rc_conversation_list_my_discussion=0x7f05003d;
public static int rc_conversation_list_my_group=0x7f05003e;
public static int rc_conversation_list_my_private_conversation=0x7f05003f;
public static int rc_conversation_list_not_connected=0x7f050040;
public static int rc_conversation_list_popup_cancel_top=0x7f050041;
public static int rc_conversation_list_popup_set_top=0x7f050042;
public static int rc_conversation_list_public_service=0x7f050043;
public static int rc_conversation_list_system_conversation=0x7f050044;
public static int rc_cs_average=0x7f0500fd;
public static int rc_cs_cancel=0x7f050045;
public static int rc_cs_evaluate=0x7f0500fe;
public static int rc_cs_evaluate_human=0x7f050046;
public static int rc_cs_evaluate_robot=0x7f050047;
public static int rc_cs_evaluate_title=0x7f0500ff;
public static int rc_cs_leave_message=0x7f050100;
public static int rc_cs_message_submited=0x7f050101;
public static int rc_cs_please_comment=0x7f050102;
public static int rc_cs_please_leave_message=0x7f050103;
public static int rc_cs_resolved_or_not=0x7f050104;
public static int rc_cs_satisfactory=0x7f050105;
public static int rc_cs_select_group=0x7f050048;
public static int rc_cs_submit=0x7f050049;
public static int rc_cs_submit_evaluate_content=0x7f050106;
public static int rc_cs_submit_message=0x7f050107;
public static int rc_cs_unsatisfactory=0x7f050108;
public static int rc_cs_very_satisfactory=0x7f050109;
public static int rc_cs_very_unsatisfactory=0x7f05010a;
public static int rc_day_format=0x7f05004a;
public static int rc_daybreak_format=0x7f05004b;
public static int rc_dialog_button_clear=0x7f05004c;
public static int rc_dialog_cancel=0x7f05004d;
public static int rc_dialog_item_message_copy=0x7f05004e;
public static int rc_dialog_item_message_delete=0x7f05004f;
public static int rc_dialog_item_message_recall=0x7f050050;
public static int rc_dialog_ok=0x7f050051;
public static int rc_discussion_nt_msg_for_add=0x7f050052;
public static int rc_discussion_nt_msg_for_added=0x7f050053;
public static int rc_discussion_nt_msg_for_exit=0x7f050054;
public static int rc_discussion_nt_msg_for_is_open_invite_close=0x7f050055;
public static int rc_discussion_nt_msg_for_is_open_invite_open=0x7f050056;
public static int rc_discussion_nt_msg_for_removed=0x7f050057;
public static int rc_discussion_nt_msg_for_rename=0x7f050058;
public static int rc_discussion_nt_msg_for_who_removed=0x7f050059;
public static int rc_discussion_nt_msg_for_you=0x7f05005a;
public static int rc_exit_calling=0x7f05005b;
public static int rc_ext_cancel=0x7f05005c;
public static int rc_ext_exit_location_sharing=0x7f05005d;
public static int rc_ext_exit_location_sharing_confirm=0x7f05005e;
public static int rc_ext_location_permission_failed=0x7f05005f;
public static int rc_ext_send=0x7f050060;
public static int rc_ext_warning=0x7f050061;
public static int rc_file_not_exist=0x7f050062;
public static int rc_forbidden_in_chatroom=0x7f050063;
public static int rc_fr_file_category_title_audio=0x7f050064;
public static int rc_fr_file_category_title_other=0x7f050065;
public static int rc_fr_file_category_title_ram=0x7f050066;
public static int rc_fr_file_category_title_sd=0x7f050067;
public static int rc_fr_file_category_title_text=0x7f050068;
public static int rc_fr_file_category_title_video=0x7f050069;
public static int rc_fr_file_list_most_selected_files=0x7f05006a;
public static int rc_fr_loading_file_message=0x7f05006b;
public static int rc_fr_no_file_message=0x7f05006c;
public static int rc_fr_storage_folder_list_no_files=0x7f05006d;
public static int rc_fr_storage_folder_list_search=0x7f05006e;
public static int rc_friday_format=0x7f05006f;
public static int rc_heartbeat_timer=0x7f05010b;
public static int rc_image_default_saved_path=0x7f05010c;
public static int rc_info_forbidden_to_talk=0x7f050070;
public static int rc_info_not_in_chatroom=0x7f050071;
public static int rc_info_not_in_discussion=0x7f050072;
public static int rc_info_not_in_group=0x7f050073;
public static int rc_init_failed=0x7f050074;
public static int rc_input_send=0x7f050075;
public static int rc_input_voice=0x7f050076;
public static int rc_item_change_group_name=0x7f050077;
public static int rc_item_create_group=0x7f050078;
public static int rc_item_created_group=0x7f050079;
public static int rc_item_dismiss_groups=0x7f05007a;
public static int rc_item_divided_string=0x7f05007b;
public static int rc_item_etc=0x7f05007c;
public static int rc_item_group_notification_summary=0x7f05007d;
public static int rc_item_invitation=0x7f05007e;
public static int rc_item_join_group=0x7f05007f;
public static int rc_item_quit_groups=0x7f050080;
public static int rc_item_remove_group_after_str=0x7f050081;
public static int rc_item_remove_group_before_str=0x7f050082;
public static int rc_item_remove_group_member=0x7f050083;
public static int rc_item_remove_self=0x7f050084;
public static int rc_item_to_join_group=0x7f050085;
public static int rc_item_you=0x7f050086;
public static int rc_join_chatroom_failure=0x7f050087;
public static int rc_kicked_from_chatroom=0x7f050088;
public static int rc_location_fail=0x7f050089;
public static int rc_location_fetching=0x7f05008a;
public static int rc_location_sharing_ended=0x7f05008b;
public static int rc_location_sharing_exceed_max=0x7f05008c;
public static int rc_location_temp_failed=0x7f05008d;
public static int rc_media_message_default_save_path=0x7f05010d;
public static int rc_message_content_draft=0x7f05008e;
public static int rc_message_content_file=0x7f05008f;
public static int rc_message_content_image=0x7f050090;
public static int rc_message_content_location=0x7f050091;
public static int rc_message_content_mentioned=0x7f050092;
public static int rc_message_content_rich_text=0x7f050093;
public static int rc_message_content_voice=0x7f050094;
public static int rc_message_unknown=0x7f050095;
public static int rc_message_unread_count=0x7f050096;
public static int rc_monday_format=0x7f050097;
public static int rc_month_format=0x7f050098;
public static int rc_morning_format=0x7f050099;
public static int rc_name=0x7f05009a;
public static int rc_network_error=0x7f05009b;
public static int rc_network_exception=0x7f05009c;
public static int rc_network_is_busy=0x7f05009d;
public static int rc_new_messages=0x7f05009e;
public static int rc_night_format=0x7f05009f;
public static int rc_noon_format=0x7f0500a0;
public static int rc_notice_connecting=0x7f0500a1;
public static int rc_notice_create_discussion=0x7f0500a2;
public static int rc_notice_create_discussion_fail=0x7f0500a3;
public static int rc_notice_data_is_loading=0x7f0500a4;
public static int rc_notice_disconnect=0x7f0500a5;
public static int rc_notice_download_fail=0x7f0500a6;
public static int rc_notice_enter_chatroom=0x7f0500a7;
public static int rc_notice_input_conversation_error=0x7f0500a8;
public static int rc_notice_load_data_fail=0x7f0500a9;
public static int rc_notice_network_unavailable=0x7f0500aa;
public static int rc_notice_select_one_picture_at_last=0x7f0500ab;
public static int rc_notice_tick=0x7f0500ac;
public static int rc_notification_new_msg=0x7f0500ad;
public static int rc_notification_new_plural_msg=0x7f0500ae;
public static int rc_notification_ticker_text=0x7f0500af;
public static int rc_other_is_sharing_location=0x7f0500b0;
public static int rc_others_are_sharing_location=0x7f0500b1;
public static int rc_permission_camera=0x7f0500b2;
public static int rc_permission_grant_needed=0x7f0500b3;
public static int rc_permission_microphone=0x7f0500b4;
public static int rc_permission_microphone_and_camera=0x7f0500b5;
public static int rc_picprev_origin=0x7f0500b6;
public static int rc_picprev_origin_size=0x7f0500b7;
public static int rc_picprev_select=0x7f0500b8;
public static int rc_picsel_catalog_allpic=0x7f0500b9;
public static int rc_picsel_catalog_number=0x7f0500ba;
public static int rc_picsel_pictype=0x7f0500bb;
public static int rc_picsel_selected_max=0x7f0500bc;
public static int rc_picsel_take_picture=0x7f0500bd;
public static int rc_picsel_toolbar=0x7f0500be;
public static int rc_picsel_toolbar_preview=0x7f0500bf;
public static int rc_picsel_toolbar_preview_num=0x7f0500c0;
public static int rc_picsel_toolbar_send=0x7f0500c1;
public static int rc_picsel_toolbar_send_num=0x7f0500c2;
public static int rc_plugin_image=0x7f0500c3;
public static int rc_plugin_location=0x7f0500c4;
public static int rc_plugin_location_message=0x7f0500c5;
public static int rc_plugin_location_sharing=0x7f0500c6;
public static int rc_plugin_recognize=0x7f0500c7;
public static int rc_plugin_recognize_check_network=0x7f0500c8;
public static int rc_plugin_recognize_clear=0x7f0500c9;
public static int rc_plugins_camera=0x7f0500ca;
public static int rc_plugins_files=0x7f0500cb;
public static int rc_plugins_voip=0x7f0500cc;
public static int rc_pub_service_info_account=0x7f0500cd;
public static int rc_pub_service_info_description=0x7f0500ce;
public static int rc_pub_service_info_enter=0x7f0500cf;
public static int rc_pub_service_info_follow=0x7f0500d0;
public static int rc_pub_service_info_unfollow=0x7f0500d1;
public static int rc_quit_custom_service=0x7f0500d2;
public static int rc_read_all=0x7f0500d3;
public static int rc_read_receipt_status=0x7f0500d4;
public static int rc_real_time_exit_notification=0x7f05010e;
public static int rc_real_time_join_notification=0x7f05010f;
public static int rc_real_time_location_sharing=0x7f0500d5;
public static int rc_real_time_location_summary=0x7f0500d6;
public static int rc_recall_failed=0x7f0500d7;
public static int rc_recalled_a_message=0x7f0500d8;
public static int rc_rejected_by_blacklist_prompt=0x7f0500d9;
public static int rc_saturday_format=0x7f0500da;
public static int rc_save_picture=0x7f0500db;
public static int rc_save_picture_at=0x7f0500dc;
public static int rc_search=0x7f0500dd;
public static int rc_send_format=0x7f0500de;
public static int rc_setting_clear_msg_fail=0x7f0500df;
public static int rc_setting_clear_msg_name=0x7f0500e0;
public static int rc_setting_clear_msg_prompt=0x7f0500e1;
public static int rc_setting_clear_msg_success=0x7f0500e2;
public static int rc_setting_conversation_notify=0x7f0500e3;
public static int rc_setting_conversation_notify_fail=0x7f0500e4;
public static int rc_setting_get_conversation_notify_fail=0x7f0500e5;
public static int rc_setting_name=0x7f0500e6;
public static int rc_setting_set_top=0x7f0500e7;
public static int rc_setting_set_top_fail=0x7f0500e8;
public static int rc_src_file_not_found=0x7f0500e9;
public static int rc_sunsay_format=0x7f0500ea;
public static int rc_thuresday_format=0x7f0500eb;
public static int rc_tuesday_format=0x7f0500ec;
public static int rc_user_recalled_message=0x7f0500ed;
public static int rc_voice_cancel=0x7f0500ee;
public static int rc_voice_failure=0x7f0500ef;
public static int rc_voice_rec=0x7f0500f0;
public static int rc_voice_short=0x7f0500f1;
public static int rc_voice_too_long=0x7f0500f2;
public static int rc_voip_cpu_error=0x7f0500f3;
public static int rc_voip_occupying=0x7f0500f4;
public static int rc_waiting=0x7f0500f5;
public static int rc_wednesday_format=0x7f0500f6;
public static int rc_year_format=0x7f0500f7;
public static int rc_yes=0x7f0500f8;
public static int rc_yesterday_format=0x7f0500f9;
public static int rc_you_are_sharing_location=0x7f0500fa;
public static int rc_you_recalled_a_message=0x7f0500fb;
public static int status_bar_notification_info_overflow=0x7f050000;
}
public static final class style {
public static int RCTheme=0x7f09000a;
public static int RCTheme_Message_RichContent_TextView=0x7f09000b;
public static int RCTheme_Message_TextView=0x7f09000c;
public static int RCTheme_Message_Username_TextView=0x7f09000d;
public static int RCTheme_MessageTime=0x7f09000e;
public static int RCTheme_Notification=0x7f09000f;
public static int RCTheme_TextView=0x7f090010;
public static int RCTheme_TextView_Large=0x7f090011;
public static int RCTheme_TextView_Large_Inverse=0x7f090012;
public static int RCTheme_TextView_Medium=0x7f090013;
public static int RCTheme_TextView_New=0x7f090014;
public static int RCTheme_TextView_Small=0x7f090015;
public static int RcDialog=0x7f090016;
public static int TextAppearance_Compat_Notification=0x7f090000;
public static int TextAppearance_Compat_Notification_Info=0x7f090001;
public static int TextAppearance_Compat_Notification_Info_Media=0x7f090002;
public static int TextAppearance_Compat_Notification_Line2=0x7f090017;
public static int TextAppearance_Compat_Notification_Line2_Media=0x7f090018;
public static int TextAppearance_Compat_Notification_Media=0x7f090003;
public static int TextAppearance_Compat_Notification_Time=0x7f090004;
public static int TextAppearance_Compat_Notification_Time_Media=0x7f090005;
public static int TextAppearance_Compat_Notification_Title=0x7f090006;
public static int TextAppearance_Compat_Notification_Title_Media=0x7f090007;
public static int Widget_Compat_NotificationActionContainer=0x7f090008;
public static int Widget_Compat_NotificationActionText=0x7f090009;
public static int horizontal_light_thin_divider=0x7f090019;
public static int rc_ac_file_manager_image_style=0x7f09001a;
public static int rc_ac_file_manager_line=0x7f09001b;
public static int rc_ac_file_manager_style=0x7f09001c;
public static int rc_ac_file_manager_title=0x7f09001d;
public static int rc_cs_rating_bar=0x7f09001e;
public static int rc_pb_file_download_progress=0x7f09001f;
public static int vertical_light_thin_divider=0x7f090020;
}
public static final class xml {
public static int rc_file_path=0x7f040000;
}
public static final class styleable {
/** Attributes that can be used with a AsyncImageView.
<p>Includes the following attributes:</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Attribute</th><th>Description</th></tr>
<tr><td><code>{@link #AsyncImageView_RCCornerRadius io.rong.recognizer:RCCornerRadius}</code></td><td></td></tr>
<tr><td><code>{@link #AsyncImageView_RCDefDrawable io.rong.recognizer:RCDefDrawable}</code></td><td></td></tr>
<tr><td><code>{@link #AsyncImageView_RCMask io.rong.recognizer:RCMask}</code></td><td></td></tr>
<tr><td><code>{@link #AsyncImageView_RCMinShortSideSize io.rong.recognizer:RCMinShortSideSize}</code></td><td></td></tr>
<tr><td><code>{@link #AsyncImageView_RCShape io.rong.recognizer:RCShape}</code></td><td></td></tr>
</table>
@see #AsyncImageView_RCCornerRadius
@see #AsyncImageView_RCDefDrawable
@see #AsyncImageView_RCMask
@see #AsyncImageView_RCMinShortSideSize
@see #AsyncImageView_RCShape
*/
public static final int[] AsyncImageView = {
0x7f010000, 0x7f010001, 0x7f010002, 0x7f010003,
0x7f010004
};
/**
<p>This symbol is the offset where the {@link io.rong.recognizer.R.attr#RCCornerRadius}
attribute's value can be found in the {@link #AsyncImageView} array.
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name io.rong.recognizer:RCCornerRadius
*/
public static int AsyncImageView_RCCornerRadius = 1;
/**
<p>This symbol is the offset where the {@link io.rong.recognizer.R.attr#RCDefDrawable}
attribute's value can be found in the {@link #AsyncImageView} array.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
@attr name io.rong.recognizer:RCDefDrawable
*/
public static int AsyncImageView_RCDefDrawable = 4;
/**
<p>This symbol is the offset where the {@link io.rong.recognizer.R.attr#RCMask}
attribute's value can be found in the {@link #AsyncImageView} array.
<p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name io.rong.recognizer:RCMask
*/
public static int AsyncImageView_RCMask = 2;
/**
<p>This symbol is the offset where the {@link io.rong.recognizer.R.attr#RCMinShortSideSize}
attribute's value can be found in the {@link #AsyncImageView} array.
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name io.rong.recognizer:RCMinShortSideSize
*/
public static int AsyncImageView_RCMinShortSideSize = 0;
/**
<p>This symbol is the offset where the {@link io.rong.recognizer.R.attr#RCShape}
attribute's value can be found in the {@link #AsyncImageView} array.
<p>Must be one or more (separated by '|') of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>square</code></td><td>0</td><td></td></tr>
<tr><td><code>circle</code></td><td>1</td><td></td></tr>
</table>
@attr name io.rong.recognizer:RCShape
*/
public static int AsyncImageView_RCShape = 3;
/** Attributes that can be used with a AutoLinkTextView.
<p>Includes the following attributes:</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Attribute</th><th>Description</th></tr>
<tr><td><code>{@link #AutoLinkTextView_RCMaxWidth io.rong.recognizer:RCMaxWidth}</code></td><td></td></tr>
</table>
@see #AutoLinkTextView_RCMaxWidth
*/
public static final int[] AutoLinkTextView = {
0x7f010005
};
/**
<p>This symbol is the offset where the {@link io.rong.recognizer.R.attr#RCMaxWidth}
attribute's value can be found in the {@link #AutoLinkTextView} array.
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name io.rong.recognizer:RCMaxWidth
*/
public static int AutoLinkTextView_RCMaxWidth = 0;
/** Attributes that can be used with a FontFamily.
<p>Includes the following attributes:</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Attribute</th><th>Description</th></tr>
<tr><td><code>{@link #FontFamily_fontProviderAuthority io.rong.recognizer:fontProviderAuthority}</code></td><td></td></tr>
<tr><td><code>{@link #FontFamily_fontProviderCerts io.rong.recognizer:fontProviderCerts}</code></td><td></td></tr>
<tr><td><code>{@link #FontFamily_fontProviderFetchStrategy io.rong.recognizer:fontProviderFetchStrategy}</code></td><td></td></tr>
<tr><td><code>{@link #FontFamily_fontProviderFetchTimeout io.rong.recognizer:fontProviderFetchTimeout}</code></td><td></td></tr>
<tr><td><code>{@link #FontFamily_fontProviderPackage io.rong.recognizer:fontProviderPackage}</code></td><td></td></tr>
<tr><td><code>{@link #FontFamily_fontProviderQuery io.rong.recognizer:fontProviderQuery}</code></td><td></td></tr>
</table>
@see #FontFamily_fontProviderAuthority
@see #FontFamily_fontProviderCerts
@see #FontFamily_fontProviderFetchStrategy
@see #FontFamily_fontProviderFetchTimeout
@see #FontFamily_fontProviderPackage
@see #FontFamily_fontProviderQuery
*/
public static final int[] FontFamily = {
0x7f010006, 0x7f010007, 0x7f010008, 0x7f010009,
0x7f01000a, 0x7f01000b
};
/**
<p>This symbol is the offset where the {@link io.rong.recognizer.R.attr#fontProviderAuthority}
attribute's value can be found in the {@link #FontFamily} array.
<p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name io.rong.recognizer:fontProviderAuthority
*/
public static int FontFamily_fontProviderAuthority = 0;
/**
<p>This symbol is the offset where the {@link io.rong.recognizer.R.attr#fontProviderCerts}
attribute's value can be found in the {@link #FontFamily} array.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
@attr name io.rong.recognizer:fontProviderCerts
*/
public static int FontFamily_fontProviderCerts = 3;
/**
<p>This symbol is the offset where the {@link io.rong.recognizer.R.attr#fontProviderFetchStrategy}
attribute's value can be found in the {@link #FontFamily} array.
<p>Must be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>blocking</code></td><td>0</td><td></td></tr>
<tr><td><code>async</code></td><td>1</td><td></td></tr>
</table>
@attr name io.rong.recognizer:fontProviderFetchStrategy
*/
public static int FontFamily_fontProviderFetchStrategy = 4;
/**
<p>This symbol is the offset where the {@link io.rong.recognizer.R.attr#fontProviderFetchTimeout}
attribute's value can be found in the {@link #FontFamily} array.
<p>May be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
<p>May be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>forever</code></td><td>-1</td><td></td></tr>
</table>
@attr name io.rong.recognizer:fontProviderFetchTimeout
*/
public static int FontFamily_fontProviderFetchTimeout = 5;
/**
<p>This symbol is the offset where the {@link io.rong.recognizer.R.attr#fontProviderPackage}
attribute's value can be found in the {@link #FontFamily} array.
<p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name io.rong.recognizer:fontProviderPackage
*/
public static int FontFamily_fontProviderPackage = 1;
/**
<p>This symbol is the offset where the {@link io.rong.recognizer.R.attr#fontProviderQuery}
attribute's value can be found in the {@link #FontFamily} array.
<p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name io.rong.recognizer:fontProviderQuery
*/
public static int FontFamily_fontProviderQuery = 2;
/** Attributes that can be used with a FontFamilyFont.
<p>Includes the following attributes:</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Attribute</th><th>Description</th></tr>
<tr><td><code>{@link #FontFamilyFont_font io.rong.recognizer:font}</code></td><td></td></tr>
<tr><td><code>{@link #FontFamilyFont_fontStyle io.rong.recognizer:fontStyle}</code></td><td></td></tr>
<tr><td><code>{@link #FontFamilyFont_fontWeight io.rong.recognizer:fontWeight}</code></td><td></td></tr>
</table>
@see #FontFamilyFont_font
@see #FontFamilyFont_fontStyle
@see #FontFamilyFont_fontWeight
*/
public static final int[] FontFamilyFont = {
0x7f01000c, 0x7f01000d, 0x7f01000e
};
/**
<p>This symbol is the offset where the {@link io.rong.recognizer.R.attr#font}
attribute's value can be found in the {@link #FontFamilyFont} array.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
@attr name io.rong.recognizer:font
*/
public static int FontFamilyFont_font = 1;
/**
<p>This symbol is the offset where the {@link io.rong.recognizer.R.attr#fontStyle}
attribute's value can be found in the {@link #FontFamilyFont} array.
<p>Must be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>normal</code></td><td>0</td><td></td></tr>
<tr><td><code>italic</code></td><td>1</td><td></td></tr>
</table>
@attr name io.rong.recognizer:fontStyle
*/
public static int FontFamilyFont_fontStyle = 0;
/**
<p>This symbol is the offset where the {@link io.rong.recognizer.R.attr#fontWeight}
attribute's value can be found in the {@link #FontFamilyFont} array.
<p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name io.rong.recognizer:fontWeight
*/
public static int FontFamilyFont_fontWeight = 2;
/** Attributes that can be used with a RongExtension.
<p>Includes the following attributes:</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Attribute</th><th>Description</th></tr>
<tr><td><code>{@link #RongExtension_RCStyle io.rong.recognizer:RCStyle}</code></td><td></td></tr>
</table>
@see #RongExtension_RCStyle
*/
public static final int[] RongExtension = {
0x7f01000f
};
/**
<p>This symbol is the offset where the {@link io.rong.recognizer.R.attr#RCStyle}
attribute's value can be found in the {@link #RongExtension} array.
<p>Must be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>SCE</code></td><td>0x123</td><td></td></tr>
<tr><td><code>SC</code></td><td>0x120</td><td></td></tr>
<tr><td><code>EC</code></td><td>0x320</td><td></td></tr>
<tr><td><code>CE</code></td><td>0x023</td><td></td></tr>
<tr><td><code>C</code></td><td>0x020</td><td></td></tr>
</table>
@attr name io.rong.recognizer:RCStyle
*/
public static int RongExtension_RCStyle = 0;
};
}
| 55.282192 | 141 | 0.72916 |
b83589dc3462d2552c2cf97d4205dc08438602b4 | 12,743 | /******************************************************************************
* Compilation: javac TwoPhaseSimplex.java
* Execution: java TwoPhaseSimplex
* Dependencies: StdOut.java
*
* Given an m-by-n matrix A, an m-length vector b, and an
* n-length vector c, solve the LP { max cx : Ax <= b, x >= 0 }.
* Unlike LinearProgramming.java, this version does not assume b >= 0,
* so it needs to find a basic feasible solution in Phase I.
*
* Creates an (m+1)-by-(n+m+1) simplex tableaux with the
* RHS in column m+n, the objective function in row m, and
* slack variables in columns m through m+n-1.
*
******************************************************************************/
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
public class TwoPhaseSimplex {
private static final double EPSILON = 1.0E-8;
private double[][] a; // tableaux
// row m = objective function
// row m+1 = artificial objective function
// column n to n+m-1 = slack variables
// column n+m to n+m+m-1 = artificial variables
private int m; // number of constraints
private int n; // number of original variables
private int[] basis; // basis[i] = basic variable corresponding to row i
// sets up the simplex tableaux
public TwoPhaseSimplex(double[][] A, double[] b, double[] c) {
m = b.length;
n = c.length;
a = new double[m+2][n+m+m+1];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
a[i][j] = A[i][j];
for (int i = 0; i < m; i++)
a[i][n+i] = 1.0;
for (int i = 0; i < m; i++)
a[i][n+m+m] = b[i];
for (int j = 0; j < n; j++)
a[m][j] = c[j];
// if negative RHS, multiply by -1
for (int i = 0; i < m; i++) {
if (b[i] < 0) {
for (int j = 0; j <= n+m+m; j++)
a[i][j] = -a[i][j];
}
}
// artificial variables form initial basis
for (int i = 0; i < m; i++)
a[i][n+m+i] = 1.0;
for (int i = 0; i < m; i++)
a[m+1][n+m+i] = -1.0;
for (int i = 0; i < m; i++)
pivot(i, n+m+i);
basis = new int[m];
for (int i = 0; i < m; i++)
basis[i] = n + m + i;
StdOut.println("before phase I");
show();
phase1();
StdOut.println("before phase II");
show();
phase2();
StdOut.println("after phase II");
show();
// check optimality conditions
assert check(A, b, c);
}
// run phase I simplex algorithm to find basic feasible solution
private void phase1() {
while (true) {
// find entering column q
int q = bland1();
if (q == -1) break; // optimal
// find leaving row p
int p = minRatioRule(q);
assert p != -1 : "Entering column = " + q;
// pivot
pivot(p, q);
// update basis
basis[p] = q;
show();
}
if (a[m+1][n+m+m] > EPSILON) throw new ArithmeticException("Infeasible LP");
}
// run simplex algorithm starting from initial basic feasible solution
private void phase2() {
while (true) {
// find entering column q
int q = bland2();
if (q == -1) break; // optimal
// find leaving row p
int p = minRatioRule(q);
if (p == -1) throw new ArithmeticException("Linear program is unbounded");
// pivot
pivot(p, q);
// update basis
basis[p] = q;
}
}
// lowest index of a non-basic column with a positive cost - using artificial objective function
private int bland1() {
for (int j = 0; j < n+m; j++)
if (a[m+1][j] > EPSILON) return j;
return -1; // optimal
}
// lowest index of a non-basic column with a positive cost
private int bland2() {
for (int j = 0; j < n+m; j++)
if (a[m][j] > EPSILON) return j;
return -1; // optimal
}
// find row p using min ratio rule (-1 if no such row)
private int minRatioRule(int q) {
int p = -1;
for (int i = 0; i < m; i++) {
if (a[i][q] <= 0) continue;
else if (p == -1) p = i;
else if ((a[i][n+m+m] / a[i][q]) < (a[p][n+m+m] / a[p][q])) p = i;
}
return p;
}
// pivot on entry (p, q) using Gauss-Jordan elimination
private void pivot(int p, int q) {
// everything but row p and column q
for (int i = 0; i <= m+1; i++) {
for (int j = 0; j <= n+m+m; j++){
if (i != p && j != q){
// StdOut.print("a["+p+"]["+j+"]"+"="+a[p][j]);
// StdOut.print(" a["+i+"]["+q+"]"+"="+a[i][q]);
// StdOut.print(" a["+p+"]["+q+"]"+"="+a[p][q]);
a[i][j] -= a[p][j] * a[i][q] / a[p][q];
// StdOut.println(" a["+i+"]["+j+"]"+"="+a[i][j]);
}
}
}
// zero out column q
for (int i = 0; i <= m+1; i++)
if (i != p) a[i][q] = 0.0;
// scale row p
for (int j = 0; j <= n+m+m; j++)
if (j != q) a[p][j] /= a[p][q];
a[p][q] = 1.0;
// StdOut.println();
// StdOut.println("Pivot: " + "p: " + p + " q: " + q);
// for (int i = 0; i <= m+1; i++) {
// for (int j = 0; j <= n+m+m; j++) {
// StdOut.printf("%7.2f ", a[i][j]);
// if (j == n+m-1 || j == n+m+m-1) StdOut.print(" |");
// }
// StdOut.println();
// }
}
// return optimal objective value
public double value() {
return -a[m][n+m+m];
}
// return primal solution vector
public double[] primal() {
double[] x = new double[n];
for (int i = 0; i < m; i++)
if (basis[i] < n) x[basis[i]] = a[i][n+m+m];
return x;
}
// return dual solution vector
public double[] dual() {
double[] y = new double[m];
for (int i = 0; i < m; i++)
y[i] = -a[m][n+i];
return y;
}
// is the solution primal feasible?
private boolean isPrimalFeasible(double[][] A, double[] b) {
double[] x = primal();
// check that x >= 0
for (int j = 0; j < x.length; j++) {
if (x[j] < 0.0) {
StdOut.println("x[" + j + "] = " + x[j] + " is negative");
return false;
}
}
// check that Ax <= b
for (int i = 0; i < m; i++) {
double sum = 0.0;
for (int j = 0; j < n; j++) {
sum += A[i][j] * x[j];
}
if (sum > b[i] + EPSILON) {
StdOut.println("not primal feasible");
StdOut.println("b[" + i + "] = " + b[i] + ", sum = " + sum);
return false;
}
}
return true;
}
// is the solution dual feasible?
private boolean isDualFeasible(double[][] A, double[] c) {
double[] y = dual();
// check that y >= 0
for (int i = 0; i < y.length; i++) {
if (y[i] < 0.0) {
StdOut.println("y[" + i + "] = " + y[i] + " is negative");
return false;
}
}
// check that yA >= c
for (int j = 0; j < n; j++) {
double sum = 0.0;
for (int i = 0; i < m; i++) {
sum += A[i][j] * y[i];
}
if (sum < c[j] - EPSILON) {
StdOut.println("not dual feasible");
StdOut.println("c[" + j + "] = " + c[j] + ", sum = " + sum);
return false;
}
}
return true;
}
// check that optimal value = cx = yb
private boolean isOptimal(double[] b, double[] c) {
double[] x = primal();
double[] y = dual();
double value = value();
// check that value = cx = yb
double value1 = 0.0;
for (int j = 0; j < x.length; j++)
value1 += c[j] * x[j];
double value2 = 0.0;
for (int i = 0; i < y.length; i++)
value2 += y[i] * b[i];
if (Math.abs(value - value1) > EPSILON || Math.abs(value - value2) > EPSILON) {
StdOut.println("value = " + value + ", cx = " + value1 + ", yb = " + value2);
return false;
}
return true;
}
private boolean check(double[][]A, double[] b, double[] c) {
return isPrimalFeasible(A, b) && isDualFeasible(A, c) && isOptimal(b, c);
}
// print tableaux
public void show() {
StdOut.println("m = " + m);
StdOut.println("n = " + n);
for (int i = 0; i <= m+1; i++) {
for (int j = 0; j <= n+m+m; j++) {
StdOut.printf("%7.2f ", a[i][j]);
if (j == n+m-1 || j == n+m+m-1) StdOut.print(" |");
}
StdOut.println();
}
StdOut.print("basis = ");
for (int i = 0; i < m; i++)
StdOut.print(basis[i] + " ");
StdOut.println();
StdOut.println();
}
public static void test(double[][] A, double[] b, double[] c) {
TwoPhaseSimplex lp = new TwoPhaseSimplex(A, b, c);
StdOut.println("value = " + lp.value());
double[] x = lp.primal();
for (int i = 0; i < x.length; i++)
StdOut.println("x[" + i + "] = " + x[i]);
double[] y = lp.dual();
for (int j = 0; j < y.length; j++)
StdOut.println("y[" + j + "] = " + y[j]);
}
// x0 = 12, x1 = 28, opt = 800
public static void test1() {
double[] c = { 13.0, 23.0 };
double[] b = { 480.0, 160.0, 1190.0 };
double[][] A = {
{ 5.0, 15.0 },
{ 4.0, 4.0 },
{ 35.0, 20.0 },
};
test(A, b, c);
}
// dual of test1(): x0 = 12, x1 = 28, opt = 800
public static void test2() {
double[] b = { -13.0, -23.0 };
double[] c = { -480.0, -160.0, -1190.0 };
double[][] A = {
{ -5.0, -4.0, -35.0 },
{ -15.0, -4.0, -20.0 }
};
test(A, b, c);
}
public static void test3() {
double[][] A = {
{ -1, 1, 0 },
{ 1, 4, 0 },
{ 2, 1, 0 },
{ 3, -4, 0 },
{ 0, 0, 1 },
};
double[] c = { 1, 1, 1 };
double[] b = { 5, 45, 27, 24, 4 };
test(A, b, c);
}
// unbounded
public static void test4() {
double[] c = { 2.0, 3.0, -1.0, -12.0 };
double[] b = { 3.0, 2.0 };
double[][] A = {
{ -2.0, -9.0, 1.0, 9.0 },
{ 1.0, 1.0, -1.0, -2.0 },
};
test(A, b, c);
}
// degenerate - cycles if you choose most positive objective function coefficient
public static void test5() {
double[] c = { 10.0, -57.0, -9.0, -24.0 };
double[] b = { 0.0, 0.0, 1.0 };
double[][] A = {
{ 0.5, -5.5, -2.5, 9.0 },
{ 0.5, -1.5, -0.5, 1.0 },
{ 1.0, 0.0, 0.0, 0.0 },
};
test(A, b, c);
}
// test client
public static void main(String[] args) {
StdOut.println("----- test 1 --------------------");
test1();
StdOut.println();
StdOut.println("----- test 2 --------------------");
test2();
StdOut.println();
StdOut.println("----- test 3 --------------------");
// test3();
StdOut.println();
StdOut.println("----- test 4 --------------------");
// try {
// test4();
// }
// catch (ArithmeticException e) {
// System.out.println(e);
// }
StdOut.println("----- test random ---------------");
// int m = Integer.parseInt(args[0]);
// int n = Integer.parseInt(args[1]);
// double[] c = new double[n];
// double[] b = new double[m];
// double[][] A = new double[m][n];
// for (int j = 0; j < n; j++)
// c[j] = StdRandom.uniform(1000);
// for (int i = 0; i < m; i++)
// b[i] = StdRandom.uniform(1000) - 200;
// for (int i = 0; i < m; i++)
// for (int j = 0; j < n; j++)
// A[i][j] = StdRandom.uniform(100) - 20;
// test(A, b, c);
}
}
| 29.913146 | 100 | 0.403908 |
3e39ebd5aca5c9d3e4bfe8108cacff5ace389b19 | 34,276 | /*
* #%L
* Alfresco Records Management Module
* %%
* Copyright (C) 2005 - 2019 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* -
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
* -
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* -
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* -
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.web.scripts.roles;
import static java.util.Collections.emptyMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.security.ExtendedReaderDynamicAuthority;
import org.alfresco.module.org_alfresco_module_rm.security.ExtendedSecurityService;
import org.alfresco.module.org_alfresco_module_rm.security.ExtendedWriterDynamicAuthority;
import org.alfresco.module.org_alfresco_module_rm.test.util.AlfMock;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest;
import org.alfresco.repo.domain.node.NodeDAO;
import org.alfresco.repo.domain.patch.PatchDAO;
import org.alfresco.repo.domain.qname.QNameDAO;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.repo.web.scripts.content.ContentStreamer;
import org.alfresco.service.cmr.model.FileFolderService;
import org.alfresco.service.cmr.model.FileInfo;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.Pair;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.extensions.webscripts.AbstractWebScript;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.WebScriptException;
import org.springframework.extensions.webscripts.WebScriptRequest;
import org.springframework.extensions.webscripts.WebScriptResponse;
/**
* DynamicAuthoritiesGet Unit Test
*
* @author Silviu Dinuta
*/
@SuppressWarnings("deprecation")
public class DynamicAuthoritiesGetUnitTest extends BaseWebScriptUnitTest implements RecordsManagementModel
{
/** test data */
private static final Long ASPECT_ID = 123l;
private static final QName ASPECT = AlfMock.generateQName();
/** mocks */
@Mock
private PatchDAO mockedPatchDAO;
@Mock
private NodeDAO mockedNodeDAO;
@Mock
private QNameDAO mockedQnameDAO;
@Mock
private NodeService mockedNodeService;
@Mock
private PermissionService mockedPermissionService;
@Mock
private ExtendedSecurityService mockedExtendedSecurityService;
@Mock
private TransactionService mockedTransactionService;
@Mock
private RetryingTransactionHelper mockedRetryingTransactionHelper;
@Mock
private ContentStreamer contentStreamer;
@Mock
private FileFolderService mockedFileFolderService;
/** test component */
@InjectMocks
private DynamicAuthoritiesGet webScript;
@Override
protected AbstractWebScript getWebScript()
{
return webScript;
}
@Override
protected String getWebScriptTemplate()
{
return "alfresco/templates/webscripts/org/alfresco/repository/roles/rm-dynamicauthorities.get.json.ftl";
}
/**
* Before test
*/
@SuppressWarnings("unchecked")
@Before
public void before()
{
MockitoAnnotations.initMocks(this);
webScript.setNodeService(mockedNodeService);
webScript.setPermissionService(mockedPermissionService);
webScript.setExtendedSecurityService(mockedExtendedSecurityService);
webScript.setFileFolderService(mockedFileFolderService);
// setup retrying transaction helper
Answer<Object> doInTransactionAnswer = new Answer<Object>()
{
@SuppressWarnings("rawtypes")
@Override
public Object answer(InvocationOnMock invocation) throws Throwable
{
RetryingTransactionCallback callback = (RetryingTransactionCallback) invocation.getArguments()[0];
return callback.execute();
}
};
doAnswer(doInTransactionAnswer).when(mockedRetryingTransactionHelper)
.<Object> doInTransaction(any(RetryingTransactionCallback.class), anyBoolean(), anyBoolean());
when(mockedTransactionService.getRetryingTransactionHelper()).thenReturn(mockedRetryingTransactionHelper);
// max node id
when(mockedPatchDAO.getMaxAdmNodeID()).thenReturn(500000L);
// aspect
when(mockedQnameDAO.getQName(ASPECT_EXTENDED_SECURITY)).thenReturn(new Pair<>(ASPECT_ID, ASPECT));
}
/**
* Given that there are no nodes with the extended security aspect
* When the action is executed Nothing happens
*
* @throws Exception
*/
@SuppressWarnings({ "unchecked" })
@Test
public void noNodesWithExtendedSecurity() throws Exception
{
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong()))
.thenReturn(Collections.emptyList());
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "10", "maxProcessedRecords", "3");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
// Check the JSON result using Jackson to allow easy equality testing.
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed 0 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
verify(mockedNodeService, never()).getProperty(any(NodeRef.class), eq(PROP_READERS));
verify(mockedNodeService, never()).getProperty(any(NodeRef.class), eq(PROP_WRITERS));
verify(mockedNodeService, never()).removeAspect(any(NodeRef.class), eq(ASPECT_EXTENDED_SECURITY));
verify(mockedPermissionService, never()).clearPermission(any(NodeRef.class),
eq(ExtendedReaderDynamicAuthority.EXTENDED_READER));
verify(mockedPermissionService, never()).clearPermission(any(NodeRef.class),
eq(ExtendedWriterDynamicAuthority.EXTENDED_WRITER));
verify(mockedExtendedSecurityService, never()).set(any(NodeRef.class), any(Set.class), any(Set.class));
}
/**
* Given that there are records with the extended security aspect
* When the action is executed
* Then the aspect is removed
* And the dynamic authorities permissions are cleared
* And extended security is set via the updated API
*
* @throws Exception
*/
@SuppressWarnings("unchecked")
@Test
public void recordsWithExtendedSecurityAspect() throws Exception
{
List<Long> ids = Stream.of(1l, 2l, 3l).collect(Collectors.toList());
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong())).thenReturn(ids)
.thenReturn(Collections.emptyList());
ids.stream().forEach((i) -> {
NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeDAO.getNodePair(i)).thenReturn(new Pair<>(i, nodeRef));
when(mockedNodeService.hasAspect(nodeRef, ASPECT_RECORD)).thenReturn(true);
when(mockedNodeService.getProperty(nodeRef, PROP_READERS))
.thenReturn((Serializable) Collections.emptyMap());
when(mockedNodeService.getProperty(nodeRef, PROP_WRITERS))
.thenReturn((Serializable) Collections.emptyMap());
});
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "10", "maxProcessedRecords", "4");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed 3 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
verify(mockedNodeService, times(3)).getProperty(any(NodeRef.class), eq(PROP_READERS));
verify(mockedNodeService, times(3)).getProperty(any(NodeRef.class), eq(PROP_WRITERS));
verify(mockedNodeService, times(3)).removeAspect(any(NodeRef.class), eq(ASPECT_EXTENDED_SECURITY));
verify(mockedPermissionService, times(3)).clearPermission(any(NodeRef.class),
eq(ExtendedReaderDynamicAuthority.EXTENDED_READER));
verify(mockedPermissionService, times(3)).clearPermission(any(NodeRef.class),
eq(ExtendedWriterDynamicAuthority.EXTENDED_WRITER));
verify(mockedExtendedSecurityService, times(3)).set(any(NodeRef.class), any(Set.class), any(Set.class));
}
/**
* Given that there are non-records with the extended security aspect
* When the web script is executed
* Then the aspect is removed And the dynamic authorities permissions are cleared
*
* @throws Exception
*/
@SuppressWarnings("unchecked")
@Test
public void nonRecordsWithExtendedSecurityAspect() throws Exception
{
List<Long> ids = Stream.of(1l, 2l, 3l).collect(Collectors.toList());
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong())).thenReturn(ids)
.thenReturn(Collections.emptyList());
ids.stream().forEach((i) -> {
NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeDAO.getNodePair(i)).thenReturn(new Pair<>(i, nodeRef));
when(mockedNodeService.hasAspect(nodeRef, ASPECT_RECORD)).thenReturn(false);
when(mockedNodeService.getProperty(nodeRef, PROP_READERS))
.thenReturn((Serializable) Collections.emptyMap());
when(mockedNodeService.getProperty(nodeRef, PROP_WRITERS))
.thenReturn((Serializable) Collections.emptyMap());
});
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "10", "maxProcessedRecords", "4");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed 3 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
verify(mockedNodeService, times(3)).getProperty(any(NodeRef.class), eq(PROP_READERS));
verify(mockedNodeService, times(3)).getProperty(any(NodeRef.class), eq(PROP_WRITERS));
verify(mockedNodeService, times(3)).removeAspect(any(NodeRef.class), eq(ASPECT_EXTENDED_SECURITY));
verify(mockedPermissionService, times(3)).clearPermission(any(NodeRef.class),
eq(ExtendedReaderDynamicAuthority.EXTENDED_READER));
verify(mockedPermissionService, times(3)).clearPermission(any(NodeRef.class),
eq(ExtendedWriterDynamicAuthority.EXTENDED_WRITER));
verify(mockedExtendedSecurityService, never()).set(any(NodeRef.class), any(Set.class), any(Set.class));
}
@Test
public void missingBatchSizeParameter() throws Exception
{
try
{
executeJSONWebScript(emptyMap());
fail("Expected exception as parameter batchsize is mandatory.");
}
catch (WebScriptException e)
{
assertEquals("If parameter batchsize is not provided then 'Bad request' should be returned.",
Status.STATUS_BAD_REQUEST, e.getStatus());
}
}
@Test
public void invalidBatchSizeParameter() throws Exception
{
try
{
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "dd");
executeJSONWebScript(parameters);
fail("Expected exception as parameter batchsize is invalid.");
}
catch (WebScriptException e)
{
assertEquals("If parameter batchsize is invalid then 'Bad request' should be returned.",
Status.STATUS_BAD_REQUEST, e.getStatus());
}
}
@Test
public void batchSizeShouldBeGraterThanZero() throws Exception
{
try
{
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "0");
executeJSONWebScript(parameters);
fail("Expected exception as parameter batchsize is not a number greater than 0.");
}
catch (WebScriptException e)
{
assertEquals("If parameter batchsize is not a number greater than 0 then 'Bad request' should be returned.",
Status.STATUS_BAD_REQUEST, e.getStatus());
}
}
@Test
public void extendedSecurityAspectNotCreated() throws Exception
{
when(mockedQnameDAO.getQName(ASPECT_EXTENDED_SECURITY)).thenReturn(null);
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "3");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"There where no records to be processed.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
}
@Test
public void processAllRecordsWhenMaxProcessedRecordsIsZero() throws Exception
{
List<Long> ids = Stream.of(1l, 2l, 3l,4l).collect(Collectors.toList());
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong())).thenReturn(ids)
.thenReturn(Collections.emptyList());
ids.stream().forEach((i) -> {
NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeDAO.getNodePair(i)).thenReturn(new Pair<>(i, nodeRef));
when(mockedNodeService.hasAspect(nodeRef, ASPECT_RECORD)).thenReturn(false);
when(mockedNodeService.getProperty(nodeRef, PROP_READERS))
.thenReturn((Serializable) Collections.emptyMap());
when(mockedNodeService.getProperty(nodeRef, PROP_WRITERS))
.thenReturn((Serializable) Collections.emptyMap());
});
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "10", "maxProcessedRecords", "0");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed 4 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
}
@Test
public void whenMaxProcessedRecordsIsMissingItDefaultsToBatchSize() throws Exception
{
List<Long> ids = Stream.of(1l, 2l, 3l, 4l, 5l).collect(Collectors.toList());
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong())).thenReturn(ids)
.thenReturn(Collections.emptyList());
ids.stream().forEach((i) -> {
NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeDAO.getNodePair(i)).thenReturn(new Pair<>(i, nodeRef));
when(mockedNodeService.hasAspect(nodeRef, ASPECT_RECORD)).thenReturn(false);
when(mockedNodeService.getProperty(nodeRef, PROP_READERS))
.thenReturn((Serializable) Collections.emptyMap());
when(mockedNodeService.getProperty(nodeRef, PROP_WRITERS))
.thenReturn((Serializable) Collections.emptyMap());
});
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "4");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed first 4 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void recordsWithExtendedSecurityAspectAndNullWritersAndReaders() throws Exception
{
List<Long> ids = Stream.of(1l, 2l, 3l).collect(Collectors.toList());
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong())).thenReturn(ids)
.thenReturn(Collections.emptyList());
ids.stream().forEach((i) -> {
NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeDAO.getNodePair(i)).thenReturn(new Pair<>(i, nodeRef));
when(mockedNodeService.hasAspect(nodeRef, ASPECT_RECORD)).thenReturn(true);
when(mockedNodeService.getProperty(nodeRef, PROP_READERS)).thenReturn(null);
when(mockedNodeService.getProperty(nodeRef, PROP_WRITERS)).thenReturn(null);
});
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "10", "maxProcessedRecords", "4");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed 3 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
ArgumentCaptor<Set> readerKeysCaptor = ArgumentCaptor.forClass(Set.class);
ArgumentCaptor<Set> writersKeysCaptor = ArgumentCaptor.forClass(Set.class);
verify(mockedNodeService, times(3)).getProperty(any(NodeRef.class), eq(PROP_READERS));
verify(mockedNodeService, times(3)).getProperty(any(NodeRef.class), eq(PROP_WRITERS));
verify(mockedNodeService, times(3)).removeAspect(any(NodeRef.class), eq(ASPECT_EXTENDED_SECURITY));
verify(mockedPermissionService, times(3)).clearPermission(any(NodeRef.class),
eq(ExtendedReaderDynamicAuthority.EXTENDED_READER));
verify(mockedPermissionService, times(3)).clearPermission(any(NodeRef.class),
eq(ExtendedWriterDynamicAuthority.EXTENDED_WRITER));
verify(mockedExtendedSecurityService, times(3)).set(any(NodeRef.class), readerKeysCaptor.capture(),
writersKeysCaptor.capture());
List<Set> allReaderKeySets = readerKeysCaptor.getAllValues();
List<Set> allWritersKeySets = writersKeysCaptor.getAllValues();
for (Set keySet : allReaderKeySets)
{
assertNull(keySet);
}
for (Set keySet : allWritersKeySets)
{
assertNull(keySet);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void recordsWithExtendedSecurityAspectAndNullWriters() throws Exception
{
List<Long> ids = Stream.of(1l, 2l, 3l).collect(Collectors.toList());
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong())).thenReturn(ids)
.thenReturn(Collections.emptyList());
ids.stream().forEach((i) -> {
NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeDAO.getNodePair(i)).thenReturn(new Pair<>(i, nodeRef));
when(mockedNodeService.hasAspect(nodeRef, ASPECT_RECORD)).thenReturn(true);
when(mockedNodeService.getProperty(nodeRef, PROP_READERS))
.thenReturn((Serializable) Collections.emptyMap());
when(mockedNodeService.getProperty(nodeRef, PROP_WRITERS)).thenReturn(null);
});
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "10", "maxProcessedRecords", "4");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed 3 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
ArgumentCaptor<Set> readerKeysCaptor = ArgumentCaptor.forClass(Set.class);
ArgumentCaptor<Set> writersKeysCaptor = ArgumentCaptor.forClass(Set.class);
verify(mockedNodeService, times(3)).getProperty(any(NodeRef.class), eq(PROP_READERS));
verify(mockedNodeService, times(3)).getProperty(any(NodeRef.class), eq(PROP_WRITERS));
verify(mockedNodeService, times(3)).removeAspect(any(NodeRef.class), eq(ASPECT_EXTENDED_SECURITY));
verify(mockedPermissionService, times(3)).clearPermission(any(NodeRef.class),
eq(ExtendedReaderDynamicAuthority.EXTENDED_READER));
verify(mockedPermissionService, times(3)).clearPermission(any(NodeRef.class),
eq(ExtendedWriterDynamicAuthority.EXTENDED_WRITER));
verify(mockedExtendedSecurityService, times(3)).set(any(NodeRef.class), readerKeysCaptor.capture(),
writersKeysCaptor.capture());
List<Set> allReaderKeySets = readerKeysCaptor.getAllValues();
List<Set> allWritersKeySets = writersKeysCaptor.getAllValues();
for (Set keySet : allReaderKeySets)
{
assertNotNull(keySet);
}
for (Set keySet : allWritersKeySets)
{
assertNull(keySet);
}
}
/**
* Given I have records that require migration
* And I am interested in knowning which records are migrated
* When I run the migration tool
* Then I will be returned a CSV file containing the name and node reference of the record migrated
*
* @throws Exception
*/
@SuppressWarnings("unchecked")
@Test
public void processWithCSVFile() throws Exception
{
List<Long> ids = Stream.of(1l, 2l, 3l).collect(Collectors.toList());
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong())).thenReturn(ids)
.thenReturn(Collections.emptyList());
ids.stream().forEach((i) -> {
NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeDAO.getNodePair(i)).thenReturn(new Pair<>(i, nodeRef));
when(mockedNodeService.hasAspect(nodeRef, ASPECT_RECORD)).thenReturn(true);
when(mockedNodeService.getProperty(nodeRef, PROP_READERS))
.thenReturn((Serializable) Collections.emptyMap());
when(mockedNodeService.getProperty(nodeRef, PROP_WRITERS))
.thenReturn((Serializable) Collections.emptyMap());
String name = "name" + i;
when(mockedNodeService.getProperty(nodeRef, ContentModel.PROP_NAME)).thenReturn((Serializable) name);
});
ArgumentCaptor<File> csvFileCaptor = ArgumentCaptor.forClass(File.class);
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "10", "maxProcessedRecords", "4", "export",
"true");
executeWebScript(parameters);
verify(contentStreamer, times(1)).streamContent(any(WebScriptRequest.class), any(WebScriptResponse.class),
csvFileCaptor.capture(), any(Long.class), any(Boolean.class), any(String.class), any(Map.class));
File fileForDownload = csvFileCaptor.getValue();
assertNotNull(fileForDownload);
}
/**
* Given that I have record that require migration
* And I'm not interested in knowing which records were migrated
* When I run the migration tool
* Then I will not be returned a CSV file of details.
*
* @throws Exception
*/
@SuppressWarnings("unchecked")
@Test
public void processedWithouthCSVFile() throws Exception
{
List<Long> ids = Stream.of(1l, 2l, 3l).collect(Collectors.toList());
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong())).thenReturn(ids)
.thenReturn(Collections.emptyList());
ids.stream().forEach((i) -> {
NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeDAO.getNodePair(i)).thenReturn(new Pair<>(i, nodeRef));
when(mockedNodeService.hasAspect(nodeRef, ASPECT_RECORD)).thenReturn(true);
when(mockedNodeService.getProperty(nodeRef, PROP_READERS))
.thenReturn((Serializable) Collections.emptyMap());
when(mockedNodeService.getProperty(nodeRef, PROP_WRITERS))
.thenReturn((Serializable) Collections.emptyMap());
});
Map<String, String> parameters = ImmutableMap.of("batchsize", "10", "maxProcessedRecords", "4", "export",
"false");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed 3 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
verify(contentStreamer, never()).streamContent(any(WebScriptRequest.class), any(WebScriptResponse.class),
any(File.class), any(Long.class), any(Boolean.class), any(String.class), any(Map.class));
}
@Test
public void invalidParentNodeRefParameter() throws Exception
{
try
{
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "10", "parentNodeRef", "invalidNodeRef");
executeJSONWebScript(parameters);
fail("Expected exception as parameter parentNodeRef is invalid.");
}
catch (WebScriptException e)
{
assertEquals("If parameter parentNodeRef is invalid then 'Internal server error' should be returned.",
Status.STATUS_INTERNAL_SERVER_ERROR, e.getStatus());
}
}
@Test
public void inexistentParentNodeRefParameter() throws Exception
{
try
{
NodeRef parentNodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeService.exists(parentNodeRef)).thenReturn(false);
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "10", "parentNodeRef",
parentNodeRef.toString());
executeJSONWebScript(parameters);
fail("Expected exception as parameter parentNodeRef does not exist.");
}
catch (WebScriptException e)
{
assertEquals("If parameter parentNodeRef is does not exist then 'Bad Reequest' should be returned.",
Status.STATUS_BAD_REQUEST, e.getStatus());
}
}
@SuppressWarnings("unchecked")
@Test
public void processedWithParentNodeRef() throws Exception
{
List<Long> ids = Stream.of(1l, 2l, 3l).collect(Collectors.toList());
NodeRef parentNodeRef = AlfMock.generateNodeRef(mockedNodeService);
List<FileInfo> children = new ArrayList<>();
ids.stream().forEach((i) -> {
NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeService.hasAspect(nodeRef, ASPECT_RECORD)).thenReturn(true);
when(mockedNodeService.hasAspect(nodeRef, ASPECT)).thenReturn(true);
when(mockedNodeService.getProperty(nodeRef, PROP_READERS))
.thenReturn((Serializable) Collections.emptyMap());
when(mockedNodeService.getProperty(nodeRef, PROP_WRITERS))
.thenReturn((Serializable) Collections.emptyMap());
String name = "name" + i;
when(mockedNodeService.getProperty(nodeRef, ContentModel.PROP_NAME)).thenReturn((Serializable) name);
FileInfo mockedFileInfo = mock(FileInfo.class);
when(mockedFileInfo.getNodeRef()).thenReturn(nodeRef);
children.add(mockedFileInfo);
});
when(mockedFileFolderService.search(eq(parentNodeRef), eq("*"), eq(true), eq(true), eq(true)))
.thenReturn(children);
Map<String, String> parameters = ImmutableMap.of("batchsize", "3", "maxProcessedRecords", "4", "export",
"false", "parentNodeRef", parentNodeRef.toString());
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed 3 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
verify(contentStreamer, never()).streamContent(any(WebScriptRequest.class), any(WebScriptResponse.class),
any(File.class), any(Long.class), any(Boolean.class), any(String.class), any(Map.class));
}
@SuppressWarnings("unchecked")
@Test
public void processedWithParentNodeRefWithFirstTwoBatchesAlreadyProcessed() throws Exception
{
List<Long> ids = Stream.of(1l, 2l, 3l, 4l, 5l, 6l, 7l, 8l).collect(Collectors.toList());
NodeRef parentNodeRef = AlfMock.generateNodeRef(mockedNodeService);
List<FileInfo> children = new ArrayList<>();
ids.stream().forEach((i) -> {
NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeService.hasAspect(nodeRef, ASPECT_RECORD)).thenReturn(true);
if (i <= 6l)
{
when(mockedNodeService.hasAspect(nodeRef, ASPECT)).thenReturn(false);
}
else
{
when(mockedNodeService.hasAspect(nodeRef, ASPECT)).thenReturn(true);
}
when(mockedNodeService.getProperty(nodeRef, PROP_READERS))
.thenReturn((Serializable) Collections.emptyMap());
when(mockedNodeService.getProperty(nodeRef, PROP_WRITERS))
.thenReturn((Serializable) Collections.emptyMap());
String name = "name" + i;
when(mockedNodeService.getProperty(nodeRef, ContentModel.PROP_NAME)).thenReturn((Serializable) name);
FileInfo mockedFileInfo = mock(FileInfo.class);
when(mockedFileInfo.getNodeRef()).thenReturn(nodeRef);
children.add(mockedFileInfo);
});
when(mockedFileFolderService.search(eq(parentNodeRef), eq("*"), eq(true), eq(true), eq(true)))
.thenReturn(children);
Map<String, String> parameters = ImmutableMap.of("batchsize", "3", "parentNodeRef", parentNodeRef.toString());
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed 2 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
verify(contentStreamer, never()).streamContent(any(WebScriptRequest.class), any(WebScriptResponse.class),
any(File.class), any(Long.class), any(Boolean.class), any(String.class), any(Map.class));
}
}
| 47.14718 | 127 | 0.678492 |
4bc18d62e61cfa77fd32bb6914db3533a083dd6d | 465 | package com.github.quintans.ezSQL.toolkit.utils;
public class Holder<T>{
private T object;
public Holder() {
}
public Holder(T object) {
this.object = object;
}
public T get() {
return object;
}
public void set(T object) {
this.object = object;
}
public boolean isEmpty(){
return object == null;
}
public String toString(){
if(object != null)
return object.toString();
else
return null;
}
}
| 14.090909 | 49 | 0.602151 |
df7d15edc56bdc7868fa07326b821d7ac5f3f3fa | 889 | class Dog implements Runnable {
private Object obj;
private String name;
private int length;
public Dog(String name, int length) {
this.obj = null;
this.name = name;
this.length = length;
}
public Dog(String name, int length, Object obj) {
this(name, length);
this.obj = obj;
}
public void run() {
if (obj != null) {
synchronized(obj) {
for (int i = 0; i < length; i++) {
System.out.println("Hello from lock " + name + ": " + i);
}
}
} else {
for (int i = 0; i < length; i++) {
System.out.println("Hello from non-lock " + name + ": " + i);
}
}
}
} | 27.78125 | 85 | 0.390326 |
ec15a84fc8c990b7f31d29edab955c6dc6ed21f7 | 4,633 | package com.example.weatherapplicationsosm;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager.widget.ViewPager;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MainActivity extends FragmentActivity {
private static final String PLACES_API_KEY = "AIzaSyA-CWYXgBjdZ7l9HjDGOxlfknuaR1e0A_U";
private RequestQueue requestQueue;
private List<String> citiesList;
private ViewPager viewPager;
private WeatherCollectionAdapter pagerAdapter;
private EditText cityId;
private Button addButton, deleteButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// HTTP Volley request queue.
requestQueue = Volley.newRequestQueue(this);
// // Places API KEY.
// Places.initialize(this, PLACES_API_KEY);
// PlacesClient placesClient = Places.createClient(this);
//
// // Initialize the AutocompleteSupportFragment.
// AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
// getSupportFragmentManager().findFragmentById(R.id.autocompleteFragment);
// // Specify the types of place data to return.
// autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));
// autocompleteFragment.setTypeFilter(TypeFilter.CITIES);
// // Set up a PlaceSelectionListener to handle the response.
// autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
// @Override
// public void onPlaceSelected(Place place) {
// pagerAdapter.addItem(place.getId());
// }
//
// @Override
// public void onError(Status status) {
// Log.i("TEST", "An error occurred: " + status);
// }
// });
// Swipe ViewPager.
viewPager = findViewById(R.id.pager);
initializeCities();
pagerAdapter = new WeatherCollectionAdapter(getSupportFragmentManager(), citiesList, requestQueue);
viewPager.setAdapter(pagerAdapter);
// City edit text.
cityId = findViewById(R.id.cityEditText);
cityId.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
Log.i("ADD", cityId.getText().toString());
pagerAdapter.addItem(cityId.getText().toString());
cityId.setText("");
return true;
}
return false;
}
});
// Add a add button.
addButton = findViewById(R.id.addCity);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("ADD", cityId.getText().toString());
pagerAdapter.addItem(cityId.getText().toString());
cityId.setText("");
}
});
// Add a delete button.
deleteButton = findViewById(R.id.deleteCity);
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("REMOVE", viewPager.getCurrentItem() + "");
pagerAdapter.removeItem(viewPager.getCurrentItem());
}
});
}
private void initializeCities() {
SharedPreferences sharedPreferences = getSharedPreferences("cities", Context.MODE_PRIVATE);
Set<String> citiesSet = sharedPreferences.getStringSet("cities", new HashSet<>(Arrays.asList("bucharest", "zurich", "london")));
citiesList = new ArrayList<>(citiesSet);
}
@Override
protected void onStop() {
super.onStop();
SharedPreferences sharedPreferences = getSharedPreferences("cities", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet("cities", new HashSet<>(citiesList));
editor.commit();
}
}
| 37.064 | 136 | 0.648608 |
0fec77a64bff5744e6ea16ac01e146d0e2941953 | 188 | public class PetError extends Exception {
public PetError() {
super("Pet error!");
}
public PetError(String message) {
super("Pet Error: " + message);
}
}
| 18.8 | 41 | 0.579787 |
4738d85dd76be7048e90a472a87760ac66ec8fa9 | 557 | package io.github.talelin.latticy.mapper;
import io.github.talelin.latticy.model.PositionDO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import io.github.talelin.latticy.model.result.PositionResultDO;
import java.util.List;
/**
* <p>
* Mapper 接口
* </p>
*
* @author 陈灿杰
* @since 2021-04-02
*/
public interface PositionMapper extends BaseMapper<PositionDO> {
PositionResultDO getById(Integer id);
boolean updateState(Integer id, Integer state);
boolean updateHits(Integer id);
List<PositionResultDO> sortByHits();
}
| 20.62963 | 64 | 0.743268 |
bd508af0ebcc96b4b5e73f5661d3207fbb05d287 | 636 | package cn.hankli.stockapp.zuulserver.filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.netflix.zuul.ZuulFilter;
@Component
public class PostFilter extends ZuulFilter {
private static Logger log = LoggerFactory.getLogger(PostFilter.class);
@Override
public String filterType() {
return "post";
}
@Override
public int filterOrder() {
return 1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
log.error("In post filter!!");
return null;
}
}
| 16.307692 | 72 | 0.685535 |
ca1e0ff6f653d14f9d6dde1c9e6d9591accc35ac | 113 | package org.openrepose.commons.utils.transform;
public interface Transform<S, T> {
T transform(S source);
}
| 16.142857 | 47 | 0.743363 |
32f09a6662e470611aae2ba1073b7f3d8bb81b06 | 1,030 | package comparison;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class Find {
static List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
interface Function1<A,B> {
B apply(A a);
}
public static abstract class Option<A> {
public Boolean isDefined() { return this instanceof Some; }
}
public static class None<A> extends Option<A> {}
public static None<Integer> NoneInt = new None<Integer>();
public static class Some<A> extends Option<A> {
public A v;
public Some(A v) { this.v = v; }
}
public static Option<Integer> find(Function1<Integer, Boolean> p) {
for (Integer i : list) {
if (p.apply(i)) return new Some<Integer>(i);
}
return NoneInt;
}
//205 chars
public static Option<Integer> fetch3() {
return find(new Function1<Integer, Boolean>() {
public Boolean apply(Integer i) {
return i == 3;
}
});
}
} | 25.75 | 71 | 0.581553 |
d6d925a19b76c3933b60733cd97e07cbb8d4cc79 | 1,069 | package cn.coderme.cblog.controller.bing;
import cn.coderme.cblog.base.PageBean;
import cn.coderme.cblog.entity.bing.BingImageArchive;
import cn.coderme.cblog.service.bing.BingImageArchiveService;
import cn.coderme.cblog.utils.BingUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created By Administrator
* Date:2018/5/11
* Time:16:01
*/
@Controller
@RequestMapping("/api/bing")
public class BingRestService {
@Autowired
private BingImageArchiveService bingImageArchiveService;
@Autowired
private BingUtils bingUtils;
@RequestMapping(value = "/today", method = RequestMethod.GET)
@ResponseBody
public BingImageArchive today() {
BingImageArchive image = bingImageArchiveService.findTodayCnImage();
bingUtils.dealImage(image);
return image;
}
} | 31.441176 | 76 | 0.781104 |
fcf91c24eafb56d7efffac37bdc7222cfe80feac | 3,175 | /*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.token;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AccessToken;
import org.springframework.util.Assert;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* A {@link SecurityTokenRepository} that associates an {@link AccessToken}
* to a {@link ClientRegistration Client} and stores it <i>in-memory</i>.
*
* @author Joe Grandja
* @since 5.0
* @see SecurityTokenRepository
* @see AccessToken
* @see ClientRegistration
*/
public final class InMemoryAccessTokenRepository implements SecurityTokenRepository<AccessToken> {
private final Map<String, AccessToken> accessTokens = new ConcurrentHashMap<>();
@Override
public AccessToken loadSecurityToken(ClientRegistration registration) {
Assert.notNull(registration, "registration cannot be null");
return this.accessTokens.get(this.getClientIdentifier(registration));
}
@Override
public void saveSecurityToken(AccessToken accessToken, ClientRegistration registration) {
Assert.notNull(accessToken, "accessToken cannot be null");
Assert.notNull(registration, "registration cannot be null");
this.accessTokens.put(this.getClientIdentifier(registration), accessToken);
}
@Override
public void removeSecurityToken(ClientRegistration registration) {
Assert.notNull(registration, "registration cannot be null");
this.accessTokens.remove(this.getClientIdentifier(registration));
}
/**
* A client is considered <i>"authorized"</i>, if it receives a successful response from the <i>Token Endpoint</i>.
*
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1.3">Section 4.1.3 Access Token Request</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-5.1">Section 5.1 Access Token Response</a>
*/
private String getClientIdentifier(ClientRegistration clientRegistration) {
StringBuilder builder = new StringBuilder();
// Access Token Request attributes
builder.append("[").append(clientRegistration.getAuthorizationGrantType().getValue()).append("]");
builder.append("[").append(clientRegistration.getRedirectUri()).append("]");
builder.append("[").append(clientRegistration.getClientId()).append("]");
// Access Token Response attributes
builder.append("[").append(clientRegistration.getScopes().toString()).append("]");
return Base64.getEncoder().encodeToString(builder.toString().getBytes());
}
}
| 40.189873 | 126 | 0.765354 |
79cd01fec69982e56556a7d56b10cfd056ee2be6 | 229 | package com.brctl.common.refactoring.chapter09.section07.after;
/**
* @author duanxiaoxing
* @created 2017/10/8
*/
public class House extends Site {
public House() {
super.setCustomer(Customer.create());
}
}
| 17.615385 | 63 | 0.676856 |
f8b8b9d631090faf89c0804f5e878ad1bffec7e4 | 624 | package com.designpattern.behavioral.memento;
public class Originator {
private String state;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
/**
* backup to memento
* @return
*/
public Memento createMemento() {
return new Memento(this.state);
}
/**
* restore from an existing memento
* @param _memento
*/
public void restoreFromMemento(Memento _memento) {
if(_memento==null) {
System.out.println("memento not found, return null;");
} else {
this.setState(_memento.getState());
}
}
}
| 17.333333 | 58 | 0.634615 |
e61022d290d2413d71a246a2b03ee0266265e56b | 5,334 | package juniebyte.javadungeons.blocks.entity;
import net.minecraft.block.BarrelBlock;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BlockEntityType;
import net.minecraft.block.entity.LootableContainerBlockEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.Inventories;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.screen.GenericContainerScreenHandler;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvent;
import net.minecraft.sound.SoundEvents;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.collection.DefaultedList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3i;
import java.util.Iterator;
import java.util.stream.IntStream;
public class DungeonsSackBlockEntity extends LootableContainerBlockEntity {
private static int[] AVAILABLE_SLOTS;
private DefaultedList<ItemStack> inventory;
private int viewerCount;
private int size;
public DungeonsSackBlockEntity(BlockPos pos, BlockState state) {
super(BlockEntityType.SHULKER_BOX, pos, state);
this.inventory = DefaultedList.ofSize(18, ItemStack.EMPTY);
AVAILABLE_SLOTS = IntStream.range(0, 18).toArray();
}
public DungeonsSackBlockEntity(BlockPos pos, BlockState state, int size) {
super(BlockEntityType.SHULKER_BOX, pos, state);
this.size = size;
this.inventory = DefaultedList.ofSize(size, ItemStack.EMPTY);
AVAILABLE_SLOTS = IntStream.range(0, 27).toArray();
}
public NbtCompound writeNbt(NbtCompound compoundTag_1) {
super.writeNbt(compoundTag_1);
if (!this.serializeLootTable(compoundTag_1)) {
Inventories.writeNbt(compoundTag_1, this.inventory);
}
return compoundTag_1;
}
public void readNbt(NbtCompound compoundTag_1) {
super.readNbt(compoundTag_1);
this.inventory = DefaultedList.ofSize(this.size(), ItemStack.EMPTY);
if (!this.deserializeLootTable(compoundTag_1)) {
Inventories.readNbt(compoundTag_1, this.inventory);
}
}
public int size() {
return 27;
}
public boolean isEmpty() {
Iterator<ItemStack> var1 = this.inventory.iterator();
ItemStack itemStack_1;
do {
if (!var1.hasNext()) {
return true;
}
itemStack_1 = var1.next();
} while (itemStack_1.isEmpty());
return false;
}
public ItemStack getStack(int int_1) {
return this.inventory.get(int_1);
}
public ItemStack removeStack(int int_1, int int_2) {
return Inventories.splitStack(this.inventory, int_1, int_2);
}
public ItemStack removeStack(int int_1) {
return Inventories.removeStack(this.inventory, int_1);
}
public void setStack(int int_1, ItemStack itemStack_1) {
this.inventory.set(int_1, itemStack_1);
if (itemStack_1.getCount() > this.getMaxCountPerStack()) {
itemStack_1.setCount(this.getMaxCountPerStack());
}
}
public void clear() {
this.inventory.clear();
}
protected DefaultedList<ItemStack> getInvStackList() {
return this.inventory;
}
protected void setInvStackList(DefaultedList<ItemStack> defaultedList_1) {
this.inventory = defaultedList_1;
}
protected Text getContainerName() {
return new TranslatableText("container.sack");
}
@Override
protected ScreenHandler createScreenHandler(int syncId, PlayerInventory playerInventory) {
return switch (size) {
case 1 -> GenericContainerScreenHandler.createGeneric9x1(syncId, playerInventory);
case 2 -> GenericContainerScreenHandler.createGeneric9x2(syncId, playerInventory);
default -> throw new IllegalStateException("Unexpected value: " + size);
};
}
public void onOpen(PlayerEntity playerEntity_1) {
if (!playerEntity_1.isSpectator()) {
if (this.viewerCount < 0) {
this.viewerCount = 0;
}
++this.viewerCount;
BlockState blockState_1 = this.getCachedState();
this.playSound(blockState_1, SoundEvents.BLOCK_BARREL_OPEN);
this.scheduleUpdate();
}
}
private void scheduleUpdate() {
this.world.getBlockTickScheduler().schedule(this.getPos(), this.getCachedState().getBlock(), 5);
}
public void onClose(PlayerEntity playerEntity_1) {
if (!playerEntity_1.isSpectator()) {
--this.viewerCount;
BlockState blockState_1 = this.getCachedState();
this.playSound(blockState_1, SoundEvents.BLOCK_BARREL_CLOSE);
}
}
private void playSound(BlockState blockState_1, SoundEvent event) {
Vec3i vec3i_1 = blockState_1.get(BarrelBlock.FACING).getVector();
double double_1 = (double) this.pos.getX() + 0.5D + (double) vec3i_1.getX() / 2.0D;
double double_2 = (double) this.pos.getY() + 0.5D + (double) vec3i_1.getY() / 2.0D;
double double_3 = (double) this.pos.getZ() + 0.5D + (double) vec3i_1.getZ() / 2.0D;
this.world.playSound(null, double_1, double_2, double_3, event, SoundCategory.BLOCKS, 0.5F, this.world.random.nextFloat() * 0.1F + 0.9F);
}
} | 32.925926 | 143 | 0.706037 |
fd44fd3d67082760550f7f265d1d66bf3721de17 | 4,896 | package com.mrmq.poker.client.impl;
import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mrmq.poker.client.AbstractClientHandler;
import com.mrmq.poker.client.manager.PokerClientManager;
import com.mrmq.poker.common.proto.AdminServiceProto.LoginResponse;
import com.mrmq.poker.common.proto.AdminServiceProto.UpdateUserResponse;
import com.mrmq.poker.common.proto.PokerModelProto.ActionType;
import com.mrmq.poker.common.proto.PokerModelProto.Table;
import com.mrmq.poker.common.proto.PokerServiceProto.EndGameEvent;
import com.mrmq.poker.common.proto.PokerServiceProto.JoinTableResponse;
import com.mrmq.poker.common.proto.PokerServiceProto.NewRoundEvent;
import com.mrmq.poker.common.proto.PokerServiceProto.PlayerActionEvent;
import com.mrmq.poker.common.proto.PokerServiceProto.StartGameEvent;
import com.mrmq.poker.common.proto.PokerServiceProto.TableResponse;
import com.mrmq.poker.common.proto.Rpc.RpcMessage;
import com.mrmq.poker.common.proto.Rpc.RpcMessage.Result;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
public class PokerClientHandler extends AbstractClientHandler {
private static Logger log = LoggerFactory.getLogger(PokerClientHandler.class);
private int position;
private long lastBet = 0;
private Table table;
public PokerClientHandler(WebSocketClientHandshaker handshaker) {
super(handshaker);
}
protected void handleRpcMessage(ChannelHandlerContext ctx, RpcMessage msg) throws Exception {
log.info("Received RpcMessage, id: {}, payload: {}", msg.getId(), msg.getPayloadClass());
Thread.sleep(1000);
if(LoginResponse.getDescriptor().getName().equals(msg.getPayloadClass())) {
//Login
if(msg.getResult() == Result.SUCCESS) {
RpcMessage tableRequest = PokerClientManager.createTableRequest();
request(ctx, tableRequest);
}
}
if(TableResponse.getDescriptor().getName().equals(msg.getPayloadClass())) {
TableResponse response = TableResponse.parseFrom(msg.getPayloadData());
log.info("TableResponse: " + response);
if(response.getTablesCount() > 0) {
Iterator<Table> iter = response.getTablesList().iterator();
Table tempTable = null;
if(table == null) {
table = iter.next();
} else
while(iter.hasNext()) {
tempTable = iter.next();
if(tempTable.getTableId().equals(table.getTableId())) {
table = tempTable;
break;
}
}
if(tempTable == null || table == tempTable) {
log.info("Join to table: {}", table);
RpcMessage joinTableRequest = PokerClientManager.createJoinTableRequest(table, position);
request(ctx, joinTableRequest);
} else
log.warn("Not found table to join, Table: {}", table);
}
}
if(JoinTableResponse.getDescriptor().getName().equals(msg.getPayloadClass())) {
JoinTableResponse response = JoinTableResponse.parseFrom(msg.getPayloadData());
log.info("JoinTableResponse: {}", response);
}
if(StartGameEvent.getDescriptor().getName().equals(msg.getPayloadClass())) {
StartGameEvent gameEvent = StartGameEvent.parseFrom(msg.getPayloadData());
log.info("StartGameEvent: {}", gameEvent);
lastBet = table.getTableRule().getBigBlind();
}
if(NewRoundEvent.getDescriptor().getName().equals(msg.getPayloadClass())) {
NewRoundEvent gameEvent = NewRoundEvent.parseFrom(msg.getPayloadData());
log.info("NewRoundEvent: {}", gameEvent);
if(gameEvent.getFirstPlayerId().equals(loginId)) {
Thread.sleep(5000);
RpcMessage actionRequest = PokerClientManager.createActionRequest(table, loginId, ActionType.RAISE, lastBet);
request(ctx, actionRequest);
}
}
if(EndGameEvent.getDescriptor().getName().equals(msg.getPayloadClass())) {
EndGameEvent gameEvent = EndGameEvent.parseFrom(msg.getPayloadData());
log.info("EndGameEvent: {}", gameEvent);
}
if(PlayerActionEvent.getDescriptor().getName().equals(msg.getPayloadClass())) {
PlayerActionEvent gameEvent = PlayerActionEvent.parseFrom(msg.getPayloadData());
log.info("PlayerActionEvent: {}", gameEvent);
lastBet = gameEvent.getRaiseAmount();
if(gameEvent.getNextPlayerId().equals(loginId)) {
Thread.sleep(5000);
RpcMessage actionRequest = PokerClientManager.createActionRequest(table, loginId, ActionType.CALL, lastBet);
request(ctx, actionRequest);
}
}
if(UpdateUserResponse.getDescriptor().getName().equals(msg.getPayloadClass())) {
UpdateUserResponse response = UpdateUserResponse.parseFrom(msg.getPayloadData());
log.info("UpdateUserResponse: {}", response);
}
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public Table getTable() {
return table;
}
public void setTable(Table table) {
this.table = table;
}
} | 34.723404 | 113 | 0.738562 |
d658af19e655e7f4dcf3fb263f87fbdf6fe08484 | 117 | package com.infamous.framework.http.core;
public abstract class RawHttpResponseBase implements RawHttpResponse {
}
| 19.5 | 70 | 0.837607 |
aaf15b38fec6da4ead372e85aca309f95b0048eb | 136 | package br.com.sinqia.resource.dto;
import lombok.Data;
@Data
public class ParticipanteLoginDTO {
String cpf;
String senha;
}
| 13.6 | 35 | 0.735294 |
8bff789d4f5975aedb873b6c5a0385fcc410c6e8 | 942 | package org.CarRental.config;
import org.CarRental.model.AppUser;
import org.CarRental.model.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import javax.sql.DataSource;
/**
* Created by intelcan on 14.05.17.
*/
@Configuration
public class GeneralConfig {
@Autowired
private DataSource dataSource;
@Bean(name = "sessionFactory")
public LocalSessionFactoryBean hibernate5SessionFactoryBean(){
LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
localSessionFactoryBean.setDataSource(dataSource);
localSessionFactoryBean.setAnnotatedClasses(
Customer.class,
AppUser.class
);
return localSessionFactoryBean;
}
}
| 29.4375 | 88 | 0.759023 |
4542be37f32bf25cd969b06d7f3cdcd7d6eab8e0 | 501 | package pinacolada.powers.temporary;
import com.megacrit.cardcrawl.core.AbstractCreature;
import com.megacrit.cardcrawl.powers.ArtifactPower;
import pinacolada.powers.common.AbstractTemporaryPower;
public class TemporaryArtifactPower extends AbstractTemporaryPower
{
public static final String POWER_ID = CreateFullID(TemporaryArtifactPower.class);
public TemporaryArtifactPower(AbstractCreature owner, int amount)
{
super(owner, amount, POWER_ID, ArtifactPower::new);
}
}
| 29.470588 | 85 | 0.804391 |
a6f9c58ecf3425c5ba6c0331a3152bbf1d043c87 | 2,281 | /*
reference: https://www.jianshu.com/p/52b0805f1950
*/
package com.util;
import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class RedisCacheUtils implements Cache {
private static Logger logger = LoggerFactory.getLogger(RedisCacheUtils.class);
private String cacheId;
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
public RedisCacheUtils(String cacheId) {
if (cacheId == null) {
throw new IllegalArgumentException("Cache instances require an ID");
}
this.cacheId = ConfigUtils.key + "." + cacheId;
logger.info("NTSRedisCache cacheId ========== " + cacheId);
if(ConfigUtils.redisSwitch){
JedisUtils.getInstance();
}
}
@Override
public String getId() {
return cacheId;
}
@Override
public void putObject(Object key, Object value) {
logger.info("NTSRedisCache putObject = " + cacheId);
if(ConfigUtils.redisSwitch){
JedisUtils.put(cacheId, key, value);
}
}
@Override
public Object getObject(Object key) {
logger.info("NTSRedisCache getObject = " + cacheId);
if(ConfigUtils.redisSwitch){
return JedisUtils.get(cacheId, key);
}else{
return null;
}
}
@Override
public Object removeObject(Object key) {
logger.info("NTSRedisCache removeObject = " + cacheId);
if(ConfigUtils.redisSwitch){
return JedisUtils.remove(cacheId, key);
}else{
return null;
}
}
@Override
public void clear() {
logger.info("NTSRedisCache clear = " + cacheId);
if(ConfigUtils.redisSwitch){
JedisUtils.removeAll(cacheId);
}
}
@Override
public int getSize() {
logger.info("NTSRedisCache getSize = " + cacheId);
if(ConfigUtils.redisSwitch){
return JedisUtils.getSize(cacheId);
}else{
return -1;
}
}
@Override
public ReadWriteLock getReadWriteLock() {
return readWriteLock;
}
}
| 24.010526 | 82 | 0.616835 |
ce437c9cc0d484c8c640d92e6f9320a469917c69 | 1,270 | package net.lecousin.reactive.data.relational.test;
import org.junit.jupiter.engine.config.CachingJupiterConfiguration;
import org.junit.jupiter.engine.config.DefaultJupiterConfiguration;
import org.junit.jupiter.engine.config.JupiterConfiguration;
import org.junit.jupiter.engine.descriptor.JupiterEngineDescriptor;
import org.junit.platform.engine.EngineDiscoveryRequest;
import org.junit.platform.engine.ExecutionRequest;
import org.junit.platform.engine.TestDescriptor;
import org.junit.platform.engine.TestEngine;
import org.junit.platform.engine.UniqueId;
import net.lecousin.reactive.data.relational.LcReactiveDataRelationalInitializer;
public class LcReactiveDataRelationalTestEngine implements TestEngine {
@Override
public String getId() {
return "net.lecousin.reactive.data.relational.engine";
}
@Override
public TestDescriptor discover(EngineDiscoveryRequest discoveryRequest, UniqueId uniqueId) {
LcReactiveDataRelationalInitializer.init();
JupiterConfiguration configuration = new CachingJupiterConfiguration(new DefaultJupiterConfiguration(discoveryRequest.getConfigurationParameters()));
return new JupiterEngineDescriptor(uniqueId, configuration);
}
@Override
public void execute(ExecutionRequest request) {
// do nothing
}
}
| 35.277778 | 151 | 0.84252 |
f68d43520022c8e6b0cc4cdbb18e8fa37d838e8a | 2,966 | package com.cym.model;
import com.cym.sqlhelper.bean.BaseModel;
import com.cym.sqlhelper.config.InitValue;
import com.cym.sqlhelper.config.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
*
* 代理目标location
*
*/
@Table
public class Location extends BaseModel {
/**
* 所属反向代理serverId
* @required
*/
String serverId;
/**
* 监控路径 例:/
* @required
*/
String path;
/**
* 代理类型 0:动态代理(默认) 1:静态代理 2:负载均衡 3:空白代理
*/
@InitValue("0")
Integer type;
@JsonIgnore
String locationParamJson;
/**
* 动态代理目标 (例:http://10.10.10.1:8080/)
*/
String value;
/**
* 代理负载协议,http or https
*/
@InitValue("http")
String upstreamType;
/**
* 代理负载均衡upstream的id
*/
String upstreamId;
/**
* 代理负载额外路径,默认为空
*/
String upstreamPath;
/**
* 静态代理路径 (例:/home/www)
*/
String rootPath;
/**
* 静态代理默认页面 (例:index.html)
*/
String rootPage;
/**
* 静态代理类型 root:根路径模式 alias:别名模式
*/
String rootType;
/**
* 是否携带Host参数 0否 1是(默认)
*/
@InitValue("1")
Integer header;
/**
* 是否开启websocket支持 0否(默认) 1是
*/
@InitValue("0")
Integer websocket;
/**
* 描述
*/
String descr;
public String getDescr() {
return descr;
}
public void setDescr(String descr) {
this.descr = descr;
}
public String getUpstreamType() {
return upstreamType;
}
public void setUpstreamType(String upstreamType) {
this.upstreamType = upstreamType;
}
public Integer getWebsocket() {
return websocket;
}
public void setWebsocket(Integer websocket) {
this.websocket = websocket;
}
public Integer getHeader() {
return header;
}
public void setHeader(Integer header) {
this.header = header;
}
public String getRootType() {
return rootType;
}
public void setRootType(String rootType) {
this.rootType = rootType;
}
public String getRootPath() {
return rootPath;
}
public void setRootPath(String rootPath) {
this.rootPath = rootPath;
}
public String getRootPage() {
return rootPage;
}
public void setRootPage(String rootPage) {
this.rootPage = rootPage;
}
public String getUpstreamPath() {
return upstreamPath;
}
public void setUpstreamPath(String upstreamPath) {
this.upstreamPath = upstreamPath;
}
public String getLocationParamJson() {
return locationParamJson;
}
public void setLocationParamJson(String locationParamJson) {
this.locationParamJson = locationParamJson;
}
public String getUpstreamId() {
return upstreamId;
}
public void setUpstreamId(String upstreamId) {
this.upstreamId = upstreamId;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getServerId() {
return serverId;
}
public void setServerId(String serverId) {
this.serverId = serverId;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| 15.528796 | 61 | 0.679366 |
5993c26b471dc7166e5a22bb73d8687344d4d6ea | 689 | package com.github.humbergroup.soccer.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
public class League implements Serializable {
@Id
@SequenceGenerator(name = "team_sequence", sequenceName = "team_sequence")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "team_sequence")
private Long id;
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "league", fetch = FetchType.EAGER)
private List<Team> teams;
}
| 21.53125 | 84 | 0.754717 |
d3ea5ece65c61b0c47a2c0278af440ffd8403138 | 25,392 | package com.vinh.doctor_x.Fragment;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.vinh.doctor_x.Main_Screen_Acitivity;
import com.vinh.doctor_x.R;
import com.vinh.doctor_x.SignUp_Activity;
import com.vinh.doctor_x.Testmap;
import com.vinh.doctor_x.User.Doctor_class;
import com.vinh.doctor_x.User.Location_cr;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import static android.app.Activity.RESULT_OK;
/**
* Created by nntd290897 on 3/12/18.
*/
public class Frg_fillinfro_doctor extends Fragment implements OnMapReadyCallback {
private static final int CAM_REQUEST = 1313;
private Dialog dialog;
private View view;
private FragmentManager fragmentManager ;
private FragmentTransaction fragmentTransaction ;
private ProgressDialog message;
FirebaseDatabase database;
DatabaseReference reference;
Bitmap thumbnail;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseauthlistener;
EditText _nameText;
EditText _addressText;
EditText _emailText;
EditText _mobileText;
EditText _doctorcode;
EditText _DOB;
EditText _workingat;
EditText _workinghour;
RadioButton rdb_man ;
RadioButton rdb_women ;
RadioGroup rdg_chooseType ;
String gender;
String specialist;
FragmentTransaction ft ;
private Fragment frg_fill_map;
Button _signupButton;
private static final String TAG = "my_log";
ImageButton img_ava_patient;
String [] values =
{
"Select an item...",
"1. Anaesthesiologist",
"2. Andrologist",
"3. Cardiologist",
"4. Cardiac Electrophysiologist",
"5. Dermatologist",
"6. Emergency Medicine / Emergency (ER) Doctors",
"7. Endocrinologist",
"8. Epidemiologist",
"9. Family Medicine Physician",
"10. Gastroenterologist",
"11. Geriatrician",
"12. Hyperbaric Physician",
"13. Hematologist",
"14. Hepatologist",
"15. Immunologist",
"16. Infectious Disease Specialist",
"17. Intensivist",
"18. Internal Medicine Specialist",
"19. Maxillofacial Surgeon / Oral Surgeon",
"20. Medical Geneticist",
"21. Neonatologist",
"22. Nephrologist",
"23. Neurologist",
"24. Neurosurgeon",
"25. Nuclear Medicine Specialist",
"26. Obstetrician/Gynecologist (OB/GYN)",
"27. Occupational Medicine Specialist",
"28. Oncologist",
"29. Ophthalmologist",
"30. Orthopedic Surgeon / Orthopedist",
"31. Otolaryngologist (also ENT Specialist)",
"32. Parasitologist",
"33. Pathologist",
"34. Perinatologist",
"35. Periodontist",
"36. Pediatrician",
"37. Physiatrist",
"38. Plastic Surgeon",
"39. Psychiatrist",
"40. Pulmonologist",
"41. Radiologist",
"42. Rheumatologist",
"43. Sleep Doctor / Sleep Disorders Specialist",
"44. Spinal Cord Injury Specialist",
"45. Sports Medicine Specialist",
"46. Surgeon",
"47. Thoracic Surgeon",
"48. Urologist",
"49. Vascular Surgeon",
"51. Allergist",
};
Spinner spn_specialist ;
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
FusedLocationProviderClient mFusedLocationClient;
LinearLayout lnl_fillinfor_doctor, lnl_getposition_doctor;
private Double getLog,getLat;
private String nameAddress;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.frg_fillinfor_doctor,container,false);
database = FirebaseDatabase.getInstance();
reference = database.getReference();
mAuth = FirebaseAuth.getInstance();
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
mapFrag = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
lnl_fillinfor_doctor = (LinearLayout)view.findViewById(R.id.lnl_fill_infor_doctor);
lnl_getposition_doctor = (LinearLayout)view.findViewById(R.id.lnl_getpositon_doctor);
spn_specialist = (Spinner)view.findViewById(R.id.spn_specialist);
_signupButton = (Button) view.findViewById(R.id.btn_signup);
_nameText = (EditText) view.findViewById(R.id.input_name);
_addressText= (EditText) view.findViewById(R.id.input_address);
_emailText= (EditText) view.findViewById(R.id.input_email);
_mobileText= (EditText) view.findViewById(R.id.input_mobile);
_doctorcode= (EditText) view.findViewById(R.id.txt_doctorCode);
_DOB= (EditText) view.findViewById(R.id.input_DOB);
_workingat= (EditText) view.findViewById(R.id.txt_workat);
_workinghour= (EditText) view.findViewById(R.id.txt_WorkingHour);
rdg_chooseType = (RadioGroup)view.findViewById(R.id.rdg_Gender);
rdb_man = (RadioButton)view.findViewById(R.id.rdb_man);
rdb_women = (RadioButton)view.findViewById(R.id.rdb_woman);
_addressText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
lnl_fillinfor_doctor.setVisibility(View.GONE);
lnl_getposition_doctor.setVisibility(View.VISIBLE);
}
});
rdg_chooseType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
if(rdb_man.isChecked())
{
gender = "man";
}
else if(rdb_women.isChecked())
{
gender = "woman";
}
}
});
final List<String> speciallist = new ArrayList<>(Arrays.asList(values));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this.getActivity(),R.layout.spinner_item,speciallist){
@Override
public boolean isEnabled(int position){
if(position == 0)
{
// Disable the first item from Spinner
// First item will be use for hint
return false;
}
else
{
return true;
}
}
@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
tv.setTextColor(Color.WHITE);
return view;
}
};
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spn_specialist.setAdapter(adapter);
dialog = new Dialog(view.getContext());
dialog.setContentView(R.layout.dialog_getavatar);
dialog.setTitle("Choose Avatar Image");
Button btn_chooseImg = (Button) dialog.findViewById(R.id.btn_choosenGallery);
Button btn_takeaphoto = (Button) dialog.findViewById(R.id.btn_choosenTakephoto);
btn_chooseImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
chooseFromGallery();
}
});
btn_takeaphoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
profilepictureOnClick();
}
});
img_ava_patient = (ImageButton) view.findViewById(R.id.img_ava_patient);
img_ava_patient.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.show();
}
});
_signupButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String key = mAuth.getCurrentUser().getUid();
Doctor_class drv = new Doctor_class();
drv.setAvatar(convertToBase64(thumbnail));
drv.setName(_nameText.getText().toString());
drv.setType("waiting");
drv.setAddress(_addressText.getText().toString());
drv.setCode(_doctorcode.getText().toString());
drv.setDOB(_DOB.getText().toString());
drv.setPhone(_mobileText.getText().toString());
drv.setSpecialist(spn_specialist.getSelectedItem().toString());
drv.setWorkat(_workingat.getText().toString());
drv.setWorkinghour(_workinghour.getText().toString());
drv.setGender(gender);
drv.setLat(getLat);
drv.setLog(getLog);
drv.setRating(0.0);
reference.child("doctor").child(key).setValue(drv);
//reference.child("loglat_current").child(key).setValue(location_cr);
((SignUp_Activity)getActivity()).location_cr.setName(_nameText.getText().toString());
((SignUp_Activity)getActivity()).location_cr.setMobile(_mobileText.getText().toString());
((SignUp_Activity)getActivity()).location_cr.setKey_user(key);
((SignUp_Activity)getActivity()).location_cr.setLog(getLog);
((SignUp_Activity)getActivity()).location_cr.setLat(getLat);
((SignUp_Activity)getActivity()).location_cr.setAddress(_addressText.getText().toString());
reference.child("loglat_current").child(key).setValue( ((SignUp_Activity)getActivity()).location_cr);
Intent intent = new Intent(getActivity(),Main_Screen_Acitivity.class);
Bundle bundle = new Bundle();
bundle.putInt("type",2);
intent.putExtra("gettype",bundle);
startActivity(intent);
}
});
return view;
}
public void chooseFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}
private void takeNewProfilePicture(){
Fragment profileFrag = this;
Intent cameraintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
profileFrag.startActivityForResult(cameraintent, CAM_REQUEST);
}
public void profilepictureOnClick(){
takeNewProfilePicture();
}
private String convertToBase64(Bitmap bm)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] byteArrayImage = baos.toByteArray();
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
return encodedImage;
}
public void showHideFragment(final Fragment fragment){
FragmentTransaction fragTransaction = getFragmentManager().beginTransaction();
fragTransaction.setCustomAnimations(android.R.animator.fade_in,
android.R.animator.fade_out);
if (fragment.isHidden()) {
fragTransaction.show(fragment);
Log.d("hidden","Show");
} else {
fragTransaction.hide(fragment);
Log.d("Shown","Hide");
}
fragTransaction.commit();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == CAM_REQUEST) {
if(requestCode == CAM_REQUEST){
thumbnail = (Bitmap) data.getExtras().get("data");
img_ava_patient.setImageBitmap(thumbnail);
dialog.dismiss();
}
}
else if (resultCode == RESULT_OK){
Uri targetUri = data.getData();
// textTargetUri.setText(targetUri.toString());
try {
Context applicationContext = SignUp_Activity.getContextOfApplication();
thumbnail = BitmapFactory.decodeStream( applicationContext.getContentResolver().openInputStream(targetUri));
img_ava_patient.setImageBitmap(thumbnail);
dialog.dismiss();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public Bitmap loadSampleResource(int imageId, int targetHeight, int targetwidth) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), imageId, options);
final int originalHeight = options.outHeight;
final int originalWidth = options.outWidth;
int inSamplesize = 1;
while ((originalHeight / (inSamplesize * 2)) > targetHeight && (originalWidth / (inSamplesize * 2)) > targetwidth) {
inSamplesize *= 2;
}
options.inSampleSize = inSamplesize;
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(getResources(), imageId, options);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(120000); // two minute interval
mLocationRequest.setFastestInterval(120000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}
mGoogleMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(LatLng latLng) {
if(mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
Toast.makeText(getContext(),latLng.toString(),Toast.LENGTH_SHORT).show();
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.patient_marker);
MarkerOptions markerOption = new MarkerOptions();
markerOption.position(latLng).icon(icon);
mCurrLocationMarker = googleMap.addMarker(markerOption);
createAndShowAlertDialog("locationcurrent",latLng.latitude,latLng.longitude);
lnl_getposition_doctor.setVisibility(View.GONE);
lnl_fillinfor_doctor.setVisibility(View.VISIBLE);
//txt_getlocationcurrent.setText(getLocationName(latLng.latitude,latLng.longitude));
//(Main_Screen_Acitivity)getActivity()).location_cr.setLat(latLng.latitude);
//((Main_Screen_Acitivity)getActivity()).location_cr.setLog(latLng.longitude);
//((Main_Screen_Acitivity)getActivity()).location_cr.setAddress(getLocationName(latLng.latitude,latLng.longitude));
}
});
}
private void createAndShowAlertDialog(String type,double lathere,double loghere) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Do you wnat get here is your's address");
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if(type == "locationcurrent")
{
getLat = lathere;
getLog = loghere;
_addressText.setText(getLocationName(lathere,loghere));
}
dialog.dismiss();
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if(type == "locationcurrent")
{
lnl_fillinfor_doctor.setVisibility(View.GONE);
lnl_getposition_doctor.setVisibility(View.VISIBLE);
}
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
public String getLocationName(double lattitude, double longitude) {
String cityName = "Not Found";
Geocoder gcd = new Geocoder(getActivity(), Locale.getDefault());
try {
List<Address> addresses = gcd.getFromLocation(lattitude, longitude,
10);
cityName = addresses.get(0).getAddressLine(0);
Log.d("ADD",cityName);
if(cityName == null)
{
cityName = "Not Found";
}
// addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName();
} catch (IOException e) {
e.printStackTrace();
}
return cityName;
}
LocationCallback mLocationCallback = new LocationCallback(){
@Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
Log.i("MapsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude());
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.patient_marker);
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(icon);
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16.0f));
}
};
};
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?-
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(getActivity())
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
}
| 40.433121 | 172 | 0.614997 |
cedc80f0eb55db50c59dca03855e7199a508a331 | 1,011 | package com.taylor.reputation.framework.util;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 文件操作工具类
*
* @author huangyong
* @since 1.0.0
*/
public final class FileUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);
/**
* 获取真实文件名(自动去掉文件路径)
*/
public static String getRealFileName(String fileName) {
return FilenameUtils.getName(fileName);
}
/**
* 创建文件
*/
public static File createFile(String filePath) {
File file;
try {
file = new File(filePath);
File parentDir = file.getParentFile();
if (!parentDir.exists()) {
FileUtils.forceMkdir(parentDir);
}
} catch (Exception e) {
LOGGER.error("create file failure", e);
throw new RuntimeException(e);
}
return file;
}
}
| 22.977273 | 81 | 0.608309 |
9912aff23f6dd228ed772f4d005ae59ef64e1f11 | 797 | /*
* @(#)BaseEntityPkDto.java 1.0 Aug 28, 2015
* Copyright 2015 by GNU Lesser General Public License (LGPL). All rights reserved.
*/
package org.nlh4j.core.dto;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* The bound class of entity primary/unique key
*
* @param <T> the entity unique key type
*
* @author Hai Nguyen (hainguyenjc@gmail.com)
*
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class BaseEntityParamControllerDto<T> extends AbstractDto {
/**
* default serial version id
*/
private static final long serialVersionUID = 1L;
/** entity primary/unique key */
private T pk;
public BaseEntityParamControllerDto() {}
public BaseEntityParamControllerDto(T pk) {
this.pk = pk;
}
}
| 23.441176 | 84 | 0.66123 |
f03637ce4eeb778a4e2d092e27bcdcc65fce4b24 | 592 | package org.erp.tarak.rawMaterial;
import java.util.List;
public interface RawMaterialService {
public void addRawMaterial(RawMaterial rawMaterial);
public List<RawMaterial> listRawMaterials();
public RawMaterial getRawMaterial(long rawMaterialId);
public void deleteRawMaterial(RawMaterial rawMaterial);
public List<RawMaterial> listRawMaterialsbyCategory(long category);
public RawMaterial getLastRawMaterial();
public RawMaterial getLastRawMaterialByCategory(long categoryId);
public RawMaterial getRawMaterialByName(String rawMaterialName);
}
| 24.666667 | 69 | 0.795608 |
ebd5e0107863243d58633421d3afcc882f1dadb2 | 1,879 | /* ========================================
* System Name : 化交线上平台
* SubSystem Name :自贸区前台服务
* File Name: GenerateContractImpl.java
* ----------------------------------------
* Create Date/Change History
* ----------------------------------------
* 2018年1月11日 池永 Create
*
*
* ----------------------------------------
* Copyright (c) SCEM . All rights reserved.
*/
package com.shcem.common.fadada.baseservice.impl;
import com.alibaba.fastjson.JSON;
import com.shcem.common.fadada.FadadaBaseService;
import com.shcem.common.fadada.FadadaBaseServiceClient;
import com.shcem.common.fadada.FadadaConstants;
import com.shcem.common.fadada.model.GenerateContractReq;
import com.shcem.common.fadada.model.GenerateContractRes;
/**
* GenerateContractImpl.java
*
* @author 池永
* @version 1.0
* @description xxx
*/
public class GenerateContractImpl extends FadadaBaseServiceClient
implements FadadaBaseService<GenerateContractReq, GenerateContractRes> {
/**
* 合同生成接口
*
* @param req
* @return
*/
public GenerateContractRes request(GenerateContractReq req, String mode) throws Exception {
// 取得ClientBase
getClientBase(mode, FadadaConstants.DIFFER_BASE);
// 初期化参数(必须)
GenerateContractRes res = new GenerateContractRes();
if (this.base == null) {
// 判断连接
res.setResult(FadadaConstants.ERROR);
res.setCode(FadadaConstants.CODE_BASEERROR);
} else {
// 执行请求
String response = this.base.invokeGenerateContract(req.getTemplate_id(), req.getContract_id(),
req.getDoc_title(), req.getFont_size(), req.getFont_type(), req.getParameter_map(),
req.getDynamic_tables());
res = JSON.parseObject(response, GenerateContractRes.class);
}
return res;
}
}
| 28.907692 | 106 | 0.610431 |
02dc6de026325aeaf48b31b4e1e70dda3a238530 | 3,499 | package ch.wetwer.moviefleur;
import ch.wetwer.moviefleur.color.ColorMask;
import ch.wetwer.moviefleur.helper.ImageSplitter;
import junit.framework.TestCase;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class FleurFilterTest {
@Test
public void testAdditive() throws IOException {
BufferedImage originalImg = ImageIO.read(new File("img/frame_default.png"));
List<BufferedImage> splits = ImageSplitter.split(originalImg);
// Run the test
final BufferedImage result = FleurFilter.additive(splits.get(0), splits.get(1));
// Verify the results
TestCase.assertEquals(splits.get(0).getWidth(), result.getWidth());
}
@Test
public void testAlphaCombine() throws IOException {
BufferedImage originalImg = ImageIO.read(new File("img/frame_default.png"));
List<BufferedImage> splits = ImageSplitter.split(originalImg);
FleurFilter.alphaCombine(splits.get(0), splits.get(1));
}
@Test
public void testColor() throws IOException {
// Setup
final BufferedImage originalImg = ImageIO.read(new File("img/frame_default.png"));
// Run the test
final BufferedImage resultRed = FleurFilter.color(originalImg, ColorMask.RED);
final BufferedImage resultGreen = FleurFilter.color(originalImg, ColorMask.GREEN);
final BufferedImage resultBlue = FleurFilter.color(originalImg, ColorMask.BLUE);
final BufferedImage resultYellow = FleurFilter.color(originalImg, ColorMask.YELLOW);
final BufferedImage resultCyan = FleurFilter.color(originalImg, ColorMask.CYAN);
final BufferedImage resultMagenta = FleurFilter.color(originalImg, ColorMask.MAGENTA);
// Verify the results
assertEquals(-16056320, resultRed.getRGB(1, 1));
assertEquals(-16774912, resultGreen.getRGB(1, 1));
assertEquals(-16777211, resultBlue.getRGB(1, 1));
assertEquals(-16054016, resultYellow.getRGB(1, 1));
assertEquals(-16774907, resultCyan.getRGB(1, 1));
assertEquals(-16056315, resultMagenta.getRGB(1, 1));
}
@Test
public void testGray() throws IOException {
// Setup
final BufferedImage originalImg = ImageIO.read(new File("img/frame_default.png"));
// Run the test
final BufferedImage result = FleurFilter.gray(originalImg);
// Verify the results
assertNotEquals(originalImg.getRGB(1, 1), result.getRGB(1, 1));
}
@Test
public void testInvert() throws IOException {
// Setup
final BufferedImage image = ImageIO.read(new File("img/frame_default.png"));
// Run the test
final BufferedImage result = FleurFilter.invert(image);
// Verify the results
assertEquals(-723206, result.getRGB(1, 1));
}
@Test
public void testTransparent() throws IOException {
// Setup
final BufferedImage bufferedImg = ImageIO.read(new File("img/frame_default.png"));
final double alpha = 0.5d;
// Run the test
final BufferedImage result = FleurFilter.transparent(bufferedImg, alpha);
// Verify the results
Color c = new Color(result.getRGB(1, 1), true);
assertEquals(128, c.getAlpha());
}
}
| 33.970874 | 94 | 0.684481 |
2243d1821b58d43f92068dea39b507d21b314f7f | 28,618 | package org.inaturalist.android;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatRadioButton;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.evernote.android.state.State;
import com.livefront.bridge.Bridge;
import org.apache.commons.collections4.CollectionUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.tinylog.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MessagesThreadActivity extends AppCompatActivity {
private static final String TAG = "MessagesThreadActivity";
public static final String MESSAGE = "message";
private static final String[] FLAG_TYPES = new String[] { "spam", "inappropriate", "other" };
private static final int[] FLAG_TITLES = new int[] { R.string.spam, R.string.offensive_inappropriate, R.string.other };
private static final int[] FLAG_DESCRIPTIONS = new int[] { R.string.commercial_solicitation, R.string.misleading_or_illegal_content, R.string.some_other_reason };
private INaturalistApp mApp;
private MessagesReceiver mMessagesReceiver;
private PostMessageReceiver mPostMessageReceiver;
private MuteUserReceiver mMuteUserReceiver;
private PostFlagReceiver mPostFlagReceiver;
@State(AndroidStateBundlers.JSONListBundler.class) public ArrayList<JSONObject> mMessages;
@State(AndroidStateBundlers.BetterJSONObjectBundler.class) public BetterJSONObject mMessage;
@State public boolean mSendingMessage;
private ProgressBar mProgress;
private RecyclerView mMessageList;
private EditText mMessageText;
private ImageView mSendMessage;
private MessageThreadAdapter mAdapter;
private ActivityHelper mHelper;
@State public String mMessageBody = "";
@State public boolean mOpenedFromUrl;
@State public boolean mMutingUser;
@State public boolean mFlaggingConversation;
@State public boolean mShowFlagDialog;
private Menu mMenu;
private AlertDialog mFlagDialog;
private int mSelectedFlagType;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bridge.restoreInstanceState(this, savedInstanceState);
mApp = (INaturalistApp)getApplication();
mApp.applyLocaleSettings(getBaseContext());
setContentView(R.layout.messages_thread);
Intent intent = getIntent();
if (savedInstanceState == null) {
Uri uri = intent.getData();
if ((uri != null) && (uri.getScheme().equals("https"))) {
// User clicked on a message link (e.g. https://www.inaturalist.org/messages/123456)
String path = uri.getPath();
Logger.tag(TAG).info("Launched from external URL: " + uri);
if (path.toLowerCase().startsWith("/messages/")) {
Pattern pattern = Pattern.compile("messages/([^ /?]+)");
Matcher matcher = pattern.matcher(path);
if (matcher.find()) {
String id = matcher.group(1);
String json = String.format("{ \"id\": %s }", id);
mMessage = new BetterJSONObject(json);
mOpenedFromUrl = true;
} else {
Logger.tag(TAG).error("Invalid URL");
finish();
return;
}
} else {
Logger.tag(TAG).error("Invalid URL");
finish();
return;
}
} else {
mMessage = new BetterJSONObject(intent.getStringExtra(MESSAGE));
}
}
if (mMessage == null) {
finish();
return;
}
ActionBar ab = getSupportActionBar();
ab.setTitle(mMessage.getString("subject"));
ab.setDisplayHomeAsUpEnabled(true);
mHelper = new ActivityHelper(this);
mProgress = findViewById(R.id.progress);
mMessageList = findViewById(R.id.message_list);
mSendMessage = findViewById(R.id.send_message);
mMessageText = findViewById(R.id.message);
mMessageText.setText(mMessageBody);
mMessageText.post(() -> mMessageText.setSelection(mMessageText.getText().length()));
mSendMessage.setOnClickListener(view -> {
if (mMessageText.getText().length() == 0) return;
// Send message on thread
// Make sure we send the message to the other user, not to ourselves
Integer toUser = getOtherUserId();
Intent serviceIntent = new Intent(INaturalistService.ACTION_POST_MESSAGE, null, this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.TO_USER, toUser);
serviceIntent.putExtra(INaturalistService.THREAD_ID, mMessage.getInt("thread_id"));
serviceIntent.putExtra(INaturalistService.SUBJECT, mMessage.getString("subject"));
serviceIntent.putExtra(INaturalistService.BODY, mMessageText.getText().toString());
ContextCompat.startForegroundService(this, serviceIntent);
mSendingMessage = true;
mHelper.loading(getString(R.string.sending_message));
});
}
private void refreshViewState(boolean refreshMessages, boolean scrollToBottom) {
if (mMessages == null) {
// Loading messages
mProgress.setVisibility(View.VISIBLE);
mMessageList.setVisibility(View.GONE);
} else if (mMessages.size() == 0) {
// No messages
mProgress.setVisibility(View.GONE);
mMessageList.setVisibility(View.GONE);
} else if (refreshMessages) {
// Show messages
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
mMessageList.setLayoutManager(layoutManager);
if (mMessageList.getItemDecorationCount() == 0) {
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this, R.drawable.divider));
mMessageList.addItemDecoration(dividerItemDecoration);
}
mAdapter = new MessageThreadAdapter(this, mMessages);
mMessageList.setAdapter(mAdapter);
if (scrollToBottom) {
// Scroll to latest message (happens when refresh latest message list after sending a new message)
mMessageList.scrollToPosition(mMessages.size() - 1);
}
mProgress.setVisibility(View.GONE);
mMessageList.setVisibility(View.VISIBLE);
}
if (mSendingMessage) {
mHelper.loading(getString(R.string.sending_message));
mMessageBody = "";
} else if (mMutingUser) {
mHelper.loading(isUserMuted() ? getString(R.string.unmuting_user) : getString(R.string.muting_user));
} else if (mFlaggingConversation) {
mHelper.loading(getString(R.string.flagging_conversation));
} else {
mHelper.stopLoading();
mMessageText.setText(mMessageBody);
mMessageText.post(() -> mMessageText.setSelection(mMessageText.getText().length()));
}
Integer userId = getOtherUserId();
if ((userId != null) && (mMenu != null)) {
boolean isMuted = isUserMuted();
mMenu.getItem(1).setVisible(isMuted);
mMenu.getItem(2).setTitle(isMuted ? R.string.unmute_this_user : R.string.mute_this_user);
boolean unresolvedFlag = MessageAdapter.hasUnresolvedFlags(mMessage.getJSONObject());
mMenu.getItem(0).setVisible(unresolvedFlag);
}
}
private void loadThread() {
Intent serviceIntent = new Intent(INaturalistService.ACTION_GET_MESSAGES, null, this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.MESSAGE_ID, mMessage.getJSONObject().optInt("id"));
ContextCompat.startForegroundService(this, serviceIntent);
}
private Integer getOtherUserId() {
if (!mMessage.has("from_user") || !mMessage.has("to_user") || mMessage.isNull("from_user") || mMessage.isNull("to_user")) {
if (!mMessage.has("from_user_id") || !mMessage.has("to_user_id") || !mMessage.has("user_id")) {
return null;
}
int thisUserId = mMessage.getInt("user_id");
return mMessage.getInt("from_user_id").equals(thisUserId) ?
mMessage.getInt("to_user_id") : mMessage.getInt("from_user_id");
}
return mMessage.getJSONObject("from_user").optString("login").equals(mApp.currentUserLogin()) ?
mMessage.getJSONObject("to_user").optInt("id") : mMessage.getJSONObject("from_user").optInt("id");
}
private boolean isUserMuted() {
int userId = getOtherUserId();
Set<Integer> mutedUsers = mApp.getMutedUsers();
return mutedUsers.contains(userId);
}
@Override
public void onResume() {
super.onResume();
if (mApp == null) {
mApp = (INaturalistApp) getApplicationContext();
}
mMessagesReceiver = new MessagesReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(INaturalistService.ACTION_MESSAGES_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mMessagesReceiver, filter, this);
mPostMessageReceiver = new PostMessageReceiver();
IntentFilter filter2 = new IntentFilter();
filter2.addAction(INaturalistService.ACTION_POST_MESSAGE_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mPostMessageReceiver, filter2, this);
mMuteUserReceiver = new MuteUserReceiver();
IntentFilter filter3 = new IntentFilter();
filter3.addAction(INaturalistService.ACTION_MUTE_USER_RESULT);
filter3.addAction(INaturalistService.ACTION_UNMUTE_USER_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mMuteUserReceiver, filter3, this);
mPostFlagReceiver = new PostFlagReceiver();
IntentFilter filter4 = new IntentFilter();
filter4.addAction(INaturalistService.ACTION_POST_FLAG_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mPostFlagReceiver, filter4, this);
if (mMessages == null) {
loadThread();
}
refreshViewState(true, false);
if (mShowFlagDialog) {
showFlagDialog();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMessageBody = mMessageText.getText().toString();
Bridge.saveInstanceState(this, outState);
}
@Override
protected void onPause() {
super.onPause();
BaseFragmentActivity.safeUnregisterReceiver(mMessagesReceiver, this);
BaseFragmentActivity.safeUnregisterReceiver(mPostMessageReceiver, this);
BaseFragmentActivity.safeUnregisterReceiver(mMuteUserReceiver, this);
BaseFragmentActivity.safeUnregisterReceiver(mPostFlagReceiver, this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.flag_conversation:
mShowFlagDialog = true;
showFlagDialog();
return true;
case R.id.is_flagged:
// Open flag URL
Intent intent = new Intent(Intent.ACTION_VIEW);
String inatNetwork = mApp.getInaturalistNetworkMember();
String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork);
JSONObject flag = MessageAdapter.getUnresolvedFlag(mMessage.getJSONObject());
intent.setData(Uri.parse(String.format("%s/flags/%d", inatHost, flag.optInt("id"))));
startActivity(intent);
return true;
case R.id.mute_user:
if (!isUserMuted()) {
// Mute user - show confirmation dialog
mHelper.confirm(
getString(R.string.mute_this_user_question),
getString(R.string.you_will_no_longer_receive_messages),
(dialogInterface, i) -> {
muteUser();
},
(dialogInterface, i) -> {
},
R.string.mute, R.string.cancel);
} else {
// Unmute user - no need to show confirmation dialog
muteUser();
}
return true;
case android.R.id.home:
// Respond to the action bar's Up/Home button
this.onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private void showFlagDialog() {
// Build the flag dialog - allowing to choose flag type (spam/offensive/other).
// If other is chosen, change OK button to Continue, and when pressed replace content
// with a flag explanation edit text.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Add title
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup content = (ViewGroup) inflater.inflate(R.layout.dialog_title_top_bar, null, false);
View titleBar = inflater.inflate(R.layout.dialog_title, null, false);
((TextView)titleBar.findViewById(R.id.title)).setText(R.string.flag_conversation);
// Options
content.addView(titleBar, 0);
View options = inflater.inflate(R.layout.flag_conversation, null, false);
content.addView(options, 1);
ViewGroup flagExplanationContainer = content.findViewById(R.id.flag_explanation_container);
EditText flagExplanation = content.findViewById(R.id.flag_explanation);
flagExplanation.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
boolean isEmpty = flagExplanation.getText().toString().length() == 0;
setFlagDialogOkButton(!isEmpty, R.string.submit);
}
});
flagExplanationContainer.setVisibility(View.GONE);
RadioGroup flagTypes = content.findViewById(R.id.flag_types);
List<RadioButton> radioButtons = new ArrayList<RadioButton>();
for (int i = 0; i < FLAG_TYPES.length; i++) {
final ViewGroup option = (ViewGroup) inflater.inflate(R.layout.network_option, null, false);
TextView title = (TextView) option.findViewById(R.id.title);
TextView subtitle = (TextView) option.findViewById(R.id.sub_title);
final AppCompatRadioButton radioButton = option.findViewById(R.id.radio_button);
title.setText(FLAG_TITLES[i]);
subtitle.setText(FLAG_DESCRIPTIONS[i]);
radioButton.setId(i);
// Set radio button color
ColorStateList colorStateList = new ColorStateList(
new int[][]{
new int[]{-android.R.attr.state_checked},
new int[]{android.R.attr.state_checked}
},
new int[]{
Color.DKGRAY, getResources().getColor(R.color.inatapptheme_color)
}
);
radioButton.setSupportButtonTintList(colorStateList);
final int index = i;
option.setOnClickListener(v -> {
// Uncheck all other radio buttons
for (int c = 0; c < radioButtons.size(); c++) {
RadioButton r = radioButtons.get(c);
r.setChecked(c == index ? true : false);
}
setFlagDialogOkButton(true, index == 2 ? R.string.continue_text : R.string.submit);
mSelectedFlagType = index;
});
radioButtons.add(radioButton);
flagTypes.addView(option);
}
// Add buttons
builder.setView(content);
builder.setPositiveButton(R.string.submit, null);
builder.setCancelable(false);
builder.setNegativeButton(R.string.cancel, (dialogInterface, i) -> {
mShowFlagDialog = false;
mFlagDialog.dismiss();
});
mFlagDialog = builder.create();
mFlagDialog.show();
setFlagDialogOkButton(false, R.string.submit);
mFlagDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.parseColor("#85B623"));
mFlagDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(view -> {
if (mSelectedFlagType == 2) {
// Other - show flag explanation EditText
flagExplanationContainer.setVisibility(View.VISIBLE);
flagTypes.setVisibility(View.GONE);
flagExplanation.postDelayed((Runnable) () -> {
flagExplanation.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(flagExplanation, InputMethodManager.SHOW_IMPLICIT);
}, 500);
setFlagDialogOkButton(false, R.string.submit);
mSelectedFlagType = -1;
} else {
// Spam, Offensive/Inappropriate, etc.
mFlagDialog.dismiss();
mShowFlagDialog = false;
String flag = null;
switch (mSelectedFlagType) {
case 0:
flag = "spam";
break;
case 1:
flag = "inappropriate";
break;
case -1:
flag = "other";
break;
}
// Post new flag
Intent serviceIntent = new Intent(INaturalistService.ACTION_POST_FLAG, null, this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.FLAGGABLE_TYPE, "Message");
serviceIntent.putExtra(INaturalistService.FLAGGABLE_ID, mMessage.getInt("thread_id"));
serviceIntent.putExtra(INaturalistService.FLAG, flag);
if (mSelectedFlagType == -1) {
serviceIntent.putExtra(INaturalistService.FLAG_EXPLANATION, flagExplanation.getText().toString());
}
ContextCompat.startForegroundService(this, serviceIntent);
mFlaggingConversation = true;
refreshViewState(false, false);
}
});
}
private void setFlagDialogOkButton(boolean enabled, int textRes) {
mFlagDialog.getButton(AlertDialog.BUTTON_POSITIVE).setText(textRes);
mFlagDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.parseColor(enabled ? "#85B623": "#B9B9B9"));
mFlagDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(enabled);
}
private void muteUser() {
// Mute/Unmute user
Integer user = getOtherUserId();
Intent serviceIntent = new Intent(isUserMuted() ? INaturalistService.ACTION_UNMUTE_USER : INaturalistService.ACTION_MUTE_USER, null, this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.USER, user);
ContextCompat.startForegroundService(this, serviceIntent);
mMutingUser = true;
refreshViewState(false, false);
}
@Override
public void onBackPressed() {
setResult(RESULT_OK);
finish();
}
private class MessagesReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
boolean isSharedOnApp = intent.getBooleanExtra(INaturalistService.IS_SHARED_ON_APP, false);
int messageId = intent.getIntExtra(INaturalistService.MESSAGE_ID, -1);
Object object = null;
BetterJSONObject resultsObject;
JSONArray results = null;
if (messageId != mMessage.getInt("id")) {
// Older results (for another message thread)
return;
}
if (isSharedOnApp) {
object = mApp.getServiceResult(intent.getAction());
} else {
object = intent.getSerializableExtra(INaturalistService.ACTION_MESSAGES_RESULT);
}
if (object == null) {
// Network error of some kind
mMessages = new ArrayList<>();
refreshViewState(true, false);
return;
}
// Messages result
resultsObject = (BetterJSONObject) object;
results = resultsObject.getJSONArray("results").getJSONArray();
ArrayList<JSONObject> resultsArray = new ArrayList<JSONObject>();
if (results == null) {
mMessages = new ArrayList<>();
refreshViewState(true, false);
return;
}
for (int i = 0; i < results.length(); i++) {
try {
JSONObject item = results.getJSONObject(i);
resultsArray.add(item);
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
}
mMessages = resultsArray;
if (mOpenedFromUrl) {
// This activity was opened from a URL, which means we don't have any other info other than the message ID.
// So now we'll replace the almost-empty message object with a full-fledged one from the results.
JSONObject message = CollectionUtils.find(mMessages, msg -> msg.optInt("id") == mMessage.getInt("id").intValue());
mMessage = new BetterJSONObject(message);
mOpenedFromUrl = false;
ActionBar ab = getSupportActionBar();
ab.setTitle(mMessage.getString("subject"));
}
mSendingMessage = false;
mMessageBody = "";
mMessageText.setText("");
refreshViewState(true, true);
}
}
private class PostMessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
boolean isSharedOnApp = intent.getBooleanExtra(INaturalistService.IS_SHARED_ON_APP, false);
Object object = null;
BetterJSONObject newMessage;
JSONArray results = null;
if (isSharedOnApp) {
object = mApp.getServiceResult(intent.getAction());
} else {
object = intent.getSerializableExtra(INaturalistService.ACTION_MESSAGES_RESULT);
}
if (object == null) {
// Network error of some kind
Toast.makeText(MessagesThreadActivity.this, String.format(getString(R.string.could_not_send_message), getString(R.string.not_connected)), Toast.LENGTH_LONG).show();
mHelper.stopLoading();
mSendingMessage = false;
return;
}
// Messages result
newMessage = (BetterJSONObject) object;
String error = newMessage.getString("error");
if (error != null) {
// Error sending message
Toast.makeText(MessagesThreadActivity.this, String.format(getString(R.string.could_not_send_message), error), Toast.LENGTH_LONG).show();
mHelper.stopLoading();
mSendingMessage = false;
return;
}
if (!newMessage.getInt("thread_id").equals(mMessage.getInt("thread_id"))) {
// Older result (for another message thread)
return;
}
// Next, refresh the message list, as the message returned by the API doesn't contain enough information
loadThread();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.message_thread_menu, menu);
mMenu = menu;
// Can't detect clicks directly (since we use a custom action view)
mMenu.getItem(0).getActionView().setOnClickListener(view -> MessagesThreadActivity.this.onOptionsItemSelected(mMenu.getItem(0)));
refreshViewState(false, true);
return true;
}
private class MuteUserReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
boolean success = intent.getBooleanExtra(INaturalistService.SUCCESS, false);
if (!success) {
mHelper.stopLoading();
Toast.makeText(MessagesThreadActivity.this, isUserMuted() ? R.string.failed_unmuting_user : R.string.failed_muting_user, Toast.LENGTH_LONG).show();
return;
}
Integer userId = getOtherUserId();
Set<Integer> muted = mApp.getMutedUsers();
if (isUserMuted()) {
// Mark as unmuted
muted.remove(userId);
} else {
// Mark as muted
muted.add(userId);
}
mApp.setMutedUsers(muted);
mMutingUser = false;
refreshViewState(false, false);
}
}
private class PostFlagReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
boolean success = intent.getBooleanExtra(INaturalistService.SUCCESS, false);
mHelper.stopLoading();
if (!success) {
Toast.makeText(MessagesThreadActivity.this, R.string.failed_flagging_conversation, Toast.LENGTH_LONG).show();
return;
}
mFlaggingConversation = false;
Toast.makeText(MessagesThreadActivity.this, R.string.thank_you_for_submitting_the_flag, Toast.LENGTH_LONG).show();
}
}
}
| 40.478076 | 181 | 0.600846 |
687e6249fea0d6300244bded3edcf2d4cc29f2af | 2,333 | package com.patient.preference;
import android.content.Context;
import com.patient.PatientApplication;
import com.patient.ui.patientUi.entity.baseTable.PartyBean;
/**
* <dl>
* <dt>LoginPreference.java</dt>
* <dd>Description:云电话登陆相关参数的保存:主要是保存 登陆的手机号,和登陆的密码,以及tokenid</dd>
* <dd>Copyright: Copyright (C) 2011</dd>
* <dd>Company: </dd>
* <dd>CreateDate: 2013-7-31 下午1:29:31</dd>
* </dl>
*
* @author lihs
*/
public class LoginPreference extends BasePreference {
private static LoginPreference loginPre;
public static LoginPreference getInstance() {
if (loginPre == null) {
loginPre = new LoginPreference(PatientApplication.getContext());
}
return loginPre;
}
// 当前用户登录的信息,已经完善过个人信息的用户在登录后会返回给我,否则
private static PartyBean userInfo = null;
public static PartyBean getUserInfo() {
if (userInfo == null) {
userInfo = new PartyBean();
}
return userInfo;
}
public static void setUserInfo(PartyBean userInfo) {
LoginPreference.userInfo = userInfo;
}
private static final String LOGIN_PREFERENCE_NAME = "cmcc_login_prefer";
public enum LoginType {
LOGIN_PHONE, // 登陆手机�? LOGIN_PASSWORD, // 登陆密码
PARTY_ROLE_ID, // 角色ID @CommonConstant.ROLE_LEADER
USER_NAME, // 登陆的用户名
PARTY_ID, // 会员Id
HEAD_URL, // 头像URL
PIC_NAME, // 头像名称
LEVEL, // 级别
PARENT_PARTY_ID, // 医生独有的字�? CUS_REGION_ID, // 学术联络员区域ID
DEPT_ID, // 学术联络员部门ID
GROUP_ID, // 项目负责�? APPID,// 应用ID
APPNAME,// 应用title 名字
FIRST_LOGIN,//首次登陆
WEATHER_BIND_ACADMIC,// 是否绑定学术联络�? JSESSION_ID,// 有效期id
CCME_APK_ID,// 下载apk的id
KEY_DOWN_LOAD_APK_FILE_PATH// 下载后的本地apk地址
}
public LoginPreference(Context context) {
super(context, LOGIN_PREFERENCE_NAME);
}
public void setString(LoginType keyType, String value) {
super.setString(keyType.name(), value);
}
public String getString(LoginType keyType, String defaultValue) {
String secrecyString = super.getString(keyType.name(), defaultValue);
if (secrecyString == null)
return defaultValue;
return secrecyString;
}
public static String getKeyValue(LoginType secrecyKeyType,
String defaultValue) {
return getInstance().getString(secrecyKeyType, defaultValue);
}
/**
* @author: lihs
* @Title: clearLoginPreference
* @Description: �?��登录时�?清空缓存的信�? * @date: 2013-8-9 下午1:55:02
*/
public void clearLoginPreference() {
}
}
| 24.819149 | 73 | 0.720532 |
37621602e324765fb7282dc774969211d710fa57 | 439 | package com.legocms.core.dto.cms;
import com.legocms.core.dto.Dto;
import com.legocms.core.dto.TypeInfo;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class CmsModelAttributeInfo extends Dto {
private static final long serialVersionUID = 1180776869572270932L;
private String code;
private String name;
private boolean required;
private TypeInfo type;
private int sort;
} | 21.95 | 71 | 0.731207 |
9ee3cb800889ab6b3bc69e72cfeadc155685b1bd | 725 | package twenty_days.day18;
/**
* @author Hs
* @Date 2021/10/18 21:49
*/
/**
* 实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。不得使用库函数,同时不需要考虑大数问题。
*
* 思路:使用快速幂,对于a的b次方,
* 如果b能被2整除,也就是b的二进制最后一位为0,那么可以转化为a的平方的b/2次方
* 如果b不能被2整除,也就是b的二进制最后一位为1,那么可以转化为a的平方的b/2次方再乘一个a
* 按照这个思路继续下去,直到b等于0, 每进行一次a=a*a,如果最后一位为1,res=res*a
*/
public class offer_16 {
public double myPow(double x, int n) {
if(x==0) return 0;
double res=1.0;
long t=n;// 在java中,int32 变量 n∈[−2147483648,2147483647] ,所以如果n=−2147483648会越界,所以要用long存储n
if(t<0){
x=1/x;
t=-t;
}
while(t>0){
if((t&1)==1) res*=x;
x=x*x;
t=t>>1;
}
return res;
}
}
| 21.969697 | 96 | 0.548966 |
c34c1a977f07166a60c7725a36f0a646167b2139 | 776 | package com.builtbroken.sheepmetal.config;
import com.builtbroken.sheepmetal.SheepMetal;
import com.builtbroken.sheepmetal.data.SheepTypes;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.Mod;
/**
* Created by Dark(DarkGuardsman, Robert) on 6/28/2019.
*/
public class ConfigTypes
{
public static class SheepConfig
{
//@Config.Name("")
//@Config.Comment("")
//@Config.RangeInt(min = 1)
public int spawnWeight = 1;
//@Config.Name("")
//@Config.Comment("")
public boolean enable = true;
public SheepConfig(int defWeight)
{
this.spawnWeight = defWeight;
}
}
}
| 22.823529 | 62 | 0.658505 |
952ef279790651be590d34bd07f3a09f3ea2cee5 | 6,582 | package com.dldhk97.kumohcafeteriaviewer.data;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.dldhk97.kumohcafeteriaviewer.UIHandler;
import com.dldhk97.kumohcafeteriaviewer.enums.ExceptionType;
import com.dldhk97.kumohcafeteriaviewer.model.MyException;
import java.util.ArrayList;
public class DatabaseManager {
private static DatabaseManager _instance;
private SQLiteDatabase mydatabase = null;
private Context context;
private DatabaseManager() {}
public void setContextIfNotExist(Context context) {
if(this.context == null)
this.context = context;
createTable();
}
public static DatabaseManager getInstance() {
if(_instance == null){
_instance = new DatabaseManager();
}
return _instance;
}
public void createTable(){
try{
if(context == null){
throw new MyException(ExceptionType.CONTEXT_NOT_INITIALIZED, "DatabaseManager not initialized");
}
//DB Open
mydatabase = context.openOrCreateDatabase(DatabaseInfo.DB_NAME.toString(), context.MODE_PRIVATE,null);
// 버전 체크
int savedVersion = Integer.parseInt(loadVersion());
int newVersion = Integer.parseInt(DatabaseInfo.DB_VERSION.toString());
if(savedVersion < newVersion){
dropTables();
Log.d("aaaaa", "Table deleted. Update table " + savedVersion + " -> " + newVersion + ".");
}
// Favorite Table 생성
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS " + DatabaseInfo.TABLE_FAVORITES +
"(" + "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
DatabaseInfo.TABLE_FAVORITES_COLUMN_ITEMNAME + " TEXT);");
// Menus Table 생성
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS " + DatabaseInfo.TABLE_MENUS +
"(" + "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
DatabaseInfo.TABLE_MENUS_COLUMN_DATE + " TEXT," +
DatabaseInfo.TABLE_MENUS_COLUMN_CAFETERIA + " TEXT," +
DatabaseInfo.TABLE_MENUS_COLUMN_MEALTIMETYPE + " TEXT," +
DatabaseInfo.TABLE_MENUS_COLUMN_ISOPEN + " TEXT," +
DatabaseInfo.TABLE_MENUS_COLUMN_ITEMNAME + " TEXT," +
DatabaseInfo.TABLE_MENUS_COLUMN_ITEMTYPE + " TEXT);");
// Alarm Table 생성
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS " + DatabaseInfo.TABLE_NOTIFICATIONITEMS +
"(" + "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
DatabaseInfo.TABLE_NOTIFICATIONITEMS + " TEXT," +
DatabaseInfo.TABLE_NOTIFICATIONITEMS_COLUMN_NAME + " TEXT," +
DatabaseInfo.TABLE_NOTIFICATIONITEMS_COLUMN_CAFETERIA + " TEXT," +
DatabaseInfo.TABLE_NOTIFICATIONITEMS_COLUMN_MEALTIME + " TEXT," +
DatabaseInfo.TABLE_NOTIFICATIONITEMS_COLUMN_HOUR + " TEXT," +
DatabaseInfo.TABLE_NOTIFICATIONITEMS_COLUMN_MIN + " TEXT," +
DatabaseInfo.TABLE_NOTIFICATIONITEMS_COLUMN_ACTIVATED + " TEXT);");
saveVersion();
}
catch(Exception e){
UIHandler.getInstance().showAlert(e.getMessage());
}
}
public void dropTables(){
dropMenusTable();
dropFavoritesTable();
dropNotificationItemsTable();
}
public void dropMenusTable(){
mydatabase.execSQL("DROP TABLE IF EXISTS " + DatabaseInfo.TABLE_MENUS);
}
public void dropFavoritesTable(){
mydatabase.execSQL("DROP TABLE IF EXISTS " + DatabaseInfo.TABLE_FAVORITES);
}
public void dropNotificationItemsTable(){
mydatabase.execSQL("DROP TABLE IF EXISTS " + DatabaseInfo.TABLE_NOTIFICATIONITEMS);
}
public boolean insert(String table , ArrayList<String> columns, ArrayList<String> values){
if(columns.size() != values.size())
return false;
ContentValues addRowValue = new ContentValues();
for(int i = 0 ; i < columns.size() ; i++){
addRowValue.put(columns.get(i), values.get(i));
}
return mydatabase.insert(table, null, addRowValue) > 0 ? true : false;
}
public ArrayList<ArrayList<String>> select(String table, ArrayList<String> columns, String where){
ArrayList<ArrayList<String>> result = new ArrayList<>();
String[] cols = new String[columns.size()];
cols = columns.toArray(cols);
Cursor cursor = mydatabase.query(table,
cols,
where,
null,
null,
null,
null);
if(cursor != null)
{
while (cursor.moveToNext())
{
ArrayList<String> row = new ArrayList<>();
for(int i = 0 ; i < columns.size() ; i++){
row.add(cursor.getString(i));
}
result.add(row);
}
}
return result.size() > 0 ? result : null;
}
public boolean deleteRow(String table, String where){
try{
String sql = "delete from " + table + " where " + where;
mydatabase.execSQL(sql);
}
catch (Exception e){
e.printStackTrace();
return false;
}
return true;
}
public boolean updateItem(String table, String set, String where){
try{
String sql = "update " + table + " set " + set + " where " + where;
mydatabase.execSQL(sql);
}
catch (Exception e){
e.printStackTrace();
return false;
}
return true;
}
private String PREFS_NAME = DatabaseInfo.DB_NAME + "_DB_VERSION";
private String PREF_PREFIX_KEY = "DB_VERSION";
private void saveVersion(){
SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, 0).edit();
prefs.putString(PREF_PREFIX_KEY, String.valueOf(DatabaseInfo.DB_VERSION.toString())); // 레이아웃 유형 저장(큰놈인지 아닌지)
prefs.apply();
}
private String loadVersion(){
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
final String version = prefs.getString(PREF_PREFIX_KEY, "0");
return version;
}
}
| 35.010638 | 124 | 0.596475 |
ef9e10086a89ccd0636e62dc44ebacbc9b6a318a | 4,018 | package org.checkerframework.dataflow.cfg.node;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.CompoundAssignmentTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.UnaryTree;
import com.sun.source.tree.VariableTree;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.javacutil.TreeUtils;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;
/**
* A node for an assignment:
*
* <pre>
* <em>variable</em> = <em>expression</em>
* <em>expression</em> . <em>field</em> = <em>expression</em>
* <em>expression</em> [ <em>index</em> ] = <em>expression</em>
* </pre>
*
* We allow assignments without corresponding AST {@link Tree}s.
*
* <p>Some desugarings create additional assignments to synthetic local variables. Such assignment
* nodes are marked as synthetic to allow special handling in transfer functions.
*/
public class AssignmentNode extends Node {
/** The underlying assignment tree. */
protected final Tree tree;
/** The node for the LHS of the assignment tree. */
protected final Node lhs;
/** The node for the RHS of the assignment tree. */
protected final Node rhs;
/** Whether the assignment node is synthetic */
protected final boolean synthetic;
/**
* Create a (non-synthetic) AssignmentNode.
*
* @param tree the {@code AssignmentTree} corresponding to the {@code AssignmentNode}
* @param target the lhs of {@code tree}
* @param expression the rhs of {@code tree}
*/
public AssignmentNode(Tree tree, Node target, Node expression) {
this(tree, target, expression, false);
}
/**
* Create an AssignmentNode.
*
* @param tree the {@code AssignmentTree} corresponding to the {@code AssignmentNode}
* @param target the lhs of {@code tree}
* @param expression the rhs of {@code tree}
* @param synthetic whether the assignment node is synthetic
*/
public AssignmentNode(Tree tree, Node target, Node expression, boolean synthetic) {
super(TreeUtils.typeOf(tree));
assert tree instanceof AssignmentTree
|| tree instanceof VariableTree
|| tree instanceof CompoundAssignmentTree
|| tree instanceof UnaryTree;
assert target instanceof FieldAccessNode
|| target instanceof LocalVariableNode
|| target instanceof ArrayAccessNode;
this.tree = tree;
this.lhs = target;
this.rhs = expression;
this.synthetic = synthetic;
}
/**
* Returns the left-hand-side of the assignment.
*
* @return the left-hand-side of the assignment
*/
public Node getTarget() {
return lhs;
}
public Node getExpression() {
return rhs;
}
@Override
public Tree getTree() {
return tree;
}
/**
* Check if the assignment node is synthetic, e.g. the synthetic assignment in a ternary
* expression.
*
* @return true if the assignment node is synthetic
*/
public boolean isSynthetic() {
return synthetic;
}
@Override
public <R, P> R accept(NodeVisitor<R, P> visitor, P p) {
return visitor.visitAssignment(this, p);
}
@Override
public String toString() {
return getTarget() + " = " + getExpression() + (synthetic ? " (synthetic)" : "");
}
@Override
public boolean equals(@Nullable Object obj) {
if (!(obj instanceof AssignmentNode)) {
return false;
}
AssignmentNode other = (AssignmentNode) obj;
return getTarget().equals(other.getTarget())
&& getExpression().equals(other.getExpression());
}
@Override
public int hashCode() {
return Objects.hash(getTarget(), getExpression());
}
@Override
public Collection<Node> getOperands() {
return Arrays.asList(getTarget(), getExpression());
}
}
| 29.985075 | 98 | 0.642111 |
fd12819e3e367d5563c72838ef180a45301fbd19 | 1,370 | /*
* Copyright 2015 Mikhail Khodonov
*
* 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.
*
* $Id$
*/
package org.homedns.mkh.dis;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;
/**
* Custom server end point configurator
*
*/
public class ServerEndpointConfigurator extends Configurator {
/**
* @see javax.websocket.server.ServerEndpointConfig.Configurator#modifyHandshake(javax.websocket.server.ServerEndpointConfig, javax.websocket.server.HandshakeRequest, javax.websocket.HandshakeResponse)
*/
@Override
public void modifyHandshake(
ServerEndpointConfig sec,
HandshakeRequest request,
HandshakeResponse response
) {
super.modifyHandshake( sec, request, response );
}
}
| 31.136364 | 202 | 0.772993 |
de21da0cb0033948b9f198e4d5d2428fd3214147 | 6,987 | package roth.lib.java.util;
import java.math.BigInteger;
import java.util.Base64;
public class BaseUtil
{
public static final int BASE_16 = 16;
public static final int BASE_36 = 36;
public static final int BASE_62 = 62;
public static final int BASE_64 = 64;
protected static final char[] CHARACTERS =
{
// base 16
'0', '1', '2', '3', '4', '5', '6', '7','8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
// base 36
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
// base 62
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
public static final String CHARACTER_STRING = new String(CHARACTERS);
public static final char BASE_PAD = CHARACTERS[0];
protected BaseUtil()
{
}
public static String encode16(String value)
{
return encode(value, BASE_16);
}
public static String encode36(String value)
{
return encode(value, BASE_36);
}
public static String encode62(String value)
{
return encode(value, BASE_62);
}
public static String encode(String value, int base)
{
return encode(value.getBytes(), base);
}
public static String encode16(byte[] bytes)
{
return encode(bytes, BASE_16);
}
public static String encode36(byte[] bytes)
{
return encode(bytes, BASE_36);
}
public static String encode62(byte[] bytes)
{
return encode(bytes, BASE_62);
}
public static String encode64(byte[] bytes)
{
return Base64.getEncoder().encodeToString(bytes);
}
public static String encode(byte[] bytes, int base)
{
if(BASE_64 == base)
{
return encode64(bytes);
}
else
{
return encode(new BigInteger(1, bytes), base);
}
}
public static String encode16(long number)
{
return encode(number, BASE_16);
}
public static String encode36(long number)
{
return encode(number, BASE_36);
}
public static String encode62(long number)
{
return encode(number, BASE_62);
}
public static String encode(long number, int base)
{
return encode(BigInteger.valueOf(number), base);
}
public static String encode16(BigInteger number)
{
return encode(number, BASE_16);
}
public static String encode36(BigInteger number)
{
return encode(number, BASE_36);
}
public static String encode62(BigInteger number)
{
return encode(number, BASE_62);
}
public static String encode(BigInteger number, int base)
{
return encode(number, null, BigInteger.valueOf(base));
}
public static String encode16(String value, int length)
{
return encode(value, length, BASE_16);
}
public static String encode36(String value, int length)
{
return encode(value, length, BASE_36);
}
public static String encode62(String value, int length)
{
return encode(value, length, BASE_62);
}
public static String encode(String value, int length, int base)
{
return encode(value.getBytes(), length, base);
}
public static String encode16(byte[] bytes, int length)
{
return encode(bytes, length, BASE_16);
}
public static String encode36(byte[] bytes, int length)
{
return encode(bytes, length, BASE_36);
}
public static String encode62(byte[] bytes, int length)
{
return encode(bytes, length, BASE_62);
}
public static String encode(byte[] bytes, int length, int base)
{
return encode(new BigInteger(1, bytes), length, base);
}
public static String encode16(long number, int length)
{
return encode(number, length, BASE_16);
}
public static String encode36(long number, int length)
{
return encode(number, length, BASE_36);
}
public static String encode62(long number, int length)
{
return encode(number, length, BASE_62);
}
public static String encode(long number, int length, int base)
{
return encode(BigInteger.valueOf(number), length, base);
}
public static String encode16(BigInteger number, int length)
{
return encode(number, length, BASE_16);
}
public static String encode36(BigInteger number, int length)
{
return encode(number, length, BASE_36);
}
public static String encode62(BigInteger number, int length)
{
return encode(number, length, BASE_62);
}
public static String encode(BigInteger number, int length, int base)
{
return encode(number, length, BigInteger.valueOf(base));
}
protected static String encode(BigInteger number, Integer length, BigInteger base)
{
StringBuilder builder = new StringBuilder();
number = number.abs();
base = base.max(BigInteger.valueOf(2));
base = base.min(BigInteger.valueOf(CHARACTERS.length));
while(number.signum() == 1)
{
builder.append(CHARACTERS[number.mod(base).intValue()]);
number = number.divide(base);
}
if(length != null)
{
return StringUtil.padLeftLimit(builder.reverse().toString(), length, BASE_PAD);
}
else
{
return builder.reverse().toString();
}
}
public static String decodeString16(String value)
{
return decodeString(value.toLowerCase(), BASE_16);
}
public static String decodeString36(String value)
{
return decodeString(value.toLowerCase(), BASE_36);
}
public static String decodeString62(String value)
{
return decodeString(value, BASE_62);
}
public static String decodeString64(String value)
{
return decodeString(value, BASE_64);
}
public static String decodeString(String value, int base)
{
return new String(decodeBytes(value, base));
}
public static byte[] decodeBytes16(String value)
{
return decodeBytes(value.toLowerCase(), BASE_16);
}
public static byte[] decodeBytes36(String value)
{
return decodeBytes(value.toLowerCase(), BASE_36);
}
public static byte[] decodeBytes62(String value)
{
return decodeBytes(value, BASE_62);
}
public static byte[] decodeBytes64(String value)
{
return Base64.getDecoder().decode(value.getBytes());
}
public static byte[] decodeBytes(String value, int base)
{
if(BASE_64 == base)
{
return decodeBytes64(value);
}
else
{
return decode(value, BigInteger.valueOf(base)).toByteArray();
}
}
public static BigInteger decode16(String value)
{
return decode(value.toLowerCase(), BASE_16);
}
public static BigInteger decode36(String value)
{
return decode(value.toLowerCase(), BASE_36);
}
public static BigInteger decode62(String value)
{
return decode(value, BASE_62);
}
public static BigInteger decode(String value, int base)
{
return decode(value, BigInteger.valueOf(base));
}
protected static BigInteger decode(String value, BigInteger base)
{
BigInteger number = BigInteger.valueOf(0);
if(value != null)
{
int baseInt = base.intValue();
int length = value.length();
for(int i = 0; i < length; i++)
{
int index = CHARACTER_STRING.indexOf(value.charAt(i));
if(index != -1 && index < baseInt)
{
number = number.multiply(base).add(BigInteger.valueOf(index));
}
}
}
return number;
}
public static void main(String[] args) throws Exception
{
}
}
| 21.366972 | 130 | 0.68055 |
90e01d41f2d904c4d757e2539fb409ff52db8a82 | 1,398 | /**
* Copyright (C) 2012 Ness Computing, 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.nesscomputing.server;
import org.skife.config.Config;
import org.skife.config.Default;
import org.skife.config.TimeSpan;
interface JvmPauseAlarmConfig
{
/**
* Turn the pause alarm on or off at config time.
*/
@Config("ness.jvm-pause.enabled")
@Default("true")
boolean isPauseAlarmEnabled();
/**
* The pause alarm will check this often to see if the JVM was taking a nap.
* This time should be significantly smaller than the pause time, or you
* may regret it...
*/
@Config("ness.jvm-pause.check-time")
@Default("50ms")
TimeSpan getCheckTime();
/**
* Report pauses that last longer than this amount.
*/
@Config("ness.jvm-pause.pause-time")
@Default("200ms")
TimeSpan getPauseAlarmTime();
}
| 29.744681 | 80 | 0.693133 |
f484e2f953281db9f877228007f3b8e7333b137b | 1,348 | package com.hills.mcs_02.dataBeans;
public class Bean_RecyclerView_mine_minor4_wallet {
private int userId;
private String userName;
private int userIcon;
private int userCoins;
public Bean_RecyclerView_mine_minor4_wallet(){
super();
}
public Bean_RecyclerView_mine_minor4_wallet(int userId, String userName, int userIcon, int userCoins){
this.userId = userId;
this.userName = userName;
this.userIcon = userIcon;
this.userCoins = userCoins;
}
public int getUserId(){
return userId;
}
public void setUserId(int userId){
this.userId = userId;
}
public String getUserName(){
return userName;
}
public void setUserName(String userName){
this.userName = userName;
}
public int getUserIcon(){
return userIcon;
}
public void setUserIcon(int userIcon){
this.userIcon = userIcon;
}
public int getUserCoins(){
return userCoins;
}
public void setUserCoins(int userCoins){
this.userCoins = userCoins;
}
@Override
public String toString(){
return "userId:" + userId + ","
+ "userName:" + userName + ","
+ "userCoins:" + userCoins;
}
}
| 22.098361 | 107 | 0.58457 |
6b66c7924d61f3cfeb6220a4c5fb1980baf6107c | 3,150 | package com.yyang.library.yedis;
import java.io.Closeable;
import java.io.IOException;
import java.net.Socket;
import javax.annotation.concurrent.NotThreadSafe;
import com.yyang.library.yedis.commands.ConnectionCommands;
import com.yyang.library.yedis.commands.DefaultBStringCommands;
import com.yyang.library.yedis.commands.DefaultConnectionCommands;
import com.yyang.library.yedis.commands.StringCommands;
import com.yyang.library.yedis.exception.RedisConnectionException;
import com.yyang.library.yedis.protocol.RESProtocol;
import com.yyang.library.yedis.util.RESPBufferedInputStream;
import com.yyang.library.yedis.util.RESPOutputStream;
import com.yyang.library.yedis.util.RedisBufferedOutputStream;
import com.yyang.library.yedis.util.SafeEncoder;
import lombok.Getter;
import lombok.Setter;
@NotThreadSafe
public class RedisBConnection implements Connection, Closeable {
private final RedisClient client;
private Socket socket;
private int connectionTimeout = RESProtocol.DEFAULT_TIMEOUT;
private int soTimeout = RESProtocol.DEFAULT_TIMEOUT;
private boolean broken = false;
@Getter
@Setter
private RESPOutputStream outputStream;
@Getter
private RESPBufferedInputStream inputStream;
RedisBConnection(RedisClient client) {
this.client = client;
}
@Override
public void close() throws IOException {
// TODO Auto-generated method stub
}
public void connect() {
if (!isConnected()) {
try {
socket = new Socket();
socket.setReuseAddress(true);
// Will monitor the TCP connection is valid
socket.setKeepAlive(true);
// close socket buffer to ensure timely delivery of data
socket.setTcpNoDelay(true);
// Control calls close() method to no block.
socket.setSoLinger(true, 0);
socket.connect(client.getSocketAddress(), connectionTimeout);
socket.setSoTimeout(soTimeout);
inputStream = new RESPBufferedInputStream(socket.getInputStream());
outputStream = new RESPOutputStream(new RedisBufferedOutputStream(socket.getOutputStream()));
;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public boolean isConnected() {
return socket != null && socket.isBound() && !socket.isClosed() && socket.isConnected()
&& !socket.isInputShutdown() && !socket.isOutputShutdown();
}
@Override
public StringCommands getStringCommands() {
connect();
return new DefaultBStringCommands(this);
}
@Override
public ConnectionCommands getConnectionCommands() {
connect();
return new DefaultConnectionCommands(this);
}
public String getReplyStatusCode(){
flush();
final byte[] resp = (byte[]) readReplyWithCheckingBroken();
if (null == resp) {
return null;
} else {
return SafeEncoder.encode(resp);
}
}
protected Object readReplyWithCheckingBroken() {
try {
return inputStream.readReply();
} catch (RedisConnectionException e) {
broken = true;
throw e;
}
}
public boolean isBroken() {
return broken;
}
protected void flush() {
try {
outputStream.flush();
} catch (IOException e) {
broken = true;
throw new RedisConnectionException(e);
}
}
}
| 25 | 97 | 0.746349 |
eb27ebb63b148cd52626bbdd01093fc510fed665 | 2,399 | /* Copyright 1999 Vince Via vvia@viaoa.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.viaoa.jfc;
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.beans.*;
import com.viaoa.hub.*;
import com.viaoa.util.*;
/**
Popup calendar that is bound to a property in a Hub.
A button can be setup that will automatically popup the OADateChooser.
<p>
Example:<br>
OAPopupDateChooser dc = new OAPopupDateChooser(hubEmployee, "hireDate");
JButton cmd = new JButton("Set Date");
dc.setButton(cmd);
-- or --
OACommand cmd = new OACommand(hubEmployee);
dc.setButton(cmd);
<p>
For more information about this package, see <a href="package-summary.html#package_description">documentation</a>.
@see OAPopup
@see OADateChooser
*/
public class OAPopupDateChooser extends OADateChooser {
protected OAPopup popup;
/**
Create a new Popup DateChooser that is bound to a property in the active object of a Hub.
*/
public OAPopupDateChooser(Hub hub, String propertyPath) {
super(hub, propertyPath);
// setIcon( new ImageIcon(getClass().getResource("images/date.gif")) );
popup = new OAPopup(this);
}
/** changing/selecting a date causes the popup to disappear. */
protected void firePropertyChange(String propertyName,Object oldValue,Object newValue) {
if (popup.isVisible()) popup.setVisible(false);
}
/**
Component used to set the popup to be visible.
*/
public void setController(JComponent comp) {
popup.setupListener(comp);
}
/**
Flag to have the popup displayed only when the right mouse button is clicked.
*/
public void setRightClickOnly(boolean b) {
popup.setRightClickOnly(b);
}
}
| 31.986667 | 118 | 0.693622 |
76de40b07724f6273c5c1261ca640895cc2d2dae | 885 | /*
* Copyright ©2016 Kaltura, Inc.
*/
package org.sakaiproject.kaltura.models.error;
/**
* Error statement model
*
* @author Robert Long (rlong @ unicon.net)
*
*/
public class Error {
private String text;
private String action;
private String identifier;
public Error(String text, String action, String identifier) {
this.text = text;
this.action = action;
this.identifier = identifier;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
}
| 18.061224 | 65 | 0.610169 |
fc7fca83b9de1e4451b09e2fd4f50312db5b33a9 | 4,322 | /*
* arcus-java-client : Arcus Java client
* Copyright 2020 JaM2in Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.spy.memcached.bulkoperation;
import junit.framework.Assert;
import net.spy.memcached.collection.BaseIntegrationTest;
import net.spy.memcached.ops.OperationStatus;
import net.spy.memcached.ops.StatusCode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class BulkDeleteTest extends BaseIntegrationTest {
public void testNullAndEmptyKeyDelete() {
// DELETE null key
try {
List<String> keys = null;
mc.asyncDeleteBulk(keys);
} catch (Exception e) {
assertEquals("Key list is null.", e.getMessage());
}
try {
String[] keys = null;
mc.asyncDeleteBulk(keys);
} catch (Exception e) {
assertEquals("Key list is null.", e.getMessage());
}
// DELETE empty key
try {
List<String> keys = new ArrayList<String>();
mc.asyncDeleteBulk(keys);
} catch (Exception e) {
assertEquals("Key list is empty.", e.getMessage());
}
}
public void testInsertAndDelete() {
String value = "MyValue";
int TEST_COUNT = 64;
try {
for (int keySize = 1; keySize < TEST_COUNT; keySize++) {
// generate key
String[] keys = new String[keySize];
for (int i = 0; i < keys.length; i++) {
keys[i] = "MyKey" + i;
}
// SET
for (String key : keys) {
mc.set(key, 60, value);
}
// Bulk delete
Future<Map<String, OperationStatus>> future = mc.
asyncDeleteBulk(Arrays.asList(keys));
Map<String, OperationStatus> errorList;
try {
errorList = future.get(20000L, TimeUnit.MILLISECONDS);
Assert.assertTrue("Error list is not empty.",
errorList.isEmpty());
} catch (TimeoutException e) {
future.cancel(true);
e.printStackTrace();
}
// GET
int errorCount = 0;
for (String key : keys) {
String v = (String) mc.get(key);
if (v != null) {
errorCount++;
}
}
Assert.assertEquals("Error count is greater than 0.", 0,
errorCount);
}
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
public void testDeleteNotFoundKey() {
int TEST_COUNT = 64;
try {
for (int keySize = 1; keySize < TEST_COUNT; keySize++) {
// generate key
String[] keys = new String[keySize];
for (int i = 0; i < keys.length; i++) {
keys[i] = "MyKey" + i;
}
for (int i = 0; i < keys.length; i++) {
if (i % 2 == 0) {
mc.set(keys[i], 60, "value");
} else {
mc.delete(keys[i]);
}
}
// Bulk delete
Future<Map<String, OperationStatus>> future = mc.
asyncDeleteBulk(Arrays.asList(keys));
Map<String, OperationStatus> errorList;
try {
errorList = future.get(20000L, TimeUnit.MILLISECONDS);
Assert.assertEquals("Error count is less than input.",
keys.length/2, errorList.size());
for (Map.Entry<String, OperationStatus> error :
errorList.entrySet()) {
Assert.assertEquals(error.getValue().getStatusCode(),
StatusCode.ERR_NOT_FOUND);
}
} catch (TimeoutException e) {
future.cancel(true);
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
}
| 28.813333 | 75 | 0.584683 |
144c9b47f70896a6a25873f8580ea342e95768ac | 2,360 | package com.mao.travelapp.bean;
import com.j256.ormlite.field.DatabaseField;
import com.mao.travelapp.sdk.BaseObject;
import java.io.Serializable;
import java.util.List;
/**
* Created by lyw on 2017/2/20.
*/
public class TravelNote extends BaseObject implements Serializable {
@DatabaseField(generatedId = true)
private int id;
@DatabaseField
private String text;
@DatabaseField
private String pictureUrls;
@DatabaseField
private String location;
@DatabaseField
private int userId;
@DatabaseField
private String publish_time;
@DatabaseField
private double latitude;
@DatabaseField
private double longitude;
public TravelNote(){}
public TravelNote(String text, String pictureUrls,
String location, int userId,
String publish_time, double latitude,
double longitude) {
this.text = text;
this.pictureUrls = pictureUrls;
this.location = location;
this.userId = userId;
this.publish_time = publish_time;
this.latitude = latitude;
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPublish_time() {
return publish_time;
}
public void setPublish_time(String publish_time) {
this.publish_time = publish_time;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getPictureUrls() {
return pictureUrls;
}
public void setPictureUrls(String pictureUrls) {
this.pictureUrls = pictureUrls;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
| 21.261261 | 68 | 0.623305 |
b88b6921f4f63015be022445f8ec47090de58a8b | 2,040 | /*
* Copyright (c) 2014-2015 University of Ulm
*
* 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 de.uniulm.omi.cloudiator.axe.aggregator.entities;
import de.uniulm.omi.cloudiator.axe.aggregator.entities.placeholder.Id;
/**
* Created by Frank on 20.08.2015.
*/
public final class SensorDescription extends Id {
public static final SensorDescription VM_CPU_SENSOR =
new SensorDescription(0, "eu.paasage.sensors.cpu.VmCpuSensor", "VM_CPU", true, false);
public static final SensorDescription COMP_CPU_SENSOR =
new SensorDescription(0, "eu.paasage.sensors.cpu.CompCpuSensor", "Comp_CPU", false, false);
private final String className;
private final String metricName;
private final boolean isVmSensor;
private final boolean isPush;
public boolean isVmSensor() {
return isVmSensor;
}
public boolean isPush() {
return isPush;
}
public String getMetricName() {
return metricName;
}
public String getClassName() {
return className;
}
public SensorDescription(long id, String _className, String _metricName, boolean _isVmSensor, boolean _isPush) {
super(id);
this.className = _className;
this.metricName = _metricName;
this.isVmSensor = _isVmSensor;
this.isPush = _isPush;
}
public String getSensorMetricName() {
return metricName;
}
}
| 30.447761 | 116 | 0.708333 |
f5d3bbfe367413a5d5b1fb1c50242b93ee412211 | 26,397 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|ddl
operator|.
name|table
operator|.
name|partition
operator|.
name|add
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|ArrayList
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|BitSet
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|Path
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|common
operator|.
name|StatsSetupConst
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|common
operator|.
name|TableName
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|common
operator|.
name|ValidReaderWriteIdList
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|metastore
operator|.
name|Warehouse
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|metastore
operator|.
name|api
operator|.
name|ColumnStatistics
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|metastore
operator|.
name|api
operator|.
name|EnvironmentContext
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|metastore
operator|.
name|api
operator|.
name|MetaException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|metastore
operator|.
name|api
operator|.
name|NoSuchObjectException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|metastore
operator|.
name|api
operator|.
name|Partition
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|ddl
operator|.
name|DDLOperation
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|ddl
operator|.
name|DDLOperationContext
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|ddl
operator|.
name|DDLUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|exec
operator|.
name|Utilities
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|hooks
operator|.
name|WriteEntity
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|io
operator|.
name|AcidUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|lockmgr
operator|.
name|LockException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|metadata
operator|.
name|HiveException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|metadata
operator|.
name|Table
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|parse
operator|.
name|ReplicationSpec
import|;
end_import
begin_comment
comment|/** * Operation process of adding a partition to a table. */
end_comment
begin_class
specifier|public
class|class
name|AlterTableAddPartitionOperation
extends|extends
name|DDLOperation
argument_list|<
name|AlterTableAddPartitionDesc
argument_list|>
block|{
specifier|public
name|AlterTableAddPartitionOperation
parameter_list|(
name|DDLOperationContext
name|context
parameter_list|,
name|AlterTableAddPartitionDesc
name|desc
parameter_list|)
block|{
name|super
argument_list|(
name|context
argument_list|,
name|desc
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
specifier|public
name|int
name|execute
parameter_list|()
throws|throws
name|HiveException
block|{
comment|// TODO: catalog name everywhere in this method
name|Table
name|table
init|=
name|context
operator|.
name|getDb
argument_list|()
operator|.
name|getTable
argument_list|(
name|desc
operator|.
name|getDbName
argument_list|()
argument_list|,
name|desc
operator|.
name|getTableName
argument_list|()
argument_list|)
decl_stmt|;
name|long
name|writeId
init|=
name|getWriteId
argument_list|(
name|table
argument_list|)
decl_stmt|;
name|List
argument_list|<
name|Partition
argument_list|>
name|partitions
init|=
name|getPartitions
argument_list|(
name|table
argument_list|,
name|writeId
argument_list|)
decl_stmt|;
name|addPartitions
argument_list|(
name|table
argument_list|,
name|partitions
argument_list|,
name|writeId
argument_list|)
expr_stmt|;
return|return
literal|0
return|;
block|}
specifier|private
name|long
name|getWriteId
parameter_list|(
name|Table
name|table
parameter_list|)
throws|throws
name|LockException
block|{
comment|// In case of replication, get the writeId from the source and use valid write Id list for replication.
if|if
condition|(
name|desc
operator|.
name|getReplicationSpec
argument_list|()
operator|.
name|isInReplicationScope
argument_list|()
operator|&&
name|desc
operator|.
name|getPartitions
argument_list|()
operator|.
name|get
argument_list|(
literal|0
argument_list|)
operator|.
name|getWriteId
argument_list|()
operator|>
literal|0
condition|)
block|{
return|return
name|desc
operator|.
name|getPartitions
argument_list|()
operator|.
name|get
argument_list|(
literal|0
argument_list|)
operator|.
name|getWriteId
argument_list|()
return|;
block|}
else|else
block|{
name|AcidUtils
operator|.
name|TableSnapshot
name|tableSnapshot
init|=
name|AcidUtils
operator|.
name|getTableSnapshot
argument_list|(
name|context
operator|.
name|getConf
argument_list|()
argument_list|,
name|table
argument_list|,
literal|true
argument_list|)
decl_stmt|;
if|if
condition|(
name|tableSnapshot
operator|!=
literal|null
operator|&&
name|tableSnapshot
operator|.
name|getWriteId
argument_list|()
operator|>
literal|0
condition|)
block|{
return|return
name|tableSnapshot
operator|.
name|getWriteId
argument_list|()
return|;
block|}
else|else
block|{
return|return
operator|-
literal|1
return|;
block|}
block|}
block|}
specifier|private
name|List
argument_list|<
name|Partition
argument_list|>
name|getPartitions
parameter_list|(
name|Table
name|table
parameter_list|,
name|long
name|writeId
parameter_list|)
throws|throws
name|HiveException
block|{
name|List
argument_list|<
name|Partition
argument_list|>
name|partitions
init|=
operator|new
name|ArrayList
argument_list|<>
argument_list|(
name|desc
operator|.
name|getPartitions
argument_list|()
operator|.
name|size
argument_list|()
argument_list|)
decl_stmt|;
for|for
control|(
name|AlterTableAddPartitionDesc
operator|.
name|PartitionDesc
name|partitionDesc
range|:
name|desc
operator|.
name|getPartitions
argument_list|()
control|)
block|{
name|Partition
name|partition
init|=
name|convertPartitionSpecToMetaPartition
argument_list|(
name|table
argument_list|,
name|partitionDesc
argument_list|)
decl_stmt|;
if|if
condition|(
name|partition
operator|!=
literal|null
operator|&&
name|writeId
operator|>
literal|0
condition|)
block|{
name|partition
operator|.
name|setWriteId
argument_list|(
name|writeId
argument_list|)
expr_stmt|;
block|}
name|partitions
operator|.
name|add
argument_list|(
name|partition
argument_list|)
expr_stmt|;
block|}
return|return
name|partitions
return|;
block|}
specifier|private
name|Partition
name|convertPartitionSpecToMetaPartition
parameter_list|(
name|Table
name|table
parameter_list|,
name|AlterTableAddPartitionDesc
operator|.
name|PartitionDesc
name|partitionSpec
parameter_list|)
throws|throws
name|HiveException
block|{
name|Path
name|location
init|=
name|partitionSpec
operator|.
name|getLocation
argument_list|()
operator|!=
literal|null
condition|?
operator|new
name|Path
argument_list|(
name|table
operator|.
name|getPath
argument_list|()
argument_list|,
name|partitionSpec
operator|.
name|getLocation
argument_list|()
argument_list|)
else|:
literal|null
decl_stmt|;
if|if
condition|(
name|location
operator|!=
literal|null
condition|)
block|{
comment|// Ensure that it is a full qualified path (in most cases it will be since tbl.getPath() is full qualified)
name|location
operator|=
operator|new
name|Path
argument_list|(
name|Utilities
operator|.
name|getQualifiedPath
argument_list|(
name|context
operator|.
name|getConf
argument_list|()
argument_list|,
name|location
argument_list|)
argument_list|)
expr_stmt|;
block|}
name|Partition
name|partition
init|=
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|metadata
operator|.
name|Partition
operator|.
name|createMetaPartitionObject
argument_list|(
name|table
argument_list|,
name|partitionSpec
operator|.
name|getPartSpec
argument_list|()
argument_list|,
name|location
argument_list|)
decl_stmt|;
if|if
condition|(
name|partitionSpec
operator|.
name|getPartParams
argument_list|()
operator|!=
literal|null
condition|)
block|{
name|partition
operator|.
name|setParameters
argument_list|(
name|partitionSpec
operator|.
name|getPartParams
argument_list|()
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|partitionSpec
operator|.
name|getInputFormat
argument_list|()
operator|!=
literal|null
condition|)
block|{
name|partition
operator|.
name|getSd
argument_list|()
operator|.
name|setInputFormat
argument_list|(
name|partitionSpec
operator|.
name|getInputFormat
argument_list|()
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|partitionSpec
operator|.
name|getOutputFormat
argument_list|()
operator|!=
literal|null
condition|)
block|{
name|partition
operator|.
name|getSd
argument_list|()
operator|.
name|setOutputFormat
argument_list|(
name|partitionSpec
operator|.
name|getOutputFormat
argument_list|()
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|partitionSpec
operator|.
name|getNumBuckets
argument_list|()
operator|!=
operator|-
literal|1
condition|)
block|{
name|partition
operator|.
name|getSd
argument_list|()
operator|.
name|setNumBuckets
argument_list|(
name|partitionSpec
operator|.
name|getNumBuckets
argument_list|()
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|partitionSpec
operator|.
name|getCols
argument_list|()
operator|!=
literal|null
condition|)
block|{
name|partition
operator|.
name|getSd
argument_list|()
operator|.
name|setCols
argument_list|(
name|partitionSpec
operator|.
name|getCols
argument_list|()
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|partitionSpec
operator|.
name|getSerializationLib
argument_list|()
operator|!=
literal|null
condition|)
block|{
name|partition
operator|.
name|getSd
argument_list|()
operator|.
name|getSerdeInfo
argument_list|()
operator|.
name|setSerializationLib
argument_list|(
name|partitionSpec
operator|.
name|getSerializationLib
argument_list|()
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|partitionSpec
operator|.
name|getSerdeParams
argument_list|()
operator|!=
literal|null
condition|)
block|{
name|partition
operator|.
name|getSd
argument_list|()
operator|.
name|getSerdeInfo
argument_list|()
operator|.
name|setParameters
argument_list|(
name|partitionSpec
operator|.
name|getSerdeParams
argument_list|()
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|partitionSpec
operator|.
name|getBucketCols
argument_list|()
operator|!=
literal|null
condition|)
block|{
name|partition
operator|.
name|getSd
argument_list|()
operator|.
name|setBucketCols
argument_list|(
name|partitionSpec
operator|.
name|getBucketCols
argument_list|()
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|partitionSpec
operator|.
name|getSortCols
argument_list|()
operator|!=
literal|null
condition|)
block|{
name|partition
operator|.
name|getSd
argument_list|()
operator|.
name|setSortCols
argument_list|(
name|partitionSpec
operator|.
name|getSortCols
argument_list|()
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|partitionSpec
operator|.
name|getColStats
argument_list|()
operator|!=
literal|null
condition|)
block|{
name|partition
operator|.
name|setColStats
argument_list|(
name|partitionSpec
operator|.
name|getColStats
argument_list|()
argument_list|)
expr_stmt|;
name|ColumnStatistics
name|statistics
init|=
name|partition
operator|.
name|getColStats
argument_list|()
decl_stmt|;
if|if
condition|(
name|statistics
operator|!=
literal|null
operator|&&
name|statistics
operator|.
name|getEngine
argument_list|()
operator|==
literal|null
condition|)
block|{
name|statistics
operator|.
name|setEngine
argument_list|(
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|conf
operator|.
name|Constants
operator|.
name|HIVE_ENGINE
argument_list|)
expr_stmt|;
block|}
comment|// Statistics will have an associated write Id for a transactional table. We need it to update column statistics.
name|partition
operator|.
name|setWriteId
argument_list|(
name|partitionSpec
operator|.
name|getWriteId
argument_list|()
argument_list|)
expr_stmt|;
block|}
return|return
name|partition
return|;
block|}
specifier|private
name|void
name|addPartitions
parameter_list|(
name|Table
name|table
parameter_list|,
name|List
argument_list|<
name|Partition
argument_list|>
name|partitions
parameter_list|,
name|long
name|writeId
parameter_list|)
throws|throws
name|HiveException
block|{
name|List
argument_list|<
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|metadata
operator|.
name|Partition
argument_list|>
name|outPartitions
init|=
literal|null
decl_stmt|;
if|if
condition|(
operator|!
name|desc
operator|.
name|getReplicationSpec
argument_list|()
operator|.
name|isInReplicationScope
argument_list|()
condition|)
block|{
name|outPartitions
operator|=
name|addPartitionsNoReplication
argument_list|(
name|table
argument_list|,
name|partitions
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|outPartitions
operator|=
name|addPartitionsWithReplication
argument_list|(
name|table
argument_list|,
name|partitions
argument_list|,
name|writeId
argument_list|)
expr_stmt|;
block|}
for|for
control|(
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|metadata
operator|.
name|Partition
name|outPartition
range|:
name|outPartitions
control|)
block|{
name|DDLUtils
operator|.
name|addIfAbsentByName
argument_list|(
operator|new
name|WriteEntity
argument_list|(
name|outPartition
argument_list|,
name|WriteEntity
operator|.
name|WriteType
operator|.
name|INSERT
argument_list|)
argument_list|,
name|context
argument_list|)
expr_stmt|;
block|}
block|}
specifier|private
name|List
argument_list|<
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|metadata
operator|.
name|Partition
argument_list|>
name|addPartitionsNoReplication
parameter_list|(
name|Table
name|table
parameter_list|,
name|List
argument_list|<
name|Partition
argument_list|>
name|partitions
parameter_list|)
throws|throws
name|HiveException
block|{
comment|// TODO: normally, the result is not necessary; might make sense to pass false
name|List
argument_list|<
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|metadata
operator|.
name|Partition
argument_list|>
name|outPartitions
init|=
operator|new
name|ArrayList
argument_list|<>
argument_list|()
decl_stmt|;
for|for
control|(
name|Partition
name|outPart
range|:
name|context
operator|.
name|getDb
argument_list|()
operator|.
name|addPartition
argument_list|(
name|partitions
argument_list|,
name|desc
operator|.
name|isIfNotExists
argument_list|()
argument_list|,
literal|true
argument_list|)
control|)
block|{
name|outPartitions
operator|.
name|add
argument_list|(
operator|new
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|metadata
operator|.
name|Partition
argument_list|(
name|table
argument_list|,
name|outPart
argument_list|)
argument_list|)
expr_stmt|;
block|}
return|return
name|outPartitions
return|;
block|}
specifier|private
name|List
argument_list|<
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|metadata
operator|.
name|Partition
argument_list|>
name|addPartitionsWithReplication
parameter_list|(
name|Table
name|table
parameter_list|,
name|List
argument_list|<
name|Partition
argument_list|>
name|partitions
parameter_list|,
name|long
name|writeId
parameter_list|)
throws|throws
name|HiveException
block|{
comment|// For replication add-ptns, we need to follow a insert-if-not-exist, alter-if-exists scenario.
comment|// TODO : ideally, we should push this mechanism to the metastore, because, otherwise, we have
comment|// no choice but to iterate over the partitions here.
name|List
argument_list|<
name|Partition
argument_list|>
name|partitionsToAdd
init|=
operator|new
name|ArrayList
argument_list|<>
argument_list|()
decl_stmt|;
name|List
argument_list|<
name|Partition
argument_list|>
name|partitionssToAlter
init|=
operator|new
name|ArrayList
argument_list|<>
argument_list|()
decl_stmt|;
name|List
argument_list|<
name|String
argument_list|>
name|partitionNames
init|=
operator|new
name|ArrayList
argument_list|<>
argument_list|()
decl_stmt|;
for|for
control|(
name|Partition
name|partition
range|:
name|partitions
control|)
block|{
name|partitionNames
operator|.
name|add
argument_list|(
name|getPartitionName
argument_list|(
name|table
argument_list|,
name|partition
argument_list|)
argument_list|)
expr_stmt|;
try|try
block|{
name|Partition
name|p
init|=
name|context
operator|.
name|getDb
argument_list|()
operator|.
name|getPartition
argument_list|(
name|desc
operator|.
name|getDbName
argument_list|()
argument_list|,
name|desc
operator|.
name|getTableName
argument_list|()
argument_list|,
name|partition
operator|.
name|getValues
argument_list|()
argument_list|)
decl_stmt|;
if|if
condition|(
name|desc
operator|.
name|getReplicationSpec
argument_list|()
operator|.
name|allowReplacementInto
argument_list|(
name|p
operator|.
name|getParameters
argument_list|()
argument_list|)
condition|)
block|{
name|ReplicationSpec
operator|.
name|copyLastReplId
argument_list|(
name|p
operator|.
name|getParameters
argument_list|()
argument_list|,
name|partition
operator|.
name|getParameters
argument_list|()
argument_list|)
expr_stmt|;
name|partitionssToAlter
operator|.
name|add
argument_list|(
name|partition
argument_list|)
expr_stmt|;
block|}
comment|// else ptn already exists, but we do nothing with it.
block|}
catch|catch
parameter_list|(
name|HiveException
name|e
parameter_list|)
block|{
if|if
condition|(
name|e
operator|.
name|getCause
argument_list|()
operator|instanceof
name|NoSuchObjectException
condition|)
block|{
comment|// if the object does not exist, we want to add it.
name|partitionsToAdd
operator|.
name|add
argument_list|(
name|partition
argument_list|)
expr_stmt|;
block|}
else|else
block|{
throw|throw
name|e
throw|;
block|}
block|}
block|}
name|List
argument_list|<
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|metadata
operator|.
name|Partition
argument_list|>
name|outPartitions
init|=
operator|new
name|ArrayList
argument_list|<>
argument_list|()
decl_stmt|;
for|for
control|(
name|Partition
name|outPartition
range|:
name|context
operator|.
name|getDb
argument_list|()
operator|.
name|addPartition
argument_list|(
name|partitionsToAdd
argument_list|,
name|desc
operator|.
name|isIfNotExists
argument_list|()
argument_list|,
literal|true
argument_list|)
control|)
block|{
name|outPartitions
operator|.
name|add
argument_list|(
operator|new
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|metadata
operator|.
name|Partition
argument_list|(
name|table
argument_list|,
name|outPartition
argument_list|)
argument_list|)
expr_stmt|;
block|}
comment|// In case of replication, statistics is obtained from the source, so do not update those on replica.
name|EnvironmentContext
name|ec
init|=
operator|new
name|EnvironmentContext
argument_list|()
decl_stmt|;
name|ec
operator|.
name|putToProperties
argument_list|(
name|StatsSetupConst
operator|.
name|DO_NOT_UPDATE_STATS
argument_list|,
name|StatsSetupConst
operator|.
name|TRUE
argument_list|)
expr_stmt|;
name|String
name|validWriteIdList
init|=
name|getValidWriteIdList
argument_list|(
name|table
argument_list|,
name|writeId
argument_list|)
decl_stmt|;
name|context
operator|.
name|getDb
argument_list|()
operator|.
name|alterPartitions
argument_list|(
name|desc
operator|.
name|getDbName
argument_list|()
argument_list|,
name|desc
operator|.
name|getTableName
argument_list|()
argument_list|,
name|partitionssToAlter
argument_list|,
name|ec
argument_list|,
name|validWriteIdList
argument_list|,
name|writeId
argument_list|)
expr_stmt|;
for|for
control|(
name|Partition
name|outPartition
range|:
name|context
operator|.
name|getDb
argument_list|()
operator|.
name|getPartitionsByNames
argument_list|(
name|desc
operator|.
name|getDbName
argument_list|()
argument_list|,
name|desc
operator|.
name|getTableName
argument_list|()
argument_list|,
name|partitionNames
argument_list|)
control|)
block|{
name|outPartitions
operator|.
name|add
argument_list|(
operator|new
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|metadata
operator|.
name|Partition
argument_list|(
name|table
argument_list|,
name|outPartition
argument_list|)
argument_list|)
expr_stmt|;
block|}
return|return
name|outPartitions
return|;
block|}
specifier|private
name|String
name|getPartitionName
parameter_list|(
name|Table
name|table
parameter_list|,
name|Partition
name|partition
parameter_list|)
throws|throws
name|HiveException
block|{
try|try
block|{
return|return
name|Warehouse
operator|.
name|makePartName
argument_list|(
name|table
operator|.
name|getPartitionKeys
argument_list|()
argument_list|,
name|partition
operator|.
name|getValues
argument_list|()
argument_list|)
return|;
block|}
catch|catch
parameter_list|(
name|MetaException
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|HiveException
argument_list|(
name|e
argument_list|)
throw|;
block|}
block|}
specifier|private
name|String
name|getValidWriteIdList
parameter_list|(
name|Table
name|table
parameter_list|,
name|long
name|writeId
parameter_list|)
throws|throws
name|LockException
block|{
if|if
condition|(
name|desc
operator|.
name|getReplicationSpec
argument_list|()
operator|.
name|isInReplicationScope
argument_list|()
operator|&&
name|desc
operator|.
name|getPartitions
argument_list|()
operator|.
name|get
argument_list|(
literal|0
argument_list|)
operator|.
name|getWriteId
argument_list|()
operator|>
literal|0
condition|)
block|{
comment|// We need a valid writeId list for a transactional change. During replication we do not
comment|// have a valid writeId list which was used for this on the source. But we know for sure
comment|// that the writeId associated with it was valid then (otherwise the change would have
comment|// failed on the source). So use a valid transaction list with only that writeId.
return|return
operator|new
name|ValidReaderWriteIdList
argument_list|(
name|TableName
operator|.
name|getDbTable
argument_list|(
name|table
operator|.
name|getDbName
argument_list|()
argument_list|,
name|table
operator|.
name|getTableName
argument_list|()
argument_list|)
argument_list|,
operator|new
name|long
index|[
literal|0
index|]
argument_list|,
operator|new
name|BitSet
argument_list|()
argument_list|,
name|writeId
argument_list|)
operator|.
name|writeToString
argument_list|()
return|;
block|}
else|else
block|{
name|AcidUtils
operator|.
name|TableSnapshot
name|tableSnapshot
init|=
name|AcidUtils
operator|.
name|getTableSnapshot
argument_list|(
name|context
operator|.
name|getConf
argument_list|()
argument_list|,
name|table
argument_list|,
literal|true
argument_list|)
decl_stmt|;
if|if
condition|(
name|tableSnapshot
operator|!=
literal|null
operator|&&
name|tableSnapshot
operator|.
name|getWriteId
argument_list|()
operator|>
literal|0
condition|)
block|{
return|return
name|tableSnapshot
operator|.
name|getValidWriteIdList
argument_list|()
return|;
block|}
else|else
block|{
return|return
literal|null
return|;
block|}
block|}
block|}
block|}
end_class
end_unit
| 14.100962 | 813 | 0.801758 |
189c1e9695ce2c432a2a0a5e6ffa2fc4765c3b5b | 195 | package com.deadapps.testmp3;
import android.view.View;
/**
* Created by Valdio Veliu on 16-08-06.
*/
public interface onItemClickListener {
public void onClick(View view, int index);
}
| 16.25 | 46 | 0.723077 |
6ba918cca3b2ae95867b9bb79d378c94a0a30772 | 22,531 | /*
* Copyright (C) 2012-2015 cketti and contributors
* https://github.com/cketti/ckChangeLog/graphs/contributors
*
* Portions Copyright (C) 2012 Martin van Zuilekom (http://martin.cubeactive.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* Based on android-change-log:
*
* Copyright (C) 2011, Karsten Priegnitz
*
* Permission to use, copy, modify, and distribute this piece of software
* for any purpose with or without fee is hereby granted, provided that
* the above copyright notice and this permission notice appear in the
* source code of all copies.
*
* It would be appreciated if you mention the author in your change log,
* contributors list or the like.
*
* http://code.google.com/p/android-change-log/
*/
package com.hctrom.romcontrol.changelog;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.XmlResourceParser;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.SparseArray;
import android.webkit.WebView;
import android.widget.Button;
import com.hctrom.romcontrol.R;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Display a dialog showing a full or partial (What's New) change log.
*/
@SuppressWarnings("UnusedDeclaration")
public class ChangeLog {
/**
* Tag that is used when sending error/debug messages to the log.
*/
protected static final String LOG_TAG = "ckChangeLog";
/**
* This is the key used when storing the version code in SharedPreferences.
*/
protected static final String VERSION_KEY = "ckChangeLog_last_version_code";
/**
* Constant that used when no version code is available.
*/
protected static final int NO_VERSION = -1;
/**
* Default CSS styles used to format the change log.
*/
public static final String DEFAULT_CSS =
"h1 { margin-left: 0px; font-size: 1.2em; }" + "\n" +
"li { margin-left: 0px; }" + "\n" +
"ul { padding-left: 2em; }";
/**
* Context that is used to access the resources and to create the ChangeLog dialogs.
*/
protected final Context mContext;
/**
* Contains the CSS rules used to format the change log.
*/
protected final String mCss;
/**
* Last version code read from {@code SharedPreferences} or {@link #NO_VERSION}.
*/
private int mLastVersionCode;
/**
* Version code of the current installation.
*/
private int mCurrentVersionCode;
/**
* Version name of the current installation.
*/
private String mCurrentVersionName;
/**
* Contains constants for the root element of {@code changelog.xml}.
*/
protected interface ChangeLogTag {
static final String NAME = "changelog";
}
/**
* Contains constants for the release element of {@code changelog.xml}.
*/
protected interface ReleaseTag {
static final String NAME = "release";
static final String ATTRIBUTE_VERSION = "version";
static final String ATTRIBUTE_VERSION_CODE = "versioncode";
}
/**
* Contains constants for the change element of {@code changelog.xml}.
*/
protected interface ChangeTag {
static final String NAME = "change";
}
/**
* Create a {@code ChangeLog} instance using the default {@link SharedPreferences} file.
*
* @param context
* Context that is used to access the resources and to create the ChangeLog dialogs.
*/
public ChangeLog(Context context) {
this(context, PreferenceManager.getDefaultSharedPreferences(context), DEFAULT_CSS);
}
/**
* Create a {@code ChangeLog} instance using the default {@link SharedPreferences} file.
*
* @param context
* Context that is used to access the resources and to create the ChangeLog dialogs.
* @param css
* CSS styles that will be used to format the change log.
*/
public ChangeLog(Context context, String css) {
this(context, PreferenceManager.getDefaultSharedPreferences(context), css);
}
/**
* Create a {@code ChangeLog} instance using the supplied {@code SharedPreferences} instance.
*
* @param context
* Context that is used to access the resources and to create the ChangeLog dialogs.
* @param preferences
* {@code SharedPreferences} instance that is used to persist the last version code.
* @param css
* CSS styles used to format the change log (excluding {@code <style>} and
* {@code </style>}).
*
*/
public ChangeLog(Context context, SharedPreferences preferences, String css) {
mContext = context;
mCss = css;
// Get last version code
mLastVersionCode = preferences.getInt(VERSION_KEY, NO_VERSION);
// Get current version code and version name
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
mCurrentVersionCode = packageInfo.versionCode;
mCurrentVersionName = packageInfo.versionName;
} catch (NameNotFoundException e) {
mCurrentVersionCode = NO_VERSION;
Log.e(LOG_TAG, "Could not get version information from manifest!", e);
}
}
/**
* Get version code of last installation.
*
* @return The version code of the last installation of this app (as described in the former
* manifest). This will be the same as returned by {@link #getCurrentVersionCode()} the
* second time this version of the app is launched (more precisely: the second time
* {@code ChangeLog} is instantiated).
*
* @see <a href="http://developer.android.com/guide/topics/manifest/manifest-element.html#vcode">android:versionCode</a>
*/
public int getLastVersionCode() {
return mLastVersionCode;
}
/**
* Get version code of current installation.
*
* @return The version code of this app as described in the manifest.
*
* @see <a href="http://developer.android.com/guide/topics/manifest/manifest-element.html#vcode">android:versionCode</a>
*/
public int getCurrentVersionCode() {
return mCurrentVersionCode;
}
/**
* Get version name of current installation.
*
* @return The version name of this app as described in the manifest.
*
* @see <a href="http://developer.android.com/guide/topics/manifest/manifest-element.html#vname">android:versionName</a>
*/
public String getCurrentVersionName() {
return mCurrentVersionName;
}
/**
* Check if this is the first execution of this app version.
*
* @return {@code true} if this version of your app is started the first time.
*/
public boolean isFirstRun() {
return mLastVersionCode < mCurrentVersionCode;
}
/**
* Check if this is a new installation.
*
* @return {@code true} if your app including {@code ChangeLog} is started the first time ever.
* Also {@code true} if your app was uninstalled and installed again.
*/
public boolean isFirstRunEver() {
return mLastVersionCode == NO_VERSION;
}
/**
* Skip the "What's new" dialog for this app version.
*
* <p>
* Future calls to {@link #isFirstRun()} and {@link #isFirstRunEver()} will return {@code false}
* for the current app version.
* </p>
*/
public void skipLogDialog() {
updateVersionInPreferences();
}
/**
* Get the "What's New" dialog.
*
* @return An AlertDialog displaying the changes since the previous installed version of your
* app (What's New). But when this is the first run of your app including
* {@code ChangeLog} then the full log dialog is show.
*/
public AlertDialog getLogDialog() {
return getDialog(isFirstRunEver());
}
/**
* Get a dialog with the full change log.
*
* @return An AlertDialog with a full change log displayed.
*/
public AlertDialog getFullLogDialog() {
return getDialog(true);
}
/**
* Create a dialog containing (parts of the) change log.
*
* @param full
* If this is {@code true} the full change log is displayed. Otherwise only changes for
* versions newer than the last version are displayed.
*
* @return A dialog containing the (partial) change log.
*/
protected AlertDialog getDialog(boolean full) {
WebView wv = new WebView(mContext);
//wv.setBackgroundColor(0); // transparent
wv.loadDataWithBaseURL(null, getLog(full), "text/html", "UTF-8", null);
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle(
mContext.getResources().getString(full ? R.string.changelog_full_title : R.string.changelog_title))
.setView(wv)
.setCancelable(false)
// OK button
.setPositiveButton(
mContext.getResources().getString(R.string.changelog_ok_button),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// The user clicked "OK" so save the current version code as
// "last version code".
updateVersionInPreferences();
}
});
if (!full) {
// Show "More…" button if we're only displaying a partial change log.
builder.setNegativeButton(R.string.changelog_show_full,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
getFullLogDialog().show();
}
});
}
AlertDialog dialog = builder.create();
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
Button positive_button = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
Button negative_button = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
if (PreferenceManager.getDefaultSharedPreferences(mContext).getInt("theme_prefs", 0) == 3) {
dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_bg_samsung_light);
positive_button.setTextColor(mContext.getResources().getColor(R.color.color_iconos_samsung_light));
negative_button.setTextColor(mContext.getResources().getColor(R.color.color_iconos_samsung_light));
}else if (PreferenceManager.getDefaultSharedPreferences(mContext).getInt("theme_prefs", 0) == 4){
dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_bg_hct);
positive_button.setTextColor(mContext.getResources().getColor(R.color.myAccentColorMaterialDark));
negative_button.setTextColor(mContext.getResources().getColor(R.color.myAccentColorMaterialDark));
}else if (PreferenceManager.getDefaultSharedPreferences(mContext).getInt("theme_prefs", 0) == 0){
dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_bg_hct);
positive_button.setTextColor(mContext.getResources().getColor(R.color.myAccentColorHCT));
negative_button.setTextColor(mContext.getResources().getColor(R.color.myAccentColorHCT));
}else {
dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_bg_dark_light);
positive_button.setTextColor(mContext.getResources().getColor(R.color.myAccentColor));
negative_button.setTextColor(mContext.getResources().getColor(R.color.myAccentColor));
}
return dialog;
}
/**
* Write current version code to the preferences.
*/
protected void updateVersionInPreferences() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = sp.edit();
editor.putInt(VERSION_KEY, mCurrentVersionCode);
// TODO: Update preferences from a background thread
editor.commit();
}
/**
* Get changes since last version as HTML string.
*
* @return HTML string containing the changes since the previous installed version of your app
* (What's New).
*/
public String getLog() {
return getLog(false);
}
/**
* Get full change log as HTML string.
*
* @return HTML string containing the full change log.
*/
public String getFullLog() {
return getLog(true);
}
/**
* Get (partial) change log as HTML string.
*
* @param full
* If this is {@code true} the full change log is returned. Otherwise only changes for
* versions newer than the last version are returned.
*
* @return The (partial) change log.
*/
protected String getLog(boolean full) {
StringBuilder sb = new StringBuilder();
sb.append("<html><head><style type=\"text/css\">");
sb.append(mCss);
sb.append("</style></head><body>");
String versionFormat = mContext.getResources().getString(R.string.changelog_version_format);
List<ReleaseItem> changelog = getChangeLog(full);
for (ReleaseItem release : changelog) {
sb.append("<h1>");
sb.append(String.format(versionFormat, release.versionName));
sb.append("</h1><ul>");
for (String change : release.changes) {
sb.append("<li>");
sb.append(change);
sb.append("</li>");
}
sb.append("</ul>");
}
sb.append("</body></html>");
return sb.toString();
}
/**
* Returns the merged change log.
*
* @param full
* If this is {@code true} the full change log is returned. Otherwise only changes for
* versions newer than the last version are returned.
*
* @return A sorted {@code List} containing {@link ReleaseItem}s representing the (partial)
* change log.
*
* @see #getChangeLogComparator()
*/
public List<ReleaseItem> getChangeLog(boolean full) {
SparseArray<ReleaseItem> masterChangelog = getMasterChangeLog(full);
SparseArray<ReleaseItem> changelog = getLocalizedChangeLog(full);
List<ReleaseItem> mergedChangeLog =
new ArrayList<ReleaseItem>(masterChangelog.size());
for (int i = 0, len = masterChangelog.size(); i < len; i++) {
int key = masterChangelog.keyAt(i);
// Use release information from localized change log and fall back to the master file
// if necessary.
ReleaseItem release = changelog.get(key, masterChangelog.get(key));
mergedChangeLog.add(release);
}
Collections.sort(mergedChangeLog, getChangeLogComparator());
return mergedChangeLog;
}
/**
* Read master change log from {@code xml/changelog_master.xml}
*
* @see #readChangeLogFromResource(int, boolean)
*/
protected SparseArray<ReleaseItem> getMasterChangeLog(boolean full) {
return readChangeLogFromResource(R.xml.changelog_master, full);
}
/**
* Read localized change log from {@code xml[-lang]/changelog.xml}
*
* @see #readChangeLogFromResource(int, boolean)
*/
protected SparseArray<ReleaseItem> getLocalizedChangeLog(boolean full) {
return readChangeLogFromResource(R.xml.changelog, full);
}
/**
* Read change log from XML resource file.
*
* @param resId
* Resource ID of the XML file to read the change log from.
* @param full
* If this is {@code true} the full change log is returned. Otherwise only changes for
* versions newer than the last version are returned.
*
* @return A {@code SparseArray} containing {@link ReleaseItem}s representing the (partial)
* change log.
*/
protected final SparseArray<ReleaseItem> readChangeLogFromResource(int resId, boolean full) {
XmlResourceParser xml = mContext.getResources().getXml(resId);
try {
return readChangeLog(xml, full);
} finally {
xml.close();
}
}
/**
* Read the change log from an XML file.
*
* @param xml
* The {@code XmlPullParser} instance used to read the change log.
* @param full
* If {@code true} the full change log is read. Otherwise only the changes since the
* last (saved) version are read.
*
* @return A {@code SparseArray} mapping the version codes to release information.
*/
protected SparseArray<ReleaseItem> readChangeLog(XmlPullParser xml, boolean full) {
SparseArray<ReleaseItem> result = new SparseArray<ReleaseItem>();
try {
int eventType = xml.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG && xml.getName().equals(ReleaseTag.NAME)) {
if (parseReleaseTag(xml, full, result)) {
// Stop reading more elements if this entry is not newer than the last
// version.
break;
}
}
eventType = xml.next();
}
} catch (XmlPullParserException e) {
Log.e(LOG_TAG, e.getMessage(), e);
} catch (IOException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return result;
}
/**
* Parse the {@code release} tag of a change log XML file.
*
* @param xml
* The {@code XmlPullParser} instance used to read the change log.
* @param full
* If {@code true} the contents of the {@code release} tag are always added to
* {@code changelog}. Otherwise only if the item's {@code versioncode} attribute is
* higher than the last version code.
* @param changelog
* The {@code SparseArray} to add a new {@link ReleaseItem} instance to.
*
* @return {@code true} if the {@code release} element is describing changes of a version older
* or equal to the last version. In that case {@code changelog} won't be modified and
* {@link #readChangeLog(XmlPullParser, boolean)} will stop reading more elements from
* the change log file.
*
* @throws XmlPullParserException
* @throws IOException
*/
private boolean parseReleaseTag(XmlPullParser xml, boolean full,
SparseArray<ReleaseItem> changelog) throws XmlPullParserException, IOException {
String version = xml.getAttributeValue(null, ReleaseTag.ATTRIBUTE_VERSION);
int versionCode;
try {
String versionCodeStr = xml.getAttributeValue(null, ReleaseTag.ATTRIBUTE_VERSION_CODE);
versionCode = Integer.parseInt(versionCodeStr);
} catch (NumberFormatException e) {
versionCode = NO_VERSION;
}
if (!full && versionCode <= mLastVersionCode) {
return true;
}
int eventType = xml.getEventType();
List<String> changes = new ArrayList<String>();
while (eventType != XmlPullParser.END_TAG || xml.getName().equals(ChangeTag.NAME)) {
if (eventType == XmlPullParser.START_TAG && xml.getName().equals(ChangeTag.NAME)) {
eventType = xml.next();
changes.add(xml.getText());
}
eventType = xml.next();
}
ReleaseItem release = new ReleaseItem(versionCode, version, changes);
changelog.put(versionCode, release);
return false;
}
/**
* Returns a {@link Comparator} that specifies the sort order of the {@link ReleaseItem}s.
*
* <p>
* The default implementation returns the items in reverse order (latest version first).
* </p>
*/
protected Comparator<ReleaseItem> getChangeLogComparator() {
return new Comparator<ReleaseItem>() {
@Override
public int compare(ReleaseItem lhs, ReleaseItem rhs) {
if (lhs.versionCode < rhs.versionCode) {
return 1;
} else if (lhs.versionCode > rhs.versionCode) {
return -1;
} else {
return 0;
}
}
};
}
/**
* Container used to store information about a release/version.
*/
public static class ReleaseItem {
/**
* Version code of the release.
*/
public final int versionCode;
/**
* Version name of the release.
*/
public final String versionName;
/**
* List of changes introduced with that release.
*/
public final List<String> changes;
ReleaseItem(int versionCode, String versionName, List<String> changes) {
this.versionCode = versionCode;
this.versionName = versionName;
this.changes = changes;
}
}
}
| 35.877389 | 124 | 0.622431 |
e10896da19638f2be8c6a455365d4a84fb9d0e79 | 12,912 | /* ###
* IP: GHIDRA
*
* 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 ghidra.app.plugin.core.navigation.locationreferences;
import static org.junit.Assert.*;
import java.util.*;
import javax.swing.table.TableColumnModel;
import org.junit.After;
import org.junit.Before;
import docking.ComponentProvider;
import docking.action.DockingActionIf;
import ghidra.app.actions.AbstractFindReferencesDataTypeAction;
import ghidra.app.cmd.data.CreateDataCmd;
import ghidra.app.cmd.refs.AddMemRefCmd;
import ghidra.app.events.ProgramLocationPluginEvent;
import ghidra.app.util.viewer.field.*;
import ghidra.app.util.viewer.listingpanel.ListingModel;
import ghidra.program.database.ProgramBuilder;
import ghidra.program.database.ProgramDB;
import ghidra.program.model.address.Address;
import ghidra.program.model.data.*;
import ghidra.program.model.data.DataUtilities.ClearDataMode;
import ghidra.program.model.listing.*;
import ghidra.program.model.symbol.RefType;
import ghidra.program.model.symbol.SourceType;
import ghidra.program.util.AddressFieldLocation;
import ghidra.program.util.FieldNameFieldLocation;
import ghidra.test.AbstractProgramBasedTest;
import ghidra.test.ClassicSampleX86ProgramBuilder;
import ghidra.util.Msg;
import ghidra.util.datastruct.Accumulator;
import ghidra.util.datastruct.ListAccumulator;
import ghidra.util.exception.CancelledException;
import ghidra.util.table.GhidraTable;
import ghidra.util.task.TaskMonitor;
/**
* A base class for use by tests that exercise various types of
* {@link LocationDescriptor}.
*/
public abstract class AbstractLocationReferencesTest extends AbstractProgramBasedTest {
protected DockingActionIf showReferencesAction;
protected ProgramBuilder builder;
protected LocationReferencesPlugin locationReferencesPlugin;
@Before
public void setUp() throws Exception {
initialize();
locationReferencesPlugin = getPlugin(tool, LocationReferencesPlugin.class);
showReferencesAction =
getAction(locationReferencesPlugin, AbstractFindReferencesDataTypeAction.NAME);
}
@Override
@After
public void tearDown() {
env.dispose();
}
@Override
protected Program getProgram() throws Exception {
builder = new ClassicSampleX86ProgramBuilder();
ProgramDB p = builder.getProgram();
configureProgram();
return p;
}
private void configureProgram() throws Exception {
//
// Xrefs
//
builder.createMemoryCallReference("0x0100446f", "0x01001004");
//
// Labels
//
builder.createMemoryReference("0x010036ee", "0x010039fe", RefType.CONDITIONAL_JUMP,
SourceType.USER_DEFINED);
//
// Arrays/Structures
//
DataType type = new IntegerDataType();
DataType pointer = new PointerDataType(type);
ArrayDataType array = new ArrayDataType(pointer, 4, pointer.getLength());
builder.applyDataType("0x01005500", array);
StructureDataType struct = new StructureDataType("struct_in_array", 0);
struct.add(new IntegerDataType(), "my_int", "comment 1");
struct.add(new ByteDataType(), "my_byte", "comment 2");
array = new ArrayDataType(struct, 4, struct.getLength());
builder.applyDataType("0x01005520", array);
struct = new StructureDataType("struct_containing_array", 0);
array = new ArrayDataType(pointer, 4, pointer.getLength());
struct.add(new ByteDataType(), "my_byte", "comment 1");
struct.add(array, "my_array", "comment 2");
builder.applyDataType("0x01005540", struct);
// a value that does not point to valid memory
builder.setBytes("0x01004480", "cc cc cc cc");
builder.applyDataType("0x01004480", new PointerDataType());
}
protected void goTo(Address a, String fieldName) {
int row = 0;
int col = 0;
assertTrue(codeBrowser.goToField(a, fieldName, row, col));
}
protected void goTo(Address a, String fieldName, int col) {
int row = 0;
assertTrue("Code Browser failed to go to " + a,
codeBrowser.goToField(a, fieldName, row, col));
}
protected void goTo(FieldNameFieldLocation fieldLocation) {
tool.firePluginEvent(new ProgramLocationPluginEvent("test", fieldLocation, program));
}
protected void goToDataNameFieldAt(Address a) {
openData(a);
goTo(a, FieldNameFieldFactory.FIELD_NAME);
}
protected void goToDataNameFieldAt(Address a, int... pathElements) {
doGoToDataNameFieldAt(a, pathElements);
}
private void doGoToDataNameFieldAt(Address a, int[] path) {
openData(a);
// note: the path here is
FieldNameFieldLocation location = new FieldNameFieldLocation(program, a, path, "name", 0);
ProgramLocationPluginEvent event =
new ProgramLocationPluginEvent("Test", location, program);
tool.firePluginEvent(event);
}
protected void goToDataAddressField(Address a) {
openData(a);
goTo(a, AddressFieldFactory.FIELD_NAME);
}
protected void goToDataAddressField(Address a, int row) {
openData(a);
AddressFieldLocation location =
new AddressFieldLocation(program, a, new int[] { row }, a.toString(), 0);
ProgramLocationPluginEvent event =
new ProgramLocationPluginEvent("Test", location, program);
tool.firePluginEvent(event);
}
protected void goToDataMnemonicField(Address a) {
openData(a);
goToMnemonicField(a);
}
protected void goToMnemonicField(Address a) {
goTo(a, MnemonicFieldFactory.FIELD_NAME);
}
protected void goToOperandField(Address a, int column) {
int row = 0;
assertTrue(codeBrowser.goToField(a, OperandFieldFactory.FIELD_NAME, row, column));
}
protected void goToOperandField(Address a) {
goTo(a, OperandFieldFactory.FIELD_NAME);
}
protected void openData(Address a) {
runSwing(() -> {
ListingModel listingModel = codeBrowser.getListingModel();
Listing listing = program.getListing();
Data parent = listing.getDataContaining(a);
assertNotNull(parent);
listingModel.openAllData(parent, TaskMonitor.DUMMY);
});
}
protected void openData(long address) {
openData(addr(address));
}
protected void waitForTable() {
LocationReferencesTableModel model = getTableModel();
if (model == null) {
return;
}
waitForTableModel(model);
}
protected GhidraTable getTable() {
LocationReferencesProvider provider = getResultsProvider();
if (provider == null) {
return null; // assume no provider was launched
}
Object referencesPanel = getInstanceField("referencesPanel", provider);
return (GhidraTable) getInstanceField("table", referencesPanel);
}
protected LocationReferencesTableModel getTableModel() {
LocationReferencesProvider provider = getResultsProvider();
if (provider == null) {
return null; // assume no provider was launched
}
Object referencesPanel = getInstanceField("referencesPanel", provider);
return (LocationReferencesTableModel) getInstanceField("tableModel", referencesPanel);
}
@SuppressWarnings("unchecked")
// we know the type is correct until the code changes
protected LocationReferencesProvider getResultsProvider() {
List<LocationReferencesProvider> providerList =
(List<LocationReferencesProvider>) getInstanceField("providerList",
locationReferencesPlugin);
if (providerList.size() == 0) {
return null;
}
return providerList.get(0);
}
protected List<LocationReference> getReferences(LocationDescriptor locationDescriptor) {
waitForTable();
Accumulator<LocationReference> accumulator = new ListAccumulator<>();
runSwing(() -> {
try {
locationDescriptor.getReferences(accumulator, TaskMonitor.DUMMY, false);
}
catch (CancelledException e) {
// can't happen!
}
});
List<LocationReference> list = new ArrayList<>(accumulator.get());
return list;
}
protected List<Address> getReferenceAddresses(LocationDescriptor locationDescriptor) {
List<Address> list = new ArrayList<>();
List<LocationReference> references = getReferences(locationDescriptor);
for (LocationReference locationReference : references) {
list.add(locationReference.getLocationOfUse());
}
return list;
}
protected void assertNoReference(List<LocationReference> list, Address... unexpected) {
for (Address addr : unexpected) {
for (LocationReference ref : list) {
if (ref.getLocationOfUse().equals(addr)) {
fail("Did expect address in list of references - unexpected " + addr +
"; found " + list);
}
}
}
}
protected void assertContains(List<LocationReference> list, Address... expected) {
if (list.size() != expected.length) {
fail("Expected\n\t" + Arrays.toString(expected) + "\n\tfound:\n\t" + list);
}
for (Address addr : expected) {
assertContainsAddr(list, addr);
}
}
protected boolean assertContainsAddr(List<LocationReference> list, Address addr) {
for (LocationReference ref : list) {
if (ref.getLocationOfUse().equals(addr)) {
return true;
}
}
fail("Did not find expected address in list of references - expected " + addr + "; found " +
list);
return false;
}
protected void assertNoResults(String msg) {
LocationReferencesProvider provider = getResultsProvider();
assertNull(msg, provider);
}
protected void assertHasResults(String msg) {
List<Address> referenceAddresses = getResultAddresses();
assertFalse(msg, referenceAddresses.isEmpty());
}
protected void assertResultCount(int expected) {
List<Address> referenceAddresses = getResultAddresses();
if (referenceAddresses.size() != expected) {
Msg.debug(this, "Result addresses found: " + referenceAddresses);
fail("Incorrect number of results; see console");
}
}
protected void assertResultCount(String msg, int expected) {
List<Address> referenceAddresses = getResultAddresses();
assertEquals(msg, expected, referenceAddresses.size());
}
protected List<LocationReference> getResultLocations() {
LocationReferencesProvider provider = getResultsProvider();
LocationDescriptor descriptor = provider.getLocationDescriptor();
List<LocationReference> references = getReferences(descriptor);
return references;
}
protected List<Address> getResultAddresses() {
LocationReferencesProvider provider = getResultsProvider();
LocationDescriptor descriptor = provider.getLocationDescriptor();
List<Address> addrs = getReferenceAddresses(descriptor);
return addrs;
}
protected String getContextColumnValue(LocationReference rowObject) {
LocationReferencesTableModel model = getTableModel();
GhidraTable table = getTable();
TableColumnModel columnModel = table.getColumnModel();
int col = columnModel.getColumnIndex("Context");
Object value = model.getColumnValueForRow(rowObject, col);
return value.toString();
}
protected void search() {
LocationReferencesProvider provider = getResultsProvider();
if (provider != null) {
// having a provider open implies we have already searched, which could cause
// follow-on searches to be lost when providers are tabbed.
closeProvider(provider);
}
performAction(showReferencesAction, getCodeViewerProvider(), true);
}
protected ComponentProvider getCodeViewerProvider() {
return codeBrowser.getProvider();
}
protected Data createData(Address a, DataType dt) {
int tx = program.startTransaction("Test");
try {
Data data =
DataUtilities.createData(program, a, dt, 1, false, ClearDataMode.CHECK_FOR_SPACE);
assertNotNull("Unable to apply data type at address: " + a, data);
return data;
}
catch (Exception e) {
failWithException("Unable to create data", e);
}
finally {
program.endTransaction(tx, true);
}
return null; // can't get here
}
protected DataType getDataType(String name) {
DataTypeManager dataTypeManager = program.getDataTypeManager();
Iterator<DataType> allDataTypes = dataTypeManager.getAllDataTypes();
DataType dataType = null;
while (allDataTypes.hasNext()) {
DataType currentDataType = allDataTypes.next();
if (currentDataType.getDisplayName().equals(name)) {
dataType = currentDataType;
break;
}
}
assertNotNull("Unable to locate a " + name + " DataType.", dataType);
return dataType;
}
protected void createReference(Address from, Address to) {
AddMemRefCmd addRefCommand =
new AddMemRefCmd(from, to, RefType.READ, SourceType.USER_DEFINED, 0);
boolean referenceAdded = applyCmd(program, addRefCommand);
assertTrue("Unable to add reference to: " + to, referenceAdded);
}
protected void createByte(long address) {
Address a = addr(address);
CreateDataCmd cmd = new CreateDataCmd(a, new ByteDataType());
assertTrue(applyCmd(program, cmd));
}
}
| 30.597156 | 94 | 0.74938 |
dc741c71e6cdac2178da4c23c7e33307bada5473 | 357 | package de.djuelg.neuronizer.domain.interactors.note;
import de.djuelg.neuronizer.domain.interactors.base.Interactor;
import de.djuelg.neuronizer.domain.model.preview.Note;
/**
* Created by djuelg on 10.07.17.
*/
public interface EditNoteBodyInteractor extends Interactor {
interface Callback {
void onNoteUpdated(Note updatedNote);
}
} | 25.5 | 63 | 0.764706 |
c7074138c673926cd0f9b6e5347e946db34cb845 | 1,778 | package com.aphysia.offer;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Solution36 {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
// 只要有一个为空,就不存在共同节点
if (pHead1 == null || pHead2 == null) {
return null;
}
ListNode head1 = pHead1;
ListNode head2 = pHead2;
while (head1 != null && head2 != null) {
if (head1 == head2) {
return head1;
} else {
// 如果下一个节点为空,则切换到另一个链表的头节点,否则下一个节点
head1 = head1.next == null ? pHead2 : head1.next;
head2 = head2.next == null ? pHead1 : head2.next;
}
}
return null;
}
public ListNode FindFirstCommonNode2(ListNode pHead1, ListNode pHead2) {
//创建集合set
Set<ListNode> set = new HashSet<>();
while (pHead1 != null) {
set.add(pHead1);
pHead1 = pHead1.next;
}
while (pHead2 != null) {
if (set.contains(pHead2))
return pHead2;
pHead2 = pHead2.next;
}
return null;
}
public ListNode FindFirstCommonNode3(ListNode pHead1, ListNode pHead2) {
// 只要有一个为空,就不存在共同节点
if (pHead1 == null || pHead2 == null) {
return null;
}
ListNode head1 = pHead1;
ListNode head2 = pHead2;
while (head1 != head2) {
// 如果下一个节点为空,则切换到另一个链表的头节点,否则下一个节点
head1 = (head1 == null) ? pHead2 : head1.next;
head2 = (head2 == null) ? pHead1 : head2.next;
}
return head1;
}
}
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
| 25.4 | 76 | 0.521372 |
2acbd0d28e3b67966303aa2f68e5cd3da441b907 | 1,942 | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.internal.ui.views.attributes.page;
import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.ExpressionPropertyDescriptorProvider;
import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.IDescriptorProvider;
import org.eclipse.birt.report.designer.internal.ui.views.attributes.section.ExpressionSection;
import org.eclipse.birt.report.model.api.TextDataHandle;
import org.eclipse.birt.report.model.api.elements.ReportDesignConstants;
import org.eclipse.swt.widgets.Composite;
/**
* Attribute page for data item expression property.
*/
public class ExpressionPage extends AttributePage
{
public void buildUI( Composite parent )
{
super.buildUI( parent );
container.setLayout( WidgetUtil.createGridLayout( 1 ,15) );
// Defines provider.
IDescriptorProvider expressionProvider = new ExpressionPropertyDescriptorProvider( TextDataHandle.VALUE_EXPR_PROP,
ReportDesignConstants.TEXT_DATA_ITEM );
// Defines section.
ExpressionSection expressionSection = new ExpressionSection( expressionProvider.getDisplayName( ),
container,
true );
expressionSection.setProvider( expressionProvider );
expressionSection.setWidth( 500 );
// Adds section into this page.
addSection( PageSectionId.EXPRESSION_VALUE_EXPR, expressionSection ); //$NON-NLS-1$
createSections( );
layoutSections( );
}
}
| 35.309091 | 116 | 0.725026 |
2f3cacde36d433a9f1a32ff1e599bf8e12d5cf30 | 1,248 | package TP3_RMI.DegreDeux;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class DegreImpl extends UnicastRemoteObject implements DegreInterface {
public DegreImpl() throws RemoteException {
super();
}
@Override
public String degre2(int a, int b, int c) throws RemoteException {
// tant que a est nul, demander une valeur a l'utilisateur
if (a == 0) {
//System.out.println("Erreur ! Entrez une valeur non nulle pour a.");
return ("Erreur ! Entrez une valeur non nulle pour a.");
}
double delta = b * b - 4 * a * c;
if (delta < 0) {
//System.out.println("Pas de solutions reelles");
return ("Pas de solutions reelles");
} else if (delta > 0) {
//System.out.println("Deux solutions : " + (-b - Math.sqrt(delta)) / (2.0 * a) + " et " + (-b + Math.sqrt(delta)) / (2.0 * a));
return ("Deux solutions : " + -(-b - Math.sqrt(delta)) / (2.0 * a) + " et " + -(-b + Math.sqrt(delta)) / (2.0 * a));
} else {
//System.out.println("Une solution unique : " + -b / (2.0 * a));
return ("Une solution unique : " + -b / (2.0 * a));
}
}
} | 39 | 139 | 0.548878 |
f69b5916f900a7f9b20efd3dc06abdbc3caf7829 | 9,901 | /*
* Copyright 2014 Tagbangers, 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.wallride.web.controller.admin.article;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.wallride.domain.CustomField;
import org.wallride.service.CustomFieldService;
import org.wallride.domain.Article;
import org.wallride.domain.Category;
import org.wallride.exception.DuplicateCodeException;
import org.wallride.exception.EmptyCodeException;
import org.wallride.model.TreeNode;
import org.wallride.service.ArticleService;
import org.wallride.support.AuthorizedUser;
import org.wallride.support.CategoryUtils;
import org.wallride.web.support.DomainObjectSavedModel;
import org.wallride.web.support.HttpNotFoundException;
import org.wallride.web.support.RestValidationErrorModel;
import javax.inject.Inject;
import javax.validation.groups.Default;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
@Controller
@RequestMapping("/{language}/articles/edit")
public class ArticleEditController {
private static Logger logger = LoggerFactory.getLogger(ArticleEditController.class);
@Inject
private ArticleService articleService;
@Inject
private CustomFieldService customFieldService;
@Inject
private CategoryUtils categoryUtils;
@Inject
private MessageSourceAccessor messageSourceAccessor;
@ModelAttribute("article")
public Article setupArticle(@RequestParam long id) {
return articleService.getArticleById(id);
}
@ModelAttribute("categoryNodes")
public List<TreeNode<Category>> setupCategoryNodes(@PathVariable String language) {
return categoryUtils.getNodes(true);
}
@ModelAttribute("query")
public String query(@RequestParam(required = false) String query) {
return query;
}
@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public @ResponseBody
RestValidationErrorModel bindException(BindException e) {
logger.debug("BindException", e);
return RestValidationErrorModel.fromBindingResult(e.getBindingResult(), messageSourceAccessor);
}
@RequestMapping(method=RequestMethod.GET)
public String edit(
@PathVariable String language,
@RequestParam long id,
Model model,
RedirectAttributes redirectAttributes) {
Article article = (Article) model.asMap().get("article");
if (article == null) {
throw new HttpNotFoundException();
}
if (!article.getLanguage().equals(language)) {
Article target = articleService.getArticleByCode(article.getCode(), language);
if (target != null) {
redirectAttributes.addAttribute("id", target.getId());
return "redirect:/_admin/{language}/articles/edit?id={id}";
} else {
redirectAttributes.addFlashAttribute("original", article);
redirectAttributes.addAttribute("code", article.getCode());
return "redirect:/_admin/{language}/articles/create?code={code}";
}
}
Set<CustomField> customFields = customFieldService.getAllCustomFields(language);
ArticleEditForm form = ArticleEditForm.fromDomainObject(article, customFields);
model.addAttribute("form", form);
Article draft = articleService.getDraftById(id);
model.addAttribute("draft", draft);
return "article/edit";
}
@RequestMapping(method=RequestMethod.GET, params="draft")
public String editDraft(
@PathVariable String language,
@RequestParam long id,
String query,
Model model,
RedirectAttributes redirectAttributes) {
Article article = (Article) model.asMap().get("article");
if (!language.equals(article.getLanguage())) {
redirectAttributes.addAttribute("language", language);
redirectAttributes.addAttribute("query", query);
return "redirect:/_admin/{language}/articles/index";
}
Article draft = articleService.getDraftById(id);
if (draft == null) {
redirectAttributes.addAttribute("language", language);
redirectAttributes.addAttribute("id", id);
redirectAttributes.addAttribute("query", query);
return "redirect:/_admin/{language}/articles/edit";
}
SortedSet<CustomField> customFields = customFieldService.getAllCustomFields(language);
ArticleEditForm form = ArticleEditForm.fromDomainObject(draft, customFields);
model.addAttribute("form", form);
return "article/edit";
}
@RequestMapping(method=RequestMethod.POST, params="draft")
public @ResponseBody DomainObjectSavedModel<?> saveAsDraft(
@PathVariable String language,
@Validated @ModelAttribute("form") ArticleEditForm form,
BindingResult errors,
Model model,
AuthorizedUser authorizedUser)
throws BindException {
if (errors.hasErrors()) {
for (ObjectError error : errors.getAllErrors()) {
if (!"validation.NotNull".equals(error.getCode())) {
throw new BindException(errors);
}
}
}
Article article = (Article) model.asMap().get("article");
try {
articleService.saveArticleAsDraft(form.buildArticleUpdateRequest(), authorizedUser);
}
catch (EmptyCodeException e) {
errors.rejectValue("code", "NotNull");
}
catch (DuplicateCodeException e) {
errors.rejectValue("code", "NotDuplicate");
}
if (errors.hasErrors()) {
logger.debug("Errors: {}", errors);
throw new BindException(errors);
}
return new DomainObjectSavedModel<>(article);
}
@RequestMapping(method=RequestMethod.POST, params="publish")
public String saveAsPublished(
@PathVariable String language,
@Validated({Default.class, ArticleEditForm.GroupPublish.class}) @ModelAttribute("form") ArticleEditForm form,
BindingResult errors,
String query,
AuthorizedUser authorizedUser,
RedirectAttributes redirectAttributes) {
if (errors.hasErrors()) {
return "article/edit";
}
Article article = null;
try {
article = articleService.saveArticleAsPublished(form.buildArticleUpdateRequest(), authorizedUser);
}
catch (EmptyCodeException e) {
errors.rejectValue("code", "NotNull");
}
catch (DuplicateCodeException e) {
errors.rejectValue("code", "NotDuplicate");
}
if (errors.hasErrors()) {
logger.debug("Errors: {}", errors);
return "article/edit";
}
redirectAttributes.addFlashAttribute("savedArticle", article);
redirectAttributes.addAttribute("language", language);
redirectAttributes.addAttribute("id", article.getId());
redirectAttributes.addAttribute("query", query);
return "redirect:/_admin/{language}/articles/describe";
}
@RequestMapping(method=RequestMethod.POST, params="unpublish")
public String saveAsUnpublished(
@PathVariable String language,
@Validated({Default.class, ArticleEditForm.GroupPublish.class}) @ModelAttribute("form") ArticleEditForm form,
BindingResult errors,
String query,
AuthorizedUser authorizedUser,
RedirectAttributes redirectAttributes) {
if (errors.hasErrors()) {
return "article/edit";
}
Article article = null;
try {
article = articleService.saveArticleAsUnpublished(form.buildArticleUpdateRequest(), authorizedUser);
}
catch (EmptyCodeException e) {
errors.rejectValue("code", "NotNull");
}
catch (DuplicateCodeException e) {
errors.rejectValue("code", "NotDuplicate");
}
if (errors.hasErrors()) {
logger.debug("Errors: {}", errors);
return "article/edit";
}
redirectAttributes.addFlashAttribute("savedArticle", article);
redirectAttributes.addAttribute("language", language);
redirectAttributes.addAttribute("id", article.getId());
redirectAttributes.addAttribute("query", query);
return "redirect:/_admin/{language}/articles/describe";
}
@RequestMapping(method=RequestMethod.POST, params="update")
public String update(
@PathVariable String language,
@Validated({Default.class, ArticleEditForm.GroupPublish.class}) @ModelAttribute("form") ArticleEditForm form,
BindingResult errors,
String query,
AuthorizedUser authorizedUser,
RedirectAttributes redirectAttributes) {
if (errors.hasErrors()) {
return "article/edit";
}
Article article = null;
try {
article = articleService.saveArticle(form.buildArticleUpdateRequest(), authorizedUser);
}
catch (EmptyCodeException e) {
errors.rejectValue("code", "NotNull");
}
catch (DuplicateCodeException e) {
errors.rejectValue("code", "NotDuplicate");
}
if (errors.hasErrors()) {
logger.debug("Errors: {}", errors);
return "article/edit";
}
redirectAttributes.addFlashAttribute("savedArticle", article);
redirectAttributes.addAttribute("language", language);
redirectAttributes.addAttribute("id", article.getId());
redirectAttributes.addAttribute("query", query);
return "redirect:/_admin/{language}/articles/describe";
}
// @RequestMapping(method=RequestMethod.POST, params="cancel")
// public String cancel(
// @Valid @ModelAttribute("form") ArticleEditForm form,
// RedirectAttributes redirectAttributes) {
// redirectAttributes.addAttribute("id", form.getId());
// return "redirect:/_admin/articles/describe/{id}";
// }
} | 33.449324 | 112 | 0.758004 |
8621b59b42dee64727f9ab4701f8615b481a8468 | 8,294 | package com.cvicse.controller;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author
* @date
*/
@RestController
@RequestMapping("flowable")
public class TestController {
@Autowired
private RuntimeService runtimeService;
@Autowired
private TaskService taskService;
@Autowired
private HistoryService historyService;
@Autowired
private RepositoryService repositoryService;
@Autowired
private ProcessEngine processEngine;
/**
* 创建流程
*
* @param userId
* @param days
* @param reason
* @return
*/
@GetMapping("add")
public String addExpense(String userId, String days, String reason) {
Map<String, Object> map = new HashMap<>();
map.put("employee", userId);
map.put("nrOfHolidays", days);
map.put("description", reason);
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("holidayRequest", map);
return "提交成功,流程ID为:" + processInstance.getId();
}
/**
* 获取指定用户组流程任务列表
*
* @param group
* @return
*/
@GetMapping("list")
public Object list(String group) {
List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup(group).list();
return tasks.toString();
}
/**
* 通过/拒绝任务
*
* @param taskId
* @param approved 1 :true 2:false
* @return
*/
@GetMapping("apply")
public String apply(String taskId, String approved) {
Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
if (task == null) {
return "流程不存在";
}
Map<String, Object> variables = new HashMap<>();
Boolean apply = approved.equals("1") ? true : false;
variables.put("approved", apply);
taskService.complete(taskId, variables);
return "审批是否通过:" + approved;
}
/**
* 查看历史流程记录
*
* @param processInstanceId
* @return
*/
@GetMapping("historyList")
public Object getHistoryList(String processInstanceId) {
List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery()
.processInstanceId(processInstanceId)
.finished()
.orderByHistoricActivityInstanceEndTime().asc().list();
return historicActivityInstances;
}
/**
* 驳回流程实例
*
* @param taskId
* @param targetTaskKey
* @return
*/
@GetMapping("rollbask")
public String rollbaskTask(String taskId, String targetTaskKey) {
Task currentTask = taskService.createTaskQuery().taskId(taskId).singleResult();
if (currentTask == null) {
return "节点不存在";
}
List<String> key = new ArrayList<>();
key.add(currentTask.getTaskDefinitionKey());
runtimeService.createChangeActivityStateBuilder()
.processInstanceId(currentTask.getProcessInstanceId())
.moveActivityIdsToSingleActivityId(key, targetTaskKey)
.changeState();
return "驳回成功...";
}
/**
* 终止流程实例
*
* @param processInstanceId
*/
public String deleteProcessInstanceById(String processInstanceId) {
// ""这个参数本来可以写删除原因
runtimeService.deleteProcessInstance(processInstanceId, "");
return "终止流程实例成功";
}
/**
* 挂起流程实例
*
* @param processInstanceId 当前流程实例id
*/
@GetMapping("hangUp")
public String handUpProcessInstance(String processInstanceId) {
runtimeService.suspendProcessInstanceById(processInstanceId);
return "挂起流程成功...";
}
/**
* 恢复(唤醒)被挂起的流程实例
*
* @param processInstanceId 流程实例id
*/
@GetMapping("recovery")
public String activateProcessInstance(String processInstanceId) {
runtimeService.activateProcessInstanceById(processInstanceId);
return "恢复流程成功...";
}
/**
* 判断传入流程实例在运行中是否存在
*
* @param processInstanceId
* @return
*/
@GetMapping("isExist/running")
public Boolean isExistProcIntRunning(String processInstanceId) {
ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
.processInstanceId(processInstanceId)
.singleResult();
if (processInstance == null) {
return false;
}
return true;
}
/**
* 判断流程实例在历史记录中是否存在
* @param processInstanceId
* @return
*/
@GetMapping("isExist/history")
public Boolean isExistProcInHistory(String processInstanceId) {
HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
.processInstanceId(processInstanceId)
.singleResult();
if (historicProcessInstance == null) {
return false;
}
return true;
}
/**
* 我发起的流程实例列表
*
* @param userId
* @return 流程实例列表
*/
@GetMapping("myTasks")
public List<HistoricProcessInstance> getMyStartProcint(String userId) {
List<HistoricProcessInstance> list = historyService
.createHistoricProcessInstanceQuery()
.startedBy(userId)
.orderByProcessInstanceStartTime()
.asc()
.list();
return list;
}
/**
* 查询流程图
*
* @param httpServletResponse
* @param processId
* @throws Exception
*/
@RequestMapping(value = "processDiagram")
public void genProcessDiagram(HttpServletResponse httpServletResponse, String processId) throws Exception {
ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
//流程走完的不显示图
if (pi == null) {
return;
}
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
//使用流程实例ID,查询正在执行的执行对象表,返回流程实例对象
String InstanceId = task.getProcessInstanceId();
List<Execution> executions = runtimeService
.createExecutionQuery()
.processInstanceId(InstanceId)
.list();
//得到正在执行的Activity的Id
List<String> activityIds = new ArrayList<>();
List<String> flows = new ArrayList<>();
for (Execution exe : executions) {
List<String> ids = runtimeService.getActiveActivityIds(exe.getId());
activityIds.addAll(ids);
}
//获取流程图
BpmnModel bpmnModel = repositoryService.getBpmnModel(pi.getProcessDefinitionId());
ProcessEngineConfiguration engconf = processEngine.getProcessEngineConfiguration();
ProcessDiagramGenerator diagramGenerator = engconf.getProcessDiagramGenerator();
InputStream in = diagramGenerator.generateDiagram(bpmnModel, "png", activityIds, flows, engconf.getActivityFontName(),
engconf.getLabelFontName(), engconf.getAnnotationFontName(), engconf.getClassLoader(), 1.0,true);
OutputStream out = null;
byte[] buf = new byte[1024];
int legth = 0;
try {
out = httpServletResponse.getOutputStream();
while ((legth = in.read(buf)) != -1) {
out.write(buf, 0, legth);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
| 29.727599 | 126 | 0.631903 |
00d0fec867a6be914212d7206b90286511860c36 | 8,020 | package com.example.pltermproject;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import org.w3c.dom.Document;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class InboxList extends AppCompatActivity {
ListView listView;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
ArrayList<HashMap<String,String>> messages = new ArrayList<HashMap<String,String>>();
ArrayAdapter arrayAdapter;
String userType, temp, receiverSubject;
String [] datesArray = new String[10];
final List<String[]> messageList = new LinkedList<String[]>();
HashMap<String, String> keyMap = new HashMap<>();
Button newMessageButton, sentMessagesButton;
List<HashMap<String,String>> realListItems = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inbox_list);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
listView = findViewById(R.id.inbox_list);
newMessageButton = findViewById(R.id.new_message_button);
sentMessagesButton = findViewById(R.id.sent_messages_button);
getSupportActionBar().setTitle("Your Inbox");
final Bundle bundle = getIntent().getExtras();
if (bundle != null){
userType = bundle.getString("UserType");
}
final Intent intent = new Intent(InboxList.this, MessageReply.class);
final List<HashMap<String,String>> listItems = new ArrayList<>();
final SimpleAdapter adapter = new SimpleAdapter(InboxList.this, realListItems, android.R.layout.simple_list_item_2, new String[]{"First Line", "Second Line"}, new int []{android.R.id.text1, android.R.id.text2});
CollectionReference questionRef = fStore.collection("messages");
questionRef.whereEqualTo("receiver", fAuth.getCurrentUser().getUid()).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull final Task<QuerySnapshot> task) {
if(task.isSuccessful()){
QuerySnapshot qSnap = task.getResult();
final Stack[] stack = {new Stack(task.getResult().getDocuments().size())};
final HashMap<String,String> datesMap = new HashMap<>();
if(!qSnap.isEmpty()){
for (DocumentSnapshot doc: task.getResult().getDocuments() ) {
stack[0].push(doc.get("date"));
receiverSubject = doc.get("senderName") + " - " + doc.get("subject");
datesMap.put(doc.get("date").toString(), receiverSubject);
}
for (int i = 0; i < task.getResult().getDocuments().size(); i++){
DocumentReference docRef = fStore.collection("users").document(task.getResult().getDocuments().get(i).get("sender").toString());
final int finalI = i;
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task2) {
if(task2.isSuccessful()){
DocumentSnapshot document = task2.getResult();
temp = document.get("name").toString() + " - " + task.getResult().getDocuments().get(finalI).get("subject").toString();
intent.putExtra("sender",document.get("name").toString());
keyMap.put(temp, task.getResult().getDocuments().get(finalI).getId());
//Log.d("key:", keyMap.get(temp));
ArrayList<String> keys= new ArrayList<>();
ArrayList<String> values= new ArrayList<>();
for (String key : keyMap.keySet()) {
keys.add(key);
Log.d("TAG", "KEY: " + key);
values.add(keyMap.get(key));
}
intent.putExtra("keys", keys);
intent.putExtra("values", values);
}
}
});
}
}
try {
stack[0] = stack[0].sortstack(stack[0]);
while (!stack[0].isEmpty())
{
HashMap<String,String> newMap = new HashMap<>();
newMap.put("First Line", datesMap.get(stack[0].peek().toString()));
newMap.put("Second Line", stack[0].peek().toString());
realListItems.add(newMap);
stack[0].pop();
}
listView.setAdapter(adapter);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
intent.putExtra("selectedItem", listView.getItemAtPosition(position).toString());
intent.putExtra("UserType", userType);
intent.putExtra("fromId", "1111");
finish();
startActivity(intent);
}
});
newMessageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Intent intent2 = new Intent(InboxList.this,UsersList.class);
intent2.putExtra("UserType", userType);
finish();
startActivity(intent2);
}
});
sentMessagesButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Intent intent2 = new Intent(InboxList.this, SentMessages.class);
intent2.putExtra("UserType", userType);
finish();
startActivity(intent2);
}
});
}
public boolean onSupportNavigateUp(){
if(userType.equals("student")){
final Intent intent2 = new Intent(InboxList.this,Student.class);
finish();
startActivity(intent2);
}
else if(userType.equals("teacher")){
final Intent intent2 = new Intent(InboxList.this,Teacher.class);
finish();
startActivity(intent2);
}
return true;
}
}
| 45.568182 | 219 | 0.552743 |
820b19fc66600d0c6f967ccdffa319d19b872793 | 1,850 | /*
*
* 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.comcast.cdn.traffic_control.traffic_monitor.data;
public class DataSummary implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private long startTime;
private long endTime;
private double average;
private double high;
private double low;
private double start;
private double end;
private int dpCount;
public DataSummary() {
}
public void accumulate(final DataPoint dp, final long t) {
final double v = Double.parseDouble(dp.getValue());
if(dpCount == 0) {
startTime = t;
endTime = t;
high = v;
low = v;
start = v;
end = v;
average = v;
} else {
if(t > endTime) {
endTime = t;
} else if(t < startTime) {
startTime = t;
}
if(v > high) {
high = v;
} else if(v < low) {
low = v;
}
// a = a' + (v-a')/(c'+1)
end = v;
average = average + (v-average)/(dpCount+1);
}
dpCount++;
}
public long getStartTime() {
return startTime;
}
public long getEndTime() {
return endTime;
}
public double getAverage() {
return average;
}
public double getHigh() {
return high;
}
public double getLow() {
return low;
}
public int getDpCount() {
return dpCount;
}
public double getStart() {
return start;
}
public double getEnd() {
return end;
}
}
| 22.560976 | 75 | 0.665405 |
2ac3e849d1a7b88e46949c16105779d61dc38285 | 943 | package xyz.brassgoggledcoders.steamagerevolution.multiblocks.crucible.blocks;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import xyz.brassgoggledcoders.steamagerevolution.machinesystem.multiblock.BlockMultiblockBase;
import xyz.brassgoggledcoders.steamagerevolution.multiblocks.crucible.tileentities.TileEntityCrucibleHeatInput;
public class BlockCrucibleHeatInput extends BlockMultiblockBase<TileEntityCrucibleHeatInput> {
public BlockCrucibleHeatInput(Material material, String name) {
super(material, name);
}
@Override
public Class<? extends TileEntity> getTileEntityClass() {
return TileEntityCrucibleHeatInput.class;
}
@Override
public TileEntity createTileEntity(World world, IBlockState blockState) {
return new TileEntityCrucibleHeatInput();
}
}
| 36.269231 | 111 | 0.806999 |
ce9630e60891c7dbdb53bed5d698139b95e5dcbd | 859 | package com.nsabina.samples.oneclickshare.javafx;
public class Workflow {
private String workflowId;
private String nextStepUrl;
private String progressCheckUrl;
public Workflow(Object context) {
this.context = context;
}
private Object context;
public Object getContext() {
return context;
}
public void setContext(Object context) {
this.context = context;
}
public String getWorkflowId() {
return workflowId;
}
public void setWorkflowId(String workflowId) {
this.workflowId = workflowId;
}
public String getNextStepUrl() {
return nextStepUrl;
}
public void setNextStepUrl(String nextStepUrl) {
this.nextStepUrl = nextStepUrl;
}
public String getProgressCheckUrl() {
return progressCheckUrl;
}
public void setProgressCheckUrl(String progressCheckUrl) {
this.progressCheckUrl = progressCheckUrl;
}
}
| 17.895833 | 59 | 0.748545 |
62d031f0e0796f640382a13c84c3721ce7142a71 | 700 | package com.calatrava.bridge;
import java.io.IOException;
public class KernelBridge {
private AssetRepository assetRepository;
private RhinoService rhinoService;
public KernelBridge(AssetRepository assetRepository, RhinoService rhinoService) throws IOException {
this.assetRepository = assetRepository;
this.rhinoService = rhinoService;
//load js libraries
loadLibrary("calatrava/scripts/underscore.js");
//load bridge
loadLibrary("calatrava/scripts/env.js");
loadLibrary("calatrava/scripts/bridge.js");
}
public void loadLibrary(String libraryName) throws IOException {
rhinoService.load(assetRepository.assetReader(libraryName), libraryName);
}
}
| 26.923077 | 102 | 0.771429 |
8a239494a7c4c8f43057abdb475cd9b7b5910ffc | 1,933 | package org.rooms;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import org.BackgroundSystem.Background;
import org.enemies.*;
import org.resources.*;
import org.walls.*;
public class EarthRoom1 extends Room {
public static final BufferedImage cave1 = ImagePack.getImage("backgrounds/caveback.png");
public static final BufferedImage cave2 = ImagePack.getImage("backgrounds/caveback2.png");
public void load() {
HEIGHT = 600;
WIDTH = 800;
spriteX = 10;
spriteY = 300 - 38;
cameraX = 225;
cameraY = 225;
visibleHEIGHT = 500;
visibleWIDTH = 500;
startLeft = false;
walls = new ThreadList<Wall>(Arrays.asList(new Wall[]{new Wall(0, 0, 0, HEIGHT), new Wall(0, 0, WIDTH, 0),
new Wall(0, HEIGHT, WIDTH, HEIGHT), new Wall(WIDTH, 0, 0, HEIGHT),}));
walls.add(new VerticalRockWall(-1, 0, HEIGHT - 300 - 70));
walls.add(new VerticalRockWall(-1, HEIGHT - 300, 300));
walls.add(new VerticalRockWall(WIDTH - 9, 0, HEIGHT - 300 - 70));
walls.add(new VerticalRockWall(WIDTH - 9, HEIGHT - 299, 300));
walls.add(new VerticalRockWall(300, 200, 400));
walls.add(new CaveDoor(0, 300 - 80));
exit = new CaveExit(WIDTH - 40, HEIGHT - 80 - 300);
walls.add(new RockPlatform(0, 300, 5));
walls.add(new RockPlatform(WIDTH - 110, 300, 5));
walls.add(new RockPlatform(80, 250, 5));
walls.add(new RockPlatform(160, 200, 5));
for (int i = 0; i < 4; i++) {
walls.add(new RockPlatform(310 - 50 - 20 * i, 300 + 75 * i, 4 + 2 * i));
}
walls.add(new RockPlatform(490, 450, 5));
walls.add(new RockPlatform(590, 375, 5));
background = new Background();
background.fillBack(new Color(68, 37, 18));
background.tessellateOnBottom(cave1);
background.tessellateOnTop(cave2);
background.addAll(walls);
enemies.add(new Voggie(100, 500));
enemies.add(new Voggie(150, 500));
enemies.add(new Slurg(400, 600 - 30));
enemies.add(new Eagle(600, 50));
}
}
| 31.688525 | 108 | 0.681324 |
51057372d30c655079843b9a6f5553fc5ff01239 | 1,726 | package com.book.service;
import com.book.dao.BookDao;
import com.book.domain.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
@Service
public class BookService {
private BookDao bookDao;
@Autowired
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
public ArrayList<Book> queryBook(String searchWord){
return bookDao.queryBook(searchWord);
}
public Book getOneBook(long bookId){
return bookDao.getBook(bookId);
}
public ArrayList<Book> getAllBooks(){
return bookDao.getAllBooks();
}
public int deleteBook(long bookId){
return bookDao.deleteBook(bookId);
}
public boolean matchBook(String searchWord){
return bookDao.matchBook(searchWord)>0;
}
public boolean addBook(Book book){
return bookDao.addBook(book)>0;
}
public Book getBook(Long bookId){
Book book=bookDao.getBook(bookId);
return book;
}
public boolean editBook(Book book){
return bookDao.editBook(book)>0;
}
//从date类型的数据中提取出年月日
public boolean parseDate(Book book){
//从birth字段中单独提取出年月日的信息
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
String dateStr = sdf.format(book.getPubdate());
String[] dateList = dateStr.split("-");
String year = dateList[0];
String month = dateList[1];
String day = dateList[2];
// System.out.println(year+" "+month+" "+day);
book.setYear(year);
book.setMonth(month);
book.setDay(day);
return true;
};
}
| 25.382353 | 64 | 0.654693 |
81877e8d8d001d49185d02213265b7a30926cb7d | 2,223 | package org.andrejs.cassandra;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.exceptions.ReadTimeoutException;
import com.datastax.driver.core.exceptions.WriteTimeoutException;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import static org.andrejs.cassandra.CassandraSpy.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class CassandraSpyTest {
@ClassRule
public static CassandraSpy cassandra = new CassandraSpy();
private App app = new App(cassandra.getHost(), cassandra.getPort());
@Before
public void startApp() {
app.start();
}
@Test(expected = WriteTimeoutException.class)
public void whenInsertPrimedThenThrowsExceptionOnAdd() throws Exception {
cassandra.when(inserts("users")).willThrow(writeTimeout());
app.addUser(1, "user1");
}
@Test(expected = WriteTimeoutException.class)
public void whenInsertWithValuesPrimedThenThrowsExceptionOnAdd() throws Exception {
cassandra.when(inserts("users", 1, "user1")).willThrow(writeTimeout());
app.addUser(1, "user1");
}
@Test
public void whenInsertPrimedWithOtherValesThenDoesNotThrow() throws Exception {
cassandra.when(inserts("users", 2, "user2")).willThrow(writeTimeout());
app.addUser(1, "user1");
}
@Test(expected = ReadTimeoutException.class)
public void whenSelectPrimedThenThrowsExceptionOnGet() throws Exception {
cassandra.when(selects("users")).willThrow(readTimeout());
app.getUser(1);
}
@Test
public void whenResetThenNoLongerThrowsException() {
cassandra.when(inserts("users")).willThrow(writeTimeout());
cassandra.when(selects("users")).willThrow(readTimeout());
cassandra.resetSpy();
app.addUser(2, "user2");
assertEquals("user2", app.getUser(2).get());
}
@Test
public void whenSessionCreatedThenSessionIsOpen() throws Exception {
Session session = cassandra.getSession();
assertFalse(session.isClosed());
}
@After
public void reset() {
cassandra.resetSpy();
}
}
| 28.5 | 87 | 0.698156 |
56d9345462dc103f3545c5af5a3022462635db5f | 659 | package com.flowerfat.initapp.ui.history;
import dagger.Module;
import dagger.Provides;
/**
* Created by clevo on 2015/6/10.
*/
@Module
public class TourDayActivityModule {
private final TourDayContract.View mTourDayView;
private final TourDayModel mTourDayModel;
public TourDayActivityModule(TourDayContract.View tourDayView, TourDayModel tourDayModel) {
this.mTourDayView = tourDayView;
this.mTourDayModel = tourDayModel;
}
@Provides
TourDayContract.View provideTourDayView() {
return mTourDayView;
}
@Provides
TourDayModel provideTourDayModel() {
return mTourDayModel;
}
}
| 19.969697 | 95 | 0.716237 |
11757608a002650c882073d555ba4eb1662e870b | 492 | package com.kenshoo.pl.audit.commands;
import com.kenshoo.pl.entity.CreateEntityCommand;
import com.kenshoo.pl.entity.EntityCommandExt;
import com.kenshoo.pl.entity.internal.audit.entitytypes.ExclusiveAuditedType;
public class CreateExclusiveAuditedCommand extends CreateEntityCommand<ExclusiveAuditedType> implements EntityCommandExt<ExclusiveAuditedType, CreateExclusiveAuditedCommand> {
public CreateExclusiveAuditedCommand() {
super(ExclusiveAuditedType.INSTANCE);
}
}
| 37.846154 | 175 | 0.837398 |
707df173aaf04ae65c4ad87800471961f8de9e73 | 112 | package com.example.design.principle.dependenceinversion;
public interface ICourse {
void studyCourse();
}
| 18.666667 | 57 | 0.785714 |
96d780a43bc9cf32918ce7a2c03634c80f2d292f | 2,998 | /*******************************************************************************
* Copyright (c) 2012 Mrbrutal. All rights reserved.
*
* @name TrainCraft
* @author Mrbrutal
******************************************************************************/
package src.train.common.blocks;
import static net.minecraftforge.common.ForgeDirection.UP;
import java.util.ArrayList;
import mods.railcraft.api.tracks.ITrackInstance;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Icon;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import src.train.common.Traincraft;
import src.train.common.library.BlockIDs;
import src.train.common.library.Info;
import src.train.common.tile.TileStopper;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class BlockStopper extends BlockContainer {
private Icon texture;
public BlockStopper(int par1, int par2) {
super(par1, Material.iron);
setCreativeTab(Traincraft.tcTab);
}
@Override
public boolean renderAsNormalBlock() {
return false;
}
@Override
public boolean isOpaqueCube() {
return false;
}
@Override
public int getRenderType() {
return RenderingRegistry.getNextAvailableRenderId();
}
@Override
public Icon getIcon(int i, int j) {
return texture;
}
@Override
public boolean canPlaceBlockAt(World world, int x, int y, int z) {
if (world.isBlockSolidOnSide(x, y - 1, z, UP)) {
return true;
}
else {
return false;
}
}
@Override
public void onBlockPlacedBy(World world, int par2, int par3, int par4, EntityLivingBase living, ItemStack stack) {
TileStopper te = (TileStopper) world.getBlockTileEntity(par2, par3, par4);
int var6 = MathHelper.floor_double((double) (living.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3;
int var7 = world.getBlockMetadata(par2, par3, par4) >> 2;
++var6;
var6 %= 4;
if (var6 == 0) {
if (te != null) {
te.setFacing(2 | var7 << 2);
}
}
if (var6 == 1) {
if (te != null) {
te.setFacing(3 | var7 << 2);
}
}
if (var6 == 2) {
if (te != null) {
te.setFacing(0 | var7 << 2);
}
}
if (var6 == 3) {
if (te != null) {
te.setFacing(1 | var7 << 2);
}
}
}
@Override
public TileEntity createNewTileEntity(World world) {
return new TileStopper();
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void addCreativeItems(ArrayList itemList) {
itemList.add(new ItemStack(this));
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister iconRegister) {
texture = iconRegister.registerIcon(Info.modID.toLowerCase() + ":stopper");
}
} | 24.57377 | 115 | 0.677118 |
962ab31a4b32e1768a82171cb9bca1e656ccc30d | 707 | package nl.limakajo.numbers.animators;
import android.graphics.Point;
public class PositionAnimator extends Animator<Point>{
/**
* Constructs a PositionAnmiator
*
* @param animationTime the time it takes to animate
*/
public PositionAnimator(long animationTime) {
this.animationTime = animationTime;
}
@Override
public void update(float factor) {
currentState = new Point(
(int) (targetState.x * (1 - factor) + startingState.x * factor),
(int) (targetState.y * (1 - factor) + startingState.y * factor));
}
public void setCurrentposition(Point position) {
this.currentState = position;
}
}
| 25.25 | 81 | 0.632249 |
0d1ce2f514e76fa5515bc705feb3099bdb0f0bda | 1,160 | package org.tlh.netty.server.handler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
/**
* 丢弃的Server 只接收请求但不给出响应
*/
public class DiscardServerHandler extends ChannelInboundHandlerAdapter {
/**
* 接受到数据时调用
* @param ctx
* @param msg
* @throws Exception
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try{
//do something here
ByteBuf in =(ByteBuf) msg;
while (in.isReadable()){
System.out.print((char)in.readByte());
System.out.flush();
}
}finally {
//每个handler都需要调用该方法用于释放ByteBuf这个引用计数对象,释放资源
ReferenceCountUtil.release(msg);
}
}
/**
* 出现异常时调用ø
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();;
//关闭连接
ctx.close();
}
}
| 24.680851 | 94 | 0.614655 |
ce7ac4ce2682338c109f8b8288df5d17abbf55c7 | 500 | import java.util.*; //prime number
public class Exercise12 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int count = 0;
for(int i = 2; i<n; i++){
if(n%i == 0){
count++;
}
}
if(count == 0){
System.out.println("Prime Number");
}
else{
System.out.println("Not a prime number");
}
sc.close();
}
}
| 23.809524 | 53 | 0.446 |
527a18d36646a8da6366cffc73310ae79c685539 | 466 | package ltd.beihu.core.tools.cast;
import java.math.BigDecimal;
/**
* [转换为字符串]
*/
public class StringCaster implements Caster {
@Override
public Object cast(Object object) {
if (object == null)
return null;
if (object instanceof Number) {
//防止java用科学计数法
return new BigDecimal(String.valueOf(object)).toPlainString();
} else {
return String.valueOf(object).trim();
}
}
}
| 22.190476 | 74 | 0.590129 |
420c9a2e5d315b77a664fee79e30785c0b7a8968 | 1,555 | package de.deutschebahn.bahnhoflive.backend.wagenstand.models;
import android.content.Context;
import de.deutschebahn.bahnhoflive.R;
public interface WaggonFeatureLabelTemplate {
WaggonFeatureLabelTemplate DEFAULT = new WaggonFeatureLabelTemplate() {
@Override
public CharSequence composeLabel(Context context, WaggonFeature waggonFeature, Status status) {
if (status.available && waggonFeature.additionalInfo != 0) {
return status.label == 0 ?
context.getString(R.string.template_feature_with_additional_info,
context.getString(waggonFeature.label), context.getString(waggonFeature.additionalInfo)) :
context.getString(R.string.template_feature_with_status_and_additional_info,
context.getString(waggonFeature.label),
context.getString(status.label),
context.getString(waggonFeature.additionalInfo));
}
return status.label == 0 ?
context.getString(R.string.template_feature_without_anything,
context.getString(waggonFeature.label)) :
context.getString(R.string.template_feature_with_status,
context.getString(waggonFeature.label),
context.getString(status.label));
}
};
CharSequence composeLabel(Context context, WaggonFeature waggonFeature, Status status);
}
| 47.121212 | 122 | 0.628939 |
087d5df7a320fc1cde589bb1669820ee46562b7a | 653 | package com.obatis.email;
import com.obatis.email.exception.SendMailException;
import java.util.Map;
public interface SendMailService {
/**
* 发送 html 格式的邮件
* @param toEmail
* @param title
* @param content
* @throws SendMailException
*/
void send(String toEmail, String title, String content) throws SendMailException;
/**
* 发送 thymeleaf模板邮件
* @param toEmail
* @param title
* @param templatePath
* @param params
* @throws SendMailException
*/
void sendTemplate(String toEmail, String title, String templatePath, Map<String, Object> params) throws SendMailException;
}
| 23.321429 | 126 | 0.673813 |
ce9f1a75151c396346a2026f18ee97ffe81d4a5c | 188 | package com.example.apispringboot;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface CandidateRepository extends MongoRepository<Candidate, String>{
}
| 26.857143 | 80 | 0.856383 |
c4f970be1f52a443f63b31bcc56640b7304c11b4 | 101 | package com.leetcode;
/**
* @author xing_seng
* @date 2020/9/21
*/
public class LeetCode_538 {
}
| 11.222222 | 27 | 0.663366 |
74ce14a6c483c5b835765a70a161e90565d9e007 | 451 | package com.axway.apim.prometheus.model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class Message {
static Logger LOG = LoggerFactory.getLogger(Message.class);
private String type;
Message() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| 17.346154 | 61 | 0.75388 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.