text
stringlengths 10
2.72M
|
|---|
package com.accp.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class MyWebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addCorsMappings(CorsRegistry registry) {
// TODO Auto-generated method stub
registry.addMapping("/**").allowedMethods("*").allowedOrigins("*").allowedHeaders("*").allowCredentials(true);
super.addCorsMappings(registry);
}
}
|
package code.fractals;
/**
*
* BurningShip subclass that defines a Multibrot fractal.
*
*/
public class BurningShip extends Fractal {
/**
* Constructs a Fractal object with default x- and y-coordinate ranges of (-1.0,1.0) and an output grid of 512 x 512 pixels.
*
*/
public BurningShip() {
/**
* Constructs a Fractal object with user-specified x- and y-coordinate ranges and an output grid of 512 x 512 pixels.
*
*@param xmin - minimum x value
*@param xmax - maximum x value
*@param ymin - minimum y value
*@param ymax - maximum y value
*/
super(-1.8, -1.7, -0.08, 0.025);
}
public BurningShip(double xmin, double xmax, double ymin, double ymax) {
super(xmin, xmax, ymin, ymax);
}
/**
* Generates a 512 x 512 square array of values according to the class's escape time algorithm.
*
* @return A 2D integer array filled with escape times for points mapped from the array indices onto appropriate (x,y) coordinate ranges.
*
*/
@Override
public int escapeTime(double x, double y, double escDist) {
double xcalc = x;
double ycalc = y;
double xholder = xcalc;
double yholder = ycalc;
int passes = 0;
double dist = Math.sqrt(xcalc*xcalc + ycalc*ycalc);
while(dist <= escDist && passes < _passesMax) {
xholder = (xcalc*xcalc) - (ycalc*ycalc) + x;
yholder = Math.abs(2*xcalc*ycalc) + y;
xcalc = xholder;
ycalc = yholder;
dist = Math.sqrt(xcalc*xcalc + ycalc*ycalc);
passes++;
}
/**
* Maps an integer between 0 and 511 onto the y-coordinate range specified at construction.
*
* @param pixel - the integer to be mapped
*
* @return The y value corresponding to the input integer based on a division of the y-coordinate range into 512 evenly-spaced numbers.
*
*/
return passes;
}
/**
* Resets the grid to original coordinates
*/
@Override
public void resetGrid() {
this.setGrid(-1.8, -1.7, -0.08, 0.025);
}
}
|
package tk.martijn_heil.elytraoptions.command.common.bukkit;
import com.sk89q.intake.CommandException;
import com.sk89q.intake.InvocationCommandException;
import com.sk89q.intake.argument.Namespace;
import com.sk89q.intake.dispatcher.Dispatcher;
import com.sk89q.intake.util.auth.AuthorizationException;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.defaults.BukkitCommand;
import org.bukkit.permissions.Permissible;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringJoiner;
public class RootCommand extends BukkitCommand
{
private Dispatcher dispatcher;
public static RootCommand of(Dispatcher dispatcher)
{
String prefix = dispatcher.getPrimaryAliases().iterator().next();
String description = dispatcher.getDescription().getShortDescription();
String usage = dispatcher.getDescription().getUsage();
List<String> aliases = new ArrayList<>(dispatcher.getAliases());
prefix = prefix != null ? prefix : "";
description = description != null ? description : "";
usage = usage != null ? usage : "";
return new RootCommand(dispatcher, prefix, description, usage, aliases);
}
private RootCommand(Dispatcher dispatcher, String prefix, String description, String usage, List<String> aliases)
{
super(prefix, description, usage, aliases);
this.dispatcher = dispatcher;
}
@Override
public boolean execute(CommandSender sender, String cmd, String[] args)
{
String command = cmd.startsWith("/") ? cmd.substring(1) : cmd;
StringJoiner sj = new StringJoiner(" ");
for (String arg : args)
{
sj.add(arg);
}
String joinedArgs = sj.toString();
command = command + " " + joinedArgs;
for (String alias : dispatcher.getAliases())
{
if (command.startsWith(alias))
{
Namespace namespace = new Namespace();
namespace.put("sender", sender);
namespace.put("senderClass", sender.getClass());
namespace.put(Permissible.class, sender);
try
{
dispatcher.call(command, namespace, Collections.emptyList());
}
catch (CommandException | AuthorizationException cx)
{
sendError(sender, cx.getMessage());
}
catch (InvocationCommandException icx)
{
icx.printStackTrace();
}
break;
}
}
return true;
}
private static void sendError(CommandSender p, String message)
{
p.sendMessage(ChatColor.RED + "Error: " + ChatColor.DARK_RED + message);
}
}
|
package com.tt.miniapp.jsbridge;
import android.text.TextUtils;
import com.tt.miniapp.AppbrandApplicationImpl;
import com.tt.miniapp.event.InnerEventHelper;
import com.tt.miniapphost.AppBrandLogger;
import com.tt.miniapphost.AppbrandApplication;
import com.tt.miniapphost.entity.AppInfoEntity;
import com.tt.option.e.e;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ApiPermissionManager {
private static List<String> controllApi;
private static String[] dxpp;
private static List<String> sAdControlApi = Arrays.asList(new String[] { "getAdSiteBaseInfo", "insertAdHTMLWebView", "updateAdHTMLWebView", "removeAdHTMLWebView" });
private static volatile List<String> sBlackAPIList;
private static JSONArray sBlackListJsonArray;
private static List<String> sHostMethodWhiteList;
private static List<String> sWhiteAPIList;
private static JSONArray sWhiteListJsonArray;
static {
controllApi = Arrays.asList(new String[] {
"dealUserRelation", "createDxppTask", "getUseDuration", "getGeneralInfo", "_serviceGetPhoneNumber", "getUsageRecord", "preloadMiniProgram", "addShortcut", "showMorePanel", "setMenuButtonVisibility",
"checkShortcut", "onBeforeCloseReturnSync", "requestSubscribeMessage", "sendUmengEventV1" });
dxpp = new String[] { "nloadA", "createDow", "ppTask" };
}
public static boolean canUseHostMethod(String paramString) {
List<String> list = sHostMethodWhiteList;
return (list == null || list.isEmpty()) ? false : sHostMethodWhiteList.contains(paramString);
}
public static List<String> getBlackAPIList() {
return sBlackAPIList;
}
public static JSONArray getBlackListJsonArray() {
if (sBlackListJsonArray == null)
sBlackListJsonArray = new JSONArray();
return sBlackListJsonArray;
}
private static String getPermissonErrorMsg(String paramString) {
try {
JSONObject jSONObject = new JSONObject();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(paramString);
stringBuilder.append(":fail platform auth deny");
jSONObject.put("errMsg", stringBuilder.toString());
return jSONObject.toString();
} catch (Exception exception) {
AppBrandLogger.stacktrace(6, "ApiPermissionManager", exception.getStackTrace());
return "";
}
}
public static JSONArray getWhiteListJsonArray() {
if (sWhiteListJsonArray == null)
sWhiteListJsonArray = new JSONArray();
return sWhiteListJsonArray;
}
public static void initApiBlackList(String paramString) {
if (TextUtils.isEmpty(paramString)) {
sBlackAPIList = new ArrayList<String>();
return;
}
try {
sBlackAPIList = jsonArray2List(new JSONArray(paramString));
return;
} catch (Exception exception) {
sBlackAPIList = new ArrayList<String>();
return;
}
}
public static void initApiWhiteList(String paramString) {
if (TextUtils.isEmpty(paramString)) {
sWhiteAPIList = new ArrayList<String>();
return;
}
try {
JSONArray jSONArray = new JSONArray(paramString);
sWhiteListJsonArray = jSONArray;
sWhiteAPIList = jsonArray2List(jSONArray);
return;
} catch (Exception exception) {
sWhiteAPIList = new ArrayList<String>();
return;
}
}
public static void initHostMethodWhiteList(String paramString) {
if (TextUtils.isEmpty(paramString)) {
sHostMethodWhiteList = new ArrayList<String>();
return;
}
try {
sHostMethodWhiteList = jsonArray2List((new JSONObject(paramString)).getJSONArray("host_method_whitelist"));
return;
} catch (Exception exception) {
sHostMethodWhiteList = new ArrayList<String>();
return;
}
}
public static boolean intercept(String paramString, int paramInt) {
if (sBlackAPIList != null && sBlackAPIList.contains(paramString)) {
StringBuilder stringBuilder = new StringBuilder("intercept event:");
stringBuilder.append(paramString);
InnerEventHelper.mpTechnologyMsg(stringBuilder.toString());
AppbrandApplication.getInst().getJsBridge().returnAsyncResult(paramInt, getPermissonErrorMsg(paramString));
return true;
}
if (controllApi.contains(paramString)) {
String str = mapToWhiteEvent(paramString);
List<String> list = sWhiteAPIList;
if (list == null || !list.contains(str)) {
AppbrandApplication.getInst().getJsBridge().returnAsyncResult(paramInt, getPermissonErrorMsg(paramString));
StringBuilder stringBuilder = new StringBuilder("intercept event:");
stringBuilder.append(paramString);
InnerEventHelper.mpTechnologyMsg(stringBuilder.toString());
return true;
}
}
return false;
}
public static boolean interceptAdApi(String paramString, int paramInt, e parame) {
if (sBlackAPIList != null && sBlackAPIList.contains(paramString)) {
StringBuilder stringBuilder = new StringBuilder("intercept event:");
stringBuilder.append(paramString);
InnerEventHelper.mpTechnologyMsg(stringBuilder.toString());
parame.callback(paramInt, getPermissonErrorMsg(paramString));
return true;
}
if (sAdControlApi.contains(paramString)) {
if (AppbrandApplicationImpl.getInst().getAppInfo().isAdSite())
return false;
List<String> list = sWhiteAPIList;
if (list == null || !list.contains(paramString)) {
StringBuilder stringBuilder = new StringBuilder("intercept event:");
stringBuilder.append(paramString);
InnerEventHelper.mpTechnologyMsg(stringBuilder.toString());
parame.callback(paramInt, getPermissonErrorMsg(paramString));
return true;
}
}
return false;
}
public static boolean isAdSiteMiniApp() {
List<String> list = sWhiteAPIList;
if (list != null && list.contains("getAdSiteBaseInfo"))
return true;
AppInfoEntity appInfoEntity = AppbrandApplicationImpl.getInst().getAppInfo();
return (appInfoEntity != null && appInfoEntity.isAdSite());
}
public static boolean isCanGetUserInfo() {
List<String> list = sWhiteAPIList;
return (list != null && list.contains("getUserInfo"));
}
private static List<String> jsonArray2List(JSONArray paramJSONArray) throws JSONException {
ArrayList<String> arrayList = new ArrayList();
if (paramJSONArray == null)
return arrayList;
int j = paramJSONArray.length();
for (int i = 0; i < j; i++)
arrayList.add(paramJSONArray.getString(i));
return arrayList;
}
private static String mapToWhiteEvent(String paramString) {
if (TextUtils.isEmpty(paramString))
return paramString;
String str = paramString;
if ("createDxppTask".equals(paramString)) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(dxpp[1]);
stringBuffer.append(dxpp[0]);
stringBuffer.append(dxpp[2]);
str = stringBuffer.toString();
}
return str;
}
public static boolean shouldCallbackBeforeClose() {
List<String> list = sWhiteAPIList;
return (list != null && list.contains("onBeforeCloseReturnSync"));
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\jsbridge\ApiPermissionManager.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package leetcode.algorithms;
import static org.junit.Assert.*;
import org.junit.Test;
public class _011_MaxArea {
public int maxArea(int[] height) {
int left = 0;
int right = height.length-1;
int maxArea = 0;
while(left < right) {
int area = (right - left) * Math.min(height[left], height[right]);
maxArea = Math.max(maxArea, area);
if(height[left] < height[right]) {
left++;
} else {
right--;
}
}
return maxArea;
}
@Test
public void test() {
_011_MaxArea p = new _011_MaxArea();
assertEquals(p.maxArea(new int []{1, 1}), 1);
assertEquals(p.maxArea(new int []{1, 2}), 1);
assertEquals(p.maxArea(new int []{2, 2}), 2);
assertEquals(p.maxArea(new int []{2, 3}), 2);
assertEquals(p.maxArea(new int []{3, 3}), 3);
assertEquals(p.maxArea(new int []{1, 1, 1}), 2);
assertEquals(p.maxArea(new int []{1, 2, 2}), 2);
assertEquals(p.maxArea(new int []{2, 2, 2}), 4);
assertEquals(p.maxArea(new int []{2, 1, 2}), 4);
assertEquals(p.maxArea(new int []{1, 2, 1, 3, 1, 1}), 5);
assertEquals(p.maxArea(new int []{1, 2, 1, 3, 1, 4}), 8);
}
}
|
package com.wb.cloud.config;
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @ClassName : LoggerConfig
* @Author : 王斌
* @Date : 2020-11-23 17:13
* @Description
* @Version
*/
@Configuration
public class LoggerConfig {
/**
* 开启feign的日志功能
* @return
*/
@Bean
public Logger.Level loggerLevel(){
return Logger.Level.FULL;
}
}
|
package com.tencent.mm.plugin.webview.ui.tools;
class WebViewUI$26 implements Runnable {
final /* synthetic */ WebViewUI pZJ;
WebViewUI$26(WebViewUI webViewUI) {
this.pZJ = webViewUI;
}
public final void run() {
this.pZJ.mhH.getCurWebviewClient().a(this.pZJ.mhH, this.pZJ.mhH.getUrl());
}
}
|
package esir.dom11.nsoc.datactrl.dao.model.mysql;
import esir.dom11.nsoc.datactrl.dao.connection.ConnectionDbMySQL;
import esir.dom11.nsoc.datactrl.dao.dao.ActionDAO;
import esir.dom11.nsoc.datactrl.dao.factory.DAOFactoryMySQL;
import esir.dom11.nsoc.model.Action;
import esir.dom11.nsoc.model.device.Actuator;
import esir.dom11.nsoc.model.device.Device;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
public class ActionDAOMySQL implements ActionDAO {
/*
* Class Attributes
*/
private static Logger logger = LoggerFactory.getLogger(ActionDAOMySQL.class.getName());
/*
* Attributes
*/
private ConnectionDbMySQL _connection;
private DAOFactoryMySQL _daoFactoryMySQL;
/*
* Constructors
*/
public ActionDAOMySQL(ConnectionDbMySQL connectionDbMySQL, DAOFactoryMySQL daoFactoryMySQL) {
_connection = connectionDbMySQL;
_daoFactoryMySQL = daoFactoryMySQL;
}
/*
* Overrides
*/
@Override
public Action create(Action action) {
Action newAction = retrieve(action.getId());
if (newAction.getId().toString().compareTo("00000000-0000-0000-0000-000000000000")==0) {
Device device = _daoFactoryMySQL.getDeviceDAO().create(action.getActuator());
if (device.getId().toString().compareTo("00000000-0000-0000-0000-000000000000")!=0) {
try {
PreparedStatement prepare = _connection.getConnection()
.prepareStatement(
"INSERT INTO actions (id, id_actuator, value)"
+ " VALUES('" + action.getId() + "',"
+ " '" + action.getActuator().getId() + "',"
+ " '" + action.getValue() + "')"
);
prepare.executeUpdate();
newAction = retrieve(action.getId());
} catch (SQLException exception) {
logger.error("Action insert error", exception);
}
}
}
return newAction;
}
@Override
public Action retrieve(UUID id) {
Action action = new Action();
try {
ResultSet result = _connection.getConnection()
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE)
.executeQuery("SELECT * FROM actions WHERE id = '" + id + "'");
if(result.first()) {
action = new Action(id,
(Actuator)_daoFactoryMySQL.getDeviceDAO().retrieve(UUID.fromString(result.getString("id_actuator"))),
result.getString("value"));
}
} catch (SQLException exception) {
logger.error("Action retrieve error", exception);
}
return action;
}
@Override
public Action update(Action action) {
return retrieve(action.getId());
}
@Override
public boolean delete(UUID id) {
try {
_connection.getConnection()
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE)
.executeUpdate("DELETE FROM actions WHERE id = '" + id + "'");
return true;
} catch (SQLException exception) {
logger.error("Action delete error",exception);
}
return false;
}
}
|
package com.heartmarket.model.dto.response;
import com.heartmarket.model.dto.Trade;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class TradeDetail {
// 게시글 정보
Trade trade;
// 매너 지수
double heartguage;
// 찜 여부
int cno;
// 거래 완료 됬으면 완료됬는지 아닌지 여부
int complete;
}
|
package com.classcheck.panel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import com.change_vision.jude.api.inf.model.IClass;
import com.change_vision.jude.api.inf.model.IComment;
import com.change_vision.jude.api.inf.model.IConstraint;
import com.classcheck.autosource.ClassBuilder;
import com.classcheck.autosource.ClassNode;
import com.classcheck.autosource.MyClass;
import com.classcheck.generic.Pocket;
import com.classcheck.panel.event.ClassLabelMouseAdapter;
import com.classcheck.panel.event.ClickedLabel;
public class MemberTabPanel extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
//フィールドの対応付を行う
FieldComparePanel fcp;
//メソッドの対応付を行う
MethodComparePanel mcp;
JSplitPane holizontalSplitePane;
JSplitPane verticalSplitePane;
JSplitPane compVerticalSplitePane;
JTree jtree;
JLabel jtrSelClass;
DefaultMutableTreeNode astahRoot;
List<MyClass> myClassList;
Map<MyClass, Pocket<SelectedType>> selectedSameFieldSigMap;
Map<MyClass, Pocket<SelectedType>> selectedSameMethodSigMap;
StatusBar astahTreeStatus;
StatusBar mcpSourceStatus;
StatusBar fcpSourceStatus;
ClassTablePanel tablePane;
Map<MyClass, Boolean> generatableMap = new HashMap<MyClass, Boolean>();
MyClass selectedMyClass;
private JPanel classNamePane;
private JPanel classFieldMethodPane;
public MemberTabPanel(FieldComparePanel fcp,MethodComparePanel mcp, ClassBuilder cb) {
selectedMyClass = null;
this.fcp = fcp;
this.mcp = mcp;
this.myClassList = cb.getClasslist();
this.selectedSameFieldSigMap = new HashMap<MyClass, Pocket<SelectedType>>();
this.selectedSameMethodSigMap = new HashMap<MyClass, Pocket<SelectedType>>();
this.tablePane = new ClassTablePanel(this,myClassList);
//テーブル情報を追加
fcp.setTableModel(tablePane.getTableModel());
mcp.setTableModel(tablePane.getTableModel());
setLayout(new BorderLayout());
initComponent();
initActionEvent();
setVisible(true);
}
public void setTableEditable(boolean isEditable){
tablePane.setTableEditable(isEditable);
}
public FieldComparePanel getFcp() {
return fcp;
}
public MethodComparePanel getMcp() {
return mcp;
}
public ClassTablePanel getTablePane() {
return tablePane;
}
public MyClass getSelectedMyClass() {
return selectedMyClass;
}
public JTree getJtree() {
return jtree;
}
private void initComponent(){
JPanel panel;
ClassNode child = null;
holizontalSplitePane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
verticalSplitePane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
compVerticalSplitePane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
astahRoot = new DefaultMutableTreeNode("Class");
jtree = new JTree(astahRoot);
jtree.setMinimumSize(new Dimension(150,200));
classNamePane = new JPanel(new FlowLayout(FlowLayout.LEFT));
//フィールド
boolean isSameFieldSelected = false;
//メソッド
boolean isSameMethodSelected = false;
//比較パネルの初期化
for (MyClass myClass : myClassList) {
child = new ClassNode(myClass);
astahRoot.add(child);
//デフォルトでフィールドのパネルに初期値データを入れる
isSameFieldSelected = fcp.initComponent(myClass, true);
selectedSameFieldSigMap.put(myClass, new Pocket<SelectedType>(SelectedType.OTHER));
//デフォルトでメソッドのパネルに初期値データを入れる
isSameFieldSelected = fcp.initComponent(myClass, true);
isSameMethodSelected = mcp.initComponent(myClass,true);
selectedSameMethodSigMap.put(myClass, new Pocket<SelectedType>(SelectedType.OTHER));
generatableMap.put(myClass, !isSameMethodSelected);
}
//デフォルトでパネルに初期値データを入れる
//->表示させないようにする
//フィールド
fcp.removeAll();
fcp.revalidate();
//メソッド
mcp.removeAll();
mcp.revalidate();
//上の左右パネル
//astah tree(左)
panel = new JPanel(new BorderLayout());
panel.add(jtree,BorderLayout.CENTER);
astahTreeStatus = new StatusBar(panel, "Class");
panel.add(astahTreeStatus,BorderLayout.SOUTH);
JScrollPane treeScrollPane = new JScrollPane(panel);
treeScrollPane.setMinimumSize(new Dimension(150, 200));
//astah and source panel(右)
//メソッドの対応パネル
panel = new JPanel(new BorderLayout());
//メソッドパネルを中央
panel.add(mcp,BorderLayout.CENTER);
mcpSourceStatus = new StatusBar(panel, "対応付けしてください");
mcp.setStatus(mcpSourceStatus);
mcpSourceStatus.setStatusLabelFont(new Font("SansSerif", Font.BOLD, 15));
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setMinimumSize(new Dimension(400, 150));
scrollPane.setSize(new Dimension(400, 200));
panel = new JPanel(new BorderLayout());
panel.add(scrollPane,BorderLayout.CENTER);
panel.add(mcpSourceStatus,BorderLayout.SOUTH);
compVerticalSplitePane.setBottomComponent(panel);
//フィールドの対応パネル
panel = new JPanel(new BorderLayout());
//フィールドパネルを中央
panel.add(fcp,BorderLayout.CENTER);
fcpSourceStatus = new StatusBar(panel, "対応付けしてください");
fcp.setStatus(fcpSourceStatus);
fcpSourceStatus.setStatusLabelFont(new Font("SansSerif", Font.BOLD, 15));
scrollPane = new JScrollPane(panel);
scrollPane.setMinimumSize(new Dimension(400, 150));
scrollPane.setSize(new Dimension(400, 200));
panel = new JPanel(new BorderLayout());
panel.add(scrollPane,BorderLayout.CENTER);
panel.add(fcpSourceStatus,BorderLayout.SOUTH);
compVerticalSplitePane.setTopComponent(panel);
compVerticalSplitePane.setContinuousLayout(true);
//クラス,フィールド,メソッドをまとめる
classFieldMethodPane = new JPanel();
classFieldMethodPane.setLayout(new BorderLayout(5,5));
classFieldMethodPane.add(classNamePane,BorderLayout.NORTH);
classFieldMethodPane.add(compVerticalSplitePane,BorderLayout.CENTER);
holizontalSplitePane.setLeftComponent(treeScrollPane);
holizontalSplitePane.setRightComponent(classFieldMethodPane);
holizontalSplitePane.setContinuousLayout(true);
//下のテーブル
JScrollPane tableScrollPane = new JScrollPane(tablePane);
tableScrollPane.setMinimumSize(new Dimension(400, 100));
tableScrollPane.setSize(new Dimension(400, 150));
tableScrollPane.add(new StatusBar(tableScrollPane, "クラスの対応関係の設定"));
verticalSplitePane.setTopComponent(holizontalSplitePane);
verticalSplitePane.setBottomComponent(tableScrollPane);
verticalSplitePane.setContinuousLayout(true);
add(verticalSplitePane,BorderLayout.CENTER);
}
private void initActionEvent() {
jtree.addTreeSelectionListener(new TreeSelectionListener(){
@Override
public void valueChanged(TreeSelectionEvent e) {
Object obj = jtree.getLastSelectedPathComponent();
StringBuilder popSb = new StringBuilder();
IClass iClass;
IComment[] comments;
IConstraint[] constraints;
if (obj instanceof ClassNode) {
ClassNode selectedNode = (ClassNode) obj;
Object userObj = selectedNode.getUserObject();
if (userObj instanceof MyClass) {
selectedMyClass = (MyClass) userObj;
iClass = selectedMyClass.getIClass();
//jtreeで選択したクラスを表示
jtrSelClass = new JLabel();
jtrSelClass.setFont(new Font("SansSerif", Font.BOLD, 18));
jtrSelClass.setCursor(new Cursor(Cursor.HAND_CURSOR));
jtrSelClass.setText(selectedMyClass.getName());
classNamePane.removeAll();
classNamePane.revalidate();
classNamePane.repaint();
classNamePane.add(jtrSelClass);
//クラス図を表示
jtrSelClass.addMouseListener(new ClassLabelMouseAdapter(selectedMyClass, jtrSelClass, getParent(),ClickedLabel.ClassName));
//説明を加える
popSb.append("<html>");
popSb.append("<p>");
popSb.append("定義:<br>");
if (selectedMyClass.getDefinition().isEmpty()) {
popSb.append("なし<br>");
}else{
String[] strs = iClass.getDefinition().split("\\n", 0);
for (String comment : strs) {
popSb.append(comment + "<br>");
}
}
popSb.append("コメント:<br>");
if (iClass.getComments().length == 0) {
popSb.append("なし<br>");
}else{
comments = iClass.getComments();
for (IComment comment : comments){
popSb.append("・"+comment.toString()+"<br>");
}
}
popSb.append("制約:<br>");
if (iClass.getConstraints().length == 0) {
popSb.append("なし<br>");
}else{
constraints = iClass.getConstraints();
for (IConstraint constraint : constraints){
popSb.append("・"+constraint.toString()+"<br>");
}
}
popSb.append("</p>");
popSb.append("</html>");
jtrSelClass.setToolTipText(popSb.toString());
//パネルの更新
//ユーザーがJComboBoxのリストのアイテム値を変更した時に記憶しておく
reLoadMemberPane(selectedMyClass,false);
}
}
}
});
}
//TODO
//フィールドやメソッドのボックスが一部空の場合に
//どのように対処するか考える
public void reLoadMemberPane(MyClass myClass,boolean isAllChange){
Map<MyClass, List<JPanel>> fieldMapPanelList = fcp.getMapPanelList();
Map<MyClass, List<JPanel>> methodMapPanelList = mcp.getMapPanelList();
List<JPanel> methodPanelList = methodMapPanelList.get(myClass);
List<JPanel> fieldPanelList = fieldMapPanelList.get(myClass);
Component component;
JComboBox methodCodeSigBox = null;
JComboBox fieldCodeSigBox = null;
List<String> fieldCodeSigList = new ArrayList<String>();
List<String> methodCodeSigList = new ArrayList<String>();
Object obj = null;
Pocket<SelectedType> fieldPocket = null;
Pocket<SelectedType> methodPocket = null;
String baseSig,comparedSig;
boolean isMethodSame;
boolean isFieldSame;
//パネルの更新
//フィールド
fcp.removeAll();
fcp.revalidate();
fcp.initComponent(myClass, isAllChange);
//メソッド
mcp.removeAll();
mcp.revalidate();
mcp.initComponent(myClass,isAllChange);
astahTreeStatus.setText("Class:"+myClass.getName());
//ステータスバーによるエラーチェック(メソッド)
for (JPanel panel : methodPanelList) {
for (int i = 0; i < panel.getComponentCount(); i++) {
component = panel.getComponent(i);
methodCodeSigBox = null;
if (component instanceof JComboBox) {
methodCodeSigBox = (JComboBox) component;
}
if (methodCodeSigBox != null) {
obj = methodCodeSigBox.getSelectedItem();
if (obj != null) {
methodCodeSigList.add(obj.toString());
}
}
}
}
//ステータスバーによるエラーチェック(フィールド)
for (JPanel panel : fieldPanelList) {
for (int i = 0; i < panel.getComponentCount(); i++) {
component = panel.getComponent(i);
fieldCodeSigBox = null;
if (component instanceof JComboBox) {
fieldCodeSigBox = (JComboBox) component;
}
if (fieldCodeSigBox != null) {
obj = fieldCodeSigBox.getSelectedItem();
if (obj != null) {
fieldCodeSigList.add(obj.toString());
}
}
}
}
isMethodSame = false;
isFieldSame = false;
//同じメソッドが選択されていないかチェック
//選択できないメソッドがあるかどうか
for(int i=0;i<methodCodeSigList.size();i++){
baseSig = methodCodeSigList.get(i);
for(int j=0;j<methodCodeSigList.size();j++){
comparedSig = methodCodeSigList.get(j);
if (i==j) {
continue ;
}
if (baseSig.equals(comparedSig)) {
isMethodSame = true;
break;
}
}
if (isMethodSame) {
break;
}
}
//同じフィールドが選択されていないかチェック
//あるいは選択できないフィールドがあるかどうか
for(int i=0;i<fieldCodeSigList.size();i++){
baseSig = fieldCodeSigList.get(i);
for(int j=0;j<fieldCodeSigList.size();j++){
comparedSig = fieldCodeSigList.get(j);
if (i==j) {
continue ;
}
if (baseSig.equals(comparedSig)) {
isFieldSame = true;
break;
}
}
if (isFieldSame) {
break;
}
}
fieldPocket = selectedSameFieldSigMap.get(myClass);
methodPocket = selectedSameMethodSigMap.get(myClass);
//フィールド
if (isFieldSame) {
fieldPocket.set(SelectedType.SAME);
}else{
fieldPocket.set(SelectedType.NOTSAME);
}
//メソッド
if (isMethodSame) {
methodPocket.set(SelectedType.SAME);
}else{
methodPocket.set(SelectedType.NOTSAME);
}
checkSameField(myClass);
checkSameMethod(myClass);
if (fieldCodeSigList.size() == 0 ||
fieldPanelList.size() - 1 != fieldCodeSigList.size()) {
fcpSourceStatus.setColor(Color.red);
fcpSourceStatus.setText("フィールドが空です");
setGeneratable(myClass, false);
}
if (methodCodeSigList.size() == 0 ||
methodPanelList.size() - 1 != methodCodeSigList.size()) {
mcpSourceStatus.setColor(Color.red);
mcpSourceStatus.setText("メソッドが空です ");
setGeneratable(myClass, false);
}
}
private void checkSameField(MyClass myClass) {
Pocket<SelectedType> pocket = selectedSameFieldSigMap.get(myClass);
if (pocket.get() == SelectedType.SAME) {
fcpSourceStatus.setColor(Color.red);
fcpSourceStatus.setText("同じフィールドを選択しないでください");
setGeneratable(myClass ,false);
}else if(pocket.get() == SelectedType.NOTSAME){
fcpSourceStatus.setColor(Color.green);
fcpSourceStatus.setText("OK");
setGeneratable(myClass ,true);
}
}
public void checkSameMethod(MyClass myClass){
Pocket<SelectedType> pocket = selectedSameMethodSigMap.get(myClass);
if (pocket.get() == SelectedType.SAME) {
mcpSourceStatus.setColor(Color.red);
mcpSourceStatus.setText("同じメソッドを選択しないでください");
setGeneratable(myClass ,false);
}else if(pocket.get() == SelectedType.NOTSAME){
mcpSourceStatus.setColor(Color.green);
mcpSourceStatus.setText("OK");
setGeneratable(myClass ,true);
}
}
public void setGeneratable(MyClass myClass , boolean b) {
generatableMap.put(myClass, b);
}
/**
* フィールドのボックスに空があるかどうか判定するメソッド
* @return
*/
public boolean isFieldPanelEmpty(){
boolean isEmpty = false;
List<JPanel> fieldPanelList;
Component comp;
JComboBox box_1;
JPanel panel;
for(MyClass myClass : generatableMap.keySet()){
fieldPanelList = fcp.getMapPanelList().get(myClass);
for(int i = 0; i<fieldPanelList.size();i++){
panel = fieldPanelList.get(i);
for(int j = 0; j<panel.getComponentCount();j++){
comp = panel.getComponent(j);
if(comp instanceof JComboBox){
box_1 = (JComboBox) comp;
if(box_1.getSelectedItem() == null){
isEmpty = true;
return isEmpty;
}
}
}
}
}
return isEmpty;
}
/**
* メソッドのボックスに空があるかどうか判定するメソッド
* @return
*/
public boolean isMethodPanelEmpty(){
boolean isEmpty = false;
List<JPanel> methodPanelList;
Component comp;
JComboBox box_1;
JPanel panel;
for(MyClass myClass : generatableMap.keySet()){
methodPanelList = mcp.getMapPanelList().get(myClass);
System.out.println("myClass : " + myClass.getName());
for(int i = 0; i<methodPanelList.size();i++){
panel = methodPanelList.get(i);
for(int j = 0; j<panel.getComponentCount();j++){
comp = panel.getComponent(j);
if(comp instanceof JComboBox){
box_1 = (JComboBox) comp;
if(box_1.getSelectedItem() == null){
isEmpty = true;
return isEmpty;
}
}
}
}
}
return isEmpty;
}
//同じフィールドがないかどうか調べる
public boolean isFieldGeneratable(){
boolean generatable = true;
List<JPanel> fieldPanelList;
Component comp;
JComboBox box_1;
JPanel panel;
for(MyClass myClass : generatableMap.keySet()){
fieldPanelList = fcp.getMapPanelList().get(myClass);
for(int i = 0; i<fieldPanelList.size();i++){
panel = fieldPanelList.get(i);
for(int j = 0; j<panel.getComponentCount();j++){
comp = panel.getComponent(j);
if(comp instanceof JComboBox){
box_1 = (JComboBox) comp;
generatable = !checkSameItemSelected(i, box_1, fieldPanelList);
if (generatable == false) {
System.out.println(generatable);
}
if (!generatable) {
return generatable;
}
}
}
}
}
return generatable;
}
public boolean isMethodGeneratable(){
boolean generatable = true;
List<JPanel> methodPanelList;
Component comp;
JComboBox box_1;
JPanel panel;
for(MyClass myClass : generatableMap.keySet()){
methodPanelList = mcp.getMapPanelList().get(myClass);
System.out.println("myClass : " + myClass.getName());
for(int i = 0; i<methodPanelList.size();i++){
panel = methodPanelList.get(i);
for(int j = 0; j<panel.getComponentCount();j++){
comp = panel.getComponent(j);
if(comp instanceof JComboBox){
box_1 = (JComboBox) comp;
generatable = !checkSameItemSelected(i, box_1, methodPanelList);
if (!generatable) {
return generatable;
}
}
}
}
}
return generatable;
}
private boolean checkSameItemSelected(int index,
JComboBox box_1,
List<JPanel> panelList) {
boolean isSame = false;
Component comp;
JComboBox box_2;
String strBox_1,strBox_2;
JPanel panel;
Object obj;
obj = box_1.getSelectedItem();
//ボックスのアイテムが空の場合
if (obj == null){
return true;
}
strBox_1 = box_1.getSelectedItem().toString();
System.out.println("strBox_1 : " + strBox_1);
for(int i=0;i<panelList.size();i++){
if (i == index) {
continue ;
}
panel = panelList.get(i);
for(int j = 0 ; j <panel.getComponentCount();j++){
comp = panel.getComponent(j);
if (comp instanceof JComboBox) {
box_2 = (JComboBox) comp;
obj = box_2.getSelectedItem();
//ボックスのアイテムが空の場合
if (obj == null) {
continue ;
}
strBox_2 = box_2.getSelectedItem().toString();
System.out.println("strBox_2 : " + strBox_2);
if (strBox_1.equals(strBox_2)) {
isSame = true;
break;
}
}
}
if (isSame) {
break;
}
}
System.out.println("isSame : "+isSame);
return isSame;
}
public boolean isFieldEpmty() {
boolean generatable = true;
List<JPanel> fieldPanelList;
JPanel panel;
Component comp;
JComboBox box_1;
for(MyClass myClass : generatableMap.keySet()){
fieldPanelList = fcp.getMapPanelList().get(myClass);
for(int i = 0; i<fieldPanelList.size();i++){
panel = fieldPanelList.get(i);
for(int j = 0; j<panel.getComponentCount();j++){
comp = panel.getComponent(j);
if(comp instanceof JComboBox){
box_1 = (JComboBox) comp;
if (box_1.getSelectedItem() == null) {
generatable = false;
return generatable;
}
}
}
}
}
return generatable;
}
public boolean isMethodEmpty() {
boolean generatable = true;
List<JPanel> methodPanelList;
JPanel panel;
Component comp;
JComboBox box_1;
for(MyClass myClass : generatableMap.keySet()){
methodPanelList = mcp.getMapPanelList().get(myClass);
for(int i = 0; i<methodPanelList.size();i++){
panel = methodPanelList.get(i);
for(int j = 0; j<panel.getComponentCount();j++){
comp = panel.getComponent(j);
if(comp instanceof JComboBox){
box_1 = (JComboBox) comp;
if (box_1.getSelectedItem() == null) {
generatable = false;
return generatable;
}
}
}
}
}
return generatable;
}
}
|
/*
* Copyright (C) 2023 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hedera.mirror.web3.evm.pricing;
import static com.hederahashgraph.api.proto.java.HederaFunctionality.ContractCall;
import static org.apache.commons.lang3.ArrayUtils.EMPTY_BYTE_ARRAY;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import com.hedera.mirror.web3.repository.FileDataRepository;
import com.hederahashgraph.api.proto.java.CurrentAndNextFeeSchedule;
import com.hederahashgraph.api.proto.java.ExchangeRate;
import com.hederahashgraph.api.proto.java.ExchangeRateSet;
import com.hederahashgraph.api.proto.java.FeeData;
import com.hederahashgraph.api.proto.java.FeeSchedule;
import com.hederahashgraph.api.proto.java.TimestampSeconds;
import com.hederahashgraph.api.proto.java.TransactionFeeSchedule;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class RatesAndFeesLoaderTest {
@Mock
private FileDataRepository fileDataRepository;
@InjectMocks
private RatesAndFeesLoader subject;
private static final long nanos = 1_234_567_890L;
private static final ExchangeRateSet exchangeRatesSet = ExchangeRateSet.newBuilder()
.setCurrentRate(ExchangeRate.newBuilder()
.setCentEquiv(1)
.setHbarEquiv(12)
.setExpirationTime(TimestampSeconds.newBuilder().setSeconds(nanos))
.build())
.setNextRate(ExchangeRate.newBuilder()
.setCentEquiv(2)
.setHbarEquiv(31)
.setExpirationTime(TimestampSeconds.newBuilder().setSeconds(2_234_567_890L))
.build())
.build();
private static final String CORRUPT_RATES_MESSAGE = "Rates 0.0.112 are corrupt!";
private static final long EXCHANGE_RATES_ID = 112L;
private static final CurrentAndNextFeeSchedule feeSchedules = CurrentAndNextFeeSchedule.newBuilder()
.setCurrentFeeSchedule(FeeSchedule.newBuilder()
.setExpiryTime(TimestampSeconds.newBuilder().setSeconds(nanos))
.addTransactionFeeSchedule(TransactionFeeSchedule.newBuilder()
.setHederaFunctionality(ContractCall)
.addFees(FeeData.newBuilder().build())))
.setNextFeeSchedule(FeeSchedule.newBuilder()
.setExpiryTime(TimestampSeconds.newBuilder().setSeconds(2_234_567_890L))
.addTransactionFeeSchedule(TransactionFeeSchedule.newBuilder()
.setHederaFunctionality(ContractCall)
.addFees(FeeData.newBuilder().build())))
.build();
private static final String CORRUPT_SCHEDULES_MESSAGE = "Fee schedule 0.0.111 is corrupt!";
private static final long FEE_SCHEDULES_ID = 111L;
@Test
void loadExchangeRates() {
when(fileDataRepository.getFileAtTimestamp(eq(EXCHANGE_RATES_ID), anyLong()))
.thenReturn(exchangeRatesSet.toByteArray());
final var actual = subject.loadExchangeRates(nanos);
assertThat(actual).isEqualTo(exchangeRatesSet);
}
@Test
void loadEmptyExchangeRates() {
when(fileDataRepository.getFileAtTimestamp(eq(EXCHANGE_RATES_ID), anyLong()))
.thenReturn(EMPTY_BYTE_ARRAY);
final var actual = subject.loadExchangeRates(nanos);
assertThat(actual).isEqualTo(ExchangeRateSet.newBuilder().build());
}
@Test
void loadWrongDataExchangeRates() {
when(fileDataRepository.getFileAtTimestamp(eq(EXCHANGE_RATES_ID), anyLong()))
.thenReturn("corrupt".getBytes());
final var exception = assertThrows(IllegalStateException.class, () -> subject.loadExchangeRates(nanos));
assertThat(exception.getMessage()).isEqualTo(CORRUPT_RATES_MESSAGE);
}
@Test
void loadFeeSchedules() {
when(fileDataRepository.getFileAtTimestamp(eq(FEE_SCHEDULES_ID), anyLong()))
.thenReturn(feeSchedules.toByteArray());
final var actual = subject.loadFeeSchedules(nanos);
assertThat(actual).isEqualTo(feeSchedules);
}
@Test
void loadEmptyFeeSchedules() {
when(fileDataRepository.getFileAtTimestamp(eq(FEE_SCHEDULES_ID), anyLong()))
.thenReturn(EMPTY_BYTE_ARRAY);
final var actual = subject.loadFeeSchedules(nanos);
assertThat(actual).isEqualTo(CurrentAndNextFeeSchedule.newBuilder().build());
}
@Test
void loadWrongDataFeeSchedules() {
when(fileDataRepository.getFileAtTimestamp(eq(FEE_SCHEDULES_ID), anyLong()))
.thenReturn("corrupt".getBytes());
final var exception = assertThrows(IllegalStateException.class, () -> subject.loadFeeSchedules(nanos));
assertThat(exception.getMessage()).isEqualTo(CORRUPT_SCHEDULES_MESSAGE);
}
}
|
package util;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;
public class Utils {
public static final String CRLF = "\r\n";
public static final String BLANK =" ";
//拼接响应协议
public static StringBuilder createHeadInfo(StringBuilder headInfo,int length,int code){
//1、构建响应行
headInfo.append("HTTP/1.1").append(BLANK);
headInfo.append(code).append(BLANK);
switch (code){
case 200:
headInfo.append("OK").append(CRLF);
break;
case 404:
headInfo.append("NOT FOUND").append(CRLF);
break;
case 505:
headInfo.append("SERVER ERROR").append(CRLF);
break;
}
//2、构建响应头
headInfo.append("Server:").append("websever Server/0.0.1;charset=utf-8").append(CRLF);
headInfo.append("Content-type:text/html").append(CRLF);
headInfo.append("Content-length:").append(length).append(CRLF);
headInfo.append("Date:").append(new Date()).append(CRLF);
headInfo.append(CRLF);
return headInfo;
}
//读取html
public static String readHtml(InputStream in,String html) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] msg = new byte[10];
int len = -1;
while ((len=in.read(msg))!=-1){
out.write(msg,0,len);
if (len < msg.length){
break;
}
}
in.close();
out.close();
return new String(out.toByteArray());
}
//利用SAX解析配置文件
public static WebContext parseText(String text){
WebContext webContext = null;
try {
//SAX解析
// 1、获取解析工厂
SAXParserFactory factory = SAXParserFactory.newInstance();
// 2、从解析工厂获取解析器
SAXParser parser = factory.newSAXParser();
// 3、解析处理器
// 4、加载文档注册处理器
WebHandler handler = new WebHandler();
// 5、解析
InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(text);
parser.parse(in,handler);
// 获取数据
webContext = new WebContext(handler.getEntities(), handler.getMappings());
} catch (Exception e) {
System.err.println("解析配置文件失败...");
e.printStackTrace();
}
return webContext;
}
}
|
package com.example.demo.exceptions;
public class ParameterNotFoundException extends Exception {
String message;
public ParameterNotFoundException(String message) {
super(message);
}
}
|
package com.e6soft.api.userright;
/**
* 组织机构接口
* @author 陈福忠
*
*/
public interface UserRightInterface {
}
|
package com.yunusunnotlari.animasyon;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
}
public void buttonClick(View view){
Animation animation= AnimationUtils.loadAnimation(this,R.anim.blink_anim);
button.startAnimation(animation);
}
}
|
class Solution {
Integer ways[];
Set<Integer>
temp = new HashSet();
public int climbStairs(int n) {
ways = new Integer [n + 1];
if(n == 0)
return 0;
ways[0] = 1;
ways[1] = 1;
return differentWays(n);
}
int differentWays(int n)
{
if(n < 0)
{
return 0;
}
if(ways[n] != null)
{
return ways[n];
}
int way1 = differentWays(n-1);
int way2 = differentWays(n-2);
ways[n] = way1 + way2;
return ways[n];
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* KReportOrderPara generated by hbm2java
*/
public class KReportOrderPara implements java.io.Serializable {
private KReportOrderParaId id;
private KReportOrder KReportOrder;
public KReportOrderPara() {
}
public KReportOrderPara(KReportOrderParaId id, KReportOrder KReportOrder) {
this.id = id;
this.KReportOrder = KReportOrder;
}
public KReportOrderParaId getId() {
return this.id;
}
public void setId(KReportOrderParaId id) {
this.id = id;
}
public KReportOrder getKReportOrder() {
return this.KReportOrder;
}
public void setKReportOrder(KReportOrder KReportOrder) {
this.KReportOrder = KReportOrder;
}
}
|
package cz.alza.uitest.tests;
import java.io.FileNotFoundException;
import static com.codeborne.selenide.Selenide.$;
public class DownloadTest {
public void downloadByXpathTest(){
try {
$("div").download();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
|
package com.github.frostyaxe.cucumber.hooks;
import com.github.frostyaxe.cucumber.controllers.BaseController;
import io.cucumber.java8.En;
/**
* <b>Description:</b> This hook class closes the browser session once the
* execution gets completed.
*
* @author Abhishek Prajapati
* @team Frostyaxe
* @email prajapatiabhishek1996@gmail.com
*
*/
public class ServiceHooks implements En{
/**
* Initialization/Declaration of class/instance variables
*/
BaseController controller;
/**
* <b>Description:</b> This constructor contains the implemented method that
* removes the browser session and closes the web browser, once the execution is
* completed.
*
* @param controller: Object of the basecontroller containing the webdriver
* object.
* @author Abhishek Prajapati
* @team Frostyaxe
* @email prajapatiabhishek1996@gmail.com
*/
public ServiceHooks(BaseController controller)
{
this.controller = controller;
/**
* It will be called when the execution of cucumber test script will get
* completed.
*/
After( (scenario)->
{
controller.getDriver().quit();
});
}
}
|
package com.njupt.ws_cxf_spring.ws.bean;
public class APPInfo {
private String devkey;
private String datatype;
private String showtype;
public APPInfo(String devkey, String datatype, String showtype) {
super();
this.devkey = devkey;
this.datatype = datatype;
this.showtype = showtype;
}
public String getDevkey() {
return devkey;
}
public void setDevkey(String devkey) {
this.devkey = devkey;
}
public String getDatatype() {
return datatype;
}
public void setDatatype(String datatype) {
this.datatype = datatype;
}
public String getShowtype() {
return showtype;
}
public void setShowtype(String showtype) {
this.showtype = showtype;
}
@Override
public String toString() {
return "APPInfo [devkey=" + devkey + ", datatype=" + datatype + ", showtype=" + showtype + "]";
}
}
|
package model;
/**
* Created by 11437 on 2017/12/5.
*/
public class Register {
private String userid;
private String code;
private String password;
private String status;
private String nickname;
private int gender;
private String Tel;
private int type;
public void setNickname(String nickname){this.nickname=nickname;}
public void setGender(int gender){this.gender=gender;}
public void setTel(String Tel){this.Tel=Tel;}
public void setType(int type){this.type=type;}
public void setUserid(String userid){
this.userid=userid;
}
public void setCode(String code){
this.code=code;
}
public void setPassword(String password){
this.password=password;
}
public void setStatus(String status){
this.status=status;
}
public String getUserid(){
return this.userid;
}
public String getCode(){
return this.code;
}
public String getPassword(){
return this.password;
}
public String getStatus(){
return this.status;
}
public int getType(){return this.type;}
public String getNickname(){return this.nickname;}
public int getGender(){return this.gender;}
public String getTel(){return this.Tel;}
}
|
package wrapper;
import beans.GraduateLeave;
import java.util.List;
public class GraduateLeaveOperate implements BasicOperate<GraduateLeave> {
@Override
public GraduateLeave getById(String x) {
return null;
}
@Override
public List<GraduateLeave> getAll() {
return null;
}
@Override
public void insert(GraduateLeave x) {
}
@Override
public void updateById(GraduateLeave x) {
}
@Override
public void softDeleteById(String Id) {
}
@Override
public void forceDeleteById(String id) {
}
@Override
public void createTable() {
}
@Override
public void dropTable() {
}
}
|
public class Course {
private String courseID;
private String courseName;
private String startDate;
private String endDate;
private String summary;
private int enrollmentLimit;
private int numberOfStudentsEnrolled;
public Course()
{
}
public Course(String courseID, String courseName, String startDate, String endDate,
String summary, int enrollmentLimit, int numberOfStudentsEnrolled) {
this.courseID = courseID;
this.courseName = courseName;
this.startDate = startDate;
this.endDate = endDate;
this.summary = summary;
this.enrollmentLimit = enrollmentLimit;
this.numberOfStudentsEnrolled = numberOfStudentsEnrolled;
}
public String getCourseID() {
return courseID;
}
public void setCourseID(String courseID) {
this.courseID = courseID;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public int getEnrollmentLimit() {
return enrollmentLimit;
}
public void setEnrollmentLimit(int enrollmentLimit) {
this.enrollmentLimit = enrollmentLimit;
}
public int getNumberOfStudentsEnrolled() {
return numberOfStudentsEnrolled;
}
public void setNumberOfStudentsEnrolled(int numberOfStudentsEnrolled) {
this.numberOfStudentsEnrolled = numberOfStudentsEnrolled;
}
public String toString()
{
return "CourseID:" + courseID + ", CourseName:" + courseName + ", EnrollmentLimit:"
+ enrollmentLimit + ", Students Enrolled:" + numberOfStudentsEnrolled;
}
}
|
/**
*
*/
package com.shubhendu.javaworld;
/**
* Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
The update(i, val) function modifies nums by updating the element at index i to val.
Example:
Given nums = [1, 3, 5]
sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8
Note:
The array is only modifiable by the update function.
You may assume the number of calls to update and sumRange function is distributed evenly.
*
*/
public class NumArray2 {
private int[] sumArr;
private int[] nums;
public NumArray2(int[] nums) {
if (nums == null || nums.length == 0) {
return;
}
this.nums = nums;
this.sumArr = new int[this.nums.length];
sumArr[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
sumArr[i] = sumArr[i - 1] + nums[i];
}
}
public void update(int i, int val) {
if (sumArr == null)
return;
if (nums[i] == val)
return;
if (i >= nums.length)
return;
int diff = val - nums[i];
nums[i] = val;
for (int x = i; x < sumArr.length; x++) {
sumArr[x] = sumArr[x] + diff;
}
}
public int sumRange(int i, int j) {
if (sumArr != null && i < sumArr.length && j < sumArr.length) {
int length = this.nums.length;
if (i == 0) {
return sumArr[j];
}
int lhs = sumArr[i - 1];
int rhs = sumArr[length - 1] - sumArr[j];
return sumArr[length - 1] - lhs - rhs;
}
return -1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
|
package com.takshine.wxcrm.service;
import com.takshine.wxcrm.base.services.EntityService;
import com.takshine.wxcrm.domain.WeekReport;
import com.takshine.wxcrm.message.error.CrmError;
import com.takshine.wxcrm.message.sugar.WeekReportResp;
/**
* 周报 业务处理接口
*
* @author dengbo
*/
public interface WeekReport2SugarService extends EntityService {
/**
* 查询周报数据列表
* @return
*/
public WeekReportResp getWeekReportList(WeekReport wReport,String source);
/**
* 查询单个周报数据
* @param rowId
* @param crmId
* @return
*/
public WeekReportResp getWeekReportSingle(String rowId, String crmId);
/**
* 保存周报信息
* @param oppty
* @return
*/
public CrmError addWeekReport(WeekReport wReport);
}
|
package Application;
import java.io.File;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.FileChooser;
public class Controller_InsertDS {
static BorderPane layout = null;
@FXML
private Label Title;
@FXML
private Label Nome_DS;
@FXML
private Button Scegli_DS;
@FXML
private Label Label_Num_Fen;
@FXML
private Label Label_Num_Caratt;
@FXML
private TextField UserName;
@FXML
private PasswordField Password;
@FXML
private TextField NomeDB;
@FXML
private TextField NomeTabella;
@FXML
private Button Avanti_Button;
private String PathAssolutoDS = "";
public static void esegui()
{
try
{
if( layout == null )
{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(TestMain.class.getResource("Insert_DataSet.fxml"));
layout = loader.load();
layout.getStylesheets().add(Controller_InsertDS.class.getResource("Style.css").toExternalForm());
}
}
catch( Exception e )
{
e.printStackTrace();
}
TestMain.setCenterLayout(layout);
}
@FXML
void initialize()
{
Title.getStyleClass().add("Title_Page");
Scegli_DS.getStyleClass().add("button_setting");
Scegli_DS.setOnAction( e -> SelezioneDataSet() );
Avanti_Button.getStyleClass().add("button_next");
Avanti_Button.setOnAction( e -> CheckInfo() );
}
private void SelezioneDataSet()
{
FileChooser File = new FileChooser();
File.setTitle("Scegli DataSet");
File.setInitialDirectory( new File( System.getProperty("user.home")) );
File.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("Text", "*.txt"),
new FileChooser.ExtensionFilter("DataSet", "*.data"),
new FileChooser.ExtensionFilter("CSV", "*.csv"),
new FileChooser.ExtensionFilter("All Files", "*.*") );
File FileScelto = File.showOpenDialog( TestMain.getStage() );
if( FileScelto != null )
{
PathAssolutoDS = FileScelto.getAbsolutePath();
Nome_DS.setText( FileScelto.getName() );
int Elemento[] = TestMain.getSessione_InCorso().Inserimento_File_DataSet(PathAssolutoDS);
Label_Num_Fen.setText("" + Elemento[0]);
Label_Num_Caratt.setText("" + Elemento[1] );
}
}
private void CheckInfo()
{
Allert_Message Mess = null;
if( PathAssolutoDS.length() == 0 )
Mess = new Allert_Message( TestMain.getStage(), "Nessun File DataSet Scelto !!!" );
else if( UserName.getLength() == 0 )
Mess = new Allert_Message( TestMain.getStage(), "Username DataBase non Inserito !!!" );
else if( NomeDB.getLength() == 0 )
Mess = new Allert_Message( TestMain.getStage(), "Nome DataBase non Inserito !!!" );
else if( NomeTabella.getLength() == 0 )
Mess = new Allert_Message( TestMain.getStage(), "Nome Tabella non Inserito !!!" );
if( Mess != null )
return;
if( TestMain.getSessione_InCorso().Crea_DataBase( UserName.getText(), Password.getText(), NomeDB.getText(), NomeTabella.getText() ) )
TestMain.getSessione_InCorso().Carica_Stage_ListDataSet();
else
Mess = new Allert_Message( TestMain.getStage(), "Inserimento Dati DataBase non Corretto !!!" );
}
}
|
package com.philippe.app.hbase;
import com.philippe.app.service.hbase.HBaseWriteManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.lang.String.format;
public class StormSimulatorTest {
private static final Logger LOGGER = LoggerFactory.getLogger(StormSimulatorTest.class);
public static void main(String args[]) {
HBaseWriteManager hBaseWriteManager = new HBaseWriteManager();
Thread streamToHBaseThread = new Thread(hBaseWriteManager);
streamToHBaseThread.setUncaughtExceptionHandler(getErrorHandler());
LOGGER.debug("About to start thread to HBase...");
streamToHBaseThread.start();
Runtime.getRuntime().addShutdownHook(new Thread(hBaseWriteManager::shutdown));
hBaseWriteManager.startScheduleTask();
}
private static Thread.UncaughtExceptionHandler getErrorHandler() {
return (th, e) -> {
String errorMsg = e.getMessage();
LOGGER.debug(format("Unhandled exception caught - %", errorMsg), e);
};
}
}
|
/**
*
*/
package chapter_4;
import java.util.*;
/**
* @author Ashish
* This programs displays the any given sting in reverse order without using in-built methods.
*
*
*/
public class ReverseString {
private String s, rev=""; //Two variables defined one to get a string value and other to hold the reverse value of string.
public void getDetails() // Method to get the values of string from the user.
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter a String");
s=sc.nextLine();
System.out.println("The entered string is "+s);
sc.close();
}
public void reverse() // Logic which reverses the string.
{
int length=s.length();
for(int i=length-1;i>=0;i--) // Loop running from the last character of the string till the first.
{
rev=rev+s.charAt(i); // Storing the reverse value to rev variable.
}
System.out.println("Reverse of String is "+rev);
}
public static void main(String[] args) {
ReverseString obj=new ReverseString(); // Object is created.
obj.getDetails(); // getDetails method called to get a value of the string fromt the user.
obj.reverse(); // reverse method called to reverse the user given string.
}
}
|
package com.netbanking.util;
import java.util.regex.Pattern;
public class XSSChecker {
public static String stripXSS(String input) {
//REFERENCE LINK USED ------ http://www.javacodegeeks.com/2012/07/anti-cross-site-scripting-xss-filter.html
if (input != null) {
input = input.replaceAll("", "");
Pattern pattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE);
input = pattern.matcher(input).replaceAll("");
pattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE);
input = pattern.matcher(input).replaceAll("");
pattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);
input = pattern.matcher(input).replaceAll("");
pattern = Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
input = pattern.matcher(input).replaceAll("");
pattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE);
input = pattern.matcher(input).replaceAll("");
pattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
input = pattern.matcher(input).replaceAll("");
pattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
input = pattern.matcher(input).replaceAll("");
pattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
input = pattern.matcher(input).replaceAll("");
pattern = Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
input = pattern.matcher(input).replaceAll("");
pattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
input = pattern.matcher(input).replaceAll("");
}
return input;
}
}
|
/*
* 2012-3 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.rtgov.tests.epn;
import java.io.Serializable;
/**
* This class is object 1.
*
*/
public class Obj1 implements Serializable {
private static final long serialVersionUID = -7692716785700403849L;
private int _value=0;
/**
* This is the constructor.
*
* @param val The value
*/
public Obj1(int val) {
_value = val;
}
/**
* This method returns the value.
*
* @return The value
*/
public int getValue() {
return (_value);
}
@Override
public int hashCode() {
return (_value);
}
@Override
public boolean equals(Object obj) {
return (obj instanceof Obj1
&& ((Obj1)obj).getValue() == _value);
}
@Override
public String toString() {
return ("Obj1["+_value+"]");
}
}
|
package com.andrew.metar;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class ShowImage extends Activity {
ImageView webCamImageView;
ImageView imageCloseButton;
Bitmap bitmap;
private DefaultHttpClient createHttpClient() {
HttpParams my_httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(my_httpParams, 3000);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
ThreadSafeClientConnManager multiThreadedConnectionManager = new ThreadSafeClientConnManager(my_httpParams, registry);
DefaultHttpClient httpclient = new DefaultHttpClient(multiThreadedConnectionManager, my_httpParams);
return httpclient;
}
private class DownloadWebcamImage extends AsyncTask<Void, Void, Void> {
byte[] mResultString;
Integer mStatusCode;
Exception mConnectionException;
@Override
protected Void doInBackground(Void... args) {
String fetchUrl = "http://88.159.160.46:60080/cam_1.jpg";
DefaultHttpClient httpclient = createHttpClient();
HttpGet httpget = new HttpGet(fetchUrl);
try {
HttpResponse response = httpclient.execute(httpget);
StatusLine statusLine = response.getStatusLine();
mStatusCode = statusLine.getStatusCode();
if (mStatusCode == 200){
mResultString = EntityUtils.toByteArray(response.getEntity());
bitmap = BitmapFactory.decodeByteArray(mResultString, 0, mResultString.length);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
mConnectionException = e;
} catch (IOException e) {
e.printStackTrace();
mConnectionException = e;
}
return null;
}
@Override
protected void onPostExecute(Void arg) {
try {
if (mStatusCode == 200){
webCamImageView.setImageBitmap(bitmap);
}
else if (mStatusCode == 404){
Toast.makeText(ShowImage.this, "Page not found - 404", Toast.LENGTH_LONG).show();
}
else if (mStatusCode > 0){
Toast.makeText(ShowImage.this, "No connection: " + mStatusCode, Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(ShowImage.this, "General error (" +mConnectionException.toString() + ")" , Toast.LENGTH_LONG).show();
}
} catch (NumberFormatException e) {
Toast.makeText(ShowImage.this, "Something went wrong..." , Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showimage);
webCamImageView = (ImageView) findViewById(R.id.webCamImageView);
imageCloseButton = (ImageView) findViewById(R.id.imageCloseButton);
View root = webCamImageView.getRootView();
root.setBackgroundColor(0xFF222222);
new DownloadWebcamImage().execute();
}
public void close(View view){
if (view == imageCloseButton){
finish();
}
}
}
|
package com.ntxdev.zuptecnico.api;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ntxdev.zuptecnico.entities.InventoryCategory;
import com.ntxdev.zuptecnico.entities.InventoryItem;
import com.ntxdev.zuptecnico.entities.responses.PublishInventoryItemResponse;
import org.json.JSONObject;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by igorlira on 3/25/14.
*/
public class PublishInventoryItemSyncAction extends SyncAction {
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Serializer
{
public InventoryItem item;
public String error;
public Serializer() { }
}
public InventoryItem item;
String error;
public PublishInventoryItemSyncAction(InventoryItem item)
{
this.item = item;
this.inventory_item_id = item.id;
}
public PublishInventoryItemSyncAction(JSONObject object, ObjectMapper mapper) throws IOException
{
Serializer serializer = mapper.readValue(object.toString(), Serializer.class);
this.item = serializer.item;
this.inventory_item_id = this.item.id;
this.error = serializer.error;
}
public boolean onPerform()
{
ApiHttpResult<PublishInventoryItemResponse> response = Zup.getInstance().publishInventoryItem(item);
if(response.statusCode == 200 || response.statusCode == 201)
{
error = null;
return true;
}
else if(response.result != null && response.result.error instanceof Map)
{
String message = "";
int j = 0;
for(Object key : ((Map)response.result.error).keySet())
{
if(j > 0)
message += "\r\n\r\n";
InventoryCategory.Section.Field field = Zup.getInstance().getInventoryCategory(item.inventory_category_id).getField(key.toString());
String fieldName;
if(field == null)
fieldName = key.toString();
else
fieldName = field.label;
message += fieldName + "\r\n";
List lst = (List)((Map)response.result.error).get(key.toString());
int i = 0;
for(Object msg : lst)
{
if(i > 0)
message += "\r\n";
message += " - " + msg;
i++;
}
j++;
}
error = message;
return false;
}
else if(response.result != null && response.result.error != null)
{
error = response.result.error.toString();
return false;
}
else
{
error = "Sem conexão com a internet.";
return false;
}
}
@Override
protected JSONObject serialize() throws Exception {
Serializer serializer = new Serializer();
serializer.item = this.item;
serializer.error = this.getError();
ObjectMapper mapper = new ObjectMapper();
String res = mapper.writeValueAsString(serializer);
return new JSONObject(res);
}
@Override
public String getError() {
return error;
}
}
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
class ClientProcThread extends Thread {
private int number;
private Socket incoming;
private InputStreamReader myIsr;
private BufferedReader myIn;
private PrintWriter myOut;
public ClientProcThread(int n, Socket i, InputStreamReader isr, BufferedReader in, PrintWriter out) {
number = n % 4;
incoming = i;
myIsr = isr;
myIn = in;
myOut = out;
}
public void run() {
try {
while (true) {
String num = myIn.readLine();
if (num != null) {
number = Integer.parseInt(num);
break;
}else {
continue;
}
}
while (true) {
switch (number) {
case 0:
String str = myIn.readLine();
System.out.println("Received from Android, Messages: "+str);
if (str != null) {
/*ここでDB参照して部屋情報を照合する*/
struct_array rs = new struct_array();
if (rs.Search(str)) {
/*またtrueならstrをテキストに書き込む*/
File file = new File("room_input.txt");
if (checkBeforeWritefile(file)){
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
pw.println(str);
pw.close();
}else{
System.out.println("ファイルに書き込めません");
}
// System.out.println(rs.name);
myOut.println("i2o");
str = myIn.readLine();
if (str.equals("o2i")) {
myOut.println(rs.g_name);
}
incoming.close();
continue;
}else{
System.out.println("入力エラーです");
myOut.println("no");
incoming.close();
continue;
}
}else {
continue;
}
case 1:
str = myIn.readLine();
System.out.println("Received from Android, Messages: "+str);
if (str != null) {
if (str.equals("OK")) {
myOut.println("ST");
incoming.close();
continue;
}else {
myOut.println("error");
continue;
}
}else {
continue;
}
case 2:
// Thread.sleep(5000);
/*roombaからの終了宣言をテキストから読みとる*/
File file = new File("finish.txt");
if (checkBeforeReadfile(file)){
BufferedReader br = new BufferedReader(new FileReader(file));
String fstr;
//while(true){
fstr = br.readLine();
// System.out.println("Read file: "+fstr);
if(fstr != null) {
if (fstr.equals("F")){
//System.out.println("案内終了状態を受理");
//}
br.close();
myOut.println("FI");
// System.out.println("FI");
incoming.close();
continue;
}
}
}else{
System.out.println("ファイルが見つからないか開けません");
}
continue;
case 3:
str = myIn.readLine();
System.out.println("Received from Android, Messages: "+str);
if (str != null) {
if (str.equals("FOK")) {
myOut.println("System close");
incoming.close();
break;
}else {
System.out.println("error");
myOut.println("error");
continue;
}
}else {
continue;
}
}
break;
}
// }catch (FileNotFoundException e){System.out.println("Not Found");
//}catch (IOException e){System.out.println("Read or Write Error");
}catch (Exception e){System.out.println("Disconnect from Android");}
}
private static boolean checkBeforeWritefile(File file){
if (file.exists()){
if (file.isFile() && file.canWrite()){
return true;
}
}
return false;
}
private static boolean checkBeforeReadfile(File file){
if (file.exists()){
if (file.isFile() && file.canRead()){
return true;
}
}
return false;
}
}
class ServerRoomba{
private static int maxConnection=100;
private static Socket[] incoming;
private static InputStreamReader[] isr;
private static BufferedReader[] in;
private static PrintWriter[] out;
private static ClientProcThread[] myClientProcThread;
public static void main(String[] args) {
incoming = new Socket[maxConnection];
isr = new InputStreamReader[maxConnection];
in = new BufferedReader[maxConnection];
out = new PrintWriter[maxConnection];
myClientProcThread = new ClientProcThread[maxConnection];
int n = 0;
try {
System.out.println("The server has launched!");
ServerSocket server = new ServerSocket(10007);
while (true) {
incoming[n] = server.accept();
System.out.println("Accept client No." + n);
isr[n] = new InputStreamReader(incoming[n].getInputStream());
in[n] = new BufferedReader(isr[n]);
out[n] = new PrintWriter(incoming[n].getOutputStream(), true);
myClientProcThread[n] = new ClientProcThread(n, incoming[n], isr[n], in[n], out[n]);//必要なパラメータを渡しスレッドを作成
myClientProcThread[n].start();
n++;
}
} catch (Exception e) {
System.err.println("ソケット作成時にエラーが発生しました: " + e);
}
}
}
|
/**
*
*/
/**
* @author c0kalla
*
*/
package stack.queue;
|
public class Moto extends Veiculo{
//Atributos
private int rodas = 0;
private int cilindrada = 0;
//Metodos
//Setters
public void setRodas(int rodas){
this.rodas = rodas;
}
public void setCilindrada(int cilindrada){
this.cilindrada = cilindrada;
}
//Getters
public int getRodas(){
return rodas;
}
public int getCilindrada(){
return cilindrada;
}
}
|
package cl.jdomynyk.pulent.presentation.views.main;
import androidx.annotation.NonNull;
import java.util.List;
import cl.jdomynyk.pulent.domain.Handler;
import cl.jdomynyk.pulent.domain.Track;
import cl.jdomynyk.pulent.domain.interactor.GetLocalTracks;
import cl.jdomynyk.pulent.domain.interactor.GetRemoteTracks;
import cl.jdomynyk.pulent.domain.interactor.UseCase;
import cl.jdomynyk.pulent.domain.interactor.UseCaseFactory;
class MainModel implements Handler<List<Track>> {
private static final String TAG = MainModel.class.getSimpleName();
private MainModelIL mListener;
private UseCaseFactory useCaseFactory;
private List<Track> tracks;
private String lastSearch;
private int currentItems;
MainModel(UseCaseFactory useCaseFactory) {
this.useCaseFactory = useCaseFactory;
}
int getCurrentItems() {
return currentItems;
}
List<Track> getTracks() {
return tracks;
}
void setListener(MainModelIL mListener) {
this.mListener = mListener;
}
void findRemoteSongs(@NonNull String name) {
this.lastSearch = name;
this.currentItems = 20;
UseCase useCase = useCaseFactory.getRemote();
useCase.execute(this, new GetRemoteTracks.Params(currentItems, name));
}
void findLocalSongs() {
this.currentItems = 20;
UseCase useCase = useCaseFactory.getLocal();
useCase.execute(this, new GetLocalTracks.Params(currentItems, lastSearch));
}
void findMoreRemoteResults() {
currentItems = currentItems + 20;
UseCase useCase = useCaseFactory.getRemote();
useCase.execute(this, new GetRemoteTracks.Params(currentItems, lastSearch));
}
void findMoreLocalResults() {
currentItems = currentItems + 20;
UseCase useCase = useCaseFactory.getLocal();
useCase.execute(this, new GetLocalTracks.Params(currentItems, lastSearch));
}
@Override
public void handle(List<Track> result) {
this.tracks = result;
mListener.onSuccessGetList();
}
@Override
public void error(Exception exception) {
mListener.onFailureGetList(exception);
}
interface MainModelIL {
void onSuccessGetList();
void onFailureGetList(Exception exception);
}
}
|
package com.tyss.cg.inheritence;
public class FunctionalInterfaceImpl implements FunctionalInterfaceEx, FunctionalInterfaceEx2 {
@Override
public void showMessage() {
System.out.println("Overriden showMessage() of FunctionalInterfaceEx");
}
@Override
public int add(int i, int j) {
return i+j;
}
public static void main(String[] args) {
FunctionalInterfaceImpl functionalInterfaceImpl=new FunctionalInterfaceImpl();
//FunctionalInterfaceEx1
functionalInterfaceImpl.dispMessage();
functionalInterfaceImpl.showMessage();
FunctionalInterfaceEx.printMessage();
//FunctionalInterfaceEx2
System.out.println(functionalInterfaceImpl.add(4, 6));
functionalInterfaceImpl.dispMessage2();
FunctionalInterfaceEx2.printMessage2();
}
}
|
package com.espendwise.manta.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.config.PlaceholderConfigurerSupport;
import javax.annotation.Resource;
import java.util.*;
@Resource(mappedName = ResourceNames.APPLICATION_SETTINGS)
public class ApplicationSettings {
private static Map<String, Map<String, String>> settings = new HashMap<String, Map<String, String>>();
private static Log logger = LogFactory.getLog(ApplicationSettings.class);
private Properties properties;
private Properties defaultProperties;
private String placeHolderPrefix = PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_PREFIX;
private String placeHolderSuffix = PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_SUFFIX;
private ApplicationSettings() {
}
public synchronized void init() {
logger.info("init()=> BEGIN");
try {
Map<String, String> properties = new HashMap<String, String>();
Set<String> emptyProperties = new HashSet<String>();
for (Map.Entry<Object, Object> e : this.properties.entrySet()) {
properties.put((String) e.getKey(), (String) e.getValue());
}
Enumeration<?> settingsPropertyKeys = defaultProperties.propertyNames();
while (settingsPropertyKeys.hasMoreElements()) {
String key = (String) settingsPropertyKeys.nextElement();
String value = (String) defaultProperties.get(key);
if (value != null) {
if (value.startsWith(placeHolderPrefix) && value.endsWith(placeHolderSuffix)) {
value = (String) this.properties.get(value.substring(2, value.length() - 1));
if (value == null) {
logger.warn("init()=> [override] Property with key [" + key + "] is empty");
emptyProperties.add(key);
}
logger.info("init()=> [override] override ['" + key + "'] -> " + value);
}
}
properties.put(key, value);
}
if (!emptyProperties.isEmpty()) {
throw new Exception("Check your configuration file, " +
"properties "+emptyProperties+" must be defined prior to use");
}
logger.info("init()=> properties.size: " + properties.size());
if (!properties.isEmpty()) {
settings.put(null, properties);
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RuntimeException("Failed to initialize application properties. " + e.getMessage(), e);
}
logger.info("init()=> settings.size: " + settings.size());
logger.info("init()=> END.");
}
public String getSettings(String property) {
return getSettings(null, property);
}
public String getSettings(String key, String property) {
String value = null;
Map<String, String> properties = settings.get(key);
if (properties != null && !properties.isEmpty()) {
value = properties.get(property);
if (value != null) {
return value;
}
}
if (key == null) {
return value;
}
properties = settings.get(null);
if (properties != null && !properties.isEmpty()) {
value = properties.get(property);
if (value != null) {
return value;
}
}
return value;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public Properties getProperties() {
return properties;
}
public void setDefaultProperties(Properties defaultProperties) {
this.defaultProperties = defaultProperties;
}
public Properties getDefaultProperties() {
return defaultProperties;
}
public String getPlaceHolderSuffix() {
return placeHolderSuffix;
}
public void setPlaceHolderSuffix(String placeHolderSuffix) {
this.placeHolderSuffix = placeHolderSuffix;
}
public String getPlaceHolderPrefix() {
return placeHolderPrefix;
}
public void setPlaceHolderPrefix(String placeHolderPrefix) {
this.placeHolderPrefix = placeHolderPrefix;
}
}
|
package library.utils;
import java.security.MessageDigest;
import java.util.Random;
/**
* Created by Administrator on 2016/12/17.
*/
public class Func {
/**
* 获取MD5加密字符串
*
* @param s
* @return
*/
public final static String getMD5(String s) {
char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
try {
byte[] btInput = s.getBytes();
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 获取分页大小
*
* @param size
* @return
*/
public static int getPageSize(String size) {
int page_size = 10;
if ("50".equals(size)) {
page_size = 50;
} else if ("30".equals(size)) {
page_size = 30;
} else if ("20".equals(size)) {
page_size = 20;
} else {
page_size = 10;
}
return page_size;
}
/**
* 获取第几分页
*
* @param str_page_now
* @return
*/
public static int getPageNow(String str_page_now) {
int page_now = getInteger(str_page_now);
if (page_now <= 0) {
page_now = 1;
}
return page_now;
}
/**
* 文字转换整型数字
*
* @param integer
* @return
*/
public static int getInteger(String integer) {
int num = -1;
try {
num = Integer.parseInt(integer);
} catch (Exception e) {
}
return num;
}
public static String randomStr(int len) {
//生成随机数,并将随机数字转换为字母
String str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Random random = new Random();
StringBuilder sRand = new StringBuilder("");
for (int i = 0; i < len; i++) {
int index = random.nextInt(str.length());
char itmp = str.charAt(index);
sRand.append(itmp);
}
return sRand.toString();
}
}
|
package cn.edu.sdjzu.xg.bysj.dao;
import cn.edu.sdjzu.xg.bysj.domain.School;
import util.Condition;
import util.JdbcHelper;
import util.Pagination;
import java.sql.*;
import java.util.Collection;
import java.util.TreeSet;
public final class SchoolDao {
public static SchoolDao schoolDao = new SchoolDao();
private SchoolDao(){
}
public static SchoolDao getInstance() {
return schoolDao;
}
//查找全部条目
public Collection<School> findAll(Connection conn,String condition,Pagination pagination) throws SQLException {
//创建集合类对象,用来保存并排序所有获得的School对象
Collection<School> schools = new TreeSet<School>();
int totalNum = SchoolDao.getInstance().count(conn);
//创建查询的主句
StringBuilder select = new StringBuilder("SELECT * from school ");
//将可能的条件附加到主句后
if (condition != null){
String clause = Condition.toWhereClause(condition);
select.append(clause);
}
if (pagination != null){
select.append(pagination.toLimitClause(totalNum)+ " ");
}//在连接上创建语句盒子对象
PreparedStatement statement = conn.prepareStatement(select.toString());
//执行SQL语句
ResultSet results = statement.executeQuery();
//遍历resultSet,并将结果写入对象存进集合内
while (results.next()){
int id = results.getInt("id");
String description = results.getString("description");
String no = results.getString("no");
String remarks = results.getString("remarks");
School school = new School(id,description,no,remarks);
schools.add(school);
}
JdbcHelper.close(results,statement,null);
//返回获得的集合对象
return schools;
}
//查找单条的方法
public School find(Integer id,Connection conn) throws SQLException {
//创建SQL语句
String search = "SELECT * from school where id = " + id;
//在连接上创建语句盒子对象
Statement statement = conn.createStatement();
try(statement){
//执行SQL语句
ResultSet results = statement.executeQuery(search);
results.next();
//将获取的对象参数写入预先创建的对象
School school = new School(results.getInt(1),
results.getString(2),
results.getString(3),
results.getString(4)
);
JdbcHelper.close(results,null,null);
return school;
}
}
//更新方法
public boolean update(School school,Connection conn) throws SQLException {
//使用预编译创建SQL语句
String update = "update School set description = ?,no= ?,remarks= ? where id = " + school.getId();
PreparedStatement statement = conn.prepareStatement(update);
//执行SQL语句并返回结果和关闭连接
try (statement) {
statement.setString(1, school.getDescription());
statement.setString(2, school.getNo());
statement.setString(3, school.getRemarks());
statement.executeUpdate();
return true;
} catch (SQLException e) {
return false;
}
}
//添加方法
public boolean add(School school,Connection conn) throws SQLException {
//使用预编译创建SQL语句
String create = "insert into School(description,no,remarks) values (?,?,?)";
PreparedStatement statement = conn.prepareStatement(create);
//执行SQL语句并返回结果和关闭连接
try (statement) {
statement.setString(1, school.getDescription());
statement.setString(2, school.getNo());
statement.setString(3, school.getRemarks());
statement.executeUpdate();
return true;
} catch (SQLException e) {
return false;
}
}
//删除方法
public boolean delete(Integer id,Connection conn) throws SQLException {
//创建删除语句
String delete = "delete from school where id = " + id;
//在连接上创建语句盒子对象
Statement statement = conn.createStatement();
//执行SQL语句
int i = statement.executeUpdate(delete);
//关闭连接
statement.close();
return (i>0);
}
public int count(Connection connection) throws SQLException {
String sql_count = "SELECT COUNT(id) as cnt FROM school";
PreparedStatement pstmt_count = connection.prepareStatement(sql_count);
int counter = 0;
ResultSet resultSet_count = pstmt_count.executeQuery();
if (resultSet_count.next()) {
counter = resultSet_count.getInt("cnt");
}return counter;
}
}
|
package io.github.apfelcreme.Pipes.Pipe;
import com.google.common.collect.Multimap;
import com.google.common.collect.MultimapBuilder;
import io.github.apfelcreme.Pipes.Exception.ChunkNotLoadedException;
import io.github.apfelcreme.Pipes.PipesConfig;
import io.github.apfelcreme.Pipes.PipesUtil;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Particle;
import org.bukkit.World;
import org.bukkit.entity.Player;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
/*
* Copyright (C) 2016 Lord36 aka Apfelcreme
* <p>
* 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 3
* of the License, or (at your option) any later version.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU General Public License along with
* this program; if not, see <http://www.gnu.org/licenses/>.
*
* @author Lord36 aka Apfelcreme
*/
public class Pipe {
private final LinkedHashMap<SimpleLocation, PipeInput> inputs;
private final LinkedHashMap<SimpleLocation, PipeOutput> outputs;
private final LinkedHashMap<SimpleLocation, ChunkLoader> chunkLoaders;
private final LinkedHashSet<SimpleLocation> pipeBlocks;
private final Material type;
private int lastTransfer = 0;
private int transfers = 0;
public Pipe(LinkedHashMap<SimpleLocation, PipeInput> inputs, LinkedHashMap<SimpleLocation, PipeOutput> outputs,
LinkedHashMap<SimpleLocation, ChunkLoader> chunkLoaders, LinkedHashSet<SimpleLocation> pipeBlocks, Material type) {
this.inputs = inputs;
this.outputs = outputs;
this.chunkLoaders = chunkLoaders;
this.pipeBlocks = pipeBlocks;
this.type = type;
}
/**
* returns the set of inputs
*
* @return the set of inputs
*/
public LinkedHashMap<SimpleLocation, PipeInput> getInputs() {
return inputs;
}
/**
* returns the set of outputs which are connected to a sorter
*
* @return the set of outputs
*/
public LinkedHashMap<SimpleLocation, PipeOutput> getOutputs() {
return outputs;
}
/**
* returns the set of furnaces that are connected to a pipe that allows the
* server to load chunks if parts of the pipe are located in unloaded chunks
*
* @return a set of chunk loaders
*/
public LinkedHashMap<SimpleLocation, ChunkLoader> getChunkLoaders() {
return chunkLoaders;
}
/**
* returns the set of glass-blocks the pipe consists of
*
* @return the set of pipe blocks
*/
public LinkedHashSet<SimpleLocation> getPipeBlocks() {
return pipeBlocks;
}
/**
* returns the pipe input object if there is one at the given location
*
* @param location a SimpleLocation
* @return a pipeinput
*/
public PipeInput getInput(SimpleLocation location) {
return inputs.get(location);
}
/**
* Get the type of this pipe
*
* @return The type of the blocks this pipe consists of
*/
public Material getType() {
return type;
}
/**
* Get the last tick this pipe transferred something
*
* @return The tick number the last transfer happened
*/
public int getLastTransfer() {
return lastTransfer;
}
/**
* Set the last tick this pipe transferred something
*
* @param lastTransfer The tick number the last transfer happened
*/
public void setLastTransfer(int lastTransfer) {
this.lastTransfer = lastTransfer;
}
/**
* Get the amount of transfers in this transfer cycle
*
* @return the amount of transfers
*/
public int getTransfers() {
return transfers;
}
/**
* Set the amount of transfers in this transfer cycle
*
* @param transfers the amount of transfers
*/
public void setTransfers(int transfers) {
this.transfers = transfers;
}
/**
* displays particles around a pipe
* @param players The player to show the pipe to, none to show it to everyone
*/
public void highlight(Player... players) {
LinkedHashSet<SimpleLocation> locations = new LinkedHashSet<>(pipeBlocks);
locations.addAll(inputs.keySet());
locations.addAll(outputs.keySet());
outputs.values().stream().map(PipeOutput::getTargetLocation).forEach(locations::add);
World world = null;
for (SimpleLocation simpleLocation : locations) {
if (world == null) {
world = Bukkit.getWorld(simpleLocation.getWorldName());
}
if (players.length == 0) {
for (int[] offset : PipesUtil.OFFSETS) {
world.spawnParticle(Particle.FLAME,
simpleLocation.getX() + offset[0],
simpleLocation.getY() + offset[1],
simpleLocation.getZ() + offset[2],
1, 0, 0, 0, 0);
}
} else {
for (Player p : players) {
for (int[] offset : PipesUtil.OFFSETS) {
p.spawnParticle(Particle.FLAME,
simpleLocation.getX() + offset[0],
simpleLocation.getY() + offset[1],
simpleLocation.getZ() + offset[2],
1, 0, 0, 0, 0);
}
}
}
}
}
/**
* returns a string with some info in it
*
* @return a string with some info in it
*/
public String getString() {
return PipesConfig.getText("info.pipe.pipeData",
String.valueOf(inputs.size()),
String.valueOf(outputs.size()),
String.valueOf(pipeBlocks.size()),
String.valueOf(chunkLoaders.size()));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pipe pipe = (Pipe) o;
return inputs.equals(pipe.inputs)
&& outputs.equals(pipe.outputs)
&& chunkLoaders.equals(pipe.chunkLoaders)
&& pipeBlocks.equals(pipe.pipeBlocks);
}
@Override
public int hashCode() {
int result = inputs.hashCode();
result = 31 * result + outputs.hashCode();
result = 31 * result + chunkLoaders.hashCode();
result = 31 * result + pipeBlocks.hashCode();
result = 31 * result + type.hashCode();
return result;
}
public void checkLoaded(SimpleLocation startLocation) throws ChunkNotLoadedException {
World world = Bukkit.getWorld(startLocation.getWorldName());
if (world == null) {
return;
}
Multimap<Integer, Integer> chunks = MultimapBuilder.hashKeys().hashSetValues().build();
LinkedHashSet<SimpleLocation> locations = new LinkedHashSet<>(pipeBlocks);
locations.addAll(inputs.keySet());
locations.addAll(outputs.keySet());
outputs.values().stream().map(PipeOutput::getTargetLocation).forEach(locations::add);
for (SimpleLocation location : locations) {
chunks.put(location.getX() >> 4, location.getZ() >> 4);
}
for (Map.Entry<Integer, Integer> chunk : chunks.entries()) {
if (!world.isChunkLoaded(chunk.getKey(), chunk.getValue())) {
throw new ChunkNotLoadedException(startLocation);
}
}
}
}
|
package cxy.twitch;
public class Vector {
private double x;
private double y;
private double z;
private double r;
private double l;
public Vector(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
this.r = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
this.l = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2));
}
public double getSinTheta() {
return y / r;
}
public double getCosTheta() {
return x / r;
}
public double getTanTheta() {
return y / x;
}
public double getSinPhi() {
return r / l;
}
public double getCosPhi() {
return z / l;
}
public double getTanPhi() {
return r / z;
}
public static Vector minus(Vector a, Vector b) {
return new Vector(a.x - b.x, a.y - b.y, a.z - b.z);
}
public static Vector plus(Vector a, Vector b) {
return new Vector(a.x + b.x, a.y + b.y, a.z + b.z);
}
public static double getAngleCos(Vector a, Vector b) {
return (a.x * b.x + a.y * b.y + a.z * b.z)/(a.l * b.l);
}
public double getangle(){
return Math.toDegrees(Math.atan2(-x, y));
}
public String gravity_instruction(){
return new Degreetoinstruction(getangle()).getInstruction();
}
}
|
package pl.cwanix.opensun.commonserver.configuration;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import pl.cwanix.opensun.commonserver.packets.SUNPacketProcessor;
import pl.cwanix.opensun.commonserver.packets.SUNPacketProcessorExecutor;
import pl.cwanix.opensun.commonserver.packets.annotations.IncomingPacket;
import pl.cwanix.opensun.commonserver.packets.annotations.OutgoingPacket;
import pl.cwanix.opensun.commonserver.packets.Packet;
import pl.cwanix.opensun.commonserver.packets.PacketException;
import pl.cwanix.opensun.utils.datatypes.PacketHeader;
import pl.cwanix.opensun.utils.datatypes.SUNDataType;
import pl.cwanix.opensun.utils.functions.ThrowingFunction;
import java.lang.reflect.Constructor;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Slf4j
@Configuration
@RequiredArgsConstructor
public class PacketTypeLoader {
private static final Marker MARKER = MarkerFactory.getMarker("PACKET TYPE LOADER");
private final SUNPacketProcessorExecutor processorExecutor;
@Bean
@SuppressWarnings("unchecked")
public Map<PacketHeader, ThrowingFunction<byte[], Packet, Exception>> clientPacketDefinitions() throws ClassNotFoundException {
ClassPathScanningCandidateComponentProvider classPathScanner = new ClassPathScanningCandidateComponentProvider(false);
classPathScanner.addIncludeFilter(new AnnotationTypeFilter(IncomingPacket.class));
Map<PacketHeader, List<Class<? extends Packet>>> classes = new HashMap<>();
Set<BeanDefinition> packetDefinitions = classPathScanner.findCandidateComponents("pl.cwanix.opensun");
for (BeanDefinition packetDefinition : packetDefinitions) {
Class<? extends Packet> packetClass = (Class<? extends Packet>) Class.forName(packetDefinition.getBeanClassName());
PacketHeader header = new PacketHeader(
packetClass.getAnnotation(IncomingPacket.class).category(),
packetClass.getAnnotation(IncomingPacket.class).operation()
);
checkIncomingPacketContract(packetClass);
classes.merge(header, Collections.singletonList(packetClass), (l1, l2) ->
Stream.of(l1, l2)
.flatMap(Collection::stream)
.collect(Collectors.toList())
);
}
checkPacketDuplicates(classes);
classes.forEach((key, value) -> log.debug(MARKER, "Loaded incoming packet type: {}", value.get(0).getSimpleName()));
return classes.entrySet()
.stream()
.map(this::mapClassEntryToConstructorFunctionEntry)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
@Bean
@SuppressWarnings("unchecked")
public void serverPacketDefinitions() throws ClassNotFoundException {
ClassPathScanningCandidateComponentProvider classPathScanner = new ClassPathScanningCandidateComponentProvider(false);
classPathScanner.addIncludeFilter(new AnnotationTypeFilter(OutgoingPacket.class));
Map<PacketHeader, List<Class<? extends Packet>>> classes = new HashMap<>();
Set<BeanDefinition> packetDefinitions = classPathScanner.findCandidateComponents("pl.cwanix.opensun");
for (BeanDefinition packetDefinition : packetDefinitions) {
Class<? extends Packet> packetClass = (Class<? extends Packet>) Class.forName(packetDefinition.getBeanClassName());
PacketHeader header = new PacketHeader(
packetClass.getAnnotation(OutgoingPacket.class).category(),
packetClass.getAnnotation(OutgoingPacket.class).operation()
);
checkOutgoingPacketContract(packetClass);
classes.merge(header, Collections.singletonList(packetClass), (l1, l2) ->
Stream.of(l1, l2)
.flatMap(Collection::stream)
.collect(Collectors.toList())
);
}
checkPacketDuplicates(classes);
classes.forEach((key, value) -> log.debug(MARKER, "Loaded outgoing packet type: {}", value.get(0).getSimpleName()));
}
private Map.Entry<PacketHeader, ThrowingFunction<byte[], Packet, Exception>> mapClassEntryToConstructorFunctionEntry(
final Map.Entry<PacketHeader, List<Class<? extends Packet>>> entry
) {
Constructor<? extends Packet> packetConstructor = getIncomingPacketConstructor(entry.getValue().get(0));
ThrowingFunction<byte[], Packet, Exception> packetConstructorFunction = packetConstructor::newInstance;
return new AbstractMap.SimpleEntry<>(entry.getKey(), packetConstructorFunction);
}
private Constructor<? extends Packet> getIncomingPacketConstructor(final Class<? extends Packet> packetClass) {
try {
return packetClass.getConstructor(byte[].class);
} catch (NoSuchMethodException e) {
throw new PacketException("IncomingPacket should implement constructor with one byte[] argument", e);
}
}
private void checkIncomingPacketContract(final Class<? extends Packet> packetClass) {
SUNPacketProcessor processor = processorExecutor.getProcessor(packetClass);
if (Objects.isNull(processor)) {
throw new PacketException("No matching processor for the packet type: " + packetClass.getSimpleName());
}
}
private void checkOutgoingPacketContract(final Class<? extends Packet> packetClass) {
Class implementingClass;
try {
implementingClass = packetClass.getMethod("getOrderedFields").getDeclaringClass();
} catch (NoSuchMethodException e) {
throw new PacketException("Wrong OutgoingPacket definition", e);
}
if (implementingClass.equals(SUNDataType.class)) {
throw new PacketException("OutgoingPacket (" + packetClass.getSimpleName() + ") should implement own getOrderedFields() method");
}
}
private void checkPacketDuplicates(final Map<PacketHeader, List<Class<? extends Packet>>> classes) {
boolean dup = false;
for (Map.Entry<PacketHeader, List<Class<? extends Packet>>> entry : classes.entrySet()) {
if (entry.getValue().size() > 1) {
dup = true;
log.error(MARKER, "Duplicate packet definitions: {}", entry.getValue().stream().map(Class::getSimpleName).collect(Collectors.joining(", ")));
}
}
if (dup) {
throw new PacketException("Duplicate packet definitions");
}
}
}
|
package cn.edu.ruc.aqi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class Crawler {
private String URL;
public String getURL() {
return URL;
}
public void setURL(String URL) {
this.URL = URL;
}
public CityData getDatafromPM2D5() {
CityData data = null;
HttpClient httpclient = null;
HttpGet httpget = null;
HttpResponse response = null;
InputStream instream = null;
try {
httpclient = new DefaultHttpClient();
// Prepare a request object
httpget = new HttpGet(URL);
// Execute the request
response = httpclient.execute(httpget);
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
data = new CityData();
instream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(instream, "utf-8"));
// do something useful with the response
String line = "";
int lineNum = 0;
while ((line = reader.readLine()) != null) {
lineNum++;
if (lineNum == 49) {
data.setCityName(line.substring(
line.lastIndexOf("=") + 3,
line.lastIndexOf("=") + 5));
//System.out.println(data.getCityName());
} else if (lineNum == 50) {
data.setAQI(Integer.parseInt(line.substring(
line.lastIndexOf("=") + 3,
line.lastIndexOf("\""))));
//System.out.println(data.getAQI());
} else if (lineNum == 85) {
data.getStationDataList().clear();
while (!(line = reader.readLine()).equals("</table>")) {
StationData stationData = new StationData();
line = reader.readLine();
stationData.setStationName(line.substring(line.indexOf(">", 5) + 1,
line.lastIndexOf("</a>")));// 观测站名称
line = reader.readLine();
line = line.substring(4, line.lastIndexOf("<"));
//System.out.println(line);
if (line.equals("—")) {
stationData.setAQI(0);
} else {
stationData.setAQI(Integer.parseInt(line));//AQI
}
reader.readLine();//去掉描述空气质量等级的文字
line = reader.readLine();
line = line.substring(4, line.lastIndexOf("μ"));
if (line.equals("—")) {
stationData.setPm25h(0);
} else {
stationData.setPm25h(Double.parseDouble(line));//PM2.5H
}
line = reader.readLine();
line = line.substring(4, line.lastIndexOf("μ"));
//System.out.println(line);
if (line.equals("—")) {
stationData.setPm25d(0);
} else {
stationData.setPm25d(Double.parseDouble(line));//PM2.5D
}
reader.readLine();
reader.readLine();
data.addStationData(stationData);
}
data.updatePM25();
break;
}
}
}
} catch (IOException ex) {
// In case of an IOException the connection will be released
// back to the connection manager automatically
} catch (RuntimeException ex) {
// In case of an unexpected exception you may want to abort
// the HTTP request in order to shut down the underlying
// connection and release it back to the connection manager.
httpget.abort();
} finally {
// Closing the input stream will trigger connection release
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
return data;
}
public CityData getWeather(CityData data, String cityNo) {
HttpClient httpclient = null;
HttpGet httpget = null;
HttpResponse response = null;
InputStream instream = null;
try {
httpclient = new DefaultHttpClient();
// Prepare a request object
httpget = new HttpGet("http://www.weather.com.cn/data/cityinfo/" + cityNo + ".html");
// Execute the request
response = httpclient.execute(httpget);
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
instream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(instream, "utf-8"));
// do something useful with the response
String line = "";
if ((line = reader.readLine()) != null) {
int begin = line.indexOf("temp1")+8;
int end = line.indexOf("℃");
data.setMaxTemp(Integer.parseInt(line.substring(begin, end)));
begin = line.indexOf("temp2")+8;
end = line.indexOf("℃", end+1);
data.setMinTemp(Integer.parseInt(line.substring(begin, end)));
begin = line.indexOf("weather", end)+10;
end = line.indexOf(",", begin)-1;
data.setWeather(line.substring(begin, end));
}
}
} catch (IOException ex) {
// In case of an IOException the connection will be released
// back to the connection manager automatically
} catch (RuntimeException ex) {
// In case of an unexpected exception you may want to abort
// the HTTP request in order to shut down the underlying
// connection and release it back to the connection manager.
httpget.abort();
} finally {
// Closing the input stream will trigger connection release
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
return data;
}
public static void main(String[] args) throws IOException {
Crawler crawler = new Crawler();
crawler.setURL("http://www.pm2d5.com/city/beijing.html");
crawler.getWeather(crawler.getDatafromPM2D5(), "101010100");
}
}
|
package com.tencent.mm.plugin.subapp.jdbiz;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.tencent.mm.ui.MMBaseActivity;
import com.tencent.mm.ui.base.x;
import com.tencent.mm.ui.widget.a.c;
import com.tencent.mm.ui.widget.a.c.a;
public class JDRemindDialog extends MMBaseActivity {
private c evj = null;
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
requestWindowFeature(1);
Vl();
}
protected void onResume() {
super.onResume();
x.b(true, null);
}
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
if (this.evj != null) {
this.evj.dismiss();
this.evj = null;
}
Vl();
}
protected void onPause() {
super.onPause();
x.b(false, null);
}
private void Vl() {
if (getIntent() != null) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
a aVar = new a(this);
aVar.abt("");
aVar.abu(extras.getString("alertcontent"));
aVar.abx(extras.getString("alertconfirm")).a(new 1(this));
aVar.aby(extras.getString("alert_cancel")).b(new 2(this));
this.evj = aVar.anj();
this.evj.setCanceledOnTouchOutside(false);
this.evj.show();
}
}
}
public static void a(Context context, String str, String str2, String str3, String str4, String str5) {
Intent intent = new Intent(context, JDRemindDialog.class);
intent.putExtra("alertcontent", str);
intent.putExtra("alertconfirm", str2);
intent.putExtra("alert_cancel", str3);
intent.putExtra("alertjumpurl", str4);
intent.putExtra("alert_activityid", str5);
intent.addFlags(805306368);
context.startActivity(intent);
}
}
|
package com.nic.form.servlet.save;
import com.nic.utility.MacAdr;
import com.nic.validation.DataConnect;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.xsshtmlfilter.HTMLFilter;
public class AllocatedDeviceUpdate extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String csrf = new HTMLFilter().filter((String) session.getAttribute("csrf_secureToken"));
String secureToken = new HTMLFilter().filter(request.getParameter("secureToken"));
String macAdr = "";
String name = new HTMLFilter().filter(request.getParameter("name"));
String ministryCode = new HTMLFilter().filter(request.getParameter("ministryCode"));
String locationCode = new HTMLFilter().filter(request.getParameter("locationCode"));
String departmentCode = new HTMLFilter().filter(request.getParameter("departmentCode"));
String floorCode = new HTMLFilter().filter(request.getParameter("floorCode"));
String sectionCode = new HTMLFilter().filter(request.getParameter("sectionCode"));
String designationCode = new HTMLFilter().filter(request.getParameter("designationCode"));
String empCode = new HTMLFilter().filter(request.getParameter("empCode"));
String contactNo = new HTMLFilter().filter(request.getParameter("contactNo"));
String InterComm = new HTMLFilter().filter(request.getParameter("InterComm"));
String email = new HTMLFilter().filter(request.getParameter("email"));
String employeeTypeCode = new HTMLFilter().filter(request.getParameter("employeeTypeCode"));
String userIpAddress = new HTMLFilter().filter(request.getParameter("ipAddress"));
String macAddress = new HTMLFilter().filter(request.getParameter("macAddress"));
String deviceTypeCode = new HTMLFilter().filter(request.getParameter("deviceTypeCode"));
String assessLevelCode = new HTMLFilter().filter(request.getParameter("assessLevelCode"));
String activationDate = new HTMLFilter().filter(request.getParameter("activationDate"));
String remarks = new HTMLFilter().filter(request.getParameter("remarks"));
String deactivationDate = new HTMLFilter().filter(request.getParameter("deactivationDate"));
String ramCode = new HTMLFilter().filter(request.getParameter("ramCode"));
String antiVirusCode = new HTMLFilter().filter(request.getParameter("antiVirusCode"));
String osCode = new HTMLFilter().filter(request.getParameter("osCode"));
Connection connect = DataConnect.getConnection();
try {
String userID = new HTMLFilter().filter((String) request.getSession(false).getAttribute("Username"));
String ipAddress = request.getHeader("X-FORWARDED-FOR");
if (ipAddress == null) {
ipAddress = request.getRemoteAddr();
}
try {
MacAdr ma = new MacAdr();
macAdr = (ma.getMac(ipAddress));
} catch (Exception e) {
System.out.println("ERRRR -- " + e);
}
StringBuilder ss1 = new StringBuilder(deviceTypeCode);
while (ss1.length() < 2) {
ss1.insert(0, '0');
}
deviceTypeCode = ss1.toString();
if (!"01".equals(deviceTypeCode)) {
ramCode = "";
antiVirusCode = "";
osCode = "";
}
String queryrenewal = "UPDATE IP_ADDRESS SET "
+ "USER_NAME = ?, "
+ "USER_DEPARTMENT=?, "
+ "USER_SECTION=?, "
+ "USER_DESIGNATION=?, "
+ "USER_MAC_ADDRESS=?, "
+ "USER_EMPLOYMENT_TYPE=?, "
+ "FLOOR=?, "
+ "LOCATION=?, "
+ "DEVICE_TYPE=?, "
+ "MAC_ADDRESS=?, "
+ "ENTERED_BY=?, "
+ "ENTERED_REMARKS=?, "
+ "ENTERED_ON=?, "
+ "ACCESS_LEVEL=?, "
+ "CONTACT_NUMBER=?, "
+ "INTERCOM=?, "
+ "EMAIL_ID=?, "
+ "USER_MINISTRY=?, "
+ "EMPLOYEE_CODE=?, "
+ "ACTIVATION_DATE=TO_TIMESTAMP(?,'dd/MM/yyyy'), "
+ "DEACTIVATION_DATE=TO_TIMESTAMP(?,'dd/MM/yyyy'), "
+ "MACHINE_OS=?, "
+ "MACHINE_RAM=?, "
+ "MACHINE_ANTIVIRUS=?, "
+ "FLAG = 'U', "
+ "IP_ADDRESS = ?"
+ " WHERE USER_IP_ADDRESS = ? AND LOCATION = ? AND RECORD_STATUS='A'";
PreparedStatement pstmt = connect.prepareStatement(queryrenewal);
pstmt.setString(1, name);
pstmt.setString(2, departmentCode);
pstmt.setString(3, sectionCode);
pstmt.setString(4, designationCode);
pstmt.setString(5, macAddress);
pstmt.setString(6, employeeTypeCode);
pstmt.setString(7, floorCode);
pstmt.setString(8, locationCode);
pstmt.setString(9, deviceTypeCode);
pstmt.setString(10, macAdr);
pstmt.setString(11, userID);
pstmt.setString(12, remarks);
pstmt.setTimestamp(13, new Timestamp(System.currentTimeMillis()));
pstmt.setString(14, assessLevelCode);
pstmt.setString(15, contactNo);
pstmt.setString(16, InterComm);
pstmt.setString(17, email);
pstmt.setString(18, ministryCode);
pstmt.setString(19, empCode);
pstmt.setString(20, activationDate);
pstmt.setString(21, deactivationDate);
pstmt.setString(22, osCode);
pstmt.setString(23, ramCode);
pstmt.setString(24, antiVirusCode);
pstmt.setString(25, ipAddress);
pstmt.setString(26, userIpAddress);
pstmt.setString(27, locationCode);
pstmt.executeUpdate();
// request.setAttribute("message", "IP Address Updated Successfully!");
// request.getRequestDispatcher("./successful.jsp").forward(request, response);
session.setAttribute("page", "./ippoolAssignUpdateModule.jsp");
session.setAttribute("message", "<div id=\"message\" width=\"50%\"><div class=\"alert alert-success\">Record Updated Successfully!<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button></div> </div>");
response.sendRedirect("./ippoolAssignUpdateModule.jsp");
} catch (SQLException _EX) {
// System.out.println("SQLException :: " + _EX);
// request.setAttribute("message", "IP Address Not Updated!");
// request.setAttribute("page", "./ippoolAssignUpdateModule.jsp");
session.setAttribute("page", "./ippoolAssignUpdateModule.jsp");
session.setAttribute("message", "<div id=\"message\" width=\"50%\"><div class=\"alert alert-success\">Record Not Updated!<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button></div> </div>");
response.sendRedirect("./ippoolAssignUpdateModule.jsp");
// request.getRequestDispatcher("./ipPoolAssignUpdate.jsp").forward(request, response);
} catch (IOException _EX) {
session.setAttribute("page", "./ippoolAssignUpdateModule.jsp");
session.setAttribute("message", "<div id=\"message\" width=\"50%\"><div class=\"alert alert-success\">Record Not Updated!<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button></div> </div>");
response.sendRedirect("./ippoolAssignUpdateModule.jsp");
// System.out.println("IOException ::" + _EX);
// request.setAttribute("error", "");
// RequestDispatcher rd = getServletContext().getRequestDispatcher("/view/ipPoolAssignUpdate.jsp");
// rd.forward(request, response);
} finally {
if (connect != null) {
try {
connect.close();
} catch (SQLException ex) {
Logger.getLogger(AllocatedDeviceUpdate.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package com.myowndev.main;
import javax.swing.JFrame;
public class Main extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String args[]) {
new Main();
}
public Main() {
add(new Panel());
setSize(560, 700);
setResizable(false);
setLocationRelativeTo(null);
setTitle("Программа калибровки данных СП-9 по измерениям Аэронет");
setDefaultCloseOperation(3);
setVisible(true);
}
}
|
package com.tencent.mm.booter;
import com.tencent.mm.model.au;
import com.tencent.mm.model.br;
import com.tencent.mm.protocal.c.aqa;
import com.tencent.mm.sdk.platformtools.bi;
import java.util.LinkedList;
public final class i {
public static void run() {
int i;
aqa aqa;
LinkedList linkedList = new LinkedList();
int a = bi.a((Integer) au.HS().get(19), 0);
for (i = 0; i < a; i++) {
aqa = new aqa();
aqa.mEb = 31;
aqa.mEl = "0";
linkedList.add(aqa);
}
a = bi.a((Integer) au.HS().get(20), 0);
for (i = 0; i < a; i++) {
aqa = new aqa();
aqa.mEb = 31;
aqa.mEl = "1";
linkedList.add(aqa);
}
if (linkedList.size() > 0) {
br.b(linkedList);
au.HS().set(19, Integer.valueOf(0));
au.HS().set(20, Integer.valueOf(0));
}
}
}
|
import java.util.Scanner;
public class L2_I5 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Podaj liczbę naturalną");
int n = s.nextInt();
int i = 2;
while(i<n) {
if(n%i==0) {
System.out.println("NIE Liczba pierwsza");
System.exit(0);
} //if
else i++;
} //while
System.out.println("Liczba pierwsza");
s.close();
} //main
} //L2_I5
|
public class p36 {
}
|
package net.minecraft.item;
import com.google.common.base.Predicate;
import java.util.List;
import javax.annotation.Nullable;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityAreaEffectCloud;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.init.PotionTypes;
import net.minecraft.init.SoundEvents;
import net.minecraft.potion.PotionUtils;
import net.minecraft.stats.StatList;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.World;
public class ItemGlassBottle extends Item {
public ItemGlassBottle() {
setCreativeTab(CreativeTabs.BREWING);
}
public ActionResult<ItemStack> onItemRightClick(World itemStackIn, EntityPlayer worldIn, EnumHand playerIn) {
List<EntityAreaEffectCloud> list = itemStackIn.getEntitiesWithinAABB(EntityAreaEffectCloud.class, worldIn.getEntityBoundingBox().expandXyz(2.0D), new Predicate<EntityAreaEffectCloud>() {
public boolean apply(@Nullable EntityAreaEffectCloud p_apply_1_) {
return (p_apply_1_ != null && p_apply_1_.isEntityAlive() && p_apply_1_.getOwner() instanceof net.minecraft.entity.boss.EntityDragon);
}
});
ItemStack itemstack = worldIn.getHeldItem(playerIn);
if (!list.isEmpty()) {
EntityAreaEffectCloud entityareaeffectcloud = list.get(0);
entityareaeffectcloud.setRadius(entityareaeffectcloud.getRadius() - 0.5F);
itemStackIn.playSound(null, worldIn.posX, worldIn.posY, worldIn.posZ, SoundEvents.ITEM_BOTTLE_FILL_DRAGONBREATH, SoundCategory.NEUTRAL, 1.0F, 1.0F);
return new ActionResult(EnumActionResult.SUCCESS, turnBottleIntoItem(itemstack, worldIn, new ItemStack(Items.DRAGON_BREATH)));
}
RayTraceResult raytraceresult = rayTrace(itemStackIn, worldIn, true);
if (raytraceresult == null)
return new ActionResult(EnumActionResult.PASS, itemstack);
if (raytraceresult.typeOfHit == RayTraceResult.Type.BLOCK) {
BlockPos blockpos = raytraceresult.getBlockPos();
if (!itemStackIn.isBlockModifiable(worldIn, blockpos) || !worldIn.canPlayerEdit(blockpos.offset(raytraceresult.sideHit), raytraceresult.sideHit, itemstack))
return new ActionResult(EnumActionResult.PASS, itemstack);
if (itemStackIn.getBlockState(blockpos).getMaterial() == Material.WATER) {
itemStackIn.playSound(worldIn, worldIn.posX, worldIn.posY, worldIn.posZ, SoundEvents.ITEM_BOTTLE_FILL, SoundCategory.NEUTRAL, 1.0F, 1.0F);
return new ActionResult(EnumActionResult.SUCCESS, turnBottleIntoItem(itemstack, worldIn, PotionUtils.addPotionToItemStack(new ItemStack(Items.POTIONITEM), PotionTypes.WATER)));
}
}
return new ActionResult(EnumActionResult.PASS, itemstack);
}
protected ItemStack turnBottleIntoItem(ItemStack p_185061_1_, EntityPlayer player, ItemStack stack) {
p_185061_1_.func_190918_g(1);
player.addStat(StatList.getObjectUseStats(this));
if (p_185061_1_.func_190926_b())
return stack;
if (!player.inventory.addItemStackToInventory(stack))
player.dropItem(stack, false);
return p_185061_1_;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\item\ItemGlassBottle.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package akademia.ox.game;
import java.util.function.IntFunction;
public class VictoryChecker {
private Board board;
private int toWin;
public VictoryChecker() {
}
public GameResult checkVictory(int lastMove, GameCharacter character, Board board, int toWin) {
setParameters(board, toWin);
int inRow = countInRow(lastMove, character);
int inCol = countInCol(lastMove, character);
int inDownDiag = countInDownDiag(lastMove, character);
int inUpDiag = countInUpDiag(lastMove, character);
if (inRow >= this.toWin || inCol >= this.toWin || inDownDiag >= this.toWin || inUpDiag >= this.toWin)
return GameResult.VICTORY;
if (board.coverage() == board.size()) {
return GameResult.DRAW;
}
return GameResult.IN_PROGRESS;
}
private int countInRow(int lastMove, GameCharacter character) {
int leftLimit = ((lastMove - 1) / board.columns()) * board.columns() + 1;
int rightLimit = leftLimit + board.columns() - 1;
IntFunction<Integer> nextRightIndexCounter = index -> index + 1;
IntFunction<Integer> nextLeftIndexCounter = index -> index - 1;
return countSmaller(lastMove, character, leftLimit, nextLeftIndexCounter) + countLarger(lastMove, character, rightLimit, nextRightIndexCounter) + 1;
}
private int countInCol(int lastMove, GameCharacter character) {
int leftLimit = 0;
int rightLimit = board.size();
IntFunction<Integer> nextRightIndexCounter = index -> index + board.columns();
IntFunction<Integer> nextLeftIndexCounter = index -> index - board.columns();
return countSmaller(lastMove, character, leftLimit, nextLeftIndexCounter) + countLarger(lastMove, character, rightLimit, nextRightIndexCounter) + 1;
}
private int countInUpDiag(int lastMove, GameCharacter character) {
int i = lastMove;
while (i % board.columns() != 1 && i < board.size() - board.columns()) {
i += (board.columns() - 1);
}
int leftLimit = i;
int j = lastMove;
while (j % board.columns() != 0 && j > board.columns()) {
j -= (board.columns() - 1);
}
int rightLimit = j;
IntFunction<Integer> nextRightIndexCounter = index -> index - board.columns() + 1;
IntFunction<Integer> nextLeftIndexCounter = index -> index + board.columns() - 1;
return countLarger(lastMove, character, leftLimit, nextLeftIndexCounter) + countSmaller(lastMove, character, rightLimit, nextRightIndexCounter) + 1;
}
private int countInDownDiag(int lastMove, GameCharacter character) {
int i = lastMove;
while (i % board.columns() != 0 && i < board.size() - board.columns()) {
i += (board.columns() + 1);
}
int rightLimit = i;
int j = lastMove;
while (j % board.columns() != 1 && j > board.columns()) {
j -= (board.columns() + 1);
}
int leftLimit = j;
IntFunction<Integer> nextRightIndexCounter = index -> index + board.columns() + 1;
IntFunction<Integer> nextLeftIndexCounter = index -> index - board.columns() - 1;
return countSmaller(lastMove, character, leftLimit, nextLeftIndexCounter) + countLarger(lastMove, character, rightLimit, nextRightIndexCounter) + 1;
}
private int countLarger(int lastMove, GameCharacter character, int limit, IntFunction<Integer> nextIndexCounter) {
int nextIndex = nextIndexCounter.apply(lastMove);
if (nextIndex > limit || !board.getCharacter(nextIndex).equals(character)) {
return 0;
}
return 1 + countLarger(nextIndex, character, limit, nextIndexCounter);
}
private int countSmaller(int lastMove, GameCharacter character, int limit, IntFunction<Integer> nextIndexCounter) {
int nextIndex = nextIndexCounter.apply(lastMove);
if (nextIndex < limit || !board.getCharacter(nextIndex).equals(character)) {
return 0;
}
return 1 + countSmaller(nextIndex, character, limit, nextIndexCounter);
}
private void setParameters(Board board, int toWin) {
this.board = board;
this.toWin = toWin;
}
}
|
/*
* 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 Gestion.utils;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.json.simple.JSONObject;
import org.orm.PersistentException;
import org.orm.PersistentSession;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author FKC-Standard
*/
public class DataUtils {
public static JSONObject getstat(String annee,String type) throws Exception{
JSONObject data = new JSONObject();
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
String requette = "select SUM(E."+type+") as venteT,"
+ "CONCAT(U.nom,' ',U.prenom) as users,"
+ "MONTH(E.date_de_vente) as mois "
+ "from Vente E,Utilisateur U "
+ "WHERE YEAR(E.date_de_vente) = :annee and E.utilisateuridUser = U.idUser "
+ "GROUP BY mois,users "
+ "ORDER BY mois asc";
Query q = session.createSQLQuery(requette);
q.setParameter("annee",annee);
q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List liste = q.list();
HashMap temp;
for (int i = 0; i < liste.size(); i++) {
temp = (HashMap) liste.get(i);
data.put(temp.get("mois")+"--"+temp.get("users"),temp.get("venteT"));
}
return data;
}
public static String getProduitDescription(String code){
String m = "";
try{
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
String requette = "SELECT CONCAT('Categorie ',G.nom,' et sous-categorie ',S.designation) as description "
+ "FROM Produit P, Grandecategorie G, Categories S, Produit_categories C "
+ "WHERE P.code='"+code+"' and P.idProduit=C.produitidProduit and C.categoriesidCategories=S.idCategories "
+ "and G.idGrandeCategorie=S.grandecategorie_idGrandeCategorie";
Query q = session.createSQLQuery(requette);
q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
HashMap temp = (HashMap) (q.list().get(0));
m = temp.get("description").toString();
}catch(Exception e){
e.printStackTrace();
}
return m;
}
private static boolean importDATA2(String requette) throws SQLException{
boolean flag = false;
Connection_TO_MYSQL con = new Connection_TO_MYSQL();
con.Statut();
Statement st = con.getConnection().createStatement();
st.executeUpdate(requette);
con.close_state();
return flag;
}
/**
*
* @param data
* @return success
* data = JSON[JSon[table,JSON[insert,update]]]
* @return
*/
public static boolean importDATA(JSONObject data,boolean all){
boolean flag = false;
if(!data.isEmpty()) {
try{
if(all){
String[] data1 = new String[12];
data1[9] = "client"; data1[6] = "grandecategorie";
data1[4] = "produit"; data1[2] = "produit_categories";
data1[8] = "fournisseur"; data1[7] = "charges";
data1[11] = "address"; data1[1] = "fournisseur_produit";
data1[5] = "categories"; data1[10] = "utilisateur";
data1[3] = "vente"; data1[0] = "produit_vente";
String req = "";
for (int i = 0; i < data1.length; i++) {
req = "DELETE FROM "+data1[i];
importDATA2(req);
}
}
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
Set cle = data.keySet();String table;SQLQuery q;String requette = "";
for (Iterator iterator = cle.iterator(); iterator.hasNext();) {
Object next = iterator.next();
table = ((JSONObject)data.get(next)).get("table").toString();
JSONObject temp = (JSONObject) ((JSONObject)data.get(next)).get("valeurs");
Set cle1 = temp.keySet();
for (Iterator iterator1 = cle1.iterator(); iterator1.hasNext();) {
Object next1 = iterator1.next();
requette = "INSERT INTO "+table+""+((JSONObject)temp.get(next1)).get("titre")+" "
+ "VALUES "+((JSONObject)temp.get(next1)).get("insert")+" "
+ "ON DUPLICATE KEY UPDATE "+((JSONObject)temp.get(next1)).get("update")+" ";
System.out.println(requette);
importDATA2(requette);
}
}
flag = true;
}catch(Exception e){
flag = false;
e.printStackTrace();
}
}
return flag;
}
public static boolean exportDATA(){
boolean flag = false;
try{
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
String[] data = new String[10];
data[0] = "client"; data[5] = "grandecategorie";
data[1] = "produit"; data[6] = "produit_categories";
data[2] = "fournisseur"; data[7] = "charges";
data[3] = "address"; data[8] = "fournisseur_produit";
data[4] = "categories"; data[9] = "utilisateur";
String requette = "";
File f = new File("Documents/Datas/");
if(!f.exists()) f.mkdir();
File[] fi = f.listFiles();
for (int i = 0; i < fi.length; i++) {
File fi1 = fi[i];
fi1.delete();
}
String m = f.getAbsolutePath();
String as = new String ("\\");
String das = new String("\\\\");
m = m.replace(as, das);
for (int i = 0; i < data.length; i++) {
requette = "SELECT * INTO OUTFILE '"+m+"\\\\"+data[i]+".txt' FIELDS TERMINATED BY '--FKC--' " // ICIIIIIIIIIIIIIIIIIIIIIIIIIII
+ "OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '--FIN--' \n"
+ "FROM "+data[i];
System.out.println(requette);
Query q = session.createSQLQuery(requette);
q.setReadOnly(true);
q.scroll();
}
flag = true;
}catch(Exception e){
e.printStackTrace();
flag = false;
}
return flag;
}
public static boolean exportAllDATA(){
boolean flag = false;
try{
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
String[] data = new String[12];
data[0] = "client"; data[5] = "grandecategorie";
data[1] = "produit"; data[6] = "produit_categories";
data[2] = "fournisseur"; data[7] = "charges";
data[3] = "address"; data[8] = "fournisseur_produit";
data[4] = "categories"; data[9] = "utilisateur";
data[10] = "vente"; data[11] = "produit_vente";
String requette = "";
File f = new File("Documents/DatasAll/");
if(!f.exists()) f.mkdir();
File[] fi = f.listFiles();
for (int i = 0; i < fi.length; i++) {
File fi1 = fi[i];
fi1.delete();
}
String m = f.getAbsolutePath();
String as = new String ("\\");
String das = new String("\\\\");
m = m.replace(as, das);
for (int i = 0; i < data.length; i++) {
requette = "SELECT * INTO OUTFILE '"+m+"\\\\"+data[i]+".txt' FIELDS TERMINATED BY '--FKC--' " //ICIIIIIIIIIIIIIIIIIIIII
+ "OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '--FIN--' \n"
+ "FROM "+data[i];
System.out.println(requette);
Query q = session.createSQLQuery(requette);
q.setReadOnly(true);
q.scroll();
}
flag = true;
}catch(Exception e){
e.printStackTrace();
flag = false;
}
return flag;
}
public static JSONObject getDETTES(String condition) throws Exception{
JSONObject data = new JSONObject();
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
String requette1 = "select concat(C.nom,' ',C.prenom) as client,"
+ "CONCAT(U.nom,' ',U.prenom) as user,"
+ "V.idVente as idvente,"
+ "V.date_de_vente as date_de_vente,"
+ "V.description as description,"
+ "V.montant_de_dette as dette "
+ "from Vente V,Utilisateur U ,Client C "
+ "WHERE V.etat=1 and V.type_enregistrement = 'pret' and V.utilisateuridUser = U.idUser and V.clientidClient = C.idClient and "+condition;
String requette2 = "select concat(C.nom,' ',C.prenom) as client,"
+ "SUM(V.montant_de_dette) as dettes,"
+ "V.clientidClient as idclient "
+ "from Vente V,Client C "
+ "WHERE V.etat=1 and V.type_enregistrement = 'pret' and V.clientidClient = C.idClient "
+ "GROUP BY idclient";
Query q1 = session.createSQLQuery(requette1);
q1.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List liste1 = q1.list();
Query q2 = session.createSQLQuery(requette2);
q2.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List liste2 = q2.list();
for (int i = 0; i < liste1.size(); i++) {
HashMap temp1 = (HashMap) liste1.get(i);
for (int j = 0; j < liste2.size(); j++) {
HashMap temp2 = (HashMap) liste2.get(j);
if(temp1.get("client").equals(temp2.get("client"))){
temp1.put("dettes",temp2.get("dettes"));
}
}
data.put(temp1.get("idvente"),temp1);
}
return data;
}
public static String getCode() {
String code = "";
try {
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
String requette = "select P.code as lastCode from Produit P where P.idProduit = (select Max(E.idProduit) "
+ "from Produit E )";
Query q = session.createSQLQuery(requette);
q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List liste = q.list();
if(liste.isEmpty()) code = "AA001";
else{
char[] get = ((HashMap) liste.get(0)).get("lastCode").toString().toCharArray();
if(get[2]==get[3] && get[3]==get[4] && get[4]=='9'){
if(get[1]!='Z') get[1] += 1;
else {
if(get[0]=='Z') {
get[1] = get[0] = 'A';
}
else {
get[0] += 1;
get[1] = 'A';
}
}
get[2] = get[3] = '0'; get[4] = '1';
}else{
int n = (Integer.parseInt(""+get[2]+""+get[3]+""+get[4])+1);
switch((""+n).length()){
case 1:
get[2] = get[3] = '0';
get[4] = (""+n).charAt(0);
break;
case 2:
get[2] = '0';
get[3] = (""+n).charAt(0);
get[4] = (""+n).charAt(1);
break;
case 3:
get[2] = (""+n).charAt(0);
get[3] = (""+n).charAt(1);
get[4] = (""+n).charAt(2);
break;
}
}
code = get[0]+""+get[1]+""+get[2]+""+get[3]+""+get[4];
}
} catch (PersistentException ex) {
Logger.getLogger(DataUtils.class.getName()).log(Level.SEVERE, null, ex);
}
return code;
}
/**
*
* @param type
* @param date
* 0 client
* 1 fornisseur
* 2 users
* 3 client dette
* 4 resultat net/brut
* 5 etat stock
* 6 vente du mois/annee :date
* 7 ventes
* @return
* @throws Exception
*/
public static JSONObject getEltToPrint(int type,String date){
JSONObject data = new JSONObject();
String requette = "";
Query q; List liste; HashMap temp; int total;
try{
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
switch(type){
case 0:
requette = "select C.numtel as tel,"
+ "CONCAT(U.nom,' ',U.prenom) as client,"
+ "C.email as email,"
+ "U.idClient as cle "
+ "from Client U,address C "
+ "WHERE C.idAddress=U.addressidAddress and CONCAT(U.nom,' ',U.prenom) <> '' "
+ "order by CONCAT(U.nom,' ',U.prenom) asc";
q = session.createSQLQuery(requette);
q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
liste = q.list();
for (int i = 0; i < liste.size(); i++) {
temp = (HashMap) liste.get(i);
String[] dat = new String[3];
dat[0] = temp.get("client").toString();
dat[1] = temp.get("tel").toString();
dat[2] = temp.get("email").toString();
data.put(temp.get("cle"),dat);
}
data.put(-1,"");
break;
case 1:
requette = "select C.numtel as tel,"
+ "U.nom as four,"
+ "C.email as email,"
+ "U.idFournisseur as cle "
+ "from Fournisseur U,address C "
+ "WHERE C.idAddress=U.addressidAddress "
+ "order by U.nom asc";
q = session.createSQLQuery(requette);
q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
liste = q.list();
for (int i = 0; i < liste.size(); i++) {
temp = (HashMap) liste.get(i);
String[] dat = new String[3];
dat[0] = temp.get("four").toString();
dat[1] = temp.get("tel").toString();
dat[2] = temp.get("email").toString();
data.put(temp.get("cle"),dat);
}
data.put(-1,"");
break;
case 2:
requette = "select C.numtel as tel,"
+ "CONCAT(U.nom,' ',U.prenom) as users,"
+ "C.email as email,"
+ "T.typeuser as type,"
+ "U.idUser as cle "
+ "from Utilisateur U,address C, Typeusers T "
+ "WHERE C.idAddress=U.addressidAddress and U.typeusersidTypeUsers=T.idTypeUsers and T.typeuser<>'ROOT' "
+ "order by CONCAT(U.nom,' ',U.prenom) asc";
q = session.createSQLQuery(requette);
q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
liste = q.list();
for (int i = 0; i < liste.size(); i++) {
temp = (HashMap) liste.get(i);
String[] dat = new String[4];
dat[0] = temp.get("users").toString();
dat[1] = temp.get("type").toString();
dat[2] = temp.get("tel").toString();
dat[3] = temp.get("email").toString();
data.put(temp.get("cle"),dat);
}
data.put(-1,"");
break;
case 3:
requette = "select C.numtel as tel,"
+ "CONCAT(U.nom,' ',U.prenom) as client,"
+ "C.email as email,"
+ "U.idClient as cle,"
+ "SUM(V.montant_de_dette) as dettes "
+ "from Client U,address C, Vente V "
+ "WHERE V.etat=1 and V.type_enregistrement = 'pret' and V.clientidClient = U.idClient and C.idAddress=U.addressidAddress "
+ "GROUP BY cle "
+ "order by CONCAT(U.nom,' ',U.prenom) asc";
q = session.createSQLQuery(requette);
q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
liste = q.list();
total = 0;
for (int i = 0; i < liste.size(); i++) {
temp = (HashMap) liste.get(i);
String[] dat = new String[4];
dat[0] = temp.get("client").toString();
dat[1] = temp.get("tel").toString();
dat[2] = temp.get("email").toString();
dat[3] = temp.get("dettes").toString();
total += Integer.parseInt(temp.get("dettes").toString());
data.put(temp.get("cle"),dat);
}
data.put(-1,"TOTAL DES DETTES = "+total);
break;
case 4:
requette = "select "
+ "CONCAT(P.code,' -- ',P.designation) as produit,"
+ "CONCAT(P.idProduit,'-',V.idVente) as cle,"
+ "C.nombre_article as qte,"
+ "P.prix_unitaire_de_vente as pv,"
+ "V.date_de_vente as dv,"
+ "V.prix_de_vente as pt,"
+ "P.prix_d_achat as pa,"
+ "V.benefices as be "
+ "from Produit P,Produit_vente C, Vente V "
+ "WHERE V.etat=1 and V.idVente = C.venteidVente and P.idProduit=C.produitidProduit and MONTH(V.date_de_vente) = "+date+" "
+ "order by CONCAT(P.code,' -- ',P.designation) asc";
q = session.createSQLQuery(requette);
q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
liste = q.list();
int total1 = 0;
for (int i = 0; i < liste.size(); i++) {
temp = (HashMap) liste.get(i);
String[] dat = new String[7];
dat[0] = temp.get("produit").toString();
dat[1] = temp.get("dv").toString();
dat[2] = temp.get("qte").toString();
dat[3] = temp.get("pa").toString();
dat[4] = temp.get("pv").toString();
dat[5] = ""+(Integer.parseInt(temp.get("pt").toString())/Integer.parseInt(temp.get("qte").toString()));
dat[6] = temp.get("pt").toString();
total1 += Integer.parseInt(temp.get("be").toString());
data.put(temp.get("cle"),dat);
}
JSONObject data1 = new JSONObject();
data1.put("beneficebrut","RESULTAT BRUT DE L'EXPLOITATION = "+total1);
String[] titre = {"Charge","Charge Mensuelle ","date d'enregistrement","Montant"};
data1.put("titrecharges",titre);
requette = "select C.designation as charge,"
+ "C.date as date,"
+ "C.montant as montant,"
+ "C.idCharges as cle,"
+ "C.type as mois "
+ "FROM Charges C "
+ "WHERE C.prisEnCompte=1 and MONTH(C.date) = "+date+" "
+ "order by C.date asc";
q = session.createSQLQuery(requette);
q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
liste = q.list();
total = 0;
for (int i = 0; i < liste.size(); i++) {
temp = (HashMap) liste.get(i);
String[] dat = new String[4];
dat[0] = temp.get("charge").toString();
dat[1] = temp.get("mois").toString();
dat[2] = temp.get("date").toString();
dat[3] = temp.get("montant").toString();
total += Integer.parseInt(temp.get("montant").toString());
data1.put(temp.get("cle"), dat);
}
data1.put("Tcharges","TOTAL DES CHARGES = "+total);
data1.put("beneficenet","RESULTAT NET DE L'EXPLOITATION = "+(total1-total));
data.put("charges",data1);
data.put(-1,"-1");
break;
case 5:
requette = "select P.code as code,"
+ "P.designation as nom,"
+ "P.quantite as qte,"
+ "G.nom as cat,"
+ "P.idProduit as cle "
+ "from Produit P,grandecategorie G,produit_categories C,categories S "
+ "where P.idProduit=C.produitidProduit and C.categoriesidCategories=S.idCategories and "
+ "S.GrandeCategorie_idGrandeCategorie = G.idGrandeCategorie "
+ "order by P.code asc";
q = session.createSQLQuery(requette);
q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
liste = q.list();
for (int i = 0; i < liste.size(); i++) {
temp = (HashMap) liste.get(i);
String[] dat = new String[4];
dat[0] = temp.get("code").toString();
dat[1] = temp.get("nom").toString();
dat[2] = temp.get("cat").toString();
dat[3] = temp.get("qte").toString();
data.put(temp.get("cle"),dat);
}
data.put(-1,"");
break;
case 6:
String[] r = date.split("--");
if(r[0].equals("mois")) date = "MONTH(V.date_de_vente) = "+r[1];
else date = "YEAR(V.date_de_vente) = "+r[1];
requette = "select "
+ "CONCAT(C.nom,' ',S.designation) as cle,"
+ "SUM(P.nombre_article) as nbre,"
+ "S.designation as scat,"
+ "C.nom as cat "
+ "from Categories S,Produit_vente P, Grandecategorie C, Vente V, Produit A, Produit_categories B "
+ "WHERE V.etat=1 and V.idVente=P.venteidVente and "
+ "A.idProduit=P.produitidProduit and S.idCategories=B.categoriesidCategories and "
+ "B.produitidProduit=A.idProduit and C.idGrandeCategorie=S.GrandeCategorie_idGrandeCategorie "
+ "and "+date+" "
+ "GROUP BY (S.idCategories) "
+ "order by C.nom asc";
q = session.createSQLQuery(requette);
q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
liste = q.list();
System.out.println(liste);
List<HashMap> liste1 = new ArrayList<HashMap>();
HashMap un = new HashMap();
un.put("cat","");
un.put("nbre","");
un.put("scat","");
liste1.add(un);
boolean flag = false;
for (int i = 0; i < liste.size(); i++) {
HashMap get = (HashMap)liste.get(i);
flag = false;
for (int j = 0; j < liste1.size(); j++) {
HashMap get1 = liste1.get(j);
if(get1.containsKey("cat") && get1.get("cat").equals(get.get("cat"))){
get1.put("scat",get1.get("scat")+"\n"+get.get("scat"));
get1.put("nbre",get1.get("nbre")+"\n"+get.get("nbre"));
flag = true;
}
}
if(!flag){
liste1.add(get);
}
}
for (int i = 0; i < liste1.size(); i++) {
temp = (HashMap) liste1.get(i);
String[] dat = new String[3];
dat[0] = temp.get("cat").toString();
dat[1] = temp.get("scat").toString();
dat[2] = temp.get("nbre").toString();
data.put(i,dat);
}
data.put(-1,"");
break;
case 7:
requette = "select "
+ "CONCAT(C.nom,' ',C.prenom) as client,"
+ "CONCAT(U.nom,' ',U.prenom) as vendeur,"
+ "V.montant_de_dette as dette,"
+ "V.prix_de_vente as total,"
+ "V.date_de_vente as date,"
+ "V.idVente as numFac,"
+ "V.description as description "
+ "from Vente V, Client C, Utilisateur U "
+ "WHERE C.idClient=V.clientidClient and V.utilisateuridUser=U.idUser "
+ "order by V.date_de_vente asc";
q = session.createSQLQuery(requette);
q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
liste = q.list();
for (int i = 0; i < liste.size(); i++) {
temp = (HashMap) liste.get(i);
String[] dat = new String[1];
String temp1 = "";
temp1 += "NUMERO DE LA FACTURE ---------> "+Gestion.utils.Utils.mettreSous6Positions(temp.get("numFac").toString())+"\n"
+ "Vendeur ----------------------> "+temp.get("vendeur").toString()+"\n"
+ "Client -------------------------> "+temp.get("client").toString()+"\n"
+ "Montant de Vente ---------> "+temp.get("total").toString()+"\n"
+ "Date de vente --------------> "+temp.get("date").toString()+"\n"
+ "Dette --------------------------> "+temp.get("dette").toString()+"\n"
+ "************* HISTORIQUES *****************\n"
+ temp.get("description").toString().replace("\n","\n--> ");
dat[0] = temp1;
data.put(i,dat);
}
data.put(-1,"");
break;
}
}catch(Exception e){
e.printStackTrace();
}
return data;
}
static ArrayList<String[]> getChamps() {
ArrayList<String[]> data = new ArrayList<>();
String[] data1 = new String[12];
data1[1] = "client"; data1[3] = "grandecategorie";
data1[7] = "produit"; data1[8] = "produit_categories";
data1[2] = "fournisseur"; data1[4] = "charges";
data1[0] = "address"; data1[9] = "fournisseur_produit";
data1[6] = "categories"; data1[5] = "utilisateur";
data1[10] = "vente";
data1[11] = "produit_vente";
try {
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
String bd = Gestion.utils.Utils.provider("Documents/parametres/paramBD.properties").get("URL").toString();
bd = bd.substring(bd.lastIndexOf("/")+1);
for (int i = 0; i < data1.length; i++) {
String requette = "SELECT COLUMN_NAME AS name " +
"FROM information_schema.COLUMNS " +
"WHERE TABLE_NAME = '"+data1[i]+"' AND TABLE_SCHEMA = '"+bd+"'";
Query q = session.createSQLQuery(requette);
q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List p = q.list();
String[] temp1 = new String[p.size()];
for (int j = 0; j < p.size(); j++) {
HashMap d = (HashMap) p.get(j);
temp1[j] = d.get("name").toString();
}
data.add(temp1);
}
}catch(Exception e){
e.printStackTrace();
}
return data;
}
public static JSONObject getproduitToChange(boolean ancien,String code){
JSONObject data = new JSONObject();
try {
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
String requette = "";
if(ancien){
requette = "SELECT\n" +
"P.`code` as codeP,\n" +
"P.designation as designation,\n" +
"P.idProduit as cleP,\n" +
"P.prix_d_achat as pua,\n" +
"P.prix_unitaire_de_vente as puv,\n" +
"P.date_de_peremtion as DateE,\n" +
"P.quantite as qte,\n" +
"P.seuil_de_vente as seuil,\n" +
"L.idClient as cleClient,\n" +
"L.addressidAddress as adC,\n" +
"L.nom as Ncl,\n" +
"L.prenom as Pcl,\n" +
"F.idfournisseur as four,\n" +
"C.idCategories as idCat,\n" +
"C.designation as scat,\n" +
"G.nom as cat,\n" +
"CONCAT(L.nom,' ',L.prenom) as Nclient,\n" +
"K.prix_unitaire_de_vente_reel as pvr,\n" +
"V.date_de_vente as dateV,\n" +
"V.idVente as numFac,\n" +
"CONCAT(U.nom,' ',U.prenom) as Nvendeur\n" +
"FROM\n" +
"produit P,\n" +
"vente V,\n" +
"utilisateur U,\n" +
"produit_vente K,\n" +
"client L,\n" +
"categories C,\n" +
"grandecategorie G,\n" +
"produit_categories N,\n" +
"fournisseur F,\n" +
"fournisseur_produit M\n" +
"WHERE\n" +
"V.idVente = K.venteidVente AND\n" +
"k.produitidProduit = P.idProduit AND\n" +
"V.clientidClient = L.idClient AND\n" +
"V.utilisateuridUser = U.idUser AND\n" +
"C.GrandeCategorie_idGrandeCategorie = G.idGrandeCategorie AND\n" +
"N.categoriesidCategories = C.idCategories AND\n" +
"N.produitidProduit = P.idProduit AND\n" +
"M.fournisseuridfournisseur = F.idfournisseur AND\n" +
"M.produitidProduit = P.idProduit AND\n" +
"P.`code` = :codeProduit";
}else{
requette = "SELECT\n" +
"P.`code` as codeP,\n" +
"P.designation as designation,\n" +
"P.idProduit as cleP,\n" +
"P.prix_d_achat as pua,\n" +
"P.prix_unitaire_de_vente as puv,\n" +
"P.date_de_peremtion as DateE,\n" +
"P.quantite as qte,\n" +
"P.seuil_de_vente as seuil,\n" +
"F.idfournisseur as four,\n" +
"C.idCategories as idCat,\n" +
"C.designation as scat,\n" +
"G.nom as cat\n" +
"FROM\n" +
"produit P,\n" +
"categories C,\n" +
"grandecategorie G,\n" +
"produit_categories N,\n" +
"fournisseur F,\n" +
"fournisseur_produit M\n" +
"WHERE\n" +
"C.GrandeCategorie_idGrandeCategorie = G.idGrandeCategorie AND\n" +
"N.categoriesidCategories = C.idCategories AND\n" +
"N.produitidProduit = P.idProduit AND\n" +
"M.fournisseuridfournisseur = F.idfournisseur AND\n" +
"M.produitidProduit = P.idProduit AND\n" +
"P.`code` = :codeProduit";
}
Query q = session.createSQLQuery(requette);
q.setParameter("codeProduit",code);
q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List liste = q.list();
if(!liste.isEmpty()){
HashMap temp = (HashMap) liste.get(0);
Set cle = temp.keySet();
for (Iterator iterator = cle.iterator(); iterator.hasNext();) {
Object next = iterator.next();
data.put(next,temp.get(next));
}
}
} catch (PersistentException ex) {
ex.printStackTrace();
}
return data;
}
}
|
package com.example.covid19;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.covid19.Stats.data;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.ValueDependentColor;
import com.jjoe64.graphview.series.BarGraphSeries;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import java.util.ArrayList;
public class Graph extends Fragment {
private RecyclerView recyclerView;
private ArrayList<HelpLineData> arrayList;
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
}
private static final String TAG = "Graph";
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.graph, container, false);
arrayList=new ArrayList<>();
initialiseArrayList();
recyclerView=view.findViewById(R.id.recyclerViewforHelLineNumber);
RecyclerViewNumber recyclerViewNumber=new RecyclerViewNumber(arrayList,getContext());
recyclerView.setAdapter(recyclerViewNumber);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
return view;
}
private void initialiseArrayList() {
arrayList.add(new HelpLineData("Andhra Pradesh","+91-866-2410978"));
arrayList.add(new HelpLineData("Arunachal Pradesh","+91-9436055743"));
arrayList.add(new HelpLineData("Assam","+91-6913347770"));
arrayList.add(new HelpLineData("Bihar","104"));
arrayList.add(new HelpLineData("Chhattisgarh","104"));
arrayList.add(new HelpLineData("Goa","104"));
arrayList.add(new HelpLineData("Gujarat","104"));
arrayList.add(new HelpLineData("Haryana","+91-8558893911"));
arrayList.add(new HelpLineData("Himachal Pradesh","104"));
arrayList.add(new HelpLineData("Jharkhand","104"));
arrayList.add(new HelpLineData("Andhra Pradesh","+91-866-2410978"));
arrayList.add(new HelpLineData("Andhra Pradesh","+91-866-2410978"));
arrayList.add(new HelpLineData("Andhra Pradesh","+91-866-2410978"));
arrayList.add(new HelpLineData("Andhra Pradesh","+91-866-2410978"));
}
}
|
package FactoryMethod;
public class Almaviva extends Vinho{
public Almaviva() {
this.setNome("ALMAVIVA");
this.setAno(2016);
this.setTipo("Tinto");
}
}
|
package com.umind.games;
import android.R;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Integer number = (Integer) parent.getItemAtPosition(pos);
Toast.makeText(parent.getContext(),
number + " series were selected",
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
Toast.makeText(arg0.getContext(),
"Default value is 3",
Toast.LENGTH_LONG).show();
}
}
|
package com.ibm.xml.parser;
import com.ibm.esc.xml.core.*;
/**
* Util is a collection of XML4J utility routines which check the conformance of various
* XML-defined values (XML name, language ID, encoding ID), and which provide services for
* converting strings to XML format.
*
* @version Revision: 09 1.5 src/com/ibm/xml/parser/Util.java, parser, xml4j2, xml4j2_0_0
* @author TAMURA Kent <kent@trl.ibm.co.jp>
*/
public class Util {
/**
* Returns whether the specified <var>string</var> consists of only XML whitespace.
* Refer to <A href="http://www.w3.org/TR/1998/REC-xml-19980210#NT-S">
* the definition of <CODE>S</CODE></A> for details.
* @param string String to be checked if it constains all XML whitespace.
* @return =true if name is all XML whitespace; otherwise =false.
*/
public static boolean checkAllSpace(String string) {
for (int s = 0; s < string.length(); s ++) {
if (!XMLChar.isSpace(string.charAt(s))) return false;
}
return true;
}
/**
* Returns whether the specified <var>name</var> conforms to <CODE>Name</CODE> in XML 1.0.
* Refer to <A href="http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name">
* the definition of <CODE>Name</CODE></A> for details.
* @param name Name to be checked as a valid XML Name.
* @return =true if name complies with XML spec; otherwise =false.
*/
public static boolean checkName(String name) {
if (1 > name.length()) return false;
char ch = name.charAt(0);
if (!(XMLChar.isLetter(ch) || '_' == ch || ':' == ch)) return false;
for (int i = 1; i < name.length(); i ++) {
if (!XMLChar.isNameChar(name.charAt(i))) return false;
}
return true;
}
}
|
package coordinates;
public class DMSlongitudeBuilder {
public DMSlongitude dmsLongitude;
public DMSlongitudeBuilder (){
dmsLongitude = new DMSlongitude();
}
public DMSlongitudeBuilder degrees (Integer d){
dmsLongitude.setDegrees(d);
return this;
}
public DMSlongitudeBuilder minutes (Integer m) {
dmsLongitude.setMinutes(m);
return this;
}
public DMSlongitudeBuilder seconds (Double s){
dmsLongitude.setSeconds(s);
return this;
}
public DMSlongitude buildDMSlongitude(){
return dmsLongitude;
}
}
|
package tss;
public class Driver {
/**
* Provide some strings to use for inputs to save having to type them
* in all the time.
*/
//private static String[][] TEST_VALUES = {
// { "The Jesus And Mary Chain", "2019-03-04T21:30", "150" },
// { "Milk and Honey Festival", "2019-03-08T19:00", "180" },
// { "Halestorm", "2019-03-13T20:00", "59" }, // short show for testing
// { "Me First And The Gimme Gimmes", "2019-03-15T21:00", "150" },
// { "Jay Rock", "2019-03-23T21:30", "180" }
//};
/**
* The main for the system.
* @param args Not used.
*/
public static void main(String[] args) {
hardwired();
}
/**
* This method provides a means to do basic testing of the system. It creates various
* objects under different circumstances and reports what happens. It is "hard-wired"
* in that the same thing happens every time it is executed (assuming no changes between
* executions of course). This makes is easy to re-run tests.
*
* The implementation is instrumented somewhat to show what's going on. The
* instrumentation messages are formatted in such a way to distinguish them from "normal"
* system messages. In what's provide ">>" describes the particular 'scenario' that is
* being shown, and "@" indicates when a constructor is called. This means that when
* this method is executed (by you, or by a marker for example), the output can be
* examined and any issues can be identified (e.g. somewhat that was supposed to happen
* for a scenario didn't happen) and evidence for behaviour of your design can be
* identified (e.g. the number of Artist objects created just requires counting the
* relevant messages).
*
* You are welcome to continue to use the conventions used in this template or to add new
* kinds of messages. Please do not change the existing conventions (">>" for scenarios
* and "@" for constructor calls). You are encouraged to add more scenarios, but keep in
* mind that the markers will be unwilling to read pages and pages of output. You need to
* provide enough evidence to support any claims you make, without overwhelming the reader.
*
* You are strongly encouraged to change the formatting of the output to make it easier
* to see what's going on. You might also consider using choosing values that will usefully
* illustrate the scenarios.
*/
private static void hardwired() {
Theatre theatre = new Theatre();
System.out.println(">>Start. Show current status (no artists, no performances)");
// Show the current status of the theatre
theatre.display();
System.out.println(); // Make sure scenarios are clearly separated.
System.out.println(">>Register first artist");
// Create an artist object, register it, and show the resulting theatre status
Artist artist1 = new Artist("The Jesus And Mary Chain");
theatre.addArtist(artist1);
theatre.display();
System.out.println(); // Make sure scenarios are clearly separated.
System.out.println(">>Register second artist");
// Create another artist object, register it, and show the resulting theatre status
Artist artist2 = new Artist("Milk and Honey Festival");
theatre.addArtist(artist2);
theatre.display();
System.out.println(); // Make sure scenarios are clearly separated.
System.out.println(">>Schedule performance for second artist");
// Create a performance for the second artist, schedule it, and show the resulting status
Performance performance1 = new Performance(artist2, "2019-03-08T19:00", 180);
theatre.addPerformance(performance1,artist2);
theatre.display();
System.out.println(); // Make sure scenarios are clearly separated.
System.out.println(">>Schedule second performance for second artist BEFORE first");
System.out.println(">>performance, so should be listed after the first.");
// etc
Performance performance2 = new Performance(artist2, "2019-02-10T19:00", 180);
theatre.addPerformance(performance2, artist2);
theatre.display();
System.out.println(); // Make sure scenarios are clearly separated.
System.out.println(">>Create performance that starts and finishes within the");
System.out.println(">>same hour of day. Note the artist has not been registered");
System.out.println(">>yet, but nor is the performance being scheduled.");
// etc
Artist artist3 = new Artist("Halestorm");
Performance performance3 = new Performance(artist3, "2019-03-13T20:00", 59);
System.out.println(); // Make sure scenarios are clearly separated.
System.out.println(">>Schedule previously-created performance for unregistered artist (no change)");
// etc
theatre.addPerformance(performance3,artist3);
theatre.display();
System.out.println(); // Make sure scenarios are clearly separated.
System.out.println(">>Register third artist and schedule performance (this time successfully)");
// etc
theatre.addArtist(artist3);
theatre.addPerformance(performance3,artist3);
theatre.display();
System.out.println(); // Make sure scenarios are clearly separated.
System.out.println(">>Try to add overlapping performance (nothing should change)");
// etc
Performance performance4 = new Performance(artist3, "2019-03-13T19:00", 120);
theatre.addPerformance(performance4, artist3);
theatre.display();
System.out.println(); // Make sure scenarios are clearly separated.
System.out.println(">>Try to create performance that finishes after midnight (nothing should change)");
// etc
Performance performance5 = new Performance(artist3, "2019-03-19T23:00", 120);
theatre.addPerformance(performance5,artist3);
theatre.display();
System.out.println(); // Make sure scenarios are clearly separated.
}
}
|
package leetcode;
/**
* @author kangkang lou
*/
/**
* 数组中位数
*/
public class Main_4 {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
if (m > n) {
return findMedianSortedArrays(nums2, nums1);
}
int i = 0, j = 0, imin = 0, imax = m, half = (m + n + 1) / 2;
double maxLeft = 0, minRight = 0;
while (imin <= imax) {
i = (imin + imax) / 2;
j = half - i;
if (j > 0 && i < m && nums2[j - 1] > nums1[i]) {
imin = i + 1;
} else if (i > 0 && j < n && nums1[i - 1] > nums2[j]) {
imax = i - 1;
} else {
if (i == 0) {
maxLeft = (double) nums2[j - 1];
} else if (j == 0) {
maxLeft = (double) nums1[i - 1];
} else {
maxLeft = (double) Math.max(nums1[i - 1], nums2[j - 1]);
}
break;
}
}
if ((m + n) % 2 == 1) {
return maxLeft;
}
if (i == m) {
minRight = (double) nums2[j];
} else if (j == n) {
minRight = (double) nums1[i];
} else {
minRight = (double) Math.min(nums1[i], nums2[j]);
}
return (maxLeft + minRight) / 2;
}
public double findMedianSortedArrays0(int[] nums1, int[] nums2) {
int n = nums1.length;
int m = nums2.length;
int left = (n + m + 1) / 2;
int right = (n + m + 2) / 2;
return (getKth(nums1, 0, n - 1, nums2, 0, m - 1, left) + getKth(nums1, 0, n - 1, nums2, 0, m - 1, right)) * 0.5;
}
private int getKth(int[] nums1, int start1, int end1, int[] nums2, int start2, int end2, int k) {
int len1 = end1 - start1 + 1;
int len2 = end2 - start2 + 1;
if (len1 > len2) return getKth(nums2, start2, end2, nums1, start1, end1, k);
if (len1 == 0) return nums2[start2 + k - 1];
if (k == 1) return Integer.min(nums1[start1], nums2[start2]);
int i = start1 + Integer.min(len1, k / 2) - 1;
int j = start2 + Integer.min(len2, k / 2) - 1;
//Eliminate half of the elements from one of the smaller arrays
if (nums1[i] > nums2[j]) {
return getKth(nums1, start1, end1, nums2, j + 1, end2, k - (j - start2 + 1));
} else {
return getKth(nums1, i + 1, end1, nums2, start2, end2, k - (i - start1 + 1));
}
}
}
|
package com.programyourhome.adventureroom.module.amazonpolly.module;
import java.util.Arrays;
import java.util.Collection;
import com.programyourhome.adventureroom.dsl.regex.AbstractRegexDslAdventureModule;
import com.programyourhome.adventureroom.dsl.regex.RegexActionConverter;
import com.programyourhome.adventureroom.model.Adventure;
import com.programyourhome.adventureroom.model.character.CharacterDescriptor;
import com.programyourhome.adventureroom.model.execution.ExecutionContext;
import com.programyourhome.adventureroom.model.toolbox.Toolbox;
import com.programyourhome.adventureroom.module.amazonpolly.dsl.converters.SpeakActionConverter;
import com.programyourhome.adventureroom.module.amazonpolly.model.characters.PollyCharacter;
import com.programyourhome.adventureroom.module.amazonpolly.service.AmazonPolly;
public class AmazonPollyAdventureModule extends AbstractRegexDslAdventureModule {
public static final String ID = "amazonpolly";
private AmazonPolly amazonPolly;
private AmazonPollyConfig config;
private Toolbox toolbox;
public AmazonPollyAdventureModule() {
this.amazonPolly = this.loadApiImpl(AmazonPolly.class);
this.initConfig();
}
public Toolbox getToolbox() {
return this.toolbox;
}
@Override
public void setToolbox(Toolbox toolbox) {
this.toolbox = toolbox;
// Create a cache wrapper around the Amazon Polly service to prevent synthesizing the same audio over and over again.
this.amazonPolly = new AmazonPollyCacheWrapper(this.amazonPolly, this.toolbox.getCacheService());
}
private void initConfig() {
this.config = new AmazonPollyConfig();
this.config.id = ID;
this.config.name = "Amazon Polly";
this.config.description = "Module to use the Amazon Polly service";
CharacterDescriptor<PollyCharacter> characterDescriptor = new CharacterDescriptor<>();
characterDescriptor.id = "polly";
characterDescriptor.name = "Amazon Polly based voice characters";
characterDescriptor.clazz = PollyCharacter.class;
this.config.addCharacterDescriptor(characterDescriptor);
this.config.addTask("Connect to Amazon AWS", () -> this.amazonPolly.connect(this.config.region));
}
@Override
public void start(Adventure adventure, ExecutionContext context) {
// No start actions needed.
}
public AmazonPolly getAmazonPolly() {
return this.amazonPolly;
}
@Override
public AmazonPollyConfig getConfig() {
return this.config;
}
@Override
protected Collection<RegexActionConverter<?>> getRegexActionConverters() {
return Arrays.asList(new SpeakActionConverter());
}
@Override
public void stop(Adventure adventure, ExecutionContext context) {
// No stop actions needed.
}
}
|
package com.ats.qa.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import com.ats.qa.base.Listeners;
import com.ats.qa.base.Log;
public class AssessmentQualifyingCriteria extends Listeners {
public WebDriver driver;
// private static Logger logger=Logger.getLogger(Log.class.getName());
public AssessmentQualifyingCriteria(WebDriver driver) throws Exception {
this.driver = driver;
}
public By Assesmentcriteria = By.id("cphMain_AssessmentQualifyCriteria");
public By AssesmentType = By.id("cphMain_ddlAssessmentType");
public By CostCentre = By.id("cphMain_ddlCostCentre");
public By Department = By.id("cphMain_ddlDepartment");
public By From = By.id("cphMain_tbFrom");
public By To = By.id("cphMain_tbTo");
public By Result = By.id("cphMain_ddlResult");
public By save = By.id("cphMain_btnSave");
public By edit = By.id("cphMain_gvAssessmentQualifyingCriteria_lbtnEdit_1");
public By Update = By.id("cphMain_btnUpdate");
// private By Delete =
// By.id("cphMain_gvAssessmentQualifyingCriteria_lbtnelete_0");
public By Homebutton = By.cssSelector("img[alt*='Home']");
public void getAssesmentcriteria() throws InterruptedException {
Thread.sleep(2000);
WebElement criteria = driver.findElement(Assesmentcriteria);
criteria.click();
Log.info("Assesment criteria is selected");
}
public Select getAssesmentType() throws InterruptedException {
Select dropdown = new Select(driver.findElement(AssesmentType));
dropdown.selectByVisibleText("VET");
Log.info("Assesment type drop down is selected");
return dropdown;
}
public Select getCostCentre() throws InterruptedException {
Thread.sleep(2000);
Select dropdown = new Select(driver.findElement(CostCentre));
dropdown.selectByVisibleText("JOINT");
Log.info("Joint cost center is selected");
return dropdown;
}
public Select getDepartment() throws InterruptedException {
Thread.sleep(2000);
Select dropdown = new Select(driver.findElement(Department));
dropdown.selectByVisibleText("Joint_Business HR");
return dropdown;
}
public void getFrom() throws InterruptedException {
Thread.sleep(2000);
driver.findElement(From).sendKeys("10");
;
Log.info("Assesment type drop down is selected");
}
public void getTo() throws InterruptedException {
Thread.sleep(2000);
driver.findElement(To).sendKeys("20");
;
Log.info("20 value is selected");
}
public void getResult() throws InterruptedException {
Thread.sleep(2000);
Select dropdown = new Select(driver.findElement(Result));
dropdown.selectByVisibleText("Ready");
Log.info("Ready drop down is selected");
}
public void getSave() throws InterruptedException {
Thread.sleep(2000);
driver.findElement(save).click();
Log.info("click on save button sucessfully");
}
public void getedit() throws InterruptedException {
Thread.sleep(2000);
JavascriptExecutor js1 = (JavascriptExecutor) driver;
js1.executeScript("scroll(0, 550)");
driver.findElement(By.xpath("//td[contains(text(),'VET')]//following::td[6]//descendant::input[@text='Edit']"))
.click();
Log.info("click on Edit button sucessfully");
}
public void getUpdate() throws InterruptedException {
Thread.sleep(2000);
driver.findElement(To).clear();
Log.info("Field is clear");
driver.findElement(To).sendKeys("20");
Log.info("20 value is entered");
driver.findElement(Update).click();
Log.info("Update button is selected");
}
public void getDelete() throws InterruptedException {
Thread.sleep(2000);
JavascriptExecutor js1 = (JavascriptExecutor) driver;
js1.executeScript("scroll(0, 250)");
driver.findElement(
By.xpath("//td[contains(text(),'VET')]//following::td[7]//descendant::input[@text='Delete']")).click();
Log.info("Delete button is selected");
Thread.sleep(2000);
driver.switchTo().alert().accept();
Log.info("Yes is selected");
Thread.sleep(2000);
driver.switchTo().alert().accept();
Log.info("OK is selected");
}
public void getHomePage() throws InterruptedException {
Thread.sleep(2000);
JavascriptExecutor js1 = (JavascriptExecutor) driver;
js1.executeScript("scroll(250, 0)");
driver.findElement(Homebutton).click();
Log.info("Home button is selected");
}
}
|
package com.ifli.mbcp.vo;
public class NeedAnalysisReportsVO {
private CustomerDetailsVO leadCustomerDetails;
private String name;
private String dateOfBirth;
private String gender;
private String maritalStatus;
public CustomerDetailsVO getLeadCustomerDetails() {
return leadCustomerDetails;
}
public void setLeadCustomerDetails(CustomerDetailsVO leadCustomerDetails) {
this.leadCustomerDetails = leadCustomerDetails;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}
public String getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
}
}
|
package org.rtmplite.red5.trash.amf.io;
public interface IRemotingClient {
Object invokeMethod(String method, Object[] params);
}
|
package ba.bitcamp.CSVBuilder;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class CSVBuilder<T> {
private static InputStream is;
private static OutputStream os;
private static FileInputStream fis;
private static FileOutputStream fos;
private static String basePath = "." + File.separator + "Base" + File.separator;
private static String currentOpen = null;
public static<T extends CSVeriazable> void saveObject(String fileName, T objectToSave) throws IOException {
if (fileName.equals(currentOpen)) {
os.write(objectToSave.objectToCSV().getBytes());
} else {
fos = new FileOutputStream(basePath + fileName + ".csv", true);
os = new DataOutputStream(fos);
currentOpen = fileName;
os.write(objectToSave.objectToCSV().getBytes());
}
System.out.println(objectToSave.objectToCSV());
}
public static<T extends CSVeriazable> T findObject(String[] array) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length-1; i++) {
sb.append(array[i]).append(", ");
}
sb.append(array.length - 1);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bis = new BufferedReader(isr);
String line = "";
String search = sb.toString();
try {
while ((line = bis.readLine()) != null) {
if (line.equals(search)) {
T newT = (T) new Object();
newT.csvToObject(line);
return newT;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return null;
}
}
|
package edu.frostburg.COSC310.TrippJohnathan;
/**
* Class representing a Singly-Linked List data structure and its Node component
* @author Johnathan Tripp (╯°□°)╯︵ ┻━┻
* @param <E> Generic type declaration for the Singly-Linked List
*/
public class SinglyLinkedList<E> {
class Node <E>{
private E element;
private Node<E> next;
public Node(E element, Node<E> next){
this.element = element;
this.next = next;
}
/**
* Get the next node
* @return the next Node
*/
public Node<E> getNext(){return next;}
/**
* Get the element of the node
* @return the element of the Node
*/
public E getElement(){return element;}
/**
* set the next Node
* @param n the next node
*/
public void setNext(Node<E> n){next = n;}
public boolean hasNext() {return next != null;}
}
private Node<E> head = null;
private Node<E> tail = null;
private int size = 0;
/**
* Gets the size of the list
* @return the size of the list
*/
public int size(){return size;}
/**
* Checks if the list is empty
* @return whether or not the list is empty
*/
public boolean isEmpty(){return size==0;}
/**
* Gets the first element of the list from the head node
* @return the first element of the list
*/
public E first() {
if(isEmpty()) return null;
return head.getElement();
}
/**
* Gets the last element of the list from the tail node
* @return the last element of the list
*/
public E last() {
if(isEmpty()) return null;
return tail.getElement();
}
/**
* Adds the specified element at the beginning of the list
* @param e the element to be added to the list
*/
public void addFirst(E e) {
head = new Node<>(e, head);
if(size==0)
tail = head;
size++;
}
/**
* Adds the specified element at the end of the list
* @param e the element to be added to the list
*/
public void addLast(E e) {
Node<E> newest = new Node<>(e, null);
if(isEmpty())
head = newest;
else
tail.setNext(newest);
tail = newest;
size++;
}
/**
* Removes the head node from the list
* @return the head node
*/
public E removeFirst() {
if(isEmpty()) return null;
E answer = head.getElement();
head = head.getNext();
size--;
if(size==0)
tail = null;
return answer;
}
/**
* Checks to determine if the specified element is contained within the list
* @param e the element to search for in the list
* @return whether or not the element was found in the list
*/
public boolean contains(E e){
if(isEmpty()) return false;
if(size == 1){
if(first().equals(e)) return true;
}
if(tail.element.equals(e)) return true;
Node n = head;
while(n.hasNext()){
if(n.element.equals(e)) return true;
n = n.next;
}
return false;
}
}
|
package com.njc.cartshopping.dto;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Builder;
import lombok.Value;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.List;
@Value
@Builder
@JsonDeserialize(builder = OrderDto.OrderDtoBuilder.class)
@ApiModel(description="All details about Orders ")
public class OrderDto {
@ApiModelProperty(notes = "Order Id created by the system")
private final long orderId;
@ApiModelProperty(notes = "Total order Price")
private final double totalPrice;
@ApiModelProperty(notes = "Order date, created when order is placed")
private final LocalDateTime orderDate;
@Email
@NotNull
private String email;
@ApiModelProperty(notes = "List of products included on the order")
@Builder.Default
private List<Long> products;
@JsonPOJOBuilder(withPrefix = "")
public static class OrderDtoBuilder {
}
}
|
package com.xu.easyweb.util;
import org.apache.commons.lang.StringUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* 超实检查过滤器
* User: zht
* Date: 12-9-17
* Time: 下午4:49
* To change this template use File | Settings | File Templates.
*/
public class SessionFilter implements Filter {
private FilterConfig filterConfig;
private String excludeUrl;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
excludeUrl = filterConfig.getInitParameter("excludeUrl");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpSession session = request.getSession(false);
String context = request.getContextPath();
String requestUrl = request.getRequestURI();
boolean filter = true;
if (!StringUtils.isEmpty(excludeUrl)) {
String[] urls = excludeUrl.split(",");
for (String url : urls) {
if (requestUrl.indexOf(url.trim()) != -1) {
filter = false;
break;
}
}
}
if (filter) {
if (null == session || null == session.getAttribute("user")) {
if(null != request.getHeader("x-requested-with") &&
request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
//ajax请求超时
response.addHeader("sessionstatus","timeout");
} else {
//http请求超时
response.sendRedirect(context + "/login.jsp");
}
return;
}
}
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
//To change body of implemented methods use File | Settings | File Templates.
}
}
|
/*
* Copyright (C) 2015 Miquel Sas
*
* 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 3 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 com.qtplaf.library.ai.learning.genetic;
import java.util.List;
/**
* Choose a network from a list.
*
* @author Miquel Sas
*/
public interface Chooser {
/**
* Choose a network from a list of networks.
*
* @param genomes The source list.
* @return The choosed network.
*/
Genome choose(List<Genome> genomes);
}
|
package com.liqw;
public class HelloServiceImp implements HelloService {
@Override
public String sayHello(String content) {
return "hello! "+ content;
}
}
|
package org.training.issuetracker.dao.interfaces;
import java.util.List;
import org.training.issuetracker.dao.entities.Role;
/**
* Interface, providing access to the user's roles and their data
* @author Dzmitry Salnikau
* @since 10.02.2014
*/
public interface RoleDAO {
/**
* @return List of all user's roles
*/
public List<Role> getRoles();
/**
* Returns Role object with stated roleId
* @param roleId
* @return Role
*/
public Role getRoleById(int roleId);
/**
* Adds new role in a data storage
* @param Role
* @return boolean - true, if it was successful
*/
public boolean createRole(Role role);
/**
* Update the role's data
* @param Role
* @return boolean - true, if it was successful
*/
public boolean updateRole(Role role);
/**
* Delete role from a data storage by the unique roleId
* @param roleId
* @return boolean - true, if it was successful
*/
public boolean deleteRole(int roleId);
}
|
package es.maltimor.genericRest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.UriInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import es.maltimor.genericUser.User;
import es.maltimor.webUtils.MapperUtils;
@SuppressWarnings("rawtypes")
public class GenericServiceMapperProvider {
final Logger log = LoggerFactory.getLogger(GenericServiceMapperProvider.class);
//user,table,info,filter
public String cntAll(Map params) {
//campos obligatorios
User user = (User) params.get("user");
String table = (String) params.get("table");
UriInfo ui = (UriInfo) params.get("ui");
Map<String,String> query = (Map<String,String>) params.get("query");
GenericMapperInfoTable info = (GenericMapperInfoTable) params.get("info");
GenericMapperInfoTableResolver resolver = info.getResolver();
String driver = info.getDriver();
List<String> fields = new ArrayList<String>();
List<GenericMapperInfoColumn> columns = info.getFields();
for (GenericMapperInfoColumn column : columns) {
fields.add(column.getName());
}
String filter = (String) params.get("filter");
if (filter==null) filter="";
else filter = filter.replace("'", "''");
// String sql = "SELECT count(*) AS COUNT FROM ("+resolver.getSQL(user,table)+")";
String sql = "SELECT count(*) FROM ("+resolver.getSQL(user,table)+")";
if (driver.equals("mysql") || driver.equals("informix") || driver.equals("access")) sql+=" t";
// if (fields!=null && fields.size()>0 && !filter.equals("")){
// //sql += filtrosWhere(info, fields, filter);
// sql += " WHERE "+getQueryWhere(filter,info);
// }
String actualFilter = "";
if (fields!=null && fields.size()>0 && !filter.equals("")) actualFilter = getQueryWhere(filter,info);
actualFilter = resolver.getQueryWhere(user, table, info, filter, ui, query, "cntAll", actualFilter);
if (!actualFilter.equals("")) sql+= " WHERE "+actualFilter;
log.debug("### cntAll:"+sql);
return sql;
}
//user,table,info,filter,limit,offset,orderby,order,fields
@SuppressWarnings("unchecked")
public String getAll(Map params) throws Exception{
User user = (User) params.get("user");
String table = (String) params.get("table");
String lfields = (String) params.get("fields");
UriInfo ui = (UriInfo) params.get("ui");
Map<String,String> query = (Map<String,String>) params.get("query");
GenericMapperInfoTable info = (GenericMapperInfoTable) params.get("info");
GenericMapperInfoTableResolver resolver = info.getResolver();
String driver = info.getDriver();
List<String> fields = new ArrayList<String>();
List<String> types = new ArrayList<String>();
List<GenericMapperInfoColumn> columns = info.getFields();
//incorporo aqui la lista de campos que se van a exportar
// TODO elimino los BLOB y CLOB AQUI y en esta llamada
if (lfields.equals("*")){
for (GenericMapperInfoColumn column : columns) {
// if (!column.getType().endsWith("LOB")) {
fields.add(column.getName().toUpperCase());
types.add(column.getType());
// }
}
} else {
//Se supone que la lista de nombres viene separada por comas, como truco se inserta una coma al principio y a l final
lfields = (","+lfields+",").toUpperCase();
for (GenericMapperInfoColumn column : columns) {
String name = column.getName().toUpperCase();
if (lfields.contains(","+name+",")) {
fields.add(name);
types.add(column.getType());
}
}
}
//for(int i=0;i<fields.size();i++){
//System.out.println("FIELD["+i+"]="+fields.get(i)+"|"+types.get(i)+"|");
//}
String filter = (String) params.get("filter");
String orderby = (String) params.get("orderby");
String order = (String) params.get("order");
//campos opcionales
if (!params.containsKey("limit")) params.put("limit",30); //TODO
if (!params.containsKey("offset")) params.put("offset",0);
Long offset = (Long) params.get("offset");
Long limit = (Long) params.get("limit");
//ORDERBY debe estar dentro de los fields
//permito que orderby y order sean una lista separada por comas
String orderClause=null;
if (orderby!=null && order!=null){
orderby=orderby.toUpperCase();
order=order.toUpperCase();
String[] ordersby=orderby.split(",");
String[] orders=order.split(",");
if (ordersby.length!=orders.length) throw new Exception("Diferente tamaño en la lista de ordenacion:"+orderby+"-"+order);
for(String oby:ordersby) if (!fields.contains(oby)) throw new Exception("No se puede ordenar por "+oby+" : "+fields+" : "+ordersby);
for(String o:orders) if (!"ASC,DESC".contains(o)) throw new Exception("Parametro order incorrecto.");
//llegado aqui me he asegurado que los datos son correctos: reconstruyo la clausula order
orderClause="";
for(int i=0;i<ordersby.length;i++){
orderClause+=", "+ordersby[i]+" "+orders[i];
}
orderClause=orderClause.substring(1);
}
if (filter==null) filter="";
else filter = filter.replace("'", "''");
String sql = "";
if (driver.equals("mysql") || driver.equals("informix") || driver.equals("access")){
sql+= "SELECT ";
if (driver.equals("informix")) sql+=" SKIP "+(offset)+" LIMIT "+(limit)+" ";
if (driver.equals("access")) sql+=" TOP "+(limit)+" ";
if (fields!=null && fields.size()>0){
for(int i=0;i<fields.size();i++){
//AÑADIR CAMBIO DE DATO PARA FECHAS PARA ACOMODARLO A UN UNICO ESTANDAR YYYY-MM-DD HH:MM:SS
// TODO Gestion ferchas en informix falta añadir tambien el nombre del alias entre ""
String type=types.get(i);
if (type.equals("F")) {
if (driver.equals("mysql") || driver.equals("informix")) sql+="DATE_FORMAT(t."+fields.get(i)+",'%Y-%m-%dT%H:%i:%s') AS "+fields.get(i);
else if (driver.equals("access")) sql+="FORMAT(t."+fields.get(i)+",'yyyy-mm-ddThh:nn:ss') AS "+fields.get(i);
} else if (type.equals("D")) {
if (driver.equals("mysql") || driver.equals("informix")) sql+="DATE_FORMAT(t."+fields.get(i)+",'%Y-%m-%d') AS "+fields.get(i);
else if (driver.equals("access")) sql+="FORMAT(t."+fields.get(i)+",'yyyy-mm-dd') AS "+fields.get(i);
} else sql+="t."+fields.get(i)+(driver.equals("informix")?" AS \""+fields.get(i).toUpperCase()+"\"":"");
if (i<fields.size()-1) sql+=", ";
}
}
sql+=" FROM ("+resolver.getSQL(user,table)+") t";
// if (fields!=null && fields.size()>0 && !filter.equals("")){
// //sql += filtrosWhere(info, fields, filter);
// sql += " WHERE "+getQueryWhere(filter,info);
// }
String actualFilter = "";
if (fields!=null && fields.size()>0 && !filter.equals("")) actualFilter = getQueryWhere(filter,info);
actualFilter = resolver.getQueryWhere(user, table, info, filter, ui, query, "getAll", actualFilter);
if (!actualFilter.equals("")) sql+= " WHERE "+actualFilter;
if (driver.equals("mysql")){
if (orderClause!=null) sql+=" ORDER BY "+orderClause;
sql+=" LIMIT "+(offset)+" , "+(limit);
} else {
//informix
if (orderClause!=null) sql+=" ORDER BY "+orderClause.toLowerCase();
}
} else {
sql+= "SELECT * FROM (SELECT ";
if (fields!=null && fields.size()>0){
for(int i=0;i<fields.size();i++){
//AÑADIR CAMBIO DE DATO PARA FECHAS PARA ACOMODARLO A UN UNICO ESTANDAR YYYY-MM-DD HH:MM:SS
String type=types.get(i);
if (type.equals("F")) sql+="TO_CHAR("+fields.get(i)+",'YYYY-MM-DD\"T\"HH24:MI:SS') AS "+fields.get(i);
else if (type.equals("D")) sql+="TO_CHAR("+fields.get(i)+",'YYYY-MM-DD') AS "+fields.get(i);
else sql+=fields.get(i);
sql+=", ";
}
}
if (orderClause!=null) sql+="ROW_NUMBER() OVER (ORDER BY "+orderClause+" ) rnk ";
else sql+="ROWNUM rnk ";
sql+="FROM ("+resolver.getSQL(user,table)+") t";
// if (fields!=null && fields.size()>0 && !filter.equals("")){
// //sql += filtrosWhere(info, fields, filter);
// sql += " WHERE "+getQueryWhere(filter,info);
// }
String actualFilter = "";
if (fields!=null && fields.size()>0 && !filter.equals("")) actualFilter = getQueryWhere(filter,info);
actualFilter = resolver.getQueryWhere(user, table, info, filter, ui, query, "getAll", actualFilter);
if (!actualFilter.equals("")) sql+= " WHERE "+actualFilter;
sql+=" ) t2 WHERE ( rnk BETWEEN "+(offset+1)+" AND "+(offset+limit)+" ) ";
}
log.debug("### getAll:"+sql);
//System.out.println("LLAMADA SQL: "+sql);
return sql;
}
//user,table,info,id
public String getById(Map params){
User user = (User) params.get("user");
String table = (String) params.get("table");
String id = (String) params.get("id");
GenericMapperInfoTable info = (GenericMapperInfoTable) params.get("info");
GenericMapperInfoTableResolver resolver = info.getResolver();
String driver = info.getDriver();
List<String> keys = info.getKeys();
splitKeys(params,info,id);
List<String> fields = new ArrayList<String>();
List<String> types = new ArrayList<String>();
List<GenericMapperInfoColumn> columns = info.getFields();
//incorporo aqui la lista de campos que se van a exportar
for (GenericMapperInfoColumn column : columns) {
fields.add(column.getName().toUpperCase());
types.add(column.getType());
}
String sql = "SELECT ";
if (driver.equals("mysql") || driver.equals("informix") || driver.equals("access")){
for(int i=0;i<fields.size();i++){
//TODO tratar fechas añadir "" en informix
String type=types.get(i);
if (type.equals("F")) {
if (driver.equals("mysql") || driver.equals("informix")) sql+="DATE_FORMAT(t."+fields.get(i)+",'%Y-%m-%dT%H:%i:%s') AS "+fields.get(i);
else if (driver.equals("access")) sql+="FORMAT(t."+fields.get(i)+",'yyyy-mm-ddThh:nn:ss') AS "+fields.get(i);
} else if (type.equals("D")) {
if (driver.equals("mysql") || driver.equals("informix")) sql+="DATE_FORMAT(t."+fields.get(i)+",'%Y-%m-%d') AS "+fields.get(i);
else if (driver.equals("access")) sql+="FORMAT(t."+fields.get(i)+",'yyyy-mm-dd') AS "+fields.get(i);
} else sql+="t."+fields.get(i)+(driver.equals("informix")?" AS \""+fields.get(i).toUpperCase()+"\"":"");
if (i<fields.size()-1) sql+=", ";
}
} else {
for(int i=0;i<fields.size();i++){
String type=types.get(i);
if (type.equals("F")) sql+="TO_CHAR("+fields.get(i)+",'YYYY-MM-DD\"T\"HH24:MI:SS') AS "+fields.get(i);
else if (type.equals("D")) sql+="TO_CHAR("+fields.get(i)+",'YYYY-MM-DD') AS "+fields.get(i);
else sql+=fields.get(i);
if (i<fields.size()-1) sql+=", ";
}
}
sql+=" FROM ("+resolver.getSQL(user,table)+")";
if (driver.equals("mysql") || driver.equals("informix") || driver.equals("access")) sql+=" t";
sql+=" WHERE ";
for(int i=0;i<keys.size();i++) {
//TODO keys de tipo fecha
sql+=keys.get(i)+"=#{id"+i+"}";
if (i<keys.size()-1) sql+=" AND ";
}
log.debug("### getById:"+sql);
return sql;
}
//user,table,data,info
@SuppressWarnings("unchecked")
public String insert(Map params){
User user = (User) params.get("user");
String table = (String) params.get("table");
GenericMapperInfoTable info = (GenericMapperInfoTable) params.get("info");
GenericMapperInfoTableResolver resolver = info.getResolver();
Map<String, Object> map = (Map<String, Object>) params.get("data");
for (GenericMapperInfoColumn column : info.getFields()) {
trataTipo(info, map, column.getName());
}
String res = resolver.getInsert(user, table, info, map);
log.debug("insert:"+res);
//System.out.println("LLAMADA PARA INSERTAR:" + res);
return res;
}
//user,table,data,info,id
@SuppressWarnings("unchecked")
public String update(Map params){
User user = (User) params.get("user");
String table = (String) params.get("table");
String id = (String) params.get("id");
GenericMapperInfoTable info = (GenericMapperInfoTable) params.get("info");
GenericMapperInfoTableResolver resolver = info.getResolver();
Map<String, Object> map = (Map<String, Object>) params.get("data");
//System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ UPDATE");
splitKeys(params,info,id);
for (GenericMapperInfoColumn column : info.getFields()) {
trataTipo(info, map, column.getName());
}
String sql = resolver.getUpdate(user,table,info,id,map);
log.debug("update:"+sql);
return sql;
}
//user,table,info,id
public String delete(Map params){
User user = (User) params.get("user");
String table = (String) params.get("table");
String id = (String) params.get("id");
GenericMapperInfoTable info = (GenericMapperInfoTable) params.get("info");
GenericMapperInfoTableResolver resolver = info.getResolver();
//mejorar esto para que admita otros rangos e incluso nulos en id
//actualmente keys.size=arr.size
//TODO de momento solo dejo el caso super especial de id=null
if (id!=null) splitKeys(params,info,id);
String sql = resolver.getDelete(user,table,info,id);
log.debug("### delete:"+sql);
return sql;
}
//user,table,data,info
@SuppressWarnings("unchecked")
public String execute(Map params){
User user = (User) params.get("user");
String table = (String) params.get("table");
GenericMapperInfoTable info = (GenericMapperInfoTable) params.get("info");
GenericMapperInfoTableResolver resolver = info.getResolver();
Map<String, Object> map = (Map<String, Object>) params.get("data");
for (GenericMapperInfoColumn column : info.getFields()) {
trataTipo(info, map, column.getName());
}
String res = resolver.getExecute(user, table, info, map);
log.debug("insert:"+res);
//System.out.println("LLAMADA PARA INSERTAR:" + res);
return res;
}
//secuence
public String getSecuenceValue(String secuence){
//String secuence = (String) params.get("secuence");
String res = "SELECT "+secuence+".CURRVAL AS VALUE FROM DUAL";
//System.out.println("SECUENCE:"+secuence);
return res;
}
@SuppressWarnings("unchecked")
private void splitKeys(Map params, GenericMapperInfoTable info, String id){
if (id==null) return;
List<String> keys = info.getKeys();
String separator = info.getKeySeparator();
String[] arr = id.split(separator);
for(int i=0;i<keys.size();i++){
String key = keys.get(i);
String field = "id"+i;
params.put(field, arr[i]);
trataTipo(info,params,key,field);
}
}
private void trataTipo(GenericMapperInfoTable table, Map<String, Object> map, String key) {
trataTipo(table,map,key,key);
}
private void trataTipo(GenericMapperInfoTable table, Map<String, Object> map, String keyIn, String keyOut) {
/* Map<String,String> types = new HashMap<String, String>();
for (GenericMapperInfoColumn column : table.getFields()) {
types.put(column.getName().toLowerCase(), column.getType());
}*/
//System.out.println("### TRATA TIPO:"+keyIn+" -> "+keyOut);
Map<String,String> types = table.getTypes();
//System.out.println("### TRATA TIPO: tipo:"+types.get(keyIn.toLowerCase()));
String type=types.get(keyIn.toLowerCase());
if (type.equals("T")) {
//TODO : dara error si supera el tamaño establecido
try {
//TODO : convertir a un varchar de tamaño dado
} catch (Exception e) {
e.printStackTrace();
}
} else if (type.equals("F")|type.equals("D")) {
try {
//System.out.println("### TRATA TIPO: TODATE");
MapperUtils.toDate(map, keyOut);
} catch (Exception e) {
e.printStackTrace();
}
} else if (type.equals("N")){
try {
MapperUtils.toDouble(map, keyOut);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private String filtrosWhere(GenericMapperInfoTable table, List<String> fields, String filter) {
//diferencia si el campo es o no una fecha.
String sql=" WHERE ";
for(int i=0;i<fields.size();i++){
String field=fields.get(i);
String type = "";
for (GenericMapperInfoColumn column : table.getFields()) {
if (column.getName().equals(field.toLowerCase()))
type = column.getType();
}
if (type.equals("F"))
sql+="UPPER( TO_CHAR("+field+", 'DD-MM-YYYY') ) like '%"+filter.toUpperCase()+"%'";
else
//TODO : pitch insensitive
sql+="UPPER("+field+") like '%"+filter.toUpperCase()+"%'";
if (i<fields.size()-1) sql+=" OR ";
}
return sql;
}
//filtra la cadena eliminando todos los caracteres de control de MyBatis
//{}'"
//TODO ver si elimino $ #
//TODO ver si transformo ' por '' y si es necesario eliminar las "
private String filterValue(String value) {
return value.replace("{", "").replace("}", "").replace("'", "").replace("\"","");
}
/*
* cols se utiliza para obtener informacion de la columnas, sobre todo el tipo de dato, si es key y si actua en fulltext
* Dado una query por url siguiendo la sintaxis:
* en el query estring se definen estos parametros:
* query=[sintaxis_query]
* start=[offset a partir del cual se empieza a mostrar datos, por defecto es 0]
* count=[numero de registros que se devuevle, por defecto es 30]
* order=[sintaxis_order]
* Sintaxis query:
* Q -> valor
* Q -> '[' key ']' op valor
* Q -> Q AND Q -- AND
* Q -> Q OR Q -- OR
* valor -> cadena de texto
* key -> nombre del campo
* op -> =, >, <, >=, <=, ==
* Sintaxis order:
* O -> Campo [ASC|DESC] [, O]
* Ejemplos de la sintaxis:
* ....?start=100&count=5&order=Campo1 ASC, Campo2 DESC&query=[Campo1]=Andres AND [Campo2]>5
*/
private String getQueryWhere(String text,GenericMapperInfoTable table){
List<String> lst = GenericFilter.parseFilter(text);
//System.out.println("********************* "+lst);
if (lst==null) return "";
if (lst.get(0).equals(GenericFilter.ERROR)) return "(1=0)";
String res = "";
String driver = table.getDriver();
List<GenericMapperInfoColumn> cols = table.getFields();
//optimizacion
Map<String,GenericMapperInfoColumn> map = new HashMap<String,GenericMapperInfoColumn>();
for(GenericMapperInfoColumn col:cols) map.put(col.getName().toLowerCase(), col);
//analizo semanticamente la cadena
res = "";
int TYPE_TEXT = 1;
int TYPE_NUMBER=2;
int TYPE_DATE = 3;
for(String cad:lst){
//aplico el filtro de manera global aqui: ahorro hacerlo muchas veces
//esto debería evitar el sql injection
cad = filterValue(cad);
//System.out.println("************** "+cad);
//System.out.println("*"+cad);
//por defecto el tipo de datos es texto
int type=TYPE_TEXT;
if (cad.startsWith("[")){
String[] aux = cad.substring(1).split("\\|",3);
String key = aux[0];
String op = aux[1];
String valor = (aux.length>2)? aux[2] : "";
boolean valorKey = valor.startsWith("[");
if (valorKey) valor = "#{"+valor.substring(1)+"}"; //convierto la expresion por algo que ibatis entiende
//aqui deberia recuperar el tipo de dato segun la columna
GenericMapperInfoColumn col = null;
if (!key.equals("NULL")) {
col = map.get(key.toLowerCase());
if (col!=null) {
String strType = col.getType().toUpperCase();
if (strType.equals("T")) type = TYPE_TEXT;
else if (strType.equals("N")) type = TYPE_NUMBER;
else if (strType.equals("F")) type = TYPE_DATE;
else if (strType.equals("D")) type = TYPE_DATE;
else type = TYPE_TEXT;
//System.out.println("COL:"+col);
} else key = "#{"+key+"}"; //evita sql injection?
}
//tengo en cuenta que por defecto todos los operadores añaden % al principio y al final
//= == <> !== !=
if (op.equals("=")||op.equals("!=")) {
//si el tipo de datos es TEXT la semantica es del tipo LIKE
//en otro caso el = el lo mismo que ==
if (type==TYPE_TEXT){
if (!valorKey) valor = "%"+valor.replace("*", "%")+"%";
op = op.equals("=")? " LIKE " : " NOT LIKE ";
} else if (type==TYPE_DATE){
//comprobar que sea una fecha y si no lo es poner NULL en el campo
try {
SimpleDateFormat formatoFecha = new SimpleDateFormat("d/M/yy");
formatoFecha.setLenient(false);
//formatoFecha.parse(valor);
} catch (Exception e) {
//System.out.println("Fecha NO valida:"+valor);
valor="";
}
}
//aplico la transformacion a valor en funcion de su tipo de datos
if (!valorKey&&((type==TYPE_TEXT)||(type==TYPE_DATE))) valor = "'"+valor+"'";
} else if (op.equals("==")||op.equals("!==")){
//este operador es identico a = excepto para TYPE_TEXT que permite comodines
if (type==TYPE_TEXT){
//si el valor contiene comodin, en vez de = pongo like
if (valor.contains("%")) op = op.equals("==")? " LIKE " : " NOT LIKE ";
else if (valor.contains("*")){
valor = valor.replace("*", "%");
op = op.equals("==")? " LIKE " : " NOT LIKE ";
} else op = op.equals("==")? "=" : "!=";
} else {
//en cualquier otro caso, el == es lo mismo que =
op = op.equals("==")? "=" : "!=";
}
//aplico la transformacion a valor en funcion de su tipo de datos
if (!valorKey&&((type==TYPE_TEXT)||(type==TYPE_DATE))) valor = "'"+valor+"'";
} else if (op.equals("=>")){
//aplico la transformacion a valor en funcion de su tipo de datos
if (!valorKey) valor = "'"+valor+"'";
} else if (op.equals(" IS ")){
//para esta operacion solo se permmite NULL y NOT NULL
if (valor.equalsIgnoreCase("NULL") || valor.equalsIgnoreCase("NOT NULL")){
valor = valor.toUpperCase();
} else if (!valorKey) valor = "'"+valor+"'";
} else if (op.equals(" IN ")) {
//aplico la transformacion a valor en funcion de su tipo de datos
if (!valorKey&&((type==TYPE_TEXT)||(type==TYPE_DATE))) valor = "'"+valor.replace(",", "','")+"'";
} else {
//aplico la transformacion a valor en funcion de su tipo de datos
if (!valorKey&&((type==TYPE_TEXT)||(type==TYPE_DATE))) valor = "'"+valor+"'";
}
if (key.equals("NULL")){
//iterar por todas las columnas de la vista que esten marcadas para la busqueda fulltext
//aqui se permite que col==null
//solo admito campos tipo text, y si es number o date se excluyen por complicar las consultas
res+=" ( (1=0) ";
for(GenericMapperInfoColumn cd:cols){
//elimino ademas los campos que empiezan por $
//System.out.println("**"+cd.getName()+","+cd.getType()+","+cd.isFullText()+" valor="+valor);
boolean valid=cd.isFullText();
String t=cd.getType().toUpperCase();
valor=(aux.length>2)? aux[2] : ""; //restablezco el valor a su posicion original
if (valid&&t.equals("T")){
//no hago cuenta a los comodines, se los pongo yo por defecto por delante y por detras
//si el valor contiene comodin, en vez de = pongo like
valor = "'%"+valor+"%'";
valor = valor.toLowerCase();
if (driver.equals("mysql") || driver.equals("informix")){
res+=" OR ( LOWER("+cd.getName()+") LIKE "+valor+" ) ";
} else if (driver.equals("access")){
res+=" OR ( LCASE("+cd.getName()+") LIKE "+valor+" ) ";
} else {
res+=" OR ( LOWER(CONVERT("+cd.getName()+",'US7ASCII')) LIKE CONVERT( "+valor+" ,'US7ASCII') ) ";
}
} else if (valid&&t.equals("N")){
//si valor es un numero incluyo esta columna
try{
double a = Double.parseDouble(valor);
if (driver.equals("mysql") || driver.equals("informix")){
res+=" OR ( LOWER("+cd.getName()+") = "+a+" ) ";
} else if (driver.equals("access")){
res+=" OR ( LCASE("+cd.getName()+") = "+a+" ) ";
} else {
res+=" OR ( LOWER(CONVERT("+cd.getName()+",'US7ASCII')) = "+a+" ) ";
}
} catch (Exception e){
//no hago nada
}
}
}
res+=" ) ";
//res+="FULLTEXT("+valor+")";
} else {
//en funcion del tipo de dato se ponen ' o no
//hay que escapar datos
//TODO si col==null lo añado aqui?
if ((col!=null) && (op.equals(" LIKE ")||op.equals(" NOT LIKE "))) {
if (driver.equals("mysql") || driver.equals("informix")){
key = "LOWER("+col.getName()+")";
valor = valor.toLowerCase();
} else if (driver.equals("access")){
key = "LCASE("+col.getName()+")";
valor = valor.toLowerCase();
} else {
key = "LOWER(CONVERT("+col.getName()+",'US7ASCII'))";
valor = "CONVERT( "+valor.toLowerCase()+" ,'US7ASCII') ";
}
res+= key+op+valor;
} else if (op.equals("=>")){
//TODO en informix esto no esta soportado
op = " IN ";
valor = "(SELECT TRIM(REGEXP_SUBSTR("+valor+", '[^,]+', 1, LEVELS.COLUMN_VALUE)) "
+ " FROM TABLE(CAST(MULTISET(SELECT LEVEL FROM DUAL "
+ " CONNECT BY LEVEL <= LENGTH (REGEXP_REPLACE("+valor+", '[^,]+')) + 1) AS SYS.OdciNumberList)) LEVELS)";
res+= key+op+valor;
} else if (op.equals(" IN ")){
if (!valorKey) {
res+= key+op+"("+valor+")";
} else {
res+= "INSTR(','||"+valor+"||',' , ','||"+key+"||',')>0";
}
} else {
//resto de casos
res+= key+op+valor;
}
}
} else {
if (cad.equals("&")) res+= " AND ";
else if (cad.equals("|")) res += " OR ";
else if (cad.equals("(")) res += "(";
else if (cad.equals(")")) res += ")";
}
//System.out.println(cad);
//System.out.println("************** "+res);
}
//System.out.println("SQLUTILS:"+res);
return res;
}
}
|
package com.espendwise.manta.service;
import com.espendwise.manta.dao.PropertyDAO;
import com.espendwise.manta.dao.PropertyDAOImpl;
import com.espendwise.manta.model.data.OrderPropertyData;
import com.espendwise.manta.model.data.PropertyData;
import com.espendwise.manta.model.view.EntityPropertiesView;
import com.espendwise.manta.util.Utility;
import org.springframework.stereotype.Service;
import java.util.List;
import javax.persistence.EntityManager;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class PropertyServiceImpl extends DataAccessService implements PropertyService{
@Override
public List<PropertyData> findEntityPropertyValues(Long entityId, String typeCode) {
PropertyDAO propertyDao = new PropertyDAOImpl(getEntityManager());
return propertyDao.findEntityProperties(entityId, Utility.toList(typeCode));
}
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public void configureEntityProperty(Long entityId, String propertyType, String propertyValue) {
EntityManager entityManager = getEntityManager();
PropertyDAO propertyDao = new PropertyDAOImpl(entityManager);
propertyDao.configureEntityProperty(entityId, propertyType, propertyValue);
}
@Override
public EntityPropertiesView findEntityProperties(Long entityId, List<String> propertyExtraTypeCds, List<String> propertyTypeCds) {
PropertyDAO propertyDao = new PropertyDAOImpl(getEntityManager());
List<PropertyData> properties = propertyDao.findEntityPropertiesByTypeOrName(Utility.toList(entityId), propertyExtraTypeCds, propertyTypeCds, null, false);
EntityPropertiesView view = new EntityPropertiesView ();
view.setBusEntityId(entityId);
view.setProperties(properties);
return view;
}
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public EntityPropertiesView saveEntityProperties(Long entityId, EntityPropertiesView pView) {
PropertyDAO propertyDao = new PropertyDAOImpl(getEntityManager());
List<PropertyData> properties = propertyDao.updateEntityProperties(entityId, pView.getProperties());
EntityPropertiesView view = new EntityPropertiesView ();
view.setBusEntityId(entityId);
view.setProperties(properties);
return view;
}
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public OrderPropertyData saveOrderProperty(Long orderId, OrderPropertyData property) {
PropertyDAO propertyDao = new PropertyDAOImpl(getEntityManager());
OrderPropertyData savedProperty = propertyDao.saveOrderProperty(orderId, property);
return savedProperty;
}
}
|
package logica;
import java.util.ArrayList;
public class Calculadora
{
ArrayList<Integer> numeros;
ArrayList<String> signos;
String numero; //Numero que estara formando
int resultado;
///////////////CONSTRUCTOR///////////////
public Calculadora()
{
numeros = new ArrayList<Integer>();
signos = new ArrayList<String>();
resultado = 0;
numero = "";
}
public void obtenerValor(String c)
{
if(c.equals("C"))//RESETEAR
resetear();
else if (c.equals("<"))//BORRAR
{
if(numero.length() == 0)//Si no estaba formando un numero.
{
signos.remove(signos.size() - 1); //Pasamos a borrar el ultimo signo ingresado
numero = String.valueOf(numeros.get(numeros.size() -1)); //y ponemos en "edicion" al ultimo numero ingresado.
numeros.remove(numeros.size() - 1); //Sacamos ese ultimo numero del array.
}
else
numero = numero.substring(0, numero.length() - 1); //Borramos el ultimo caracter del numero en "edicion".
}
else if(c.equals("="))//CALCULAR
{
if(numeros.size() == 0 && numero.length() == 0)//Si no se agrego ningun numero y no se estuvo formando uno retornamos.
return;
if(numeros.size() == 0 && numero.length() > 0)//Si no se agrego ningun numero y se estuvo formando uno agregamos este ultimo.
{
numeros.add(Integer.parseInt(numero));
numero = "";
}
if(numero.length() != 0) //Chequeamos que se estuviera formando un numero antes de agregarlo.
numeros.add(Integer.parseInt(numero));
calcular();
numero = "";
}
else if(c.equals("+") || c.equals("-") || c.equals("/") || c.equals("*"))
{
if(numero == "" && signos.size() > 0) //Chequeamos si por ultima vez se estaba formando un numero o si se
signos.set(signos.size() - 1, c); //agrego un signo, de ser esto ultimo, se lo reemplaza.
else
signos.add(c);
if(signos.size() == 1 && numero.length() == 0 && numeros.size() == 0) //Si se agrego un signo sin que halla ningun
{ //numero se lo elimina.
signos.remove(0);
return;
}
if(numero != "")
numeros.add(Integer.parseInt(numero));
numero = "";
}
else
numero = numero + c;
}
private void calcular()
{
resultado = numeros.get(0);
numeros.remove(0);
while(numeros.size() != 0)
{
if(signos.get(0).equals("+"))
sumar(resultado, numeros.get(0));
if(signos.get(0).equals("-"))
restar(resultado, numeros.get(0));
if(signos.get(0).equals("/"))
dividir(resultado, numeros.get(0));
if(signos.get(0).equals("*"))
multiplicar(resultado, numeros.get(0));
numeros.remove(0);
signos.remove(0);
}
numeros.add(resultado);
}
private void resetear() //Funcion que resetea todos los datos de la calculadora
{
numero = "";
resultado = 0;
while(numeros.size() != 0)
numeros.remove(0);
while(signos.size() != 0)
signos.remove(0);
}
private void sumar(int num1, int num2)
{
resultado = num1 + num2;
}
private void restar(int num1, int num2)
{
resultado = num1 - num2;
}
private void dividir( int num1, int num2)
{
resultado = num1 / num2;
}
private void multiplicar (int num1, int num2)
{
resultado = num1 * num2;
}
public int getResultado()
{
return resultado;
}
}
|
package com.appc.report.model;
import com.appc.framework.mybatis.annotation.Query;
import com.appc.framework.mybatis.annotation.Where;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
/**
* UserRole
*
* @version : Ver 1.0
* @author : panda
* @date : 2017-9-19
*/
@Entity
@Table
@Query
public class UserRole implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
@Where
@Getter(onMethod = @__({@ApiModelProperty("")}))
@Setter(onMethod = @__({@ApiModelProperty("")}))
private Long userId;
/**
*
*/
@Where
@Getter(onMethod = @__({@ApiModelProperty("")}))
@Setter(onMethod = @__({@ApiModelProperty("")}))
private Integer roleId;
/**
*
*/
@Id
@Where
@Getter(onMethod = @__({@GeneratedValue(), @ApiModelProperty("")}))
@Setter(onMethod = @__({@ApiModelProperty("")}))
private Integer id;
}
|
package softblue.innerlocal;
public class Main {
public static void main(String[] args) {
String t2 = "Imprimir dado fora";
class Texto {
private String t;
public Texto(String t) {
this.t = t;
}
public void imprimir() {
System.out.println(t);
}
public void imprimir2() {
System.out.println(t2);
}
}
Texto txt = new Texto("Meu texto");
txt.imprimir();
txt.imprimir2();
}
}
|
/*
* SE1021 - 021
* Winter 2017
* Lab: Lab 3 Interfaces
* Name: Rock Boynton
* Created: 12/13/17
*/
package boyntonrl.Lab3;
import java.text.DecimalFormat;
/**
* A class to represent bolt objects.
*/
public class Bolt implements Part {
/**
* Number used to calculate the weight of the bolt
*/
public static final double LBS_MULTIPLIER = 0.05;
/**
* Number used to calculate the price of the bolt
*/
public static final double USD_MULTIPLIER = 1.00;
private final DecimalFormat costFormat = new DecimalFormat("$0.00");
private final DecimalFormat weightFormat = new DecimalFormat("#.###");
private double diameterInches;
private double lengthInches;
/**
* Constructor for the bolt, which has a length and diameter
* @param diameterInches the diameter of the bolt in inches
* @param lengthInches the length of the bolt in inches
*/
public Bolt(double diameterInches, double lengthInches) {
this.diameterInches = diameterInches;
this.lengthInches = lengthInches;
}
@Override
public double getCost() {
return USD_MULTIPLIER * diameterInches * lengthInches;
}
@Override
public String getName() {
return diameterInches + "x" + lengthInches + " bolt";
}
@Override
public double getWeight() {
return LBS_MULTIPLIER * Math.pow(diameterInches, 2) * lengthInches;
}
/**
* Prints the bill for the bolt.
* Lists the name, diameter, length, cost, and weight.
*/
@Override
public void printBillOfMaterials() {
System.out.println("==========================\n" +
getName() + "\n" +
"==========================\n" +
"Diameter: " + diameterInches + " inches\n" +
"Length: " + lengthInches + " inches\n" +
"Cost: " + costFormat.format(getCost()) + "\n" +
"Weight: " + weightFormat.format(getWeight()) + " lbs\n");
}
}
|
package me.zakeer.justchat.services;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import me.zakeer.justchat.interfaces.OnAsyncTaskListener;
import me.zakeer.justchat.utility.AsyncLoadVolley;
import me.zakeer.justchat.utility.Constant;
public class ResponseRequestService extends Service {
protected static final String TAG = "ResponseRequestService";
private Handler handler;
SharedPreferences sharedPreferences;
InputStream inputStream;
private String friendRequestId;
private String friendId, userId, adminId, type;
AsyncLoadVolley asyncLoadVolley;
public ResponseRequestService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
handler = new Handler();
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle extras = intent.getExtras();
friendRequestId = extras.getString(Constant.FRIEND_REQUEST_ID);
friendId = extras.getString(Constant.FRIEND_ID);
type = extras.getString(Constant.TYPE);
userId = extras.getString(Constant.USER_ID);
//adminId = extras.getString(Constant.ADMIN_ID);
Log.e("IN CHECK", "START");
//check();
onUploadStart(friendRequestId, type, friendId, userId);
return super.onStartCommand(intent, flags, startId);
}
public void onUploadStart(String friendRequestId, String type, String friendId, String userId) {
asyncLoadVolley = new AsyncLoadVolley(this, "friendrequestgcm");
Map<String, String> map = new HashMap<String, String>();
map.put(Constant.ID, friendRequestId);
map.put(Constant.TYPE, type);
map.put(Constant.FRIEND_ID, friendId);
map.put(Constant.USER_ID, userId);
asyncLoadVolley.setBasicNameValuePair(map);
asyncLoadVolley.setOnAsyncTaskListener(uploadAsyncTaskListener);
handler.post(new Runnable() {
public void run()
{
asyncLoadVolley.beginTask();
}
});
}
OnAsyncTaskListener uploadAsyncTaskListener = new OnAsyncTaskListener() {
@Override
public void onTaskComplete(boolean isComplete, String message) {
Log.e(TAG, " mess : "+message);
/*
Intent intent = new Intent(Constant.FRIEND);
intent.putExtra(Constant.STATUS, true);
intent.putExtra(Constant.POSITION, position);
intent.putExtra(Constant.IMAGE, imageName);
//sendBroadcast(intent);
*/
stopSelf();
//onUploadComplete();
}
@Override
public void onTaskBegin() {
}
};
/////
@Override
public void onDestroy() {
Log.w("mine", "CLICKED");
super.onDestroy();
}
}
|
package com.dzz.policy.service.service.notify;
import com.dzz.policy.api.domain.dto.PolicyPayDataUpdateParam;
import com.dzz.policy.api.service.PolicyService;
import com.dzz.util.response.ResponsePack;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* 支付成功处理接口
*
* @author dzz
* @version 1.0.0
* @since 2019年08月19 13:44
*/
@Service
@Slf4j
@SuppressWarnings("ALL")
public class PaySuccessNotifyHandlerService {
private PolicyService policyService;
@Autowired
public void setPolicyService(PolicyService policyService) {
this.policyService = policyService;
}
/**
* 支付成功处理接口,更新投保单支付状态等信息
* @param decodeSign 已经解密后的数据
* @return 处理结果
*/
@Transactional(rollbackFor = Exception.class)
public ResponsePack<Boolean> paySuccessHandler(String decodeSign) {
PolicyPayDataUpdateParam payDataUpdateParam = new PolicyPayDataUpdateParam();
return policyService.updatePolicyPayData(payDataUpdateParam);
}
}
|
/*
* Copyright (C) 2023 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hedera.services.store.contracts.precompile;
import static com.hedera.services.store.contracts.precompile.HTSTestsUtil.*;
import static com.hedera.services.store.contracts.precompile.impl.RevokeKycPrecompile.decodeRevokeTokenKyc;
import static java.util.function.UnaryOperator.identity;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import com.hedera.mirror.web3.evm.account.MirrorEvmContractAliases;
import com.hedera.mirror.web3.evm.properties.MirrorNodeEvmProperties;
import com.hedera.mirror.web3.evm.store.Store;
import com.hedera.mirror.web3.evm.store.contract.HederaEvmStackedWorldStateUpdater;
import com.hedera.node.app.service.evm.store.contracts.precompile.EvmHTSPrecompiledContract;
import com.hedera.node.app.service.evm.store.contracts.precompile.EvmInfrastructureFactory;
import com.hedera.services.fees.FeeCalculator;
import com.hedera.services.fees.HbarCentExchange;
import com.hedera.services.fees.calculation.UsagePricesProvider;
import com.hedera.services.fees.pricing.AssetsLoader;
import com.hedera.services.hapi.utils.fees.FeeObject;
import com.hedera.services.store.contracts.precompile.impl.RevokeKycPrecompile;
import com.hedera.services.store.contracts.precompile.utils.PrecompilePricingUtils;
import com.hedera.services.store.models.TokenRelationship;
import com.hedera.services.txn.token.RevokeKycLogic;
import com.hedera.services.utils.accessors.AccessorFactory;
import com.hederahashgraph.api.proto.java.ExchangeRate;
import com.hederahashgraph.api.proto.java.HederaFunctionality;
import com.hederahashgraph.api.proto.java.SubType;
import com.hederahashgraph.api.proto.java.TokenRevokeKycTransactionBody;
import com.hederahashgraph.api.proto.java.TransactionBody;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.tuweni.bytes.Bytes;
import org.hyperledger.besu.datatypes.Wei;
import org.hyperledger.besu.evm.frame.MessageFrame;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class RevokeKycPrecompileTest {
private static final long TEST_SERVICE_FEE = 5_000_000;
private static final long TEST_NETWORK_FEE = 400_000;
private static final long TEST_NODE_FEE = 300_000;
private static final int CENTS_RATE = 12;
private static final int HBAR_RATE = 1;
private static final long EXPECTED_GAS_PRICE =
(TEST_SERVICE_FEE + TEST_NETWORK_FEE + TEST_NODE_FEE) / DEFAULT_GAS_PRICE * 6 / 5;
private static final Bytes REVOKE_TOKEN_KYC_INPUT = Bytes.fromHexString(
"0xaf99c63300000000000000000000000000000000000000000000000000000000000004b200000000000000000000000000000000000000000000000000000000000004b0");
private final TransactionBody.Builder transactionBody =
TransactionBody.newBuilder().setTokenRevokeKyc(TokenRevokeKycTransactionBody.newBuilder());
@Mock
private AccessorFactory accessorFactory;
@Mock
private AssetsLoader assetLoader;
@Mock
private EvmHTSPrecompiledContract evmHTSPrecompiledContract;
@Mock
private EvmInfrastructureFactory infrastructureFactory;
@Mock
private ExchangeRate exchangeRate;
@Mock
private FeeCalculator feeCalculator;
@Mock
private FeeObject mockFeeObject;
@Mock
private HbarCentExchange exchange;
@Mock
private HederaEvmStackedWorldStateUpdater worldUpdater;
@Mock
private MessageFrame frame;
@Mock
private MirrorEvmContractAliases contractAliases;
@Mock
private MirrorNodeEvmProperties evmProperties;
@Mock
private Store store;
@Mock
private TokenRelationship tokenRelationship;
@Mock
private UsagePricesProvider resourceCosts;
private HTSPrecompiledContract subject;
private PrecompileMapper precompileMapper;
private RevokeKycLogic revokeKycLogic;
private RevokeKycPrecompile revokeKycPrecompile;
private SyntheticTxnFactory syntheticTxnFactory;
@BeforeEach
void setUp() throws IOException {
final Map<HederaFunctionality, Map<SubType, BigDecimal>> canonicalPrices = new HashMap<>();
canonicalPrices.put(
HederaFunctionality.TokenRevokeKycFromAccount, Map.of(SubType.DEFAULT, BigDecimal.valueOf(0)));
given(assetLoader.loadCanonicalPrices()).willReturn(canonicalPrices);
final PrecompilePricingUtils precompilePricingUtils =
new PrecompilePricingUtils(assetLoader, exchange, feeCalculator, resourceCosts, accessorFactory);
syntheticTxnFactory = new SyntheticTxnFactory();
revokeKycLogic = new RevokeKycLogic();
revokeKycPrecompile = new RevokeKycPrecompile(revokeKycLogic, syntheticTxnFactory, precompilePricingUtils);
precompileMapper = new PrecompileMapper(Set.of(revokeKycPrecompile));
subject = new HTSPrecompiledContract(
infrastructureFactory, evmProperties, precompileMapper, evmHTSPrecompiledContract);
}
@Test
void RevokeKyc() {
// given
givenFrameContext();
givenPricingUtilsContext();
given(worldUpdater.permissivelyUnaliased(any()))
.willAnswer(invocationOnMock -> invocationOnMock.getArgument(0));
given(worldUpdater.getStore()).willReturn(store);
given(store.getTokenRelationship(any(), any())).willReturn(tokenRelationship);
given(feeCalculator.estimatedGasPriceInTinybars(HederaFunctionality.ContractCall, HTSTestsUtil.timestamp))
.willReturn(1L);
given(feeCalculator.computeFee(any(), any(), any(), any(), any())).willReturn(mockFeeObject);
// when
subject.prepareFields(frame);
subject.prepareComputation(REVOKE_TOKEN_KYC_INPUT, a -> a);
subject.getPrecompile()
.getGasRequirement(HTSTestsUtil.TEST_CONSENSUS_TIME, transactionBody, store, contractAliases);
final var result = subject.computeInternal(frame);
// then
assertEquals(successResult, result);
}
@Test
void gasRequirementReturnsCorrectValueForRevokeKyc() {
// given
givenMinimalFrameContext();
givenPricingUtilsContext();
given(worldUpdater.permissivelyUnaliased(any()))
.willAnswer(invocationOnMock -> invocationOnMock.getArgument(0));
given(feeCalculator.computeFee(any(), any(), any(), any(), any()))
.willReturn(new FeeObject(TEST_NODE_FEE, TEST_NETWORK_FEE, TEST_SERVICE_FEE));
given(feeCalculator.estimatedGasPriceInTinybars(any(), any())).willReturn(DEFAULT_GAS_PRICE);
// when
subject.prepareFields(frame);
subject.prepareComputation(REVOKE_TOKEN_KYC_INPUT, a -> a);
final var result =
subject.getPrecompile().getGasRequirement(TEST_CONSENSUS_TIME, transactionBody, store, contractAliases);
// then
assertEquals(EXPECTED_GAS_PRICE, result);
}
@Test
void decodeRevokeTokenKycInput() {
final var decodedInput = decodeRevokeTokenKyc(REVOKE_TOKEN_KYC_INPUT, identity());
assertTrue(decodedInput.token().getTokenNum() > 0);
assertTrue(decodedInput.account().getAccountNum() > 0);
}
private void givenMinimalFrameContext() {
given(frame.getWorldUpdater()).willReturn(worldUpdater);
given(frame.getSenderAddress()).willReturn(contractAddress);
}
private void givenFrameContext() {
givenMinimalFrameContext();
given(frame.getRemainingGas()).willReturn(300L);
given(frame.getValue()).willReturn(Wei.ZERO);
}
private void givenPricingUtilsContext() {
given(exchange.rate(any())).willReturn(exchangeRate);
given(exchangeRate.getCentEquiv()).willReturn(CENTS_RATE);
given(exchangeRate.getHbarEquiv()).willReturn(HBAR_RATE);
given(worldUpdater.permissivelyUnaliased(any()))
.willAnswer(invocationOnMock -> invocationOnMock.getArgument(0));
}
}
|
package BikeStore;
public class BicycleManagement {
private final int MAXBIKES = 20;
private Bicycle[] bikelist = new Bicycle[MAXBIKES];
private int count = 0;
/**
* @param bike
*/
public void addbike(Bicycle bike) {
if (count < MAXBIKES) {
bikelist[count] = bike;
count += 1;
} else {
System.out.println("MAX Bikes");
}
}
public String imprimir() {
String resp = "";
for (int i = 0; i < this.count; i++) {
if (this.bikelist[i] instanceof MountainBike) {
MountainBike mountainbike = (MountainBike) this.bikelist[i];
resp += mountainbike.printMountain(); // imprime mountain bikes
} else if (this.bikelist[i] instanceof RoadBike) {
RoadBike roadBike = (RoadBike) this.bikelist[i];
resp += roadBike.printRoad(); // imprime road bikes
} else {
resp += this.bikelist[i].toString(); // imprime default bicycle
}
resp += "\n";
}
return resp;
}
public String imprimirMountainBikes() {
String resp = "";
for (int i = 0; i < this.count; i++) {
if (this.bikelist[i] instanceof MountainBike) {
MountainBike mountainbike = (MountainBike) this.bikelist[i];
resp += mountainbike.printMountain(); // imprime mountain bikes
}
}
return resp;
}
public String imprimirRoadBikes() {
String resp = "";
for (int i = 0; i < this.count; i++) {
if (this.bikelist[i] instanceof RoadBike) {
RoadBike roadBike = (RoadBike) this.bikelist[i];
resp += roadBike.printRoad(); // imprime road bikes
}
}
return resp;
}
@Override
public String toString() {
String text = "";
for (int i = 0; i < count; i++) {
text += "Bike " + (i + 1) + " : " + "\n" + bikelist[i].toString() + "\n";
}
return text;
}
}
|
package org.forit.blog.dao;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import org.forit.blog.dto.PostDTO;
import org.forit.blog.entity.PostEntity;
import org.forit.blog.exception.BlogException;
public class PostDAO {
public final static String DB_URL = "jdbc:mysql://localhost:3306/blog?useSSL=false&user=forit&password=12345";
public static final String INSERT_POST = "INSERT INTO post (id_categoria, titolo, descrizione, data ,id_autore, visibile) values (?, ?, ?, ?, ?, ?)";
public static final String UPDATE_POST
= "UPDATE POST "
+ "SET ID_CATEGORIA = ?, TITOLO = ?, DESCRIZIONE = ?, DATA = ?, VISIBILE = ?,VISITE=?, ID_AUTORE = ? "
+ "WHERE ID = ?";
public List<PostDTO> getPostsList() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("blog_pu");
EntityManager em = emf.createEntityManager();
TypedQuery<PostEntity> query = em.createNamedQuery("post.selectAll", PostEntity.class);
List<PostEntity> list = query.getResultList();
List<PostDTO> posts = list.stream().map(entity -> {
PostDTO post = new PostDTO(entity.getID(), entity.getIdCategoria(), entity.getTitolo(), entity.getDescrizione(), entity.getData(),
entity.isVisibile(),entity.getVisite(), entity.getIdAutore()
);
return post;
}).collect(Collectors.toList());
em.close();
emf.close();
return posts;
}
public PostDTO getPost(long ID) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("blog_pu");
EntityManager em = emf.createEntityManager();
PostEntity entity = em.find(PostEntity.class, ID);
PostDTO post = new PostDTO(entity.getID(), entity.getIdCategoria(), entity.getTitolo(), entity.getDescrizione(), entity.getData(),
entity.isVisibile(),entity.getVisite(), entity.getIdAutore()
);
em.close();
emf.close();
return post;
}
public void insertPost(long ID, long IdCategoria, String titolo, String descrizione, LocalDate data, boolean visibile,int visite, long IdAutore) throws BlogException {
try (
Connection conn = DriverManager.getConnection(DB_URL);
PreparedStatement ps = conn.prepareStatement(INSERT_POST)) {
ps.setLong(1, IdCategoria);
ps.setString(2, titolo);
ps.setString(3, descrizione);
ps.setDate(4, Date.valueOf(data));
ps.setLong(5, IdAutore);
ps.setBoolean(6, visibile);
ps.executeUpdate();
} catch (SQLException ex) {
System.out.println("Si è verificato un errore " + ex.getMessage());
throw new BlogException(ex);
}
}
public void updatePost(long ID, long IdCategoria, String titolo, String descrizione, LocalDate data, boolean visibile,int visite, long IdAutore) throws BlogException {
try (
Connection conn = DriverManager.getConnection(DB_URL);
PreparedStatement ps = conn.prepareStatement(UPDATE_POST);) {
ps.setLong(1, ID);
ps.setLong(2, IdCategoria);
ps.setString(3, titolo);
ps.setString(4, descrizione);
ps.setDate(4, Date.valueOf(data));
ps.setBoolean(5, visibile);
ps.setInt(6, visite);
ps.setLong(7, IdAutore);
} catch (SQLException ex) {
System.out.println("Si è verificato un errore " + ex.getMessage());
throw new BlogException(ex);
}
}
public void deletePost(long ID) throws BlogException {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("blog_pu");
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
try {
transaction.begin();
PostEntity post = em.find(PostEntity.class, ID);
em.remove(post);
transaction.commit();
} catch (Exception ex) {
transaction.rollback();
throw new BlogException(ex);
} finally {
em.close();
emf.close();
}
}
}
|
package com.cisco.prototype.ledsignaldetection;
/**
* Created by jessicalandreth on 7/17/15.
*/
public class imagePair {
public String kickstartImage;
public String systemImage;
public imagePair(String kick, String sys){
kickstartImage = kick;
systemImage = sys;
}
}
|
package lesson15.hw02;
import java.util.Arrays;
public class GoogleAPI implements API {
private Room[] rooms;
public GoogleAPI(Room[] rooms) {
this.rooms = rooms;
}
public Room[] getRooms() {
return rooms;
}
@Override
public Room[] findRooms(int price, int persons, String city, String hotel) {
Room findRoom = new Room(0, price, persons, null, hotel, city);
int counter = 0;
for (Room room : getRooms()) {
if (room.equals(findRoom))
counter++;
}
Room[] searchRooms = new Room[counter];
int index = 0;
for (Room room : getRooms()) {
if (room.equals(findRoom)) {
searchRooms[index] = room;
index++;
}
}
System.out.println(3 + " " + Arrays.toString(searchRooms));
return searchRooms;
}
@Override
public Room[] getAll() {
int index = 0;
Room[] allRooms = new Room[rooms.length];
for (Room room : getRooms()) {
allRooms[index] = room;
index++;
}
return allRooms;
}
}
|
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.*;
public class ComponentEventWin extends JFrame{
private static final long serialVersionUID = 1L;
JTextArea txtArea = new JTextArea();
class MyComponentAdapter extends ComponentAdapter {
public void componentResized(ComponentEvent e) {
String str = e.getSource().getClass() + " 컴포넌트 크기 재조정 : ";
str += e.getComponent().getBounds() + "\n" ;
txtArea.append(str);
}
}
public ComponentEventWin() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,150);
add(txtArea, "Center");
txtArea.addComponentListener(new MyComponentAdapter());
setVisible(true);
}
public static void main(String[] args) {
ComponentEventWin myWin = new ComponentEventWin();
myWin.setTitle("컴포넌트 이벤트 처리");
}
}
|
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.staticUIExtensions.web;
import jetbrains.buildServer.staticUIExtensions.model.Rule;
import jetbrains.buildServer.web.openapi.PagePlaces;
import jetbrains.buildServer.web.openapi.PluginDescriptor;
import org.jetbrains.annotations.NotNull;
/**
* @author Eugene Petrenko (eugene.petrenko@gmail.com)
* Date: 16.11.11 19:58
*/
public class RulePageExtensionsFactory {
private final PagePlaces myPlaces;
private final PluginDescriptor myDescription;
private final ControllerPaths myPaths;
public RulePageExtensionsFactory(@NotNull final PagePlaces places,
@NotNull final PluginDescriptor description,
@NotNull final ControllerPaths paths) {
myPlaces = places;
myDescription = description;
myPaths = paths;
}
@NotNull
public RulePageExtension createExtension(@NotNull final Rule rule) {
return new RulePageExtension(myPlaces, myDescription, myPaths, rule);
}
}
|
package edu.itserulik.product.controller;
import edu.itserulik.product.model.Item;
import edu.itserulik.product.service.ProductProviderService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import java.util.Set;
@RestController
public class ProductController {
private final ProductProviderService productProviderService;
public ProductController(ProductProviderService productProviderService) {
this.productProviderService = productProviderService;
}
@GetMapping(path = "/getBySku", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
public Flux<Item> getItemsBySku(@RequestParam("sku") String sku) {
return productProviderService.getItemsBySku(sku);
}
@GetMapping(path = "/getByIds", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
public Flux<Item> getItemByIds(@RequestParam("ids") Set<String> ids) {
return productProviderService.getItemByIds(ids);
}
}
|
package com.lingnet.vocs.service.equipment;
import java.util.HashMap;
import java.util.List;
import com.lingnet.common.service.BaseService;
import com.lingnet.util.Pager;
import com.lingnet.vocs.entity.Machine;
public interface EquipmentUseService extends BaseService<Machine, String>{
/**
* 设备基础信息编辑保存
*
* @Title: saveOrUpdate
* @param machine
* @return
* @throws Exception
* String
* @author suihl
* @since 2017年10月09日 V 1.0
*/
public String saveOrUpdate(Machine machine , String girdData) throws Exception;
/**
* 设备基础信息列表展示
*
* @Title: getListData
* @param pager
* @return String
* @author suihl
* @since 2017年10月09日 V 1.0
*/
public String getListData(Pager pager);
/**
* 设备基础信息删除
*
* @Title: remove
* @param inspectId
* @return
* @throws Exception
* String
* @author suihl
* @since 2017年10月09日 V 1.0
*/
public String remove(String machineId) throws Exception;
/**
* 设备信息展示
* @Title: getSblist
* @param id
* @return
* String
* @author lizk
* @param type
* @since 2017年10月25日 V 1.0
*/
public String getSblist(String sbmc,String gylx,String sbcs,String id,String start,String count,String isrm);
public String getRmlist();
public String getGylx();
public String getSbcj();
public String getData(Pager pager);
public List<Machine> findBySupplierId(String id);
}
|
package com.hly.o2o.dao;
import com.hly.o2o.entity.Award;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class AwardDaoTest {
@Autowired
private AwardDao awardDao;
/**
* 添加奖品测试
*/
@Test
public void testAInsertAward(){
long shopId=2;
Award award=new Award();
award.setAwardName("奖品1");
award.setAwardImg("f://image/award");
award.setAwardDesc("奖品一描述");
award.setCreateTime(new Date());
award.setLastEditTime(new Date());
award.setPoint(5);
award.setPriority(1);
award.setEnableStatus(1);
award.setShopId(shopId);
int effectedNum = awardDao.insertAward(award);
assertEquals(1,effectedNum);
Award award2=new Award();
award2.setAwardName("奖品2");
award2.setAwardImg("f://image/award");
award2.setAwardDesc("奖品2描述");
award2.setCreateTime(new Date());
award2.setLastEditTime(new Date());
award2.setPoint(6);
award2.setPriority(2);
award2.setEnableStatus(1);
award2.setShopId(shopId);
int effectedNum2 = awardDao.insertAward(award);
assertEquals(1,effectedNum2);
}
@Test
public void testBQueryAwardList(){
Award award=new Award();
List<Award> awardList = awardDao.queryAwardList(award, 0, 3);
assertEquals(3,awardList.size());
int awardCount = awardDao.queryAwardCount(award);
assertEquals(4,awardCount);
award.setAwardName("奖品");
int i = awardDao.queryAwardCount(award);
assertEquals(3,i);
}
@Test
public void testCQueryAwardById(){
Award award=new Award();
award.setAwardName("奖品1");
List<Award> awards = awardDao.queryAwardList(award, 0, 1);
assertEquals(1,awards.size());
Award award1 = awardDao.queryAwardByAwardId(awards.get(0).getAwardId());
assertEquals("奖品1",award1.getAwardName());
}
@Test
public void testCUpdateAward(){
Award award=new Award();
award.setAwardName("奖品1");
List<Award> awards = awardDao.queryAwardList(award, 0, 1);
awards.get(0).setAwardName("第一个奖品1");
int effectNum = awardDao.updateAward(awards.get(0));
assertEquals(1,effectNum);
Award award1 = awardDao.queryAwardByAwardId(awards.get(0).getAwardId());
assertEquals("第一个奖品1",award1.getAwardName());
}
@Test
public void TestDDeleteAward(){
Award award=new Award();
award.setAwardName("第一个奖品1");
List<Award> awardList = awardDao.queryAwardList(award, 0, 1);
assertEquals(1,awardList.size());
for(Award award1:awardList){
int effectNum = awardDao.deleteAward(award1.getAwardId(), award1.getShopId());
assertEquals(1,effectNum);
}
}
}
|
package com.java.phondeux.team;
import org.bukkit.ChatColor;
import com.java.phondeux.team.StatsHandler.TeamStats;
public class TeamUtils {
public static String colorize(String string) {
for (ChatColor cc : ChatColor.values()) {
string = string.replaceAll("%" + cc.name(), cc.toString());
}
return string;
}
public static String formatTeam(TeamStats stats, String string) {
string = string.replaceAll("%members", stats.NumMembers().toString());
string = string.replaceAll("%kills", stats.NumKills().toString());
string = string.replaceAll("%deaths", stats.NumDeaths().toString());
string = string.replaceAll("%pvpdeaths", stats.NumPvpDeaths().toString());
return colorize(string);
}
}
|
package com.google.sample.cast.refplayer;
public class SolutionMessage {
public String senderId;
public String solution;
}
|
package dev.evertonsavio.app.webfluxtests;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
@ExtendWith(SpringExtension.class) //JUnit 5
class WebfluxTestsApplicationTests {
@Test
void contextLoads() {
}
@Test
void fluxTest(){
Flux<String> stringFlux = Flux.just("Spring", "Spring Boot", "Reactive Spring")
//.concatWith(Flux.error(new RuntimeException("Exception Occurred")))
.concatWith(Flux.just("After error"))
.log();
StepVerifier.create(stringFlux)
.expectSubscription()
.expectNext("Spring")
.expectNext("Spring Boot")
.expectNext("Reactive Spring")
.expectNext("After error")
.verifyComplete();
// stringFlux.subscribe(System.out::println,
// (e) -> System.err.println("Exception is :" + e),
// () -> System.out.println("Complete"));
}
}
|
package pattern_test.visitor;
/**
* Description:
*
* @author Baltan
* @date 2019-04-02 10:40
*/
public class Monitor implements Component {
@Override
public void getPrice(ComputerPriceTable table) {
table.showPrice(this);
}
}
|
package com.example.ahmed.octopusmart.Interfaces;
import android.view.View;
import com.example.ahmed.octopusmart.Model.ServiceModels.ProductModel;
import com.example.ahmed.octopusmart.Model.ServiceModels.CatModel;
/**
* Created by sotra on 12/9/2017.
*/
public interface HomeAdapterListener {
void onProductClicked(ProductModel productModel , View shared , int postion );
void onSliderProductClicked(ProductModel productModel , View shared , int postion );
void onCategoryHeadarClicked(CatModel catModel , View shared , int postion );
}
|
package es.utils.mapper.annotation;
import es.utils.mapper.configuration.Configuration;
import es.utils.mapper.defaultvalue.DefaultValueFactory;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.function.Supplier;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* This annotation allows the mapper to supply a default value for the setters.<br>
* Examples of use cases:
* <ul>
* <li>Simple string value:
* <ul>{@code @Default("default value")}</ul>
* </li>
* <li>String value with custom charset (the {@code charset} field is used for all the cases where the {@code value} field is used):
* <ul>{@code @Default(value="default value", charset="UTF-8")}</ul>
* </li>
* <li>Integer number value:
* <ul>{@code @Default(number=42)}</ul>
* </li>
* <li>Decimal number value:
* <ul>{@code @Default(decimal=0.5)}</ul>
* </li>
* <li>Boolean value:
* <ul>{@code @Default(boolean=true)}</ul>
* </li>
* <li>Character value:
* <ul>{@code @Default(character='c')}</ul>
* </li>
* <li>Class type value:
* <ul>{@code @Default(type=MyType.class)}</ul>
* </li>
* <li>Class type to use to ask the {@link Configuration} for the correct supplier:
* <ul>{@code @Default(type=MyTypeToSupply.class)}</ul>
* </li>
* <li>Enum value:
* <ul>{@code @Default(enumType=TimeUnit.class,value="MILLISECONDS")}</ul>
* </li>
* <li>Custom supplier class (similar to a factory but does not require an input):
* <ul>{@code @Default(supplier=MySupplier.class)}</ul>
* </li>
* <li>Custom factory:
* <ul>{@code @Default(factory=MyDefaultValueFactory.class, value="input value")}</ul>
* </li>
* <li>Custom factory with parameters:
* <ul>{@code @Default(factory=MyDateDefaultValue.class, value="24/12/2010", parameters="DD/mm/YYYY")}</ul>
* </li>
* </ul>
* @author eschoysman
*/
@Retention(RUNTIME)
@Target(FIELD)
public @interface Default {
String value() default "";
long number() default 0;
double decimal() default 0;
boolean bool() default false;
char character() default 0;
Class<?> type() default Object.class;
Class<? extends Enum> enumType() default Enum.class;
Class<? extends Supplier> supplier() default Supplier.class;
Class<? extends DefaultValueFactory> factory() default DefaultValueFactory.class;
String[] parameters() default {};
String charset() default "";
}
|
package ogr.hpe.bridge;
import java.util.UUID;
import java.util.function.Consumer;
import org.hpe.df.event.MessageConsumer;
import org.hpe.df.event.MessageProducer;
import org.hpe.dnslog.DNSLogCallBack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient;
import com.hivemq.client.mqtt.mqtt5.Mqtt5Client;
import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5Publish;
public class MQTTBridge {
private static final Logger logger = LoggerFactory.getLogger(MQTTBridge.class);
private String bridgeId;
private Mqtt5AsyncClient mqttClient;
public MQTTBridge() {
bridgeId = "bridge_" + UUID.randomUUID();
mqttClient = Mqtt5Client.builder()
.identifier(bridgeId)
.serverHost("localhost")
.serverPort(1883)
.automaticReconnectWithDefaultConfig()
.buildAsync();
}
private void connect(String user, String password) {
mqttClient.toBlocking().connectWith()
.simpleAuth()
.username(user)
.password(password.getBytes())
.applySimpleAuth()
.send();
}
private void publish(String topic, byte[] message) {
mqttClient.publishWith()
.topic(topic)
.payload(message)
.send()
.whenComplete((publish, throwable) -> {
if (throwable != null) {
logger.error("Publish failed: {}", throwable);
} else {
logger.info("Publish: {}", message);
}
});
}
private void subscribe(String topic, Consumer<Mqtt5Publish> mqttConsumer) {
mqttClient.subscribeWith()
.topicFilter(topic)
.callback(mqttConsumer)
.send()
.whenComplete((subAck, throwable) -> {
if (throwable != null) {
logger.error("Subscription to {} failed: {}", topic, throwable );
} else {
logger.debug("Subscription established: {}", topic);
}
});
}
public static void main(String[] args) throws Exception {
MQTTBridge bridge = new MQTTBridge();
String MQTT_TOPIC = "/sensor";
String KAFKA_INCOMING_TOPIC = "/sensor:metric";
String KAFKA_OUTGOING_TOPIC = "/sensor:action";
bridge.connect( "fberque", "password");
try (
MessageProducer<byte[],String,byte[]> producer = new MessageProducer.Builder<byte[],String,byte[]>()
.async(true)
.topicName(KAFKA_INCOMING_TOPIC)
.propsFile("/byteArrayProducer.props")
.callback( DNSLogCallBack.class)
.keyFunction( v -> "" )
.valueFunction( v -> v )
.build();
MessageConsumer<String,byte[]> consumer = new MessageConsumer.Builder<String,byte[]>()
.pooling(100)
.topicName(KAFKA_OUTGOING_TOPIC)
.propsFile("/byteArrayConsumer.props")
.consumerFunction( message -> bridge.publish("/action", message.value() ) )
.build();
) {
bridge.subscribe( MQTT_TOPIC, mqtt5Publish -> producer.send( mqtt5Publish.getPayloadAsBytes()) );
consumer.run();
}
}
}
|
package com.google.tv.android.polycastengine.gl.shader;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
public class ShaderLoader {
private Context mContext;
public ShaderLoader(Context context) {
mContext = context;
}
public String getVertexShader(String name) {
return doLoad("shaders/"+name+"/" + name + ".vtx");
}
public String getFragmentShader(String name) {
return doLoad("shaders/"+name+"/" + name + ".frag");
}
private String doLoad(String name) {
String shader = "";
try {
InputStream is = mContext.getAssets().open(name);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
shader = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
return shader;
}
}
|
package com.tencent.mm.plugin.appbrand;
import android.app.Activity;
import android.os.Build.VERSION;
import com.tencent.mm.plugin.appbrand.appcache.WxaCommLibRuntimeReader;
import com.tencent.mm.plugin.appbrand.appcache.ao;
import com.tencent.mm.plugin.appbrand.appcache.d.a;
import com.tencent.mm.plugin.appbrand.config.AppBrandSysConfig;
import com.tencent.mm.plugin.appbrand.debugger.r;
import com.tencent.mm.plugin.appbrand.debugger.r.1;
import com.tencent.mm.plugin.appbrand.g.b;
import com.tencent.mm.plugin.appbrand.g.e;
import com.tencent.mm.plugin.appbrand.g.f;
import com.tencent.mm.plugin.appbrand.g.h;
import com.tencent.mm.plugin.appbrand.jsapi.c;
import com.tencent.mm.plugin.appbrand.jsapi.d;
import com.tencent.mm.plugin.appbrand.performance.AppBrandPerformanceManager;
import com.tencent.mm.plugin.appbrand.r.i;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.util.Iterator;
import java.util.LinkedList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class l extends c {
public volatile boolean Sx = true;
public g fdO;
public d fdP = aaF();
public b fdQ = aaE();
public o fdR;
protected LinkedList<a> fdS = new LinkedList();
public boolean fdT = false;
private boolean fdU = false;
private long fdV = System.currentTimeMillis();
public long fdW;
private volatile boolean fdX = false;
public String mAppId;
public l() {
if (this.fdQ.y(f.class) != null && r.aaM()) {
d dVar = new d(this, (f) this.fdQ.y(f.class));
this.fdQ.addJavascriptInterface(dVar, "WeixinJSContext");
dVar.aad();
this.fdX = true;
}
this.fdR = new o(this);
this.fdQ.setJsExceptionHandler(new 1(this));
this.fdW = System.currentTimeMillis() - this.fdV;
}
public b aaE() {
return h.cD(ad.getContext());
}
public d aaF() {
d dVar = new d(this, this.fdQ);
this.fdQ.addJavascriptInterface(dVar, "WeixinJSCore");
return dVar;
}
public void h(g gVar) {
x.i("MicroMsg.AppBrandService", "onRuntimeReady, mPreLoadWebView %b", new Object[]{Boolean.valueOf(this.fdT)});
this.fdO = gVar;
this.mAppId = gVar.mAppId;
if (this.fdQ.y(e.class) != null) {
((e) this.fdQ.y(e.class)).setJsRuntimeTitle(String.format("https://servicewechat.com/%s/js-engine", new Object[]{this.mAppId}));
}
}
public void init() {
aaJ();
aaH();
if (!this.fdX) {
String a = ao.a(this.fdO, "app-service.js");
com.tencent.mm.plugin.report.service.h.mEJ.a(370, 9, 1, false);
i.a(this.fdQ, "app-service.js", a, new 6(this));
r.a(this.fdO, this.fdQ, "app-service.js");
g gVar = this.fdO;
b bVar = this.fdQ;
if (gVar == null || bVar == null) {
x.w("MicroMsg.SourceMapInjector", "runtime or jsRuntime is null.");
} else if (a.jC(gVar.fcu.frm.fih)) {
x.i("MicroMsg.SourceMapInjector", "current running type is ReleaseType do not need to inject sourceMap.");
} else {
a = WxaCommLibRuntimeReader.qJ("WASourceMap.js");
if (a == null || a.length() == 0) {
x.w("MicroMsg.SourceMapInjector", "WASourceMap.js is null or nil");
} else {
i.a(bVar, a, new 1());
}
}
}
aaG();
}
public void qw(String str) {
if (this.fdX) {
try {
j("onSubPackageReady", new JSONObject().put("moduleName", str).toString(), 0);
return;
} catch (Exception e) {
x.e("MicroMsg.AppBrandService", "loadModule using isolate context, notify but get exception %s");
return;
}
}
String str2 = str + (str.endsWith("/") ? "" : "/") + "app-service.js";
String a = ao.a(this.fdO, str2);
com.tencent.mm.plugin.report.service.h.mEJ.a(370, 30, 1, false);
i.a(this.fdQ, str2, a, new 2(this, str));
r.a(this.fdO, this.fdQ, str2);
}
public final synchronized void aaG() {
Iterator it = this.fdS.iterator();
while (it.hasNext()) {
a aVar = (a) it.next();
super.j(aVar.bHA, aVar.data, aVar.src);
}
this.fdS = null;
}
public final void aaH() {
if (!this.fdU) {
this.fdU = true;
i.a(this.fdQ, com.tencent.mm.plugin.appbrand.q.c.vM("wxa_library/android.js"), new 3(this));
i.a(this.fdQ, WxaCommLibRuntimeReader.qJ("WAService.js"), new i.a() {
public final void qe(String str) {
x.i("MicroMsg.AppBrandService", "Inject SDK Service Script Success");
com.tencent.mm.plugin.report.service.h.mEJ.a(370, 7, 1, false);
l.this.fdQ.evaluateJavascript("(function(){return JSON.stringify(wx.version);})()", new 1(this));
}
public final void fM(String str) {
int i = 0;
x.e("MicroMsg.AppBrandService", "Inject SDK Service Script Failed: %s", new Object[]{str});
com.tencent.mm.plugin.report.service.h.mEJ.a(370, 6, 1, false);
com.tencent.mm.plugin.appbrand.report.a.G(l.this.mAppId, 24, 0);
int i2 = -1;
if (l.this.fdO != null) {
i = l.this.fdO.fcu.frm.fii;
i2 = l.this.fdO.fcu.frm.fih;
}
com.tencent.mm.plugin.appbrand.report.a.a(l.this.mAppId, i, i2, 370, 6);
}
});
com.tencent.mm.plugin.report.service.h.mEJ.a(370, 5, 1, false);
}
if (this.fdO != null) {
String str = "";
if (AppBrandPerformanceManager.vi(this.mAppId)) {
str = WxaCommLibRuntimeReader.qJ("WAPerf.js");
}
if (bi.oW(str)) {
x.i("MicroMsg.AppBrandService", "execInternalInitScript, performanceJs nil");
} else {
i.a(this.fdQ, str, new 5(this));
}
}
}
public void j(String str, String str2, int i) {
synchronized (this) {
if (this.fdS != null) {
this.fdS.add(new a(str, str2, i));
return;
}
super.j(str, str2, i);
}
}
public final void a(String str, String str2, int[] iArr) {
this.fdO.fcz.c(str, str2, iArr);
}
public final boolean isRunning() {
return this.Sx;
}
public final Activity getContext() {
return this.fdO == null ? null : this.fdO.fcq;
}
public final String getAppId() {
return this.mAppId;
}
public final g getRuntime() {
return this.fdO;
}
public final b aaI() {
return this.fdQ;
}
public void cleanup() {
super.cleanup();
this.Sx = false;
this.fdQ.destroy();
this.fdP.cleanup();
}
public void aaJ() {
JSONObject aaK = aaK();
String str = this.fdO.fcv.foU;
this.fdQ.evaluateJavascript(String.format("var __wxConfig = %s;\nvar __wxIndexPage = \"%s\"", new Object[]{aaK.toString(), str}), null);
if (this.fdT) {
super.j("onWxConfigReady", "", 0);
}
}
public final JSONObject aaK() {
JSONObject jSONObject = new JSONObject();
AppBrandSysConfig appBrandSysConfig = this.fdO.fcu;
com.tencent.mm.plugin.appbrand.config.a aVar = this.fdO.fcv;
if (appBrandSysConfig == null || aVar == null) {
return new JSONObject();
}
JSONObject jSONObject2 = aVar.foT;
Iterator keys = jSONObject2.keys();
while (keys.hasNext()) {
String str = (String) keys.next();
try {
jSONObject.putOpt(str, jSONObject2.opt(str));
} catch (Exception e) {
x.e("MicroMsg.AppBrandService", e.getMessage());
}
}
a(jSONObject, "appType", Integer.valueOf(this.fdO.fct.bGM));
a(jSONObject, "debug", Boolean.valueOf(this.fdO.fcu.fqL));
a(jSONObject, "downloadDomain", appBrandSysConfig.frg);
g(jSONObject);
Object jSONObject3 = new JSONObject();
a((JSONObject) jSONObject3, "scene", Integer.valueOf(this.fdO.aan()));
String aao = this.fdO.aao();
a((JSONObject) jSONObject3, "path", com.tencent.mm.plugin.appbrand.q.l.vP(aao));
a((JSONObject) jSONObject3, "query", new JSONObject(com.tencent.mm.plugin.appbrand.q.l.vQ(aao)));
a((JSONObject) jSONObject3, "topBarStatus", Boolean.valueOf(this.fdO.fct.fqy));
a((JSONObject) jSONObject3, "referrerInfo", this.fdO.fct.fqA.aef());
a((JSONObject) jSONObject3, "shareInfo", this.fdO.fct.aec());
a((JSONObject) jSONObject3, "isSticky", Boolean.valueOf(this.fdO.fct.fqy));
com.tencent.mm.plugin.appbrand.report.a.e.a(this.fdO, jSONObject3);
Object jSONObject4 = new JSONObject();
try {
a((JSONObject) jSONObject4, "template", new JSONArray(appBrandSysConfig.fqK));
} catch (Exception e2) {
}
a((JSONObject) jSONObject4, "maxRequestConcurrent", Integer.valueOf(appBrandSysConfig.fqT));
a((JSONObject) jSONObject4, "maxUploadConcurrent", Integer.valueOf(appBrandSysConfig.fqU));
a((JSONObject) jSONObject4, "maxDownloadConcurrent", Integer.valueOf(appBrandSysConfig.fqV));
a((JSONObject) jSONObject4, "maxWebsocketConnect", Integer.valueOf(appBrandSysConfig.fqW));
a((JSONObject) jSONObject4, "maxWorkerConcurrent", Integer.valueOf(appBrandSysConfig.fqX));
a(jSONObject, "appLaunchInfo", jSONObject3);
a(jSONObject, "wxAppInfo", jSONObject4);
a(jSONObject, "isPluginMiniProgram", Boolean.valueOf(this.fdO.aap()));
jSONObject3 = new JSONObject();
a((JSONObject) jSONObject3, "USER_DATA_PATH", (Object) "wxfile://usr");
a(jSONObject, "env", jSONObject3);
try {
a(jSONObject, "appContactInfo", new JSONObject(bi.aG(this.fdO.fct.fqu, "{}")));
} catch (JSONException e3) {
x.e("MicroMsg.AppBrandService", "generateWxConfig appID(%s) parse clientJsExtInfo(%s) failed e = %s", new Object[]{this.mAppId, r2, e3});
}
a(jSONObject, "accountInfo", this.fdO.fct.aed());
try {
jSONObject.put("envVersion", com.tencent.mm.plugin.appbrand.jsapi.miniprogram_navigator.a.kO(this.fdO.fct.fig).name().toLowerCase());
} catch (Exception e4) {
}
return f(jSONObject);
}
public JSONObject f(JSONObject jSONObject) {
if (this.fdX && getClass() == l.class) {
a(jSONObject, "isIsolateContext", Boolean.valueOf(true));
}
return jSONObject;
}
public final void g(JSONObject jSONObject) {
a(jSONObject, "platform", (Object) "android");
a(jSONObject, "clientVersion", Integer.valueOf(com.tencent.mm.protocal.d.qVN));
a(jSONObject, "nativeBufferEnabled", Boolean.valueOf(this.fdQ.y(com.tencent.mm.plugin.appbrand.g.d.class) != null));
a(jSONObject, "system", "Android " + VERSION.RELEASE);
}
public static void a(JSONObject jSONObject, String str, Object obj) {
try {
jSONObject.put(str, obj);
} catch (Exception e) {
x.e("MicroMsg.AppBrandService", e.getMessage());
}
}
}
|
package sqlite;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SQLite {
private static Connection connection;
private Statement statement;
private PreparedStatement preparedStatement;
private ResultSet resultSet;
public SQLite() throws ClassNotFoundException, SQLException {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:SQLite.db");
statement = connection.createStatement();
initialize();
}
public ResultSet runQuery(String query) throws SQLException {
return statement.executeQuery(query);
}
public void runQueryWithoutReturn(String query) throws SQLException {
statement.execute(query);
}
public PreparedStatement preparedStatement(String query)
throws SQLException {
return connection.prepareStatement(query);
}
private void initialize() throws ClassNotFoundException, SQLException {
if (!checkTable().next())
createData();
}
public void createData() {
createTables();
addUser("John", "McNeil");
addUser("Paul", "Smith");
}
public ResultSet checkTable() throws ClassNotFoundException, SQLException {
return runQuery("SELECT name FROM sqlite_master " +
"WHERE type='table' AND name='user'");
}
public void createTables() throws ClassNotFoundException, SQLException {
runQueryWithoutReturn("CREATE TABLE user(" +
"id integer, " +
"firstName varchar(60), " +
"lastName varchar(60), " +
"primary key(id));"
);
}
public void addUser(String firstName, String lastName)
throws ClassNotFoundException, SQLException {
setPreparedStatement("INSERT INTO user values(?, ?, ?);");
preparedStatementSetString(2, firstName);
preparedStatementSetString(3, lastName);
preparedStatementExecute();
}
public void setPreparedStatement(String query)
throws ClassNotFoundException, SQLException {
preparedStatement = preparedStatement(query);
}
public void preparedStatementSetString(int columnIndex, String value)
throws SQLException {
preparedStatement.setString(columnIndex, value);
}
public void preparedStatementExecute() throws SQLException {
preparedStatement.execute();
}
}
|
package com.mysql.cj.protocol.a;
import com.mysql.cj.conf.PropertyKey;
import com.mysql.cj.protocol.ColumnDefinition;
import com.mysql.cj.protocol.Message;
import com.mysql.cj.protocol.ProtocolEntityFactory;
import com.mysql.cj.protocol.Resultset;
import com.mysql.cj.protocol.ResultsetRow;
import com.mysql.cj.protocol.a.result.ByteArrayRow;
import com.mysql.cj.protocol.a.result.TextBufferRow;
public class TextRowFactory extends AbstractRowFactory implements ProtocolEntityFactory<ResultsetRow, NativePacketPayload> {
public TextRowFactory(NativeProtocol protocol, ColumnDefinition colDefinition, Resultset.Concurrency resultSetConcurrency, boolean canReuseRowPacketForBufferRow) {
this.columnDefinition = colDefinition;
this.resultSetConcurrency = resultSetConcurrency;
this.canReuseRowPacketForBufferRow = canReuseRowPacketForBufferRow;
this.useBufferRowSizeThreshold = protocol.getPropertySet().getMemorySizeProperty(PropertyKey.largeRowSizeThreshold);
this.exceptionInterceptor = protocol.getExceptionInterceptor();
this.valueDecoder = new MysqlTextValueDecoder();
}
public ResultsetRow createFromMessage(NativePacketPayload rowPacket) {
boolean useBufferRow = (this.canReuseRowPacketForBufferRow || this.columnDefinition.hasLargeFields() || rowPacket.getPayloadLength() >= ((Integer)this.useBufferRowSizeThreshold.getValue()).intValue());
if (this.resultSetConcurrency == Resultset.Concurrency.UPDATABLE || !useBufferRow) {
byte[][] rowBytes = new byte[(this.columnDefinition.getFields()).length][];
for (int i = 0; i < (this.columnDefinition.getFields()).length; i++)
rowBytes[i] = rowPacket.readBytes(NativeConstants.StringSelfDataType.STRING_LENENC);
return (ResultsetRow)new ByteArrayRow(rowBytes, this.exceptionInterceptor);
}
return (ResultsetRow)new TextBufferRow(rowPacket, this.columnDefinition, this.exceptionInterceptor, this.valueDecoder);
}
public boolean canReuseRowPacketForBufferRow() {
return this.canReuseRowPacketForBufferRow;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\protocol\a\TextRowFactory.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.