blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
332
content_id
stringlengths
40
40
detected_licenses
listlengths
0
50
license_type
stringclasses
2 values
repo_name
stringlengths
7
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
557 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
77.7k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
82 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
5.41M
extension
stringclasses
11 values
content
stringlengths
7
5.41M
authors
listlengths
1
1
author
stringlengths
0
161
9d02052724b28c0150d26f4cc1e2b04734500be4
f482c5289a57c71b395c8812ca5c8e901b03082d
/Java RPG Project Test/src/com/zaddy/core/Background.java
7de0686c825cc62de8dd4f8fd0e5ca1482d5af50
[]
no_license
zaddypoo/Java-RPG-Game-Project
0dc8d7ae7bd18422e791b72fe968c173ac232255
f354602483f7813f185fff0d80aa7121ed9fa5b9
refs/heads/master
2021-01-01T03:31:15.827991
2016-04-14T12:05:48
2016-04-14T12:05:48
56,126,300
0
0
null
null
null
null
UTF-8
Java
false
false
301
java
package com.zaddy.core; import java.awt.Graphics; import java.awt.Rectangle; public class Background extends Rectangle { public int[] id = { -1, -1 }; public Background(Rectangle rect, int id[]) { setBounds(rect); this.id = id; } public void render(Graphics g) { } }
[ "krazykris47421@gmail.com" ]
krazykris47421@gmail.com
9a7f868ea662cae60379a677f6e306d5c1a1bd13
821082830de806c574bda36f83f0693713885eef
/src/com/edaixi/util/Base64Util.java
860126a358d11d85c5e1a41d5b32c42331bbbf57
[]
no_license
caocf/HpuWashing
a062cf4019cb4c3d8de37a8a8433aa922b8e7ec2
4523f2dcd1f846f3e804819702d8e2e961cdaed5
refs/heads/master
2021-01-21T20:22:36.845197
2015-09-24T09:51:56
2015-09-24T09:51:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,090
java
package com.edaixi.util; import java.io.UnsupportedEncodingException; public class Base64Util { private static char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; private static byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 }; public static String encode(byte[] data) { StringBuffer sb = new StringBuffer(); int len = data.length; int i = 0; int b1, b2, b3; while (i < len) { b1 = data[i++] & 0xff; if (i == len) { sb.append(base64EncodeChars[b1 >>> 2]); sb.append(base64EncodeChars[(b1 & 0x3) << 4]); sb.append("=="); break; } b2 = data[i++] & 0xff; if (i == len) { sb.append(base64EncodeChars[b1 >>> 2]); sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]); sb.append(base64EncodeChars[(b2 & 0x0f) << 2]); sb.append("="); break; } b3 = data[i++] & 0xff; sb.append(base64EncodeChars[b1 >>> 2]); sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]); sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]); sb.append(base64EncodeChars[b3 & 0x3f]); } return sb.toString(); } public static byte[] decode(String str) throws UnsupportedEncodingException { StringBuffer sb = new StringBuffer(); byte[] data = str.getBytes("US-ASCII"); int len = data.length; int i = 0; int b1, b2, b3, b4; while (i < len) { /* b1 */ do { b1 = base64DecodeChars[data[i++]]; } while (i < len && b1 == -1); if (b1 == -1) break; /* b2 */ do { b2 = base64DecodeChars[data[i++]]; } while (i < len && b2 == -1); if (b2 == -1) break; sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4))); /* b3 */ do { b3 = data[i++]; if (b3 == 61) return sb.toString().getBytes("ISO-8859-1"); b3 = base64DecodeChars[b3]; } while (i < len && b3 == -1); if (b3 == -1) break; sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2))); /* b4 */ do { b4 = data[i++]; if (b4 == 61) return sb.toString().getBytes("ISO-8859-1"); b4 = base64DecodeChars[b4]; } while (i < len && b4 == -1); if (b4 == -1) break; sb.append((char) (((b3 & 0x03) << 6) | b4)); } return sb.toString().getBytes("ISO-8859-1"); } }
[ "weichunsheng3611@gmail.com" ]
weichunsheng3611@gmail.com
2b308a9fe56a17116316edc456a811f9fea508ab
80b76e23d429acf8d2e17698f1e191ed2d355069
/app/src/main/java/com/fuicuiedu/idedemo/easyshop_demo/components/AvatarLoadOptions.java
44b44b7526e624650937731cd4e927307d71d257
[]
no_license
junguang00/-
f48a3b2e914a95b4230e7d30985f22d909bf8419
72d674d55b1352ae3701adb6195e63a33097b4ff
refs/heads/master
2020-06-18T12:30:37.789974
2016-11-28T03:17:13
2016-11-28T03:17:13
75,138,266
2
0
null
null
null
null
UTF-8
Java
false
false
1,813
java
package com.fuicuiedu.idedemo.easyshop_demo.components; import com.fuicuiedu.idedemo.easyshop_demo.R; import com.nostra13.universalimageloader.core.DisplayImageOptions; public class AvatarLoadOptions { private AvatarLoadOptions() { } private static DisplayImageOptions options; /** * 用户头像加载选项 */ public static DisplayImageOptions build() { if (options == null) { options = new DisplayImageOptions.Builder() .showImageForEmptyUri(R.drawable.user_ico)/*如果空url显示什么*/ .showImageOnLoading(R.drawable.user_ico)/*加载中显示什么*/ .showImageOnFail(R.drawable.user_ico)/*加载失败显示什么*/ .cacheOnDisk(true)/*开启硬盘缓存*/ .cacheInMemory(true)/*开启内存缓存*/ .resetViewBeforeLoading(true)/*加载前重置ImageView*/ .build(); } return options; } private static DisplayImageOptions options_item; /** * 图片加载选项 */ public static DisplayImageOptions build_item() { if (options_item == null) { options_item = new DisplayImageOptions.Builder() .showImageForEmptyUri(R.drawable.image_error)/*如果空url显示什么*/ .showImageOnLoading(R.drawable.image_loding)/*加载中显示什么*/ .showImageOnFail(R.drawable.image_error)/*加载失败显示什么*/ .cacheOnDisk(true)/*开启硬盘缓存*/ .cacheInMemory(true)/*开启内存缓存*/ .resetViewBeforeLoading(true)/*加载前重置ImageView*/ .build(); } return options_item; } }
[ "wxcican@qq.com" ]
wxcican@qq.com
6e8efe0116867946f2a79b893a06709f90ba11e2
3a761065fbec236406c29a6fa88684d58ad7c9ec
/src/main/java/com/lulan/shincolle/client/gui/GuiDesk.java
5ebca88aa78158ce7129a4cc7af67e43cb8058a6
[]
no_license
PinkaLulan/ShinColle
f6a84152d5224ac8ef3a055e9a593e9322c751f3
a576df79ac47afb67ee94c33dc38f3fc923a48e3
refs/heads/mc-1.12.2
2021-01-24T09:09:29.392613
2018-09-02T11:29:31
2018-09-02T11:31:17
24,890,170
92
78
null
2020-05-15T04:37:17
2014-10-07T12:56:52
Java
UTF-8
Java
false
false
72,591
java
package com.lulan.shincolle.client.gui; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import com.lulan.shincolle.capability.CapaTeitoku; import com.lulan.shincolle.client.gui.inventory.ContainerDesk; import com.lulan.shincolle.crafting.ShipCalc; import com.lulan.shincolle.entity.BasicEntityMount; import com.lulan.shincolle.entity.BasicEntityShip; import com.lulan.shincolle.network.C2SGUIPackets; import com.lulan.shincolle.network.C2SInputPackets; import com.lulan.shincolle.proxy.ClientProxy; import com.lulan.shincolle.proxy.CommonProxy; import com.lulan.shincolle.reference.Enums; import com.lulan.shincolle.reference.ID; import com.lulan.shincolle.reference.Reference; import com.lulan.shincolle.reference.Values; import com.lulan.shincolle.team.TeamData; import com.lulan.shincolle.tileentity.TileEntityDesk; import com.lulan.shincolle.utility.CalcHelper; import com.lulan.shincolle.utility.EntityHelper; import com.lulan.shincolle.utility.GuiHelper; import com.lulan.shincolle.utility.LogHelper; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiTextField; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.GlStateManager.DestFactor; import net.minecraft.client.renderer.GlStateManager.SourceFactor; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.resources.I18n; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.TextFormatting; /** admiral's desk * * type: * 0: open GUI with TileEntity * 1: open GUI with radar item * 2: open GUI with book item * * function: * 0: no function * 1: radar * 2: book * 3: fleet manage * 4: target selector * */ public class GuiDesk extends GuiContainer { private static final ResourceLocation guiTexture = new ResourceLocation(Reference.TEXTURES_GUI+"GuiDesk.png"); private static final ResourceLocation guiRadar = new ResourceLocation(Reference.TEXTURES_GUI+"GuiDeskRadar.png"); private static final ResourceLocation guiBook = new ResourceLocation(Reference.TEXTURES_GUI+"GuiDeskBook.png"); private static final ResourceLocation guiBook2 = new ResourceLocation(Reference.TEXTURES_GUI+"GuiDeskBook2.png"); private static final ResourceLocation guiTeam = new ResourceLocation(Reference.TEXTURES_GUI+"GuiDeskTeam.png"); private static final ResourceLocation guiTarget = new ResourceLocation(Reference.TEXTURES_GUI+"GuiDeskTarget.png"); private static final ResourceLocation guiNameIcon0 = new ResourceLocation(Reference.TEXTURES_GUI+"GuiNameIcon0.png"); private static final ResourceLocation guiNameIcon1 = new ResourceLocation(Reference.TEXTURES_GUI+"GuiNameIcon1.png"); private static final ResourceLocation guiNameIcon2 = new ResourceLocation(Reference.TEXTURES_GUI+"GuiNameIcon2.png"); private TileEntityDesk tile; public int tickGUI; private int xClick, yClick, xMouse, yMouse, tempCD, lastXMouse, lastYMouse; private int guiFunc, type; private float GuiScale, GuiScaleInv; private int[] listNum, listClicked; //list var: 0:radar 1:team 2:target 3:teamAlly 4:teamBan private static final int CLICKCD = 60; private static final int LISTCLICK_RADAR = 0; private static final int LISTCLICK_TEAM = 1; private static final int LISTCLICK_TARGET = 2; private static final int LISTCLICK_ALLY = 3; private static final int LISTCLICK_BAN = 4; private static String StrPos, StrHeight, StrTeamID, StrBreak, StrAlly, StrOK, StrUnban, StrBan, StrCancel, StrAllyList, StrBanList, StrRename, StrDisband, StrCreate, StrNeutral, StrBelong, StrAllied, StrHostile, StrRemove; //player data EntityPlayer player; CapaTeitoku capa; //radar private int radar_zoomLv; //0:256x256 1:64x64 2:16x16 private List<RadarEntity> shipList; //ship list private List<RadarEntity> itemList; //BasicEntityItem list //book private int book_chapNum; private int book_pageNum; //team private int teamState; //team operation state private int listFocus; //list focus private GuiTextField textField; private static final int TEAMSTATE_MAIN = 0; private static final int TEAMSTATE_CREATE = 1; private static final int TEAMSTATE_ALLY = 2; private static final int TEAMSTATE_RENAME = 3; private static final int TEAMSTATE_BAN = 4; //target list Entity targetEntity = null; //entity for model display private ArrayList<String> tarList; //target list private float mScale, mRotateX, mRotateY; //target model parms //ship model BasicEntityShip shipModel = null; BasicEntityMount shipMount = null; private int shipType, shipClass, shipStats, shipMaxStats; private int[][] iconXY = null; //object: ship entity + pixel position private class RadarEntity { public Entity ship; public String name; public double pixelx; //included guiLeft/guiTop distance public double pixely; public double pixelz; public int posX; //entity position public int posY; public int posZ; public RadarEntity() {} public RadarEntity(Entity ship) { this.ship = ship; //get name if (((EntityLiving) ship).getCustomNameTag() != null && ((EntityLiving) ship).getCustomNameTag().length() > 0) { name = ((EntityLiving) ship).getCustomNameTag(); } else { name = ship.getName(); } } public RadarEntity(double pixelx, double pixely, double pixelz, int posX, int posY, int posZ) { this.pixelx = pixelx; this.pixely = pixely; this.pixelz = pixelz; this.posX = posX; this.posY = posY; this.posZ = posZ; } } public GuiDesk(EntityPlayer player, TileEntityDesk tile, int type) { super(new ContainerDesk(player, tile, type)); this.type = type; this.tile = tile; this.player = player; this.GuiScale = 1.25F; this.GuiScaleInv = 1F / this.GuiScale; this.xSize = (int) (256 * this.GuiScale); this.ySize = (int) (192 * this.GuiScale); this.lastXMouse = 0; this.lastYMouse = 0; this.tickGUI = 0; //ticks in gui (not game tick) this.tempCD = CLICKCD; //get tile value //open GUI with Tile if (type == 0) { updateDeskValue(); } //open GUI with item else { this.guiFunc = this.type; this.book_chapNum = 0; this.book_pageNum = 0; this.radar_zoomLv = 0; } //player data player = ClientProxy.getClientPlayer(); capa = CapaTeitoku.getTeitokuCapability(player); //list var: 0:radar 1:team 2:target this.listNum = new int[] {0, 0, 0, 0, 0}; this.listClicked = new int[] {-1, -1, -1, -1, -1}; //radar this.shipList = new ArrayList(); this.itemList = new ArrayList(); //team this.teamState = 0; this.listFocus = LISTCLICK_TEAM; //target updateTargetClassList(); this.mScale = 30F; this.mRotateX = 0F; this.mRotateY = -30F; //ship model setShipModel(this.book_chapNum, this.book_pageNum); //add text input field Keyboard.enableRepeatEvents(true); //string StrPos = I18n.format("gui.shincolle:radar.position"); StrHeight = I18n.format("gui.shincolle:radar.height"); StrTeamID = I18n.format("gui.shincolle:team.teamid"); StrBreak = I18n.format("gui.shincolle:team.break"); StrAlly = I18n.format("gui.shincolle:team.ally"); StrOK = I18n.format("gui.shincolle:general.ok"); StrUnban = I18n.format("gui.shincolle:team.unban"); StrBan = I18n.format("gui.shincolle:team.ban"); StrCancel = I18n.format("gui.shincolle:general.cancel"); StrAllyList = I18n.format("gui.shincolle:team.allylist"); StrBanList = I18n.format("gui.shincolle:team.banlist"); StrRename = I18n.format("gui.shincolle:team.rename"); StrDisband = I18n.format("gui.shincolle:team.disband"); StrCreate = I18n.format("gui.shincolle:team.create"); StrNeutral = I18n.format("gui.shincolle:team.neutral"); StrBelong = I18n.format("gui.shincolle:team.belong"); StrAllied = I18n.format("gui.shincolle:team.allied"); StrHostile = I18n.format("gui.shincolle:team.hostile"); StrRemove = I18n.format("gui.shincolle:target.remove"); } //有用到fontRendererObj的必須放在此init @Override public void initGui() { super.initGui(); //textField: font, x, y, width, height this.textField = new GuiTextField(1, this.fontRendererObj, (int)((this.guiLeft+10)*this.GuiScale), (int)((this.guiTop+24)*this.GuiScale), 153, 12); this.textField.setTextColor(-1); //點選文字框時文字顏色 this.textField.setDisabledTextColour(-1); //無點選文字框時文字顏色 this.textField.setEnableBackgroundDrawing(true); //畫出文字框背景 this.textField.setMaxStringLength(64); //接受最大文字長度 this.textField.setEnabled(false); this.textField.setFocused(false); } private void updateDeskValue() { this.guiFunc = this.tile.getField(0); this.book_chapNum = this.tile.getField(1); this.book_pageNum = this.tile.getField(2); this.radar_zoomLv = this.tile.getField(3); } //get new mouseX,Y and redraw gui @Override public void drawScreen(int mouseX, int mouseY, float f) { GlStateManager.pushMatrix(); GlStateManager.scale(this.GuiScale, this.GuiScale, 1F); super.drawScreen(mouseX, mouseY, f); GlStateManager.popMatrix(); //update GUI var xMouse = mouseX; yMouse = mouseY; tickGUI += 1; if (this.tempCD > 0) tempCD--; //draw GUI text input GlStateManager.pushMatrix(); GlStateManager.disableLighting(); GlStateManager.disableBlend(); if (this.teamState == TEAMSTATE_CREATE || this.teamState == TEAMSTATE_RENAME) { this.textField.setEnabled(true); this.textField.drawTextBox(); } else { this.textField.setEnabled(false); } GlStateManager.popMatrix(); } //draw tooltip private void handleHoveringText() { int x2 = (int) (xMouse * this.GuiScaleInv); int y2 = (int) (yMouse * this.GuiScaleInv); int mx = x2 - guiLeft; int my = y2 - guiTop; //draw ship name on light spot in radar function switch (this.guiFunc) { case 1: /** radar */ //draw ship name List list = new ArrayList(); for (RadarEntity obj : this.shipList) { Entity ship = null; if (obj != null) { //mouse point at light spot icon if (x2 < obj.pixelx+4 && x2 > obj.pixelx-2 && y2 < obj.pixelz+4 && y2 > obj.pixelz-2) { ship = obj.ship; } } if (ship != null) { String strName = obj.name; list.add(strName); //add string to draw list } }//end for all obj in shipList //draw BasicEntityItem list for (RadarEntity obj : this.itemList) { if (obj != null) { //mouse point at light spot icon if (x2 < obj.pixelx+4 && x2 > obj.pixelx-2 && y2 < obj.pixelz+4 && y2 > obj.pixelz-2) { String strCoord = String.valueOf(obj.posX) + ", " + String.valueOf(obj.posY) + ", " + String.valueOf(obj.posZ); list.add(strCoord); } } }//end for all obj in shipList drawHoveringText(list, mx, my, this.fontRendererObj); break; //end radar case 2: /** book */ int getbtn = GuiHelper.getButton(ID.Gui.ADMIRALDESK, 2, mx, my); //get chap text if (getbtn > 1 && getbtn < 9) { getbtn -= 2; String strChap = I18n.format("gui.shincolle:book.chap"+getbtn+".title"); List list2 = CalcHelper.stringConvNewlineToList(strChap); int strLen = this.fontRendererObj.getStringWidth(strChap); drawHoveringText(list2, mx-strLen-20, my, this.fontRendererObj); } //get item text else { int id = GuiBook.getIndexID(this.book_chapNum, this.book_pageNum); List<int[]> cont = Values.BookList.get(id); if (cont != null) { for (int[] getc : cont) { if (getc != null && getc.length == 5 && getc[0] == 2 && (getc[1] == GuiBook.PageLeftCurrent || getc[1] == GuiBook.PageRightCurrent)) { int xa = getc[2] + GuiBook.Page0LX - 1; //at left page if ((getc[1] & 1) == 1) xa = getc[2] + GuiBook.Page0RX - 1; //at right page int xb = xa + 16; int ya = getc[3] + GuiBook.Page0Y; int yb = ya + 16; ItemStack item = GuiBook.getItemStackForIcon(getc[4]); if (mx > xa-1 && mx < xb+1 && my > ya-1 && my < yb+1) { this.renderToolTip(item, mx, my); break; } } }//end for book content }//end if book content } break; //end book }//end func switch } //GUI前景: 文字 @Override protected void drawGuiContainerForegroundLayer(int i, int j) { //draw ship data in radar function switch (this.guiFunc) { case 1: //radar drawRadarText(); break; //end radar case 2: //book boolean canDrawText = true; //chap 4,5,6, check list first if (this.book_pageNum > 0) { if (this.book_chapNum == 4 || this.book_chapNum == 5) { //set draw model if (this.shipModel == null) { canDrawText = false; } //draw page number String str = "No. "+this.book_pageNum; int strlen = (int)(fontRendererObj.getStringWidth(str) * 0.5F); fontRendererObj.drawStringWithShadow(str, 55, 32, this.book_chapNum == 4 ? Enums.EnumColors.RED_DARK.getValue() : Enums.EnumColors.CYAN.getValue()); } else if (this.book_chapNum == 6) { //TODO } } if (canDrawText) GuiBook.drawBookContent(this, this.fontRendererObj, this.book_chapNum, this.book_pageNum); break; case 3: //team drawTeamText(); break; //end team case 4: //target drawTargetText(); break; //end target } //畫出tooltip handleHoveringText(); } //GUI背景: 背景圖片 @Override protected void drawGuiContainerBackgroundLayer(float par1,int par2, int par3) { //reset color GlStateManager.color(1F, 1F, 1F, 1F); Minecraft.getMinecraft().getTextureManager().bindTexture(guiTexture); //若gui貼圖不為256x256, 則使用以下兩個方法畫貼圖 //func_146110_a(x, y, u, v, xSize, ySize, textXSize, textYSize) //func_152125_a(x, y, u, v, xSize, ySize, drawXSize, drawYSize textXSize, textYSize) if (this.type == 0) { drawTexturedModalRect(guiLeft, guiTop, 0, 0, 256, 192); //get new value updateDeskValue(); //畫出功能按鈕 switch (this.guiFunc) { case 1: //radar drawTexturedModalRect(guiLeft+3, guiTop+2, 0, 192, 16, 16); break; case 2: //book drawTexturedModalRect(guiLeft+22, guiTop+2, 16, 192, 16, 16); break; case 3: //team drawTexturedModalRect(guiLeft+41, guiTop+2, 32, 192, 16, 16); break; case 4: //target drawTexturedModalRect(guiLeft+60, guiTop+2, 48, 192, 16, 16); break; } } //畫出功能介面 switch (this.guiFunc) { case 1: //radar //background Minecraft.getMinecraft().getTextureManager().bindTexture(guiRadar); drawTexturedModalRect(guiLeft, guiTop, 0, 0, 256, 192); //draw zoom level button int texty = 192; switch (this.radar_zoomLv) { case 1: texty = 200; break; case 2: texty = 208; break; } drawTexturedModalRect(guiLeft+9, guiTop+160, 24, texty, 44, 8); //draw ship clicked circle if (this.listClicked[LISTCLICK_RADAR] > -1 && this.listClicked[LISTCLICK_RADAR] < 5) { int cirY = 25 + this.listClicked[LISTCLICK_RADAR] * 32; drawTexturedModalRect(guiLeft+142, guiTop+cirY, 68, 192, 108, 31); } //draw radar ship icon drawRadarIcon(); //draw morale icon drawMoraleIcon(); break; //end radar case 2: //book //background Minecraft.getMinecraft().getTextureManager().bindTexture(guiBook); drawTexturedModalRect(guiLeft, guiTop, 0, 0, 256, 192); //if mouse on page button, change button color if (xMouse < guiLeft + 137 * this.GuiScale) { drawTexturedModalRect(guiLeft+53, guiTop+182, 0, 192, 18, 10); } else { drawTexturedModalRect(guiLeft+175, guiTop+182, 0, 202, 18, 10); } //draw ship model if chap = 4,5 if (this.book_pageNum > 0 && (this.book_chapNum == 4 || this.book_chapNum == 5)) { drawShipModel(); } break; //end book case 3: //team //background Minecraft.getMinecraft().getTextureManager().bindTexture(guiTeam); drawTexturedModalRect(guiLeft, guiTop, 0, 0, 256, 192); drawTeamPic(); break; //end team case 4: //target //background Minecraft.getMinecraft().getTextureManager().bindTexture(guiTarget); drawTexturedModalRect(guiLeft, guiTop, 0, 0, 256, 192); //draw ship clicked circle if (this.listClicked[LISTCLICK_TARGET] > -1 && this.listClicked[LISTCLICK_TARGET] < 13) { int cirY = 25 + this.listClicked[LISTCLICK_TARGET] * 12; drawTexturedModalRect(guiLeft+142, guiTop+cirY, 68, 192, 108, 31); } //draw target model drawTargetModel(); break; //end target }//end switch } //mouse input @Override public void handleMouseInput() throws IOException { super.handleMouseInput(); int wheel = Mouse.getEventDWheel(); //scroll down if (wheel < 0) { handleWheelMove(false); } //scroll up else if (wheel > 0) { handleWheelMove(true); } } //handle mouse wheel move private void handleWheelMove(boolean isWheelUp) { //get list size int listSize = 0; int listID = -1; switch (this.guiFunc) { case 1: //radar listSize = this.shipList.size(); listID = LISTCLICK_RADAR; break; case 2: //book if (isWheelUp) { this.mScale += 2F; if(this.mScale > 200F) this.mScale = 200F; } else { this.mScale -= 2F; if(this.mScale < 5F) this.mScale = 5F; } break; case 3: //team //right side: team list if (xMouse - guiLeft > 138) { if (this.capa.getPlayerTeamDataMap() != null) { listSize = this.capa.getPlayerTeamDataMap().size(); listID = LISTCLICK_TEAM; } } //left side: ally list else { if (this.teamState == TEAMSTATE_ALLY && this.capa.getPlayerTeamAllyList() != null) { listSize = this.capa.getPlayerTeamAllyList().size(); listID = LISTCLICK_ALLY; } else if (this.teamState == TEAMSTATE_BAN && this.capa.getPlayerTeamBannedList() != null) { listSize = this.capa.getPlayerTeamBannedList().size(); listID = LISTCLICK_BAN; } } break; case 4: //target if (xMouse - guiLeft > 190) { listSize = this.tarList.size(); listID = LISTCLICK_TARGET; } else { if (isWheelUp) { this.mScale += 4F; if(this.mScale > 200F) this.mScale = 200F; } else { this.mScale -= 4F; if(this.mScale < 5F) this.mScale = 5F; } } break; }//end switch if (listID < 0) return; if (isWheelUp) { listClicked[listID]++; listNum[listID]--; if (listNum[listID] < 0) { listNum[listID] = 0; listClicked[listID]--; //捲過頭, 補回1 } } else { if (listSize > 0) { listClicked[listID]--; listNum[listID]++; if (listNum[listID] > listSize - 1) { listNum[listID] = listSize - 1; listClicked[listID]++; } if (listNum[listID] < 0) { listNum[listID] = 0; listClicked[listID]++; //捲過頭, 補回1 } } } } //handle mouse click, @parm posX, posY, mouseKey (0:left 1:right 2:middle 3:...etc) @Override protected void mouseClicked(int posX, int posY, int mouseKey) throws IOException { super.mouseClicked(posX, posY, mouseKey); //set focus for textField, CHECK BEFORE GUI SCALE!! this.textField.mouseClicked(posX, posY, mouseKey); //gui scale posX = (int)(posX * this.GuiScaleInv); posY = (int)(posY * this.GuiScaleInv); xClick = posX - this.guiLeft; yClick = posY - this.guiTop; //match all pages if (this.type == 0) { int getFunc = GuiHelper.getButton(ID.Gui.ADMIRALDESK, 0, xClick, yClick); setDeskFunction(getFunc); } //match radar page switch (this.guiFunc) { case 1: //radar int radarBtn = GuiHelper.getButton(ID.Gui.ADMIRALDESK, 1, xClick, yClick); switch (radarBtn) { case 0: //radar scale this.radar_zoomLv++; if (this.radar_zoomLv > 2) this.radar_zoomLv = 0; break; case 1: //ship slot 0~5 case 2: case 3: case 4: case 5: int oldClick = this.listClicked[LISTCLICK_RADAR]; this.listClicked[LISTCLICK_RADAR] = radarBtn - 1; //if click same slot, open ship GUI if (oldClick == this.listClicked[LISTCLICK_RADAR]) this.openShipGUI(); break; }//end switch break; //end radar case 2: //book int getbtn2 = -1; if (this.book_chapNum == 4 || this.book_chapNum == 5) { getbtn2 = GuiHelper.getButton(ID.Gui.ADMIRALDESK, 5, xClick, yClick); //protected area for model state buttons if (getbtn2 < 0 && xClick > 15 && xClick < 115 && yClick > 150 && yClick < 180) { getbtn2 = 0; } } //get no button in ch5, check ch2 button if(getbtn2 < 0) { int getbtn = GuiHelper.getButton(ID.Gui.ADMIRALDESK, 2, xClick, yClick); switch (getbtn) { case 0: //left if (mouseKey == 0) { this.book_pageNum--; } else { this.book_pageNum -= 10; } if (this.book_pageNum < 0) this.book_pageNum = 0; setShipModel(this.book_chapNum, this.book_pageNum); LogHelper.debug("DEBUG: desk: book page: "+book_pageNum); break; case 1: //right if (mouseKey == 0) { this.book_pageNum++; } else { this.book_pageNum += 10; } if (this.book_pageNum > GuiBook.getMaxPageNumber(book_chapNum)) { this.book_pageNum = GuiBook.getMaxPageNumber(book_chapNum); } setShipModel(this.book_chapNum, this.book_pageNum); LogHelper.debug("DEBUG: desk: book page: "+book_pageNum); break; case 2: //chap 0 case 3: //chap 1 case 4: //chap 2 case 5: //chap 3 case 6: //chap 4 case 7: //chap 5 case 8: //chap 6 this.book_chapNum = getbtn - 2; this.book_pageNum = 0; LogHelper.debug("DEBUG: desk: book chap: "+book_chapNum); break; } } //get ship model button else { if (this.shipModel != null) { switch (getbtn2) { case 0: //ship model break; case 1: //sit this.shipModel.setSitting(!this.shipModel.isSitting()); //roll Emotion if (this.shipModel.getRNG().nextInt(2) == 0) { this.shipModel.setStateEmotion(ID.S.Emotion, ID.Emotion.BORED, false); } else { this.shipModel.setStateEmotion(ID.S.Emotion, ID.Emotion.NORMAL, false); } //roll Emotion4 if (this.shipModel.getRNG().nextInt(2) == 0) { this.shipModel.setStateEmotion(ID.S.Emotion4, ID.Emotion.BORED, false); } else { this.shipModel.setStateEmotion(ID.S.Emotion4, ID.Emotion.NORMAL, false); } break; case 2: //run this.shipModel.setSprinting(!this.shipModel.isSprinting()); if (this.shipMount != null) this.shipMount.setSprinting(this.shipModel.isSprinting()); break; case 3: //attack this.shipModel.setAttackTick(50); this.shipModel.setStateEmotion(ID.S.Phase, this.shipModel.getRNG().nextInt(4), false); if (this.shipMount != null) this.shipMount.setAttackTick(50); break; case 4: //emotion //roll Emotion4 if (this.shipModel.getRNG().nextInt(2) == 0) { this.shipModel.setStateEmotion(ID.S.Emotion4, ID.Emotion.BORED, false); } else { this.shipModel.setStateEmotion(ID.S.Emotion4, ID.Emotion.NORMAL, false); } //roll sneaking this.shipModel.setSneaking(this.shipModel.getRNG().nextInt(5) == 0); //roll Emotion/NoFuel if (this.shipModel.getRNG().nextInt(8) == 0) { this.shipModel.setStateFlag(ID.F.NoFuel, true); } else { this.shipModel.setStateFlag(ID.F.NoFuel, false); this.shipModel.setStateEmotion(ID.S.Emotion, this.shipModel.getRNG().nextInt(10), false); if (this.shipMount != null) this.shipMount.setStateEmotion(ID.S.Emotion, this.shipMount.getRNG().nextInt(10), false); } break; case 5: //model state 1~16 case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20: this.shipModel.setStateEmotion(ID.S.State, this.shipModel.getStateEmotion(ID.S.State) ^ Values.N.Pow2[getbtn2-5], false); //set mounts if (this.shipModel.hasShipMounts()) this.setShipMount(); break; }//end switch }//end get ship model }//end get ship model page button break; //end book case 3: //team int teamBtn = GuiHelper.getButton(ID.Gui.ADMIRALDESK, 3, xClick, yClick); switch (teamBtn) { case 0: //left top button switch (this.teamState) { case TEAMSTATE_MAIN: handleClickTeamMain(0); break; case TEAMSTATE_ALLY: handleClickTeamAlly(0); break; case TEAMSTATE_BAN: handleClickTeamBan(0); break; case TEAMSTATE_CREATE: handleClickTeamCreate(0); break; case TEAMSTATE_RENAME: handleClickTeamRename(0); break; }//end switch break; case 1: //team slot 0~4 case 2: case 3: case 4: case 5: this.listFocus = LISTCLICK_TEAM; this.listClicked[LISTCLICK_TEAM] = teamBtn - 1; break; case 6: //left bottom button switch (this.teamState) { case TEAMSTATE_MAIN: handleClickTeamMain(1); break; case TEAMSTATE_ALLY: handleClickTeamAlly(1); break; case TEAMSTATE_BAN: handleClickTeamBan(1); break; case TEAMSTATE_CREATE: handleClickTeamCreate(1); break; case TEAMSTATE_RENAME: handleClickTeamRename(1); break; } break; case 7: //right top button switch (this.teamState) { case TEAMSTATE_MAIN: handleClickTeamMain(2); break; } break; case 8: //right bottom button switch (this.teamState) { case TEAMSTATE_MAIN: handleClickTeamMain(3); break; } break; case 9: case 10: case 11: switch (this.teamState) { case TEAMSTATE_ALLY: this.listFocus = LISTCLICK_ALLY; this.listClicked[LISTCLICK_ALLY] = teamBtn - 9; break; case TEAMSTATE_BAN: this.listFocus = LISTCLICK_BAN; this.listClicked[LISTCLICK_BAN] = teamBtn - 9; break; } break; }//end switch break; //end team case 4: //target //update target list updateTargetClassList(); int targetBtn = GuiHelper.getButton(ID.Gui.ADMIRALDESK, 4, xClick, yClick); switch (targetBtn) { case 0: //remove target int clicked = this.listNum[LISTCLICK_TARGET]+this.listClicked[LISTCLICK_TARGET]; if (clicked >= 0 && clicked < this.tarList.size()) { String tarstr = this.tarList.get(clicked); LogHelper.debug("DEBUG: desk: remove target class: "+tarstr); //remove clicked target CommonProxy.channelG.sendToServer(new C2SGUIPackets(player, C2SGUIPackets.PID.SetTarClass, tarstr)); } break; case 1: //target slot case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: this.listClicked[LISTCLICK_TARGET] = targetBtn - 1; getEntityByClick(); break; }//end switch break; //end target }//end switch syncTileEntityC2S(); } @Override protected void mouseClickMove(int mx, int my, int button, long time) { super.mouseClickMove(mx, my, button, time); int dx = mx - this.lastXMouse; int dy = my - this.lastYMouse; this.lastXMouse = mx; this.lastYMouse = my; if (dx > 20 || dx < -20 || dy > 20 || dy < -20) return; int gx = (int) (mx * this.GuiScaleInv - this.guiLeft); int gy = (int) (my * this.GuiScaleInv - this.guiTop); //func: target list if (this.guiFunc == 4 || this.guiFunc == 2) { if (gx > 8 && gx < 117 && gy > 47 && gy < 154) { if (dx > 0) { this.mRotateY += dx * 3F; } if (dx < 0) { this.mRotateY += dx * 3F; } if (dy > 0) { this.mRotateX += dy * 2F; if(this.mRotateX > 90F) this.mRotateX = 90F; } if (dy < 0) { this.mRotateX += dy * 2F; if(this.mRotateX < -90F) this.mRotateX = -90F; } } } } private void setDeskFunction(int button) { if (button >= 0) { if(this.guiFunc != button+1) { this.guiFunc = button+1; LogHelper.debug("DEBUG: GUI click: desk: click function button"); } else { this.guiFunc = 0; } syncTileEntityC2S(); } } //client to server sync private void syncTileEntityC2S() { if (this.type == 0) { this.tile.setField(0, this.guiFunc); this.tile.setField(1, this.book_chapNum); this.tile.setField(2, this.book_pageNum); this.tile.setField(3, this.radar_zoomLv); this.tile.sendSyncPacketC2S(); } } //draw light spot in radar screen private void drawRadarIcon() { if (this.capa != null) { List<Integer> ships = capa.getShipEIDList(); //icon setting GlStateManager.enableBlend(); GlStateManager.blendFunc(SourceFactor.SRC_ALPHA, DestFactor.ONE_MINUS_SRC_ALPHA); Entity ship; double ox = 0D; double oy = 0D; double oz = 0D; int dx = 0; int dy = 0; int dz = 0; int id = 0; this.shipList = new ArrayList(); this.itemList = new ArrayList(); //set origin position if (this.type == 0) { ox = this.tile.getPos().getX(); oy = this.tile.getPos().getY(); oz = this.tile.getPos().getZ(); } else { ox = this.player.posX; oy = this.player.posY; oz = this.player.posZ; } //get scale factor float radarScale = 1F; //256x256: scale = 0.5 pixel = 1 block switch (this.radar_zoomLv) { case 1: //64x64 radarScale = 2; break; case 2: //16x16 radarScale = 4; break; } //for all ships in ship list for (int eid : ships) { RadarEntity getent = null; double px = -1; double py = -1; double pz = -1; //get ship position if (eid > 0) { ship = EntityHelper.getEntityByID(eid, 0, true); if (ship != null) { getent = new RadarEntity(ship); px = ship.posX; py = ship.posY; pz = ship.posZ; } } else { continue; } //draw ship icon on the radar if (py > 0) { //change ship position to radar position //zoom lv 0: 128x128: 1 pixel = 1 block //zoom lv 1: 64x64: 2 pixel = 1 block //zoom lv 2: 32x32: 4 pixel = 1 block px -= ox; py -= oy; pz -= oz; //scale distance px *= radarScale; py *= radarScale; pz *= radarScale; //radar display distance limit = 64 pixels if ((int)px > 64) px = 64; if ((int)px < -64) px = -64; if ((int)pz > 64) pz = 64; if ((int)pz < -64) pz = -64; //add ship to shiplist getent.pixelx = guiLeft + 69 + px; getent.pixely = py; getent.pixelz = guiTop + 88 + pz; this.shipList.add(getent); //select icon int sIcon = 0; if (MathHelper.abs((int)px) > 48 || MathHelper.abs((int)pz) > 48) { sIcon = (int)(this.tickGUI * 0.125F + 6) % 8 * 3; } else if (MathHelper.abs((int)px) > 32 || MathHelper.abs((int)pz) > 32) { sIcon = (int)(this.tickGUI * 0.125F + 4) % 8 * 3; } else if (MathHelper.abs((int)px) > 16 || MathHelper.abs((int)pz) > 16) { sIcon = (int)(this.tickGUI * 0.125F + 2) % 8 * 3; } else { sIcon = (int)(this.tickGUI * 0.125F) % 8 * 3; } //draw icon by radar zoom level, radar center = [70,89] if (id == this.listNum[LISTCLICK_RADAR] + this.listClicked[LISTCLICK_RADAR]) { GlStateManager.color(1F, 0F, 0F, 1F); drawTexturedModalRect(guiLeft+69+(int)px, guiTop+88+(int)pz, 0, 192, 3, 3); } else { GlStateManager.color(1F, 0.684F, 0.788F, 1F); drawTexturedModalRect(guiLeft+69+(int)px, guiTop+88+(int)pz, sIcon, 192, 3, 3); } id++; }//end y position > 0 }//end for all ship //draw BasicEntityItem list if (CommonProxy.entityItemList != null && CommonProxy.entityItemList.length > 1) { int entlen = CommonProxy.entityItemList.length / 3; for (int i = 0; i < entlen; i++) { double px = CommonProxy.entityItemList[i * 3]; double py = CommonProxy.entityItemList[i * 3 + 1]; double pz = CommonProxy.entityItemList[i * 3 + 2]; int posX = MathHelper.ceil(px); int posY = MathHelper.ceil(py); int posZ = MathHelper.ceil(pz); //change ship position to radar position //zoom lv 0: 128x128: 1 pixel = 1 block //zoom lv 1: 64x64: 2 pixel = 1 block //zoom lv 2: 32x32: 4 pixel = 1 block px -= ox; py -= oy; pz -= oz; //scale distance px *= radarScale; py *= radarScale; pz *= radarScale; //radar display distance limit = 64 pixels if ((int)px > 64) px = 64; if ((int)px < -64) px = -64; if ((int)pz > 64) pz = 64; if ((int)pz < -64) pz = -64; //add ship to shiplist RadarEntity getent = new RadarEntity(guiLeft + 69 + px, py, guiTop + 88 + pz, posX, posY, posZ); this.itemList.add(getent); //select icon int sIcon = 0; if (MathHelper.abs((int)px) > 48 || MathHelper.abs((int)pz) > 48) { sIcon = (int)(this.tickGUI * 0.125F + 6) % 8 * 3; } else if (MathHelper.abs((int)px) > 32 || MathHelper.abs((int)pz) > 32) { sIcon = (int)(this.tickGUI * 0.125F + 4) % 8 * 3; } else if (MathHelper.abs((int)px) > 16 || MathHelper.abs((int)pz) > 16) { sIcon = (int)(this.tickGUI * 0.125F + 2) % 8 * 3; } else { sIcon = (int)(this.tickGUI * 0.125F) % 8 * 3; } //draw icon by radar zoom level, radar center = [70,89] GlStateManager.color(0F, 1F, 1F, 1F); drawTexturedModalRect(guiLeft+69+(int)px, guiTop+88+(int)pz, sIcon, 192, 3, 3); } } GlStateManager.color(1F, 1F, 1F, 1F); GlStateManager.disableBlend(); }//end get player }//end draw radar icon //draw morale icon private void drawMoraleIcon() { Minecraft.getMinecraft().getTextureManager().bindTexture(guiNameIcon0); //draw ship list if (this.shipList != null) { int texty = 37; for (int i = this.listNum[LISTCLICK_RADAR]; i < shipList.size() && i < this.listNum[LISTCLICK_RADAR] + 5; ++i) { //get ship RadarEntity s = shipList.get(i); if (s != null && s.ship instanceof BasicEntityShip) { BasicEntityShip s2 = (BasicEntityShip) s.ship; int ix = 44; switch (EntityHelper.getMoraleLevel(s2.getMorale())) { case ID.Morale.Excited: ix = 0; break; case ID.Morale.Happy: ix = 11; break; case ID.Morale.Normal: ix = 22; break; case ID.Morale.Tired: ix = 33; break; } drawTexturedModalRect(guiLeft+237, guiTop+texty-1, ix, 240, 11, 11); } texty += 32; } } } //draw ship text in radar screen private void drawRadarText() { String str, str2; RadarEntity s; BasicEntityShip s2; int texty = 27; //draw ship list in radar for (int i = this.listNum[LISTCLICK_RADAR]; i < shipList.size() && i < this.listNum[LISTCLICK_RADAR] + 5; ++i) { //get ship position s = shipList.get(i); if (s != null && s.ship instanceof BasicEntityShip) { s2 = (BasicEntityShip) s.ship; //draw name fontRendererObj.drawString(s.name, 147, texty, Enums.EnumColors.WHITE.getValue()); texty += 12; //draw pos str = "LV " + TextFormatting.YELLOW + s2.getLevel() + " " + TextFormatting.GOLD + (int)s2.getHealth() + TextFormatting.RED + " / " + (int)s2.getMaxHealth(); str2 = StrPos + " " + TextFormatting.YELLOW + MathHelper.ceil(s.ship.posX) + " , " + MathHelper.ceil(s.ship.posZ) + " " + TextFormatting.LIGHT_PURPLE + StrHeight + " " + TextFormatting.YELLOW + (int)(s.ship.posY); GlStateManager.pushMatrix(); GlStateManager.scale(0.8F, 0.8F, 1F); fontRendererObj.drawString(str, 184, (int)(texty*1.25F), Enums.EnumColors.CYAN.getValue()); texty += 9; fontRendererObj.drawString(str2, 184, (int)(texty*1.25F), Enums.EnumColors.PURPLE_LIGHT.getValue()); texty += 11; GlStateManager.popMatrix(); } } } //draw team text private void drawTeamPic() { int cirY = 0; //draw team select circle if (this.listFocus == LISTCLICK_TEAM && this.listClicked[LISTCLICK_TEAM] > -1 && this.listClicked[LISTCLICK_TEAM] < 5) { cirY = 25 + this.listClicked[LISTCLICK_TEAM] * 32; drawTexturedModalRect(guiLeft+142, guiTop+cirY, 0, 192, 108, 31); } //draw ally select circle else if (this.listFocus == LISTCLICK_ALLY && this.listClicked[LISTCLICK_ALLY] > -1 && this.listClicked[LISTCLICK_ALLY] < 3) { cirY = 61 + this.listClicked[LISTCLICK_ALLY] * 31; drawTexturedModalRect(guiLeft+6, guiTop+cirY, 109, 192, 129, 31); } //draw ban select circle else if (this.listFocus == LISTCLICK_BAN && this.listClicked[LISTCLICK_BAN] > -1 && this.listClicked[LISTCLICK_BAN] < 3) { cirY = 61 + this.listClicked[LISTCLICK_BAN] * 31; drawTexturedModalRect(guiLeft+6, guiTop+cirY, 109, 192, 129, 31); } } //draw team text private void drawTeamText() { //null check if (this.capa == null) return; String str = null; TeamData tdata = null; //draw team name and id if (this.capa.hasTeam()) { tdata = this.capa.getPlayerTeamData(this.capa.getPlayerUID()); if (tdata != null) { GlStateManager.pushMatrix(); GlStateManager.scale(0.8F, 0.8F, 0.8F); //draw team id str = TextFormatting.GRAY + StrTeamID +": "+ TextFormatting.YELLOW + this.capa.getPlayerUID() +" : "+ TextFormatting.LIGHT_PURPLE + tdata.getTeamLeaderName(); fontRendererObj.drawString(str, 11, 34, 0); //org pos: 11,42 //draw team name str = TextFormatting.WHITE + tdata.getTeamName(); fontRendererObj.drawSplitString(str, 11, 44, 160, 0); GlStateManager.popMatrix(); } } //draw button text String strLT = null; String strLB = null; String strRT = null; String strRB = null; int colorLT = Enums.EnumColors.WHITE.getValue(); int colorLB = colorLT; int colorRT = colorLT; int colorRB = colorLT; //get button string switch (this.teamState) { case TEAMSTATE_ALLY: if (this.tempCD > 0) { strLT = String.valueOf((int)(tempCD * 0.05F)); colorLT = Enums.EnumColors.GRAY_LIGHT.getValue(); } else { int clicki = -1; List tlist = null; //clicked team list clicki = listClicked[LISTCLICK_TEAM] + this.listNum[LISTCLICK_TEAM]; tlist = this.capa.getPlayerTeamDataList(); //get clicked team id if (this.listFocus == LISTCLICK_TEAM && tlist != null && clicki >= 0 && clicki < tlist.size()) { TeamData getd = (TeamData) tlist.get(clicki); if (getd != null) { //is ally, show break button if (this.capa.getPlayerUID() != getd.getTeamID() && this.capa.isTeamAlly(getd.getTeamID())) { strLT = StrBreak; colorLT = Enums.EnumColors.YELLOW.getValue(); } //not ally, show ally button else { strLT = StrAlly; colorLT = Enums.EnumColors.CYAN.getValue(); } } } //clicked ally list? else if (this.listFocus == LISTCLICK_ALLY) { clicki = listClicked[LISTCLICK_ALLY] + this.listNum[LISTCLICK_ALLY]; tlist = this.capa.getPlayerTeamAllyList(); //has clicked ally if (tlist != null && clicki >= 0 && clicki < tlist.size()) { strLT = StrBreak; colorLT = Enums.EnumColors.YELLOW.getValue(); } } }//end btn cd strLB = StrOK; colorLB = Enums.EnumColors.WHITE.getValue(); break; case TEAMSTATE_BAN: if (this.tempCD > 0) { strLT = String.valueOf((int)(tempCD * 0.05F)); colorLT = Enums.EnumColors.GRAY_LIGHT.getValue(); } else { int clicki2 = -1; List tlist2 = null; //clicked team list clicki2 = listClicked[LISTCLICK_TEAM] + this.listNum[LISTCLICK_TEAM]; tlist2 = this.capa.getPlayerTeamDataList(); //get clicked team id if (this.listFocus == LISTCLICK_TEAM && tlist2 != null && clicki2 >= 0 && clicki2 < tlist2.size()) { TeamData getd = (TeamData) tlist2.get(clicki2); if (getd != null) { //is banned, show truce button if (this.capa.getPlayerUID() != getd.getTeamID() && this.capa.isTeamBanned(getd.getTeamID())) { strLT = StrUnban; colorLT = Enums.EnumColors.CYAN.getValue(); } //not banned, show battle button else { strLT = StrBan; colorLT = Enums.EnumColors.YELLOW.getValue(); } } } //clicked ban list? else if (this.listFocus == LISTCLICK_BAN) { clicki2 = listClicked[LISTCLICK_BAN] + this.listNum[LISTCLICK_BAN]; tlist2 = this.capa.getPlayerTeamBannedList(); //has clicked ally if (tlist2 != null && clicki2 >= 0 && clicki2 < tlist2.size()) { strLT = StrUnban; colorLT = Enums.EnumColors.CYAN.getValue(); } } }//end btn cd strLB = StrOK; colorLB = Enums.EnumColors.WHITE.getValue(); break; case TEAMSTATE_CREATE: str = TextFormatting.WHITE + StrTeamID +" "+ TextFormatting.YELLOW + this.capa.getPlayerUID(); //use pUID for team ID fontRendererObj.drawString(str, 10, 43, 0); strLB = StrOK; colorLB = Enums.EnumColors.WHITE.getValue(); strLT = StrCancel; colorLT = Enums.EnumColors.GRAY_LIGHT.getValue(); break; case TEAMSTATE_RENAME: strLB = StrOK; colorLB = Enums.EnumColors.WHITE.getValue(); strLT = StrCancel; colorLT = Enums.EnumColors.GRAY_LIGHT.getValue(); break; default: //0: main state //in team if (this.capa.hasTeam()) { strLT = StrAllyList; colorLT = Enums.EnumColors.CYAN.getValue(); strLB = StrBanList; colorLB = Enums.EnumColors.YELLOW.getValue(); if (this.tempCD > 0) { strRT = String.valueOf((int)(tempCD * 0.05F)); colorRT = Enums.EnumColors.GRAY_LIGHT.getValue(); } else { strRT = StrRename; colorRT = Enums.EnumColors.WHITE.getValue(); } if (this.capa.getPlayerTeamCooldown() > 0) { strRB = String.valueOf(this.capa.getPlayerTeamCooldownInSec()); colorRB = Enums.EnumColors.GRAY_LIGHT.getValue(); } else { strRB = StrDisband; colorRB = Enums.EnumColors.GRAY_DARK.getValue(); } } //no team else { if (this.capa.getPlayerTeamCooldown() > 0) { strRB = String.valueOf(this.capa.getPlayerTeamCooldownInSec()); colorRB = Enums.EnumColors.GRAY_LIGHT.getValue(); } else { strRB = StrCreate; colorRB = Enums.EnumColors.CYAN.getValue(); } } break; }//end switch //draw button string int strlen = (int) (this.fontRendererObj.getStringWidth(strLT) * 0.5F); fontRendererObj.drawString(strLT, 31-strlen, 160, colorLT); strlen = (int) (this.fontRendererObj.getStringWidth(strLB) * 0.5F); fontRendererObj.drawString(strLB, 31-strlen, 174, colorLB); strlen = (int) (this.fontRendererObj.getStringWidth(strRT) * 0.5F); fontRendererObj.drawString(strRT, 110-strlen, 160, colorRT); strlen = (int) (this.fontRendererObj.getStringWidth(strRB) * 0.5F); fontRendererObj.drawString(strRB, 110-strlen, 174, colorRB); //draw team list List<TeamData> tlist = this.capa.getPlayerTeamDataList(); int texty = 33; GlStateManager.pushMatrix(); GlStateManager.scale(0.8F, 0.8F, 0.8F); for (int i = this.listNum[LISTCLICK_TEAM]; i < tlist.size() && i < this.listNum[LISTCLICK_TEAM] + 5; ++i) { //get team data TeamData tdata2 = tlist.get(i); if (tdata2 != null) { //get ally string String allyInfo = TextFormatting.WHITE +"("+ StrNeutral +")"; if (this.capa.getPlayerUID() == tdata2.getTeamID()) { allyInfo = TextFormatting.GOLD +"("+ StrBelong +")"; } else if (this.capa.isTeamAlly(tdata2.getTeamID())) { allyInfo = TextFormatting.AQUA +"("+ StrAllied +")"; } else if (this.capa.isTeamBanned(tdata2.getTeamID())) { allyInfo = TextFormatting.RED +"("+ StrHostile +")"; } //draw info str = TextFormatting.YELLOW +""+ tdata2.getTeamID() +" : "+ TextFormatting.LIGHT_PURPLE + tdata2.getTeamLeaderName() +" "+ allyInfo; //org pos: 146, texty fontRendererObj.drawString(str, 181, texty, Enums.EnumColors.WHITE.getValue()); texty += 9; //draw name drawSplitString fontRendererObj.drawSplitString(tdata2.getTeamName(), 181, texty, 132, Enums.EnumColors.WHITE.getValue()); texty += 31; } //get null team data, draw space to guarantee order else { texty += 40; } }//end draw team list GlStateManager.popMatrix(); //draw ally or ban list List<Integer> tlist3 = null; texty = 79; int listID = LISTCLICK_ALLY; if (tdata != null) { if (this.teamState == TEAMSTATE_ALLY) { tlist3 = tdata.getTeamAllyList(); listID = LISTCLICK_ALLY; } else if (this.teamState == TEAMSTATE_BAN) { tlist3 = tdata.getTeamBannedList(); listID = LISTCLICK_BAN; } if (tlist3 != null) { GlStateManager.pushMatrix(); GlStateManager.scale(0.8F, 0.8F, 0.8F); for (int i = this.listNum[listID]; i < tlist3.size() && i < this.listNum[listID] + 3; ++i) { //get team data int getid = tlist3.get(i); TeamData tdata3 = this.capa.getPlayerTeamData(getid); if (tdata3 != null) { //get ally string String allyInfo = TextFormatting.WHITE +"("+ StrNeutral +")"; if (this.capa.getPlayerUID() == tdata3.getTeamID()) { allyInfo = TextFormatting.GOLD +"("+ StrBelong +")"; } else if (this.capa.isTeamAlly(tdata3.getTeamID())) { allyInfo = TextFormatting.AQUA +"("+ StrAllied +")"; } else if (this.capa.isTeamBanned(tdata3.getTeamID())) { allyInfo = TextFormatting.RED +"("+ StrHostile +")"; } //draw info str = TextFormatting.GRAY + StrTeamID +": "+ TextFormatting.YELLOW + tdata3.getTeamID() +" : "+ TextFormatting.LIGHT_PURPLE + tdata3.getTeamLeaderName() +" "+ allyInfo; //org pos: 146, texty fontRendererObj.drawString(str, 11, texty, 0); texty += 9; //draw name fontRendererObj.drawSplitString(tdata3.getTeamName(), 11, texty, 170, Enums.EnumColors.WHITE.getValue()); texty += 30; } //get null team data, draw space to guarantee order else { texty += 39; } }//end for all team id GlStateManager.popMatrix(); } }//end draw ally or ban list } //get clicked entity by entity simple name private void getEntityByClick() { final String tarStr; int clicked = this.listClicked[LISTCLICK_TARGET] + this.listNum[LISTCLICK_TARGET]; //get target simple name if (clicked >= 0 && clicked < this.tarList.size()) { tarStr = this.tarList.get(clicked); if (tarStr != null) { Map<Class<? extends Entity> ,String> entityMap = EntityList.CLASS_TO_NAME; if (entityMap != null) { entityMap.forEach((k, v) -> { if (tarStr.equals(k.getSimpleName())) { this.targetEntity = EntityList.createEntityByName(v, this.player.world); return; } }); } } } } //draw target model private void drawTargetModel() { if (this.targetEntity != null) { RenderManager rm = Minecraft.getMinecraft().getRenderManager(); int x = this.guiLeft + 72; int y = this.guiTop + 136; //set basic position and rotation GlStateManager.enableColorMaterial(); GlStateManager.pushMatrix(); GlStateManager.translate(x, y, 50F); GlStateManager.scale(-this.mScale, this.mScale, this.mScale); GlStateManager.rotate(180F, 0F, 0F, 1F); //set the light of model (face to player) GlStateManager.rotate(135F, 0F, 1F, 0F); RenderHelper.enableStandardItemLighting(); GlStateManager.rotate(-135F, 0F, 1F, 0F); //set head look angle GlStateManager.rotate(this.mRotateY, 0F, 1F, 0F); GlStateManager.rotate(this.mRotateX, 1F, 0F, 0F); GlStateManager.translate(0F, this.targetEntity.getYOffset(), 0F); rm.setPlayerViewY(180.0F); rm.setRenderShadow(false); rm.doRenderEntity(this.targetEntity, 0D, 0D, 0D, 0F, 1F, false); rm.setRenderShadow(true); GlStateManager.popMatrix(); RenderHelper.disableStandardItemLighting(); GlStateManager.disableRescaleNormal(); GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit); GlStateManager.disableTexture2D(); GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); } }//end target model //draw target class text in target screen private void drawTargetText() { //draw button text String str = StrRemove; int strlen = (int) (this.fontRendererObj.getStringWidth(str) * 0.5F); fontRendererObj.drawString(str, 31-strlen, 160, Enums.EnumColors.WHITE.getValue()); //draw target list int texty = 28; for (int i = this.listNum[LISTCLICK_TARGET]; i < tarList.size() && i < this.listNum[LISTCLICK_TARGET] + 13; ++i) { //get ship position str = tarList.get(i); if (str != null) { //draw name fontRendererObj.drawString(str, 146, texty, Enums.EnumColors.WHITE.getValue()); texty += 12; } } } //open ship GUI private void openShipGUI() { int clickid = this.listNum[LISTCLICK_RADAR] + this.listClicked[LISTCLICK_RADAR]; if (clickid >= 0 && clickid < this.shipList.size()) { Entity ent = this.shipList.get(clickid).ship; if (ent instanceof BasicEntityShip) { this.mc.player.closeScreen(); //send GUI packet CommonProxy.channelG.sendToServer(new C2SGUIPackets(player, C2SGUIPackets.PID.OpenShipGUI, ent.getEntityId())); } } } //按鍵按下時執行此方法, 此方法等同key input event @Override protected void keyTyped(char input, int keyID) throws IOException { if (this.textField.textboxKeyTyped(input, keyID)) { //test } else { super.keyTyped(input, keyID); } } /** btn: 0:left top, 1:left bottom, 2:right top, 3:right bottom*/ private void handleClickTeamMain(int btn) { switch (btn) { case 0: //left top btn: ally page if (this.capa.hasTeam()) { this.teamState = TEAMSTATE_ALLY; } break; case 1: //left bottom btn: ban page if (this.capa.hasTeam()) { this.teamState = TEAMSTATE_BAN; } break; case 2: //right top btn: rename page if (this.tempCD > 0) { break; } else if (this.capa.hasTeam()) { this.teamState = TEAMSTATE_RENAME; } break; case 3: //right bottom btn: disband or create team // LogHelper.info("DEBUG : desk: team cooldown "+this.capa.getTeamCooldown()); if (this.capa.getPlayerTeamCooldown() <= 0) { //has team if (this.capa.hasTeam()) { //disband team CommonProxy.channelG.sendToServer(new C2SGUIPackets(player, C2SGUIPackets.PID.Desk_Disband, 0)); //return to main state this.teamState = TEAMSTATE_MAIN; this.tempCD = CLICKCD; } //no team else { this.teamState = TEAMSTATE_CREATE; } } break; }//end switch }//end btn in team main /** btn: 0:left top, 1:left bottom, 2:right top, 3:right bottom*/ private void handleClickTeamAlly(int btn) { switch (btn) { case 0: //left top btn: ally or break ally if (this.tempCD > 0) { break; } int clicki = -1; int getTeamID = 0; boolean isAlly = false; /** get clicked team id */ //clicked team list clicki = listClicked[LISTCLICK_TEAM] + this.listNum[LISTCLICK_TEAM]; List tlist = this.capa.getPlayerTeamDataList(); if (this.listFocus == LISTCLICK_TEAM && tlist != null && clicki >= 0 && clicki < tlist.size()) { TeamData getd = (TeamData) tlist.get(clicki); if (getd != null) { //get team id getTeamID = getd.getTeamID(); //check is ally if (this.capa.isTeamAlly(getTeamID)) { isAlly = true; } } } //clicked ally list else if (this.listFocus == LISTCLICK_ALLY) { clicki = listClicked[LISTCLICK_ALLY] + this.listNum[LISTCLICK_ALLY]; tlist = this.capa.getPlayerTeamAllyList(); if (tlist != null && clicki >= 0 && clicki < tlist.size()) { //get team id getTeamID = (Integer) tlist.get(clicki); isAlly = true; } } /** send ally or break ally packet */ if (getTeamID > 0) { //break ally if (isAlly) { CommonProxy.channelG.sendToServer(new C2SGUIPackets(player, C2SGUIPackets.PID.Desk_Break, getTeamID)); } //ally else { CommonProxy.channelG.sendToServer(new C2SGUIPackets(player, C2SGUIPackets.PID.Desk_Ally, getTeamID)); } this.tempCD = CLICKCD; } break; case 1: //left bottom btn: OK //return to main state this.teamState = TEAMSTATE_MAIN; break; }//end switch }//end btn in team ally /** btn: 0:left top, 1:left bottom, 2:right top, 3:right bottom*/ private void handleClickTeamCreate(int btn) { switch (btn) { case 0: //left top btn: cancel this.teamState = TEAMSTATE_MAIN; //return to main state break; case 1: //left bottom btn: OK if (!this.capa.hasTeam()) { String str = this.textField.getText(); if (str != null && str.length() > 1) { LogHelper.debug("DEBUG: desk: create team: "+str); //change team id CommonProxy.channelG.sendToServer(new C2SGUIPackets(player, C2SGUIPackets.PID.Desk_Create, str)); //return to main state this.teamState = TEAMSTATE_MAIN; this.tempCD = CLICKCD; } } break; }//end switch }//end btn in team create /** btn: 0:left top, 1:left bottom, 2:right top, 3:right bottom*/ private void handleClickTeamRename(int btn) { switch (btn) { case 0: //left top btn: cancel this.teamState = TEAMSTATE_MAIN; //return to main state break; case 1: //left bottom btn: OK if (this.capa.hasTeam()) { String str = this.textField.getText(); if (str != null && str.length() > 1) { LogHelper.debug("DEBUG: desk: rename team: "+str); //change team name CommonProxy.channelG.sendToServer(new C2SGUIPackets(player, C2SGUIPackets.PID.Desk_Rename, str)); //return to main state this.teamState = TEAMSTATE_MAIN; this.tempCD = CLICKCD; } } break; }//end switch }//end btn in team rename /** btn: 0:left top, 1:left bottom, 2:right top, 3:right bottom*/ private void handleClickTeamBan(int btn) { switch (btn) { case 0: //left top btn: if (this.tempCD > 0) { break; } int clicki = -1; int getTeamID = 0; boolean isBanned = false; /** get clicked team id */ //clicked team list clicki = listClicked[LISTCLICK_TEAM] + this.listNum[LISTCLICK_TEAM]; List tlist = this.capa.getPlayerTeamDataList(); if (this.listFocus == LISTCLICK_TEAM && tlist != null && clicki >= 0 && clicki < tlist.size()) { TeamData getd = (TeamData) tlist.get(clicki); if (getd != null) { //get team id getTeamID = getd.getTeamID(); //check is banned if (this.capa.isTeamBanned(getTeamID)) { isBanned = true; } } } //clicked banned list else if (this.listFocus == LISTCLICK_BAN) { clicki = listClicked[LISTCLICK_BAN] + this.listNum[LISTCLICK_BAN]; tlist = this.capa.getPlayerTeamBannedList(); if(tlist != null && clicki >= 0 && clicki < tlist.size()) { //get team id getTeamID = (Integer) tlist.get(clicki); isBanned = true; } } /** send ban or unban packet */ if (getTeamID > 0) { //unban if (isBanned) { CommonProxy.channelG.sendToServer(new C2SGUIPackets(player, C2SGUIPackets.PID.Desk_Unban, getTeamID)); } //ban else { CommonProxy.channelG.sendToServer(new C2SGUIPackets(player, C2SGUIPackets.PID.Desk_Ban, getTeamID)); } this.tempCD = CLICKCD; } break; case 1: //left bottom btn: return //return to main state this.teamState = TEAMSTATE_MAIN; break; }//end switch }//end btn in team ban //close gui if tile dead or too far away @Override public void updateScreen() { super.updateScreen(); //update text field cursor this.textField.updateCursorCounter(); //close gui if tile broken if (this.type == 0 && this.tile == null) { this.mc.player.closeScreen(); } //every 64 ticks if ((this.tickGUI & 63) == 0) { if (this.player != null) { //send radar entity list request CommonProxy.channelI.sendToServer(new C2SInputPackets(C2SInputPackets.PID.Request_EntityItemList, 0)); } }//end every 64 ticks } private void setShipModel(int chap, int page) { int classID = -1; String shipName = null; //clear mount if (this.shipModel != null) { this.shipModel.dismountRidingEntity(); this.shipMount = null; } else { this.shipMount = null; } //get ship try { if (page > 0) { if (chap == 4) { classID = Values.ShipBookList.get(page - 1); } else if (chap == 5) { classID = Values.EnemyBookList.get(page - 1); } } } catch (Exception e) { e.printStackTrace(); } //get no ship if (classID < 0) { this.shipModel = null; return; } //get ship but not in colled list if (!EntityHelper.checkShipColled(classID, this.capa)) { this.shipModel = null; return; } //get entity name shipName = ShipCalc.getEntityToSpawnName(classID); //set ship model if (EntityList.NAME_TO_CLASS.containsKey(shipName)) { this.shipModel = (BasicEntityShip) EntityList.createEntityByName(shipName, player.world); if (this.shipModel != null) { this.shipModel.setStateFlag(ID.F.NoFuel, false); this.shipType = this.shipModel.getShipType(); this.shipClass = this.shipModel.getAttrClass(); this.shipMaxStats = this.shipModel.getStateMinor(ID.M.NumState); this.iconXY = new int[2][3]; this.iconXY[0] = Values.ShipTypeIconMap.get((byte)this.shipType); this.iconXY[1] = Values.ShipNameIconMap.get(this.shipClass); } else { this.shipMaxStats = 0; this.shipStats = 0; } } } private void setShipMount() { if (this.shipModel != null && this.shipModel.hasShipMounts()) { //summon mount if emotion state >= equip00 if (this.shipModel.canSummonMounts()) { if (!this.shipModel.isRiding()) { //summon mount entity this.shipMount = this.shipModel.summonMountEntity(); this.shipMount.initAttrs(this.shipModel); //set riding entity this.shipModel.startRiding(this.shipMount, true); } } else { //clear mount this.shipModel.dismountRidingEntity(); this.shipMount = null; } } } private void drawShipModel() { if (this.shipModel != null) { //draw background //draw ship model background Minecraft.getMinecraft().getTextureManager().bindTexture(guiBook2); if (this.book_chapNum == 4) { //shinkei drawTexturedModalRect(guiLeft+20, guiTop+48, 0, 0, 87, 130); } else { //kanmusu drawTexturedModalRect(guiLeft+20, guiTop+48, 105, 0, 87, 130); } //draw model state buttons this.shipStats = this.shipModel.getStateEmotion(ID.S.State); int numstats = 0; for (int i = 0; i < 8; i++) { if (numstats > this.shipMaxStats) break; for (int j = 0; j < 2; j++) { if (++numstats > this.shipMaxStats) break; if ((this.shipStats & Values.N.Pow2[numstats-1]) == Values.N.Pow2[numstats-1]) { drawTexturedModalRect(guiLeft+45+i*9, guiTop+158+j*9, 115, 156, 7, 9); } else { drawTexturedModalRect(guiLeft+45+i*9, guiTop+158+j*9, 115, 147, 7, 9); } } } try { //draw type icon Minecraft.getMinecraft().getTextureManager().bindTexture(guiNameIcon0); drawTexturedModalRect(guiLeft+23, guiTop+53, this.iconXY[0][0], this.iconXY[0][1], 28, 28); //draw name icon int offx = 0; int offy = 0; if (iconXY[1][0] < 100) { Minecraft.getMinecraft().getTextureManager().bindTexture(guiNameIcon1); if (iconXY[1][0] == 4) offy = -10; } else { Minecraft.getMinecraft().getTextureManager().bindTexture(guiNameIcon2); if (iconXY[1][0] == 6) offy = -10; else offy = 10; } drawTexturedModalRect(guiLeft+30+offx, guiTop+94+offy, this.iconXY[1][1], this.iconXY[1][2], 11, 59); } catch (Exception e) { LogHelper.info("Exception : desk GUI: get name icon fail "+e); } //tick time int modelTicking = this.tickGUI % 3; if (modelTicking == 0) { this.shipModel.ticksExisted++; if (this.shipModel.getAttackTick() > 0) this.shipModel.setAttackTick(this.shipModel.getAttackTick()-1); //set moving motion if (this.shipModel.isSprinting()) { this.shipModel.moveEntityWithHeading(1F, 0F); } else { this.shipModel.prevSwingProgress = 0F; this.shipModel.swingProgress = 0F; this.shipModel.prevLimbSwingAmount = 0F; this.shipModel.limbSwingAmount = 0F; } if (this.shipMount != null) { this.shipMount.ticksExisted++; if (this.shipMount.getAttackTick() > 0) this.shipMount.setAttackTick(this.shipMount.getAttackTick() - 1); //set mount moving motion if (this.shipMount.isSprinting()) { this.shipMount.moveEntityWithHeading(1F, 0F); } else { this.shipMount.prevSwingProgress = 0F; this.shipMount.swingProgress = 0F; this.shipMount.prevLimbSwingAmount = 0F; this.shipMount.limbSwingAmount = 0F; } } } RenderManager rm = Minecraft.getMinecraft().getRenderManager(); int x = this.guiLeft + 72; int y = this.guiTop + 110; //set basic position and rotation GlStateManager.enableColorMaterial(); GlStateManager.pushMatrix(); GlStateManager.translate(x, y + this.mScale * 1.1F, 50F); GlStateManager.scale(-this.mScale, this.mScale, this.mScale); GlStateManager.rotate(180F, 0F, 0F, 1F); //set the light of model (face to player) GlStateManager.rotate(135F, 0F, 1F, 0F); RenderHelper.enableStandardItemLighting(); GlStateManager.rotate(-135F, 0F, 1F, 0F); //提高旋轉中心 GlStateManager.translate(0F, 0.7F, 0F); //set head look angle GlStateManager.rotate(this.mRotateY, 0F, 1F, 0F); GlStateManager.rotate(this.mRotateX, 1F, 0F, 0F); GlStateManager.translate(0F, this.shipModel.getYOffset() - 0.7F, 0F); //draw mount float partialTick = modelTicking * 0.33F; this.shipModel.rotationYawHead = 0F; rm.setPlayerViewY(180.0F); rm.setRenderShadow(false); if (this.shipMount != null) { float[] seatPos = this.shipMount.getSeatPos(); //ship必須先畫才畫mounts GlStateManager.translate(seatPos[2], seatPos[1] + this.shipModel.getYOffset(), seatPos[0]); rm.doRenderEntity(this.shipModel, 0D, 0D, 0D, 0F, partialTick, false); GlStateManager.translate(-seatPos[2], -seatPos[1] - this.shipModel.getYOffset(), -seatPos[0]); rm.doRenderEntity(this.shipMount, 0D, 0D, 0D, 0F, partialTick, false); } else { rm.doRenderEntity(this.shipModel, 0D, 0D, 0D, 0F, partialTick, false); } rm.setRenderShadow(true); GlStateManager.popMatrix(); RenderHelper.disableStandardItemLighting(); GlStateManager.disableRescaleNormal(); GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit); GlStateManager.disableTexture2D(); GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); } //no ship else { Minecraft.getMinecraft().getTextureManager().bindTexture(guiBook2); drawTexturedModalRect(guiLeft+20, guiTop+48, 0, 148, 87, 108); } } private void updateTargetClassList() { this.tarList = new ArrayList<String>(); if (this.capa != null) { HashMap<Integer, String> m = this.capa.getTargetClassMap(); if (m != null) { m.forEach((k, v) -> { this.tarList.add(v); }); } } } }
[ "zec_tails@yahoo.com.tw" ]
zec_tails@yahoo.com.tw
d98bc6e5ae7855d41875932255b4f8481270e461
66424ee67ab96a5096dcfe7bb5b4b54f024c3ae8
/src/BurgerSimulator/ConsoleSimulation.java
1f7ff36f81d74b8d2602057b03ebdccb0e2ff636
[]
no_license
MrDevonLee/Burger-Stand-Simulator
bc453ae5e471ad3c01c724563667676979cc0cf0
2b6fb73b7dc7260a2f72782918da5aa320d62011
refs/heads/main
2023-07-05T03:27:16.815251
2021-08-12T19:31:46
2021-08-12T19:31:46
395,390,416
0
0
null
null
null
null
UTF-8
Java
false
false
3,904
java
package BurgerSimulator; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; /** * This class handles all of the I/O for a simulation run in a console * environment and sends commands to the Simulation class for processing * * @author Devon Lee */ public class ConsoleSimulation { private Simulation mySim; File file = new File("GivenInput.in"); BufferedReader stdin; Scanner jin; /** * Determines if a given command is one of the predetermined valid * commands * * @param cmdTokens The command to be validated * @return True if the command is valid, false otherwise */ private boolean validCommand(String[] cmdTokens) { boolean isValid; isValid = cmdTokens.length == 1 && (cmdTokens[0].equals("A") || cmdTokens[0].equals("L") || cmdTokens[0].equals("S")) || cmdTokens.length == 2 && cmdTokens[0].equals("C") && isInteger(cmdTokens[1]); return isValid; } /** * Determines whether the given string is an integer * * @param str The string to be evaluated for status as an integer * @return True if the string is a valid integer, false otherwise */ private boolean isInteger(String str) { boolean isInteger; try { Integer.parseInt(str); isInteger = true; } catch (NumberFormatException e) { isInteger = false; } return isInteger; } /** * Given a valid command, this method extracts the components of that * command, calls the appropriate method in Simulation to execute the * command, and prints the resulting output from the Simulation class * * @param cmdTokens A valid command */ private void processCommand(String[] cmdTokens) { int time; String report; if(cmdTokens[0].equals("A")) report = mySim.customerArrives(); else if(cmdTokens[0].equals("L")) report = mySim.customerLeaves(); else if(cmdTokens[0].equals("C")) { // Extracts time from known command format time = Integer.parseInt(cmdTokens[1]); // Safe, already checked report = mySim.manipulateClock(time); } else // cmdType == 'S' { System.out.println(); // Extra line to make statistics stand out report = mySim.calculateStatistics(); } System.out.println(report); } /** * Prints an error message with the offending command and its invalidity * * @param cmdTokens An invalid command to be echoed */ private void printErrorMessage(String[] cmdTokens) { System.out.println(cmdTokens[0] + " is NOT a valid command!"); } /** * Starts simulation operations in a console environment; functions as * a main method because it is called by the Prog4 class * * @throws IOException The program could not read the input line */ public void run() throws IOException { mySim = new Simulation(); boolean timeToQuit = false; String cmd; String[] tokens; jin = new Scanner(System.in); // Keyboard //stdin = new BufferedReader(new FileReader(file)); // File while(!timeToQuit && (cmd = jin.nextLine()) != null) // Keyboard //while(!timeToQuit && (cmd = stdin.readLine()) != null ) // File { tokens = cmd.split(" "); if(tokens.length == 1 && (tokens[0].equals("Q") || tokens[0].equals("q"))) timeToQuit = true; else if(validCommand(tokens)) processCommand(tokens); else printErrorMessage(tokens); } System.out.println("Simulation statistics:"); System.out.println(mySim.calculateStatistics()); System.out.println("Simulation terminated."); } }
[ "devonewo@gmail.com" ]
devonewo@gmail.com
89b0db5da7b629ecda5746d0d5129eb61b4698e2
4e395108a51c7dee797219e3f3a65868a1757ff2
/src/Behavioral_Patterns/Interpreter/exemple/AndExpression.java
6aa08f11c798d4a8efc49a67fc1418feb9ab752c
[ "MIT" ]
permissive
jacquant/Design-Patterns
13a5c2c5875fd27a2619e5f0c5e601c91025f65f
2beeee77669109e4c5b729429dea19abf42535f7
refs/heads/master
2020-05-25T16:54:39.361452
2019-05-27T14:11:05
2019-05-27T14:11:05
187,896,912
3
0
null
null
null
null
UTF-8
Java
false
false
440
java
package Behavioral_Patterns.Interpreter.exemple; public class AndExpression implements Expression { private Expression expr1 = null; private Expression expr2 = null; public AndExpression(Expression expr1, Expression expr2) { this.expr1 = expr1; this.expr2 = expr2; } @Override public boolean interpret(String context) { return expr1.interpret(context) && expr2.interpret(context); } }
[ "antoine.jacques@student.unamur.be" ]
antoine.jacques@student.unamur.be
750c8f780a246c8438c74830d3335ddf86e47509
1d2bd82844afdfd0a9386d4d290ca1e87417184f
/CodeJava/src/leetcode/P855_ExamRoom.java
0b633970445f91b8810a97df882118bf6c88c1a0
[]
no_license
txqgit/LeetCode
53801b498595a997b557332e628c8581529f93d7
c4b755792d2bb98bd38ba5ee1b987f404f1847b2
refs/heads/master
2023-02-11T09:28:42.652748
2021-01-17T04:04:17
2021-01-17T04:04:17
272,142,058
0
0
null
null
null
null
UTF-8
Java
false
false
1,269
java
package leetcode; import java.util.TreeSet; class ExamRoom { int N; TreeSet<Integer> students; public ExamRoom(int N) { this.N = N; this.students = new TreeSet<>(); } public int seat() { int student = 0; if (students.size()>0) { int dist = students.first(); Integer pre = null; for (Integer s: students) { if (pre!=null) { int d = (s-pre)/2; if (d>dist) { dist = d; student = pre+d; } } pre = s; } if (N-1-students.last()>dist) { student = N-1; } } students.add(student); return student; } public void leave(int p) { students.remove(p); } } public class P855_ExamRoom { public static void main(String[] args) { ExamRoom solution = new ExamRoom(10); System.out.println(solution.seat()); System.out.println(solution.seat()); System.out.println(solution.seat()); System.out.println(solution.seat()); solution.leave(4); System.out.println(solution.seat()); } }
[ "371867040@qq.com" ]
371867040@qq.com
f186ccd0ff287d37315e0c1c844d731dac89977e
1f6ae914b985d7f9fc0b8419d7ed6ed0b068f08a
/java/Activity3_1.java
bf6e96aca915a5c242d23b70afa8158f92bd0de1
[]
no_license
Sangeethasm93/sdet
9f297c5757cab98d93352240b9d966ed5feccd8e
e4f5aef20cd2f2594916ea8d0c48b3fe6ea47f40
refs/heads/main
2023-03-19T06:02:39.685847
2021-03-10T04:25:32
2021-03-10T04:25:32
333,320,446
0
0
null
2021-01-27T06:02:56
2021-01-27T06:02:55
null
UTF-8
Java
false
false
871
java
package Session3; import java.util.ArrayList; public class Activity3_1 { public static void main(String[] args) { // declaring Array List of String objects ArrayList<String> myList = new ArrayList<String>(); // Adding objects to Array List at default index myList.add("Apple"); myList.add("Mango"); myList.add("Orange"); // Adding object at specific index myList.add(3, "Grapes"); myList.add(1, "Papaya"); System.out.println("Print All the Objects:"); for (String s : myList) { System.out.println(s); } System.out.println("3rd element in the list is: " + myList.get(2)); System.out.println("Is Chicku is in list: " + myList.contains("Chicku")); System.out.println("Size of ArrayList: " + myList.size()); myList.remove("Papaya"); System.out.println("New Size of ArrayList: " + myList.size()); } }
[ "noreply@github.com" ]
noreply@github.com
7098a9eb3a5559a136385b37ab1a447830f79fb7
588394d5a6e03ca46d2e2fea63c35a1da7dc1f50
/junit-calc-maven/src/test/java/com/hdp/dev/TestApp.java
5acaf48ca5806276865db31cc65022ffa4fd4873
[]
no_license
sandeep344078/Junit-sample-project
1629b9c5894789da88ac880216cb9ea79a654ce7
a81962a48407869a1e3558ac3b6d3c716c48d65c
refs/heads/master
2020-03-21T20:36:00.838451
2018-06-29T10:10:12
2018-06-29T10:10:12
139,017,082
0
0
null
null
null
null
UTF-8
Java
false
false
313
java
package com.hdp.dev; import org.junit.Assert; import org.junit.Test; public class TestApp { @Test public void testPrintHelloWorld() { Assert.assertEquals(App.getHelloWorld(), "Hello World"); } @Test public void testPrintHelloWorld2() { Assert.assertEquals(App.getHelloWorld2(), "Hello World 2"); } }
[ "sandeep.katika@wipro.com" ]
sandeep.katika@wipro.com
f64be068bbe15a5a9e95c4e227d466baf4d24115
9c161e5a1154f89f2851c1db37d7b2cfeb440ca5
/DsAlgoInJava/src/main/java/ds/chapter06trees/binarysearchtrees/problems/Problem054.java
fe706ddf75bdaf6cd9477989432706d7003cdd02
[]
no_license
nehapsb/Practise
31bb4fdac518b709e543aac67f369d70dddf6a2b
a818a3e4e033c1c780f050aa6c4ccf9094f12c66
refs/heads/master
2022-12-23T02:15:42.112920
2022-12-16T07:37:09
2022-12-16T07:37:09
144,556,883
0
0
null
null
null
null
UTF-8
Java
false
false
1,142
java
package ds.chapter06trees.binarysearchtrees.problems; import ds.chapter06trees.binarysearchtrees.implementation.BinarySearchTreeNode; public class Problem054 { public BinarySearchTreeNode findLCA(BinarySearchTreeNode root, BinarySearchTreeNode a, BinarySearchTreeNode b){ if(root == null){ return root; } if(root == a || root == b ){ return root; } if(Math.max(a.getData(), b.getData()) < root.getData()){ return findLCA(root.getLeft(), a, b); }else if(Math.min(a.getData(), b.getData()) > root.getData()){ return findLCA(root.getRight(), a, b); }else{ return root; } } public static void main(String[] args){ int[] preorder = new int[]{10,5,8,15,20,4}; BinarySearchTreeContruction binarySearchTreeContruction = new BinarySearchTreeContruction(); BinarySearchTreeNode root = binarySearchTreeContruction.contructBSTFromPreorderTraversal(preorder, preorder[0], Integer.MIN_VALUE, Integer.MAX_VALUE); BinarySearchTreeNode lca = new Problem054().findLCA(root, new BinarySearchTreeNode(8), new BinarySearchTreeNode(5)); System.out.println(lca.getData()); } }
[ "junas01@ca.com" ]
junas01@ca.com
57bd5bf922dc8406a201470445c3bfdf631e22cc
944f0f42b05b149fba0d98f565cb5874a268586a
/src/test/java/ua/yet/adv/java/generics/TestBoundedWildcards.java
79c4fb4dd2fff20efe76f80b5cac0b634ddeb0e2
[ "MIT" ]
permissive
MikeLaptev/advanced_java_generics
906812ae14e1e230b5dce6f44d7f5f0eba0c78b7
123b89a8fe06c218df021f173263d089274dd2c5
refs/heads/master
2020-05-29T11:00:15.658069
2016-06-13T22:55:34
2016-06-13T22:55:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,370
java
package ua.yet.adv.java.generics; import static org.junit.Assert.*; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import org.junit.Before; import org.junit.Test; import ua.yet.adv.java.generics.domain.Camera; import ua.yet.adv.java.generics.domain.Container; import ua.yet.adv.java.generics.domain.Phone; public class TestBoundedWildcards { private Container<Camera> cameraContainer; @Before public void setup() { cameraContainer = new Container<Camera>(new Camera("camera")); } @Test public void test() { Collection<Camera> cams = new ArrayList<>(); Collection<Camera> cams2 = new ArrayList<>(); cameraContainer.copy(cams, cams2); Container.copyStatic(cams, cams2); Collection<Object> objects = new ArrayList<>(); cameraContainer.copy(cams, objects); Container.copyStatic(cams, objects); Collection<Serializable> serializableObjects = new ArrayList<>(); cameraContainer.copy(cams, serializableObjects); Container.copyStatic(cams, serializableObjects); Collection<Phone> phones = new ArrayList<>(); // cameraContainer.copy(cams, phones); - compile error // Container.copyStatic(cams, phones); - compile error } }
[ "yuriytkach@gmail.com" ]
yuriytkach@gmail.com
60bea7a799013d9e0346581f4bfde1cae2ce01ea
acac3256b5609c35edc6e7e28e103a81f19837c9
/auditservice/src/main/java/com/infy/auditservice/configuration/SwaggerConfiguration.java
1040d6ddd357bc248bb1f2559a3c71b9866a69b9
[]
no_license
srujan587/MicroservicesApp
7fa4e3b3c345c5fd67f657919b1431bbab8318b9
d561e9e26781ea49c464cceda466910ff1928043
refs/heads/master
2022-07-05T17:45:42.438654
2020-05-21T11:51:35
2020-05-21T11:51:35
257,184,978
0
0
null
2022-06-25T07:30:21
2020-04-20T05:54:23
Java
UTF-8
Java
false
false
1,337
java
package com.infy.auditservice.configuration; import org.springframework.boot.actuate.trace.http.HttpTraceRepository; import org.springframework.boot.actuate.trace.http.InMemoryHttpTraceRepository; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfiguration { @Bean public Docket loanApi() { return new Docket(DocumentationType.SWAGGER_2).select() .apis(RequestHandlerSelectors.basePackage("com.infy.auditservice.controller")) // .paths(PathSelectors.ant("/loandetails/*")) .build().apiInfo(apiInfo()); } //Added for actuators @Bean public HttpTraceRepository htttpTraceRepository() { return new InMemoryHttpTraceRepository(); } public ApiInfo apiInfo() { ApiInfo apiInfomation=new ApiInfo("Loan Details API", "Loan Details API Info", "1.0", "", new Contact("Srujan Kumar", "", "srujankumar.r@infosys.com"), "", ""); return apiInfomation; } }
[ "rsrujankumar2011@gmail.com" ]
rsrujankumar2011@gmail.com
6e4996efef31c0bc94cf953981e3dfbeca52a2f1
c03cbfb27774195847ce2335cf0734711a63ebb7
/kvdb/src/test/java/com/kvdb/KVDBUnitTest.java
4a9a54c2c3879a1699fb1960d13282cc4a28f39b
[]
no_license
brijeshpateln/KVStore
4e04ab58e59ebe810b166d90bfc9bfb887ee16c1
850403f50c5eb0d979cdd9ef0344946eae6d2e25
refs/heads/master
2021-01-19T01:25:54.770036
2016-07-19T19:04:15
2016-07-19T19:04:15
63,720,772
1
0
null
null
null
null
UTF-8
Java
false
false
9,043
java
package com.kvdb; import com.kvdb.DB; import com.kvdb.KVDBException; import com.kvdb.connection.DBConnection; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import java.util.ArrayList; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class KVDBUnitTest { @Test public void testOpenWithFolder() throws KVDBException { DB db = DB.open(System.getProperty("user.home")); db.close(); } @Test public void testOpenWithName() throws KVDBException { DB db = DB.open(System.getProperty("user.home"),"test1.db"); db.close(); } @Test public void testOpenWithFlags() throws KVDBException { DB db = DB.open(System.getProperty("user.home"),"test2.db",DB.OPEN_CREATE | DB.OPEN_READWRITE); db.close(); } @Test public void testOpenWithReadFlag() throws KVDBException { DB db = DB.open(System.getProperty("user.home"),"test2.db",DB.OPEN_READONLY); db.close(); } @Test public void testConnectionCreate() throws KVDBException { DB db = DB.open(System.getProperty("user.home"),DB.OPEN_CREATE | DB.OPEN_READWRITE); DBConnection c = db.getConnection(); assertFalse(!c.isOpen()); c.release(); } @Test public void testConnectionOpenClose() throws KVDBException { DB db = DB.open(System.getProperty("user.home"),DB.OPEN_CREATE | DB.OPEN_READWRITE); DBConnection c = db.getConnection(); c.close(); c.open(); assertFalse(!c.isOpen()); c.release(); } @Test public void testConnectionPutIntCheck() throws KVDBException { DB db = DB.open(System.getProperty("user.home"),DB.OPEN_CREATE | DB.OPEN_READWRITE); DBConnection c = db.getConnection(); assertFalse(!c.isOpen()); c.putInt("int", 1234); assertEquals(1234,c.getInt("int")); c.release(); } @Test public void testConnectionPutShortCheck() throws KVDBException { DB db = DB.open(System.getProperty("user.home"),DB.OPEN_CREATE | DB.OPEN_READWRITE); DBConnection c = db.getConnection(); assertFalse(!c.isOpen()); c.putShort("short", (short) 123); assertEquals(123,c.getShort("short")); c.release(); } @Test public void testConnectionPutLongCheck() throws KVDBException { DB db = DB.open(System.getProperty("user.home"),DB.OPEN_CREATE | DB.OPEN_READWRITE); DBConnection c = db.getConnection(); assertFalse(!c.isOpen()); c.putLong("long", 123456789012345L); assertEquals(123456789012345L,c.getLong("long")); c.release(); } @Test public void testConnectionPutFloatCheck() throws KVDBException { DB db = DB.open(System.getProperty("user.home"),DB.OPEN_CREATE | DB.OPEN_READWRITE); DBConnection c = db.getConnection(); assertFalse(!c.isOpen()); c.putFloat("float", 5.4f); assertEquals(5.4f,c.getFloat("float"),0.01); c.release(); } @Test public void testConnectionPutDoubleCheck() throws KVDBException { DB db = DB.open(System.getProperty("user.home"),DB.OPEN_CREATE | DB.OPEN_READWRITE); DBConnection c = db.getConnection(); assertFalse(!c.isOpen()); c.putDouble("double", 123.4); assertEquals(123.4,c.getFloat("double"),0.01); c.release(); } @Test public void testConnectionPutBooleanCheck() throws KVDBException { DB db = DB.open(System.getProperty("user.home"),DB.OPEN_CREATE | DB.OPEN_READWRITE); DBConnection c = db.getConnection(); assertFalse(!c.isOpen()); c.putBoolean("boolean", true); assertEquals(true,c.getBoolean("boolean")); c.release(); } @Test public void testConnectionPutStringCheck() throws KVDBException { DB db = DB.open(System.getProperty("user.home"),DB.OPEN_CREATE | DB.OPEN_READWRITE); DBConnection c = db.getConnection(); assertFalse(!c.isOpen()); c.put("mystring","Winter is coming!! Really!!"); String ret = c.get("mystring"); assertFalse(!ret.equals("Winter is coming!! Really!!")); c.release(); } @Test public void testConnectionPutObjectCheck() throws KVDBException { DB db = DB.open(System.getProperty("user.home"),DB.OPEN_CREATE | DB.OPEN_READWRITE); DBConnection c = db.getConnection(); assertFalse(!c.isOpen()); ArrayList<String> data = new ArrayList<>(); data.add("KVDB"); data.add("Store"); c.put("object", data); assertFalse(!c.get("object",data.getClass()).get(0).equals("KVDB")); assertFalse(!c.get("object",data.getClass()).get(1).equals("Store")); c.release(); } @Test public void testConnectionPutBytesCheck() throws KVDBException { DB db = DB.open(System.getProperty("user.home"),DB.OPEN_CREATE | DB.OPEN_READWRITE); DBConnection c = db.getConnection(); assertFalse(!c.isOpen()); byte[] data = "This is byte data".getBytes(); c.put("bytes",data); byte[] ret = c.getBytes("bytes"); for(int i = 0; i < ret.length; i++){ assertFalse(ret[i]!=data[i]); } c.release(); } @Test public void testConnectionPutArrayOfObjectsCheck() throws KVDBException { DB db = DB.open(System.getProperty("user.home"),DB.OPEN_CREATE | DB.OPEN_READWRITE); DBConnection c = db.getConnection(); assertFalse(!c.isOpen()); String[] data = {"Game", "Of", "Thrones"}; c.put("array",data); String[] ret = c.getArray("array",String.class); for(int i = 0; i < ret.length; i++){ assertFalse(!data[i].equals(data[i])); } c.release(); } @Test public void testConnectionReadWriteTransactionCheck() throws KVDBException { DB db = DB.open(System.getProperty("user.home"),DB.OPEN_CREATE | DB.OPEN_READWRITE); DBConnection c = db.getConnection(); assertFalse(!c.isOpen()); c.beginReadWriteTransaction(); for(int i = 0; i < 1000; i++){ c.put("String " + i, "default"); } c.endReadWriteTransaction(); c.release(); } @Test public void testConnectionReadZTransactionCheck() throws KVDBException { DB db = DB.open(System.getProperty("user.home"),DB.OPEN_CREATE | DB.OPEN_READWRITE); DBConnection c = db.getConnection(); assertFalse(!c.isOpen()); c.beginReadTransaction(); for(int i = 0; i < 1000; i++){ assertFalse(!"default".equals(c.get("String " + i))); } c.endReadTransaction(); c.release(); } @Test public void testConnectionRollbackCheck() throws KVDBException { DB db = DB.open(System.getProperty("user.home"),DB.OPEN_CREATE | DB.OPEN_READWRITE); DBConnection c = db.getConnection(); assertFalse(!c.isOpen()); c.beginReadWriteTransaction(); for(int i = 0; i < 1000; i++){ c.put("Coco " + i, "default"); } c.rollbackTransaction(); c.release(); } @Test public void testConnectionZZParallelCheck() throws KVDBException, InterruptedException { DB db = DB.open(System.getProperty("user.home"),DB.OPEN_CREATE | DB.OPEN_READWRITE); DBConnection c = db.getConnection(); assertFalse(!c.isOpen()); Thread t = new Thread(new Runnable() { @Override public void run() { try { DB _db = DB.open(System.getProperty("user.home"),DB.OPEN_CREATE | DB.OPEN_READWRITE); DBConnection _c = _db.getConnection(); _c.beginReadTransaction(); for(int j = 0; j < 1000; j++){ assertFalse(!"default".equals(_c.get("String " + j))); } _c.endReadTransaction(); _c.release(); } catch (KVDBException e) { e.printStackTrace(); } } }); t.start(); c.beginReadWriteTransaction(); for(int i = 0; i < 1000; i++){ c.put("Coco " + i, "default"); } c.endReadWriteTransaction(); t.join(); c = db.getConnection(); c.beginReadTransaction(); for(int i = 0; i < 1000; i++){ assertFalse(!"default".equals(c.get("Coco " + i))); } c.endReadTransaction(); c.release(); c.release(); } public static void main(String[] args){ Result result = JUnitCore.runClasses(KVDBUnitTest.class); for(Failure f : result.getFailures()){ System.out.println(f.getDescription()); } System.out.println(result.wasSuccessful()); } }
[ "brijeshpateln@gmail.com" ]
brijeshpateln@gmail.com
73b71e8af8a8f2c7d323c201bde36e62636b2beb
b3a694913d943bdb565fbf828d6ab8a08dd7dd12
/sources/p213q/p217b/p301c/p302a/p315m0/C3821o0.java
42513b9ef721640fb0c405c28e6d694d5943eedd
[]
no_license
v1ckxy/radar-covid
feea41283bde8a0b37fbc9132c9fa5df40d76cc4
8acb96f8ccd979f03db3c6dbfdf162d66ad6ac5a
refs/heads/master
2022-12-06T11:29:19.567919
2020-08-29T08:00:19
2020-08-29T08:00:19
294,198,796
1
0
null
2020-09-09T18:39:43
2020-09-09T18:39:43
null
UTF-8
Java
false
false
301
java
package p213q.p217b.p301c.p302a.p315m0; /* renamed from: q.b.c.a.m0.o0 */ public final class C3821o0 extends C3814l { public C3821o0(byte[] bArr) { super(bArr); } /* renamed from: a */ public C3810j mo10043a(byte[] bArr, int i) { return new C3819n0(bArr, i); } }
[ "josemmoya@outlook.com" ]
josemmoya@outlook.com
01f17fc57584242c8ff86bdb4b06fa0f1dc3c9e8
4d6f449339b36b8d4c25d8772212bf6cd339f087
/netreflected/src/Framework/System.ServiceModel,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089/system/servicemodel/configuration/XmlDictionaryReaderQuotasElement.java
a93d4ac2e722fbc1a6b515b5a54b0f6b9b28eb0a
[ "MIT" ]
permissive
lvyitian/JCOReflector
299a64550394db3e663567efc6e1996754f6946e
7e420dca504090b817c2fe208e4649804df1c3e1
refs/heads/master
2022-12-07T21:13:06.208025
2020-08-28T09:49:29
2020-08-28T09:49:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
15,989
java
/* * MIT License * * Copyright (c) 2020 MASES s.r.l. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /************************************************************************************** * <auto-generated> * This code was generated from a template using JCOReflector * * Manual changes to this file may cause unexpected behavior in your application. * Manual changes to this file will be overwritten if the code is regenerated. * </auto-generated> *************************************************************************************/ package system.servicemodel.configuration; import org.mases.jcobridge.*; import org.mases.jcobridge.netreflection.*; import java.util.ArrayList; // Import section import system.servicemodel.configuration.ServiceModelConfigurationElement; /** * The base .NET class managing System.ServiceModel.Configuration.XmlDictionaryReaderQuotasElement, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089. Extends {@link NetObject}. * <p> * * See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.ServiceModel.Configuration.XmlDictionaryReaderQuotasElement" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.ServiceModel.Configuration.XmlDictionaryReaderQuotasElement</a> */ public class XmlDictionaryReaderQuotasElement extends ServiceModelConfigurationElement { /** * Fully assembly qualified name: System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 */ public static final String assemblyFullName = "System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; /** * Assembly name: System.ServiceModel */ public static final String assemblyShortName = "System.ServiceModel"; /** * Qualified class name: System.ServiceModel.Configuration.XmlDictionaryReaderQuotasElement */ public static final String className = "System.ServiceModel.Configuration.XmlDictionaryReaderQuotasElement"; static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName); /** * The type managed from JCOBridge. See {@link JCType} */ public static JCType classType = createType(); static JCEnum enumInstance = null; JCObject classInstance = null; static JCType createType() { try { return bridge.GetType(className + ", " + (JCOBridgeInstance.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName)); } catch (JCException e) { return null; } } void addReference(String ref) throws Throwable { try { bridge.AddReference(ref); } catch (JCNativeException jcne) { throw translateException(jcne); } } public XmlDictionaryReaderQuotasElement(Object instance) throws Throwable { super(instance); if (instance instanceof JCObject) { classInstance = (JCObject) instance; } else throw new Exception("Cannot manage object, it is not a JCObject"); } public String getJCOAssemblyName() { return assemblyFullName; } public String getJCOClassName() { return className; } public String getJCOObjectName() { return className + ", " + (JCOBridgeInstance.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); } public Object getJCOInstance() { return classInstance; } public void setJCOInstance(JCObject instance) { classInstance = instance; super.setJCOInstance(classInstance); } public JCType getJCOType() { return classType; } /** * Try to cast the {@link IJCOBridgeReflected} instance into {@link XmlDictionaryReaderQuotasElement}, a cast assert is made to check if types are compatible. */ public static XmlDictionaryReaderQuotasElement cast(IJCOBridgeReflected from) throws Throwable { NetType.AssertCast(classType, from); return new XmlDictionaryReaderQuotasElement(from.getJCOInstance()); } // Constructors section public XmlDictionaryReaderQuotasElement() throws Throwable, system.ArgumentOutOfRangeException, system.ArgumentException, system.ArgumentNullException, system.collections.generic.KeyNotFoundException { try { // add reference to assemblyName.dll file addReference(JCOBridgeInstance.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); setJCOInstance((JCObject)classType.NewObject()); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Methods section // Properties section public int getMaxArrayLength() throws Throwable, system.ArgumentNullException, system.ObjectDisposedException, system.threading.AbandonedMutexException, system.ArgumentException, system.InvalidOperationException, system.reflection.AmbiguousMatchException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.NotSupportedException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.IndexOutOfRangeException, system.configuration.ConfigurationErrorsException, system.TypeLoadException, system.collections.generic.KeyNotFoundException, system.configuration.ConfigurationException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (int)classInstance.Get("MaxArrayLength"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setMaxArrayLength(int MaxArrayLength) throws Throwable, system.ArgumentNullException, system.ObjectDisposedException, system.threading.AbandonedMutexException, system.ArgumentException, system.InvalidOperationException, system.reflection.AmbiguousMatchException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.NotSupportedException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.IndexOutOfRangeException, system.configuration.ConfigurationErrorsException, system.TypeLoadException, system.collections.generic.KeyNotFoundException, system.NullReferenceException, system.globalization.CultureNotFoundException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("MaxArrayLength", MaxArrayLength); } catch (JCNativeException jcne) { throw translateException(jcne); } } public int getMaxBytesPerRead() throws Throwable, system.ArgumentNullException, system.ObjectDisposedException, system.threading.AbandonedMutexException, system.ArgumentException, system.InvalidOperationException, system.reflection.AmbiguousMatchException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.NotSupportedException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.IndexOutOfRangeException, system.configuration.ConfigurationErrorsException, system.TypeLoadException, system.collections.generic.KeyNotFoundException, system.configuration.ConfigurationException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (int)classInstance.Get("MaxBytesPerRead"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setMaxBytesPerRead(int MaxBytesPerRead) throws Throwable, system.ArgumentNullException, system.ObjectDisposedException, system.threading.AbandonedMutexException, system.ArgumentException, system.InvalidOperationException, system.reflection.AmbiguousMatchException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.NotSupportedException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.IndexOutOfRangeException, system.configuration.ConfigurationErrorsException, system.TypeLoadException, system.collections.generic.KeyNotFoundException, system.NullReferenceException, system.globalization.CultureNotFoundException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("MaxBytesPerRead", MaxBytesPerRead); } catch (JCNativeException jcne) { throw translateException(jcne); } } public int getMaxDepth() throws Throwable, system.ArgumentNullException, system.ObjectDisposedException, system.threading.AbandonedMutexException, system.ArgumentException, system.InvalidOperationException, system.reflection.AmbiguousMatchException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.NotSupportedException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.IndexOutOfRangeException, system.configuration.ConfigurationErrorsException, system.TypeLoadException, system.collections.generic.KeyNotFoundException, system.configuration.ConfigurationException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (int)classInstance.Get("MaxDepth"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setMaxDepth(int MaxDepth) throws Throwable, system.ArgumentNullException, system.ObjectDisposedException, system.threading.AbandonedMutexException, system.ArgumentException, system.InvalidOperationException, system.reflection.AmbiguousMatchException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.NotSupportedException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.IndexOutOfRangeException, system.configuration.ConfigurationErrorsException, system.TypeLoadException, system.collections.generic.KeyNotFoundException, system.NullReferenceException, system.globalization.CultureNotFoundException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("MaxDepth", MaxDepth); } catch (JCNativeException jcne) { throw translateException(jcne); } } public int getMaxNameTableCharCount() throws Throwable, system.ArgumentNullException, system.ObjectDisposedException, system.threading.AbandonedMutexException, system.ArgumentException, system.InvalidOperationException, system.reflection.AmbiguousMatchException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.NotSupportedException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.IndexOutOfRangeException, system.configuration.ConfigurationErrorsException, system.TypeLoadException, system.collections.generic.KeyNotFoundException, system.configuration.ConfigurationException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (int)classInstance.Get("MaxNameTableCharCount"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setMaxNameTableCharCount(int MaxNameTableCharCount) throws Throwable, system.ArgumentNullException, system.ObjectDisposedException, system.threading.AbandonedMutexException, system.ArgumentException, system.InvalidOperationException, system.reflection.AmbiguousMatchException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.NotSupportedException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.IndexOutOfRangeException, system.configuration.ConfigurationErrorsException, system.TypeLoadException, system.collections.generic.KeyNotFoundException, system.NullReferenceException, system.globalization.CultureNotFoundException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("MaxNameTableCharCount", MaxNameTableCharCount); } catch (JCNativeException jcne) { throw translateException(jcne); } } public int getMaxStringContentLength() throws Throwable, system.ArgumentNullException, system.ObjectDisposedException, system.threading.AbandonedMutexException, system.ArgumentException, system.InvalidOperationException, system.reflection.AmbiguousMatchException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.NotSupportedException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.IndexOutOfRangeException, system.configuration.ConfigurationErrorsException, system.TypeLoadException, system.collections.generic.KeyNotFoundException, system.configuration.ConfigurationException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (int)classInstance.Get("MaxStringContentLength"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setMaxStringContentLength(int MaxStringContentLength) throws Throwable, system.ArgumentNullException, system.ObjectDisposedException, system.threading.AbandonedMutexException, system.ArgumentException, system.InvalidOperationException, system.reflection.AmbiguousMatchException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.NotSupportedException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.IndexOutOfRangeException, system.configuration.ConfigurationErrorsException, system.TypeLoadException, system.collections.generic.KeyNotFoundException, system.NullReferenceException, system.globalization.CultureNotFoundException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("MaxStringContentLength", MaxStringContentLength); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Instance Events section }
[ "mario.mastrodicasa@masesgroup.com" ]
mario.mastrodicasa@masesgroup.com
1e3dce8fc24c383c197066a2caae4e13a72a242f
2240a39c09db4a74c1c80c737bc5399bbe10a824
/app/src/main/java/com/team2052/frckrawler/fragments/event/EventInfoFragment.java
8b9e13f966e0d47be38f2318495b09e0521e5531
[ "MIT" ]
permissive
MAKtheUnknown/FRC-Krawler
96c8bccc2315cc68175ff88d1e90598fb17738a3
166052279a206e2a525812c0522d7a1b86f7711e
refs/heads/master
2020-12-25T20:43:01.165372
2016-09-16T01:36:34
2016-09-16T01:36:34
59,162,880
0
0
null
2016-05-19T01:11:43
2016-05-19T01:11:42
null
UTF-8
Java
false
false
4,810
java
package com.team2052.frckrawler.fragments.event; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.widget.AppCompatEditText; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.team2052.frckrawler.R; import com.team2052.frckrawler.activities.BaseActivity; import com.team2052.frckrawler.background.DeleteEventTask; import com.team2052.frckrawler.databinding.FragmentEventInfoBinding; import com.team2052.frckrawler.db.Event; import com.team2052.frckrawler.fragments.BaseFragment; import com.team2052.frckrawler.listeners.ListUpdateListener; import com.team2052.frckrawler.util.Util; /** * Created by adam on 6/15/15. */ public class EventInfoFragment extends BaseFragment implements ListUpdateListener { public static final String EVENT_ID = "EVENT_ID"; private FragmentEventInfoBinding binding; private Event mEvent; public static EventInfoFragment newInstance(Event event) { Bundle args = new Bundle(); args.putLong(EVENT_ID, event.getId()); EventInfoFragment fragment = new EventInfoFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); mEvent = mDbManager.getEventsTable().load(getArguments().getLong(EVENT_ID)); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_event_info, null); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); binding = FragmentEventInfoBinding.bind(view); updateList(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.edit_delete_menu, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_delete: buildDeleteDialog().show(); break; case R.id.menu_edit: buildEditDialog().show(); break; } return super.onOptionsItemSelected(item); } public AlertDialog buildDeleteDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Delete Event?"); builder.setMessage("Are you sure you want to delete this event?"); builder.setPositiveButton("Ok", (dialog, which) -> { new DeleteEventTask(getActivity(), mEvent, true).execute(); }); builder.setNegativeButton("Cancel", null); return builder.create(); } public AlertDialog buildEditDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); AppCompatEditText name = new AppCompatEditText(getActivity()); name.setText(mEvent.getName()); int padding = Util.getPixelsFromDp(getActivity(), 16); name.setPadding(padding, padding, padding, padding); builder.setView(name); builder.setTitle("Edit Event"); builder.setPositiveButton("Ok", (dialog, which) -> { mEvent.setName(name.getText().toString()); mEvent.update(); ((BaseActivity) getActivity()).setActionBarSubtitle(mEvent.getName()); }); builder.setNegativeButton("Cancel", null); return builder.create(); } @Override public void updateList() { new LoadEventInfo().execute(); } public class LoadEventInfo extends AsyncTask<Void, Void, Void> { int numOfTeams = 0; int numOfMatches = 0; int numOfPitData = 0; int numOfMatchData = 0; @Override protected Void doInBackground(Void... params) { numOfTeams = mDbManager.getEventsTable().getRobotEvents(mEvent).size(); numOfMatches = mDbManager.getEventsTable().getMatches(mEvent).size(); numOfPitData = mDbManager.getEventsTable().getPitData(mEvent).size(); numOfMatchData = mDbManager.getEventsTable().getMatchData(mEvent).size(); return null; } @Override protected void onPostExecute(Void aVoid) { binding.setNumOfTeams(numOfTeams); binding.setNumOfMatches(numOfMatches); binding.setNumOfPitData(numOfPitData); binding.setNumOfMatchData(numOfMatchData); } } }
[ "Acorpstein8234@gmail.com" ]
Acorpstein8234@gmail.com
aee59c84b369052837c8a348681af7d203720df3
64ffe1830175e4d7d4612d57e16d06cde298ca86
/avro-serialization/producer/src/test/java/com/example/producer02/Producer02ApplicationTests.java
13634c19fbacb7926053b91625eb19c2a620b089
[]
no_license
vking34/basic-kafka
79e5b41c5b3a5de95049fd4e4e403285d1972d33
6ce3566d2e74de04ae0209d3ae382d5928b87876
refs/heads/master
2022-11-30T20:00:42.366093
2020-08-20T04:48:10
2020-08-20T04:48:10
288,418,548
0
0
null
null
null
null
UTF-8
Java
false
false
227
java
package com.example.producer02; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class Producer02ApplicationTests { @Test void contextLoads() { } }
[ "lzzvkingzzl@gmail.com" ]
lzzvkingzzl@gmail.com
26ce00e3af4d98d86a4756d8626844ee3210b132
18c267316085f9f6df83e13ba50a0455e6386d45
/_51Park/build/generated/source/buildConfig/androids/debug/cn/com/unispark/BuildConfig.java
cc2ac112c94a775031d3984cb1c6a0e050de2c8d
[]
no_license
Sunnyfor/51Park
e2fae32728bbca2f28c3f10b5d87365368794333
8c8a9cb31fcf8e53b06762b62b93006d4abcd533
refs/heads/master
2020-09-30T10:17:27.233421
2019-12-11T03:07:41
2019-12-11T03:07:41
227,263,238
0
0
null
null
null
null
UTF-8
Java
false
false
449
java
/** * Automatically generated file. DO NOT MODIFY */ package cn.com.unispark; public final class BuildConfig { public static final boolean DEBUG = Boolean.parseBoolean("true"); public static final String APPLICATION_ID = "cn.com.unispark"; public static final String BUILD_TYPE = "debug"; public static final String FLAVOR = "androids"; public static final int VERSION_CODE = 110; public static final String VERSION_NAME = "5.4.0"; }
[ "yongzuo.chen@foxmail.com" ]
yongzuo.chen@foxmail.com
422cedeb77e195f70dfe27fc45f8fb04507baf80
311a0d7e7dcacf2312fc7a01a37dbc62770306e2
/src/main/java/com/caoc/test/proxy/Hello.java
d0fc6e803170d4f4751176b6321c29efe5d232a7
[]
no_license
aizen1984/all-test
d7cc93cdf22d756be92c93d7db79ec567469e9ec
7af729da7f3d4333a47254588aa309a2d1b685c9
refs/heads/master
2022-06-28T22:25:08.874297
2021-08-30T08:56:59
2021-08-30T08:56:59
207,789,556
1
0
null
2022-06-17T02:48:56
2019-09-11T10:54:35
Java
UTF-8
Java
false
false
116
java
package com.caoc.test.proxy; public interface Hello { void sayHello(String name); void sayHello2(String name); }
[ "n_f.s@163.com" ]
n_f.s@163.com
bac72a908b0e50608276524e0b62c5cdba346e4c
76f64ad9882cc74af57047544aa80b1aa9d1e344
/src/Model/Room.java
08e9a505453a539a837f6c97c14072dbe8d2e494
[]
no_license
ywj657947813/Dormitorymanagement
a4226aa3da701e2e03bdd462887eafeb42ab2a33
f65e4e63afd1e2015869dec119484cd9dff00dbf
refs/heads/master
2021-06-27T22:00:13.854191
2017-09-18T02:39:40
2017-09-18T02:54:43
103,879,807
2
1
null
null
null
null
UTF-8
Java
false
false
623
java
package Model; public class Room { String id; String roomno; String dormno; public Room() { super(); // TODO Auto-generated constructor stub } public Room(String id, String roomno, String dormno) { super(); this.id = id; this.roomno = roomno; this.dormno = dormno; } public String getRoomno() { return roomno; } public void setRoomno(String roomno) { this.roomno = roomno; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDormno() { return dormno; } public void setDormno(String dormno) { this.dormno = dormno; } }
[ "30714806+ywj657947813@users.noreply.github.com" ]
30714806+ywj657947813@users.noreply.github.com
d03a63e47208b9b115c53f833781db3a29574276
18fe28e1846feae194ec1de58b75150297c7c46a
/xroad-catalog-lister/src/main/java/fi/vrk/xroad/catalog/lister/ServiceController.java
d692bac5e5031275ee2aaf10572f78b1305dc527
[ "MIT", "Apache-2.0" ]
permissive
andresmmujica/xroad-catalog
d24ab5af9fce4f5b2b4754949879eb52bdc6dac6
3392d48b7b5f61511c013da74a808c541c89b607
refs/heads/master
2023-01-03T01:57:23.728300
2020-10-29T11:28:34
2020-10-29T11:28:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
12,511
java
/** * The MIT License * Copyright (c) 2020, Population Register Centre (VRK) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package fi.vrk.xroad.catalog.lister; import fi.vrk.xroad.catalog.persistence.dto.SecurityServerInfo; import fi.vrk.xroad.catalog.persistence.CatalogService; import fi.vrk.xroad.catalog.persistence.dto.ListOfServicesResponse; import fi.vrk.xroad.catalog.persistence.dto.MemberDataList; import fi.vrk.xroad.catalog.persistence.dto.ServiceStatistics; import fi.vrk.xroad.catalog.persistence.dto.ServiceStatisticsResponse; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.core.io.ByteArrayResource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.xml.sax.SAXException; import java.io.IOException; import java.io.StringWriter; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import javax.ws.rs.core.*; import javax.xml.parsers.ParserConfigurationException; @RestController @RequestMapping("/api") @PropertySource("classpath:lister.properties") public class ServiceController { @Value("${xroad-catalog.max-history-length-in-days}") private Integer maxHistoryLengthInDays; @Value("${xroad-catalog.shared-params-file}") private String sharedParamsFile; @Autowired private CatalogService catalogService; @Autowired private SharedParamsParser sharedParamsParser; @GetMapping(path = "/getServiceStatistics/{historyAmountInDays}", produces = "application/json") public ResponseEntity<?> getServiceStatistics(@PathVariable Long historyAmountInDays) { if (historyAmountInDays < 1 || historyAmountInDays > maxHistoryLengthInDays) { return new ResponseEntity<>( "Input parameter historyAmountInDays must be greater " + "than zero and less than the required maximum of " + maxHistoryLengthInDays + " days", HttpStatus.BAD_REQUEST); } List<ServiceStatistics> serviceStatisticsList = catalogService.getServiceStatistics(historyAmountInDays); if (serviceStatisticsList == null || serviceStatisticsList.isEmpty()) { return ResponseEntity.noContent().build(); } else { return ResponseEntity.ok(ServiceStatisticsResponse.builder().serviceStatisticsList(serviceStatisticsList).build()); } } @GetMapping(path = "/getServiceStatisticsCSV/{historyAmountInDays}", produces = "text/csv") public ResponseEntity<?> getServiceStatisticsCSV(@PathVariable Long historyAmountInDays) { if (historyAmountInDays < 1 || historyAmountInDays > maxHistoryLengthInDays) { return new ResponseEntity<>( "Input parameter historyAmountInDays must be greater " + "than zero and less than the required maximum of " + maxHistoryLengthInDays + " days", HttpStatus.BAD_REQUEST); } List<ServiceStatistics> serviceStatisticsList = catalogService.getServiceStatistics(historyAmountInDays); if (serviceStatisticsList != null) { try { StringWriter sw = new StringWriter(); CSVPrinter csvPrinter = new CSVPrinter(sw, CSVFormat.DEFAULT .withHeader("Date", "Number of REST services", "Number of SOAP services", "Total distinct services")); serviceStatisticsList.forEach(serviceStatistics -> printCSVRecord(csvPrinter, Arrays.asList(serviceStatistics.getCreated().toString(), serviceStatistics.getNumberOfRestServices().toString(), serviceStatistics.getNumberOfSoapServices().toString(), serviceStatistics.getTotalNumberOfDistinctServices().toString()))); String reportName = "service_statistics_" + LocalDateTime.now().toString(); sw.close(); csvPrinter.close(); return ResponseEntity.ok() .header("Content-Disposition", "attachment; filename=" + reportName + ".csv") .contentType(org.springframework.http.MediaType.parseMediaType("text/csv")) .body(new ByteArrayResource(sw.toString().getBytes())); } catch (IOException e) { e.printStackTrace(); } } return ResponseEntity.noContent().build(); } @GetMapping(path = "/getListOfServices/{historyAmountInDays}", produces = "application/json") public ResponseEntity<?> getListOfServices(@PathVariable Long historyAmountInDays) { if (historyAmountInDays < 1 || historyAmountInDays > maxHistoryLengthInDays) { return new ResponseEntity<>( "Input parameter historyAmountInDays must be greater " + "than zero and less than the required maximum of " + maxHistoryLengthInDays + " days", HttpStatus.BAD_REQUEST); } List<SecurityServerInfo> securityServerList = getSecurityServerData(); List<MemberDataList> memberDataList = catalogService.getMemberData(historyAmountInDays); if (memberDataList != null) { return ResponseEntity.ok(ListOfServicesResponse.builder() .memberData(memberDataList) .securityServerData(securityServerList) .build()); } else { return ResponseEntity.noContent().build(); } } @GetMapping(path = "/getListOfServicesCSV/{historyAmountInDays}", produces = "text/csv") public ResponseEntity<?> getListOfServicesCSV(@PathVariable Long historyAmountInDays) { if (historyAmountInDays < 1 || historyAmountInDays > maxHistoryLengthInDays) { return new ResponseEntity<>( "Input parameter historyAmountInDays must be greater " + "than zero and less than the required maximum of " + maxHistoryLengthInDays + " days", HttpStatus.BAD_REQUEST); } List<SecurityServerInfo> securityServerList = getSecurityServerData(); List<MemberDataList> memberDataList = catalogService.getMemberData(historyAmountInDays); if (memberDataList != null) { try { StringWriter sw = new StringWriter(); CSVPrinter csvPrinter = new CSVPrinter(sw, CSVFormat.DEFAULT .withHeader("Date", "XRoad instance", "Member class", "Member code", "Member name", "Member created", "Subsystem code", "Subsystem created", "Service code", "Service version", "Service created")); printListOfServicesCSV(csvPrinter, memberDataList, securityServerList); String reportName = "list_of_services_" + LocalDateTime.now().toString(); sw.close(); csvPrinter.close(); return ResponseEntity.ok() .header("Content-Disposition", "attachment; filename=" + reportName + ".csv") .contentType(org.springframework.http.MediaType.valueOf(MediaType.TEXT_PLAIN)) .body(new ByteArrayResource(sw.toString().getBytes())); } catch (IOException e) { e.printStackTrace(); } } return ResponseEntity.noContent().build(); } private void printCSVRecord(CSVPrinter csvPrinter, List<String> data) { try { csvPrinter.printRecord(data); } catch (IOException e) { e.printStackTrace(); } } private void printListOfServicesCSV(CSVPrinter csvPrinter, List<MemberDataList> memberDataList, List<SecurityServerInfo> securityServerList) { memberDataList.forEach(memberList -> { printCSVRecord(csvPrinter, Arrays.asList(memberList.getDate().toString(), "", "", "", "", "", "", "", "", "", "")); memberList.getMemberDataList().forEach(memberData -> { String memberCreated = memberData.getCreated().toString(); String xRoadInstance = memberData.getXRoadInstance(); String memberClass = memberData.getMemberClass(); String memberCode = memberData.getMemberCode(); String memberName = memberData.getName(); if (memberData.getSubsystemList().isEmpty() || memberData.getSubsystemList() == null) { printCSVRecord(csvPrinter, Arrays.asList("", xRoadInstance, memberClass, memberCode, memberName, memberCreated, "", "", "", "", "")); } memberData.getSubsystemList().forEach(subsystemData -> { if (subsystemData.getServiceList().isEmpty() || subsystemData.getServiceList() == null) { printCSVRecord(csvPrinter, Arrays.asList("", xRoadInstance, memberClass, memberCode, memberName, memberCreated, subsystemData.getSubsystemCode(), subsystemData.getCreated().toString(), "", "", "")); } subsystemData.getServiceList().forEach(serviceData -> printCSVRecord(csvPrinter, Arrays.asList( "", xRoadInstance, memberClass, memberCode, memberName, memberCreated, subsystemData.getSubsystemCode(), subsystemData.getCreated().toString(), serviceData.getServiceCode(), serviceData.getServiceVersion(), serviceData.getCreated().toString()))); }); }); }); if (securityServerList != null && !securityServerList.isEmpty()) { printCSVRecord(csvPrinter, Arrays.asList("", "Security server (SS) info:", "", "", "", "", "", "", "", "", "")); printCSVRecord(csvPrinter, Arrays.asList("member class", "member code", "server code", "address", "", "", "", "", "","", "")); securityServerList.forEach(securityServerInfo -> printCSVRecord(csvPrinter, Arrays.asList(securityServerInfo.getMemberClass(), securityServerInfo.getMemberCode(), securityServerInfo.getServerCode(), securityServerInfo.getAddress() , "", "", "", "", "", "", ""))); } } private List<SecurityServerInfo> getSecurityServerData() { List<SecurityServerInfo> securityServerList = new ArrayList<>(); try { Set<SecurityServerInfo> securityServerInfos = sharedParamsParser.parse(sharedParamsFile); if (securityServerInfos.iterator().hasNext()) { securityServerList = new ArrayList<>(securityServerInfos); } } catch (ParserConfigurationException | IOException | SAXException e) { throw new RuntimeException(e); } return securityServerList; } }
[ "bert.viikmae@gofore.com" ]
bert.viikmae@gofore.com
cbf8337852668d3fcbdf2ef396a86de9b09c9bea
21187a0f7fa8a45180a0368b6e8ec22bc19e7ed3
/TareaEstructuradedatos/src/main/java/Unidad4_ejercicio2/NodoHijo.java
b33864451c89697879701db6eaf418da1d4c483f
[]
no_license
Alexis-e/Tarea
7aba363dff302eaa7f413474b24ae608838c10f6
089bcf361cf41bb39a4cfffc4a9c3a4a91d1c919
refs/heads/main
2023-05-15T21:43:22.078804
2021-06-14T05:52:53
2021-06-14T05:52:53
376,713,474
0
0
null
null
null
null
UTF-8
Java
false
false
229
java
package Unidad4_ejercicio2; public class NodoHijo { NodoGeneral direccionHijo; NodoHijo ant, sig; public NodoHijo(NodoGeneral HijoApuntar){ direccionHijo = HijoApuntar; ant = sig = null; } }
[ "noreply@github.com" ]
noreply@github.com
44c9b01ec9e7e12444c3e7814297c8aadd850838
7753166224bbfa9816114e4d7b247d568c3614f0
/src/com/javarush/test/level15/lesson12/home04/Solution.java
1f1893207dda996711a0285a4a603605d00396af
[]
no_license
CruelIks/JavaRushHomeWork
dc6af567d5a12df8f7048ea6a6e98938295541bb
210a86f2b88031791feba175f9baf3b713878486
refs/heads/master
2021-01-18T23:20:59.544294
2016-09-16T17:53:06
2016-09-16T17:53:06
51,065,329
0
0
null
null
null
null
UTF-8
Java
false
false
1,719
java
package com.javarush.test.level15.lesson12.home04; /* Закрепляем Singleton pattern 1. Найти в гугле пример для - Singleton pattern Lazy initialization. 2. По образу и подобию в отдельных файлах создать три синглтон класса Sun, Moon, Earth. 3. Реализовать интерфейс Planet для классов Sun, Moon, Earth. 4. В статическом блоке класса Solution вызвать метод readKeyFromConsoleAndInitPlanet. 5. Реализовать функционал метода readKeyFromConsoleAndInitPlanet: 5.1. С консоли считать один параметр типа String. 5.2. Если параметр равен одной из констант интерфейса Planet, то создать соответствующий объект и присвоить его Planet thePlanet, иначе обнулить Planet thePlanet. 5.3. Сравнивать введенный параметр можно только с константами из Planet, нельзя создавать свои строки. */ import java.util.Scanner; public class Solution { public static Planet thePlanet; static { readKeyFromConsoleAndInitPlanet(); } public static void readKeyFromConsoleAndInitPlanet() { Scanner sc = new Scanner(System.in); String line = sc.nextLine(); if (line.equals(Planet.EARTH)) thePlanet = Earth.getInstance(); else if(line.equals(Planet.SUN)) thePlanet = Sun.getInstance(); else if(line.equals(Planet.MOON)) thePlanet = Moon.getInstance(); else thePlanet = null; } }
[ "iks.gog@gmail.com" ]
iks.gog@gmail.com
585326737a46178e86566f8d7b4b69085e919e9d
14ba819674e9852b6750fc294c85892fabd2bec4
/Crux29Dec/src/Lec2/Pattern13.java
5d726b3af877773a4595920c06e9df313ab94a31
[]
no_license
rishichaurasia/Java-Programming
f2de81af2da334140f69f4a8ed92033ccbc46139
7cc1b3ec18896f602505a79438c825438a8e01e0
refs/heads/master
2021-07-19T02:15:47.560672
2021-01-13T13:14:52
2021-01-13T13:14:52
231,965,087
2
3
null
2020-10-15T17:10:56
2020-01-05T19:26:00
Java
UTF-8
Java
false
false
423
java
package Lec2; import java.util.Scanner; public class Pattern13 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scn = new Scanner(System.in); int n = scn.nextInt(); for (int row = 1, nst = 1; row <= 2 * n - 1; row++) { for (int cst = 1; cst <= nst; cst++) { System.out.print("*"); } if (row < n) nst++; else nst--; System.out.println(); } } }
[ "rishi.r.chaurasia@gmail.com" ]
rishi.r.chaurasia@gmail.com
b3c7b06e1b6340e4e5a43b9841256145bbefa913
df0879c28ed47d8385e1ff46845cf1cf09169aed
/gradle-runner-agent/src/test/resources/testProjects/MultiProjectC/projectD/src/test/java/test/GradleGreeterDTest.java
870f7194653c46c87a61b63f658466ad90209970
[]
no_license
kamaljitsingh76/teamcity-gradle
bc263a3e442bb4dd58e98753c933a1ae034cc565
1458ac42b7ab6c8da7087b3fd7acfb2f6222643e
refs/heads/master
2022-12-05T18:47:51.237490
2020-09-03T15:57:31
2020-09-03T17:14:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
621
java
package test; import my.module.GreeterD; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; public class GradleGreeterDTest { private static final String HELLO_WORLD = "Hello, World!"; private static final String GRADLE_GUINEA_PIG = "I'm Project_D guinea pig"; @Test public void testGreet() throws Exception { Assert.assertEquals("Wrong greeting", HELLO_WORLD, GreeterD.greet()); } @Ignore @Test public void testIntro() throws Exception { Assert.assertEquals("Wrong greeter", GRADLE_GUINEA_PIG, GreeterD.intro()); } }
[ "Nikita.Skvortsov@jetbrains.com" ]
Nikita.Skvortsov@jetbrains.com
8e0d161459a5cac726c98ccc55bbd83e3bdfd697
e70ad89d6330389b6747630000fdaa999e2feded
/src/test/java/utilities/TestBase.java
a461f878f9a1261f53775909d3db94d96c1cc13d
[]
no_license
gokcestrbgz/chicagob11
9b62aaddfd50063677c32c5e3413754a47af0583
773c877d3f4625d6b5e52d658014987aad57d44f
refs/heads/master
2023-05-12T13:20:58.937768
2019-07-16T23:58:54
2019-07-16T23:58:54
196,084,142
0
0
null
2023-05-09T18:09:33
2019-07-09T21:08:37
Java
UTF-8
Java
false
false
914
java
package utilities; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.asserts.SoftAssert; import java.util.concurrent.TimeUnit; public class TestBase { public WebDriver driver; SoftAssert softAssert; @BeforeClass public void beforeClass() { WebDriverManager.chromedriver().setup(); } @BeforeMethod public void setUp() { driver = new ChromeDriver(); driver.manage().window().fullscreen(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); softAssert = new SoftAssert(); } @AfterMethod public void tearDown() throws InterruptedException{ softAssert.assertAll(); } }
[ "rgokcekadioglu@gmail.com" ]
rgokcekadioglu@gmail.com
bcf5231325d3ee08430f54df6bdcad23a664fa46
a78397c01fc417f37115d38ed014e293026dd853
/MyProject/app/src/main/java/com/android/pullview/IPullToZoom.java
8ac5b58c3c760576e751481320879bbc76d332b2
[]
no_license
KW000/shimaogit
4ab4db397109510849349311ef6d79908dcf9504
f91dd7843618930e0de64491296f19086d10aef0
refs/heads/master
2020-12-02T21:11:28.972791
2017-07-05T03:54:04
2017-07-05T03:54:04
96,268,935
0
0
null
null
null
null
UTF-8
Java
false
false
1,108
java
package com.android.pullview; import android.content.res.TypedArray; import android.view.View; public interface IPullToZoom<T extends View> { /** * Get the Wrapped Zoom View. Anything returned here has already been * added to the content view. * * @return The View which is currently wrapped */ public View getZoomView(); public View getHeaderView(); /** * Get the Wrapped root View. * * @return The View which is currently wrapped */ public T getPullRootView(); /** * Whether Pull-to-Refresh is enabled * * @return enabled */ public boolean isPullToZoomEnabled(); /** * Returns whether the Widget is currently in the Zooming state * * @return true if the Widget is currently zooming */ public boolean isZooming(); /** * Returns whether the Widget is currently in the Zooming anim type * * @return true if the anim is parallax */ public boolean isParallax(); public boolean isHideHeader(); public void handleStyledAttributes(TypedArray a); }
[ "shimao@tzbao.com" ]
shimao@tzbao.com
a1f82117bbac9976fd70e25b7e3ddc4fc6943e2b
dec6bd85db1d028edbbd3bd18fe0ca628eda012e
/netbeans-projects/TrabalhoPSII/SisComPizzariaServidor/src/control/funcoes/Dados.java
e2217c37594f2512caf2d5af9809f4126c23c9ca
[]
no_license
MatheusGrenfell/java-projects
21b961697e2c0c6a79389c96b588e142c3f70634
93c7bfa2e4f73a232ffde2d38f30a27f2a816061
refs/heads/master
2022-12-29T12:55:00.014296
2020-10-16T00:54:30
2020-10-16T00:54:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
450
java
package control.funcoes; import java.util.HashMap; public class Dados { private HashMap<String, String> dados; public Dados() { this.dados = new HashMap<>(); } public void addInfo(String dsChave, String info) { this.dados.put(dsChave, info); } public String getInfo(String dsChave) { return dados.get(dsChave); } public HashMap<String, String> getDados() { return dados; } }
[ "caiohobus@gmail.com" ]
caiohobus@gmail.com
ea755f1eaba6886a13e24705c760022ea123f959
ffed8f1647e924f4ef55b9eeed1aa00b95733eae
/Pilae_servicio/src/main/java/com/example/multimodule/repository/servicio/ensamblador/entidad/implementacion/EquipoEnsambladorEntidad.java
e89a99699c63b63ef222fb4472c85e9eb61c63f4
[]
no_license
juancamilosalazar/pilae
e8aba0c788ca0adcb009da09b43c1db8bf1b862f
7233efdedccbc892eb28cbbcd1efe65c4e224542
refs/heads/master
2023-04-19T21:06:21.254775
2021-05-05T18:01:25
2021-05-05T18:01:25
306,167,091
0
0
null
null
null
null
UTF-8
Java
false
false
2,247
java
package com.example.multimodule.repository.servicio.ensamblador.entidad.implementacion; import java.util.ArrayList; import java.util.List; import com.example.multimodule.dominio.EquipoDominio; import com.example.multimodule.entidad.EquipoEntidad; import com.example.multimodule.repository.servicio.ensamblador.entidad.EnsambladorEntidad; import com.example.multimodule.transversal.excepciones.PILAEDominioExcepcion; import com.example.multimodule.transversal.excepciones.base.TipoExcepcionEnum; import com.example.multimodule.transversal.utilitarios.UtilObjeto; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class EquipoEnsambladorEntidad implements EnsambladorEntidad<EquipoEntidad, EquipoDominio> { private ModelMapper modelMapper = new ModelMapper(); private static final EnsambladorEntidad<EquipoEntidad, EquipoDominio> instancia = new EquipoEnsambladorEntidad(); private EquipoEnsambladorEntidad() { } public static EnsambladorEntidad<EquipoEntidad, EquipoDominio> obtenerEquipoEnsambladorEntidad() { return instancia; } @Override public EquipoEntidad ensamblarEntidad(EquipoDominio dominio) { if (UtilObjeto.objetoEsNulo(dominio)) { String mensajeUsuario = "objeto nulo"; String mensajeTecnico = "objeto nulo"; throw PILAEDominioExcepcion.crear(TipoExcepcionEnum.NEGOCIO, mensajeUsuario, mensajeTecnico); } return modelMapper.map(dominio,EquipoEntidad.class); } @Override public EquipoDominio ensamblarDominio(EquipoEntidad entidad) { if (UtilObjeto.objetoEsNulo(entidad)) { String mensajeUsuario = "objeto nulo"; String mensajeTecnico = "objeto nulo"; throw PILAEDominioExcepcion.crear(TipoExcepcionEnum.NEGOCIO, mensajeUsuario, mensajeTecnico); } return modelMapper.map(entidad,EquipoDominio.class); } @Override public List<EquipoDominio> ensamblarListaDominio(List<EquipoEntidad> listaEntidades) { List<EquipoDominio> listaDominios = new ArrayList<>(); if (!UtilObjeto.objetoEsNulo(listaEntidades)) { for (EquipoEntidad equipoEntidad : listaEntidades) { listaDominios.add(ensamblarDominio(equipoEntidad)); } } return listaDominios; } }
[ "juan.camilo.salazar.zuluaga@gmail.com" ]
juan.camilo.salazar.zuluaga@gmail.com
696a13488e60b0ba5196c95bdb8a392029fcde94
94228df04c8d71ef72d0278ed049e9eac43566bc
/modules/projectroyalty/projectroyalty-consumer/src/main/java/com/bjike/goddess/projectroyalty/action/projectroyalty/ContractAmountAction.java
2249e7af5ff4a54c65ac2c9bbce15599ad5fb3bc
[]
no_license
yang65700/goddess-java
b1c99ac4626c29651250969d58d346b7a13eb9ad
3f982a3688ee7c97d8916d9cb776151b5af8f04f
refs/heads/master
2021-04-12T11:10:39.345659
2017-09-12T02:32:51
2017-09-12T02:32:51
126,562,737
0
0
null
2018-03-24T03:33:53
2018-03-24T03:33:53
null
UTF-8
Java
false
false
4,652
java
package com.bjike.goddess.projectroyalty.action.projectroyalty; import com.bjike.goddess.common.api.entity.ADD; import com.bjike.goddess.common.api.entity.EDIT; import com.bjike.goddess.common.api.exception.ActException; import com.bjike.goddess.common.api.exception.SerException; import com.bjike.goddess.common.api.restful.Result; import com.bjike.goddess.common.consumer.restful.ActResult; import com.bjike.goddess.common.utils.bean.BeanTransform; import com.bjike.goddess.projectroyalty.api.ContractAmountAPI; import com.bjike.goddess.projectroyalty.dto.ContractAmountDTO; import com.bjike.goddess.projectroyalty.to.ContractAmountTO; import com.bjike.goddess.projectroyalty.vo.ContractAmountVO; import com.bjike.goddess.projectroyalty.vo.OpinionVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; /** * 合同金额 * * @Author: [ dengjunren ] * @Date: [ 2017-06-07 09:45 ] * @Description: [ 合同金额 ] * @Version: [ v1.0.0 ] * @Copy: [ com.bjike ] */ @RestController @RequestMapping("contractamount") public class ContractAmountAction { @Autowired private ContractAmountAPI contractAmountAPI; /** * 保存 * * @param to 合同金额传输对象 * @return class ContractAmountVO * @version v1 */ @PostMapping("v1/save") public Result save(@Validated(ADD.class) ContractAmountTO to, BindingResult result) throws ActException { try { return ActResult.initialize(BeanTransform.copyProperties(contractAmountAPI.save(to), ContractAmountVO.class)); } catch (SerException e) { throw new ActException(e.getMessage()); } } /** * 修改 * * @param to 合同金额传输对象 * @return class ContractAmountVO * @version v1 */ @PutMapping("v1/update/{id}") public Result update(@Validated(EDIT.class) ContractAmountTO to, BindingResult result) throws ActException { try { return ActResult.initialize(BeanTransform.copyProperties(contractAmountAPI.update(to), ContractAmountVO.class)); } catch (SerException e) { throw new ActException(e.getMessage()); } } /** * 删除 * * @param id 合同金额数据id * @return class ContractAmountVO * @version v1 */ @DeleteMapping("v1/delete/{id}") public Result delete(@Validated String id) throws ActException { try { return ActResult.initialize(BeanTransform.copyProperties(contractAmountAPI.delete(id), ContractAmountVO.class)); } catch (SerException e) { throw new ActException(e.getMessage()); } } /** * 根据id获取合同金额数据 * * @param id 合同金额数据id * @return class ContractAmountVO * @version v1 */ @GetMapping("v1/findById/{id}") public Result getById(@Validated String id) throws ActException { try { return ActResult.initialize(BeanTransform.copyProperties(contractAmountAPI.getById(id), ContractAmountVO.class)); } catch (SerException e) { throw new ActException(e.getMessage()); } } /** * 获取选项 * * @return class OpinionVO * @version v1 */ @GetMapping("v1/findOpinion") public Result findOpinion() throws ActException { try { return ActResult.initialize(BeanTransform.copyProperties(contractAmountAPI.findOpinion(), OpinionVO.class)); } catch (SerException e) { throw new ActException(e.getMessage()); } } /** * 列表 * * @param dto 合同金额数据传输对象 * @return class ContractAmountVO * @version v1 */ @GetMapping("v1/maps") public Result maps(ContractAmountDTO dto, HttpServletRequest request) throws ActException { try { return ActResult.initialize(BeanTransform.copyProperties(contractAmountAPI.maps(dto), ContractAmountVO.class, request)); } catch (SerException e) { throw new ActException(e.getMessage()); } } /** * 获取总条数 * * @version v1 */ @GetMapping("v1/getTotal") public Result getTotal() throws ActException { try { return ActResult.initialize(contractAmountAPI.getTotal()); } catch (SerException e) { throw new ActException(e.getMessage()); } } }
[ "196329217@qq.com" ]
196329217@qq.com
f4ee1473ac04100bfdec6a642b1775f50888a0c4
4f4e8b46db3328510c222247cb05a9ef978ce84e
/CodigoFuente/Proyecto/Proyecto-ejb/src/java/cl/uv/proyecto/persistencia/ejb/ComentarioSolicitudFacade.java
8fe000db2dad532efb124542b8721684f0e8a487
[]
no_license
yano2h/TESIS
46c2faad7a79abe37a52fa366a916bd3f3848e41
6c3d1f165497ef689c394f63c65b4b3fde8b3e27
refs/heads/master
2021-01-19T05:44:10.667446
2013-01-29T03:53:38
2013-01-29T03:53:38
3,670,899
1
0
null
null
null
null
UTF-8
Java
false
false
1,338
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package cl.uv.proyecto.persistencia.ejb; import cl.uv.proyecto.persistencia.entidades.ComentarioSolicitud; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; /** * * @author Jano */ @Stateless public class ComentarioSolicitudFacade extends AbstractFacade<ComentarioSolicitud> implements ComentarioSolicitudFacadeLocal { @PersistenceContext(unitName = "Proyecto-ejbPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public ComentarioSolicitudFacade() { super(ComentarioSolicitud.class); } @Override public void remove(ComentarioSolicitud c){ super.remove(find(c.getIdComentario())); } @Override public List<ComentarioSolicitud> buscarComentariosPorSolicitud(Long idSolicitudRequerimiento){ System.out.println("/*Buscar Comentarios*/"); TypedQuery<ComentarioSolicitud> q = em.createNamedQuery("ComentarioSolicitud.findByIdSolicitud", ComentarioSolicitud.class); q.setParameter("id", idSolicitudRequerimiento); return q.getResultList(); } }
[ "yano2h@gmail.com" ]
yano2h@gmail.com
5fe01ef827271ebfcf893d6d9ca40dfd4cbab0c2
232fdda858eb32ceb1240999ff14680aec38da79
/Library/BaiduMap/src/cn/softnado/Gwt/Map/Baidu/Client/Dom/Service/GeolocationResult.java
571ab37ef8a2708fbce9f269500bcd1bb91ca065
[]
no_license
besafinado/snmapforbaidu
c28b8b847fd2f9f0604a31f9afa16b1d8748e906
d367faebea3fa95075f3f150d32611c233964bed
refs/heads/master
2020-05-30T15:56:40.479211
2013-10-12T08:30:59
2013-10-12T08:30:59
35,956,187
1
0
null
null
null
null
UTF-8
Java
false
false
438
java
package cn.softnado.Gwt.Map.Baidu.Client.Dom.Service; import cn.softnado.Gwt.Map.Baidu.Client.Dom.Base.Point; import com.google.gwt.core.client.JavaScriptObject; public class GeolocationResult extends JavaScriptObject { protected GeolocationResult() { } public final native Point getPoint() /*-{ return this.point; }-*/; public final native double getAccuracy() /*-{ return this.accuracy; }-*/; }
[ "daniel.softnado@gmail.com@2f53b927-c39d-b057-4287-c099bb29d176" ]
daniel.softnado@gmail.com@2f53b927-c39d-b057-4287-c099bb29d176
fb9b2385476425d44a4bba3d7563b2acfc69f550
a885d4206fb60ca7229b3f017220dc8091dd92d2
/src/main/java/hr/barisic/ivan/fejkbuk/exception/nonexistentresource/NonexistentPersonException.java
963f79368fa67d15f2206cb700eea152aeda40cf
[]
no_license
IBarisic1/fakebook
4ee924b01ca4499f73e843124949311b1f0dfab2
d53031652e11a1d9ca660a2100071c0120e212ae
refs/heads/master
2022-12-31T05:33:24.920953
2020-10-04T16:40:04
2020-10-04T16:40:04
301,204,125
0
0
null
null
null
null
UTF-8
Java
false
false
510
java
package hr.barisic.ivan.fejkbuk.exception.nonexistentresource; public class NonexistentPersonException extends NonexistentResourceException { private static final String MESSAGE = "The person doesn't exist!"; public NonexistentPersonException() { super(MESSAGE); } public NonexistentPersonException(String message) { super(message); } public NonexistentPersonException(long personId) { super("The person with id='" + personId + "' doesn't exist!"); } }
[ "ivan.barisic@snt.hr" ]
ivan.barisic@snt.hr
b4c4975d7e81fe80cc3f565cc0fa6ee96274df8c
fe13adac8aabb12171860b4d64f51074cc3f1d75
/src/main/java/com/gas/web/service/IWorkflowService.java
651b45bb1cbac52400cd4347b95d44c91f15b960
[]
no_license
DongyuanPan/GAS-UI
6c40786d4229c48bda1ff2d57b00a8c3b8670d20
7a67af7bd653cbaa399b8f0587af4e748cb79cf9
refs/heads/master
2022-07-01T05:50:07.207414
2021-03-08T08:43:31
2021-03-08T08:43:31
221,342,828
4
8
null
2022-06-17T02:39:29
2019-11-13T01:02:27
Java
UTF-8
Java
false
false
528
java
package com.gas.web.service; import com.gas.web.entity.Student; import com.gas.web.entity.Workflow; import java.util.List; import java.util.Map; public interface IWorkflowService { Map<String, Object> workflowFindAll(); Workflow workflowFindById(Integer id); List<Workflow> workflowFindByInformation(String information); Workflow workflowUpdate(Workflow workflow); Workflow workflowAdd(Workflow workflow); void workflowDelete(Integer id); void workflowDeleteBatch(List<Workflow> stuList); }
[ "723211376@qq.com" ]
723211376@qq.com
43058fc66e30aef13f00a84e7a80b9477cbd6771
dea32ceae6ceb694876120a29c85e20b1e72ed7d
/app/src/main/java/arabulkazan/albatros/com/arabulkazan/Fragments/Revenues.java
8656f97fa57d65c07bc4252b95c07d0fffe7983e
[]
no_license
hacegan/arabulkazan
0166a0158bcfa3528c254030073e401c3a19db6f
2854af14bc7d31e4cc0c134fb8076285a1f53b5d
refs/heads/master
2020-03-11T16:12:24.258140
2018-05-07T13:55:02
2018-05-07T13:55:02
130,109,406
0
0
null
null
null
null
UTF-8
Java
false
false
10,041
java
package arabulkazan.albatros.com.arabulkazan.Fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.MobileAds; import com.google.android.gms.ads.reward.RewardItem; import com.google.android.gms.ads.reward.RewardedVideoAd; import com.google.android.gms.ads.reward.RewardedVideoAdListener; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.text.SimpleDateFormat; import java.util.Date; import arabulkazan.albatros.com.arabulkazan.Helpers.Data; import arabulkazan.albatros.com.arabulkazan.Helpers.UI; import arabulkazan.albatros.com.arabulkazan.Pojos.Mywallet_Pojo; import arabulkazan.albatros.com.arabulkazan.Pojos.Result; import arabulkazan.albatros.com.arabulkazan.R; import arabulkazan.albatros.com.arabulkazan.Helpers.Constants; /** * Created by PC on 29.03.2018. */ public class Revenues extends android.support.v4.app.Fragment implements View.OnClickListener { AdView ad; public RewardedVideoAd gecis; Button btn; static String videoit = "", videoft = ""; private TextView tur, tutar, tarih, tarih1, tarih2,zenmiktar; Button anket_doldur,takiple_kazan,gizli_musteri,hizmet_kazancı; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_revenues, container, false); TextView izleKazanButton = (TextView) root.findViewById(R.id.btn_izle_kazan); //anket doldur,takiple kazan,gizli musteri,hizmet kazancı anket_doldur=root.findViewById(R.id.anket_doldur_btn); takiple_kazan=root.findViewById(R.id.takiple_kazan_btn); gizli_musteri=root.findViewById(R.id.gizli_musteri_btn); hizmet_kazancı=root.findViewById(R.id.hizmet_kazanci_btn); // anket_doldur.setOnClickListener(this); // takiple_kazan.setOnClickListener(this); // gizli_musteri.setOnClickListener(this); // hizmet_kazancı.setOnClickListener(this);//layout dosyası editlenecek ve buralar aktif hale gelicek. zenmiktar=root.findViewById(R.id.zencounttxt); izleKazanButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(Revenues.this.getActivity(), "Test Denemeler", Toast.LENGTH_SHORT).show(); } }); ad = (AdView) root.findViewById(R.id.adView); // ad.setAdUnitId(""); // // ad.setAdSize(AdSize.BANNER); final AdRequest request = new AdRequest.Builder() .build(); ad.loadAd(request); ad.setAdListener(new AdListener() { @Override public void onAdClosed() { super.onAdClosed(); } @Override public void onAdFailedToLoad(int i) { super.onAdFailedToLoad(i); } @Override public void onAdLeftApplication() { super.onAdLeftApplication(); } @Override public void onAdOpened() { Toast.makeText(getContext(), "Tebrikler kazancınız hesabınıza eklendi.", Toast.LENGTH_SHORT).show(); videoit=videoft=String.valueOf(Constants.dateFormat.format(new Date())); // Data.kazancim(Revenues.this.getActivity(),UI.getString(Revenues.this.getActivity(),"tc"), UI.getString(Revenues.this.getActivity(),"pass"),videoit,videoft, new Data.OnPostExecuteListener() { // @Override // public void onPostExecute(String result) { // final Result sonuc = new Gson().fromJson(result, Result.class); // if (sonuc.getError().equals("1")) { // UI.showErrorDialog(Revenues.this.getActivity(), "Hata", sonuc.getMesssage(), null); // } else { // zenmiktar.setText( String.valueOf( Double.valueOf(zenmiktar.getText().toString().split(" Zen")[0] )+0.01 )+" Zen" ); // UI.showSuccesDialog(Revenues.this.getActivity(), "Başarılı", "Kazancınız Bakiyenize Eklendi", null); // } // // // } // }); super.onAdOpened(); } @Override public void onAdLoaded() { super.onAdLoaded(); } @Override public void onAdClicked() { super.onAdClicked(); } @Override public void onAdImpression() { super.onAdImpression(); } }); gecis = MobileAds.getRewardedVideoAdInstance(getContext()); btn = root.findViewById(R.id.btn_izle_kazan); // Data.reklamgecenzaman(Revenues.this.getActivity(),UI.getString(Revenues.this.getActivity(),"tc"), UI.getString(Revenues.this.getActivity(),"pass"), new Data.OnPostExecuteListener() { // @Override // public void onPostExecute(String result) { // final Result sonuc = new Gson().fromJson(result,Result.class); // if (sonuc.getError().equals("1")) { // UI.showErrorDialog(Revenues.this.getActivity(), "Hata", sonuc.getMesssage(), null); // } else { // // String cur_date=Constants.dateFormat.format(new Date()); // // String[] db_saat=sonuc.getTarih().split(" ")[1].split(":"); // // String[] cur_saat=cur_date.split(" ")[1].split(":"); // // int diff=Integer.valueOf(cur_saat[1])-Integer.valueOf(db_saat[1]); // // if(diff>5){ // btn.setEnabled(false); // } // // } // // // } // }); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btn.setEnabled(false); /* if(gecis.isLoaded()){ gecis.show(); }*/ gecis.setRewardedVideoAdListener( new RewardedVideoAdListener() { @Override public void onRewardedVideoAdLoaded() { System.out.println("Reklam Yüklendi!"); gecis.show(); btn.setEnabled(true); } @Override public void onRewardedVideoAdOpened() { } @Override public void onRewardedVideoStarted() { videoit=String.valueOf(Constants.dateFormat.format(new Date())); } @Override public void onRewardedVideoAdClosed() { } @Override public void onRewarded(RewardItem rewardItem) { videoft=String.valueOf(Constants.dateFormat.format(new Date())); Toast.makeText(getContext(), "Tebrikler kazancınız hesabınıza eklendi.", Toast.LENGTH_SHORT).show(); Data.kazancim(Revenues.this.getActivity(), UI.getString(Revenues.this.getActivity(),"tc"), UI.getString(Revenues.this.getActivity(),"pass"),videoit,videoft, new Data.OnPostExecuteListener() { @Override public void onPostExecute(String result) { final Result sonuc = new Gson().fromJson(result, Result.class); if (sonuc.getError().equals("1")) { UI.showErrorDialog(Revenues.this.getActivity(), "Hata", sonuc.getMesssage(), null); } else { zenmiktar.setText( String.valueOf( Double.valueOf(zenmiktar.getText().toString().split(" Zen")[0] )+0.01 )+" Zen" ); UI.showSuccesDialog(Revenues.this.getActivity(), "Başarılı", "Kazancınız Bakiyenize Eklendi", null); } } }); } @Override public void onRewardedVideoAdLeftApplication() { UI.showErrorDialog(Revenues.this.getActivity(), "Hata","Kazanç sağlayabilmeniz için videoyu sonuna kadar izlemeniz gerekiyor!", null); } @Override public void onRewardedVideoAdFailedToLoad(int i) { UI.showErrorDialog(Revenues.this.getActivity(), "Hata","Reklam Yüklenirken Bir hata oluştu!", null); } }); gecis.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build()); } }); MobileAds.initialize(getContext(), "ca-app-pub-3940256099942544~3347511713"); return root; } @Override public void onClick(View view) { Toast.makeText(Revenues.this.getContext(),"Yakında...",Toast.LENGTH_SHORT); } }
[ "samet822@hotmail.com" ]
samet822@hotmail.com
67347a7e743593c6c14916f8655871b5dc8d57b8
31b7456e8bc54e58775c26fe3d8c5f323a5b60bf
/MyMusicPlayer/app/src/main/java/com/vic/liteplayer/activity/SongListActivity.java
835cdbcbe1bf9c965a00f59fe3c36d3df65b05f8
[]
no_license
Vic7/AndroidFirstLine_ForPractice
8851105b7c2fc879e593365cce5cd319411a4fe6
cd2d4058f289730c407818dbbeaf2cceedb2e368
refs/heads/master
2021-01-15T12:41:55.224681
2016-08-09T03:57:33
2016-08-09T03:57:33
64,199,253
0
0
null
null
null
null
UTF-8
Java
false
false
5,327
java
package com.vic.liteplayer.activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleAdapter; import com.vic.liteplayer.R; import com.vic.liteplayer.method.Mp3Info; import com.vic.liteplayer.utils.MediaUtil; import java.util.HashMap; import java.util.List; public class SongListActivity extends AppCompatActivity { ListView list; List<Mp3Info> mp3Infos; // private HomeReceiver homeReceiver; // 自定义的广播接收器 // 一系列动作 public static final String UPDATE_ACTION = "com.wwj.action.UPDATE_ACTION"; // 更新动作 public static final String MUSIC_CURRENT = "com.wwj.action.MUSIC_CURRENT"; // 当前音乐改变动作 public static final String MUSIC_DURATION = "com.wwj.action.MUSIC_DURATION"; // 音乐时长改变动作 public static final String REPEAT_ACTION = "com.wwj.action.REPEAT_ACTION"; // 音乐重复改变动作 public static final String SHUFFLE_ACTION = "com.wwj.action.SHUFFLE_ACTION"; // 音乐随机播放动作 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_song_list); findView(); Scan(); setListener(); } private void findView() { list = (ListView)findViewById(R.id.songList); } private void setListener() { list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (mp3Infos != null) { Mp3Info mp3Info = mp3Infos.get(position); Intent intent = new Intent(SongListActivity.this, MainActivity.class); // 定义Intent对象,跳转到PlayerActivity intent.putExtra("listPosition", position); setResult(1, intent); finish(); } } }); } public void Scan() { mp3Infos = MediaUtil.getMp3Infos(SongListActivity.this); List<HashMap<String, String>> queues = MediaUtil.getMusicMaps(mp3Infos); SimpleAdapter adapter = new SimpleAdapter(this, queues, R.layout.song_list_item, new String[]{"title","artist","duration"}, new int[]{R.id.names,R.id.artist,R.id.duration}); list.setAdapter(adapter); } // 自定义的BroadcastReceiver,负责监听从Service传回来的广播 // public class HomeReceiver extends BroadcastReceiver { // // @Override // public void onReceive(Context context, Intent intent) { // String action = intent.getAction(); // if (action.equals(MUSIC_CURRENT)) { // // currentTime代表当前播放的时间 // currentTime = intent.getIntExtra("currentTime", -1); // musicDuration.setText(MediaUtil.formatTime(currentTime)); // } else if (action.equals(MUSIC_DURATION)) { // duration = intent.getIntExtra("duration", -1); // } else if (action.equals(UPDATE_ACTION)) { // // 获取Intent中的current消息,current代表当前正在播放的歌曲 // listPosition = intent.getIntExtra("current", -1); // if (listPosition >= 0) { // musicTitle.setText(mp3Infos.get(listPosition).getTitle()); // } // } else if (action.equals(REPEAT_ACTION)) { // repeatState = intent.getIntExtra("repeatState", -1); // switch (repeatState) { // case isCurrentRepeat: // 单曲循环 // repeatBtn // .setBackgroundResource(R.drawable.repeat_current_selector); // shuffleBtn.setClickable(false); // break; // case isAllRepeat: // 全部循环 // repeatBtn // .setBackgroundResource(R.drawable.repeat_all_selector); // shuffleBtn.setClickable(false); // break; // case isNoneRepeat: // 无重复 // repeatBtn // .setBackgroundResource(R.drawable.repeat_none_selector); // shuffleBtn.setClickable(true); // break; // } // } else if (action.equals(SHUFFLE_ACTION)) { // isShuffle = intent.getBooleanExtra("shuffleState", false); // if (isShuffle) { // isNoneShuffle = false; // shuffleBtn // .setBackgroundResource(R.drawable.shuffle_selector); // repeatBtn.setClickable(false); // } else { // isNoneShuffle = true; // shuffleBtn // .setBackgroundResource(R.drawable.shuffle_none_selector); // repeatBtn.setClickable(true); // } // } // } // // } }
[ "934983126@qq.com" ]
934983126@qq.com
b743daf5231a4fdb9f25535eabcf79570ccaa2e7
93db052fbe7a040fcea53e912d7fa341ec04b237
/tree/Count_leaf.java
12f0a86b0d035d64fa58e576fe95821787b1d600
[]
no_license
PratyPratyush/Code
d747e4102ff95dffd67cbfd8e3dfc0952e90b527
918813e83b3819a29a365726d81b76db77d3f3b6
refs/heads/master
2021-01-24T20:12:48.986230
2018-05-22T04:00:23
2018-05-22T04:00:23
123,244,646
0
0
null
null
null
null
UTF-8
Java
false
false
1,046
java
import java.io.*; import java.util.*; class Count_leaf { static int count =0; Node head; class Node { int data; Node left; Node right; Node(int info){ data = info; left = null; right = null; } } int half_count(Node ptr) { if(ptr==null) return 0; int left = half_count(ptr.left); int right = half_count(ptr.right); if(left == right) return 1; else if(left != right){ count++; } return 1; } public static void main(String args[]) { Count_leaf cl = new Count_leaf(); cl.head = cl.new Node(2); cl.head.left = cl.new Node(7); cl.head.right = cl.new Node(5); cl.head.left.right = cl.new Node(6); cl.head.right.right = cl.new Node(9); cl.head.left.right.left = cl.new Node(1); cl.head.left.right.right = cl.new Node(11); cl.head.right.right.left = cl.new Node(14); cl.head.right.right.left.right = cl.new Node(23); System.out.println(cl.head.left.right.data); System.out.println(cl.head.right.right.data); int check = cl.half_count(cl.head); System.out.println(count); } }
[ "pratypratyush.nit@gmail.com" ]
pratypratyush.nit@gmail.com
df399d762b811ecb8b7cc3d03f3c5516a855e8e6
cb63f49a34bca7abd52adcc703083ed3f9cd88cf
/LearnDemo/25/WEB端/outHelp/src/com/back/base/pageModel/Position.java
80cb3dec1465dd32865b8b3543c2d53f673b008b
[]
no_license
CarvenChen/CCAndroid
ebe699b4a619777dc03cd477ef665b763f3e0893
1c3b3e78029fb3e87bb51d81c12fac34ce206092
refs/heads/master
2023-01-31T05:59:41.571482
2020-11-23T07:51:05
2020-11-23T07:51:05
255,521,952
1
0
null
null
null
null
UTF-8
Java
false
false
2,036
java
package com.back.base.pageModel; public class Position { private String id; private String pid; private String name; private String mark; private String type; private String grade; private String isleader; private String leaderlevel; private String description; private String createtime; private String updatetime; private boolean updateFlag; public boolean isUpdateFlag() { return updateFlag; } public void setUpdateFlag(boolean updateFlag) { this.updateFlag = updateFlag; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMark() { return mark; } public void setMark(String mark) { this.mark = mark; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public String getIsleader() { return isleader; } public void setIsleader(String isleader) { this.isleader = isleader; } public String getLeaderlevel() { return leaderlevel; } public void setLeaderlevel(String leaderlevel) { this.leaderlevel = leaderlevel; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCreatetime() { return createtime; } public void setCreatetime(String createtime) { this.createtime = createtime; } public String getUpdatetime() { return updatetime; } public void setUpdatetime(String updatetime) { this.updatetime = updatetime; } }
[ "chenhaihua@znlhzl.com" ]
chenhaihua@znlhzl.com
a89feaf3ecc7f5f2add918376a7d8623b79361b6
74c85dd87cd5c6836178f14f6c46773c5df9adc5
/Bluetooth_Social/src/main/java/edu/minggo/chat/util/MyScrollLayout.java
80793a3e3c14eba42d6f8251f91b46ca08453a65
[]
no_license
GillianZhu/bluetooth_social
75dfc9534d769ee9751bc653509bfcdd666fb2d1
3476e43eeb7f324d3aa9d32cc6def093a74bff0c
refs/heads/master
2020-05-31T13:32:45.586034
2019-06-17T16:11:49
2019-06-17T16:11:49
190,300,071
0
0
null
2019-06-05T00:42:25
2019-06-05T00:42:24
null
UTF-8
Java
false
false
7,032
java
package edu.minggo.chat.util; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewGroup; import android.widget.Scroller; public class MyScrollLayout extends ViewGroup{ private static final String TAG = "ScrollLayout"; private VelocityTracker mVelocityTracker; // 鐢ㄤ簬鍒ゆ柇鐢╁姩鎵嬪娍 private static final int SNAP_VELOCITY = 600; private Scroller mScroller; // 婊戝姩鎺у埗锟�? private int mCurScreen; private int mDefaultScreen = 0; private float mLastMotionX; private OnViewChangeListener mOnViewChangeListener; public MyScrollLayout(Context context) { super(context); // TODO Auto-generated constructor stub init(context); } public MyScrollLayout(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub init(context); } public MyScrollLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub init(context); } private void init(Context context) { mCurScreen = mDefaultScreen; // mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); mScroller = new Scroller(context); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { // TODO Auto-generated method stub if (changed) { int childLeft = 0; final int childCount = getChildCount(); for (int i=0; i<childCount; i++) { final View childView = getChildAt(i); if (childView.getVisibility() != View.GONE) { final int childWidth = childView.getMeasuredWidth(); childView.layout(childLeft, 0, childLeft+childWidth, childView.getMeasuredHeight()); childLeft += childWidth; } } } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO Auto-generated method stub super.onMeasure(widthMeasureSpec, heightMeasureSpec); final int width = MeasureSpec.getSize(widthMeasureSpec); @SuppressWarnings("unused") final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int count = getChildCount(); for (int i = 0; i < count; i++) { getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec); } scrollTo(mCurScreen * width, 0); } public void snapToDestination() { final int screenWidth = getWidth(); final int destScreen = (getScrollX()+ screenWidth/2)/screenWidth; snapToScreen(destScreen); } public void snapToScreen(int whichScreen) { // get the valid layout page whichScreen = Math.max(0, Math.min(whichScreen, getChildCount()-1)); if (getScrollX() != (whichScreen*getWidth())) { final int delta = whichScreen*getWidth()-getScrollX(); mScroller.startScroll(getScrollX(), 0, delta, 0, Math.abs(delta)*2); mCurScreen = whichScreen; invalidate(); // Redraw the layout if (mOnViewChangeListener != null) { mOnViewChangeListener.OnViewChange(mCurScreen); } } } @Override public void computeScroll() { // TODO Auto-generated method stub if (mScroller.computeScrollOffset()) { scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); postInvalidate(); } } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub final int action = event.getAction(); final float x = event.getX(); @SuppressWarnings("unused") final float y = event.getY(); switch (action) { case MotionEvent.ACTION_DOWN: Log.i("", "onTouchEvent ACTION_DOWN"); if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(event); } if (!mScroller.isFinished()){ mScroller.abortAnimation(); } mLastMotionX = x; break; case MotionEvent.ACTION_MOVE: int deltaX = (int)(mLastMotionX - x); if (IsCanMove(deltaX)) { if (mVelocityTracker != null) { mVelocityTracker.addMovement(event); } mLastMotionX = x; scrollBy(deltaX, 0); } break; case MotionEvent.ACTION_UP: int velocityX = 0; if (mVelocityTracker != null) { mVelocityTracker.addMovement(event); mVelocityTracker.computeCurrentVelocity(1000); velocityX = (int) mVelocityTracker.getXVelocity(); } if (velocityX > SNAP_VELOCITY && mCurScreen > 0) { // Fling enough to move left Log.e(TAG, "snap left"); snapToScreen(mCurScreen - 1); } else if (velocityX < -SNAP_VELOCITY && mCurScreen < getChildCount() - 1) { // Fling enough to move right Log.e(TAG, "snap right"); snapToScreen(mCurScreen + 1); } else { snapToDestination(); } if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } // mTouchState = TOUCH_STATE_REST; break; } return true; } private boolean IsCanMove(int deltaX) { if (getScrollX() <= 0 && deltaX < 0 ) { return false; } if (getScrollX() >= (getChildCount() - 1) * getWidth() && deltaX > 0) { return false; } return true; } public void SetOnViewChangeListener(OnViewChangeListener listener) { mOnViewChangeListener = listener; } }
[ "843122034@qq.com" ]
843122034@qq.com
b2dcf0d9013e25a4e7a947a7c039c2c4b142255a
068e240bc99c9c6889a0519145852ba2c43dae2f
/app/src/main/java/com/gustavo/example/tvshows/model/Season.java
df302d5a17c9f5ef4dcfc7c9e56a8f650eeda09f
[]
no_license
tavo/tv_shows
50b6a397e8262236820bbc6319cea10d2c11fcfc
cc5db13a212707f45da370c2a7eaecbf3fcbe9cb
refs/heads/master
2021-01-17T21:21:46.305460
2015-01-16T17:59:02
2015-01-16T17:59:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
770
java
package com.gustavo.example.tvshows.model; import com.google.gson.annotations.SerializedName; /** * Created by gustavo on 13/01/15. */ public class Season { private int id; @SerializedName("air_date") private String airDate; @SerializedName("season_number") private int seasonNumber; @SerializedName("poster_path") private String posterPath; @SerializedName("episode_count") private int episodeCount; public int getEpisodeCount() { return episodeCount; } public String getAirDate() { return airDate; } public int getSeasonNumber() { return seasonNumber; } public String getPosterPath() { return posterPath; } public int getId() { return id; } }
[ "tavo.ucv@gmail.com" ]
tavo.ucv@gmail.com
624837d2939116c9e94a3cb7c45cf5ccbdffa366
80a5aa732971ee069236ccb4a312afc9d83d77de
/src/main/java/com/hospital/hospital/repository/CadastroPacienteRepository.java
1cb193a0ca9af12fbe656bde0c65b7e4541a3c6d
[]
no_license
HenriqueJorge/TABD
b555ea2dfe467c4c8b5b6a6ad21458160902303c
1ad86dafb0e31953a9c7286b867ab8e5f7e78eea
refs/heads/master
2021-03-09T19:18:50.696411
2020-03-10T18:04:54
2020-03-10T18:04:54
246,371,948
0
0
null
null
null
null
UTF-8
Java
false
false
320
java
package com.hospital.hospital.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.hospital.hospital.entity.CadastroPaciente; @Repository public interface CadastroPacienteRepository extends JpaRepository<CadastroPaciente, Integer>{ }
[ "henrique.jorge6414@gmail.com" ]
henrique.jorge6414@gmail.com
39a0ad0434c7217a4b7a5d0359e64450b68feb53
ac7687f3f867e69e4b13423b40dcd2f73b293879
/Laboratorul 10 - Strategy State/src/ro/ase/csie/cts/dp/strategy/state/StareDeplasareRanitCritic.java
7dc2a86a3b473b25b7bf520d6c32ff6262dbfddc
[]
no_license
dobramarian/CTS_1088_Laborator
2904899603c67e5be901a3d30ab96c4f41d521da
f2b6e08d80845bb4e22c7a28e87bfd9f273bfa6b
refs/heads/main
2023-05-08T05:37:13.146115
2021-06-03T10:36:26
2021-06-03T10:36:26
342,210,528
0
0
null
null
null
null
UTF-8
Java
false
false
246
java
package ro.ase.csie.cts.dp.strategy.state; public class StareDeplasareRanitCritic implements InterfataModDeplasare{ @Override public void seMisca(SuperErou erou) { System.out.println(erou.nume + " nu se poate deplasa"); } }
[ "dobramarian18@stud.ase.ro" ]
dobramarian18@stud.ase.ro
01ab18e25e0e7709e8b869769fc805c50ad3832a
50d11a1ffc5f6b20f6dbca61b6e9e9d63ae7bf40
/app/src/main/java/com/tru/trudiancloud/main/tenement/fragment/RepairListWaitCommentFragment.java
ec2c50498ab409956f9da9a1367b7e4b9168126c
[ "MIT" ]
permissive
TIHubGitHub/TDEntranceGuard
af9e73b139e55d6570f2540317f5d208f488f3fc
cd1b015a257290507e5f22db3abeff38b4030314
refs/heads/master
2023-08-11T21:29:33.758680
2021-09-10T08:42:04
2021-09-10T08:42:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
12,799
java
package com.tru.trudiancloud.main.tenement.fragment; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Bundle; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.tru.trudiancloud.GlobalKey; import com.tru.trudiancloud.GlobalMethods; import com.tru.trudiancloud.NetUrl; import com.tru.trudiancloud.R; import com.tru.trudiancloud.main.controller.fragment.AbsFragment; import com.tru.trudiancloud.main.controller.net.RequestCallBack; import com.tru.trudiancloud.main.controller.utils.LogTools; import com.tru.trudiancloud.main.controller.utils.NetUtils; import com.tru.trudiancloud.main.controller.utils.RefreshLayout; import com.tru.trudiancloud.main.controller.utils.ToastTools; import com.tru.trudiancloud.main.tenement.activity.RepairListActivity; import com.tru.trudiancloud.main.tenement.bean.income.NetIncomeRepairListBean; import com.tru.trudiancloud.main.tenement.bean.out.YzRepairListBean; import com.tru.trudiancloud.main.tenement.interfaces.IRefresh; import com.tru.trudiancloud.smartHome.controller.utils.ImageLoaderHelper; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import tru.cn.com.trudianlibrary.global.controller.utils.TimeTools; /** * 全部维修列表数据 * * @author devin * @create 2017/1/11 * @update devin * @update_time 2017/1/11f */ public class RepairListWaitCommentFragment extends AbsFragment implements IRefresh { @BindView(R.id.rl_refrsh) RefreshLayout rlSearchCourses; @BindView(R.id.tv_no_data) TextView mTvNoData; @BindView(R.id.ll_no_network) LinearLayout mLlNoNetwork; private ListViewAdapter mListViewAdapter; private boolean mNOMoreData; private String communityId;//社区ID private int pageNum;//页码 private int statusIds;//状态id /** * 列表数据 * * @date 2017/1/11 */ private List<YzRepairListBean.RepairListBean> mConversationInfoListBeanList; public static Bundle createArgs(String communityId, int statusIds) { Bundle bundle = new Bundle(); bundle.putString(GlobalKey.PUBLIC_STRING_COMMUNITY_ID, communityId); bundle.putInt(GlobalKey.INCOME_INT_STATUS_ID, statusIds); return bundle; } public static RepairListWaitCommentFragment newInstance(Bundle bundle) { RepairListWaitCommentFragment searchCourseFragment = new RepairListWaitCommentFragment(); searchCourseFragment.setArguments(bundle); return searchCourseFragment; } @OnClick(value = {R.id.tv_net_reload,R.id.tv_set_network}) public void onClick(View view) { switch (view.getId()) { case R.id.tv_set_network: break; case R.id.tv_net_reload: setGetContentPost(); break; } } @Override protected void initCrashCache(Bundle savedInstanceState) { if (savedInstanceState != null) { communityId = savedInstanceState.getString(GlobalKey.PUBLIC_STRING_COMMUNITY_ID); statusIds = savedInstanceState.getInt(GlobalKey.INCOME_INT_STATUS_ID); } else if (getArguments() != null) { communityId = getArguments().getString(GlobalKey.PUBLIC_STRING_COMMUNITY_ID); statusIds = getArguments().getInt(GlobalKey.INCOME_INT_STATUS_ID); } else { ToastTools.showToastShort(mActivity, getString(R.string.error_data)); return; } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(GlobalKey.PUBLIC_STRING_COMMUNITY_ID, communityId); outState.putInt(GlobalKey.INCOME_INT_STATUS_ID, statusIds); } @Override public int getLayoutResource() { return R.layout.fragment_refresh_list; } /** * 获得数据请求 * * @date 2017/1/11 */ private void setGetContentPost() { httpsPost(NetUrl.URL_STRING_YZ_GET_REPAIR_LIST, new NetIncomeRepairListBean(communityId, pageNum, GlobalKey.PUBLIC_STATUS_INT_WAIT_COMMENT), new RequestCallBack<YzRepairListBean>(mActivity,true) { @Override protected void onStart() { super.onStart(); if (!NetUtils.isNetworkAvailable(mActivity)) { mLlNoNetwork.setVisibility(View.VISIBLE); } else { mLlNoNetwork.setVisibility(View.GONE); } } @Override protected void onSuccess(YzRepairListBean data, String msg) { super.onSuccess(data, msg); try{ if (mActivity == null || mActivity.isDestroyed() || isDetached()) { return; } if (data.getRepairList().size() < GlobalKey.PUBLIC_INT_PAGE_SIZE) { mNOMoreData = true;//没有更多 数据了 } if (pageNum == 1 && mConversationInfoListBeanList.size() > 0) { mConversationInfoListBeanList.clear(); } mConversationInfoListBeanList.addAll(data.getRepairList()); mListViewAdapter.notifyDataSetChanged(); updateRedDot(data.getCountTodo(),data.getCountProceeding(), data.getCountUnevaluate()); }catch (Exception e){e.printStackTrace();} } @Override protected void onUnCatchStatus(int status, String msg, String data) { super.onUnCatchStatus(status, msg, data); } @SuppressLint("WrongConstant") @Override protected void onFinally() { super.onFinally(); if (mActivity == null || mActivity.isDestroyed() || isDetached()) { return; } if (mConversationInfoListBeanList.size() == 0) { mTvNoData.setVisibility(View.VISIBLE); } else { mTvNoData.setVisibility(View.GONE); } hideLoadingView(); } @Override protected void onException(Exception e, String msg) { super.onException(e, msg); LogTools.logDebug(GlobalKey.PUBLIC_TEXT_DEVELOPER_DEVIN, "RepairListAllFragment(onException<158>):" + e); } }); } /** * 更新红点 * * @date 2017/1/18 * @author devin */ private void updateRedDot(final int waitHandler, final int alreadySent, final int waitCommentCount) { mActivity.runOnUiThread(new Runnable() { @Override public void run() { if (mActivity instanceof RepairListActivity) { ((RepairListActivity) mActivity).doUpdateRedDot(waitHandler, alreadySent, waitCommentCount); } } }); } @Override protected void initViewData(View rootView) { mConversationInfoListBeanList = new ArrayList<>(); mListViewAdapter = new ListViewAdapter(getActivity()); rlSearchCourses.setListViewAdapter(mListViewAdapter); rlSearchCourses.setColorSchemeResources(R.color.public_blue_ff00ddff, R.color.public_green_ff99cc00, R.color.public_orange_ffffbb33, R.color.public_red_ffff4444); rlSearchCourses.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { if (isAdded()) { pageNum = 1; mNOMoreData = false; setGetContentPost(); } } }); rlSearchCourses.setOnLoadListener(new RefreshLayout.OnLoadListener() { @Override public void onLoad() { if (!mNOMoreData) { pageNum++; setGetContentPost(); } else { ToastTools.showToastShort(mActivity, getString(R.string.load_more_finish)); rlSearchCourses.setLoading(false); } } }); rlSearchCourses.setRefreshing(true); pageNum = 1; setGetContentPost(); } private void hideLoadingView() { mActivity.runOnUiThread(new Runnable() { @Override public void run() { //去除: rlSearchCourses.setRefreshing(false); rlSearchCourses.setLoading(false); mListViewAdapter.notifyDataSetChanged(); } }); } @Override public void onRefresh(int refreshType) { if (!isAdded()) { return; } if ((refreshType & FLAG_INT_REFRESH_DEFAULT | FLAG_INT_REFRESH_REPAIR_LIST_ALREADY_SENT) > 0) { pageNum = 1; setGetContentPost(); } } public class ListViewAdapter extends BaseAdapter { private LayoutInflater mInflater; public ListViewAdapter(Activity context) { mInflater = LayoutInflater.from(context); } @Override public int getCount() { return mConversationInfoListBeanList.size(); } @Override public Object getItem(int position) { return mConversationInfoListBeanList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View view, ViewGroup parent) { Holder holder; if (view == null) { view = mInflater.inflate(R.layout.view_unit_item_repair, null); holder = new Holder(); ButterKnife.bind(holder, view); view.setTag(holder); } else { holder = (Holder) view.getTag(); } holder.setData(position); return view; } } class Holder { @BindView(R.id.iv_avatar) public ImageView ivAvatar; @BindView(R.id.tv_content) public TextView tvContent; @BindView(R.id.tv_address) public TextView tvAddress; @BindView(R.id.tv_repair_status) public TextView tvRepairStatus; @BindView(R.id.tv_record_time) public TextView tvRecordTime; @BindView(R.id.ll_repair_list_item) LinearLayout mLlItem; public void setData(final int position) { final YzRepairListBean.RepairListBean item = mConversationInfoListBeanList.get(position); String imgUrl; if (mConversationInfoListBeanList.size() == 0) { ivAvatar.setImageResource(R.drawable.icon_trudian_default); } else { imgUrl = item.getImage(); if (!TextUtils.isEmpty(imgUrl)) { ImageLoaderHelper.showRepairPic(imgUrl, ivAvatar,mActivity); }else { ivAvatar.setImageResource(R.drawable.icon_trudian_default); } } if (!TextUtils.isEmpty(item.getSubject())) { tvContent.setText(item.getSubject()); } if (!TextUtils.isEmpty(item.getHouseName())) { tvAddress.setText(item.getHouseName()); } GlobalMethods.setRepairStatusView(mActivity, tvRepairStatus, item.getStatus()); tvRecordTime.setText(TimeTools.doFormatDateToYMDHmSs(item.getCreateTime())); mLlItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (GlobalMethods.isClickTooFast(view)) { return; } statusIds = mConversationInfoListBeanList.get(position).getStatus(); if (mActivity instanceof RepairListActivity) { LogTools.logDebug(GlobalKey.PUBLIC_TEXT_DEVELOPER_DEVIN, "Holder(onClick<255>):" + statusIds); ((RepairListActivity) mActivity).sendGetRepairDetailsMsgPost(Integer.valueOf(statusIds), String.valueOf(mConversationInfoListBeanList.get(position).getId())); } } }); } } }
[ "" ]
fcc2c3dd5acfafc6acbaeec280c680ed42b5ab2c
b5d0eb010e2a04caf91bdc07a7a10f99227481dc
/stone-mmrk-common/src/main/java/com/allen/stone/common/annotation/ThreadSafe.java
a85b8143b633e1e75043046f5ca5c9cb1fd42d44
[]
no_license
AllenAlan/stone-mmrk
8134efb747a23f45db5cb4d3e6c69930f730fe36
9220236c7760c276396ed2593b1908e80f5824f5
refs/heads/master
2021-10-01T17:57:09.047448
2018-11-27T23:30:36
2018-11-27T23:30:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
430
java
package com.allen.stone.common.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 用于标识线程安全 * @author Allen * @version V1.0.0 * @date 2018/10/22 15:26 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) public @interface ThreadSafe { String value() default ""; }
[ "15869157637@163.com" ]
15869157637@163.com
d3236dd4afcb2733fb5a2faafa6cbfb07e3f6fb7
6878b384613588461bfcafbbfdae5485579374fd
/das_api/src/main/java/com/gw/das/business/dao/room/entity/DasChartFlowAttribution.java
8c20c552a5c2f1e6cf1259d2647f91afe67d3072
[]
no_license
wuwenxing/das
be8e1a33bad09ac0aa75c6b30a2dfbfb86b7a23e
bc6e32cdd699f869205765df80c3d52e761b9f23
refs/heads/master
2021-05-10T15:28:56.606507
2018-01-23T05:52:01
2018-01-23T05:52:01
118,551,407
1
2
null
null
null
null
UTF-8
Java
false
false
2,926
java
package com.gw.das.business.dao.room.entity; import java.util.Date; import com.gw.das.business.common.orm.Column; import com.gw.das.business.common.orm.UnColumn; import com.gw.das.business.dao.base.BaseModel; /** * 归因统计表 */ public class DasChartFlowAttribution extends BaseModel { @Column(name = "rowkey") private String rowKey; // 日期(yyyy-MM-dd)分区字段 @Column(name = "datatime") private String dataTime; // 广告来源 @Column(name = "utmcsr") private String utmcsr; // 广告媒介 @Column(name = "utmcmd") private String utmcmd; // 模拟开户总数 @Column(name = "demoCount") private Double demoCount; // 真实开户总数 @Column(name = "realCount") private Double realCount; //标识业务平台访问,1:外汇网站 2:贵金属网站 @Column(name = "businessPlatform") private String businessPlatform; //标识是手机还是pc访问,0和空代表pc访问,1代表手机访问(默认为0) @Column(name = "devicetype") private String devicetype; //开始时间 查询用 @UnColumn private Date dataTimeStart; //结束时间 查询用 @UnColumn private Date dataTimeEnd; //设备次数 @Column(name = "devicecount") private Integer devicecount = 0; public String getRowKey() { return rowKey; } public void setRowKey(String rowKey) { this.rowKey = rowKey; } public String getDataTime() { return dataTime; } public void setDataTime(String dataTime) { this.dataTime = dataTime; } public String getUtmcsr() { return utmcsr; } public void setUtmcsr(String utmcsr) { this.utmcsr = utmcsr; } public String getUtmcmd() { return utmcmd; } public void setUtmcmd(String utmcmd) { this.utmcmd = utmcmd; } public Double getDemoCount() { return demoCount; } public void setDemoCount(Double demoCount) { this.demoCount = demoCount; } public Double getRealCount() { return realCount; } public void setRealCount(Double realCount) { this.realCount = realCount; } public String getBusinessPlatform() { return businessPlatform; } public void setBusinessPlatform(String businessPlatform) { this.businessPlatform = businessPlatform; } public String getDevicetype() { return devicetype; } public void setDevicetype(String devicetype) { this.devicetype = devicetype; } public Date getDataTimeStart() { return dataTimeStart; } public void setDataTimeStart(Date dataTimeStart) { this.dataTimeStart = dataTimeStart; } public Date getDataTimeEnd() { return dataTimeEnd; } public void setDataTimeEnd(Date dataTimeEnd) { this.dataTimeEnd = dataTimeEnd; } public Integer getDevicecount() { return devicecount; } public void setDevicecount(Integer devicecount) { this.devicecount = devicecount; } }
[ "wuwenxing-nc@qq.com" ]
wuwenxing-nc@qq.com
a214d66e36269afd2b98bfd8eb45e344c2485632
714ce5de122d2e215d5ffa1cf754898ceb791cb0
/src/main/java/com/core/tools/DateUtil.java
05751e67a29a009be6e7830f36641c0d0c8b0570
[]
no_license
swsm/svshGit
58812acfa598915db9731db58b9e5c1cfb0ae780
4ebb9517c0f532d32a586179bf750255716e2ed1
refs/heads/master
2020-03-18T16:19:04.574798
2018-06-11T15:19:20
2018-06-11T15:19:20
134,958,955
0
0
null
null
null
null
UTF-8
Java
false
false
4,152
java
package com.core.tools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateUtil { /** * 日志 */ private static Logger logger = LoggerFactory.getLogger(DateUtil.class); public static String formatDate(Date date, String format) { if (date == null) return ""; SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(date); } public static String getDateTimeString(Date date) { return formatDate(date, "yyyy-MM-dd HH:mm"); } public static Date getDateTime(String dateStr) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; try { date = dateFormat.parse(dateStr.replace("T", " ")); } catch (ParseException e) { logger.error(e.getMessage(), e); } return date; } public static String getDateTimeCnString(Date date) { return formatDate(date, "yyyy年MM月dd日 HH:mm"); } public static String getDateString(Date date) { return formatDate(date, "yyyy-MM-dd"); } public static String fixTimestamp(String str) { if (str.indexOf(':') == -1) return qualify(str) + " 00:00:00"; else { int i = str.indexOf(' '); return qualify(str.substring(0, i)) + str.substring(i); } } private static String qualify(String dateStr) { if (dateStr.length() == 10) return dateStr; String[] sec = StringUtil.split(dateStr, "-"); if (sec.length == 3) { StringBuilder buf = new StringBuilder(10); buf.append(sec[0]); buf.append("-"); if (sec[1].length() == 1) buf.append("0"); buf.append(sec[1]); buf.append("-"); if (sec[2].length() == 1) buf.append("0"); buf.append(sec[2]); return buf.toString(); } else return dateStr; } public static String fixTime(String str) { if (str.indexOf(':') == -1) return "00:00:00"; int b = str.indexOf(' '), e = str.indexOf('.'); if (b == -1) b = 0; if (e == -1) e = str.length(); return str.substring(b, e); } public static String getHours(long milliSecs) { long h = milliSecs / 3600000, hm = milliSecs % 3600000; long m = hm / 60000, mm = hm % 60000; long s = mm / 1000, sm = mm % 1000; return StringUtil.concat(Long.toString(h), ":", Long.toString(m), ":", Long.toString(s), ".", Long.toString(sm)); } public static int daysInMonth(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.getActualMaximum(Calendar.DAY_OF_MONTH); } public static int dayOfMonth(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.DAY_OF_MONTH); } public static int yearOf(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.YEAR); } public static int dayOfYear(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.DAY_OF_YEAR); } public static int dayOfWeek(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.DAY_OF_WEEK); } public static String toString(Date date) { if (date == null) return ""; Timestamp t = new Timestamp(date.getTime()); return t.toString(); } public static Date incYear(Date date, int years) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.YEAR, years); return cal.getTime(); } public static Date incMonth(Date date, int months) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.MONTH, months); return cal.getTime(); } public static int hourOfDay(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.HOUR_OF_DAY); } public static Date incDay(Date date, long days) { return new Date(date.getTime() + 86400000 * days); } public static Date incSecond(Date date, long seconds) { return new Date(date.getTime() + 1000 * seconds); } }
[ "776502545@qq.com" ]
776502545@qq.com
5afb31204edd408f6dd9b856842546c10da3d3bb
6fbe8fe0bd05637a71ccaa9d2ef6235f5ecdaf48
/JavaInputOutput/src/Examples/Example_3.java
aca32ce31f9a52cb69a8f5fd7949eca0bf0098c9
[]
no_license
Pils48/Java-course
1808ccca5fc27a90e904e50a5d759cf890ad74a8
bab1e3e2652f0cc73d2001b3a64bdd48c4e00adc
refs/heads/master
2020-05-18T14:30:28.431759
2019-05-01T20:37:33
2019-05-01T20:37:33
184,472,860
1
0
null
null
null
null
UTF-8
Java
false
false
797
java
package Examples; import java.io.*; import java.nio.channels.FileChannel; public class Example_3 { public static void copyByChannels (File fileSrc, File fileDst) throws IOException { try(FileInputStream in = new FileInputStream(fileSrc); FileOutputStream out = new FileOutputStream(fileDst, false)){ FileChannel inChannel = in.getChannel(); FileChannel outChannel = out.getChannel(); long count = 0; long size = inChannel.size(); while(count < size) { long currentPosition = count; long byteleft = size - count; count += outChannel.transferFrom(inChannel, currentPosition, byteleft); } }catch(IOException e) { throw new IOException("Exception was thrown during coping from " + fileSrc + " to file " + fileDst); } } }
[ "ha.rg@yandex.ru" ]
ha.rg@yandex.ru
a918bef9f6ac3d507fde24c9d37e091d75c935d4
0e5695b64ff5c83a022023272c5270f992bc19f6
/src/main/java/sample/usecase/security/ApiLoginHandler.java
d3e1bddae3c362c4f83e0a3037f00e7031c5d06b
[ "MIT" ]
permissive
lospejos/sample-micronaut-jpa
4f8818e64066a25c356d6b7f725ab5febe88fe37
20fb5a1bfaadfb3568560d006858c32fd918724b
refs/heads/master
2020-04-29T05:07:52.627395
2019-03-15T19:06:09
2019-03-15T19:06:09
175,871,130
0
0
null
2019-03-15T18:20:16
2019-03-15T18:20:16
null
UTF-8
Java
false
false
1,119
java
package sample.usecase.security; import javax.inject.Singleton; import io.micronaut.context.annotation.Replaces; import io.micronaut.http.*; import io.micronaut.http.annotation.Produces; import io.micronaut.security.authentication.*; import io.micronaut.security.session.*; import io.micronaut.session.*; /** * API correspondence of SessionLoginHandler. */ @Produces(MediaType.APPLICATION_JSON) @Singleton @Replaces(SessionLoginHandler.class) public class ApiLoginHandler extends SessionLoginHandler { public ApiLoginHandler(SecuritySessionConfiguration securitySessionConfiguration, SessionStore<Session> sessionStore) { super(securitySessionConfiguration, sessionStore); } /** {@inheritDoc} */ @Override public HttpResponse<?> loginSuccess(UserDetails userDetails, HttpRequest<?> request) { super.loginSuccess(userDetails, request); return HttpResponse.ok(); } /** {@inheritDoc} */ @Override public HttpResponse<?> loginFailed(AuthenticationFailed authenticationFailed) { return HttpResponse.unauthorized(); } }
[ "junichiro_kazama@xon.jp" ]
junichiro_kazama@xon.jp
a78d9001944299e47ac3e45e9c5aafefc7746c3e
d1be5caae85e0e2d56452d23050ab52d6e17d340
/src/main/java/com/study/thread/threadSafeAndUnsafe/TestThreadSafeAndUnsafe.java
9e60f3573dba549e12b9dc7e6e8a2ce2839824af
[]
no_license
yiding17/study
d7f191957cafcbf5e25da79c3617dd9dd4c873b4
5b1f311f73303f53d4156f9482880c4d4ecc37ce
refs/heads/master
2021-08-19T08:26:57.994663
2017-11-25T13:19:33
2017-11-25T13:19:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,406
java
package com.study.thread.threadSafeAndUnsafe; import java.util.ArrayList; import java.util.List; import java.util.Vector; import java.util.concurrent.CountDownLatch; public class TestThreadSafeAndUnsafe { public static void main(String[] args) { for(int i=0;i<10;i++){ test(); } } private static void test() { // List<Object> list = new ArrayList<Object>(); Vector<Object> list = new Vector<Object>(); int threadNum = 1000; CountDownLatch countDownLatch = new CountDownLatch(threadNum); //启动threadNum个子线程 for(int i=0;i<threadNum;i++){ Thread thread = new Thread(new MyThread(list,countDownLatch)); thread.start(); } try{ //主线程等待所有子线程执行完成,再向下执行 countDownLatch.await();; }catch(InterruptedException e){ e.printStackTrace(); } System.out.println(list.size()); } } class MyThread implements Runnable{ private Vector<Object> list; // private List<Object> list; private CountDownLatch countDownLatch; // public MyThread(List<Object> list,CountDownLatch countDownLatch){ public MyThread(Vector<Object> list,CountDownLatch countDownLatch){ this.list = list; this.countDownLatch = countDownLatch; } public void run() { //每个线程向List中添加100个对象 for(int i=0;i<100;i++){ list.add(new Object()); } //完成一个子线程 countDownLatch.countDown(); } }
[ "liuyingan@163.com" ]
liuyingan@163.com
02ac8652c730f3b04b9f1ac6ee960f7757342dcf
a06d84971f698c940cbe1b0fd4fa36e6b7cf44f5
/tiantian-manager/tiantian-manager-service/src/main/java/com/tiantian/service/ContentService.java
f7007ac10d63a603c19bb9c6ca975cf70f045ee9
[]
no_license
HaomiaoDuan/TianTianOnlineShop
8d6065e8b1e45b3770fc2ffb03360a1a5b90cdf9
6a6fbe8e4b799dd44470197f3a3f9dd380b82c11
refs/heads/master
2022-12-30T07:50:51.249713
2019-07-15T12:17:24
2019-07-15T12:17:24
194,461,981
0
0
null
null
null
null
UTF-8
Java
false
false
372
java
package com.tiantian.service; import com.tiantian.common.pojo.EasyUIDataGridResult; import com.tiantian.common.pojo.TiantianResult; import com.tiantian.pojo.TbContent; public interface ContentService { EasyUIDataGridResult getContentListByCatId(Integer page, Integer rows,Long categoryId); public TiantianResult insertContent(TbContent content); }
[ "893713287@qq.com" ]
893713287@qq.com
6b2dcefaa1fc4cea23cdff9b8a64326f8afb4e97
0d6888a15142eb01d291a1ebafc6d79ce4c4f5b8
/KKBS_School/src/grp/four/kkbs/HovedMenuGui.java
e616cb9db34fe7c43d559f568345be9972d9353b
[]
no_license
R1-Group-POP/KKBS
19925fa8bcc3bb1eda7710faa04f5c686892f309
2b74ea9b9799e3add610aa8b0da7b2ea53e5ff60
refs/heads/master
2016-09-06T19:51:28.288527
2013-03-03T22:29:46
2013-03-03T22:29:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
9,096
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package grp.four.kkbs; import grp.four.bk.BKGUI; import grp.four.bk.OpretDagsHandler; import grp.four.klr.KLRGUI; import grp.four.klr.OpretKorelaererHandler; import grp.four.ktr.KTRGui; import grp.four.ktr.OpretKoretojHandler; import grp.four.tk.TKGUI; import grp.four.tk.TilknytKoretojHandler; /** * * @author Henrikh */ public class HovedMenuGui extends javax.swing.JFrame { private KTRGui kTRGui; private OpretKoretojHandler koretojHandler; private KLRGUI kLRGUI; private OpretKorelaererHandler korelaererHandler; private BKGUI bKGUI; private OpretDagsHandler dagsHandler; private TKGUI tKGUI; private TilknytKoretojHandler tilknytKoretojHandler; /** * Creates new form HovedMenuGui */ public HovedMenuGui(KTRGui kTRGui, OpretKoretojHandler koretojHandler, KLRGUI kLRGUI, OpretKorelaererHandler korelaererHandler, BKGUI bKGUI, OpretDagsHandler dagsHandler, TKGUI tKGUI, TilknytKoretojHandler tilknytkKoretojHandler) { this.koretojHandler=koretojHandler; this.kTRGui=kTRGui; this.kLRGUI=kLRGUI; this.korelaererHandler=korelaererHandler; this.bKGUI = bKGUI; this.dagsHandler = dagsHandler; this.tKGUI = tKGUI; this.tilknytKoretojHandler = tilknytkKoretojHandler; initComponents(); setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); tilknytKoretoj = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("KKBS"); setResizable(false); jButton1.setText("Opret køretøj"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Opret kørelærer"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setText("Book kursus"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); tilknytKoretoj.setText("Tilknyt køretøj"); tilknytKoretoj.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tilknytKoretojActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 236, Short.MAX_VALUE) .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(tilknytKoretoj, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(tilknytKoretoj) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed String koretojsliste = koretojHandler.startKoretojsRegistrering(); kTRGui.setTA(koretojsliste); kTRGui.setVisible(true); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed kLRGUI.setTA(korelaererHandler.startKørelærerRegistrering()); kLRGUI.setVisible(true); }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed bKGUI.opdaterDatoListe(); bKGUI.opdaterKorelaererListe(); bKGUI.populerKategorier(); bKGUI.setVisible(true); }//GEN-LAST:event_jButton3ActionPerformed private void tilknytKoretojActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tilknytKoretojActionPerformed tKGUI.resetTilfojedeKoretojer(); tKGUI.populerBookedeKurser(); tKGUI.setCompStatus(); tKGUI.setVisible(true); }//GEN-LAST:event_tilknytKoretojActionPerformed /** * @param args the command line arguments */ // public static void main(String args[]) { // /* Set the Nimbus look and feel */ // //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> // /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. // * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html // */ // try { // for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { // if ("Nimbus".equals(info.getName())) { // javax.swing.UIManager.setLookAndFeel(info.getClassName()); // break; // } // } // } catch (ClassNotFoundException ex) { // java.util.logging.Logger.getLogger(HovedMenuGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (InstantiationException ex) { // java.util.logging.Logger.getLogger(HovedMenuGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (IllegalAccessException ex) { // java.util.logging.Logger.getLogger(HovedMenuGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (javax.swing.UnsupportedLookAndFeelException ex) { // java.util.logging.Logger.getLogger(HovedMenuGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } // //</editor-fold> // // /* Create and display the form */ // java.awt.EventQueue.invokeLater(new Runnable() { // public void run() { // new HovedMenuGui().setVisible(true); // } // }); // } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JPanel jPanel1; private javax.swing.JButton tilknytKoretoj; // End of variables declaration//GEN-END:variables }
[ "pkkann@gmail.com" ]
pkkann@gmail.com
9f48631bc81fc7490c46d6916a28ced1cd8b79a2
8d7846d59e0e03eb352c91a267d3910ffba495a8
/app/src/main/java/com/armchina/cph/wrappers/DisplayManager.java
a09f13c892465c6d4dd7b8d386486daeac5ddccd
[]
no_license
zhs1397/Android-Screen-Projector
2b6d2a701c35037a4674ac49105076f5433d5331
259b1cd70ecf97a5be71537c085d740d99ff4936
refs/heads/master
2023-08-27T16:38:43.596758
2020-07-31T06:43:14
2020-07-31T06:43:14
305,647,540
2
1
null
null
null
null
UTF-8
Java
false
false
1,541
java
package com.armchina.cph.wrappers; import android.os.IInterface; import com.armchina.cph.screenutils.DisplayInfo; import com.armchina.cph.screenutils.Size; public final class DisplayManager { private final IInterface manager; public DisplayManager(IInterface manager) { this.manager = manager; } public DisplayInfo getDisplayInfo(int displayId) { try { Object displayInfo = manager.getClass().getMethod("getDisplayInfo", int.class).invoke(manager, displayId); if (displayInfo == null) { return null; } Class<?> cls = displayInfo.getClass(); // width and height already take the rotation into account int width = cls.getDeclaredField("logicalWidth").getInt(displayInfo); int height = cls.getDeclaredField("logicalHeight").getInt(displayInfo); int rotation = cls.getDeclaredField("rotation").getInt(displayInfo); int layerStack = cls.getDeclaredField("layerStack").getInt(displayInfo); int flags = cls.getDeclaredField("flags").getInt(displayInfo); return new DisplayInfo(displayId, new Size(width, height), rotation, layerStack, flags); } catch (Exception e) { throw new AssertionError(e); } } public int[] getDisplayIds() { try { return (int[]) manager.getClass().getMethod("getDisplayIds").invoke(manager); } catch (Exception e) { throw new AssertionError(e); } } }
[ "dennis.zhang@armchina.com" ]
dennis.zhang@armchina.com
e99d38ff4dbacda42fee7162d3cbf35648e3b41c
1314268d5ec621f7d11fab7ead97bb88e3d9a35c
/src/sharedFunctions/Logs.java
764d8923d22cd3b82ae796dfa2520f58887e33b4
[]
no_license
TimFries/Item_Inventory_Managment
8199f6e21651b35ab7e959437073b3e7d5300944
d04e27d7c25194b2d41efc67ff4ddbb54cb89ef2
refs/heads/master
2021-08-08T18:58:18.419706
2017-11-10T22:31:19
2017-11-10T22:31:19
110,156,845
0
0
null
null
null
null
UTF-8
Java
false
false
939
java
/* * 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 sharedFunctions; /** * * @author Tim */ public class Logs { public String username; public String time; public String log; public Logs(){ this.username = ""; this.time = ""; this.log = ""; } public String getUsername(){ return username; } public String getTime(){ return time; } public String getLog(){ return log; } public void setUsername(String username){ this.username = username; } public void setTime(String time){ this.time = time; } public void setLog(String log){ this.log = log; } }
[ "noreply@github.com" ]
noreply@github.com
e925f3eb790bf9e039959c8b31f7e2ebf7665780
7c9f40c50e5cabcb320195e3116384de139002c6
/Plugin_Core/src/tinyos/yeti/utility/GenericTemplate.java
070d4b7077b69eb74c48e48c777cf429da27b88d
[]
no_license
phsommer/yeti
8e89ad89f1a4053e46693244256d03e71fe830a8
dec8c79e75b99c2a2a43aa5425f608128b883e39
refs/heads/master
2021-01-10T05:33:57.285499
2015-05-21T19:41:02
2015-05-21T19:41:02
36,033,399
3
0
null
null
null
null
UTF-8
Java
false
false
12,894
java
/* * Yeti 2, NesC development in Eclipse. * Copyright (C) 2009 ETH Zurich * * 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/>. * * Web: http://tos-ide.ethz.ch * Mail: tos-ide@tik.ee.ethz.ch */ package tinyos.yeti.utility; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.link.LinkedModeModel; import org.eclipse.jface.text.link.LinkedModeUI; import org.eclipse.jface.text.link.LinkedPosition; import org.eclipse.jface.text.link.LinkedPositionGroup; import org.eclipse.swt.graphics.Point; import tinyos.yeti.editors.NesCEditor; /** * A generic template is an easy way to insert complex structures into * a document. A template may contain these options: * <ul> * <li>${var} inserts a variable named var with text <code>var</code></li> * <li>${var,text} inserts a variable named var with text <code>text</code></li> * <li>Arguments can be written in quotes to allow special signs like a comma</li> * <li>$x gets replaced by x, x will not be seen as special sign</li> * <li>${cursor} marks the future cursor position</li> * </ul> * @author Benjamin Sigg */ public class GenericTemplate { private List<Piece> pieces; private String template; /** * Creates a new template * @param template the content of this template */ public GenericTemplate( String template ){ this.template = template; } /** * Applies this template to <code>editor</code> on behalf of <code>command</code>. This * method will effectively replace whatever <code>command</code> would have * done. * @param editor the editor into which this template will be inserted * @param command the command which gets replaced by this template */ public void apply( NesCEditor editor, DocumentCommand command ){ apply( editor.getEditorSourceViewer(), command.offset ); Point selection = getSelection( editor.getDocument(), command.offset ); editor.selectAndReveal( selection ); command.offset = selection.x; command.length = 0; command.text = null; command.caretOffset = selection.x + selection.y; command.shiftsCaret = false; } /** * Applies this template to <code>editor</code>. * @param editor the editor into which this template will be inserted * @param offset the location where the template will be inserted */ public void apply( NesCEditor editor, int offset ){ apply( editor.getEditorSourceViewer(), offset ); Point selection = getSelection( editor.getDocument(), offset ); editor.selectAndReveal( selection ); } /** * Inserts this template into <code>viewer</code>. * @param viewer a viewer of a document into which the template is inserted * @param offset where to insert the template */ public void apply( ITextViewer viewer, int offset ){ apply( viewer, offset, offset ); } /** * Inserts this template into <code>viewer</code>. * @param viewer a viewer of a document into which the template is inserted * @param offset where to insert the template * @param triggerOffset the current location of the cursor, must be * greater or equal than <code>offset</code> */ public void apply( ITextViewer viewer, int offset, int triggerOffset ){ try{ IDocument document = viewer.getDocument(); ensurePieces(); LinkedModeModel model = new LinkedModeModel(); Map<String, LinkedPositionGroup> groups = new HashMap<String, LinkedPositionGroup>(); StringBuilder text = new StringBuilder(); int replacementOffset = offset; int rank = 0; for( Piece piece : pieces ){ if( piece.text ){ text.append( piece.arguments[0] ); offset += piece.arguments[0].length(); } else{ String var = piece.arguments[0]; if( !"cursor".equals( var )){ String name = var; if( piece.arguments.length > 1 ) name = piece.arguments[1]; LinkedPositionGroup group = groups.get( var ); if( group == null ){ group = new LinkedPositionGroup(); groups.put( var, group ); } LinkedPosition position = new LinkedPosition( document, offset, name.length(), rank++ ); group.addPosition( position ); text.append( name ); offset += name.length(); } } } for( LinkedPositionGroup group : groups.values() ){ model.addGroup( group ); } document.replace( replacementOffset, triggerOffset - replacementOffset, text.toString() ); if( groups.size() > 0 ){ model.forceInstall(); LinkedModeUI ui= new LinkedModeUI( model, viewer ); ui.setExitPosition( viewer, replacementOffset + text.length(), 0, Integer.MAX_VALUE ); ui.enter(); } } catch( BadLocationException ex ){ ex.printStackTrace(); } } /** * The region that should be selected after this template has been * applied. * @param document the document into which this template was inserted * @param offset where this template was inserted * @return the selection */ public Point getSelection( IDocument document, int offset ){ ensurePieces(); int selectionOffset = offset; // search for {cursor} for( Piece piece : pieces ){ if( piece.text ){ selectionOffset += piece.arguments[0].length(); } else{ if( "cursor".equals( piece.arguments[0] )){ return new Point( selectionOffset, 0 ); } if( piece.arguments.length > 1 ) selectionOffset += piece.arguments[1].length(); else selectionOffset += piece.arguments[0].length(); } } // nothing, now just select the first one selectionOffset = offset; for( Piece piece : pieces ){ if( piece.text ){ selectionOffset += piece.arguments[0].length(); } else{ int length; if( piece.arguments.length > 1 ) length = piece.arguments[1].length(); else length = piece.arguments[0].length(); return new Point( selectionOffset, length ); } } return new Point( selectionOffset, 0 ); } private void ensurePieces(){ if( pieces == null ){ pieces = parse( template ); } } private List<Piece> parse( String template ){ StringBuilder builder = new StringBuilder(); List<Piece> result = new ArrayList<Piece>(); boolean readDollar = false; boolean readText = true; boolean quotet = false; for( int i = 0, n = template.length(); i<n; i++ ){ char c = template.charAt( i ); if( c == '$' ){ if( readDollar ){ readDollar = false; builder.append( c ); continue; } else{ readDollar = true; continue; } } if( c == '"' && !readDollar ){ quotet = !quotet; } if( !quotet ){ if( c == '{' && readText && readDollar ){ // begin block if( builder.length() > 0 ){ result.add( new Piece( true, builder.toString() ) ); builder.setLength( 0 ); } readDollar = false; readText = false; } else if( c == '}' && !readText && !readDollar ){ result.add( new Piece( false, split( builder.toString() ) )); builder.setLength( 0 ); readText = true; } else{ builder.append( c ); readDollar = false; } } else{ builder.append( c ); readDollar = false; } } if( readText && builder.length() > 0 ){ result.add( new Piece( true, builder.toString() ) ); } return result; } private String[] split( String text ){ List<String> list = new ArrayList<String>(); int offset = 0; int length = 0; boolean quoted = false; boolean skip = false; for( int i = 0, n = text.length(); i<n; i++ ){ char c = text.charAt( i ); if( quoted ){ if( c == '"' ){ quoted = false; skip = true; } else{ length++; } } else{ if( c == '"' ){ quoted = true; offset = i+1; length = 0; } else if( c == ',' ){ list.add( text.substring( offset, offset+length ) ); skip = false; offset = i+1; length = 0; } else if( !skip ){ length++; } } } list.add( text.substring( offset, offset+length ) ); return list.toArray( new String[ list.size() ] ); } @Override public int hashCode(){ final int prime = 31; int result = 1; result = prime * result + ((pieces == null) ? 0 : pieces.hashCode()); result = prime * result + ((template == null) ? 0 : template.hashCode()); return result; } @Override public boolean equals( Object obj ){ if( this == obj ) return true; if( obj == null ) return false; if( getClass() != obj.getClass() ) return false; GenericTemplate other = (GenericTemplate)obj; if( pieces == null ){ if( other.pieces != null ) return false; } else if( !pieces.equals( other.pieces ) ) return false; if( template == null ){ if( other.template != null ) return false; } else if( !template.equals( other.template ) ) return false; return true; } private static class Piece{ public final boolean text; public final String[] arguments; public Piece( boolean text, String... arguments ){ this.text = text; this.arguments = arguments; } @Override public String toString(){ if( text ){ return Arrays.toString( arguments ); } else{ return "${" + Arrays.toString( arguments ) + "}"; } } @Override public int hashCode(){ final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode( arguments ); result = prime * result + (text ? 1231 : 1237); return result; } @Override public boolean equals( Object obj ){ if( this == obj ) return true; if( obj == null ) return false; if( getClass() != obj.getClass() ) return false; Piece other = (Piece)obj; if( !Arrays.equals( arguments, other.arguments ) ) return false; if( text != other.text ) return false; return true; } } }
[ "besigg@2a69fd7c-12de-fc47-e5bb-db751a41839b" ]
besigg@2a69fd7c-12de-fc47-e5bb-db751a41839b
01df8589f03e874598186a7a1626b52c577f3044
937b42841bcd43ae6fc5c14f3b375dc31307ad39
/src/com/winga/xxl/classifier/data/store/DocWordProbMap.java
63e1bceeff5d6839957301d72c7421175cc0f6a2
[ "Apache-2.0" ]
permissive
xiaoliable/EssayClassifier
47e92539fb29f94239be32798c4c0b7df4435ab9
b42e71a8cb24708a5d150868473f8d0edb64ff49
refs/heads/master
2021-01-10T01:18:49.842724
2015-12-07T15:21:02
2015-12-07T15:21:02
46,348,064
1
0
null
null
null
null
UTF-8
Java
false
false
11,451
java
package com.winga.xxl.classifier.data.store; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Comparator; import java.util.Map.Entry; import com.winga.xxl.classifier.data.exception.SaxParseService; /** * <p> * For the naive bayes classifier. * </p> * <p> * The underlayer calculation class.(Singleton pattern) * </p> * <p> * Version : 2014-9-22 * </p> * * @author xiaoxiao * @version 1.0 */ public class DocWordProbMap { private static DocWordProbMap singleton = new DocWordProbMap(); private DocWordProbMap() { } public static DocWordProbMap getInstance() { return singleton; } // Map< categoryName, Map< docID, Map< wordHash, countWordInDoc>>> // private Map<String, Map<Long, Map<Long, Long>>> wordNumInDocInClass = new // HashMap<String, Map<Long, Map<Long, Long>>>(); // chi-square calculation variable /** Total words' number in all the documents. */ private long totalDifferWordNum = 0; /** Total words' occurrence number in all the documents. */ private double totalWordOccurNum = 0; // The appointed feature word's number for every category // public final static int FEATURE_WORD_NUM = 1000; /** Every class' total words number. */ private Map<String, Double> totalWordNumInClass = new HashMap<String, Double>(); /** Every word's total occurrence number in all the documents. */ private Map<Long, Double> wordNumInTotalClass = new HashMap<Long, Double>(); /** Every word's total occurrence number in every class. */ private Map<String, Map<Long, Long>> wordNumInClass = new HashMap<String, Map<Long, Long>>(); // private Map<Long, Map<String, Long>> allWordChiSquareInClass = new // HashMap<Long, Map<String, Long>>(); // private List<Long> allFeatureWord = new ArrayList<Long>(); // Train multinormalNB private Map<String, Map<Long, Double>> condprob = new HashMap<String, Map<Long, Double>>(); private Map<String, Double> prior = new HashMap<String, Double>(); /** * Set the temporary data for the follow calculation. */ public void init(File categoryDir) { SaxParseService sax = new SaxParseService(); IDocuments[] beginCenter = sax.ReadSampleCenterXML(categoryDir .listFiles()); init(beginCenter); } /** * Read the different sample center documents and calculate the NB model. * * @param documents * : The sample center documents array. * */ public void init(IDocuments[] documents) { for (int i = 0; i < documents.length; i++) { // Put the content map into the title map. String categoryName = documents[i].getCategory(); documents[i].getTitleVector().putAll( documents[i].getContentVector()); Map<Long, Integer> contentMap = documents[i].getTitleVector(); // Update every class' total number, every word's total occurrence // number, the total number of all the diffrent words, Map<Long, Long> wordNumInThisClass = new HashMap<Long, Long>(); totalWordNumInClass.put(categoryName, 0D); for (Iterator<Long> it = contentMap.keySet().iterator(); it .hasNext();) { Long wordHash = it.next(); int wordCount = contentMap.get(wordHash); // If this word never appear in the whole sample documents, we // should initialize some intermediate variable. if (wordNumInTotalClass.containsKey(wordHash)) { wordNumInTotalClass.put(wordHash, wordNumInTotalClass.get(wordHash) + wordCount); } else { wordNumInTotalClass.put(wordHash, (double) wordCount); ++totalDifferWordNum; } // If this word never appear in this category sample documents, // we should initialize some intermediate variable. // (In the document's contentMap, there isn't two same words.) wordNumInThisClass.put(wordHash, (long) wordCount); totalWordNumInClass.put(categoryName, totalWordNumInClass.get(categoryName) + (double) wordCount); totalWordOccurNum += (double) wordCount; } wordNumInClass.put(categoryName, wordNumInThisClass); } // Calculate the prior prob of every category for (int i = 0; i < documents.length; i++) { String categoryName = documents[i].getCategory(); prior.put(categoryName, totalWordNumInClass.get(categoryName) / totalWordOccurNum); } } /** * Set the member variable allWordChiSquare, which is all the words' * chi-square weight. * <p> * Formula : X^2(D, t, c) = ( ( N11 + N10 + N01 + N00 ) * ( N11 * N00 - N10 * * N01 )^2 ) / ( ( N11 + N01 ) * ( N11 + N10 ) * ( N10 + N00 ) * ( N01 + * N00 ) ) * </p> * <p> * Here we use the approximate formula : chi-square-value = (N11 * N00 - N01 * * N10)^2 / ( N11 + N10 ) * ( N01 + N00) * <p> * From : 《信息检索导论》 13章5小节:特征选择 P194 * */ public Map<String, Map<Long, Double>> chiSquare(int featureWordNum) { Map<String, Map<Long, Double>> featureWordInClass = new HashMap<String, Map<Long, Double>>(); // Calculate every category's chiSquare feature for (Iterator<String> itCategory = wordNumInClass.keySet().iterator(); itCategory .hasNext();) { String categoryName = itCategory.next(); Map<Long, Double> chiSquareInThisClassMap = new HashMap<Long, Double>(); Map<Long, Long> wordNumInThisClass = wordNumInClass .get(categoryName); for (Iterator<Long> itWord = wordNumInThisClass.keySet().iterator(); itWord .hasNext();) { long wordHash = itWord.next(); double N11 = wordNumInThisClass.get(wordHash); double N10 = wordNumInTotalClass.get(wordHash) - N11; double N01 = totalWordNumInClass.get(categoryName) - N11; double N00 = totalWordOccurNum - N11 - N10 - N01; // 分子 double numerator = Math.pow(N11 * N00 - N10 * N01, 2); // 分母 double denominator = wordNumInTotalClass.get(wordHash) * (totalWordOccurNum - wordNumInTotalClass .get(wordHash)); double chiSquareInThisClass = numerator / denominator; chiSquareInThisClassMap.put(wordHash, chiSquareInThisClass); } // Sort every category's words to get the first FEATURE_WORD_NUM // number chiSquare feature words List<Map.Entry<Long, Double>> mappingList = new ArrayList<Map.Entry<Long, Double>>( chiSquareInThisClassMap.entrySet()); Collections.sort(mappingList, new Comparator<Map.Entry<Long, Double>>() { public int compare(Map.Entry<Long, Double> mapping1, Map.Entry<Long, Double> mapping2) { // Descending sort return mapping2.getValue().compareTo( mapping1.getValue()); } }); // Record featureWordNum word's chiSquare value in every category to // allWordChiSquateInClass featureWordInClass Iterator<Entry<Long, Double>> itWord = mappingList.iterator(); Map<Long, Double> featureWordInThisCLass = new HashMap<Long, Double>(); for (int i = 0; i < featureWordNum && itWord.hasNext(); ++i) { Entry<Long, Double> wordEntry = itWord.next(); featureWordInThisCLass.put(wordEntry.getKey(), chiSquareInThisClassMap.get(wordEntry.getKey())); } featureWordInClass.put(categoryName, featureWordInThisCLass); } return featureWordInClass; } /** * <p> * Title: Train multinormalNB * <p> * * @param allFeatureWord * : chi-square feature words * @param wordNumInClass * : category set * @return conprob: P( word | c ) * */ public void chiSquareTrainMultiNormalNB( Map<String, Map<Long, Double>> featureWordInClass) { for (Iterator<String> itCategory = wordNumInClass.keySet().iterator(); itCategory .hasNext();) { String categoryName = itCategory.next(); Map<Long, Double> conprobWordInThisClass = new HashMap<Long, Double>(); // Every feature word should calculate its chiSquare value in this // category for (Iterator<Long> itWord = featureWordInClass.get(categoryName) .keySet().iterator(); itWord.hasNext();) { long wordHash = itWord.next(); if (wordNumInClass.get(categoryName).containsKey(wordHash)) { conprobWordInThisClass .put(wordHash, (wordNumInClass.get(categoryName).get( wordHash) + 1) / (totalWordNumInClass .get(categoryName) + totalDifferWordNum)); } else { conprobWordInThisClass.put(wordHash, (1 / (totalWordNumInClass.get(categoryName)))); } } condprob.put(categoryName, conprobWordInThisClass); } } public void trainMultiNormalNB() { for (Iterator<String> itCategory = wordNumInClass.keySet().iterator(); itCategory .hasNext();) { String categoryName = itCategory.next(); Map<Long, Double> conprobWordInThisClass = new HashMap<Long, Double>(); // Every feature word should calculate its chiSquare value in this // category for (Iterator<Long> itWord = wordNumInClass.get(categoryName) .keySet().iterator(); itWord.hasNext();) { long wordHash = itWord.next(); conprobWordInThisClass.put(wordHash, (wordNumInClass.get(categoryName).get(wordHash) + 1) / (totalWordNumInClass.get(categoryName))); } condprob.put(categoryName, conprobWordInThisClass); } } // // public void outputChiSquareProb(File outputFile) throws IOException { // // if (condprob.size() == 0) { // System.out // .println("You need to use the NBClassifier function to initialize all the intermediate variable firstly!"); // return; // } // // try { // if (!outputFile.exists()) { // outputFile.createNewFile(); // } // } catch (Exception e) { // System.out.print("Fail to create this specified XML file."); // } // // FileWriter out = new FileWriter(outputFile); // BufferedWriter bout = new BufferedWriter(out); // DocWordHashMap wordsDictionary = DocWordHashMap.getInstance(); // // bout.write("<naiveBeyes>\n"); // for (Iterator<String> itCategory = featureWordInClass.keySet() // .iterator(); itCategory.hasNext();) { // String categoryName = itCategory.next(); // bout.write("<category>\n<categoryName>\n" + categoryName // + "\n</categoryName>\n"); // // for (Iterator<Long> itWord = featureWordInClass.get(categoryName) // .keySet().iterator(); itWord.hasNext();) { // long wordHash = itWord.next(); // String word = wordsDictionary.getWordStringHash().get(wordHash); // bout.write("<featureWord>\n<wordHash>\n" + wordHash // + "\n</wordHash>\n"); // bout.write("<string>\n" + word + "\n</string>\n"); // bout.write("<chiSquare>\n" // + featureWordInClass.get(categoryName).get(wordHash) // + "\n</chiSquare>\n</featureWord>\n"); // } // bout.write("\n</category>\n"); // } // bout.write("\n</naiveBeyes>\n"); // bout.flush(); // out.close(); // } /** * Initialize all the intermediate variable. * * @param file * : The directory of all the category sample documents * */ public void chiSquareNBclassifier(File file, int featureWordNum) { init(file); chiSquareTrainMultiNormalNB(chiSquare(featureWordNum)); } /** * <p> * CreateTime : 2014-11-20 * * */ public void chiSquareNBclassifier(IDocuments[] docs, int featureWordNum) { // initialize the naive bayes word prob map and the category word prob map. init(docs); // Generate the condprob and prior map of the model. chiSquareTrainMultiNormalNB(chiSquare(featureWordNum)); } public Map<String, Map<Long, Double>> getCondprob() { return condprob; } public Map<String, Double> getPrior() { return prior; } }
[ "xiaoxiaoliable@gmail.com" ]
xiaoxiaoliable@gmail.com
47aa619d70bd601615c9b0e4ed01c8b8f002c458
f0332dd41c7ce6a97ea987f832713a55b90121a5
/src/main/java/com/hxy/nzxy/stexam/center/region/controller/ExamRoomController.java
941c2fe8f48e6b4f5f63d828702416c9622442e0
[]
no_license
tanghui11/workings
ec363b972427b871f42cabdbe5e2fd3ed22ea2f8
cb7ad7c7c27a1636a6cbfaff3904581f7b1e8ef8
refs/heads/master
2022-01-23T09:46:59.060235
2019-08-27T08:33:55
2019-08-27T08:33:55
180,955,439
0
0
null
null
null
null
UTF-8
Java
false
false
3,520
java
package com.hxy.nzxy.stexam.center.region.controller; import java.util.List; import java.util.Map; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.hxy.nzxy.stexam.domain.ExamRoomDO; import com.hxy.nzxy.stexam.center.region.service.ExamRoomService; import com.hxy.nzxy.stexam.common.utils.*; import com.hxy.nzxy.stexam.common.service.CommonService; import com.hxy.nzxy.stexam.system.controller.SystemBaseController; /** * 考场 * * @author lzl * @email 7414842@qq.com * @date 2018-08-07 18:39:18 */ @Controller @RequestMapping("/region/examRoom") public class ExamRoomController extends SystemBaseController{ @Autowired private ExamRoomService examRoomService; @Autowired private CommonService commonService; @GetMapping() @RequiresPermissions("region:examRoom:examRoom") String ExamRoom(){ return "center/region/examRoom/examRoom"; } @ResponseBody @GetMapping("/list") @RequiresPermissions("region:examRoom:examRoom") public PageUtils list(@RequestParam Map<String, Object> params){ //查询列表数据 Query query = new Query(params); List<ExamRoomDO> examRoomList = examRoomService.list(query); for (ExamRoomDO item : examRoomList) { item.setOperator(UserUtil.getName(item.getOperator())); item.setUpdateDate(DateUtils.format(item.getUpdateDate(), DateUtils.DATE_PATTERN)); } int total = examRoomService.count(query); PageUtils pageUtils = new PageUtils(examRoomList, total); return pageUtils; } @GetMapping("/add") @RequiresPermissions("region:examRoom:add") String add(Model model){ return "center/region/examRoom/add"; } @GetMapping("/edit/{id}") @RequiresPermissions("region:examRoom:edit") String edit(@PathVariable("id") Long id,Model model){ ExamRoomDO examRoom = examRoomService.get(id); model.addAttribute("examRoom", examRoom); return "center/region/examRoom/edit"; } /** * 保存 */ @ResponseBody @PostMapping("/save") @RequiresPermissions("region:examRoom:add") public R save( ExamRoomDO examRoom){ examRoom.setOperator(ShiroUtils.getUserId().toString()); if(examRoomService.save(examRoom)>0){ return R.ok(); } return R.error(); } /** * 修改 */ @ResponseBody @RequestMapping("/update") @RequiresPermissions("region:examRoom:edit") public R update( ExamRoomDO examRoom){ examRoom.setOperator(ShiroUtils.getUserId().toString()); examRoomService.update(examRoom); return R.ok(); } /** * 删除 */ @PostMapping( "/remove") @ResponseBody @RequiresPermissions("region:examRoom:remove") public R remove( Long id){ if(examRoomService.remove(id)>0){ return R.ok(); } return R.error(); } /** * 删除 */ @PostMapping( "/batchRemove") @ResponseBody @RequiresPermissions("region:examRoom:batchRemove") public R remove(@RequestParam("ids[]") Long[] ids){ examRoomService.batchRemove(ids); return R.ok(); } }
[ "2435029719@qq.com" ]
2435029719@qq.com
ad8c3a3c0b264c6e56da5fc77cdacd78651d94a0
1eb158d0e1c9062a97e15e0b233278bf158ecd57
/Sdet/src/test/java/com/crm/vtiger/testcases/TC_01_CreateOrganisationTest.java
acaab40ccf0de6dad1b0327b04a86598e4e6a7cf
[]
no_license
Shubh053/AutomationFrameworkArchitecture
0b3ecf7bd286a06668f15e2f766e54e07a50696c
90cbf03929b8c6401cbce13699a6ed129af221fb
refs/heads/master
2023-07-30T01:40:29.784698
2021-09-19T10:06:27
2021-09-19T10:06:27
408,092,428
0
0
null
null
null
null
UTF-8
Java
false
false
2,547
java
package com.crm.vtiger.testcases; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; import org.testng.annotations.Test; import com.crm.vtiger.genericutils.ExcelUtility; import com.crm.vtiger.genericutils.FileUtility; import com.crm.vtiger.genericutils.JavaUtility; import com.crm.vtiger.genericutils.CommonUtility; public class TC_01_CreateOrganisationTest { WebDriver driver; @Test public void createOrganisationTest() throws Throwable { // get the data from external resources FileUtility file = new FileUtility(); CommonUtility wdu = new CommonUtility(); JavaUtility ju = new JavaUtility(); ExcelUtility eu = new ExcelUtility(); String BROWSER = file.getDataFromJson("browser"); String URl =file.getDataFromJson("url"); String USERNAME = file.getDataFromJson("username"); String PASSWORD = file.getDataFromJson("password"); String ORGANIZATIONNAME = eu.getDataFromExcel("Sheet1", 1, 2); // select the browser if(BROWSER.equalsIgnoreCase("chrome")) { driver = new ChromeDriver(); } else if (BROWSER.equalsIgnoreCase("firefox")) { driver = new FirefoxDriver(); } else { System.out.println("Invalid Browser"); } // wait for the element to load wdu.waitUntilPageLoad(driver); // maximise the browser wdu.maximizeWindow(driver); // launch browser driver.get(URl); // login to application driver.findElement(By.name("user_name")).sendKeys(USERNAME); driver.findElement(By.name("user_password")).sendKeys(PASSWORD); driver.findElement(By.id("submitButton")).click(); // create organization driver.findElement(By.linkText("Organizations")).click(); driver.findElement(By.cssSelector("img[title='Create Organization...']")).click(); driver.findElement(By.name("accountname")).sendKeys(ORGANIZATIONNAME + ju.getRanDomNumber()); driver.findElement(By.xpath("//input[@value=' Save ']")).click(); // sign out from application WebElement editButton = driver.findElement(By.name("Edit")); wdu.waitForElementVisibility(driver, editButton); WebElement signOut = driver.findElement(By.xpath("//img[@src='themes/softed/images/user.PNG']")); wdu.mouseOver(driver, signOut); WebElement clickSignOut = driver.findElement(By.linkText("Sign Out")); wdu.mouseOver(driver, clickSignOut); // close the browser wdu.closeBrowser(driver); } }
[ "shubhams053@gmail.com" ]
shubhams053@gmail.com
91168d1dcb41fc28fdda96f683cc3044f0937d2f
4aa38dc3cdb15257889c939a3ce8eef5c7842026
/src/Solution/InsertArray.java
e3bb28e0dd8f5df5d1759fe06e3d87f17cdf4dbf
[]
no_license
missxie523/InsertArray
5ce7bf11ac286388b8a78af92f4b8cf70a3aa6cf
f6b9a20eb0642d783dffbb99b3ad18793e3d97b9
refs/heads/master
2020-03-23T02:16:47.854723
2018-07-14T17:46:39
2018-07-14T17:46:39
140,966,212
0
0
null
null
null
null
UTF-8
Java
false
false
1,062
java
package Solution; import java.util.Arrays; /* Given an array, and an element to insert, and the position to insert this element. Return a new array with the element inserted. */ public class InsertArray { public static int[] insert(int[] array, int num, int position){ int[] newArray = new int[array.length + 1]; position = Math.min(array.length, position); for(int i = 0; i < position; i++){ newArray[i] = array[i]; } newArray[position] = num; for(int j = position; j < array.length; j++){ newArray[j + 1] = array[j]; } return newArray; } public static void main(String[] args){ int[] array = new int[] {1, 3, 5, 6, 9}; int num = 5; int position = 4; System.out.println(Arrays.toString(insert(array, num, position))); } } /* Is it possible to write a version of this method that returns void and changes x in place? No. Because array has fixed initialized length, so to add an element, you need to create a new array. */
[ "missxie523@gmail.com" ]
missxie523@gmail.com
b559f815af4d9b5495a4c964907721a6150b431a
26f117318db6be8a2bd0fef18bc782ef6c57c273
/2D Arrays/src/Challenges.java
3553aa07cdc8ecb0b5a0312e124775ca8843e0c9
[]
no_license
DonovanCo/2D-Arrays
14980a7444fa05497ff4e72ef15084606996062b
ac0d7beb84758cd2b15b9cb644f07942bdd08224
refs/heads/master
2016-09-05T18:20:18.541769
2015-05-22T14:05:55
2015-05-22T14:05:55
36,075,397
0
0
null
null
null
null
UTF-8
Java
false
false
1,250
java
public class Challenges { public static void findNine() { int counter = 0; int newArray[][] = { { 2, 4, 6, 8 }, { 3, 6, 9, 12 }, { 4, 8, 12, 16 } }; for (int i = 0; i < 3; i++) { System.out.println(); for (int x = 0; x < 4; x++) { System.out.print(newArray[counter][x] + "\t"); } counter = counter + 1; } System.out.println("\n" + newArray[1][2]); } public static void printMustangs() { String[][] mustArray = new String[5][3]; String must = "Mustangs"; for (int y = 0; y < 5; y++) { for (int m = 0; m < 3; m++) { mustArray[y][m] = must; } } for (int row = 0; row < 5; row++) { System.out.println("\n"); for (int column = 0; column < 3; column++) { System.out.print(mustArray[row][column] + "\t"); } } } public static void print10s(); { int helpMe=0; int[][] printTen = new int[3][3]; for (int ghostnappa = 0; ghostnappa < 3; ghostnappa++) { for (int krilin = 0; krilin < 3; krilin++) { printTen[ghostnappa][krilin]=((1+helpMe)*10); } } } public static void main(String[] args) { findNine(); printMustangs(); } }
[ "cole.donovan@MU-C3-10.mullen.pvt.k12.co.us" ]
cole.donovan@MU-C3-10.mullen.pvt.k12.co.us
52daa0cc2f7ad13eb7f12d9519e4ef8b5f2d4158
a6627cc752a55c6f208a6855f656b47e5e8ecbf8
/src/test/java/FirstTest.java
6c8479f99f49c1817e5e80d5574f36bdad1d2cb4
[]
no_license
plijy8/test-course
111534fe27abc154be7a89c3743782e1a226a709
382ffadc1e5da9b1b49a7162267d8da8093dd09f
refs/heads/master
2021-05-01T06:02:58.928106
2018-02-11T15:25:06
2018-02-11T15:25:06
121,135,265
0
0
null
null
null
null
UTF-8
Java
false
false
5,054
java
package autotest; import org.junit.BeforeClass; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.List; import java.util.concurrent.TimeUnit; import static org.openqa.selenium.By.className; import static org.openqa.selenium.By.cssSelector; import static org.openqa.selenium.By.xpath; public class FirstTest { private static WebDriver driver; @BeforeClass public void DriverStart(){ System.setProperty("webdriver.chrome.driver","src/main/resources/chromedriver"); driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } @Test public void MailRuLocatorsTest(){ driver.get("https://account.mail.ru/signup?from=main&rf=auth.mail.ru"); WebElement headerText = driver.findElement(cssSelector("span.b-panel__header__text")); WebElement firstNameLabel = driver.findElement(xpath("//*[@data-field-name = 'firstname']//label")); WebElement secondNameLabel = driver.findElement(xpath("//*[@data-field-name = 'lastname']//label")); WebElement firstNameInput = driver.findElement(By.name("firstname")); WebElement secondNameInput = driver.findElement(By.name("lastname")); WebElement birthdate = driver.findElement(xpath("//*[@data-field-name = 'birthdate']//label")); WebElement dateDaySelector = driver.findElement(cssSelector("div.b-date__day")); List<WebElement> dateDays = driver.findElements(cssSelector("div.b-date__day a")); WebElement dateMonthSelector = driver.findElement(cssSelector("div.b-date__month")); List<WebElement> dateMonths = driver.findElements(cssSelector("div.b-date__month a")); WebElement dateYearSelector = driver.findElement(cssSelector("div.b-date__year")); List<WebElement> dateYears = driver.findElements(cssSelector("div.b-date__year a")); WebElement menSexBtn = driver.findElement(xpath("(//*[@class= 'b-radiogroup__radio'])[1]")); WebElement womenSexBtn = driver.findElement(xpath("(//*[@class= 'b-radiogroup__radio'])[2]")); WebElement menSexLabel = driver.findElement(xpath("//*[@data-mnemo = 'sex-male']//span/span/span")); WebElement womenSexLabel = driver.findElement(xpath("//*[@data-mnemo = 'sex-female']//span/span/span")); WebElement emailLabel = driver.findElement(xpath("//*[@data-field-name = 'email']//label")); WebElement emailInput = driver.findElement(cssSelector(".b-email__name > input")); WebElement passwordInput = driver.findElement(By.name("password")); WebElement passwordLabel = driver.findElement(xpath("//*[@data-field-name = 'password']//label")); WebElement passwordEye = driver.findElement(cssSelector("div.b-password__eye")); WebElement phoneLabel = driver.findElement(xpath("//*[@data-field-name = 'phone']//label")); WebElement coutrySelector = driver.findElement(xpath("(//*[@class = 'b-dropdown__ctrl'])[5]")); List<WebElement> countries = driver.findElements(xpath("(//*[@class = 'b-dropdown__list'])[5]/a")); WebElement phoneNumberInput = driver.findElement(cssSelector(".b-phone__input-box input")); WebElement phoneLink = driver.findElement(cssSelector("div.b-form-field__message a")); WebElement registerationBtn = driver.findElement(cssSelector("button.btn ")); WebElement agrigmentLink = driver.findElement(cssSelector("div.b-form__controls__message a")); } @Test public void SoftwareLocatorsTest(){ driver.get("http://software-testing.ru/"); WebElement homeLink = driver.findElement(cssSelector("#tpdiv-logo a")); WebElement sidebarMenuItem = driver.findElement(xpath("//*[@class = 'menu']/li[4]")); WebElement sidebarInstrumentItem = driver.findElement(xpath("//*[text()='Selenium']")); WebElement topMenuItem = driver.findElement(xpath("//*[@id='tp-cssmenu']/li[3]/a")); WebElement search = driver.findElement(className("inputbox-search")); WebElement fontSizeBtn = driver.findElement(cssSelector(".fontSizePlus img")); WebElement postTitle = driver.findElements(className("contentheading")).get(3); } @Test public void WeatherTest() { driver.get("https://ya.ru/"); WebElement search = driver.findElement(cssSelector(".input__control.input__input")); search.clear(); search.sendKeys("Погода в Пензе", Keys.ENTER); String searchResult = driver.findElement(xpath("//li[@class = 'serp-item'][1]//h2/a")).getText(); Assert.assertEquals(searchResult,"Погода в Пензе"); } @AfterClass public void DriverClose(){ driver.quit(); } }
[ "barmotin@haulmont.com" ]
barmotin@haulmont.com
45c9fdc609a9ac7e0fd8173661575f70dad84c4a
34d660b60ce7d4d9a3593e57d20843d3a09075c2
/src/main/java/geo/db/CoordinatesControllerService.java
65974e999026f94d7e76a24f60a8bd994ecc23ac
[]
no_license
kola981/NominatimTest
c4de2cb7a77ef2232244065d797ee5ef9a60efd3
4639c03ed5200f92efcd21a33caa18478f7802fb
refs/heads/main
2023-07-14T06:47:39.259931
2021-08-31T23:12:35
2021-08-31T23:12:35
400,578,518
0
0
null
null
null
null
UTF-8
Java
false
false
852
java
package geo.db; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import geo.db.entity.Coordinates; import geo.web.dto.CoordinatesDto; @Service public class CoordinatesControllerService { private final CoordinatesDataService dataService; @Autowired public CoordinatesControllerService(CoordinatesDataService dataService) { this.dataService = dataService; } public void save(CoordinatesDto dto) { Coordinates entity = CoordinatesConverter.convert(dto); dataService.save(entity); } public List<CoordinatesDto> getAllCoordinates() { List<Coordinates> entities = dataService.findAll(); return entities.stream() .map(CoordinatesConverter::convert) .collect(Collectors.toList()); } }
[ "baxykkit@outlook.com" ]
baxykkit@outlook.com
1141d540e9e753772819feb1a3ec68ab6305b99e
93f3035429165ea7e1854670e4b8fecd9d3a9f01
/medsys/src/main/java/com/medsys/orders/bd/PurchaseOrderBD.java
348a2e66208b9394a73284301a1bd598d54d0ce7
[]
no_license
tisyak/codepensieve
46e88e64ade9c0917f3af18b8bf1541f985a62aa
31d96013c6669628c0b05762e142b423b4ab7c39
refs/heads/master
2021-01-11T20:51:38.964679
2018-03-02T12:02:31
2018-03-02T12:02:31
79,198,517
0
0
null
null
null
null
UTF-8
Java
false
false
1,331
java
package com.medsys.orders.bd; import java.util.Date; import java.util.List; import com.medsys.common.model.Response; import com.medsys.orders.model.PurchaseOrder; import com.medsys.orders.model.PurchaseOrderProductSet; public interface PurchaseOrderBD { public Response addPurchaseOrder(PurchaseOrder purchaseOrder); public PurchaseOrder getPurchaseOrder(Integer purchaseOrderId); public PurchaseOrder updatePurchaseOrder(PurchaseOrder purchaseOrder); public Response deletePurchaseOrder(Integer purchaseOrderId); public List<PurchaseOrder> getAllPurchaseOrder(); public List<PurchaseOrder> searchForPurchaseOrder(PurchaseOrder purchaseOrder); public List<PurchaseOrderProductSet> getAllProductsInPurchaseOrder(Integer purchaseOrderId); public Response addProductToPurchaseOrder(PurchaseOrderProductSet newPOProductSet); public PurchaseOrderProductSet getProductInPurchaseOrder(Integer poProductSetId); public Response updateProductInPurchaseOrder(PurchaseOrderProductSet poProductSet); public Response deleteProductFromPurchaseOrder(PurchaseOrderProductSet poProductSet); public List<PurchaseOrder> searchForPurchaseOrder(Date fromDate, Date toDate); public int getCountOfTotalPurchaseOrdersInMonth(); public int getCountOfTotalPurchaseOrdersForYear(); }
[ "tisya.krishnan@gmail.com" ]
tisya.krishnan@gmail.com
bf43c0ebc03a529b1cd7b0a75cc021f42aed3e6e
d1ca473a2f6e5eea125efdf218c3ad336f0cd338
/src/oct1621/LinkedHashSetTest.java
4962bb58c69753aeb6e6678290e67882c3f16d4f
[]
no_license
sumeetyajnik/Java_Core_Phase1
c9c21084402253eac3808c40a678babde4c45bda
2a9c68e3a56da8a3b8eacff3e84f3de2d2f6548f
refs/heads/main
2023-09-05T07:03:27.520411
2021-10-24T15:12:23
2021-10-24T15:12:23
417,088,558
0
0
null
null
null
null
UTF-8
Java
false
false
1,100
java
package oct1621; import java.util.LinkedHashSet; import java.util.Scanner; public class LinkedHashSetTest { public static void main(String[] args) { LinkedHashSet l1 = new LinkedHashSet(); l1.add(1); l1.add(2); l1.add(5.6f); l1.add(3.76f); l1.add('a'); l1.add('b'); l1.add(true); System.out.println("LinkedHashSet l1 is " + l1); System.out.println("Size of LinkedHashSet l1 is " + l1.size()); LinkedHashSet<Integer> l2 = new LinkedHashSet<Integer>(); System.out.println("Enter the input Interger any order 1 to 8"); Scanner input = new Scanner(System.in); int i1 = input.nextInt(); int i2 = input.nextInt(); int i3 = input.nextInt(); int i4 = input.nextInt(); int i5 = input.nextInt(); int i6 = input.nextInt(); int i7 = input.nextInt(); int i8 = input.nextInt(); l2.add(i1); l2.add(i2); l2.add(i3); l2.add(i4); l2.add(i5); l2.add(i6); l2.add(i7); l2.add(i8); System.out.println("LinkedHashSet l2 is : " + l2); System.out.println("Size of LinkedHashSet l2 is " + l2.size()); } }
[ "sumeet.yajnik@ellucian.com" ]
sumeet.yajnik@ellucian.com
cb170ffa90ddd92730ce4412b815b0b89eccc847
8171a014b6974b5e7addb663c389fa06cbac563f
/src/test/java/mybatis/MybatisTest.java
8a102dac652233d5597727d5d2b094e3a641dd2b
[]
no_license
bestwishCT/mongodb-web
4ccd8bb689cc0df1e1124b2ae32594678e576a4f
35ad8bf76d0932ca3ba1303c86f4e380a98d2a6c
refs/heads/master
2023-01-12T03:50:46.365553
2020-11-17T09:40:30
2020-11-17T09:40:30
309,590,580
1
0
null
null
null
null
UTF-8
Java
false
false
107
java
package mybatis; public class MybatisTest { public static void main(String[] args) { } }
[ "1758031883@qq.com" ]
1758031883@qq.com
155d3336134578a74acd9f1e27ee4f4e48698b98
9c59825811c27cbf6c3dc22bd9c4123d6e3625f4
/app/src/main/java/com/example/softpool/softpool/CriarBoleiaFragment.java
8915e97727f18ee569a6e02c8ed8f8823cd84c2c
[ "MIT" ]
permissive
L31T40/SoftPool-Android
b576c6bfb576a5797e9a73217a4f5a51ec734fd6
4c166046c5e5b90f2a059c66c743e8973e75392d
refs/heads/master
2020-03-19T03:43:16.790968
2020-02-29T17:32:47
2020-02-29T17:32:47
135,755,555
0
0
null
null
null
null
UTF-8
Java
false
false
23,003
java
package com.example.softpool.softpool; import android.app.Activity; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.Spinner; import android.widget.Switch; import android.widget.TextView; import android.widget.TimePicker; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import static android.content.ContentValues.TAG; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link CriarBoleiaFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link CriarBoleiaFragment#newInstance} factory method to * create an instance of this fragment. */ public class CriarBoleiaFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; public Activity aa; Calendar currentDate; int mDay, mMonth, mShowMonth, mYear,hour, mhour, minute; TextView tvdataPartida,tvhoraPartida; TextView tvdataChegada,tvhoraChegada; String format; // AutoCompleteTextView autoTextViewPartida,autoTextViewChegada,t1,t2; int posPartidaCria=0; int posChegadaCria=0; String tempPartida=""; String tempChegada=""; //Switch SwitchSeguro; Switch SwitchMotivo; public ArrayList<HashMap<String, String>> ListaLocais; public ArrayList<HashMap<String, String>> listaViaturas; String array1[]; int spinnerPos; int spinnerPosViatura; String spinnerStringViatura; Spinner spinnerLotacao; Spinner mySpinnerLotacao; EditText matricula; Object item; Object itemViatura; int posPartidaPes=0; int posChegadaPes=0; Spinner mySpinnerChegada, mySpinnerPartida,t1,t2; String spinnerChegStr, spinnerPartStr; public CriarBoleiaFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment CriarBoleiaFragment. */ // TODO: Rename and change types and number of parameters public static CriarBoleiaFragment newInstance(String param1, String param2) { CriarBoleiaFragment fragment = new CriarBoleiaFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } VarGlobals g1=(VarGlobals) getActivity().getApplication(); final String idfuncglobal=g1.idFuncGlobal; VarGlobals g3=(VarGlobals) getActivity().getApplication(); listaViaturas=g3.ViaturasUser; VarGlobals g=(VarGlobals) getActivity().getApplication(); // variavel global para detetar se foi feita a decoração no recyclerview g.flagDecoration=false; VarGlobals gLocais=(VarGlobals) getActivity().getApplication(); /** Buscar a string para o autoextview**/ ListaLocais=gLocais.listaLocais1; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view= inflater.inflate(R.layout.criar_boleia_fragment, container, false); String arrayViaturas[] = new String[listaViaturas.size()]; //colca as viaturas num array para encher o spinner for (int i = 0; i < listaViaturas.size(); i++) { arrayViaturas[i] = listaViaturas.get(i).get("matricula"); } ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, arrayViaturas); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); final Spinner spinner = view.findViewById(R.id.spinnerViatura); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) { itemViatura = adapterView.getItemAtPosition(position); spinnerPosViatura=position; spinnerStringViatura=itemViatura.toString(); if (item != null) { int nlotacao=lotacaoParaViatura(itemViatura.toString()); array1 = new String[nlotacao]; for (int i = 0; i < nlotacao; i++) { array1[i] = String.valueOf(i+1); } chamaSpinner(array1); //coloca lotação da viatura referente ao veiculo escolhido } } @Override public void onNothingSelected(AdapterView<?> adapterView) { // TODO Auto-generated method stub } }); spinnerLotacao = view.findViewById(R.id.spinnerLotacao); spinnerLotacao.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub //Code Here } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); /**TODO https://stackoverflow.com/questions/33297676/set-second-spinner-adapter-from-first-spinner*/ SwitchMotivo=view.findViewById(R.id.switch_Motivo); SwitchMotivo.setChecked(false); String spinnerArrayLocais[] = new String[ListaLocais.size()]; // coloca os nomes das cidade em um array para apresentar no spinner for(int j =0;j<ListaLocais.size();j++){ spinnerArrayLocais[j] = ListaLocais.get(j).get("nomecidade"); Log.e(TAG, "DADOS SPINNER " + spinnerArrayLocais[j]); } final ArrayAdapter<String> adapterSpinner = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, spinnerArrayLocais); adapterSpinner.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); mySpinnerPartida = view.findViewById(R.id.spinner_FiltraData); mySpinnerPartida.setAdapter(adapterSpinner); String localFunc= SharedPref.readStr(SharedPref.KEY_LOCAL, null); mySpinnerPartida.setSelection(adapterSpinner.getPosition(localFunc)); mySpinnerPartida.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Object item = parent.getItemAtPosition(position); if (item != null) { posPartidaPes=position; spinnerPartStr=item.toString(); } Log.e("LOCAL PARTIDA : ",spinnerPartStr); } @Override public void onNothingSelected(AdapterView<?> adapterView) { // TODO Auto-generated method stub } }); mySpinnerChegada = view.findViewById(R.id.spinner_Chegada); mySpinnerChegada.setAdapter(adapterSpinner); mySpinnerChegada.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Object item = parent.getItemAtPosition(position); if (item != null) { posChegadaPes=position; spinnerChegStr=item.toString(); } Log.e("LOCAL CHEGADA : ",spinnerChegStr); } @Override public void onNothingSelected(AdapterView<?> adapterView) { // TODO Auto-generated method stub } }); tvdataPartida = view.findViewById(R.id.textViewCriarDataBoleia); tvhoraPartida = view.findViewById(R.id.textViewCriarHoraBoleia); tvdataChegada = view.findViewById(R.id.textViewCriarDataBoleiaChegada); tvhoraChegada = view.findViewById(R.id.textViewCriarHoraBoleiaChegada); currentDate = Calendar.getInstance(); mDay = currentDate.get(Calendar.DAY_OF_MONTH); mMonth = currentDate.get(Calendar.MONTH); mYear = currentDate.get(Calendar.YEAR); mhour = currentDate.get(Calendar.HOUR_OF_DAY); minute = currentDate.get(Calendar.MINUTE); mShowMonth=mMonth+1; tvdataChegada.setText(String.format("%02d/%02d/%02d",mDay,mShowMonth,mYear)); //mostra a data com zero à esquerda tvdataPartida.setText(String.format("%02d/%02d/%02d",mDay,mShowMonth,mYear)); tvhoraPartida.setText(String.format("%02d : %02d",mhour,minute));//mostra a hora com zero à esquerda tvhoraChegada.setText(String.format("%02d : %02d",mhour,minute)); mySpinnerLotacao = view.findViewById(R.id.spinner_Lotacao); matricula = view.findViewById(R.id.editText_Matricula); TextView buttonData = tvdataPartida; buttonData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { DatePickerDialog datePickerDialog = new DatePickerDialog( getActivity(), new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int i, int i1, int i2) { i1 = i1 + 1; tvdataPartida.setText(String.format("%02d/%02d/%02d",i2,i1,i)); } }, mYear, mMonth, mDay); datePickerDialog.show(); }}); TextView buttonDataChegada = tvdataChegada; buttonDataChegada.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { DatePickerDialog datePickerDialog = new DatePickerDialog( getActivity(), new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int i, int i1, int i2) { i1 = i1 + 1; tvdataChegada.setText(String.format("%02d/%02d/%02d",i2,i1,i)); //tvdataChegada.setText(i2 + "/" + i1 + "/" + i); } }, mYear, mMonth, mDay); datePickerDialog.show(); }}); TextView buttonHora = tvhoraPartida; buttonHora.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { //hourOfDay = selectedTimeFormat(hourOfDay); tvhoraPartida.setText(hourOfDay + " : " + minute); } }, hour , minute, true); timePickerDialog.show(); }}); TextView buttonHoraChegada = tvhoraChegada; buttonHoraChegada.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { //hourOfDay = selectedTimeFormat(hourOfDay); tvhoraChegada.setText(hourOfDay + " : " + minute); } }, hour , minute, true); timePickerDialog.show(); }}); ImageView swapbutton = view.findViewById(R.id.imageView_swap); swapbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { //String strtemp=tempPartida; // variavel temporaria para inverter as posições int posTemp=posPartidaPes; t1 = view.findViewById(R.id.spinner_FiltraData); mySpinnerPartida.setSelection(posChegadaPes); t2 = view.findViewById(R.id.spinner_Chegada); mySpinnerChegada.setSelection(posTemp); posPartidaPes=posChegadaPes; posChegadaPes=posTemp; }}); final Spinner spinnerlotacao = view.findViewById(R.id.spinnerLotacao); /**botao para criação de boleia * * falta acrescentar mais cenas nomeadamente coisas**/ Button btncriar = view.findViewById(R.id.btnCriar); btncriar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String partidaArray[] = new String[ListaLocais.size()]; // vai buscar o IDlocal das coidades escolhidas for(int j =0;j<ListaLocais.size();j++){ partidaArray[j] = ListaLocais.get(j).get("nomecidade"); if (partidaArray[j].equals(spinnerPartStr)){ spinnerPartStr=ListaLocais.get(j).get("idlocal"); Log.e(TAG, "PARAMETRO PARTIDA " + spinnerPartStr); }; if (partidaArray[j].equals(spinnerChegStr)){ spinnerChegStr=ListaLocais.get(j).get("idlocal"); Log.e(TAG, "PARAMETRO CHEGADA " + spinnerChegStr); }; } String swMotivo="0",swSeguro="0"; if (SwitchMotivo.isChecked()){ swMotivo="1"; } String idViatura = indexParaViatura(itemViatura.toString()); String PartidaCria = String.valueOf(spinnerPartStr); String ChegadaCria = String.valueOf(spinnerChegStr); String DataBoleiaPartida = tvdataPartida.getText().toString() + " " + tvhoraPartida.getText().toString(); String DataBoleiaChegada = tvdataChegada.getText().toString() + " " + tvhoraChegada.getText().toString(); Utils utils=new Utils(aa); String dataPartida = utils.stringParaData(String.valueOf(DataBoleiaPartida),"dd/MM/yyyy HH : mm","yyyy-MM-dd HH:mm:ss"); //devolve data no formato indicado String dataChegada = utils.stringParaData(String.valueOf(DataBoleiaChegada),"dd/MM/yyyy HH : mm","yyyy-MM-dd HH:mm:ss"); //devolve data no formato indicado String lotacao = spinnerlotacao.getSelectedItem().toString(); try{ JSONObject jsonObject = new JSONObject(); jsonObject.put("IDVIATURA",idViatura); jsonObject.put("ORIGEM",PartidaCria); jsonObject.put("DESTINO",ChegadaCria); jsonObject.put("DATA_DE_PARTIDA",dataPartida); jsonObject.put("DATA_DE_CHEGADA",dataChegada); jsonObject.put("LUGARES_DISPONIVEIS",lotacao); jsonObject.put("OBJECTIVO_PESSOAL",swMotivo); jsonObject.put("IDUTILIZADOR",SharedPref.readStr(SharedPref.KEY_USER, null)); aa=getActivity(); EnviarJSONparaBD dp = new EnviarJSONparaBD(aa); //Criar viaturas dp.jsonObjSend=jsonObject; dp.urljson= "http://soft.allprint.pt/index.php/criar/criarboleiamobile"; dp.execute(); Utils.minhaTosta(aa, R.drawable.completo, "Boleia Criada", "long", "sucesso").show(); }catch (JSONException ex){ //TODO handle Error here Utils.minhaTosta(aa, R.drawable.cancelado, "ERRO no Servidor", "short", "erro").show(); } }}); Button btncancelar = view.findViewById(R.id.btnCancelar); btncancelar.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager(); fm.popBackStack(); } }); return view; } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /**Procura o ID da viatura na Arraylist, de acordo com a matricula e volve o resultado**/ String indexParaViatura(String strMatricula) { for (int i = 0; i < listaViaturas.size(); i++) { /**percorre a lista dos veiculos do utilizador*/ HashMap<String, String> map = listaViaturas.get(i); if (map.containsValue(strMatricula)) { String idviat = map.get("idviatura"); return idviat; } } return "-1"; // não encontrado } protected void chamaSpinner(String lotacao[]) { // TODO Auto-generated method stub ArrayAdapter ad2=new ArrayAdapter(getActivity(), android.R.layout.simple_spinner_item,lotacao); ad2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); spinnerLotacao.setAdapter(ad2); // spinnerLotacao.setSelection(ad2.getPosition(lotacao.length)); } /**Procura a lotacao da viatura na Arraylist, de acordo com a matricula e devolve o resultado**/ protected int lotacaoParaViatura(String strMatricula) { for (int i = 0; i < listaViaturas.size(); i++) { /**percorre a lista dos veiculos do utilizador*/ HashMap<String, String> map = listaViaturas.get(i); if (map.containsValue(strMatricula)) { return Integer.parseInt(map.get("lotacao")); } } return -1; // não encontrado } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } } /* // insere o array dos locais nas 2 autotextview do layout autoTextViewPartida =view.findViewById(R.id.autoCompleteTextView_criarLocalPartida); autoTextViewChegada = view.findViewById(R.id.autoCompleteTextView_criarLocalChegada); ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, listaLocaiss); autoTextViewPartida.setThreshold(1); autoTextViewChegada.setThreshold(1); autoTextViewPartida.setAdapter(adapter1); autoTextViewChegada.setAdapter(adapter1); //SwitchSeguro=view.findViewById(R.id.switch_Seguro); // SwitchSeguro.setChecked(false); this.autoTextViewPartida.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { VarGlobals g1=(VarGlobals) getActivity().getApplication(); // Buscar a string para o autoextview final ArrayList<String> listaLocaiz=g1.listaLocais; posPartidaCria=listaLocaiz.indexOf(autoTextViewPartida.getText().toString())+1; //Verifica a posição da escolha no autotextview incrementa 1 valor, pois o array começa a 0 tempPartida = autoTextViewPartida.getText().toString();// atribui a string da posição escolhida à variavel //Toast.makeText(getActivity(), "posição: "+pos, Toast.LENGTH_LONG).show(); // should be your desired number } }); this.autoTextViewChegada.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { VarGlobals g1=(VarGlobals) getActivity().getApplication(); //Buscar a string para o autoextview final ArrayList<String> listaLocaiz=g1.listaLocais; posChegadaCria=listaLocaiz.indexOf(autoTextViewChegada.getText().toString())+1; //Verifica a posição da escolha no autotextview incrementa 1 valor, pois o array começa a 0 tempChegada = autoTextViewChegada.getText().toString(); // atribui a string da posição escolhida à variavel //Toast.makeText(getActivity(), "posição: "+pos, Toast.LENGTH_LONG).show(); // should be your desired number } });*/
[ "jorgeleitao76@gmail.com" ]
jorgeleitao76@gmail.com
e71b2502a8724487a4dcb62d25e7a0779786684c
84683bd04fe4a8d6d27732dabbb0df62578a1fe7
/enum/src/com/enumpkg/Demoswitch.java
e3b11f0388ac11b1163dd3355f7a6feee4013adf
[]
no_license
vivekanandbellale-tudip/aaaaaaaaaaaaaa
f8a2d40759bf258d95b319bd2d381618620013fc
43134119a8743cc428732e7573b7ee4f5857d0c6
refs/heads/master
2021-01-12T09:13:03.474078
2016-12-23T03:27:16
2016-12-23T03:27:16
76,800,418
0
0
null
null
null
null
UTF-8
Java
false
false
612
java
package com.enumpkg; public class Demoswitch { public static void main(String[] args) { // TODO Auto-generated method stub Days d = Days.mo; switch (d) { case su: System.out.println("SUNDAY"); break; case mo: System.out.println("MONDAY"); break; case tu: System.out.println("TUESDAY"); break; case we: System.out.println("WEDNESDAY"); break; case th: System.out.println("THURSDAY"); break; case fr: System.out.println("FRIDAY"); break; case sa: System.out.println("SATURDAY"); break; // case WEEK: // // break; } } }
[ "vickybellale@gmail.com" ]
vickybellale@gmail.com
b65fe9b66b444422e5bb72d5cb479795906ea729
430e1fcf16140de1f68d909609df82182a5faf21
/ch11/tflite/android/app/src/test/java/com/ailabby/hellotflite/ExampleUnitTest.java
d442c264bf59029571e1f6ffc16b21ad29732c65
[ "MIT" ]
permissive
richardawe/Intelligent-Mobile-Projects-with-TensorFlow
50029b188c5c4097dd5171967f5fe3b9a70db25b
79a546b776ece025ee274a6fe2a01225cefdc69b
refs/heads/master
2023-05-11T06:43:59.882148
2023-05-09T00:38:09
2023-05-09T00:38:09
231,757,448
0
0
MIT
2020-01-04T12:14:22
2020-01-04T12:14:21
null
UTF-8
Java
false
false
401
java
package com.ailabby.hellotflite; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
[ "akhiln@packtpub.com" ]
akhiln@packtpub.com
c49de53443cdb1b13df18131169f9ef3023e14d8
32a761f1c418dc6e111fecf0b508bdb6845cda65
/httplibrary/src/main/java/com/example/httplibrary/callback/BaseObserver.java
347111ed3a6e76847330c5edfd1c71f272dceb1b
[]
no_license
546547tete/Day06
06148055f7058ea849a756b5f503d42bf0cc697e
7e059eaa8d2fd8c168e896d19949f75e95a0339e
refs/heads/master
2022-11-26T17:25:54.721229
2020-08-05T12:53:08
2020-08-05T12:53:08
285,287,306
0
0
null
null
null
null
UTF-8
Java
false
false
2,118
java
package com.example.httplibrary.callback; import android.text.TextUtils; import com.example.httplibrary.HttpGlobalConfig; import com.example.httplibrary.disposable.RequestManagerIml; import com.example.httplibrary.exception.ApiException; import com.example.httplibrary.exception.ExceptionEngine; import com.example.httplibrary.utils.ThreadUtils; import io.reactivex.Observer; import io.reactivex.disposables.Disposable; /** * 项目名:Shopping * 包名: com.example.httplibrary.callback * 文件名:BaseObserver * 创建者:liangxq * 创建时间:2020/8/1 14:15 * 描述:TODO */ public abstract class BaseObserver implements Observer{ String tag; @Override public void onSubscribe(Disposable d) { if(!TextUtils.isEmpty(tag)){ RequestManagerIml.getInstance().add(tag,d); } } @Override public void onNext(Object t) { if(!TextUtils.isEmpty(tag)){ RequestManagerIml.getInstance().remove(tag); } } @Override public void onError(Throwable e) { if(e instanceof ApiException){ ApiException apiException= (ApiException) e; onError(apiException.getMsg(),apiException.getCode()); }else{ onError("未知异常", ExceptionEngine.UN_KNOWN_ERROR); } if(!TextUtils.isEmpty(tag)){ RequestManagerIml.getInstance().remove(tag); } } @Override public void onComplete() { if(!RequestManagerIml.getInstance().isDispose(tag)){ RequestManagerIml.getInstance().cancle(tag); } } //回调错错误信息 public abstract void onError(String message, int code); public abstract void cancle(); //网络请求取消 public void canclend(){ if(!ThreadUtils.isMainThread()){ HttpGlobalConfig.getInsance().getHandler().post(new Runnable() { @Override public void run() { cancle(); } }); } } public void setTag(String tag) { this.tag = tag; } }
[ "2506969944@qq.com" ]
2506969944@qq.com
428f8610af76df602d217cd4f94133ea9adcadb4
f99c839924f6c17347c7dc6816792ff204daa703
/hibernate-tutorial/src/com/luv2code/hibernate/demo/CreateStudentDemo.java
3781ad833961867c7206785df4bc425767f06057
[]
no_license
JagadishNandeesh/springAndHibernate
240ce1249ff058803d6fc6f96f8d65356c546167
a3b1bb2087c10264627dc9c26577865018b91aa2
refs/heads/master
2020-12-29T09:54:35.134503
2020-03-16T23:52:25
2020-03-16T23:52:25
238,563,473
0
0
null
null
null
null
UTF-8
Java
false
false
1,030
java
package com.luv2code.hibernate.demo; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.luv2code.hibernate.demo.entity.Student; public class CreateStudentDemo { public static void main(String[] args) { SessionFactory factory = new Configuration() .configure("hibernate.cfg.xml") .addAnnotatedClass(Student.class) .buildSessionFactory(); Session session =factory.getCurrentSession(); try { Student tempStudent = new Student("paul","wall", "paul@luv2code.com"); session.beginTransaction(); session.save(tempStudent); session.getTransaction().commit(); System.out.println("done"); session = factory.getCurrentSession(); System.out.println(tempStudent.getId()); session.beginTransaction(); Student myStudent= session.get(Student.class, tempStudent.getId()); session.getTransaction().commit(); System.out.println(myStudent); } finally { factory.close(); } } }
[ "jagadishthunders@gmail.com" ]
jagadishthunders@gmail.com
74fe1e8c3787e2d50b6a69f9d13d9ed4ba7707e6
d704ec43f7a5a296b91f5de0023def92f013dcda
/core/src/main/java/org/elasticsearch/http/netty/NettyHttpServerTransport.java
fe8d6eaad1c35ecaedc05716a7ddc5ff5f30802c
[ "Apache-2.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
diegopacheco/elassandra
e4ede3085416750d4a71bcdf1ae7b77786b6cc36
d7f85d1768d5ca8e7928d640609dd5a777b2523c
refs/heads/master
2021-01-12T08:24:05.935475
2016-12-15T06:53:09
2016-12-15T06:53:09
76,563,249
0
1
Apache-2.0
2023-03-20T11:53:08
2016-12-15T13:46:19
Java
UTF-8
Java
false
false
26,489
java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.http.netty; import org.elasticsearch.common.Booleans; import com.carrotsearch.hppc.IntHashSet; import com.carrotsearch.hppc.IntSet; import org.elasticsearch.common.Strings; import org.elasticsearch.common.component.AbstractLifecycleComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.netty.NettyUtils; import org.elasticsearch.common.netty.OpenChannelsHandler; import org.elasticsearch.common.network.NetworkAddress; import org.elasticsearch.common.network.NetworkService; import org.elasticsearch.common.network.NetworkUtils; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.*; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.common.util.concurrent.EsExecutors; import org.elasticsearch.http.netty.pipelining.HttpPipeliningHandler; import org.elasticsearch.monitor.jvm.JvmInfo; import org.elasticsearch.http.BindHttpException; import org.elasticsearch.http.HttpInfo; import org.elasticsearch.http.HttpServerAdapter; import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.http.HttpStats; import org.elasticsearch.http.netty.cors.CorsConfig; import org.elasticsearch.http.netty.cors.CorsConfigBuilder; import org.elasticsearch.http.netty.cors.CorsHandler; import org.elasticsearch.http.netty.pipelining.HttpPipeliningHandler; import org.elasticsearch.monitor.jvm.JvmInfo; import org.elasticsearch.rest.RestChannel; import org.elasticsearch.rest.RestRequest; import org.elasticsearch.rest.support.RestUtils; import org.elasticsearch.transport.BindTransportException; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.*; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; import org.jboss.netty.handler.codec.http.HttpChunkAggregator; import org.jboss.netty.handler.codec.http.HttpContentCompressor; import org.jboss.netty.handler.codec.http.HttpMethod; import org.jboss.netty.handler.codec.http.HttpRequestDecoder; import org.jboss.netty.handler.timeout.ReadTimeoutException; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; import static org.elasticsearch.common.network.NetworkService.TcpSettings.*; import static org.elasticsearch.common.util.concurrent.EsExecutors.daemonThreadFactory; import static org.elasticsearch.common.network.NetworkService.TcpSettings.TCP_BLOCKING; import static org.elasticsearch.common.network.NetworkService.TcpSettings.TCP_KEEP_ALIVE; import static org.elasticsearch.common.network.NetworkService.TcpSettings.TCP_NO_DELAY; import static org.elasticsearch.common.network.NetworkService.TcpSettings.TCP_RECEIVE_BUFFER_SIZE; import static org.elasticsearch.common.network.NetworkService.TcpSettings.TCP_REUSE_ADDRESS; import static org.elasticsearch.common.network.NetworkService.TcpSettings.TCP_SEND_BUFFER_SIZE; import static org.elasticsearch.http.netty.cors.CorsHandler.ANY_ORIGIN; /** * */ public class NettyHttpServerTransport extends AbstractLifecycleComponent<HttpServerTransport> implements HttpServerTransport { static { NettyUtils.setup(); } public static final String SETTING_CORS_ENABLED = "http.cors.enabled"; public static final String SETTING_CORS_ALLOW_ORIGIN = "http.cors.allow-origin"; public static final String SETTING_CORS_MAX_AGE = "http.cors.max-age"; public static final String SETTING_CORS_ALLOW_METHODS = "http.cors.allow-methods"; public static final String SETTING_CORS_ALLOW_HEADERS = "http.cors.allow-headers"; public static final String SETTING_CORS_ALLOW_CREDENTIALS = "http.cors.allow-credentials"; public static final String SETTING_PIPELINING = "http.pipelining"; public static final String SETTING_PIPELINING_MAX_EVENTS = "http.pipelining.max_events"; public static final String SETTING_HTTP_COMPRESSION = "http.compression"; public static final String SETTING_HTTP_COMPRESSION_LEVEL = "http.compression_level"; public static final String SETTING_HTTP_DETAILED_ERRORS_ENABLED = "http.detailed_errors.enabled"; public static final boolean DEFAULT_SETTING_PIPELINING = true; public static final int DEFAULT_SETTING_PIPELINING_MAX_EVENTS = 10000; public static final String DEFAULT_PORT_RANGE = "9200-9300"; private static final String[] DEFAULT_CORS_METHODS = { "OPTIONS", "HEAD", "GET", "POST", "PUT", "DELETE" }; private static final String[] DEFAULT_CORS_HEADERS = { "X-Requested-With", "Content-Type", "Content-Length" }; private static final int DEFAULT_CORS_MAX_AGE = 1728000; protected final NetworkService networkService; protected final BigArrays bigArrays; protected final ByteSizeValue maxContentLength; protected final ByteSizeValue maxInitialLineLength; protected final ByteSizeValue maxHeaderSize; protected final ByteSizeValue maxChunkSize; protected final int workerCount; protected final boolean blockingServer; protected final boolean pipelining; protected final int pipeliningMaxEvents; protected final boolean compression; protected final int compressionLevel; protected final boolean resetCookies; protected final String port; protected final String bindHosts[]; protected final String publishHosts[]; protected final boolean detailedErrorsEnabled; protected final String tcpNoDelay; protected final String tcpKeepAlive; protected final boolean reuseAddress; protected final ByteSizeValue tcpSendBufferSize; protected final ByteSizeValue tcpReceiveBufferSize; protected final ReceiveBufferSizePredictorFactory receiveBufferSizePredictorFactory; protected final ByteSizeValue maxCumulationBufferCapacity; protected final int maxCompositeBufferComponents; protected volatile ServerBootstrap serverBootstrap; protected volatile BoundTransportAddress boundAddress; protected volatile List<Channel> serverChannels = new ArrayList<>(); // package private for testing OpenChannelsHandler serverOpenChannels; protected volatile HttpServerAdapter httpServerAdapter; private final CorsConfig corsConfig; @Inject public NettyHttpServerTransport(Settings settings, NetworkService networkService, BigArrays bigArrays) { super(settings); this.networkService = networkService; this.bigArrays = bigArrays; if (settings.getAsBoolean("netty.epollBugWorkaround", false)) { System.setProperty("org.jboss.netty.epollBugWorkaround", "true"); } ByteSizeValue maxContentLength = settings.getAsBytesSize("http.netty.max_content_length", settings.getAsBytesSize("http.max_content_length", new ByteSizeValue(100, ByteSizeUnit.MB))); this.maxChunkSize = settings.getAsBytesSize("http.netty.max_chunk_size", settings.getAsBytesSize("http.max_chunk_size", new ByteSizeValue(8, ByteSizeUnit.KB))); this.maxHeaderSize = settings.getAsBytesSize("http.netty.max_header_size", settings.getAsBytesSize("http.max_header_size", new ByteSizeValue(8, ByteSizeUnit.KB))); this.maxInitialLineLength = settings.getAsBytesSize("http.netty.max_initial_line_length", settings.getAsBytesSize("http.max_initial_line_length", new ByteSizeValue(4, ByteSizeUnit.KB))); // don't reset cookies by default, since I don't think we really need to // note, parsing cookies was fixed in netty 3.5.1 regarding stack allocation, but still, currently, we don't need cookies this.resetCookies = settings.getAsBoolean("http.netty.reset_cookies", settings.getAsBoolean("http.reset_cookies", false)); this.maxCumulationBufferCapacity = settings.getAsBytesSize("http.netty.max_cumulation_buffer_capacity", null); this.maxCompositeBufferComponents = settings.getAsInt("http.netty.max_composite_buffer_components", -1); this.workerCount = settings.getAsInt("http.netty.worker_count", EsExecutors.boundedNumberOfProcessors(settings) * 2); this.blockingServer = settings.getAsBoolean("http.netty.http.blocking_server", settings.getAsBoolean(TCP_BLOCKING_SERVER, settings.getAsBoolean(TCP_BLOCKING, false))); this.port = settings.get("http.netty.port", settings.get("http.port", DEFAULT_PORT_RANGE)); this.bindHosts = settings.getAsArray("http.netty.bind_host", settings.getAsArray("http.bind_host", settings.getAsArray("http.host", null))); this.publishHosts = settings.getAsArray("http.netty.publish_host", settings.getAsArray("http.publish_host", settings.getAsArray("http.host", null))); this.tcpNoDelay = settings.get("http.netty.tcp_no_delay", settings.get(TCP_NO_DELAY, "true")); this.tcpKeepAlive = settings.get("http.netty.tcp_keep_alive", settings.get(TCP_KEEP_ALIVE, "true")); this.reuseAddress = settings.getAsBoolean("http.netty.reuse_address", settings.getAsBoolean(TCP_REUSE_ADDRESS, NetworkUtils.defaultReuseAddress())); this.tcpSendBufferSize = settings.getAsBytesSize("http.netty.tcp_send_buffer_size", settings.getAsBytesSize(TCP_SEND_BUFFER_SIZE, TCP_DEFAULT_SEND_BUFFER_SIZE)); this.tcpReceiveBufferSize = settings.getAsBytesSize("http.netty.tcp_receive_buffer_size", settings.getAsBytesSize(TCP_RECEIVE_BUFFER_SIZE, TCP_DEFAULT_RECEIVE_BUFFER_SIZE)); this.detailedErrorsEnabled = settings.getAsBoolean(SETTING_HTTP_DETAILED_ERRORS_ENABLED, true); long defaultReceiverPredictor = 512 * 1024; if (JvmInfo.jvmInfo().getMem().getDirectMemoryMax().bytes() > 0) { // we can guess a better default... long l = (long) ((0.3 * JvmInfo.jvmInfo().getMem().getDirectMemoryMax().bytes()) / workerCount); defaultReceiverPredictor = Math.min(defaultReceiverPredictor, Math.max(l, 64 * 1024)); } // See AdaptiveReceiveBufferSizePredictor#DEFAULT_XXX for default values in netty..., we can use higher ones for us, even fixed one ByteSizeValue receivePredictorMin = settings.getAsBytesSize("http.netty.receive_predictor_min", settings.getAsBytesSize("http.netty.receive_predictor_size", new ByteSizeValue(defaultReceiverPredictor))); ByteSizeValue receivePredictorMax = settings.getAsBytesSize("http.netty.receive_predictor_max", settings.getAsBytesSize("http.netty.receive_predictor_size", new ByteSizeValue(defaultReceiverPredictor))); if (receivePredictorMax.bytes() == receivePredictorMin.bytes()) { receiveBufferSizePredictorFactory = new FixedReceiveBufferSizePredictorFactory((int) receivePredictorMax.bytes()); } else { receiveBufferSizePredictorFactory = new AdaptiveReceiveBufferSizePredictorFactory((int) receivePredictorMin.bytes(), (int) receivePredictorMin.bytes(), (int) receivePredictorMax.bytes()); } this.compression = settings.getAsBoolean(SETTING_HTTP_COMPRESSION, false); this.compressionLevel = settings.getAsInt(SETTING_HTTP_COMPRESSION_LEVEL, 6); this.pipelining = settings.getAsBoolean(SETTING_PIPELINING, DEFAULT_SETTING_PIPELINING); this.pipeliningMaxEvents = settings.getAsInt(SETTING_PIPELINING_MAX_EVENTS, DEFAULT_SETTING_PIPELINING_MAX_EVENTS); this.corsConfig = buildCorsConfig(settings); // validate max content length if (maxContentLength.bytes() > Integer.MAX_VALUE) { logger.warn("maxContentLength[" + maxContentLength + "] set to high value, resetting it to [100mb]"); maxContentLength = new ByteSizeValue(100, ByteSizeUnit.MB); } this.maxContentLength = maxContentLength; logger.debug("using max_chunk_size[{}], max_header_size[{}], max_initial_line_length[{}], max_content_length[{}], receive_predictor[{}->{}], pipelining[{}], pipelining_max_events[{}]", maxChunkSize, maxHeaderSize, maxInitialLineLength, this.maxContentLength, receivePredictorMin, receivePredictorMax, pipelining, pipeliningMaxEvents); } public Settings settings() { return this.settings; } @Override public void httpServerAdapter(HttpServerAdapter httpServerAdapter) { this.httpServerAdapter = httpServerAdapter; } @Override protected void doStart() { this.serverOpenChannels = new OpenChannelsHandler(logger); if (blockingServer) { serverBootstrap = new ServerBootstrap(new OioServerSocketChannelFactory( Executors.newCachedThreadPool(daemonThreadFactory(settings, "http_server_boss")), Executors.newCachedThreadPool(daemonThreadFactory(settings, "http_server_worker")) )); } else { serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory( Executors.newCachedThreadPool(daemonThreadFactory(settings, "http_server_boss")), Executors.newCachedThreadPool(daemonThreadFactory(settings, "http_server_worker")), workerCount)); } serverBootstrap.setPipelineFactory(configureServerChannelPipelineFactory()); if (!"default".equals(tcpNoDelay)) { serverBootstrap.setOption("child.tcpNoDelay", Booleans.parseBoolean(tcpNoDelay, null)); } if (!"default".equals(tcpKeepAlive)) { serverBootstrap.setOption("child.keepAlive", Booleans.parseBoolean(tcpKeepAlive, null)); } if (tcpSendBufferSize != null && tcpSendBufferSize.bytes() > 0) { serverBootstrap.setOption("child.sendBufferSize", tcpSendBufferSize.bytes()); } if (tcpReceiveBufferSize != null && tcpReceiveBufferSize.bytes() > 0) { serverBootstrap.setOption("child.receiveBufferSize", tcpReceiveBufferSize.bytes()); } serverBootstrap.setOption("receiveBufferSizePredictorFactory", receiveBufferSizePredictorFactory); serverBootstrap.setOption("child.receiveBufferSizePredictorFactory", receiveBufferSizePredictorFactory); serverBootstrap.setOption("reuseAddress", reuseAddress); serverBootstrap.setOption("child.reuseAddress", reuseAddress); this.boundAddress = createBoundHttpAddress(); } private BoundTransportAddress createBoundHttpAddress() { // Bind and start to accept incoming connections. InetAddress hostAddresses[]; try { hostAddresses = networkService.resolveBindHostAddresses(bindHosts); } catch (IOException e) { throw new BindHttpException("Failed to resolve host [" + Arrays.toString(bindHosts) + "]", e); } List<InetSocketTransportAddress> boundAddresses = new ArrayList<>(hostAddresses.length); for (InetAddress address : hostAddresses) { boundAddresses.add(bindAddress(address)); } final InetAddress publishInetAddress; try { publishInetAddress = networkService.resolvePublishHostAddresses(publishHosts); } catch (Exception e) { throw new BindTransportException("Failed to resolve publish address", e); } final int publishPort = resolvePublishPort(settings, boundAddresses, publishInetAddress); final InetSocketAddress publishAddress = new InetSocketAddress(publishInetAddress, publishPort); return new BoundTransportAddress(boundAddresses.toArray(new TransportAddress[boundAddresses.size()]), new InetSocketTransportAddress(publishAddress)); } // package private for tests static int resolvePublishPort(Settings settings, List<InetSocketTransportAddress> boundAddresses, InetAddress publishInetAddress) { int publishPort = settings.getAsInt("http.netty.publish_port", settings.getAsInt("http.publish_port", -1)); if (publishPort < 0) { for (InetSocketTransportAddress boundAddress : boundAddresses) { InetAddress boundInetAddress = boundAddress.address().getAddress(); if (boundInetAddress.isAnyLocalAddress() || boundInetAddress.equals(publishInetAddress)) { publishPort = boundAddress.getPort(); break; } } } // if no matching boundAddress found, check if there is a unique port for all bound addresses if (publishPort < 0) { final IntSet ports = new IntHashSet(); for (InetSocketTransportAddress boundAddress : boundAddresses) { ports.add(boundAddress.getPort()); } if (ports.size() == 1) { publishPort = ports.iterator().next().value; } } if (publishPort < 0) { throw new BindHttpException("Failed to auto-resolve http publish port, multiple bound addresses " + boundAddresses + " with distinct ports and none of them matched the publish address (" + publishInetAddress + "). " + "Please specify a unique port by setting http.port or http.publish_port"); } return publishPort; } private CorsConfig buildCorsConfig(Settings settings) { if (settings.getAsBoolean(SETTING_CORS_ENABLED, false) == false) { return CorsConfigBuilder.forOrigins().disable().build(); } String origin = settings.get(SETTING_CORS_ALLOW_ORIGIN); final CorsConfigBuilder builder; if (Strings.isNullOrEmpty(origin)) { builder = CorsConfigBuilder.forOrigins(); } else if (origin.equals(ANY_ORIGIN)) { builder = CorsConfigBuilder.forAnyOrigin(); } else { Pattern p = RestUtils.checkCorsSettingForRegex(origin); if (p == null) { builder = CorsConfigBuilder.forOrigins(RestUtils.corsSettingAsArray(origin)); } else { builder = CorsConfigBuilder.forPattern(p); } } if (settings.getAsBoolean(SETTING_CORS_ALLOW_CREDENTIALS, false)) { builder.allowCredentials(); } String[] strMethods = settings.getAsArray(SETTING_CORS_ALLOW_METHODS, DEFAULT_CORS_METHODS); HttpMethod[] methods = new HttpMethod[strMethods.length]; for (int i = 0; i < methods.length; i++) { methods[i] = HttpMethod.valueOf(strMethods[i]); } return builder.allowedRequestMethods(methods) .maxAge(settings.getAsInt(SETTING_CORS_MAX_AGE, DEFAULT_CORS_MAX_AGE)) .allowedRequestHeaders(settings.getAsArray(SETTING_CORS_ALLOW_HEADERS, DEFAULT_CORS_HEADERS)) .shortCircuit() .build(); } private InetSocketTransportAddress bindAddress(final InetAddress hostAddress) { PortsRange portsRange = new PortsRange(port); final AtomicReference<Exception> lastException = new AtomicReference<>(); final AtomicReference<InetSocketAddress> boundSocket = new AtomicReference<>(); boolean success = portsRange.iterate(new PortsRange.PortCallback() { @Override public boolean onPortNumber(int portNumber) { try { synchronized (serverChannels) { Channel channel = serverBootstrap.bind(new InetSocketAddress(hostAddress, portNumber)); serverChannels.add(channel); boundSocket.set((InetSocketAddress) channel.getLocalAddress()); } } catch (Exception e) { lastException.set(e); return false; } return true; } }); if (!success) { throw new BindHttpException("Failed to bind to [" + port + "]", lastException.get()); } if (logger.isDebugEnabled()) { logger.debug("Bound http to address {{}}", NetworkAddress.format(boundSocket.get())); } return new InetSocketTransportAddress(boundSocket.get()); } @Override protected void doStop() { synchronized (serverChannels) { if (serverChannels != null) { for (Channel channel : serverChannels) { channel.close().awaitUninterruptibly(); } serverChannels = null; } } if (serverOpenChannels != null) { serverOpenChannels.close(); serverOpenChannels = null; } if (serverBootstrap != null) { serverBootstrap.releaseExternalResources(); serverBootstrap = null; } } @Override protected void doClose() { } @Override public BoundTransportAddress boundAddress() { return this.boundAddress; } @Override public HttpInfo info() { BoundTransportAddress boundTransportAddress = boundAddress(); if (boundTransportAddress == null) { return null; } return new HttpInfo(boundTransportAddress, maxContentLength.bytes()); } @Override public HttpStats stats() { OpenChannelsHandler channels = serverOpenChannels; return new HttpStats(channels == null ? 0 : channels.numberOfOpenChannels(), channels == null ? 0 : channels.totalChannels()); } public CorsConfig getCorsConfig() { return corsConfig; } protected void dispatchRequest(RestRequest request, RestChannel channel) { httpServerAdapter.dispatchRequest(request, channel); } protected void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (e.getCause() instanceof ReadTimeoutException) { if (logger.isTraceEnabled()) { logger.trace("Connection timeout [{}]", ctx.getChannel().getRemoteAddress()); } ctx.getChannel().close(); } else { if (!lifecycle.started()) { // ignore return; } if (!NetworkExceptionHelper.isCloseConnectionException(e.getCause())) { logger.warn("Caught exception while handling client http traffic, closing connection {}", e.getCause(), ctx.getChannel()); ctx.getChannel().close(); } else { logger.debug("Caught exception while handling client http traffic, closing connection {}", e.getCause(), ctx.getChannel()); ctx.getChannel().close(); } } } public ChannelPipelineFactory configureServerChannelPipelineFactory() { return new HttpChannelPipelineFactory(this, detailedErrorsEnabled); } protected static class HttpChannelPipelineFactory implements ChannelPipelineFactory { protected final NettyHttpServerTransport transport; protected final HttpRequestHandler requestHandler; public HttpChannelPipelineFactory(NettyHttpServerTransport transport, boolean detailedErrorsEnabled) { this.transport = transport; this.requestHandler = new HttpRequestHandler(transport, detailedErrorsEnabled); } @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("openChannels", transport.serverOpenChannels); HttpRequestDecoder requestDecoder = new HttpRequestDecoder( (int) transport.maxInitialLineLength.bytes(), (int) transport.maxHeaderSize.bytes(), (int) transport.maxChunkSize.bytes() ); if (transport.maxCumulationBufferCapacity != null) { if (transport.maxCumulationBufferCapacity.bytes() > Integer.MAX_VALUE) { requestDecoder.setMaxCumulationBufferCapacity(Integer.MAX_VALUE); } else { requestDecoder.setMaxCumulationBufferCapacity((int) transport.maxCumulationBufferCapacity.bytes()); } } if (transport.maxCompositeBufferComponents != -1) { requestDecoder.setMaxCumulationBufferComponents(transport.maxCompositeBufferComponents); } pipeline.addLast("decoder", requestDecoder); pipeline.addLast("decoder_compress", new ESHttpContentDecompressor(transport.compression)); HttpChunkAggregator httpChunkAggregator = new HttpChunkAggregator((int) transport.maxContentLength.bytes()); if (transport.maxCompositeBufferComponents != -1) { httpChunkAggregator.setMaxCumulationBufferComponents(transport.maxCompositeBufferComponents); } pipeline.addLast("aggregator", httpChunkAggregator); pipeline.addLast("encoder", new ESHttpResponseEncoder()); if (transport.compression) { pipeline.addLast("encoder_compress", new HttpContentCompressor(transport.compressionLevel)); } if (transport.settings().getAsBoolean(SETTING_CORS_ENABLED, false)) { pipeline.addLast("cors", new CorsHandler(transport.getCorsConfig())); } if (transport.pipelining) { pipeline.addLast("pipelining", new HttpPipeliningHandler(transport.pipeliningMaxEvents)); } pipeline.addLast("handler", requestHandler); return pipeline; } } }
[ "vroyer@vroyer.org" ]
vroyer@vroyer.org
114e3f36c750fbe7b731d5e7b91feeb26cc6b21b
4b1b9cccae125bf8565bd1c7524a790da534247b
/src/main/java/io/swagger/model/DTO/ExceptionDTO.java
540bc5b0e63aa3748259ff92b425e4163b3b1576
[]
no_license
salahb10/ProjectCodegen
11a87a645ef869bf521b5021d9e2a1a96a1f911d
368f77105f886f6833b2a6ca7e46338e3d3b932b
refs/heads/main
2023-06-08T01:46:59.607529
2021-06-27T21:45:35
2021-06-27T21:45:35
null
0
0
null
null
null
null
UTF-8
Java
false
false
318
java
package io.swagger.model.DTO; public class ExceptionDTO { private String message; public ExceptionDTO(String message) { this.message = message; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
[ "chungheyg@gmail.com" ]
chungheyg@gmail.com
41df1637da10627f52a423f3f4801e9bc0c820da
4a5b8d37d70aff90d9c3e4d6d53239c12726f88e
/lib-okhttp/src/main/java/cn/ollyice/library/okhttp/MultipartBody.java
d2d5ff3a7928f49862cddfe50be05253749da148
[]
no_license
paqxyz/AndGameDemo
29dfad61e371cf6db833107d903acffb8502e647
53271818ffff94564ec4e3337ebf4af13956d5de
refs/heads/master
2020-03-21T04:29:11.037764
2018-06-20T06:06:50
2018-06-20T06:06:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
11,047
java
/* * Copyright (C) 2014 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.ollyice.library.okhttp; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.annotation.Nullable; import cn.ollyice.library.okhttp.internal.Util; import cn.ollyice.library.okio.Buffer; import cn.ollyice.library.okio.BufferedSink; import cn.ollyice.library.okio.ByteString; /** An <a href="http://www.ietf.org/rfc/rfc2387.txt">RFC 2387</a>-compliant request body. */ public final class MultipartBody extends RequestBody { /** * The "mixed" subtype of "multipart" is intended for use when the body parts are independent and * need to be bundled in a particular order. Any "multipart" subtypes that an implementation does * not recognize must be treated as being of subtype "mixed". */ public static final MediaType MIXED = MediaType.parse("multipart/mixed"); /** * The "multipart/alternative" type is syntactically identical to "multipart/mixed", but the * semantics are different. In particular, each of the body parts is an "alternative" version of * the same information. */ public static final MediaType ALTERNATIVE = MediaType.parse("multipart/alternative"); /** * This type is syntactically identical to "multipart/mixed", but the semantics are different. In * particular, in a digest, the default {@code Content-Type} value for a body part is changed from * "text/plain" to "message/rfc822". */ public static final MediaType DIGEST = MediaType.parse("multipart/digest"); /** * This type is syntactically identical to "multipart/mixed", but the semantics are different. In * particular, in a parallel entity, the order of body parts is not significant. */ public static final MediaType PARALLEL = MediaType.parse("multipart/parallel"); /** * The media-type multipart/form-data follows the rules of all multipart MIME data streams as * outlined in RFC 2046. In forms, there are a series of fields to be supplied by the user who * fills out the form. Each field has a name. Within a given form, the names are unique. */ public static final MediaType FORM = MediaType.parse("multipart/form-data"); private static final byte[] COLONSPACE = {':', ' '}; private static final byte[] CRLF = {'\r', '\n'}; private static final byte[] DASHDASH = {'-', '-'}; private final ByteString boundary; private final MediaType originalType; private final MediaType contentType; private final List<Part> parts; private long contentLength = -1L; MultipartBody(ByteString boundary, MediaType type, List<Part> parts) { this.boundary = boundary; this.originalType = type; this.contentType = MediaType.parse(type + "; boundary=" + boundary.utf8()); this.parts = Util.immutableList(parts); } public MediaType type() { return originalType; } public String boundary() { return boundary.utf8(); } /** The number of parts in this multipart body. */ public int size() { return parts.size(); } public List<Part> parts() { return parts; } public Part part(int index) { return parts.get(index); } /** A combination of {@link #type()} and {@link #boundary()}. */ @Override public MediaType contentType() { return contentType; } @Override public long contentLength() throws IOException { long result = contentLength; if (result != -1L) return result; return contentLength = writeOrCountBytes(null, true); } @Override public void writeTo(BufferedSink sink) throws IOException { writeOrCountBytes(sink, false); } /** * Either writes this request to {@code sink} or measures its content length. We have one method * do double-duty to make sure the counting and content are consistent, particularly when it comes * to awkward operations like measuring the encoded length of header strings, or the * length-in-digits of an encoded integer. */ private long writeOrCountBytes( @Nullable BufferedSink sink, boolean countBytes) throws IOException { long byteCount = 0L; Buffer byteCountBuffer = null; if (countBytes) { sink = byteCountBuffer = new Buffer(); } for (int p = 0, partCount = parts.size(); p < partCount; p++) { Part part = parts.get(p); Headers headers = part.headers; RequestBody body = part.body; sink.write(DASHDASH); sink.write(boundary); sink.write(CRLF); if (headers != null) { for (int h = 0, headerCount = headers.size(); h < headerCount; h++) { sink.writeUtf8(headers.name(h)) .write(COLONSPACE) .writeUtf8(headers.value(h)) .write(CRLF); } } MediaType contentType = body.contentType(); if (contentType != null) { sink.writeUtf8("Content-Type: ") .writeUtf8(contentType.toString()) .write(CRLF); } long contentLength = body.contentLength(); if (contentLength != -1) { sink.writeUtf8("Content-Length: ") .writeDecimalLong(contentLength) .write(CRLF); } else if (countBytes) { // We can't measure the body's size without the sizes of its components. byteCountBuffer.clear(); return -1L; } sink.write(CRLF); if (countBytes) { byteCount += contentLength; } else { body.writeTo(sink); } sink.write(CRLF); } sink.write(DASHDASH); sink.write(boundary); sink.write(DASHDASH); sink.write(CRLF); if (countBytes) { byteCount += byteCountBuffer.size(); byteCountBuffer.clear(); } return byteCount; } /** * Appends a quoted-string to a StringBuilder. * * <p>RFC 2388 is rather vague about how one should escape special characters in form-data * parameters, and as it turns out Firefox and Chrome actually do rather different things, and * both say in their comments that they're not really sure what the right approach is. We go with * Chrome's behavior (which also experimentally seems to match what IE does), but if you actually * want to have a good chance of things working, please avoid double-quotes, newlines, percent * signs, and the like in your field names. */ static StringBuilder appendQuotedString(StringBuilder target, String key) { target.append('"'); for (int i = 0, len = key.length(); i < len; i++) { char ch = key.charAt(i); switch (ch) { case '\n': target.append("%0A"); break; case '\r': target.append("%0D"); break; case '"': target.append("%22"); break; default: target.append(ch); break; } } target.append('"'); return target; } public static final class Part { public static Part create(RequestBody body) { return create(null, body); } public static Part create(@Nullable Headers headers, RequestBody body) { if (body == null) { throw new NullPointerException("body == null"); } if (headers != null && headers.get("Content-Type") != null) { throw new IllegalArgumentException("Unexpected header: Content-Type"); } if (headers != null && headers.get("Content-Length") != null) { throw new IllegalArgumentException("Unexpected header: Content-Length"); } return new Part(headers, body); } public static Part createFormData(String name, String value) { return createFormData(name, null, RequestBody.create(null, value)); } public static Part createFormData(String name, @Nullable String filename, RequestBody body) { if (name == null) { throw new NullPointerException("name == null"); } StringBuilder disposition = new StringBuilder("form-data; name="); appendQuotedString(disposition, name); if (filename != null) { disposition.append("; filename="); appendQuotedString(disposition, filename); } return create(Headers.of("Content-Disposition", disposition.toString()), body); } final @Nullable Headers headers; final RequestBody body; private Part(@Nullable Headers headers, RequestBody body) { this.headers = headers; this.body = body; } public @Nullable Headers headers() { return headers; } public RequestBody body() { return body; } } public static final class Builder { private final ByteString boundary; private MediaType type = MIXED; private final List<Part> parts = new ArrayList<>(); public Builder() { this(UUID.randomUUID().toString()); } public Builder(String boundary) { this.boundary = ByteString.encodeUtf8(boundary); } /** * Set the MIME type. Expected values for {@code type} are {@link #MIXED} (the default), {@link * #ALTERNATIVE}, {@link #DIGEST}, {@link #PARALLEL} and {@link #FORM}. */ public Builder setType(MediaType type) { if (type == null) { throw new NullPointerException("type == null"); } if (!type.type().equals("multipart")) { throw new IllegalArgumentException("multipart != " + type); } this.type = type; return this; } /** Add a part to the body. */ public Builder addPart(RequestBody body) { return addPart(Part.create(body)); } /** Add a part to the body. */ public Builder addPart(@Nullable Headers headers, RequestBody body) { return addPart(Part.create(headers, body)); } /** Add a form data part to the body. */ public Builder addFormDataPart(String name, String value) { return addPart(Part.createFormData(name, value)); } /** Add a form data part to the body. */ public Builder addFormDataPart(String name, @Nullable String filename, RequestBody body) { return addPart(Part.createFormData(name, filename, body)); } /** Add a part to the body. */ public Builder addPart(Part part) { if (part == null) throw new NullPointerException("part == null"); parts.add(part); return this; } /** Assemble the specified parts into a request body. */ public MultipartBody build() { if (parts.isEmpty()) { throw new IllegalStateException("Multipart body must have at least one part."); } return new MultipartBody(boundary, type, parts); } } }
[ "289776839@qq.com" ]
289776839@qq.com
6ea3aea4e2d744e1e9e2e45279b2554242345dd1
465e2baf3d80f488a978cb935ac61713e2cb9475
/src/main/java/io/suriya/ProductController.java
8aba7a6b68b1ca000c000c3f8f138da8cbbc1512
[]
no_license
kartsuri89/springboot-interceptor
f14c01c48d4138100e6312f6a0a410890db6c53b
34043602e0ecdafeb7ad02fb4779f909b1095e3b
refs/heads/master
2023-07-27T20:38:35.767867
2021-09-05T20:20:44
2021-09-05T20:20:44
403,403,161
0
0
null
null
null
null
UTF-8
Java
false
false
354
java
package io.suriya; import java.util.Arrays; import java.util.List; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class ProductController { @GetMapping("/cars") public List<String> getCarNames(){ return Arrays.asList("Ferrari","BMW", "Benz"); } }
[ "kartsuri89@gmail.com" ]
kartsuri89@gmail.com
b7a0ec501163801a3b9961beec44fb7b2d3b66df
b6a32e5c8b8c2b83b3a7d4dbff2fed58da72a94d
/practice-netty/src/main/java/com/zbt/netty/protocol/discard/TimeServer.java
dac240fd76de9b2b5067c49876605ee5e977f87b
[]
no_license
zhangbaitong/practice
aec0e35cad8e7af7606a95fb23a2a33fc3ea0ccd
85b033b2197c0786ec3873cde645684d71a4d5ed
refs/heads/master
2022-12-23T11:50:03.324454
2017-01-07T07:58:26
2017-01-07T07:58:26
14,135,404
2
1
null
2022-12-16T03:39:40
2013-11-05T07:56:39
JavaScript
UTF-8
Java
false
false
1,539
java
package com.zbt.netty.protocol.discard; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.group.ChannelGroupFuture; import org.jboss.netty.channel.group.DefaultChannelGroup; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; public class TimeServer { //ChannelGroup使用 static final ChannelGroup allChannels = new DefaultChannelGroup("time-server"); /** * @param args */ public static void main(String[] args) { ChannelFactory factory = new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ServerBootstrap bootstrap = new ServerBootstrap(factory); TimeServerHandler handler = new TimeServerHandler(); //原始的 // ChannelPipeline pipeline = bootstrap.getPipeline(); // pipeline.addLast("handle", handler); //使用unittime的 bootstrap.setPipelineFactory(new TimeServerPipelineFactory()); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); Channel channel = bootstrap.bind(new InetSocketAddress(8080)); //ChannelGroup使用 allChannels.add(channel); //waitForShutdownCommand(); ChannelGroupFuture future = allChannels.close(); future.awaitUninterruptibly(); factory.releaseExternalResources(); } }
[ "zhangbaitong@gmail.com" ]
zhangbaitong@gmail.com
f03faa39b8d76a390313d4a012b5b5b49129eadc
68a19507f18acff18aa4fa67d6611f5b8ac8913c
/lxs/lxs-api/src/main/java/lxs/api/action/order/line/PayBargainMoneyAction.java
3559b40debcf5aa2d609bc9ee8d4d49a0150e804
[]
no_license
ksksks2222/pl-workspace
cf0d0be2dfeaa62c0d4d5437f85401f60be0eadd
6146e3e3c2384c91cac459d25b27ffeb4f970dcd
refs/heads/master
2021-09-13T08:59:17.177105
2018-04-27T09:46:42
2018-04-27T09:46:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,235
java
package lxs.api.action.order.line; import hg.log.util.HgLogger; import lxs.api.action.LxsAction; import lxs.api.base.ApiRequest; import lxs.api.base.ApiResponse; import lxs.api.v1.request.command.order.line.PayBargainMoneyCommand; import lxs.api.v1.response.order.line.PayBargainMoneyResponse; import lxs.app.service.line.LineOrderLocalService; import lxs.pojo.command.line.AlipayCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSON; /** * * @类功能说明:为了满足支付定金为0元情况 * @类修改者: * @修改日期:2015年6月5日下午12:06:24 * @修改说明: * @公司名称:浙江票量科技有限公司 * @作者:cangs * @创建时间:2015年6月5日下午12:06:24 */ @Component("PayBargainMoneyAction") public class PayBargainMoneyAction implements LxsAction{ @Autowired private LineOrderLocalService lineOrderLocalService; @Override public String execute(ApiRequest apiRequest) { HgLogger.getInstance().info("lxs_dev", "【PayBargainMoneyAction】"+"进入action"); PayBargainMoneyCommand payBargainMoneyCommand= JSON.parseObject(apiRequest.getBody().getPayload(), PayBargainMoneyCommand.class); AlipayCommand alipayCommand = new AlipayCommand(); alipayCommand.setDealerOrderNo(payBargainMoneyCommand.getDealerOrderNo()); //付款零元 alipayCommand.setPrice(0.0); alipayCommand.setRequestType(AlipayCommand.LOCAL); HgLogger.getInstance().info("lxs_dev", "【PayBargainMoneyAction】"+"开始修改状态(APP内部支付0元)"); lineOrderLocalService.payLineOrder(alipayCommand); HgLogger.getInstance().info("lxs_dev", "【PayBargainMoneyAction】"+"完成修改状态(APP内部支付0元)"); PayBargainMoneyResponse payBargainMoneyResponse = new PayBargainMoneyResponse(); payBargainMoneyResponse.setResult(ApiResponse.RESULT_CODE_OK); payBargainMoneyResponse.setMessage("修改状态成功"); HgLogger.getInstance().info("lxs_dev", "【PayBargainMoneyAction】"+"查询线路结果"+JSON.toJSONString(payBargainMoneyResponse)); return JSON.toJSONString(payBargainMoneyResponse); } }
[ "cangsong6908@gmail.com" ]
cangsong6908@gmail.com
cbbc068c6e88f132d6e3c6636d63ef83c4862fc6
4402f9b2d6f89e39ebea103895837aac128d0081
/app/src/main/java/io/github/buniaowanfeng/view/INotification.java
0e9c38edb0ba8138dfa56c3c0978f234d7eecbae
[ "Apache-2.0" ]
permissive
erzhiqianyi/yitian
0ccc0490863adb5b233ff3418249d1cf3d790aee
dcbb405ea28c3e05ea0e18897533060a1951c137
refs/heads/master
2022-07-19T06:43:15.091199
2019-03-02T04:04:51
2019-03-02T04:04:51
173,125,949
2
0
Apache-2.0
2022-07-01T22:16:30
2019-02-28T14:23:44
Python
UTF-8
Java
false
false
214
java
package io.github.buniaowanfeng.view; import io.github.buniaowanfeng.data.DailyInfo; /** * Created by caofeng on 16-7-15. */ public interface INotification { void updateNotification(DailyInfo dailyInfo); }
[ "github@caofeng.me" ]
github@caofeng.me
05e7913fc781340e64561756b95e35ab985e60ea
58326bd900bad94a8d9c1368a2f69e300ff5db5b
/api/api/src/main/java/com/orbix/api/models/SubClass.java
fb7b33c3bb92c018519af953b6388cd46b1abaf7
[]
no_license
godfreydesidery/Orbix-Master
7cce868df64c78c41e945241287b2b60c56ba59e
a4a8d8359af9b00e8286a46d7ef5a49296a58b70
refs/heads/master
2023-08-28T11:43:55.364166
2021-11-06T12:38:58
2021-11-06T12:38:58
388,428,877
0
1
null
null
null
null
UTF-8
Java
false
false
2,177
java
package com.orbix.api.models; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.validation.constraints.NotBlank; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.stereotype.Component; /** * @author GODFREY * */ @Entity @Component @Table(name = "sub_classes") @EntityListeners(AuditingEntityListener.class) public class SubClass { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotBlank @Column(unique = true) private String code; @NotBlank @Column(unique = true) private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Clas getClas() { return clas; } public void setClas(Clas clas) { this.clas = clas; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } @ManyToOne(targetEntity = Clas.class, fetch = FetchType.EAGER, optional = true) @JoinColumn(name = "class_id", nullable = true , updatable = true) @OnDelete(action = OnDeleteAction.NO_ACTION) @Autowired @Embedded private Clas clas; @ManyToOne(targetEntity = Department.class, fetch = FetchType.EAGER, optional = true) @JoinColumn(name = "department_id", nullable = true , updatable = true) @OnDelete(action = OnDeleteAction.NO_ACTION) @Autowired @Embedded private Department department; }
[ "desideryg@gmail.com" ]
desideryg@gmail.com
02e95d3f402652e26ddf3043e8c25168dd76d11b
91055c6cbe2b4b38e6a8ded88a28788fad800b52
/src/CH5/ArraysMethodDemo2.java
74c6d6be0b820deaaee4d18768fd38d1e0e4aec7
[]
no_license
guanchenchen/JavaSe
17497319176df72a0b6c0b6efd598d564bb44c72
e1b8ef422e9763826aa9c83bc4fd0fcd65a221c0
refs/heads/master
2020-07-09T07:31:34.511975
2019-08-23T04:41:28
2019-08-23T04:41:28
203,916,141
1
0
null
null
null
null
UTF-8
Java
false
false
475
java
package CH5; import java.util.Arrays; public class ArraysMethodDemo2 { public static void main(String[] args) { int[] arr1 = new int[10]; int[] arr2 = new int[10]; int[] arr3 = new int[10]; System.out.print("arr1: "); for (int i = 0; i < arr1.length; i++) { System.out.print(arr1[i] + " "); } System.out.println("\narr1 = arr2 ? " + Arrays.equals(arr1, arr2)); System.out.println("arr1 = arr3 ? " + Arrays.equals(arr1, arr3)); } }
[ "37575346+guanchenchen@users.noreply.github.com" ]
37575346+guanchenchen@users.noreply.github.com
1754c17c2d851f805a83bc4abcea76f21852c899
f86e34fe5640c0070dc1f52d6f0c472a6e0d55af
/2.JavaCore/src/com/javarush/task/task20/task2023/Solution.java
c6ac69b419450ff64052adfc49c138f1e0fbc785
[]
no_license
Darkger/JavaRushTasks
24beda54dc492423fdce2ce0233c5760653c0476
333d2e9d2b89839e299d02084d1f2502819eac7f
refs/heads/master
2021-05-08T18:59:41.507621
2018-01-30T14:11:02
2018-01-30T14:11:02
119,538,997
0
0
null
null
null
null
UTF-8
Java
false
false
990
java
package com.javarush.task.task20.task2023; /* Делаем правильный вывод */ public class Solution { public static void main(String[] s) { A a = new C(); a.method2(); } public static class A { private void method1() { System.out.println("A class, method1"); } public void method2() { System.out.println("A class, method2"); method1(); } } public static class B extends A { public void method1() { super.method2(); System.out.println("B class, method1"); } public void method2() { System.out.println("B class, method2"); } } public static class C extends B { public void method1() { System.out.println("C class, method1"); } public void method2() { System.out.println("C class, method2"); super.method1(); } } }
[ "borninger@yandex.ru" ]
borninger@yandex.ru
c52e23fd4617a8b5ae69de206e718ad1fe814b9f
63d568dd1e5fd1552390c155e1fc99aa4344c597
/TestApplication/src/main/java/com/mycompany/testapplication/entity/service/LoginService.java
59ffa0ff2f2766c2d9b48deb6f57772ef7b7d277
[]
no_license
InnokentiyA/MyWebApplication
e254af908c0fe221a6dd1058f672851e38ee265f
72c09e92514e751d436294ba194cd7b90062d7ff
refs/heads/master
2021-08-29T19:43:34.373455
2017-12-14T20:15:28
2017-12-14T20:15:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
746
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.testapplication.entity.service; import com.mycompany.testapplication.entity.User; import com.mycompany.testapplication.entity.business.BusinessFacade; /** * * @author user */ public class LoginService { public String doLogin(String username, String password) { System.out.println("LOGIN SERVICE!!!!! " + username + ", " + password); User user = BusinessFacade.getUser(username, password); if (user != null) { return "SUCCESS"; } else { return "FAILURE"; } } }
[ "innatihun2265@gmail.com" ]
innatihun2265@gmail.com
2c6e9fb6999ef505e8e4e1b38a9d8700bb9a86b4
4c9d447c51b89912c6484569120c4eac79a79413
/src/main/java/agent/transformer/config/ClassDef.java
cf124b8589cfd3f6729d8c64ab6e05f138f45b6c
[]
no_license
pamtrak06/class-agent
53e2cb21f1a8622efd6dcabb45c31f1cf00a63b3
e35127fd02a614425cba2530252bccf6bf17c4a9
refs/heads/master
2020-06-06T16:12:37.546764
2014-12-14T17:52:28
2014-12-14T17:52:28
20,355,547
1
0
null
null
null
null
UTF-8
Java
false
false
1,348
java
package agent.transformer.config; import java.util.ArrayList; import java.util.List; public class ClassDef { private String classForName; private boolean defaultConstructor; private List<MethodDef> methodDefs = new ArrayList<MethodDef>(); private List<FieldDef> fieldDefs = new ArrayList<FieldDef>(); public ClassDef() { super(); } public ClassDef(String classForName, boolean defaultConstructor) { super(); this.classForName = classForName; this.defaultConstructor = defaultConstructor; } public String getClassForName() { return classForName; } public void setClassForName(String classForName) { this.classForName = classForName; } public List<MethodDef> getMethodDefs() { return methodDefs; } public void setMethodDefs(List<MethodDef> methodDefs) { this.methodDefs = methodDefs; } public List<FieldDef> getFieldDefs() { return fieldDefs; } public void setFieldDefs(List<FieldDef> fieldDefs) { this.fieldDefs = fieldDefs; } public boolean isDefaultConstructor() { return defaultConstructor; } public void setDefaultConstructor(boolean defaultConstructor) { this.defaultConstructor = defaultConstructor; } }
[ "pamtrak06@gmail.com" ]
pamtrak06@gmail.com
a0d82312f0d74ab7509a51966320a8d2d02f9ada
575c9f31731b0ab140fba5078fa978ecc5743302
/src/main/java/org/lisapark/octopusweb/MRUI.java
3ed7ee35ea8431ee6903ce9c34bda3ba5b575155
[]
no_license
alexmy21/OctopusWebVaadin_2014
694d2a125ef629338241c567de12de680a84a79a
8a05291c1d19c657fc986d760901e7bc726316fd
refs/heads/master
2021-01-23T12:10:39.999331
2014-07-19T22:51:30
2014-07-19T22:51:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,710
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.lisapark.octopusweb; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinSession; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.HorizontalSplitPanel; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.apache.commons.io.IOUtils; import org.openide.util.Exceptions; /** * * @author alexmy */ public class MRUI extends UI { static String TREE_VISIBLE = "TREE_VISIBLE"; static String MODEL_TREE_FIELDS = "MODEL_TREE_FIELDS"; static String MODEL_JSON = "MODEL_JSON"; static final String MODEL_NAME = "MODEL_NAME"; static String JETTY_SEARCH_URL = "http://localhost:8084/search/search"; static String JETTY_RUN_URL = "http://localhost:8084/run/run"; static String MODEL_TREE_LAYOUT = "MODEL_TREE_LAYOUT"; static String SOURCE = "SOURCE"; static String SINK = "SINK"; static String PROCESSOR = "PROCESSOR"; static String PROC_TYPE = "PROC_TYPE"; static String PROC_NAME_VALUE = "PROC_NAME_VALUE"; static String PROC_GROUP_NAME = "PROCESSORS"; static String SINK_GROUP_NAME = "SINKS"; static String SOURCE_GROUP_NAME = "SOURCES"; static String OCTOPUS_PROPERTIS = "octopus.properties"; static String MODEL_NAME_PARAM = "MODEL_NAME_PARAM"; static String JSON_NAME_PARAM = "JSON_NAME_PARAMs"; @Override protected void init(VaadinRequest request) { try { Properties properties = parseProperties(OCTOPUS_PROPERTIS); VaadinSession.getCurrent().setAttribute(MODEL_NAME_PARAM, properties.getProperty("model.name.param")); VaadinSession.getCurrent().setAttribute(JSON_NAME_PARAM, properties.getProperty("model.json.param")); initLayout(); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } private void initLayout() { /* Root of the user interface component tree is set */ HorizontalSplitPanel splitPanel = new HorizontalSplitPanel(); splitPanel.setSplitPosition(30, Unit.PERCENTAGE); setContent(splitPanel); VerticalLayout leftLayout = new ModelListLayout(); VaadinSession.getCurrent().setAttribute(MRUI.TREE_VISIBLE, Boolean.TRUE); if(VaadinSession.getCurrent().getAttribute(MRUI.MODEL_TREE_LAYOUT) == null){ VaadinSession.getCurrent().setAttribute(MRUI.MODEL_TREE_LAYOUT, ModelTreeLayout.initModelTreeLayout(null)); } VerticalLayout rightLayout = (VerticalLayout) VaadinSession.getCurrent().getAttribute(MRUI.MODEL_TREE_LAYOUT); splitPanel.addComponent(leftLayout); splitPanel.addComponent(rightLayout); leftLayout.setSizeFull(); /* Put a little margin around the fields in the right side editor */ rightLayout.setMargin(true); rightLayout.setSizeFull(); // rightLayout.setVisible(false); } private static Properties parseProperties(String propertyFileName) throws IOException { InputStream fin = null; Properties properties = null; try { fin = MRUI.class.getResourceAsStream("/" + propertyFileName); properties = new Properties(); properties.load(fin); } finally { IOUtils.closeQuietly(fin); } return properties; } }
[ "alexmy@e949ee57-6d0f-44c4-9115-0daea41eab00" ]
alexmy@e949ee57-6d0f-44c4-9115-0daea41eab00
3025c34198928a817a6ac0d95f14ebaeca9b2220
7eb13d669cdeb914642a64e747ec6ef1484a64a1
/engine/src/es/eucm/eadandroid/ecore/control/functionaldata/functionalhighlights/FunctionalHighlightRed.java
a7cf3edf63f106aba66853a302ef397028b7dc62
[]
no_license
e-ucm/eadventure-legacy-android
7efe68326dc272cee467b597b66153adf17bcd11
905a4f45e83f59e199645c086a9708cd9a82410b
refs/heads/master
2016-09-02T00:51:45.594583
2014-01-30T14:48:09
2014-01-30T14:48:09
14,957,009
1
0
null
null
null
null
UTF-8
Java
false
false
4,142
java
/******************************************************************************* * <e-Adventure> Mobile for Android(TM) is a port of the <e-Adventure> research project to the Android(TM) platform. * * Copyright 2009-2012 <e-UCM> research group. * * <e-UCM> is a research group of the Department of Software Engineering * and Artificial Intelligence at the Complutense University of Madrid * (School of Computer Science). * * C Profesor Jose Garcia Santesmases sn, * 28040 Madrid (Madrid), Spain. * * For more info please visit: <http://e-adventure.e-ucm.es/android> or * <http://www.e-ucm.es> * * *Android is a trademark of Google Inc. * * **************************************************************************** * This file is part of <e-Adventure> Mobile, version 1.0. * * Main contributors - Roberto Tornero * * Former contributors - Alvaro Villoria * Juan Manuel de las Cuevas * Guillermo Martin * * Directors - Baltasar Fernandez Manjon * Eugenio Marchiori * * You can access a list of all the contributors to <e-Adventure> Mobile at: * http://e-adventure.e-ucm.es/contributors * * **************************************************************************** * <e-Adventure> Mobile is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * <e-Adventure> Mobile is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * See <http://www.gnu.org/licenses/> ******************************************************************************/ package es.eucm.eadandroid.ecore.control.functionaldata.functionalhighlights; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import es.eucm.eadandroid.ecore.gui.GUI; public class FunctionalHighlightRed extends FunctionalHighlight { public FunctionalHighlightRed(boolean animated) { this.animated = animated; this.time = System.currentTimeMillis( ); } @Override public Bitmap getHighlightedImage( Bitmap image ) { if (animated) calculateDisplacements(image.getWidth( ), image.getHeight( )); if (oldImage == null || oldImage != image) { Bitmap temp = GUI.getInstance( ).getGraphicsConfiguration( ).createCompatibleImage(image.getWidth(), image.getHeight(), true ); Canvas c = new Canvas(temp); c.drawBitmap(image, 0, 0, null); //GRAPHICS //temp.getGraphics( ).drawImage( image, 0, 0, null ); //OPTIMIZE improve performance using android API? for (int i = 0 ; i < image.getWidth( ); i++) { for (int j = 0; j < image.getHeight( ); j++) { temp.setPixel( i, j, temp.getPixel(i, j) | 0x00ff0000 ); } } oldImage = image; newImage = temp; } Bitmap temp = GUI.getInstance( ).getGraphicsConfiguration( ).createCompatibleImage( Math.round( image.getWidth( ) * scale ), Math.round( image.getHeight( ) * scale ), true ); Canvas c = new Canvas(temp); Matrix m = new Matrix(); m.setScale(scale, scale); c.drawBitmap(temp, m, null); return temp; // return newImage.getScaledInstance( (int)(image.getWidth(null) * scale), (int)(image.getHeight( null ) * scale), Image.SCALE_SMOOTH ); } }
[ "jtorrente@e-ucm.es" ]
jtorrente@e-ucm.es
5467a40d3963e49a13a11e0bd3c4fd52f4940445
05381b7f3f73bf2584a496c36b4156b032683792
/src/main/java/com/project/university/Application.java
232ecda81713b293cfdf801913e2402731bfe679
[]
no_license
CristianOcheana/projectUniversity
e5594cb77128e14e5fbe2d91389cf3ff81f88593
a63039be19e6dcaa2f1164fcb47cbf05f3267260
refs/heads/master
2022-07-26T23:50:37.886561
2020-04-21T14:34:49
2020-04-21T14:34:49
214,492,109
0
0
null
2022-06-29T18:04:32
2019-10-11T17:17:52
JavaScript
UTF-8
Java
false
false
312
java
package com.project.university; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
[ "cristian.ocheana@yahoo.com" ]
cristian.ocheana@yahoo.com
38ef827797e3e9800353008cba59c02d35450544
1119ec3add922342f18e3c40baa1cdb3e400618c
/Mybatistest/src/com/briup/many2many/Student.java
10607d8392e17d711c6f3ae88649a8458c0bb37e
[]
no_license
lzpooo/javaSE
f965ff7c137f7325a0783baff97046c20624e731
9f63c08047a73f40d5879c2b8682cce29c7d4a8a
refs/heads/master
2021-07-11T03:34:00.204773
2017-10-14T06:59:37
2017-10-14T06:59:37
85,571,626
0
0
null
null
null
null
UTF-8
Java
false
false
1,800
java
package com.briup.many2many; import java.util.List; public class Student { private Integer id; private String name; // 姓名 private String gender; // 性别 private String major; // 专业 private String grade; // 年级 private List<Course> courses;// 所选的课程 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public List<Course> getCourses() { return courses; } public void setCourses(List<Course> courses) { this.courses = courses; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", gender=" + gender + ", major=" + major + ", grade=" + grade + ", courses=" + courses + "]"; } public Student(Integer id, String name, String gender, String major, String grade, List<Course> courses) { this.id = id; this.name = name; this.gender = gender; this.major = major; this.grade = grade; this.courses = courses; } public Student(String name, String gender, String major, String grade, List<Course> courses) { this.name = name; this.gender = gender; this.major = major; this.grade = grade; this.courses = courses; } public Student(String name, String gender, String major, String grade) { this.name = name; this.gender = gender; this.major = major; this.grade = grade; } public Student() { } }
[ "1598857724@qq.com" ]
1598857724@qq.com
b1051b309fa1c6516a931cd791d861a7437b979b
c37da20386534912af7918114bd0bae1f041cdb8
/APIQuarkus/clog/src/main/java/br/com/conectcar/clog/entity/LogMessage.java
fcdbaf2ff993106775a924fa8a4fb58aa461b17e
[]
no_license
ViniciusVendramelGalhiardi/quakusconect
39e06abced9b881a25bb0538fb5e0b2b92997216
0b3abfe511ff43636b7c17d74cec7c51d63c0c3c
refs/heads/master
2023-05-31T04:56:54.303398
2021-06-18T12:44:48
2021-06-18T12:44:48
354,403,164
0
0
null
null
null
null
UTF-8
Java
false
false
635
java
package br.com.conectcar.clog.entity; import java.io.Serializable; public class LogMessage implements Serializable{ private static final long serialVersionUID = 1L; public String Data; public String UserName; public String MessageType; public String Message; public LogMessage() { super(); } public LogMessage(String data, String userName, String messageType, String message) { this.Data = data; this.UserName = userName; this.MessageType = messageType; this.Message = message; } }
[ "fabio.abr@hotmail.com" ]
fabio.abr@hotmail.com
c005549d256d7b1426b26a12fbbaa7844002a0a7
0218e5fec5e26eb2284a07f4e09e1759f7de0736
/FakaManagement/src/main/java/com/tecsun/sisp/fakamanagement/modules/util/ThreadPoolUtil.java
93c7e9e8471c33ea51fe43a5fcff8b00c8019c86
[]
no_license
KqSMea8/Mestudy
7dd7d2bda4ea49745f2da10b18e029b086be4518
f504bdd71ee3a6341d946ca1a03a9d83b5820970
refs/heads/master
2020-04-09T06:34:03.624202
2018-12-03T01:43:38
2018-12-03T01:43:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,166
java
package com.tecsun.sisp.fakamanagement.modules.util; import java.util.concurrent.*; /** * ClassName: ThreadPoolUtil * Description:线程池用来处理业务分析子系统数据 * Author: 张清洁 * CreateTime: 2015年07月31日 15时:20分 */ public class ThreadPoolUtil { private static ThreadPoolExecutor threadPool = null; private static boolean isInit = false; public static final void init() { if (!isInit) { initThreadPool(); isInit = true; } } /** * CachedThreadPool 执行线程不固定, * 好处:可以把新增任务全部缓存在一起, * 坏处:只能用在短时间完成的任务(占用时间较长的操作可以导致线程数无限增大,系统资源耗尽) */ private static void initThreadPool() { threadPool = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); } public static ThreadPoolExecutor getThreadPool() { if (threadPool == null) { initThreadPool(); } return threadPool; } }
[ "zengyunhuago@163.com" ]
zengyunhuago@163.com
60c177c06c1f2b239272244b62c09b7a19a48f68
f87159958de445ed05e24b79f770ee590d824781
/src/com/merson/mobile/mobilemanager/SplashActivity.java
02d523f51d93dfd8d0848ca4ba740f76fab7af56
[]
no_license
ruruoran/MobileManager
15e755a0cec58cb5f786b4b06f1f568f16145e33
e0e4785e3148a2265258acd54d48e95a3bacebaf
refs/heads/master
2021-01-10T04:32:44.210201
2016-04-06T13:00:59
2016-04-06T13:00:59
54,720,745
0
0
null
null
null
null
GB18030
Java
false
false
13,155
java
package com.merson.mobile.mobilemanager; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.ResponseHandlerInterface; import com.merson.mobile.application.MyApplication; import com.merson.mobile.utils.HTTPUtils; import com.merson.mobilemanager.R; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.logging.LogRecord; import junit.framework.Assert; public class SplashActivity extends Activity { private static final String TAG = "SplashActivity"; private static final int MSG_OK =1; private String current_version; //增加以下 private TextView tv_splash_version; private ProgressBar pb_splash_download; private static final int MSG_ERROR_INTERSEVER =-1; private static final int MSG_ERROR_URL =-2; private static final int MSG_ERROR_IO =-3; private static final int MSG_ERROR_JSON =-4; private static final int MSG_WATI_TIMEOUT =2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); tv_splash_version = (TextView) findViewById(R.id.tv_splash_version); ProgressBar pb_splash_down = (ProgressBar) findViewById(R.id.pb_splash_down); current_version = getVersionName(); tv_splash_version.setText("current_version : "+current_version); // 优化:只有在用户开启 检测主动升级 才检测新版本 //getNewVersion(); if (MyApplication.configsp.getBoolean("autoupdate", true)) { getNewVersion(); }else //新增 waitaWhile函数 等待在splash页面停留几秒 waitaWhile(); copydb(); } //将数据库从assets目录下 copy到 data/data/packagename/ private void copydb() { // TODO Auto-generated method stub try { File db = new File("data/data/"+getPackageName()+"/location.db"); if (db.exists()) return;//db 存在 直接返回 无需再复制 final AssetManager assetManager = getAssets(); final InputStream open = assetManager.open("naddress.db"); FileOutputStream fos = new FileOutputStream(db); byte[] bys = new byte[1024]; int len = -1; while ((len=open.read(bys,0,1024))!=-1) { fos.write(bys,0,len); } fos.close(); open.close(); } catch (FileNotFoundException e) { // TODO: handle exception e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void waitaWhile() { // TODO Auto-generated method stub new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { Thread.sleep(5000); /*当需要修改页面时 * runOnUiThread(new Runnable() { + @Override + public void run() { + enterHome(); + + } + });*/ } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Message msg = myhandler.obtainMessage(); msg.what=MSG_WATI_TIMEOUT; myhandler.sendMessage(msg); } }).start(); } private String getVersionName(){ String versionName =""; //管理当前手机的应用 PackageManager manager=getPackageManager(); try { PackageInfo packageInfo = manager.getPackageInfo(getPackageName(), 0); versionName = packageInfo.versionName; int versionCode= packageInfo.versionCode; // Log.i(TAG,"version"+versionName +versionCode); return versionName; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); //can't reach } return versionName; } Handler myhandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case MSG_OK: String[] info = (String[]) msg.obj; String version= info[0]; String newVersiondescription =info[1]; String downurl =info[2]; float newver= Float.parseFloat(version); float currver = Float.parseFloat(current_version); if (newver>currver){ update(info); } break; //增加以下case case MSG_ERROR_INTERSEVER: Toast.makeText(SplashActivity.this, MSG_ERROR_INTERSEVER+"",Toast.LENGTH_LONG).show(); enterHome(); break; case MSG_ERROR_JSON: Toast.makeText(SplashActivity.this, MSG_ERROR_JSON+"",Toast.LENGTH_LONG).show(); enterHome(); break; case MSG_ERROR_URL: Toast.makeText(SplashActivity.this, MSG_ERROR_URL+"",Toast.LENGTH_LONG).show(); enterHome(); break; case MSG_ERROR_IO: Toast.makeText(SplashActivity.this, MSG_ERROR_IO+"",Toast.LENGTH_LONG).show(); enterHome(); break; case MSG_WATI_TIMEOUT: enterHome(); break; } } }; public void update(final String[] info){ // Log.i(TAG,"update"); new AlertDialog.Builder(this) .setTitle("发现新版本") .setMessage(info[1]) .setPositiveButton("更新", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //download AsyncHttpClient client = new AsyncHttpClient(); // client.get("http://192.168.3.36/MobileManager"+info[2], new MyAsyncHttpHandler() ); //地址用变量替换 便于管理 client.get(MyApplication.SERVER_PATH+info[2], new MyAsyncHttpHandler() ); pb_splash_download.setVisibility(View.VISIBLE); // client.get } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //进入到主页面 enterHome(); } }) .show(); } class MyAsyncHttpHandler extends AsyncHttpResponseHandler{ @Override public void onSuccess(int i, Header[] headers, byte[] bytes) { File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/moblie.apk"); try { FileOutputStream fos = new FileOutputStream(file); fos.write(bytes); fos.close(); install(file); } catch (FileNotFoundException e) { e.printStackTrace(); //出错 需要进入主页 enterHome(); } catch (IOException e) { e.printStackTrace(); enterHome(); } } @Override public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) { Toast.makeText(SplashActivity.this,"下载失败",Toast.LENGTH_LONG).show(); //进入到主页面 enterHome(); } @Override public void onProgress(long bytesWritten, long totalSize) { // TODO Auto-generated method stub super.onProgress(bytesWritten, totalSize); pb_splash_download.setMax((int) totalSize); pb_splash_download.setProgress((int) bytesWritten); } } private void install(File f){ //思路比较简单,和调用系统其他app类似 Intent intent =new Intent(); intent.setAction("android.intent.action.VIEW"); intent.addCategory("android.intent.category.DEFAULT"); intent.setDataAndType(Uri.fromFile(f), "application/vnd.android.package-archive"); // startActivity(intent); startActivityForResult(intent, 100); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if (resultCode==RESULT_CANCELED) { enterHome(); } } //跳转主页 public void enterHome(){ Log.i("splash","enterHome"); startActivity(new Intent(SplashActivity.this,HomeActivity.class)); finish(); } private void getNewVersion(){ new Thread(){ @Override public void run() { super.run(); // String path ="http://192.168.3.36/MobileManager/version.json"; String path = MyApplication.SERVER_PATH+"/version.json"; Message msg = myhandler.obtainMessage(); try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); conn.connect(); int ret =conn.getResponseCode(); //进行json解析 if (ret==200){ InputStream is= conn.getInputStream(); String text= HTTPUtils.getTextFromStream(is); JSONObject obj = new JSONObject(text) ; String newVersion = obj.getString("version"); String downlaodurl = obj.getString("download_url"); String newVersiondescription =obj.getString("description"); String[] newversioninfo = {newVersion,newVersiondescription,downlaodurl}; Log.i(TAG,newVersion+":"+downlaodurl); // Message msg = myhandler.obtainMessage(); msg.what=MSG_OK; msg.obj=newversioninfo; // myhandler.sendMessage(msg); }else{ if (ret==500) { msg.what=MSG_ERROR_INTERSEVER; } } } catch (MalformedURLException e) { e.printStackTrace(); msg.what=MSG_ERROR_URL; } catch (IOException e) { e.printStackTrace(); msg.what=MSG_ERROR_IO; } catch (JSONException e) { e.printStackTrace(); msg.what=MSG_ERROR_JSON; }finally{ myhandler.sendMessage(msg); } } }.start(); } }
[ "ruruoran@126.com" ]
ruruoran@126.com
16b114362219c64e456f7402720c77889a4b8adb
eec37fe37a57a37eb3eba99c71f1b96e467d9571
/trunk/bps.yun.service/src/main/java/bps/order/OrderServiceImpl.java
fac4042ebcfbd02e69be07bbd38e16bb15a51b40
[]
no_license
chocoai/SOA
625d93a30d5dce4f8b931f8739dcf6e0f2bcd41d
86c539fb084cfa05230e309ceeeaff87ef05772e
refs/heads/master
2020-04-14T19:31:31.433552
2016-06-28T08:22:36
2016-06-28T08:22:36
164,061,005
0
1
null
2019-01-04T05:11:55
2019-01-04T05:11:55
null
UTF-8
Java
false
false
79,973
java
package bps.order; import bps.application.Appliction; import bps.common.*; import bps.order.Command.Command; import com.kinorsoft.ams.services.FreezeService; import ime.core.Environment; import ime.core.Reserved; import ime.core.event.Event; import ime.core.event.EventManager; import ime.core.services.DynamicEntityService; import ime.security.LoginSession; import ime.security.Password; import ime.security.util.TripleDES; import java.text.SimpleDateFormat; import java.util.*; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.json.JSONArray; import org.json.JSONObject; import com.kinorsoft.ams.ITradeCommand.CommandResult; import com.kinorsoft.ams.TradeCommandManager; import com.kinorsoft.ams.services.QueryService; import com.kinorsoft.ams.services.TradeService; import apf.util.BusinessException; import apf.util.EntityManagerUtil; import apf.work.QueryWork; import apf.work.TransactionWork; import bps.account.AccountServiceImpl; import bps.code.CodeServiceImpl; import bps.external.tradecommand.ItsManage; import bps.member.Member; import bps.rule.TradeRule; import bps.service.AccountService; import bps.service.OrderService; import bps.util.CodeUtil; // 交易类型为转账,交易子类型(除了转账到卡,用户),部分字段写入订单明细表。 /** * * @author Administrator * */ public class OrderServiceImpl implements OrderService{ private static Logger logger = Logger.getLogger(OrderServiceImpl.class.getName()); private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private static SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd"); /**** * * @Title applyOrder * @Description TODO 订单申请接口 * @param applicationId 应用ID * @param memberId 会员ID * @param bizOrderNo 业务订单号 * @param money 金额 * @param orderType 订单类型 * @param tradeType 交易类型 * @param source 来源 * @param extParams * bankCardId 银行卡编号 * accountCodeNo 账户类型编号 * phone 充值的手机号 * subTradeType 子交易类型 * transactionType 支付类型 * merchantOrderNo 外部交易号 * orderName 订单名称 * remark 备注 * memberIp 用户ip * orgUserId 外部会员唯一标识 * orgNo 机构号 * extendInfo 扩展信息 * qrCode 二维码 * outSerialNumber 外部流水号 * accountNo 银行卡号 * enAccountNo 加密后的银行卡号 * bankCode 银行代码 * accountName 开户名 * bankName 银行名称 * @param accountList 内部账号 * 成员对象属性Map * accountCodeNo String 账户类型编号 * tradeMoney Long 交易金额 * seqNo Long 顺序号 * @param payInterfaceList 支付通道 * 成员当对象Map * seqNo Long 顺序号 * cardList 卡对象列表 多条传入列表中 * tradeMoney * @return Map 返回类型 * @throws BizException */ public Map<String, Object> applyOrder(Long applicationId, Long memberId,String bizOrderNo, Long money, Long orderType, Long tradeType, Long source, Map<String, Object> extParams, List accountList, List payInterfaceList, List couponList) throws BizException { // TODO Auto-generated method stub logger.info("OrderServiceImpl.createOrder start"); logger.info("memberId="+memberId+"money="+money+"orderType="+orderType+"tradeType="+tradeType+"source="+source); logger.info("extParams="+extParams); logger.info("accountList="+accountList); logger.info("payInterfaceList="+payInterfaceList); logger.info("couponList=" + couponList); // String orderNo=""; Map<String,Object> ret = null; Long subTradeType = (Long) extParams.get("subTradeType"); if(accountList == null){ accountList = new ArrayList<>(); } extParams.put("memberId", memberId); extParams.put("money", money); extParams.put("orderType", orderType); extParams.put("tradeType", tradeType); extParams.put("source", source); extParams.put("bizOrderNo", bizOrderNo); extParams.put("accountList", accountList); extParams.put("payInterfaceList", payInterfaceList); extParams.put("couponList", couponList); try { Member member = new Member(memberId); if( Constant.USER_STATE_LOCKED.equals(member.getUser_state())) { throw new BizException(ErrorCode.ACCOUNT_EX_LOCKING, "该用户已被锁定或关闭"); } Map<String,Object> applicationEntity = DynamicEntityService.getEntity(applicationId, "AMS_Organization"); if(applicationEntity == null){ throw new BizException(ErrorCode.APPLICATION_NOTEXSIT,"应用不存在"); } //交易规则 TradeRule.checkTradeRule(tradeType, subTradeType, payInterfaceList, accountList, applicationEntity); //交易规则 end String applicationName = (String)applicationEntity.get("name"); extParams.put("applicationId", applicationId); extParams.put("applicationName", applicationName); extParams.put("applicationName", applicationName); extParams.put("orgNo", applicationEntity.get("codeNo")); extParams.put("applicationMemberId", (Long)applicationEntity.get("member_id")); Order order = OrderFactory.getOrder(tradeType, subTradeType); logger.info("aaaa"); ret = order.applyOrder(extParams); logger.info("订单申请返回:" + ret); //交易监测 // List<Map<String, Object>> commandList = getCommands((String)ret.get("orderNo")); // for(Map<String, Object> command : commandList){ // TransMonitor.monitor("response" ,command, new HashMap<String, Object>()); // } } catch(BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR, e.getMessage()); } return ret; } /*** * * (非 Javadoc) * <p>Title: confirmPay</p> 支付确认 * <p>Description: </p> * @param memberId 会员ID * @param orderNo 订单号 * @param oriTraceNum 原交易号 * @param user_ip 用户IP * @param phone 手机号 * @param phoneCode 短信验证码 * @return Map 支付结果 * @throws BizException * @see bps.service.OrderService#confirmPay(java.lang.Long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ // public Map<String, Object> confirmPay(Long memberId, String orderNo, String oriTraceNum, String user_ip, String phone, Long isSendSm, String phoneCode, Long codeType) throws BizException{ public Map<String, Object> confirmPay(Long memberId, String orderNo, String oriTraceNum, String user_ip, String phone, String phoneCode) throws BizException{ logger.info("OrderServiceImpl.confirmPay start"); logger.info("phone="+phone+"memberId="+memberId+"orderNo="+orderNo+"oriTraceNum="+oriTraceNum +"phoneCode="+phoneCode+"user_ip="+user_ip); Map<String, Object> jsonobject = new HashMap<> (); try{ jsonobject.put("status", "fail"); if(StringUtils.isBlank(phone)){ throw new BizException(ErrorCode.PARAM_ERROR, "手机号不能为空"); } Member member = new Member(memberId); if(member.getUserId() == null){ throw new BizException(ErrorCode.PARAM_ERROR, "该用户不存在"); } if(Constant.USER_STATE_LOCKED.equals(member.getUser_state())) { throw new BizException(ErrorCode.ACCOUNT_EX_LOCKING, "该用户已被锁定或关闭"); } if(StringUtils.isBlank(orderNo)){ throw new BizException(ErrorCode.PARAM_ERROR, "订单号不能为空"); } Map<String, Object> order_entity = getOrder(orderNo); if(order_entity == null){ throw new BizException(ErrorCode.PARAM_ERROR, "该订单不存在"); } if( !member.getUserId().equals(order_entity.get("member_uuid"))){ throw new BizException(ErrorCode.ORDER_ERROR, "该订单会员和支付确认传入的会员不同。"); } List commandList = getCommands(orderNo); if(commandList.isEmpty()) { throw new Exception("支付失败"); } //验证机构准备金账户是否充足 if( member.getApplicationId().equals(Constant.YUN_APPLICATION_ID) ){ checkYUNAgencyFees(orderNo); }else{ checkAgencyFees(orderNo); } //end Map<String, Object> command = (Map<String, Object>)commandList.get(0); String pay_interfaceNo = (String)command.get("pay_interfaceNo"); String withdrawType = (String)command.get("withdrawType"); Long withdrawReserveModel = (Long)command.get("withdrawReserveModel"); // if ( pay_interfaceNo.equals(Constant.PAY_INTERFACE_TLT_DF) || pay_interfaceNo.equals(Constant.PAY_INTERFACE_TLT_BACH_DF) ){ // Long fee = (Long)order_entity.get("fee"); // if( fee > 0L ){ // logger.info("调取多账户冻结金额接口"); // final Map<String, Object> param = new HashMap<>(); // // String bizid = (String)command.get("bizid"); // String source_userId = (String)command.get("source_userId"); // Long account_type_id = (Long)command.get("account_type_id"); // // param.put("userId", source_userId); // param.put("account_type_id", account_type_id); // param.put("bizid", bizid); // param.put("freeze_money", fee); // param.put("remark", "代付手续费,冻结金额"); // // LoginSession.backUse(null, Reserved.BACKUSER_ID, Reserved.MAIN_DOMAIN_ID); // EntityManagerUtil.execute(new TransactionWork<Map<String, Object>>() { // @Override // public Map<String, Object> doTransaction(Session session, Transaction tx) // throws Exception { // FreezeService.freezeMoney(param); // return null; // } // }); // } // } if( "T1".equals(withdrawType) ) {//T+1批量代付-冻结金额、放到队列。 WithdrawOrderToBatchDaiFu bdfr = new WithdrawOrderToBatchDaiFu(); bdfr.confirmPay(command, Constant.WITHDRAW_RESERVE_MODEL_ACTIVE); final String _orderNo = orderNo; EntityManagerUtil.execute(new TransactionWork<Object>() { @Override public Object doTransaction(Session session, Transaction tx) throws Exception { Order.updateOrderPending(_orderNo, session ); return null; } }); jsonobject.put("orderNo", orderNo); jsonobject.put("status", "pending"); }else if ( "T0".equals(withdrawType) && withdrawReserveModel.equals(Constant.WITHDRAW_RESERVE_MODEL_ENTRUST) ){//T+0批量代付 WithdrawOrderToBatchDaiFu bdfr = new WithdrawOrderToBatchDaiFu(); bdfr.confirmPay(command, withdrawReserveModel); final String _orderNo = orderNo; EntityManagerUtil.execute(new TransactionWork<Object>() { @Override public Object doTransaction(Session session, Transaction tx) throws Exception { Order.updateOrderPending(_orderNo, session ); return null; } }); jsonobject.put("orderNo", orderNo); jsonobject.put("status", "pending"); }else if(pay_interfaceNo.equals(Constant.PAY_INTERFACE_QUICK)) {//its支付 if(StringUtils.isBlank(oriTraceNum)){ throw new BizException(ErrorCode.PARAM_ERROR, "源交易码不能为空"); } // if(StringUtils.isBlank(phoneCode) && isSendSm.equals(1L)){ if(StringUtils.isBlank(phoneCode)){ throw new BizException(ErrorCode.PARAM_ERROR, "验证码不能为空"); } Map<String, String> temp = new HashMap<>(); temp.put("ORI_TRACE_NUM", oriTraceNum); temp.put("VERIFY_CODE", phoneCode); temp.put("isSendSm", "1"); temp.put("userId", member.getUserId()); Map<String, String> result_its = ItsManage.payACK(temp); if( "000000".equals(result_its.get("RET_CODE")) ){ updateOrderIP(orderNo, user_ip); jsonobject.put("status", "success"); }else{ if(result_its.get("ERROR_MSG") != null && !"".equals(result_its.get("ERROR_MSG"))){ jsonobject.put("payFailMessage", result_its.get("ERROR_MSG")); }else{ jsonobject.put("payFailMessage", result_its.get("RET_MSG")); } } } else { // if(isSendSm == null || isSendSm.equals(1L)) { if((Constant.TRADE_TYPE_WITHDRAW.equals(order_entity.get("trade_type")) && Constant.SUB_TRADE_TYPE_WITHDRAW_WITHOUT_CONFIRM.equals(order_entity.get("sub_trade_type"))) || (Constant.TRADE_TYPE_DEPOSIT.equals(order_entity.get("trade_type")) && Constant.SUB_TRADE_TYPE_DEPOSIT_WITHOUT_CONFIRM.equals(order_entity.get("sub_trade_type"))) || (Constant.TRADE_TYPE_TRANSFER.equals(order_entity.get("trade_type")) && Constant.SUB_TRADE_TYPE_SHOPPING_WITHOUT_CONFIRM.equals(order_entity.get("sub_trade_type")))){ //无验证提现 取消短信验证 logger.info("confirmPay:取消短信"); }else { //验证短信验证码 CodeServiceImpl codeServiceImpl = new CodeServiceImpl(); Long code_id = codeServiceImpl.checkPhoneVerificationCode(Constant.APPLICATION_ID_BPS_YUN, phone, Constant.VERIFICATION_CODE_AUTH_PAY, phoneCode); //设置短信验证码已验证 codeServiceImpl.setPhoneVerificationCode(code_id); } // } Map<String, Object> retMap = new HashMap<>(); TradeCommandManager tradeCommandManager = TradeCommandManager.instance(); try { CommandResult command_state = tradeCommandManager.doCommands(orderNo, null); retMap.put("command_result", command_state); } catch(Exception e) { logger.error(e.getMessage(), e); retMap.put("command_result", CommandResult.FailStop); retMap.put("err_msg1", e.getMessage()); } //Map<String, Object> retMap = OrderService.doCommand(orderNo); logger.info("retMap------------------:"+retMap); CommandResult command_state = (CommandResult)retMap.get("command_result"); logger.info("ret_code1------------------:"+command_state); Map<String, Object> setParam = new HashMap<>(); //{command_result=PendingStop, ret_code2=null, ret_code1=1000, err_msg1=序号为0 的交易中账号:6214835741131658 没有从协议库中找到对应的协议号, err_msg2=null} if( command_state.equals(CommandResult.Success) ){ jsonobject.put("orderNo", orderNo); jsonobject.put("status", "success"); /* if(((Long)order_entity.get("sub_trade_type")).equals(Constant.SUB_TRADE_TYPE_PHONE) && ((String)order_entity.get("orgNo")).equals(Constant.ORG_NO_ALLINPAY)) { OrderService.phoneDepositOrderComplatePay((Long)order_entity.get("id")); } */ }else if(command_state.equals(CommandResult.PendingContinue)){ jsonobject.put("orderNo", orderNo); jsonobject.put("status", "pending"); }else if(command_state.equals(CommandResult.PendingStop)){ jsonobject.put("orderNo", orderNo); jsonobject.put("status", "pending"); }else if( command_state.equals(CommandResult.FailStop) ){ jsonobject.put("status", "fail"); if( retMap.get("err_msg1") != null ) jsonobject.put("payFailMessage", retMap.get("err_msg1")); else jsonobject.put("payFailMessage", retMap.get("err_msg2")); setParam.put("order_state", Constant.ORDER_STATE_CLOSE); }else{ jsonobject.put("status", "fail"); if( retMap.get("err_msg1") != null ) jsonobject.put("payFailMessage", retMap.get("err_msg1")); else jsonobject.put("payFailMessage", retMap.get("err_msg2")); } } //返回剩余可投资金额 朱成-2016-3-22 // Long order_type = order_entity.get("order_type") == null ? null : (Long)order_entity.get("order_type"); // String biz_trade_code = order_entity.get("biz_trade_code") == null ? "" : (String)order_entity.get("biz_trade_code"); // Long goodsType = order_entity.get("goodsType") == null ? null : (Long)order_entity.get("goodsType"); // String goodsNo = order_entity.get("goodsNo") == null ? "" : (String)order_entity.get("goodsNo"); // // if ( Constant.ORDER_TYPE_DAISHOU.equals(order_type) && "1001".equals( biz_trade_code ) ){ // List<Map<String, Object>> orderList = getOrderListByGoods(order_type,biz_trade_code,goodsType,goodsNo); // Long sumOldAmount = 0L; // for (Map<String, Object> temp : orderList){ // Long tempAmount = temp.get("order_money") == null ? 0L : (Long)temp.get("order_money"); // sumOldAmount += tempAmount; // } // // GoodsServiceImpl gsi = new GoodsServiceImpl(); // Map<String,Object> goods = gsi.queryGoods((Long)order_entity.get("application_id"),goodsType,goodsNo); // Long highest_amount = goods.get("highest_amount") == null ? (Long)goods.get("total_amount") : (Long)goods.get("highest_amount"); // // logger.info("highest_amount:"+highest_amount); // logger.info("sumOldAmount:"+sumOldAmount); // // Long remainAmount = highest_amount - sumOldAmount; // jsonobject.put("remainAmount",remainAmount); // } }catch(BizException e){ logger.error(e.getMessage(), e); throw e; }catch(Exception e){ logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR, e.getMessage()); } logger.info("组合支付结束"); return jsonobject; } /** * 获取指令集 * @param orderNo 订单号 * @throws Exception */ public List getCommands(String orderNo)throws BizException{ logger.info("OrderServiceImpl.getCommand start"); try { final String _orderNo = orderNo; List<Map<String, Object>> res= EntityManagerUtil.execute(new QueryWork<List<Map<String, Object>>>() { @Override public List<Map<String, Object>> doQuery(Session session) throws Exception { Query query = session.createQuery("from AMS_OrderPayDetail where bizid=:orderNo and pay_state=:pay_state order by seq_no asc"); query.setParameter("orderNo", _orderNo); query.setParameter("pay_state", com.kinorsoft.ams.Constant.COMMAND_STATE_UNPAY); return query.list(); } }); return res; } catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } public void closeCommandOrder(String commandNo, Map<String, Object> params) throws BizException{ logger.info("OrderServiceImpl.closeCommandOrder=" + commandNo + ",params=" + params); final String _commandNo = commandNo; final Map<String, Object> _params = params; try { EntityManagerUtil.execute(new TransactionWork<Object>() { @Override public Object doTransaction(Session session, Transaction tx) throws Exception { String orderNo = _commandNo.split(Constant.COMMAND_SPLIT_SIGN)[0]; Command.closeCommandByCommandNo(_commandNo, _params, session); Order.closeOrder(orderNo, _params, session); return null; } }); } catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.OTHER_ERROR,e.getMessage()); } } /**** * * @Title: closeOrder * @Description: TODO(关闭订单 * @param @param orderNo * @param @param extParams * @param @throws BizException 设定文件 * @return void 返回类型 * @throws */ public void closeOrder(String orderNo, Map<String, Object> extParams) throws BizException { logger.info("OrderServiceImpl.closeOrder start"); logger.info("extParams="+extParams); final String _orderNo=orderNo; final Map<String, Object> param=extParams; try { EntityManagerUtil.execute(new TransactionWork<Object>() { @Override public Object doTransaction(Session session, Transaction tx) throws Exception { Order.closeOrder(_orderNo, param, session); return null; } }); } catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } // public Map<String, String> itsSignApply(String bankCode, // String accountName, Long cardType, String accountNo, // Long accountTypeId, String accountTypeName, String phone, // String bankName, Long memberId, Long payType, Map<String, Object> extParams) /** * 绑定银行卡申请 * @param bankCode 银行代码 * @param accountName 开户名 * @param cardType 卡类型 * @param accountNo 卡号 * @param phone 手机 * @param bankName 银行名称 * @param memberId 会员编号 * @param payType 1正常,3免验证码 * @param extParams 扩展参数 * acctValiddate 有效期 信用卡属性 * cvv2 cvv2 信用卡属性 * identityCardNo 身份证 * identityCardNoEncrypt 身份证加密码 * identityCardNoMask 身份证掩码 * cnlMchtName 商户名称 * cnlMchtType 商户类型 * cnlMchtId id 应用ID * @return Map<String,String> * @throws BizException */ public Map<String, String> itsSignApply(String bankCode, String accountName, Long cardType, String accountNo,String phone, String bankName, Long memberId, Long payType, Map<String, Object> extParams) throws BizException { logger.info("OrderServiceImpl.itsSignApply start"); try { Member member = new Member(memberId); if(member.getUserId() == null) { throw new BizException(ErrorCode.USER_NOTEXSIT, "该用户不存在"); } //组装参数 Map<String, String> params = new HashMap<>(); params.put("BANK_CODE", bankCode); params.put("ACCT_NAME", accountName); params.put("ACCT_CAT", cardType.toString()); params.put("member_id", memberId.toString()); if(extParams.get("acctValiddate") != null) params.put("ACCT_VALIDDATE", extParams.get("acctValiddate").toString()); if(extParams.get("cvv2") != null) params.put("CVV2", extParams.get("cvv2").toString()); params.put("ACCT_NO", accountNo); // params.put("ACCOUNT_TYPE_ID", accountTypeId.toString()); // params.put("ACCOUNT_TYPE_LABEL", accountTypeName); if(extParams.get("identityCardNo") != null) params.put("ID_NO", extParams.get("identityCardNo").toString()); if(extParams.get("identityCardNoEncrypt") != null) params.put("ID_NO_ENCRYPT", extParams.get("identityCardNoEncrypt").toString()); if(extParams.get("identityCardNoMask") != null) params.put("ID_NO_MASK", extParams.get("identityCardNoMask").toString()); if(extParams.get("isSafeCard") != null) params.put("isSafeCard", String.valueOf(extParams.get("isSafeCard"))); params.put("PHONE_NO", phone); params.put("BANK_NAME", bankName); params.put("userId", member.getUserId()); params.put("payType", payType.toString()); if(extParams.get("cnlMchtName") != null) params.put("CNL_MCHT_NAME", extParams.get("cnlMchtName").toString()); if(extParams.get("cnlMchtType") != null) params.put("CNL_MCHT_TYPE", extParams.get("cnlMchtType").toString()); if(extParams.get("cnlMchtId") != null) params.put("CNL_MCHT_ID", extParams.get("cnlMchtId").toString()); //验证传入的身份真和姓名是否与实名记录一致 params.put("accountName",accountName); Member.chickBindBankCardID(params, member); // if(Constant.MEMBER_TYPE_PERSON.equals(member.getMember_type())){ // if(!accountName.equals(member.getName())) // throw new BizException(ErrorCode.VERIFY_REAL_NAME_FAIL,"银行卡用户信息不一致"); // //身份证最后一位是X时验证:把x转成大小写来验证,二者过一个就可以。 // if(params.get("ID_NO")!=null){ // String id_no = params.get("ID_NO"); // String identity_cardNo_md5 = Password.encode(id_no, "MD5"); // // String id_no_x = ""; // if(id_no.contains("x")){ // id_no_x = id_no.toUpperCase(); // }else if(id_no.contains("X")){ // id_no_x = id_no.toLowerCase(); // } // if( !id_no_x.equals("")){ // id_no_x = Password.encode(id_no_x, "MD5"); // if(!identity_cardNo_md5.equals(member.getIdentity_cardNo_md5())){ // if(!id_no_x.equals(member.getIdentity_cardNo_md5())){ // throw new BizException(ErrorCode.VERIFY_REAL_NAME_FAIL,"银行卡用户信息不一致"); // } // } // }else{ // if(!identity_cardNo_md5.equals(member.getIdentity_cardNo_md5())){ // throw new BizException(ErrorCode.VERIFY_REAL_NAME_FAIL,"银行卡用户信息不一致"); // } // } // }else if(params.get("ID_NO_ENCRYPT")!=null){ // String id_no = TripleDES.decrypt(member.getUserId() + Constant.MEMBER_BANK_ENCODE_KEY, params.get("ID_NO_ENCRYPT")); // String identity_cardNo_md5 = Password.encode(id_no, "MD5"); // // String id_no_x = ""; // if(id_no.contains("x")){ // id_no_x = id_no.toUpperCase(); // }else if(id_no.contains("X")){ // id_no_x = id_no.toLowerCase(); // } // if( !id_no_x.equals("")){ // id_no_x = Password.encode(id_no_x, "MD5"); // if(!identity_cardNo_md5.equals(member.getIdentity_cardNo_md5())){ // if(!id_no_x.equals(member.getIdentity_cardNo_md5())){ // throw new BizException(ErrorCode.VERIFY_REAL_NAME_FAIL,"银行卡用户信息不一致"); // } // } // }else{ // if(!identity_cardNo_md5.equals(member.getIdentity_cardNo_md5())){ // throw new BizException(ErrorCode.VERIFY_REAL_NAME_FAIL,"银行卡用户信息不一致"); // } // } // } // } //调用its申请绑卡接口 Map<String, String> result_its = ItsManage.signApply(params); logger.info("result_its:"+result_its); if( "000000".equals(result_its.get("RET_CODE")) || "359037".equals(result_its.get("RET_CODE"))){ if(result_its.get("SEND_SMS") ==null || "2".equals(result_its.get("SEND_SMS")) ){ params = new HashMap<String, String>(); params.put("ORI_TRACE_NUM", result_its.get("TRACE_NUM")); params.put("ORI_TRANS_DATE", result_its.get("TRANS_DATE")); params.put("PHONE_NO", phone); params.put("userId", member.getUserId()); params.put("member_id", memberId.toString()); Map<String, String> result_its2 = ItsManage.signMessageSend(params); if("000000".equals(result_its2.get("RET_CODE")) || "359037".equals(result_its2.get("RET_CODE"))){ return result_its; }else{ if(result_its2.get("ERROR_MSG") != null && !"".equals(result_its2.get("ERROR_MSG").toString())){ throw new Exception(result_its2.get("ERROR_MSG")); }else{ throw new Exception(result_its2.get("RET_MSG")); } } } } return result_its; } catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } /** * @Title:itsSignACK * @Description: 绑定银行卡确认接口 * @param oriTraceNum:流水号,请求绑定银行卡接口返回 * @param oriTransDate:申请时间,请求绑定银行卡接口返回 * @param memberId:会员ID * param verifyCode:手机验证码 */ public void itsSignACK(String oriTraceNum, String oriTransDate, Long memberId, String verifyCode, Long payType) throws BizException { logger.info("OrderServiceImpl.itsSignACK start"); try { Member member = new Member(memberId); if(member.getUserId() == null) { throw new BizException(ErrorCode.USER_NOTEXSIT, "该用户不存在"); } //检查应用准备金是否足够 Map<String, Object> memberEntity = member.getUserInfo(); Long applicationId =(Long)memberEntity.get("application_id"); Map<String, Object> applicationEntity = DynamicEntityService.getEntity(applicationId, "AMS_Organization"); String orgNo = (String)applicationEntity.get("codeNo"); Long applicationMemberId = (Long)applicationEntity.get("member_id"); Map<String, Object> applicationMemberEntity = DynamicEntityService.getEntity(applicationMemberId, "AMS_Member"); String applicationUserId = (String)applicationMemberEntity.get("userId"); Map<String, Object> orgFeeEntity = Member.checkFee(orgNo, applicationUserId, Constant.FEE_TYPE_BIND_BANK_CARD); //绑卡 Map<String, String> params = new HashMap<String, String>(); params.put("ORI_TRACE_NUM", oriTraceNum); params.put("ORI_TRANS_DATE", oriTransDate); params.put("VERIFY_CODE", verifyCode); params.put("userId", member.getUserId()); params.put("payType", payType.toString()); Map<String, String> ret = ItsManage.signACK(params); //检查是否成功 String retCode = ret.get("RET_CODE"); //成功 if("000000".equals(retCode) || "359037".equals(retCode)){ //手续费 if(orgFeeEntity != null){ final Map<String, Object> _orgFeeEntity = orgFeeEntity; final Map<String, Object> _applicationMemberEntity = applicationMemberEntity; EntityManagerUtil.execute(new TransactionWork<String>() { @Override public String doTransaction(Session session, Transaction tx) throws Exception { Member.feeOpe(_applicationMemberEntity, _orgFeeEntity, Constant.FEE_TYPE_BIND_BANK_CARD, session); return null; } }); } } //失败 else{ // throw new BusinessException(ErrorCode.BIND_BANK_CARD_ERROR, "绑卡失败。"); if(ret.get("ERROR_MSG") != null && !"".equals(ret.get("ERROR_MSG").toString())){ throw new BusinessException(ErrorCode.BIND_BANK_CARD_ERROR, ret.get("ERROR_MSG")); }else{ throw new BusinessException(ErrorCode.BIND_BANK_CARD_ERROR, ret.get("RET_MSG")); } } } catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } public void completeOrder(String orderNo, Map<String, Object> param) throws BizException{ logger.info("OrderServiceImpl.completeOrder start"); logger.info("orderNo="+orderNo+"param="+param); final Map<String, Object> order_entity = getOrder(orderNo); final Long tradeType = (Long) order_entity.get("trade_type"); final Long subTradeType = (Long) order_entity.get("sub_trade_type"); final Map<String, Object> _param = param; try{ EntityManagerUtil.execute(new TransactionWork<Object>(){ @Override public Object doTransaction(Session session, Transaction tx) throws Exception { Order order = OrderFactory.getOrder(tradeType, subTradeType); order.completeOrder(order_entity, _param, session); return null; } }); }catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } public Map<String, Object> getOrder(String _orderNo) throws BizException { logger.info("OrderServiceImpl.getOrder start"); try { final String orderNo=_orderNo; Map<String, Object> res= EntityManagerUtil.execute(new QueryWork<Map<String, Object>>() { @Override public Map<String, Object> doQuery(Session session) throws Exception { return Order.getOrder(orderNo, session); } }); return res; } catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } public Map<String, Object> getOrder(Long applicationId,String bizOrderNo) throws BizException{ logger.info("OrderServiceImpl.getOrder start"); try { final Long _applicationId=applicationId; final String _bizOrderNo = bizOrderNo; Map<String, Object> res= EntityManagerUtil.execute(new QueryWork<Map<String, Object>>() { @Override public Map<String, Object> doQuery(Session session) throws Exception { return Order.getOrder(_applicationId,_bizOrderNo, session); } }); return res; } catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } public void updateOrderIP(String _orderNo, String _memberIp)throws BizException { logger.info("OrderServiceImpl.updateOrderIP start"); try { final String orderNo=_orderNo; final String member_ip=_memberIp; EntityManagerUtil.execute(new TransactionWork<Object>() { @Override public Object doTransaction(Session session, Transaction tx) throws Exception { Order.updateOrderIP(orderNo, member_ip, session); return null; } }); } catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } public Map<String, Object> getOrg(String _orgNo) throws BizException { logger.info("OrderServiceImpl.getOrg start"); try { final String orgNo=_orgNo; Map<String, Object> res= EntityManagerUtil.execute(new QueryWork< Map<String, Object> >() { @Override public Map<String, Object> doQuery(Session session) throws Exception { return Order.getOrgByOrgNo(orgNo, session); } }); return res; } catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } /*** * * @Title: getOrgList 获取应用 * @Description: TODO(这里用一句话描述这个方法的作用) * @param @return * @param @throws BizException 设定文件 * @return List 返回类型 * @throws */ public List getOrgList()throws BizException{ logger.info("OrderServiceImpl.getCommand start"); try { List<Map<String, Object>> res= EntityManagerUtil.execute(new QueryWork<List<Map<String, Object>>>() { @Override public List<Map<String, Object>> doQuery(Session session) throws Exception { Query query = session.createQuery("from AMS_Organization where state=1"); return query.list(); } }); return res; } catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } public String getITSBankCode(String bankCode) throws BizException { logger.info("OrderServiceImpl.getITSBankCode start"); try { final String bank_code=bankCode; String res= EntityManagerUtil.execute(new QueryWork<String >() { @Override public String doQuery(Session session) throws Exception { return Order.getITSBankCode(bank_code, session); } }); return res; } catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } public void modifyITSBankSMSSender(Boolean isSmsVerify, String bankCode) throws BizException { logger.info("OrderServiceImpl.modifyITSBankSMSSender start"); try { final String bank_code=bankCode; final boolean is_sms_verify=isSmsVerify; EntityManagerUtil.execute(new TransactionWork<Object>() { @Override public Object doTransaction(Session session, Transaction tx) throws Exception { session.beginTransaction(); Query query = session.createQuery("update AMS_PayInterfaceBank set is_sms_verify=:is_sms_verify where pay_interfaceNo=:pay_interfaceNo and bank_code=:bank_code"); query.setParameter("is_sms_verify", is_sms_verify); query.setParameter("pay_interfaceNo", Constant.PAY_INTERFACE_QUICK); query.setParameter("bank_code", bank_code); query.executeUpdate(); return null; } }); } catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } /** * 外部支付渠道充值 * @param param * @throws Exception */ public void payChannelDeposit(Map<String, Object> param)throws BizException{ logger.info("TradeService payChannelDeposit start"); logger.info("param:" + param); final String orderNo = (String)param.get("orderNo"); //订单号 final Long order_money = (Long)param.get("orderMoney"); //订单金额 final String out_trade_id = (String)param.get("outTradeId"); //外部流水号 final String out_bizno = (String)param.get("out_bizNo"); String pay_channelNo = (String)param.get("payChannelNo"); final String pay_interfaceNo = (String)param.get("payInterfaceNo"); final String bank_code = (String)param.get("bank_code"); final String extend_info = (String)param.get("extend_info"); final Date trade_time = (Date)param.get("tradeTime"); final String remark = (String)param.get("remark"); final Long card_type = (Long)param.get("card_type"); final String biz_orderNo = (String)param.get("biz_orderNo"); final String pay_serialNo = (String)param.get("pay_serialNo"); final int index = orderNo.indexOf(Constant.COMMAND_SPLIT_SIGN); //判断是否多指令集 final Map<String, Object> _param = new HashMap<String, Object>(); Boolean isOK = false; if(orderNo == null) throw new BizException(ErrorCode.PARAM_ERROR, "请传入参数 orderNo"); if(order_money == null) throw new BizException(ErrorCode.PARAM_ERROR, "请传入参数 order_money"); if(out_trade_id == null) throw new BizException(ErrorCode.PARAM_ERROR, "请传入参数 out_trade_id"); if(pay_channelNo == null) throw new BizException(ErrorCode.PARAM_ERROR, "请传入参数 pay_channelNo"); if(pay_interfaceNo == null) throw new BizException(ErrorCode.PARAM_ERROR, "请传入参数 pay_interfaceNo"); if(trade_time == null) throw new BizException(ErrorCode.PARAM_ERROR, "请传入参数 trade_time"); try { logger.info("测试++++++"+LoginSession.isLogined()); if(!LoginSession.isLogined()) LoginSession.backUse(null, Reserved.BACKUSER_ID, Reserved.MAIN_DOMAIN_ID); String order_No = null; Long seq_no = null; if(index >= 0) { order_No = orderNo.substring(0, index); seq_no = Long.parseLong(orderNo.substring(index+1)); } else { order_No = orderNo; seq_no = 1L; } _param.put("order_No", order_No); _param.put("seq_no", seq_no); _param.put("isOK", isOK); EntityManagerUtil.execute(new TransactionWork<String>() { @Override public boolean before(Session session) throws Exception { Map<String, Object> depositParam = new HashMap<String, Object>(); //查询指令 StringBuilder sb = new StringBuilder(); sb.setLength(0); sb.append("from AMS_OrderPayDetail where bizid=:bizid and seq_no=:seq_no and pay_state=:pay_state"); Query query = session.createQuery(sb.toString()); query.setParameter("bizid", _param.get("order_No")); query.setParameter("seq_no", _param.get("seq_no")); query.setParameter("pay_state", com.kinorsoft.ams.Constant.COMMAND_STATE_UNPAY); List list = query.list(); if(list == null || list.isEmpty()) throw new Exception("无此订单号"); Map<String, Object> orderPayDetail_entity = (Map<String, Object>)list.get(0); Long commandId = (Long)orderPayDetail_entity.get("id"); //查询订单 Map<String, Object> order_entity = TradeService.getOrder((String)_param.get("order_No"), session); if(order_entity == null) throw new Exception("无此订单号"); Long orderId = (Long)order_entity.get("id"); Long trade_money = (Long)orderPayDetail_entity.get("trade_money"); if(!order_money.equals(trade_money)) throw new Exception("交易金额不一致"); Long pay_state = (Long)orderPayDetail_entity.get("pay_state"); if(!pay_state.equals(com.kinorsoft.ams.Constant.COMMAND_STATE_UNPAY)) //判断订单状态 throw new Exception("订单非未支付状态"); depositParam.put("source_userId", orderPayDetail_entity.get("source_userId")); depositParam.put("account_type_id", orderPayDetail_entity.get("account_type_id")); depositParam.put("target_account_type_id", orderPayDetail_entity.get("target_account_type_id")); depositParam.put("trade_money", trade_money); depositParam.put("target_userId", orderPayDetail_entity.get("target_userId")); depositParam.put("out_trade_id", out_trade_id); depositParam.put("out_bizno", out_bizno); depositParam.put("bizid", _param.get("order_No")); depositParam.put("command_no", orderNo); depositParam.put("source_memberNo", orderPayDetail_entity.get("source_memberNo")); depositParam.put("target_memberNo", orderPayDetail_entity.get("target_memberNo")); depositParam.put("isMaster", orderPayDetail_entity.get("isMaster")); depositParam.put("orgNo", orderPayDetail_entity.get("orgNo")); depositParam.put("pay_channelNo", orderPayDetail_entity.get("pay_channelNo")); depositParam.put("sub_trade_type", orderPayDetail_entity.get("sub_trade_type")); depositParam.put("source_member_name", orderPayDetail_entity.get("source_member_name")); depositParam.put("target_member_name", orderPayDetail_entity.get("target_member_name")); depositParam.put("pay_interfaceNo", pay_interfaceNo); depositParam.put("bank_code", bank_code); depositParam.put("extend_info", extend_info); depositParam.put("trade_time", trade_time); depositParam.put("remark", remark); depositParam.put("card_type", card_type == null ? order_entity.get("card_type") : card_type); depositParam.put("biz_orderNo", biz_orderNo); depositParam.put("pay_serialNo", pay_serialNo); _param.put("depositParam", depositParam); _param.put("commandId", commandId); return true; } @Override public String doTransaction(Session session, Transaction tx) throws Exception { TradeService.deposit((Map<String, Object>)_param.get("depositParam")); if(index > 0){ //更新交易指令结果 Query query = session.createQuery("update AMS_OrderPayDetail set pay_state=:pay_state,out_trade_id=:outTradeId where id=:commandId"); query.setParameter("pay_state", com.kinorsoft.ams.Constant.COMMAND_STATE_SUCESS); query.setParameter("outTradeId", out_trade_id); query.setParameter("commandId", (Long)_param.get("commandId")); query.executeUpdate(); } _param.put("isOK", true); return orderNo; } }); } catch(BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e){ logger.info(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR, e.getMessage()); } logger.info("isOK="+isOK); logger.info("index="+index); try { if((Boolean)_param.get("isOK")){ if(index > 0) //继续下一条指令 TradeCommandManager.instance().doCommands(orderNo, (Long)_param.get("commandId")); else{ //单指令,触发订单支付完成事件 Event event = new Event(com.kinorsoft.ams.Constant.EVENT_TYPE_ORDERCOMPLETEPAY, param, null); EventManager.instance().fireEvent(event); } } } catch(BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e){ logger.info(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR, e.getMessage()); } } /** * 检查准备金账户手续费 * @param orderNo 要执行的订单号 * @throws BizException */ public void checkAgencyFees(String orderNo) throws BizException { // TODO Auto-generated method stub final String _orderNo = orderNo; try{ EntityManagerUtil.execute(new QueryWork<Boolean>() { @Override public Boolean doQuery(Session session) throws Exception { Map<String,Object> order_entity = Order.getOrder(_orderNo, session); Long fee = Order.getAgencyFees(order_entity, session); logger.info("检测机构手续费fee:"+fee); if(fee > 0){ AccountService accountService = new AccountServiceImpl(); Map<String,Object> application = DynamicEntityService.getEntity((Long)order_entity.get("application_id"), "AMS_Organization"); Map<String,Object> accountType = QueryService.getAccountType(Constant.ACCOUNT_NO_STANDARD_READY); Map<String,Object> accountMap = accountService.getMemberAccountByType((Long)application.get("member_id"), (Long)accountType.get("id")); if(accountMap == null){ throw new BizException(ErrorCode.READ_ACCOUNT_NO_ENOUGH,"准备金账户手续费不足!"); }else{ Long amount = (Long)accountMap.get("amount"); if(amount==null ||amount< fee.longValue()){ throw new BizException(ErrorCode.READ_ACCOUNT_NO_ENOUGH,"准备金账户手续费不足!"); } } } return true; } }); }catch(BizException e){ logger.error(e.getMessage(), e); throw e; }catch(Exception e){ logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } //end } /** * 检查云平台准备金账户手续费 * @param orderNo 要执行的订单号 * @throws BizException */ public void checkYUNAgencyFees(String orderNo) throws BizException { // TODO Auto-generated method stub final String _orderNo = orderNo; try{ EntityManagerUtil.execute(new QueryWork<Boolean>() { @Override public Boolean doQuery(Session session) throws Exception { Map<String,Object> order_entity = Order.getOrder(_orderNo, session); Long fee = Order.getYUNAgencyFees(order_entity, session); logger.info("检测机构手续费fee:"+fee); if(fee > 0){ AccountService accountService = new AccountServiceImpl(); Map<String,Object> application = DynamicEntityService.getEntity((Long)order_entity.get("application_id"), "AMS_Organization"); Map<String,Object> accountType = QueryService.getAccountType(Constant.ACCOUNT_NO_STANDARD_READY); Map<String,Object> accountMap = accountService.getMemberAccountByType((Long)application.get("member_id"), (Long)accountType.get("id")); if(accountMap == null){ throw new BizException(ErrorCode.READ_ACCOUNT_NO_ENOUGH,"准备金账户手续费不足!"); }else{ Long amount = (Long)accountMap.get("amount"); if(amount==null ||amount< fee.longValue()){ throw new BizException(ErrorCode.READ_ACCOUNT_NO_ENOUGH,"准备金账户手续费不足!"); } } } return true; } }); }catch(BizException e){ logger.error(e.getMessage(), e); throw e; }catch(Exception e){ logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } //end } public static void updateBankCardContractNo(Long bankCardId, String contractNo) throws Exception { logger.info("OrderServiceImpl.updateBankCardContractNo start"); try { final Long _bankCardId = bankCardId; final String _contractNo = contractNo; EntityManagerUtil.execute(new TransactionWork<Object>(){ @Override public Object doTransaction(Session session, Transaction tx) throws Exception { Order.updateBankCardContractNo(_bankCardId, _contractNo, session); return null; } }); } catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } @SuppressWarnings("unchecked") public List<Map<String, Object>> getAccountChgDetailList(Long memberId, Map<String, Object> param, Long start, Long end) throws BizException { // TODO Auto-generated method stub try{ logger.info("getAccountChgDetailList start : memberId:"+memberId+",param:"+param+",start:"+start+",end:"+end); Member member = new Member(memberId); final String userId = member.getUserId(); if(userId == null ||"".equals(userId)){ throw new BizException(ErrorCode.PARAM_ERROR, "该用户不存在"); } final Map<String,Object> _param = param; final Long _start = start; final Long _end = end; List<Map<String,Object>> list = EntityManagerUtil.execute(new QueryWork<List<Map<String,Object>>>() { @Override public List<Map<String,Object>> doQuery(Session session) throws Exception { StringBuffer hql = new StringBuffer(); hql.append("from AMS_AccountChgLog where userId=:userId"); if(_param.get("account_type_id")!=null){ hql.append(" and account_type_id=:account_type_id"); } if(_param.get("chg_time_start")!=null){ hql.append(" and chg_time>=:chg_time_start"); } if(_param.get("chg_time_end")!=null){ hql.append(" and chg_time<=:chg_time_end"); } hql.append(" order by chg_time desc"); Query query = session.createQuery(hql.toString()); query.setParameter("userId", userId); if(_param.get("account_type_id")!=null){ query.setParameter("account_type_id", (Long)_param.get("account_type_id")); } if(_param.get("chg_time_start")!=null){ query.setParameter("chg_time_start", (Date)_param.get("chg_time_start")); } if(_param.get("chg_time_end")!=null){ query.setParameter("chg_time_end", (Date)_param.get("chg_time_end")); } query.setFirstResult(_start.intValue()); query.setMaxResults(_end.intValue()); return query.list(); } }); return list; }catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } public Long getAccountChgDetailCount(Long memberId, Map<String, Object> param) throws BizException { // TODO Auto-generated method stub try{ logger.info("getAccountChgDetailCount start : memberId:"+memberId+",param:"+param); Member member = new Member(memberId); final String userId = member.getUserId(); if(userId == null ||"".equals(userId)){ throw new BizException(ErrorCode.PARAM_ERROR, "该用户不存在"); } final Map<String,Object> _param = param; Long ret = EntityManagerUtil.execute(new QueryWork<Long>() { @Override public Long doQuery(Session session) throws Exception { StringBuffer hql = new StringBuffer(); hql.append("select count(*) from AMS_AccountChgLog where userId=:userId"); if(_param.get("account_type_id")!=null){ hql.append(" and account_type_id=:account_type_id"); } if(_param.get("chg_time_start")!=null){ hql.append(" and chg_time>=:chg_time_start"); } if(_param.get("chg_time_end")!=null){ hql.append(" and chg_time<=:chg_time_end"); } Query query = session.createQuery(hql.toString()); query.setParameter("userId", userId); if(_param.get("account_type_id")!=null){ query.setParameter("account_type_id", (Long)_param.get("account_type_id")); } if(_param.get("chg_time_start")!=null){ query.setParameter("chg_time_start", (Date)_param.get("chg_time_start")); } if(_param.get("chg_time_end")!=null){ query.setParameter("chg_time_end", (Date)_param.get("chg_time_end")); } return (Long) query.uniqueResult(); } }); return ret; }catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } @SuppressWarnings("unchecked") public List<Map<String, Object>> getPayOrderList(Long applicationId, Map<String, Object> param, Long start, Long end) throws BizException { // TODO Auto-generated method stub try{ logger.info("getPayOrderList start:applicationId:"+applicationId+",param:"+param+",start:"+start+",end:"+end); final Long _applicationId = applicationId; final Map<String,Object> _param = param; final Long _start = start; final Long _end = end; List<Map<String,Object>> list = EntityManagerUtil.execute(new QueryWork<List<Map<String,Object>>>() { @Override public List<Map<String,Object>> doQuery(Session session) throws Exception { StringBuffer hql = new StringBuffer(); hql.append("from AMS_Order where application_id=:application_id"); if(_param.get("member_id")!=null){ hql.append(" and member_id=:member_id"); } if(_param.get("order_type")!=null){ hql.append(" and order_type=:order_type"); } if(_param.get("order_state")!=null){ hql.append(" and order_state=:order_state"); } if(_param.get("orderNo")!=null){ hql.append(" and orderNo=:orderNo"); } if(_param.get("create_time_start")!=null){ hql.append(" and create_time>=:create_time_start"); } if(_param.get("create_time_end")!=null){ hql.append(" and create_time<=:create_time_end"); } hql.append(" order by create_time desc"); Query query = session.createQuery(hql.toString()); query.setParameter("application_id", _applicationId); if(_param.get("member_id")!=null){ query.setParameter("member_id", (Long)_param.get("member_id")); } if(_param.get("order_type")!=null){ query.setParameter("order_type", (Long)_param.get("order_type")); } if(_param.get("order_state")!=null){ query.setParameter("order_state", (Long)_param.get("order_state")); } if(_param.get("orderNo")!=null){ query.setParameter("orderNo", (String)_param.get("orderNo")); } if(_param.get("create_time_start")!=null){ query.setParameter("create_time_start", (Date)_param.get("create_time_start")); } if(_param.get("create_time_end")!=null){ query.setParameter("create_time_end", (Date)_param.get("create_time_end")); } query.setFirstResult(_start.intValue()); query.setMaxResults(_end.intValue()); return query.list(); } }); return list; }catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } public Long getPayOrderCount(Long applicationId, Map<String, Object> param) throws BizException { // TODO Auto-generated method stub try{ logger.info("getPayOrderCount start:applicationId:"+applicationId+",param:"+param); final Long _applicationId = applicationId; final Map<String,Object> _param = param; Long ret = EntityManagerUtil.execute(new QueryWork<Long>() { @Override public Long doQuery(Session session) throws Exception { StringBuffer hql = new StringBuffer(); hql.append("select count(*) from AMS_Order where application_id=:application_id"); if(_param.get("member_id")!=null){ hql.append(" and member_id=:member_id"); } if(_param.get("order_type")!=null){ hql.append(" and order_type=:order_type"); } if(_param.get("order_state")!=null){ hql.append(" and order_state=:order_state"); } if(_param.get("orderNo")!=null){ hql.append(" and orderNo=:orderNo"); } if(_param.get("create_time_start")!=null){ hql.append(" and create_time>=:create_time_start"); } if(_param.get("create_time_end")!=null){ hql.append(" and create_time<=:create_time_end"); } Query query = session.createQuery(hql.toString()); query.setParameter("application_id", _applicationId); if(_param.get("member_id")!=null){ query.setParameter("member_id", (Long)_param.get("member_id")); } if(_param.get("order_type")!=null){ query.setParameter("order_type", (Long)_param.get("order_type")); } if(_param.get("order_state")!=null){ query.setParameter("order_state", (Long)_param.get("order_state")); } if(_param.get("orderNo")!=null){ query.setParameter("orderNo", (String)_param.get("orderNo")); } if(_param.get("create_time_start")!=null){ query.setParameter("create_time_start", (Date)_param.get("create_time_start")); } if(_param.get("create_time_end")!=null){ query.setParameter("create_time_end", (Date)_param.get("create_time_end")); } return (Long) query.uniqueResult(); } }); return ret; }catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } @SuppressWarnings("unchecked") public List<Map<String, Object>> getPayDetailList(Long orderId) throws BizException { // TODO Auto-generated method stub try{ logger.info("getPayDetailList orderId:"+orderId); final Long _orderId = orderId; List<Map<String,Object>> list = EntityManagerUtil.execute(new QueryWork<List<Map<String,Object>>>() { @Override public List<Map<String,Object>> doQuery(Session session) throws Exception { StringBuffer hql = new StringBuffer(); hql.append("from AMS_PayDetail where pay_order_id=:orderId"); Query query = session.createQuery(hql.toString()); query.setParameter("orderId", _orderId); return query.list(); } }); return list; }catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } /** * MD5签名 * @param param * @return * @throws Exception * @xul */ public String getCertPaySign(Map<String,Object> param)throws BizException{ logger.info("getCertPaySign参数:" + param); String inputCharset = (String)param.get("inputCharset"); String receiveUrl = (String)param.get("receiveUrl"); String version = (String)param.get("version"); String signType = (String)param.get("signType"); String merchantId = (String)param.get("merchantId"); String orderNo = (String)param.get("orderNo"); Long orderAmount = (Long)param.get("orderAmount"); String orderCurrency = (String)param.get("orderCurrency"); String orderDatetime = (String)param.get("orderDatetime"); String productName = (String)param.get("productName"); String payType = (String)param.get("payType"); String cardNo = (String)param.get("cardNo"); String tradeNature = (String)param.get("tradeNature"); Long applicationId = (Long)param.get("applicationId"); Long memberId = (Long)param.get("memberId"); try{ //验证参数 Environment environment = Environment.instance(); if(!environment.getSystemProperty("certPay.receiveUrl").equals(receiveUrl)) throw new BizException(ErrorCode.PARAM_ERROR, "后台回调地址错误"); if(!"0".equals(signType)) throw new BizException(ErrorCode.PARAM_ERROR, "非法签名类型"); if(!("0".equals(orderCurrency) || "156".equals(orderCurrency))) throw new BizException(ErrorCode.PARAM_ERROR, "币种只支持人民币"); Map<String, Object> orderEntity = getOrder(orderNo); logger.info("getOrder返回:" + orderEntity); if(orderEntity == null || orderEntity.isEmpty()){ throw new BizException(ErrorCode.ORDER_NOTEXSIT, "订单不存在。"); } //检查订单是否过期 if(orderEntity.get("ordErexpireDatetime") != null){ Date ordErexpireDatetime = (Date)orderEntity.get("ordErexpireDatetime"); if(ordErexpireDatetime.before(new Date())){ throw new BizException(ErrorCode.ORDER_PASE_DUE, "订单过期。"); } } //检查订单是否处于未支付状态 Long orderState = (Long)orderEntity.get("order_state"); if(!orderState.equals(Constant.ORDER_STATE_WAIT_PAY)){ throw new BizException(ErrorCode.ORDER_NOT_UNPAY, "订单不是未支付状态。"); } Long orderType = (Long)orderEntity.get("order_type"); if(!(Constant.ORDER_TYPE_DAISHOU.equals(orderType) || Constant.ORDER_TYPE_DEPOSIT.equals(orderType) || Constant.ORDER_TYPE_SHOPPING.equals(orderType))) throw new BizException(ErrorCode.ORDER_ERROR, "订单类型错误。"); Long orderMoney = (Long)orderEntity.get("order_money"); //验证金额 if(!orderMoney.equals(orderAmount)) throw new BizException(ErrorCode.ORDER_NOT_UNPAY, "订单金额错误。"); OrderService orderService = new OrderServiceImpl(); Map<String, Object> command = orderService.getAllCommands(orderNo).get(0); //验证支付方式 Long orderPayType = (Long)command.get("pay_type"); if(!(orderPayType == 27)){ throw new BizException(ErrorCode.OTHER_ERROR, "订单支付方式不是移动认证支付。"); } //验证账号 if(!StringUtils.isBlank(cardNo)){ String accountNo = (String)command.get("accountNo"); if(accountNo == null || !accountNo.equals(cardNo)){ throw new BizException(ErrorCode.OTHER_ERROR, "银行卡号和创建订单时不一致。"); } } //获取key Map<String, Object> applicationEntity = DynamicEntityService.getEntity(applicationId, "AMS_Organization"); if(applicationEntity == null || applicationEntity.isEmpty()){ throw new BizException(ErrorCode.APPLICATION_NOTEXSIT, "应用不存在。"); } String orgNo = (String)applicationEntity.get("codeNo"); JSONObject payInterfaceAppConf = new JSONObject(JedisUtils.getCacheByKey(Constant.REDIS_KEY_PI_APP_CONF)); String cacheKey = Constant.PAY_INTERFACE_CERT_PAY + "_" + orgNo; logger.info("cacheKey=" + cacheKey); JSONObject certPayCacheValue = (JSONObject)payInterfaceAppConf.get(cacheKey); if(certPayCacheValue == null || certPayCacheValue.length() == 0){ logger.error("此用户不支持移动认证支付。"); throw new Exception("此用户不支持移动认证支付。"); } String key = (String)certPayCacheValue.get("mobile_cert_pay_key"); logger.info("key=" + key); if(StringUtils.isBlank(key)){ logger.error("密钥为空。"); throw new Exception("密钥为空。"); } //组装数据 StringBuilder sb = new StringBuilder(); String signMsg = ""; sb.append("inputCharset="+inputCharset+"&"); sb.append("receiveUrl="+receiveUrl+"&"); sb.append("version="+version+"&"); sb.append("signType="+signType+"&"); sb.append("merchantId="+merchantId+"&"); sb.append("orderNo="+orderNo+"&"); sb.append("orderAmount="+orderAmount+"&"); sb.append("orderCurrency="+orderCurrency+"&"); sb.append("orderDatetime="+orderDatetime+"&"); sb.append("productName="+productName+"&"); sb.append("payType="+payType+"&"); if(StringUtils.isBlank(tradeNature)) sb.append("tradeNature="+tradeNature+"&"); if(!StringUtils.isBlank(cardNo)) sb.append("cardNo="+cardNo+"&"); logger.info("=====signMsgStr:"+sb.toString()); return (MD5Util.MD5(sb.toString())).toUpperCase(); }catch(BizException e){ logger.error(e.getMessage(), e); throw e; } catch(Exception e){ logger.error(e.getMessage(), e); throw new BizException(ErrorCode.OTHER_ERROR, "其他错误。"); } } /** * 获取所有指令 * @param orderNo * @return * @throws BizException */ public List<Map<String, Object>> getAllCommands(String orderNo) throws BizException{ logger.info("getAllCommands参数orderNo=" + orderNo); final String _orderNo = orderNo; try{ return EntityManagerUtil.execute(new QueryWork<List<Map<String, Object>>>(){ @Override public List<Map<String, Object>> doQuery(Session session) throws Exception { return Order.getCommands(_orderNo, session); } }); }catch(BizException bizE){ logger.error(bizE.getMessage(), bizE); throw bizE; }catch(Exception e){ logger.error(e.getMessage(), e); throw new BizException(ErrorCode.OTHER_ERROR, "其他错误。"); } } @Override public Map<String, Object> getOrderByPos(String posCode) throws Exception { logger.info("--------getOrderByPos begin"); try { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR)-24); Date now = calendar.getTime(); final String _now = sdf.format(now); final String _posCode = posCode; logger.info("posCode:"+posCode); logger.info("now:"+_now); Map<String,Object> ret = EntityManagerUtil.execute(new QueryWork<Map<String,Object>>() { @Override public Map<String, Object> doQuery(Session session) throws Exception { StringBuffer hql = new StringBuffer(); hql.append("select d.trade_money,o.member_name,o.application_id from AMS_Order o, AMS_OrderPayDetail d " + " where o.orderNo = d.bizid and o.pos_pay_code=:posCode and order_state=:order_state and o.create_time >=to_date('"+_now+"', 'yyyy-MM-dd HH24:mi:ss')"); logger.info("sql:"+hql.toString()); Query query = session.createQuery(hql.toString()); query.setParameter("posCode", _posCode); query.setParameter("order_state", Constant.ORDER_STATE_WAIT_PAY); List<Object[]> list = query.list(); if (list.isEmpty() || list.size() <= 0) return null; Object[] temp = list.get(0); //String create_time = (String)temp[0]; Long trade_money = (Long)temp[0]; String member_name = (String)temp[1]; Long application_id = (Long)temp[2]; Double _trade_money = trade_money / 100.00; java.text.DecimalFormat df =new java.text.DecimalFormat("0.00"); Map<String, Object> shop = Appliction.getApplicationMemberEntity(application_id); Map<String, Object> order = new HashMap<>(); order.put("paycode" ,_posCode); order.put("amt", df.format( _trade_money ) ); order.put("name", member_name); order.put("merchantname", shop.get("name")); logger.info("========返回的参数:"+ order+"========="); return order; } }); return ret; } catch(BizException bizE){ logger.error(bizE.getMessage(), bizE); throw bizE; }catch(Exception e){ logger.error(e.getMessage(), e); throw new BizException(ErrorCode.OTHER_ERROR, "其他错误。"); } } @Override public void setPosOrder(Map<String, Object> posOrder) throws Exception { logger.info("OrderServiceImpl.setPosOrder start"); try { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR)-24); Date now = calendar.getTime(); final String _now = sdf.format(now); final String paycode = (String)posOrder.get("paycode"); final String terminal_id = (String)posOrder.get("terminal_id"); final String mcht_cd = (String)posOrder.get("mcht_cd"); EntityManagerUtil.execute(new TransactionWork<Object>() { @Override public Object doTransaction(Session session, Transaction tx) throws Exception { StringBuffer hql = new StringBuffer(); hql.append("select d.id from AMS_Order o, AMS_OrderPayDetail d " + " where o.orderNo = d.bizid and o.pos_pay_code=:posCode and order_state=:order_state and o.create_time >=to_date('"+_now+"', 'yyyy-MM-dd HH24:mi:ss')"); logger.info("sql:"+hql.toString()); Query query = session.createQuery(hql.toString()); query.setParameter("posCode", paycode); query.setParameter("order_state", Constant.ORDER_STATE_WAIT_PAY); List<Object[]> list = query.list(); if (list.isEmpty() || list.size() <= 0) { throw new Exception("订单过期或没有支付码对应的订单。"); } Object detail_id = list.get(0); query = session.createQuery("update AMS_OrderPayDetail " + "set pos_pay_code=:pos_pay_code, terminal_id=:terminal_id, mcht_cd=:mcht_cd \n" + " where id=:id"); query.setParameter("pos_pay_code", paycode); query.setParameter("terminal_id", terminal_id); query.setParameter("mcht_cd", mcht_cd); query.setParameter("id", detail_id); query.executeUpdate(); return null; } }); } catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } /** * pos支付成功回调 * @param posOrder 更新信息 * paycode 支付码 * pay_type 支付方式 * trace_no 凭证号 * refer_no 银行流水号(对账用的) * amt 交易金额 * bank_card_no 银行卡号 * bank_code 银行代码 * terminal_id 终端号 * mcht_cd 商户号 * @throws Exception */ public void setPosOrderAndOver(Map<String, Object> posOrder) throws Exception { logger.info("OrderServiceImpl.setPosOrderAndOver start"); try { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR)-24); Date now = calendar.getTime(); final String _now = sdf.format(now); final String paycode = (String)posOrder.get("paycode"); final String pay_type = (String)posOrder.get("pay_type"); final String trace_no = (String)posOrder.get("trace_no"); final String refer_no = (String)posOrder.get("refer_no"); String amt = (String)posOrder.get("amt"); final String bank_card_no = (String)posOrder.get("bank_card_no"); final String bank_code = (String)posOrder.get("bank_code"); final String terminal_id = (String)posOrder.get("terminal_id"); final String mcht_cd = (String)posOrder.get("mcht_cd"); logger.info("paycode:"+paycode+"--pay_type:"+pay_type+"--trace_no:"+trace_no+"--refer_no:"+refer_no+"--amt:"+amt+"" + "--bank_card_no:"+bank_card_no+"--bank_code:"+bank_code+"--terminal_id:"+terminal_id+"--mcht_cd:"+mcht_cd); Double D_amt = Double.parseDouble(amt); D_amt = D_amt * 100; final Long _amt = D_amt.longValue(); EntityManagerUtil.execute(new TransactionWork<Object>() { @Override public Object doTransaction(Session session, Transaction tx) throws Exception { StringBuffer hql = new StringBuffer(); hql.append("select d.id, d.terminal_id, d.mcht_cd,d.command_no from AMS_Order o, AMS_OrderPayDetail d " + " where o.orderNo = d.bizid and o.pos_pay_code=:posCode and order_state=:order_state and o.create_time >=to_date('"+_now+"', 'yyyy-MM-dd HH24:mi:ss')"); logger.info("sql:"+hql.toString()); Query query = session.createQuery(hql.toString()); query.setParameter("posCode", paycode); query.setParameter("order_state", Constant.ORDER_STATE_WAIT_PAY); List<Object[]> list = query.list(); if (list.isEmpty() || list.size() <= 0){ throw new Exception("订单过期或没有支付码对应的订单。"); } Object[] detail = list.get(0); if( !terminal_id.equals(detail[1]) || !mcht_cd.equals(detail[2])){ logger.error("申请的terminal_id:"+detail[1]+"------mcht_cd:"+detail[2]); throw new Exception("申请和确认支付时的终端号或商户号不一样!"); } hql.setLength(0); hql.append(" update AMS_OrderPayDetail set "); hql.append(" pos_pay_type=:pos_pay_type,"); hql.append(" trace_no=:trace_no,"); hql.append(" refer_no=:refer_no,"); //hql.append(" trade_money=:trade_money,"); hql.append(" accountNo=:bank_card_no,"); hql.append(" bank_code=:bank_code "); hql.append(" where id=:id "); query = session.createQuery(hql.toString()); query.setParameter("pos_pay_type", Long.parseLong(pay_type)); query.setParameter("trace_no", trace_no); query.setParameter("refer_no", refer_no); // query.setParameter("trade_money", _amt); query.setParameter("bank_card_no", bank_card_no); query.setParameter("bank_code", bank_code); query.setParameter("id", detail[0]); query.executeUpdate(); Map<String, Object> param = new HashMap<>(); param.put("orderNo", detail[3]); param.put("orderMoney", _amt); param.put("outTradeId", refer_no); param.put("payChannelNo", Constant.PAY_CHANNEL_POS); param.put("payInterfaceNo", Constant.PAY_INTERFACE_POS); param.put("tradeTime", new Date()); logger.info("payChannelDeposit参数:param=" + param); payChannelDeposit(param); return null; } }); } catch (BizException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.UNKNOWN_ERROR,e.getMessage()); } } /** * 查询标得订单 * @param order_type 订单类型 * @param biz_trade_code 交易码 * @param goodsType 商品类型 * @param goodsNo 商品编码 * @return 标得订单列表 * @throws Exception */ public List<Map<String, Object>> getOrderListByGoods(Long order_type, String biz_trade_code, Long goodsType, String goodsNo, Long orderState) throws Exception { logger.info("getOrderListByGoods参数order_type=" + order_type); final Long _order_type = order_type; final String _biz_trade_code = biz_trade_code; final Long _goodsType = goodsType; final String _goodsNo = goodsNo; final Long _orderState = orderState; try { return EntityManagerUtil.execute(new QueryWork<List<Map<String, Object>>>() { @Override public List<Map<String, Object>> doQuery(Session session) throws Exception { return Order.getOrderListByGoods(_order_type, _biz_trade_code, _goodsType, _goodsNo, _orderState, session); } }); } catch (BizException bizE) { logger.error(bizE.getMessage(), bizE); throw bizE; } catch (Exception e) { logger.error(e.getMessage(), e); throw new BizException(ErrorCode.OTHER_ERROR, "其他错误。"); } } @Override public Map<String, Object> statistics(Long application) throws BizException { return null; } /** * 平台转账 * @param sourceAccountSetNo 源账户集编号 * @param targetMemberId 目标用户id * @param targetAccountSetNo 目标账户集编号 * @param amount 金额 * @param remark 备注 * @param extendInfo 扩展信息 * @return * @throws BizException */ public Map<String, Object> applicationTransfer(String bizTransferNo, Long applicationId, String sourceAccountSetNo, Long targetMemberId, String targetAccountSetNo, Long amount, String remark, String extendInfo) throws BizException { logger.info("transfer参数applicationId=" + applicationId + ",sourceAccountSetNo=" + sourceAccountSetNo + ",targetMemberId=" + targetMemberId + ",targetAccountSetNo=" + targetAccountSetNo + ",amount=" + amount + ",remark=" + remark + ",extendInfo=" + extendInfo); try{ //检查参数 if(applicationId == null || applicationId == 0) throw new BizException(ErrorCode.PARAM_ERROR_NULL, "applicationId不能为空。"); if(StringUtils.isBlank(sourceAccountSetNo)) throw new BizException(ErrorCode.PARAM_ERROR_NULL, "sourceAccountSetNo不能为空。"); if(targetMemberId == null || targetMemberId == 0) throw new BizException(ErrorCode.PARAM_ERROR_NULL, "targetMemberId不能为空。"); if(StringUtils.isBlank(targetAccountSetNo)) throw new BizException(ErrorCode.PARAM_ERROR_NULL, "targetAccountSetNo不能为空。"); if(amount == null || amount == 0) throw new BizException(ErrorCode.PARAM_ERROR_NULL, "amount不能为空或者0。"); //目前只支持从平台的保证金账户或者营销专用账户转出 if(!Constant.ACCOUNT_NO_STANDARD_BOND.equals(sourceAccountSetNo) && !Constant.ACCOUNT_NO_COUPON.equals(sourceAccountSetNo)){ throw new BizException(ErrorCode.ACCOUNT_TYPE_ERROR, "目前只支持从保证金账户或者营销专用账户转出。"); } Map<String, Object> applicationEntity = DynamicEntityService.getEntity(applicationId, "AMS_Organization"); if(applicationEntity == null || applicationEntity.isEmpty()) throw new BizException(ErrorCode.APPLICATION_NOTEXSIT, "应用不存在。"); Map<String, Object> sourceMemberEntity = DynamicEntityService.getEntity((Long)applicationEntity.get("member_id"), "AMS_Member"); if(sourceMemberEntity == null || sourceMemberEntity.isEmpty()) throw new BizException(ErrorCode.USER_NOTEXSIT, "应用用户不存在。"); Map<String, Object> targetMemberEntity = DynamicEntityService.getEntity(targetMemberId, "AMS_Member"); if(targetMemberEntity == null || targetMemberEntity.isEmpty()) throw new BizException(ErrorCode.USER_NOTEXSIT, "目标用户不存在。"); //监测商户系统转账编号是否唯一 final String _sourceUserId = (String)sourceMemberEntity.get("userId"); final String _outBizno = bizTransferNo; List tradeLoglist = EntityManagerUtil.execute(new QueryWork<List<Map<String, Object>>>(){ @Override public List<Map<String, Object>> doQuery(Session session) throws Exception { return (List<Map<String, Object>>)Order.getTradeLog(Constant.TRADE_TYPE_TRANSFER, Constant.SUB_TRADE_TYPE_APPLICATION, _sourceUserId, _outBizno, session); } }); if(!(tradeLoglist == null || tradeLoglist.isEmpty())){ throw new BizException(ErrorCode.OTHER_ERROR, "商户系统转账编号已经存在。"); } AccountService accountService = new AccountServiceImpl(); Map<String, Object> sourceAccountTypeEntity = accountService.getAccountTypeByNo(sourceAccountSetNo); Map<String, Object> targetAccountTypeEntity = accountService.getAccountTypeByNo(targetAccountSetNo); //获取云账户平台转账编号 String bizid = CodeUtil.getCode(Constant.CODE_PREFIX_APPLICATION_TRANSFER, Constant.CODE_TYPE_APPLICATION_TRANSFER, Constant.CODE_LENGTH_APPLICATION_TRANSFER); //组装信息 Map<String, Object> param = new HashMap<String, Object>(); param.put("source_userId", (String)sourceMemberEntity.get("userId")); param.put("source_memberNo", (String)sourceMemberEntity.get("memberNo")); param.put("source_member_name", (String)sourceMemberEntity.get("name")); param.put("target_userId", (String)targetMemberEntity.get("userId")); param.put("target_memberNo", (String)targetMemberEntity.get("memberNo")); param.put("target_member_name", (String)targetMemberEntity.get("name")); param.put("trade_type", Constant.TRADE_TYPE_TRANSFER); param.put("sub_trade_type", Constant.SUB_TRADE_TYPE_APPLICATION); param.put("trade_money", amount); param.put("bizid", bizid); param.put("out_bizno", bizTransferNo); param.put("remark", remark); param.put("account_type_id", (Long)sourceAccountTypeEntity.get("id")); param.put("target_account_type_id", (Long)targetAccountTypeEntity.get("id")); param.put("isMaster", true); param.put("pay_interfaceNo", Constant.PAY_INTERFACE_AMS); param.put("isMaster", true); param.put("orgNo", (String)applicationEntity.get("codeNo")); //调用自定义转账 TradeService.customTransfer(param); Map<String, Object> ret = new HashMap<String, Object>(); ret.put("transferNo", bizid); return ret; }catch(BizException e){ logger.error(e.getMessage(), e); throw e; }catch(Exception e){ logger.error(e.getMessage(), e); throw new BizException(ErrorCode.OTHER_ERROR, e.getMessage()); } } }
[ "742590394@qq.com" ]
742590394@qq.com
bcb3426f662eafc63a375a5964e218be7ce0ff29
a6805b548abbab89a2b3c66000ea9e7f3677e51b
/app/src/main/java/br/pro/adalto/applistacompras/FormularioActivity.java
ab8e7cb51de720d87c4a75eb309ff9b3b2b0efdc
[]
no_license
alinnezanin/ListaCompras
71cab83b737fb46d4873895627ca8f408086e390
895557910220b5e7b22128d5d20a892e3210d17c
refs/heads/master
2021-09-28T08:14:54.605603
2018-11-15T17:43:26
2018-11-15T17:43:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,618
java
package br.pro.adalto.applistacompras; import android.content.DialogInterface; import android.graphics.Color; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import java.util.List; import br.pro.adalto.applistacompras.dao.CategoriaDAO; import br.pro.adalto.applistacompras.dao.ProdutoDAO; import br.pro.adalto.applistacompras.model.Categoria; import br.pro.adalto.applistacompras.model.Produto; public class FormularioActivity extends AppCompatActivity { private Spinner spCategoria; private ArrayAdapter adapter; private List<Categoria> listaDeCategorias; private EditText etNome, etQuantidade; private Button btnSalvar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_formulario); etNome = (EditText) findViewById(R.id.etNomeProduto); etQuantidade = (EditText) findViewById(R.id.etQuantidade); btnSalvar = (Button) findViewById(R.id.btnSalvar); spCategoria = (Spinner) findViewById(R.id.spCategoria); carregarCategorias(); btnSalvar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { salvarProduto(); } }); } private void salvarProduto(){ String nome = etNome.getText().toString(); if ( nome.isEmpty() || spCategoria.getSelectedItemPosition() == 0 ){ AlertDialog.Builder alerta = new AlertDialog.Builder(this); alerta.setTitle(getResources().getString(R.string.txtAtencao)); alerta.setIcon( android.R.drawable.ic_dialog_alert ); alerta.setMessage( R.string.txtCamposObrigatorios ); alerta.setNeutralButton("OK", null); alerta.show(); }else { Produto prod = new Produto(); prod.setNome( nome ); String quantidade = etQuantidade.getText().toString(); double qtd = 0; if( ! quantidade.isEmpty() ){ quantidade = quantidade.replace("," , "."); qtd = Double.valueOf( quantidade ); } prod.setQuantidade(qtd); prod.setCategoria( (Categoria) spCategoria.getSelectedItem() ); ProdutoDAO.inserir(this, prod); finish(); } } private void carregarCategorias(){ listaDeCategorias = CategoriaDAO.getCategorias(this); Categoria fake = new Categoria(); fake.setId(0); fake.setNome( getResources().getString(R.string.txtSelecione) ); listaDeCategorias.add(0 , fake); adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1 , listaDeCategorias ); spCategoria.setAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_formulario, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if( item.getItemId() == R.id.menu_nova_categoria ){ AlertDialog.Builder alerta = new AlertDialog.Builder(FormularioActivity.this); alerta.setTitle( getResources().getString(R.string.txtNovaCategoria)); alerta.setIcon( android.R.drawable.ic_menu_edit ); final EditText nomeCat = new EditText(FormularioActivity.this); nomeCat.setHint(R.string.hintCategoria); nomeCat.setTextColor(Color.BLUE); alerta.setView(nomeCat); alerta.setNeutralButton("Cancelar", null); alerta.setPositiveButton(getResources().getString(R.string.txtSalvar), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Categoria cat = new Categoria(); cat.setNome( nomeCat.getText().toString() ); CategoriaDAO.inserir(FormularioActivity.this, cat); carregarCategorias(); } }); alerta.show(); } return super.onOptionsItemSelected(item); } }
[ "alinnezanin@gmail.com" ]
alinnezanin@gmail.com
41d2e58c00b882653b5677899b733a6d78a95ad8
90136278c6877319930114fcb03b29c925eb0191
/patienttracker/src/main/java/com/patienttracker/daoimpl/PrescriptionDaoImpl.java
f156ebcc87b906207e96b59baf96b4b96151a3e1
[]
no_license
kumaranM25/PatientTracker
aa2969b0aafa6ce1e90331923e1ddecc15e0b724
d68bc165c1361ad25155522a4a401ebaef816ece
refs/heads/master
2022-12-21T13:29:42.464923
2020-02-19T11:13:02
2020-02-19T11:13:02
240,263,125
1
0
null
2022-12-16T03:47:47
2020-02-13T13:10:11
Java
UTF-8
Java
false
false
2,360
java
package com.patienttracker.daoimpl; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; import com.patienttracker.dao.PrescriptionDao; import com.patienttracker.model.Clerk; import com.patienttracker.model.Prescription; @Repository public class PrescriptionDaoImpl implements PrescriptionDao { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public void addPrescription(Prescription prescription) { // TODO Auto-generated method stub Session session = this.sessionFactory.getCurrentSession(); session.persist(prescription); System.out.println("Prescription details saved successfully, Prescription Details=" + prescription); } public void updatePrescription(Prescription prescription) { // TODO Auto-generated method stub Session session = this.sessionFactory.getCurrentSession(); session.update(prescription); System.out.println("prescription updated successfully, prescription Details=" + prescription); } @SuppressWarnings("unchecked") public List<Prescription> listPrescription() { // TODO Auto-generated method stub Session session = this.sessionFactory.getCurrentSession(); List<Prescription> prescriptionList = session.createQuery("from Prescription").list(); for (Prescription prescription : prescriptionList) { System.out.println("Prescription List::" + prescription); } return prescriptionList; } public Prescription getPrescriptionByRequestID(int requestID) { Session session = this.sessionFactory.getCurrentSession(); Prescription prescription = (Prescription) session.load(Prescription.class, new Integer(requestID)); System.out.println("Prescription loaded successfully, Prescription details=" + prescription); return prescription; } public void removePrescription(int requestID) { // TODO Auto-generated method stub Session session = this.sessionFactory.getCurrentSession(); Prescription prescription = (Prescription) session.load(Prescription.class, new Integer(requestID)); if (null != prescription) { session.delete(prescription); } System.out.println("prescription deleted successfully, prescription details=" + prescription); } }
[ "KuldipKumarD@DS-PB02PYNR.HCLT.CORP.HCL.IN" ]
KuldipKumarD@DS-PB02PYNR.HCLT.CORP.HCL.IN
90f5062c58e0660278e9613480a6384197e904b9
a82d6698f653535dc291227748b7b165796a16f4
/src/com/hzerai/db/prototypes/factory/Prototype5.java
3c83ad8491f83276cbb9d78c3cfb1a9408fba2f1
[]
no_license
hzerai/dynamic-beans
b0bcddeb701cddb60ffd98e4f3c09bdfaeba0259
8d8584b7eef55a27be9a9e5aeeeeac2b068643b2
refs/heads/master
2023-08-11T12:16:20.614154
2021-09-30T12:17:26
2021-09-30T12:17:26
389,306,255
0
0
null
null
null
null
UTF-8
Java
false
false
180
java
/** * */ package com.hzerai.db.prototypes.factory; import com.hzerai.db.prototypes.Prototype; /** * @author Habib Zerai * */ public class Prototype5 extends Prototype { }
[ "hpiplolz@gmail.com" ]
hpiplolz@gmail.com
3f17aba2cc85e53a15f047929e2c2d336d74995e
3cf37989d9cd0d3ebc68b4ced7e60f7bb07a4ec0
/Week03/day02/gradle-test/src/main/java/util/Fibonacci.java
f8830cf840143e83131c43c33f10b6fb1b39ad66
[ "Apache-2.0" ]
permissive
SimonaMueh/PropulsionCourse
cd35e228f409a59e2f8d8ae9d64adf3d168c2ce6
1171e468adb9fc7d519fa927d17997da629c43ad
refs/heads/master
2021-06-18T08:27:41.742588
2017-06-16T15:24:37
2017-06-16T15:24:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
497
java
package util; public class Fibonacci { static int fibonacci(int n) { if (n == 0) { return 0; } else if (n == 1) { return 1; } return fibonacci(n - 1) + fibonacci(n - 2); } public static void main(String[] args) { System.out.println(fibonacci(0)); // 0 System.out.println(fibonacci(1)); // 1 System.out.println(fibonacci(2)); // 1 System.out.println(fibonacci(3)); // 2 System.out.println(fibonacci(7)); // 13 System.out.println(fibonacci(12)); // 144 } }
[ "alles0815@gmx.ch" ]
alles0815@gmx.ch
10475a9cf49eac45fd14896d6473fa4fbddc9926
2ddf32ab42b8ea1e901595b8d45fd19f5e840ae7
/sample/src/main/java/com/ahamed/sample/payload/PayloadActivity.java
41caab02fd5500f41725b531a23c7dfc89bc6658
[ "Apache-2.0" ]
permissive
HelloWmz/MultiViewAdapter
7ef3636b14cf1718eb3c5c182228f26e81982a3c
12e6f62dffc8dee19278b357d6189b4c4747b204
refs/heads/master
2020-12-02T18:10:34.067957
2017-07-05T19:19:32
2017-07-05T19:19:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,147
java
/* * Copyright 2017 Riyaz Ahamed * * 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.ahamed.sample.payload; import android.content.Context; import android.content.Intent; import android.support.annotation.LayoutRes; import android.support.v7.widget.LinearLayoutManager; import android.view.View; import android.widget.Toast; import com.ahamed.multiviewadapter.DataListManager; import com.ahamed.multiviewadapter.RecyclerAdapter; import com.ahamed.multiviewadapter.util.PayloadProvider; import com.ahamed.multiviewadapter.util.SimpleDividerDecoration; import com.ahamed.sample.R; import com.ahamed.sample.common.BaseActivity; import com.ahamed.sample.common.model.Flower; import java.util.ArrayList; import java.util.List; import java.util.Random; import static com.ahamed.multiviewadapter.util.SimpleDividerDecoration.VERTICAL; public class PayloadActivity extends BaseActivity { private Random random = new Random(); private DataListManager<Flower> dataListManager; private int itemIndex = 0; public static void start(Context context) { Intent starter = new Intent(context, PayloadActivity.class); context.startActivity(starter); } @Override public void setContentView(@LayoutRes int layoutResID) { super.setContentView(R.layout.activity_payload); } @Override protected void setUpAdapter() { RecyclerAdapter recyclerAdapter = new RecyclerAdapter(); dataListManager = new DataListManager<>(recyclerAdapter, new PayloadProvider<Flower>() { @Override public boolean areContentsTheSame(Flower oldItem, Flower newItem) { return oldItem.getFlowerId() == newItem.getFlowerId(); } @Override public Object getChangePayload(Flower oldItem, Flower newItem) { return newItem.getFlowerName(); } }); recyclerAdapter.registerBinder( new FlowerBinderWithPayload(new SimpleDividerDecoration(this, VERTICAL))); recyclerAdapter.addDataManager(dataListManager); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(linearLayoutManager); recyclerView.addItemDecoration(recyclerAdapter.getItemDecorationManager()); recyclerView.setAdapter(recyclerAdapter); List<Flower> dataList = new ArrayList<>(); for (; itemIndex < 3; itemIndex++) { dataList.add(new Flower(itemIndex, "Flower " + itemIndex)); } dataListManager.set(dataList); } public void add(View view) { Flower flower = new Flower(itemIndex, "Flower " + itemIndex); //if (random.nextBoolean()) { dataListManager.add(flower); //} else { // int indexToAdd = random.nextInt(dataListManager.getCount() - 1); // dataListManager.add(indexToAdd, flower); //} itemIndex++; } public void remove(View view) { if (dataListManager.getCount() == 0) { Toast.makeText(this, "No items in adapter to remove!", Toast.LENGTH_SHORT).show(); return; } if (random.nextBoolean()) { dataListManager.remove(0); } else { int indexToRemove = random.nextInt(dataListManager.getCount() - 1); dataListManager.remove(indexToRemove); } } public void update(View view) { if (dataListManager.getCount() == 0) { Toast.makeText(this, "No items in adapter to update!", Toast.LENGTH_SHORT).show(); return; } int indexToUpdate = random.nextBoolean() ? 0 : random.nextInt(dataListManager.getCount() - 1); Flower flower = dataListManager.get(indexToUpdate); flower.setFlowerName("Updated Flower " + flower.getFlowerId()); dataListManager.set(indexToUpdate, flower); } }
[ "dev.ahamed@gmail.com" ]
dev.ahamed@gmail.com
0fdcd8bc475554bbc5bf46ef89eb80f444248d1a
93d95d8ef14bf7da75ed409aabe8904993ad2f32
/MegaDriver.java
b0711f101ae748a9c0a4b24230ff1e1690151875
[]
no_license
SonOfJ/MKS21X-WordSearch
282c6ffd2f8ffb27d604f15f07e630833fbcfb6a
4c9a0dd6ef93542a2af7c433b340e3dac7ef4fb3
refs/heads/master
2020-04-05T06:49:18.963956
2018-11-19T21:02:28
2018-11-19T21:02:28
156,652,629
0
0
null
null
null
null
UTF-8
Java
false
false
30,071
java
public class MegaDriver { public static void main(String[] args) { WordSearch WSe = new WordSearch(10,14,"words.txt"); System.out.println("WordSearch WSe = new WordSearch(10,14,\"words.txt\")"); System.out.println(WSe); /* |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"CLOUD\",0,2,0,0)"); if(WSe.addWord("CLOUD",0,2,0,0)) { System.out.println("> addition success."); System.out.println("> TEST CASE - FAIL"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - PASS"); } // > addition failure. // should fail, rowIncrement and colIncrement both equal 0 System.out.println(WSe); /* |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"CLOUD\",0,2,0,1)"); if(WSe.addWord("CLOUD",0,2,0,1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - PASS"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - FAIL"); } // > addition success. // should succeed, CLOUD is within bounds, no destructive interference System.out.println(WSe); /* |_ _ C L O U D _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"CLOUD\",0,0,0,1)"); if(WSe.addWord("CLOUD",0,0,0,1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - FAIL"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - PASS"); } // > addition failure. // should fail, CLOUD is within bounds, yes destructive interference System.out.println(WSe); /* |_ _ C L O U D _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"TIFA\",1,3,0,-1)"); if(WSe.addWord("TIFA",1,3,0,-1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - PASS"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - FAIL"); } // > addition success. // should succeed, TIFA is within bounds, no destructive interference System.out.println(WSe); /* |_ _ C L O U D _ _ _ _ _ _ _| |A F I T _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"TIFA\",1,5,0,-1)"); if(WSe.addWord("TIFA",1,5,0,-1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - FAIL"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - PASS"); } // > addition failure. // should fail, TIFA is within bounds, yes destructive interference System.out.println(WSe); /* |_ _ C L O U D _ _ _ _ _ _ _| |A F I T _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"AERITH\",0,10,0,1)"); if(WSe.addWord("AERITH",0,10,0,1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - FAIL"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - PASS"); } // > addition failure. // should fail, AERITH is out of bounds System.out.println(WSe); /* |_ _ C L O U D _ _ _ _ _ _ _| |A F I T _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"AERITH\",2,3,0,-1)"); if(WSe.addWord("AERITH",2,3,0,-1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - FAIL"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - PASS"); } // > addition failure. // should fail, AERITH is out of bounds System.out.println(WSe); /* |_ _ C L O U D _ _ _ _ _ _ _| |A F I T _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"BARRET\",0,8,1,0)"); if(WSe.addWord("BARRET",0,8,1,0)) { System.out.println("> addition success."); System.out.println("> TEST CASE - PASS"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - FAIL"); } // > addition success. // should succeed, BARRET is within bounds, no destructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ _ _ _ A _ _ _ _ _| |_ _ _ _ _ _ _ _ R _ _ _ _ _| |_ _ _ _ _ _ _ _ R _ _ _ _ _| |_ _ _ _ _ _ _ _ E _ _ _ _ _| |_ _ _ _ _ _ _ _ T _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"YUFFIE\",0,0,1,0)"); if(WSe.addWord("YUFFIE",0,0,1,0)) { System.out.println("> addition success."); System.out.println("> TEST CASE - FAIL"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - PASS"); } // > addition failure. // should fail, YUFFIE is within bounds, yes destructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ _ _ _ A _ _ _ _ _| |_ _ _ _ _ _ _ _ R _ _ _ _ _| |_ _ _ _ _ _ _ _ R _ _ _ _ _| |_ _ _ _ _ _ _ _ E _ _ _ _ _| |_ _ _ _ _ _ _ _ T _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"YUFFIE\",6,5,-1,0)"); if(WSe.addWord("YUFFIE",6,5,-1,0)) { System.out.println("> addition success."); System.out.println("> TEST CASE - PASS"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - FAIL"); } // > addition success. // should succeed, YUFFIE is within bounds, no destructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E _ _ A _ _ _ _ _| |_ _ _ _ _ I _ _ R _ _ _ _ _| |_ _ _ _ _ F _ _ R _ _ _ _ _| |_ _ _ _ _ F _ _ E _ _ _ _ _| |_ _ _ _ _ U _ _ T _ _ _ _ _| |_ _ _ _ _ Y _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"YUFFIE\",5,2,-1,0)"); if(WSe.addWord("YUFFIE",5,2,-1,0)) { System.out.println("> addition success."); System.out.println("> TEST CASE - FAIL"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - PASS"); } // > addition failure. // should fail, YUFFIE is within bounds, yes destructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E _ _ A _ _ _ _ _| |_ _ _ _ _ I _ _ R _ _ _ _ _| |_ _ _ _ _ F _ _ R _ _ _ _ _| |_ _ _ _ _ F _ _ E _ _ _ _ _| |_ _ _ _ _ U _ _ T _ _ _ _ _| |_ _ _ _ _ Y _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"AERITH\",8,0,1,0)"); if(WSe.addWord("AERITH",8,0,1,0)) { System.out.println("> addition success."); System.out.println("> TEST CASE - FAIL"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - PASS"); } // > addition failure. // should fail, AERITH is out of bounds System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E _ _ A _ _ _ _ _| |_ _ _ _ _ I _ _ R _ _ _ _ _| |_ _ _ _ _ F _ _ R _ _ _ _ _| |_ _ _ _ _ F _ _ E _ _ _ _ _| |_ _ _ _ _ U _ _ T _ _ _ _ _| |_ _ _ _ _ Y _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"AERITH\",2,10,-1,0)"); if(WSe.addWord("AERITH",2,10,-1,0)) { System.out.println("> addition success."); System.out.println("> TEST CASE - FAIL"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - PASS"); } // > addition failure. // should fail, AERITH is out of bounds System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E _ _ A _ _ _ _ _| |_ _ _ _ _ I _ _ R _ _ _ _ _| |_ _ _ _ _ F _ _ R _ _ _ _ _| |_ _ _ _ _ F _ _ E _ _ _ _ _| |_ _ _ _ _ U _ _ T _ _ _ _ _| |_ _ _ _ _ Y _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"TIFA\",2,4,0,1)"); if(WSe.addWord("TIFA",2,4,0,1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - PASS"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - FAIL"); } // > addition success. // should succeed, TIFA is within bounds, only constructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E _ _ A _ _ _ _ _| |_ _ _ _ T I F A R _ _ _ _ _| |_ _ _ _ _ F _ _ R _ _ _ _ _| |_ _ _ _ _ F _ _ E _ _ _ _ _| |_ _ _ _ _ U _ _ T _ _ _ _ _| |_ _ _ _ _ Y _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"TIFA\",3,7,0,-1)"); if(WSe.addWord("TIFA",3,7,0,-1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - PASS"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - FAIL"); } // > addition success. // should succeed, TIFA is within bounds, only constructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E _ _ A _ _ _ _ _| |_ _ _ _ T I F A R _ _ _ _ _| |_ _ _ _ A F I T R _ _ _ _ _| |_ _ _ _ _ F _ _ E _ _ _ _ _| |_ _ _ _ _ U _ _ T _ _ _ _ _| |_ _ _ _ _ Y _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"AERITH\",1,0,1,0)"); if(WSe.addWord("AERITH",1,0,1,0)) { System.out.println("> addition success."); System.out.println("> TEST CASE - PASS"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - FAIL"); } // > addition success. // should succeed, AERITH is within bounds, only constructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E _ _ A _ _ _ _ _| |E _ _ _ T I F A R _ _ _ _ _| |R _ _ _ A F I T R _ _ _ _ _| |I _ _ _ _ F _ _ E _ _ _ _ _| |T _ _ _ _ U _ _ T _ _ _ _ _| |H _ _ _ _ Y _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"VINCENT\",7,3,-1,0)"); if(WSe.addWord("VINCENT",7,3,-1,0)) { System.out.println("> addition success."); System.out.println("> TEST CASE - PASS"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - FAIL"); } // > addition success. // should succeed, VINCENT is within bounds, only constructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E _ _ A _ _ _ _ _| |E _ _ N T I F A R _ _ _ _ _| |R _ _ E A F I T R _ _ _ _ _| |I _ _ C _ F _ _ E _ _ _ _ _| |T _ _ N _ U _ _ T _ _ _ _ _| |H _ _ I _ Y _ _ _ _ _ _ _ _| |_ _ _ V _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"CAIT\",6,1,1,1)"); if(WSe.addWord("CAIT",6,1,1,1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - PASS"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - FAIL"); } // > addition success. // should succeed, CAIT is within bounds, no destructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E _ _ A _ _ _ _ _| |E _ _ N T I F A R _ _ _ _ _| |R _ _ E A F I T R _ _ _ _ _| |I _ _ C _ F _ _ E _ _ _ _ _| |T _ _ N _ U _ _ T _ _ _ _ _| |H C _ I _ Y _ _ _ _ _ _ _ _| |_ _ A V _ _ _ _ _ _ _ _ _ _| |_ _ _ I _ _ _ _ _ _ _ _ _ _| |_ _ _ _ T _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"CID\",9,2,-1,-1)"); if(WSe.addWord("CID",9,2,-1,-1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - PASS"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - FAIL"); } // > addition success. // should succeed, CID is within bounds, no destructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E _ _ A _ _ _ _ _| |E _ _ N T I F A R _ _ _ _ _| |R _ _ E A F I T R _ _ _ _ _| |I _ _ C _ F _ _ E _ _ _ _ _| |T _ _ N _ U _ _ T _ _ _ _ _| |H C _ I _ Y _ _ _ _ _ _ _ _| |D _ A V _ _ _ _ _ _ _ _ _ _| |_ I _ I _ _ _ _ _ _ _ _ _ _| |_ _ C _ T _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"CID\",6,2,1,-1)"); if(WSe.addWord("CID",6,2,1,-1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - PASS"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - FAIL"); } // > addition success. // should succeed, CID is within bounds, no destructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E _ _ A _ _ _ _ _| |E _ _ N T I F A R _ _ _ _ _| |R _ _ E A F I T R _ _ _ _ _| |I _ _ C _ F _ _ E _ _ _ _ _| |T _ _ N _ U _ _ T _ _ _ _ _| |H C C I _ Y _ _ _ _ _ _ _ _| |D I A V _ _ _ _ _ _ _ _ _ _| |D I _ I _ _ _ _ _ _ _ _ _ _| |_ _ C _ T _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"CID\",9,3,-1,1)"); if(WSe.addWord("CID",9,3,-1,1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - PASS"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - FAIL"); } // > addition success. // should succeed, CID is within bounds, no destructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E _ _ A _ _ _ _ _| |E _ _ N T I F A R _ _ _ _ _| |R _ _ E A F I T R _ _ _ _ _| |I _ _ C _ F _ _ E _ _ _ _ _| |T _ _ N _ U _ _ T _ _ _ _ _| |H C C I _ Y _ _ _ _ _ _ _ _| |D I A V _ D _ _ _ _ _ _ _ _| |D I _ I I _ _ _ _ _ _ _ _ _| |_ _ C C T _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"REDXIII\",1,11,1,1)"); if(WSe.addWord("REDXIII",1,11,1,1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - FAIL"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - PASS"); } // > addition failure. // should fail, REDXIII is out of bounds System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E _ _ A _ _ _ _ _| |E _ _ N T I F A R _ _ _ _ _| |R _ _ E A F I T R _ _ _ _ _| |I _ _ C _ F _ _ E _ _ _ _ _| |T _ _ N _ U _ _ T _ _ _ _ _| |H C C I _ Y _ _ _ _ _ _ _ _| |D I A V _ D _ _ _ _ _ _ _ _| |D I _ I I _ _ _ _ _ _ _ _ _| |_ _ C C T _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"REDXIII\",1,11,-1,-1)"); if(WSe.addWord("REDXIII",1,11,-1,-1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - FAIL"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - PASS"); } // > addition failure. // should fail, REDXIII is out of bounds System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E _ _ A _ _ _ _ _| |E _ _ N T I F A R _ _ _ _ _| |R _ _ E A F I T R _ _ _ _ _| |I _ _ C _ F _ _ E _ _ _ _ _| |T _ _ N _ U _ _ T _ _ _ _ _| |H C C I _ Y _ _ _ _ _ _ _ _| |D I A V _ D _ _ _ _ _ _ _ _| |D I _ I I _ _ _ _ _ _ _ _ _| |_ _ C C T _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"REDXIII\",8,11,1,-1)"); if(WSe.addWord("REDXIII",8,11,-1,-1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - FAIL"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - PASS"); } // > addition failure. // should fail, REDXIII is out of bounds System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E _ _ A _ _ _ _ _| |E _ _ N T I F A R _ _ _ _ _| |R _ _ E A F I T R _ _ _ _ _| |I _ _ C _ F _ _ E _ _ _ _ _| |T _ _ N _ U _ _ T _ _ _ _ _| |H C C I _ Y _ _ _ _ _ _ _ _| |D I A V _ D _ _ _ _ _ _ _ _| |D I _ I I _ _ _ _ _ _ _ _ _| |_ _ C C T _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"REDXIII\",1,11,-1,1)"); if(WSe.addWord("REDXIII",1,11,-1,1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - FAIL"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - PASS"); } // > addition failure. // should fail, REDXIII is out of bounds System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E _ _ A _ _ _ _ _| |E _ _ N T I F A R _ _ _ _ _| |R _ _ E A F I T R _ _ _ _ _| |I _ _ C _ F _ _ E _ _ _ _ _| |T _ _ N _ U _ _ T _ _ _ _ _| |H C C I _ Y _ _ _ _ _ _ _ _| |D I A V _ D _ _ _ _ _ _ _ _| |D I _ I I _ _ _ _ _ _ _ _ _| |_ _ C C T _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"BARRET\",1,6,1,1)"); if(WSe.addWord("BARRET",1,6,1,1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - PASS"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - FAIL"); } // > addition success. // should succeed, BARRET is within bounds, only constructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E B _ A _ _ _ _ _| |E _ _ N T I F A R _ _ _ _ _| |R _ _ E A F I T R _ _ _ _ _| |I _ _ C _ F _ _ E R _ _ _ _| |T _ _ N _ U _ _ T _ E _ _ _| |H C C I _ Y _ _ _ _ _ T _ _| |D I A V _ D _ _ _ _ _ _ _ _| |D I _ I I _ _ _ _ _ _ _ _ _| |_ _ C C T _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"TIFA\",7,4,-1,-1)"); if(WSe.addWord("TIFA",7,4,-1,-1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - PASS"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - FAIL"); } // > addition success. // should succeed, TIFA is within bounds, only constructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E B _ A _ _ _ _ _| |E _ _ N T I F A R _ _ _ _ _| |R _ _ E A F I T R _ _ _ _ _| |I A _ C _ F _ _ E R _ _ _ _| |T _ F N _ U _ _ T _ E _ _ _| |H C C I _ Y _ _ _ _ _ T _ _| |D I A V T D _ _ _ _ _ _ _ _| |D I _ I I _ _ _ _ _ _ _ _ _| |_ _ C C T _ _ _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"AERITH\",4,11,1,-1)"); if(WSe.addWord("AERITH",4,11,1,-1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - PASS"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - FAIL"); } // > addition success. // should succeed, AERITH is within bounds, only constructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ _ _ _| |A F I T _ E B _ A _ _ _ _ _| |E _ _ N T I F A R _ _ _ _ _| |R _ _ E A F I T R _ _ _ _ _| |I A _ C _ F _ _ E R _ A _ _| |T _ F N _ U _ _ T _ E _ _ _| |H C C I _ Y _ _ _ R _ T _ _| |D I A V T D _ _ I _ _ _ _ _| |D I _ I I _ _ T _ _ _ _ _ _| |_ _ C C T _ H _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"BARRET\",5,6,-1,1)"); if(WSe.addWord("BARRET",5,6,-1,1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - PASS"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - FAIL"); } // > addition success. // should succeed, BARRET is within bounds, only constructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ T _ _| |A F I T _ E B _ A _ E _ _ _| |E _ _ N T I F A R R _ _ _ _| |R _ _ E A F I T R _ _ _ _ _| |I A _ C _ F _ A E R _ A _ _| |T _ F N _ U B _ T _ E _ _ _| |H C C I _ Y _ _ _ R _ T _ _| |D I A V T D _ _ I _ _ _ _ _| |D I _ I I _ _ T _ _ _ _ _ _| |_ _ C C T _ H _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"ZACK\",4,4,1,1)"); if(WSe.addWord("ZACK",4,4,1,1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - FAIL"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - PASS"); } // > addition failure. // should fail, ZACK is within bounds, yes destructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ T _ _| |A F I T _ E B _ A _ E _ _ _| |E _ _ N T I F A R R _ _ _ _| |R _ _ E A F I T R _ _ _ _ _| |I A _ C _ F _ A E R _ A _ _| |T _ F N _ U B _ T _ E _ _ _| |H C C I _ Y _ _ _ R _ T _ _| |D I A V T D _ _ I _ _ _ _ _| |D I _ I I _ _ T _ _ _ _ _ _| |_ _ C C T _ H _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"ZACK\",4,4,-1,-1)"); if(WSe.addWord("ZACK",4,4,-1,-1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - FAIL"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - PASS"); } // > addition failure. // should fail, ZACK is within bounds, yes destructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ T _ _| |A F I T _ E B _ A _ E _ _ _| |E _ _ N T I F A R R _ _ _ _| |R _ _ E A F I T R _ _ _ _ _| |I A _ C _ F _ A E R _ A _ _| |T _ F N _ U B _ T _ E _ _ _| |H C C I _ Y _ _ _ R _ T _ _| |D I A V T D _ _ I _ _ _ _ _| |D I _ I I _ _ T _ _ _ _ _ _| |_ _ C C T _ H _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"ZACK\",4,4,1,-1)"); if(WSe.addWord("ZACK",4,4,1,-1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - FAIL"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - PASS"); } // > addition failure. // should fail, ZACK is within bounds, yes destructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ T _ _| |A F I T _ E B _ A _ E _ _ _| |E _ _ N T I F A R R _ _ _ _| |R _ _ E A F I T R _ _ _ _ _| |I A _ C _ F _ A E R _ A _ _| |T _ F N _ U B _ T _ E _ _ _| |H C C I _ Y _ _ _ R _ T _ _| |D I A V T D _ _ I _ _ _ _ _| |D I _ I I _ _ T _ _ _ _ _ _| |_ _ C C T _ H _ _ _ _ _ _ _| */ System.out.println("WSe.addWord(\"ZACK\",4,4,-1,1)"); if(WSe.addWord("ZACK",4,4,-1,1)) { System.out.println("> addition success."); System.out.println("> TEST CASE - FAIL"); } else { System.out.println("> addition failure."); System.out.println("> TEST CASE - PASS"); } // > addition failure. // should fail, ZACK is within bounds, yes destructive interference System.out.println(WSe); /* |_ _ C L O U D _ B _ _ T _ _| |A F I T _ E B _ A _ E _ _ _| |E _ _ N T I F A R R _ _ _ _| |R _ _ E A F I T R _ _ _ _ _| |I A _ C _ F _ A E R _ A _ _| |T _ F N _ U B _ T _ E _ _ _| |H C C I _ Y _ _ _ R _ T _ _| |D I A V T D _ _ I _ _ _ _ _| |D I _ I I _ _ T _ _ _ _ _ _| |_ _ C C T _ H _ _ _ _ _ _ _| */ if(args.length == 2) { WordSearch WSe2 = new WordSearch(Integer.parseInt(args[0]),Integer.parseInt(args[1]),"words.txt"); System.out.println("WordSearch WSe2 = new WordSearch(args[0],args[1],\"words.txt\")"); System.out.println(WSe2); /* example: java Driver_Test 10 12 |_ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _| example: java Driver_Test 3 5 |_ _ _ _ _| |_ _ _ _ _| |_ _ _ _ _| example: java Driver_Test 6 6 |_ _ _ _ _ _| |_ _ _ _ _ _| |_ _ _ _ _ _| |_ _ _ _ _ _| |_ _ _ _ _ _| |_ _ _ _ _ _| */ WSe2.addAllWords(); System.out.println(WSe2); // hopefully filled WordSearch } else if(args.length == 1) { System.out.println("MISSING INPUT:\nDriver_Test class needs terminal line args:"); System.out.println("- int rows [FOUND]\n- int cols [NOT FOUND]"); } else if(args.length == 0) { System.out.println("MISSING INPUT:\nDriver_Test class needs terminal line args:"); System.out.println("- int rows [NOT FOUND]\n- int cols [NOT FOUND]"); } else { System.out.println("INVALID INPUT:\nDriver_Test class only needs 2 int terminal line args"); } /* A spectre is haunting Europe — the spectre of communism. All the powers of old Europe have entered into a holy alliance to exorcise this spectre: Pope and Tsar, Metternich and Guizot, French Radicals and German police-spies. Where is the party in opposition that has not been decried as communistic by its opponents in power? Where is the opposition that has not hurled back the branding reproach of communism, against the more advanced opposition parties, as well as against its reactionary adversaries? Two things result from this fact: I. Communism is already acknowledged by all European powers to be itself a power. II. It is high time that Communists should openly, in the face of the whole world, publish their views, their aims, their tendencies, and meet this nursery tale of the Spectre of Communism with a manifesto of the party itself. To this end, Communists of various nationalities have assembled in London and sketched the following manifesto, to be published in the English, French, German, Italian, Flemish and Danish languages. */ } }
[ "zzheng3@stuy.edu" ]
zzheng3@stuy.edu
3abdae1ac515cd07433081f49c553f89085165c3
72e5e440b18211a7a533edc32f391a1846fdadca
/Doubly Linked List/testDLinkedList.java
cb2a0cb38e3e44257cf6a5e723397e7ffdac7734
[]
no_license
tanisha-bhadani/Hacktoberfest2021
297d40c9368e78ffa87eb859117fadc2c7506f61
b2454a395082f2b1dce5b04752524b31563ed84d
refs/heads/master
2023-08-17T22:01:05.278571
2021-10-18T18:41:47
2021-10-18T18:41:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
827
java
class testDLinkedList{ public static void main(String args[]){ DLinkedList list = new DLinkedList(); list.insertFirst(10); list.insertFirst(20); list.insertFirst(30); list.insertFirst(70); list.insertFirst(80); list.insertFirst(90); list.insertEnd(40); list.printList(); System.out.println(); Node n1 = new Node(20); list.insertAfter(n1, 100); list.printList(); System.out.println(); Node n2 = new Node(30); list.printFrom(n2); System.out.println(); Node n3 = list.removeFirst(); System.out.println(n3.data); list.printList(); System.out.println(); Node n4 = list.removeLast(); System.out.println(n4.data); System.out.println(); list.printList(); System.out.println(); list.removeAfter(n1); list.printList(); } }
[ "tanishabhadanianve@gmail.com" ]
tanishabhadanianve@gmail.com
eaa6c7a4f017a7806a0190ec5341f41b34a06b64
136c13d0af9edcf35cbaf2ef23e316f9cd75de72
/lojinha/src/lojinha/Item.java
cef9c702126a34e2337b9099a4de746e53d61d94
[]
no_license
doug337/lojin
1e255e40b35b0e75d5bf812e98e535bc955357f7
1c3be7472498fd35f8c0f60477ad99dc55455282
refs/heads/master
2021-01-01T19:41:00.138072
2017-08-04T12:28:05
2017-08-04T12:28:05
98,647,685
0
0
null
null
null
null
UTF-8
Java
false
false
838
java
/* * 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 lojinha; /** * * @author aluno */ public class Item { /** * @return the quantidade */ public int getQuantidade() { return quantidade; } /** * @param quantidade the quantidade to set */ public void setQuantidade(int quantidade) { this.quantidade = quantidade; } /** * @return the subtotal */ public float getSubtotal() { return subtotal; } /** * @param subtotal the subtotal to set */ public void setSubtotal(float subtotal) { this.subtotal = subtotal; } private int quantidade; private float subtotal; }
[ "douglasreislima337@gmail.com" ]
douglasreislima337@gmail.com
a709507b010b7c59c2f72fe297a49742795e848f
0ff9b865e8db69ec62433528b049f2a51c052c00
/itsv/src/main/java/com/data/itsv/mapper/SConGroupOrdAlarmResMapper.java
5cdbb482973a868c7f014d78bc143cc70c017410
[]
no_license
yangshichao123/itsv
3bd369c0c0b721792b1a6ed4a91845d8e7dcb0e4
517a72e1835138dac2c1397ad35906284b30755d
refs/heads/master
2023-03-03T02:46:55.372575
2021-02-07T03:30:14
2021-02-07T03:30:14
329,769,003
0
0
null
null
null
null
UTF-8
Java
false
false
364
java
package com.data.itsv.mapper; import com.data.itsv.base.BaseMapper; import com.data.itsv.model.SConGroupOrdAlarmRes; public interface SConGroupOrdAlarmResMapper extends BaseMapper<SConGroupOrdAlarmRes> { int insert(SConGroupOrdAlarmRes record); int insertSelective(SConGroupOrdAlarmRes record); SConGroupOrdAlarmRes selectByPrimaryId(Integer id); }
[ "“xxxxxx@449155439@" ]
“xxxxxx@449155439@
252e2a3d747e0f5b19bd6ba9a056b1c931916f42
2529e8040ca696fe665227ea551c20d0479c4f07
/src/main/java/net/simpleframework/lib/org/mvel2/integration/impl/StackDemarcResolverFactory.java
ecba4656d2ad2914fd5b309a3970f2eba886ef64
[]
no_license
toinfinity/simple-common
38bc3363118c74612b6f236ff0e66d63c0fb91bc
98c3e2b7add307ba79c6fcb90ebea07a5e19b200
refs/heads/master
2021-01-15T14:59:04.923879
2015-11-16T08:14:19
2015-11-16T08:14:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,675
java
package net.simpleframework.lib.org.mvel2.integration.impl; import java.util.Set; import net.simpleframework.lib.org.mvel2.integration.VariableResolver; import net.simpleframework.lib.org.mvel2.integration.VariableResolverFactory; /** * @author Mike Brock */ public class StackDemarcResolverFactory implements VariableResolverFactory { private final VariableResolverFactory delegate; private boolean tilt = false; public StackDemarcResolverFactory(final VariableResolverFactory delegate) { this.delegate = delegate; } @Override public VariableResolver createVariable(final String name, final Object value) { return delegate.createVariable(name, value); } @Override public VariableResolver createIndexedVariable(final int index, final String name, final Object value) { return delegate.createIndexedVariable(index, name, value); } @Override public VariableResolver createVariable(final String name, final Object value, final Class<?> type) { return delegate.createVariable(name, value, type); } @Override public VariableResolver createIndexedVariable(final int index, final String name, final Object value, final Class<?> typee) { return delegate.createIndexedVariable(index, name, value, typee); } @Override public VariableResolver setIndexedVariableResolver(final int index, final VariableResolver variableResolver) { return delegate.setIndexedVariableResolver(index, variableResolver); } @Override public VariableResolverFactory getNextFactory() { return delegate.getNextFactory(); } @Override public VariableResolverFactory setNextFactory(final VariableResolverFactory resolverFactory) { return delegate.setNextFactory(resolverFactory); } @Override public VariableResolver getVariableResolver(final String name) { return delegate.getVariableResolver(name); } @Override public VariableResolver getIndexedVariableResolver(final int index) { return delegate.getIndexedVariableResolver(index); } @Override public boolean isTarget(final String name) { return delegate.isTarget(name); } @Override public boolean isResolveable(final String name) { return delegate.isResolveable(name); } @Override public Set<String> getKnownVariables() { return delegate.getKnownVariables(); } @Override public int variableIndexOf(final String name) { return delegate.variableIndexOf(name); } @Override public boolean isIndexedFactory() { return delegate.isIndexedFactory(); } @Override public boolean tiltFlag() { return tilt; } @Override public void setTiltFlag(final boolean tilt) { this.tilt = tilt; } public VariableResolverFactory getDelegate() { return delegate; } }
[ "cknet@126.com" ]
cknet@126.com
1ec6f12f0284660b809cdb9d12bc4ad5fa865bbb
64b94a2617a9bbc8ece9af486b756e7f51330570
/src/main/java/com/blog/sys/common/utils/AddressUtils.java
cd9f807f3dd4f7092d43fe8441f12695cee8d5eb
[]
no_license
yanakai/blog
c072a478ff4c873f7d65a3a02654afb6adbf1c3e
0c846f512ac3b4a671939bc8c201c90f6f45b095
refs/heads/master
2022-07-30T16:29:47.719874
2020-03-30T08:15:49
2020-03-30T08:15:49
210,007,199
4
1
null
2022-06-17T02:37:55
2019-09-21T15:18:28
JavaScript
UTF-8
Java
false
false
1,429
java
package com.blog.sys.common.utils; import com.blog.sys.common.config.Global; import com.blog.sys.common.http.HttpUtils; import com.blog.sys.common.json.JSON; import com.blog.sys.common.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 获取地址类 * */ public class AddressUtils { private static final Logger log = LoggerFactory.getLogger(AddressUtils.class); public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php"; public static String getRealAddressByIP(String ip){ String address = "XX XX"; // 内网不查询 if (IpUtils.internalIp(ip)){ return "内网IP"; } if (Global.isAddressEnabled()){ String rspStr = HttpUtils.sendPost(IP_URL, "ip=" + ip); if (StringUtils.isEmpty(rspStr)) { log.error("获取地理位置异常 {}", ip); return address; } JSONObject obj; try{ obj = JSON.unmarshal(rspStr, JSONObject.class); JSONObject data = obj.getObj("data"); String region = data.getStr("region"); String city = data.getStr("city"); address = region + " " + city; }catch (Exception e){ log.error("获取地理位置异常 {}", ip); } } return address; } }
[ "yanakai@126.com" ]
yanakai@126.com