text
stringlengths 10
2.72M
|
|---|
/*
* Copyright: 2020 forchange Inc. All rights reserved.
*/
package com.research.redis;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
/**
* @fileName: RedisExtendClient.java
* @description: jedis连接池扩展客户端
* @author: by echo huang
* @date: 2020-02-25 16:06
*/
public class RedisExtendClient {
private ShardedJedis jedisPool;
public RedisExtendClient(ShardedJedisPool jedisPool) {
this.jedisPool = jedisPool.getResource();
}
public ShardedJedis getJedisPool() {
return jedisPool;
}
public void setJedisPool(ShardedJedis jedisPool) {
this.jedisPool = jedisPool;
}
}
|
package hello.hellospring.aop;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component // SpringConfig.java에서 @Bean으로 등록하지 않고 @Component로 등록
public class TimeTraceAOP {
private static final Logger log = LogManager.getLogger(TimeTraceAOP.class);
@Around("execution(* hello.hellospring..*(..))")
public Object execute(final ProceedingJoinPoint joinPoint) throws Throwable {
final long start = System.currentTimeMillis();
log.info("START: {}", joinPoint);
try {
return joinPoint.proceed();
} finally {
final long finish = System.currentTimeMillis();
final long timeMs = finish - start;
log.info("END: {} {}ms", joinPoint, timeMs);
}
}
}
|
package com.khaale.bigdatarampup.mapreduce.hw3.part2.parsing;
import org.apache.hadoop.io.Text;
/**
* Created by Aleksander_Khanteev on 3/30/2016.
*/
public class IpDataParser {
private static final int delimeter = '\t';
private String ip;
private String userAgent;
private Double biddingPrice;
public void set(Text input) {
String line = input.toString();
int beginIndex;
int endIndex = 0;
for(int i = 0; i < 19; i++) {
beginIndex = endIndex + 1;
endIndex = line.indexOf(delimeter, beginIndex);
if (i == 3) {
userAgent = line.substring(beginIndex, endIndex);
} else if (i == 4) {
ip = line.substring(beginIndex, endIndex);
} if (i == 18) {
biddingPrice = Double.valueOf(line.substring(beginIndex, endIndex));
}
}
}
public String getIp() {
return ip;
}
public String getUserAgent() {
return userAgent;
}
public Double getBiddingPrice() {
return biddingPrice;
}
}
|
package com.elkattanman.farmFxml.controllers;
import com.elkattanman.farmFxml.controllers.settings.Preferences;
import com.elkattanman.farmFxml.domain.User;
import com.elkattanman.farmFxml.repositories.UserRepository;
import com.elkattanman.farmFxml.util.AlertMaker;
import com.elkattanman.farmFxml.util.AssistantUtil;
import com.jfoenix.controls.JFXPasswordField;
import com.jfoenix.controls.JFXTextField;
import javafx.animation.FadeTransition;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.util.Duration;
import lombok.extern.slf4j.Slf4j;
import net.rgielen.fxweaver.core.FxWeaver;
import net.rgielen.fxweaver.core.FxmlView;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.net.URL;
import java.util.Optional;
import java.util.ResourceBundle;
@Component
@FxmlView("/FXML/Login.fxml")
@Slf4j
public class LoginController implements Initializable {
@Autowired private FxWeaver fxWeaver;
@FXML private AnchorPane rootPane;
@FXML
private JFXTextField username;
@FXML
private JFXPasswordField password;
// private Preferences preference = Preferences.getPreferences();
private UserRepository userRepository;
public LoginController(UserRepository userRepository) {
this.userRepository = userRepository;
}
private void Animation() {
FadeTransition fadeTransition1 = new FadeTransition(Duration.seconds(1.5), rootPane);
fadeTransition1.setFromValue(0);
fadeTransition1.setToValue(1);
fadeTransition1.play();
}
@FXML
private void loginAction(){
doLogin();
}
void doLogin(){
String uname = StringUtils.trimToEmpty(username.getText());
// String pword = DigestUtils.shaHex(password.getText());
String pword =StringUtils.trimToEmpty(password.getText());
Optional<User> byUsername = userRepository.findByUsername(uname);
Optional<User> byEmail= userRepository.findByEmail(uname);
if ( (byUsername.isPresent() && byUsername.get().getPassword().equals(pword)) || (byEmail.isPresent() && byEmail.get().getPassword().equals(pword)) ){
Preferences preferences = Preferences.getPreferences();
preferences.setUsername(uname);
preferences.setPassword(pword);
Preferences.writePreferenceToFile(preferences);
AssistantUtil.loadWindow(AssistantUtil.getStage(rootPane), fxWeaver.loadView(MainController.class));
log.info("User successfully logged in {}", uname);
} else {
username.getStyleClass().add("wrong-credentials");
password.getStyleClass().add("wrong-credentials");
AlertMaker.showSimpleAlert("Email or password not valid", "اسم المستخدم او كلمة المرور خطأ");
}
// if (uname.equals(preference.getUsername()) && pword.equals(preference.getPassword()))
}
@FXML
private void closeButtonAction(){
Stage st=(Stage)rootPane.getScene().getWindow();st.close();
}
@FXML
private void minimizeButtonAction(){
Stage st=(Stage)rootPane.getScene().getWindow();st.setIconified(true);
}
@Override
public void initialize(URL url, ResourceBundle rb) {
Animation();
// preference=Preferences.getPreferences();
}
public void pressEnter(KeyEvent keyEvent) {
if (keyEvent.getCode() == KeyCode.ENTER) {
doLogin();
}
}
}
|
package com.yhy.dataservices.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 修改用户权限时,使用的DTO
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class UpdateUserAccessRequestDTO {
//用户表主键ID
private Integer id;
//角色表主键ID
private Integer roleId;
}
|
/**
* Copyright (C) 2009-2012 BonitaSoft S.A.
* BonitaSoft, 31 rue Gustave Eiffel - 38000 Grenoble
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2.0 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bonitasoft.studio.actors.model.organization;
import org.eclipse.emf.ecore.EFactory;
/**
* <!-- begin-user-doc -->
* The <b>Factory</b> for the model.
* It provides a create method for each non-abstract class of the model.
* <!-- end-user-doc -->
* @see org.bonitasoft.studio.actors.model.organization.OrganizationPackage
* @generated
*/
public interface OrganizationFactory extends EFactory {
/**
* The singleton instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
OrganizationFactory eINSTANCE = org.bonitasoft.studio.actors.model.organization.impl.OrganizationFactoryImpl.init();
/**
* Returns a new object of class '<em>Contact Data</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Contact Data</em>'.
* @generated
*/
ContactData createContactData();
/**
* Returns a new object of class '<em>Custom User Info Definition</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Custom User Info Definition</em>'.
* @generated
*/
CustomUserInfoDefinition createCustomUserInfoDefinition();
/**
* Returns a new object of class '<em>Custom User Info Definitions</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Custom User Info Definitions</em>'.
* @generated
*/
CustomUserInfoDefinitions createCustomUserInfoDefinitions();
/**
* Returns a new object of class '<em>Custom User Info Value</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Custom User Info Value</em>'.
* @generated
*/
CustomUserInfoValue createCustomUserInfoValue();
/**
* Returns a new object of class '<em>Custom User Info Values Type</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Custom User Info Values Type</em>'.
* @generated
*/
CustomUserInfoValuesType createCustomUserInfoValuesType();
/**
* Returns a new object of class '<em>Document Root</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Document Root</em>'.
* @generated
*/
DocumentRoot createDocumentRoot();
/**
* Returns a new object of class '<em>Group</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Group</em>'.
* @generated
*/
Group createGroup();
/**
* Returns a new object of class '<em>Groups</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Groups</em>'.
* @generated
*/
Groups createGroups();
/**
* Returns a new object of class '<em>Membership</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Membership</em>'.
* @generated
*/
Membership createMembership();
/**
* Returns a new object of class '<em>Memberships</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Memberships</em>'.
* @generated
*/
Memberships createMemberships();
/**
* Returns a new object of class '<em>Metadata</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Metadata</em>'.
* @generated
*/
Metadata createMetadata();
/**
* Returns a new object of class '<em>Meta Datas Type</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Meta Datas Type</em>'.
* @generated
*/
MetaDatasType createMetaDatasType();
/**
* Returns a new object of class '<em>Organization</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Organization</em>'.
* @generated
*/
Organization createOrganization();
/**
* Returns a new object of class '<em>Role</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Role</em>'.
* @generated
*/
Role createRole();
/**
* Returns a new object of class '<em>Roles</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Roles</em>'.
* @generated
*/
Roles createRoles();
/**
* Returns a new object of class '<em>User</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>User</em>'.
* @generated
*/
User createUser();
/**
* Returns a new object of class '<em>Users</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Users</em>'.
* @generated
*/
Users createUsers();
/**
* Returns a new object of class '<em>Password Type</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Password Type</em>'.
* @generated
*/
PasswordType createPasswordType();
/**
* Returns the package supported by this factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the package supported by this factory.
* @generated
*/
OrganizationPackage getOrganizationPackage();
} //OrganizationFactory
|
package com.tencent.mm.plugin.soter.b;
import com.tencent.d.b.a.b;
import com.tencent.d.b.a.c;
import com.tencent.d.b.a.e;
import com.tencent.mm.plugin.soter.c.a;
import com.tencent.mm.sdk.platformtools.x;
class g$1 implements b<c> {
final /* synthetic */ g onB;
g$1(g gVar) {
this.onB = gVar;
}
public final /* synthetic */ void a(e eVar) {
c cVar = (c) eVar;
x.i("MicroMsg.SoterNetDelegateUtil", "generate and upload ask onResult errCode: %d, errMsg: %s", Integer.valueOf(cVar.errCode), cVar.Yy);
if (!cVar.isSuccess()) {
a.dL(1, cVar.errCode);
if (this.onB.onz != null) {
this.onB.onz.xN(cVar.errCode);
}
} else if (this.onB.onz != null) {
this.onB.onz.bFc();
}
}
}
|
package org.sbbs.base.searcher.impl;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.sbbs.base.searcher.SearchFilter;
import org.sbbs.base.searcher.SearchRule;
public class JqgridSelfSearchFilter extends SearchFilter {
private JqgridSelfSearchFilter(String field, String op, String searchFor) {
this.setMultiSearch(false);
this.setGroupOp("single");
SearchRule sr = new SearchRule();
sr.setData(searchFor);
sr.setField(field);
sr.setOp(op);
this.getRules().add(sr);
}
private JqgridSelfSearchFilter(String jqgridfilters) {
if (jqgridfilters != null && !jqgridfilters.equalsIgnoreCase("")) {
this.setMultiSearch(true);// = true;
JSONObject jsonFilter = (JSONObject) JSONSerializer
.toJSON(jqgridfilters);
this.setGroupOp(jsonFilter.getString("groupOp"));
Object rules_string = jsonFilter.get("rules");
if (rules_string != null) {
JSONArray jsonRules = (JSONArray) JSONSerializer
.toJSON(rules_string);
int rulesCount = JSONArray.getDimensions(jsonRules)[0];
for (int i = 0; i < rulesCount; i++) {
JSONObject rule = jsonRules.getJSONObject(i);
SearchRule srule = new SearchRule();
srule.setField(rule.getString("field"));
srule.setOp(rule.getString("op"));
srule.setData(rule.getString("data"));
this.getRules().add(srule);
}
}
Object groups_string = jsonFilter.get("groups");
if (groups_string != null) {
JSONArray jsonGroups = (JSONArray) JSONSerializer
.toJSON(groups_string);
int groupsCount = JSONArray.getDimensions(jsonGroups)[0];
for (int i = 0; i < groupsCount; i++) {
JSONObject group = jsonGroups.getJSONObject(i);
SearchFilter sf = new JqgridSelfSearchFilter(group
.toString());
this.getGroups().add(sf);
}
}
}
}
public static SearchFilter BuildSearchFilter(HttpServletRequest req) {
String field = req.getParameter("searchField");
String oper = req.getParameter("searchOper");
String data = req.getParameter("searchString");
String filters = req.getParameter("filters");
SearchFilter sf = null;
if (filters != null && !filters.equals("")) {
sf = new JqgridSelfSearchFilter(filters);
} else if (field != null && data != null && oper != null) {
sf = new JqgridSelfSearchFilter(field, oper, data);
} else {
sf = null;
}
return sf;
}
}
|
package com.sdk4.boot.exception;
import lombok.Getter;
/**
* 数据库操作异常
*/
@Getter
public class DaoException extends RuntimeException {
private static final long serialVersionUID = 1L;
private int errorCode;
private String errorMessage;
public DaoException() {
super();
}
public DaoException(String message) {
super(message);
}
public DaoException(String message, Throwable cause) {
super(message, cause);
}
public DaoException(Throwable cause) {
super(cause);
}
public DaoException(int errorCode, String errorMessage, Throwable cause) {
super(errorMessage, cause);
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public DaoException(int errorCode, String errorMessage) {
super(errorMessage);
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
}
|
package com.github.ezauton.visualizer.processor;
import com.github.ezauton.recorder.base.RobotStateRecorder;
import com.github.ezauton.recorder.base.frame.RobotStateFrame;
import com.github.ezauton.visualizer.util.DataProcessor;
import com.github.ezauton.visualizer.util.Environment;
import javafx.animation.Interpolator;
import javafx.animation.KeyValue;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.transform.Rotate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RobotStateDataProcessor implements DataProcessor {
private final RobotStateRecorder robotRec;
private final List<RobotStateFrame> dataFrames;
private Rectangle robot;
private Circle posCircle;
private Label headingLabel, posLabel, velocityLabel;
private double spatialScaleFactorX;
private double spatialScaleFactorY;
private double originYPx;
private double originXPx;
private int robotLengthPx;
private int robotWidthPx;
public RobotStateDataProcessor(RobotStateRecorder robotRec) {
this.robotRec = robotRec;
dataFrames = robotRec.getDataFrames();
}
private double getX(double feetX) {
return feetX * spatialScaleFactorX + originXPx;
}
private double getY(double feetY) {
return -feetY * spatialScaleFactorY + originYPx;
}
@Override
public void initEnvironment(Environment environment) {
this.spatialScaleFactorX = environment.getScaleFactorX();
this.spatialScaleFactorY = environment.getScaleFactorY();
this.originXPx = environment.getOrigin().get(0);
this.originYPx = environment.getOrigin().get(1);
// box for robot
robotWidthPx = (int) (dataFrames.get(0).getRobotWidth() * spatialScaleFactorX);
robotLengthPx = (int) (dataFrames.get(0).getRobotLength() * spatialScaleFactorY);
robot = new Rectangle(0, 0, robotWidthPx, robotLengthPx);
posCircle = new Circle(3, Paint.valueOf("white"));
posCircle.setStroke(Paint.valueOf("black"));
// heading info
headingLabel = new Label("0 radians");
// x y loc
posLabel = new Label("(0, 0)");
velocityLabel = new Label("(0, 0)");
robot.setFill(Paint.valueOf("cyan"));
robot.setStroke(Paint.valueOf("black"));
environment.getFieldAnchorPane().getChildren().add(0, robot);
environment.getFieldAnchorPane().getChildren().add(posCircle);
GridPane dataGridPane = environment.getDataGridPane(robotRec.getName());
dataGridPane.addRow(0, new Label("Heading: "), headingLabel);
dataGridPane.addRow(1, new Label("Position: "), posLabel);
dataGridPane.addRow(2, new Label("Velocity: "), velocityLabel);
}
@Override
public Map<Double, List<KeyValue>> generateKeyValues(Interpolator interpolator) {
Map<Double, List<KeyValue>> ret = new HashMap<>();
Rotate robotRotation = new Rotate();
robot.getTransforms().add(robotRotation);
for (RobotStateFrame frame : robotRec.getDataFrames()) {
List<KeyValue> keyValues = new ArrayList<>();
double x, y, heading;
if (frame.getPos() != null) {
x = getX(frame.getPos().get(0));
y = getY(frame.getPos().get(1));
heading = frame.getHeading();
double robotX = x - robotWidthPx / 2D;
double robotY = y - robotLengthPx;
keyValues.add(new KeyValue(robot.xProperty(), robotX, interpolator));
keyValues.add(new KeyValue(robot.yProperty(), robotY, interpolator));
// keyValues.add(new KeyValue(robot.rotateProperty(), -Math.toDegrees(heading), interpolator));
keyValues.add(new KeyValue(robotRotation.angleProperty(), -Math.toDegrees(heading), interpolator));
keyValues.add(new KeyValue(robotRotation.pivotXProperty(), x, interpolator));
keyValues.add(new KeyValue(robotRotation.pivotYProperty(), y, interpolator));
keyValues.add(new KeyValue(robot.visibleProperty(), true, interpolator));
keyValues.add(new KeyValue(posCircle.centerXProperty(), x, interpolator));
keyValues.add(new KeyValue(posCircle.centerYProperty(), y, interpolator));
keyValues.add(new KeyValue(headingLabel.textProperty(), String.format("%.02f radians", heading)));
keyValues.add(new KeyValue(posLabel.textProperty(), String.format("(%.02f, %.02f)", frame.getPos().get(0), frame.getPos().get(1))));
keyValues.add(new KeyValue(velocityLabel.textProperty(), String.format("(%.02f, %.02f)", frame.getRobotVelocity().get(0), frame.getRobotVelocity().get(1))));
} else {
keyValues.add(new KeyValue(robot.visibleProperty(), false, interpolator));
}
ret.put(frame.getTime(),
keyValues);
}
return ret;
}
}
|
package com.facebook.yoga;
public enum YogaFlexDirection {
COLUMN(0),
COLUMN_REVERSE(1),
ROW(2),
ROW_REVERSE(3);
private final int mIntValue;
static {
$VALUES = new YogaFlexDirection[] { COLUMN, COLUMN_REVERSE, ROW, ROW_REVERSE };
}
YogaFlexDirection(int paramInt1) {
this.mIntValue = paramInt1;
}
public static YogaFlexDirection fromInt(int paramInt) {
if (paramInt != 0) {
if (paramInt != 1) {
if (paramInt != 2) {
if (paramInt == 3)
return ROW_REVERSE;
StringBuilder stringBuilder = new StringBuilder("Unknown enum value: ");
stringBuilder.append(paramInt);
throw new IllegalArgumentException(stringBuilder.toString());
}
return ROW;
}
return COLUMN_REVERSE;
}
return COLUMN;
}
public final int intValue() {
return this.mIntValue;
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\yoga\YogaFlexDirection.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.kzw.leisure.ui.activity;
import android.app.DownloadManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import com.kzw.leisure.R;
import com.kzw.leisure.base.BaseActivity;
import com.kzw.leisure.utils.Constant;
import com.kzw.leisure.utils.DocumentHelper;
import com.kzw.leisure.utils.FileUtils;
import com.kzw.leisure.widgets.X5WebView;
import com.tencent.smtt.sdk.URLUtil;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import butterknife.BindView;
public class DownloadFrontActivity extends BaseActivity {
@BindView(R.id.webview)
X5WebView webview;
@BindView(R.id.toolbar)
Toolbar toolbar;
String fontPath = FileUtils.getSdCardPath() + "/Fonts";
@Override
protected int getContentView() {
return R.layout.activity_download_front;
}
@Override
public void initView(Bundle savedInstanceState) {
setActionBar("字体下载", true, toolbar);
webview.loadUrl(Constant.FRONT_DOWNLOAD_URL);
webview.setDownloadListener((s, s1, s2, s3, l) -> download(s, s2, s3));
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void initPresenter() {
}
@Override
public void initData() {
}
private void download(String url, String contentDisposition, String mimeType) {
// 指定下载地址
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
// 允许媒体扫描,根据下载的文件类型被加入相册、音乐等媒体库
request.allowScanningByMediaScanner();
// 设置通知的显示类型,下载进行时和完成后显示通知
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// 设置通知栏的标题,如果不设置,默认使用文件名
request.setTitle("字体下载");
// 设置通知栏的描述
//request.setDescription("This is description");
// 允许在计费流量下下载
request.setAllowedOverMetered(false);
// 允许该记录在下载管理界面可见
request.setVisibleInDownloadsUi(false);
// 允许漫游时下载
request.setAllowedOverRoaming(true);
// 允许下载的网路类型
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
// 设置下载文件保存的路径和文件名
String fileName = URLUtil.guessFileName(url, contentDisposition, mimeType);
DocumentHelper.createDirIfNotExist(fontPath);
request.setDestinationInExternalPublicDir("Fonts", fileName);
//另外可选一下方法,自定义下载路径
//request.setDestinationUri()
//request.setDestinationInExternalFilesDir()
final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
// 添加一个下载任务
long downloadId = downloadManager.enqueue(request);
}
}
|
package com.tencent.mm.plugin.setting.ui.setting;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
class SettingsTrustFriendUI$11 implements OnMenuItemClickListener {
final /* synthetic */ SettingsTrustFriendUI mUl;
SettingsTrustFriendUI$11(SettingsTrustFriendUI settingsTrustFriendUI) {
this.mUl = settingsTrustFriendUI;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
SettingsTrustFriendUI.g(this.mUl);
return true;
}
}
|
package org.estore.common.secure;
import java.awt.image.BufferedImage;
public class IdentityCodeUtils {
/**
* 生成验证码
* @return
*/
public static String generateIdentityCode(){
// TODO
return "";
}
/**
* 根据验证码生成验证码图片
* @param iCode
* @return
*/
public static BufferedImage generateIndentityImage(String iCode){
return null;
}
}
|
package cn.canlnac.onlinecourse.presentation.model;
/**
* 用户数据模型.
*/
public class UserModel {
private int id;
private long date;
private String status;
private String userStatus;
private long lockDate;
private long lockEndDate;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUserStatus() {
return userStatus;
}
public void setUserStatus(String userStatus) {
this.userStatus = userStatus;
}
public long getLockDate() {
return lockDate;
}
public void setLockDate(long lockDate) {
this.lockDate = lockDate;
}
public long getLockEndDate() {
return lockEndDate;
}
public void setLockEndDate(long lockEndDate) {
this.lockEndDate = lockEndDate;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
package xframe.example.pattern.chainofresp;
public class Response {
}
|
package ar.edu.utn.frlp.app.mapper;
import ar.edu.utn.frlp.app.domain.User;
import ar.edu.utn.frlp.app.dto.UserDTO;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class UserMapper implements EntityMapper<UserDTO, User> {
@Override
public User toEntity(UserDTO dto) {
User user = new User();
user.setId(dto.getId());
user.setUsername(dto.getUsername());
user.setFirstname(dto.getFirstname());
user.setLastname(dto.getLastname());
return user;
}
@Override
public UserDTO toDto(User entity) {
UserDTO userDTO = new UserDTO();
userDTO.setId(entity.getId());
userDTO.setUsername(entity.getUsername());
userDTO.setFirstname(entity.getFirstname());
userDTO.setLastname(entity.getLastname());
return userDTO;
}
@Override
public List<User> toEntity(List<UserDTO> dtoList) {
List<User> list = new ArrayList<User>();
for (UserDTO userDTO : dtoList) {
list.add(toEntity(userDTO));
}
return list;
}
@Override
public List<UserDTO> toDto(List<User> entityList) {
List<UserDTO> list = new ArrayList<UserDTO>();
for (User user : entityList) {
list.add(toDto(user));
}
return list;
}
User fromId(Long id) {
if (id == null) {
return null;
}
User user = new User();
user.setId(id);
return user;
}
}
|
package com.vilio.nlbs.commonMapper.dao;
import java.util.List;
import java.util.Map;
import com.vilio.nlbs.commonMapper.pojo.NlbsOperationHistory;
/**
* @实体名称 操作历史表
* @数据库表 NLBS_OPERATION_HISTORY
* @开发日期 2017-06-15
* @技术服务 www.fwjava.com
*/
public interface NlbsOperationHistoryMapper {
/**
* 1.新增一条数据
* 注: 根据Bean实体执行新增操作.
* @param nlbsOperationHistory - 操作历史表
* @throws Exception - 异常捕捉
*/
public void getInsert(NlbsOperationHistory nlbsOperationHistory) throws Exception;
public List<Map<String ,Object>> getListBySerialNo(String serialNo) throws Exception;
}
|
package swexpert;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class SWEA_6782_D5_현주가_좋아하는_제곱근_놀이 {
private static double N;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int TC = Integer.parseInt(br.readLine());
for (int t = 1; t <= TC; t++) {
sb.append("#").append(t).append(" ");
N = Double.parseDouble(br.readLine());
int count = 0;
while(N>2) {
double tmp = Math.sqrt(N);
if((long)tmp ==tmp) {
N = tmp;
count++;
}else {
// 현재 수보다 큰 제곱수 만큼 증가 시켜준다. 한번에 (그만큼 카운트)
count += ((long)tmp +1) * ((long)tmp +1)- (long) N;
N = ((long)tmp +1) * ((long)tmp +1);
}
}
sb.append(count).append("\n");
}
System.out.println(sb);
}
}
|
package rs.pupin.custompolyline2;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import android.*;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.VideoView;
public class ImageChoosingFragment extends Fragment {
static interface ImageListener {
void imageChosen(String path, Bitmap image);
}
private ImageListener listener;
private static final int ACTION_TAKE_PHOTO_B = 1;
private static final int ACTION_TAKE_PHOTO_S = 2;
private static final int PICK_IMAGE_REQUEST = 1;
private static final String BITMAP_STORAGE_KEY = "viewbitmap";
private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
//private ImageView mImageView;
private Bitmap mImageBitmap;
//private static final String VIDEO_STORAGE_KEY = "viewvideo";
//private static final String VIDEOVIEW_VISIBILITY_STORAGE_KEY = "videoviewvisibility";
//private VideoView mVideoView;
//private Uri mVideoUri;
private String mCurrentPhotoPath;
private static final String JPEG_FILE_PREFIX = "IMG_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private AlbumStorageDirFactory mAlbumStorageDirFactory = null;
public ImageChoosingFragment() {
//required empty constructor
}
/* Photo album for this application */
private String getAlbumName() {
return "CustomPolyline2";
}
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
// Callback onRequestPermissionsResult interceptado na Activity MainActivity
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MapsActivity.REQUEST_CAMERA);
} else {
storageDir = mAlbumStorageDirFactory.getAlbumStorageDir(getAlbumName());
if (storageDir != null) {
if (!storageDir.mkdirs()) {
if (!storageDir.exists()) {
Log.d("CameraSample", "failed to create directory");
return null;
}
}
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
Log.d("CameraSample", "everything works");
return storageDir;
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File albumF = getAlbumDir();
File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
return imageF;
}
private File setUpPhotoFile() throws IOException {
File f = createImageFile();
mCurrentPhotoPath = f.getAbsolutePath();
return f;
}
private void setPic() {
/* There isn't enough memory to open up more than a couple camera photos */
/* So pre-scale the target bitmap into which the file is decoded */
/* Get the size of the ImageView */
int targetW = 40;
int targetH = 40;
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
/* Figure out which way needs to be reduced less */
int scaleFactor = 1;
if ((targetW > 0) && (targetH > 0)) {
scaleFactor = Math.min(photoW / targetW, photoH / targetH);
}
/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
listener.imageChosen(mCurrentPhotoPath, bitmap);
Log.d("IMAGE", "set image");
Log.d("IMAGE", mCurrentPhotoPath);
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
private void dispatchTakePictureIntent(int actionCode) {
// Check permission for CAMERA
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
// Callback onRequestPermissionsResult interceptado na Activity MainActivity
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.CAMERA},
MapsActivity.REQUEST_CAMERA);
} else {
// permission has been granted, continue as usual
switch (actionCode) {
case ACTION_TAKE_PHOTO_B:
File f = null;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
startActivityForResult(takePictureIntent, actionCode);
break;
case ACTION_TAKE_PHOTO_S:
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
startActivityForResult(intent, actionCode);
break;
default:
break;
} // switch
//else nothing happens
}
}
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
}
public void handleBigCameraPhoto() {
if (mCurrentPhotoPath != null) {
setPic();
galleryAddPic();
mCurrentPhotoPath = null;
}
}
private void handleCameraVideo(Intent intent) {
mImageBitmap = null;
}
Button.OnClickListener mTakePicOnClickListener =
new Button.OnClickListener() {
@Override
public void onClick(View v) {
dispatchTakePictureIntent(ACTION_TAKE_PHOTO_B);
}
};
Button.OnClickListener mTakePicSOnClickListener =
new Button.OnClickListener() {
@Override
public void onClick(View v) {
dispatchTakePictureIntent(ACTION_TAKE_PHOTO_S);
}
};
/**
* Called when the activity is first created.
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_image_choosing, container, false);
mImageBitmap = null;
Button picBtn = (Button) v.findViewById(R.id.gallery);
setBtnListenerOrDisable(
picBtn,
mTakePicOnClickListener,
MediaStore.ACTION_IMAGE_CAPTURE
);
Button picSBtn = (Button) v.findViewById(R.id.camera);
setBtnListenerOrDisable(
picSBtn,
mTakePicSOnClickListener,
MediaStore.ACTION_IMAGE_CAPTURE
);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
} else {
mAlbumStorageDirFactory = new BaseAlbumDirFactory();
}
return v;
}
public boolean hasPermissionInManifest(Context context, String permissionName) {
final String packageName = context.getPackageName();
try {
final PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
final String[] declaredPermisisons = packageInfo.requestedPermissions;
if (declaredPermisisons != null && declaredPermisisons.length > 0) {
for (String p : declaredPermisisons) {
if (p.equals(permissionName)) {
return true;
}
}
}
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTION_TAKE_PHOTO_B: {
if (resultCode == Activity.RESULT_OK) {
handleBigCameraPhoto();
}
break;
} // ACTION_TAKE_PHOTO_B
case ACTION_TAKE_PHOTO_S: {
if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
InputStream inputStream = getActivity().getContentResolver().openInputStream(data.getData());
String filename = "/sdcard/" + getFileName_CustomFormat() + ".mp4";
copyInputStreamToFile(inputStream, new File(filename));
listener.imageChosen(filename, bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
} // switch
}
private String getFileName_CustomFormat() {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
private void copyInputStreamToFile( InputStream in, File file ) {
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Indicates whether the specified action can be used as an intent. This
* method queries the package manager for installed packages that can
* respond to an intent with the specified action. If no suitable package is
* found, this method returns false.
* http://android-developers.blogspot.com/2009/01/can-i-use-this-intent.html
*
* @param context The application's environment.
* @param action The Intent action to check for availability.
* @return True if an Intent with the specified action can be sent and
* responded to, false otherwise.
*/
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
private void setBtnListenerOrDisable(
Button btn,
Button.OnClickListener onClickListener,
String intentName
) {
if (isIntentAvailable(getActivity(), intentName)) {
btn.setOnClickListener(onClickListener);
} else {
btn.setText(
btn.getText());
btn.setClickable(false);
}
}
@TargetApi(23)
@Override
public void onAttach(Context context) {
super.onAttach(context);
Activity a;
if (context instanceof Activity) {
a = (Activity) context;
this.listener = (ImageListener) a;
}
}
/*
* Deprecated on API 23
* Use onAttachToContext instead
*/
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (Build.VERSION.SDK_INT < 23) {
this.listener = (ImageListener) activity;
}
}
}
|
package com.my.javap;
import org.junit.Test;
public class Calculate_Test {
@Test
public void test_success() {
Calculate calculate = new Calculate();
calculate.factorial(10);
}
@Test
public void test_fail() {
Calculate calculate = new Calculate();
calculate.factorial(0);
}
}
|
package com.jc.databinding.module.sampledatabind;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.OnRebindCallback;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import com.jc.databinding.R;
import com.jc.databinding.databinding.DBSample;
import com.jc.databinding.module.sampledatabind.bean.SampleDataBindBean;
/**
* Created by jc on 2016-5-12.
*/
public class SampleDataBindActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DBSample viewBinding = DataBindingUtil.setContentView(this, R.layout.layout_sample_databind);
viewBinding.addOnRebindCallback(new OnRebindCallback() {
@Override
public boolean onPreBind(ViewDataBinding binding) {
return super.onPreBind(binding);
}
@Override
public void onCanceled(ViewDataBinding binding) {
super.onCanceled(binding);
}
@Override
public void onBound(ViewDataBinding binding) {
super.onBound(binding);
}
});
SampleDataBindBean sampleDataBindBean = new SampleDataBindBean("sampleData");
viewBinding.setItem(sampleDataBindBean);
}
public static void startActivity(Context context){
context.startActivity(new Intent(context,SampleDataBindActivity.class));
}
}
|
package fr.solutec.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class ClientToClient {
@Id @GeneratedValue
protected Long id;
@ManyToOne
private Client clientEnvoi;
@ManyToOne
private Client clientRecu;
private boolean accepted;
public ClientToClient() {
super();
}
public ClientToClient(Client clientEnvoi, Client clientRecu, boolean accepted) {
super();
this.clientEnvoi = clientEnvoi;
this.clientRecu = clientRecu;
this.accepted = accepted;
}
public Client getClientEnvoi() {
return clientEnvoi;
}
public void setClientEnvoi(Client clientEnvoi) {
this.clientEnvoi = clientEnvoi;
}
public Client getClientRecu() {
return clientRecu;
}
public void setClientRecu(Client clientRecu) {
this.clientRecu = clientRecu;
}
public boolean isAccepted() {
return accepted;
}
public void setAccepted(boolean accepted) {
this.accepted = accepted;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
|
package huawei;
/**
* @author kangkang lou
*/
import java.util.Scanner;
public class Main_53 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String s1 = sc.nextLine();
String s2 = sc.nextLine();
System.out.println(getMaxSubstring(s1, s2));
}
sc.close();
}
public static String getMaxSubstring(String s1, String s2) {
String max = (s1.length() > s2.length()) ? s1 : s2;
String min = (s1.equals(max)) ? s2 : s1;
for (int i = 0; i < min.length(); i++) {
for (int j = 0, k = min.length() - i; k != min.length() + 1; j++, k++) {
String s = min.substring(j, k);
if (max.contains(s))
return s;
}
}
return null;
}
}
|
package security;
class CameraFacade extends SecurityProductFacade {
CameraFacade() {
setSecurityProductFactoryType(new CameraFactory());
SecurityProductFactory cameraFactory = getSecurityProductFactory();
SecurityProduct securityProductBox = cameraFactory.createProduct(SecurityProductType.BOX);
SecurityProduct securityProductDome = cameraFactory.createProduct(SecurityProductType.DOME);
SecurityProduct securityProductIP = cameraFactory.createProduct(SecurityProductType.IP);
SecurityProduct securityProductThermal = cameraFactory.createProduct(SecurityProductType.THERMAL);
populateSecurityProductsList(securityProductBox, securityProductDome, securityProductIP, securityProductThermal);
}
}
|
interface A{
public abstract void show();
}
interface B{
public void add (int a, int b);
}
class C implements A,B{
private int num;
public void add(int a, int b){
this.num = a + b;
}
public void show(){
MyUtil.println("a + b = " + num);
}
}
class D{
public static void main(String[] args){
C c = new C();
c.add(4 ,2);
c.show();
}
}
|
package hyghlander.mods.ports.DragonScales.common;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import hyghlander.mods.ports.DragonScales.common.events.PlayerTickHandler;
import net.minecraft.client.model.ModelBiped;
public class CommonProxy {
public void preInit()
{
DragonScalesHandler.registerAll();
}
public void init()
{
DragonScalesHandler.registerRecipes();
registerRenderThings();
registerHandlers();
}
public void postInit()
{
}
public void registerHandlers() {
FMLCommonHandler.instance().bus().register(new PlayerTickHandler());
}
public void registerRenderThings(){
}
public ModelBiped getArmorModel(int id) {
return null;
}
}
|
/**
* Clase encargada de guardar los atributos de los nodos, con el fin de facilitar la navegación en el árbol que genera el agente.
* @author Miguel Angel Askar Rodriguez - 1355842
* @author Danny Fernando Cruz Arango - 1449949
*/
public class Nodo
{
private Estado estado;
private int padre;
private int profundidad;
private int posicion;
private int puntajeRojo;
private int puntajeNegro;
private int minimax;
/**
* @return the minimax
*/
public int getMinimax() {
return minimax;
}
/**
* @param minimax the minimax to set
*/
public void setMinimax(int minimax) {
this.minimax = minimax;
}
public Nodo(Estado estado, int padre, int profundidad)
{
this.estado= estado;
this.padre= padre;
this.profundidad= profundidad;
}
public Estado getEstado() {
return estado;
}
public void setEstado(Estado estado) {
this.estado = estado;
}
public int getPadre() {
return padre;
}
public void setPadre(int padre) {
this.padre = padre;
}
public int getProfundidad() {
return profundidad;
}
public void setProfundidad(int profundidad) {
this.profundidad = profundidad;
}
public int getPosicion() {
return posicion;
}
public void setPosicion(int posicion) {
this.posicion = posicion;
}
/**
* @return the puntajeRojo
*/
public int getPuntajeRojo() {
return puntajeRojo;
}
/**
* @param puntajeRojo the puntajeRojo to set
*/
public void setPuntajeRojo(int puntajeRojo) {
this.puntajeRojo = puntajeRojo;
}
/**
* @return the puntajeNegro
*/
public int getPuntajeNegro() {
return puntajeNegro;
}
/**
* @param puntajeNegro the puntajeNegro to set
*/
public void setPuntajeNegro(int puntajeNegro) {
this.puntajeNegro = puntajeNegro;
}
public void printEstado()
{
int[][] tablero= estado.getTablero();
for(int i= 0; i<6; i++)
{
for(int j=0; j<10; j++)
{
System.out.print(tablero[i][j]+ " ");
}
System.out.println("");
}
}
}
|
/*
* @Class
* Account.java
* @Purpose
* In this class, we need to test the Account.java, and make sure that it can converge 100%
* @Programmer YANG HONG
* @Programmer Haozhe Xu
*/
package tests;
import static org.junit.Assert.*;
import org.junit.Test;
import model.Account;
import model.Song;
public class AccountTest {
@Test
public void testAccount() {
Account user01 = new Account("user01", "pass01");
Song song01 = new Song("song.mp3", "Song", "Zero One", 80000);
Song song02 = new Song("song.mp3", "Song", "Zero One", 8000);
assertTrue(user01.isValidUser("user01", "pass01"));
assertFalse(user01.isValidUser("user", "pass01"));
assertFalse(user01.isValidUser("user01", "pass"));
assertFalse(user01.isValidUser("user", "pass"));
assertEquals("user01",user01.getUserName());
assertEquals(0, user01.getSongsPLayed());
assertEquals(90000, user01.getSecondsRemaining());
assertEquals("25:00:00", user01.getTimeRemaining());
assertTrue(user01.canPlay(song01));
assertTrue(user01.canPlay(song02));
user01.increaseSongsPlayed();
user01.decreaseListeningTime(10000);
assertEquals(1, user01.getSongsPLayed());
assertEquals(80000, user01.getSecondsRemaining());
assertEquals("22:13:20", user01.getTimeRemaining());
assertTrue(user01.canPlay(song01));
assertTrue(user01.canPlay(song02));
user01.increaseSongsPlayed();
user01.decreaseListeningTime(10000);
assertEquals(2, user01.getSongsPLayed());
assertEquals(70000, user01.getSecondsRemaining());
assertEquals("19:26:40", user01.getTimeRemaining());
assertFalse(user01.canPlay(song01));
assertTrue(user01.canPlay(song02));
user01.increaseSongsPlayed();
user01.decreaseListeningTime(10000);
assertEquals(3, user01.getSongsPLayed());
assertEquals(60000, user01.getSecondsRemaining());
assertEquals("16:40:00", user01.getTimeRemaining());
assertFalse(user01.canPlay(song01));
assertFalse(user01.canPlay(song02));
user01.plusCurrentDateBy(1);
assertEquals(3, user01.getSongsPLayed());
assertEquals(60000, user01.getSecondsRemaining());
assertEquals("16:40:00", user01.getTimeRemaining());
assertTrue(user01.canPlay(song01));
assertTrue(user01.canPlay(song02));
assertEquals(0, user01.getSongsPLayed());
assertEquals(90000, user01.getSecondsRemaining());
assertEquals("25:00:00", user01.getTimeRemaining());
}
}
|
import java.util.*;
/**
* @version 1.0
* @autor Maksym Bilozir
*/
public class Cinema {
private TreeMap<Days, Schedule> schedules = new TreeMap<>();
private ArrayList<Movie> moviesLibrary = new ArrayList<>();
private Time openTime;
private Time closeTime;
private ArrayList<Ticket> tickets = new ArrayList<>();
public Cinema() {
}
public TreeMap<Days, Schedule> getSchedules() {
return schedules;
}
public void setSchedules(TreeMap<Days, Schedule> schedules) {
this.schedules = schedules;
}
public ArrayList<Movie> getMoviesLibrary() {
return moviesLibrary;
}
public Time getOpenTime() {
return openTime;
}
public void setOpenTime(Time openTime) {
this.openTime = openTime;
}
public Time getCloseTime() {
return closeTime;
}
public void setCloseTime(Time closeTime) {
this.closeTime = closeTime;
}
public void addMovie(Movie movie) {
moviesLibrary.add(movie);
}
public void addSeance(Seance seance, String dayWeek) {
boolean checkOpen = checkOpen(seance.getStartTime(), seance.getEndTime());
if (checkOpen) {
for (Days day : Days.values()){
if (day.toString().equalsIgnoreCase(dayWeek)) {
Schedule tempList = null;
if (schedules.containsKey(day)) {
tempList = schedules.get(day);
if(tempList == null)
tempList = new Schedule();
tempList.addSeance(seance);
} else {
tempList = new Schedule();
tempList.addSeance(seance);
}
schedules.put(day, tempList);
}
}
} else System.out.println("Close!!!");
}
public void removeMovie(Movie movie) {
moviesLibrary.remove(movie);
}
public void removeSeance(Seance seance, String s) {
schedules.entrySet().stream().forEach(e -> {
if (e.getKey().toString().equalsIgnoreCase(s)) {
e.getValue().removeSeance(seance);
}
});
}
public void showAllMovies() {
int i = 0;
System.out.println("Show list of movies: ");
for (Movie movie : moviesLibrary) {
System.out.println("ID " + i + " " + movie);
i++;
}
}
public void showAllSeasons() {
Iterator iterator = schedules.keySet().iterator();
Schedule tempList = null;
while (iterator.hasNext()) {
String key = iterator.next().toString();
System.out.println(key);
tempList = schedules.get(Days.valueOf(key));
if (tempList != null) {
System.out.println(tempList.toString());
}
else System.out.println("List empty");
}
}
// System.out.println(schedules.toString());
// for (Map.Entry<Days, Schedule> entry : schedules.entrySet()) {
// Days key = entry.getKey();
// Schedule value = entry.getValue();
// System.out.printf("%s : %s\n", key.toString(), value.toString());
// }
public void sellTicket(Ticket ticket) {
tickets.add(ticket);
}
public void showAllTickets() {
System.out.println("Show all tickets");
System.out.println(tickets.toString());
}
public void removeTicket(int i) {
tickets.remove(i);
}
private boolean checkOpen(Time openC, Time closeC) {
if (openC.compareTo(openTime) < 0 || closeC.compareTo(closeTime) > 0) {
return false;
} else
return true;
}
@Override
public String toString() {
return "Cinema{" +
"schedules=" + schedules +
", moviesLibrary=" + moviesLibrary +
", openTime=" + openTime +
", closeTime=" + closeTime +
'}';
}
}
|
package com.example.dllo.notestudio.DemoBroTwoFr;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.dllo.notestudio.R;
/**
* Created by dllo on 16/11/15.
*/
public class DemoTwoFragmentAll extends Fragment implements View.OnClickListener {
private Button btn1 ;
private EditText et1 ;
private TextView tv1 ;
private LocalBroadcastManager broadcastManager ;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.demo_two_bro_items,container,false);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
btn1 = (Button) view.findViewById(R.id.demo_two_bro_items_btn1);
tv1 = (TextView) view.findViewById(R.id.demo_two_bro_items_tv1);
et1 = (EditText) view.findViewById(R.id.demo_two_bro_items_et1);
btn1.setOnClickListener(this);
//自定义接收广播方法
receivebroadcast();
}
private void receivebroadcast() {
broadcastManager = LocalBroadcastManager.getInstance(getContext());
IntentFilter intentFlter = new IntentFilter();
intentFlter.addAction("com.example.dllo.notestudio.DemoBroTwoFr.MYMY");
broadcastManager.registerReceiver( broadcast , intentFlter);
}
//定义的广播接收者对象
private BroadcastReceiver broadcast = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//这里写要执行的逻辑
tv1.setText(intent.getStringExtra("key1"));
}
};
@Override
public void onClick(View view) {
//传值
Intent intent = new Intent("com.example.dllo.notestudio.DemoBroTwoFr.MYMY");
intent.putExtra("key1" , et1.getText().toString());
//在fragment里面的广播发送方法不一样
LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
}
}
|
/**
*
*/
package com.spower.business.therapy.service;
import java.util.List;
import com.spower.basesystem.common.command.Page;
import com.spower.business.therapy.command.TherapyEditInfo;
import com.spower.business.therapy.command.TherapyQueryInfo;
import com.spower.business.therapy.valueobject.Therapy;
/* *************************************************************
* @Title ITherapyService.java
* @Describe 治疗信息模块综合操作类接口
*
* @Company 南宁超创信息工程科技有限公司
* @Copyright ChaoChuang (c) 2014
* @Author 廖浩添
* @CreateDate 2014-11-24
* @LastModify 2014-11-24
* @Remark 暂无备注...
*
* ************************************************************/
public interface ITherapyService {
void deleteTherapy(Therapy therapy);
Page selectTherapyList(TherapyQueryInfo info);
Long saveTherapy(TherapyEditInfo info);
Therapy selectTherapy(Long therapyId);
void saveTherapy(Therapy therapy);
/**通过个人id查询其治疗信息*/
List<Therapy> selectTherapyByPersonId(Long personId);
}
|
/*
* 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 dungeon;
import java.util.ArrayList;
/**
*
* @author Muzyk
*/
public class Map {
private int[][] mapDimensions;
private VampiresHandler vampires;
private Player player;
private boolean vampiresMove;
public Map(int x, int y, int moves, int vampiresNumber, boolean vampiresMove) {
mapDimensions = new int[x][y];
player = new Player(moves);
this.vampires = new VampiresHandler(mapDimensions, vampiresNumber);
this.vampiresMove = vampiresMove;
}
public void drawMap() {
for (int x = 0; x < mapDimensions.length; x++) {
for (int y = 0; y < mapDimensions[x].length; y++) {
if (player.isThere(x, y)) {
System.out.print("@");
} else if (vampires.isThere(x, y)) {
System.out.print("v");
} else {
System.out.print(".");
}
}
System.out.println("");
}
System.out.println("");
}
public void movePlayer(int x, int y, int mapLenght) {
player.move(x, y, mapLenght);
vampires.checkCollision(player.getCoordinates());
moveVampires();
}
public void moveVampires() {
if (vampiresMove) {
vampires.moveVampires();
}
}
public Player getPlayer() {
return this.player;
}
public VampiresHandler getVampires() {
return vampires;
}
public boolean checkVictoryConditions() {
if (player.getTurns() <= 0) {
System.out.println("YOU LOSE");
return false;
} else if (vampires.isEmpty()){
System.out.println("YOU WIN");
return false;
}
return true;
}
public int getLength() {
return mapDimensions[0].length;
}
}
|
/*
* Copyright (c) 2016, Oracle and/or its affiliates.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.oracle.truffle.llvm.parser.bc.impl;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.oracle.truffle.api.frame.FrameDescriptor;
import com.oracle.truffle.api.frame.FrameSlot;
import com.oracle.truffle.api.frame.FrameSlotKind;
import com.oracle.truffle.llvm.parser.bc.impl.LLVMControlFlowAnalysis.LLVMControlFlow;
import uk.ac.man.cs.llvm.ir.model.InstructionBlock;
import uk.ac.man.cs.llvm.ir.model.FunctionDeclaration;
import uk.ac.man.cs.llvm.ir.model.FunctionDefinition;
import uk.ac.man.cs.llvm.ir.model.FunctionParameter;
import uk.ac.man.cs.llvm.ir.model.FunctionVisitor;
import uk.ac.man.cs.llvm.ir.model.GlobalConstant;
import uk.ac.man.cs.llvm.ir.model.GlobalVariable;
import uk.ac.man.cs.llvm.ir.model.InstructionVisitor;
import uk.ac.man.cs.llvm.ir.model.Model;
import uk.ac.man.cs.llvm.ir.model.ModelVisitor;
import uk.ac.man.cs.llvm.ir.model.elements.AllocateInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.BinaryOperationInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.BranchInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.CallInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.CastInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.CompareInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.ConditionalBranchInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.ExtractElementInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.ExtractValueInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.GetElementPointerInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.IndirectBranchInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.InsertElementInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.InsertValueInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.LoadInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.PhiInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.ReturnInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.SelectInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.ShuffleVectorInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.StoreInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.SwitchInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.SwitchOldInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.UnreachableInstruction;
import uk.ac.man.cs.llvm.ir.model.elements.VoidCallInstruction;
import uk.ac.man.cs.llvm.ir.types.Type;
public final class LLVMFrameDescriptors {
public static LLVMFrameDescriptors generate(Model model) {
LLVMControlFlowAnalysis cfg = LLVMControlFlowAnalysis.generate(model);
LLVMFrameDescriptorsVisitor visitor = new LLVMFrameDescriptorsVisitor(cfg);
model.accept(visitor);
return new LLVMFrameDescriptors(visitor.getDescriptors(), visitor.getSlots());
}
private final Map<String, FrameDescriptor> descriptors;
private final Map<String, Map<InstructionBlock, List<FrameSlot>>> slots;
private LLVMFrameDescriptors(Map<String, FrameDescriptor> descriptors, Map<String, Map<InstructionBlock, List<FrameSlot>>> slots) {
this.descriptors = descriptors;
this.slots = slots;
}
public FrameDescriptor getDescriptor(String method) {
return descriptors.get(method);
}
public FrameDescriptor getDescriptor() {
return descriptors.values().iterator().next(); /* Any will do */
}
public Map<InstructionBlock, List<FrameSlot>> getSlots(String method) {
return slots.get(method);
}
private static class LLVMFrameDescriptorsVisitor implements ModelVisitor {
private final LLVMControlFlowAnalysis cfg;
private final Map<String, FrameDescriptor> descriptors = new HashMap<>();
private final Map<String, Map<InstructionBlock, List<FrameSlot>>> slots = new HashMap<>();
LLVMFrameDescriptorsVisitor(LLVMControlFlowAnalysis cfg) {
this.cfg = cfg;
}
public Map<String, FrameDescriptor> getDescriptors() {
return descriptors;
}
public Map<String, Map<InstructionBlock, List<FrameSlot>>> getSlots() {
return slots;
}
@Override
public void visit(GlobalConstant constant) {
}
@Override
public void visit(GlobalVariable variable) {
}
@Override
public void visit(FunctionDeclaration method) {
}
@Override
public void visit(FunctionDefinition method) {
FrameDescriptor frame = new FrameDescriptor();
frame.addFrameSlot(LLVMBitcodeHelper.FUNCTION_RETURN_VALUE_FRAME_SLOT_ID);
frame.addFrameSlot(LLVMBitcodeHelper.STACK_ADDRESS_FRAME_SLOT_ID, FrameSlotKind.Object);
for (FunctionParameter parameter : method.getParameters()) {
frame.addFrameSlot(parameter.getName(), LLVMBitcodeHelper.toFrameSlotKind(parameter.getType()));
}
LLVMFrameDescriptorsFunctionVisitor visitor = new LLVMFrameDescriptorsFunctionVisitor(frame, cfg.dependencies(method.getName()));
method.accept(visitor);
descriptors.put(method.getName(), frame);
slots.put(method.getName(), visitor.getSlotMap());
}
@Override
public void visit(Type type) {
}
}
private static class LLVMFrameDescriptorsFunctionVisitor implements FunctionVisitor, InstructionVisitor {
private final FrameDescriptor frame;
private LLVMControlFlow cfg;
private final Map<InstructionBlock, List<FrameSlot>> map = new HashMap<>();
private InstructionBlock entry = null;
LLVMFrameDescriptorsFunctionVisitor(FrameDescriptor frame, LLVMControlFlow cfg) {
this.frame = frame;
this.cfg = cfg;
}
private List<InstructionBlock> getNondominatingBlocks(InstructionBlock block) {
List<InstructionBlock> nondominating = new ArrayList<>();
if (block != entry) {
getNondominatingBlocksWorker(block, entry, nondominating);
}
return nondominating;
}
private void getNondominatingBlocksWorker(InstructionBlock dominator, InstructionBlock block, List<InstructionBlock> nondominating) {
for (InstructionBlock blk : cfg.successor(block)) {
if (!nondominating.contains(blk) && !dominator.equals(blk)) {
nondominating.add(blk);
getNondominatingBlocksWorker(dominator, blk, nondominating);
}
}
}
public Map<InstructionBlock, List<FrameSlot>> getSlotMap() {
return map;
}
public List<FrameSlot> getSlots(InstructionBlock block) {
int count = frame.getSize();
block.accept(this);
return new ArrayList<>(frame.getSlots().subList(count, frame.getSize()));
}
private boolean isDominating(InstructionBlock dominator, InstructionBlock block) {
if (dominator.equals(block)) {
return true;
}
return !getNondominatingBlocks(dominator).contains(block);
}
@Override
public void visit(InstructionBlock block) {
if (entry == null) {
entry = block;
}
List<InstructionBlock> processed = new ArrayList<>();
List<FrameSlot> slots = new ArrayList<>();
Deque<InstructionBlock> currentQueue = new ArrayDeque<>();
Set<InstructionBlock> successors = cfg.successor(block);
currentQueue.push(block);
while (!currentQueue.isEmpty()) {
InstructionBlock blk = currentQueue.pop();
processed.add(blk);
boolean dominates = false;
for (InstructionBlock successor : successors) {
dominates |= isDominating(blk, successor);
}
if (!dominates) {
slots.addAll(getSlots(blk));
Set<InstructionBlock> predecessors = cfg.predecessor(blk);
for (InstructionBlock predecessor : predecessors) {
if (!processed.contains(predecessor)) {
currentQueue.push(predecessor);
}
}
}
}
map.put(block, slots);
}
@Override
public void visit(AllocateInstruction allocate) {
frame.findOrAddFrameSlot(allocate.getName(), LLVMBitcodeHelper.toFrameSlotKind(allocate.getType()));
}
@Override
public void visit(BinaryOperationInstruction operation) {
frame.findOrAddFrameSlot(operation.getName(), LLVMBitcodeHelper.toFrameSlotKind(operation.getType()));
}
@Override
public void visit(BranchInstruction branch) {
}
@Override
public void visit(CallInstruction call) {
frame.findOrAddFrameSlot(call.getName(), LLVMBitcodeHelper.toFrameSlotKind(call.getType()));
}
@Override
public void visit(CastInstruction cast) {
frame.findOrAddFrameSlot(cast.getName(), LLVMBitcodeHelper.toFrameSlotKind(cast.getType()));
}
@Override
public void visit(CompareInstruction compare) {
frame.findOrAddFrameSlot(compare.getName(), LLVMBitcodeHelper.toFrameSlotKind(compare.getType()));
}
@Override
public void visit(ConditionalBranchInstruction branch) {
}
@Override
public void visit(ExtractElementInstruction extract) {
frame.findOrAddFrameSlot(extract.getName(), LLVMBitcodeHelper.toFrameSlotKind(extract.getType()));
}
@Override
public void visit(ExtractValueInstruction extract) {
frame.findOrAddFrameSlot(extract.getName(), LLVMBitcodeHelper.toFrameSlotKind(extract.getType()));
}
@Override
public void visit(GetElementPointerInstruction gep) {
frame.findOrAddFrameSlot(gep.getName(), LLVMBitcodeHelper.toFrameSlotKind(gep.getType()));
}
@Override
public void visit(IndirectBranchInstruction ibi) {
}
@Override
public void visit(InsertElementInstruction insert) {
frame.findOrAddFrameSlot(insert.getName(), LLVMBitcodeHelper.toFrameSlotKind(insert.getType()));
}
@Override
public void visit(InsertValueInstruction insert) {
frame.findOrAddFrameSlot(insert.getName(), LLVMBitcodeHelper.toFrameSlotKind(insert.getType()));
}
@Override
public void visit(LoadInstruction load) {
frame.findOrAddFrameSlot(load.getName(), LLVMBitcodeHelper.toFrameSlotKind(load.getType()));
}
@Override
public void visit(PhiInstruction phi) {
frame.findOrAddFrameSlot(phi.getName(), LLVMBitcodeHelper.toFrameSlotKind(phi.getType()));
}
@Override
public void visit(ReturnInstruction ret) {
}
@Override
public void visit(SelectInstruction select) {
frame.findOrAddFrameSlot(select.getName(), LLVMBitcodeHelper.toFrameSlotKind(select.getType()));
}
@Override
public void visit(ShuffleVectorInstruction shuffle) {
frame.findOrAddFrameSlot(shuffle.getName(), LLVMBitcodeHelper.toFrameSlotKind(shuffle.getType()));
}
@Override
public void visit(StoreInstruction store) {
}
@Override
public void visit(SwitchInstruction branch) {
}
@Override
public void visit(SwitchOldInstruction si) {
}
@Override
public void visit(UnreachableInstruction unreachable) {
}
@Override
public void visit(VoidCallInstruction call) {
}
}
}
|
package com.example.javax.xml;
import java.io.File;
import java.io.FileInputStream;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.springframework.util.ResourceUtils;
public class XMLStreamDemo {
private void printIndent(int depth) {
for (int i = 0; i < depth; i++) {
System.out.print(" ");
}
}
@Test
public void event() throws Exception {
XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
// 合并CHARACTERS类型的内容,不配置的话<record>foo<![CDATA[bar]]></record>将分为foo和bar两次Event
xmlFactory.setProperty("javax.xml.stream.isCoalescing", true);
xmlFactory.setProperty("javax.xml.stream.isSupportingExternalEntities", false);
xmlFactory.setProperty("javax.xml.stream.supportDTD", false);
File file = ResourceUtils.getFile("classpath:xmls/customer-info.xml");
int depth = 0;
XMLEventReader eventReader = xmlFactory.createXMLEventReader(new FileInputStream(file));
while (eventReader.hasNext()) {
XMLEvent xmlEvent = eventReader.nextEvent();
if (xmlEvent.getEventType() != XMLEvent.START_ELEMENT
&& xmlEvent.getEventType() != XMLEvent.END_ELEMENT) {
printIndent(depth);
}
switch (xmlEvent.getEventType()) {
case XMLEvent.START_DOCUMENT:
System.out.println("START_DOCUMENT");
break;
case XMLEvent.END_DOCUMENT:
System.out.println("END_DOCUMENT");
break;
case XMLEvent.START_ELEMENT:
printIndent(depth);
depth++;
System.out.println("START_ELEMENT");
break;
case XMLEvent.END_ELEMENT:
depth--;
printIndent(depth);
System.out.println("END_ELEMENT");
break;
case XMLEvent.COMMENT:
System.out.println("COMMENT");
break;
case XMLEvent.ATTRIBUTE:
System.out.println("ATTRIBUTE");
break;
case XMLEvent.CDATA:
System.out.println("CDATA");
break;
case XMLEvent.CHARACTERS:
System.out.println("CHARACTERS");
if (xmlEvent.asCharacters().isWhiteSpace()) {
//忽略掉空字符
continue;
}
printIndent(depth);
System.out.println(StringUtils
.replaceEach(xmlEvent.asCharacters().getData(), new String[]{"\r\n", "\n"},
new String[]{"", ""}));
break;
case XMLEvent.DTD:
System.out.println("DTD");
break;
case XMLEvent.ENTITY_DECLARATION:
System.out.println("ENTITY_DECLARATION");
break;
case XMLEvent.ENTITY_REFERENCE:
System.out.println("ENTITY_REFERENCE");
break;
case XMLEvent.NAMESPACE:
System.out.println("NAMESPACE");
break;
case XMLEvent.NOTATION_DECLARATION:
System.out.println("NOTATION_DECLARATION");
break;
case XMLEvent.PROCESSING_INSTRUCTION:
System.out.println("PROCESSING_INSTRUCTION");
break;
case XMLEvent.SPACE:
System.out.println("SPACE");
break;
}
}
}
@Test
public void stream() throws Exception {
XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
File file = ResourceUtils.getFile("classpath:xmls/customer-info.xml");
XMLStreamReader streamReader = xmlFactory.createXMLStreamReader(new FileInputStream(file));
int depth = 0;
while (streamReader.hasNext()) {
int next = streamReader.next();
if (next != XMLEvent.START_ELEMENT && next != XMLEvent.END_ELEMENT) {
printIndent(depth);
}
switch (next) {
case XMLEvent.START_DOCUMENT:
System.out.println("START_DOCUMENT");
break;
case XMLEvent.END_DOCUMENT:
System.out.println("END_DOCUMENT");
break;
case XMLEvent.START_ELEMENT:
printIndent(depth);
depth++;
System.out.println("START_ELEMENT");
break;
case XMLEvent.END_ELEMENT:
depth--;
printIndent(depth);
System.out.println("END_ELEMENT");
break;
case XMLEvent.COMMENT:
System.out.println("COMMENT");
break;
case XMLEvent.ATTRIBUTE:
System.out.println("ATTRIBUTE");
break;
case XMLEvent.CDATA:
System.out.println("CDATA");
break;
case XMLEvent.CHARACTERS:
System.out.println("CHARACTERS");
System.out.println(streamReader.getText());
break;
case XMLEvent.DTD:
System.out.println("DTD");
break;
case XMLEvent.ENTITY_DECLARATION:
System.out.println("ENTITY_DECLARATION");
break;
case XMLEvent.ENTITY_REFERENCE:
System.out.println("ENTITY_REFERENCE");
break;
case XMLEvent.NAMESPACE:
System.out.println("NAMESPACE");
break;
case XMLEvent.NOTATION_DECLARATION:
System.out.println("NOTATION_DECLARATION");
break;
case XMLEvent.PROCESSING_INSTRUCTION:
System.out.println("PROCESSING_INSTRUCTION");
break;
case XMLEvent.SPACE:
System.out.println("SPACE");
break;
}
}
}
}
|
package com.zjm.design.d3_singleton;
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
// 线程不安全
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
// 线程安全,但是每一次访问都有进行对象加锁
public static synchronized Singleton getInstance1() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
// 表面上是第一次实例化加锁,实际不是,
public static Singleton getInstance2() {
if (instance == null) {
synchronized (instance) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
|
package com.github.w4o.sa.domain;
import com.github.w4o.sa.commons.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Column;
import javax.persistence.Entity;
import java.util.Date;
/**
* TableList
*
* @author frank
* @date 2019-05-15
*/
@Entity
@Data
@EqualsAndHashCode(callSuper = false)
public class TableList extends BaseEntity {
/**
* 标题
*/
@Column(name = "title")
private String title;
/**
* 作者
*/
@Column(name = "author")
private String author;
/**
* 阅读数
*/
@Column(name = "views")
private Integer views;
/**
* 状态
*/
@Column(name = "status")
private Integer status;
/**
* 创建时间
*/
@Column(name = "create_time")
private Date createTime;
}
|
package servlet;
import dao.UserDao;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import beans.Book;
import dao.BookDao;
public class BookDelete extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
req.setCharacterEncoding("utf-8");
int id = Integer.parseInt(req.getParameter("id"));
//Book book = new Book();
//book.setId(Integer.parseInt(id));
BookDao bookdao = new BookDao();
try {
bookdao.delete(id);
req.getRequestDispatcher("successDB.jsp").forward(req, resp);
} catch (Exception e) {
e.printStackTrace();
req.getRequestDispatcher("errorDB.jsp").forward(req, resp);
}
}
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
this.doGet(req, resp);
}
}
|
package com.contactlist.contactlist;
/**
* Created by saurabh on 5/20/2017.
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.util.Log;
import com.contactlist.contactlist.bean.ContactDetails;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
public class Helper extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/com.contactlist.contactlist/databases/";
private static String DB_NAME = "Contact.sqlite";
private SQLiteDatabase myDataBase;
private final Context myContext;
private String TAG = "Helper";
Cursor cursorGetData;
public Helper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (!dbExist) {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
/* File dbFile = myContext.getDatabasePath(DB_NAME);
return dbFile.exists();*/
try {
String myPath = DB_PATH + DB_NAME;
File file = new File(myPath);
if (file.exists() && !file.isDirectory())
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
Log.e(TAG, "Error is" + e.toString());
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public Helper openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
return null;
}
/**
* Closing database after operation done
*/
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
/**
* getting information based on SQL Query
*
* @param sql
* @return Output of Query
*/
private Cursor getData(String sql) {
try {
openDataBase();
cursorGetData = getReadableDatabase().rawQuery(sql, null);
} catch (Exception e) {
e.printStackTrace();
}
return cursorGetData;
}
/**
* Inserting information based on table name and values
*
* @param tableName
* @param values
* @return
*/
private long insertData(String tableName, ContentValues values) {
try {
openDataBase();
} catch (Exception e) {
e.printStackTrace();
}
return myDataBase.insert(tableName, null, values);
}
/**
* Updating information based on table name and Condition
*
* @param tableName
* @param values
* @return
*/
private int updateData(String tableName, ContentValues values, String condition) {
try {
openDataBase();
} catch (Exception e) {
e.printStackTrace();
}
return myDataBase.update(tableName, values, condition, null);
}
public void exportDatabase() {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//com.deepshooter.grozip//databases//grozip.sqlite";
String backupDBPath = "grozip.sqlite";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Log.e("db", "copied");
} else {
Log.e("db", "dbnotexist");
}
} else {
Log.e("db", "notcopied");
}
} catch (Exception e) {
Log.e("db", "error");
}
}
// Insert Into contactlist Table
public long insertIntoContactTable(ContactDetails contactDetailses) {
long mTotalInsertedValues = 0;
try {
ContactDetails pd = contactDetailses;
ContentValues cv = new ContentValues();
cv.put("FirstName", pd.getmFName());
cv.put("LastName", pd.getmLName());
cv.put("PhoneNumber", pd.getpNo());
cv.put("NickName", pd.getnName());
long rowId = 0;
rowId = insertData("contactlist", cv);
exportDatabase();
Log.e("contactlist", "insertion contactlist working");
if (rowId != 0) {
mTotalInsertedValues++;
}
Log.e("contactlist", ""
+ mTotalInsertedValues);
} catch (Exception e) {
e.printStackTrace();
Log.e("Exception", "Insertion contactlist failed");
}
exportDatabase();
return mTotalInsertedValues;
}
//Get From contactlist Table
public ArrayList<ContactDetails> getContactTable() {
ArrayList<ContactDetails> arrayList = new ArrayList<>();
String sql = "select * from contactlist";
Cursor cursor = getData(sql);
Log.e("chk", "chk" + cursor.getCount());
if (cursor != null || cursor.getCount() > 0) {
cursor.moveToFirst();
Log.e("check", "check");
for (int size = 0; size < cursor.getCount(); size++) {
ContactDetails contactDetails = new ContactDetails();
contactDetails.setId(cursor.getString(0));
contactDetails.setmFName(cursor.getString(1));
contactDetails.setmLName(cursor.getString(2));
contactDetails.setpNo(cursor.getString(3));
contactDetails.setnName(cursor.getString(4));
arrayList.add(contactDetails);
cursor.moveToNext();
}
cursor.close();
cursorGetData.close();
myDataBase.close();
}
return arrayList;
}
public void deleteItem(String s) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM contactlist WHERE PhoneNumber='" + s + "'");
db.close();
}
public boolean isthereExists(String s) {
boolean isexist = false;
String sql = "select * from contactlist WHERE PhoneNumber='" + s + "'";
Cursor cursor = getData(sql);
Log.e("chk", "chk" + cursor.getCount());
if (cursor != null || cursor.getCount() > 0) {
isexist = true;
}
return isexist;
}
public ContactDetails getContact(String phone) {
ContactDetails contactDetails = new ContactDetails();
String sql = "select * from contactlist WHERE PhoneNumber='" + phone + "'";
Cursor cursor = getData(sql);
Log.e("chk", "chk" + cursor.getCount());
if (cursor != null || cursor.getCount() > 0) {
cursor.moveToFirst();
Log.e("check", "check");
contactDetails.setmFName(cursor.getString(1));
contactDetails.setmLName(cursor.getString(2));
contactDetails.setpNo(cursor.getString(3));
contactDetails.setnName(cursor.getString(4));
cursor.moveToNext();
}
cursor.close();
cursorGetData.close();
myDataBase.close();
return contactDetails;
}
public void updateIntoContactTable(ContactDetails contactDetails, String id) {
ContentValues cv = new ContentValues();
cv.put("FirstName", contactDetails.getmFName());
cv.put("LastName", contactDetails.getmLName());
cv.put("PhoneNumber", contactDetails.getpNo());
cv.put("NickName", contactDetails.getnName());
SQLiteDatabase db = this.getWritableDatabase();
db.update("contactlist", cv, "ID=" + id, null);
}
}
|
package org.nyer.sns.oauth.v1;
/**
* OAuth1服务协议
* @author leiting
*
*/
public interface OAuth1Protocal {
String authorizeUrl(OAuth1TokenPair requestTokenPair, String from, String scope);
OAuth1TokenPair getAccessToken(String oauthVerifier, OAuth1TokenPair requestTokenPair);
OAuth1TokenPair getRequestToken();
}
|
package chefcharlesmich.smartappphonebook.VcardProgram;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import chefcharlesmich.smartappphonebook.R;
public class AboutYouActivity extends AppCompatActivity {
private static final String TAG = "T1";
EditText companyname, name, title, address, phone, email, birthday, website, industry, social1,
social2, description, weblink1, weblink2;
private ImageButton picture;
DBHandlerVcard mdb;
int vcardid;
boolean extras_recieved = false;
int REQUEST_CODE_PICK_CONTACTS = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pick__about_you_vcard);
getSupportActionBar().hide();
Log.d("AYA", "onCreate: AboutYouActivity");
mdb = new DBHandlerVcard(this);
companyname = findViewById(R.id.editTextCompanyName);
name = findViewById(R.id.editTextName);
title = findViewById(R.id.editTextTitle);
address = findViewById(R.id.editTextAddress);
phone = findViewById(R.id.editTextPhone);
email = findViewById(R.id.editTextEmail);
birthday = findViewById(R.id.editTextDate);
website = findViewById(R.id.editTextWebsite);
industry = findViewById(R.id.editTextIndustry);
social1 = findViewById(R.id.editTextSocialMedia1);
social2 = findViewById(R.id.editTextSocialMedia2);
weblink1 = findViewById(R.id.editTextWebLink1);
weblink2 = findViewById(R.id.editTextWebLink2);
description = findViewById(R.id.editTextDescription);
picture = findViewById(R.id.imageBtnPerson);
(findViewById(R.id.button_pick_contact)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE_PICK_CONTACTS);
}
});
if (getIntent().getExtras() != null) {
extras_recieved = true;
vcardid = getIntent().getExtras().getInt("vcardidpassed");
if (vcardid != -1) {
VCardMide got = mdb.getVCardById(vcardid);
got.loadImage();
companyname.setText(got.company_name);
name.setText(got.name);
title.setText(got.title);
address.setText(got.address);
phone.setText(got.phone);
email.setText(got.email);
birthday.setText(got.birthday);
website.setText(got.website);
industry.setText(got.industry);
social1.setText(got.social1);
social2.setText(got.social2);
weblink1.setText(got.weblink1);
weblink2.setText(got.weblink2);
description.setText(got.description);
if (got.picture != null) {
picture.setBackground(new BitmapDrawable(getResources(), got.picture));
} else {
Toast.makeText(AboutYouActivity.this, "load Image Error", Toast.LENGTH_SHORT).show();
picture.setBackground(getResources().getDrawable(R.drawable.ic_person));
}
}
}
(findViewById(R.id.btnAddContact)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
VCardMide card = new VCardMide(vcardid,
companyname.getText().toString(), name.getText().toString(),
title.getText().toString(), address.getText().toString(), phone.getText().toString(),
email.getText().toString(), description.getText().toString(), birthday.getText().toString(),
website.getText().toString(), industry.getText().toString(), social1.getText().toString(),
social2.getText().toString(), weblink1.getText().toString(), weblink2.getText().toString(),
"File_" + new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date()) + ".png",
"", ((BitmapDrawable) picture.getBackground()).getBitmap());
if (!extras_recieved || vcardid == -1) {
card.id = 0;
mdb.addVcardIfo(card);
} else {
VCardMide got = mdb.getVCardById(vcardid);
card.pic_link = got.pic_link;
mdb.updateVcard(card);
}
card.saveImage();
Toast.makeText(AboutYouActivity.this, "All Info Updated to the app", Toast.LENGTH_SHORT).show();
startActivity(new Intent(AboutYouActivity.this, MainActivityVcard.class));
finish();
}
});
picture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CropImage.activity().setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1).start(AboutYouActivity.this);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PICK_CONTACTS && resultCode == RESULT_OK) {
VCardMide card = retrieveContact(data.getData());
if (card != null) {
name.setText(card.name);
phone.setText(card.phone);
email.setText(card.email);
address.setText(card.address);
website.setText(card.website);
description.setText(card.description);
birthday.setText(card.birthday);
companyname.setText(card.company_name);
title.setText(card.title);
social1.setText(card.social1);
social2.setText(card.social2);
weblink1.setText(card.weblink1);
weblink2.setText(card.weblink2);
if (card.picture != null) {
picture.setBackground(new BitmapDrawable(getResources(), card.picture));
} else {
picture.setBackground(getResources().getDrawable(R.drawable.ic_person));
}
} else {
Toast.makeText(AboutYouActivity.this, "Card is null", Toast.LENGTH_SHORT).show();
}
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
Uri resultUri = result.getUri();
InputStream is;
Drawable icon;
try {
is = this.getContentResolver().openInputStream(resultUri);
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap preview_bitmap = BitmapFactory.decodeStream(is, null, options);
icon = new BitmapDrawable(getResources(), preview_bitmap);
} catch (FileNotFoundException e) {
icon = getResources().getDrawable(R.drawable.ic_person);
}
picture.setBackground(icon);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(AboutYouActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
public VCardMide retrieveContact(Uri uriContact) {
String contactID = null;
Cursor cursorID = getContentResolver().query(uriContact, null,
null, null, null);
Log.d(TAG, "retrieveContact: " + uriContact.toString());
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
Log.d(TAG, "Contact ID from Pick: " + contactID);
VCardMide card = (new ContactData(AboutYouActivity.this, contactID)).getcontact();
Log.d(TAG, "retrieveContact: from class \n " + card.toString());
return card;
}
}
class ContactData {
private static final String TAG = "T1";
private final Context context;
private final String contactID;
ContactData(Context context, String contactID) {
this.context = context;
this.contactID = contactID;
}
public VCardMide getcontact() {
return new VCardMide(0, getCompanyName(), getName(), getTitle(), getAddress(), getNumber(),
getEmail(), getNote(), getBirthdate(), getWebsite(0), "", getWebsite(3),
getWebsite(4), getWebsite(1), getWebsite(2)
, "", "", getPhoto());
}
private Bitmap getPhoto() {
Bitmap photo = null;
try {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactID)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
}
if (inputStream != null)
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return photo;
}
private String getNumber() {
String contactNumber = null;
// Using the contact ID now we will get contact phone number
Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactID, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (number != null) {
contactNumber = number;
break;
}
}
phones.close();
return contactNumber;
}
private String getName() {
String contactName = null;
// querying contact data store
Cursor cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{contactID},
null);
if (cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
cursor.close();
return contactName;
}
private String getEmail() {
String contactEmail = null;
Cursor cursor = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{contactID},
null);
while (cursor.moveToNext()) {
String a = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
if (a != null) {
contactEmail = a;
break;
}
}
cursor.close();
return contactEmail;
}
private String getBirthdate() {
String birthdate = null;
Cursor cursor = context.getContentResolver().query(android.provider.ContactsContract.Data.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Event.DATA},
android.provider.ContactsContract.Data.CONTACT_ID + " = " +
contactID + " AND " + ContactsContract.Contacts.Data.MIMETYPE + " = '" +
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "' AND " +
ContactsContract.CommonDataKinds.Event.TYPE + " = " +
ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY, null,
android.provider.ContactsContract.Data.DISPLAY_NAME);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String a = cursor.getString(0);
if (a != null) {
birthdate = a;
break;
}
}
}
cursor.close();
return birthdate;
}
private String getAddress() {
String address = null;
Cursor cursor = context.getContentResolver().query(
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null,
ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = ?",
new String[]{contactID}, null);
while (cursor.moveToNext()) {
String street = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
String state = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
String zip = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
String city = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
String country = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
if (street == null)
street = "";
if (state == null)
state = "";
if (zip == null)
zip = "";
if (city == null)
city = "";
if (country == null)
country = "";
address = street + " " + state + " " + city + " " + zip + " " + country;
address = address.trim();
if (!address.equals(""))
break;
}
cursor.close();
return address;
}
private String getCompanyName() {
String orgWhere = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{getRawContactId(contactID),
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (cursor == null) return null;
String name = null;
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
}
cursor.close();
return name;
}
private String getTitle() {
String orgWhere = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{getRawContactId(contactID),
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (cursor == null) return null;
String name = null;
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
}
cursor.close();
return name;
}
private String getRawContactId(String contactId) {
String[] projection = new String[]{ContactsContract.RawContacts._ID};
String selection = ContactsContract.RawContacts.CONTACT_ID + "=?";
String[] selectionArgs = new String[]{contactId};
Cursor c = context.getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
if (c == null) return null;
int rawContactId = -1;
if (c.moveToFirst()) {
rawContactId = c.getInt(c.getColumnIndex(ContactsContract.RawContacts._ID));
}
c.close();
return String.valueOf(rawContactId);
}
private String getWebsite(int c) {
String website = null;
int counter = 0;
String orgWhere = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{getRawContactId(contactID),
ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE};
Cursor cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
while (cursor.moveToNext()) {
String a = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL));
if (a != null) {
if (counter == c) {
website = a;
break;
}
counter++;
}
}
cursor.close();
return website;
}
private String getNote() {
String note = null;
String orgWhere = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{getRawContactId(contactID),
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
while (cursor.moveToNext()) {
String a = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
if (a != null) {
note = a;
}
}
cursor.close();
return note;
}
}
|
package com.github.jotagit.component;
public interface KafkaConsumidor {
void listen(String message);
}
|
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2016.05.11 um 01:33:35 PM CEST
//
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java-Klasse für SCHNEIDSolldatenType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="SCHNEIDSolldatenType">
* <complexContent>
* <extension base="{http://www-fls.thyssen.com/xml/schema/qcs}ArbeitsvorgangSolldatenType">
* <sequence>
* <element name="AnzahlTafelnImPaket" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="PaketHoehe" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SCHNEIDSolldatenType", propOrder = {
"anzahlTafelnImPaket",
"paketHoehe"
})
public class SCHNEIDSolldatenType
extends ArbeitsvorgangSolldatenType
{
@XmlElement(name = "AnzahlTafelnImPaket")
protected Integer anzahlTafelnImPaket;
@XmlElement(name = "PaketHoehe")
protected Double paketHoehe;
/**
* Ruft den Wert der anzahlTafelnImPaket-Eigenschaft ab.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getAnzahlTafelnImPaket() {
return anzahlTafelnImPaket;
}
/**
* Legt den Wert der anzahlTafelnImPaket-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setAnzahlTafelnImPaket(Integer value) {
this.anzahlTafelnImPaket = value;
}
/**
* Ruft den Wert der paketHoehe-Eigenschaft ab.
*
* @return
* possible object is
* {@link Double }
*
*/
public Double getPaketHoehe() {
return paketHoehe;
}
/**
* Legt den Wert der paketHoehe-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Double }
*
*/
public void setPaketHoehe(Double value) {
this.paketHoehe = value;
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.f.a;
class c$9 implements Runnable {
final /* synthetic */ c fTi;
c$9(c cVar) {
this.fTi = cVar;
}
public final void run() {
if (this.fTi.fSW != null) {
this.fTi.fSW.getView().setVisibility(8);
this.fTi.fSW.clean();
this.fTi.fSW.onDestroy();
}
}
}
|
package digitalInnovation.javaBasico;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
public class Aula_12_Optionals {
public static void main(String[] args) {
Optional<String> optionalString = Optional.of("Valor presente"); //declaracao do Optional com valor presente
System.out.print("Valor do Optional presente: ");
optionalString.ifPresentOrElse(System.out::println, () -> System.out.println("Valor nao esta presente")); //verifica se Optinal possui valor ou nao
Optional<String> optionalNull = Optional.ofNullable(null); //declaracao do Optional com valor vazio Null
System.out.print("Valor do Optional vazio: ");
optionalNull.ifPresentOrElse(System.out::println, () -> System.out.println("Null - nao esta presente")); //verifica se Optinal possui valor ou nao
Optional<String> optionalEmpty = Optional.empty(); //declaracao do Optional com valor vazio Empyt
System.out.print("Valor do Optional empty: ");
optionalEmpty.ifPresentOrElse(System.out::println, () -> System.out.println("Empty - nao esta presente")); //verifica se Optinal possui valor ou nao'
// Optional<String> optionalNullPointer = Optional.of(null);
// System.out.print("Valor do Optional of Null: ");
// optionalNullPointer.ifPresentOrElse(System.out::println, () -> System.out.println("NullPointerException - nao esta presente"));
System.out.println("\n\n");
System.out.print("Valor INT opcional: ");
OptionalInt.of(29).ifPresent(System.out::println);
System.out.print("Valor DOUBLE opcional: ");
OptionalDouble.of(71.2).ifPresent(System.out::println);
System.out.print("Valor LONG opcional: ");
OptionalLong.of(25L).ifPresent(System.out::println);
System.out.println("\n\n");
System.out.println("Optional isPresent: " + optionalString.isPresent());
//System.out.println("Optional isEmpty: " + optionalString.isEmpty());
optionalString.ifPresent(System.out::println);
}
}
|
package com.tencent.mm.plugin.luckymoney.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import com.tencent.mm.sdk.platformtools.x;
class LuckyMoneyNewYearReceiveUI$3 implements OnCancelListener {
final /* synthetic */ LuckyMoneyNewYearReceiveUI kWg;
LuckyMoneyNewYearReceiveUI$3(LuckyMoneyNewYearReceiveUI luckyMoneyNewYearReceiveUI) {
this.kWg = luckyMoneyNewYearReceiveUI;
}
public final void onCancel(DialogInterface dialogInterface) {
if (LuckyMoneyNewYearReceiveUI.b(this.kWg) != null && LuckyMoneyNewYearReceiveUI.b(this.kWg).isShowing()) {
LuckyMoneyNewYearReceiveUI.b(this.kWg).dismiss();
}
this.kWg.kUg.baT();
if (LuckyMoneyNewYearReceiveUI.c(this.kWg).getVisibility() == 8 || LuckyMoneyNewYearReceiveUI.d(this.kWg).getVisibility() == 4) {
x.i("MicroMsg.LuckyMoneyNewYearReceiveUI", "usr cancel, & visibility not visiable, so finish");
this.kWg.finish();
}
}
}
|
package com.yida.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import com.google.gson.Gson;
/**
*********************
* 排序算法工具类
*
* @author yangke
* @version 1.0
* @created 2018年7月12日 下午5:14:02
***********************
*/
public class SortUtils {
public static void main(String[] args) {
Gson gson = new Gson();
Random random = new Random();
int[] array = new int[20];
for (int i = 0; i < array.length; i++) {
array[i] = random.nextInt(100);
}
System.out.println(gson.toJson(array));
mergeSort(array, new int[array.length], 0, array.length - 1);
System.out.println(gson.toJson(array));
}
/**
* 直接插入排序 :把新的数据插入到已经排好的数据列中。
*
* @param array
* @return
*/
public static void insertSort(int[] array) {
int length = array.length;
int insertNum;
for (int i = 1; i < length; i++) {
int j = i - 1;
insertNum = array[i];
for (; j >= 0 && array[j] > insertNum; j--) {
array[j + 1] = array[j];
}
array[j + 1] = insertNum;
}
}
/**
* 希尔排序:对于直接插入排序问题,数据量巨大时。
*
* @param array
* @return
*/
public static void shellSort(int[] array) {
int length = array.length;
int d = length / 2;
int insertNum;
int j = 0;
for (; d > 0; d /= 2) {
for (int i = d; i < length; i++) {
insertNum = array[i];
for (j = i - d; j >= 0 && insertNum < array[j]; j -= d) {
array[j + d] = array[j];
}
array[j + d] = insertNum;
}
}
}
/**
* 简单选择排序:常用于取序列中最大最小的几个数时。
*
* @param array
* @return
*/
public static void selectSort(int[] array) {
int length = array.length;
for (int i = 0; i < length; i++) {
int min = array[i];
int minPosition = i;
for (int j = i + 1; j < length; j++) {
if (array[j] < min) {
min = array[j];
minPosition = j;
}
}
array[minPosition] = array[i];
array[i] = min;
}
}
/**
* 堆排序:对简单选择排序的优化。
*
* @param array
*/
public static void heapSort(int[] array) {
// 将无序堆构造成一个大根堆,大根堆有length/2个父节点
int length = array.length;
for (int i = length / 2 - 1; i >= 0; i--) {
headAdjust(array, i, length);
}
// 逐步将每个最大值的根节点与末尾元素交换,并且再调整其为大根堆
for (int i = length - 1; i > 0; i--) {
// 将堆顶节点和当前未经排序的子序列的最后一个元素交换位置
swap(array, 0, i);
headAdjust(array, 0, i);
}
}
/**
* 交换数组中两个位置的元素
*
* @param array
* @param top
* @param last
*/
private static void swap(int[] array, int top, int last) {
int temp = array[top];
array[top] = array[last];
array[last] = temp;
}
/**
* 构建大顶堆
*
* @param array
* @param i
* @param length
*/
private static void headAdjust(int[] array, int parent, int length) {
// 保存当前父节点
int temp = array[parent];
// 左子节点
int leftChild = parent * 2 + 1;
while (leftChild < length) {
// 得到较大的子节点
if (leftChild + 1 < length && array[leftChild] < array[leftChild + 1]) {
leftChild++;
}
if (temp > array[leftChild]) {
break;
}
array[parent] = array[leftChild];
parent = leftChild;
leftChild = parent * 2 + 1;
}
array[parent] = temp;
}
/**
* 冒泡排序:一般不用。
*
* @param array
*/
public static void bubbleSort(int[] array) {
int length = array.length;
for (int i = 0; i < length - 1; i++) {
for (int j = 0; j < length - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
}
}
}
/**
* 快速排序:要求时间最快时。
*
* @param array
* @param left
* @param right
*/
public static void quickSort(int[] array, int left, int right) {
if (left < right) {
// 分割数组,找到分割点
int point = partition(array, left, right);
// 递归调用,对左子数组进行快速排序
quickSort(array, left, point - 1);
// 递归调用,对右子数组进行快速排序
quickSort(array, point + 1, right);
}
}
/**
* 找到分割点
*
* @param array
* @param left
* @param right
* @return
*/
private static int partition(int[] array, int left, int right) {
int first = array[left];
while (left < right) {
while (left < right && array[right] >= first) {
right--;
}
swap(array, left, right);
while (left < right && array[left] <= first) {
left++;
}
swap(array, left, right);
}
return left;
}
/**
* 归并排序
*
* @param array
* @param left
* @param right
*/
public static void mergeSort(int[] array, int[] tempArray, int head, int rear) {
if (head < rear) {
// 取分割位置
int middle = (head + rear) / 2;
// 递归划分列表的左序列
mergeSort(array, tempArray, head, middle);
// 递归划分列表的右序列
mergeSort(array, tempArray, middle + 1, rear);
// 列表的合并操作
merge(array, tempArray, head, middle + 1, rear);
}
}
/**
* 列表的两两合并
*
* @param array
* @param tempArray
* @param head
* @param middle
* @param rear
*/
private static void merge(int[] array, int[] tempArray, int head, int middle, int rear) {
// 左指针尾
int headEnd = middle - 1;
// 右指针头
int rearStart = middle;
// 临时列表的下标
int tempIndex = head;
// 列表合并后的长度
int tempLength = rear - head + 1;
// 先循环两个区间段都没有结束的情况
while ((headEnd >= head) && (rearStart <= rear)) {
// 如果发现右序列大,则将此数放入临时列表
if (array[head] < array[rearStart]) {
tempArray[tempIndex++] = array[head++];
} else {
tempArray[tempIndex++] = array[rearStart++];
}
}
// 判断左序列是否结束
while (head <= headEnd) {
tempArray[tempIndex++] = array[head++];
}
// 判断右序列是否结束
while (rearStart <= rear) {
tempArray[tempIndex++] = array[rearStart++];
}
// 交换数据
for (int i = 0; i < tempLength; i++) {
array[rear] = tempArray[rear];
rear--;
}
}
/**
* 基数排序:用于大量数,很长的数进行排序时。
*
* @param array
*/
public static void sort(int[] array) {
int max = array[0];
for (int i : array) {
if (max < i) {
max = i;
}
}
int time = 0;
int length = array.length;
// 判断位数
while (max > 0) {
max /= 10;
time++;
}
// 建立10个队列;
List<List<Integer>> queue = new ArrayList<List<Integer>>();
for (int i = 0; i < 10; i++) {
List<Integer> queue1 = new ArrayList<Integer>();
queue.add(queue1);
}
// 建立10个队列;
for (int i = 0; i < time; i++) {
for (int j = 0; j < length; j++) {
int x = array[j] % (int) Math.pow(10, i + 1) / (int) Math.pow(10, i);
List<Integer> queue2 = queue.get(x);
queue2.add(array[j]);
queue.set(x, queue2);
}
int count = 0;// 元素计数器;
// 收集队列元素;
for (int k = 0; k < 10; k++) {
while (queue.get(k).size() > 0) {
List<Integer> queue3 = queue.get(k);
array[count] = queue3.get(0);
queue3.remove(0);
count++;
}
}
}
}
}
|
package learn.calorietracker.data;
import learn.calorietracker.models.LogEntry;
import learn.calorietracker.models.LogEntryType;
import org.springframework.context.annotation.Primary;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.List;
@Primary
@Repository
public class LogEntryJdbcTemplateRepository implements LogEntryRepository {
private final JdbcTemplate template;
public LogEntryJdbcTemplateRepository(JdbcTemplate template) {
this.template = template;
}
@Override
public List<LogEntry> findAll() {
final String sql = "select log_entry_id, logged_on, log_entry_type_id, description, calories from log_entry;";
return template.query(sql, mapper);
}
@Override
public List<LogEntry> findByType(LogEntryType type) {
final String sql = "select log_entry_id, logged_on, log_entry_type_id, description, calories from log_entry where log_entry_type_id = ?;";
return template.query(sql, mapper, type.getValue());
}
@Override
public LogEntry findById(int id) {
final String sql = "select log_entry_id, logged_on, log_entry_type_id, description, calories from log_entry where log_entry_id = ?;";
try {
return template.queryForObject(sql, mapper, id);
} catch (EmptyResultDataAccessException ex) {
return null;
}
}
@Override
public LogEntry create(LogEntry entry) {
final String sql = "insert into log_entry(logged_on, log_entry_type_id, description, calories) values (?, ?, ?, ?);";
KeyHolder keyHolder = new GeneratedKeyHolder();
int rowsAffected = template.update(connection -> {
PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, entry.getLoggedOn());
ps.setInt(2, entry.getType().getValue());
ps.setString(3, entry.getDescription());
ps.setInt(4, entry.getCalories());
return ps;
}, keyHolder);
if (rowsAffected <= 0) {
return null;
}
entry.setId(keyHolder.getKey().intValue());
return entry;
}
@Override
public boolean update(LogEntry entry) {
final String sql = "update log_entry set logged_on = ?, log_entry_type_id = ?, description = ?, calories = ? where log_entry_id = ?;";
return template.update(sql, entry.getLoggedOn(), entry.getType().getValue(), entry.getDescription(), entry.getCalories(), entry.getId()) > 0;
}
@Override
public boolean delete(int id) {
final String sql = "delete from log_entry where log_entry_id = ?;";
return template.update(sql, id) > 0;
}
private final RowMapper<LogEntry> mapper = ((resultSet, rowNum) -> {
LogEntry entry = new LogEntry();
entry.setId(resultSet.getInt("log_entry_id"));
entry.setLoggedOn(resultSet.getString("logged_on"));
entry.setType(LogEntryType.findByValue(resultSet.getInt("log_entry_type_id")));
entry.setDescription(resultSet.getString("description"));
entry.setCalories(resultSet.getInt("calories"));
return entry;
});
}
|
package MouseActions;
public class AnimDate {
}
|
package org.sankozi.rogueland.model.coords;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.AbstractSet;
import java.util.Iterator;
import static com.google.common.base.Preconditions.checkArgument;
/**
* Immutable set containing coordinates on a vertical line. For example [5,5] [5,6] [5,7] -> [5,5:7]
*
* Set cannot be empty. Order of iteration - from lowest x to highest.
*
* @author sankozi
*/
public class VerticalLineCoordsSet extends AbstractSet<Coords> {
private final static Logger LOG = LogManager.getLogger(VerticalLineCoordsSet.class);
final int x;
final int y1;
final int y2;
public VerticalLineCoordsSet(int x, int y1, int y2) {
checkArgument(y2 > y1, "y2 (%s) must be larger than y1 (%s)", y2, y1);
this.x = x;
this.y1 = y1;
this.y2 = y2;
}
@Override
public String toString() {
return "[" + x + "," + y1 + ":" + y2 + "]";
}
@Override
public boolean contains(Object o) {
if(o instanceof Coords){
Coords coords = (Coords) o;
return x == coords.x && y1 <= coords.y && coords.y <= y2;
} else {
return false;
}
}
@Override
public int size() {
return y2 - y1 + 1;
}
@Override
public Iterator<Coords> iterator() {
return new FlatIterator(y1){
@Override
public boolean hasNext() {
return i <= y2;
}
@Override
public Coords next() {
return new Coords(x, i++);
}
};
}
@Override
public boolean isEmpty() {
return false;
}
}
|
package com.allen.lightstreamdemo;
import android.os.Handler;
import android.widget.TextView;
import com.allen.lightstreamdemo.base.Constant;
import com.lightstreamer.client.ItemUpdate;
import com.lightstreamer.client.Subscription;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* Created by: allen on 16/8/30.
*/
public class Stock extends SimpleSubscriptionListener {
private final String[] fields;
private SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("HH:mm:ss");
private HashMap<String, TextView> holder = null;
private HashMap<String, UpdateRunnable> turnOffRunnables = new HashMap<>();
Set<String> numericField;
private Handler handler;
private Subscription mSubscription;
public Stock(Set<String> numericFields, String[] fields, Handler handler, HashMap<String, TextView> holder) {
super("Stock");
this.fields = fields;
this.numericField = numericFields;
this.handler = handler;
this.holder = holder;
}
@Override
public void onListenStart(Subscription subscription) {
super.onListenStart(subscription);
this.mSubscription = subscription;
handler.post(new ResetRunnable());
}
@Override
public void onListenEnd(Subscription subscription) {
super.onListenEnd(subscription);
this.mSubscription = null;
}
@Override
public void onItemUpdate(ItemUpdate itemUpdate) {
super.onItemUpdate(itemUpdate);
this.updateView(itemUpdate);
}
private void updateView(ItemUpdate newData) {
boolean snapshot = newData.isSnapshot();
String itemName = newData.getItemName();
Iterator<Map.Entry<String, String>> changedFields = newData.getChangedFields().entrySet().iterator();
while (changedFields.hasNext()) {
Map.Entry<String, String> updatedField = changedFields.next();
String value = updatedField.getValue();
String fieldName = updatedField.getKey();
TextView field = holder.get(fieldName);
if (field != null) {
if (fieldName.equals(Constant.TIMESTAMP)) {
Date then = new Date(Long.parseLong(value));
value = mSimpleDateFormat.format(then);
}
double upDown = 0.0;
int color;
if (!snapshot) {
if (numericField.contains(fieldName)) {
try {
String oldValue = mSubscription.getValue(itemName, fieldName);
double valueNum = Double.parseDouble(value);
double oldValueNum = Double.parseDouble(oldValue);
upDown = valueNum - oldValueNum;
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
if (upDown < 0) {
color = R.color.lower_highlight;
} else {
color = R.color.higher_highlight;
}
} else {
color = R.color.lower_highlight;
}
UpdateRunnable turnOff = turnOffRunnables.get(fieldName);
if (turnOff != null) {
turnOff.invalidate();
}
turnOff = new UpdateRunnable(R.color.transparent, field, null);
this.turnOffRunnables.put(fieldName, turnOff);
handler.post(new UpdateRunnable(color, field, value));
handler.postDelayed(turnOff, 600);
}
}
}
private class ResetRunnable implements Runnable {
@Override
public synchronized void run() {
resetHolder(holder, fields);
}
private void resetHolder(HashMap<String, TextView> holder, String[] fields) {
for (int i = 0; i < fields.length; i++) {
TextView field = holder.get(fields[i]);
if (field != null) {
field.setText("N/A");
}
}
}
}
private class UpdateRunnable implements Runnable {
private int background;
private TextView mTextView;
private String text;
private boolean valid = true;
public UpdateRunnable(int background, TextView textView, String text) {
this.background = background;
mTextView = textView;
this.text = text;
}
@Override
public synchronized void run() {
if (this.valid) {
if (this.text != null) {
mTextView.setText(text);
}
mTextView.setBackgroundResource(background);
mTextView.invalidate();
}
}
public synchronized void invalidate() {
this.valid = false;
}
}
}
|
package com.tuanhk.ui.fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import com.tuanhk.TuanHKApp;
import com.tuanhk.di.component.ApplicationComponent;
import com.tuanhk.di.component.UserComponent;
import com.tuanhk.navigation.Navigator;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public abstract class BaseFragment extends Fragment {
protected abstract void setupFragmentComponent();
protected abstract int getResLayoutId();
public final String TAG = getClass().getSimpleName();
// private Snackbar mSnackBar;
// private SweetAlertDialog mProgressDialog;
private Unbinder unbinder;
// private Handler mShowLoadingTimeoutHandler;
// private Runnable mShowLoadingTimeoutRunnable;
protected final Navigator navigator = TuanHKApp.instance().getAppComponent().navigator();
// protected final UserConfig userConfig = AndroidApplication.instance().getAppComponent().userConfig();
protected UserComponent getUserComponent() {
return TuanHKApp.instance().getUserComponent();
}
public ApplicationComponent getAppComponent() {
return TuanHKApp.instance().getAppComponent();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(getResLayoutId(), container, false);
unbinder = ButterKnife.bind(this, view);
setupFragmentComponent();
return view;
}
@Override
public void onDestroyView() {
hideKeyboard();
// cancelShowLoadingTimeoutRunnable();
// hideProgressDialog();
super.onDestroyView();
// mShowLoadingTimeoutHandler = null;
// mShowLoadingTimeoutRunnable = null;
// mProgressDialog = null;
unbinder.unbind();
}
public boolean onBackPressed() {
return false;
}
// public void showSnackbar(int message, View.OnClickListener listener) {
// hideSnackbar();
// mSnackBar = Snackbar.make(getActivity().findViewById(android.R.id.content), message, Snackbar.LENGTH_LONG);
// if (listener != null) mSnackBar.setAction(R.string.btn_retry, listener);
// mSnackBar.show();
// }
// public void showNetworkError() {
// showSnackbar(R.string.exception_no_connection, null);
// }
//
// public void hideSnackbar() {
// if (mSnackBar != null) mSnackBar.dismiss();
// }
//
// public boolean isShowingLoading() {
// return mProgressDialog != null && mProgressDialog.isShowing();
// }
//
// public void hideProgressDialog() {
// if (mProgressDialog == null || !mProgressDialog.isShowing()) {
// return;
// }
// mProgressDialog.dismiss();
// cancelShowLoadingTimeoutRunnable();
// }
//
// public void showProgressDialog() {
// cancelShowLoadingTimeoutRunnable();
// if (mProgressDialog == null) {
// mProgressDialog = new SweetAlertDialog(getContext(),
// SweetAlertDialog.PROGRESS_TYPE, R.style.alert_dialog_transparent);
// mProgressDialog.setCancelable(false);
// mProgressDialog.setOnKeyListener((dialogInterface, keyCode, keyEvent) -> {
// if (keyCode == KeyEvent.KEYCODE_BACK) {
// Activity activity = getActivity();
// if (activity != null && !activity.isFinishing()) {
// activity.onBackPressed();
// }
// return true;
// } else {
// return false;
// }
// });
// }
// if (!isShowingLoading()) {
// mProgressDialog.show();
// }
// }
//
// public void showProgressDialog(final long timeout) {
// showProgressDialog();
// startShowLoadingTimeoutRunnable(timeout);
// }
//
// public void showProgressDialogWithTimeout() {
// showProgressDialog(35000);
// }
//
// private void startShowLoadingTimeoutRunnable(final long timeout) {
// if (timeout <= 0) {
// return;
// }
// if (mShowLoadingTimeoutHandler == null) {
// mShowLoadingTimeoutHandler = new Handler();
// }
// if (mShowLoadingTimeoutRunnable == null) {
// mShowLoadingTimeoutRunnable = new Runnable() {
// @Override
// public void run() {
// onTimeoutLoading(timeout);
// }
// };
// }
// mShowLoadingTimeoutHandler.postDelayed(mShowLoadingTimeoutRunnable, timeout);
// }
//
// private void cancelShowLoadingTimeoutRunnable() {
// if (mShowLoadingTimeoutHandler != null && mShowLoadingTimeoutRunnable != null) {
// mShowLoadingTimeoutHandler.removeCallbacks(mShowLoadingTimeoutRunnable);
// }
// }
//
// protected void onTimeoutLoading(long timeout) {
// Timber.d("time out show loading");
// if (isShowingLoading()) {
// hideProgressDialog();
// }
// }
//
// public void showNetworkErrorDialog() {
// showNetworkErrorDialog(null);
// }
//
// public void showNetworkErrorDialog(OnSweetDialogListener listener) {
// DialogHelper.showNetworkErrorDialog(getActivity(), listener);
// }
//
// public void showWarningDialog(String message,
// OnEventDialogListener cancelListener) {
// DialogHelper.showWarningDialog(getActivity(), message, cancelListener);
// }
//
// public void showWarningDialog(String message,
// String cancelBtnText,
// final OnEventDialogListener cancelListener) {
// DialogHelper.showWarningDialog(getActivity(),
// message,
// cancelBtnText,
// cancelListener);
// }
//
// public void showNotificationDialog(String message) {
// showErrorDialog(message,
// getString(R.string.txt_close),
// null);
// }
//
// public void showErrorDialog(String message) {
// showErrorDialog(message,
// getString(R.string.txt_close),
// null);
// }
//
// public void showErrorDialog(String message,
// final OnEventDialogListener cancelListener) {
// DialogHelper.showNotificationDialog(getActivity(),
// message,
// getString(R.string.txt_close),
// cancelListener);
// }
//
// public void showErrorDialog(String message,
// String cancelText,
// final OnEventDialogListener cancelListener) {
// DialogHelper.showNotificationDialog(getActivity(),
// message,
// cancelText,
// cancelListener);
// }
//
// public void showConfirmDialog(String pMessage,
// String pOKButton,
// String pCancelButton,
// final OnEventConfirmDialogListener callback) {
// DialogHelper.showConfirmDialog(getActivity(),
// pMessage,
// pOKButton,
// pCancelButton,
// callback);
// }
//
// public void showSuccessDialog(String message, OnEventDialogListener listener) {
// DialogHelper.showSuccessDialog(getActivity(), message, listener);
// }
//
// public UserComponent getUserComponent() {
// return AndroidApplication.instance().getUserComponent();
// }
//
// public ApplicationComponent getAppComponent() {
// return AndroidApplication.instance().getAppComponent();
// }
//
// public void showToast(String message) {
// ToastUtil.showToast(getActivity(), message);
// }
//
// public void showToast(int message) {
// ToastUtil.showToast(getActivity(), message);
// }
public void hideKeyboard() {
if (getView() == null) {
return;
}
final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null) {
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
}
}
public void hideKeyboard(View view) {
if (view == null) {
return;
}
final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm !=null) {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
public void onNewIntent(Intent intent) {
}
}
|
package com.salesianos.ModeloManyToMany.service;
import com.salesianos.ModeloManyToMany.model.JustAdded;
import com.salesianos.ModeloManyToMany.model.Playlist;
import com.salesianos.ModeloManyToMany.model.Song;
import com.salesianos.ModeloManyToMany.repositories.JustAddedRepository;
import com.salesianos.ModeloManyToMany.service.base.BaseService;
import org.springframework.stereotype.Service;
@Service
public class JustAddedService
extends BaseService<JustAdded, Long, JustAddedRepository> {
public void addSongToPlaylist(Playlist p, Song s, PlayListService pService, SongService sService) {
JustAdded justAdded = new JustAdded();
justAdded.addSongToPlaylist(s,p);
save(justAdded);
pService.edit(p);
sService.edit(s);
}
public Song added(Song s, Playlist p) {
s.getJustAddeds().forEach(justAdded -> {
JustAdded j = JustAdded.builder()
.song(s)
.playlist(p)
.build();
save(j);
});
return s;
}
}
|
package bgu.spl171.net.impl.packets;
public class DIRQPacket implements Packet {
@Override
public short opCode() {
return 6;
}
}
|
package vantoan.blog_security.repo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import vantoan.blog_security.model.Blog;
@Repository
public interface BlogRepo extends CrudRepository<Blog,Long> {
}
|
package com.lingnet.vocs.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.lingnet.common.entity.BaseEntity;
/**
* 提醒
* @ClassName: JcsjRemind
* @Description: TODO
* @author 邹云鹏
* @date 2014-12-5 上午11:48:37
*
*/
@Entity
@Table(name = "JCSJ_REMIND")
public class JcsjRemind extends BaseEntity implements java.io.Serializable {
// Fields
/**
*
*/
private static final long serialVersionUID = -4591422861833469391L;
private String createMan;//创建人
private String operater;//操作人
private String moduleName;//模块名称
private String trxCode;//单据编号
private String url;//链接地址
private String content;//内容
private String ynRemind;//是否提醒 0:不再提醒 1:提醒
private String status;//完成状态 0:未完成 1:完成
private String bz;//备注
// Constructors
/** default constructor */
public JcsjRemind() {
}
/** full constructor */
public JcsjRemind(String createMan, String operater, String moduleName,
String trxCode, String url, String content, String ynRemind,
String status,String bz) {
this.createMan = createMan;
this.operater = operater;
this.moduleName = moduleName;
this.trxCode = trxCode;
this.url = url;
this.content = content;
this.ynRemind = ynRemind;
this.status = status;
this.bz = bz;
}
@Column(name = "CREATE_MAN")
public String getCreateMan() {
return this.createMan;
}
public void setCreateMan(String createMan) {
this.createMan = createMan;
}
@Column(name = "OPERATER")
public String getOperater() {
return this.operater;
}
public void setOperater(String operater) {
this.operater = operater;
}
@Column(name = "MODULE_NAME")
public String getModuleName() {
return this.moduleName;
}
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
@Column(name = "TRX_CODE")
public String getTrxCode() {
return this.trxCode;
}
public void setTrxCode(String trxCode) {
this.trxCode = trxCode;
}
@Column(name = "URL")
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
@Column(name = "CONTENT")
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
@Column(name = "YN_REMIND", length = 1)
public String getYnRemind() {
return this.ynRemind;
}
public void setYnRemind(String ynRemind) {
this.ynRemind = ynRemind;
}
@Column(name = "STATUS", length = 1)
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
@Column(name = "BZ")
public String getBz() {
return bz;
}
public void setBz(String bz) {
this.bz = bz;
}
}
|
package com.shopify.admin.code.popup;
import lombok.Data;
/**
* Code Data(Popup)
* @author : kyh
* @since : 2020-02-03
* @desc : tb_use_code 정보
*/
@Data
public class AdminCodePopupData {
//세션정보
private int shop_idx;
private String email;
private String id;
private String shop;
private String shop_id;
private String ecommerce;
private String access_token;
private String access_key;
private String scope;
private String expires_in;
private String combine_yn;
private String account_owner;
private String locale;
private String collaborator;
private String use_yn;
//TB_BOARD TABLE
private String codeId;
private String codeGroup;
private int codeSeq;
private String codeKname;
private String codeEname;
private String codeEtc;
private String codeDiscript;
private String codeUseYn;
private String codeRegDate;
}
|
/*
* SessionBean1.java
*
* Created on 13 janv. 2009, 08:46:39
* Copyright bbernard
*/
package an1;
import an1.exceptions.NonexistentEntityException;
import an1.exceptions.PreexistingEntityException;
import an1.exceptions.RollbackFailureException;
import an1.persistence.CodesEcrituresJpaController;
import an1.persistence.Ecritures;
import an1.persistence.EcrituresJpaController;
import an1.persistence.MembresJpaController;
import an1.persistence.Membres;
import an1.persistence.MembresFamilles;
import an1.persistence.GroupesUtilisateurs;
import an1.persistence.GroupesUtilisateursJpaController;
import an1.persistence.MembresFamillesJpaController;
import an1.persistence.Reservations;
import an1.persistence.ReservationsJpaController;
import an1.persistence.Servicerefuge;
import an1.persistence.ServicerefugeJpaController; //import com.sun.rave.web.ui.appbase.AbstractSessionBean;
//import com.sun.sql.rowset.CachedRowSetXImpl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletRequest;
/**
* <p>
* Session scope data bean for your application. Create properties here to
* represent cached data that should be made available across multiple HTTP
* requests for an individual user.
* </p>
*
* <p>
* An instance of this class will be created for you automatically, the first
* time your application evaluates a value binding expression or method binding
* expression that references a managed bean using this class.
* </p>
*/
public class SessionBean1 {
private MembresFamillesJpaController membresFamillesJpaController;
private String Connecté = "non connecté";
private Membres MembreLoggé;
private Boolean retourVersMembre=false;
private Ecritures ecritureEnCours;
private CodesEcrituresJpaController codesEcrituresJpaController;
private String[] selectedCheckboxAffichage={"Demande","Option","Ferme","AcomptePayé","Payé"};
private static final SelectItem[] checkBoxAffichage = new SelectItem[]{
new SelectItem(Reservations.StatutReservation.Demande),
new SelectItem(Reservations.StatutReservation.Option),
new SelectItem(Reservations.StatutReservation.Ferme),
new SelectItem(Reservations.StatutReservation.AcomptePayé),
new SelectItem(Reservations.StatutReservation.Payé)};
public Membres getMembreLoggé() {
return MembreLoggé;
}
public void setMembreLoggé(Membres membreLoggé) {
MembreLoggé = membreLoggé;
}
public String getConnecté() {
return Connecté;
}
public void voirActionListener(ActionEvent event) {
setMembreEnCours((Membres) event.getComponent().getAttributes().get("membre"));
System.out.println("Membre"+membreEnCours.getNom());
}
public String voirMembre() {
return "listemembres";
}
public void statusChanged(ValueChangeEvent vce) {
System.out.println("statut changed");
}
public String getMembreEnCoursString() {
if (membreEnCours == null)
return "pas de membre en cours";
StringBuffer message = new StringBuffer();
message.append("Nom: " + membreEnCours.getNom() + "<br/>");
message.append("Prénom: " + membreEnCours.getPrenom() + "<br/>");
message.append("adresse1: " + membreEnCours.getAdresse1() + "<br/>");
message.append("adresse2: " + membreEnCours.getAdresse2() + "<br/>");
message.append("Code postal: " + membreEnCours.getCodePostal()
+ "<br/>");
message.append("Ville: " + membreEnCours.getVille() + "<br/>");
message.append("Email: " + membreEnCours.getEmail() + "<br/>");
message.append("Téléphone domicile: "
+ membreEnCours.getTelephoneDomicile() + "<br/>");
message.append("Téléphone portable: " + membreEnCours.getTelephoneGsm()
+ "<br/>");
message.append("mot de passe: " + membreEnCours.getPassword()
+ "<br/>");
return message.toString();
}
public void setConnecté(String connecté) {
Connecté = connecté;
}
void editMembreEnCours() {
try {
membresJpaController.edit(membreEnCours);
} catch (NonexistentEntityException ex) {
Logger.getLogger(SessionBean1.class.getName()).log(Level.SEVERE,
null, ex);
} catch (RollbackFailureException ex) {
Logger.getLogger(SessionBean1.class.getName()).log(Level.SEVERE,
null, ex);
} catch (Exception ex) {
Logger.getLogger(SessionBean1.class.getName()).log(Level.SEVERE,
null, ex);
}
}
void nouveauMembreFamille() {
MembresFamilles mf = new MembresFamilles(membreEnCours);
try {
membresFamillesJpaController.create(mf);
membreEnCours.getMembresFamille().add(mf);
} catch (PreexistingEntityException ex) {
Logger.getLogger(SessionBean1.class.getName()).log(Level.SEVERE,
null, ex);
} catch (RollbackFailureException ex) {
Logger.getLogger(SessionBean1.class.getName()).log(Level.SEVERE,
null, ex);
} catch (Exception ex) {
Logger.getLogger(SessionBean1.class.getName()).log(Level.SEVERE,
null, ex);
}
}
/**
* <p>
* Automatically managed component initialization. <strong>WARNING:</strong>
* This method is automatically generated, so any user-specified code
* inserted here is subject to being replaced.
* </p>
*/
// private void _init() throws Exception {
// membresRowSet.setDataSourceName("java:comp/env/jdbc/AN_MySQL");
// membresRowSet.setCommand("SELECT * FROM membres");
// membresRowSet.setTableName("membres");
// }
// </editor-fold>
/**
* <p>
* Construct a new session data bean instance.
* </p>
*/
private GroupesUtilisateurs groupeUtilisateursEnCours;
private Membres membreEnCours = null;
private List<MembresFamilles> membresFamilleEnCours;
private List<Servicerefuge> servicesRefugeEnCours;
private List<Membres> listeMembres = new ArrayList<Membres>();
private MembresJpaController membresJpaController;
private GroupesUtilisateursJpaController groupesUtilisateursJpaController;
// private CachedRowSetXImpl membresRowSet = new CachedRowSetXImpl();
private ServicerefugeJpaController serviceRefugeJpaController;
private Servicerefuge serviceRefugeEnCours;
private CalendrierUtil calendrier1;
private ReservationsJpaController reservationsJPAControler;
private Reservations reservationEnCours;
private List<Reservations> reservationsMembreEnCours;
private EcrituresJpaController ecrituresJPAController;
/*
* public CachedRowSetXImpl getMembresRowSet() { return membresRowSet; }
*
* public void setMembresRowSet(CachedRowSetXImpl crsxi) {
* this.membresRowSet = crsxi; }
*/
public SessionBean1() {
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext != null) {
membresJpaController = new MembresJpaController();
membresFamillesJpaController = new MembresFamillesJpaController(); // facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(),
// null,
// "MembresFamillesJpaController");
groupesUtilisateursJpaController = new GroupesUtilisateursJpaController();// facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(),
// null,
// "GroupesUtilisateursJpaController");
serviceRefugeJpaController = new ServicerefugeJpaController();// facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(),
// null,
// "ServicerefugeJpaController");
reservationsJPAControler = new ReservationsJpaController(); // facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(),
// null,
// "ReservationsJpaController");
setEcrituresJPAController(new EcrituresJpaController());
setCodesEcrituresJpaController(new CodesEcrituresJpaController());
litTableMembres();
calendrier1 = new CalendrierUtil(new Date(),
getServiceRefugeJpaController(),
getReservationsJPAControler());
}
}
/**
* @return the membreEnCours
*/
public void LitMembresParNom(String nom) {
listeMembres=membresJpaController.rechercheMembresParNomPartiel(nom);
}
public Membres getMembreEnCours() {
return membreEnCours;
}
/**
* @param membreEnCours
* the membreEnCours to set
*/
public void setMembreEnCours(Membres membreEnCours) {
this.membreEnCours = membreEnCours;
servicesRefugeEnCours = getServiceRefugeJpaController()
.getServiceRefuge(membreEnCours);
reservationsMembreEnCours = reservationsJPAControler
.getReservationsMembre(membreEnCours);
}
/**
* @return the listeMembres
*/
public List<Membres> getListeMembres() {
return listeMembres;
}
/**
* @param listeMembres
* the listeMembres to set
*/
public void setListeMembres(List<Membres> listeMembres) {
this.listeMembres = listeMembres;
}
/**
* @return the membresJpaController
*/
public MembresJpaController getMembresJpaController() {
return membresJpaController;
}
/**
* @return the autorisationsJpaController
*/
public GroupesUtilisateursJpaController getGroupesUtilisateursJpaController() {
return groupesUtilisateursJpaController;
}
/**
* @return the membresFamilleEnCours
*/
public List<MembresFamilles> getMembresFamilleEnCours() {
return membresFamilleEnCours;
}
/**
* @param membresFamilleEnCours
* the membresFamilleEnCours to set
*/
public void setMembresFamilleEnCours(
List<MembresFamilles> membresFamilleEnCours) {
this.membresFamilleEnCours = membresFamilleEnCours;
}
public boolean isValidMembreEnCours() {
return (membreEnCours != null);
}
/**
* @return the membresFamillesJpaController
*/
public MembresFamillesJpaController getMembresFamillesJpaController() {
return membresFamillesJpaController;
}
/**
* @return the serviceRefugeEnCours
*/
public List<Servicerefuge> getServicesRefugeEnCours() {
return servicesRefugeEnCours;
}
/**
* @param serviceRefugeEnCours
* the serviceRefugeEnCours to set
*/
public void setServicesRefugeEnCours(
List<Servicerefuge> serviceRefugeEnCours) {
this.servicesRefugeEnCours = serviceRefugeEnCours;
}
public void litTableMembres() {
listeMembres = membresJpaController.findMembresTrieParNom();
}
public void effaceMembreEnCours() {
if (membreEnCours != null) {
try {
reservationsJPAControler.effaceReservationsMembre(membreEnCours);
serviceRefugeJpaController.effaceServicesRefugeMembre(membreEnCours);
membresJpaController.destroy(membreEnCours.getCode());
membreEnCours = null;
litTableMembres();
} catch (NonexistentEntityException ex) {
Logger.getLogger(SessionBean1.class.getName()).log(
Level.SEVERE, null, ex);
} catch (RollbackFailureException ex) {
Logger.getLogger(SessionBean1.class.getName()).log(
Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(SessionBean1.class.getName()).log(
Level.SEVERE, null, ex);
}
}
}
/**
* @return the serviceRefugeEnCours
*/
public Servicerefuge getServiceRefugeEnCours() {
return serviceRefugeEnCours;
}
/**
* @param serviceRefugeEnCours
* the serviceRefugeEnCours to set
*/
public void setServiceRefugeEnCours(Servicerefuge serviceRefugeEnCours) {
this.serviceRefugeEnCours = serviceRefugeEnCours;
}
/**
* @return the calendrier1
*/
public CalendrierUtil getCalendrier1() {
return calendrier1;
}
/**
* @param calendrier1
* the calendrier1 to set
*/
public void setCalendrier1(CalendrierUtil calendrier1) {
this.calendrier1 = calendrier1;
}
/**
* @return the groupeUtilisateursEnCours
*/
public GroupesUtilisateurs getGroupeUtilisateursEnCours() {
return groupeUtilisateursEnCours;
}
/**
* @param groupeUtilisateursEnCours
* the groupeUtilisateursEnCours to set
*/
public void setGroupeUtilisateursEnCours(
GroupesUtilisateurs groupeUtilisateursEnCours) {
this.groupeUtilisateursEnCours = groupeUtilisateursEnCours;
}
/**
* @return the reservationJPAControler
*/
public ReservationsJpaController getReservationsJPAControler() {
return reservationsJPAControler;
}
/**
* @return the reservationEnCours
*/
public Reservations getReservationEnCours() {
return reservationEnCours;
}
/**
* @param reservationEnCours
* the reservationEnCours to set
*/
public void setReservationEnCours(Reservations reservationEnCours) {
this.reservationEnCours = reservationEnCours;
}
/**
* @return the reservationsMembreEnCours
*/
public List<Reservations> getReservationsMembreEnCours() {
return reservationsMembreEnCours;
}
/**
* @param reservationsMembreEnCours
* the reservationsMembreEnCours to set
*/
public void setReservationsMembreEnCours(
List<Reservations> reservationsMembreEnCours) {
this.reservationsMembreEnCours = reservationsMembreEnCours;
}
public void refreshServicesRefugesMembreEnCours() {
servicesRefugeEnCours = getServiceRefugeJpaController()
.getServiceRefuge(membreEnCours);
}
public void refreshReservationsMembreEnCours() {
reservationsMembreEnCours = reservationsJPAControler
.getReservationsMembre(membreEnCours);
}
/**
* @return the serviceRefugeJpaController
*/
public ServicerefugeJpaController getServiceRefugeJpaController() {
return serviceRefugeJpaController;
}
/**
* @param serviceRefugeJpaController
* the serviceRefugeJpaController to set
*/
public void setServiceRefugeJpaController(
ServicerefugeJpaController serviceRefugeJpaController) {
this.serviceRefugeJpaController = serviceRefugeJpaController;
}
public void setRetourVersMembre(Boolean retourVersMembre) {
this.retourVersMembre = retourVersMembre;
}
public Boolean getRetourVersMembre() {
return retourVersMembre;
}
public void setEcrituresJPAController(EcrituresJpaController ecrituresJPAController) {
this.ecrituresJPAController = ecrituresJPAController;
}
public EcrituresJpaController getEcrituresJPAController() {
return ecrituresJPAController;
}
public void setEcritureEnCours(Ecritures ecritureEnCours) {
this.ecritureEnCours = ecritureEnCours;
}
public Ecritures getEcritureEnCours() {
return ecritureEnCours;
}
public void setCodesEcrituresJpaController(
CodesEcrituresJpaController codesEcrituresJpaController) {
this.codesEcrituresJpaController = codesEcrituresJpaController;
}
public CodesEcrituresJpaController getCodesEcrituresJpaController() {
return codesEcrituresJpaController;
}
public SelectItem[] getCheckBoxAffichage() {
return checkBoxAffichage;
}
public void setSelectedCheckboxAffichage(String[] selectedCheckboxAffichage) {
this.selectedCheckboxAffichage = selectedCheckboxAffichage;
}
public String[] getSelectedCheckboxAffichage() {
return selectedCheckboxAffichage;
}
}
|
package vpl;
import java.util.List;
import java.util.Map;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Przemysław Czuj
*/
public class VplScene {
// VplScene (single)
// |- VplExperiment (starting[] + current)
// |- VplExperimentExecution (object)
// |- VplObject (physical state)
// | |- VplShape (final + reference)
// |- VplForce (can be attached to VplObject)
// |- VplGravity (global force)
// core of LOGIC layer
// collection of independant experiments - to switch between
// current experiment copy with its state changed in time
// (collection of experiment snapshots - for experiment rewind)
// user preferences
// new + load + save
private Map<String, VplExperiment> experiments;
private VplExperimentExecution execution;
private VplSettings settings;
}
|
package net.optifine;
public class TextureAnimationFrame {
public int index;
public int duration;
public int counter;
public TextureAnimationFrame(final int index, final int duration)
{
this.index = index;
this.duration = duration;
this.counter = 0;
}
}
|
package am.main.data.jaxb.log4jData;
import javax.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the am.main.data.jaxb.log4jData package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and amt.model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: am.main.data.jaxb.log4jData
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link Configuration }
*
*/
public Configuration createConfiguration() {
return new Configuration();
}
/**
* Create an instance of {@link Loggers }
*
*/
public Loggers createConfigurationLoggers() {
return new Loggers();
}
/**
* Create an instance of {@link Logger }
*
*/
public Logger createConfigurationLoggersLogger() {
return new Logger();
}
/**
* Create an instance of {@link Root }
*
*/
public Root createConfigurationLoggersRoot() {
return new Root();
}
/**
* Create an instance of {@link Appenders }
*
*/
public Appenders createConfigurationAppenders() {
return new Appenders();
}
/**
* Create an instance of {@link RollingFile }
*
*/
public RollingFile createConfigurationAppendersRollingFile() {
return new RollingFile();
}
/**
* Create an instance of {@link Policies }
*
*/
public Policies createConfigurationAppendersRollingFilePolicies() {
return new Policies();
}
/**
* Create an instance of {@link Console }
*
*/
public Console createConfigurationAppendersConsole() {
return new Console();
}
/**
* Create an instance of {@link AppenderRef }
*
*/
public AppenderRef createConfigurationLoggersLoggerAppenderRef() {
return new AppenderRef();
}
/**
* Create an instance of {@link AppenderRef }
*
*/
public AppenderRef createConfigurationLoggersRootAppenderRef() {
return new AppenderRef();
}
/**
* Create an instance of {@link PatternLayout }
*
*/
public PatternLayout createConfigurationAppendersRollingFilePatternLayout() {
return new PatternLayout();
}
/**
* Create an instance of {@link SizeBasedTriggeringPolicy }
*
*/
public SizeBasedTriggeringPolicy createConfigurationAppendersRollingFilePoliciesSizeBasedTriggeringPolicy() {
return new SizeBasedTriggeringPolicy();
}
/**
* Create an instance of {@link PatternLayout }
*
*/
public PatternLayout createConfigurationAppendersConsolePatternLayout() {
return new PatternLayout();
}
}
|
package com.Mingyang.GossipBoard;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GossipBoardApplication {
public static void main(String[] args) {
SpringApplication.run(GossipBoardApplication.class, args);
}
}
|
package lesson5.task3;
public class DoWhile {
public static void main(String args[]) {
int n = 1;
while (n < 11) {
n = getN(n);
}
}
private static int getN(int n) {
System.out.println("Task " + n);
n++;
return n;
}
}
|
package pattern_test.abstract_factory;
/**
* Description:
*
* @author Baltan
* @date 2019-04-02 11:09
*/
public class WheelB implements Wheel {
public WheelB() {
System.out.println("生产WheelB");
}
}
|
package com.tencent.mm.protocal;
import com.tencent.mm.protocal.c.g;
public class c$ee extends g {
public c$ee() {
super("nfcConnect", "nfcConnect", 140, false);
}
}
|
package com.dmzj.manhua.push;
import android.content.Context;
public class MessagePushTool {
public static native void onMessageObtain(Context context, String title,
String description, String customContentString);
public static native void onBaiduBind(String appid,String userId, String
channelId, String requestId);
}
|
package com.company;
public class Male extends Person {
public Male(int age, String gender) {
super(age, gender);
}
@Override
void talk() {
System.out.println("Person who talk is a men");
}
@Override
public String toString() {
return "Male{" +
"age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
|
package com.example.icebuild2;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.HashMap;
public class SetQuizActivity extends AppCompatActivity {
private EditText Question,option1,option2,option3,option4;
private RadioButton optnA,optnB,optnC,optnD;
private Button SetQuestionBtn;
private RadioGroup radioGroup;
int noOfQuestions,counter;
private String currentBoardName;
private DatabaseReference QuizzesRef;
private HashMap<String,Object> Questions;
private Toolbar mToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_quiz);
noOfQuestions=getIntent().getIntExtra("noOfQuestions",0);
currentBoardName = getIntent().getStringExtra("BoardName");
counter=1;
////////////////////////////////////////////////////////////////////////////////////////////
mToolbar=(Toolbar)findViewById(R.id.SetQuiz_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Set Quiz for "+currentBoardName);
////////////////////////////////////////////////////////////////////////////////////////////
QuizzesRef=FirebaseDatabase.getInstance().getReference().child("Board Quizzes").child(currentBoardName);
initializeFields();
SetQuestionBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
verifyAndAddQuestion();
}
});
}
private void initializeFields() {
Questions=new HashMap<>();
SetQuestionBtn=(Button)findViewById(R.id.setQuestionBtn);
////////////////////////////////////////////////////////////////////////////////////////////
Question=(EditText)findViewById(R.id.QuestionEditText);
option1=(EditText)findViewById(R.id.Option1EditText);
option2=(EditText)findViewById(R.id.Option2EditText);
option3=(EditText)findViewById(R.id.Option3EditText);
option4=(EditText)findViewById(R.id.Option4EditText);
////////////////////////////////////////////////////////////////////////////////////////////
radioGroup=(RadioGroup)findViewById(R.id.RadioGroupofSetting);
////////////////////////////////////////////////////////////////////////////////////////////
optnA=(RadioButton) radioGroup.findViewById(R.id.optionARadioBtn);
optnB=(RadioButton) radioGroup.findViewById(R.id.optionBRadioBtn);
optnC=(RadioButton) radioGroup.findViewById(R.id.optionCRadioBtn);
optnD=(RadioButton) radioGroup.findViewById(R.id.optionDRadioBtn);
////////////////////////////////////////////////////////////////////////////////////////////
}
private void verifyAndAddQuestion() {
String question,optionA,optionB,optionC,optionD,correctAnswer;
question=Question.getText().toString();
if(question.isEmpty()){
Question.setError("A valid Question required");
Question.requestFocus();
return;
}
optionA=option1.getText().toString();
if(optionA.isEmpty()){
option1.setError("A valid Option required");
option1.requestFocus();
return;
}
optionB=option2.getText().toString();
if(optionB.isEmpty()){
option2.setError("A valid Question required");
option2.requestFocus();
return;
}
optionC=option3.getText().toString();
if(optionC.isEmpty()){
option3.setError("A valid Question required");
option3.requestFocus();
return;
}
optionD=option4.getText().toString();
if(optionD.isEmpty()){
option4.setError("A valid Question required");
option4.requestFocus();
return;
}
int radioButtonID=radioGroup.getCheckedRadioButtonId();
if(radioButtonID==R.id.optionARadioBtn){
correctAnswer=optionA;
}else if(radioButtonID==R.id.optionBRadioBtn){
correctAnswer=optionB;
}else if(radioButtonID==R.id.optionCRadioBtn){
correctAnswer=optionC;
}else if(radioButtonID==R.id.optionDRadioBtn){
correctAnswer=optionD;
}else{
Toast.makeText(this, "Error: Correct option Required "+ radioButtonID+" "+R.id.optionARadioBtn, Toast.LENGTH_SHORT).show();
return;
}
HashMap<String,Object> QuestionInfoMap=new HashMap<>();
QuestionInfoMap.put("question",question);
QuestionInfoMap.put("option1",optionA);
QuestionInfoMap.put("option2",optionB);
QuestionInfoMap.put("option3",optionC);
QuestionInfoMap.put("option4",optionD);
QuestionInfoMap.put("answer",correctAnswer);
addQuestion(QuestionInfoMap);
}
private void addQuestion(HashMap<String, Object> questionInfoMap) {
Questions.put("Question "+counter,questionInfoMap);
QuizzesRef.child("Question_"+counter).updateChildren(questionInfoMap).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(SetQuizActivity.this, "Question Added.", Toast.LENGTH_SHORT).show();
resetFields();
counter++;
if(counter>noOfQuestions){
QuizzesRef.child("Total_Questions").setValue(counter-1).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(SetQuizActivity.this, "Quiz Successfully Added.", Toast.LENGTH_SHORT).show();
sendTeacherToTheDrawerActivity();
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(SetQuizActivity.this, "Error, Try Setting Again.", Toast.LENGTH_SHORT).show();
}
});
}
private void sendTeacherToTheDrawerActivity() {
Intent intent=new Intent(SetQuizActivity.this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
private void resetFields() {
Question.setText("");
option1.setText("");
option2.setText("");
option3.setText("");
option4.setText("");
radioGroup.clearCheck();
}
}
|
package com.jadn.cc.services;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
/*
* Based on http://www.androidcompetencycenter.com/2009/06/start-service-at-boot/
*/
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(context);
if(app_preferences.getBoolean("autoDownload", false)) {
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.jadn.cc.services.AlarmHostService");
context.startService(serviceIntent);
}
}
}
|
package com.takeaway.gameofthree.event.service;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.takeaway.gameofthree.event.model.GameMoveEvent;
import lombok.extern.slf4j.Slf4j;
/**
*
* @author Bharadwaj.Adepu
*
*/
@Slf4j
@Service
public class GameEventProducer {
private enum PLAYER{PLAYER1, PLAYER2}
@Value("${config.rabbitmq.routingkey.player1}")
private String player1RoutingKey;
@Value("${config.rabbitmq.routingkey.player2}")
private String player2RoutingKey;
@Autowired
private AmqpTemplate rabbitCustomTemplate;
public void send(GameMoveEvent moveEvent) {
if(moveEvent.getMoveBy().equalsIgnoreCase(PLAYER.PLAYER2.name()))
rabbitCustomTemplate.convertAndSend(player1RoutingKey, moveEvent);
else
rabbitCustomTemplate.convertAndSend(player2RoutingKey, moveEvent);
log.info("Event created for GapmeMove = {} by Player: {}", moveEvent, moveEvent.getMoveBy());
}
}
|
//Author: Timothy van der Graaff
package views;
import java.util.ArrayList;
import utilities.Form_Validation;
import utilities.Find_and_replace;
public class Show_For_Sale_Item_Details {
//global variables
public static ArrayList<ArrayList<String>> for_sale_item_details = new ArrayList<>();
public static ArrayList<ArrayList<String>> for_sale_item_additional_pictures = new ArrayList<>();
public static ArrayList<ArrayList<String>> for_sale_item_reviews = new ArrayList<>();
public static int page_number_count;
public static String show_for_sale_item_details() {
String output = "";
ArrayList<String> find = new ArrayList<>();
ArrayList<String> replace = new ArrayList<>();
find.add("<script");
find.add("<style");
find.add("\"");
find.add("'");
find.add("<br />");
find.add("<br>");
find.add("<div>");
find.add("</div>");
replace.add("<script");
replace.add("<style");
replace.add(""");
replace.add("'");
replace.add(" ");
replace.add("");
replace.add("");
replace.add("");
output += "[";
for (int i = 0; i < for_sale_item_details.get(0).size(); i++) {
output += "{\"row_id\": \"" +
Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_item_details.get(0).get(i)).replace("<", "<").replace(">", ">")) +
"\", \"item\": \"" +
Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_item_details.get(1).get(i)).replace("<", "<").replace(">", ">")) +
"\", \"thumbnail\": \"" +
Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_item_details.get(2).get(i)).replace("<", "<").replace(">", ">")) +
"\", \"item_category\": \"" +
Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_item_details.get(3).get(i)).replace("<", "<").replace(">", ">")) +
"\", \"description\": \"" +
Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_item_details.get(4).get(i)).replace("<", "<").replace(">", ">")) +
"\", \"price\": \"" +
Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_item_details.get(5).get(i)).replace("<", "<").replace(">", ">")) +
"\", \"inventory\": \"" +
Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_item_details.get(6).get(i)).replace("<", "<").replace(">", ">")) +
"\"}, ";
}
output += "{}]";
output = output.replace(", {}", "");
return output;
}
public static String show_for_sale_item_additional_pictures() {
String output = "";
ArrayList<String> find = new ArrayList<>();
ArrayList<String> replace = new ArrayList<>();
find.add("<script");
find.add("<style");
find.add("\"");
find.add("'");
find.add("<br />");
find.add("<br>");
find.add("<div>");
find.add("</div>");
replace.add("<script");
replace.add("<style");
replace.add(""");
replace.add("'");
replace.add(" ");
replace.add("");
replace.add("");
replace.add("");
output += "[";
for (int i = 0; i < for_sale_item_additional_pictures.get(0).size(); i++) {
output += "{\"row_id\": \"" +
Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_item_additional_pictures.get(0).get(i)).replace("<", "<").replace(">", ">")) +
"\", \"thumbnail\": \"" +
Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_item_additional_pictures.get(1).get(i)).replace("<", "<").replace(">", ">")) +
"\"}, ";
}
output += "{}]";
output = output.replace(", {}", "");
return output;
}
public static String show_for_sale_item_reviews() {
String output = "";
ArrayList<String> find = new ArrayList<>();
ArrayList<String> replace = new ArrayList<>();
find.add("<script");
find.add("<style");
find.add("\"");
find.add("'");
find.add("<br />");
find.add("<br>");
find.add("<div>");
find.add("</div>");
replace.add("<script");
replace.add("<style");
replace.add(""");
replace.add("'");
replace.add(" ");
replace.add("");
replace.add("");
replace.add("");
output += "[";
for (int i = 0; i < for_sale_item_reviews.get(0).size(); i++) {
output += "{\"row_id\": \"" +
Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_item_reviews.get(0).get(i)).replace("<", "<").replace(">", ">")) +
"\", \"item_id\": \"" +
Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_item_reviews.get(1).get(i)).replace("<", "<").replace(">", ">")) +
"\", \"rating\": \"" +
Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_item_reviews.get(2).get(i)).replace("<", "<").replace(">", ">"));
if (Form_Validation.is_string_null_or_white_space(for_sale_item_reviews.get(3).get(i))) {
output += "\", \"subject\": \"No subject";
} else {
output += "\", \"subject\": \"" +
Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_item_reviews.get(3).get(i)).replace("<", "<").replace(">", ">"));
}
if (Form_Validation.is_string_null_or_white_space(for_sale_item_reviews.get(4).get(i))) {
output += "\", \"description\": \"No comment";
} else {
output += "\", \"description\": \"" +
Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_item_reviews.get(4).get(i)).replace("<", "<").replace(">", ">"));
}
if (Form_Validation.is_string_null_or_white_space(for_sale_item_reviews.get(5).get(i))) {
output += "\", \"name\": \"Anonymous";
} else {
output += "\", \"name\": \"" +
Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_item_reviews.get(5).get(i)).replace("<", "<").replace(">", ">"));
}
if (Form_Validation.is_string_null_or_white_space(for_sale_item_reviews.get(6).get(i))) {
output += "\", \"date_received\": \"Not specified";
} else {
output += "\", \"date_received\": \"" +
Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_item_reviews.get(6).get(i)).replace("<", "<").replace(">", ">"));
}
output += "\"}, ";
}
output += "{}]";
output = output.replace(", {}", "");
return output;
}
public static String show_page_numbers() {
String output = "";
output += "[";
for (int i = 0; i < page_number_count; i++) {
output += "{\"page_number\": \"" + (i + 1) + "\"}, ";
}
output += "{}]";
output = output.replace(", {}", "");
return output;
}
}
|
package cn.lbxx;
import java.net.ConnectException;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class HandleRequest extends Thread {
private static String KHost = "Host:";
private Socket clSocket ;
private Socket seSocket ;
private Scanner cdata ;
protected String remotehost ;
protected int remoteport ;
protected boolean https ;
private List<String> bufflist ;
public HandleRequest(Socket c){
this.clSocket = c;
this.bufflist = new ArrayList<String>();
}
public void run()
{
try {
cdata = new Scanner(clSocket.getInputStream());
int beginIndex = KHost.length() + 1;
String line;
while(cdata.hasNextLine() && (line = cdata.nextLine()).length() != 0)
{
if(line.length() > 5)
{
if(line.substring(0, KHost.length()).equals(KHost))
{
int hend;
if((hend = line.indexOf(':', beginIndex)) != -1)
{
remotehost = line.substring(beginIndex, hend);
remoteport = Integer.parseInt(line.substring(hend + 1));
} else {
remotehost = line.substring(beginIndex);
remoteport = 80;
}
}
if(line.substring(0, line.indexOf(' ')).equals("CONNECT")){
https = true;
}
}
bufflist.add(line);
}
System.out.println(remotehost + " -> " + remoteport + " " + https);
if(remotehost != null)
{
seSocket = new Socket(remotehost, remoteport);
if (https) {
List<String> list = new ArrayList<>();
list.add("HTTP/1.1 200 Connection Established");
new ForwardData(list, seSocket, clSocket).start();
new ForwardData(null, clSocket, seSocket).start();
} else {
toUri(bufflist);
new ForwardData(bufflist, clSocket, seSocket).start();
new ForwardData(null, seSocket, clSocket).start();
}
}
} catch (ConnectException c) {
System.err.println("连接超时");
} catch (SocketException se) {
System.err.println("无法连接-> " + remotehost + ":" + remoteport);
} catch (Exception e) {
System.err.println("发生错误" + e);
}
}
private void toUri(List<String> buff)
{
for (int i = 0; i < buff.size(); i++)
{
String line = buff.get(i);
String head = line.substring(0, line.indexOf(' '));
int hlen = head.length() + 1;
if(line.substring(hlen, hlen + 7).equals("http://"))
{
String uri = line.substring(line.indexOf('/', hlen + 7));
buff.set(i, head + " " + uri);
break;
}
}
}
}
|
package com.company;
import java.util.Scanner;
public class Eleventh {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.next(),str1 = "";
int n = in.nextInt();
for (int i = 0; i < str.length(); i++) {
if (i != n - 1)
str1 += str.charAt(i);
}
System.out.println(str1);
}
}
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.numix.calculator;
import java.util.List;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.numix.calculator.BaseModule.Mode;
import com.numix.calculator.Calculator.Panel;
import com.numix.calculator.view.MatrixEditText;
import com.numix.calculator.view.MatrixInverseView;
import com.numix.calculator.view.MatrixTransposeView;
import com.numix.calculator.view.MatrixView;
public class EventListener implements View.OnKeyListener, View.OnClickListener, View.OnLongClickListener {
Context mContext;
Logic mHandler;
ViewPager mPager;
ViewPager mSmallPager;
ViewPager mLargePager;
private String mErrorString;
private String mModString;
private String mX;
private String mY;
private String mDX;
private String mDY;
void setHandler(Context context, Logic handler, ViewPager pager) {
setHandler(context, handler, pager, null, null);
}
void setHandler(Context context, Logic handler, ViewPager smallPager, ViewPager largePager) {
setHandler(context, handler, null, smallPager, largePager);
}
private void setHandler(Context context, Logic handler, ViewPager pager, ViewPager smallPager, ViewPager largePager) {
mContext = context;
mHandler = handler;
mPager = pager;
mSmallPager = smallPager;
mLargePager = largePager;
mErrorString = mContext.getString(R.string.error);
mModString = mContext.getString(R.string.mod);
mX = mContext.getString(R.string.X);
mY = mContext.getString(R.string.Y);
mDX = mContext.getString(R.string.dx);
mDY = mContext.getString(R.string.dy);
}
@Override
public void onClick(View view) {
View v;
EditText active;
int id = view.getId();
switch(id) {
case R.id.del:
mHandler.onDelete();
break;
case R.id.clear:
mHandler.onClear();
break;
case R.id.equal:
if(mHandler.getText().contains(mX) || mHandler.getText().contains(mY)) {
if(!mHandler.getText().contains("=")) {
mHandler.insert("=");
returnToBasic();
}
break;
}
mHandler.onEnter();
break;
case R.id.hex:
mHandler.setText(mHandler.mBaseModule.setMode(Mode.HEXADECIMAL));
view.setSelected(true);
((View) view.getParent()).findViewById(R.id.bin).setSelected(false);
((View) view.getParent()).findViewById(R.id.dec).setSelected(false);
applyAllBannedResources(mHandler.mBaseModule, Mode.HEXADECIMAL);
break;
case R.id.bin:
mHandler.setText(mHandler.mBaseModule.setMode(Mode.BINARY));
view.setSelected(true);
((View) view.getParent()).findViewById(R.id.hex).setSelected(false);
((View) view.getParent()).findViewById(R.id.dec).setSelected(false);
applyAllBannedResources(mHandler.mBaseModule, Mode.BINARY);
break;
case R.id.dec:
mHandler.setText(mHandler.mBaseModule.setMode(Mode.DECIMAL));
view.setSelected(true);
((View) view.getParent()).findViewById(R.id.bin).setSelected(false);
((View) view.getParent()).findViewById(R.id.hex).setSelected(false);
applyAllBannedResources(mHandler.mBaseModule, Mode.DECIMAL);
break;
case R.id.matrix:
mHandler.insert(MatrixView.getPattern(mContext));
returnToBasic();
break;
case R.id.matrix_inverse:
mHandler.insert(MatrixInverseView.PATTERN);
returnToBasic();
break;
case R.id.matrix_transpose:
mHandler.insert(MatrixTransposeView.PATTERN);
returnToBasic();
break;
case R.id.plus_row:
v = mHandler.mDisplay.getActiveEditText();
if(v instanceof MatrixEditText) ((MatrixEditText) v).getMatrixView().addRow();
break;
case R.id.minus_row:
v = mHandler.mDisplay.getActiveEditText();
if(v instanceof MatrixEditText) ((MatrixEditText) v).getMatrixView().removeRow();
break;
case R.id.plus_col:
v = mHandler.mDisplay.getActiveEditText();
if(v instanceof MatrixEditText) ((MatrixEditText) v).getMatrixView().addColumn();
break;
case R.id.minus_col:
v = mHandler.mDisplay.getActiveEditText();
if(v instanceof MatrixEditText) ((MatrixEditText) v).getMatrixView().removeColumn();
break;
case R.id.next:
if(mHandler.getText().equals(mErrorString)) mHandler.setText("");
active = mHandler.mDisplay.getActiveEditText();
if(active.getSelectionStart() == active.getText().length()) {
v = mHandler.mDisplay.getActiveEditText().focusSearch(View.FOCUS_FORWARD);
if(v != null) v.requestFocus();
active = mHandler.mDisplay.getActiveEditText();
active.setSelection(0);
}
else {
active.setSelection(active.getSelectionStart() + 1);
}
break;
// +/-, changes the sign of the current number. Might be useful later
// (but removed for now)
// case R.id.sign:
// if(mHandler.getText().equals(mErrorString)) mHandler.setText("");
// active = mHandler.mDisplay.getActiveEditText();
// int selection = active.getSelectionStart();
// if(active.getText().toString().matches(Logic.NUMBER)) {
// if(active.getText().toString().startsWith(String.valueOf(Logic.MINUS)))
// {
// active.setText(active.getText().toString().substring(1));
// selection--;
// }
// else {
// active.setText(Logic.MINUS + active.getText().toString());
// selection++;
// }
// if(selection > active.length()) selection--;
// if(selection < 0) selection = 0;
// active.setSelection(selection);
// }
// break;
case R.id.parentheses:
if(mHandler.getText().equals(mErrorString)) mHandler.setText("");
if(mHandler.getText().contains("=")) {
String[] equation = mHandler.getText().split("=");
if(equation.length > 1) {
mHandler.setText(equation[0] + "=(" + equation[1] + ")");
}
else {
mHandler.setText(equation[0] + "=()");
}
}
else {
mHandler.setText("(" + mHandler.getText() + ")");
}
returnToBasic();
break;
case R.id.mod:
if(mHandler.getText().equals(mErrorString)) mHandler.setText("");
if(mHandler.getText().contains("=")) {
String[] equation = mHandler.getText().split("=");
if(equation.length > 1) {
mHandler.setText(equation[0] + "=" + mModString + "(" + equation[1] + ",");
}
else {
mHandler.insert(mModString + "(");
}
}
else {
if(mHandler.getText().length() > 0) {
mHandler.setText(mModString + "(" + mHandler.getText() + ",");
}
else {
mHandler.insert(mModString + "(");
}
}
returnToBasic();
break;
case R.id.easter:
Toast.makeText(mContext, R.string.easter_egg, Toast.LENGTH_SHORT).show();
break;
default:
if(view instanceof Button) {
String text = ((Button) view).getText().toString();
if(text.equals(mDX) || text.equals(mDY)) {
// Do nothing
}
else if(text.length() >= 2) {
// Add paren after sin, cos, ln, etc. from buttons
text += "(";
}
mHandler.insert(text);
returnToBasic();
}
}
}
private void applyAllBannedResources(BaseModule base, Mode baseMode) {
for(Mode key : base.mBannedResources.keySet()) {
if(baseMode.compareTo(key) != 0) {
applyBannedResources(base, key, true);
}
}
applyBannedResources(base, baseMode, false);
}
private void applyBannedResources(BaseModule base, Mode baseMode, boolean enabled) {
List<Integer> resources = base.mBannedResources.get(baseMode);
ViewPager pager = mPager != null ? mPager : mSmallPager;
for(Integer resource : resources) {
final int resId = resource.intValue();
// There are multiple views with the same id,
// but the id is unique per page
// Find ids on every page
int count = pager.getAdapter().getCount();
for(int i = 0; i < count; i++) {
View child = ((CalculatorPageAdapter) pager.getAdapter()).getViewAt(i);
View v = child.findViewById(resId);
if(v != null) {
v.setEnabled(enabled);
}
}
// An especial check when current pager is mLargePager
if(mPager == null && mLargePager != null) {
count = mLargePager.getAdapter().getCount();
for(int i = 0; i < count; i++) {
View child = ((CalculatorPageAdapter) mLargePager.getAdapter()).getViewAt(i);
View v = child.findViewById(resId);
if(v != null) {
v.setEnabled(enabled);
}
}
}
}
}
@Override
public boolean onLongClick(View view) {
switch(view.getId()) {
case R.id.del:
mHandler.onClear();
return true;
case R.id.next:
// Handle back
EditText active = mHandler.mDisplay.getActiveEditText();
if(active.getSelectionStart() == 0) {
View v = mHandler.mDisplay.getActiveEditText().focusSearch(View.FOCUS_BACKWARD);
if(v != null) v.requestFocus();
active = mHandler.mDisplay.getActiveEditText();
active.setSelection(active.getText().length());
}
else {
active.setSelection(active.getSelectionStart() - 1);
}
return true;
}
if(view.getTag() != null) {
String text = (String) view.getTag();
if(!text.isEmpty()) {
Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
return true;
}
}
if(view instanceof TextView && ((TextView) view).getHint() != null) {
String text = ((TextView) view).getHint().toString();
if(text.length() >= 2) {
// Add paren after sin, cos, ln, etc. from buttons
text += "(";
}
mHandler.insert(text);
returnToBasic();
return true;
}
return false;
}
@Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
int action = keyEvent.getAction();
// Work-around for spurious key event from IME, bug #1639445
if(action == KeyEvent.ACTION_MULTIPLE && keyCode == KeyEvent.KEYCODE_UNKNOWN) {
return true; // eat it
}
if(keyEvent.getUnicodeChar() == '=') {
if(action == KeyEvent.ACTION_UP) {
mHandler.onEnter();
}
return true;
}
if(keyCode != KeyEvent.KEYCODE_DPAD_CENTER && keyCode != KeyEvent.KEYCODE_DPAD_UP && keyCode != KeyEvent.KEYCODE_DPAD_DOWN
&& keyCode != KeyEvent.KEYCODE_ENTER) {
if(keyEvent.isPrintingKey() && action == KeyEvent.ACTION_UP) {
// Tell the handler that text was updated.
mHandler.onTextChanged();
}
return false;
}
/*
* We should act on KeyEvent.ACTION_DOWN, but strangely sometimes the
* DOWN event isn't received, only the UP. So the workaround is to act
* on UP... http://b/issue?id=1022478
*/
if(action == KeyEvent.ACTION_UP) {
switch(keyCode) {
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_DPAD_CENTER:
mHandler.onEnter();
break;
case KeyEvent.KEYCODE_DPAD_UP:
mHandler.onUp();
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
mHandler.onDown();
break;
}
}
return true;
}
private boolean returnToBasic() {
if(mPager != null && mPager.getCurrentItem() != Panel.BASIC.getOrder() && CalculatorSettings.returnToBasic(mContext)) {
mPager.setCurrentItem(Panel.BASIC.getOrder());
return true;
}
return false;
}
}
|
package Puzzles.GlobalLogic.Anagrams;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Map;
/**
* Created by skyll on 05.10.2017.
*/
public class Runner {
public static void main(String[] args) {
System.out.print("String 1: ");
String string1 = readLine();
System.out.print("String 2: ");
String string2 = readLine();
Anagram anagram = new Anagram(string1, string2);
Anagram test1 = new Anagram("abcdef", "bcdaef");
Anagram test2 = new Anagram("abcdef", "aacdfg");
Anagram test3 = new Anagram("abcdffff", "aacdffea");
System.out.println(getResult(anagram));
System.out.println(getResult(test1));
System.out.println(getResult(test2));
System.out.println(getResult(test3));
}
private static String readLine() {
try {
return new BufferedReader(new InputStreamReader(System.in)).readLine();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
private static String getResult(Anagram anagram) {
if (anagram.isAnagram()) {
return "Strings are anagrams";
} else {
return getMissingCharacters(anagram);
}
}
/**
* To get the characters you need to change in string1 to make string2 an anagram, I check
* the character presence from string2 at string1. If the character is absent,
* then we add him to the missingChar. And if amount of certain character at the
* string1 is more than in string2, we add him to missingChar too.
*
* Since the task does not have an exact condition for all possible solutions,
* we get all the characters that need to be replaced in string1.
* Conditions can be changed in code, which is marked with comment 1 (below).
*/
private static String getMissingCharacters(Anagram anagram) {
String missingChar = "";
Map<Character, Integer> map1 = Anagram.getMap(anagram.getString1());
Map<Character, Integer> map2 = Anagram.getMap(anagram.getString2());
for (Map.Entry<Character, Integer> pair : map1.entrySet()) {
if (!map2.containsKey(pair.getKey())) {
missingChar += pair.getKey().toString();
} else {
if (map2.get(pair.getKey()) < (pair.getValue())) { // ####
for (int i = map2.get(pair.getKey()); i < pair.getValue(); i++) { // ##
missingChar += pair.getKey().toString(); // ##
} // ##
} // ######
}
}
return Arrays.toString(missingChar.toCharArray());
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.catalogversions.impl;
import de.hybris.platform.catalog.CatalogService;
import de.hybris.platform.catalog.CatalogVersionService;
import de.hybris.platform.catalog.model.CatalogModel;
import de.hybris.platform.catalog.model.CatalogVersionModel;
import de.hybris.platform.cms2.catalogversion.service.CMSCatalogVersionService;
import de.hybris.platform.cms2.exceptions.CMSItemNotFoundException;
import de.hybris.platform.cms2.model.site.CMSSiteModel;
import de.hybris.platform.cms2.servicelayer.services.admin.CMSAdminSiteService;
import de.hybris.platform.cmsfacades.catalogversions.CatalogVersionFacade;
import de.hybris.platform.cmsfacades.catalogversions.service.PageDisplayConditionService;
import de.hybris.platform.cmsfacades.data.CatalogVersionData;
import de.hybris.platform.core.model.security.PrincipalModel;
import de.hybris.platform.servicelayer.dto.converter.Converter;
import java.util.List;
import java.util.Objects;
import de.hybris.platform.servicelayer.user.UserService;
import org.springframework.beans.factory.annotation.Required;
import static java.util.stream.Collectors.toList;
/**
* Facade interface which deals with methods related to catalog version operations.
*/
public class DefaultCatalogVersionFacade implements CatalogVersionFacade
{
private CatalogVersionService catalogVersionService;
private Converter<CatalogVersionModel, CatalogVersionData> cmsCatalogVersionConverter;
private PageDisplayConditionService pageDisplayConditionService;
private CMSCatalogVersionService cmsCatalogVersionService;
private CatalogService catalogService;
private CMSAdminSiteService cmsAdminSiteService;
private UserService userService;
@Override
public CatalogVersionData getCatalogVersion(final String catalogId, final String versionId) throws CMSItemNotFoundException
{
final CatalogVersionModel catalogVersionModel = getCatalogVersionService().getCatalogVersion(catalogId, versionId);
// populate basic information : catalog id, name and version
final CatalogVersionData catalogVersion = getCmsCatalogVersionConverter().convert(catalogVersionModel);
if (Objects.isNull(catalogVersion))
{
throw new CMSItemNotFoundException("Cannot find catalog version");
}
// find all page display options per page type
catalogVersion.setPageDisplayConditions(getPageDisplayConditionService().getDisplayConditions());
return catalogVersion;
}
@Override
public List<CatalogVersionData> getWritableContentCatalogVersionTargets(final String siteId, final String catalogId,
final String versionId)
{
CatalogModel catalogModel = getCatalogService().getCatalogForId(catalogId);
final CMSSiteModel siteModel = getCmsAdminSiteService().getSiteForId(siteId);
PrincipalModel principalModel = getUserService().getCurrentUser();
CatalogVersionModel catalogVersionModel = getCatalogVersionService().getCatalogVersion(catalogId, versionId);
List<CatalogVersionModel> catalogVersionModels = null;
if (catalogVersionModel.getActive())
{
catalogVersionModels = getCmsCatalogVersionService()
.getWritableChildContentCatalogVersions(principalModel, siteModel, catalogModel);
}
else
{
catalogVersionModels = getCmsCatalogVersionService()
.getWritableContentCatalogVersions(principalModel, catalogModel);
}
return convertToListData(catalogVersionModels);
}
protected List<CatalogVersionData> convertToListData(List<CatalogVersionModel> catalogVersionModels)
{
return catalogVersionModels.stream()
.map(versionModel ->
getCmsCatalogVersionConverter().convert(versionModel)).collect(toList());
}
protected Converter<CatalogVersionModel, CatalogVersionData> getCmsCatalogVersionConverter()
{
return cmsCatalogVersionConverter;
}
@Required
public void setCmsCatalogVersionConverter(final Converter<CatalogVersionModel, CatalogVersionData> cmsCatalogVersionConverter)
{
this.cmsCatalogVersionConverter = cmsCatalogVersionConverter;
}
protected CatalogVersionService getCatalogVersionService()
{
return catalogVersionService;
}
@Required
public void setCatalogVersionService(final CatalogVersionService catalogVersionService)
{
this.catalogVersionService = catalogVersionService;
}
protected PageDisplayConditionService getPageDisplayConditionService()
{
return pageDisplayConditionService;
}
@Required
public void setPageDisplayConditionService(final PageDisplayConditionService pageDisplayConditionService)
{
this.pageDisplayConditionService = pageDisplayConditionService;
}
protected CMSCatalogVersionService getCmsCatalogVersionService()
{
return cmsCatalogVersionService;
}
@Required
public void setCmsCatalogVersionService(CMSCatalogVersionService cmsCatalogVersionService)
{
this.cmsCatalogVersionService = cmsCatalogVersionService;
}
protected CatalogService getCatalogService()
{
return catalogService;
}
@Required
public void setCatalogService(CatalogService catalogService)
{
this.catalogService = catalogService;
}
protected CMSAdminSiteService getCmsAdminSiteService()
{
return cmsAdminSiteService;
}
@Required
public void setCmsAdminSiteService(CMSAdminSiteService cmsAdminSiteService)
{
this.cmsAdminSiteService = cmsAdminSiteService;
}
protected UserService getUserService()
{
return userService;
}
@Required
public void setUserService(UserService userService)
{
this.userService = userService;
}
}
|
package com.appc.report.common.enums;
public enum EncodingType {
UTF8("utf8"), GBK("gbk"), ISO8859_1("iso8859_1"), GB2312("gb2312");
private String code;
EncodingType(String code) {
this.code = code;
}
public static DataSourseType getTypeByCode(String code) {
for (DataSourseType element : DataSourseType.values()) {
if (element.getCode().equals(code)) {
return element;
}
}
return null;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
|
package com.flutterwave.raveandroid.ach;
import com.flutterwave.raveandroid.rave_java_commons.Payload;
public class NullAchView implements AchUiContract.View {
@Override
public void showProgressIndicator(boolean active) {
}
@Override
public void onAmountValidated(String amountToSet, int visibility) {
}
@Override
public void showRedirectMessage(boolean b) {
}
@Override
public void onPaymentError(String message) {
}
@Override
public void showWebView(String authUrl, String flwRef) {
}
@Override
public void onPaymentFailed(String responseAsJSONString) {
}
@Override
public void onTransactionFeeRetrieved(String chargeAmount, Payload payload, String fee) {
}
@Override
public void onPaymentSuccessful(String responseAsJSONString) {
}
@Override
public void onFeeFetchError(String errorMessage) {
}
@Override
public void showAmountError(String msg) {
}
@Override
public void showFee(String authUrl, String flwRef, String chargedAmount, String currency) {
}
@Override
public void onValidationSuccessful(String amount) {
}
}
|
package fr.jmini.htmlchecker;
import static org.junit.Assert.assertEquals;
import java.io.File;
import org.junit.Before;
import org.junit.Test;
import com.google.common.io.Files;
public class HtmlUtilityTest {
protected File tempDirectory;
@Before
public void before() throws Exception {
tempDirectory = Files.createTempDir();
tempDirectory.deleteOnExit();
}
@Test
public void testComputeRelPathFile() {
assertEquals("", HtmlUtility.computeRelPath(new File(new File(new File(tempDirectory, "site"), "folder"), "page1.html"), new File(new File(new File(tempDirectory, "site"), "folder"), "page1.html")));
assertEquals("", HtmlUtility.computeRelPath((File) null, (File) null));
assertEquals("", HtmlUtility.computeRelPath(null, tempDirectory));
assertEquals("", HtmlUtility.computeRelPath(tempDirectory, null));
assertEquals("", HtmlUtility.computeRelPath(new File(tempDirectory, "page1.html"), new File(tempDirectory, "page2.html")));
assertEquals("", HtmlUtility.computeRelPath(new File(new File(tempDirectory, "folder"), "page1.html"), new File(new File(tempDirectory, "folder"), "page1.html")));
assertEquals("site/folder/", HtmlUtility.computeRelPath(new File(tempDirectory, "index.html"), new File(new File(new File(tempDirectory, "site"), "folder"), "page1.html")));
assertEquals("dir/", HtmlUtility.computeRelPath(new File(new File(tempDirectory, "folder"), "page1.html"), new File(new File(new File(tempDirectory, "folder"), "dir"), "page1.html")));
assertEquals("../", HtmlUtility.computeRelPath(new File(new File(tempDirectory, "folder"), "page1.html"), new File(tempDirectory, "page2.html")));
assertEquals("../site/folder/", HtmlUtility.computeRelPath(new File(new File(tempDirectory, "archive"), "page1.html"), new File(new File(new File(tempDirectory, "site"), "folder"), "page1.html")));
}
@Test
public void testComputeRelPathString() {
assertEquals("", HtmlUtility.computeRelPath("site/folder/page1.html", "site/folder/page1.html"));
assertEquals("", HtmlUtility.computeRelPath("", ""));
assertEquals("", HtmlUtility.computeRelPath((String) null, (String) null));
assertEquals("", HtmlUtility.computeRelPath(null, ""));
assertEquals("", HtmlUtility.computeRelPath("", null));
assertEquals("", HtmlUtility.computeRelPath("index.html", "page2.html"));
assertEquals("", HtmlUtility.computeRelPath("index.html", "/page2.html"));
assertEquals("", HtmlUtility.computeRelPath("/index.html", "page2.html"));
assertEquals("", HtmlUtility.computeRelPath("/index.html", "/page2.html"));
assertEquals("", HtmlUtility.computeRelPath("a/index.html", "a/page2.html"));
assertEquals("", HtmlUtility.computeRelPath("a/index.html", "/a/page2.html"));
assertEquals("", HtmlUtility.computeRelPath("/a/index.html", "a/page2.html"));
assertEquals("", HtmlUtility.computeRelPath("/a/index.html", "/a/page2.html"));
assertEquals("site/folder/", HtmlUtility.computeRelPath("index.html", "site/folder/page1.html"));
assertEquals("site/folder/", HtmlUtility.computeRelPath("index.html", "/site/folder/page1.html"));
assertEquals("site/folder/", HtmlUtility.computeRelPath("/index.html", "site/folder/page1.html"));
assertEquals("site/folder/", HtmlUtility.computeRelPath("/index.html", "/site/folder/page1.html"));
assertEquals("site/f/", HtmlUtility.computeRelPath("index.html", "site/f/"));
assertEquals("site/f/", HtmlUtility.computeRelPath("index.html", "/site/f/"));
assertEquals("site/f/", HtmlUtility.computeRelPath("/index.html", "site/f/"));
assertEquals("site/f/", HtmlUtility.computeRelPath("/index.html", "/site/f/"));
assertEquals("dir/", HtmlUtility.computeRelPath("site/page1.html", "site/dir/page1.html"));
assertEquals("dir/", HtmlUtility.computeRelPath("site/page1.html", "/site/dir/page1.html"));
assertEquals("dir/", HtmlUtility.computeRelPath("/site/page1.html", "site/dir/page1.html"));
assertEquals("dir/", HtmlUtility.computeRelPath("/site/page1.html", "/site/dir/page1.html"));
assertEquals("directory/", HtmlUtility.computeRelPath("site/page1.html", "site/directory/"));
assertEquals("directory/", HtmlUtility.computeRelPath("site/page1.html", "/site/directory/"));
assertEquals("directory/", HtmlUtility.computeRelPath("/site/page1.html", "site/directory/"));
assertEquals("directory/", HtmlUtility.computeRelPath("/site/page1.html", "/site/directory/"));
assertEquals("../", HtmlUtility.computeRelPath("site/page1.html", "page1.html"));
assertEquals("../", HtmlUtility.computeRelPath("site/page1.html", "/page1.html"));
assertEquals("../", HtmlUtility.computeRelPath("/site/page1.html", "page1.html"));
assertEquals("../", HtmlUtility.computeRelPath("/site/page1.html", "/page1.html"));
assertEquals("../site/folder/", HtmlUtility.computeRelPath("archive/page1.html", "site/folder/page1.html"));
assertEquals("../site/folder/", HtmlUtility.computeRelPath("archive/page1.html", "/site/folder/page1.html"));
assertEquals("../site/folder/", HtmlUtility.computeRelPath("/archive/page1.html", "site/folder/page1.html"));
assertEquals("../site/folder/", HtmlUtility.computeRelPath("/archive/page1.html", "/site/folder/page1.html"));
}
@Test
public void testIsExternalPath() throws Exception {
assertEquals(true, HtmlUtility.isExternalPath("http://github.com"));
assertEquals(true, HtmlUtility.isExternalPath("http://site.net/page.php?some=value#test"));
assertEquals(true, HtmlUtility.isExternalPath("http://localhost:8080/some"));
assertEquals(true, HtmlUtility.isExternalPath("ftp://some.com/"));
assertEquals(true, HtmlUtility.isExternalPath("ftp://use@some.com/"));
assertEquals(true, HtmlUtility.isExternalPath("ssh:git@github.com:jmini/htmlchecker.git"));
assertEquals(false, HtmlUtility.isExternalPath(""));
assertEquals(false, HtmlUtility.isExternalPath("site/folder/page1.html"));
assertEquals(false, HtmlUtility.isExternalPath("/archive/page1.html"));
}
@Test
public void testRemoveAnchorAndQuery() throws Exception {
assertEquals("/archive/page1.html", HtmlUtility.removeAnchorAndQuery("/archive/page1.html"));
assertEquals("/archive/page1.html", HtmlUtility.removeAnchorAndQuery("/archive/page1.html#anchor"));
assertEquals("/archive/page1.html", HtmlUtility.removeAnchorAndQuery("/archive/page1.html#"));
assertEquals("/archive/page1.html", HtmlUtility.removeAnchorAndQuery("/archive/page1.html?query"));
assertEquals("/archive/page1.html", HtmlUtility.removeAnchorAndQuery("/archive/page1.html?"));
assertEquals("/archive/page1.html", HtmlUtility.removeAnchorAndQuery("/archive/page1.html?query#anchor"));
assertEquals("/archive/page1.html", HtmlUtility.removeAnchorAndQuery("/archive/page1.html#anchor?"));
assertEquals("", HtmlUtility.removeAnchorAndQuery(""));
assertEquals("", HtmlUtility.removeAnchorAndQuery("?id=1"));
assertEquals("", HtmlUtility.removeAnchorAndQuery("#test"));
assertEquals(null, HtmlUtility.removeAnchorAndQuery(null));
}
@Test
public void testUrlDecode() throws Exception {
assertEquals("my file.html", HtmlUtility.urlDecode("my%20file.html"));
assertEquals(null, HtmlUtility.urlDecode(null));
}
}
|
package TextThread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//创建线程 1:extends Thread,覆写run方法
class MyThread1 extends Thread {
private String name;
public MyThread1(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(name + "-i:" + i);
}
}
}
//创建线程 2:implements Runnable,在new的Thread对象中传入实现Runnable的类对象
class MyThread2 implements Runnable {
private String name;
public MyThread2(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(name + " i:" + i);
}
}
}
//创建线程 3:implements Callable,在new的FutureTask对象中传入实现Callable的类对象
//在new的Thread对象中传入FutureTask对象
class MyThread3 implements Callable<String> {
private String name;
public MyThread3(String name) {
this.name = name;
}
@Override
public String call() throws Exception {
for (int i = 0; i < 3; i++) {
System.out.println(name + "i:" + i);
}
return name;
}
}
public class CreateThread {
public static void MyThread1() {
MyThread1 myThread1 = new MyThread1("Java-Thread-1");
MyThread1 myThread2 = new MyThread1("Java-Thread-2");
MyThread1 myThread3 = new MyThread1("Java-Thread-3");
//仅仅是调用了类中的run方法,并不是启动线程
/*myThread1.run();
myThread2.run();
myThread3.run();*/
//使用start才是真正的启动线程,只能调用一次
myThread1.start();
myThread2.start();
myThread3.start();
}
public static void MyThread2() {
MyThread2 myThread = new MyThread2("Java-Thread");
new Thread(myThread).start();
new Thread(myThread).start();
new Thread(myThread).start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("匿名对象-Thread");
}
}).start();
Runnable runnable = () -> System.out.println("lambda-Thread");
new Thread(runnable).start();
}
public static void MyThread3() throws ExecutionException, InterruptedException {
//FutureTask在多线程并发下,保证任务只执行一次
FutureTask<String> futureTask = new FutureTask<>(new MyThread3("Java-Thread"));
new Thread(futureTask).start();
new Thread(futureTask).start();
new Thread(futureTask).start();
new Thread(futureTask).start();
//get方法是阻塞操作
System.out.println(futureTask.get());
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyThread2();
}
}
|
package com.forsrc.utils;
import br.eti.mertz.wkhtmltopdf.wrapper.Pdf;
import br.eti.mertz.wkhtmltopdf.wrapper.page.PageType;
import br.eti.mertz.wkhtmltopdf.wrapper.params.Param;
import org.junit.*;
public class WkhtmltopdfTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() throws Exception {
Pdf pdf = new Pdf();
//pdf.addPage("<html><head><meta charset=\"utf-8\"></head><h1>Müller</h1></html>", PageType.htmlAsString);
pdf.addPage("https://github.com/", PageType.url);
// Add a Table of contents
pdf.addToc();
// The `wkhtmltopdf` shell command accepts different types of options such as global, page, headers and footers, and toc. Please see `wkhtmltopdf -H` for a full explanation.
// All options are passed as array, for example:
//pdf.addParam(new Param("--no-footer-line"), new Param("--header-html", "file:///header.html"));
pdf.addParam(new Param("--enable-javascript"));
// Save the PDF
pdf.saveAs("out/B.pdf");
}
}
|
import java.util.Arrays;
import java.util.*;
/**
* Write a description of class Trip here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Trip
{
private ArrayList<Flight> flights;
public Trip(ArrayList<Flight> flights) {
this.flights = flights;
}
/**
* @return the number of minutes from the departure of the first
* flight to the arrival of the last flight if there are one
* or more flights in the trip; 0, if there are no flights
* in the trip
*/
public int getDuration() {
return 123456789;
}
/**
* @return the smallest number of minutes between the arrival of a
* flight and the departure of the flight immediately after it,
* if there are two or more flights in the trip; -1, if there
* are fewer than two flights in the trip
*/
public int getShortistLayover() {
//most likely a loop & store min thing
return 123456789;
}
}
|
package nl.ru.ai.vroon.mdp;
import nl.ru.ai.SiemenLooijen4083679.reinforcement.ValueIteration;
/**
* This main is for testing purposes (and to show you how to use the MDP class).
*
* @author Jered Vroon
*
*/
public class Main
{
/**
* @param args,
* not used
*/
public static void main(String[] args)
{
MarkovDecisionProblem mdp = new MarkovDecisionProblem();
mdp.setInitialState(0, 0);
mdp.setDeterministic();
ValueIteration v = new ValueIteration(mdp);
//MarkovDecisionProblem mdp2 = new MarkovDecisionProblem(10, 10);
//mdp2.setField(5, 5, Field.REWARD);
}
}
|
package com.dreamworks.example.service;
import com.dreamworks.example.model.Task;
import com.dreamworks.example.model.TaskVersion;
import com.dreamworks.example.model.request.TaskPayload;
import com.dreamworks.example.model.request.TaskVersionPayload;
/**
* Created by mmonti on 4/20/17.
*/
public interface TaskService {
/**
*
* @param payload
* @return
*/
Task create(final TaskPayload payload);
/**
*
* @param taskId
* @param versionId
* @param payload
* @return
*/
TaskVersion create(final String taskId, final String versionId, final TaskVersionPayload payload);
/**
*
* @param taskId
* @return
*/
Task get(final String taskId);
}
|
package com.mszalek.cleaningservice.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.time.LocalDateTime;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CleaningLog {
@Id
@GeneratedValue
private Long id;
private int roomNumber;
private LocalDateTime timeOfFinish;
private CleaningComplexity cleaningComplexity;
public CleaningLog(int roomNumber, LocalDateTime cleanTime) {
this.roomNumber = roomNumber;
this.timeOfFinish = cleanTime;
}
}
|
package com.lzt.roomsdemo;
import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.migration.Migration;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.lzt.roomsdemo.adapter.AnimalAdapter;
import com.lzt.roomsdemo.dao.AnimalDao;
import com.lzt.roomsdemo.dao.FoodDao;
import com.lzt.roomsdemo.entity.Animal;
import com.lzt.roomsdemo.entity.Country;
import com.lzt.roomsdemo.entity.Food;
import com.lzt.roomsdemo.global.AppDataBase;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import java.util.Arrays;
import java.util.List;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
public class MainActivity extends AppCompatActivity {
private RecyclerView rv;
private EditText idET;
private EditText nameET;
private EditText placeET;
private EditText countryET;
private TextView insertTV;
private TextView deleteTV;
private TextView queryTV;
private TextView updateTV;
private TextView foodTV;
private AnimalAdapter adapter;
private AnimalDao dao;
private FoodDao foodDao;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initListener();
initData();
}
private void initView() {
rv = (RecyclerView) findViewById(R.id.rv);
idET = (EditText) findViewById(R.id.et_id);
nameET = (EditText) findViewById(R.id.et_name);
placeET = (EditText) findViewById(R.id.et_place);
countryET = (EditText) findViewById(R.id.et_country);
insertTV = (TextView) findViewById(R.id.tv_insert);
deleteTV = (TextView) findViewById(R.id.tv_delete);
queryTV = (TextView) findViewById(R.id.tv_query);
updateTV = (TextView) findViewById(R.id.tv_update);
foodTV = (TextView) findViewById(R.id.tv_food);
}
private void initListener() {
insertTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Animal animal = formatAnimal(new Animal());
Flowable.create(new FlowableOnSubscribe<List>(){
@Override
public void subscribe(FlowableEmitter<List> e) throws Exception {
dao.insertAnimal(animal);
List list = Arrays.asList(dao.query());
e.onNext(list);
e.onComplete();
}
},BackpressureStrategy.BUFFER)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<List>() {
@Override
public void onSubscribe(Subscription s) {
s.request(Long.MAX_VALUE);
//subscription = s;
}
@Override
public void onNext(List list) {
adapter.animals = list;
adapter.notifyDataSetChanged();
}
@Override
public void onError(Throwable t) {
}
@Override
public void onComplete() {}
});
}
});
deleteTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Flowable.create(new FlowableOnSubscribe<List>(){
@Override
public void subscribe(FlowableEmitter<List> e) throws Exception {
Animal[] animals = null;
if(!TextUtils.isEmpty(idET.getText().toString().trim())){
animals = dao.queryUid(Integer.valueOf(idET.getText().toString().trim()));
}else if(!TextUtils.isEmpty(nameET.getText().toString().trim())){
animals = dao.queryName(nameET.getText().toString().trim());
}else if(!TextUtils.isEmpty(placeET.getText().toString().trim())){
animals = dao.queryPlace(placeET.getText().toString().trim());
}else{
animals = dao.queryCid(formatCountry(countryET.getText().toString().trim()));
}
dao.deleteAnimal(animals);
e.onNext(Arrays.asList(dao.query()));
e.onComplete();
}
},BackpressureStrategy.BUFFER)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<List>() {
@Override
public void onSubscribe(Subscription s) {
s.request(Long.MAX_VALUE);
//subscription = s;
}
@Override
public void onNext(List list) {
adapter.animals = list;
adapter.notifyDataSetChanged();
}
@Override
public void onError(Throwable t) {
}
@Override
public void onComplete() {}
});
}
});
queryTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Flowable.create(new FlowableOnSubscribe<List>(){
@Override
public void subscribe(FlowableEmitter<List> e) throws Exception {
Animal[] animals = null;
Food[] foods = foodDao.query();
adapter.foods = Arrays.asList(foods);
if(!TextUtils.isEmpty(idET.getText().toString().trim())){
animals = dao.queryUid(Integer.valueOf(idET.getText().toString().trim()));
}else if(!TextUtils.isEmpty(nameET.getText().toString().trim())){
animals = dao.queryName(nameET.getText().toString().trim());
}else if(!TextUtils.isEmpty(placeET.getText().toString().trim())){
animals = dao.queryPlace(placeET.getText().toString().trim());
}else if(!TextUtils.isEmpty(countryET.getText().toString().trim())){
animals = dao.queryCid(formatCountry(countryET.getText().toString().trim()));
}else{
animals = dao.query();
}
e.onNext(Arrays.asList(animals));
e.onComplete();
}
},BackpressureStrategy.BUFFER)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<List>() {
@Override
public void onSubscribe(Subscription s) {
s.request(Long.MAX_VALUE);
//subscription = s;
}
@Override
public void onNext(List list) {
adapter.animals = list;
adapter.notifyDataSetChanged();
}
@Override
public void onError(Throwable t) {
}
@Override
public void onComplete() {}
});
}
});
updateTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Flowable.create(new FlowableOnSubscribe<List>(){
@Override
public void subscribe(FlowableEmitter<List> e) throws Exception {
Animal[] animals = dao.queryUid(Integer.valueOf(idET.getText().toString().trim()));
if(animals!=null&&animals.length>0){
animals[0] = formatAnimal(animals[0]);
dao.updateAnimal(animals[0]);
}
e.onNext(Arrays.asList(dao.query()));
e.onComplete();
}
},BackpressureStrategy.BUFFER)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<List>() {
@Override
public void onSubscribe(Subscription s) {
s.request(Long.MAX_VALUE);
//subscription = s;
}
@Override
public void onNext(List list) {
adapter.animals = list;
adapter.notifyDataSetChanged();
}
@Override
public void onError(Throwable t) {
}
@Override
public void onComplete() {}
});
}
});
foodTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,FoodActivity.class));
}
});
}
private Animal formatAnimal(Animal animal) {
animal.aid = Integer.valueOf(idET.getText().toString().trim());
animal.scientificName = nameET.getText().toString().trim();
animal.place = placeET.getText().toString().trim();
Country country = new Country();
country.cid = formatCountry(countryET.getText().toString().trim());
country.cname = countryET.getText().toString();
animal.country = country;
return animal;
}
private int formatCountry(String country) {
int cid = 0;
if("中国".equals(country)){
cid = 100;
}else if("美国".equals(country)){
cid = 200;
}else if("俄罗斯".equals(country)){
cid = 300;
}else if("南极".equals(country)){
cid = 400;
}
return cid;
}
private void initData() {
adapter = new AnimalAdapter();
rv.setLayoutManager(new LinearLayoutManager(this));
rv.setAdapter(adapter);
AppDataBase db = Room.databaseBuilder(getApplicationContext(),
AppDataBase.class, "database-name")/*.addMigrations(MIGRATION_1_2,MIGRATION_2_3)*/.build();
dao = db.animalDao();
foodDao = db.foodDao();
}
//app由版本1更新2时,迁移版本1的Animal的Table到版本2中,可以指定迁移哪些字段
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL("CREATE TABLE 'animal' ('uid' INTEGER, "
+ "'sname' TEXT,'place' TEXT,'viviparity' INTEGER,'cid' INTEGER,'cname' TEXT, PRIMARY KEY(`uid`))");
}
};
//app由版本2更新至3时,给版本2的Animal的Table插入新的字段 liveTime
static final Migration MIGRATION_2_3 = new Migration(2, 3) {
@Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE animal "
+ " ADD COLUMN liveTime INTEGER");
}
};
}
|
package ru.hitpoint.lib.hitpoint;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
/**
* Created by hlopu on 28.03.2018.
*/
public class CheckPermissionService {
public static final int REQUEST_PERMISSION = 777;
private Context context;
public CheckPermissionService(Context context) {
this.context = context;
}
public boolean checkPermissionsStorage(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
//TODO тут сразу 2 в одном
Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_PERMISSION);
// dialog.dismiss();
return false;
}
else{
return true;
}
}
}
|
package com.zpjr.cunguan.presenter.presenter.setting;
import com.zpjr.cunguan.common.retrofit.PresenterCallBack;
/**
* Description: 描述
* Autour: LF
* Date: 2017/8/22 11:31
*/
public interface ICMSWebViewPresenter {
//获取cms的内容
void getCmsContent(String url);
//获取关于我们
void getAboutUsContent(String url);
}
|
package Login;
import java.awt.Container;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
public class CheckBox {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100,50,700,500);
Container c = frame.getContentPane();
JCheckBox b1 = new JCheckBox("Core java");
JCheckBox b2 = new JCheckBox("Advance java");
b1.setBounds(100,50,100,30);
b2.setBounds(200,50,100,30);
b1.setSelected(true);
c.add(b1);
c.add(b2);
c.setLayout(null);
}
}
|
import java.util.function.Function;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Polyline;
/**
* The main problems in this program occur in three methods, namely, functionToPolygon(), functionToPolyline() and drawYAxis().
* <pre>
* 1. In functionToPolygon() method, it should calculate the coordinates used for drawing, not the x and y values in the function inputted. And it also lacks the coordinates of the last two points of the polygon, which are the right and left endpoints of the x axis (please note the order!).
* 2. In functionToPolyline() method, it should calculate the coordinates used for drawing, not the x and y values in the function inputted. And it aslo should calculate the maximum and minimum values of the function in the [a, b] interval.
* 3. In drawYAxis() method, the abscissa of the Y axis should be 0 - a instead of b - 0.
* </pre>
* This class is to display a non-constant function such as x goes to x*x and the area between the function graph and the x-axis in a given interval [a,b]. It is done by drawing the x-axis and the y-axis as well as defining a polyline from the function, the end-point (b, f(b)) and the starting point at (a, f(a)) and then displaying the corresponding polygon filled with colour and adquately scaled.
*
* @version 2019-11-17
* @author Zetian Qin zxq876 and Manfred Kerber
*/
public class DisplayFunctionArea extends Application{
/** X_SIZE is the width of the panel in pixels. Set to 600.
*/
public static final int X_SIZE = 600;
/** Y_SIZE the height of the panel in pixels. Set to 600.
*/
public static final int Y_SIZE = 600;
/**
* f is the function to be displayed. We introduce it as a global variable so that it can be used in the start method, but be defined in the main method.
*/
//private static Function<Double,Double> f;
/**
* a is the left border of the interval on which the function is to be displayed. We introduce it as a global variable so that it can be used in the start method, but be defined in the main method.
*/
private static double a;
/**
* b is the right border of the interval on which the function is to be displayed. We introduce it as a global variable so that it can be used in the start method, but be defined in the main method.
*/
private static double b;
/** min is an approximation of the minimum of f in the interval [a,b]. It is introduced as a global variable so that it does not have to be recomputed.
*/
private static double min;
/** max is an approximation of the maximum of f in the interval [a,b]. It is introduced as a global variable so that it does not have to be recomputed.
*/
private static double max;
/**
* n is the granularity. More concretely, the interval [a,b] will be subdivided in n parts and on each the function will be approximated by a straight line.
*/
private static int n;
/**
* The polyline will be the approximation of the function and be displayed.
*/
private static Polyline polyline;
/**
* The polygon will be the area between the function and the x-axis.
*/
private static Polygon polygon;
/**
* The colour in which the area is displayed.
*/
public static Color areaColour = Color.YELLOW;
/**
* The method generates a polygon corresponding to the area between the function f and the x-axis in the interval [a,b].
* @param f The function to be drawn.
* @param n The number of equidistant intervals to be drawn.
* @param a The minimal x-value in the interval.
* @param b The maximal x-value in the interval.
* @return The polygon corresponding to the area between the function f and the x-axis over the interval [a,b] with granularity n.
*/
public static Polygon functionToPolygon(Function<Double,Double> f, int n, double a, double b) {
if (a >= b) {
throw new IllegalArgumentException();
} else {
double[] points = new double[2*(n+1)+4];
double x, y;
/* Loop: Add x and y values to the corresponding arrays
* for a, b and n-1 equidistant values in between.
* The (x_i,y_i) values are added to the points array in pairs.
*/
for (int i = 0; i <= DisplayFunctionArea.n ; i++){
x = a + (b - a) * i / n;
y = f.apply(x);
// Changed - The actual coordinates of Points in PolyLine, not the x and y in f function.
points[2 * i] = (x - a) * X_SIZE / (b - a);
points[2 * i + 1] = (max - y) * Y_SIZE / (max - min);
}
// Changed - The last two Point of the Polygon have not been added in, so I add these now.
// Please note this, the Fisrt one must be the the Right endpoint of the X axis.
points[2 * (n + 1)] = X_SIZE;
points[2 * (n + 1) + 1] = (max - 0) * Y_SIZE / (max - min);
// And the Second one is the Lift endpoint of the X axis.
points[2 * (n + 1) + 2] = 0;
points[2 * (n + 1) + 3] = (max - 0) * Y_SIZE / (max - min);
/* Draw graph */
return new Polygon(points);
}
}
/**
* The method generates a polyline corresponding to the graph of function f in the interval [a,b]
* @param f The function to be drawn.
* @param n The number of equidistant intervals to be drawn.
* @param a The minimal x-value in the interval.
* @param b The maximal x-value in the interval.
* @return The polyline corresponding to the function f over the interval [a,b] with granularity n.
*/
public static Polyline functionToPolyline(Function<Double,Double> f, int n, double a, double b) {
if (a >= b) {
throw new IllegalArgumentException();
} else {
double[] points = new double[2*(n+1)];
double x, y;
// Changed - Using the following loop, compute the min and max of f in the interval [a,b].
double minTmp = f.apply(a);
double maxTmp = f.apply(a);
/* Loop: Add x and y values to the corresponding arrays for a, b and n-1 equidistant values in between.
* The (x_i,y_i) values are added to the points array in pairs.
*/
for(int i = 0; i <= n; i++) {
x = a + (b - a) * i / n;
y = f.apply(x);
// Changed - The x is not the X coordinate of Point in Polyline, so I need to compute the right X coordinate.
points[2*i] = (x - a) * X_SIZE / (b - a);
points[2*i+1] = y; // I do not fix this bug since I have not got the value of min and max.
if(minTmp > y) {
minTmp = y;
}
if(maxTmp < y) {
maxTmp = y;
}
}
min = minTmp;
max = maxTmp;
// Changed - Fine, I got the min and max, then, I could compute the right Y coordinate of Point in Polyline.
for(int i = 0; i <= n; i++) {
points[2 * i + 1] = (max - points[2 * i + 1]) * Y_SIZE / (max - min);
}
/* Draw graph */
Polyline result = new Polyline(points);
result.setStrokeWidth(3);
return result;
}
}
/**
* The method draws the x-axis if 0 is in the interval [min, max].
* It is assumed that the function is not constant.
* @param root The group to which the x-axis is to be added.
*/
public static void drawXAxis(Group root){
if (min < 0 && 0 < max) {
Line line = new Line(0, (max-0) * Y_SIZE/(max-min),
X_SIZE, (max-0) * Y_SIZE/(max-min));
line.setStrokeWidth(2);
root.getChildren().add(line);
}
}
/**
* The method draws the y-axis if 0 is in the interval [a, b].
* @param root The group to which the y-axis is to be added.
*/
public static void drawYAxis(Group root){
if (a < 0 && 0 < b) {
// Changed - The abscissa of the Y axis should be 0 - a instead of b - 0.
Line line = new Line((0 - a) * X_SIZE / (b - a), 0,
(0 - a) * X_SIZE / (b - a), Y_SIZE);
line.setStrokeWidth(2);
root.getChildren().add(line);
}
}
/**
* @param stage The window to be displayed.
*/
@Override
public void start(Stage stage) throws Exception {
// Create a Group (scene graph) with the line as single element.
Group root = new Group();
root.getChildren().add(polyline);
root.getChildren().add(polygon);
drawXAxis(root);
drawYAxis(root);
// The scene consists of just one group.
Scene scene = new Scene(root, X_SIZE,Y_SIZE);
// Give the stage (window) a title and add the scene.
stage.setTitle("Function Graph");
stage.setScene(scene);
stage.show();
}
/**
* The method gives values to the static variables a, b, n, and polyline.
* @param f The function to be displayed.
* @param numberOfValues The number of points on the polyline.
* @param left The left border of the interval to be displayed.
* @param right The right border of the interval to be displayed.
*/
public static void displayFunctionArea(Function<Double, Double> f, double left, double right, int numberOfValues){
a = left;
b = right;
n = numberOfValues;
polyline = functionToPolyline(f, numberOfValues, left, right);
polygon = functionToPolygon(f, numberOfValues, left, right);
polygon.setFill(areaColour);
}
/*
* main method to launch the application.
*/
public static void main(String[] args) {
displayFunctionArea(x -> x*x*x - 8 * x * x, -2, 9, 500);
launch(args);
}
}
|
package samples.findbugs;
import java.util.List;
import javax.annotation.Nonnull;
@SuppressWarnings({ "PMD.OverrideBothEqualsAndHashcode", "checkstyle:equalshashcode" })
public class OnlyEqualsImplementation {
private final List<String> versions;
public OnlyEqualsImplementation(@Nonnull final List<String> versions) {
this.versions = versions;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final OnlyEqualsImplementation other = (OnlyEqualsImplementation) obj;
if (versions == null) {
if (other.versions != null) {
return false;
}
} else if (!versions.equals(other.versions)) {
return false;
}
return true;
}
@Override
public String toString() {
return "OnlyEqualsImplementation [versions=" + versions + "]";
}
}
|
package com.chan.demo.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import com.chan.demo.vo.chattingVO;
import javax.validation.Valid;
@Repository("chattingMapper")
@Mapper
public interface chatMapper {
public void setChatRoom(@Valid chattingVO cv);
public String getChCode(int ch_postnum);
}
|
package com.sapiy.controller;
import com.sapiy.domain.Hospital;
import com.sapiy.service.HospitalService;
import com.sapiy.service.ServiceInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hospital")
public class HospitalController extends GeneralController<Hospital> {
@Autowired
HospitalService hospitalService;
@Override
public ServiceInterface<Hospital> getService() {
return hospitalService;
}
}
|
package org.scilab.forge.jlatexmath.geom;
import org.robovm.apple.coregraphics.CGRect;
import org.scilab.forge.jlatexmath.platform.geom.RoundRectangle2D;
public class RoundRectangle2DI implements RoundRectangle2D {
private CGRect mRect;
private double mArcw;
private double mArch;
public RoundRectangle2DI(double x, double y, double w, double h, double arcw, double arch) {
mRect = new CGRect();
setRectangle(x, y, w, h);
mArcw = arcw;
mArch = arch;
}
public void setRectangle(double x, double y, double w, double h) {
mRect = new CGRect((float)x, (float)y, (float)w, (float)h);
}
public double getArcW() {
return mArcw;
}
public double getArcH() {
return mArch;
}
public double getX() {
return mRect.getOrigin().getX();
}
public double getY() {
return mRect.getOrigin().getY();
}
public double getWidth() {
return mRect.getWidth();
}
public double getHeight() {
return mRect.getHeight();
}
public CGRect getCGRect() {
return mRect;
}
public void setRoundRectangle(double x, double y, double w, double h, double arcw, double arch) {
setRectangle(x, y, w, h);
mArcw = arcw;
mArch = arch;
}
}
|
package moe.vergo.seasonalseiyuuapi.adapter.out.web.dto;
public class AnimeSeiyuuDto {
private PersonDto person;
private String language;
public PersonDto getPerson() {
return person;
}
public String getLanguage() {
return language;
}
}
|
package gameLogic;
import gameLogic.goal.Goal;
import gameLogic.goal.GoalManager;
import gameLogic.resource.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* class to store player info
* @author FVS, Lisa
*
*/
public class Player {
private PlayerManager pm;
private List<Resource> resources;
private List<Goal> goals;
private int number;
private int score;
/**
* New instance of a player's inventory
* @param pm The player manager
* @param playerNumber An integer number
*/
public Player(PlayerManager pm, int playerNumber) {
goals = new ArrayList<Goal>();
resources = new ArrayList<Resource>();
this.pm = pm;
number = playerNumber;
score = 0;
}
/**
* Returns the players resources
* @return resources
*/
public List<Resource> getResources() {
return resources;
}
public void addResource(Resource resource) {
resources.add(resource);
changed();
}
public void removeResource(Resource resource) {
resources.remove(resource);
resource.dispose();
changed();
}
public void addGoal(Goal goal) {
int uncompleteGoals = 0;
for(Goal existingGoal : goals) {
if(!existingGoal.getComplete()) {
uncompleteGoals++;
}
}
if (uncompleteGoals >= GoalManager.CONFIG_MAX_PLAYER_GOALS) {
//throw new RuntimeException("Max player goals exceeded");
return;
}
goals.add(goal);
changed();
}
/**
* sets goal to complete and updates player score
* @param goal
*/
public void completeGoal(Goal goal) {
goal.setComplete();
score += goal.getReward();
changed();
}
/**
* Method is called whenever a property of this player changes, or one of the player's resources changes
*/
public void changed() {
pm.playerChanged();
}
public List<Goal> getGoals() {
return goals;
}
public PlayerManager getPlayerManager() {
return pm;
}
public int getPlayerNumber() {
return number;
}
public int getPlayerScore() {
return score;
}
}
|
package com.batiaev.java3.lesson4.homework.mfu;
public class Printer extends Device {
public Printer() {
super("Напечатано");
}
}
|
package start.entity;
import lombok.Data;
/**
* @Author: Jason
* @Create: 2020/10/11 16:37
* @Description 全局锁类 主要有名称与value值
*/
@Data
public class Lock {
private String name;
private String value;
public Lock(String name, String value){
this.name = name;
this.value = value;
}
}
|
/**
*
*/
package com.opendatams.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* @author pengr
*
* 2019年3月13日
*/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeRequests()
.antMatchers("/", "home")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGloabal(final AuthenticationManagerBuilder authenticationManagerBuilder)
throws Exception {
authenticationManagerBuilder
.inMemoryAuthentication()
.withUser("admin")
.password("admin")
.roles("admin");
}
}
|
package com.rawa.ac.uk;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.yaml.snakeyaml.Yaml;
import com.connexience.api.StorageClient;
import com.connexience.api.model.EscDocument;
import com.connexience.api.model.EscFolder;
public class BlockEnvironment {
public String source;
public String OutputFileName;
public Map<String,String> block;
public String blueprint;
public String BlockName;
public Map getBlockTemplate(String ServiceTemplate, String BlockNodeTemplate) throws Exception
{
final Yaml yaml = new Yaml();
Reader reader = null;
reader = new FileReader(ServiceTemplate);
Map<String, String> map = (Map<String, String>) yaml.load(reader);
String st="node_templates";
Object temp=map.get(st);; //get the node templates with all info
Map m= (Map) temp;
Set s = m.keySet(); //get node templates as keys
java.util.Iterator ir = s.iterator();
while (ir.hasNext())
{
String key = (String) ir.next();
if ( key.equals(BlockNodeTemplate))
{
Object value = m.get(key);
map = (Map) value;
break;
}
}
return map;
}
public Map get_value(Map<String,String> map,String key)
{
if(!map.containsKey(key))
return null;
Object temp=map.get(key);
Map m= (Map) temp;
return m;
}
public String get_property(String serviceTemplate, String block, String property) throws Exception
{
String st="notblock";
Map m=get_value(getBlockTemplate(serviceTemplate, block),"properties");
if(m!=null)
{
//System.out.println(block+"::::"+m);
if(m.containsKey(property))
{
st= (String)m.get(property);
return st;
}
}
return st;
}
public boolean IsBlock(String blueprint, String block) throws Exception
{
//System.out.println(get_property(blueprint, block, "service_type"));
String st = get_property(blueprint, block, "service_type");
//System.out.println(st);
if(!(st.matches("block")))
return false;
return true;
}
public String output_location(String ServiceTemplate, String block) throws Exception
{
final Yaml yaml = new Yaml();
System.out.println(ServiceTemplate+" "+block);
Reader reader = null;
try {
reader = new FileReader(ServiceTemplate);
Map<String, String> map = (Map<String, String>) yaml.load(reader); //blueprint
boolean in=false,out=false;
String st="";
Map Block=getBlockTemplate(ServiceTemplate, block);
//System.out.println(Block);
ArrayList Relations =(ArrayList)Block.get("relationships");
System.out.println(((Map)Relations.get(0)).get("target"));
String host=(String) ((Map)Relations.get(0)).get("target");
System.out.println(host);
Map nodes=get_value(map,"node_templates"); //get node templates for the blocks
Set s = nodes.keySet();
Iterator ir = s.iterator();
while (ir.hasNext())
{ //while
String item= (String) ir.next();
if (IsBlock(ServiceTemplate, item ) && (! item.matches(block)))
{ //first if
System.out.println("block "+item);
Map node=(Map)nodes.get(item);
Relations =(ArrayList)node.get("relationships");
//System.out.println(Relations);
for (int i=0;i<Relations.size();i++)
{
//System.out.println(Relations.get(i));
if(((String) ((Map)Relations.get(i)).get("type")).matches("cloudify.relationships.contained_in"))
{
if(((String) ((Map)Relations.get(i)).get("target")).matches(host))
{ int j;
for( j=i+1;j<Relations.size();j++)
if(((String) ((Map)Relations.get(j)).get("type")).matches("block_link"))
if(((String) ((Map)Relations.get(j)).get("target")).matches(block))
{ in=true; break; }
if(j<Relations.size())
break;
}
}
else
if(((String) ((Map)Relations.get(i)).get("type")).matches("block_link"))
if(((String) ((Map)Relations.get(i)).get("target")).matches(block))
{
out=true; break;
}
}//for
} //first if
} //while
if(in)
st= "in";
if(out)
st= "out";
if(in&&out)
st= "both";
return st;
} //try
catch (final FileNotFoundException fnfe) {
System.err.println("We had a problem reading the YAML from the file because we couldn't find the file." + fnfe);
} finally {
if (null != reader) {
try {
reader.close();
} catch (final IOException ioe) {
System.err.println("We got the following exception trying to clean up the reader: " + ioe);
}
}
}
return null;
}
public String input_store(String ServiceTemplate, String block) throws Exception
{
final Yaml yaml = new Yaml();
Reader reader = null;
try {
Map<String,String> blockTemplate=getBlockTemplate(ServiceTemplate, block);
ArrayList relation = (ArrayList) ((Object)blockTemplate.get("relationships"));
for(int i=0; i<relation.size();i++)
{
Map r= (Map)relation.get(i);
String blockType=((String)getBlockTemplate(ServiceTemplate,(String)r.get("target")).get("type"));
if(((String)r.get("type")).matches("cloudify.relationships.depends_on")&&blockType.matches("WFblock"))
{
Map m=getBlockTemplate(ServiceTemplate,(String)r.get("target"));
if(((String)get_value(blockTemplate,"properties").get("container_ID")).matches((String)get_value(m,"properties").get("container_ID")))
return "in";
else
return "out";
}
}
} //try
catch (final FileNotFoundException fnfe)
{
System.err.println("We had a problem reading the YAML from the file because we couldn't find the file." + fnfe);
}
finally
{
if (null != reader)
{
try {
reader.close();
}
catch (final IOException ioe) {
System.err.println("We got the following exception trying to clean up the reader: " + ioe);
}
}
}
return "null";
}
public String DownloadBlueprint(String blueprint) throws Exception
{
//get eSc credentials
geteScCred();
File file=new File("eSc.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String HOSTNAME=br.readLine();//"192.168.56.101";
int PORT=8080;
Boolean SECURE=false;
String USERNAME=br.readLine();//"rawa_qasha@yahoo.com";
String PASSWORD=br.readLine();//"123";
File localFile=null;
try {
// Create a new storage client with username and password
StorageClient client = new StorageClient(HOSTNAME,PORT,SECURE, USERNAME,PASSWORD);
EscFolder homeFolder = client.homeFolder();
EscFolder[] subFolders = client.listChildFolders(homeFolder.getId());
String folder_ID=getFolderID(blueprint,subFolders);
EscDocument[] subDocs = client.folderDocuments(folder_ID);
//download the file from the server
//BlockInputs.getFileID(blueprint, subDocs));
EscDocument doc = client.getDocument(subDocs[0].getId());
String OS=System.getProperty("os.name");
String root=null;
if(OS.substring(0, 3).matches("Win"))
root="D:"+File.separator;
else
root=System.getProperty( "user.home" )+File.separator;
File dir=new File(root+blueprint);
if(!dir.exists())
dir.mkdir();
localFile=new File(root+blueprint+File.separator+blueprint+".yaml");
client.download(doc, localFile);
}
catch (Exception e){
e.printStackTrace();
}
return localFile.getPath();
}
public static String getFolderID(String fileName,EscFolder[] folds )
{//System.out.println(docs.length);
for( int i=0; i<folds.length;i++)
{if(fileName.equalsIgnoreCase(folds[i].getName()))
return folds[i].getId();
}
return null;
}
public void geteScCred() throws Exception
{
String link = "https://raw.githubusercontent.com/rawaqasha/Data/master/eSc.txt";
String fileName = "eSc.txt";
URL url = new URL( link );
HttpURLConnection http = (HttpURLConnection)url.openConnection();
Map< String, List< String >> header = http.getHeaderFields();
while( isRedirected( header )) {
link = header.get( "Location" ).get( 0 );
url = new URL( link );
http = (HttpURLConnection)url.openConnection();
header = http.getHeaderFields();
}
InputStream input = http.getInputStream();
byte[] buffer = new byte[4096];
int n = -1;
OutputStream output = new FileOutputStream( new File( fileName ));
while ((n = input.read(buffer)) != -1) {
output.write( buffer, 0, n );
}
output.close();
}
private static boolean isRedirected( Map<String, List<String>> header ) {
for( String hv : header.get( null )) {
if( hv.contains( " 301 " )
|| hv.contains( " 302 " )) return true;
}
return false;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.