blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
269ebe3a6ad57ddf322bb890874002226334902a
18,116,172,064,714
ac1cbcd992cee06e6efb6cb2ee61490b2a9ae42d
/common/buildcraft/transport/utils/FacadeMatrix.java
179382f5e09f0560e16470dba11577715f3a130f
[]
no_license
ReikaKalseki/BuildCraft
https://github.com/ReikaKalseki/BuildCraft
bbd664a76c2b97bd75c7c350e8e486d215682301
87cd9220b8859523bcb4e90249c0f61e0b91e4b5
refs/heads/master
2021-01-24T02:31:24.975000
2014-09-02T21:15:01
2014-09-02T21:15:01
13,462,085
2
0
null
true
2014-09-02T21:15:02
2013-10-10T04:35:20
2014-01-04T13:06:43
2014-09-02T21:15:01
7,425
0
0
0
Java
null
null
/** * Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team * http://www.mod-buildcraft.com * * BuildCraft is distributed under the terms of the Minecraft Mod Public * License 1.0, or MMPL. Please check the contents of the license located in * http://www.mod-buildcraft.com/MMPL-1.0.txt */ package buildcraft.transport.utils; import io.netty.buffer.ByteBuf; import net.minecraft.block.Block; import net.minecraftforge.common.util.ForgeDirection; public class FacadeMatrix { private final Block[] blocks = new Block[ForgeDirection.VALID_DIRECTIONS.length]; private final int[] blockMetas = new int[ForgeDirection.VALID_DIRECTIONS.length]; private boolean dirty = false; public FacadeMatrix() { } public void setFacade(ForgeDirection direction, Block block, int blockMeta) { if (blocks[direction.ordinal()] != block || blockMetas[direction.ordinal()] != blockMeta) { blocks[direction.ordinal()] = block; blockMetas[direction.ordinal()] = blockMeta; dirty = true; } } public Block getFacadeBlock(ForgeDirection direction) { return blocks[direction.ordinal()]; } public int getFacadeMetaId(ForgeDirection direction) { return blockMetas[direction.ordinal()]; } public boolean isDirty() { return dirty; } public void clean() { dirty = false; } public void writeData(ByteBuf data) { for (int i = 0; i < ForgeDirection.VALID_DIRECTIONS.length; i++) { if (blocks [i] == null) { data.writeShort(0); } else { data.writeShort(Block.blockRegistry.getIDForObject(blocks[i])); } data.writeByte(blockMetas[i]); } } public void readData(ByteBuf data) { for (int i = 0; i < ForgeDirection.VALID_DIRECTIONS.length; i++) { short id = data.readShort(); Block block; if (id == 0) { block = null; } else { block = (Block) Block.blockRegistry.getObjectById(id); } if (blocks[i] != block) { blocks[i] = block; dirty = true; } byte meta = data.readByte(); if (blockMetas[i] != meta) { blockMetas[i] = meta; dirty = true; } } } }
UTF-8
Java
2,066
java
FacadeMatrix.java
Java
[]
null
[]
/** * Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team * http://www.mod-buildcraft.com * * BuildCraft is distributed under the terms of the Minecraft Mod Public * License 1.0, or MMPL. Please check the contents of the license located in * http://www.mod-buildcraft.com/MMPL-1.0.txt */ package buildcraft.transport.utils; import io.netty.buffer.ByteBuf; import net.minecraft.block.Block; import net.minecraftforge.common.util.ForgeDirection; public class FacadeMatrix { private final Block[] blocks = new Block[ForgeDirection.VALID_DIRECTIONS.length]; private final int[] blockMetas = new int[ForgeDirection.VALID_DIRECTIONS.length]; private boolean dirty = false; public FacadeMatrix() { } public void setFacade(ForgeDirection direction, Block block, int blockMeta) { if (blocks[direction.ordinal()] != block || blockMetas[direction.ordinal()] != blockMeta) { blocks[direction.ordinal()] = block; blockMetas[direction.ordinal()] = blockMeta; dirty = true; } } public Block getFacadeBlock(ForgeDirection direction) { return blocks[direction.ordinal()]; } public int getFacadeMetaId(ForgeDirection direction) { return blockMetas[direction.ordinal()]; } public boolean isDirty() { return dirty; } public void clean() { dirty = false; } public void writeData(ByteBuf data) { for (int i = 0; i < ForgeDirection.VALID_DIRECTIONS.length; i++) { if (blocks [i] == null) { data.writeShort(0); } else { data.writeShort(Block.blockRegistry.getIDForObject(blocks[i])); } data.writeByte(blockMetas[i]); } } public void readData(ByteBuf data) { for (int i = 0; i < ForgeDirection.VALID_DIRECTIONS.length; i++) { short id = data.readShort(); Block block; if (id == 0) { block = null; } else { block = (Block) Block.blockRegistry.getObjectById(id); } if (blocks[i] != block) { blocks[i] = block; dirty = true; } byte meta = data.readByte(); if (blockMetas[i] != meta) { blockMetas[i] = meta; dirty = true; } } } }
2,066
0.67909
0.671346
85
23.305882
24.705334
93
false
false
0
0
0
0
0
0
2
false
false
11
ea692ccf51896db3fa11ba6d40373fde7357ee32
3,977,139,763,567
eb4fa239230156e0e0acb42d87edd94d61f635bd
/src/main/java/com/master/washcloth/pojo/MessageTable.java
0621e263ebf242994dcf73946eaf8fc63612cb4c
[]
no_license
qiaoguangtong/washcloth
https://github.com/qiaoguangtong/washcloth
0b1187b9676b5c03336662043b4ed0a9bd12933c
361101a25c4eaf6b4fab6b7269056f53dfd0a619
refs/heads/master
2021-05-26T02:37:08.600000
2020-04-08T08:05:58
2020-04-08T08:05:58
254,018,705
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.master.washcloth.pojo; import java.util.Date; public class MessageTable { private Integer id; private Integer userId; private String messageType; private String messageContent; private String messageReply; private Date messageTime; private String state; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getMessageType() { return messageType; } public void setMessageType(String messageType) { this.messageType = messageType == null ? null : messageType.trim(); } public String getMessageContent() { return messageContent; } public void setMessageContent(String messageContent) { this.messageContent = messageContent == null ? null : messageContent.trim(); } public String getMessageReply() { return messageReply; } public void setMessageReply(String messageReply) { this.messageReply = messageReply == null ? null : messageReply.trim(); } public Date getMessageTime() { return messageTime; } public void setMessageTime(Date messageTime) { this.messageTime = messageTime; } public String getState() { return state; } public void setState(String state) { this.state = state == null ? null : state.trim(); } }
UTF-8
Java
1,553
java
MessageTable.java
Java
[]
null
[]
package com.master.washcloth.pojo; import java.util.Date; public class MessageTable { private Integer id; private Integer userId; private String messageType; private String messageContent; private String messageReply; private Date messageTime; private String state; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getMessageType() { return messageType; } public void setMessageType(String messageType) { this.messageType = messageType == null ? null : messageType.trim(); } public String getMessageContent() { return messageContent; } public void setMessageContent(String messageContent) { this.messageContent = messageContent == null ? null : messageContent.trim(); } public String getMessageReply() { return messageReply; } public void setMessageReply(String messageReply) { this.messageReply = messageReply == null ? null : messageReply.trim(); } public Date getMessageTime() { return messageTime; } public void setMessageTime(Date messageTime) { this.messageTime = messageTime; } public String getState() { return state; } public void setState(String state) { this.state = state == null ? null : state.trim(); } }
1,553
0.6349
0.6349
75
19.719999
20.92371
84
false
false
0
0
0
0
0
0
0.306667
false
false
11
5de9d7e43a9b939a84d67a59be208432c50b3dcb
3,977,139,760,968
fd77508dc3317509743ec8adcff9e59e07cf2934
/Adventurer/src/test/pdc/command/FakeBuildingDisplayCiv.java
25fa4249cf0839827cdca662115ab1c8bca24b4f
[]
no_license
Carolla/Adventurer
https://github.com/Carolla/Adventurer
111156826b8ec303b2c67fb3597ca8ff7a9e1f1f
5aab2f640c3ee3c8080a2edd467d4b0789336ca5
refs/heads/master
2020-05-21T23:09:18.734000
2018-06-16T20:24:56
2018-06-16T20:24:56
22,960,004
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test.pdc.command; import chronos.pdc.buildings.Building; import civ.BuildingDisplayCiv; public class FakeBuildingDisplayCiv extends BuildingDisplayCiv { public FakeBuildingDisplayCiv() { super(new FakeMainframeCiv(), null, null); } private String _currentBuildingName = ""; public boolean _canApproach = true; public boolean _canEnter = true; public String _displayedBldg = ""; public String _displayedImg = ""; public String _displayedText = ""; @Override public void enterBuilding(String name) { _currentBuildingName = name; _insideBldg = true; } public void setBuilding(Building bldg) { _currentBldg = bldg; _currentBuildingName = bldg.getName(); enterBuilding(_currentBuildingName); } @Override public boolean approachBuilding(String bldg) { if (_currentBuildingName.isEmpty()) { _currentBuildingName = bldg; _insideBldg = false; return true; } else { _currentBuildingName = bldg; _insideBldg = false; return _currentBuildingName.equals(bldg); } } public void setBuildingName(String name) { _currentBuildingName = name; } @Override public void returnToTown() { super.returnToTown(); _currentBuildingName = null; } @Override public String getCurrentBuilding() { return _currentBuildingName; } @Override public boolean canApproach(String bldgParm) { return _canApproach; } @Override public boolean canEnter(String bldgParm) { return _canEnter; } @Override public String inspectTarget(String target) { String result = super.inspectTarget(target); _displayedText = result; return result; } @Override public void displayBuildingInterior() { super.displayBuildingInterior(); _displayedText = ((FakeMainframeCiv) _mfCiv)._text.get(0); } @Override public boolean talkToTarget(String target) { if (super.talkToTarget(target)) { _displayedText = ((FakeMainframeCiv) _mfCiv)._text.get(0); return true; } else { return false; } } @Override public void openTown() { _insideBldg = false; _currentBldg = null; _currentBuildingName = ""; } }
UTF-8
Java
2,336
java
FakeBuildingDisplayCiv.java
Java
[]
null
[]
package test.pdc.command; import chronos.pdc.buildings.Building; import civ.BuildingDisplayCiv; public class FakeBuildingDisplayCiv extends BuildingDisplayCiv { public FakeBuildingDisplayCiv() { super(new FakeMainframeCiv(), null, null); } private String _currentBuildingName = ""; public boolean _canApproach = true; public boolean _canEnter = true; public String _displayedBldg = ""; public String _displayedImg = ""; public String _displayedText = ""; @Override public void enterBuilding(String name) { _currentBuildingName = name; _insideBldg = true; } public void setBuilding(Building bldg) { _currentBldg = bldg; _currentBuildingName = bldg.getName(); enterBuilding(_currentBuildingName); } @Override public boolean approachBuilding(String bldg) { if (_currentBuildingName.isEmpty()) { _currentBuildingName = bldg; _insideBldg = false; return true; } else { _currentBuildingName = bldg; _insideBldg = false; return _currentBuildingName.equals(bldg); } } public void setBuildingName(String name) { _currentBuildingName = name; } @Override public void returnToTown() { super.returnToTown(); _currentBuildingName = null; } @Override public String getCurrentBuilding() { return _currentBuildingName; } @Override public boolean canApproach(String bldgParm) { return _canApproach; } @Override public boolean canEnter(String bldgParm) { return _canEnter; } @Override public String inspectTarget(String target) { String result = super.inspectTarget(target); _displayedText = result; return result; } @Override public void displayBuildingInterior() { super.displayBuildingInterior(); _displayedText = ((FakeMainframeCiv) _mfCiv)._text.get(0); } @Override public boolean talkToTarget(String target) { if (super.talkToTarget(target)) { _displayedText = ((FakeMainframeCiv) _mfCiv)._text.get(0); return true; } else { return false; } } @Override public void openTown() { _insideBldg = false; _currentBldg = null; _currentBuildingName = ""; } }
2,336
0.638699
0.637842
112
18.839285
17.423073
64
false
false
0
0
0
0
0
0
0.357143
false
false
11
3983ae45be3e5d0b722d370c2b13afe371fdff80
3,590,592,674,795
a5d9095b664f4aa9116e526b08f5517e269d6a75
/manager/src/main/java/com/caicai/ottx/manager/controller/autokeeper/form/ZookeeperForm.java
94a99f4b4314cd911c2fb99f40cb5b49a279862c
[]
no_license
ranqiqiang/dayu
https://github.com/ranqiqiang/dayu
dbc852d26c47af3002d7ada90c9b2da9e6b2b257
d597957c8618028e47b78ec10aeeb494ecc4510a
refs/heads/master
2022-11-14T07:32:55.891000
2019-11-29T08:16:15
2019-11-29T08:16:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.caicai.ottx.manager.controller.autokeeper.form; import com.caicai.ottx.manager.controller.BaseForm; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.List; /** * Created by huaseng on 2019/9/2. */ @Data @EqualsAndHashCode(callSuper = true) public class ZookeeperForm extends BaseForm { private Long id; private List<String> serverList; private String clusterName; private String description; }
UTF-8
Java
447
java
ZookeeperForm.java
Java
[ { "context": "shCode;\n\nimport java.util.List;\n\n/**\n * Created by huaseng on 2019/9/2.\n */\n@Data\n@EqualsAndHashCode(callSup", "end": 216, "score": 0.9985213279724121, "start": 209, "tag": "USERNAME", "value": "huaseng" } ]
null
[]
package com.caicai.ottx.manager.controller.autokeeper.form; import com.caicai.ottx.manager.controller.BaseForm; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.List; /** * Created by huaseng on 2019/9/2. */ @Data @EqualsAndHashCode(callSuper = true) public class ZookeeperForm extends BaseForm { private Long id; private List<String> serverList; private String clusterName; private String description; }
447
0.767338
0.753915
19
22.526316
18.423008
59
false
false
0
0
0
0
0
0
0.473684
false
false
11
1061c44d54e24b2ce830e6bcb8ce93d7c86e9409
29,102,698,412,099
3b6bbc401351f23105060f03ee89c0d64035a5be
/MetaVisualizer/src/main/java/com/entoptic/metaVisualizer/user/MV_Display.java
96f54b8165dfc7e735a379ae2d98dca9552330ab
[ "Apache-2.0" ]
permissive
spatialized/MetaVisualizer
https://github.com/spatialized/MetaVisualizer
45f35d98c250746b0c4dfaed2c760eb650168f3d
9818de99e3599a7890443a72d917b3119eab4cb7
refs/heads/master
2021-03-27T16:51:22.181000
2018-10-19T00:49:23
2018-10-19T00:49:23
69,623,774
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main.java.com.entoptic.metaVisualizer.user; import java.awt.Image; import java.awt.image.BufferedImage; import java.util.ArrayList; import main.java.com.entoptic.metaVisualizer.MetaVisualizer; import main.java.com.entoptic.metaVisualizer.media.WMV_Image; import main.java.com.entoptic.metaVisualizer.media.WMV_Panorama; import main.java.com.entoptic.metaVisualizer.media.WMV_Video; import main.java.com.entoptic.metaVisualizer.misc.WMV_Utilities; import main.java.com.entoptic.metaVisualizer.model.WMV_Cluster; import main.java.com.entoptic.metaVisualizer.model.WMV_Date; import main.java.com.entoptic.metaVisualizer.model.WMV_Time; import main.java.com.entoptic.metaVisualizer.model.WMV_TimeSegment; import main.java.com.entoptic.metaVisualizer.model.WMV_Timeline; import main.java.com.entoptic.metaVisualizer.system.MV_Library; import main.java.com.entoptic.metaVisualizer.world.WMV_Field; import main.java.com.entoptic.metaVisualizer.world.WMV_World; import processing.core.*; /*********************************** * Object for displaying 2D text, maps and graphics * @author davidgordon */ public class MV_Display { /* Classes */ public MetaVisualizer mv; public MV_Window window; /* Main interaction window */ public MV_Map map2D; private WMV_Utilities utilities; /* Utility methods */ /* Display View */ private int displayView = 0; /* {0: Scene 1: Map 2: Library 3: Timeline 4: Media} */ /* Debug */ public boolean drawForceVector = false; /* Setup */ private boolean worldSetup = true; public boolean dataFolderFound = false; public float setupProgress = 0.f; /* Window Behavior */ public boolean disableLostFocusHook = false; /* Buttons */ ArrayList<MV_Button> buttons; public float buttonWidth, buttonHeight; public float buttonSpacing; /* Graphics */ private PMatrix3D originalMatrix; /* For restoring 3D view after 2D HUD */ private float currentFieldOfView; public boolean drawGrid = false; /* Draw 3D grid */ // -- Unused private final float hudDistanceInit = -1000.f; /* Distance of the Heads-Up Display from the virtual camera */ private float messageHUDDistance = hudDistanceInit * 6.f; private int screenWidth = -1, screenHeight = -1; /* Display dimensions */ private int windowWidth = -1, windowHeight = -1; /* Window dimensions */ public int blendMode = 0; /* Alpha blending mode */ // private final int numBlendModes = 10; /* Number of blending modes */ // PImage startupImage; private float hudLeftMargin, hudCenterXOffset, hudRightMargin, hudTopMargin; private float displayWidthFactor; /* Map View */ private boolean setupMapView = false; public int mapViewMode = 1; // 0: World, 1: Field, (2: Cluster -- In progress) public boolean initializedMaps = false; public boolean initializedSatelliteMap = false; MV_Button btnFieldMode, btnWorldMode; MV_Button btnZoomToField, btnZoomToWorld, btnZoomToCluster; MV_Button btnZoomMapIn, btnZoomMapOut; MV_Button btnPanMapUp, btnPanMapDown; MV_Button btnPanMapLeft, btnPanMapRight; private final float imageHue = 140.f; private final float panoramaHue = 190.f; private final float videoHue = 100.f; private final float soundHue = 40.f; /* Time View */ private boolean setupTimeView = false; private float timelineScreenSize, timelineHeight; private float timelineStart = 0.f, timelineEnd = 0.f; private float datelineStart = 0.f, datelineEnd = 0.f; public int displayDate = -1; public boolean updateCurrentSelectableTimeSegment = true, updateCurrentSelectableDate = true; MV_Button btnScrollLeft, btnScrollRight; MV_Button btnTimelineZoomIn, btnTimelineZoomOut; MV_Button btnZoomToFit, btnZoomToSelection, btnZoomToCurrentDate, btnZoomToTimeline; private ArrayList<SelectableTimeSegment> selectableTimeSegments; // Selectable time segments on timeline private ArrayList<SelectableDate> selectableDates; // Selectable dates on dateline private SelectableDate allDates; private final float minSegmentSeconds = 15.f; private boolean fieldTimelineCreated = false, fieldDatelineCreated = false, updateFieldTimeline = true; private float timelineXOffset = 0.f, timelineYOffset = 0.f, datelineYOffset = 0.f; private SelectableTimeSegment currentSelectableTimeSegment; private int selectedTime = -1, selectedCluster = -1, currentSelectableTimeSegmentID = -1, currentSelectableTimeSegmentFieldTimeSegmentID = -1; private int selectedDate = -1, currentSelectableDate = -1; private boolean timelineTransition = false, timelineZooming = false, timelineScrolling = false; private int transitionScrollDirection = -1, transitionZoomDirection = -1; private int timelineTransitionStartFrame = 0, timelineTransitionEndFrame = 0; private int timelineTransitionLength = 30; private final int initTimelineTransitionLength = 30; private float timelineStartTransitionStart = 0, timelineStartTransitionTarget = 0; private float timelineEndTransitionStart = 0, timelineEndTransitionTarget = 0; public float transitionScrollIncrement = 1750.f; public final float initTransitionScrollIncrement = 1750.f; // Seconds to scroll per frame public final float transitionZoomInIncrement = 0.95f, transitionZoomOutIncrement = 1.052f; /* Library View */ private int libraryViewMode = 2; // 0: World, 1: Field, 2: Location (Cluster) private boolean setupLibraryView = false; public int currentDisplayField = 0, currentDisplayCluster = 0; private float clusterMediaXOffset, clusterMediaYOffset; private final float thumbnailWidth = 85.f; private final float thumbnailSpacing = 0.1f; MV_Button btnLibraryViewCluster, btnLibraryViewField, btnLibraryViewLibrary; private boolean createdSelectableMedia = false; ArrayList<SelectableMedia> selectableMedia; /* Selectable media thumbnails */ private SelectableMedia currentSelectableMedia; /* Current selected media in grid */ private int selectedMedia = -1; private boolean updateSelectableMedia = true; /* Media View */ private int mediaViewMediaType = -1; private int mediaViewMediaID = -1; /* Text – 3D HUD */ private float messageXOffset, messageYOffset; private float metadataXOffset, metadataYOffset; private float largeTextSize = 56.f; // -- Set from display size?? private float mediumTextSize = 44.f; private float smallTextSize = 36.f; private float messageTextSize = 48.f; private float linePadding = 20.f; private float lineWidth = smallTextSize + linePadding; // private float lineWidthWide = largeTextSize + linePadding; private float lineWidthWide = largeTextSize * 2.f; /* Text – 2D */ private float hudVeryLargeTextSize; private float hudLargeTextSize; private float hudMediumTextSize; private float hudSmallTextSize; private float hudVerySmallTextSize; private float hudLinePadding; private float hudLinePaddingWide; private float hudLineWidth; private float hudLineWidthWide; private float hudLineWidthVeryWide; // private float hudVeryLargeTextSize = 32.f; // private float hudLargeTextSize = 26.f; // private float hudMediumTextSize = 22.f; // private float hudSmallTextSize = 18.f; // private float hudVerySmallTextSize = 16.f; // private float hudLinePadding = 4.f; // private float hudLinePaddingWide = 8.f; // private float hudLineWidth = hudMediumTextSize + hudLinePadding; // private float hudLineWidthWide = hudLargeTextSize + hudLinePaddingWide; // private float hudLineWidthVeryWide = hudLargeTextSize * 2.f; /* Messages */ public ArrayList<String> startupMessages; // Messages to display on screen private ArrayList<String> messages; // Messages to display on screen private ArrayList<String> metadata; // Metadata messages to display on screen private PFont defaultFont, messageFont; private final int messageDuration = 40; // Frame length to display messages private final int maxMessages = 16; // Maximum simultaneous messages on screen int messageStartFrame = -1; int metadataStartFrame = -1; int startupMessageStartFrame = -1; /** * Constructor for 2D display * @param mv Parent app */ public MV_Display(MetaVisualizer parent) { mv = parent; utilities = new WMV_Utilities(); originalMatrix = mv.getMatrix((PMatrix3D)null); // float aspect = (float)screenHeight / (float)screenWidth; // if(aspect != 0.625f) // monitorOffsetXAdjustment = (0.625f / aspect); screenWidth = mv.displayWidth; screenHeight = mv.displayHeight; messages = new ArrayList<String>(); metadata = new ArrayList<String>(); startupMessages = new ArrayList<String>(); /* Text – 3D HUD */ messageXOffset = screenWidth * 1.75f; messageYOffset = -screenHeight * 0.33f; metadataXOffset = -screenWidth * 2.f; metadataYOffset = -screenHeight / 2.f; largeTextSize = screenWidth * 0.0333f; mediumTextSize = screenWidth * 0.025f; smallTextSize = screenWidth * 0.02f; messageTextSize = screenWidth * 0.03f; linePadding = screenWidth * 0.0125f; // largeTextSize = 56.f; // -- Set from display size?? // mediumTextSize = 44.f; // smallTextSize = 36.f; // // messageTextSize = 48.f; // linePadding = 20.f; lineWidth = smallTextSize + linePadding; // lineWidthWide = largeTextSize + linePadding; lineWidthWide = largeTextSize * 2.f; /* 2D Displays */ timelineStart = 0.f; timelineEnd = utilities.getTimePVectorSeconds(new PVector(24,0,0)); /* Text – 2D */ hudVeryLargeTextSize = screenWidth * 0.017f; hudLargeTextSize = screenWidth * 0.015f; hudMediumTextSize = screenWidth * 0.0125f; hudSmallTextSize = screenWidth * 0.010f; hudVerySmallTextSize = screenWidth * 0.0095f; hudLinePadding = screenHeight * 0.004f; hudLinePaddingWide = hudLinePadding * 2.f; hudLineWidth = screenHeight * 0.02f + hudLinePadding; hudLineWidthWide = screenHeight * 0.0233f + hudLinePaddingWide; hudLineWidthVeryWide = screenHeight * 0.0466f; // hudVeryLargeTextSize = 32.f; // hudLargeTextSize = 26.f; // hudMediumTextSize = 22.f; // hudSmallTextSize = 18.f; // hudVerySmallTextSize = 16.f; // hudLinePadding = 4.f; // hudLinePaddingWide = 8.f; // hudLineWidth = hudMediumTextSize + hudLinePadding; // hudLineWidthWide = hudLargeTextSize + hudLinePaddingWide; // hudLineWidthVeryWide = hudLargeTextSize * 2.f; currentSelectableTimeSegment = null; currentSelectableTimeSegmentID = -1; currentSelectableTimeSegmentFieldTimeSegmentID = -1; map2D = new MV_Map(this); buttons = new ArrayList<MV_Button>(); messageFont = mv.createFont("ArialNarrow-Bold", messageTextSize); defaultFont = mv.createFont("SansSerif", smallTextSize); // startupImage = p.p.loadImage("res/WMV_Title.jpg"); } /** * Finish 2D display setup */ public void setupScreen() { windowWidth = mv.width; windowHeight = mv.height; clusterMediaXOffset = windowWidth * 0.1f; clusterMediaYOffset = windowHeight * 0.5f; // Default; actual value changes with Library View text line count hudCenterXOffset = windowWidth * 0.5f; hudLeftMargin = windowWidth * 0.05f; hudRightMargin = windowWidth * 0.95f; hudTopMargin = windowHeight * 0.075f; timelineXOffset = windowWidth * 0.1f; timelineYOffset = windowHeight * 0.4f; timelineScreenSize = windowWidth * 0.8f; timelineHeight = windowHeight * 0.1f; // timelineHeight = screenHeight * 0.1f; datelineYOffset = windowHeight * 0.533f; buttonWidth = windowWidth * 0.075f; buttonHeight = windowWidth * 0.0175f; buttonSpacing = windowWidth * 0.0125f; displayWidthFactor = mv.width / 1440.f; // hudVeryLargeTextSize *= displayWidthFactor; // hudLargeTextSize *= displayWidthFactor; // hudMediumTextSize *= displayWidthFactor; // hudSmallTextSize *= displayWidthFactor; // hudVerySmallTextSize *= displayWidthFactor; // hudLinePadding *= displayWidthFactor; // hudLinePaddingWide *= displayWidthFactor; // hudLineWidth *= displayWidthFactor; // hudLineWidthWide *= displayWidthFactor; // hudLineWidthVeryWide *= displayWidthFactor; // hudVeryLargeTextSize = 32.f * displayWidthFactor; // hudLargeTextSize = 26.f * displayWidthFactor; // hudMediumTextSize = 22.f * displayWidthFactor; // hudSmallTextSize = 18.f * displayWidthFactor; // hudVerySmallTextSize = 16.f * displayWidthFactor; // hudLinePadding = 4.f * displayWidthFactor; // hudLinePaddingWide = 8.f * displayWidthFactor; // hudLineWidth = (hudMediumTextSize + hudLinePadding) * displayWidthFactor; // hudLineWidthWide = (hudLargeTextSize + hudLinePaddingWide) * displayWidthFactor; // hudLineWidthVeryWide = (hudLargeTextSize * 2.f) * displayWidthFactor; } /** * Display HUD elements (messages, satellite map, statistics, metadata, etc.) * @param p Parent world */ public void display(MetaVisualizer ml) { if(worldSetup) { ml.hint(PApplet.DISABLE_DEPTH_TEST); // Disable depth testing for drawing HUD displayStartup(ml.world, ml.state.inLibrarySetup); // Draw startup messages } else { if( displayView == 0 ) // World View { if( messages.size() > 0 || metadata.size() > 0 ) { // ml.hint(PApplet.DISABLE_DEPTH_TEST); // Disable depth testing for drawing HUD if(messages.size() > 0) displayMessages(ml.world); if(ml.world.getState().showMetadata && metadata.size() > 0 && ml.world.viewer.getSettings().selection) displayMetadata(ml.world); } } else // 2D Views { ml.hint(PApplet.DISABLE_DEPTH_TEST); // Disable depth testing for drawing HUD switch(displayView) { case 1: // Map View if(!setupMapView) setupMapView(); displayMapView(); updateMapView(ml.world); break; case 2: // Time View if(!setupTimeView) setupTimeView(); updateFieldTimeline(ml.world); displayTimeView(ml.world); updateTimeView(ml.world); break; case 3: // Library view if(!setupLibraryView) setupLibraryView(); displayLibraryView(ml.world); updateLibraryView(ml.world); break; case 4: // Media View displayMediaView(ml.world); break; } } if(window.subjectDistanceUpBtnDown) ml.world.getCurrentField().fadeFocusDistances(ml.world, 0.985f); else if(window.subjectDistanceDownBtnDown) ml.world.getCurrentField().fadeFocusDistances(ml.world, 1.015228f); } } /** * Setup Library View * @param world Parent world */ private void setupTimeView() { createTimeViewButtons(); setupTimeView = true; } /** * Create Time View buttons */ private void createTimeViewButtons() { buttons = new ArrayList<MV_Button>(); float x = hudCenterXOffset - buttonWidth * 0.5f; float y = datelineYOffset + hudLineWidth; // Starting vertical position btnScrollLeft = new MV_Button(0, "Left", hudVerySmallTextSize, x-buttonWidth * 0.75f, x, y, y+buttonHeight); x += buttonSpacing; btnScrollRight = new MV_Button(1, "Right", hudVerySmallTextSize, x+=buttonWidth * 0.75f, x+=buttonWidth, y, y+buttonHeight); x = hudCenterXOffset - buttonWidth * 0.5f; y += buttonHeight + buttonSpacing; btnTimelineZoomIn = new MV_Button(2, "In", hudVerySmallTextSize, x-buttonWidth * 0.75f, x, y, y+buttonHeight); x += buttonSpacing; btnTimelineZoomOut = new MV_Button(3, "Out", hudVerySmallTextSize, x+=buttonWidth * 0.75f, x+=buttonWidth, y, y+buttonHeight); buttons.add(btnScrollLeft); buttons.add(btnScrollRight); buttons.add(btnTimelineZoomIn); buttons.add(btnTimelineZoomOut); y += buttonHeight + buttonSpacing; x = hudCenterXOffset - buttonWidth * 2.f - buttonSpacing * 2.f; btnZoomToFit = new MV_Button(4, "Field", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); x += buttonSpacing; btnZoomToSelection = new MV_Button(5, "Location", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); x += buttonSpacing; btnZoomToCurrentDate = new MV_Button(6, "Current Date", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); x += buttonSpacing; btnZoomToTimeline = new MV_Button(7, "Full Day", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); buttons.add(btnZoomToFit); buttons.add(btnZoomToSelection); buttons.add(btnZoomToCurrentDate); buttons.add(btnZoomToTimeline); // ML_Button btnZoomToFit, btnZoomToSelection, btnZoomToTimeline; // case "TimelineZoomToFit": // ml.display.zoomToTimeline(ml.world, true); // break; // case "TimelineZoomToSelected": // ml.display.zoomToCurrentSelectableTimeSegment(ml.world, true); // break; // case "TimelineZoomToDate": // ml.display.zoomToCurrentSelectableDate(ml.world, true); // break; // case "TimelineZoomToFull": // ml.display.resetZoom(ml.world, true); // break; // ML_Button previous, next, current; // // x = hudCenterXOffset - buttonWidth * 1.5f; // y += buttonHeight + buttonSpacing; // Starting vertical position // // previous = new ML_Button(10, "Previous (left)", hudVerySmallTextSize, x-buttonWidth*0.5f, x+=buttonWidth, y, y+buttonHeight); // x += buttonSpacing; // current = new ML_Button(12, "Current", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); // x += buttonSpacing; // next = new ML_Button(11, "Next (right)", hudVerySmallTextSize, x, x+=buttonWidth + buttonWidth * 0.5f, y, y+buttonHeight); // // buttons.add(previous); // buttons.add(current); // buttons.add(next); } /** * Setup Library View * @param world Parent world */ private void setupMapView() { createMapViewButtons(); setupMapView = true; } /** * Create Time View buttons */ private void createMapViewButtons() { buttons = new ArrayList<MV_Button>(); // ML_Button fieldMode, worldMode; // ML_Button fieldMap, worldMap, viewer; // ML_Button panUp, panDown; // ML_Button panLeft, panRight; float x = hudLeftMargin + buttonWidth + buttonSpacing * 0.5f; // float x = hudCenterXOffset - buttonWidth * 0.5f; float y = hudTopMargin; // Starting vertical position btnFieldMode = new MV_Button(11, "Field", hudVerySmallTextSize, x, x+buttonWidth, y, y+buttonHeight); x += buttonSpacing; btnWorldMode = new MV_Button(10, "Environment", hudVerySmallTextSize, x+=buttonWidth, x+=buttonWidth, y, y+buttonHeight); buttons.add(btnFieldMode); buttons.add(btnWorldMode); // x = hudLeftMargin + buttonWidth * 0.5f; x = hudLeftMargin + buttonWidth + buttonSpacing * 0.5f; y += buttonHeight + buttonSpacing; btnZoomToCluster = new MV_Button(0, "Viewer", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); x += buttonSpacing; btnZoomToField = new MV_Button(1, "Field", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); x += buttonSpacing; btnZoomToWorld = new MV_Button(2, "Environment", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); btnZoomToWorld.setVisible(mapViewMode == 0); // x = hudLeftMargin; x = hudLeftMargin + buttonWidth; y += buttonHeight + buttonSpacing; btnZoomMapIn = new MV_Button(7, "In", hudVerySmallTextSize, x-buttonWidth, x, y, y+buttonHeight); x += buttonSpacing; btnZoomMapOut = new MV_Button(8, "Out", hudVerySmallTextSize, x+=buttonWidth, x+=buttonWidth, y, y+buttonHeight); buttons.add(btnZoomMapIn); buttons.add(btnZoomMapOut); x = hudLeftMargin + buttonWidth + buttonSpacing * 0.5f; y += buttonHeight + buttonSpacing; btnPanMapUp = new MV_Button(3, "Up", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); x = hudLeftMargin; y += buttonHeight + buttonSpacing; btnPanMapLeft = new MV_Button(4, "Left", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); x += buttonSpacing; btnPanMapRight = new MV_Button(5, "Right", hudVerySmallTextSize, x+=buttonWidth, x+=buttonWidth, y, y+buttonHeight); x = hudLeftMargin + buttonWidth + buttonSpacing * 0.5f; y += buttonHeight + buttonSpacing; btnPanMapDown = new MV_Button(6, "Down", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); buttons.add(btnZoomToCluster); buttons.add(btnZoomToField); buttons.add(btnZoomToWorld); buttons.add(btnPanMapUp); buttons.add(btnPanMapLeft); buttons.add(btnPanMapRight); buttons.add(btnPanMapDown); // ML_Button zoomIn, zoomOut; // // x = hudLeftMargin + buttonWidth * 0.5f; // y += buttonHeight + buttonSpacing; // // zoomIn = new ML_Button(7, "In", hudVerySmallTextSize, x-buttonWidth, x, y, y+buttonHeight); // x += buttonSpacing; // zoomOut = new ML_Button(8, "Out", hudVerySmallTextSize, x+=buttonWidth, x+=buttonWidth, y, y+buttonHeight); // // buttons.add(zoomIn); // buttons.add(zoomOut); } /** * Setup Library View * @param world Parent world */ private void setupLibraryView() { createLibraryViewButtons(); setupLibraryView = true; } /** * Create Library View buttons */ private void createLibraryViewButtons() { buttons = new ArrayList<MV_Button>(); float x = hudCenterXOffset - buttonWidth * 0.5f; float y = hudTopMargin; // Starting vertical position // float y = hudTopMargin + lineWidth; // Starting vertical position btnLibraryViewCluster = new MV_Button(0, "Location", hudVerySmallTextSize, x-buttonWidth, x, y, y+buttonHeight); // cluster.addLabel("Displaying: "); x += buttonSpacing; btnLibraryViewField = new MV_Button(1, "Field", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); x += buttonSpacing; btnLibraryViewLibrary = new MV_Button(2, "Environment", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); buttons.add(btnLibraryViewCluster); buttons.add(btnLibraryViewField); buttons.add(btnLibraryViewLibrary); MV_Button previous, next, current; x = hudCenterXOffset - buttonWidth * 1.5f; y += buttonHeight + buttonSpacing; // y += buttonHeight * 3.f + buttonSpacing * 0.5f; previous = new MV_Button(10, "Previous (left)", hudVerySmallTextSize, x-buttonWidth*0.5f, x+=buttonWidth, y, y+buttonHeight); x += buttonSpacing; current = new MV_Button(12, "Current", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); x += buttonSpacing; next = new MV_Button(11, "Next (right)", hudVerySmallTextSize, x, x+=buttonWidth + buttonWidth * 0.5f, y, y+buttonHeight); buttons.add(previous); buttons.add(current); buttons.add(next); } /** * Begin Heads-Up Display * @param ml Parent app */ public void beginHUD(MetaVisualizer ml) { ml.g.pushMatrix(); ml.g.hint(PConstants.DISABLE_DEPTH_TEST); ml.g.resetMatrix(); // Load identity matrix. ml.g.applyMatrix(originalMatrix); // Apply original transformation matrix. } /** * End Heads-Up Display * @param ml Parent app */ public void endHUD(MetaVisualizer ml) { // ml.g.hint(PConstants.ENABLE_DEPTH_TEST); ml.g.popMatrix(); } /** * Set the current initialization progress bar position * @param progress New progress bar position {0.f to 1.f} */ public void setupProgress(float progress) { setupProgress = progress; } public void displayMapView() { mv.rectMode(PApplet.CORNER); // Specify top left point in rect() -- Needed? if(mapViewMode == 0) // World Mode { if(initializedMaps) map2D.displayWorldMap(mv.world); map2D.update(mv.world); // -- Added 6/22 } else if(mapViewMode == 1) // Field Mode { if(initializedMaps) map2D.displaySatelliteMap(mv.world); if(mv.state.interactive) displayInteractiveClustering(mv.world); map2D.update(mv.world); } // startDisplayHUD(); mv.pushMatrix(); mv.textFont(defaultFont); // = ml.createFont("SansSerif", 30); float x = hudLeftMargin + buttonWidth * 0.5f; float y = hudTopMargin + buttonSpacing * 0.75f; // + lineWidth; // Starting vertical position mv.fill(0, 0, 255, 255); mv.textSize(hudSmallTextSize); mv.text("Map Mode:", x + buttonSpacing * 0.3f, y - buttonSpacing * 0.15f, 0); x = hudLeftMargin + buttonWidth * 0.5f; y += buttonHeight + buttonSpacing; mv.text("Zoom To:", x, y, 0); x = hudLeftMargin + buttonWidth * 1.5f + buttonSpacing * 0.5f; y += buttonHeight + buttonSpacing; mv.text("Zoom", x, y, 0); y += buttonHeight * 2.f + buttonSpacing * 1.75f; mv.text("Pan", x, y, 0); mv.popMatrix(); // endDisplayHUD(); // -- Added 6/29/17 for(MV_Button b : buttons) b.display(mv.world, 0.f, 0.f, 255.f); mv.rectMode(PApplet.CENTER); // Return rect mode to Center } /** * Display Time View in main window * @param p Parent world */ public void displayTimeView(WMV_World p) { mv.rectMode(PApplet.CORNER); // Specify top left point in rect() -- Needed? startDisplayHUD(); mv.pushMatrix(); mv.textFont(defaultFont); // = ml.createFont("SansSerif", 30); float xPos = hudCenterXOffset; float yPos = hudTopMargin; // Starting vertical position WMV_Field f = p.getCurrentField(); mv.fill(0, 0, 255, 255); mv.textSize(hudVeryLargeTextSize); mv.text(""+p.getCurrentField().getName(), xPos, yPos, 0); mv.textFont(defaultFont); // = ml.createFont("SansSerif", 30); // startDisplayHUD(); // ml.pushMatrix(); for(MV_Button b : buttons) b.display(p, 0.f, 0.f, 255.f); // ml.popMatrix(); // endDisplayHUD(); mv.textSize(hudLargeTextSize - 5.f); String strDisplayDate = ""; if(displayDate >= 0) { strDisplayDate = utilities.getDateAsString(p.getCurrentField().getDate(displayDate)); } else { strDisplayDate = "Showing All Dates"; mv.fill(35, 115, 255, 255); } mv.text(strDisplayDate, xPos, yPos += hudLineWidthVeryWide, 0); mv.textSize(hudMediumTextSize); mv.fill(0, 0, 255, 255); mv.text(" Time Zone: "+ f.getTimeZoneID(), xPos, yPos += hudLineWidthWide, 0); // ml.text("Scroll", xPos, yPos += hudLineWidth, 0); // ml.text("Zoom", xPos, yPos += hudLineWidth, 0); // ml.popMatrix(); // endDisplayHUD(); // xPos = hudCenterXOffset; mv.textSize(hudSmallTextSize); yPos = datelineYOffset + hudLineWidth + buttonHeight * 0.5f; mv.text("Scroll", xPos, yPos, 0); mv.text("Zoom", xPos, yPos += buttonHeight + buttonSpacing, 0); mv.popMatrix(); if(fieldDatelineCreated) displayDateline(p); if(fieldTimelineCreated) displayTimeline(p); endDisplayHUD(); // -- Added 6/29/17 mv.rectMode(PApplet.CENTER); // Return rect mode to Center // updateTimelineMouse(p); } /** * Update field timeline every frame * @param p Parent world */ private void updateFieldTimeline(WMV_World p) { if(timelineTransition) updateTimelineTransition(p); if(!fieldDatelineCreated || !fieldTimelineCreated || updateFieldTimeline) { if(!timelineTransition) { createFieldDateline(p); createFieldTimeline(p); updateFieldTimeline = false; } } if(updateCurrentSelectableTimeSegment && !timelineTransition) { if(p.viewer.getCurrentFieldTimeSegment() >= 0) { updateTimelineSelection(p); } else System.out.println("Display.updateCurrentSelectableTimeSegment()... ERROR: No current time segment!"); } } /** * Update Time View * @param p Parent world */ private void updateMapView(WMV_World p) { updateMapViewMouse(p); } /** * Update Time View * @param p Parent world */ private void updateTimeView(WMV_World p) { updateTimelineMouse(p); } /** * Update Library View * @param p Parent world */ private void updateLibraryView(WMV_World p) { if(updateSelectableMedia) { WMV_Field f = p.getCurrentField(); WMV_Cluster c = f.getCluster(currentDisplayCluster); // Get the cluster to display info about ArrayList<WMV_Image> imageList = f.getImagesInCluster(c.getID(), p.getCurrentField().getImages()); if(imageList != null) createClusterSelectableMedia(p, imageList); updateSelectableMedia = false; } updateLibraryViewMouse(); } /** * Update user selection in Timeline View * @param p Parent world */ private void updateTimelineSelection(WMV_World p) { WMV_TimeSegment t = p.getCurrentField().getTimeSegment(p.viewer.getCurrentFieldTimeSegment()); int previous = currentSelectableTimeSegmentID; if(t != null) { currentSelectableTimeSegmentID = getSelectableTimeIDOfFieldTimeSegment(t); // Set current selectable time (white rectangle) from current field time segment if(currentSelectableTimeSegmentID != -1) { currentSelectableTimeSegment = selectableTimeSegments.get(currentSelectableTimeSegmentID); currentSelectableTimeSegmentFieldTimeSegmentID = currentSelectableTimeSegment.segment.getFieldTimelineID(); // Set current selectable time (white rectangle) from current field time segment } else { currentSelectableTimeSegmentFieldTimeSegmentID = -1; currentSelectableTimeSegment = null; } } else { currentSelectableTimeSegmentID = -1; currentSelectableTimeSegmentFieldTimeSegmentID = -1; currentSelectableTimeSegment = null; } if(updateCurrentSelectableDate) { if(currentSelectableTimeSegmentID != previous && currentSelectableDate > -1) // If changed field segment and displaying a single date { int fieldDate = p.getCurrentField().getTimeSegment(p.viewer.getCurrentFieldTimeSegment()).getFieldDateID(); // Update date displayed setCurrentSelectableDate(fieldDate); } else { System.out.println("Display.updateTimelineSelection()... 1 updateCurrentSelectableDate... currentSelectableDate:"+currentSelectableDate); if(currentSelectableDate == -100) setCurrentSelectableDate(-1); } } updateCurrentSelectableTimeSegment = false; updateCurrentSelectableDate = false; } /** * Create field dateline * @param p Parent world */ private void createFieldDateline(WMV_World p) { WMV_Field f = p.getCurrentField(); if(f.getDateline().size() > 0) { WMV_Date first = f.getDate(0); float padding = 1.f; int firstDay = first.getDay(); int firstMonth = first.getMonth(); int firstYear = first.getYear(); WMV_Date last = f.getDate(f.getDateline().size()-1); int lastDay = last.getDay(); int lastMonth = last.getMonth(); int lastYear = last.getYear(); if(f.getDateline().size() == 2) padding = utilities.getDaysSince1980(p.getCurrentField().getTimeZoneID(), lastDay, lastMonth, lastYear) - utilities.getDaysSince1980(p.getCurrentField().getTimeZoneID(), firstDay, firstMonth, firstYear); else if(f.getDateline().size() > 2) padding = (utilities.getDaysSince1980(p.getCurrentField().getTimeZoneID(), lastDay, lastMonth, lastYear) - utilities.getDaysSince1980(p.getCurrentField().getTimeZoneID(), firstDay, firstMonth, firstYear)) * 0.33f; datelineStart = utilities.getDaysSince1980(p.getCurrentField().getTimeZoneID(), firstDay, firstMonth, firstYear) - padding; datelineEnd = utilities.getDaysSince1980(p.getCurrentField().getTimeZoneID(), lastDay, lastMonth, lastYear) + padding; createSelectableDates(p); fieldDatelineCreated = true; } else { System.out.println("ERROR no dateline in field!!"); } } /** * Create viewable timeline for field * @param p Parent world */ private void createFieldTimeline(WMV_World p) { WMV_Field f = p.getCurrentField(); selectableTimeSegments = new ArrayList<SelectableTimeSegment>(); if(f.getDateline().size() == 1) /* Field contains media from single date */ { int count = 0; for(WMV_TimeSegment t : f.getTimeline().timeline) { SelectableTimeSegment st = getSelectableTimeSegment(t, count); if(st != null) { selectableTimeSegments.add(st); count++; } } } else if(f.getDateline().size() > 1) /* Field contains media from multiple dates */ { if(displayDate == -1) { int count = 0; for(WMV_Timeline ts : f.getTimelines()) { for(WMV_TimeSegment t:ts.timeline) { SelectableTimeSegment st = getSelectableTimeSegment(t, count); if(st != null) { selectableTimeSegments.add(st); count++; } } } } else { if(displayDate < f.getTimelines().size()) { ArrayList<WMV_TimeSegment> ts = f.getTimelines().get(displayDate).timeline; int count = 0; for(WMV_TimeSegment t:ts) { SelectableTimeSegment st = getSelectableTimeSegment(t, count); if(st != null) { selectableTimeSegments.add(st); count++; } } } } } fieldTimelineCreated = true; } /** * Create selectable dates for current field * @param p Parent world */ private void createSelectableDates(WMV_World p) { WMV_Field f = p.getCurrentField(); selectableDates = new ArrayList<SelectableDate>(); if(f.getDateline().size() == 1) { SelectableDate sd = getSelectableDate(f.getDate(0), 0); if(sd != null) selectableDates.add(sd); } else if(f.getDateline().size() > 1) { int count = 0; for(WMV_Date t : f.getDateline()) { SelectableDate sd = getSelectableDate(t, count); if(sd != null) { selectableDates.add(sd); count++; } } float xOffset = timelineXOffset; PVector loc = new PVector(xOffset, datelineYOffset, 0); // PVector loc = new PVector(xOffset, datelineYOffset, hudDistanceInit); allDates = new SelectableDate(-100, loc, 25.f, null); // int newID, int newClusterID, PVector newLocation, Box newRectangle } } /** * Transition timeline zoom from current to given value * @param newStart New timeline left edge value * @param newEnd New timeline right edge value * @param transitionLength Transition length in frames * @param frameCount Current frame count */ public void timelineTransition(float newStart, float newEnd, int transitionLength, int frameCount) { timelineTransitionLength = transitionLength; if(!timelineTransition) { if(timelineStart != newStart || timelineEnd != newEnd) // Check if already at target { timelineTransition = true; timelineTransitionStartFrame = frameCount; timelineTransitionEndFrame = timelineTransitionStartFrame + timelineTransitionLength; if(timelineStart != newStart && timelineEnd != newEnd) { timelineStartTransitionStart = timelineStart; timelineStartTransitionTarget = newStart; timelineEndTransitionStart = timelineEnd; timelineEndTransitionTarget = newEnd; } else if(timelineStart != newStart && timelineEnd == newEnd) { timelineStartTransitionStart = timelineStart; timelineStartTransitionTarget = newStart; timelineEndTransitionTarget = timelineEnd; } else if(timelineStart == newStart && timelineEnd != newEnd) { timelineStartTransitionTarget = timelineStart; timelineEndTransitionStart = timelineEnd; timelineEndTransitionTarget = newEnd; } } else { timelineTransition = false; } } } /** * Update map zoom level each frame * @param p Parent world */ void updateTimelineTransition(WMV_World p) { float newStart = timelineStart; float newEnd = timelineEnd; if (mv.frameCount >= timelineTransitionEndFrame) { newStart = timelineStartTransitionTarget; newEnd = timelineEndTransitionTarget; timelineTransition = false; updateFieldTimeline = true; updateCurrentSelectableTimeSegment = true; transitionScrollIncrement = initTransitionScrollIncrement * getZoomLevel(); } else { if(timelineStart != timelineStartTransitionTarget) { newStart = utilities.mapValue( mv.frameCount, timelineTransitionStartFrame, timelineTransitionEndFrame, timelineStartTransitionStart, timelineStartTransitionTarget); } if(timelineEnd != timelineEndTransitionTarget) { newEnd = utilities.mapValue( mv.frameCount, timelineTransitionStartFrame, timelineTransitionEndFrame, timelineEndTransitionStart, timelineEndTransitionTarget); } } if(timelineStart != newStart) timelineStart = newStart; if(timelineEnd != newEnd) timelineEnd = newEnd; if(timelineScrolling) scroll(p, transitionScrollDirection); if(timelineZooming) zoomTimeline(p, transitionZoomDirection, true); } /** * Create and return selectable time segment from timeline * @param t Time segment * @param id Time segment id * @return New SelectableTimeSegment object */ private SelectableTimeSegment getSelectableTimeSegment(WMV_TimeSegment t, int id) { float lowerSeconds = utilities.getTimePVectorSeconds(t.getLower().getTimeAsPVector()); float upperSeconds = utilities.getTimePVectorSeconds(t.getUpper().getTimeAsPVector()); if(upperSeconds == lowerSeconds) { lowerSeconds -= minSegmentSeconds * 0.5f; upperSeconds += minSegmentSeconds * 0.5f; } float xOffset = utilities.mapValue(lowerSeconds, timelineStart, timelineEnd, timelineXOffset, timelineXOffset + timelineScreenSize); float xOffset2 = utilities.mapValue(upperSeconds, timelineStart, timelineEnd, timelineXOffset, timelineXOffset + timelineScreenSize); if(xOffset > timelineXOffset && xOffset2 < timelineXOffset + timelineScreenSize) { float rectLeftEdge, rectRightEdge, rectTopEdge, rectBottomEdge; float rectWidth = xOffset2 - xOffset; PVector loc = new PVector(xOffset, timelineYOffset, 0); // -- Z doesn't affect selection! rectLeftEdge = loc.x; rectRightEdge = rectLeftEdge + rectWidth; rectTopEdge = timelineYOffset - timelineHeight * 0.5f; rectBottomEdge = timelineYOffset + timelineHeight * 0.5f; loc.x += (xOffset2 - xOffset) * 0.5f; SelectableTimeSegment st = new SelectableTimeSegment(id, t.getFieldTimelineID(), t.getClusterID(), t, loc, rectLeftEdge, rectRightEdge, rectTopEdge, rectBottomEdge); // int newID, int newClusterID, PVector newLocation, Box newRectangle return st; } else return null; } /** * Create and return selectable date from dateline * @param t Time segment * @param id Time segment id * @return SelectableTime object */ private SelectableDate getSelectableDate(WMV_Date d, int id) { // float xOffset = utilities.mapValue(lowerSeconds, timelineStart, timelineEnd, timelineXOffset, timelineXOffset + timelineScreenSize); // float xOffset2 = utilities.mapValue(upperSeconds, timelineStart, timelineEnd, timelineXOffset, timelineXOffset + timelineScreenSize); float date = d.getDaysSince1980(); float xOffset = utilities.mapValue(date, datelineStart, datelineEnd, timelineXOffset, timelineXOffset + timelineScreenSize); if(xOffset > timelineXOffset && xOffset < timelineXOffset + timelineScreenSize) { float radius = 25.f; PVector loc = new PVector(xOffset, datelineYOffset, 0); // PVector loc = new PVector(xOffset, datelineYOffset, hudDistanceInit); SelectableDate st = new SelectableDate(id, loc, radius, d); // int newID, int newClusterID, PVector newLocation, Box newRectangle return st; } else return null; } /** * Draw the field timeline * @param p Parent world */ private void displayTimeline(WMV_World p) { WMV_Field f = p.getCurrentField(); mv.tint(255); mv.stroke(0.f, 0.f, 255.f, 255.f); mv.strokeWeight(3.f); mv.fill(0.f, 0.f, 255.f, 255.f); mv.line(timelineXOffset, timelineYOffset, 0, timelineXOffset + timelineScreenSize, timelineYOffset, 0); // ml.line(timelineXOffset, timelineYOffset, hudDistanceInit, timelineXOffset + timelineScreenSize, timelineYOffset, hudDistanceInit); String startTime = utilities.secondsToTimeAsString(timelineStart, false, false); String endTime = utilities.secondsToTimeAsString(timelineEnd, false, false); mv.textSize(hudVerySmallTextSize); float firstHour = utilities.roundSecondsToHour(timelineStart); if(firstHour == (int)(timelineStart / 3600.f) * 3600.f) firstHour += 3600.f; float lastHour = utilities.roundSecondsToHour(timelineEnd); if(lastHour == (int)(timelineEnd / 3600.f + 1.f) * 3600.f) lastHour -= 3600.f; float timeLength = timelineEnd - timelineStart; float timeToScreenRatio = timelineScreenSize / timeLength; if(lastHour / 3600.f - firstHour / 3600.f <= 16.f) { float xOffset = timelineXOffset + (firstHour - timelineStart) * timeToScreenRatio - 20.f; float pos; for( pos = firstHour ; pos <= lastHour ; pos += 3600.f ) { String time = utilities.secondsToTimeAsString(pos, false, false); mv.text(time, xOffset, timelineYOffset - timelineHeight * 0.5f - 40.f, 0); // ml.text(time, xOffset, timelineYOffset - timelineHeight * 0.5f - 40.f, hudDistanceInit); xOffset += 3600.f * timeToScreenRatio; } if( (firstHour - timelineStart) * timeToScreenRatio - 20.f > 200.f) mv.text(startTime, timelineXOffset, timelineYOffset - timelineHeight * 0.5f - 40.f, 0); // ml.text(startTime, timelineXOffset, timelineYOffset - timelineHeight * 0.5f - 40.f, hudDistanceInit); xOffset -= 3600.f * timeToScreenRatio; if(timelineXOffset + timelineScreenSize - 40.f - xOffset > 200.f) mv.text(endTime, timelineXOffset + timelineScreenSize - 40.f, timelineYOffset - timelineHeight * 0.5f - 40.f, 0); // ml.text(endTime, timelineXOffset + timelineScreenSize - 40.f, timelineYOffset - timelineHeight * 0.5f - 40.f, hudDistanceInit); } else { float xOffset = timelineXOffset; for( float pos = firstHour - 3600.f ; pos <= lastHour ; pos += 7200.f ) { String time = utilities.secondsToTimeAsString(pos, false, false); mv.text(time, xOffset, timelineYOffset - timelineHeight * 0.5f - 40.f, 0); // ml.text(time, xOffset, timelineYOffset - timelineHeight * 0.5f - 40.f, hudDistanceInit); xOffset += 7200.f * timeToScreenRatio; } } if(f.getDateline().size() == 1) { for(WMV_TimeSegment t : f.getTimeline().timeline) displayTimeSegment(p, t); } else if(f.getDateline().size() > 1) { if(displayDate == -1) { for(WMV_Timeline ts : f.getTimelines()) for(WMV_TimeSegment t:ts.timeline) displayTimeSegment(p, t); } else { if(displayDate < f.getTimelines().size()) { ArrayList<WMV_TimeSegment> ts = f.getTimelines().get(displayDate).timeline; for(WMV_TimeSegment t:ts) displayTimeSegment(p, t); } } } if(!timelineTransition) { if(currentSelectableTimeSegmentID >= 0 && currentSelectableTimeSegmentID < selectableTimeSegments.size()) { if(currentSelectableTimeSegmentFieldTimeSegmentID == selectableTimeSegments.get(currentSelectableTimeSegmentID).segment.getFieldTimelineID()) { if(currentSelectableTimeSegmentID != -1 && selectableTimeSegments.size() > 0 && currentSelectableTimeSegmentID < selectableTimeSegments.size()) { if(displayDate == -1 || selectableTimeSegments.get(currentSelectableTimeSegmentID).segment.getFieldDateID() == displayDate) { if(selectedTime == -1) /* Draw current time segment */ selectableTimeSegments.get(currentSelectableTimeSegmentID).display(p, 0.f, 0.f, 255.f, true); else selectableTimeSegments.get(currentSelectableTimeSegmentID).display(p, 0.f, 0.f, 255.f, false); } } } } /* Draw selected time segment */ if(selectedTime != -1 && selectableTimeSegments.size() > 0 && selectedTime < selectableTimeSegments.size()) selectableTimeSegments.get(selectedTime).display(p, 40.f, 255.f, 255.f, true); } } /** * Display dateline for current field * @param p Parent world */ private void displayDateline(WMV_World p) { WMV_Field f = p.getCurrentField(); mv.tint(255); mv.stroke(0.f, 0.f, 255.f, 255.f); mv.strokeWeight(3.f); mv.fill(0.f, 0.f, 255.f, 255.f); mv.line(timelineXOffset, datelineYOffset, 0, timelineXOffset + timelineScreenSize, datelineYOffset, 0); // ml.line(datelineXOffset, datelineYOffset, hudDistanceInit, datelineXOffset + timelineScreenSize, datelineYOffset, hudDistanceInit); if(f.getDateline().size() == 1) { displayDate(p, f.getDate(0)); } else if(f.getDateline().size() > 1) { for(WMV_Date d : f.getDateline()) displayDate(p, d); } if(selectedDate >= 0 && selectableDates.size() > 0 && selectedDate < selectableDates.size()) selectableDates.get(selectedDate).display(p, 40.f, 255.f, 255.f, true); if(currentSelectableDate >= 0 && selectableDates.size() > 0 && currentSelectableDate < selectableDates.size()) selectableDates.get(currentSelectableDate).display(p, 0.f, 0.f, 255.f, false); if(displayDate >= 0 && allDates != null) { allDates.display(p, 55.f, 120.f, 255.f, false); mv.textSize(hudSmallTextSize); mv.fill(35, 115, 255, 255); mv.text("Show All", allDates.getLocation().x - 3, allDates.getLocation().y + 30, 0); } } /** * Display date on dateline * @param p Parent world * @param d Date to display */ private void displayDate(WMV_World p, WMV_Date d) { float date = d.getDaysSince1980(); float xOffset = utilities.mapValue(date, datelineStart, datelineEnd, timelineXOffset, timelineXOffset + timelineScreenSize); if(xOffset > timelineXOffset && xOffset < timelineXOffset + timelineScreenSize) { mv.strokeWeight(0.f); mv.fill(120.f, 165.f, 245.f, 155.f); mv.pushMatrix(); mv.stroke(120.f, 165.f, 245.f, 155.f); mv.strokeWeight(25.f); // ml.point(xOffset, datelineYOffset, hudDistanceInit); mv.point(xOffset, datelineYOffset, 0); mv.popMatrix(); } } /** * Display time segment on timeline * @param t Time segment to display * @param id */ private void displayTimeSegment(WMV_World p, WMV_TimeSegment t) { PVector lowerTime = t.getLower().getTimeAsPVector(); // Format: PVector(hour, minute, second) PVector upperTime = t.getUpper().getTimeAsPVector(); float lowerSeconds = utilities.getTimePVectorSeconds(lowerTime); float upperSeconds = utilities.getTimePVectorSeconds(upperTime); if(upperSeconds == lowerSeconds) { lowerSeconds -= minSegmentSeconds * 0.5f; upperSeconds += minSegmentSeconds * 0.5f; } ArrayList<WMV_Time> tsTimeline = t.getTimeline(); // Get timeline for this time segment ArrayList<PVector> times = new ArrayList<PVector>(); for(WMV_Time ti : tsTimeline) times.add(ti.getTimeAsPVector()); float xOffset = utilities.mapValue(lowerSeconds, timelineStart, timelineEnd, timelineXOffset, timelineXOffset + timelineScreenSize); float xOffset2 = utilities.mapValue(upperSeconds, timelineStart, timelineEnd, timelineXOffset, timelineXOffset + timelineScreenSize); if(xOffset > timelineXOffset && xOffset2 < timelineXOffset + timelineScreenSize) { mv.pushMatrix(); mv.translate(0.f, timelineYOffset, 0); // ml.translate(0.f, timelineYOffset, hudDistanceInit); mv.stroke(imageHue, 185.f, 255.f, 155.f); mv.strokeWeight(1.f); for(WMV_Time ti : tsTimeline) { PVector time = ti.getTimeAsPVector(); float seconds = utilities.getTimePVectorSeconds(time); float xOff = utilities.mapValue(seconds, timelineStart, timelineEnd, timelineXOffset, timelineXOffset + timelineScreenSize); if(xOff > timelineXOffset && xOff < timelineXOffset + timelineScreenSize) { switch(ti.getMediaType()) { case 0: mv.stroke(imageHue, 165.f, 215.f, 225.f); break; case 1: mv.stroke(panoramaHue, 165.f, 215.f, 225.f); break; case 2: mv.stroke(videoHue, 165.f, 215.f, 225.f); break; case 3: mv.stroke(soundHue, 165.f, 215.f, 225.f); break; } mv.line(xOff, -timelineHeight / 2.f, 0.f, xOff, timelineHeight / 2.f, 0.f); } } /* Set hue according to media type */ float firstHue = imageHue; float secondHue = imageHue; if(t.hasVideo()) firstHue = videoHue; if(t.hasSound()) { if(firstHue == videoHue) secondHue = soundHue; else firstHue = soundHue; } if(t.hasPanorama()) { if(firstHue == soundHue) secondHue = panoramaHue; else if(firstHue == videoHue) { if(secondHue == imageHue) secondHue = panoramaHue; } else firstHue = panoramaHue; } if(!t.hasImage()) { float defaultHue = 0.f; if(firstHue == imageHue) System.out.println("ERROR: firstHue still imageHue but segment has no image!"); else defaultHue = firstHue; if(secondHue == imageHue) secondHue = defaultHue; } mv.strokeWeight(2.f); /* Draw rectangle around time segment */ mv.stroke(firstHue, 165.f, 215.f, 225.f); mv.line(xOffset, -timelineHeight * 0.5f, 0.f, xOffset, timelineHeight * 0.5f, 0.f); mv.line(xOffset, timelineHeight * 0.5f, 0.f, xOffset2, timelineHeight * 0.5f, 0.f); mv.stroke(secondHue, 165.f, 215.f, 225.f); mv.line(xOffset2, -timelineHeight * 0.5f, 0.f, xOffset2, timelineHeight * 0.5f, 0.f); mv.line(xOffset, -timelineHeight * 0.5f, 0.f, xOffset2, -timelineHeight * 0.5f, 0.f); mv.popMatrix(); } } /** * Get selected time segment for given mouse 3D location * @param mouseScreenLoc Mouse 3D location * @return Selected time segment */ private SelectableTimeSegment getSelectedTimeSegment(PVector mouseLoc) { for(SelectableTimeSegment st : selectableTimeSegments) if( mouseLoc.x > st.leftEdge && mouseLoc.x < st.rightEdge && mouseLoc.y > st.topEdge && mouseLoc.y < st.bottomEdge ) return st; return null; } /** * Get selected time segment for given mouse 3D location * @param mouseScreenLoc Mouse 3D location * @return Selected time segment */ private SelectableMedia getSelectedMedia(PVector mouseLoc) { for(SelectableMedia m : selectableMedia) if( mouseLoc.x > m.leftEdge && mouseLoc.x < m.rightEdge && mouseLoc.y > m.topEdge && mouseLoc.y < m.bottomEdge ) return m; return null; } /** * Get selected time segment for given mouse 3D location * @param mouseScreenLoc Mouse 3D location * @return Selected time segment */ private SelectableDate getSelectedDate(PVector mouseLoc) { for(SelectableDate sd : selectableDates) { if(PVector.dist(mouseLoc, sd.getLocation()) < sd.radius) return sd; } if(allDates != null) { if(PVector.dist(mouseLoc, allDates.getLocation()) < allDates.radius) return allDates; else return null; } else return null; } /** * Update timeline based on current mouse position * @param p Parent world */ public void updateMapViewMouse(WMV_World p) { // System.out.println("Display.updateMapViewMouse()... mouseX:"+ml.mouseX+" mouseY:"+ml.mouseY); PVector mouseLoc = new PVector(mv.mouseX, mv.mouseY); if(buttons.size() > 0) { for(MV_Button b : buttons) { if(b.isVisible()) { if( mouseLoc.x > b.leftEdge && mouseLoc.x < b.rightEdge && mouseLoc.y > b.topEdge && mouseLoc.y < b.bottomEdge ) b.setSelected(true); else b.setSelected(false); } } } } /** * Update timeline based on current mouse position * @param p Parent world */ public void updateTimelineMouse(WMV_World p) { // System.out.println("Display.updateTimelineMouse()... mouseX:"+ml.mouseX+" mouseY:"+ml.mouseY); PVector mouseLoc = new PVector(mv.mouseX, mv.mouseY); if(mv.debug.mouse) { startDisplayHUD(); mv.stroke(155, 0, 255); mv.strokeWeight(5); mv.point(mouseLoc.x, mouseLoc.y, 0); // Show mouse adjusted location for debugging endDisplayHUD(); } if(buttons.size() > 0) { for(MV_Button b : buttons) { if(b.isVisible()) { if( mouseLoc.x > b.leftEdge && mouseLoc.x < b.rightEdge && mouseLoc.y > b.topEdge && mouseLoc.y < b.bottomEdge ) b.setSelected(true); else b.setSelected(false); } } } if(selectableTimeSegments != null) { SelectableTimeSegment timeSelected = getSelectedTimeSegment(mouseLoc); if(timeSelected != null) { selectedTime = timeSelected.getID(); // Set to selected selectedCluster = timeSelected.getClusterID(); if(mv.debug.time && mv.debug.detailed) System.out.println("Selected time segment:"+selectedTime+" selectedCluster:"+selectedCluster); updateFieldTimeline = true; // Update timeline to show selected segment } else selectedTime = -1; } if(selectedTime == -1 && selectableDates != null) { SelectableDate dateSelected = getSelectedDate(mouseLoc); if(dateSelected != null) { selectedDate = dateSelected.getID(); // Set to selected updateFieldTimeline = true; // Update timeline to show selected segment // updateCurrentSelectableDate = true; // Added 6-24-17 } else selectedDate = -1; } } /** * Update Library View based on current mouse position * @param p Parent world */ private void updateLibraryViewMouse() { // System.out.println("Display.updateLibraryViewMouse()... frameCount:"+ml.frameCount+" mouseX:"+ml.mouseX+" mouseY:"+ml.mouseY+" displayView:"+displayView); PVector mouseLoc = new PVector(mv.mouseX, mv.mouseY); if(mv.debug.mouse) { startDisplayHUD(); mv.stroke(155, 0, 255); mv.strokeWeight(5); mv.point(mouseLoc.x, mouseLoc.y, 0); // Show mouse adjusted location for debugging endDisplayHUD(); } if(buttons.size() > 0) { for(MV_Button b : buttons) { if(b.isVisible()) { if( mouseLoc.x > b.leftEdge && mouseLoc.x < b.rightEdge && mouseLoc.y > b.topEdge && mouseLoc.y < b.bottomEdge ) b.setSelected(true); else b.setSelected(false); } } } if(createdSelectableMedia) { if(selectableMedia != null) { SelectableMedia mediaSelected = getSelectedMedia(mouseLoc); if(mediaSelected != null) { if(selectedMedia != mediaSelected.getID()) { selectedMedia = mediaSelected.getID(); // Set to selected if(mv.debug.library && mv.debug.detailed) System.out.println("Display.updateLibraryMouse()... Selected media: "+selectedMedia); } } else selectedMedia = -1; } } } /** * Zoom to current selectable time segment * @param p Parent World * @param transition Whether to use smooth zooming transition */ public void zoomToCurrentSelectableTimeSegment(WMV_World p, boolean transition) { if(currentSelectableTimeSegmentID >= 0) { float first = selectableTimeSegments.get(currentSelectableTimeSegmentID).segment.getLower().getAbsoluteTime(); float last = selectableTimeSegments.get(currentSelectableTimeSegmentID).segment.getUpper().getAbsoluteTime(); float day = utilities.getTimePVectorSeconds(new PVector(24,0,0)); // Seconds in a day first *= day; // Convert from normalized value to seconds last *= day; float newTimelineStart = utilities.roundSecondsToInterval(first, 600.f); // Round down to nearest hour if(newTimelineStart > first) newTimelineStart -= 600; if(newTimelineStart < 0.f) newTimelineStart = 0.f; float newTimelineEnd = utilities.roundSecondsToInterval(last, 600.f); // Round up to nearest hour if(newTimelineEnd < last) newTimelineEnd += 600; if(newTimelineEnd > day) newTimelineEnd = day; if(transition) { timelineTransition(newTimelineStart, newTimelineEnd, initTimelineTransitionLength, mv.frameCount); } else { timelineStart = newTimelineStart; timelineEnd = newTimelineEnd; } } } /** * Zoom to the current selectable date * @param p Parent world * @param transition Whether to use smooth zooming transition */ public void zoomToCurrentSelectableDate(WMV_World p, boolean transition) { if(currentSelectableDate >= 0) { WMV_Field f = p.getCurrentField(); int curDate = selectableDates.get(currentSelectableDate).getID(); float first = f.getTimelines().get(curDate).timeline.get(0).getLower().getAbsoluteTime(); float last = f.getTimelines().get(curDate).timeline.get(f.getTimelines().get(curDate).timeline.size()-1).getUpper().getAbsoluteTime(); float day = utilities.getTimePVectorSeconds(new PVector(24,0,0)); // Seconds in a day first *= day; // Convert from normalized value to seconds last *= day; float newTimelineStart = utilities.roundSecondsToInterval(first, 1800.f); // Round down to nearest hour if(newTimelineStart > first) newTimelineStart -= 1800; if(newTimelineStart < 0.f) newTimelineStart = 0.f; float newTimelineEnd = utilities.roundSecondsToInterval(last, 1800.f); // Round up to nearest hour if(newTimelineEnd < last) newTimelineEnd += 1800; if(newTimelineEnd > day) newTimelineEnd = day; if(transition) { timelineTransition(newTimelineStart, newTimelineEnd, initTimelineTransitionLength, mv.frameCount); } else { timelineStart = newTimelineStart; timelineEnd = newTimelineEnd; } } } /** * Zoom out to full timeline * @param p Parent world * @param transition Whether to use smooth zooming transition */ public void zoomToTimeline(WMV_World p, boolean transition) { WMV_Field f = p.getCurrentField(); float first = f.getTimeSegment(0).getLower().getAbsoluteTime(); // First field media time, normalized float last = f.getTimeSegment(f.getTimeline().timeline.size()-1).getUpper().getAbsoluteTime(); // Last field media time, normalized float day = utilities.getTimePVectorSeconds(new PVector(24,0,0)); // Seconds in a day first *= day; // Convert from normalized value to seconds last *= day; float newTimelineStart = utilities.roundSecondsToHour(first); // Round down to nearest hour if(newTimelineStart > first) newTimelineStart -= 3600; if(newTimelineStart < 0.f) newTimelineStart = 0.f; float newTimelineEnd = utilities.roundSecondsToHour(last); // Round up to nearest hour if(newTimelineEnd < last) newTimelineEnd += 3600; if(newTimelineEnd > day) newTimelineEnd = day; if(transition) { timelineTransition(newTimelineStart, newTimelineEnd, initTimelineTransitionLength, mv.frameCount); } else { timelineStart = newTimelineStart; timelineEnd = newTimelineEnd; } } public void resetZoom(WMV_World p, boolean fade) { float newTimelineStart = 0.f; float newTimelineEnd = utilities.getTimePVectorSeconds(new PVector(24,0,0)); if(fade) { timelineTransition(newTimelineStart, newTimelineEnd, initTimelineTransitionLength, mv.frameCount); } else { timelineStart = newTimelineStart; timelineEnd = newTimelineEnd; } } /** * Get current zoom level * @return Zoom level */ public float getZoomLevel() { float day = utilities.getTimePVectorSeconds(new PVector(24,0,0)); // Seconds in a day float result = (timelineEnd - timelineStart) / day; return result; } /** * Start timeline zoom transition * @param p Parent world * @param direction -1: In 1: Out * @param transition Whether to use smooth zooming transition */ public void zoomTimeline(WMV_World p, int direction, boolean transition) { boolean zoom = true; transitionZoomDirection = direction; float length = timelineEnd - timelineStart; float newLength; float day = utilities.getTimePVectorSeconds(new PVector(24,0,0)); // Seconds in a day if(transitionZoomDirection == -1) // Zooming in newLength = length * transitionZoomInIncrement; else // Zooming out newLength = length * transitionZoomOutIncrement; float newTimelineStart, newTimelineEnd; if(transitionZoomDirection == -1) // Zooming in { float diff = length - newLength; newTimelineStart = timelineStart + diff / 2.f; newTimelineEnd = timelineEnd - diff / 2.f; } else // Zooming out { float diff = newLength - length; newTimelineStart = timelineStart - diff / 2.f; newTimelineEnd = timelineEnd + diff / 2.f; if(newTimelineEnd > day) { newTimelineStart -= (newTimelineEnd - day); newTimelineEnd = day; } if(newTimelineStart < 0.f) { newTimelineEnd -= newTimelineStart; newTimelineStart = 0.f; } if(newTimelineEnd > day) zoom = false; } if(zoom) { WMV_Field f = p.getCurrentField(); float first = f.getTimeSegment(0).getLower().getAbsoluteTime(); // First field media time, normalized float last = f.getTimeSegment(f.getTimeline().timeline.size()-1).getUpper().getAbsoluteTime(); // Last field media time, normalized if(transitionZoomDirection == 1) { if(length - newLength > 300.f) { newTimelineStart = utilities.roundSecondsToInterval(newTimelineStart, 600.f); // Round up to nearest 10 min. if(newTimelineStart > first) newTimelineStart -= 600; newTimelineEnd = utilities.roundSecondsToInterval(newTimelineEnd, 600.f); // Round up to nearest 10 min. if(newTimelineEnd < last) newTimelineEnd += 600; } } if(newTimelineEnd > day) newTimelineEnd = day; if(newTimelineStart < 0.f) newTimelineEnd = 0.f; if(transition) { timelineTransition( newTimelineStart, newTimelineEnd, 10, mv.frameCount ); // timelineTransition( timelineStart, newTimelineEnd, 10, ml.frameCount ); timelineZooming = true; } else timelineEnd = newTimelineEnd; } } /** * Zoom by a factor * @param p Parent world * @param amount Factor to zoom by * @param transition Whether to use smooth zooming transition */ public void zoomByAmount(WMV_World p, float amount, boolean transition) { float length = timelineEnd - timelineStart; float newLength = length * amount; float result = timelineStart + newLength; if(result < utilities.getTimePVectorSeconds(new PVector(24,0,0))) { WMV_Field f = p.getCurrentField(); float last = f.getTimeSegment(f.getTimeline().timeline.size()-1).getUpper().getAbsoluteTime(); // Last field media time, normalized float day = utilities.getTimePVectorSeconds(new PVector(24,0,0)); // Seconds in a day float newTimelineEnd; if(length - newLength > 300.f) { newTimelineEnd = utilities.roundSecondsToInterval(result, 600.f); // Round up to nearest 10 min. if(newTimelineEnd < last) newTimelineEnd += 600; } else newTimelineEnd = result; // Changing length less than 5 min., no rounding if(newTimelineEnd > day) newTimelineEnd = day; if(transition) timelineTransition(timelineStart, newTimelineEnd, initTimelineTransitionLength, mv.frameCount); else timelineEnd = newTimelineEnd; } } /** * Start scrolling timeline in specified direction * @param p Parent world * @param direction Left: -1 or Right: 1 */ public void scroll(WMV_World p, int direction) { transitionScrollDirection = direction; float newStart = timelineStart + transitionScrollIncrement * transitionScrollDirection; float newEnd = timelineEnd + transitionScrollIncrement * transitionScrollDirection; float day = utilities.getTimePVectorSeconds(new PVector(24,0,0)); if(newStart > 0.f && newEnd < day) { timelineScrolling = true; timelineTransition(newStart, newEnd, 10, mv.frameCount); } } /** * Stop zooming the timeline */ public void stopZooming() { timelineZooming = false; updateFieldTimeline = true; transitionScrollIncrement = initTransitionScrollIncrement * getZoomLevel(); } /** * Stop scrolling the timeline */ public void stopScrolling() { timelineScrolling = false; updateFieldTimeline = true; } /** * Handle mouse released event * @param p Parent world * @param mouseX Mouse x position * @param mouseY Mouse y position */ public void handleMapViewMouseReleased(WMV_World p, float mouseX, float mouseY) { updateMapViewMouse(p); for(MV_Button b : buttons) { if( b.isSelected() && b.containsPoint(new PVector(mouseX, mouseY) )) { switch(b.getID()) { case 0: // Zoom to Viewer map2D.zoomToCluster(mv.world, mv.world.getCurrentCluster(), true); // Zoom to current cluster break; case 1: // Zoom to Field map2D.zoomToField(mv.world.getCurrentField(), true); break; case 2: // Zoom to World map2D.resetMapZoom(true); // map2D.zoomToWorld(true); break; case 3: // Pan Up map2D.stopPanning(); break; case 4: // Pan Left map2D.stopPanning(); break; case 5: // Pan Right map2D.stopPanning(); break; case 6: // Pan Down map2D.stopPanning(); break; case 7: // Zoom In map2D.stopZooming(); break; case 8: // Zoom Out map2D.stopZooming(); break; case 10: // Set Map View: World Mode setMapViewMode(0); break; case 11: // Set Map View: Field Mode setMapViewMode(1); break; // PRESSED // case "MapZoomIn": // if(map2D.isZooming()) // map2D.stopZooming(); // else // map2D.startZoomingIn(ml.world); // break; // case "MapZoomOut": // if(map2D.isZooming()) // map2D.stopZooming(); // else // map2D.startZoomingOut(ml.world); // break; // case "PanUp": // if(map2D.isPanning()) // map2D.stopPanning(); // else // map2D.panUp(); // break; // case "PanLeft": // if(map2D.isPanning()) // map2D.stopPanning(); // else // map2D.panLeft(); // break; // case "PanDown": // if(map2D.isPanning()) // map2D.stopPanning(); // else // map2D.panDown(); // break; // case "PanRight": // if(map2D.isPanning()) // map2D.stopPanning(); // else // map2D.panRight(); // break; // CLICKED // case "PanUp": // if(map2D.isPanning()) // map2D.stopPanning(); // break; // case "PanLeft": // if(map2D.isPanning()) // map2D.stopPanning(); // break; // case "PanDown": // if(map2D.isPanning()) // map2D.stopPanning(); // break; // case "PanRight": // if(map2D.isPanning()) // map2D.stopPanning(); // break; // case "ZoomToViewer": // map2D.zoomToCluster(ml.world, ml.world.getCurrentCluster(), true); // Zoom to current cluster // break; // case "ZoomToField": // map2D.zoomToField(ml.world.getCurrentField(), true); // break; // case "MapZoomIn": // if(map2D.isZooming()) // map2D.stopZooming(); // break; // case "ResetMapZoom": // map2D.resetMapZoom(true); // // map2D.zoomToWorld(true); // break; // case "MapZoomOut": // if(map2D.isZooming()) // map2D.stopZooming(); // break; // // RELEASED // case "PanUp": // case "PanLeft": // case "PanDown": // case "PanRight": // display.map2D.stopPanning(); // break; // case "MapZoomIn": // case "MapZoomOut": // display.map2D.stopZooming(); // break; } b.setSelected(false); } } if(map2D.mousePressedFrame > map2D.mouseDraggedFrame) { if(getDisplayView() == 1) // In Map View { if(mapViewMode == 1) // Field Mode { System.out.println("Display.handleMapViewMouseReleased()... map2D.selectedCluster:"+map2D.selectedCluster+" getCurrentField().getClusters().size():"+mv.world.getCurrentField().getClusters().size()+"..."); if(map2D.selectedCluster >= 0 && map2D.selectedCluster < mv.world.getCurrentField().getClusters().size()) { if(map2D.selectedCluster != mv.world.viewer.getState().getCurrentClusterID()) map2D.zoomToCluster(mv.world, mv.world.getCurrentField().getCluster(map2D.selectedCluster), true); System.out.println("Display.handleMapViewMouseReleased()... Started zooming, will moveToClusterOnMap()..."); mv.world.viewer.moveToClusterOnMap(map2D.selectedCluster, true); // Move to cluster on map and stay in Map View } } else if(mapViewMode == 0) // World Mode { if(map2D.selectedField >= 0 && map2D.selectedField < mv.world.getFields().size()) { currentDisplayCluster = 0; map2D.selectedCluster = -1; map2D.zoomToField(mv.world.getField(map2D.selectedField), true); } } } } } /** * Handle mouse released event * @param p Parent world * @param mouseX Mouse x position * @param mouseY Mouse y position */ public void handleMapViewMousePressed(WMV_World p, float mouseX, float mouseY) { updateMapViewMouse(p); for(MV_Button b : buttons) { if( b.isSelected() && b.containsPoint(new PVector(mouseX, mouseY)) ) { switch(b.getID()) { // case 0: // Zoom to Viewer // map2D.zoomToCluster(ml.world, ml.world.getCurrentCluster(), true); // Zoom to current cluster // break; // case 1: // Zoom to Field // map2D.zoomToField(ml.world.getCurrentField(), true); // break; // case 2: // Zoom to World // map2D.resetMapZoom(true); // // map2D.zoomToWorld(true); // break; case 3: // Pan Up if(map2D.isPanning()) map2D.stopPanning(); else map2D.panUp(); break; case 4: // Pan Left if(map2D.isPanning()) map2D.stopPanning(); else map2D.panLeft(); break; case 5: // Pan Right if(map2D.isPanning()) map2D.stopPanning(); else map2D.panRight(); break; case 6: // Pan Down if(map2D.isPanning()) map2D.stopPanning(); else map2D.panDown(); break; case 7: // Zoom In if(map2D.isZooming()) map2D.stopZooming(); else map2D.startZoomingIn(mv.world); break; case 8: // Zoom Out if(map2D.isZooming()) map2D.stopZooming(); else map2D.startZoomingOut(mv.world); break; // PRESSED // // case "MapZoomIn": // if(map2D.isZooming()) // map2D.stopZooming(); // else // map2D.startZoomingIn(ml.world); // break; // case "MapZoomOut": // if(map2D.isZooming()) // map2D.stopZooming(); // else // map2D.startZoomingOut(ml.world); // break; // case "PanUp": // if(map2D.isPanning()) // map2D.stopPanning(); // else // map2D.panUp(); // break; // case "PanLeft": // if(map2D.isPanning()) // map2D.stopPanning(); // else // map2D.panLeft(); // break; // case "PanDown": // if(map2D.isPanning()) // map2D.stopPanning(); // else // map2D.panDown(); // break; // case "PanRight": // if(map2D.isPanning()) // map2D.stopPanning(); // else // map2D.panRight(); // break; // CLICKED // case "PanUp": // if(map2D.isPanning()) // map2D.stopPanning(); // break; // case "PanLeft": // if(map2D.isPanning()) // map2D.stopPanning(); // break; // case "PanDown": // if(map2D.isPanning()) // map2D.stopPanning(); // break; // case "PanRight": // if(map2D.isPanning()) // map2D.stopPanning(); // break; // case "ZoomToViewer": // map2D.zoomToCluster(ml.world, ml.world.getCurrentCluster(), true); // Zoom to current cluster // break; // case "ZoomToField": // map2D.zoomToField(ml.world.getCurrentField(), true); // break; // case "MapZoomIn": // if(map2D.isZooming()) // map2D.stopZooming(); // break; // case "ResetMapZoom": // map2D.resetMapZoom(true); // // map2D.zoomToWorld(true); // break; // case "MapZoomOut": // if(map2D.isZooming()) // map2D.stopZooming(); // break; // // RELEASED // case "PanUp": // case "PanLeft": // case "PanDown": // case "PanRight": // display.map2D.stopPanning(); // break; // case "MapZoomIn": // case "MapZoomOut": // display.map2D.stopZooming(); // break; } b.setSelected(false); } } } /** * Handle mouse released event * @param p Parent world * @param mouseX Mouse x position * @param mouseY Mouse y position */ public void handleTimeViewMouseReleased(WMV_World p, float mouseX, float mouseY) { updateTimelineMouse(p); if(selectedTime != -1) if(selectedCluster != -1) p.viewer.teleportToCluster(selectedCluster, false, selectableTimeSegments.get(selectedTime).segment.getFieldTimelineID()); if(selectedDate != -1) setCurrentSelectableDate(selectedDate); for(MV_Button b : buttons) { if( b.isSelected() && b.containsPoint(new PVector(mouseX, mouseY) )) { switch(b.getID()) { case 0: // Scroll left stopScrolling(); break; case 1: // Scroll right stopScrolling(); break; case 2: // Zoom in stopZooming(); break; case 3: // Zoom out stopZooming(); break; case 4: // Zoom out mv.display.zoomToTimeline(mv.world, true); break; case 5: // Zoom out mv.display.zoomToCurrentSelectableTimeSegment(mv.world, true); break; case 6: // Zoom out mv.display.zoomToCurrentSelectableDate(mv.world, true); break; case 7: // Zoom out mv.display.resetZoom(mv.world, true); break; // case "TimelineZoomToFit": 4 // ml.display.zoomToTimeline(ml.world, true); // break; // case "TimelineZoomToSelected": 5 // ml.display.zoomToCurrentSelectableTimeSegment(ml.world, true); // break; // case "TimelineZoomToDate": 6 // ml.display.zoomToCurrentSelectableDate(ml.world, true); // break; // case "TimelineZoomToFull": 7 // ml.display.resetZoom(ml.world, true); // break; // PRESSED // // case "TimelineZoomIn": // if(isZooming()) // stopZooming(); // else // zoom(ml.world, -1, true); // break; // case "TimelineZoomOut": // if(isZooming()) // stopZooming(); // else // zoom(ml.world, 1, true); // break; // case "TimelineReverse": // if(isScrolling()) // stopScrolling(); // else // scroll(ml.world, -1); // break; // case "TimelineForward": // if(isScrolling()) // stopScrolling(); // else // scroll(ml.world, 1); // break; // CLICKED // case "TimelineZoomIn": // stopZooming(); // break; // case "TimelineZoomOut": // stopZooming(); // break; // case "TimelineZoomToFit": // zoomToTimeline(ml.world, true); // break; // case "TimelineZoomToSelected": // zoomToCurrentSelectableTimeSegment(ml.world, true); // break; // case "TimelineZoomToDate": // zoomToCurrentSelectableDate(ml.world, true); // break; // case "TimelineZoomToFull": // resetZoom(ml.world, true); // break; // RELEASED // case "TimelineZoomIn": // stopZooming(); // break; // case "TimelineZoomOut": // stopZooming(); // break; // case "TimelineReverse": // stopScrolling(); // break; // case "TimelineForward": // stopScrolling(); // break; } b.setSelected(false); } } } /** * Handle mouse released event * @param p Parent world * @param mouseX Mouse x position * @param mouseY Mouse y position */ public void handleTimeViewMousePressed(WMV_World p, float mouseX, float mouseY) { updateTimelineMouse(p); if(selectedTime != -1) if(selectedCluster != -1) p.viewer.teleportToCluster(selectedCluster, false, selectableTimeSegments.get(selectedTime).segment.getFieldTimelineID()); if(selectedDate != -1) setCurrentSelectableDate(selectedDate); for(MV_Button b : buttons) { if( b.isSelected() && b.containsPoint(new PVector(mouseX, mouseY)) ) { switch(b.getID()) { case 0: // Scroll left if(isScrolling()) stopScrolling(); else scroll(mv.world, -1); break; case 1: // Scroll right if(isScrolling()) stopScrolling(); else scroll(mv.world, 1); break; case 2: // Zoom in if(isZooming()) stopZooming(); else zoomTimeline(mv.world, -1, true); break; case 3: // Zoom out if(isZooming()) stopZooming(); else zoomTimeline(mv.world, 1, true); break; // PRESSED // // case "TimelineZoomIn": // if(isZooming()) // stopZooming(); // else // zoom(ml.world, -1, true); // break; // case "TimelineZoomOut": // if(isZooming()) // stopZooming(); // else // zoom(ml.world, 1, true); // break; // case "TimelineReverse": // if(isScrolling()) // stopScrolling(); // else // scroll(ml.world, -1); // break; // case "TimelineForward": // if(isScrolling()) // stopScrolling(); // else // scroll(ml.world, 1); // break; // CLICKED // case "TimelineZoomIn": // stopZooming(); // break; // case "TimelineZoomOut": // stopZooming(); // break; // case "TimelineZoomToFit": // zoomToTimeline(ml.world, true); // break; // case "TimelineZoomToSelected": // zoomToCurrentSelectableTimeSegment(ml.world, true); // break; // case "TimelineZoomToDate": // zoomToCurrentSelectableDate(ml.world, true); // break; // case "TimelineZoomToFull": // resetZoom(ml.world, true); // break; // RELEASED // case "TimelineZoomIn": // stopZooming(); // break; // case "TimelineZoomOut": // stopZooming(); // break; // case "TimelineReverse": // stopScrolling(); // break; // case "TimelineForward": // stopScrolling(); // break; } b.setSelected(false); } } } /** * Handle mouse released event in Library View * @param p Parent world * @param mouseX Mouse x position * @param mouseY Mouse y position */ public void handleLibraryViewMouseReleased(WMV_World p, float mouseX, float mouseY) { updateLibraryViewMouse(); if(selectedMedia != -1) p.viewer.startViewingMedia(0, selectedMedia); // Only images currently implemented for(MV_Button b : buttons) { if( b.isSelected() && b.containsPoint(new PVector(mouseX, mouseY) )) { switch(b.getID()) { case 0: // Set Library Display if(getLibraryViewMode() != 2) setLibraryViewMode(2); break; case 1: // Set Field Display if(getLibraryViewMode() != 1) setLibraryViewMode(1); break; case 2: // Set Cluster Display if(getLibraryViewMode() != 0) setLibraryViewMode(0); break; case 10: // Previous Location showPreviousItem(); break; case 11: // Next Location showNextItem(); break; case 12: // Current Location if(getLibraryViewMode() == 1) setDisplayItem( mv.world.viewer.getCurrentFieldID() ); else if(getLibraryViewMode() == 2) setDisplayItem( mv.world.viewer.getCurrentClusterID() ); break; } b.setSelected(false); } } } /** * Handle mouse released event in Library View * @param p Parent world * @param mouseX Mouse x position * @param mouseY Mouse y position */ public void handleMediaViewMouseReleased(WMV_World p, float mouseX, float mouseY) { p.viewer.exitMediaView(); } /** * Draw Interactive Clustering screen * @param p Parent world */ void displayInteractiveClustering(WMV_World p) { map2D.displaySatelliteMap(p); if(messages.size() > 0) displayMessages(p); } /** * Reset all HUD displays */ public void reset() { // ml = parent; /* Display View */ displayView = 0; /* {0: Scene 1: Map 2: Library 3: Timeline 4: Media} */ /* Setup */ worldSetup = true; dataFolderFound = false; setupProgress = 0.f; /* Windows */ disableLostFocusHook = false; /* Graphics */ messageHUDDistance = hudDistanceInit * 6.f; blendMode = 0; /* Alpha blending mode */ /* Map View */ mapViewMode = 1; // {0: World, 1: Field, (2: Cluster -- In progress)} initializedMaps = false; initializedSatelliteMap = false; /* Time View */ timelineStart = 0.f; timelineEnd = 0.f; datelineStart = 0.f; datelineEnd = 0.f; displayDate = -1; updateCurrentSelectableTimeSegment = true; updateCurrentSelectableDate = true; selectableTimeSegments = new ArrayList<SelectableTimeSegment>(); selectableDates = new ArrayList<SelectableDate>(); allDates = null; fieldTimelineCreated = false; fieldDatelineCreated = false; updateFieldTimeline = true; // hudLeftMargin = 0.f; timelineYOffset = 0.f; timelineYOffset = 0.f; timelineXOffset = 0.f; datelineYOffset = 0.f; selectedTime = -1; selectedCluster = -1; currentSelectableTimeSegmentID = -1; currentSelectableTimeSegmentFieldTimeSegmentID = -1; selectedDate = -1; currentSelectableDate = -1; currentSelectableTimeSegment = null; currentSelectableTimeSegmentID = -1; currentSelectableTimeSegmentFieldTimeSegmentID = -1; timelineTransition = false; timelineZooming = false; timelineScrolling = false; transitionScrollDirection = -1; transitionZoomDirection = -1; timelineTransitionStartFrame = 0; timelineTransitionEndFrame = 0; timelineTransitionLength = 30; timelineStartTransitionStart = 0; timelineStartTransitionTarget = 0; timelineEndTransitionStart = 0; timelineEndTransitionTarget = 0; transitionScrollIncrement = 1750.f; /* Library View */ libraryViewMode = 2; currentDisplayField = 0; currentDisplayCluster = 0; createdSelectableMedia = false; selectableMedia = null; currentSelectableMedia = null; /* Current selected media in grid */ selectedMedia = -1; updateSelectableMedia = true; /* Media View */ mediaViewMediaType = -1; mediaViewMediaID = -1; messageStartFrame = -1; metadataStartFrame = -1; startupMessageStartFrame = -1; screenWidth = mv.displayWidth; screenHeight = mv.displayHeight; // float aspect = (float)screenHeight / (float)screenWidth; // if(aspect != 0.625f) // monitorOffsetXAdjustment = (0.625f / aspect); startupMessages = new ArrayList<String>(); messages = new ArrayList<String>(); metadata = new ArrayList<String>(); /* 3D HUD Displays */ messageXOffset = screenWidth * 1.75f; messageYOffset = -screenHeight * 0.33f; metadataXOffset = -screenWidth * 1.33f; metadataYOffset = -screenHeight / 2.f; /* 2D HUD Displays */ // timelineScreenSize = screenWidth * 0.86f; // timelineHeight = screenHeight * 0.1f; timelineStart = 0.f; timelineEnd = utilities.getTimePVectorSeconds(new PVector(24,0,0)); // timelineYOffset = screenHeight * 0.33f; // hudCenterXOffset = screenWidth * 0.5f; // hudTopMargin = screenHeight * 0.085f; // timelineXOffset = screenWidth * 0.07f; // datelineYOffset = screenHeight * 0.5f; setupScreen(); map2D.reset(); startWorldSetup(); // Start World Setup Display Mode after reset // messageFont = ml.createFont("ArialNarrow-Bold", messageTextSize); // defaultFont = ml.createFont("SansSerif", smallTextSize); } /** * Add message to queue * @param ml Parent app * @param message Message to send */ public void message(MetaVisualizer ml, String message) { if(ml.state.interactive) { messages.add(message); while(messages.size() > maxMessages) messages.remove(0); } else { messageStartFrame = ml.world.getState().frameCount; messages.add(message); while(messages.size() > maxMessages) messages.remove(0); } } /** * Get current HUD Distance along Z-Axis * @return Current HUD Z-Axis Distance */ public float getMessageHUDDistance() { float distance = messageHUDDistance; distance /= (Math.sqrt(mv.world.viewer.getSettings().fieldOfView)); return distance; } /** * Get current HUD Distance along Z-Axis * @return Current HUD Z-Axis Distance */ public float getMessageTextSize() { return largeTextSize * mv.world.viewer.getSettings().fieldOfView * 3.f; } /** * Display current messages * @p Parent world */ void displayMessages(WMV_World p) { float xFactor = (float) Math.pow( mv.world.viewer.getSettings().fieldOfView * 12.f, 3) * 0.33f; float yFactor = mv.world.viewer.getSettings().fieldOfView * 4.f; float xPos = messageXOffset * xFactor; float yPos = messageYOffset * yFactor - lineWidth * yFactor; mv.pushMatrix(); mv.fill(0, 0, 255, 255); mv.textFont(messageFont); // float hudDist = getMessageHUDDistance(); if(mv.state.interactive) { for(String s : messages) { yPos += lineWidth * yFactor; displayScreenText(mv, s, xPos, yPos += lineWidth * yFactor, getMessageTextSize()); } } else if(mv.frameCount - messageStartFrame < messageDuration) { for(String s : messages) { yPos += lineWidth * yFactor; displayScreenText(mv, s, messageXOffset, yPos, getMessageTextSize()); } } else { clearMessages(); // Clear messages after duration has ended } mv.popMatrix(); } /** * Add a metadata message (single line) to the display queue * @param curFrameCount Current frame count * @param message Line of metadata */ public void metadata(int curFrameCount, String message) { metadataStartFrame = curFrameCount; metadata.add(message); while(metadata.size() > 16) metadata.remove(0); } /** * Draw current metadata messages to the screen * @param p Parent world */ public void displayMetadata(WMV_World p) { float xFactor = mv.world.viewer.getSettings().fieldOfView * 8.f; float yFactor = mv.world.viewer.getSettings().fieldOfView * 4.f; float yPos = metadataYOffset * yFactor - lineWidth * yFactor; mv.textFont(defaultFont); mv.pushMatrix(); mv.fill(0, 0, 255, 255); // White text mv.textSize(mediumTextSize); float xOffset = metadataXOffset * xFactor; for(String s : metadata) { yPos += lineWidth * yFactor; displayScreenText(mv, s, metadataXOffset, yPos, getMessageTextSize()); } mv.popMatrix(); } public void displayScreenText(MetaVisualizer ml, String text, float x, float y, float textSize) { ml.textSize(textSize); startHUD(); ml.text(text, x, y, getMessageHUDDistance()); // Use period character to draw a point } /** * @param message Message to be sent * Add startup message to display queue */ public void sendSetupMessage(WMV_World p, String message) { if(worldSetup) { startupMessageStartFrame = mv.frameCount; startupMessages.add(message); while(startupMessages.size() > 16) startupMessages.remove(0); if(mv.debug.print) System.out.println(message); } } /** * Display startup windows * @param Parent world */ public void displayStartup(WMV_World p, boolean librarySetup) { startHUD(); mv.pushMatrix(); mv.fill(0, 0, 245.f, 255.f); mv.textSize(largeTextSize * 1.5f); if(worldSetup) // Showing setup messages + windows { if(mv.createNewLibrary) { if(mv.state.chooseMediaFolders) { // ml.text("Please select media folder(s)...", screenWidth / 2.1f, yPos += lineWidthVeryWide * 5.f, hudDistanceInit); if(!window.setupCreateLibraryWindow) { window.showCreateLibraryWindow = true; window.openCreateLibraryWindow(); mv.library = new MV_Library(""); // Create new library } } else if(!mv.state.selectedNewLibraryDestination) { window.setCreateLibraryWindowText("Please select new library destination...", null); } } else { if(mv.state.startup && !mv.state.selectedLibrary) { if(!mv.state.gettingExiftoolPath) // Getting Exiftool program filepath { if(!window.setupStartupWindow) window.openStartupWindow(); // Open Startup Window else if(!window.showStartupWindow) window.showStartupWindow(false); // Show Startup Window } } } mv.textSize(largeTextSize); // p.p.text("For support and the latest updates, visit: www.spatializedmusic.com/MultimediaLocator", screenWidth / 2.f, yPos, hudDistance); } else { displayMessages(p); } mv.popMatrix(); } /** * Draw Library View * @param p Parent world */ public void displayLibraryView(WMV_World p) { mv.rectMode(PApplet.CORNER); // Specify top left point in rect() -- Needed? WMV_Field f;// = p.getCurrentField(); mv.textFont(defaultFont); // = ml.createFont("SansSerif", 30); startDisplayHUD(); mv.pushMatrix(); for(MV_Button b : buttons) { if(libraryViewMode > 0) { b.display(p, 0.f, 0.f, 255.f); } else { if(b.getID() < 3) b.display(p, 0.f, 0.f, 255.f); } } mv.textFont(defaultFont); // = ml.createFont("SansSerif", 30); float x = hudCenterXOffset - buttonWidth * 2.f - buttonSpacing * 4.f; float y = hudTopMargin + buttonHeight * 0.5f; // Starting vertical position // float y = hudTopMargin + buttonHeight * 2.5f; // Starting vertical position mv.fill(0, 0, 255, 255); mv.textSize(hudSmallTextSize); mv.text("Current View:", x, y, 0); y += buttonHeight + buttonSpacing; switch(libraryViewMode) { case 1: // Field mv.text("Go To Field:", x - buttonSpacing * 0.5f, y, 0); break; case 2: // Location (Cluster) mv.text("Go To Location:", x - buttonSpacing * 0.5f, y, 0); break; } x = hudLeftMargin + buttonWidth * 0.75f; y = hudTopMargin + buttonHeight * 0.5f; // Starting vertical position mv.textSize(hudSmallTextSize); WMV_Cluster c = p.getCurrentCluster(); if(currentDisplayCluster != c.getID()) { String strGPS = mv.utilities.formatGPSLocation( mv.world.viewer.getGPSLocation(), false ); mv.text("Current Location:", x, y, 0); mv.text(strGPS, x, y += hudLineWidthWide, 0); } mv.popMatrix(); endDisplayHUD(); c = null; // WMV_Cluster c = null; x = hudCenterXOffset; y = hudTopMargin + buttonHeight * 5.f; // Starting vertical position switch(libraryViewMode) { case 0: // Library f = p.getCurrentField(); startDisplayHUD(); mv.pushMatrix(); mv.fill(0.f, 0.f, 255.f, 255.f); mv.textSize(hudVeryLargeTextSize); if(mv.library.getName(false) != null && mv.library.getName(false) != "") mv.text(mv.library.getName(false), x, y); else mv.text("Untitled Environment", x, y); y += hudLineWidthVeryWide; // y += hudLineWidthVeryWide + buttonHeight + buttonSpacing * 2.f; // ml.textSize(hudMediumTextSize); // ml.text(ml.world.getCurrentField().getName(), x, y); // ml.text("Single Field Environment", x, y ); // ml.text("No Current Library", x, y += lineWidthWide * 1.5f); // } // else // { // y += hudLineWidthWide + buttonHeight * 2.f + buttonSpacing * 2.f; // // ml.textSize(hudLargeTextSize); // if(ml.library.getName(false) != null && ml.library.getName(false) != "") // ml.text(ml.library.getName(false), x, y += lineWidthWide * 1.5f); // else // ml.text("Untitled Environment", x, y += lineWidthWide * 1.5f); // } mv.textSize(hudSmallTextSize); if(mv.world.getFieldCount() > 1) mv.text("Current Field: "+mv.world.getCurrentField().getName()+", #"+ (f.getID()+1)+" of "+ mv.world.getFields().size(), x, y += lineWidthWide); else mv.text("Current Field: "+mv.world.getCurrentField().getName()+" (Single Field Environment)", x, y); mv.text(" Library Location: "+mv.library.getLibraryFolder(), x, y += lineWidthWide); mv.text(" Output Folder: "+(mv.world.outputFolder==null?"None":mv.world.outputFolder), x, y += lineWidth); mv.popMatrix(); endDisplayHUD(); break; case 1: // Field f = p.getField(currentDisplayField); startDisplayHUD(); mv.pushMatrix(); mv.fill(0, 0, 255, 255); mv.textSize(hudVeryLargeTextSize); if(currentDisplayField == mv.world.getCurrentField().getID()) mv.text(mv.world.getCurrentField().getName()+" (Current)", x, y); else mv.text(mv.world.getCurrentField().getName(), x, y); y += hudLineWidthVeryWide; mv.textSize(hudMediumTextSize); if(mv.library.getName(false) != null && mv.library.getName(false) != "") mv.text("Environment: "+mv.library.getName(false), x, y); else if(mv.world.getFields().size()>1) mv.text("Environment: "+"Untitled (Not Saved)", x, y); y += hudLineWidthWide * 1.5f; c = p.getCurrentCluster(); mv.textSize(hudSmallTextSize); // if(ml.world.getFieldCount() > 1) // ml.text("Field #"+ (f.getID()+1)+" of "+ ml.world.getFields().size(), x, y); // ml.textSize(hudMediumTextSize); // ml.text(" Points of Interest: "+(f.getClusters().size()), x, y += hudLineWidthWide, 0); mv.textSize(hudSmallTextSize); mv.text("Spatial Locations: "+(f.getClusters().size()), x, y, 0); // ml.text(" Visible: "+ml.world.getVisibleClusters().size(), x, y += hudLineWidth); mv.text("Time Segments: "+(f.getTimeline().timeline.size()), x, y += hudLineWidth, 0); mv.text( "Field Width: " + utilities.round( f.getModel().getState().fieldWidth, 3 )+ " Length: "+utilities.round( f.getModel().getState().fieldLength, 3)+ " Height: " + utilities.round( f.getModel().getState().fieldHeight, 3 ), x, y += hudLineWidth * 2.f); mv.text(" Media Density (per sq. m.): "+utilities.round( f.getModel().getState().mediaDensity, 3 ), x, y += hudLineWidthWide); // ml.textSize(hudMediumTextSize); // ml.text(" Viewer ", x, y += hudLineWidthWide, 0); mv.textSize(hudSmallTextSize); // ml.text("Viewer Location "+(f.getClusters().size()), x, y += hudLineWidth, 0); // if(c != null) // ml.text("Viewer Location: " + ml.utilities.formatGPSLocation( ml.world.viewer.getGPSLocation() ) + " (#" + (c.getID()+1) + ")", x, y += hudLineWidth, 0); // ml.text(" Time ", x, y += hudLineWidth, 0); // String strTime = getCurrentFormattedTime(); if(mv.world.getState().getTimeMode() == 0) // Location { int tsID = mv.world.viewer.getCurrentFieldTimeSegment(); // WMV_TimeSegment ts = ml.world.getCurrentField().getTimeline().timeline.get(tsID); WMV_Time t = c.getClosestTimeToClusterTime( c.getCurrentTime() ); // String strClusterTime = t.getFormattedTime(true, false); // String strFieldTime = ts.getCenter().getFormattedTime(true, false); mv.text("Current Time Segment #"+tsID+" of "+mv.world.getCurrentField().getTimeline().timeline.size()+" (#"+(t.getID()+1)+" of "+c.getTimeline().timeline.size()+" at current location)", x, y += hudLineWidthWide, 0); //// ml.text(""+ strFieldTime + ", #"+tsID+" of "+ml.world.getCurrentField().getTimeline().timeline.size(), x, y += hudLineWidth, 0); //// ml.text(" Visible: "+ml.world.getVisibleClusters().size(), x, y += hudLineWidth); } else // Field { int tsID = mv.world.viewer.getCurrentFieldTimeSegment(); // WMV_TimeSegment ts = ml.world.getCurrentField().getTimeline().timeline.get(tsID); // String strFieldTime = ts.getCenter().getFormattedTime(true, false); mv.text("Current Time Segment #"+tsID+" of "+mv.world.getCurrentField().getTimeline().timeline.size(), x, y += hudLineWidth, 0); //// ml.text(" Visible: "+ml.world.getVisibleClusters().size(), x, y += hudLineWidth); } mv.text(" Time Mode: "+(mv.world.getState().getTimeMode() == 0 ? "Location":"Field"), x, y += hudLineWidth, 0); // ml.text(" Merged: "+f.getModel().getState().mergedClusters+" out of "+(f.getModel().getState().mergedClusters+f.getClusters().size())+" Total", x, y += hudLineWidth, 0); // if(p.getState().hierarchical) ml.text(" Current Cluster Depth: "+f.getState().clusterDepth, x, y += hudLineWidth, 0); // ml.text(" Minimum Distance: "+p.settings.minClusterDistance, x, y += hudLineWidth, 0); // ml.text(" Maximum Distance: "+p.settings.maxClusterDistance, x, y += hudLineWidth, 0); // ml.text(" Population Factor: "+f.getModel().getState().clusterPopulationFactor, x, y += hudLineWidth, 0); mv.text(" Images: "+f.getImageCount()+" Visible Range: "+f.getImagesVisible(), x, y += hudLineWidth); mv.text(" Panoramas: "+f.getPanoramaCount()+" Visible Range: "+f.getPanoramasVisible(), x, y += hudLineWidth); mv.text(" Videos: "+f.getVideoCount()+" Visible Range: "+f.getVideosVisible()+" Playing: "+f.getVideosPlaying(), x, y += hudLineWidth); mv.text(" Sounds: "+f.getSoundCount()+" In Audible Range: "+f.getSoundsAudible()+" Playing: "+f.getSoundsPlaying(), x, y += hudLineWidth); // if(f.getDateline() != null) // { // ml.textSize(hudMediumTextSize); // if(f.getDateline().size() > 0) // { // int fieldDate = p.getCurrentField().getTimeSegment(p.viewer.getCurrentFieldTimeSegment()).getFieldDateID(); // ml.text(" Current Time:", x, y += hudLineWidthWide, 0); // //// ml.text(" Current Time Segment", x, y += hudLineWidthWide, 0); //// ml.text(" ID: "+ p.viewer.getCurrentFieldTimeSegment()+" of "+ p.getCurrentField().getTimeline().timeline.size() +" in Main Timeline", x, y += hudLineWidthWide, 0); //// ml.text(" Date: "+ (fieldDate)+" of "+ p.getCurrentField().getDateline().size(), x, y += hudLineWidth, 0); //// ml.text(" Date-Specific ID: "+ p.getCurrentField().getTimeSegment(p.viewer.getCurrentFieldTimeSegment()).getFieldTimelineIDOnDate() //// +" of "+ p.getCurrentField().getTimelines().get(fieldDate).timeline.size() + " in Timeline #"+(fieldDate), x, y += hudLineWidth, 0); // } // } mv.popMatrix(); endDisplayHUD(); // map2D.displaySmallBasicMap(p); // -- Display small map break; case 2: // Cluster f = p.getCurrentField(); if(currentDisplayCluster != -1) c = f.getCluster(currentDisplayCluster); // Get cluster to display info for WMV_Cluster cl = p.getCurrentCluster(); startDisplayHUD(); mv.pushMatrix(); mv.fill(0, 0, 255, 255); mv.textSize(hudVeryLargeTextSize); mv.text(" Location #"+ (c.getID()+1) + ((c.getID() == cl.getID())?" (Current)":"")+ " of "+mv.world.getCurrentField().getClusters().size(), x, y, 0); y += hudLineWidthVeryWide; mv.textSize(hudMediumTextSize); String strGPSLoc = mv.utilities.formatGPSLocation( c.getGPSLocation(mv.world), true ); mv.text(strGPSLoc, x, y, 0); if(c != null) { WMV_Time t1 = c.getTimeline().timeline.get(0).getLower(); WMV_Time t2 = c.getTimeline().timeline.get(c.getTimeline().timeline.size()-1).getUpper(); String strTime1 = t1.getFormattedTime(true, false); String strDate1 = t1.getFormattedDate(); String strTime2 = t2.getFormattedTime(true, false); String strDate2 = t2.getFormattedDate(); String strTime = strTime1 + ", "+ strDate1 + " - " + strTime2 + ", " + strDate2; mv.text(strTime, x, y += hudLineWidthWide, 0); // Display location time and date range y += hudLineWidthWide; mv.text("Field: "+p.getCurrentField().getName(), x, y, 0); mv.textSize(hudSmallTextSize); if(f.getImageCount() > 0) mv.text(" Images: "+c.getState().images.size(), x, y += hudLineWidthVeryWide); if(f.getPanoramaCount() > 0) mv.text(" Panoramas: "+c.getState().panoramas.size(), x, y += hudLineWidth); if(f.getVideoCount() > 0) mv.text(" Videos: "+c.getState().videos.size(), x, y += hudLineWidth); if(f.getSoundCount() > 0) mv.text(" Sounds: "+c.getState().sounds.size(), x, y += hudLineWidth); mv.text(" Total Media: "+ c.getState().mediaCount, x, y += hudLineWidth, 0); mv.text(" Spatial Segments: "+ c.segments.size(), x, y += hudLineWidthWide, 0); mv.text(" Time Segments: "+ c.getTimeline().timeline.size(), x, y += hudLineWidth, 0); mv.text(" Viewer Distance: "+utilities.round(PVector.dist(c.getLocation(), p.viewer.getLocation()), 1)+" m.", x, y += hudLineWidthWide, 0); } clusterMediaYOffset = y + 65.f; // Set cluster media Y offset if(createdSelectableMedia) { drawClusterMediaGrid(); // Draw media in cluster in grid } else { ArrayList<WMV_Image> imageList = f.getImagesInCluster(c.getID(), p.getCurrentField().getImages()); if(imageList != null) createClusterSelectableMedia(p, imageList); } mv.popMatrix(); endDisplayHUD(); break; } mv.rectMode(PApplet.CENTER); // Return rect mode to Center } /** * Get current time as formatted string * @return Current time as formatted string */ public String getCurrentFormattedTime() { String strTime = "00:00:00"; if(mv.world.getState().getTimeMode() == 0) // Location { WMV_Cluster c = mv.world.getCurrentCluster(); int tsID = mv.world.viewer.getCurrentFieldTimeSegment(); // WMV_TimeSegment ts = mv.world.getCurrentField().getTimeline().timeline.get(tsID); WMV_Time t = c.getClosestTimeToClusterTime( c.getCurrentTime() ); if(t != null) strTime = t.getFormattedTime(true, false); } else // Field { int tsID = mv.world.viewer.getCurrentFieldTimeSegment(); WMV_TimeSegment ts = mv.world.getCurrentField().getTimeline().timeline.get(tsID); if(ts != null) strTime = ts.getCenter().getFormattedTime(true, false); } return strTime; } /** * Set library window text * @param newText New text */ public void updateTimeWindowCurrentTime() { String strTime = getCurrentFormattedTime()+", "+getCurrentFormattedDate(); window.lblCurrentTime.setText(strTime); } /** * Get current date as formatted string * @return */ public String getCurrentFormattedDate() { int dateID = mv.world.getState().currentDate; WMV_Date d = mv.world.getCurrentField().getDate(dateID); return d.getFormattedDate(); } /** * Create selectable media for Library View grid * @param p * @param imageList */ private void createClusterSelectableMedia(WMV_World p, ArrayList<WMV_Image> imageList) { selectableMedia = new ArrayList<SelectableMedia>(); int count = 1; float imgXPos = clusterMediaXOffset; float imgYPos = clusterMediaYOffset; // Starting vertical position for(WMV_Image i : imageList) { float origWidth = i.getWidth(); float origHeight = i.getHeight(); float thumbnailHeight = thumbnailWidth * origHeight / origWidth; /* Create thumbnail */ PImage image = mv.loadImage(i.getFilePath()); Image iThumbnail = image.getImage().getScaledInstance((int)thumbnailWidth, (int)thumbnailHeight, BufferedImage.SCALE_SMOOTH); PImage thumbnail = new PImage(iThumbnail); SelectableMedia newMedia = new SelectableMedia( i.getID(), thumbnail, new PVector(imgXPos, imgYPos), thumbnailWidth, thumbnailHeight ); selectableMedia.add(newMedia); imgXPos += thumbnailWidth + thumbnailWidth * thumbnailSpacing; if(imgXPos > mv.width - clusterMediaXOffset) { imgXPos = clusterMediaXOffset; imgYPos += thumbnailHeight + thumbnailHeight * thumbnailSpacing; } count++; // if(count > maxSelectableMedia) // break; } if(mv.debug.ml) mv.systemMessage("Display.createClusterSelectableMedia()... Created selectable media... Count: "+selectableMedia.size()+" p.ml.width:"+mv.width+"clusterMediaXOffset:"+clusterMediaXOffset); createdSelectableMedia = true; } /** * Set display item in Library View * @param itemID New item ID */ public void setDisplayItem(int itemID) { if(libraryViewMode == 1) { if(currentDisplayField != itemID) currentDisplayField = itemID; } else if(libraryViewMode == 2) { if(currentDisplayCluster != itemID) { currentDisplayCluster = itemID; updateSelectableMedia = true; } } } /** * Move to previous Display Item in Library View */ public void showPreviousItem() { if(libraryViewMode == 1) { currentDisplayField--; if(currentDisplayField < 0) currentDisplayField = mv.world.getFields().size() - 1; } else if(libraryViewMode == 2) // Cluster { currentDisplayCluster--; if(currentDisplayCluster < 0) currentDisplayCluster = mv.world.getCurrentFieldClusters().size() - 1; int count = 0; while(mv.world.getCurrentField().getCluster(currentDisplayCluster).isEmpty()) { currentDisplayCluster--; count++; if(currentDisplayCluster < 0) currentDisplayCluster = mv.world.getCurrentFieldClusters().size() - 1; if(count > mv.world.getCurrentFieldClusters().size()) break; } updateSelectableMedia = true; } } /** * Move to next Display Item in Library View */ public void showNextItem() { if(libraryViewMode == 1) { currentDisplayField++; if( currentDisplayField >= mv.world.getFields().size()) currentDisplayField = 0; } else if(libraryViewMode == 2) // Cluster { currentDisplayCluster++; if( currentDisplayCluster >= mv.world.getCurrentFieldClusters().size()) currentDisplayCluster = 0; int count = 0; while(mv.world.getCurrentField().getCluster(currentDisplayCluster).isEmpty()) { currentDisplayCluster++; count++; if( currentDisplayCluster >= mv.world.getCurrentFieldClusters().size()) currentDisplayCluster = 0; if(count > mv.world.getCurrentFieldClusters().size()) break; } updateSelectableMedia(); } } /** * Update Library View media grid items */ public void updateSelectableMedia() { updateSelectableMedia = true; } /** * Set current object viewable in Media View * @param mediaType Media type * @param mediaID Media ID */ public void setMediaViewItem(int mediaType, int mediaID) { mediaViewMediaType = mediaType; mediaViewMediaID = mediaID; if(mediaType == 2) { WMV_Video v = mv.world.getCurrentField().getVideo(mediaID); if(!v.isLoaded()) v.loadMedia(mv); if(!v.isPlaying()) v.play(mv); } } /** * Display selected media centered in window at full brightness * @param p Parent world */ private void displayMediaView(WMV_World p) { if(mediaViewMediaType > -1 && mediaViewMediaID > -1) { switch(mediaViewMediaType) { case 0: displayImage2D(p.getCurrentField().getImage(mediaViewMediaID)); break; case 1: displayPanorama2D(p.getCurrentField().getPanorama(mediaViewMediaID)); break; case 2: displayVideo2D(p.getCurrentField().getVideo(mediaViewMediaID)); break; // case 3: // -- In progress // displaySound2D(p.getCurrentField().getSound(mediaViewMediaID)); // break; } } } /** * Display image in Media View * @param image Image to display */ private void displayImage2D(WMV_Image image) { image.display2D(mv); } /** * Display 360-degree panorama texture in Media View * @param panorama Panorama to display */ private void displayPanorama2D(WMV_Panorama panorama) { panorama.display2D(mv); } /** * Display video in Media View * @param video Video to display */ private void displayVideo2D(WMV_Video video) { video.display2D(mv); } /** * Initialize 2D drawing * @param p Parent world */ public void startHUD() { mv.camera(); } /** * Initialize 2D drawing * @param p Parent world */ private void startDisplayHUD() { currentFieldOfView = mv.world.viewer.getFieldOfView(); mv.world.viewer.resetPerspective(); beginHUD(mv); } /** * End 2D drawing * @param p Parent world */ private void endDisplayHUD() { endHUD(mv); mv.world.viewer.zoomToFieldOfView(currentFieldOfView); } /** * Draw thumbnails of media in cluster in grid format * @param p Parent world * @param imageList Images in cluster */ private void drawClusterMediaGrid() { int count = 0; mv.stroke(255, 255, 255); mv.strokeWeight(15); mv.fill(0, 0, 255, 255); for(SelectableMedia m : selectableMedia) { if(m != null) { boolean selected = m.getID() == selectedMedia; if(count < 200) m.display(mv.world, 0.f, 0.f, 255.f, selected); count++; } else { mv.systemMessage("Display.drawSelectableMedia()... Selected media is null!"); } } } /** * @return Whether current view mode is a 2D display mode (true) or 3D World View (false) */ public boolean inDisplayView() { if( displayView != 0 ) return true; else return false; } /** * Set display view * @param p Parent world * @param newDisplayView New display view */ public void setDisplayView(WMV_World p, int newDisplayView) { p.viewer.setLastDisplayView( displayView ); displayView = newDisplayView; // Set display view if(mv.debug.display) System.out.println("Display.setDisplayView()... displayView:"+displayView); switch(newDisplayView) { case 0: // World View if(window.setupMainMenu) { window.optWorldView.setSelected(true); window.optMapView.setSelected(false); window.optTimelineView.setSelected(false); window.optLibraryView.setSelected(false); window.btnSaveLibrary.setEnabled(true); window.btnSaveField.setEnabled(true); } if(window.setupTimeWindow) { // window.btnTimeView.setEnabled(true); } if(setupMapView) setupMapView = false; if(setupTimeView) setupTimeView = false; if(setupLibraryView) setupLibraryView = false; break; case 1: // Map View if(!initializedMaps) { map2D.initialize(p); } else if(mv.world.getCurrentField().getGPSTracks() != null) { if(mv.world.getCurrentField().getGPSTracks().size() > 0) { if(mv.world.viewer.getSelectedGPSTrackID() != -1) { if(!map2D.createdGPSMarker) { map2D.createMarkers(mv.world); } } } } map2D.resetMapZoom(false); if(window.setupMainMenu) { window.optWorldView.setSelected(false); window.optMapView.setSelected(true); window.optTimelineView.setSelected(false); window.optLibraryView.setSelected(false); window.btnSaveLibrary.setEnabled(false); window.btnSaveField.setEnabled(false); } if(setupTimeView) setupTimeView = false; if(setupLibraryView) setupLibraryView = false; break; case 2: // Timeline View if(window.setupMainMenu) { window.optWorldView.setSelected(false); window.optMapView.setSelected(false); window.optTimelineView.setSelected(true); window.optLibraryView.setSelected(false); window.btnSaveLibrary.setEnabled(false); window.btnSaveField.setEnabled(false); } if(window.setupNavigationWindow) { // window.setMapControlsEnabled(false); // window.btnMapView.setEnabled(true); // window.btnWorldView.setEnabled(true); } if(window.setupTimeWindow) { // window.btnTimeView.setEnabled(false); // window.setTimeWindowControlsEnabled(true); } zoomToTimeline(mv.world, true); if(setupLibraryView) setupLibraryView = false; if(setupMapView) setupMapView = false; break; case 3: /* Library View */ switch(libraryViewMode) { case 0: break; case 1: setDisplayItem(p.getCurrentField().getID()); break; case 2: setDisplayItem(p.viewer.getCurrentClusterID()); break; } if(window.setupMainMenu) { window.optWorldView.setSelected(false); window.optMapView.setSelected(false); window.optTimelineView.setSelected(false); window.optLibraryView.setSelected(true); window.btnSaveLibrary.setEnabled(false); window.btnSaveField.setEnabled(false); } if(window.setupTimeWindow) { // window.btnTimeView.setEnabled(true); } if(setupTimeView) setupTimeView = false; if(setupMapView) setupMapView = false; break; case 4: // Media View break; } } /** * Set Library View Mode * @param newLibraryViewMode */ public void setLibraryViewMode(int newLibraryViewMode) { if( newLibraryViewMode >= 0 && newLibraryViewMode < 3) libraryViewMode = newLibraryViewMode; else if( newLibraryViewMode < 0 ) libraryViewMode = 2; else if( newLibraryViewMode >= 3) libraryViewMode = 0; if(window.setupPreferencesWindow) { // switch(libraryViewMode) // { // case 0: // window.optLibraryViewWorldMode.setSelected(true); // window.optLibraryViewFieldMode.setSelected(false); // window.optLibraryViewClusterMode.setSelected(false); // window.lblLibraryViewText.setText(ml.library.getName(false)); // break; // // case 1: // setDisplayItem(ml.world.getCurrentField().getID()); // window.optLibraryViewWorldMode.setSelected(false); // window.optLibraryViewFieldMode.setSelected(true); // window.optLibraryViewClusterMode.setSelected(false); // window.lblLibraryViewText.setText("Field:"); // break; // // case 2: // setDisplayItem(ml.world.viewer.getCurrentClusterID()); // window.optLibraryViewWorldMode.setSelected(false); // window.optLibraryViewFieldMode.setSelected(false); // window.optLibraryViewClusterMode.setSelected(true); // window.lblLibraryViewText.setText("Interest Point:"); // break; // } } } /** * Get Library View Mode * @return Current Library View Mode */ public int getLibraryViewMode() { return libraryViewMode; } public int getDisplayView() { return displayView; } /** * Clear previous messages */ public void clearMessages() { messages = new ArrayList<String>(); } /** * Clear previous metadata messages */ public void clearMetadata() { metadata = new ArrayList<String>(); // Reset message list } /** * Clear previous setup messages */ public void clearSetupMessages() { startupMessages = new ArrayList<String>(); } /** * Reset display modes and clear messages */ public void resetDisplayModes() { setDisplayView(mv.world, 0); // displayView = 0; mapViewMode = 0; setLibraryViewMode( 2 ); clearMessages(); clearMetadata(); } /** * Draw Interactive Clustering footer text * @param ml Parent app */ public void displayClusteringInfo(MetaVisualizer ml) { if(ml.world.state.hierarchical) { message(ml, "Hierarchical Clustering"); message(ml, " "); message(ml, "Use arrow keys UP and DOWN to change clustering depth... "); message(ml, "Use [ and ] to change Minimum Cluster Distance... "); } else { message(ml, "K-Means Clustering"); message(ml, " "); message(ml, "Use arrow keys LEFT and RIGHT to change Iterations... "); message(ml, "Use arrow keys UP and DOWN to change Population Factor... "); message(ml, "Use [ and ] to change Minimum Cluster Distance... "); } message(ml, " "); message(ml, "Press <spacebar> to restart simulation..."); } /** * Set Map View Mode * @param newMapViewMode New map view mode {0: World, 1: Field} */ public void setMapViewMode(int newMapViewMode) { if(mapViewMode != newMapViewMode) { mapViewMode = newMapViewMode; // Set Map View Mode if(!initializedMaps) { map2D.initialize(mv.world); } else { map2D.createMarkers(mv.world); // Create map markers for new mode map2D.resetMapZoom(true); switch(mapViewMode) { case 0: // World Mode btnZoomToWorld.setVisible(true); // map2D.zoomToWorld(false); break; case 1: // Field Mode btnZoomToWorld.setVisible(false); // map2D.zoomToField(ml.world, ml.world.getCurrentField(), false); break; } } } } /** * Get associated selectable time segment ID for given time segment * @param t Given time segment * @return Selectable time segment ID associated with given time segment */ private int getSelectableTimeIDOfFieldTimeSegment(WMV_TimeSegment t) { for(SelectableTimeSegment st : selectableTimeSegments) { if( t.getClusterID() == st.segment.getClusterID() && t.getClusterDateID() == st.segment.getClusterDateID() && t.getClusterTimelineID() == st.segment.getClusterTimelineID() && t.getFieldTimelineID() == st.segment.getFieldTimelineID() ) { return st.getID(); } } return -1; } /** * Set current selectable date (white rectangle) * @param newSelectableDate New selectable date ID */ private void setCurrentSelectableDate(int newSelectableDate) { if(newSelectableDate == -1 || newSelectableDate == -100) { showAllDates(); } else { displayDate = newSelectableDate; currentSelectableDate = newSelectableDate; updateFieldTimeline = true; } updateCurrentSelectableTimeSegment = true; updateCurrentSelectableDate = false; } /** * Selectable time segment on Time View timeline * @author davidgordon */ private class SelectableTimeSegment { private int id, clusterID; public float leftEdge, rightEdge, topEdge, bottomEdge; WMV_TimeSegment segment; SelectableTimeSegment(int newID, int newFieldTimelineID, int newClusterID, WMV_TimeSegment newSegment, PVector newLocation, float newLeftEdge, float newRightEdge, float newTopEdge, float newBottomEdge) { id = newID; // fieldTimelineID = newFieldTimelineID; clusterID = newClusterID; segment = newSegment; leftEdge = newLeftEdge; rightEdge = newRightEdge; topEdge = newTopEdge; bottomEdge = newBottomEdge; } public int getID() { return id; } public int getClusterID() { return clusterID; } public void display(WMV_World p, float hue, float saturation, float brightness, boolean preview) { mv.stroke(hue, saturation, brightness, 255); // Yellow rectangle around selected time segment mv.strokeWeight(3.f); mv.pushMatrix(); mv.line(leftEdge, topEdge, 0, leftEdge, bottomEdge, 0); mv.line(rightEdge, topEdge, 0, rightEdge, bottomEdge, 0); mv.line(leftEdge, topEdge, 0, rightEdge, topEdge, 0); mv.line(leftEdge, bottomEdge, 0, rightEdge, bottomEdge, 0); if(preview) { mv.fill(hue, saturation, brightness, 255); // Yellow rectangle around selected time segment mv.textSize(hudSmallTextSize); // ml.textSize(smallTextSize); String strTimespan = segment.getTimespanAsString(false, false); String strPreview = String.valueOf( segment.getTimeline().size() ) + " media, "+strTimespan; float length = timelineEnd - timelineStart; float day = utilities.getTimePVectorSeconds(new PVector(24,0,0)); // Seconds in a day float xOffset = -35.f * utilities.mapValue(length, 0.f, day, 0.2f, 1.f); mv.text(strPreview, (rightEdge+leftEdge)/2.f + xOffset, bottomEdge + 25.f, 0); } mv.popMatrix(); } } public boolean isZooming() { return timelineZooming; } public boolean isScrolling() { return timelineScrolling; } private class SelectableDate { private int id; private PVector location; public float radius; WMV_Date date; SelectableDate(int newID, PVector newLocation, float newRadius, WMV_Date newDate) { id = newID; location = newLocation; radius = newRadius; date = newDate; } public int getID() { return id; } public PVector getLocation() { return location; } /** * Display date and, if selected, preview text * @param p Parent world * @param hue Hue * @param saturation Saturation * @param brightness Brightness * @param selected Whether date is selected */ public void display(WMV_World p, float hue, float saturation, float brightness, boolean selected) { mv.pushMatrix(); mv.stroke(hue, saturation, brightness, 255.f); mv.strokeWeight(25.f); mv.point(location.x, location.y, location.z); if(selected && selectedDate != -1) { mv.fill(hue, saturation, brightness, 255); // Yellow rectangle around selected time segment mv.textSize(hudSmallTextSize); String strDate = date.getFormattedDate(); float textWidth = strDate.length() * displayWidthFactor; mv.text(strDate, location.x - textWidth * 0.5f, location.y + 30.f, location.z); // -- Should center based on actual text size! } mv.popMatrix(); } } private class SelectableMedia { private int id; private PVector location; // Screen location public float width, height; PImage thumbnail; public float leftEdge, rightEdge, topEdge, bottomEdge; SelectableMedia(int newID, PImage newThumbnail, PVector newLocation, float newWidth, float newHeight) { id = newID; thumbnail = newThumbnail; location = newLocation; width = newWidth; height = newHeight; leftEdge = location.x; rightEdge = leftEdge + width; topEdge = location.y; bottomEdge = topEdge + height; } public int getID() { return id; } public PVector getLocation() { return location; } /** * Display selection box * @param p * @param hue * @param saturation * @param brightness * @param selected */ public void display(WMV_World p, float hue, float saturation, float brightness, boolean selected) { // ml.stroke(hue, saturation, brightness, 255.f); // ml.strokeWeight(25.f); // ml.point(location.x, location.y, location.z); if(thumbnail != null) { mv.pushMatrix(); mv.translate(location.x, location.y, 0); mv.tint(255); mv.image(thumbnail, 0, 0, width, height); mv.popMatrix(); } else { mv.systemMessage("SelectableMedia.display()... Selected media #"+getID()+" thumbnail is null!"); } if(selected) { mv.stroke(hue, saturation, brightness, 255); // Yellow rectangle around selected time segment mv.strokeWeight(3.f); mv.pushMatrix(); mv.line(leftEdge, topEdge, 0, leftEdge, bottomEdge, 0); mv.line(rightEdge, topEdge, 0, rightEdge, bottomEdge, 0); mv.line(leftEdge, topEdge, 0, rightEdge, topEdge, 0); mv.line(leftEdge, bottomEdge, 0, rightEdge, bottomEdge, 0); mv.popMatrix(); } // if(selected && selectedDate != -1) // { // ml.fill(hue, saturation, brightness, 255); // Yellow rectangle around selected time segment // ml.textSize(hudSmallTextSize); // String strDate = date.getDateAsString(); // ml.text(strDate, location.x - 15.f, location.y + 50.f, location.z); // -- Should center based on actual text size! // } } } public void showAllDates() { displayDate = -1; selectedDate = -1; currentSelectableDate = -1; updateFieldTimeline = true; } public int getSelectedCluster() { return selectedCluster; } public int getCurrentSelectableTimeSegment() { return currentSelectableTimeSegmentID; } /** * Start World Setup Display Mode */ public void startWorldSetup() { worldSetup = true; } /** * Stop World Setup Display Mode */ public void stopWorldSetup() { worldSetup = false; } /** * @return Whether in World Setup Display Mode */ public boolean inWorldSetup() { return worldSetup; } /** -- Obsolete * Get mouse 3D location from screen location * @param mouseX * @param mouseY * @return */ // private PVector getMouse3DLocation(float mouseX, float mouseY) // { //// /* WORKS */ // float centerX = screenWidth * 0.5f; /* Center X location */ // float centerY = screenHeight * 0.5f; /* Center Y location */ // // float mouseXFactor = 2.55f; // float mouseYFactor = 2.55f; // float screenXFactor = 0.775f; // float screenYFactor = 0.775f; // // float x = mouseX * mouseXFactor - screenWidth * screenXFactor; // float y = mouseY * mouseYFactor - screenHeight * screenYFactor; // // float dispX = x - centerX; /* Mouse X displacement from the center */ // float dispY = y - centerY; /* Mouse Y displacement from the center */ // // float offsetXFactor = 0, offsetYFactor = 0; // if(screenWidth == 1280 && screenHeight == 800) // { // offsetXFactor = 0.111f; /* Offset X displacement from the center */ /* DEFAULT */ // offsetYFactor = 0.111f; /* Offset Y displacement from the center */ // } // else if(screenWidth == 1440 && screenHeight == 900) // { // offsetXFactor = 0.039f; /* Offset X displacement from the center */ /* SCALED x 1 */ // offsetYFactor = 0.039f; /* Offset Y displacement from the center */ // } // else if(screenWidth == 1680 && screenHeight == 1050) // { // offsetXFactor = -0.043f; /* Offset X displacement from the center */ /* SCALED x 2 */ // offsetYFactor = -0.043f; /* Offset Y displacement from the center */ // } // // float offsetX = dispX * offsetXFactor; /* Adjusted X offset */ // float offsetY = dispY * offsetYFactor; /* Adjusted Y offset */ // // x += offsetX; // y += offsetY; // //// if(ml.debug.mouse) //// System.out.println("Display.getMouse3DLocation()... screenWidth:"+screenWidth+" screenHeight:"+screenHeight+" offsetXFactor:"+offsetXFactor+" offsetYFactor:"+offsetYFactor); //// if(ml.debug.mouse) //// System.out.println("Display.getMouse3DLocation()... x2:"+x+" y2:"+y+" offsetX:"+offsetX+" offsetY:"+offsetY); // // PVector result = new PVector(x, y, hudDistanceInit); // -- Doesn't affect selection! // // if(ml.debug.mouse) // { // ml.stroke(155, 0, 255); // ml.strokeWeight(5); // ml.point(result.x, result.y, result.z); // Show mouse location for debugging // // ml.stroke(0, 255, 255); // ml.strokeWeight(10); // ml.point(centerX, centerY, hudDistanceInit); //// ml.point(0, 0, hudDistanceInit); // // System.out.println("Mouse 3D Location: x:"+result.x+" y:"+result.y); // } // // return result; // } /** * Display the main key commands on screen -- Obsolete */ // public void displayControls(WMV_World p) // { // startHUD(); // p.p.pushMatrix(); // // float xPos = centerTextXOffset; // float yPos = topTextYOffset; // Starting vertical position // // p.p.fill(0, 0, 255, 255); // p.p.textSize(largeTextSize); // p.p.text(" Keyboard Controls ", xPos, yPos, hudDistance); // // xPos = midLeftTextXOffset; // p.p.textSize(mediumTextSize); // p.p.text(" Main", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" R Restart MultimediaLocator", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" CMD + q Quit MultimediaLocator", xPos, yPos += lineWidth, hudDistance); // // p.p.textSize(mediumTextSize); // p.p.text(" Display", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" 1 Show/Hide Field Map +SHIFT to Overlay", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" 2 Show/Hide Field Statistics +SHIFT to Overlay", xPos, yPos += lineWidth, hudDistance); // p.p.text(" 3 Show/Hide Cluster Statistics +SHIFT to Overlay", xPos, yPos += lineWidth, hudDistance); // p.p.text(" 4 Show/Hide Keyboard Controls +SHIFT to Overlay", xPos, yPos += lineWidth, hudDistance); // // p.p.textSize(mediumTextSize); // p.p.text(" Time", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" T Time Fading On/Off", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" D Date Fading On/Off", xPos, yPos += lineWidth, hudDistance); // p.p.text(" space Pause On/Off ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" &/* Default Media Length - / +", xPos, yPos += lineWidth, hudDistance); // p.p.text(" SHIFT + Lt/Rt Cycle Length - / +", xPos, yPos += lineWidth, hudDistance); // p.p.text(" SHIFT + Up/Dn Current Time - / +", xPos, yPos += lineWidth, hudDistance); // // p.p.textSize(mediumTextSize); // p.p.text(" Time Navigation", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" t Teleport to Earliest Time in Field", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" T Move to Earliest Time in Field", xPos, yPos += lineWidth, hudDistance); // p.p.text(" d Teleport to Earliest Time on Earliest Date", xPos, yPos += lineWidth, hudDistance); // p.p.text(" D Move to Earliest Time on Earliest Date", xPos, yPos += lineWidth, hudDistance); // p.p.text(" n Move to Next Time Segment in Field", xPos, yPos += lineWidthWide, hudDistance); // p.p.text(" N Move to Next Time Segment in Cluster", xPos, yPos += lineWidth, hudDistance); // p.p.text(" b Move to Previous Time Segment in Field", xPos, yPos += lineWidth, hudDistance); // p.p.text(" B Move to Previous Time Segment in Cluster", xPos, yPos += lineWidth, hudDistance); // p.p.text(" l Move to Next Date in Field", xPos, yPos += lineWidth, hudDistance); // p.p.text(" L Move to Next Date in Cluster", xPos, yPos += lineWidth, hudDistance); // p.p.text(" k Move to Previous Date in Field", xPos, yPos += lineWidth, hudDistance); // p.p.text(" K Move to Previous Date in Cluster", xPos, yPos += lineWidth, hudDistance); // // xPos = centerTextXOffset; // yPos = topTextYOffset; // Starting vertical position // // /* Model */ // p.p.textSize(mediumTextSize); // p.p.text(" Model", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" [ ] Altitude Scaling Adjustment + / - ", xPos, yPos += lineWidthVeryWide, hudDistance); //// p.p.text(" , . Object Distance + / - ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" - = Object Distance - / + ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" OPTION + - Visible Angle - ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" OPTION + = Visible Angle + ", xPos, yPos += lineWidth, hudDistance); // // /* Graphics */ // p.p.textSize(mediumTextSize); // p.p.text(" Graphics", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" G Angle Fading On/Off", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" H Angle Thinning On/Off", xPos, yPos += lineWidth, hudDistance); // p.p.text(" P Transparency Mode On / Off ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" ( ) Blend Mode - / + ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" i h v Hide images / panoramas / videos ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" D Video Mode On/Off ", xPos, yPos += lineWidth, hudDistance); // // /* Movement */ // p.p.textSize(mediumTextSize); // p.p.text(" Movement", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" a d w s Walk Left / Right / Forward / Backward ", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" Arrows Turn Camera ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" q z Zoom In / Out + / - ", xPos, yPos += lineWidth, hudDistance); // // /* Navigation */ // p.p.textSize(mediumTextSize); // p.p.text(" Navigation", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" > Follow Timeline Only", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" . Follow Timeline by Date", xPos, yPos += lineWidth, hudDistance); // p.p.text(" OPTION + . Follow Dateline Only", xPos, yPos += lineWidth, hudDistance); // p.p.text(" E Move to Nearest Cluster", xPos, yPos += lineWidthWide, hudDistance); // p.p.text(" W Move to Nearest Cluster in Front", xPos, yPos += lineWidth, hudDistance); // p.p.text(" Q Move to Next Cluster in Time", xPos, yPos += lineWidth, hudDistance); // p.p.text(" A Move to Next Location in Memory", xPos, yPos += lineWidth, hudDistance); // p.p.text(" Z Move to Random Cluster", xPos, yPos += lineWidth, hudDistance); // p.p.text(" U Move to Next Video ", xPos, yPos += lineWidthWide, hudDistance); // p.p.text(" u Teleport to Next Video ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" M Move to Next Panorama ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" m Teleport to Next Panorama ", xPos, yPos += lineWidth, hudDistance); //// p.p.text(" C Lock Viewer to Nearest Cluster On/Off", xPos, yPos += lineWidthWide, hudDistance); //// p.p.text(" l Look At Selected Media", xPos, yPos += lineWidth, hudDistance); //// p.p.text(" L Look for Media", xPos, yPos += lineWidth, hudDistance); // p.p.text(" { } Teleport to Next / Previous Field ", xPos, yPos += lineWidth, hudDistance); // // xPos = midRightTextXOffset; // yPos = topTextYOffset; // Starting vertical position // // p.p.textSize(mediumTextSize); // p.p.text(" Interaction", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" O Selection Mode On/Off", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" S Multi-Selection Mode On/Off", xPos, yPos += lineWidth, hudDistance); // p.p.text(" OPTION + s Segment Selection Mode On/Off", xPos, yPos += lineWidthWide, hudDistance); // p.p.text(" x Select Media in Front", xPos, yPos += lineWidth, hudDistance); // p.p.text(" X Deselect Media in Front", xPos, yPos += lineWidth, hudDistance); // p.p.text(" OPTION + x Deselect All Media", xPos, yPos += lineWidth, hudDistance); // // p.p.textSize(mediumTextSize); // p.p.text(" GPS Tracks", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" g Load GPS Track from File", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" OPTION + g Follow GPS Track", xPos, yPos += lineWidth, hudDistance); // // p.p.textSize(mediumTextSize); // p.p.text(" Memory", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" ` Save Current View to Memory", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" ~ Follow Memory Path", xPos, yPos += lineWidth, hudDistance); // p.p.text(" Y Clear Memory", xPos, yPos += lineWidth, hudDistance); // // p.p.textSize(mediumTextSize); // p.p.text(" Output", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" o Set Image Output Folder", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" p Save Screen Image to Disk", xPos, yPos += lineWidth, hudDistance); // // p.p.popMatrix(); // } /** * Increment blendMode by given amount and call setBlendMode() * @param inc Increment to blendMode number */ // public void changeBlendMode(WMV_World p, int inc) // { // if(inc > 0) // { // if (blendMode+inc < numBlendModes) // blendMode += inc; // else // blendMode = 0; // } // else if(inc < 0) // { // { // if (blendMode-inc >= 0) // blendMode -= inc; // else // blendMode = numBlendModes - 1; // } // } // // if(inc != 0) // setBlendMode(p, blendMode); // } // /** // * Change effect of image alpha channel on blending // * @param blendMode // */ // public void setBlendMode(WMV_World p, int blendMode) { // switch (blendMode) { // case 0: // ml.blendMode(PApplet.BLEND); // break; // // case 1: // ml.blendMode(PApplet.ADD); // break; // // case 2: // ml.blendMode(PApplet.SUBTRACT); // break; // // case 3: // ml.blendMode(PApplet.DARKEST); // break; // // case 4: // ml.blendMode(PApplet.LIGHTEST); // break; // // case 5: // ml.blendMode(PApplet.DIFFERENCE); // break; // // case 6: // ml.blendMode(PApplet.EXCLUSION); // break; // // case 7: // ml.blendMode(PApplet.MULTIPLY); // break; // // case 8: // ml.blendMode(PApplet.SCREEN); // break; // // case 9: // ml.blendMode(PApplet.REPLACE); // break; // // case 10: // // blend(HARD_LIGHT); // break; // // case 11: // // blend(SOFT_LIGHT); // break; // // case 12: // // blend(OVERLAY); // break; // // case 13: // // blend(DODGE); // break; // // case 14: // // blend(BURN); // break; // } // // if (ml.debugSettings.world) // System.out.println("blendMode:" + blendMode); // } /** * Show statistics of the current simulation */ // void displayStatisticsView(WMV_World p) // { // startHUD(); // p.p.pushMatrix(); // // float xPos = centerTextXOffset; // float yPos = topTextYOffset; // Starting vertical position // // WMV_Field f = p.getCurrentField(); // // if(p.viewer.getState().getCurrentClusterID() >= 0) // { // WMV_Cluster c = p.getCurrentCluster(); //// float[] camTar = p.viewer.camera.target(); // // // p.p.text(" Clusters:"+(f.getClusters().size()-f.getModel().getState().mergedClusters), xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" Merged: "+f.getModel().getState().mergedClusters+" out of "+f.getClusters().size()+" Total", xPos, yPos += lineWidth, hudDistance); // p.p.text(" Minimum Distance: "+p.settings.minClusterDistance, xPos, yPos += lineWidth, hudDistance); // p.p.text(" Maximum Distance: "+p.settings.maxClusterDistance, xPos, yPos += lineWidth, hudDistance); // if(p.settings.altitudeScaling) // p.p.text(" Altitude Scaling Factor: "+p.settings.altitudeScalingFactor+" (Altitude Scaling)", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" Clustering Method : "+ ( p.getState().hierarchical ? "Hierarchical" : "K-Means" ), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Population Factor: "+f.getModel().getState().clusterPopulationFactor, xPos, yPos += lineWidth, hudDistance); // if(p.getState().hierarchical) p.p.text(" Current Cluster Depth: "+f.getState().clusterDepth, xPos, yPos += lineWidth, hudDistance); // // p.p.textSize(mediumTextSize); // p.p.text(" Viewer ", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" Location, x: "+PApplet.round(p.viewer.getLocation().x)+" y:"+PApplet.round(p.viewer.getLocation().y)+" z:"+ // PApplet.round(p.viewer.getLocation().z), xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" GPS Longitude: "+p.viewer.getGPSLocation().x+" Latitude:"+p.viewer.getGPSLocation().y, xPos, yPos += lineWidth, hudDistance); // // p.p.text(" Current Cluster: "+p.viewer.getState().getCurrentClusterID(), xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" Media Points: "+c.getState().mediaCount, xPos, yPos += lineWidth, hudDistance); // p.p.text(" Media Segments: "+p.getCurrentCluster().segments.size(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Distance: "+PApplet.round(PVector.dist(c.getLocation(), p.viewer.getLocation())), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Stitched Panoramas: "+p.getCurrentCluster().stitched.size(), xPos, yPos += lineWidth, hudDistance); // if(p.viewer.getAttractorClusterID() != -1) // { // p.p.text(" Destination Cluster : "+p.viewer.getAttractorCluster(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Destination Media Points: "+p.getCurrentField().getCluster(p.viewer.getAttractorClusterID()).getState().mediaCount, xPos, yPos += lineWidth, hudDistance); // p.p.text(" Destination Distance: "+PApplet.round( PVector.dist(f.getClusters().get(p.viewer.getAttractorClusterID()).getLocation(), p.viewer.getLocation() )), xPos, yPos += lineWidth, hudDistance); // } // // if(p.p.debugSettings.viewer) // { // p.p.text(" Debug: Current Attraction: "+p.viewer.getAttraction().mag(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Debug: Current Acceleration: "+p.viewer.getAcceleration().mag(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Debug: Current Velocity: "+ p.viewer.getVelocity().mag() , xPos, yPos += lineWidth, hudDistance); // p.p.text(" Debug: Moving? " + p.viewer.getState().isMoving(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Debug: Slowing? " + p.viewer.isSlowing(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Debug: Halting? " + p.viewer.isHalting(), xPos, yPos += lineWidth, hudDistance); // } // // if(p.p.debugSettings.viewer) // { // p.p.text(" Debug: X Orientation (Yaw):" + p.viewer.getXOrientation(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Debug: Y Orientation (Pitch):" + p.viewer.getYOrientation(), xPos, yPos += lineWidth, hudDistance); //// p.p.text(" Debug: Target Point x:" + camTar[0] + ", y:" + camTar[1] + ", z:" + camTar[2], xPos, yPos += lineWidth, hudDistance); // } // else // { // p.p.text(" Compass Direction:" + utilities.angleToCompass(p.viewer.getXOrientation())+" Angle: "+p.viewer.getXOrientation(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Vertical Direction:" + PApplet.degrees(p.viewer.getYOrientation()), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Zoom:"+p.viewer.getFieldOfView(), xPos, yPos += lineWidth, hudDistance); // } // p.p.text(" Field of View:"+p.viewer.getFieldOfView(), xPos, yPos += lineWidth, hudDistance); // // xPos = midRightTextXOffset; // yPos = topTextYOffset; // Starting vertical position // // p.p.textSize(mediumTextSize); // p.p.text(" Time ", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" Time Mode: "+ ((p.p.world.getState().getTimeMode() == 0) ? "Cluster" : "Field"), xPos, yPos += lineWidthVeryWide, hudDistance); // // if(p.p.world.getState().getTimeMode() == 0) // p.p.text(" Current Field Time: "+ p.getState().currentTime, xPos, yPos += lineWidth, hudDistance); // if(p.p.world.getState().getTimeMode() == 1) // p.p.text(" Current Cluster Time: "+ p.getCurrentCluster().getState().currentTime, xPos, yPos += lineWidth, hudDistance); // p.p.text(" Current Field Timeline Segments: "+ p.getCurrentField().getTimeline().timeline.size(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Current Field Time Segment: "+ p.viewer.getCurrentFieldTimeSegment(), xPos, yPos += lineWidth, hudDistance); // if(f.getTimeline().timeline.size() > 0 && p.viewer.getCurrentFieldTimeSegment() >= 0 && p.viewer.getCurrentFieldTimeSegment() < f.getTimeline().timeline.size()) // p.p.text(" Upper: "+f.getTimeSegment(p.viewer.getCurrentFieldTimeSegment()).getUpper().getTime() // +" Center:"+f.getTimeSegment(p.viewer.getCurrentFieldTimeSegment()).getCenter().getTime()+ // " Lower: "+f.getTimeSegment(p.viewer.getCurrentFieldTimeSegment()).getLower().getTime(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Current Cluster Timeline Segments: "+ p.getCurrentCluster().getTimeline().timeline.size(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Field Dateline Segments: "+ p.getCurrentField().getDateline().size(), xPos, yPos += lineWidth, hudDistance); // p.p.textSize(mediumTextSize); // // if(p.p.debugSettings.memory) // { // if(p.p.debugSettings.detailed) // { // p.p.text("Total memory (bytes): " + p.p.debugSettings.totalMemory, xPos, yPos += lineWidth, hudDistance); // p.p.text("Available processors (cores): "+p.p.debugSettings.availableProcessors, xPos, yPos += lineWidth, hudDistance); // p.p.text("Maximum memory (bytes): " + (p.p.debugSettings.maxMemory == Long.MAX_VALUE ? "no limit" : p.p.debugSettings.maxMemory), xPos, yPos += lineWidth, hudDistance); // p.p.text("Total memory (bytes): " + p.p.debugSettings.totalMemory, xPos, yPos += lineWidth, hudDistance); // p.p.text("Allocated memory (bytes): " + p.p.debugSettings.allocatedMemory, xPos, yPos += lineWidth, hudDistance); // } // p.p.text("Free memory (bytes): "+p.p.debugSettings.freeMemory, xPos, yPos += lineWidth, hudDistance); // p.p.text("Approx. usable free memory (bytes): " + p.p.debugSettings.approxUsableFreeMemory, xPos, yPos += lineWidth, hudDistance); // } // } // // p.p.popMatrix(); // } // void setFullScreen(boolean newState) // { // if(newState && !fullscreen) // Switch to Fullscreen // { //// if(!p.viewer.selection) window.viewsSidebar.setVisible(false); //// else window.selectionSidebar.setVisible(false); // } // if(!newState && fullscreen) // Switch to Window Size // { //// if(!p.viewer.selection) window.mainSidebar.setVisible(true); //// else window.selectionSidebar.setVisible(true); // } // // fullscreen = newState; // } }
UTF-8
Java
144,185
java
MV_Display.java
Java
[ { "context": "r displaying 2D text, maps and graphics\n * @author davidgordon\n */\npublic class MV_Display\n{\n\t/* Classes */\n\tpub", "end": 1102, "score": 0.9357509613037109, "start": 1091, "tag": "USERNAME", "value": "davidgordon" }, { "context": "ble time segment on Time View timeline\n\t * @author davidgordon\n\t */\n\tprivate class SelectableTimeSegment\n\t{\n\t\tpr", "end": 116870, "score": 0.7343705296516418, "start": 116859, "tag": "USERNAME", "value": "davidgordon" } ]
null
[]
package main.java.com.entoptic.metaVisualizer.user; import java.awt.Image; import java.awt.image.BufferedImage; import java.util.ArrayList; import main.java.com.entoptic.metaVisualizer.MetaVisualizer; import main.java.com.entoptic.metaVisualizer.media.WMV_Image; import main.java.com.entoptic.metaVisualizer.media.WMV_Panorama; import main.java.com.entoptic.metaVisualizer.media.WMV_Video; import main.java.com.entoptic.metaVisualizer.misc.WMV_Utilities; import main.java.com.entoptic.metaVisualizer.model.WMV_Cluster; import main.java.com.entoptic.metaVisualizer.model.WMV_Date; import main.java.com.entoptic.metaVisualizer.model.WMV_Time; import main.java.com.entoptic.metaVisualizer.model.WMV_TimeSegment; import main.java.com.entoptic.metaVisualizer.model.WMV_Timeline; import main.java.com.entoptic.metaVisualizer.system.MV_Library; import main.java.com.entoptic.metaVisualizer.world.WMV_Field; import main.java.com.entoptic.metaVisualizer.world.WMV_World; import processing.core.*; /*********************************** * Object for displaying 2D text, maps and graphics * @author davidgordon */ public class MV_Display { /* Classes */ public MetaVisualizer mv; public MV_Window window; /* Main interaction window */ public MV_Map map2D; private WMV_Utilities utilities; /* Utility methods */ /* Display View */ private int displayView = 0; /* {0: Scene 1: Map 2: Library 3: Timeline 4: Media} */ /* Debug */ public boolean drawForceVector = false; /* Setup */ private boolean worldSetup = true; public boolean dataFolderFound = false; public float setupProgress = 0.f; /* Window Behavior */ public boolean disableLostFocusHook = false; /* Buttons */ ArrayList<MV_Button> buttons; public float buttonWidth, buttonHeight; public float buttonSpacing; /* Graphics */ private PMatrix3D originalMatrix; /* For restoring 3D view after 2D HUD */ private float currentFieldOfView; public boolean drawGrid = false; /* Draw 3D grid */ // -- Unused private final float hudDistanceInit = -1000.f; /* Distance of the Heads-Up Display from the virtual camera */ private float messageHUDDistance = hudDistanceInit * 6.f; private int screenWidth = -1, screenHeight = -1; /* Display dimensions */ private int windowWidth = -1, windowHeight = -1; /* Window dimensions */ public int blendMode = 0; /* Alpha blending mode */ // private final int numBlendModes = 10; /* Number of blending modes */ // PImage startupImage; private float hudLeftMargin, hudCenterXOffset, hudRightMargin, hudTopMargin; private float displayWidthFactor; /* Map View */ private boolean setupMapView = false; public int mapViewMode = 1; // 0: World, 1: Field, (2: Cluster -- In progress) public boolean initializedMaps = false; public boolean initializedSatelliteMap = false; MV_Button btnFieldMode, btnWorldMode; MV_Button btnZoomToField, btnZoomToWorld, btnZoomToCluster; MV_Button btnZoomMapIn, btnZoomMapOut; MV_Button btnPanMapUp, btnPanMapDown; MV_Button btnPanMapLeft, btnPanMapRight; private final float imageHue = 140.f; private final float panoramaHue = 190.f; private final float videoHue = 100.f; private final float soundHue = 40.f; /* Time View */ private boolean setupTimeView = false; private float timelineScreenSize, timelineHeight; private float timelineStart = 0.f, timelineEnd = 0.f; private float datelineStart = 0.f, datelineEnd = 0.f; public int displayDate = -1; public boolean updateCurrentSelectableTimeSegment = true, updateCurrentSelectableDate = true; MV_Button btnScrollLeft, btnScrollRight; MV_Button btnTimelineZoomIn, btnTimelineZoomOut; MV_Button btnZoomToFit, btnZoomToSelection, btnZoomToCurrentDate, btnZoomToTimeline; private ArrayList<SelectableTimeSegment> selectableTimeSegments; // Selectable time segments on timeline private ArrayList<SelectableDate> selectableDates; // Selectable dates on dateline private SelectableDate allDates; private final float minSegmentSeconds = 15.f; private boolean fieldTimelineCreated = false, fieldDatelineCreated = false, updateFieldTimeline = true; private float timelineXOffset = 0.f, timelineYOffset = 0.f, datelineYOffset = 0.f; private SelectableTimeSegment currentSelectableTimeSegment; private int selectedTime = -1, selectedCluster = -1, currentSelectableTimeSegmentID = -1, currentSelectableTimeSegmentFieldTimeSegmentID = -1; private int selectedDate = -1, currentSelectableDate = -1; private boolean timelineTransition = false, timelineZooming = false, timelineScrolling = false; private int transitionScrollDirection = -1, transitionZoomDirection = -1; private int timelineTransitionStartFrame = 0, timelineTransitionEndFrame = 0; private int timelineTransitionLength = 30; private final int initTimelineTransitionLength = 30; private float timelineStartTransitionStart = 0, timelineStartTransitionTarget = 0; private float timelineEndTransitionStart = 0, timelineEndTransitionTarget = 0; public float transitionScrollIncrement = 1750.f; public final float initTransitionScrollIncrement = 1750.f; // Seconds to scroll per frame public final float transitionZoomInIncrement = 0.95f, transitionZoomOutIncrement = 1.052f; /* Library View */ private int libraryViewMode = 2; // 0: World, 1: Field, 2: Location (Cluster) private boolean setupLibraryView = false; public int currentDisplayField = 0, currentDisplayCluster = 0; private float clusterMediaXOffset, clusterMediaYOffset; private final float thumbnailWidth = 85.f; private final float thumbnailSpacing = 0.1f; MV_Button btnLibraryViewCluster, btnLibraryViewField, btnLibraryViewLibrary; private boolean createdSelectableMedia = false; ArrayList<SelectableMedia> selectableMedia; /* Selectable media thumbnails */ private SelectableMedia currentSelectableMedia; /* Current selected media in grid */ private int selectedMedia = -1; private boolean updateSelectableMedia = true; /* Media View */ private int mediaViewMediaType = -1; private int mediaViewMediaID = -1; /* Text – 3D HUD */ private float messageXOffset, messageYOffset; private float metadataXOffset, metadataYOffset; private float largeTextSize = 56.f; // -- Set from display size?? private float mediumTextSize = 44.f; private float smallTextSize = 36.f; private float messageTextSize = 48.f; private float linePadding = 20.f; private float lineWidth = smallTextSize + linePadding; // private float lineWidthWide = largeTextSize + linePadding; private float lineWidthWide = largeTextSize * 2.f; /* Text – 2D */ private float hudVeryLargeTextSize; private float hudLargeTextSize; private float hudMediumTextSize; private float hudSmallTextSize; private float hudVerySmallTextSize; private float hudLinePadding; private float hudLinePaddingWide; private float hudLineWidth; private float hudLineWidthWide; private float hudLineWidthVeryWide; // private float hudVeryLargeTextSize = 32.f; // private float hudLargeTextSize = 26.f; // private float hudMediumTextSize = 22.f; // private float hudSmallTextSize = 18.f; // private float hudVerySmallTextSize = 16.f; // private float hudLinePadding = 4.f; // private float hudLinePaddingWide = 8.f; // private float hudLineWidth = hudMediumTextSize + hudLinePadding; // private float hudLineWidthWide = hudLargeTextSize + hudLinePaddingWide; // private float hudLineWidthVeryWide = hudLargeTextSize * 2.f; /* Messages */ public ArrayList<String> startupMessages; // Messages to display on screen private ArrayList<String> messages; // Messages to display on screen private ArrayList<String> metadata; // Metadata messages to display on screen private PFont defaultFont, messageFont; private final int messageDuration = 40; // Frame length to display messages private final int maxMessages = 16; // Maximum simultaneous messages on screen int messageStartFrame = -1; int metadataStartFrame = -1; int startupMessageStartFrame = -1; /** * Constructor for 2D display * @param mv Parent app */ public MV_Display(MetaVisualizer parent) { mv = parent; utilities = new WMV_Utilities(); originalMatrix = mv.getMatrix((PMatrix3D)null); // float aspect = (float)screenHeight / (float)screenWidth; // if(aspect != 0.625f) // monitorOffsetXAdjustment = (0.625f / aspect); screenWidth = mv.displayWidth; screenHeight = mv.displayHeight; messages = new ArrayList<String>(); metadata = new ArrayList<String>(); startupMessages = new ArrayList<String>(); /* Text – 3D HUD */ messageXOffset = screenWidth * 1.75f; messageYOffset = -screenHeight * 0.33f; metadataXOffset = -screenWidth * 2.f; metadataYOffset = -screenHeight / 2.f; largeTextSize = screenWidth * 0.0333f; mediumTextSize = screenWidth * 0.025f; smallTextSize = screenWidth * 0.02f; messageTextSize = screenWidth * 0.03f; linePadding = screenWidth * 0.0125f; // largeTextSize = 56.f; // -- Set from display size?? // mediumTextSize = 44.f; // smallTextSize = 36.f; // // messageTextSize = 48.f; // linePadding = 20.f; lineWidth = smallTextSize + linePadding; // lineWidthWide = largeTextSize + linePadding; lineWidthWide = largeTextSize * 2.f; /* 2D Displays */ timelineStart = 0.f; timelineEnd = utilities.getTimePVectorSeconds(new PVector(24,0,0)); /* Text – 2D */ hudVeryLargeTextSize = screenWidth * 0.017f; hudLargeTextSize = screenWidth * 0.015f; hudMediumTextSize = screenWidth * 0.0125f; hudSmallTextSize = screenWidth * 0.010f; hudVerySmallTextSize = screenWidth * 0.0095f; hudLinePadding = screenHeight * 0.004f; hudLinePaddingWide = hudLinePadding * 2.f; hudLineWidth = screenHeight * 0.02f + hudLinePadding; hudLineWidthWide = screenHeight * 0.0233f + hudLinePaddingWide; hudLineWidthVeryWide = screenHeight * 0.0466f; // hudVeryLargeTextSize = 32.f; // hudLargeTextSize = 26.f; // hudMediumTextSize = 22.f; // hudSmallTextSize = 18.f; // hudVerySmallTextSize = 16.f; // hudLinePadding = 4.f; // hudLinePaddingWide = 8.f; // hudLineWidth = hudMediumTextSize + hudLinePadding; // hudLineWidthWide = hudLargeTextSize + hudLinePaddingWide; // hudLineWidthVeryWide = hudLargeTextSize * 2.f; currentSelectableTimeSegment = null; currentSelectableTimeSegmentID = -1; currentSelectableTimeSegmentFieldTimeSegmentID = -1; map2D = new MV_Map(this); buttons = new ArrayList<MV_Button>(); messageFont = mv.createFont("ArialNarrow-Bold", messageTextSize); defaultFont = mv.createFont("SansSerif", smallTextSize); // startupImage = p.p.loadImage("res/WMV_Title.jpg"); } /** * Finish 2D display setup */ public void setupScreen() { windowWidth = mv.width; windowHeight = mv.height; clusterMediaXOffset = windowWidth * 0.1f; clusterMediaYOffset = windowHeight * 0.5f; // Default; actual value changes with Library View text line count hudCenterXOffset = windowWidth * 0.5f; hudLeftMargin = windowWidth * 0.05f; hudRightMargin = windowWidth * 0.95f; hudTopMargin = windowHeight * 0.075f; timelineXOffset = windowWidth * 0.1f; timelineYOffset = windowHeight * 0.4f; timelineScreenSize = windowWidth * 0.8f; timelineHeight = windowHeight * 0.1f; // timelineHeight = screenHeight * 0.1f; datelineYOffset = windowHeight * 0.533f; buttonWidth = windowWidth * 0.075f; buttonHeight = windowWidth * 0.0175f; buttonSpacing = windowWidth * 0.0125f; displayWidthFactor = mv.width / 1440.f; // hudVeryLargeTextSize *= displayWidthFactor; // hudLargeTextSize *= displayWidthFactor; // hudMediumTextSize *= displayWidthFactor; // hudSmallTextSize *= displayWidthFactor; // hudVerySmallTextSize *= displayWidthFactor; // hudLinePadding *= displayWidthFactor; // hudLinePaddingWide *= displayWidthFactor; // hudLineWidth *= displayWidthFactor; // hudLineWidthWide *= displayWidthFactor; // hudLineWidthVeryWide *= displayWidthFactor; // hudVeryLargeTextSize = 32.f * displayWidthFactor; // hudLargeTextSize = 26.f * displayWidthFactor; // hudMediumTextSize = 22.f * displayWidthFactor; // hudSmallTextSize = 18.f * displayWidthFactor; // hudVerySmallTextSize = 16.f * displayWidthFactor; // hudLinePadding = 4.f * displayWidthFactor; // hudLinePaddingWide = 8.f * displayWidthFactor; // hudLineWidth = (hudMediumTextSize + hudLinePadding) * displayWidthFactor; // hudLineWidthWide = (hudLargeTextSize + hudLinePaddingWide) * displayWidthFactor; // hudLineWidthVeryWide = (hudLargeTextSize * 2.f) * displayWidthFactor; } /** * Display HUD elements (messages, satellite map, statistics, metadata, etc.) * @param p Parent world */ public void display(MetaVisualizer ml) { if(worldSetup) { ml.hint(PApplet.DISABLE_DEPTH_TEST); // Disable depth testing for drawing HUD displayStartup(ml.world, ml.state.inLibrarySetup); // Draw startup messages } else { if( displayView == 0 ) // World View { if( messages.size() > 0 || metadata.size() > 0 ) { // ml.hint(PApplet.DISABLE_DEPTH_TEST); // Disable depth testing for drawing HUD if(messages.size() > 0) displayMessages(ml.world); if(ml.world.getState().showMetadata && metadata.size() > 0 && ml.world.viewer.getSettings().selection) displayMetadata(ml.world); } } else // 2D Views { ml.hint(PApplet.DISABLE_DEPTH_TEST); // Disable depth testing for drawing HUD switch(displayView) { case 1: // Map View if(!setupMapView) setupMapView(); displayMapView(); updateMapView(ml.world); break; case 2: // Time View if(!setupTimeView) setupTimeView(); updateFieldTimeline(ml.world); displayTimeView(ml.world); updateTimeView(ml.world); break; case 3: // Library view if(!setupLibraryView) setupLibraryView(); displayLibraryView(ml.world); updateLibraryView(ml.world); break; case 4: // Media View displayMediaView(ml.world); break; } } if(window.subjectDistanceUpBtnDown) ml.world.getCurrentField().fadeFocusDistances(ml.world, 0.985f); else if(window.subjectDistanceDownBtnDown) ml.world.getCurrentField().fadeFocusDistances(ml.world, 1.015228f); } } /** * Setup Library View * @param world Parent world */ private void setupTimeView() { createTimeViewButtons(); setupTimeView = true; } /** * Create Time View buttons */ private void createTimeViewButtons() { buttons = new ArrayList<MV_Button>(); float x = hudCenterXOffset - buttonWidth * 0.5f; float y = datelineYOffset + hudLineWidth; // Starting vertical position btnScrollLeft = new MV_Button(0, "Left", hudVerySmallTextSize, x-buttonWidth * 0.75f, x, y, y+buttonHeight); x += buttonSpacing; btnScrollRight = new MV_Button(1, "Right", hudVerySmallTextSize, x+=buttonWidth * 0.75f, x+=buttonWidth, y, y+buttonHeight); x = hudCenterXOffset - buttonWidth * 0.5f; y += buttonHeight + buttonSpacing; btnTimelineZoomIn = new MV_Button(2, "In", hudVerySmallTextSize, x-buttonWidth * 0.75f, x, y, y+buttonHeight); x += buttonSpacing; btnTimelineZoomOut = new MV_Button(3, "Out", hudVerySmallTextSize, x+=buttonWidth * 0.75f, x+=buttonWidth, y, y+buttonHeight); buttons.add(btnScrollLeft); buttons.add(btnScrollRight); buttons.add(btnTimelineZoomIn); buttons.add(btnTimelineZoomOut); y += buttonHeight + buttonSpacing; x = hudCenterXOffset - buttonWidth * 2.f - buttonSpacing * 2.f; btnZoomToFit = new MV_Button(4, "Field", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); x += buttonSpacing; btnZoomToSelection = new MV_Button(5, "Location", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); x += buttonSpacing; btnZoomToCurrentDate = new MV_Button(6, "Current Date", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); x += buttonSpacing; btnZoomToTimeline = new MV_Button(7, "Full Day", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); buttons.add(btnZoomToFit); buttons.add(btnZoomToSelection); buttons.add(btnZoomToCurrentDate); buttons.add(btnZoomToTimeline); // ML_Button btnZoomToFit, btnZoomToSelection, btnZoomToTimeline; // case "TimelineZoomToFit": // ml.display.zoomToTimeline(ml.world, true); // break; // case "TimelineZoomToSelected": // ml.display.zoomToCurrentSelectableTimeSegment(ml.world, true); // break; // case "TimelineZoomToDate": // ml.display.zoomToCurrentSelectableDate(ml.world, true); // break; // case "TimelineZoomToFull": // ml.display.resetZoom(ml.world, true); // break; // ML_Button previous, next, current; // // x = hudCenterXOffset - buttonWidth * 1.5f; // y += buttonHeight + buttonSpacing; // Starting vertical position // // previous = new ML_Button(10, "Previous (left)", hudVerySmallTextSize, x-buttonWidth*0.5f, x+=buttonWidth, y, y+buttonHeight); // x += buttonSpacing; // current = new ML_Button(12, "Current", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); // x += buttonSpacing; // next = new ML_Button(11, "Next (right)", hudVerySmallTextSize, x, x+=buttonWidth + buttonWidth * 0.5f, y, y+buttonHeight); // // buttons.add(previous); // buttons.add(current); // buttons.add(next); } /** * Setup Library View * @param world Parent world */ private void setupMapView() { createMapViewButtons(); setupMapView = true; } /** * Create Time View buttons */ private void createMapViewButtons() { buttons = new ArrayList<MV_Button>(); // ML_Button fieldMode, worldMode; // ML_Button fieldMap, worldMap, viewer; // ML_Button panUp, panDown; // ML_Button panLeft, panRight; float x = hudLeftMargin + buttonWidth + buttonSpacing * 0.5f; // float x = hudCenterXOffset - buttonWidth * 0.5f; float y = hudTopMargin; // Starting vertical position btnFieldMode = new MV_Button(11, "Field", hudVerySmallTextSize, x, x+buttonWidth, y, y+buttonHeight); x += buttonSpacing; btnWorldMode = new MV_Button(10, "Environment", hudVerySmallTextSize, x+=buttonWidth, x+=buttonWidth, y, y+buttonHeight); buttons.add(btnFieldMode); buttons.add(btnWorldMode); // x = hudLeftMargin + buttonWidth * 0.5f; x = hudLeftMargin + buttonWidth + buttonSpacing * 0.5f; y += buttonHeight + buttonSpacing; btnZoomToCluster = new MV_Button(0, "Viewer", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); x += buttonSpacing; btnZoomToField = new MV_Button(1, "Field", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); x += buttonSpacing; btnZoomToWorld = new MV_Button(2, "Environment", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); btnZoomToWorld.setVisible(mapViewMode == 0); // x = hudLeftMargin; x = hudLeftMargin + buttonWidth; y += buttonHeight + buttonSpacing; btnZoomMapIn = new MV_Button(7, "In", hudVerySmallTextSize, x-buttonWidth, x, y, y+buttonHeight); x += buttonSpacing; btnZoomMapOut = new MV_Button(8, "Out", hudVerySmallTextSize, x+=buttonWidth, x+=buttonWidth, y, y+buttonHeight); buttons.add(btnZoomMapIn); buttons.add(btnZoomMapOut); x = hudLeftMargin + buttonWidth + buttonSpacing * 0.5f; y += buttonHeight + buttonSpacing; btnPanMapUp = new MV_Button(3, "Up", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); x = hudLeftMargin; y += buttonHeight + buttonSpacing; btnPanMapLeft = new MV_Button(4, "Left", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); x += buttonSpacing; btnPanMapRight = new MV_Button(5, "Right", hudVerySmallTextSize, x+=buttonWidth, x+=buttonWidth, y, y+buttonHeight); x = hudLeftMargin + buttonWidth + buttonSpacing * 0.5f; y += buttonHeight + buttonSpacing; btnPanMapDown = new MV_Button(6, "Down", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); buttons.add(btnZoomToCluster); buttons.add(btnZoomToField); buttons.add(btnZoomToWorld); buttons.add(btnPanMapUp); buttons.add(btnPanMapLeft); buttons.add(btnPanMapRight); buttons.add(btnPanMapDown); // ML_Button zoomIn, zoomOut; // // x = hudLeftMargin + buttonWidth * 0.5f; // y += buttonHeight + buttonSpacing; // // zoomIn = new ML_Button(7, "In", hudVerySmallTextSize, x-buttonWidth, x, y, y+buttonHeight); // x += buttonSpacing; // zoomOut = new ML_Button(8, "Out", hudVerySmallTextSize, x+=buttonWidth, x+=buttonWidth, y, y+buttonHeight); // // buttons.add(zoomIn); // buttons.add(zoomOut); } /** * Setup Library View * @param world Parent world */ private void setupLibraryView() { createLibraryViewButtons(); setupLibraryView = true; } /** * Create Library View buttons */ private void createLibraryViewButtons() { buttons = new ArrayList<MV_Button>(); float x = hudCenterXOffset - buttonWidth * 0.5f; float y = hudTopMargin; // Starting vertical position // float y = hudTopMargin + lineWidth; // Starting vertical position btnLibraryViewCluster = new MV_Button(0, "Location", hudVerySmallTextSize, x-buttonWidth, x, y, y+buttonHeight); // cluster.addLabel("Displaying: "); x += buttonSpacing; btnLibraryViewField = new MV_Button(1, "Field", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); x += buttonSpacing; btnLibraryViewLibrary = new MV_Button(2, "Environment", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); buttons.add(btnLibraryViewCluster); buttons.add(btnLibraryViewField); buttons.add(btnLibraryViewLibrary); MV_Button previous, next, current; x = hudCenterXOffset - buttonWidth * 1.5f; y += buttonHeight + buttonSpacing; // y += buttonHeight * 3.f + buttonSpacing * 0.5f; previous = new MV_Button(10, "Previous (left)", hudVerySmallTextSize, x-buttonWidth*0.5f, x+=buttonWidth, y, y+buttonHeight); x += buttonSpacing; current = new MV_Button(12, "Current", hudVerySmallTextSize, x, x+=buttonWidth, y, y+buttonHeight); x += buttonSpacing; next = new MV_Button(11, "Next (right)", hudVerySmallTextSize, x, x+=buttonWidth + buttonWidth * 0.5f, y, y+buttonHeight); buttons.add(previous); buttons.add(current); buttons.add(next); } /** * Begin Heads-Up Display * @param ml Parent app */ public void beginHUD(MetaVisualizer ml) { ml.g.pushMatrix(); ml.g.hint(PConstants.DISABLE_DEPTH_TEST); ml.g.resetMatrix(); // Load identity matrix. ml.g.applyMatrix(originalMatrix); // Apply original transformation matrix. } /** * End Heads-Up Display * @param ml Parent app */ public void endHUD(MetaVisualizer ml) { // ml.g.hint(PConstants.ENABLE_DEPTH_TEST); ml.g.popMatrix(); } /** * Set the current initialization progress bar position * @param progress New progress bar position {0.f to 1.f} */ public void setupProgress(float progress) { setupProgress = progress; } public void displayMapView() { mv.rectMode(PApplet.CORNER); // Specify top left point in rect() -- Needed? if(mapViewMode == 0) // World Mode { if(initializedMaps) map2D.displayWorldMap(mv.world); map2D.update(mv.world); // -- Added 6/22 } else if(mapViewMode == 1) // Field Mode { if(initializedMaps) map2D.displaySatelliteMap(mv.world); if(mv.state.interactive) displayInteractiveClustering(mv.world); map2D.update(mv.world); } // startDisplayHUD(); mv.pushMatrix(); mv.textFont(defaultFont); // = ml.createFont("SansSerif", 30); float x = hudLeftMargin + buttonWidth * 0.5f; float y = hudTopMargin + buttonSpacing * 0.75f; // + lineWidth; // Starting vertical position mv.fill(0, 0, 255, 255); mv.textSize(hudSmallTextSize); mv.text("Map Mode:", x + buttonSpacing * 0.3f, y - buttonSpacing * 0.15f, 0); x = hudLeftMargin + buttonWidth * 0.5f; y += buttonHeight + buttonSpacing; mv.text("Zoom To:", x, y, 0); x = hudLeftMargin + buttonWidth * 1.5f + buttonSpacing * 0.5f; y += buttonHeight + buttonSpacing; mv.text("Zoom", x, y, 0); y += buttonHeight * 2.f + buttonSpacing * 1.75f; mv.text("Pan", x, y, 0); mv.popMatrix(); // endDisplayHUD(); // -- Added 6/29/17 for(MV_Button b : buttons) b.display(mv.world, 0.f, 0.f, 255.f); mv.rectMode(PApplet.CENTER); // Return rect mode to Center } /** * Display Time View in main window * @param p Parent world */ public void displayTimeView(WMV_World p) { mv.rectMode(PApplet.CORNER); // Specify top left point in rect() -- Needed? startDisplayHUD(); mv.pushMatrix(); mv.textFont(defaultFont); // = ml.createFont("SansSerif", 30); float xPos = hudCenterXOffset; float yPos = hudTopMargin; // Starting vertical position WMV_Field f = p.getCurrentField(); mv.fill(0, 0, 255, 255); mv.textSize(hudVeryLargeTextSize); mv.text(""+p.getCurrentField().getName(), xPos, yPos, 0); mv.textFont(defaultFont); // = ml.createFont("SansSerif", 30); // startDisplayHUD(); // ml.pushMatrix(); for(MV_Button b : buttons) b.display(p, 0.f, 0.f, 255.f); // ml.popMatrix(); // endDisplayHUD(); mv.textSize(hudLargeTextSize - 5.f); String strDisplayDate = ""; if(displayDate >= 0) { strDisplayDate = utilities.getDateAsString(p.getCurrentField().getDate(displayDate)); } else { strDisplayDate = "Showing All Dates"; mv.fill(35, 115, 255, 255); } mv.text(strDisplayDate, xPos, yPos += hudLineWidthVeryWide, 0); mv.textSize(hudMediumTextSize); mv.fill(0, 0, 255, 255); mv.text(" Time Zone: "+ f.getTimeZoneID(), xPos, yPos += hudLineWidthWide, 0); // ml.text("Scroll", xPos, yPos += hudLineWidth, 0); // ml.text("Zoom", xPos, yPos += hudLineWidth, 0); // ml.popMatrix(); // endDisplayHUD(); // xPos = hudCenterXOffset; mv.textSize(hudSmallTextSize); yPos = datelineYOffset + hudLineWidth + buttonHeight * 0.5f; mv.text("Scroll", xPos, yPos, 0); mv.text("Zoom", xPos, yPos += buttonHeight + buttonSpacing, 0); mv.popMatrix(); if(fieldDatelineCreated) displayDateline(p); if(fieldTimelineCreated) displayTimeline(p); endDisplayHUD(); // -- Added 6/29/17 mv.rectMode(PApplet.CENTER); // Return rect mode to Center // updateTimelineMouse(p); } /** * Update field timeline every frame * @param p Parent world */ private void updateFieldTimeline(WMV_World p) { if(timelineTransition) updateTimelineTransition(p); if(!fieldDatelineCreated || !fieldTimelineCreated || updateFieldTimeline) { if(!timelineTransition) { createFieldDateline(p); createFieldTimeline(p); updateFieldTimeline = false; } } if(updateCurrentSelectableTimeSegment && !timelineTransition) { if(p.viewer.getCurrentFieldTimeSegment() >= 0) { updateTimelineSelection(p); } else System.out.println("Display.updateCurrentSelectableTimeSegment()... ERROR: No current time segment!"); } } /** * Update Time View * @param p Parent world */ private void updateMapView(WMV_World p) { updateMapViewMouse(p); } /** * Update Time View * @param p Parent world */ private void updateTimeView(WMV_World p) { updateTimelineMouse(p); } /** * Update Library View * @param p Parent world */ private void updateLibraryView(WMV_World p) { if(updateSelectableMedia) { WMV_Field f = p.getCurrentField(); WMV_Cluster c = f.getCluster(currentDisplayCluster); // Get the cluster to display info about ArrayList<WMV_Image> imageList = f.getImagesInCluster(c.getID(), p.getCurrentField().getImages()); if(imageList != null) createClusterSelectableMedia(p, imageList); updateSelectableMedia = false; } updateLibraryViewMouse(); } /** * Update user selection in Timeline View * @param p Parent world */ private void updateTimelineSelection(WMV_World p) { WMV_TimeSegment t = p.getCurrentField().getTimeSegment(p.viewer.getCurrentFieldTimeSegment()); int previous = currentSelectableTimeSegmentID; if(t != null) { currentSelectableTimeSegmentID = getSelectableTimeIDOfFieldTimeSegment(t); // Set current selectable time (white rectangle) from current field time segment if(currentSelectableTimeSegmentID != -1) { currentSelectableTimeSegment = selectableTimeSegments.get(currentSelectableTimeSegmentID); currentSelectableTimeSegmentFieldTimeSegmentID = currentSelectableTimeSegment.segment.getFieldTimelineID(); // Set current selectable time (white rectangle) from current field time segment } else { currentSelectableTimeSegmentFieldTimeSegmentID = -1; currentSelectableTimeSegment = null; } } else { currentSelectableTimeSegmentID = -1; currentSelectableTimeSegmentFieldTimeSegmentID = -1; currentSelectableTimeSegment = null; } if(updateCurrentSelectableDate) { if(currentSelectableTimeSegmentID != previous && currentSelectableDate > -1) // If changed field segment and displaying a single date { int fieldDate = p.getCurrentField().getTimeSegment(p.viewer.getCurrentFieldTimeSegment()).getFieldDateID(); // Update date displayed setCurrentSelectableDate(fieldDate); } else { System.out.println("Display.updateTimelineSelection()... 1 updateCurrentSelectableDate... currentSelectableDate:"+currentSelectableDate); if(currentSelectableDate == -100) setCurrentSelectableDate(-1); } } updateCurrentSelectableTimeSegment = false; updateCurrentSelectableDate = false; } /** * Create field dateline * @param p Parent world */ private void createFieldDateline(WMV_World p) { WMV_Field f = p.getCurrentField(); if(f.getDateline().size() > 0) { WMV_Date first = f.getDate(0); float padding = 1.f; int firstDay = first.getDay(); int firstMonth = first.getMonth(); int firstYear = first.getYear(); WMV_Date last = f.getDate(f.getDateline().size()-1); int lastDay = last.getDay(); int lastMonth = last.getMonth(); int lastYear = last.getYear(); if(f.getDateline().size() == 2) padding = utilities.getDaysSince1980(p.getCurrentField().getTimeZoneID(), lastDay, lastMonth, lastYear) - utilities.getDaysSince1980(p.getCurrentField().getTimeZoneID(), firstDay, firstMonth, firstYear); else if(f.getDateline().size() > 2) padding = (utilities.getDaysSince1980(p.getCurrentField().getTimeZoneID(), lastDay, lastMonth, lastYear) - utilities.getDaysSince1980(p.getCurrentField().getTimeZoneID(), firstDay, firstMonth, firstYear)) * 0.33f; datelineStart = utilities.getDaysSince1980(p.getCurrentField().getTimeZoneID(), firstDay, firstMonth, firstYear) - padding; datelineEnd = utilities.getDaysSince1980(p.getCurrentField().getTimeZoneID(), lastDay, lastMonth, lastYear) + padding; createSelectableDates(p); fieldDatelineCreated = true; } else { System.out.println("ERROR no dateline in field!!"); } } /** * Create viewable timeline for field * @param p Parent world */ private void createFieldTimeline(WMV_World p) { WMV_Field f = p.getCurrentField(); selectableTimeSegments = new ArrayList<SelectableTimeSegment>(); if(f.getDateline().size() == 1) /* Field contains media from single date */ { int count = 0; for(WMV_TimeSegment t : f.getTimeline().timeline) { SelectableTimeSegment st = getSelectableTimeSegment(t, count); if(st != null) { selectableTimeSegments.add(st); count++; } } } else if(f.getDateline().size() > 1) /* Field contains media from multiple dates */ { if(displayDate == -1) { int count = 0; for(WMV_Timeline ts : f.getTimelines()) { for(WMV_TimeSegment t:ts.timeline) { SelectableTimeSegment st = getSelectableTimeSegment(t, count); if(st != null) { selectableTimeSegments.add(st); count++; } } } } else { if(displayDate < f.getTimelines().size()) { ArrayList<WMV_TimeSegment> ts = f.getTimelines().get(displayDate).timeline; int count = 0; for(WMV_TimeSegment t:ts) { SelectableTimeSegment st = getSelectableTimeSegment(t, count); if(st != null) { selectableTimeSegments.add(st); count++; } } } } } fieldTimelineCreated = true; } /** * Create selectable dates for current field * @param p Parent world */ private void createSelectableDates(WMV_World p) { WMV_Field f = p.getCurrentField(); selectableDates = new ArrayList<SelectableDate>(); if(f.getDateline().size() == 1) { SelectableDate sd = getSelectableDate(f.getDate(0), 0); if(sd != null) selectableDates.add(sd); } else if(f.getDateline().size() > 1) { int count = 0; for(WMV_Date t : f.getDateline()) { SelectableDate sd = getSelectableDate(t, count); if(sd != null) { selectableDates.add(sd); count++; } } float xOffset = timelineXOffset; PVector loc = new PVector(xOffset, datelineYOffset, 0); // PVector loc = new PVector(xOffset, datelineYOffset, hudDistanceInit); allDates = new SelectableDate(-100, loc, 25.f, null); // int newID, int newClusterID, PVector newLocation, Box newRectangle } } /** * Transition timeline zoom from current to given value * @param newStart New timeline left edge value * @param newEnd New timeline right edge value * @param transitionLength Transition length in frames * @param frameCount Current frame count */ public void timelineTransition(float newStart, float newEnd, int transitionLength, int frameCount) { timelineTransitionLength = transitionLength; if(!timelineTransition) { if(timelineStart != newStart || timelineEnd != newEnd) // Check if already at target { timelineTransition = true; timelineTransitionStartFrame = frameCount; timelineTransitionEndFrame = timelineTransitionStartFrame + timelineTransitionLength; if(timelineStart != newStart && timelineEnd != newEnd) { timelineStartTransitionStart = timelineStart; timelineStartTransitionTarget = newStart; timelineEndTransitionStart = timelineEnd; timelineEndTransitionTarget = newEnd; } else if(timelineStart != newStart && timelineEnd == newEnd) { timelineStartTransitionStart = timelineStart; timelineStartTransitionTarget = newStart; timelineEndTransitionTarget = timelineEnd; } else if(timelineStart == newStart && timelineEnd != newEnd) { timelineStartTransitionTarget = timelineStart; timelineEndTransitionStart = timelineEnd; timelineEndTransitionTarget = newEnd; } } else { timelineTransition = false; } } } /** * Update map zoom level each frame * @param p Parent world */ void updateTimelineTransition(WMV_World p) { float newStart = timelineStart; float newEnd = timelineEnd; if (mv.frameCount >= timelineTransitionEndFrame) { newStart = timelineStartTransitionTarget; newEnd = timelineEndTransitionTarget; timelineTransition = false; updateFieldTimeline = true; updateCurrentSelectableTimeSegment = true; transitionScrollIncrement = initTransitionScrollIncrement * getZoomLevel(); } else { if(timelineStart != timelineStartTransitionTarget) { newStart = utilities.mapValue( mv.frameCount, timelineTransitionStartFrame, timelineTransitionEndFrame, timelineStartTransitionStart, timelineStartTransitionTarget); } if(timelineEnd != timelineEndTransitionTarget) { newEnd = utilities.mapValue( mv.frameCount, timelineTransitionStartFrame, timelineTransitionEndFrame, timelineEndTransitionStart, timelineEndTransitionTarget); } } if(timelineStart != newStart) timelineStart = newStart; if(timelineEnd != newEnd) timelineEnd = newEnd; if(timelineScrolling) scroll(p, transitionScrollDirection); if(timelineZooming) zoomTimeline(p, transitionZoomDirection, true); } /** * Create and return selectable time segment from timeline * @param t Time segment * @param id Time segment id * @return New SelectableTimeSegment object */ private SelectableTimeSegment getSelectableTimeSegment(WMV_TimeSegment t, int id) { float lowerSeconds = utilities.getTimePVectorSeconds(t.getLower().getTimeAsPVector()); float upperSeconds = utilities.getTimePVectorSeconds(t.getUpper().getTimeAsPVector()); if(upperSeconds == lowerSeconds) { lowerSeconds -= minSegmentSeconds * 0.5f; upperSeconds += minSegmentSeconds * 0.5f; } float xOffset = utilities.mapValue(lowerSeconds, timelineStart, timelineEnd, timelineXOffset, timelineXOffset + timelineScreenSize); float xOffset2 = utilities.mapValue(upperSeconds, timelineStart, timelineEnd, timelineXOffset, timelineXOffset + timelineScreenSize); if(xOffset > timelineXOffset && xOffset2 < timelineXOffset + timelineScreenSize) { float rectLeftEdge, rectRightEdge, rectTopEdge, rectBottomEdge; float rectWidth = xOffset2 - xOffset; PVector loc = new PVector(xOffset, timelineYOffset, 0); // -- Z doesn't affect selection! rectLeftEdge = loc.x; rectRightEdge = rectLeftEdge + rectWidth; rectTopEdge = timelineYOffset - timelineHeight * 0.5f; rectBottomEdge = timelineYOffset + timelineHeight * 0.5f; loc.x += (xOffset2 - xOffset) * 0.5f; SelectableTimeSegment st = new SelectableTimeSegment(id, t.getFieldTimelineID(), t.getClusterID(), t, loc, rectLeftEdge, rectRightEdge, rectTopEdge, rectBottomEdge); // int newID, int newClusterID, PVector newLocation, Box newRectangle return st; } else return null; } /** * Create and return selectable date from dateline * @param t Time segment * @param id Time segment id * @return SelectableTime object */ private SelectableDate getSelectableDate(WMV_Date d, int id) { // float xOffset = utilities.mapValue(lowerSeconds, timelineStart, timelineEnd, timelineXOffset, timelineXOffset + timelineScreenSize); // float xOffset2 = utilities.mapValue(upperSeconds, timelineStart, timelineEnd, timelineXOffset, timelineXOffset + timelineScreenSize); float date = d.getDaysSince1980(); float xOffset = utilities.mapValue(date, datelineStart, datelineEnd, timelineXOffset, timelineXOffset + timelineScreenSize); if(xOffset > timelineXOffset && xOffset < timelineXOffset + timelineScreenSize) { float radius = 25.f; PVector loc = new PVector(xOffset, datelineYOffset, 0); // PVector loc = new PVector(xOffset, datelineYOffset, hudDistanceInit); SelectableDate st = new SelectableDate(id, loc, radius, d); // int newID, int newClusterID, PVector newLocation, Box newRectangle return st; } else return null; } /** * Draw the field timeline * @param p Parent world */ private void displayTimeline(WMV_World p) { WMV_Field f = p.getCurrentField(); mv.tint(255); mv.stroke(0.f, 0.f, 255.f, 255.f); mv.strokeWeight(3.f); mv.fill(0.f, 0.f, 255.f, 255.f); mv.line(timelineXOffset, timelineYOffset, 0, timelineXOffset + timelineScreenSize, timelineYOffset, 0); // ml.line(timelineXOffset, timelineYOffset, hudDistanceInit, timelineXOffset + timelineScreenSize, timelineYOffset, hudDistanceInit); String startTime = utilities.secondsToTimeAsString(timelineStart, false, false); String endTime = utilities.secondsToTimeAsString(timelineEnd, false, false); mv.textSize(hudVerySmallTextSize); float firstHour = utilities.roundSecondsToHour(timelineStart); if(firstHour == (int)(timelineStart / 3600.f) * 3600.f) firstHour += 3600.f; float lastHour = utilities.roundSecondsToHour(timelineEnd); if(lastHour == (int)(timelineEnd / 3600.f + 1.f) * 3600.f) lastHour -= 3600.f; float timeLength = timelineEnd - timelineStart; float timeToScreenRatio = timelineScreenSize / timeLength; if(lastHour / 3600.f - firstHour / 3600.f <= 16.f) { float xOffset = timelineXOffset + (firstHour - timelineStart) * timeToScreenRatio - 20.f; float pos; for( pos = firstHour ; pos <= lastHour ; pos += 3600.f ) { String time = utilities.secondsToTimeAsString(pos, false, false); mv.text(time, xOffset, timelineYOffset - timelineHeight * 0.5f - 40.f, 0); // ml.text(time, xOffset, timelineYOffset - timelineHeight * 0.5f - 40.f, hudDistanceInit); xOffset += 3600.f * timeToScreenRatio; } if( (firstHour - timelineStart) * timeToScreenRatio - 20.f > 200.f) mv.text(startTime, timelineXOffset, timelineYOffset - timelineHeight * 0.5f - 40.f, 0); // ml.text(startTime, timelineXOffset, timelineYOffset - timelineHeight * 0.5f - 40.f, hudDistanceInit); xOffset -= 3600.f * timeToScreenRatio; if(timelineXOffset + timelineScreenSize - 40.f - xOffset > 200.f) mv.text(endTime, timelineXOffset + timelineScreenSize - 40.f, timelineYOffset - timelineHeight * 0.5f - 40.f, 0); // ml.text(endTime, timelineXOffset + timelineScreenSize - 40.f, timelineYOffset - timelineHeight * 0.5f - 40.f, hudDistanceInit); } else { float xOffset = timelineXOffset; for( float pos = firstHour - 3600.f ; pos <= lastHour ; pos += 7200.f ) { String time = utilities.secondsToTimeAsString(pos, false, false); mv.text(time, xOffset, timelineYOffset - timelineHeight * 0.5f - 40.f, 0); // ml.text(time, xOffset, timelineYOffset - timelineHeight * 0.5f - 40.f, hudDistanceInit); xOffset += 7200.f * timeToScreenRatio; } } if(f.getDateline().size() == 1) { for(WMV_TimeSegment t : f.getTimeline().timeline) displayTimeSegment(p, t); } else if(f.getDateline().size() > 1) { if(displayDate == -1) { for(WMV_Timeline ts : f.getTimelines()) for(WMV_TimeSegment t:ts.timeline) displayTimeSegment(p, t); } else { if(displayDate < f.getTimelines().size()) { ArrayList<WMV_TimeSegment> ts = f.getTimelines().get(displayDate).timeline; for(WMV_TimeSegment t:ts) displayTimeSegment(p, t); } } } if(!timelineTransition) { if(currentSelectableTimeSegmentID >= 0 && currentSelectableTimeSegmentID < selectableTimeSegments.size()) { if(currentSelectableTimeSegmentFieldTimeSegmentID == selectableTimeSegments.get(currentSelectableTimeSegmentID).segment.getFieldTimelineID()) { if(currentSelectableTimeSegmentID != -1 && selectableTimeSegments.size() > 0 && currentSelectableTimeSegmentID < selectableTimeSegments.size()) { if(displayDate == -1 || selectableTimeSegments.get(currentSelectableTimeSegmentID).segment.getFieldDateID() == displayDate) { if(selectedTime == -1) /* Draw current time segment */ selectableTimeSegments.get(currentSelectableTimeSegmentID).display(p, 0.f, 0.f, 255.f, true); else selectableTimeSegments.get(currentSelectableTimeSegmentID).display(p, 0.f, 0.f, 255.f, false); } } } } /* Draw selected time segment */ if(selectedTime != -1 && selectableTimeSegments.size() > 0 && selectedTime < selectableTimeSegments.size()) selectableTimeSegments.get(selectedTime).display(p, 40.f, 255.f, 255.f, true); } } /** * Display dateline for current field * @param p Parent world */ private void displayDateline(WMV_World p) { WMV_Field f = p.getCurrentField(); mv.tint(255); mv.stroke(0.f, 0.f, 255.f, 255.f); mv.strokeWeight(3.f); mv.fill(0.f, 0.f, 255.f, 255.f); mv.line(timelineXOffset, datelineYOffset, 0, timelineXOffset + timelineScreenSize, datelineYOffset, 0); // ml.line(datelineXOffset, datelineYOffset, hudDistanceInit, datelineXOffset + timelineScreenSize, datelineYOffset, hudDistanceInit); if(f.getDateline().size() == 1) { displayDate(p, f.getDate(0)); } else if(f.getDateline().size() > 1) { for(WMV_Date d : f.getDateline()) displayDate(p, d); } if(selectedDate >= 0 && selectableDates.size() > 0 && selectedDate < selectableDates.size()) selectableDates.get(selectedDate).display(p, 40.f, 255.f, 255.f, true); if(currentSelectableDate >= 0 && selectableDates.size() > 0 && currentSelectableDate < selectableDates.size()) selectableDates.get(currentSelectableDate).display(p, 0.f, 0.f, 255.f, false); if(displayDate >= 0 && allDates != null) { allDates.display(p, 55.f, 120.f, 255.f, false); mv.textSize(hudSmallTextSize); mv.fill(35, 115, 255, 255); mv.text("Show All", allDates.getLocation().x - 3, allDates.getLocation().y + 30, 0); } } /** * Display date on dateline * @param p Parent world * @param d Date to display */ private void displayDate(WMV_World p, WMV_Date d) { float date = d.getDaysSince1980(); float xOffset = utilities.mapValue(date, datelineStart, datelineEnd, timelineXOffset, timelineXOffset + timelineScreenSize); if(xOffset > timelineXOffset && xOffset < timelineXOffset + timelineScreenSize) { mv.strokeWeight(0.f); mv.fill(120.f, 165.f, 245.f, 155.f); mv.pushMatrix(); mv.stroke(120.f, 165.f, 245.f, 155.f); mv.strokeWeight(25.f); // ml.point(xOffset, datelineYOffset, hudDistanceInit); mv.point(xOffset, datelineYOffset, 0); mv.popMatrix(); } } /** * Display time segment on timeline * @param t Time segment to display * @param id */ private void displayTimeSegment(WMV_World p, WMV_TimeSegment t) { PVector lowerTime = t.getLower().getTimeAsPVector(); // Format: PVector(hour, minute, second) PVector upperTime = t.getUpper().getTimeAsPVector(); float lowerSeconds = utilities.getTimePVectorSeconds(lowerTime); float upperSeconds = utilities.getTimePVectorSeconds(upperTime); if(upperSeconds == lowerSeconds) { lowerSeconds -= minSegmentSeconds * 0.5f; upperSeconds += minSegmentSeconds * 0.5f; } ArrayList<WMV_Time> tsTimeline = t.getTimeline(); // Get timeline for this time segment ArrayList<PVector> times = new ArrayList<PVector>(); for(WMV_Time ti : tsTimeline) times.add(ti.getTimeAsPVector()); float xOffset = utilities.mapValue(lowerSeconds, timelineStart, timelineEnd, timelineXOffset, timelineXOffset + timelineScreenSize); float xOffset2 = utilities.mapValue(upperSeconds, timelineStart, timelineEnd, timelineXOffset, timelineXOffset + timelineScreenSize); if(xOffset > timelineXOffset && xOffset2 < timelineXOffset + timelineScreenSize) { mv.pushMatrix(); mv.translate(0.f, timelineYOffset, 0); // ml.translate(0.f, timelineYOffset, hudDistanceInit); mv.stroke(imageHue, 185.f, 255.f, 155.f); mv.strokeWeight(1.f); for(WMV_Time ti : tsTimeline) { PVector time = ti.getTimeAsPVector(); float seconds = utilities.getTimePVectorSeconds(time); float xOff = utilities.mapValue(seconds, timelineStart, timelineEnd, timelineXOffset, timelineXOffset + timelineScreenSize); if(xOff > timelineXOffset && xOff < timelineXOffset + timelineScreenSize) { switch(ti.getMediaType()) { case 0: mv.stroke(imageHue, 165.f, 215.f, 225.f); break; case 1: mv.stroke(panoramaHue, 165.f, 215.f, 225.f); break; case 2: mv.stroke(videoHue, 165.f, 215.f, 225.f); break; case 3: mv.stroke(soundHue, 165.f, 215.f, 225.f); break; } mv.line(xOff, -timelineHeight / 2.f, 0.f, xOff, timelineHeight / 2.f, 0.f); } } /* Set hue according to media type */ float firstHue = imageHue; float secondHue = imageHue; if(t.hasVideo()) firstHue = videoHue; if(t.hasSound()) { if(firstHue == videoHue) secondHue = soundHue; else firstHue = soundHue; } if(t.hasPanorama()) { if(firstHue == soundHue) secondHue = panoramaHue; else if(firstHue == videoHue) { if(secondHue == imageHue) secondHue = panoramaHue; } else firstHue = panoramaHue; } if(!t.hasImage()) { float defaultHue = 0.f; if(firstHue == imageHue) System.out.println("ERROR: firstHue still imageHue but segment has no image!"); else defaultHue = firstHue; if(secondHue == imageHue) secondHue = defaultHue; } mv.strokeWeight(2.f); /* Draw rectangle around time segment */ mv.stroke(firstHue, 165.f, 215.f, 225.f); mv.line(xOffset, -timelineHeight * 0.5f, 0.f, xOffset, timelineHeight * 0.5f, 0.f); mv.line(xOffset, timelineHeight * 0.5f, 0.f, xOffset2, timelineHeight * 0.5f, 0.f); mv.stroke(secondHue, 165.f, 215.f, 225.f); mv.line(xOffset2, -timelineHeight * 0.5f, 0.f, xOffset2, timelineHeight * 0.5f, 0.f); mv.line(xOffset, -timelineHeight * 0.5f, 0.f, xOffset2, -timelineHeight * 0.5f, 0.f); mv.popMatrix(); } } /** * Get selected time segment for given mouse 3D location * @param mouseScreenLoc Mouse 3D location * @return Selected time segment */ private SelectableTimeSegment getSelectedTimeSegment(PVector mouseLoc) { for(SelectableTimeSegment st : selectableTimeSegments) if( mouseLoc.x > st.leftEdge && mouseLoc.x < st.rightEdge && mouseLoc.y > st.topEdge && mouseLoc.y < st.bottomEdge ) return st; return null; } /** * Get selected time segment for given mouse 3D location * @param mouseScreenLoc Mouse 3D location * @return Selected time segment */ private SelectableMedia getSelectedMedia(PVector mouseLoc) { for(SelectableMedia m : selectableMedia) if( mouseLoc.x > m.leftEdge && mouseLoc.x < m.rightEdge && mouseLoc.y > m.topEdge && mouseLoc.y < m.bottomEdge ) return m; return null; } /** * Get selected time segment for given mouse 3D location * @param mouseScreenLoc Mouse 3D location * @return Selected time segment */ private SelectableDate getSelectedDate(PVector mouseLoc) { for(SelectableDate sd : selectableDates) { if(PVector.dist(mouseLoc, sd.getLocation()) < sd.radius) return sd; } if(allDates != null) { if(PVector.dist(mouseLoc, allDates.getLocation()) < allDates.radius) return allDates; else return null; } else return null; } /** * Update timeline based on current mouse position * @param p Parent world */ public void updateMapViewMouse(WMV_World p) { // System.out.println("Display.updateMapViewMouse()... mouseX:"+ml.mouseX+" mouseY:"+ml.mouseY); PVector mouseLoc = new PVector(mv.mouseX, mv.mouseY); if(buttons.size() > 0) { for(MV_Button b : buttons) { if(b.isVisible()) { if( mouseLoc.x > b.leftEdge && mouseLoc.x < b.rightEdge && mouseLoc.y > b.topEdge && mouseLoc.y < b.bottomEdge ) b.setSelected(true); else b.setSelected(false); } } } } /** * Update timeline based on current mouse position * @param p Parent world */ public void updateTimelineMouse(WMV_World p) { // System.out.println("Display.updateTimelineMouse()... mouseX:"+ml.mouseX+" mouseY:"+ml.mouseY); PVector mouseLoc = new PVector(mv.mouseX, mv.mouseY); if(mv.debug.mouse) { startDisplayHUD(); mv.stroke(155, 0, 255); mv.strokeWeight(5); mv.point(mouseLoc.x, mouseLoc.y, 0); // Show mouse adjusted location for debugging endDisplayHUD(); } if(buttons.size() > 0) { for(MV_Button b : buttons) { if(b.isVisible()) { if( mouseLoc.x > b.leftEdge && mouseLoc.x < b.rightEdge && mouseLoc.y > b.topEdge && mouseLoc.y < b.bottomEdge ) b.setSelected(true); else b.setSelected(false); } } } if(selectableTimeSegments != null) { SelectableTimeSegment timeSelected = getSelectedTimeSegment(mouseLoc); if(timeSelected != null) { selectedTime = timeSelected.getID(); // Set to selected selectedCluster = timeSelected.getClusterID(); if(mv.debug.time && mv.debug.detailed) System.out.println("Selected time segment:"+selectedTime+" selectedCluster:"+selectedCluster); updateFieldTimeline = true; // Update timeline to show selected segment } else selectedTime = -1; } if(selectedTime == -1 && selectableDates != null) { SelectableDate dateSelected = getSelectedDate(mouseLoc); if(dateSelected != null) { selectedDate = dateSelected.getID(); // Set to selected updateFieldTimeline = true; // Update timeline to show selected segment // updateCurrentSelectableDate = true; // Added 6-24-17 } else selectedDate = -1; } } /** * Update Library View based on current mouse position * @param p Parent world */ private void updateLibraryViewMouse() { // System.out.println("Display.updateLibraryViewMouse()... frameCount:"+ml.frameCount+" mouseX:"+ml.mouseX+" mouseY:"+ml.mouseY+" displayView:"+displayView); PVector mouseLoc = new PVector(mv.mouseX, mv.mouseY); if(mv.debug.mouse) { startDisplayHUD(); mv.stroke(155, 0, 255); mv.strokeWeight(5); mv.point(mouseLoc.x, mouseLoc.y, 0); // Show mouse adjusted location for debugging endDisplayHUD(); } if(buttons.size() > 0) { for(MV_Button b : buttons) { if(b.isVisible()) { if( mouseLoc.x > b.leftEdge && mouseLoc.x < b.rightEdge && mouseLoc.y > b.topEdge && mouseLoc.y < b.bottomEdge ) b.setSelected(true); else b.setSelected(false); } } } if(createdSelectableMedia) { if(selectableMedia != null) { SelectableMedia mediaSelected = getSelectedMedia(mouseLoc); if(mediaSelected != null) { if(selectedMedia != mediaSelected.getID()) { selectedMedia = mediaSelected.getID(); // Set to selected if(mv.debug.library && mv.debug.detailed) System.out.println("Display.updateLibraryMouse()... Selected media: "+selectedMedia); } } else selectedMedia = -1; } } } /** * Zoom to current selectable time segment * @param p Parent World * @param transition Whether to use smooth zooming transition */ public void zoomToCurrentSelectableTimeSegment(WMV_World p, boolean transition) { if(currentSelectableTimeSegmentID >= 0) { float first = selectableTimeSegments.get(currentSelectableTimeSegmentID).segment.getLower().getAbsoluteTime(); float last = selectableTimeSegments.get(currentSelectableTimeSegmentID).segment.getUpper().getAbsoluteTime(); float day = utilities.getTimePVectorSeconds(new PVector(24,0,0)); // Seconds in a day first *= day; // Convert from normalized value to seconds last *= day; float newTimelineStart = utilities.roundSecondsToInterval(first, 600.f); // Round down to nearest hour if(newTimelineStart > first) newTimelineStart -= 600; if(newTimelineStart < 0.f) newTimelineStart = 0.f; float newTimelineEnd = utilities.roundSecondsToInterval(last, 600.f); // Round up to nearest hour if(newTimelineEnd < last) newTimelineEnd += 600; if(newTimelineEnd > day) newTimelineEnd = day; if(transition) { timelineTransition(newTimelineStart, newTimelineEnd, initTimelineTransitionLength, mv.frameCount); } else { timelineStart = newTimelineStart; timelineEnd = newTimelineEnd; } } } /** * Zoom to the current selectable date * @param p Parent world * @param transition Whether to use smooth zooming transition */ public void zoomToCurrentSelectableDate(WMV_World p, boolean transition) { if(currentSelectableDate >= 0) { WMV_Field f = p.getCurrentField(); int curDate = selectableDates.get(currentSelectableDate).getID(); float first = f.getTimelines().get(curDate).timeline.get(0).getLower().getAbsoluteTime(); float last = f.getTimelines().get(curDate).timeline.get(f.getTimelines().get(curDate).timeline.size()-1).getUpper().getAbsoluteTime(); float day = utilities.getTimePVectorSeconds(new PVector(24,0,0)); // Seconds in a day first *= day; // Convert from normalized value to seconds last *= day; float newTimelineStart = utilities.roundSecondsToInterval(first, 1800.f); // Round down to nearest hour if(newTimelineStart > first) newTimelineStart -= 1800; if(newTimelineStart < 0.f) newTimelineStart = 0.f; float newTimelineEnd = utilities.roundSecondsToInterval(last, 1800.f); // Round up to nearest hour if(newTimelineEnd < last) newTimelineEnd += 1800; if(newTimelineEnd > day) newTimelineEnd = day; if(transition) { timelineTransition(newTimelineStart, newTimelineEnd, initTimelineTransitionLength, mv.frameCount); } else { timelineStart = newTimelineStart; timelineEnd = newTimelineEnd; } } } /** * Zoom out to full timeline * @param p Parent world * @param transition Whether to use smooth zooming transition */ public void zoomToTimeline(WMV_World p, boolean transition) { WMV_Field f = p.getCurrentField(); float first = f.getTimeSegment(0).getLower().getAbsoluteTime(); // First field media time, normalized float last = f.getTimeSegment(f.getTimeline().timeline.size()-1).getUpper().getAbsoluteTime(); // Last field media time, normalized float day = utilities.getTimePVectorSeconds(new PVector(24,0,0)); // Seconds in a day first *= day; // Convert from normalized value to seconds last *= day; float newTimelineStart = utilities.roundSecondsToHour(first); // Round down to nearest hour if(newTimelineStart > first) newTimelineStart -= 3600; if(newTimelineStart < 0.f) newTimelineStart = 0.f; float newTimelineEnd = utilities.roundSecondsToHour(last); // Round up to nearest hour if(newTimelineEnd < last) newTimelineEnd += 3600; if(newTimelineEnd > day) newTimelineEnd = day; if(transition) { timelineTransition(newTimelineStart, newTimelineEnd, initTimelineTransitionLength, mv.frameCount); } else { timelineStart = newTimelineStart; timelineEnd = newTimelineEnd; } } public void resetZoom(WMV_World p, boolean fade) { float newTimelineStart = 0.f; float newTimelineEnd = utilities.getTimePVectorSeconds(new PVector(24,0,0)); if(fade) { timelineTransition(newTimelineStart, newTimelineEnd, initTimelineTransitionLength, mv.frameCount); } else { timelineStart = newTimelineStart; timelineEnd = newTimelineEnd; } } /** * Get current zoom level * @return Zoom level */ public float getZoomLevel() { float day = utilities.getTimePVectorSeconds(new PVector(24,0,0)); // Seconds in a day float result = (timelineEnd - timelineStart) / day; return result; } /** * Start timeline zoom transition * @param p Parent world * @param direction -1: In 1: Out * @param transition Whether to use smooth zooming transition */ public void zoomTimeline(WMV_World p, int direction, boolean transition) { boolean zoom = true; transitionZoomDirection = direction; float length = timelineEnd - timelineStart; float newLength; float day = utilities.getTimePVectorSeconds(new PVector(24,0,0)); // Seconds in a day if(transitionZoomDirection == -1) // Zooming in newLength = length * transitionZoomInIncrement; else // Zooming out newLength = length * transitionZoomOutIncrement; float newTimelineStart, newTimelineEnd; if(transitionZoomDirection == -1) // Zooming in { float diff = length - newLength; newTimelineStart = timelineStart + diff / 2.f; newTimelineEnd = timelineEnd - diff / 2.f; } else // Zooming out { float diff = newLength - length; newTimelineStart = timelineStart - diff / 2.f; newTimelineEnd = timelineEnd + diff / 2.f; if(newTimelineEnd > day) { newTimelineStart -= (newTimelineEnd - day); newTimelineEnd = day; } if(newTimelineStart < 0.f) { newTimelineEnd -= newTimelineStart; newTimelineStart = 0.f; } if(newTimelineEnd > day) zoom = false; } if(zoom) { WMV_Field f = p.getCurrentField(); float first = f.getTimeSegment(0).getLower().getAbsoluteTime(); // First field media time, normalized float last = f.getTimeSegment(f.getTimeline().timeline.size()-1).getUpper().getAbsoluteTime(); // Last field media time, normalized if(transitionZoomDirection == 1) { if(length - newLength > 300.f) { newTimelineStart = utilities.roundSecondsToInterval(newTimelineStart, 600.f); // Round up to nearest 10 min. if(newTimelineStart > first) newTimelineStart -= 600; newTimelineEnd = utilities.roundSecondsToInterval(newTimelineEnd, 600.f); // Round up to nearest 10 min. if(newTimelineEnd < last) newTimelineEnd += 600; } } if(newTimelineEnd > day) newTimelineEnd = day; if(newTimelineStart < 0.f) newTimelineEnd = 0.f; if(transition) { timelineTransition( newTimelineStart, newTimelineEnd, 10, mv.frameCount ); // timelineTransition( timelineStart, newTimelineEnd, 10, ml.frameCount ); timelineZooming = true; } else timelineEnd = newTimelineEnd; } } /** * Zoom by a factor * @param p Parent world * @param amount Factor to zoom by * @param transition Whether to use smooth zooming transition */ public void zoomByAmount(WMV_World p, float amount, boolean transition) { float length = timelineEnd - timelineStart; float newLength = length * amount; float result = timelineStart + newLength; if(result < utilities.getTimePVectorSeconds(new PVector(24,0,0))) { WMV_Field f = p.getCurrentField(); float last = f.getTimeSegment(f.getTimeline().timeline.size()-1).getUpper().getAbsoluteTime(); // Last field media time, normalized float day = utilities.getTimePVectorSeconds(new PVector(24,0,0)); // Seconds in a day float newTimelineEnd; if(length - newLength > 300.f) { newTimelineEnd = utilities.roundSecondsToInterval(result, 600.f); // Round up to nearest 10 min. if(newTimelineEnd < last) newTimelineEnd += 600; } else newTimelineEnd = result; // Changing length less than 5 min., no rounding if(newTimelineEnd > day) newTimelineEnd = day; if(transition) timelineTransition(timelineStart, newTimelineEnd, initTimelineTransitionLength, mv.frameCount); else timelineEnd = newTimelineEnd; } } /** * Start scrolling timeline in specified direction * @param p Parent world * @param direction Left: -1 or Right: 1 */ public void scroll(WMV_World p, int direction) { transitionScrollDirection = direction; float newStart = timelineStart + transitionScrollIncrement * transitionScrollDirection; float newEnd = timelineEnd + transitionScrollIncrement * transitionScrollDirection; float day = utilities.getTimePVectorSeconds(new PVector(24,0,0)); if(newStart > 0.f && newEnd < day) { timelineScrolling = true; timelineTransition(newStart, newEnd, 10, mv.frameCount); } } /** * Stop zooming the timeline */ public void stopZooming() { timelineZooming = false; updateFieldTimeline = true; transitionScrollIncrement = initTransitionScrollIncrement * getZoomLevel(); } /** * Stop scrolling the timeline */ public void stopScrolling() { timelineScrolling = false; updateFieldTimeline = true; } /** * Handle mouse released event * @param p Parent world * @param mouseX Mouse x position * @param mouseY Mouse y position */ public void handleMapViewMouseReleased(WMV_World p, float mouseX, float mouseY) { updateMapViewMouse(p); for(MV_Button b : buttons) { if( b.isSelected() && b.containsPoint(new PVector(mouseX, mouseY) )) { switch(b.getID()) { case 0: // Zoom to Viewer map2D.zoomToCluster(mv.world, mv.world.getCurrentCluster(), true); // Zoom to current cluster break; case 1: // Zoom to Field map2D.zoomToField(mv.world.getCurrentField(), true); break; case 2: // Zoom to World map2D.resetMapZoom(true); // map2D.zoomToWorld(true); break; case 3: // Pan Up map2D.stopPanning(); break; case 4: // Pan Left map2D.stopPanning(); break; case 5: // Pan Right map2D.stopPanning(); break; case 6: // Pan Down map2D.stopPanning(); break; case 7: // Zoom In map2D.stopZooming(); break; case 8: // Zoom Out map2D.stopZooming(); break; case 10: // Set Map View: World Mode setMapViewMode(0); break; case 11: // Set Map View: Field Mode setMapViewMode(1); break; // PRESSED // case "MapZoomIn": // if(map2D.isZooming()) // map2D.stopZooming(); // else // map2D.startZoomingIn(ml.world); // break; // case "MapZoomOut": // if(map2D.isZooming()) // map2D.stopZooming(); // else // map2D.startZoomingOut(ml.world); // break; // case "PanUp": // if(map2D.isPanning()) // map2D.stopPanning(); // else // map2D.panUp(); // break; // case "PanLeft": // if(map2D.isPanning()) // map2D.stopPanning(); // else // map2D.panLeft(); // break; // case "PanDown": // if(map2D.isPanning()) // map2D.stopPanning(); // else // map2D.panDown(); // break; // case "PanRight": // if(map2D.isPanning()) // map2D.stopPanning(); // else // map2D.panRight(); // break; // CLICKED // case "PanUp": // if(map2D.isPanning()) // map2D.stopPanning(); // break; // case "PanLeft": // if(map2D.isPanning()) // map2D.stopPanning(); // break; // case "PanDown": // if(map2D.isPanning()) // map2D.stopPanning(); // break; // case "PanRight": // if(map2D.isPanning()) // map2D.stopPanning(); // break; // case "ZoomToViewer": // map2D.zoomToCluster(ml.world, ml.world.getCurrentCluster(), true); // Zoom to current cluster // break; // case "ZoomToField": // map2D.zoomToField(ml.world.getCurrentField(), true); // break; // case "MapZoomIn": // if(map2D.isZooming()) // map2D.stopZooming(); // break; // case "ResetMapZoom": // map2D.resetMapZoom(true); // // map2D.zoomToWorld(true); // break; // case "MapZoomOut": // if(map2D.isZooming()) // map2D.stopZooming(); // break; // // RELEASED // case "PanUp": // case "PanLeft": // case "PanDown": // case "PanRight": // display.map2D.stopPanning(); // break; // case "MapZoomIn": // case "MapZoomOut": // display.map2D.stopZooming(); // break; } b.setSelected(false); } } if(map2D.mousePressedFrame > map2D.mouseDraggedFrame) { if(getDisplayView() == 1) // In Map View { if(mapViewMode == 1) // Field Mode { System.out.println("Display.handleMapViewMouseReleased()... map2D.selectedCluster:"+map2D.selectedCluster+" getCurrentField().getClusters().size():"+mv.world.getCurrentField().getClusters().size()+"..."); if(map2D.selectedCluster >= 0 && map2D.selectedCluster < mv.world.getCurrentField().getClusters().size()) { if(map2D.selectedCluster != mv.world.viewer.getState().getCurrentClusterID()) map2D.zoomToCluster(mv.world, mv.world.getCurrentField().getCluster(map2D.selectedCluster), true); System.out.println("Display.handleMapViewMouseReleased()... Started zooming, will moveToClusterOnMap()..."); mv.world.viewer.moveToClusterOnMap(map2D.selectedCluster, true); // Move to cluster on map and stay in Map View } } else if(mapViewMode == 0) // World Mode { if(map2D.selectedField >= 0 && map2D.selectedField < mv.world.getFields().size()) { currentDisplayCluster = 0; map2D.selectedCluster = -1; map2D.zoomToField(mv.world.getField(map2D.selectedField), true); } } } } } /** * Handle mouse released event * @param p Parent world * @param mouseX Mouse x position * @param mouseY Mouse y position */ public void handleMapViewMousePressed(WMV_World p, float mouseX, float mouseY) { updateMapViewMouse(p); for(MV_Button b : buttons) { if( b.isSelected() && b.containsPoint(new PVector(mouseX, mouseY)) ) { switch(b.getID()) { // case 0: // Zoom to Viewer // map2D.zoomToCluster(ml.world, ml.world.getCurrentCluster(), true); // Zoom to current cluster // break; // case 1: // Zoom to Field // map2D.zoomToField(ml.world.getCurrentField(), true); // break; // case 2: // Zoom to World // map2D.resetMapZoom(true); // // map2D.zoomToWorld(true); // break; case 3: // Pan Up if(map2D.isPanning()) map2D.stopPanning(); else map2D.panUp(); break; case 4: // Pan Left if(map2D.isPanning()) map2D.stopPanning(); else map2D.panLeft(); break; case 5: // Pan Right if(map2D.isPanning()) map2D.stopPanning(); else map2D.panRight(); break; case 6: // Pan Down if(map2D.isPanning()) map2D.stopPanning(); else map2D.panDown(); break; case 7: // Zoom In if(map2D.isZooming()) map2D.stopZooming(); else map2D.startZoomingIn(mv.world); break; case 8: // Zoom Out if(map2D.isZooming()) map2D.stopZooming(); else map2D.startZoomingOut(mv.world); break; // PRESSED // // case "MapZoomIn": // if(map2D.isZooming()) // map2D.stopZooming(); // else // map2D.startZoomingIn(ml.world); // break; // case "MapZoomOut": // if(map2D.isZooming()) // map2D.stopZooming(); // else // map2D.startZoomingOut(ml.world); // break; // case "PanUp": // if(map2D.isPanning()) // map2D.stopPanning(); // else // map2D.panUp(); // break; // case "PanLeft": // if(map2D.isPanning()) // map2D.stopPanning(); // else // map2D.panLeft(); // break; // case "PanDown": // if(map2D.isPanning()) // map2D.stopPanning(); // else // map2D.panDown(); // break; // case "PanRight": // if(map2D.isPanning()) // map2D.stopPanning(); // else // map2D.panRight(); // break; // CLICKED // case "PanUp": // if(map2D.isPanning()) // map2D.stopPanning(); // break; // case "PanLeft": // if(map2D.isPanning()) // map2D.stopPanning(); // break; // case "PanDown": // if(map2D.isPanning()) // map2D.stopPanning(); // break; // case "PanRight": // if(map2D.isPanning()) // map2D.stopPanning(); // break; // case "ZoomToViewer": // map2D.zoomToCluster(ml.world, ml.world.getCurrentCluster(), true); // Zoom to current cluster // break; // case "ZoomToField": // map2D.zoomToField(ml.world.getCurrentField(), true); // break; // case "MapZoomIn": // if(map2D.isZooming()) // map2D.stopZooming(); // break; // case "ResetMapZoom": // map2D.resetMapZoom(true); // // map2D.zoomToWorld(true); // break; // case "MapZoomOut": // if(map2D.isZooming()) // map2D.stopZooming(); // break; // // RELEASED // case "PanUp": // case "PanLeft": // case "PanDown": // case "PanRight": // display.map2D.stopPanning(); // break; // case "MapZoomIn": // case "MapZoomOut": // display.map2D.stopZooming(); // break; } b.setSelected(false); } } } /** * Handle mouse released event * @param p Parent world * @param mouseX Mouse x position * @param mouseY Mouse y position */ public void handleTimeViewMouseReleased(WMV_World p, float mouseX, float mouseY) { updateTimelineMouse(p); if(selectedTime != -1) if(selectedCluster != -1) p.viewer.teleportToCluster(selectedCluster, false, selectableTimeSegments.get(selectedTime).segment.getFieldTimelineID()); if(selectedDate != -1) setCurrentSelectableDate(selectedDate); for(MV_Button b : buttons) { if( b.isSelected() && b.containsPoint(new PVector(mouseX, mouseY) )) { switch(b.getID()) { case 0: // Scroll left stopScrolling(); break; case 1: // Scroll right stopScrolling(); break; case 2: // Zoom in stopZooming(); break; case 3: // Zoom out stopZooming(); break; case 4: // Zoom out mv.display.zoomToTimeline(mv.world, true); break; case 5: // Zoom out mv.display.zoomToCurrentSelectableTimeSegment(mv.world, true); break; case 6: // Zoom out mv.display.zoomToCurrentSelectableDate(mv.world, true); break; case 7: // Zoom out mv.display.resetZoom(mv.world, true); break; // case "TimelineZoomToFit": 4 // ml.display.zoomToTimeline(ml.world, true); // break; // case "TimelineZoomToSelected": 5 // ml.display.zoomToCurrentSelectableTimeSegment(ml.world, true); // break; // case "TimelineZoomToDate": 6 // ml.display.zoomToCurrentSelectableDate(ml.world, true); // break; // case "TimelineZoomToFull": 7 // ml.display.resetZoom(ml.world, true); // break; // PRESSED // // case "TimelineZoomIn": // if(isZooming()) // stopZooming(); // else // zoom(ml.world, -1, true); // break; // case "TimelineZoomOut": // if(isZooming()) // stopZooming(); // else // zoom(ml.world, 1, true); // break; // case "TimelineReverse": // if(isScrolling()) // stopScrolling(); // else // scroll(ml.world, -1); // break; // case "TimelineForward": // if(isScrolling()) // stopScrolling(); // else // scroll(ml.world, 1); // break; // CLICKED // case "TimelineZoomIn": // stopZooming(); // break; // case "TimelineZoomOut": // stopZooming(); // break; // case "TimelineZoomToFit": // zoomToTimeline(ml.world, true); // break; // case "TimelineZoomToSelected": // zoomToCurrentSelectableTimeSegment(ml.world, true); // break; // case "TimelineZoomToDate": // zoomToCurrentSelectableDate(ml.world, true); // break; // case "TimelineZoomToFull": // resetZoom(ml.world, true); // break; // RELEASED // case "TimelineZoomIn": // stopZooming(); // break; // case "TimelineZoomOut": // stopZooming(); // break; // case "TimelineReverse": // stopScrolling(); // break; // case "TimelineForward": // stopScrolling(); // break; } b.setSelected(false); } } } /** * Handle mouse released event * @param p Parent world * @param mouseX Mouse x position * @param mouseY Mouse y position */ public void handleTimeViewMousePressed(WMV_World p, float mouseX, float mouseY) { updateTimelineMouse(p); if(selectedTime != -1) if(selectedCluster != -1) p.viewer.teleportToCluster(selectedCluster, false, selectableTimeSegments.get(selectedTime).segment.getFieldTimelineID()); if(selectedDate != -1) setCurrentSelectableDate(selectedDate); for(MV_Button b : buttons) { if( b.isSelected() && b.containsPoint(new PVector(mouseX, mouseY)) ) { switch(b.getID()) { case 0: // Scroll left if(isScrolling()) stopScrolling(); else scroll(mv.world, -1); break; case 1: // Scroll right if(isScrolling()) stopScrolling(); else scroll(mv.world, 1); break; case 2: // Zoom in if(isZooming()) stopZooming(); else zoomTimeline(mv.world, -1, true); break; case 3: // Zoom out if(isZooming()) stopZooming(); else zoomTimeline(mv.world, 1, true); break; // PRESSED // // case "TimelineZoomIn": // if(isZooming()) // stopZooming(); // else // zoom(ml.world, -1, true); // break; // case "TimelineZoomOut": // if(isZooming()) // stopZooming(); // else // zoom(ml.world, 1, true); // break; // case "TimelineReverse": // if(isScrolling()) // stopScrolling(); // else // scroll(ml.world, -1); // break; // case "TimelineForward": // if(isScrolling()) // stopScrolling(); // else // scroll(ml.world, 1); // break; // CLICKED // case "TimelineZoomIn": // stopZooming(); // break; // case "TimelineZoomOut": // stopZooming(); // break; // case "TimelineZoomToFit": // zoomToTimeline(ml.world, true); // break; // case "TimelineZoomToSelected": // zoomToCurrentSelectableTimeSegment(ml.world, true); // break; // case "TimelineZoomToDate": // zoomToCurrentSelectableDate(ml.world, true); // break; // case "TimelineZoomToFull": // resetZoom(ml.world, true); // break; // RELEASED // case "TimelineZoomIn": // stopZooming(); // break; // case "TimelineZoomOut": // stopZooming(); // break; // case "TimelineReverse": // stopScrolling(); // break; // case "TimelineForward": // stopScrolling(); // break; } b.setSelected(false); } } } /** * Handle mouse released event in Library View * @param p Parent world * @param mouseX Mouse x position * @param mouseY Mouse y position */ public void handleLibraryViewMouseReleased(WMV_World p, float mouseX, float mouseY) { updateLibraryViewMouse(); if(selectedMedia != -1) p.viewer.startViewingMedia(0, selectedMedia); // Only images currently implemented for(MV_Button b : buttons) { if( b.isSelected() && b.containsPoint(new PVector(mouseX, mouseY) )) { switch(b.getID()) { case 0: // Set Library Display if(getLibraryViewMode() != 2) setLibraryViewMode(2); break; case 1: // Set Field Display if(getLibraryViewMode() != 1) setLibraryViewMode(1); break; case 2: // Set Cluster Display if(getLibraryViewMode() != 0) setLibraryViewMode(0); break; case 10: // Previous Location showPreviousItem(); break; case 11: // Next Location showNextItem(); break; case 12: // Current Location if(getLibraryViewMode() == 1) setDisplayItem( mv.world.viewer.getCurrentFieldID() ); else if(getLibraryViewMode() == 2) setDisplayItem( mv.world.viewer.getCurrentClusterID() ); break; } b.setSelected(false); } } } /** * Handle mouse released event in Library View * @param p Parent world * @param mouseX Mouse x position * @param mouseY Mouse y position */ public void handleMediaViewMouseReleased(WMV_World p, float mouseX, float mouseY) { p.viewer.exitMediaView(); } /** * Draw Interactive Clustering screen * @param p Parent world */ void displayInteractiveClustering(WMV_World p) { map2D.displaySatelliteMap(p); if(messages.size() > 0) displayMessages(p); } /** * Reset all HUD displays */ public void reset() { // ml = parent; /* Display View */ displayView = 0; /* {0: Scene 1: Map 2: Library 3: Timeline 4: Media} */ /* Setup */ worldSetup = true; dataFolderFound = false; setupProgress = 0.f; /* Windows */ disableLostFocusHook = false; /* Graphics */ messageHUDDistance = hudDistanceInit * 6.f; blendMode = 0; /* Alpha blending mode */ /* Map View */ mapViewMode = 1; // {0: World, 1: Field, (2: Cluster -- In progress)} initializedMaps = false; initializedSatelliteMap = false; /* Time View */ timelineStart = 0.f; timelineEnd = 0.f; datelineStart = 0.f; datelineEnd = 0.f; displayDate = -1; updateCurrentSelectableTimeSegment = true; updateCurrentSelectableDate = true; selectableTimeSegments = new ArrayList<SelectableTimeSegment>(); selectableDates = new ArrayList<SelectableDate>(); allDates = null; fieldTimelineCreated = false; fieldDatelineCreated = false; updateFieldTimeline = true; // hudLeftMargin = 0.f; timelineYOffset = 0.f; timelineYOffset = 0.f; timelineXOffset = 0.f; datelineYOffset = 0.f; selectedTime = -1; selectedCluster = -1; currentSelectableTimeSegmentID = -1; currentSelectableTimeSegmentFieldTimeSegmentID = -1; selectedDate = -1; currentSelectableDate = -1; currentSelectableTimeSegment = null; currentSelectableTimeSegmentID = -1; currentSelectableTimeSegmentFieldTimeSegmentID = -1; timelineTransition = false; timelineZooming = false; timelineScrolling = false; transitionScrollDirection = -1; transitionZoomDirection = -1; timelineTransitionStartFrame = 0; timelineTransitionEndFrame = 0; timelineTransitionLength = 30; timelineStartTransitionStart = 0; timelineStartTransitionTarget = 0; timelineEndTransitionStart = 0; timelineEndTransitionTarget = 0; transitionScrollIncrement = 1750.f; /* Library View */ libraryViewMode = 2; currentDisplayField = 0; currentDisplayCluster = 0; createdSelectableMedia = false; selectableMedia = null; currentSelectableMedia = null; /* Current selected media in grid */ selectedMedia = -1; updateSelectableMedia = true; /* Media View */ mediaViewMediaType = -1; mediaViewMediaID = -1; messageStartFrame = -1; metadataStartFrame = -1; startupMessageStartFrame = -1; screenWidth = mv.displayWidth; screenHeight = mv.displayHeight; // float aspect = (float)screenHeight / (float)screenWidth; // if(aspect != 0.625f) // monitorOffsetXAdjustment = (0.625f / aspect); startupMessages = new ArrayList<String>(); messages = new ArrayList<String>(); metadata = new ArrayList<String>(); /* 3D HUD Displays */ messageXOffset = screenWidth * 1.75f; messageYOffset = -screenHeight * 0.33f; metadataXOffset = -screenWidth * 1.33f; metadataYOffset = -screenHeight / 2.f; /* 2D HUD Displays */ // timelineScreenSize = screenWidth * 0.86f; // timelineHeight = screenHeight * 0.1f; timelineStart = 0.f; timelineEnd = utilities.getTimePVectorSeconds(new PVector(24,0,0)); // timelineYOffset = screenHeight * 0.33f; // hudCenterXOffset = screenWidth * 0.5f; // hudTopMargin = screenHeight * 0.085f; // timelineXOffset = screenWidth * 0.07f; // datelineYOffset = screenHeight * 0.5f; setupScreen(); map2D.reset(); startWorldSetup(); // Start World Setup Display Mode after reset // messageFont = ml.createFont("ArialNarrow-Bold", messageTextSize); // defaultFont = ml.createFont("SansSerif", smallTextSize); } /** * Add message to queue * @param ml Parent app * @param message Message to send */ public void message(MetaVisualizer ml, String message) { if(ml.state.interactive) { messages.add(message); while(messages.size() > maxMessages) messages.remove(0); } else { messageStartFrame = ml.world.getState().frameCount; messages.add(message); while(messages.size() > maxMessages) messages.remove(0); } } /** * Get current HUD Distance along Z-Axis * @return Current HUD Z-Axis Distance */ public float getMessageHUDDistance() { float distance = messageHUDDistance; distance /= (Math.sqrt(mv.world.viewer.getSettings().fieldOfView)); return distance; } /** * Get current HUD Distance along Z-Axis * @return Current HUD Z-Axis Distance */ public float getMessageTextSize() { return largeTextSize * mv.world.viewer.getSettings().fieldOfView * 3.f; } /** * Display current messages * @p Parent world */ void displayMessages(WMV_World p) { float xFactor = (float) Math.pow( mv.world.viewer.getSettings().fieldOfView * 12.f, 3) * 0.33f; float yFactor = mv.world.viewer.getSettings().fieldOfView * 4.f; float xPos = messageXOffset * xFactor; float yPos = messageYOffset * yFactor - lineWidth * yFactor; mv.pushMatrix(); mv.fill(0, 0, 255, 255); mv.textFont(messageFont); // float hudDist = getMessageHUDDistance(); if(mv.state.interactive) { for(String s : messages) { yPos += lineWidth * yFactor; displayScreenText(mv, s, xPos, yPos += lineWidth * yFactor, getMessageTextSize()); } } else if(mv.frameCount - messageStartFrame < messageDuration) { for(String s : messages) { yPos += lineWidth * yFactor; displayScreenText(mv, s, messageXOffset, yPos, getMessageTextSize()); } } else { clearMessages(); // Clear messages after duration has ended } mv.popMatrix(); } /** * Add a metadata message (single line) to the display queue * @param curFrameCount Current frame count * @param message Line of metadata */ public void metadata(int curFrameCount, String message) { metadataStartFrame = curFrameCount; metadata.add(message); while(metadata.size() > 16) metadata.remove(0); } /** * Draw current metadata messages to the screen * @param p Parent world */ public void displayMetadata(WMV_World p) { float xFactor = mv.world.viewer.getSettings().fieldOfView * 8.f; float yFactor = mv.world.viewer.getSettings().fieldOfView * 4.f; float yPos = metadataYOffset * yFactor - lineWidth * yFactor; mv.textFont(defaultFont); mv.pushMatrix(); mv.fill(0, 0, 255, 255); // White text mv.textSize(mediumTextSize); float xOffset = metadataXOffset * xFactor; for(String s : metadata) { yPos += lineWidth * yFactor; displayScreenText(mv, s, metadataXOffset, yPos, getMessageTextSize()); } mv.popMatrix(); } public void displayScreenText(MetaVisualizer ml, String text, float x, float y, float textSize) { ml.textSize(textSize); startHUD(); ml.text(text, x, y, getMessageHUDDistance()); // Use period character to draw a point } /** * @param message Message to be sent * Add startup message to display queue */ public void sendSetupMessage(WMV_World p, String message) { if(worldSetup) { startupMessageStartFrame = mv.frameCount; startupMessages.add(message); while(startupMessages.size() > 16) startupMessages.remove(0); if(mv.debug.print) System.out.println(message); } } /** * Display startup windows * @param Parent world */ public void displayStartup(WMV_World p, boolean librarySetup) { startHUD(); mv.pushMatrix(); mv.fill(0, 0, 245.f, 255.f); mv.textSize(largeTextSize * 1.5f); if(worldSetup) // Showing setup messages + windows { if(mv.createNewLibrary) { if(mv.state.chooseMediaFolders) { // ml.text("Please select media folder(s)...", screenWidth / 2.1f, yPos += lineWidthVeryWide * 5.f, hudDistanceInit); if(!window.setupCreateLibraryWindow) { window.showCreateLibraryWindow = true; window.openCreateLibraryWindow(); mv.library = new MV_Library(""); // Create new library } } else if(!mv.state.selectedNewLibraryDestination) { window.setCreateLibraryWindowText("Please select new library destination...", null); } } else { if(mv.state.startup && !mv.state.selectedLibrary) { if(!mv.state.gettingExiftoolPath) // Getting Exiftool program filepath { if(!window.setupStartupWindow) window.openStartupWindow(); // Open Startup Window else if(!window.showStartupWindow) window.showStartupWindow(false); // Show Startup Window } } } mv.textSize(largeTextSize); // p.p.text("For support and the latest updates, visit: www.spatializedmusic.com/MultimediaLocator", screenWidth / 2.f, yPos, hudDistance); } else { displayMessages(p); } mv.popMatrix(); } /** * Draw Library View * @param p Parent world */ public void displayLibraryView(WMV_World p) { mv.rectMode(PApplet.CORNER); // Specify top left point in rect() -- Needed? WMV_Field f;// = p.getCurrentField(); mv.textFont(defaultFont); // = ml.createFont("SansSerif", 30); startDisplayHUD(); mv.pushMatrix(); for(MV_Button b : buttons) { if(libraryViewMode > 0) { b.display(p, 0.f, 0.f, 255.f); } else { if(b.getID() < 3) b.display(p, 0.f, 0.f, 255.f); } } mv.textFont(defaultFont); // = ml.createFont("SansSerif", 30); float x = hudCenterXOffset - buttonWidth * 2.f - buttonSpacing * 4.f; float y = hudTopMargin + buttonHeight * 0.5f; // Starting vertical position // float y = hudTopMargin + buttonHeight * 2.5f; // Starting vertical position mv.fill(0, 0, 255, 255); mv.textSize(hudSmallTextSize); mv.text("Current View:", x, y, 0); y += buttonHeight + buttonSpacing; switch(libraryViewMode) { case 1: // Field mv.text("Go To Field:", x - buttonSpacing * 0.5f, y, 0); break; case 2: // Location (Cluster) mv.text("Go To Location:", x - buttonSpacing * 0.5f, y, 0); break; } x = hudLeftMargin + buttonWidth * 0.75f; y = hudTopMargin + buttonHeight * 0.5f; // Starting vertical position mv.textSize(hudSmallTextSize); WMV_Cluster c = p.getCurrentCluster(); if(currentDisplayCluster != c.getID()) { String strGPS = mv.utilities.formatGPSLocation( mv.world.viewer.getGPSLocation(), false ); mv.text("Current Location:", x, y, 0); mv.text(strGPS, x, y += hudLineWidthWide, 0); } mv.popMatrix(); endDisplayHUD(); c = null; // WMV_Cluster c = null; x = hudCenterXOffset; y = hudTopMargin + buttonHeight * 5.f; // Starting vertical position switch(libraryViewMode) { case 0: // Library f = p.getCurrentField(); startDisplayHUD(); mv.pushMatrix(); mv.fill(0.f, 0.f, 255.f, 255.f); mv.textSize(hudVeryLargeTextSize); if(mv.library.getName(false) != null && mv.library.getName(false) != "") mv.text(mv.library.getName(false), x, y); else mv.text("Untitled Environment", x, y); y += hudLineWidthVeryWide; // y += hudLineWidthVeryWide + buttonHeight + buttonSpacing * 2.f; // ml.textSize(hudMediumTextSize); // ml.text(ml.world.getCurrentField().getName(), x, y); // ml.text("Single Field Environment", x, y ); // ml.text("No Current Library", x, y += lineWidthWide * 1.5f); // } // else // { // y += hudLineWidthWide + buttonHeight * 2.f + buttonSpacing * 2.f; // // ml.textSize(hudLargeTextSize); // if(ml.library.getName(false) != null && ml.library.getName(false) != "") // ml.text(ml.library.getName(false), x, y += lineWidthWide * 1.5f); // else // ml.text("Untitled Environment", x, y += lineWidthWide * 1.5f); // } mv.textSize(hudSmallTextSize); if(mv.world.getFieldCount() > 1) mv.text("Current Field: "+mv.world.getCurrentField().getName()+", #"+ (f.getID()+1)+" of "+ mv.world.getFields().size(), x, y += lineWidthWide); else mv.text("Current Field: "+mv.world.getCurrentField().getName()+" (Single Field Environment)", x, y); mv.text(" Library Location: "+mv.library.getLibraryFolder(), x, y += lineWidthWide); mv.text(" Output Folder: "+(mv.world.outputFolder==null?"None":mv.world.outputFolder), x, y += lineWidth); mv.popMatrix(); endDisplayHUD(); break; case 1: // Field f = p.getField(currentDisplayField); startDisplayHUD(); mv.pushMatrix(); mv.fill(0, 0, 255, 255); mv.textSize(hudVeryLargeTextSize); if(currentDisplayField == mv.world.getCurrentField().getID()) mv.text(mv.world.getCurrentField().getName()+" (Current)", x, y); else mv.text(mv.world.getCurrentField().getName(), x, y); y += hudLineWidthVeryWide; mv.textSize(hudMediumTextSize); if(mv.library.getName(false) != null && mv.library.getName(false) != "") mv.text("Environment: "+mv.library.getName(false), x, y); else if(mv.world.getFields().size()>1) mv.text("Environment: "+"Untitled (Not Saved)", x, y); y += hudLineWidthWide * 1.5f; c = p.getCurrentCluster(); mv.textSize(hudSmallTextSize); // if(ml.world.getFieldCount() > 1) // ml.text("Field #"+ (f.getID()+1)+" of "+ ml.world.getFields().size(), x, y); // ml.textSize(hudMediumTextSize); // ml.text(" Points of Interest: "+(f.getClusters().size()), x, y += hudLineWidthWide, 0); mv.textSize(hudSmallTextSize); mv.text("Spatial Locations: "+(f.getClusters().size()), x, y, 0); // ml.text(" Visible: "+ml.world.getVisibleClusters().size(), x, y += hudLineWidth); mv.text("Time Segments: "+(f.getTimeline().timeline.size()), x, y += hudLineWidth, 0); mv.text( "Field Width: " + utilities.round( f.getModel().getState().fieldWidth, 3 )+ " Length: "+utilities.round( f.getModel().getState().fieldLength, 3)+ " Height: " + utilities.round( f.getModel().getState().fieldHeight, 3 ), x, y += hudLineWidth * 2.f); mv.text(" Media Density (per sq. m.): "+utilities.round( f.getModel().getState().mediaDensity, 3 ), x, y += hudLineWidthWide); // ml.textSize(hudMediumTextSize); // ml.text(" Viewer ", x, y += hudLineWidthWide, 0); mv.textSize(hudSmallTextSize); // ml.text("Viewer Location "+(f.getClusters().size()), x, y += hudLineWidth, 0); // if(c != null) // ml.text("Viewer Location: " + ml.utilities.formatGPSLocation( ml.world.viewer.getGPSLocation() ) + " (#" + (c.getID()+1) + ")", x, y += hudLineWidth, 0); // ml.text(" Time ", x, y += hudLineWidth, 0); // String strTime = getCurrentFormattedTime(); if(mv.world.getState().getTimeMode() == 0) // Location { int tsID = mv.world.viewer.getCurrentFieldTimeSegment(); // WMV_TimeSegment ts = ml.world.getCurrentField().getTimeline().timeline.get(tsID); WMV_Time t = c.getClosestTimeToClusterTime( c.getCurrentTime() ); // String strClusterTime = t.getFormattedTime(true, false); // String strFieldTime = ts.getCenter().getFormattedTime(true, false); mv.text("Current Time Segment #"+tsID+" of "+mv.world.getCurrentField().getTimeline().timeline.size()+" (#"+(t.getID()+1)+" of "+c.getTimeline().timeline.size()+" at current location)", x, y += hudLineWidthWide, 0); //// ml.text(""+ strFieldTime + ", #"+tsID+" of "+ml.world.getCurrentField().getTimeline().timeline.size(), x, y += hudLineWidth, 0); //// ml.text(" Visible: "+ml.world.getVisibleClusters().size(), x, y += hudLineWidth); } else // Field { int tsID = mv.world.viewer.getCurrentFieldTimeSegment(); // WMV_TimeSegment ts = ml.world.getCurrentField().getTimeline().timeline.get(tsID); // String strFieldTime = ts.getCenter().getFormattedTime(true, false); mv.text("Current Time Segment #"+tsID+" of "+mv.world.getCurrentField().getTimeline().timeline.size(), x, y += hudLineWidth, 0); //// ml.text(" Visible: "+ml.world.getVisibleClusters().size(), x, y += hudLineWidth); } mv.text(" Time Mode: "+(mv.world.getState().getTimeMode() == 0 ? "Location":"Field"), x, y += hudLineWidth, 0); // ml.text(" Merged: "+f.getModel().getState().mergedClusters+" out of "+(f.getModel().getState().mergedClusters+f.getClusters().size())+" Total", x, y += hudLineWidth, 0); // if(p.getState().hierarchical) ml.text(" Current Cluster Depth: "+f.getState().clusterDepth, x, y += hudLineWidth, 0); // ml.text(" Minimum Distance: "+p.settings.minClusterDistance, x, y += hudLineWidth, 0); // ml.text(" Maximum Distance: "+p.settings.maxClusterDistance, x, y += hudLineWidth, 0); // ml.text(" Population Factor: "+f.getModel().getState().clusterPopulationFactor, x, y += hudLineWidth, 0); mv.text(" Images: "+f.getImageCount()+" Visible Range: "+f.getImagesVisible(), x, y += hudLineWidth); mv.text(" Panoramas: "+f.getPanoramaCount()+" Visible Range: "+f.getPanoramasVisible(), x, y += hudLineWidth); mv.text(" Videos: "+f.getVideoCount()+" Visible Range: "+f.getVideosVisible()+" Playing: "+f.getVideosPlaying(), x, y += hudLineWidth); mv.text(" Sounds: "+f.getSoundCount()+" In Audible Range: "+f.getSoundsAudible()+" Playing: "+f.getSoundsPlaying(), x, y += hudLineWidth); // if(f.getDateline() != null) // { // ml.textSize(hudMediumTextSize); // if(f.getDateline().size() > 0) // { // int fieldDate = p.getCurrentField().getTimeSegment(p.viewer.getCurrentFieldTimeSegment()).getFieldDateID(); // ml.text(" Current Time:", x, y += hudLineWidthWide, 0); // //// ml.text(" Current Time Segment", x, y += hudLineWidthWide, 0); //// ml.text(" ID: "+ p.viewer.getCurrentFieldTimeSegment()+" of "+ p.getCurrentField().getTimeline().timeline.size() +" in Main Timeline", x, y += hudLineWidthWide, 0); //// ml.text(" Date: "+ (fieldDate)+" of "+ p.getCurrentField().getDateline().size(), x, y += hudLineWidth, 0); //// ml.text(" Date-Specific ID: "+ p.getCurrentField().getTimeSegment(p.viewer.getCurrentFieldTimeSegment()).getFieldTimelineIDOnDate() //// +" of "+ p.getCurrentField().getTimelines().get(fieldDate).timeline.size() + " in Timeline #"+(fieldDate), x, y += hudLineWidth, 0); // } // } mv.popMatrix(); endDisplayHUD(); // map2D.displaySmallBasicMap(p); // -- Display small map break; case 2: // Cluster f = p.getCurrentField(); if(currentDisplayCluster != -1) c = f.getCluster(currentDisplayCluster); // Get cluster to display info for WMV_Cluster cl = p.getCurrentCluster(); startDisplayHUD(); mv.pushMatrix(); mv.fill(0, 0, 255, 255); mv.textSize(hudVeryLargeTextSize); mv.text(" Location #"+ (c.getID()+1) + ((c.getID() == cl.getID())?" (Current)":"")+ " of "+mv.world.getCurrentField().getClusters().size(), x, y, 0); y += hudLineWidthVeryWide; mv.textSize(hudMediumTextSize); String strGPSLoc = mv.utilities.formatGPSLocation( c.getGPSLocation(mv.world), true ); mv.text(strGPSLoc, x, y, 0); if(c != null) { WMV_Time t1 = c.getTimeline().timeline.get(0).getLower(); WMV_Time t2 = c.getTimeline().timeline.get(c.getTimeline().timeline.size()-1).getUpper(); String strTime1 = t1.getFormattedTime(true, false); String strDate1 = t1.getFormattedDate(); String strTime2 = t2.getFormattedTime(true, false); String strDate2 = t2.getFormattedDate(); String strTime = strTime1 + ", "+ strDate1 + " - " + strTime2 + ", " + strDate2; mv.text(strTime, x, y += hudLineWidthWide, 0); // Display location time and date range y += hudLineWidthWide; mv.text("Field: "+p.getCurrentField().getName(), x, y, 0); mv.textSize(hudSmallTextSize); if(f.getImageCount() > 0) mv.text(" Images: "+c.getState().images.size(), x, y += hudLineWidthVeryWide); if(f.getPanoramaCount() > 0) mv.text(" Panoramas: "+c.getState().panoramas.size(), x, y += hudLineWidth); if(f.getVideoCount() > 0) mv.text(" Videos: "+c.getState().videos.size(), x, y += hudLineWidth); if(f.getSoundCount() > 0) mv.text(" Sounds: "+c.getState().sounds.size(), x, y += hudLineWidth); mv.text(" Total Media: "+ c.getState().mediaCount, x, y += hudLineWidth, 0); mv.text(" Spatial Segments: "+ c.segments.size(), x, y += hudLineWidthWide, 0); mv.text(" Time Segments: "+ c.getTimeline().timeline.size(), x, y += hudLineWidth, 0); mv.text(" Viewer Distance: "+utilities.round(PVector.dist(c.getLocation(), p.viewer.getLocation()), 1)+" m.", x, y += hudLineWidthWide, 0); } clusterMediaYOffset = y + 65.f; // Set cluster media Y offset if(createdSelectableMedia) { drawClusterMediaGrid(); // Draw media in cluster in grid } else { ArrayList<WMV_Image> imageList = f.getImagesInCluster(c.getID(), p.getCurrentField().getImages()); if(imageList != null) createClusterSelectableMedia(p, imageList); } mv.popMatrix(); endDisplayHUD(); break; } mv.rectMode(PApplet.CENTER); // Return rect mode to Center } /** * Get current time as formatted string * @return Current time as formatted string */ public String getCurrentFormattedTime() { String strTime = "00:00:00"; if(mv.world.getState().getTimeMode() == 0) // Location { WMV_Cluster c = mv.world.getCurrentCluster(); int tsID = mv.world.viewer.getCurrentFieldTimeSegment(); // WMV_TimeSegment ts = mv.world.getCurrentField().getTimeline().timeline.get(tsID); WMV_Time t = c.getClosestTimeToClusterTime( c.getCurrentTime() ); if(t != null) strTime = t.getFormattedTime(true, false); } else // Field { int tsID = mv.world.viewer.getCurrentFieldTimeSegment(); WMV_TimeSegment ts = mv.world.getCurrentField().getTimeline().timeline.get(tsID); if(ts != null) strTime = ts.getCenter().getFormattedTime(true, false); } return strTime; } /** * Set library window text * @param newText New text */ public void updateTimeWindowCurrentTime() { String strTime = getCurrentFormattedTime()+", "+getCurrentFormattedDate(); window.lblCurrentTime.setText(strTime); } /** * Get current date as formatted string * @return */ public String getCurrentFormattedDate() { int dateID = mv.world.getState().currentDate; WMV_Date d = mv.world.getCurrentField().getDate(dateID); return d.getFormattedDate(); } /** * Create selectable media for Library View grid * @param p * @param imageList */ private void createClusterSelectableMedia(WMV_World p, ArrayList<WMV_Image> imageList) { selectableMedia = new ArrayList<SelectableMedia>(); int count = 1; float imgXPos = clusterMediaXOffset; float imgYPos = clusterMediaYOffset; // Starting vertical position for(WMV_Image i : imageList) { float origWidth = i.getWidth(); float origHeight = i.getHeight(); float thumbnailHeight = thumbnailWidth * origHeight / origWidth; /* Create thumbnail */ PImage image = mv.loadImage(i.getFilePath()); Image iThumbnail = image.getImage().getScaledInstance((int)thumbnailWidth, (int)thumbnailHeight, BufferedImage.SCALE_SMOOTH); PImage thumbnail = new PImage(iThumbnail); SelectableMedia newMedia = new SelectableMedia( i.getID(), thumbnail, new PVector(imgXPos, imgYPos), thumbnailWidth, thumbnailHeight ); selectableMedia.add(newMedia); imgXPos += thumbnailWidth + thumbnailWidth * thumbnailSpacing; if(imgXPos > mv.width - clusterMediaXOffset) { imgXPos = clusterMediaXOffset; imgYPos += thumbnailHeight + thumbnailHeight * thumbnailSpacing; } count++; // if(count > maxSelectableMedia) // break; } if(mv.debug.ml) mv.systemMessage("Display.createClusterSelectableMedia()... Created selectable media... Count: "+selectableMedia.size()+" p.ml.width:"+mv.width+"clusterMediaXOffset:"+clusterMediaXOffset); createdSelectableMedia = true; } /** * Set display item in Library View * @param itemID New item ID */ public void setDisplayItem(int itemID) { if(libraryViewMode == 1) { if(currentDisplayField != itemID) currentDisplayField = itemID; } else if(libraryViewMode == 2) { if(currentDisplayCluster != itemID) { currentDisplayCluster = itemID; updateSelectableMedia = true; } } } /** * Move to previous Display Item in Library View */ public void showPreviousItem() { if(libraryViewMode == 1) { currentDisplayField--; if(currentDisplayField < 0) currentDisplayField = mv.world.getFields().size() - 1; } else if(libraryViewMode == 2) // Cluster { currentDisplayCluster--; if(currentDisplayCluster < 0) currentDisplayCluster = mv.world.getCurrentFieldClusters().size() - 1; int count = 0; while(mv.world.getCurrentField().getCluster(currentDisplayCluster).isEmpty()) { currentDisplayCluster--; count++; if(currentDisplayCluster < 0) currentDisplayCluster = mv.world.getCurrentFieldClusters().size() - 1; if(count > mv.world.getCurrentFieldClusters().size()) break; } updateSelectableMedia = true; } } /** * Move to next Display Item in Library View */ public void showNextItem() { if(libraryViewMode == 1) { currentDisplayField++; if( currentDisplayField >= mv.world.getFields().size()) currentDisplayField = 0; } else if(libraryViewMode == 2) // Cluster { currentDisplayCluster++; if( currentDisplayCluster >= mv.world.getCurrentFieldClusters().size()) currentDisplayCluster = 0; int count = 0; while(mv.world.getCurrentField().getCluster(currentDisplayCluster).isEmpty()) { currentDisplayCluster++; count++; if( currentDisplayCluster >= mv.world.getCurrentFieldClusters().size()) currentDisplayCluster = 0; if(count > mv.world.getCurrentFieldClusters().size()) break; } updateSelectableMedia(); } } /** * Update Library View media grid items */ public void updateSelectableMedia() { updateSelectableMedia = true; } /** * Set current object viewable in Media View * @param mediaType Media type * @param mediaID Media ID */ public void setMediaViewItem(int mediaType, int mediaID) { mediaViewMediaType = mediaType; mediaViewMediaID = mediaID; if(mediaType == 2) { WMV_Video v = mv.world.getCurrentField().getVideo(mediaID); if(!v.isLoaded()) v.loadMedia(mv); if(!v.isPlaying()) v.play(mv); } } /** * Display selected media centered in window at full brightness * @param p Parent world */ private void displayMediaView(WMV_World p) { if(mediaViewMediaType > -1 && mediaViewMediaID > -1) { switch(mediaViewMediaType) { case 0: displayImage2D(p.getCurrentField().getImage(mediaViewMediaID)); break; case 1: displayPanorama2D(p.getCurrentField().getPanorama(mediaViewMediaID)); break; case 2: displayVideo2D(p.getCurrentField().getVideo(mediaViewMediaID)); break; // case 3: // -- In progress // displaySound2D(p.getCurrentField().getSound(mediaViewMediaID)); // break; } } } /** * Display image in Media View * @param image Image to display */ private void displayImage2D(WMV_Image image) { image.display2D(mv); } /** * Display 360-degree panorama texture in Media View * @param panorama Panorama to display */ private void displayPanorama2D(WMV_Panorama panorama) { panorama.display2D(mv); } /** * Display video in Media View * @param video Video to display */ private void displayVideo2D(WMV_Video video) { video.display2D(mv); } /** * Initialize 2D drawing * @param p Parent world */ public void startHUD() { mv.camera(); } /** * Initialize 2D drawing * @param p Parent world */ private void startDisplayHUD() { currentFieldOfView = mv.world.viewer.getFieldOfView(); mv.world.viewer.resetPerspective(); beginHUD(mv); } /** * End 2D drawing * @param p Parent world */ private void endDisplayHUD() { endHUD(mv); mv.world.viewer.zoomToFieldOfView(currentFieldOfView); } /** * Draw thumbnails of media in cluster in grid format * @param p Parent world * @param imageList Images in cluster */ private void drawClusterMediaGrid() { int count = 0; mv.stroke(255, 255, 255); mv.strokeWeight(15); mv.fill(0, 0, 255, 255); for(SelectableMedia m : selectableMedia) { if(m != null) { boolean selected = m.getID() == selectedMedia; if(count < 200) m.display(mv.world, 0.f, 0.f, 255.f, selected); count++; } else { mv.systemMessage("Display.drawSelectableMedia()... Selected media is null!"); } } } /** * @return Whether current view mode is a 2D display mode (true) or 3D World View (false) */ public boolean inDisplayView() { if( displayView != 0 ) return true; else return false; } /** * Set display view * @param p Parent world * @param newDisplayView New display view */ public void setDisplayView(WMV_World p, int newDisplayView) { p.viewer.setLastDisplayView( displayView ); displayView = newDisplayView; // Set display view if(mv.debug.display) System.out.println("Display.setDisplayView()... displayView:"+displayView); switch(newDisplayView) { case 0: // World View if(window.setupMainMenu) { window.optWorldView.setSelected(true); window.optMapView.setSelected(false); window.optTimelineView.setSelected(false); window.optLibraryView.setSelected(false); window.btnSaveLibrary.setEnabled(true); window.btnSaveField.setEnabled(true); } if(window.setupTimeWindow) { // window.btnTimeView.setEnabled(true); } if(setupMapView) setupMapView = false; if(setupTimeView) setupTimeView = false; if(setupLibraryView) setupLibraryView = false; break; case 1: // Map View if(!initializedMaps) { map2D.initialize(p); } else if(mv.world.getCurrentField().getGPSTracks() != null) { if(mv.world.getCurrentField().getGPSTracks().size() > 0) { if(mv.world.viewer.getSelectedGPSTrackID() != -1) { if(!map2D.createdGPSMarker) { map2D.createMarkers(mv.world); } } } } map2D.resetMapZoom(false); if(window.setupMainMenu) { window.optWorldView.setSelected(false); window.optMapView.setSelected(true); window.optTimelineView.setSelected(false); window.optLibraryView.setSelected(false); window.btnSaveLibrary.setEnabled(false); window.btnSaveField.setEnabled(false); } if(setupTimeView) setupTimeView = false; if(setupLibraryView) setupLibraryView = false; break; case 2: // Timeline View if(window.setupMainMenu) { window.optWorldView.setSelected(false); window.optMapView.setSelected(false); window.optTimelineView.setSelected(true); window.optLibraryView.setSelected(false); window.btnSaveLibrary.setEnabled(false); window.btnSaveField.setEnabled(false); } if(window.setupNavigationWindow) { // window.setMapControlsEnabled(false); // window.btnMapView.setEnabled(true); // window.btnWorldView.setEnabled(true); } if(window.setupTimeWindow) { // window.btnTimeView.setEnabled(false); // window.setTimeWindowControlsEnabled(true); } zoomToTimeline(mv.world, true); if(setupLibraryView) setupLibraryView = false; if(setupMapView) setupMapView = false; break; case 3: /* Library View */ switch(libraryViewMode) { case 0: break; case 1: setDisplayItem(p.getCurrentField().getID()); break; case 2: setDisplayItem(p.viewer.getCurrentClusterID()); break; } if(window.setupMainMenu) { window.optWorldView.setSelected(false); window.optMapView.setSelected(false); window.optTimelineView.setSelected(false); window.optLibraryView.setSelected(true); window.btnSaveLibrary.setEnabled(false); window.btnSaveField.setEnabled(false); } if(window.setupTimeWindow) { // window.btnTimeView.setEnabled(true); } if(setupTimeView) setupTimeView = false; if(setupMapView) setupMapView = false; break; case 4: // Media View break; } } /** * Set Library View Mode * @param newLibraryViewMode */ public void setLibraryViewMode(int newLibraryViewMode) { if( newLibraryViewMode >= 0 && newLibraryViewMode < 3) libraryViewMode = newLibraryViewMode; else if( newLibraryViewMode < 0 ) libraryViewMode = 2; else if( newLibraryViewMode >= 3) libraryViewMode = 0; if(window.setupPreferencesWindow) { // switch(libraryViewMode) // { // case 0: // window.optLibraryViewWorldMode.setSelected(true); // window.optLibraryViewFieldMode.setSelected(false); // window.optLibraryViewClusterMode.setSelected(false); // window.lblLibraryViewText.setText(ml.library.getName(false)); // break; // // case 1: // setDisplayItem(ml.world.getCurrentField().getID()); // window.optLibraryViewWorldMode.setSelected(false); // window.optLibraryViewFieldMode.setSelected(true); // window.optLibraryViewClusterMode.setSelected(false); // window.lblLibraryViewText.setText("Field:"); // break; // // case 2: // setDisplayItem(ml.world.viewer.getCurrentClusterID()); // window.optLibraryViewWorldMode.setSelected(false); // window.optLibraryViewFieldMode.setSelected(false); // window.optLibraryViewClusterMode.setSelected(true); // window.lblLibraryViewText.setText("Interest Point:"); // break; // } } } /** * Get Library View Mode * @return Current Library View Mode */ public int getLibraryViewMode() { return libraryViewMode; } public int getDisplayView() { return displayView; } /** * Clear previous messages */ public void clearMessages() { messages = new ArrayList<String>(); } /** * Clear previous metadata messages */ public void clearMetadata() { metadata = new ArrayList<String>(); // Reset message list } /** * Clear previous setup messages */ public void clearSetupMessages() { startupMessages = new ArrayList<String>(); } /** * Reset display modes and clear messages */ public void resetDisplayModes() { setDisplayView(mv.world, 0); // displayView = 0; mapViewMode = 0; setLibraryViewMode( 2 ); clearMessages(); clearMetadata(); } /** * Draw Interactive Clustering footer text * @param ml Parent app */ public void displayClusteringInfo(MetaVisualizer ml) { if(ml.world.state.hierarchical) { message(ml, "Hierarchical Clustering"); message(ml, " "); message(ml, "Use arrow keys UP and DOWN to change clustering depth... "); message(ml, "Use [ and ] to change Minimum Cluster Distance... "); } else { message(ml, "K-Means Clustering"); message(ml, " "); message(ml, "Use arrow keys LEFT and RIGHT to change Iterations... "); message(ml, "Use arrow keys UP and DOWN to change Population Factor... "); message(ml, "Use [ and ] to change Minimum Cluster Distance... "); } message(ml, " "); message(ml, "Press <spacebar> to restart simulation..."); } /** * Set Map View Mode * @param newMapViewMode New map view mode {0: World, 1: Field} */ public void setMapViewMode(int newMapViewMode) { if(mapViewMode != newMapViewMode) { mapViewMode = newMapViewMode; // Set Map View Mode if(!initializedMaps) { map2D.initialize(mv.world); } else { map2D.createMarkers(mv.world); // Create map markers for new mode map2D.resetMapZoom(true); switch(mapViewMode) { case 0: // World Mode btnZoomToWorld.setVisible(true); // map2D.zoomToWorld(false); break; case 1: // Field Mode btnZoomToWorld.setVisible(false); // map2D.zoomToField(ml.world, ml.world.getCurrentField(), false); break; } } } } /** * Get associated selectable time segment ID for given time segment * @param t Given time segment * @return Selectable time segment ID associated with given time segment */ private int getSelectableTimeIDOfFieldTimeSegment(WMV_TimeSegment t) { for(SelectableTimeSegment st : selectableTimeSegments) { if( t.getClusterID() == st.segment.getClusterID() && t.getClusterDateID() == st.segment.getClusterDateID() && t.getClusterTimelineID() == st.segment.getClusterTimelineID() && t.getFieldTimelineID() == st.segment.getFieldTimelineID() ) { return st.getID(); } } return -1; } /** * Set current selectable date (white rectangle) * @param newSelectableDate New selectable date ID */ private void setCurrentSelectableDate(int newSelectableDate) { if(newSelectableDate == -1 || newSelectableDate == -100) { showAllDates(); } else { displayDate = newSelectableDate; currentSelectableDate = newSelectableDate; updateFieldTimeline = true; } updateCurrentSelectableTimeSegment = true; updateCurrentSelectableDate = false; } /** * Selectable time segment on Time View timeline * @author davidgordon */ private class SelectableTimeSegment { private int id, clusterID; public float leftEdge, rightEdge, topEdge, bottomEdge; WMV_TimeSegment segment; SelectableTimeSegment(int newID, int newFieldTimelineID, int newClusterID, WMV_TimeSegment newSegment, PVector newLocation, float newLeftEdge, float newRightEdge, float newTopEdge, float newBottomEdge) { id = newID; // fieldTimelineID = newFieldTimelineID; clusterID = newClusterID; segment = newSegment; leftEdge = newLeftEdge; rightEdge = newRightEdge; topEdge = newTopEdge; bottomEdge = newBottomEdge; } public int getID() { return id; } public int getClusterID() { return clusterID; } public void display(WMV_World p, float hue, float saturation, float brightness, boolean preview) { mv.stroke(hue, saturation, brightness, 255); // Yellow rectangle around selected time segment mv.strokeWeight(3.f); mv.pushMatrix(); mv.line(leftEdge, topEdge, 0, leftEdge, bottomEdge, 0); mv.line(rightEdge, topEdge, 0, rightEdge, bottomEdge, 0); mv.line(leftEdge, topEdge, 0, rightEdge, topEdge, 0); mv.line(leftEdge, bottomEdge, 0, rightEdge, bottomEdge, 0); if(preview) { mv.fill(hue, saturation, brightness, 255); // Yellow rectangle around selected time segment mv.textSize(hudSmallTextSize); // ml.textSize(smallTextSize); String strTimespan = segment.getTimespanAsString(false, false); String strPreview = String.valueOf( segment.getTimeline().size() ) + " media, "+strTimespan; float length = timelineEnd - timelineStart; float day = utilities.getTimePVectorSeconds(new PVector(24,0,0)); // Seconds in a day float xOffset = -35.f * utilities.mapValue(length, 0.f, day, 0.2f, 1.f); mv.text(strPreview, (rightEdge+leftEdge)/2.f + xOffset, bottomEdge + 25.f, 0); } mv.popMatrix(); } } public boolean isZooming() { return timelineZooming; } public boolean isScrolling() { return timelineScrolling; } private class SelectableDate { private int id; private PVector location; public float radius; WMV_Date date; SelectableDate(int newID, PVector newLocation, float newRadius, WMV_Date newDate) { id = newID; location = newLocation; radius = newRadius; date = newDate; } public int getID() { return id; } public PVector getLocation() { return location; } /** * Display date and, if selected, preview text * @param p Parent world * @param hue Hue * @param saturation Saturation * @param brightness Brightness * @param selected Whether date is selected */ public void display(WMV_World p, float hue, float saturation, float brightness, boolean selected) { mv.pushMatrix(); mv.stroke(hue, saturation, brightness, 255.f); mv.strokeWeight(25.f); mv.point(location.x, location.y, location.z); if(selected && selectedDate != -1) { mv.fill(hue, saturation, brightness, 255); // Yellow rectangle around selected time segment mv.textSize(hudSmallTextSize); String strDate = date.getFormattedDate(); float textWidth = strDate.length() * displayWidthFactor; mv.text(strDate, location.x - textWidth * 0.5f, location.y + 30.f, location.z); // -- Should center based on actual text size! } mv.popMatrix(); } } private class SelectableMedia { private int id; private PVector location; // Screen location public float width, height; PImage thumbnail; public float leftEdge, rightEdge, topEdge, bottomEdge; SelectableMedia(int newID, PImage newThumbnail, PVector newLocation, float newWidth, float newHeight) { id = newID; thumbnail = newThumbnail; location = newLocation; width = newWidth; height = newHeight; leftEdge = location.x; rightEdge = leftEdge + width; topEdge = location.y; bottomEdge = topEdge + height; } public int getID() { return id; } public PVector getLocation() { return location; } /** * Display selection box * @param p * @param hue * @param saturation * @param brightness * @param selected */ public void display(WMV_World p, float hue, float saturation, float brightness, boolean selected) { // ml.stroke(hue, saturation, brightness, 255.f); // ml.strokeWeight(25.f); // ml.point(location.x, location.y, location.z); if(thumbnail != null) { mv.pushMatrix(); mv.translate(location.x, location.y, 0); mv.tint(255); mv.image(thumbnail, 0, 0, width, height); mv.popMatrix(); } else { mv.systemMessage("SelectableMedia.display()... Selected media #"+getID()+" thumbnail is null!"); } if(selected) { mv.stroke(hue, saturation, brightness, 255); // Yellow rectangle around selected time segment mv.strokeWeight(3.f); mv.pushMatrix(); mv.line(leftEdge, topEdge, 0, leftEdge, bottomEdge, 0); mv.line(rightEdge, topEdge, 0, rightEdge, bottomEdge, 0); mv.line(leftEdge, topEdge, 0, rightEdge, topEdge, 0); mv.line(leftEdge, bottomEdge, 0, rightEdge, bottomEdge, 0); mv.popMatrix(); } // if(selected && selectedDate != -1) // { // ml.fill(hue, saturation, brightness, 255); // Yellow rectangle around selected time segment // ml.textSize(hudSmallTextSize); // String strDate = date.getDateAsString(); // ml.text(strDate, location.x - 15.f, location.y + 50.f, location.z); // -- Should center based on actual text size! // } } } public void showAllDates() { displayDate = -1; selectedDate = -1; currentSelectableDate = -1; updateFieldTimeline = true; } public int getSelectedCluster() { return selectedCluster; } public int getCurrentSelectableTimeSegment() { return currentSelectableTimeSegmentID; } /** * Start World Setup Display Mode */ public void startWorldSetup() { worldSetup = true; } /** * Stop World Setup Display Mode */ public void stopWorldSetup() { worldSetup = false; } /** * @return Whether in World Setup Display Mode */ public boolean inWorldSetup() { return worldSetup; } /** -- Obsolete * Get mouse 3D location from screen location * @param mouseX * @param mouseY * @return */ // private PVector getMouse3DLocation(float mouseX, float mouseY) // { //// /* WORKS */ // float centerX = screenWidth * 0.5f; /* Center X location */ // float centerY = screenHeight * 0.5f; /* Center Y location */ // // float mouseXFactor = 2.55f; // float mouseYFactor = 2.55f; // float screenXFactor = 0.775f; // float screenYFactor = 0.775f; // // float x = mouseX * mouseXFactor - screenWidth * screenXFactor; // float y = mouseY * mouseYFactor - screenHeight * screenYFactor; // // float dispX = x - centerX; /* Mouse X displacement from the center */ // float dispY = y - centerY; /* Mouse Y displacement from the center */ // // float offsetXFactor = 0, offsetYFactor = 0; // if(screenWidth == 1280 && screenHeight == 800) // { // offsetXFactor = 0.111f; /* Offset X displacement from the center */ /* DEFAULT */ // offsetYFactor = 0.111f; /* Offset Y displacement from the center */ // } // else if(screenWidth == 1440 && screenHeight == 900) // { // offsetXFactor = 0.039f; /* Offset X displacement from the center */ /* SCALED x 1 */ // offsetYFactor = 0.039f; /* Offset Y displacement from the center */ // } // else if(screenWidth == 1680 && screenHeight == 1050) // { // offsetXFactor = -0.043f; /* Offset X displacement from the center */ /* SCALED x 2 */ // offsetYFactor = -0.043f; /* Offset Y displacement from the center */ // } // // float offsetX = dispX * offsetXFactor; /* Adjusted X offset */ // float offsetY = dispY * offsetYFactor; /* Adjusted Y offset */ // // x += offsetX; // y += offsetY; // //// if(ml.debug.mouse) //// System.out.println("Display.getMouse3DLocation()... screenWidth:"+screenWidth+" screenHeight:"+screenHeight+" offsetXFactor:"+offsetXFactor+" offsetYFactor:"+offsetYFactor); //// if(ml.debug.mouse) //// System.out.println("Display.getMouse3DLocation()... x2:"+x+" y2:"+y+" offsetX:"+offsetX+" offsetY:"+offsetY); // // PVector result = new PVector(x, y, hudDistanceInit); // -- Doesn't affect selection! // // if(ml.debug.mouse) // { // ml.stroke(155, 0, 255); // ml.strokeWeight(5); // ml.point(result.x, result.y, result.z); // Show mouse location for debugging // // ml.stroke(0, 255, 255); // ml.strokeWeight(10); // ml.point(centerX, centerY, hudDistanceInit); //// ml.point(0, 0, hudDistanceInit); // // System.out.println("Mouse 3D Location: x:"+result.x+" y:"+result.y); // } // // return result; // } /** * Display the main key commands on screen -- Obsolete */ // public void displayControls(WMV_World p) // { // startHUD(); // p.p.pushMatrix(); // // float xPos = centerTextXOffset; // float yPos = topTextYOffset; // Starting vertical position // // p.p.fill(0, 0, 255, 255); // p.p.textSize(largeTextSize); // p.p.text(" Keyboard Controls ", xPos, yPos, hudDistance); // // xPos = midLeftTextXOffset; // p.p.textSize(mediumTextSize); // p.p.text(" Main", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" R Restart MultimediaLocator", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" CMD + q Quit MultimediaLocator", xPos, yPos += lineWidth, hudDistance); // // p.p.textSize(mediumTextSize); // p.p.text(" Display", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" 1 Show/Hide Field Map +SHIFT to Overlay", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" 2 Show/Hide Field Statistics +SHIFT to Overlay", xPos, yPos += lineWidth, hudDistance); // p.p.text(" 3 Show/Hide Cluster Statistics +SHIFT to Overlay", xPos, yPos += lineWidth, hudDistance); // p.p.text(" 4 Show/Hide Keyboard Controls +SHIFT to Overlay", xPos, yPos += lineWidth, hudDistance); // // p.p.textSize(mediumTextSize); // p.p.text(" Time", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" T Time Fading On/Off", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" D Date Fading On/Off", xPos, yPos += lineWidth, hudDistance); // p.p.text(" space Pause On/Off ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" &/* Default Media Length - / +", xPos, yPos += lineWidth, hudDistance); // p.p.text(" SHIFT + Lt/Rt Cycle Length - / +", xPos, yPos += lineWidth, hudDistance); // p.p.text(" SHIFT + Up/Dn Current Time - / +", xPos, yPos += lineWidth, hudDistance); // // p.p.textSize(mediumTextSize); // p.p.text(" Time Navigation", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" t Teleport to Earliest Time in Field", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" T Move to Earliest Time in Field", xPos, yPos += lineWidth, hudDistance); // p.p.text(" d Teleport to Earliest Time on Earliest Date", xPos, yPos += lineWidth, hudDistance); // p.p.text(" D Move to Earliest Time on Earliest Date", xPos, yPos += lineWidth, hudDistance); // p.p.text(" n Move to Next Time Segment in Field", xPos, yPos += lineWidthWide, hudDistance); // p.p.text(" N Move to Next Time Segment in Cluster", xPos, yPos += lineWidth, hudDistance); // p.p.text(" b Move to Previous Time Segment in Field", xPos, yPos += lineWidth, hudDistance); // p.p.text(" B Move to Previous Time Segment in Cluster", xPos, yPos += lineWidth, hudDistance); // p.p.text(" l Move to Next Date in Field", xPos, yPos += lineWidth, hudDistance); // p.p.text(" L Move to Next Date in Cluster", xPos, yPos += lineWidth, hudDistance); // p.p.text(" k Move to Previous Date in Field", xPos, yPos += lineWidth, hudDistance); // p.p.text(" K Move to Previous Date in Cluster", xPos, yPos += lineWidth, hudDistance); // // xPos = centerTextXOffset; // yPos = topTextYOffset; // Starting vertical position // // /* Model */ // p.p.textSize(mediumTextSize); // p.p.text(" Model", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" [ ] Altitude Scaling Adjustment + / - ", xPos, yPos += lineWidthVeryWide, hudDistance); //// p.p.text(" , . Object Distance + / - ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" - = Object Distance - / + ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" OPTION + - Visible Angle - ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" OPTION + = Visible Angle + ", xPos, yPos += lineWidth, hudDistance); // // /* Graphics */ // p.p.textSize(mediumTextSize); // p.p.text(" Graphics", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" G Angle Fading On/Off", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" H Angle Thinning On/Off", xPos, yPos += lineWidth, hudDistance); // p.p.text(" P Transparency Mode On / Off ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" ( ) Blend Mode - / + ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" i h v Hide images / panoramas / videos ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" D Video Mode On/Off ", xPos, yPos += lineWidth, hudDistance); // // /* Movement */ // p.p.textSize(mediumTextSize); // p.p.text(" Movement", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" a d w s Walk Left / Right / Forward / Backward ", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" Arrows Turn Camera ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" q z Zoom In / Out + / - ", xPos, yPos += lineWidth, hudDistance); // // /* Navigation */ // p.p.textSize(mediumTextSize); // p.p.text(" Navigation", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" > Follow Timeline Only", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" . Follow Timeline by Date", xPos, yPos += lineWidth, hudDistance); // p.p.text(" OPTION + . Follow Dateline Only", xPos, yPos += lineWidth, hudDistance); // p.p.text(" E Move to Nearest Cluster", xPos, yPos += lineWidthWide, hudDistance); // p.p.text(" W Move to Nearest Cluster in Front", xPos, yPos += lineWidth, hudDistance); // p.p.text(" Q Move to Next Cluster in Time", xPos, yPos += lineWidth, hudDistance); // p.p.text(" A Move to Next Location in Memory", xPos, yPos += lineWidth, hudDistance); // p.p.text(" Z Move to Random Cluster", xPos, yPos += lineWidth, hudDistance); // p.p.text(" U Move to Next Video ", xPos, yPos += lineWidthWide, hudDistance); // p.p.text(" u Teleport to Next Video ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" M Move to Next Panorama ", xPos, yPos += lineWidth, hudDistance); // p.p.text(" m Teleport to Next Panorama ", xPos, yPos += lineWidth, hudDistance); //// p.p.text(" C Lock Viewer to Nearest Cluster On/Off", xPos, yPos += lineWidthWide, hudDistance); //// p.p.text(" l Look At Selected Media", xPos, yPos += lineWidth, hudDistance); //// p.p.text(" L Look for Media", xPos, yPos += lineWidth, hudDistance); // p.p.text(" { } Teleport to Next / Previous Field ", xPos, yPos += lineWidth, hudDistance); // // xPos = midRightTextXOffset; // yPos = topTextYOffset; // Starting vertical position // // p.p.textSize(mediumTextSize); // p.p.text(" Interaction", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" O Selection Mode On/Off", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" S Multi-Selection Mode On/Off", xPos, yPos += lineWidth, hudDistance); // p.p.text(" OPTION + s Segment Selection Mode On/Off", xPos, yPos += lineWidthWide, hudDistance); // p.p.text(" x Select Media in Front", xPos, yPos += lineWidth, hudDistance); // p.p.text(" X Deselect Media in Front", xPos, yPos += lineWidth, hudDistance); // p.p.text(" OPTION + x Deselect All Media", xPos, yPos += lineWidth, hudDistance); // // p.p.textSize(mediumTextSize); // p.p.text(" GPS Tracks", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" g Load GPS Track from File", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" OPTION + g Follow GPS Track", xPos, yPos += lineWidth, hudDistance); // // p.p.textSize(mediumTextSize); // p.p.text(" Memory", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" ` Save Current View to Memory", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" ~ Follow Memory Path", xPos, yPos += lineWidth, hudDistance); // p.p.text(" Y Clear Memory", xPos, yPos += lineWidth, hudDistance); // // p.p.textSize(mediumTextSize); // p.p.text(" Output", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" o Set Image Output Folder", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" p Save Screen Image to Disk", xPos, yPos += lineWidth, hudDistance); // // p.p.popMatrix(); // } /** * Increment blendMode by given amount and call setBlendMode() * @param inc Increment to blendMode number */ // public void changeBlendMode(WMV_World p, int inc) // { // if(inc > 0) // { // if (blendMode+inc < numBlendModes) // blendMode += inc; // else // blendMode = 0; // } // else if(inc < 0) // { // { // if (blendMode-inc >= 0) // blendMode -= inc; // else // blendMode = numBlendModes - 1; // } // } // // if(inc != 0) // setBlendMode(p, blendMode); // } // /** // * Change effect of image alpha channel on blending // * @param blendMode // */ // public void setBlendMode(WMV_World p, int blendMode) { // switch (blendMode) { // case 0: // ml.blendMode(PApplet.BLEND); // break; // // case 1: // ml.blendMode(PApplet.ADD); // break; // // case 2: // ml.blendMode(PApplet.SUBTRACT); // break; // // case 3: // ml.blendMode(PApplet.DARKEST); // break; // // case 4: // ml.blendMode(PApplet.LIGHTEST); // break; // // case 5: // ml.blendMode(PApplet.DIFFERENCE); // break; // // case 6: // ml.blendMode(PApplet.EXCLUSION); // break; // // case 7: // ml.blendMode(PApplet.MULTIPLY); // break; // // case 8: // ml.blendMode(PApplet.SCREEN); // break; // // case 9: // ml.blendMode(PApplet.REPLACE); // break; // // case 10: // // blend(HARD_LIGHT); // break; // // case 11: // // blend(SOFT_LIGHT); // break; // // case 12: // // blend(OVERLAY); // break; // // case 13: // // blend(DODGE); // break; // // case 14: // // blend(BURN); // break; // } // // if (ml.debugSettings.world) // System.out.println("blendMode:" + blendMode); // } /** * Show statistics of the current simulation */ // void displayStatisticsView(WMV_World p) // { // startHUD(); // p.p.pushMatrix(); // // float xPos = centerTextXOffset; // float yPos = topTextYOffset; // Starting vertical position // // WMV_Field f = p.getCurrentField(); // // if(p.viewer.getState().getCurrentClusterID() >= 0) // { // WMV_Cluster c = p.getCurrentCluster(); //// float[] camTar = p.viewer.camera.target(); // // // p.p.text(" Clusters:"+(f.getClusters().size()-f.getModel().getState().mergedClusters), xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" Merged: "+f.getModel().getState().mergedClusters+" out of "+f.getClusters().size()+" Total", xPos, yPos += lineWidth, hudDistance); // p.p.text(" Minimum Distance: "+p.settings.minClusterDistance, xPos, yPos += lineWidth, hudDistance); // p.p.text(" Maximum Distance: "+p.settings.maxClusterDistance, xPos, yPos += lineWidth, hudDistance); // if(p.settings.altitudeScaling) // p.p.text(" Altitude Scaling Factor: "+p.settings.altitudeScalingFactor+" (Altitude Scaling)", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" Clustering Method : "+ ( p.getState().hierarchical ? "Hierarchical" : "K-Means" ), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Population Factor: "+f.getModel().getState().clusterPopulationFactor, xPos, yPos += lineWidth, hudDistance); // if(p.getState().hierarchical) p.p.text(" Current Cluster Depth: "+f.getState().clusterDepth, xPos, yPos += lineWidth, hudDistance); // // p.p.textSize(mediumTextSize); // p.p.text(" Viewer ", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" Location, x: "+PApplet.round(p.viewer.getLocation().x)+" y:"+PApplet.round(p.viewer.getLocation().y)+" z:"+ // PApplet.round(p.viewer.getLocation().z), xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" GPS Longitude: "+p.viewer.getGPSLocation().x+" Latitude:"+p.viewer.getGPSLocation().y, xPos, yPos += lineWidth, hudDistance); // // p.p.text(" Current Cluster: "+p.viewer.getState().getCurrentClusterID(), xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.text(" Media Points: "+c.getState().mediaCount, xPos, yPos += lineWidth, hudDistance); // p.p.text(" Media Segments: "+p.getCurrentCluster().segments.size(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Distance: "+PApplet.round(PVector.dist(c.getLocation(), p.viewer.getLocation())), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Stitched Panoramas: "+p.getCurrentCluster().stitched.size(), xPos, yPos += lineWidth, hudDistance); // if(p.viewer.getAttractorClusterID() != -1) // { // p.p.text(" Destination Cluster : "+p.viewer.getAttractorCluster(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Destination Media Points: "+p.getCurrentField().getCluster(p.viewer.getAttractorClusterID()).getState().mediaCount, xPos, yPos += lineWidth, hudDistance); // p.p.text(" Destination Distance: "+PApplet.round( PVector.dist(f.getClusters().get(p.viewer.getAttractorClusterID()).getLocation(), p.viewer.getLocation() )), xPos, yPos += lineWidth, hudDistance); // } // // if(p.p.debugSettings.viewer) // { // p.p.text(" Debug: Current Attraction: "+p.viewer.getAttraction().mag(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Debug: Current Acceleration: "+p.viewer.getAcceleration().mag(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Debug: Current Velocity: "+ p.viewer.getVelocity().mag() , xPos, yPos += lineWidth, hudDistance); // p.p.text(" Debug: Moving? " + p.viewer.getState().isMoving(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Debug: Slowing? " + p.viewer.isSlowing(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Debug: Halting? " + p.viewer.isHalting(), xPos, yPos += lineWidth, hudDistance); // } // // if(p.p.debugSettings.viewer) // { // p.p.text(" Debug: X Orientation (Yaw):" + p.viewer.getXOrientation(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Debug: Y Orientation (Pitch):" + p.viewer.getYOrientation(), xPos, yPos += lineWidth, hudDistance); //// p.p.text(" Debug: Target Point x:" + camTar[0] + ", y:" + camTar[1] + ", z:" + camTar[2], xPos, yPos += lineWidth, hudDistance); // } // else // { // p.p.text(" Compass Direction:" + utilities.angleToCompass(p.viewer.getXOrientation())+" Angle: "+p.viewer.getXOrientation(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Vertical Direction:" + PApplet.degrees(p.viewer.getYOrientation()), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Zoom:"+p.viewer.getFieldOfView(), xPos, yPos += lineWidth, hudDistance); // } // p.p.text(" Field of View:"+p.viewer.getFieldOfView(), xPos, yPos += lineWidth, hudDistance); // // xPos = midRightTextXOffset; // yPos = topTextYOffset; // Starting vertical position // // p.p.textSize(mediumTextSize); // p.p.text(" Time ", xPos, yPos += lineWidthVeryWide, hudDistance); // p.p.textSize(smallTextSize); // p.p.text(" Time Mode: "+ ((p.p.world.getState().getTimeMode() == 0) ? "Cluster" : "Field"), xPos, yPos += lineWidthVeryWide, hudDistance); // // if(p.p.world.getState().getTimeMode() == 0) // p.p.text(" Current Field Time: "+ p.getState().currentTime, xPos, yPos += lineWidth, hudDistance); // if(p.p.world.getState().getTimeMode() == 1) // p.p.text(" Current Cluster Time: "+ p.getCurrentCluster().getState().currentTime, xPos, yPos += lineWidth, hudDistance); // p.p.text(" Current Field Timeline Segments: "+ p.getCurrentField().getTimeline().timeline.size(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Current Field Time Segment: "+ p.viewer.getCurrentFieldTimeSegment(), xPos, yPos += lineWidth, hudDistance); // if(f.getTimeline().timeline.size() > 0 && p.viewer.getCurrentFieldTimeSegment() >= 0 && p.viewer.getCurrentFieldTimeSegment() < f.getTimeline().timeline.size()) // p.p.text(" Upper: "+f.getTimeSegment(p.viewer.getCurrentFieldTimeSegment()).getUpper().getTime() // +" Center:"+f.getTimeSegment(p.viewer.getCurrentFieldTimeSegment()).getCenter().getTime()+ // " Lower: "+f.getTimeSegment(p.viewer.getCurrentFieldTimeSegment()).getLower().getTime(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Current Cluster Timeline Segments: "+ p.getCurrentCluster().getTimeline().timeline.size(), xPos, yPos += lineWidth, hudDistance); // p.p.text(" Field Dateline Segments: "+ p.getCurrentField().getDateline().size(), xPos, yPos += lineWidth, hudDistance); // p.p.textSize(mediumTextSize); // // if(p.p.debugSettings.memory) // { // if(p.p.debugSettings.detailed) // { // p.p.text("Total memory (bytes): " + p.p.debugSettings.totalMemory, xPos, yPos += lineWidth, hudDistance); // p.p.text("Available processors (cores): "+p.p.debugSettings.availableProcessors, xPos, yPos += lineWidth, hudDistance); // p.p.text("Maximum memory (bytes): " + (p.p.debugSettings.maxMemory == Long.MAX_VALUE ? "no limit" : p.p.debugSettings.maxMemory), xPos, yPos += lineWidth, hudDistance); // p.p.text("Total memory (bytes): " + p.p.debugSettings.totalMemory, xPos, yPos += lineWidth, hudDistance); // p.p.text("Allocated memory (bytes): " + p.p.debugSettings.allocatedMemory, xPos, yPos += lineWidth, hudDistance); // } // p.p.text("Free memory (bytes): "+p.p.debugSettings.freeMemory, xPos, yPos += lineWidth, hudDistance); // p.p.text("Approx. usable free memory (bytes): " + p.p.debugSettings.approxUsableFreeMemory, xPos, yPos += lineWidth, hudDistance); // } // } // // p.p.popMatrix(); // } // void setFullScreen(boolean newState) // { // if(newState && !fullscreen) // Switch to Fullscreen // { //// if(!p.viewer.selection) window.viewsSidebar.setVisible(false); //// else window.selectionSidebar.setVisible(false); // } // if(!newState && fullscreen) // Switch to Window Size // { //// if(!p.viewer.selection) window.mainSidebar.setVisible(true); //// else window.selectionSidebar.setVisible(true); // } // // fullscreen = newState; // } }
144,185
0.660841
0.646996
4,597
30.363064
32.071613
239
false
false
0
0
0
0
0
0
3.755275
false
false
11
4c24526b33ff1877a439a76b207ee529d01ba7cf
28,037,546,524,047
72ab4f80ee60962b647b5ec0d7c7aec7f66f2824
/动态规划/337_medium_house-robber-iii.java
4f535b41804894f79bb6edbf5c280cc32d7689e7
[]
no_license
yangjiabeiyu/Arithmetic_Leetcode
https://github.com/yangjiabeiyu/Arithmetic_Leetcode
aa7ca0052ec35954b5c3e9f9a64b6085df7ef866
74d0af104a893fe452f99163d5f7be94a3d88e49
refs/heads/master
2023-06-10T23:30:42.197000
2021-07-03T09:29:59
2021-07-03T09:29:59
299,489,595
0
0
null
false
2020-09-29T03:19:23
2020-09-29T02:59:51
2020-09-29T03:14:38
2020-09-29T03:19:22
0
0
0
0
null
false
false
/* 打家劫舍III https://leetcode-cn.com/problems/house-robber-iii/ 题目描述 在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。 示例 示例 1: 输入: [3,2,3,null,3,null,1] 3 / \ 2 3 \ \ 3 1 输出: 7 解释: 小偷一晚能够盗取的最高金额 = 3 + 3 + 1 = 7. */ /* 解法一:使用递归遍历每个节点,同时记录下以每个节点为入口时,能够盗取的最大金额。对于每个节点,只有两种情况: 1、盗取该节点,总钱数为该节点+左右子节点的子节点; 2、不盗取该节点,总钱数为左右子节点的加和。 执行用时:899 ms, 在所有 Java 提交中击败了15.70% 的用户 内存消耗:38.5 MB, 在所有 Java 提交中击败了76.70% 的用户 */ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int rob(TreeNode root) { if(root == null) return 0; int v1 = root.val, v2 = 0; if(root.left != null) v1 += rob(root.left.right) + rob(root.left.left); if(root.right != null) v1 += rob(root.right.right) + rob(root.right.left); v2 = rob(root.left) + rob(root.right); return Math.max(v1, v2); } } /* 解法二:可以考虑每个节点处返回两个值,一个值为盗取该节点时获取的最大金额数val1;另一个值为不盗取时获取的最大金额数val2。 因此对于每个节点,只有两种情况: 1、当前val+左子节点的val2+右子节点的val2; 2、左右字节点的{val1和val2中的较大值}的加和(左右子节点可盗取可不盗取) 执行用时:1 ms, 在所有 Java 提交中击败了75.18% 的用户 内存消耗:38.7 MB, 在所有 Java 提交中击败了38.60% 的用户 */ class Solution { public int rob(TreeNode root) { int[] v = nodeVal(root); return Math.max(v[0], v[1]); } public static int[] nodeVal(TreeNode root) { if(root == null) return new int[] {0, 0}; int[] v1 = nodeVal(root.left); int[] v2 = nodeVal(root.right); int contains = root.val + v1[1] + v2[1]; int notContains = Math.max(v1[0], v1[1]) + Math.max(v2[0], v2[1]); return new int[] {contains, notContains}; } }
UTF-8
Java
2,871
java
337_medium_house-robber-iii.java
Java
[]
null
[]
/* 打家劫舍III https://leetcode-cn.com/problems/house-robber-iii/ 题目描述 在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。 示例 示例 1: 输入: [3,2,3,null,3,null,1] 3 / \ 2 3 \ \ 3 1 输出: 7 解释: 小偷一晚能够盗取的最高金额 = 3 + 3 + 1 = 7. */ /* 解法一:使用递归遍历每个节点,同时记录下以每个节点为入口时,能够盗取的最大金额。对于每个节点,只有两种情况: 1、盗取该节点,总钱数为该节点+左右子节点的子节点; 2、不盗取该节点,总钱数为左右子节点的加和。 执行用时:899 ms, 在所有 Java 提交中击败了15.70% 的用户 内存消耗:38.5 MB, 在所有 Java 提交中击败了76.70% 的用户 */ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int rob(TreeNode root) { if(root == null) return 0; int v1 = root.val, v2 = 0; if(root.left != null) v1 += rob(root.left.right) + rob(root.left.left); if(root.right != null) v1 += rob(root.right.right) + rob(root.right.left); v2 = rob(root.left) + rob(root.right); return Math.max(v1, v2); } } /* 解法二:可以考虑每个节点处返回两个值,一个值为盗取该节点时获取的最大金额数val1;另一个值为不盗取时获取的最大金额数val2。 因此对于每个节点,只有两种情况: 1、当前val+左子节点的val2+右子节点的val2; 2、左右字节点的{val1和val2中的较大值}的加和(左右子节点可盗取可不盗取) 执行用时:1 ms, 在所有 Java 提交中击败了75.18% 的用户 内存消耗:38.7 MB, 在所有 Java 提交中击败了38.60% 的用户 */ class Solution { public int rob(TreeNode root) { int[] v = nodeVal(root); return Math.max(v[0], v[1]); } public static int[] nodeVal(TreeNode root) { if(root == null) return new int[] {0, 0}; int[] v1 = nodeVal(root.left); int[] v2 = nodeVal(root.right); int contains = root.val + v1[1] + v2[1]; int notContains = Math.max(v1[0], v1[1]) + Math.max(v2[0], v2[1]); return new int[] {contains, notContains}; } }
2,871
0.612374
0.570598
74
24.554054
19.954098
74
false
false
0
0
0
0
0
0
0.472973
false
false
11
202faa8e39646776309939d2f001115f755b3a5b
18,270,790,892,117
e3312201bf377c68774b171112be9c5f2396377c
/rabbitdemo/src/main/java/com/chariotsolutions/rabbitmq/aspects/LoggingAspect.java
2b980ae1f2943e55b9d8c270f286d258dab470ce
[]
no_license
liveeadmin/RabbitMQ-Demos
https://github.com/liveeadmin/RabbitMQ-Demos
0e3741f6b64a526b54bf697ecc1399fe740f2ad0
25710e1f410f3ef49d7e7ff69fca689f173906d2
refs/heads/master
2021-05-26T16:32:54.916000
2012-01-20T19:46:40
2012-01-20T19:46:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.chariotsolutions.rabbitmq.aspects; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Aspect public class LoggingAspect { private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class); // @Around(value = "execution(* com.chariotsolutions.rabbitmq.service.MezzageService+.*(..))") //good @Around(value = "execution(* com.chariotsolutions.rabbitmq..*.*(..))") //good public Object cache(ProceedingJoinPoint point) throws Throwable { Object value = null; String methodName = point.getSignature().getName(); logger.debug("**** Invoking Method '{}'", methodName); value = point.proceed(); if (value != null) { logger.debug("**** Method '{}' returning Object '{}' containing '{}'", value.getClass().getName(), value.toString()); } return value; } }
UTF-8
Java
1,004
java
LoggingAspect.java
Java
[]
null
[]
package com.chariotsolutions.rabbitmq.aspects; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Aspect public class LoggingAspect { private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class); // @Around(value = "execution(* com.chariotsolutions.rabbitmq.service.MezzageService+.*(..))") //good @Around(value = "execution(* com.chariotsolutions.rabbitmq..*.*(..))") //good public Object cache(ProceedingJoinPoint point) throws Throwable { Object value = null; String methodName = point.getSignature().getName(); logger.debug("**** Invoking Method '{}'", methodName); value = point.proceed(); if (value != null) { logger.debug("**** Method '{}' returning Object '{}' containing '{}'", value.getClass().getName(), value.toString()); } return value; } }
1,004
0.679283
0.677291
26
37.615383
33.856117
129
false
false
0
0
0
0
0
0
0.615385
false
false
11
ec91203087c08ab7453e2e279fb397bc72d7737c
6,012,954,215,674
c4d58715847a6c70b794df54a4b440db3510b6da
/yh_skill/src/main/java/qcbl/skill/base/protected_study/X/A.java
4df69030fe9c6b9dfca055a61ff073355aceb28e
[]
no_license
hejianhua/skill
https://github.com/hejianhua/skill
1827fda6c3a2c76734a300726bb495e371eb69e8
1afd5be799f7647f032a7d741622d80320386cd9
refs/heads/master
2018-12-25T05:15:43.836000
2018-12-19T12:08:16
2018-12-19T12:08:16
153,572,408
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package qcbl.skill.base.protected_study.X; /** * 总结一下修饰符。 * * public 修饰的属性和方法,在哪都能被访问。无论是new出来的对象去 . 访问, 还是继承的形式去 . 访问,都能成功 * * * protected 修饰符 ,在同一个包下和public一样。无论是new出来的对象去 . 访问, 还是继承的形式去 . 访问,都能成功 * * 注意的是,如果不在同一个包下。 new出来的对象去 . 访问是不行的。 但是继承的形式去 . 可以访问. * * * * 默认的修饰符, 如果在同一个包下,那么和public一样。去了别人的包,那就和private一样 * * * private 修饰的属性,甭管你在哪,无论是new出来的对象去 . 不能访问, 还是继承的形式去 . 不能访问 * * * */ public class A { protected int a=3; int b=6; protected void showInfo(){ System.out.println("AAAA"); } class B2 { void visit(){ System.out.println(a); showInfo(); } } }
UTF-8
Java
1,079
java
A.java
Java
[]
null
[]
package qcbl.skill.base.protected_study.X; /** * 总结一下修饰符。 * * public 修饰的属性和方法,在哪都能被访问。无论是new出来的对象去 . 访问, 还是继承的形式去 . 访问,都能成功 * * * protected 修饰符 ,在同一个包下和public一样。无论是new出来的对象去 . 访问, 还是继承的形式去 . 访问,都能成功 * * 注意的是,如果不在同一个包下。 new出来的对象去 . 访问是不行的。 但是继承的形式去 . 可以访问. * * * * 默认的修饰符, 如果在同一个包下,那么和public一样。去了别人的包,那就和private一样 * * * private 修饰的属性,甭管你在哪,无论是new出来的对象去 . 不能访问, 还是继承的形式去 . 不能访问 * * * */ public class A { protected int a=3; int b=6; protected void showInfo(){ System.out.println("AAAA"); } class B2 { void visit(){ System.out.println(a); showInfo(); } } }
1,079
0.576751
0.57228
42
14.976191
21.219362
72
false
false
0
0
0
0
0
0
0.166667
false
false
11
cd4e5f0338ed6756126ee316c159640290760bab
23,802,708,777,050
0badd9c1cc67af6b4c9652b21050bbb535dfb13d
/src/main/java/com/partyrgame/userservice/model/Relationship.java
f13eda7fba0c0dee8fb4a9c0b805b6609c2d2cd9
[ "MIT" ]
permissive
matthewlong29/partyr-service
https://github.com/matthewlong29/partyr-service
c6d8fa0ae9195b8ce4f439da370e87283a65bd6f
2e5d49d14046ed2ccbd7bae5652b4abf796b5911
refs/heads/master
2021-08-22T17:44:47.286000
2019-12-03T06:04:04
2019-12-03T06:04:04
204,222,895
1
0
MIT
false
2021-07-23T10:40:31
2019-08-24T23:16:42
2019-12-04T02:12:25
2021-07-23T10:40:28
383
1
0
10
Java
false
false
package com.partyrgame.userservice.model; import lombok.Data; @Data public class Relationship { private String relatingUsername; private String relatedUsername; private RelationshipStatus relationshipStatus; }
UTF-8
Java
218
java
Relationship.java
Java
[]
null
[]
package com.partyrgame.userservice.model; import lombok.Data; @Data public class Relationship { private String relatingUsername; private String relatedUsername; private RelationshipStatus relationshipStatus; }
218
0.821101
0.821101
10
20.799999
17.376997
48
false
false
0
0
0
0
0
0
0.5
false
false
11
18a5344b8bee67de2f34963c6d15e8ddb6687807
27,676,769,274,742
231354b9df7d09f13c935cccb2ff7b41137ca4ea
/app/src/main/java/com/example/multi_theme_ui/AppPermission.java
8d4739530ba1af67f20362d8a09f9d41a5911dcb
[]
no_license
saini2sandeep/MultiThemeUiSample
https://github.com/saini2sandeep/MultiThemeUiSample
c46e96c2db0a5ec32fc57018a3d17b5f948cebfc
c962ac92dfaacae276bca9c29f341af90495d0d1
refs/heads/master
2020-06-15T17:15:41.886000
2019-07-05T06:24:58
2019-07-05T06:24:58
195,351,056
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.multi_theme_ui; import android.Manifest; import android.app.Activity; import android.content.Context; import pub.devrel.easypermissions.EasyPermissions; /** * Created by sandeepsaini on 03,July,2019 */ public class AppPermission { private Activity activity; public AppPermission(Activity activity) { this.activity = activity; } public boolean hasCameraPermission(Context context) { return EasyPermissions.hasPermissions(context, Manifest.permission.CAMERA); } public boolean hasSmsPermission(Context context) { return EasyPermissions.hasPermissions(context, Manifest.permission.READ_SMS); } public boolean hasStoragePermission(Context context) { return EasyPermissions.hasPermissions(context, Manifest.permission.WRITE_EXTERNAL_STORAGE); } public boolean hasReadPermission(Context context){ return EasyPermissions.hasPermissions(context,Manifest.permission.READ_EXTERNAL_STORAGE); } public boolean hasLocationPermission(Context context) { return EasyPermissions.hasPermissions(context, Manifest.permission.ACCESS_FINE_LOCATION); } }
UTF-8
Java
1,166
java
AppPermission.java
Java
[ { "context": "asypermissions.EasyPermissions;\n\n/**\n * Created by sandeepsaini on 03,July,2019\n */\npublic class AppPermission {\n", "end": 206, "score": 0.9992653727531433, "start": 194, "tag": "USERNAME", "value": "sandeepsaini" } ]
null
[]
package com.example.multi_theme_ui; import android.Manifest; import android.app.Activity; import android.content.Context; import pub.devrel.easypermissions.EasyPermissions; /** * Created by sandeepsaini on 03,July,2019 */ public class AppPermission { private Activity activity; public AppPermission(Activity activity) { this.activity = activity; } public boolean hasCameraPermission(Context context) { return EasyPermissions.hasPermissions(context, Manifest.permission.CAMERA); } public boolean hasSmsPermission(Context context) { return EasyPermissions.hasPermissions(context, Manifest.permission.READ_SMS); } public boolean hasStoragePermission(Context context) { return EasyPermissions.hasPermissions(context, Manifest.permission.WRITE_EXTERNAL_STORAGE); } public boolean hasReadPermission(Context context){ return EasyPermissions.hasPermissions(context,Manifest.permission.READ_EXTERNAL_STORAGE); } public boolean hasLocationPermission(Context context) { return EasyPermissions.hasPermissions(context, Manifest.permission.ACCESS_FINE_LOCATION); } }
1,166
0.753859
0.748714
40
28.15
31.519478
99
false
false
0
0
0
0
0
0
0.475
false
false
11
7d94298be9a87a6fa57775cbdbafad311730e4fc
7,945,689,523,472
4696ddaab23551f4332270b418702051ba2040ae
/Spring/ProSpring-4/prospring4/src/main/java/com/apress/prospring4/ch5/ErrorBean.java
5a0e8bfedf0eaa1bf0e07445e012803d2fb83da8
[]
no_license
koylubaevnt/study
https://github.com/koylubaevnt/study
870c844a3a54dadeed93ae5a4950bb70fdef5506
3a5474186c596a68883c59082a675d73fde5b397
refs/heads/master
2020-03-21T07:03:16.784000
2018-06-25T10:06:44
2018-06-25T10:06:44
138,257,738
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.apress.prospring4.ch5; public class ErrorBean { public void errorPhoneMethod() throws Exception { throw new Exception("Foo"); } public void otherErrorPhoneMethod() throws IllegalArgumentException { throw new IllegalArgumentException("Bar"); } }
UTF-8
Java
274
java
ErrorBean.java
Java
[]
null
[]
package com.apress.prospring4.ch5; public class ErrorBean { public void errorPhoneMethod() throws Exception { throw new Exception("Foo"); } public void otherErrorPhoneMethod() throws IllegalArgumentException { throw new IllegalArgumentException("Bar"); } }
274
0.751825
0.744526
14
18.571428
22.509409
70
false
false
0
0
0
0
0
0
1.071429
false
false
11
b0a271abb5dafc72cd63c509c51b493d7af1fe17
32,521,492,384,512
c4ab995759babec6e8d518165174833105e5b2d5
/app/src/main/java/youkagames/com/yokaasset/db/dao/UserEntityDao.java
62970b9b71dac640bcb03e198ba48a0e7f080350
[]
no_license
soondh/asset
https://github.com/soondh/asset
a78a21e75298e16e25887e8f4fe04995b683c9e7
2b3e399a073f2f3e75b37a2c4979a053fd1d78d9
refs/heads/master
2020-04-14T15:56:56.078000
2019-01-03T08:24:26
2019-01-03T08:24:26
163,940,586
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package youkagames.com.yokaasset.db.dao; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Delete; import android.arch.persistence.room.Insert; import android.arch.persistence.room.OnConflictStrategy; import android.arch.persistence.room.Query; import android.arch.persistence.room.Update; import youkagames.com.yokaasset.db.entity.UserEntity; import java.util.List; /** * Created by song dehua on 2018/3/20. * */ @Dao public interface UserEntityDao { @Query("select * FROM User") List<UserEntity> getUserList(); @Query("select * FROM User WHERE name = :name") UserEntity getUserByName(String name); @Insert(onConflict = OnConflictStrategy.REPLACE) void addUser(UserEntity userEntity); @Delete() void deleteUser(UserEntity userEntity); @Update void update(UserEntity entity); }
UTF-8
Java
858
java
UserEntityDao.java
Java
[ { "context": "Entity;\n\nimport java.util.List;\n\n/**\n * Created by song dehua on 2018/3/20.\n *\n */\n@Dao\npublic interface UserEn", "end": 428, "score": 0.9989204406738281, "start": 418, "tag": "NAME", "value": "song dehua" } ]
null
[]
package youkagames.com.yokaasset.db.dao; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Delete; import android.arch.persistence.room.Insert; import android.arch.persistence.room.OnConflictStrategy; import android.arch.persistence.room.Query; import android.arch.persistence.room.Update; import youkagames.com.yokaasset.db.entity.UserEntity; import java.util.List; /** * Created by <NAME> on 2018/3/20. * */ @Dao public interface UserEntityDao { @Query("select * FROM User") List<UserEntity> getUserList(); @Query("select * FROM User WHERE name = :name") UserEntity getUserByName(String name); @Insert(onConflict = OnConflictStrategy.REPLACE) void addUser(UserEntity userEntity); @Delete() void deleteUser(UserEntity userEntity); @Update void update(UserEntity entity); }
854
0.751748
0.74359
35
23.542856
20.533377
56
false
false
0
0
0
0
0
0
0.4
false
false
11
14a28e2a8c5f85a0c220e3edd24fb8351adf4a66
32,521,492,381,580
e7396dd3538bc2113ab4599db41078871e83aeb8
/Fitple/src/Servlet/GroupAddTestServlet.java
709fa80c990567ce5a144da168ebbadeac3bfbff
[]
no_license
yeeeahj/FitpleServer
https://github.com/yeeeahj/FitpleServer
44767489a1bd01682712120c7e51579876cbc462
1f974f86dc9e5723b177e47c1809b3341e4fe08f
refs/heads/master
2021-01-19T21:59:38.377000
2017-04-20T06:43:27
2017-04-20T06:43:27
88,736,111
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Servlet; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.oreilly.servlet.MultipartRequest; import com.oreilly.servlet.multipart.DefaultFileRenamePolicy; import com.oreilly.servlet.*; @SuppressWarnings("serial") // ����� 5/ ���н� 6 public class GroupAddTestServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("euc-kr"); ServletContext sc = this.getServletContext(); Statement stmt = null; ResultSet rs = null; PreparedStatement prepare = null; String CookieId=null; try { // YJ:DB���� Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection(sc.getInitParameter("url"), sc.getInitParameter("username"), sc.getInitParameter("password")); sc.setAttribute("conn", conn); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); //get Cookie Cookie[] cookies = request.getCookies(); System.out.println(request.getCookies()); System.out.println("도"); int group_result; int groupmember_result; String saveFolder = sc.getRealPath("image"); //String saveFolder = "/Users/oosl1/Documents/apache-tomcat-7.0.62/webapps/manager/images"; String imageURL= "http://203.252.219.238:8080/Fitple/image"; //실제 저장경로 /Users/oosl1/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Fitple/image int sizeLimit=1024*1024*5; MultipartRequest multi = new MultipartRequest(request, saveFolder,sizeLimit, "UTF-8",new DefaultFileRenamePolicy()); String fileName=multi.getFilesystemName("photo"); imageURL=imageURL+"/"+fileName; System.out.println("imageurl"+imageURL+multi.getParameter("groupname")); String qqqqq = new String(multi.getParameter("group_info").getBytes("UTF-8"),"euc-kr"); System.out.println(qqqqq); if(fileName == null) { // 파일이 업로드 되지 않았을때 System.out.print("파일 업로드 되지 않았음"); } else { // 파일이 업로드 되었을때 fileName=new String(fileName.getBytes("8859_1"),"euc-kr"); // 한글인코딩 - 브라우져에 출력 } // YJ:add group prepare = conn.prepareStatement( "INSERT INTO Fitple.GROUP(groupname,group_info,host,group_image,public_seq,permission_seq)" + "values(?,?,?,?,?,?)"); prepare.setString(1, multi.getParameter("groupname")); prepare.setString(2, multi.getParameter("group_info")); prepare.setString(3, multi.getParameter("member_seq")); prepare.setString(4, imageURL); prepare.setString(5, multi.getParameter("public_seq")); prepare.setString(6, multi.getParameter("permission_seq")); group_result = prepare.executeUpdate(); Map<String, String> map = new HashMap(); List<Map<String, String>> list = new ArrayList(); Map<String, String> list_map = new HashMap(); Map<String, Object> j_map = new HashMap(); //select group_seq prepare = conn.prepareStatement( "SELECT GROUP_SEQ FROM Fitple.Group WHERE groupname=?"); String group_seq=""; prepare.setString(1, multi.getParameter("groupname")); rs=prepare.executeQuery(); while(rs.next()){ group_seq=rs.getString("group_seq"); } //add groupmember prepare = conn.prepareStatement( "INSERT INTO Fitple.GROUPMEMBER(group_seq,member_seq)" + "values(?,?)"); prepare.setString(1, group_seq); prepare.setString(2, multi.getParameter("member_seq")); groupmember_result = prepare.executeUpdate(); if (group_result == 0 || groupmember_result==0) { j_map.put("responseCode", 6); } else { j_map.put("responseCode", 5); list_map.put("groupname", multi.getParameter("groupname")); list_map.put("group_info", multi.getParameter("group_info")); list_map.put("host", multi.getParameter("member_seq")); list_map.put("group_image", imageURL); list_map.put("public_seq", multi.getParameter("public_seq")); list_map.put("permission_seq", multi.getParameter("permission_seq")); j_map.put("GroupData", list_map); } String json = new Gson().toJson(j_map); out.println(json); System.out.println(json); } catch (Exception e) { e.printStackTrace(); PrintWriter out = response.getWriter(); Map<String,Object> map = new HashMap(); map.put("responseCode", 6); Gson gson = new GsonBuilder().serializeNulls().create(); String json = gson.toJson(map); //PrintWriter out = response.getWriter(); out.println(json); } finally { try { if (rs != null) rs.close(); } catch (Exception e) { } try { if (stmt != null) stmt.close(); } catch (Exception e) { } } } }
UTF-8
Java
5,691
java
GroupAddTestServlet.java
Java
[ { "context": "alPath(\"image\");\n\t\t\t//String saveFolder = \"/Users/oosl1/Documents/apache-tomcat-7.0.62/webapps/manager/im", "end": 2112, "score": 0.996992290019989, "start": 2107, "tag": "USERNAME", "value": "oosl1" }, { "context": "apps/manager/images\";\n\t\t\tString imageURL= \"http://203.252.219.238:8080/Fitple/image\";\n\t\t\t\n\t\t\t//실제 저장경로 /Users/oosl1", "end": 2212, "score": 0.9996650218963623, "start": 2197, "tag": "IP_ADDRESS", "value": "203.252.219.238" }, { "context": "9.238:8080/Fitple/image\";\n\t\t\t\n\t\t\t//실제 저장경로 /Users/oosl1/Documents/workspace/.metadata/.plugins/org.eclips", "end": 2262, "score": 0.9919946789741516, "start": 2257, "tag": "USERNAME", "value": "oosl1" } ]
null
[]
package Servlet; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.oreilly.servlet.MultipartRequest; import com.oreilly.servlet.multipart.DefaultFileRenamePolicy; import com.oreilly.servlet.*; @SuppressWarnings("serial") // ����� 5/ ���н� 6 public class GroupAddTestServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("euc-kr"); ServletContext sc = this.getServletContext(); Statement stmt = null; ResultSet rs = null; PreparedStatement prepare = null; String CookieId=null; try { // YJ:DB���� Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection(sc.getInitParameter("url"), sc.getInitParameter("username"), sc.getInitParameter("password")); sc.setAttribute("conn", conn); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); //get Cookie Cookie[] cookies = request.getCookies(); System.out.println(request.getCookies()); System.out.println("도"); int group_result; int groupmember_result; String saveFolder = sc.getRealPath("image"); //String saveFolder = "/Users/oosl1/Documents/apache-tomcat-7.0.62/webapps/manager/images"; String imageURL= "http://192.168.3.11:8080/Fitple/image"; //실제 저장경로 /Users/oosl1/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Fitple/image int sizeLimit=1024*1024*5; MultipartRequest multi = new MultipartRequest(request, saveFolder,sizeLimit, "UTF-8",new DefaultFileRenamePolicy()); String fileName=multi.getFilesystemName("photo"); imageURL=imageURL+"/"+fileName; System.out.println("imageurl"+imageURL+multi.getParameter("groupname")); String qqqqq = new String(multi.getParameter("group_info").getBytes("UTF-8"),"euc-kr"); System.out.println(qqqqq); if(fileName == null) { // 파일이 업로드 되지 않았을때 System.out.print("파일 업로드 되지 않았음"); } else { // 파일이 업로드 되었을때 fileName=new String(fileName.getBytes("8859_1"),"euc-kr"); // 한글인코딩 - 브라우져에 출력 } // YJ:add group prepare = conn.prepareStatement( "INSERT INTO Fitple.GROUP(groupname,group_info,host,group_image,public_seq,permission_seq)" + "values(?,?,?,?,?,?)"); prepare.setString(1, multi.getParameter("groupname")); prepare.setString(2, multi.getParameter("group_info")); prepare.setString(3, multi.getParameter("member_seq")); prepare.setString(4, imageURL); prepare.setString(5, multi.getParameter("public_seq")); prepare.setString(6, multi.getParameter("permission_seq")); group_result = prepare.executeUpdate(); Map<String, String> map = new HashMap(); List<Map<String, String>> list = new ArrayList(); Map<String, String> list_map = new HashMap(); Map<String, Object> j_map = new HashMap(); //select group_seq prepare = conn.prepareStatement( "SELECT GROUP_SEQ FROM Fitple.Group WHERE groupname=?"); String group_seq=""; prepare.setString(1, multi.getParameter("groupname")); rs=prepare.executeQuery(); while(rs.next()){ group_seq=rs.getString("group_seq"); } //add groupmember prepare = conn.prepareStatement( "INSERT INTO Fitple.GROUPMEMBER(group_seq,member_seq)" + "values(?,?)"); prepare.setString(1, group_seq); prepare.setString(2, multi.getParameter("member_seq")); groupmember_result = prepare.executeUpdate(); if (group_result == 0 || groupmember_result==0) { j_map.put("responseCode", 6); } else { j_map.put("responseCode", 5); list_map.put("groupname", multi.getParameter("groupname")); list_map.put("group_info", multi.getParameter("group_info")); list_map.put("host", multi.getParameter("member_seq")); list_map.put("group_image", imageURL); list_map.put("public_seq", multi.getParameter("public_seq")); list_map.put("permission_seq", multi.getParameter("permission_seq")); j_map.put("GroupData", list_map); } String json = new Gson().toJson(j_map); out.println(json); System.out.println(json); } catch (Exception e) { e.printStackTrace(); PrintWriter out = response.getWriter(); Map<String,Object> map = new HashMap(); map.put("responseCode", 6); Gson gson = new GsonBuilder().serializeNulls().create(); String json = gson.toJson(map); //PrintWriter out = response.getWriter(); out.println(json); } finally { try { if (rs != null) rs.close(); } catch (Exception e) { } try { if (stmt != null) stmt.close(); } catch (Exception e) { } } } }
5,688
0.695793
0.685725
186
28.903225
24.886221
121
false
false
0
0
0
0
0
0
2.811828
false
false
11
bc2db061a24a6014cd1790ccb99c6e8d8553b35d
33,165,737,491,836
6d0cb6aef1e09c3d2fc3cb8f733f7fbcaf110b21
/toolset/src/main/java/com/softteco/toolset/push/android/AbstractAndroidPushServiceBean.java
619dda5b715e01dde8cf20b3108c8c505169b920
[ "Apache-2.0" ]
permissive
SoftTeco/st-toolset
https://github.com/SoftTeco/st-toolset
408c49bb9173fbff9b872e51e134e02a3159be17
c5dc60877bb0fe2d49b4f2da1cf59c32dac1bf0a
refs/heads/master
2023-06-23T05:21:13.118000
2023-06-20T10:43:49
2023-06-20T10:43:49
20,715,456
1
0
Apache-2.0
false
2022-06-29T19:26:26
2014-06-11T06:53:05
2020-08-28T13:36:28
2022-06-29T19:26:25
1,050
2
3
16
Java
false
false
package com.softteco.toolset.push.android; import com.fasterxml.jackson.databind.ObjectMapper; import com.softteco.toolset.push.PushServiceProvider; import com.softteco.toolset.rs.AbstractRestDao; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.MessageFormat; import java.util.Collections; import java.util.List; /** * @author sergeizenevich */ public abstract class AbstractAndroidPushServiceBean extends AbstractRestDao implements PushServiceProvider { private final ObjectMapper objectMapper = new ObjectMapper(); protected abstract String getKey(); @Override protected final String getHost() { return "android.googleapis.com"; } @Override protected final String getProtocol() { return "https"; } private ResponseDto execute(final RequestDto requestDto) { PostMethod postMethod = null; String response = null; try { postMethod = new PostMethod("/gcm/send"); postMethod.addRequestHeader("Content-Type", "application/json"); postMethod.addRequestHeader("Accept", "application/json"); postMethod.addRequestHeader("Authorization", "key=" + getKey()); postMethod.setRequestEntity(new StringRequestEntity(objectMapper.writeValueAsString(requestDto), "application/json", "utf-8")); getClient().executeMethod(postMethod); response = postMethod.getResponseBodyAsString(); System.out.println(MessageFormat.format("REQUEST: {0}, //\n RESPONSE: {1}", objectMapper.writeValueAsString(requestDto), response)); return objectMapper.readValue(response, ResponseDto.class); } catch (UnsupportedEncodingException e) { System.out.println("RESPONSE: " + response); throw new RuntimeException(e); } catch (IOException e) { System.out.println("RESPONSE: " + response); throw new RuntimeException(e); } finally { if (postMethod != null) { postMethod.releaseConnection(); } } } @Override public final boolean sendMessage(final String to, final Object data) { return sendMessage(Collections.singletonList(to), data); } @Override public final boolean sendMessage(final List<String> to, final Object data) { final RequestDto requestDto = new RequestDto(); requestDto.registrationIds = to; requestDto.data = data; return execute(requestDto).success > 0; } }
UTF-8
Java
2,684
java
AbstractAndroidPushServiceBean.java
Java
[ { "context": "ollections;\nimport java.util.List;\n\n/**\n * @author sergeizenevich\n */\npublic abstract class AbstractAndroidPushServ", "end": 510, "score": 0.9981887936592102, "start": 496, "tag": "USERNAME", "value": "sergeizenevich" } ]
null
[]
package com.softteco.toolset.push.android; import com.fasterxml.jackson.databind.ObjectMapper; import com.softteco.toolset.push.PushServiceProvider; import com.softteco.toolset.rs.AbstractRestDao; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.MessageFormat; import java.util.Collections; import java.util.List; /** * @author sergeizenevich */ public abstract class AbstractAndroidPushServiceBean extends AbstractRestDao implements PushServiceProvider { private final ObjectMapper objectMapper = new ObjectMapper(); protected abstract String getKey(); @Override protected final String getHost() { return "android.googleapis.com"; } @Override protected final String getProtocol() { return "https"; } private ResponseDto execute(final RequestDto requestDto) { PostMethod postMethod = null; String response = null; try { postMethod = new PostMethod("/gcm/send"); postMethod.addRequestHeader("Content-Type", "application/json"); postMethod.addRequestHeader("Accept", "application/json"); postMethod.addRequestHeader("Authorization", "key=" + getKey()); postMethod.setRequestEntity(new StringRequestEntity(objectMapper.writeValueAsString(requestDto), "application/json", "utf-8")); getClient().executeMethod(postMethod); response = postMethod.getResponseBodyAsString(); System.out.println(MessageFormat.format("REQUEST: {0}, //\n RESPONSE: {1}", objectMapper.writeValueAsString(requestDto), response)); return objectMapper.readValue(response, ResponseDto.class); } catch (UnsupportedEncodingException e) { System.out.println("RESPONSE: " + response); throw new RuntimeException(e); } catch (IOException e) { System.out.println("RESPONSE: " + response); throw new RuntimeException(e); } finally { if (postMethod != null) { postMethod.releaseConnection(); } } } @Override public final boolean sendMessage(final String to, final Object data) { return sendMessage(Collections.singletonList(to), data); } @Override public final boolean sendMessage(final List<String> to, final Object data) { final RequestDto requestDto = new RequestDto(); requestDto.registrationIds = to; requestDto.data = data; return execute(requestDto).success > 0; } }
2,684
0.683308
0.681818
75
34.786667
31.303373
144
false
false
0
0
0
0
0
0
0.64
false
false
11
b4cef47f760a42eb9d167b89e44766cc0b0adfab
24,902,220,413,719
9d6ed7dfdf22e7beb7598c08710fbd89b7441158
/src/main/java/io/daocloud/shop/order/controller/OrderController.java
2caf99a93706b450971030d83cd32be390b04e27
[]
no_license
DaoCloud-Labs/daoshop-order
https://github.com/DaoCloud-Labs/daoshop-order
4a6cbff4a88cd2760eb12435184ab2bbb8f32d58
aa280929e7b09e8c75655b9978d2c1707818f5a8
refs/heads/master
2020-05-07T13:29:33.936000
2020-04-16T08:32:21
2020-04-16T08:32:21
180,551,706
2
8
null
false
2019-05-23T06:09:56
2019-04-10T09:47:01
2019-04-10T09:47:15
2019-05-23T06:06:13
58
0
1
0
Java
false
false
package io.daocloud.shop.order.controller; import io.daocloud.shop.order.entity.ItemEntity; import io.daocloud.shop.order.entity.OrderEntity; import io.daocloud.shop.order.repository.ItemRepository; import io.daocloud.shop.order.repository.OrderRepository; import io.daocloud.shop.order.vo.OrderVo; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.transaction.Transactional; import java.util.List; import java.util.stream.Collectors; /** * @Package io.daocloud.shop.order.controller * @Classname OrderController * @Description TODO * @Date 2019/3/17 下午10:45 * @Created by chenghao * @desc OrderController * @project order */ @RestController @RequestMapping() public class OrderController { private final OrderRepository orderRepository; private final ItemRepository itemRepository; public OrderController(OrderRepository orderRepository, ItemRepository itemRepository) { this.orderRepository = orderRepository; this.itemRepository = itemRepository; } @PostMapping("/orders") @ResponseStatus(HttpStatus.CREATED) @Transactional public void createOrder(@RequestBody List<OrderVo> orderVos, @RequestHeader("token")Long token){ Double amount = orderVos.stream().map(e -> e.getCount() * e.getPrice()) .reduce(Double::sum).orElse(0.0); OrderEntity orderEntity = OrderEntity.builder().userId(token).amount(amount).build(); List<ItemEntity> collect = orderVos.stream().map(e -> { ItemEntity itemEntity = ItemEntity.builder().count(e.getCount()) .price(e.getPrice()) .productId(e.getProductId()) .productName(e.getProductName()).build(); return itemEntity; }).collect(Collectors.toList()); orderEntity.setItems(collect); OrderEntity save = orderRepository.save(orderEntity); } @GetMapping("/user/{id}/orders") public Iterable<OrderEntity> getOrdersByUser(@RequestHeader("token")Long token){ return orderRepository.findAllByUserId(token); } @GetMapping("/orders/{id}") public OrderEntity getOrdersDetail(@RequestHeader("token")Long token, @PathVariable("id")long id){ return orderRepository.findById(id) .get(); } private String getUserName(String token){ return token; } }
UTF-8
Java
2,482
java
OrderController.java
Java
[ { "context": "ion TODO\n * @Date 2019/3/17 下午10:45\n * @Created by chenghao\n * @desc OrderController\n * @project order\n */\n@R", "end": 646, "score": 0.8477850556373596, "start": 638, "tag": "USERNAME", "value": "chenghao" } ]
null
[]
package io.daocloud.shop.order.controller; import io.daocloud.shop.order.entity.ItemEntity; import io.daocloud.shop.order.entity.OrderEntity; import io.daocloud.shop.order.repository.ItemRepository; import io.daocloud.shop.order.repository.OrderRepository; import io.daocloud.shop.order.vo.OrderVo; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.transaction.Transactional; import java.util.List; import java.util.stream.Collectors; /** * @Package io.daocloud.shop.order.controller * @Classname OrderController * @Description TODO * @Date 2019/3/17 下午10:45 * @Created by chenghao * @desc OrderController * @project order */ @RestController @RequestMapping() public class OrderController { private final OrderRepository orderRepository; private final ItemRepository itemRepository; public OrderController(OrderRepository orderRepository, ItemRepository itemRepository) { this.orderRepository = orderRepository; this.itemRepository = itemRepository; } @PostMapping("/orders") @ResponseStatus(HttpStatus.CREATED) @Transactional public void createOrder(@RequestBody List<OrderVo> orderVos, @RequestHeader("token")Long token){ Double amount = orderVos.stream().map(e -> e.getCount() * e.getPrice()) .reduce(Double::sum).orElse(0.0); OrderEntity orderEntity = OrderEntity.builder().userId(token).amount(amount).build(); List<ItemEntity> collect = orderVos.stream().map(e -> { ItemEntity itemEntity = ItemEntity.builder().count(e.getCount()) .price(e.getPrice()) .productId(e.getProductId()) .productName(e.getProductName()).build(); return itemEntity; }).collect(Collectors.toList()); orderEntity.setItems(collect); OrderEntity save = orderRepository.save(orderEntity); } @GetMapping("/user/{id}/orders") public Iterable<OrderEntity> getOrdersByUser(@RequestHeader("token")Long token){ return orderRepository.findAllByUserId(token); } @GetMapping("/orders/{id}") public OrderEntity getOrdersDetail(@RequestHeader("token")Long token, @PathVariable("id")long id){ return orderRepository.findById(id) .get(); } private String getUserName(String token){ return token; } }
2,482
0.680791
0.675545
71
33.901409
25.081924
93
false
false
0
0
0
0
0
0
0.394366
false
false
11
9c9233a54cc2692af01cf659156396d8e83ca5e8
23,493,471,145,056
a71bcaf3a56d2dd2229b4113b57324f9a0256e45
/SWIFTDesk/src/com/sd/training/struts2/serviceImpl/PayeeServiceImpl.java
a75b6513cde03690925b4cbbf11c45273a8f3923
[]
no_license
jarekjj/training
https://github.com/jarekjj/training
db869e74fffc8f23783951b61883ba3a19a64d52
0e60b563b424bb4b3816fa36b038430b7f63b67f
refs/heads/master
2018-01-16T03:10:26.238000
2015-05-24T11:33:16
2015-05-24T11:33:16
39,078,783
0
0
null
true
2015-07-14T14:13:32
2015-07-14T14:13:32
2015-05-24T11:30:18
2015-05-24T11:33:16
30,748
0
0
0
null
null
null
package com.sd.training.struts2.serviceImpl; import com.sd.training.struts2.bean.Payee; import com.sd.training.struts2.dao.PayeeDao; import com.sd.training.struts2.daoimpl.PayeeDaoImpl; import com.sd.training.struts2.service.PayeeService; public class PayeeServiceImpl implements PayeeService{ @Override public Payee save(Payee payee) throws RuntimeException { PayeeDao payeeDao=new PayeeDaoImpl(); payee=payeeDao.save(payee); return payee; } }
UTF-8
Java
475
java
PayeeServiceImpl.java
Java
[]
null
[]
package com.sd.training.struts2.serviceImpl; import com.sd.training.struts2.bean.Payee; import com.sd.training.struts2.dao.PayeeDao; import com.sd.training.struts2.daoimpl.PayeeDaoImpl; import com.sd.training.struts2.service.PayeeService; public class PayeeServiceImpl implements PayeeService{ @Override public Payee save(Payee payee) throws RuntimeException { PayeeDao payeeDao=new PayeeDaoImpl(); payee=payeeDao.save(payee); return payee; } }
475
0.774737
0.764211
17
25.941177
22.309246
57
false
false
0
0
0
0
0
0
1
false
false
11
2e95bdc5982679df2c778378eb837d4b58223dc7
15,298,673,542,318
db0f3e5205e651e2e6ba858aa4944dce2ae925ea
/service3/src/main/java/com/cap/anurag/service/MovieService.java
a12c298e449ad93b69acccea5a87c05c5befa0d2
[]
no_license
Manasareddy549/Movie-Refund
https://github.com/Manasareddy549/Movie-Refund
726358ef88bb7c2643917f52cd279534973d3c42
d5a19dd4f99c5e93bed96caf7854c3c3e89fc563
refs/heads/master
2022-07-17T15:11:13.317000
2020-05-19T14:13:22
2020-05-19T14:13:22
264,694,970
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cap.anurag.service; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cap.anurag.dao.SeatsDao; import com.cap.anurag.entity.Seats; import com.cap.anurag.exception.InvalidDetailsException; @Service @Transactional public class MovieService implements MovieServiceInterface { @Autowired private SeatsDao seats; //Fetching remaining seats info @Override public Seats seatDetails(String s_type) { return seats.seatDetails(s_type); } //Updating seats after refund @Override public String setSeats(Seats seat) throws InvalidDetailsException{ boolean bool = seats.existsById(seat.getSno()); if(bool) { seats.save(seat); return "seats updated successfully!!"; } else { throw new InvalidDetailsException("Sorry!! particular seats does not exist"); //return "Sorry!! particular seats does not exist"; } } }
UTF-8
Java
983
java
MovieService.java
Java
[]
null
[]
package com.cap.anurag.service; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cap.anurag.dao.SeatsDao; import com.cap.anurag.entity.Seats; import com.cap.anurag.exception.InvalidDetailsException; @Service @Transactional public class MovieService implements MovieServiceInterface { @Autowired private SeatsDao seats; //Fetching remaining seats info @Override public Seats seatDetails(String s_type) { return seats.seatDetails(s_type); } //Updating seats after refund @Override public String setSeats(Seats seat) throws InvalidDetailsException{ boolean bool = seats.existsById(seat.getSno()); if(bool) { seats.save(seat); return "seats updated successfully!!"; } else { throw new InvalidDetailsException("Sorry!! particular seats does not exist"); //return "Sorry!! particular seats does not exist"; } } }
983
0.754832
0.754832
37
25.594595
22.774405
81
false
false
0
0
0
0
0
0
1.918919
false
false
11
009fb0f83e1287eaf72f859670573155f030e197
4,776,003,675,809
b6c9714026c9b7c11bc025faf7bdfb232719cd69
/src/test/java/utils/ImagePPMUtilsTest.java
31845553bb65969ab9bb3b913915ea3272c258ca
[]
no_license
mklimasz/EncogAppUnivie
https://github.com/mklimasz/EncogAppUnivie
8370900696202bee968dda4d7bf5ef1f9859f174
28b200e92ff8f0af529e77e159482d2c26dd1c65
refs/heads/master
2016-08-09T18:54:42.160000
2016-01-15T15:37:17
2016-01-15T15:37:17
49,725,033
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package utils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertArrayEquals; public class ImagePPMUtilsTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void readImageColorsTest() throws IOException { double[][] expected = { {0, 0, 0, 1, 1, 1, 255, 255, 255}, {1, 1, 1, 1, 1, 1, 0, 0, 0} }; assertArrayEquals(expected, ImagePPMUtils.readImageColors(this.getClass() .getResource("/test.ppm") .getPath())); } @Test public void saveFileTest() throws IOException { double[][] expected = { {0, 0, 0, 1, 1, 1, 255, 255, 255}, {1, 1, 1, 1, 1, 1, 0, 0, 0} }; String fileName = "tmp.ppm"; File file = folder.newFile(fileName); ImagePPMUtils.saveColorsToFile(expected, file); assertArrayEquals(expected, ImagePPMUtils.readImageColors(file.getPath())); } }
UTF-8
Java
1,155
java
ImagePPMUtilsTest.java
Java
[]
null
[]
package utils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertArrayEquals; public class ImagePPMUtilsTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void readImageColorsTest() throws IOException { double[][] expected = { {0, 0, 0, 1, 1, 1, 255, 255, 255}, {1, 1, 1, 1, 1, 1, 0, 0, 0} }; assertArrayEquals(expected, ImagePPMUtils.readImageColors(this.getClass() .getResource("/test.ppm") .getPath())); } @Test public void saveFileTest() throws IOException { double[][] expected = { {0, 0, 0, 1, 1, 1, 255, 255, 255}, {1, 1, 1, 1, 1, 1, 0, 0, 0} }; String fileName = "tmp.ppm"; File file = folder.newFile(fileName); ImagePPMUtils.saveColorsToFile(expected, file); assertArrayEquals(expected, ImagePPMUtils.readImageColors(file.getPath())); } }
1,155
0.566234
0.524675
41
27.170732
20.759838
63
false
false
0
0
0
0
0
0
1.268293
false
false
11
334f927db6ea79aad242f1de1f758ab9be3ed23c
4,776,003,676,736
ff7bb827de59978662bc63b033ddc3c42506c989
/aggagent/src/org/cougaar/lib/aggagent/util/InverseSax.java
0e30c976502d6ed0e9682751d35675249e3f600c
[]
no_license
djw1149/cougaar-aggagent
https://github.com/djw1149/cougaar-aggagent
40211e0e4814b9e812d0e2338aca518e032c8067
67c5f24596bf9535044ae879a4d0cb20b52eacfb
refs/heads/master
2021-01-17T06:24:34.707000
2012-06-12T19:03:47
2012-06-12T19:03:47
40,079,643
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * <copyright> * * Copyright 2003-2004 BBNT Solutions, LLC * under sponsorship of the Defense Advanced Research Projects * Agency (DARPA). * * You can redistribute this software and/or modify it under the * terms of the Cougaar Open Source License as published on the * Cougaar Open Source Website (www.cougaar.org). * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * </copyright> */ package org.cougaar.lib.aggagent.util; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * InverseSax is a class that acts as the reverse of a SAX parser. In other * words, it creates the text of an XML document by accepting notification * of parts of the XML structure through method calls. Those parts include * opening and closing tags, attributes, and text. In the attributes and * text, encoding of special characters is handled automatically. */ public class InverseSax { private static class NameNode { public String tag = null; public NameNode next = null; public NameNode (String t, NameNode n) { tag = t; next = n; } } private static byte EMPTY = 0; private static byte IN_TAG = 1; private static byte IN_ELEMENT = 2; private static byte IN_TEXT = 3; private static byte DONE = 4; private byte state = EMPTY; private StringBuffer buf = new StringBuffer(); private NameNode nameStack = null; private boolean lenientMode = false; private boolean prettyPrint = false; private int indentTabs = 0; private void pushName (String name) { nameStack = new NameNode(name, nameStack); } private boolean nameStackEmpty () { return nameStack == null; } private String popName () { NameNode p = nameStack; nameStack = p.next; return p.tag; } private void encode (String s) { char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (c == '&') buf.append("&amp;"); else if (c == '<') buf.append("&lt;"); else if (c == '>') buf.append("&gt;"); else if (c == '\'') buf.append("&apos;"); else if (c == '"') buf.append("&quot;"); else buf.append(c); } } /** * Set the lenient mode on or off. In lenient mode, the tag and attribute * names are not checked for invalid characters. This class accepts only * the Latin alphabet (upper- and lower-case) as letters and {0, 1, ..., 9} * as digits, and it does not allow the colon (used in XML namespaces). * There are many other sets of letters, digits, and punctuation characters * in the UNICODE spec that are allowed by standard XML. To use these * characters or XML namespaces, lenient mode must be turned on. * <br><br> * Use at your own risk. */ public void setLenientMode (boolean b) { lenientMode = b; } /** * turn pretty-printing on or off */ public void setPrettyPrintMode (boolean b) { if (state != EMPTY) throw new IllegalStateException( "Pretty-print must be set before content is added."); prettyPrint = b; } // add indentation private void indent () { buf.append("\n"); for (int i = 0; i < indentTabs; i++) buf.append(" "); } // Allow upper- and lower-case letters and underscores. // Currently, the colon is not allowed--we don't use namespaces. private static boolean validateInitial (char c) { return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '_' /* || c == ':' */; } // Any initial is allowed here, as well as digits, hyphens, and periods. private static boolean validateNameChar (char c) { return validateInitial(c) || ('0' <= c && c <= '9') || c == '-' || c == '.'; } private boolean validateName (String s) { if (s == null || s.length() == 0) { return false; } else if (!lenientMode) { char[] chars = s.toCharArray(); if (!validateInitial(chars[0])) return false; else for (int i = 1; i < chars.length; i++) if (!validateNameChar(chars[i])) return false; } return true; } /** * Return this XML document generator to its pristine state, abandoning any * work previously in progress. */ public void reset () { buf = new StringBuffer(); nameStack = null; state = EMPTY; } /** * Add a new element to the document. This can be the document root or a * child of another element. After the root element has been closed, no * more elements may be added, and attempting to do so will result in an * IllegalStateException. This method also verifies that the tag name is * valid (see above). */ public void addElement (String tag) { if (state == DONE) throw new IllegalStateException("end of document--can't add elements"); if (!validateName(tag)) throw new IllegalArgumentException("illegal tag name: " + tag); if (state == IN_TAG) buf.append(">"); if (prettyPrint) { if (state == IN_TAG || state == IN_TEXT) indentTabs++; indent(); } buf.append("<"); buf.append(tag); pushName(tag); state = IN_TAG; } /** * Convenience method for adding an element with text but no attributes or * child elements. */ public void addTextElement (String tag, String text) { addElement(tag); addText(text); endElement(); } /** * Convenience method for adding an element with a single attribute and * no content. */ public void addEltAtt (String tag, String att, String val) { addEltAttText(tag, att, val, null); } /** * Convenience method for adding an element with a single attribute and * text for content. Specify null for no content. */ public void addEltAttText (String tag, String att, String val, String text) { addElement(tag); addAttribute(att, val); if (text != null) addText(text); endElement(); } /** * Add an attribute to the current XML element. This method is only valid * after creating an element and before adding other contents, such as text * or child elements. Use of this method at any other time will raise an * IllegalStateException. Special characters within the attribute value are * automatically replaced with the appropriate character entities. This * method also verifies that the tag name is valid (see above). */ public void addAttribute (String name, String value) { if (state != IN_TAG) throw new IllegalStateException("attributes belong inside an XML tag"); if (!validateName(name)) throw new IllegalArgumentException("illegal attribute name: " + name); buf.append(" "); buf.append(name); buf.append("=\""); encode(value); buf.append("\""); } /** * Add text content to the current XML element. This method is valid any * time after the root element is opened but before it is closed. This * method may be called multiple times within a single element, but the * effect is the same as calling it once with the concatenation of the text * of the many calls (in the same order). */ public void addText (String text) { if (state == EMPTY || state == DONE) throw new IllegalStateException("text belongs inside an XML element"); if (state == IN_TAG) { buf.append(">"); state = IN_TEXT; } encode(text); } /** * Close the current element. Every tag must be closed explicitly by a * call to this method (or endDocument, which calls this method). */ public void endElement () { if (state == EMPTY || state == DONE) throw new IllegalStateException("can't close element--none is current"); String tag = popName(); if (state == IN_TAG) { buf.append("/>"); } else { if (prettyPrint && state == IN_ELEMENT) { indentTabs--; indent(); } buf.append("</"); buf.append(tag); buf.append(">"); } if (nameStackEmpty()) state = DONE; else state = IN_ELEMENT; } /** * This method probably shouldn't be used under normal conditions. However, * in case an error or some other unexpected condition is encountered while * creating the XML document, this method can be used to end the document * gracefully. Following any call to this method, toString() is guaranteed * to return either the text of a well-formed XML document or the empty * String (and the latter only if no elements were added). * <br><br> * After this method is called, no more content may be added, even if the * document is empty. */ public void endDocument () { while (!nameStackEmpty()) endElement(); state = DONE; } /** * Return the text of the XML document. */ public String toString () { return buf.toString(); } // - - - - - - - Testing Harness - - - - - - - - - - - - - - - - - - - - - - - public static void main (String[] argv) { InverseSax doc = new InverseSax(); doc.setPrettyPrintMode(true); doc.addElement("bla.bla"); doc.addAttribute("type", "bl<a>h"); doc.addAttribute("bla.id", "sc&um"); doc.addText("SomeText"); for (int i = 0; i < 5; i++) { doc.addElement("yargh"); doc.addAttribute("value", "high"); doc.addText("<" + i + ">"); doc.endElement(); } doc.endElement(); System.out.println(doc.toString()); System.out.println(); try { Element elt = XmlUtils.parse(doc.toString()); recursivePrint(elt); } catch (Exception bugger_off) { } } private static void recursivePrint (Element elt) { System.out.print("{node(" + elt.getNodeName() + ")["); NamedNodeMap nnm = elt.getAttributes(); for (int i = 0; i < nnm.getLength(); i++) { Node att = nnm.item(i); System.out.print(att.getNodeName() + "=" + att.getNodeValue() + ";"); } System.out.print("]"); NodeList nl = elt.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node child = nl.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) recursivePrint((Element) child); else if (child.getNodeType() == Node.TEXT_NODE) System.out.print("\"" + child.getNodeValue() + "\""); } System.out.print("}"); } }
UTF-8
Java
11,187
java
InverseSax.java
Java
[]
null
[]
/* * <copyright> * * Copyright 2003-2004 BBNT Solutions, LLC * under sponsorship of the Defense Advanced Research Projects * Agency (DARPA). * * You can redistribute this software and/or modify it under the * terms of the Cougaar Open Source License as published on the * Cougaar Open Source Website (www.cougaar.org). * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * </copyright> */ package org.cougaar.lib.aggagent.util; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * InverseSax is a class that acts as the reverse of a SAX parser. In other * words, it creates the text of an XML document by accepting notification * of parts of the XML structure through method calls. Those parts include * opening and closing tags, attributes, and text. In the attributes and * text, encoding of special characters is handled automatically. */ public class InverseSax { private static class NameNode { public String tag = null; public NameNode next = null; public NameNode (String t, NameNode n) { tag = t; next = n; } } private static byte EMPTY = 0; private static byte IN_TAG = 1; private static byte IN_ELEMENT = 2; private static byte IN_TEXT = 3; private static byte DONE = 4; private byte state = EMPTY; private StringBuffer buf = new StringBuffer(); private NameNode nameStack = null; private boolean lenientMode = false; private boolean prettyPrint = false; private int indentTabs = 0; private void pushName (String name) { nameStack = new NameNode(name, nameStack); } private boolean nameStackEmpty () { return nameStack == null; } private String popName () { NameNode p = nameStack; nameStack = p.next; return p.tag; } private void encode (String s) { char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (c == '&') buf.append("&amp;"); else if (c == '<') buf.append("&lt;"); else if (c == '>') buf.append("&gt;"); else if (c == '\'') buf.append("&apos;"); else if (c == '"') buf.append("&quot;"); else buf.append(c); } } /** * Set the lenient mode on or off. In lenient mode, the tag and attribute * names are not checked for invalid characters. This class accepts only * the Latin alphabet (upper- and lower-case) as letters and {0, 1, ..., 9} * as digits, and it does not allow the colon (used in XML namespaces). * There are many other sets of letters, digits, and punctuation characters * in the UNICODE spec that are allowed by standard XML. To use these * characters or XML namespaces, lenient mode must be turned on. * <br><br> * Use at your own risk. */ public void setLenientMode (boolean b) { lenientMode = b; } /** * turn pretty-printing on or off */ public void setPrettyPrintMode (boolean b) { if (state != EMPTY) throw new IllegalStateException( "Pretty-print must be set before content is added."); prettyPrint = b; } // add indentation private void indent () { buf.append("\n"); for (int i = 0; i < indentTabs; i++) buf.append(" "); } // Allow upper- and lower-case letters and underscores. // Currently, the colon is not allowed--we don't use namespaces. private static boolean validateInitial (char c) { return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '_' /* || c == ':' */; } // Any initial is allowed here, as well as digits, hyphens, and periods. private static boolean validateNameChar (char c) { return validateInitial(c) || ('0' <= c && c <= '9') || c == '-' || c == '.'; } private boolean validateName (String s) { if (s == null || s.length() == 0) { return false; } else if (!lenientMode) { char[] chars = s.toCharArray(); if (!validateInitial(chars[0])) return false; else for (int i = 1; i < chars.length; i++) if (!validateNameChar(chars[i])) return false; } return true; } /** * Return this XML document generator to its pristine state, abandoning any * work previously in progress. */ public void reset () { buf = new StringBuffer(); nameStack = null; state = EMPTY; } /** * Add a new element to the document. This can be the document root or a * child of another element. After the root element has been closed, no * more elements may be added, and attempting to do so will result in an * IllegalStateException. This method also verifies that the tag name is * valid (see above). */ public void addElement (String tag) { if (state == DONE) throw new IllegalStateException("end of document--can't add elements"); if (!validateName(tag)) throw new IllegalArgumentException("illegal tag name: " + tag); if (state == IN_TAG) buf.append(">"); if (prettyPrint) { if (state == IN_TAG || state == IN_TEXT) indentTabs++; indent(); } buf.append("<"); buf.append(tag); pushName(tag); state = IN_TAG; } /** * Convenience method for adding an element with text but no attributes or * child elements. */ public void addTextElement (String tag, String text) { addElement(tag); addText(text); endElement(); } /** * Convenience method for adding an element with a single attribute and * no content. */ public void addEltAtt (String tag, String att, String val) { addEltAttText(tag, att, val, null); } /** * Convenience method for adding an element with a single attribute and * text for content. Specify null for no content. */ public void addEltAttText (String tag, String att, String val, String text) { addElement(tag); addAttribute(att, val); if (text != null) addText(text); endElement(); } /** * Add an attribute to the current XML element. This method is only valid * after creating an element and before adding other contents, such as text * or child elements. Use of this method at any other time will raise an * IllegalStateException. Special characters within the attribute value are * automatically replaced with the appropriate character entities. This * method also verifies that the tag name is valid (see above). */ public void addAttribute (String name, String value) { if (state != IN_TAG) throw new IllegalStateException("attributes belong inside an XML tag"); if (!validateName(name)) throw new IllegalArgumentException("illegal attribute name: " + name); buf.append(" "); buf.append(name); buf.append("=\""); encode(value); buf.append("\""); } /** * Add text content to the current XML element. This method is valid any * time after the root element is opened but before it is closed. This * method may be called multiple times within a single element, but the * effect is the same as calling it once with the concatenation of the text * of the many calls (in the same order). */ public void addText (String text) { if (state == EMPTY || state == DONE) throw new IllegalStateException("text belongs inside an XML element"); if (state == IN_TAG) { buf.append(">"); state = IN_TEXT; } encode(text); } /** * Close the current element. Every tag must be closed explicitly by a * call to this method (or endDocument, which calls this method). */ public void endElement () { if (state == EMPTY || state == DONE) throw new IllegalStateException("can't close element--none is current"); String tag = popName(); if (state == IN_TAG) { buf.append("/>"); } else { if (prettyPrint && state == IN_ELEMENT) { indentTabs--; indent(); } buf.append("</"); buf.append(tag); buf.append(">"); } if (nameStackEmpty()) state = DONE; else state = IN_ELEMENT; } /** * This method probably shouldn't be used under normal conditions. However, * in case an error or some other unexpected condition is encountered while * creating the XML document, this method can be used to end the document * gracefully. Following any call to this method, toString() is guaranteed * to return either the text of a well-formed XML document or the empty * String (and the latter only if no elements were added). * <br><br> * After this method is called, no more content may be added, even if the * document is empty. */ public void endDocument () { while (!nameStackEmpty()) endElement(); state = DONE; } /** * Return the text of the XML document. */ public String toString () { return buf.toString(); } // - - - - - - - Testing Harness - - - - - - - - - - - - - - - - - - - - - - - public static void main (String[] argv) { InverseSax doc = new InverseSax(); doc.setPrettyPrintMode(true); doc.addElement("bla.bla"); doc.addAttribute("type", "bl<a>h"); doc.addAttribute("bla.id", "sc&um"); doc.addText("SomeText"); for (int i = 0; i < 5; i++) { doc.addElement("yargh"); doc.addAttribute("value", "high"); doc.addText("<" + i + ">"); doc.endElement(); } doc.endElement(); System.out.println(doc.toString()); System.out.println(); try { Element elt = XmlUtils.parse(doc.toString()); recursivePrint(elt); } catch (Exception bugger_off) { } } private static void recursivePrint (Element elt) { System.out.print("{node(" + elt.getNodeName() + ")["); NamedNodeMap nnm = elt.getAttributes(); for (int i = 0; i < nnm.getLength(); i++) { Node att = nnm.item(i); System.out.print(att.getNodeName() + "=" + att.getNodeValue() + ";"); } System.out.print("]"); NodeList nl = elt.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node child = nl.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) recursivePrint((Element) child); else if (child.getNodeType() == Node.TEXT_NODE) System.out.print("\"" + child.getNodeValue() + "\""); } System.out.print("}"); } }
11,187
0.625548
0.622687
358
30.251396
25.259954
80
false
false
0
0
0
0
0
0
0.597765
false
false
11
80d2577a04ee13ffdf560aa01b01af62519f616f
18,184,891,582,517
acc797a8ede48a4ce49a6970af2ddfe0f9a8ecaf
/eclipse/Quest/src/test/playertests/HandTest.java
edbe7a393d20d6ce4138afd32d6035479ed159e5
[ "MIT" ]
permissive
xiaroy/Quests-of-the-Round-Table
https://github.com/xiaroy/Quests-of-the-Round-Table
85a240b80d281e4bc7cad107591339a01e73c67b
17698808fb156652a3d88064ddca434a885833f1
refs/heads/master
2021-03-24T10:01:28.426000
2018-04-13T14:28:17
2018-04-13T14:28:17
118,040,949
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test.playertests; import junit.framework.TestCase; import model.cards.AdventureCard; import model.cards.WeaponCard; import model.cards.WeaponCard.WeaponTypes; import model.player.Hand; public class HandTest extends TestCase { public void testAdd() { Hand hand = new Hand(); hand.AddCard(new WeaponCard(WeaponTypes.Dagger)); hand.AddCard(new WeaponCard(WeaponTypes.Horse)); hand.AddCard(new WeaponCard(WeaponTypes.Dagger)); assertEquals(3, hand.GetCards().length); } public void testRemove() { Hand hand = new Hand(); hand.AddCard(new WeaponCard(WeaponTypes.Dagger)); hand.AddCard(new WeaponCard(WeaponTypes.Horse)); hand.AddCard(new WeaponCard(WeaponTypes.Dagger)); hand.RemoveCard(hand.GetCards()[1]); assertEquals(2, hand.GetCards().length); } public void testCardsInHand() { Hand hand = new Hand(); hand.AddCard(new WeaponCard(WeaponTypes.Dagger)); hand.AddCard(new WeaponCard(WeaponTypes.Horse)); hand.AddCard(new WeaponCard(WeaponTypes.Dagger)); hand.AddCard(new WeaponCard(WeaponTypes.Dagger)); hand.RemoveCard(hand.GetCards()[2]); int other = 0, dagger = 0, horse = 0; for (AdventureCard card : hand.GetCards()) { if (card.getName().equals(WeaponCard.getWeaponName(WeaponTypes.Dagger))) dagger++; else if (card.getName().equals(WeaponCard.getWeaponName(WeaponTypes.Horse))) horse++; else other++; } assertEquals(0, other); assertEquals(2, dagger); assertEquals(1, horse); } }
UTF-8
Java
1,541
java
HandTest.java
Java
[]
null
[]
package test.playertests; import junit.framework.TestCase; import model.cards.AdventureCard; import model.cards.WeaponCard; import model.cards.WeaponCard.WeaponTypes; import model.player.Hand; public class HandTest extends TestCase { public void testAdd() { Hand hand = new Hand(); hand.AddCard(new WeaponCard(WeaponTypes.Dagger)); hand.AddCard(new WeaponCard(WeaponTypes.Horse)); hand.AddCard(new WeaponCard(WeaponTypes.Dagger)); assertEquals(3, hand.GetCards().length); } public void testRemove() { Hand hand = new Hand(); hand.AddCard(new WeaponCard(WeaponTypes.Dagger)); hand.AddCard(new WeaponCard(WeaponTypes.Horse)); hand.AddCard(new WeaponCard(WeaponTypes.Dagger)); hand.RemoveCard(hand.GetCards()[1]); assertEquals(2, hand.GetCards().length); } public void testCardsInHand() { Hand hand = new Hand(); hand.AddCard(new WeaponCard(WeaponTypes.Dagger)); hand.AddCard(new WeaponCard(WeaponTypes.Horse)); hand.AddCard(new WeaponCard(WeaponTypes.Dagger)); hand.AddCard(new WeaponCard(WeaponTypes.Dagger)); hand.RemoveCard(hand.GetCards()[2]); int other = 0, dagger = 0, horse = 0; for (AdventureCard card : hand.GetCards()) { if (card.getName().equals(WeaponCard.getWeaponName(WeaponTypes.Dagger))) dagger++; else if (card.getName().equals(WeaponCard.getWeaponName(WeaponTypes.Horse))) horse++; else other++; } assertEquals(0, other); assertEquals(2, dagger); assertEquals(1, horse); } }
1,541
0.698897
0.692408
54
26.537037
21.070177
79
false
false
0
0
0
0
0
0
2.240741
false
false
11
1fa248df537232382f34558cc4e7def22e7890f9
6,176,162,983,203
412d9215d7084f55c351c4c37dc65c52327afbcc
/src/test/java/taskmanager/TaskManangerTestUtil.java
819bdf71c787c4711b8fbdf19efe7bac098226a4
[]
no_license
pawlowa/TaskManager
https://github.com/pawlowa/TaskManager
547b378acbf46f5cc4476ffd3b765bc8aac260f8
4ccf8fe875b126a07cf55f7f17615e2d26ddca55
refs/heads/master
2023-04-13T02:06:16.520000
2021-04-28T09:14:09
2021-04-28T09:14:09
362,085,798
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package taskmanager; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class TaskManangerTestUtil { static List<PriorityEnum> mapPriorityList(List<Process> processes) { return processes.stream().map(Process::getPriority).collect(Collectors.toList()); } static List<Integer> mapPidList(List<Process> processes) { return processes.stream().map(Process::getPid).collect(Collectors.toList()); } /** * maps String representation of process list to process list * @param processListString, e.g. "MEDIUM HIGH LOW" * @return e.g. (1,MEDIUM) (2,HIGH) (3,LOW) */ public static List<Process> toProcessList(String processListString) { return Arrays.stream(processListString.split(" ")) .filter(s -> !(s.trim().isEmpty())) .map(name -> createTestProcess(PriorityEnum.valueOf(name))) .collect(Collectors.toList()); } /** * Creates a process only for Tests. In Production, only the TaskManager creates Processes. */ public static Process createTestProcess(PriorityEnum priorityEnum){ return new Process(priorityEnum); } }
UTF-8
Java
1,204
java
TaskManangerTestUtil.java
Java
[]
null
[]
package taskmanager; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class TaskManangerTestUtil { static List<PriorityEnum> mapPriorityList(List<Process> processes) { return processes.stream().map(Process::getPriority).collect(Collectors.toList()); } static List<Integer> mapPidList(List<Process> processes) { return processes.stream().map(Process::getPid).collect(Collectors.toList()); } /** * maps String representation of process list to process list * @param processListString, e.g. "MEDIUM HIGH LOW" * @return e.g. (1,MEDIUM) (2,HIGH) (3,LOW) */ public static List<Process> toProcessList(String processListString) { return Arrays.stream(processListString.split(" ")) .filter(s -> !(s.trim().isEmpty())) .map(name -> createTestProcess(PriorityEnum.valueOf(name))) .collect(Collectors.toList()); } /** * Creates a process only for Tests. In Production, only the TaskManager creates Processes. */ public static Process createTestProcess(PriorityEnum priorityEnum){ return new Process(priorityEnum); } }
1,204
0.669435
0.666944
35
33.400002
30.895399
95
false
false
0
0
0
0
0
0
0.371429
false
false
11
da43fa751107f425f1d54c957cbaa470f7a4413b
7,035,156,472,156
3bccc93bbfe5fd90a91344182bf55be15599094c
/app/src/main/java/com/ydlm/app/view/adapter/viewholder/TrandactExpendituteHolderRv.java
16b689198d1f8e1d96ab0cb820072a6360810bcd
[ "Apache-2.0" ]
permissive
liuyongfeng90/EDAllianc
https://github.com/liuyongfeng90/EDAllianc
2f7699f5c420530ed99a0a391b6de2bf3cb6c8aa
eb124416ed8d45c22ef6f41a950621365341d780
refs/heads/master
2020-04-09T04:55:22.003000
2018-12-12T08:51:04
2018-12-12T08:51:04
160,043,368
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ydlm.app.view.adapter.viewholder; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.ydlm.app.R; import com.ydlm.app.model.entity.transaction.SearchConsumptionDetailBean; import com.ydlm.app.view.adapter.TrandactExpenditureAdapterRv; import com.ydlm.app.view.adapter.city.BaseHolderRV; /** * Created by Tm on 2017/11/1. */ public class TrandactExpendituteHolderRv extends BaseHolderRV<SearchConsumptionDetailBean.DATABean> { private TextView titleTv; private TextView businessCost; private TextView timeTv; private TextView detailTv; private TextView businessCostMun; private TextView line; public TrandactExpendituteHolderRv(Context context, ViewGroup parent, TrandactExpenditureAdapterRv adapter, int itemType) { super(context, parent, adapter, itemType, R.layout.item_transaction_expenditure_detail); } @Override public void onFindViews(View itemView) { titleTv = (TextView) itemView.findViewById(R.id.title_tv); businessCost = (TextView) itemView.findViewById(R.id.business_cost); timeTv = (TextView) itemView.findViewById(R.id.time_tv); detailTv = (TextView) itemView.findViewById(R.id.detail_tv); businessCostMun = (TextView) itemView.findViewById(R.id.business_cost_mun); line = (TextView) itemView.findViewById(R.id.line); } @Override protected void onItemClick(View itemView, int position, SearchConsumptionDetailBean.DATABean dataBean) { } @Override protected void onRefreshView(SearchConsumptionDetailBean.DATABean dataBean, int position) { if (position==adapter.listData.size()-1){ line.setVisibility(View.GONE); } if (dataBean != null) { titleTv.setText(dataBean.getType_name()); timeTv.setText(dataBean.getTime()); if (Double.parseDouble(dataBean.getMoney()) <= 0){ detailTv.setTextColor(0xffff4790); detailTv.setText(dataBean.getMoney()); }else { detailTv.setTextColor(0xff999999); detailTv.setText("+"+dataBean.getMoney()); } if (dataBean.getBusiness_cost() != null && Double.parseDouble(dataBean.getBusiness_cost()) != 0) { businessCostMun.setText(dataBean.getBusiness_cost()); businessCost.setVisibility(View.VISIBLE); businessCostMun.setVisibility(View.VISIBLE); } else { businessCost.setVisibility(View.GONE); businessCostMun.setVisibility(View.GONE); } } } }
UTF-8
Java
2,787
java
TrandactExpendituteHolderRv.java
Java
[ { "context": "adapter.city.BaseHolderRV;\r\n\r\n\r\n/**\r\n * Created by Tm on 2017/11/1.\r\n */\r\n\r\npublic class TrandactExpend", "end": 417, "score": 0.9993172287940979, "start": 415, "tag": "USERNAME", "value": "Tm" } ]
null
[]
package com.ydlm.app.view.adapter.viewholder; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.ydlm.app.R; import com.ydlm.app.model.entity.transaction.SearchConsumptionDetailBean; import com.ydlm.app.view.adapter.TrandactExpenditureAdapterRv; import com.ydlm.app.view.adapter.city.BaseHolderRV; /** * Created by Tm on 2017/11/1. */ public class TrandactExpendituteHolderRv extends BaseHolderRV<SearchConsumptionDetailBean.DATABean> { private TextView titleTv; private TextView businessCost; private TextView timeTv; private TextView detailTv; private TextView businessCostMun; private TextView line; public TrandactExpendituteHolderRv(Context context, ViewGroup parent, TrandactExpenditureAdapterRv adapter, int itemType) { super(context, parent, adapter, itemType, R.layout.item_transaction_expenditure_detail); } @Override public void onFindViews(View itemView) { titleTv = (TextView) itemView.findViewById(R.id.title_tv); businessCost = (TextView) itemView.findViewById(R.id.business_cost); timeTv = (TextView) itemView.findViewById(R.id.time_tv); detailTv = (TextView) itemView.findViewById(R.id.detail_tv); businessCostMun = (TextView) itemView.findViewById(R.id.business_cost_mun); line = (TextView) itemView.findViewById(R.id.line); } @Override protected void onItemClick(View itemView, int position, SearchConsumptionDetailBean.DATABean dataBean) { } @Override protected void onRefreshView(SearchConsumptionDetailBean.DATABean dataBean, int position) { if (position==adapter.listData.size()-1){ line.setVisibility(View.GONE); } if (dataBean != null) { titleTv.setText(dataBean.getType_name()); timeTv.setText(dataBean.getTime()); if (Double.parseDouble(dataBean.getMoney()) <= 0){ detailTv.setTextColor(0xffff4790); detailTv.setText(dataBean.getMoney()); }else { detailTv.setTextColor(0xff999999); detailTv.setText("+"+dataBean.getMoney()); } if (dataBean.getBusiness_cost() != null && Double.parseDouble(dataBean.getBusiness_cost()) != 0) { businessCostMun.setText(dataBean.getBusiness_cost()); businessCost.setVisibility(View.VISIBLE); businessCostMun.setVisibility(View.VISIBLE); } else { businessCost.setVisibility(View.GONE); businessCostMun.setVisibility(View.GONE); } } } }
2,787
0.654826
0.646932
82
31.987804
32.172359
127
false
false
0
0
0
0
0
0
0.536585
false
false
11
0630098f5b17991879a678bae9419533d4c86184
1,520,418,442,847
bdf445db08f9132fe625a03af247ed432d002da4
/Draughts/src/com/ipl/training/induction/draughts/model/package-info.java
17c2aa2d7d59a2511e9af298ce9c7b913f58dad9
[]
no_license
Civica-Grads/challenge
https://github.com/Civica-Grads/challenge
258c5f73492323cc7279ef6f0a22a48514ec4f45
a112541e1b7f1ed333d976dc081114dee0a65950
refs/heads/master
2021-05-15T13:35:36.610000
2016-10-18T13:14:19
2016-10-18T13:14:19
107,113,282
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Copyright (C) 2012 IPL Information Processing Ltd. All rights reserved. /** * Provides model objects in the Draughts MVC structure. */ package com.ipl.training.induction.draughts.model;
UTF-8
Java
193
java
package-info.java
Java
[]
null
[]
// Copyright (C) 2012 IPL Information Processing Ltd. All rights reserved. /** * Provides model objects in the Draughts MVC structure. */ package com.ipl.training.induction.draughts.model;
193
0.756477
0.735751
6
31
29.899834
74
false
false
0
0
0
0
0
0
0.166667
false
false
11
d4b4e058f24a12c2b160bf668d49d7af78207452
7,868,380,132,418
c86ec0dccd09ae0e6366d43023d28766fea7671b
/src/main/java/com/example/shopping/mall/controller/OrdersController.java
15e21bad9b324f5d0e8e01a3827cc23870ec5c80
[]
no_license
wplace123/ShoppingMall
https://github.com/wplace123/ShoppingMall
c79c80022e7309699b0a29f806b1131e4cb2d17d
753e623cec75cfacf217a3a21c737644260d8505
refs/heads/master
2020-04-05T12:02:07.173000
2018-12-03T15:26:11
2018-12-03T15:26:11
156,855,646
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.shopping.mall.controller; import static com.example.shopping.mall.vo.ResponseCode.SUCCES_CODE; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.example.shopping.mall.common.DefaultHeader; import com.example.shopping.mall.exception.MallException; import com.example.shopping.mall.model.OrdersModel; import com.example.shopping.mall.service.IOrdersService; import com.example.shopping.mall.vo.ResponseCode; import com.example.shopping.mall.vo.ServerResponse; /** * * @author ryan wang * @date 2018/11/11 */ @RestController @RequestMapping(value = "/api") public class OrdersController extends DefaultHeader { @Autowired IOrdersService ordersService; @SuppressWarnings("rawtypes") @RequestMapping(value = "/orders", method = RequestMethod.GET) public ResponseEntity<ServerResponse> getAll() { return new ResponseEntity<ServerResponse>( ServerResponse.create(SUCCES_CODE.getRetCode(), ordersService.getAll()), DefaultHeader.HEADERS, HttpStatus.OK); } @SuppressWarnings("rawtypes") @RequestMapping(value = "/orders/{id}", method = RequestMethod.GET) public ResponseEntity<ServerResponse> findByStatus(@PathVariable int id) { return new ResponseEntity<ServerResponse>( ServerResponse.create(SUCCES_CODE.getRetCode(), ordersService.findById(id)), DefaultHeader.HEADERS, HttpStatus.OK); } /** * 動態查詢 * * @return */ @SuppressWarnings("rawtypes") @RequestMapping(value = "/orders", method = RequestMethod.POST) public ResponseEntity<ServerResponse> getOrders(@RequestBody OrdersModel ordersModel) { return new ResponseEntity<ServerResponse>( ServerResponse.create(ResponseCode.SUCCES_CODE.getRetCode(), ordersService.findAll(ordersModel)), DefaultHeader.HEADERS, HttpStatus.OK); } /** * update * * @return */ @SuppressWarnings("rawtypes") @RequestMapping(value = "/orders/update", method = RequestMethod.PUT) public ResponseEntity<ServerResponse> updateOrders(@RequestBody OrdersModel ordersModel) { try { return new ResponseEntity<ServerResponse>( ServerResponse.create(ResponseCode.SUCCES_CODE.getRetCode(), ordersService.update(ordersModel)), DefaultHeader.HEADERS, HttpStatus.OK); } catch (MallException e) { return new ResponseEntity<ServerResponse>( ServerResponse.create(ResponseCode.SUCCES_CODE.getRetCode(), e.getMessage()), DefaultHeader.HEADERS, HttpStatus.OK); } } /** * create * * @return */ @SuppressWarnings("rawtypes") @RequestMapping(value = "/orders/create", method = RequestMethod.PUT) public ResponseEntity<ServerResponse> createOrders(@RequestBody OrdersModel ordersModel) { if (ordersModel.getId() == null) { return new ResponseEntity<ServerResponse>( ServerResponse.create(ResponseCode.SUCCES_CODE.getRetCode(), ordersService.save(ordersModel)), DefaultHeader.HEADERS, HttpStatus.OK); } else { return new ResponseEntity<ServerResponse>( ServerResponse.create(ResponseCode.ERROR_CODE.getRetCode(), "Id must be null"), DefaultHeader.HEADERS, HttpStatus.OK); } } /** * delete * * @param id * @return */ @SuppressWarnings("rawtypes") @RequestMapping(value = "/orders/{id}", method = RequestMethod.DELETE) public ResponseEntity<ServerResponse> delete(@PathVariable int id) { String result = ""; try { result = ordersService.delete(id); } catch (MallException e) { return new ResponseEntity<ServerResponse>( ServerResponse.create(ResponseCode.ERROR_CODE.getRetCode(), e.getMessage()), DefaultHeader.HEADERS, HttpStatus.OK); } if (id < 1) { return new ResponseEntity<ServerResponse>(ServerResponse.create(ResponseCode.ERROR_CODE.getRetCode(), ""), DefaultHeader.HEADERS, HttpStatus.OK); } return new ResponseEntity<ServerResponse>(ServerResponse.create(ResponseCode.SUCCES_CODE.getRetCode(), result), DefaultHeader.HEADERS, HttpStatus.OK); } }
UTF-8
Java
4,931
java
OrdersController.java
Java
[ { "context": "ng.mall.vo.ServerResponse;\r\n\r\n/**\r\n * \r\n * @author ryan wang\r\n * @date 2018/11/11\r\n */\r\n@RestController\r\n@Requ", "end": 957, "score": 0.9997910261154175, "start": 948, "tag": "NAME", "value": "ryan wang" } ]
null
[]
package com.example.shopping.mall.controller; import static com.example.shopping.mall.vo.ResponseCode.SUCCES_CODE; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.example.shopping.mall.common.DefaultHeader; import com.example.shopping.mall.exception.MallException; import com.example.shopping.mall.model.OrdersModel; import com.example.shopping.mall.service.IOrdersService; import com.example.shopping.mall.vo.ResponseCode; import com.example.shopping.mall.vo.ServerResponse; /** * * @author <NAME> * @date 2018/11/11 */ @RestController @RequestMapping(value = "/api") public class OrdersController extends DefaultHeader { @Autowired IOrdersService ordersService; @SuppressWarnings("rawtypes") @RequestMapping(value = "/orders", method = RequestMethod.GET) public ResponseEntity<ServerResponse> getAll() { return new ResponseEntity<ServerResponse>( ServerResponse.create(SUCCES_CODE.getRetCode(), ordersService.getAll()), DefaultHeader.HEADERS, HttpStatus.OK); } @SuppressWarnings("rawtypes") @RequestMapping(value = "/orders/{id}", method = RequestMethod.GET) public ResponseEntity<ServerResponse> findByStatus(@PathVariable int id) { return new ResponseEntity<ServerResponse>( ServerResponse.create(SUCCES_CODE.getRetCode(), ordersService.findById(id)), DefaultHeader.HEADERS, HttpStatus.OK); } /** * 動態查詢 * * @return */ @SuppressWarnings("rawtypes") @RequestMapping(value = "/orders", method = RequestMethod.POST) public ResponseEntity<ServerResponse> getOrders(@RequestBody OrdersModel ordersModel) { return new ResponseEntity<ServerResponse>( ServerResponse.create(ResponseCode.SUCCES_CODE.getRetCode(), ordersService.findAll(ordersModel)), DefaultHeader.HEADERS, HttpStatus.OK); } /** * update * * @return */ @SuppressWarnings("rawtypes") @RequestMapping(value = "/orders/update", method = RequestMethod.PUT) public ResponseEntity<ServerResponse> updateOrders(@RequestBody OrdersModel ordersModel) { try { return new ResponseEntity<ServerResponse>( ServerResponse.create(ResponseCode.SUCCES_CODE.getRetCode(), ordersService.update(ordersModel)), DefaultHeader.HEADERS, HttpStatus.OK); } catch (MallException e) { return new ResponseEntity<ServerResponse>( ServerResponse.create(ResponseCode.SUCCES_CODE.getRetCode(), e.getMessage()), DefaultHeader.HEADERS, HttpStatus.OK); } } /** * create * * @return */ @SuppressWarnings("rawtypes") @RequestMapping(value = "/orders/create", method = RequestMethod.PUT) public ResponseEntity<ServerResponse> createOrders(@RequestBody OrdersModel ordersModel) { if (ordersModel.getId() == null) { return new ResponseEntity<ServerResponse>( ServerResponse.create(ResponseCode.SUCCES_CODE.getRetCode(), ordersService.save(ordersModel)), DefaultHeader.HEADERS, HttpStatus.OK); } else { return new ResponseEntity<ServerResponse>( ServerResponse.create(ResponseCode.ERROR_CODE.getRetCode(), "Id must be null"), DefaultHeader.HEADERS, HttpStatus.OK); } } /** * delete * * @param id * @return */ @SuppressWarnings("rawtypes") @RequestMapping(value = "/orders/{id}", method = RequestMethod.DELETE) public ResponseEntity<ServerResponse> delete(@PathVariable int id) { String result = ""; try { result = ordersService.delete(id); } catch (MallException e) { return new ResponseEntity<ServerResponse>( ServerResponse.create(ResponseCode.ERROR_CODE.getRetCode(), e.getMessage()), DefaultHeader.HEADERS, HttpStatus.OK); } if (id < 1) { return new ResponseEntity<ServerResponse>(ServerResponse.create(ResponseCode.ERROR_CODE.getRetCode(), ""), DefaultHeader.HEADERS, HttpStatus.OK); } return new ResponseEntity<ServerResponse>(ServerResponse.create(ResponseCode.SUCCES_CODE.getRetCode(), result), DefaultHeader.HEADERS, HttpStatus.OK); } }
4,928
0.66687
0.665042
127
36.763779
33.299042
119
false
false
0
0
0
0
0
0
0.511811
false
false
11
f2d22f5c2c681e717e8afe379fe92a8e2e5afcd4
25,065,429,181,652
55d851a493eb32744a3fd999367b03b4ce93c668
/app/src/main/java/com/ygaps/travelapp/API/Responses/StopPointFeedbackResponse.java
b4a29e6368ce34fd0bbab5ca35c87d11270121be
[]
no_license
dinhhn2000/iOS-CQ2017-32
https://github.com/dinhhn2000/iOS-CQ2017-32
5a38f8d014fc93a6b257858f9e17f1e1565ed895
678f184463b59c905873aa560c749482fa801477
refs/heads/master
2020-09-05T22:44:16.721000
2019-12-29T15:47:51
2019-12-29T15:47:51
220,234,508
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ygaps.travelapp.API.Responses; import com.ygaps.travelapp.utils.StopPointFeedback; import java.util.ArrayList; public class StopPointFeedbackResponse { private ArrayList<StopPointFeedback> feedbackList; public StopPointFeedbackResponse(ArrayList<StopPointFeedback> feedbackList) { this.feedbackList = feedbackList; } @Override public String toString() { return "StopPointFeedbackResponse{" + "feedbackList=" + feedbackList + '}'; } public ArrayList<StopPointFeedback> getFeedbackList() { return feedbackList; } public void setFeedbackList(ArrayList<StopPointFeedback> feedbackList) { this.feedbackList = feedbackList; } }
UTF-8
Java
745
java
StopPointFeedbackResponse.java
Java
[]
null
[]
package com.ygaps.travelapp.API.Responses; import com.ygaps.travelapp.utils.StopPointFeedback; import java.util.ArrayList; public class StopPointFeedbackResponse { private ArrayList<StopPointFeedback> feedbackList; public StopPointFeedbackResponse(ArrayList<StopPointFeedback> feedbackList) { this.feedbackList = feedbackList; } @Override public String toString() { return "StopPointFeedbackResponse{" + "feedbackList=" + feedbackList + '}'; } public ArrayList<StopPointFeedback> getFeedbackList() { return feedbackList; } public void setFeedbackList(ArrayList<StopPointFeedback> feedbackList) { this.feedbackList = feedbackList; } }
745
0.699329
0.699329
28
25.607143
24.721794
81
false
false
0
0
0
0
0
0
0.285714
false
false
11
de36e4b18495a4aef451b3b3efdecde99e84a3ee
12,498,354,877,922
58bd411c39131b24b30b283e5aefa3858e72b177
/Programming_lab8-main/src/Utils/ServerPart/ServerClasses/Commands/Remove_lower_key.java
12da2399a2a5e4f98289fc5f91779cccb53e988c
[]
no_license
Ioutcast/lab8
https://github.com/Ioutcast/lab8
36def55ca4dbab209019aaf27163162bf51b5341
de4e7ce9c41f35ebbeeb21340389ad53d38538e3
refs/heads/main
2023-02-09T21:07:53.612000
2020-12-31T08:03:18
2020-12-31T08:03:18
322,627,857
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Utils.ServerPart.ServerClasses.Commands; import Worker.Worker; import Utils.ServerPart.DataBaseManager; import java.util.Map; public class Remove_lower_key extends AbstractCommand{ public Remove_lower_key() { command = "remove_lower_key"; TextInfo = " {key}: удалить значение по ключу, если новое значение больше старого.\n (Удалаются только те экземпляры, владельцем которых являетесь Вы)"; NeedAnStr = true; } public synchronized String execute(DataBaseManager dataBaseManager, String arg) { String msg = " "; if(!dataBaseManager.getCollection().isEmpty()) { int rlk = Integer.parseInt(arg); msg = ("suc_rld"); for (Map.Entry<Integer, Worker> workerEntry : dataBaseManager.getCollection().entrySet()) { String userName = workerEntry.getValue().getUserName().trim(); if ((workerEntry.getKey() < rlk) && userName.equals(user)) { dataBaseManager.getCollection().remove(workerEntry.getValue().getId()); dataBaseManager.removeFromDataBase(workerEntry.getValue().getId(), user); } } }else{ msg = ("collection_empty"); } return msg; } }
UTF-8
Java
1,436
java
Remove_lower_key.java
Java
[]
null
[]
package Utils.ServerPart.ServerClasses.Commands; import Worker.Worker; import Utils.ServerPart.DataBaseManager; import java.util.Map; public class Remove_lower_key extends AbstractCommand{ public Remove_lower_key() { command = "remove_lower_key"; TextInfo = " {key}: удалить значение по ключу, если новое значение больше старого.\n (Удалаются только те экземпляры, владельцем которых являетесь Вы)"; NeedAnStr = true; } public synchronized String execute(DataBaseManager dataBaseManager, String arg) { String msg = " "; if(!dataBaseManager.getCollection().isEmpty()) { int rlk = Integer.parseInt(arg); msg = ("suc_rld"); for (Map.Entry<Integer, Worker> workerEntry : dataBaseManager.getCollection().entrySet()) { String userName = workerEntry.getValue().getUserName().trim(); if ((workerEntry.getKey() < rlk) && userName.equals(user)) { dataBaseManager.getCollection().remove(workerEntry.getValue().getId()); dataBaseManager.removeFromDataBase(workerEntry.getValue().getId(), user); } } }else{ msg = ("collection_empty"); } return msg; } }
1,436
0.595937
0.595937
43
28.860466
36.228977
160
false
false
0
0
0
0
0
0
0.465116
false
false
11
51bc15f2f8fec867d36762beeb43c83f8dd60af8
24,764,781,468,281
2da5eabea9bd0976dae34e044515fcef0ed3eeea
/module_util/src/main/java/com/zxdc/utils/library/http/HandlerConstant.java
dfaef3e257a1367e7d516b45eea74c8f242032e3
[]
no_license
qijiuyu79/YB_Student
https://github.com/qijiuyu79/YB_Student
57a4cba72edb8c52fdec8d9aee028f55bffec505
9ade4e1a7990e8961c7d36f8f07c91c97994e336
refs/heads/master
2023-01-29T19:30:04.070000
2020-12-12T00:53:19
2020-12-12T00:53:19
286,910,506
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zxdc.utils.library.http; public class HandlerConstant { public static final int DOWNLOAD_PRORESS=10001; public static final int DOWNLOAD_SUCCESS=10002; }
UTF-8
Java
177
java
HandlerConstant.java
Java
[]
null
[]
package com.zxdc.utils.library.http; public class HandlerConstant { public static final int DOWNLOAD_PRORESS=10001; public static final int DOWNLOAD_SUCCESS=10002; }
177
0.768362
0.711864
8
21.125
21.877142
51
false
false
0
0
0
0
0
0
0.375
false
false
11
c20a89a774d49b0363ec2a0a7b7f3937df86013f
30,451,318,170,016
8b8a8fab3f3bb0c33f4a2bbd09245df7156faa2c
/src/main/java/com/rubixdev/rug/mixins/BowItemMixin.java
cefad55802030ac61f42a9dd16188eceb2340b17
[ "CC0-1.0" ]
permissive
cherie535/fabric-rug
https://github.com/cherie535/fabric-rug
7d76255b079bd04f21e5e7627e2dc9ad9bd5f454
6f72570d5ac526aac0a56060877b75c681b9bc8c
refs/heads/main
2023-03-22T02:25:44.933000
2021-03-18T20:44:07
2021-03-18T20:44:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rubixdev.rug.mixins; import com.rubixdev.rug.RugSettings; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.enchantment.Enchantments; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.BowItem; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(BowItem.class) public class BowItemMixin { @Redirect(method = "use", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/PlayerEntity;getArrowType(Lnet/minecraft/item/ItemStack;)Lnet/minecraft/item/ItemStack;")) private ItemStack onUse(PlayerEntity playerEntity, ItemStack stack) { ItemStack arrowType = playerEntity.getArrowType(stack); if (!RugSettings.infinityNeedsArrow && arrowType.isEmpty() && EnchantmentHelper.getLevel(Enchantments.INFINITY, stack) > 0) { return new ItemStack(Items.ARROW); } else { return arrowType; } } }
UTF-8
Java
1,092
java
BowItemMixin.java
Java
[]
null
[]
package com.rubixdev.rug.mixins; import com.rubixdev.rug.RugSettings; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.enchantment.Enchantments; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.BowItem; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(BowItem.class) public class BowItemMixin { @Redirect(method = "use", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/PlayerEntity;getArrowType(Lnet/minecraft/item/ItemStack;)Lnet/minecraft/item/ItemStack;")) private ItemStack onUse(PlayerEntity playerEntity, ItemStack stack) { ItemStack arrowType = playerEntity.getArrowType(stack); if (!RugSettings.infinityNeedsArrow && arrowType.isEmpty() && EnchantmentHelper.getLevel(Enchantments.INFINITY, stack) > 0) { return new ItemStack(Items.ARROW); } else { return arrowType; } } }
1,092
0.757326
0.75641
25
42.68
40.125523
186
false
false
0
0
0
0
0
0
0.84
false
false
11
0113258c9f5f25e5f55ed2c3ef72b7554624f6a3
31,533,649,929,758
f223eb2c942f1ea11871d9a74c5451b592d50bd4
/src/main/java/br/com/bandtec/osirisapi/swagger/SwaggerConfiguration.java
90813d2c47baa53d97274d9231acf200726e8c34
[]
no_license
kaio-baleeiro/pipeline-spring-boot-azure
https://github.com/kaio-baleeiro/pipeline-spring-boot-azure
bbc96e49bbead1a31b815e599b0be9ea6000c77b
4ef9e35f3b6b6ce9a3c2ddf126aa306904d5ad98
refs/heads/main
2023-08-04T22:34:08.178000
2021-09-09T05:46:15
2021-09-09T05:46:15
377,562,262
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.bandtec.osirisapi.swagger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; 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; @Configuration public class SwaggerConfiguration { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("br.com.bandtec.osirisapi")) .paths(PathSelectors.ant("/**")) .build() .apiInfo(getApiInfo()); } private ApiInfo getApiInfo() { return new ApiInfoBuilder() .title("Osíris API") .description("Esta API está relacionada aos trabalhos exercidos pela Osíris") .contact(new Contact("Contato Osíris", "http://osiris.com.br", "contato@osiris.com.br")) .version("1.0.0") .build(); } }
UTF-8
Java
1,297
java
SwaggerConfiguration.java
Java
[ { "context": ")\n .contact(new Contact(\"Contato Osíris\", \"http://osiris.com.br\", \"contato@osiris.com.br\"", "end": 1172, "score": 0.6119652390480042, "start": 1168, "tag": "NAME", "value": "íris" }, { "context": "ontact(\"Contato Osíris\", \"http://osiris.com.br\", \"contato@osiris.com.br\"))\n .version(\"1.0.0\")\n ", "end": 1221, "score": 0.9999050498008728, "start": 1200, "tag": "EMAIL", "value": "contato@osiris.com.br" } ]
null
[]
package br.com.bandtec.osirisapi.swagger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; 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; @Configuration public class SwaggerConfiguration { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("br.com.bandtec.osirisapi")) .paths(PathSelectors.ant("/**")) .build() .apiInfo(getApiInfo()); } private ApiInfo getApiInfo() { return new ApiInfoBuilder() .title("Osíris API") .description("Esta API está relacionada aos trabalhos exercidos pela Osíris") .contact(new Contact("Contato Osíris", "http://osiris.com.br", "<EMAIL>")) .version("1.0.0") .build(); } }
1,283
0.686775
0.683681
34
37.029411
26.649672
104
false
false
0
0
0
0
0
0
0.411765
false
false
11
f9f49803f3502f3707fceb4c02d6ca3cafcd7163
10,780,367,959,933
01ebbc94cd4d2c63501c2ebd64b8f757ac4b9544
/backend/gxqpt-admin/gxqpt-developer-repository/src/main/java/com/hengyunsoft/platform/developer/repository/fast/meet/dao/MeetMapper.java
90be7ef479e8889181b58d13ee9e6b4191fdcb68
[]
no_license
KevinAnYuan/gxq
https://github.com/KevinAnYuan/gxq
60529e527eadbbe63a8ecbbad6aaa0dea5a61168
9b59f4e82597332a70576f43e3f365c41d5cfbee
refs/heads/main
2023-01-04T19:35:18.615000
2020-10-27T06:24:37
2020-10-27T06:24:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hengyunsoft.platform.developer.repository.fast.meet.dao; import org.springframework.stereotype.Repository; @Repository public interface MeetMapper extends com.hengyunsoft.base.dao.BaseAllDao<Long, com.hengyunsoft.platform.developer.entity.fast.meet.po.Meet, com.hengyunsoft.platform.developer.repository.fast.meet.example.MeetExample> { }
UTF-8
Java
352
java
MeetMapper.java
Java
[]
null
[]
package com.hengyunsoft.platform.developer.repository.fast.meet.dao; import org.springframework.stereotype.Repository; @Repository public interface MeetMapper extends com.hengyunsoft.base.dao.BaseAllDao<Long, com.hengyunsoft.platform.developer.entity.fast.meet.po.Meet, com.hengyunsoft.platform.developer.repository.fast.meet.example.MeetExample> { }
352
0.846591
0.846591
7
49.42857
72.834167
217
false
false
0
0
0
0
0
0
0.571429
false
false
11
65b41ffe9550470b1ead044fdc99c8ac15f3d793
31,748,398,257,659
b2e14c76034a93a679f1143ec2dbbbd7b346c526
/src-mlp/OCRemi.java
fb9aabe2a66cca306ed159f56a6eabdcbe7fe839
[]
no_license
remiwong/ocr
https://github.com/remiwong/ocr
cd28498f1d6e4e85e14e32f8b37066c80fceca3a
4dd750e7bc3493902ed9c80f25bda939aa9ef4f4
refs/heads/master
2022-10-06T11:02:12.206000
2020-06-08T16:46:27
2020-06-08T16:46:27
267,374,845
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * * @author Rémi Wong * @version 1.0 * Main Class for Multi-Layer Perceptron problem for Digit Recognition * */ import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class OCRemi { public static void main(String[] args) { //set network parameters int epoch = 100; double trainingFold = 2810; double testFold = 2810; //initialise matrix arrays for training and test sets int[][] trainingSet = new int[2810][65]; int[][] testSet = new int[2810][65]; int[] trainingClass = new int[2810]; int[] testClass = new int[2810]; System.out.println( "[WELCOME TO DIGIT RECOGNITION PROBLEM]\nIn Progres .... "); String csvFile = "cw2DataSet1.csv"; String csvFile2 = "cw2DataSet2.csv"; BufferedReader br = null; String line = ""; String cvsSplitBy = ","; //reads training set lines and adds to training matrix array trainingSet = ReadCSV(csvFile, br, line, cvsSplitBy); for (int countClass = 0; countClass < 2810; countClass++) { trainingClass[countClass] = trainingSet[countClass][64]; } //reads test set lines and adds to training matrix array testSet = ReadCSV(csvFile2, br, line, cvsSplitBy); for (int setTClass = 0; setTClass < 2810; setTClass++) { testClass[setTClass] = testSet[setTClass][64]; } Network net = new Network(); net.Net(); // net.printWeights(); // net.printHiddenWeights(); //Based on defined no of epoch, runs the training of the network through a loop of forward and backward propagation to claibrate weights for(int countEpoch=0;countEpoch<epoch; countEpoch++) { for (int trainingSetLine = 0; trainingSetLine < trainingFold; trainingSetLine++) { int targetClass = trainingClass[trainingSetLine]; net.ForwardPropagation(trainingSet, targetClass, trainingSetLine); net.Backpass(trainingSet, trainingSetLine); net.backpassHiddenWeight(); net.BackpassInputWeight(trainingSet, trainingSetLine); //System.out.println("target: " + targetClass); } // net.printHiddenWeights(); } //counters to measure expected and classified digits int expected0 = 0, expected1 = 0, expected2 = 0, expected3 = 0, expected4 = 0, expected5 = 0, expected6 = 0, expected7 = 0, expected8 = 0, expected9 = 0; int classified0 = 0, classified1 = 0, classified2 = 0, classified3 = 0, classified4 = 0, classified5 = 0, classified6 = 0, classified7 = 0, classified8 = 0, classified9 = 0; double totalClassified = 0; double totalEx=0; //conducts the testing of the test dataset based on defined two-fold through forward propagation based on calibrated weights for(int testSetLine = 0; testSetLine< testFold; testSetLine++) { totalEx++; int testOutput = testClass[testSetLine]; switch(testOutput) { case 0: expected0++; break; case 1: expected1++; break; case 2: expected2++; break; case 3: expected3++; break; case 4: expected4++; break; case 5: expected5++; break; case 6: expected6++; break; case 7: expected7++; break; case 8: expected8++; break; case 9: expected9++; break; } net.ForwardPropagation(testSet, testOutput, testSetLine); //System.out.println("expected class: " + testOutput); int forwardOutput = net.sortingTestSet(testOutput); //System.out.println("Test Class" + testSetLine+ "output: " + forwardOutput); //measure classified digits if(testOutput == forwardOutput) { switch(testOutput) { case 0: classified0++; break; case 1: classified1++; break; case 2: classified2++; break; case 3: classified3++; break; case 4: classified4++; break; case 5: classified5++; break; case 6: classified6++; break; case 7: classified7++; break; case 8: classified8++; break; case 9: classified9++; break; } totalClassified++; } } //display results and accuracy of the algorithm System.out.println("Digit-0 training: " + expected0+ " test: " + classified0); System.out.println("Digit-1 training: " + expected1+ " test: " + classified1); System.out.println("Digit-2 training: " + expected2+ " test: " + classified2); System.out.println("Digit-3 training: " + expected3+ " test: " + classified3); System.out.println("Digit-4 training: " + expected4+ " test: " + classified4); System.out.println("Digit-5 training: " + expected5+ " test: " + classified5); System.out.println("Digit-6 training: " + expected6+ " test: " + classified6); System.out.println("Digit-7 training: " + expected7+ " test: " + classified7); System.out.println("Digit-8 training: " + expected8+ " test: " + classified8); System.out.println("Digit-9 training: " + expected9+ " test: " + classified9); double accuracy = totalClassified/totalEx*100; System.out.println("Total Classified: "+ totalClassified + " Total Expected : "+totalEx+ " Overall Accuracy: " + accuracy + " %"); } //method to convert CSV sources values to matrix array elements public static int[][] ReadCSV(String file, BufferedReader b, String l, String s) { int[][] currentSet = new int[2810][65]; int numInputs = 0; try { b = new BufferedReader(new FileReader(file)); while ((l = b.readLine()) != null) { // use comma as separator String[] pixel = l.split(s); // int c = 0; for (int a = 0; a < 65; a++) { currentSet[numInputs][a] = Integer.parseInt(pixel[c]); c++; } numInputs++; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (b != null) { try { b.close(); } catch (IOException e) { e.printStackTrace(); } } } return currentSet; } }
WINDOWS-1250
Java
5,906
java
OCRemi.java
Java
[ { "context": "/**\r\n *\r\n * @author Rémi Wong\r\n * @version 1.0\r\n * Main Class for Multi-Layer P", "end": 29, "score": 0.9998529553413391, "start": 20, "tag": "NAME", "value": "Rémi Wong" } ]
null
[]
/** * * @author <NAME> * @version 1.0 * Main Class for Multi-Layer Perceptron problem for Digit Recognition * */ import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class OCRemi { public static void main(String[] args) { //set network parameters int epoch = 100; double trainingFold = 2810; double testFold = 2810; //initialise matrix arrays for training and test sets int[][] trainingSet = new int[2810][65]; int[][] testSet = new int[2810][65]; int[] trainingClass = new int[2810]; int[] testClass = new int[2810]; System.out.println( "[WELCOME TO DIGIT RECOGNITION PROBLEM]\nIn Progres .... "); String csvFile = "cw2DataSet1.csv"; String csvFile2 = "cw2DataSet2.csv"; BufferedReader br = null; String line = ""; String cvsSplitBy = ","; //reads training set lines and adds to training matrix array trainingSet = ReadCSV(csvFile, br, line, cvsSplitBy); for (int countClass = 0; countClass < 2810; countClass++) { trainingClass[countClass] = trainingSet[countClass][64]; } //reads test set lines and adds to training matrix array testSet = ReadCSV(csvFile2, br, line, cvsSplitBy); for (int setTClass = 0; setTClass < 2810; setTClass++) { testClass[setTClass] = testSet[setTClass][64]; } Network net = new Network(); net.Net(); // net.printWeights(); // net.printHiddenWeights(); //Based on defined no of epoch, runs the training of the network through a loop of forward and backward propagation to claibrate weights for(int countEpoch=0;countEpoch<epoch; countEpoch++) { for (int trainingSetLine = 0; trainingSetLine < trainingFold; trainingSetLine++) { int targetClass = trainingClass[trainingSetLine]; net.ForwardPropagation(trainingSet, targetClass, trainingSetLine); net.Backpass(trainingSet, trainingSetLine); net.backpassHiddenWeight(); net.BackpassInputWeight(trainingSet, trainingSetLine); //System.out.println("target: " + targetClass); } // net.printHiddenWeights(); } //counters to measure expected and classified digits int expected0 = 0, expected1 = 0, expected2 = 0, expected3 = 0, expected4 = 0, expected5 = 0, expected6 = 0, expected7 = 0, expected8 = 0, expected9 = 0; int classified0 = 0, classified1 = 0, classified2 = 0, classified3 = 0, classified4 = 0, classified5 = 0, classified6 = 0, classified7 = 0, classified8 = 0, classified9 = 0; double totalClassified = 0; double totalEx=0; //conducts the testing of the test dataset based on defined two-fold through forward propagation based on calibrated weights for(int testSetLine = 0; testSetLine< testFold; testSetLine++) { totalEx++; int testOutput = testClass[testSetLine]; switch(testOutput) { case 0: expected0++; break; case 1: expected1++; break; case 2: expected2++; break; case 3: expected3++; break; case 4: expected4++; break; case 5: expected5++; break; case 6: expected6++; break; case 7: expected7++; break; case 8: expected8++; break; case 9: expected9++; break; } net.ForwardPropagation(testSet, testOutput, testSetLine); //System.out.println("expected class: " + testOutput); int forwardOutput = net.sortingTestSet(testOutput); //System.out.println("Test Class" + testSetLine+ "output: " + forwardOutput); //measure classified digits if(testOutput == forwardOutput) { switch(testOutput) { case 0: classified0++; break; case 1: classified1++; break; case 2: classified2++; break; case 3: classified3++; break; case 4: classified4++; break; case 5: classified5++; break; case 6: classified6++; break; case 7: classified7++; break; case 8: classified8++; break; case 9: classified9++; break; } totalClassified++; } } //display results and accuracy of the algorithm System.out.println("Digit-0 training: " + expected0+ " test: " + classified0); System.out.println("Digit-1 training: " + expected1+ " test: " + classified1); System.out.println("Digit-2 training: " + expected2+ " test: " + classified2); System.out.println("Digit-3 training: " + expected3+ " test: " + classified3); System.out.println("Digit-4 training: " + expected4+ " test: " + classified4); System.out.println("Digit-5 training: " + expected5+ " test: " + classified5); System.out.println("Digit-6 training: " + expected6+ " test: " + classified6); System.out.println("Digit-7 training: " + expected7+ " test: " + classified7); System.out.println("Digit-8 training: " + expected8+ " test: " + classified8); System.out.println("Digit-9 training: " + expected9+ " test: " + classified9); double accuracy = totalClassified/totalEx*100; System.out.println("Total Classified: "+ totalClassified + " Total Expected : "+totalEx+ " Overall Accuracy: " + accuracy + " %"); } //method to convert CSV sources values to matrix array elements public static int[][] ReadCSV(String file, BufferedReader b, String l, String s) { int[][] currentSet = new int[2810][65]; int numInputs = 0; try { b = new BufferedReader(new FileReader(file)); while ((l = b.readLine()) != null) { // use comma as separator String[] pixel = l.split(s); // int c = 0; for (int a = 0; a < 65; a++) { currentSet[numInputs][a] = Integer.parseInt(pixel[c]); c++; } numInputs++; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (b != null) { try { b.close(); } catch (IOException e) { e.printStackTrace(); } } } return currentSet; } }
5,902
0.647587
0.616765
175
31.742857
31.034491
175
false
false
0
0
0
0
0
0
3.102857
false
false
11
1c11d040f939c965f97dde4cc55f3295e0674df5
5,463,198,445,604
61ca80dbb014ee6a513b5e6cceb485904e19b2ff
/mycop/src/main/java/com/gever/sysman/basedata/impl/DB2CommandImpl.java
d86f6c1cd03a3e7980a3c95104d8778a14434089
[]
no_license
myosmatrix/mycop
https://github.com/myosmatrix/mycop
3fbc1e243dfbb32fe9c4b3cef5f2bfa7d984f1f4
b1f0260ea8d21176ebc2fc06de47b523e22e27df
refs/heads/master
2021-05-29T13:10:02.076000
2010-09-11T15:23:34
2010-09-11T15:23:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gever.sysman.basedata.impl; import java.sql.*; import java.io.*; import com.gever.config.Constants; import com.gever.jdbc.connection.ConnectionProvider; import com.gever.jdbc.connection.ConnectionProviderFactory; import com.gever.sysman.basedata.DB2Command; import com.gever.sysman.basedata.DB2Export; public class DB2CommandImpl implements DB2Command { public DB2CommandImpl() { } public void exec(String[] tables, String filename) { ConnectionProvider cp = null; Connection conn = null; String[] ddls = null; try { cp = ConnectionProviderFactory.getConnectionProvider(Constants. DATA_SOURCE); conn = cp.getConnection(); DB2Export db2Export = new DB2Export(conn); if (tables == null) { tables = db2Export.getTablesWithSchema(true); } ddls = db2Export.buildAllInsertStatement(tables, true, ";", true, false); writeDdlFile(ddls, filename); } catch (Exception e) { e.printStackTrace(); } } private static void writeDdlFile(String[] ddls, String filename) { PrintWriter pw = null; try { pw = new PrintWriter(new FileOutputStream(filename)); for (int i = 0; i < ddls.length; i++) { pw.println(ddls[i]); } pw.close(); } catch (FileNotFoundException ex) { } } }
UTF-8
Java
1,380
java
DB2CommandImpl.java
Java
[]
null
[]
package com.gever.sysman.basedata.impl; import java.sql.*; import java.io.*; import com.gever.config.Constants; import com.gever.jdbc.connection.ConnectionProvider; import com.gever.jdbc.connection.ConnectionProviderFactory; import com.gever.sysman.basedata.DB2Command; import com.gever.sysman.basedata.DB2Export; public class DB2CommandImpl implements DB2Command { public DB2CommandImpl() { } public void exec(String[] tables, String filename) { ConnectionProvider cp = null; Connection conn = null; String[] ddls = null; try { cp = ConnectionProviderFactory.getConnectionProvider(Constants. DATA_SOURCE); conn = cp.getConnection(); DB2Export db2Export = new DB2Export(conn); if (tables == null) { tables = db2Export.getTablesWithSchema(true); } ddls = db2Export.buildAllInsertStatement(tables, true, ";", true, false); writeDdlFile(ddls, filename); } catch (Exception e) { e.printStackTrace(); } } private static void writeDdlFile(String[] ddls, String filename) { PrintWriter pw = null; try { pw = new PrintWriter(new FileOutputStream(filename)); for (int i = 0; i < ddls.length; i++) { pw.println(ddls[i]); } pw.close(); } catch (FileNotFoundException ex) { } } }
1,380
0.644928
0.636957
48
26.791666
20.909487
79
false
false
0
0
0
0
0
0
0.666667
false
false
11
d383766103da095a2706a3cf8abba1625cfc622f
5,669,356,882,170
cb7ca0dbcf976c2d547da93866b3fa86039773fb
/src/main/java/com/wechat/jfinal/model/base/BaseRobotExpression.java
e4c6646aa71e7a08225875fdc4580528989f7059
[]
no_license
alive-jh/Alive
https://github.com/alive-jh/Alive
a18850830a508483d4950b0e10026996eab0601b
0a5f32930546af6ebcd271171fb68366709337e3
refs/heads/main
2023-08-28T18:15:37.107000
2021-10-25T08:28:54
2021-10-25T08:28:54
420,863,338
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wechat.jfinal.model.base; import com.jfinal.plugin.activerecord.Model; import com.jfinal.plugin.activerecord.IBean; /** * Generated by JFinal, do not modify this file. */ @SuppressWarnings({"serial", "unchecked"}) public abstract class BaseRobotExpression<M extends BaseRobotExpression<M>> extends Model<M> implements IBean { public M setId(java.lang.Integer id) { set("id", id); return (M)this; } public java.lang.Integer getId() { return getInt("id"); } public M setName(java.lang.String name) { set("name", name); return (M)this; } public java.lang.String getName() { return getStr("name"); } public M setText(java.lang.String text) { set("text", text); return (M)this; } public java.lang.String getText() { return getStr("text"); } public M setImageUrl(java.lang.String imageUrl) { set("image_url", imageUrl); return (M)this; } public java.lang.String getImageUrl() { return getStr("image_url"); } public M setActionCmd(java.lang.String actionCmd) { set("actionCmd", actionCmd); return (M)this; } public java.lang.String getActionCmd() { return getStr("actionCmd"); } public M setInsertTime(java.util.Date insertTime) { set("insert_time", insertTime); return (M)this; } public java.util.Date getInsertTime() { return get("insert_time"); } }
UTF-8
Java
1,334
java
BaseRobotExpression.java
Java
[]
null
[]
package com.wechat.jfinal.model.base; import com.jfinal.plugin.activerecord.Model; import com.jfinal.plugin.activerecord.IBean; /** * Generated by JFinal, do not modify this file. */ @SuppressWarnings({"serial", "unchecked"}) public abstract class BaseRobotExpression<M extends BaseRobotExpression<M>> extends Model<M> implements IBean { public M setId(java.lang.Integer id) { set("id", id); return (M)this; } public java.lang.Integer getId() { return getInt("id"); } public M setName(java.lang.String name) { set("name", name); return (M)this; } public java.lang.String getName() { return getStr("name"); } public M setText(java.lang.String text) { set("text", text); return (M)this; } public java.lang.String getText() { return getStr("text"); } public M setImageUrl(java.lang.String imageUrl) { set("image_url", imageUrl); return (M)this; } public java.lang.String getImageUrl() { return getStr("image_url"); } public M setActionCmd(java.lang.String actionCmd) { set("actionCmd", actionCmd); return (M)this; } public java.lang.String getActionCmd() { return getStr("actionCmd"); } public M setInsertTime(java.util.Date insertTime) { set("insert_time", insertTime); return (M)this; } public java.util.Date getInsertTime() { return get("insert_time"); } }
1,334
0.691904
0.691904
66
19.212122
20.857754
111
false
false
0
0
0
0
0
0
1.348485
false
false
11
3bfd00d787ce016be929a1334f74d08ad4445ced
3,358,664,478,392
47951b04b66b6dc9222871778021ed2d4b746a4b
/backend/src/main/java/com/vm/xyz/app/exception/XyzExceptionHandler.java
c4c29784fb4b8aae0175cad3d4efed46002b5be8
[]
no_license
jingdrew/vendormachine
https://github.com/jingdrew/vendormachine
0d5cad63ed694eb5839f59ede6812cf29e49459b
501dee63ca8b3a0ff05c2b888e232a235379d977
refs/heads/master
2023-02-16T03:36:38.237000
2020-07-07T22:01:54
2020-07-07T22:01:54
277,200,672
0
0
null
false
2021-01-06T06:31:49
2020-07-04T23:33:52
2020-07-07T22:01:57
2021-01-06T06:31:48
304
0
0
1
Java
false
false
package com.vm.xyz.app.exception; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import java.text.ParseException; @ControllerAdvice public class XyzExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(value = NoDataFoundException.class) public ResponseEntity<Object> handleNoDataFoundException(NoDataFoundException e) { HttpStatus status = HttpStatus.NO_CONTENT; XyzException exception = new XyzException(e.getMessage(), status); return new ResponseEntity<>(exception, status); } @ExceptionHandler(value = BadRequestException.class) public ResponseEntity<Object> handleBadRequestException(BadRequestException e) { HttpStatus status = HttpStatus.BAD_REQUEST; XyzException exception = new XyzException(e.getMessage(), status); return new ResponseEntity<>(exception, status); } @ExceptionHandler(value = ForbiddenException.class) public ResponseEntity<Object> handleForbiddenException(ForbiddenException e) { HttpStatus status = HttpStatus.FORBIDDEN; XyzException exception = new XyzException(e.getMessage(), status); return new ResponseEntity<>(exception, status); } @ExceptionHandler(value = UnauthorizedException.class) public ResponseEntity<Object> handleUnauthorizedException(UnauthorizedException e) { HttpStatus status = HttpStatus.UNAUTHORIZED; XyzException exception = new XyzException(e.getMessage(), status); return new ResponseEntity<>(exception, status); } @ExceptionHandler(value = ParseException.class) public ResponseEntity<Object> handleParseException(ParseException e) { HttpStatus status = HttpStatus.BAD_REQUEST; XyzException exception = new XyzException(e.getMessage(), status); return new ResponseEntity<>(exception, status); } }
UTF-8
Java
2,128
java
XyzExceptionHandler.java
Java
[]
null
[]
package com.vm.xyz.app.exception; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import java.text.ParseException; @ControllerAdvice public class XyzExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(value = NoDataFoundException.class) public ResponseEntity<Object> handleNoDataFoundException(NoDataFoundException e) { HttpStatus status = HttpStatus.NO_CONTENT; XyzException exception = new XyzException(e.getMessage(), status); return new ResponseEntity<>(exception, status); } @ExceptionHandler(value = BadRequestException.class) public ResponseEntity<Object> handleBadRequestException(BadRequestException e) { HttpStatus status = HttpStatus.BAD_REQUEST; XyzException exception = new XyzException(e.getMessage(), status); return new ResponseEntity<>(exception, status); } @ExceptionHandler(value = ForbiddenException.class) public ResponseEntity<Object> handleForbiddenException(ForbiddenException e) { HttpStatus status = HttpStatus.FORBIDDEN; XyzException exception = new XyzException(e.getMessage(), status); return new ResponseEntity<>(exception, status); } @ExceptionHandler(value = UnauthorizedException.class) public ResponseEntity<Object> handleUnauthorizedException(UnauthorizedException e) { HttpStatus status = HttpStatus.UNAUTHORIZED; XyzException exception = new XyzException(e.getMessage(), status); return new ResponseEntity<>(exception, status); } @ExceptionHandler(value = ParseException.class) public ResponseEntity<Object> handleParseException(ParseException e) { HttpStatus status = HttpStatus.BAD_REQUEST; XyzException exception = new XyzException(e.getMessage(), status); return new ResponseEntity<>(exception, status); } }
2,128
0.761748
0.761748
48
43.333332
30.111137
92
false
false
0
0
0
0
0
0
0.666667
false
false
11
777e83f8a3bc900ade1f614215f5e99109ee8573
17,463,337,057,247
f916d9cc1cb2a1da961d5f1b59916920cf2e080e
/src/com/sxca/myb/modules/config/corporcode/web/CorporcodeController.java
ebc4551757177ec32389b17aebc6dfc78ee965bd
[]
no_license
iikspiral/myb
https://github.com/iikspiral/myb
cb90f392a51f15b9ee0cfe599b857f4bf2413088
0c3bf05838e94b0a458f63148f485d4b16c6dae7
refs/heads/master
2021-09-15T11:00:57.508000
2018-05-31T06:03:24
2018-05-31T06:03:24
135,524,109
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sxca.myb.modules.config.corporcode.web; import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.sxca.myb.common.persistence.Page; import com.sxca.myb.common.utils.StringUtils; import com.sxca.myb.common.web.BaseController; import com.sxca.myb.modules.cert.entity.CertInfo; import com.sxca.myb.modules.cert.entity.CertapplyInfo; import com.sxca.myb.modules.cert.service.CertInfoService; import com.sxca.myb.modules.cert.service.CertapplyInfoService; import com.sxca.myb.modules.config.corporcode.entity.CorporationRequestCode; import com.sxca.myb.modules.config.corporcode.service.CorporcodeService; import com.sxca.myb.modules.config.corporcode.util.CorporcodeVo; import com.sxca.myb.modules.config.corporcode.vo.CorporationRequestCodeVo; import com.sxca.myb.modules.idinfo.entity.CorporationInfo; import com.sxca.myb.modules.idinfo.entity.CorporationUserRelation; import com.sxca.myb.modules.idinfo.service.CorporationInfoService; import com.sxca.myb.modules.idinfo.service.CorporationUserRelationnService; import com.sxca.myb.modules.mobile.service.MobileService; import com.sxca.myb.modules.pro.entity.ProjectInfo; import com.sxca.myb.modules.pro.service.ProjectInfoService; /** * @author lihuilong * @date : 2017年4月14日 上午9:44:44 */ @Controller @RequestMapping(value = "${adminPath}/corporcode") public class CorporcodeController extends BaseController { @Autowired private CorporcodeService corporcodeService; @Autowired private CorporationInfoService corporationInfoService; @Autowired private CertInfoService certInfoService; @Autowired private CertapplyInfoService certapplyInfoService; @Autowired private CorporationUserRelationnService corporationUserRelationnService; @Autowired private ProjectInfoService projectInfoService; @Autowired private MobileService mobileService; @RequestMapping(value = "list") public String corporCodeList(CorporationRequestCode entity,String clickType, HttpServletRequest request, HttpServletResponse response, Model model) { //通过clickType 来对查询实体entity 进行赋值 clickType = 1 代表界面查询操作,进行赋值 if(StringUtils.isNotBlank(clickType) && ("1").equals(clickType)){ CorporationRequestCodeVo corporationRequestCodeVo = new CorporationRequestCodeVo(); corporationRequestCodeVo.setProjectId(entity.getProjectId()); corporationRequestCodeVo.setCorporationId(entity.getCorporationId()); corporationRequestCodeVo.setCorporUserId(entity.getCorporUserId()); corporationRequestCodeVo.setCertSubject(entity.getCertSubject()); corporationRequestCodeVo.setType(entity.getType()); corporationRequestCodeVo.setStatus(entity.getStatus()); request.getSession().setAttribute("corporationRequestCodeVo", corporationRequestCodeVo); model.addAttribute("corporationRequestCodeVo", corporationRequestCodeVo); }else if(StringUtils.isNotBlank(clickType) && ("2").equals(clickType)){ CorporationRequestCodeVo corporationRequestCodeVo = (CorporationRequestCodeVo) request.getSession().getAttribute("corporationRequestCodeVo"); entity.setProjectId(corporationRequestCodeVo.getProjectId()); entity.setCorporationId(corporationRequestCodeVo.getCorporationId()); entity.setCorporUserId(corporationRequestCodeVo.getCorporUserId()); entity.setCertSubject(corporationRequestCodeVo.getCertSubject()); entity.setType(corporationRequestCodeVo.getType()); entity.setStatus(corporationRequestCodeVo.getStatus()); model.addAttribute("corporationRequestCodeVo", corporationRequestCodeVo); }else{ request.getSession().setAttribute("corporationRequestCodeVo", new CorporationRequestCodeVo()); } Page<CorporationRequestCode> page = corporcodeService.findPage( new Page<CorporationRequestCode>(request, response), entity); model.addAttribute("page", page); return "modules/config/corporcode/corporcodeList"; } @RequestMapping(value = "form") private String index(CorporationRequestCode entity, HttpServletRequest request, HttpServletResponse response, Model model) { entity = new CorporationRequestCode(); String sessionid = request.getSession().getId(); model.addAttribute("sessionid", sessionid); model.addAttribute("corporationRequestCode", entity); return "modules/config/corporcode/form"; } @RequestMapping(value = "edit") private String edit(CorporationRequestCode entity, HttpServletRequest request, HttpServletResponse response, Model model) { entity = corporcodeService.get(entity.getId()); String sessionid = request.getSession().getId(); model.addAttribute("sessionid", sessionid); model.addAttribute("corporationRequestCode", entity); return "modules/config/corporcode/edit"; } @RequestMapping(value = "corList") private String corList(CorporcodeVo corporcodeVo, HttpServletRequest request, HttpServletResponse response, Model model) { String ids=""; //证书新制,个人白名单 选则用户时,需要对未添加过的企业用户过滤,如该企业用户已存在证书,证书状态为正在使用,也需要对该类型用户进行过滤 //获取到企业与企业用户中间表id,企业白名单中已添加,取到现在生效的白名单 String checkIds = corporcodeService.fingCheckIds(corporcodeVo .getProjectId()); //去查询一下 当前项目下,正在使用的证书 String resulIds = corporcodeService.getCorpuseridsByProid(corporcodeVo .getProjectId()); if(StringUtils.isNotBlank(checkIds)){ ids += checkIds; } if(StringUtils.isNotBlank(resulIds)){ ids += resulIds; } List<String> result = null; if (StringUtils.isNotBlank(ids)) { result = Arrays.asList(ids.split(",")); } CorporationInfo corporationInfo = new CorporationInfo(); if(StringUtils.isNotBlank(corporcodeVo.getCorpname())){ corporationInfo.setCorpname(corporcodeVo.getCorpname()); } corporationInfo.setStrList(result); Page<CorporationInfo> page = new Page<CorporationInfo>(request, response); corporationInfo.setPage(page); page.setList(corporationInfoService.findProUserlist(corporationInfo)); model.addAttribute("page", page); model.addAttribute("corporcodeVo", corporcodeVo); return "modules/config/corporcode/corList"; } @RequestMapping(value = "certList") private String certList(CorporcodeVo corporcodeVo, HttpServletRequest request, HttpServletResponse response, Model model) { List<String> result = null; String checkCerts = corporcodeService.fingCheckCerts(); if (checkCerts != null) { result = Arrays.asList(checkCerts.split(",")); } CertInfo certInfo = new CertInfo(); certInfo.setCertList(result); certInfo.setCertStatus("Use"); certInfo.setCertType("corporation_info"); CertapplyInfo certapplyInfo = new CertapplyInfo(); certInfo.setCertapplyInfo(certapplyInfo); if(StringUtils.isNotBlank(corporcodeVo.getCertSubject())){ certInfo.setCertSubject(corporcodeVo.getCertSubject()); } Page<CertInfo> page = certInfoService.findPage(new Page<CertInfo>( request, response), certInfo); model.addAttribute("page", page); model.addAttribute("corporcodeVo", corporcodeVo); return "modules/config/corporcode/certList"; } @RequestMapping(value = "save") public String corporCodeSave(CorporationRequestCode entity, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) { if (corporcodeService.saveCorpor(entity)) { addMessage(redirectAttributes, "保存成功"); } else { addMessage(redirectAttributes, "保存失败"); } return "redirect:" + adminPath + "/corporcode/list/?repage"; } @RequestMapping(value = "updateSave") public String updateSave(CorporationRequestCode entity, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) { if ("1".equals(entity.getType())) { // 判断是否为变更,如果为变更,需从申请信息表中查询相关用户id 插入到表中 CertapplyInfo certapplyInfo = new CertapplyInfo(); certapplyInfo.setCertSn(entity.getCertSn()); List<CertapplyInfo> certApplyList = certapplyInfoService .findList(certapplyInfo); if (certApplyList != null && certApplyList.size() > 0) { entity.setCorporationId(certApplyList.get(0).getUserInfoId()); entity.setCorporUserId(certApplyList.get(0).getCorpUserId()); // 判断项目是否为空,如果为空,去证书申请表中通过证书序列号查询项目id if (StringUtils.isBlank(entity.getProjectId())) { entity.setProjectId(certApplyList.get(0).getProjectId()); } else { entity.setProjectId(entity.getProjectId()); } } } else { if (StringUtils.isNotBlank(entity.getCorporUserRelaId())) { // 企业与企业用户中间表 CorporationUserRelation corporationUserRelation = corporationUserRelationnService .get(entity.getCorporUserRelaId()); entity.setCorporationId(corporationUserRelation .getCorporationId()); entity.setCorporUserId(corporationUserRelation .getCorporationUserId()); } } corporcodeService.update(entity); addMessage(redirectAttributes, "保存成功"); return "redirect:" + adminPath + "/corporcode/list/?repage"; } @RequestMapping(value = "delete") public String corporCodeDelete(CorporationRequestCode entity, RedirectAttributes redirectAttributes) { corporcodeService.delete(entity); addMessage(redirectAttributes, "删除成功"); return "redirect:" + adminPath + "/corporcode/list/?repage"; } @RequestMapping(value = "getCor") @ResponseBody public CorporationInfo getCor(String corId, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) { CorporationInfo corporationInfo = corporationInfoService.get(corId); return corporationInfo; } @RequestMapping(value = "getCert") @ResponseBody public CertInfo getCert(String certSn, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) { CertInfo certInfo = certInfoService.get(certSn); return certInfo; } /** * * @param request * @param response * @param model * @param corporationId * 前台选中ids * @return */ @RequestMapping(value = "corporlist") public String certlist(HttpServletRequest request, HttpServletResponse response, Model model, String corporationId) { if (StringUtils.isNoneBlank(corporationId)) { List<String> result = null; result = Arrays.asList(corporationId.split(",")); List<CorporationInfo> corporList = corporationInfoService .fingByids(result); model.addAttribute("corporList", corporList); } else { model.addAttribute("corporList", null); } return "modules/config/corporcode/corselectList"; } /** * * @param request * @param response * @param model * @param corporationId * 前台选中ids * @return */ @RequestMapping(value = "certSelectlist") public String certSelectlist(HttpServletRequest request, HttpServletResponse response, Model model, String certSn) { if (StringUtils.isNoneBlank(certSn)) { List<String> result = null; result = Arrays.asList(certSn.split(",")); List<CertInfo> certList = certInfoService.fingByids(result); model.addAttribute("certList", certList); } else { model.addAttribute("certList", null); } return "modules/config/corporcode/certselectList"; } @RequestMapping(value = "checkUniqueCorpuser") @ResponseBody public Boolean checkUniqueCorpuser(String id, String corporUserRelaId, String projectId, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) { CorporationRequestCode corporationRequestCode = corporcodeService .get(id); if (corporationRequestCode != null) { if (corporUserRelaId.equals(corporationRequestCode.getCorporUserRelaId()) && projectId.equals(corporationRequestCode.getProjectId())) { return true; } else { CorporationRequestCode entity = new CorporationRequestCode(); entity.setCorporUserRelaId(corporUserRelaId); entity.setProjectId(projectId); entity.setStatus("0"); List<CorporationRequestCode> list = corporcodeService.findList(entity); List<CertInfo> certInfos = null; CorporationUserRelation corporationUserRelation = corporationUserRelationnService.get(corporUserRelaId); if(corporationUserRelation != null) { certInfos = corporcodeService.getStatus(projectId, corporationUserRelation.getCorporationUserId()); } if (list != null && list.size() > 0) { return false; } else { if(certInfos!=null && certInfos.size()>0) { return false; }else { return true; } } } } else { return true; } } @RequestMapping(value = "checkUniqueCert") @ResponseBody public Boolean checkUniqueCert(String id, String certSn, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) { CorporationRequestCode corporationRequestCode = corporcodeService .get(id); if (corporationRequestCode != null) { if (certSn.equals(corporationRequestCode.getCertSn())) { return true; } else { CorporationRequestCode entity = new CorporationRequestCode(); entity.setStatus("0"); entity.setCertSn(certSn); List<CorporationRequestCode> list = corporcodeService .findList(entity); if (list != null && list.size() > 0) { return false; } else { return true; } } } else { return true; } } /**author:wyf * description:页面提示信息校验。 * @param userInfoId * @param entity * @param model * @param request * @param response * @param redirectAttributes * @return */ @RequestMapping(value = "Judgement") @ResponseBody public String showUser(String userInfoId,String projectInfoId,Model model ,String certSn, HttpServletRequest request,HttpServletResponse response) { String isOK = null; try { if(userInfoId!=null && !"".equals(userInfoId)){ isOK="OK"; }else if(StringUtils.isNotBlank(certSn)){ String[] certsn=certSn.split(","); for(String cert : certsn){ if(StringUtils.isNotBlank(cert)){ CertapplyInfo certapplyInfo = new CertapplyInfo(); certapplyInfo.setCertSn(cert); List<CertapplyInfo> certapplyInfolist=certapplyInfoService.findbyList(certapplyInfo); if(certapplyInfolist!=null && certapplyInfolist.size()>0){ String Pid=certapplyInfolist.get(0).getProjectId(); if(Pid!=null && !"".equals(Pid) && projectInfoId!=null && !"".equals(projectInfoId) && !Pid.equals(projectInfoId) ){ isOK = "fail"; return isOK; } } } isOK="OK"; } } // -------------------------- } catch (Exception e) { isOK = "fail"; e.getStackTrace(); } return isOK; } }
UTF-8
Java
15,236
java
CorporcodeController.java
Java
[ { "context": "es.pro.service.ProjectInfoService;\n\n/**\n * @author lihuilong\n * @date : 2017年4月14日 上午9:44:44\n */\n@Controller\n@", "end": 1660, "score": 0.9942060708999634, "start": 1651, "tag": "USERNAME", "value": "lihuilong" }, { "context": "}\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\n\t}\n\t\n\t/**author:wyf\n\t * description:页面提示信息校验。\n\t * @param userInfoId\n\t", "end": 13419, "score": 0.9994229078292847, "start": 13416, "tag": "USERNAME", "value": "wyf" } ]
null
[]
package com.sxca.myb.modules.config.corporcode.web; import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.sxca.myb.common.persistence.Page; import com.sxca.myb.common.utils.StringUtils; import com.sxca.myb.common.web.BaseController; import com.sxca.myb.modules.cert.entity.CertInfo; import com.sxca.myb.modules.cert.entity.CertapplyInfo; import com.sxca.myb.modules.cert.service.CertInfoService; import com.sxca.myb.modules.cert.service.CertapplyInfoService; import com.sxca.myb.modules.config.corporcode.entity.CorporationRequestCode; import com.sxca.myb.modules.config.corporcode.service.CorporcodeService; import com.sxca.myb.modules.config.corporcode.util.CorporcodeVo; import com.sxca.myb.modules.config.corporcode.vo.CorporationRequestCodeVo; import com.sxca.myb.modules.idinfo.entity.CorporationInfo; import com.sxca.myb.modules.idinfo.entity.CorporationUserRelation; import com.sxca.myb.modules.idinfo.service.CorporationInfoService; import com.sxca.myb.modules.idinfo.service.CorporationUserRelationnService; import com.sxca.myb.modules.mobile.service.MobileService; import com.sxca.myb.modules.pro.entity.ProjectInfo; import com.sxca.myb.modules.pro.service.ProjectInfoService; /** * @author lihuilong * @date : 2017年4月14日 上午9:44:44 */ @Controller @RequestMapping(value = "${adminPath}/corporcode") public class CorporcodeController extends BaseController { @Autowired private CorporcodeService corporcodeService; @Autowired private CorporationInfoService corporationInfoService; @Autowired private CertInfoService certInfoService; @Autowired private CertapplyInfoService certapplyInfoService; @Autowired private CorporationUserRelationnService corporationUserRelationnService; @Autowired private ProjectInfoService projectInfoService; @Autowired private MobileService mobileService; @RequestMapping(value = "list") public String corporCodeList(CorporationRequestCode entity,String clickType, HttpServletRequest request, HttpServletResponse response, Model model) { //通过clickType 来对查询实体entity 进行赋值 clickType = 1 代表界面查询操作,进行赋值 if(StringUtils.isNotBlank(clickType) && ("1").equals(clickType)){ CorporationRequestCodeVo corporationRequestCodeVo = new CorporationRequestCodeVo(); corporationRequestCodeVo.setProjectId(entity.getProjectId()); corporationRequestCodeVo.setCorporationId(entity.getCorporationId()); corporationRequestCodeVo.setCorporUserId(entity.getCorporUserId()); corporationRequestCodeVo.setCertSubject(entity.getCertSubject()); corporationRequestCodeVo.setType(entity.getType()); corporationRequestCodeVo.setStatus(entity.getStatus()); request.getSession().setAttribute("corporationRequestCodeVo", corporationRequestCodeVo); model.addAttribute("corporationRequestCodeVo", corporationRequestCodeVo); }else if(StringUtils.isNotBlank(clickType) && ("2").equals(clickType)){ CorporationRequestCodeVo corporationRequestCodeVo = (CorporationRequestCodeVo) request.getSession().getAttribute("corporationRequestCodeVo"); entity.setProjectId(corporationRequestCodeVo.getProjectId()); entity.setCorporationId(corporationRequestCodeVo.getCorporationId()); entity.setCorporUserId(corporationRequestCodeVo.getCorporUserId()); entity.setCertSubject(corporationRequestCodeVo.getCertSubject()); entity.setType(corporationRequestCodeVo.getType()); entity.setStatus(corporationRequestCodeVo.getStatus()); model.addAttribute("corporationRequestCodeVo", corporationRequestCodeVo); }else{ request.getSession().setAttribute("corporationRequestCodeVo", new CorporationRequestCodeVo()); } Page<CorporationRequestCode> page = corporcodeService.findPage( new Page<CorporationRequestCode>(request, response), entity); model.addAttribute("page", page); return "modules/config/corporcode/corporcodeList"; } @RequestMapping(value = "form") private String index(CorporationRequestCode entity, HttpServletRequest request, HttpServletResponse response, Model model) { entity = new CorporationRequestCode(); String sessionid = request.getSession().getId(); model.addAttribute("sessionid", sessionid); model.addAttribute("corporationRequestCode", entity); return "modules/config/corporcode/form"; } @RequestMapping(value = "edit") private String edit(CorporationRequestCode entity, HttpServletRequest request, HttpServletResponse response, Model model) { entity = corporcodeService.get(entity.getId()); String sessionid = request.getSession().getId(); model.addAttribute("sessionid", sessionid); model.addAttribute("corporationRequestCode", entity); return "modules/config/corporcode/edit"; } @RequestMapping(value = "corList") private String corList(CorporcodeVo corporcodeVo, HttpServletRequest request, HttpServletResponse response, Model model) { String ids=""; //证书新制,个人白名单 选则用户时,需要对未添加过的企业用户过滤,如该企业用户已存在证书,证书状态为正在使用,也需要对该类型用户进行过滤 //获取到企业与企业用户中间表id,企业白名单中已添加,取到现在生效的白名单 String checkIds = corporcodeService.fingCheckIds(corporcodeVo .getProjectId()); //去查询一下 当前项目下,正在使用的证书 String resulIds = corporcodeService.getCorpuseridsByProid(corporcodeVo .getProjectId()); if(StringUtils.isNotBlank(checkIds)){ ids += checkIds; } if(StringUtils.isNotBlank(resulIds)){ ids += resulIds; } List<String> result = null; if (StringUtils.isNotBlank(ids)) { result = Arrays.asList(ids.split(",")); } CorporationInfo corporationInfo = new CorporationInfo(); if(StringUtils.isNotBlank(corporcodeVo.getCorpname())){ corporationInfo.setCorpname(corporcodeVo.getCorpname()); } corporationInfo.setStrList(result); Page<CorporationInfo> page = new Page<CorporationInfo>(request, response); corporationInfo.setPage(page); page.setList(corporationInfoService.findProUserlist(corporationInfo)); model.addAttribute("page", page); model.addAttribute("corporcodeVo", corporcodeVo); return "modules/config/corporcode/corList"; } @RequestMapping(value = "certList") private String certList(CorporcodeVo corporcodeVo, HttpServletRequest request, HttpServletResponse response, Model model) { List<String> result = null; String checkCerts = corporcodeService.fingCheckCerts(); if (checkCerts != null) { result = Arrays.asList(checkCerts.split(",")); } CertInfo certInfo = new CertInfo(); certInfo.setCertList(result); certInfo.setCertStatus("Use"); certInfo.setCertType("corporation_info"); CertapplyInfo certapplyInfo = new CertapplyInfo(); certInfo.setCertapplyInfo(certapplyInfo); if(StringUtils.isNotBlank(corporcodeVo.getCertSubject())){ certInfo.setCertSubject(corporcodeVo.getCertSubject()); } Page<CertInfo> page = certInfoService.findPage(new Page<CertInfo>( request, response), certInfo); model.addAttribute("page", page); model.addAttribute("corporcodeVo", corporcodeVo); return "modules/config/corporcode/certList"; } @RequestMapping(value = "save") public String corporCodeSave(CorporationRequestCode entity, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) { if (corporcodeService.saveCorpor(entity)) { addMessage(redirectAttributes, "保存成功"); } else { addMessage(redirectAttributes, "保存失败"); } return "redirect:" + adminPath + "/corporcode/list/?repage"; } @RequestMapping(value = "updateSave") public String updateSave(CorporationRequestCode entity, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) { if ("1".equals(entity.getType())) { // 判断是否为变更,如果为变更,需从申请信息表中查询相关用户id 插入到表中 CertapplyInfo certapplyInfo = new CertapplyInfo(); certapplyInfo.setCertSn(entity.getCertSn()); List<CertapplyInfo> certApplyList = certapplyInfoService .findList(certapplyInfo); if (certApplyList != null && certApplyList.size() > 0) { entity.setCorporationId(certApplyList.get(0).getUserInfoId()); entity.setCorporUserId(certApplyList.get(0).getCorpUserId()); // 判断项目是否为空,如果为空,去证书申请表中通过证书序列号查询项目id if (StringUtils.isBlank(entity.getProjectId())) { entity.setProjectId(certApplyList.get(0).getProjectId()); } else { entity.setProjectId(entity.getProjectId()); } } } else { if (StringUtils.isNotBlank(entity.getCorporUserRelaId())) { // 企业与企业用户中间表 CorporationUserRelation corporationUserRelation = corporationUserRelationnService .get(entity.getCorporUserRelaId()); entity.setCorporationId(corporationUserRelation .getCorporationId()); entity.setCorporUserId(corporationUserRelation .getCorporationUserId()); } } corporcodeService.update(entity); addMessage(redirectAttributes, "保存成功"); return "redirect:" + adminPath + "/corporcode/list/?repage"; } @RequestMapping(value = "delete") public String corporCodeDelete(CorporationRequestCode entity, RedirectAttributes redirectAttributes) { corporcodeService.delete(entity); addMessage(redirectAttributes, "删除成功"); return "redirect:" + adminPath + "/corporcode/list/?repage"; } @RequestMapping(value = "getCor") @ResponseBody public CorporationInfo getCor(String corId, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) { CorporationInfo corporationInfo = corporationInfoService.get(corId); return corporationInfo; } @RequestMapping(value = "getCert") @ResponseBody public CertInfo getCert(String certSn, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) { CertInfo certInfo = certInfoService.get(certSn); return certInfo; } /** * * @param request * @param response * @param model * @param corporationId * 前台选中ids * @return */ @RequestMapping(value = "corporlist") public String certlist(HttpServletRequest request, HttpServletResponse response, Model model, String corporationId) { if (StringUtils.isNoneBlank(corporationId)) { List<String> result = null; result = Arrays.asList(corporationId.split(",")); List<CorporationInfo> corporList = corporationInfoService .fingByids(result); model.addAttribute("corporList", corporList); } else { model.addAttribute("corporList", null); } return "modules/config/corporcode/corselectList"; } /** * * @param request * @param response * @param model * @param corporationId * 前台选中ids * @return */ @RequestMapping(value = "certSelectlist") public String certSelectlist(HttpServletRequest request, HttpServletResponse response, Model model, String certSn) { if (StringUtils.isNoneBlank(certSn)) { List<String> result = null; result = Arrays.asList(certSn.split(",")); List<CertInfo> certList = certInfoService.fingByids(result); model.addAttribute("certList", certList); } else { model.addAttribute("certList", null); } return "modules/config/corporcode/certselectList"; } @RequestMapping(value = "checkUniqueCorpuser") @ResponseBody public Boolean checkUniqueCorpuser(String id, String corporUserRelaId, String projectId, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) { CorporationRequestCode corporationRequestCode = corporcodeService .get(id); if (corporationRequestCode != null) { if (corporUserRelaId.equals(corporationRequestCode.getCorporUserRelaId()) && projectId.equals(corporationRequestCode.getProjectId())) { return true; } else { CorporationRequestCode entity = new CorporationRequestCode(); entity.setCorporUserRelaId(corporUserRelaId); entity.setProjectId(projectId); entity.setStatus("0"); List<CorporationRequestCode> list = corporcodeService.findList(entity); List<CertInfo> certInfos = null; CorporationUserRelation corporationUserRelation = corporationUserRelationnService.get(corporUserRelaId); if(corporationUserRelation != null) { certInfos = corporcodeService.getStatus(projectId, corporationUserRelation.getCorporationUserId()); } if (list != null && list.size() > 0) { return false; } else { if(certInfos!=null && certInfos.size()>0) { return false; }else { return true; } } } } else { return true; } } @RequestMapping(value = "checkUniqueCert") @ResponseBody public Boolean checkUniqueCert(String id, String certSn, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) { CorporationRequestCode corporationRequestCode = corporcodeService .get(id); if (corporationRequestCode != null) { if (certSn.equals(corporationRequestCode.getCertSn())) { return true; } else { CorporationRequestCode entity = new CorporationRequestCode(); entity.setStatus("0"); entity.setCertSn(certSn); List<CorporationRequestCode> list = corporcodeService .findList(entity); if (list != null && list.size() > 0) { return false; } else { return true; } } } else { return true; } } /**author:wyf * description:页面提示信息校验。 * @param userInfoId * @param entity * @param model * @param request * @param response * @param redirectAttributes * @return */ @RequestMapping(value = "Judgement") @ResponseBody public String showUser(String userInfoId,String projectInfoId,Model model ,String certSn, HttpServletRequest request,HttpServletResponse response) { String isOK = null; try { if(userInfoId!=null && !"".equals(userInfoId)){ isOK="OK"; }else if(StringUtils.isNotBlank(certSn)){ String[] certsn=certSn.split(","); for(String cert : certsn){ if(StringUtils.isNotBlank(cert)){ CertapplyInfo certapplyInfo = new CertapplyInfo(); certapplyInfo.setCertSn(cert); List<CertapplyInfo> certapplyInfolist=certapplyInfoService.findbyList(certapplyInfo); if(certapplyInfolist!=null && certapplyInfolist.size()>0){ String Pid=certapplyInfolist.get(0).getProjectId(); if(Pid!=null && !"".equals(Pid) && projectInfoId!=null && !"".equals(projectInfoId) && !Pid.equals(projectInfoId) ){ isOK = "fail"; return isOK; } } } isOK="OK"; } } // -------------------------- } catch (Exception e) { isOK = "fail"; e.getStackTrace(); } return isOK; } }
15,236
0.750611
0.748778
452
31.575222
26.241747
144
false
false
0
0
0
0
0
0
2.581858
false
false
11
4039b761d1d645c7a8aa5714262650d3c5212998
13,322,988,605,222
ff30d5901b033b8379bd90374b512d6ae340bc46
/cmdb4j-core/src/test/java/org/cmdb4j/core/command/ResourceCommandRegistryTest.java
2123294a9a2f3a94e8facd26db0c619e1c20acdc
[]
no_license
Arnaud-Nauwynck/cmdb4j
https://github.com/Arnaud-Nauwynck/cmdb4j
0c57562f4bf6c802125a536ca966fa4607468da7
b3980716412af59cb5342357e5e33c39ca4daac4
refs/heads/master
2022-04-27T20:25:23.654000
2018-05-31T06:08:59
2018-06-04T06:44:58
33,074,922
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.cmdb4j.core.command; import java.util.List; import org.cmdb4j.core.model.reflect.ResourceTypeRepository; import org.cmdb4j.core.tst.TomcatJvmProcessResourceTypesMock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class ResourceCommandRegistryTest { ResourceTypeRepository resourceTypeRepository; TomcatJvmProcessResourceTypesMock tcTypesMock; ResourceCommandRegistry sut; @Before public void setup() { resourceTypeRepository = new ResourceTypeRepository(); tcTypesMock = new TomcatJvmProcessResourceTypesMock(resourceTypeRepository); sut = new ResourceCommandRegistry(resourceTypeRepository); ResourceCommandsMock.scanRegisterMockMethods(sut, resourceTypeRepository); } @Test public void testFindByTypeHierarchy() { // Prepare // Perform List<ResourceCommand> res = sut.findByTypeHierarchy(tcTypesMock.tomcatType); // Post-check Assert.assertNotNull(res); Assert.assertEquals(7, res.size()); Assert.assertEquals("Tomcat.start", res.get(0).toString()); Assert.assertEquals("Tomcat.start_sleep", res.get(1).toString()); Assert.assertEquals("Tomcat.start_sleep_default", res.get(2).toString()); Assert.assertEquals("Tomcat.stop", res.get(3).toString()); Assert.assertEquals("JvmProcess.threadsDump", res.get(4).toString()); Assert.assertEquals("Process.kill9Process", res.get(5).toString()); Assert.assertEquals("Process.killProcess", res.get(6).toString()); } }
UTF-8
Java
1,597
java
ResourceCommandRegistryTest.java
Java
[]
null
[]
package org.cmdb4j.core.command; import java.util.List; import org.cmdb4j.core.model.reflect.ResourceTypeRepository; import org.cmdb4j.core.tst.TomcatJvmProcessResourceTypesMock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class ResourceCommandRegistryTest { ResourceTypeRepository resourceTypeRepository; TomcatJvmProcessResourceTypesMock tcTypesMock; ResourceCommandRegistry sut; @Before public void setup() { resourceTypeRepository = new ResourceTypeRepository(); tcTypesMock = new TomcatJvmProcessResourceTypesMock(resourceTypeRepository); sut = new ResourceCommandRegistry(resourceTypeRepository); ResourceCommandsMock.scanRegisterMockMethods(sut, resourceTypeRepository); } @Test public void testFindByTypeHierarchy() { // Prepare // Perform List<ResourceCommand> res = sut.findByTypeHierarchy(tcTypesMock.tomcatType); // Post-check Assert.assertNotNull(res); Assert.assertEquals(7, res.size()); Assert.assertEquals("Tomcat.start", res.get(0).toString()); Assert.assertEquals("Tomcat.start_sleep", res.get(1).toString()); Assert.assertEquals("Tomcat.start_sleep_default", res.get(2).toString()); Assert.assertEquals("Tomcat.stop", res.get(3).toString()); Assert.assertEquals("JvmProcess.threadsDump", res.get(4).toString()); Assert.assertEquals("Process.kill9Process", res.get(5).toString()); Assert.assertEquals("Process.killProcess", res.get(6).toString()); } }
1,597
0.714465
0.706951
42
37.023811
28.598608
84
false
false
0
0
0
0
0
0
0.785714
false
false
11
c9d1771f21cf2d76638f72c848d46efee50f8916
12,756,052,915,296
964e072806c12c17f94ebde16147058619318fa9
/src/client/Test.java
71b0143d64c912eb8f85af36b24e991baed1e3ba
[]
no_license
ysyonline/selfTest
https://github.com/ysyonline/selfTest
72189d794666cafe7f6dff31b06416d697b8e7ee
8b32122a9c2a8e9da0233598ab9868bbda808ffb
refs/heads/master
2021-05-04T05:55:32.494000
2016-10-05T04:47:53
2016-10-05T04:47:53
70,045,166
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package client; import impl.CircelAdapter; import impl.EventEmitter; import impl.Rangle; import impl.TextCircle; import inter.Circle; import inter.EventService; import inter.EventHandler; import inter.Shape; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub // EventEmitter event = new EventEmitter(); // // event.on("click", new EventHandler() { // // @Override // public void callback(EventService e) { // // System.out.println("click..."); // // e.trigger("mouseover"); // } // }); // // event.on("mouseover", new EventHandler() { // // @Override // public void callback(EventService EventService) { // // System.out.println("mouseover..."); // } // }); // // event.trigger("click"); // //event.trigger("mouseover"); Test t = new Test(); Circle circle = new TextCircle(); CircelAdapter adapter = new CircelAdapter(circle); t.regist(adapter).draw(); } private Shape regist(Shape s){ return s; } }
UTF-8
Java
1,042
java
Test.java
Java
[]
null
[]
package client; import impl.CircelAdapter; import impl.EventEmitter; import impl.Rangle; import impl.TextCircle; import inter.Circle; import inter.EventService; import inter.EventHandler; import inter.Shape; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub // EventEmitter event = new EventEmitter(); // // event.on("click", new EventHandler() { // // @Override // public void callback(EventService e) { // // System.out.println("click..."); // // e.trigger("mouseover"); // } // }); // // event.on("mouseover", new EventHandler() { // // @Override // public void callback(EventService EventService) { // // System.out.println("mouseover..."); // } // }); // // event.trigger("click"); // //event.trigger("mouseover"); Test t = new Test(); Circle circle = new TextCircle(); CircelAdapter adapter = new CircelAdapter(circle); t.regist(adapter).draw(); } private Shape regist(Shape s){ return s; } }
1,042
0.626679
0.626679
58
16.931034
15.834121
54
false
false
0
0
0
0
0
0
2.103448
false
false
11
cccd259c9751de6f9c13ac8b3eaf9df3af5e9c0e
22,359,599,784,336
f9c637ab9501b0a68fa0d18a061cbd555abf1f79
/test/import-data/MarioConsumer/src/main/java/com/mario/consumer/MarioConsumer.java
b122ce91efc15f861724080dac926ff37b91e227
[]
no_license
minha361/leanHTMl
https://github.com/minha361/leanHTMl
c05000a6447b31f7869b75c532695ca2b0cd6968
dc760e7d149480c0b36f3c7064b97d0f3d4b3872
refs/heads/master
2022-06-01T02:54:46.048000
2020-08-11T03:20:34
2020-08-11T03:20:34
48,735,593
0
0
null
false
2022-05-20T20:49:57
2015-12-29T07:55:48
2020-08-11T03:20:36
2022-05-20T20:49:57
109,807
0
0
4
Java
false
false
package com.mario.consumer; import com.hazelcast.config.Config; import com.hazelcast.config.XmlConfigBuilder; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import com.mario.consumer.api.MarioApiFactory; import com.mario.consumer.entity.EntityManager; import com.mario.consumer.entity.handler.RequestController; import com.mario.consumer.extension.ExtensionManager; import com.mario.consumer.gateway.GatewayManager; import com.mario.consumer.schedule.impl.SchedulerFactory; import com.mario.consumer.solr.SolrClientConfig; import com.mario.consumer.solr.SolrClientManager; import com.nhb.common.db.sql.SQLDataSourceConfig; import com.nhb.common.db.sql.SQLDataSourceManager; import com.nhb.common.utils.FileSystemUtils; import com.nhb.common.utils.Initializer; public final class MarioConsumer { static { Initializer.bootstrap(MarioConsumer.class); } public static void main(String[] args) { final MarioConsumer app = new MarioConsumer(); try { Runtime.getRuntime().addShutdownHook(new Thread() { { this.setName("Shutdown Thread"); this.setPriority(MAX_PRIORITY); } @Override public void run() { app.stop(); } }); app.start(); } catch (Exception e) { System.err.println("error while starting application: "); e.printStackTrace(); System.exit(1); } } private MarioConsumer() { } private boolean running = false; private ExtensionManager extensionManager; private GatewayManager gatewayManager; private EntityManager entityManager; private SQLDataSourceManager sqlDataSourceManager; private RequestController requestController; private MarioApiFactory apiFactory; private SchedulerFactory schedulerFactory; private HazelcastInstance hazelcast; private SolrClientManager solrClientManager; private void start() throws Exception { if (this.running) { throw new IllegalAccessException("Application is already running"); } this.schedulerFactory = SchedulerFactory.getInstance(); Config config = new XmlConfigBuilder(FileSystemUtils.createAbsolutePathFrom("conf", "hazelcast.xml")).build(); this.hazelcast = Hazelcast.newHazelcastInstance(config); this.extensionManager = new ExtensionManager(); this.extensionManager.load(); this.solrClientManager = new SolrClientManager(); for (SolrClientConfig solrClientConfig : this.extensionManager.getSolrClientConfigs()) { this.solrClientManager.register(solrClientConfig); } this.sqlDataSourceManager = new SQLDataSourceManager(); this.apiFactory = new MarioApiFactory(this.sqlDataSourceManager, this.schedulerFactory, hazelcast, this.solrClientManager); for (SQLDataSourceConfig dataSourceConfig : this.extensionManager.getDataSourceConfigs()) { this.sqlDataSourceManager.registerDataSource(dataSourceConfig.getName(), dataSourceConfig.getProperties()); } this.entityManager = new EntityManager(this.extensionManager, this.apiFactory); this.entityManager.start(); this.requestController = new RequestController(); this.requestController.start(this.entityManager.getGatewayToWorkersMap()); this.gatewayManager = new GatewayManager(this.extensionManager, this.requestController); this.gatewayManager.start(); this.running = true; } private void stop() { if (this.running) { this.gatewayManager.stop(); } try { this.entityManager.stop(); } catch (Exception e) { System.err.println("error while trying to stop entity manager"); e.printStackTrace(); } try { this.solrClientManager.shutdown(); } catch (Exception ex) { ex.printStackTrace(); } try { this.requestController.stop(); } catch (Exception e) { e.printStackTrace(); } try { this.schedulerFactory.stop(); } catch (Exception e) { e.printStackTrace(); } try { this.hazelcast.shutdown(); } catch (Exception e) { e.printStackTrace(); } } }
UTF-8
Java
3,892
java
MarioConsumer.java
Java
[]
null
[]
package com.mario.consumer; import com.hazelcast.config.Config; import com.hazelcast.config.XmlConfigBuilder; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import com.mario.consumer.api.MarioApiFactory; import com.mario.consumer.entity.EntityManager; import com.mario.consumer.entity.handler.RequestController; import com.mario.consumer.extension.ExtensionManager; import com.mario.consumer.gateway.GatewayManager; import com.mario.consumer.schedule.impl.SchedulerFactory; import com.mario.consumer.solr.SolrClientConfig; import com.mario.consumer.solr.SolrClientManager; import com.nhb.common.db.sql.SQLDataSourceConfig; import com.nhb.common.db.sql.SQLDataSourceManager; import com.nhb.common.utils.FileSystemUtils; import com.nhb.common.utils.Initializer; public final class MarioConsumer { static { Initializer.bootstrap(MarioConsumer.class); } public static void main(String[] args) { final MarioConsumer app = new MarioConsumer(); try { Runtime.getRuntime().addShutdownHook(new Thread() { { this.setName("Shutdown Thread"); this.setPriority(MAX_PRIORITY); } @Override public void run() { app.stop(); } }); app.start(); } catch (Exception e) { System.err.println("error while starting application: "); e.printStackTrace(); System.exit(1); } } private MarioConsumer() { } private boolean running = false; private ExtensionManager extensionManager; private GatewayManager gatewayManager; private EntityManager entityManager; private SQLDataSourceManager sqlDataSourceManager; private RequestController requestController; private MarioApiFactory apiFactory; private SchedulerFactory schedulerFactory; private HazelcastInstance hazelcast; private SolrClientManager solrClientManager; private void start() throws Exception { if (this.running) { throw new IllegalAccessException("Application is already running"); } this.schedulerFactory = SchedulerFactory.getInstance(); Config config = new XmlConfigBuilder(FileSystemUtils.createAbsolutePathFrom("conf", "hazelcast.xml")).build(); this.hazelcast = Hazelcast.newHazelcastInstance(config); this.extensionManager = new ExtensionManager(); this.extensionManager.load(); this.solrClientManager = new SolrClientManager(); for (SolrClientConfig solrClientConfig : this.extensionManager.getSolrClientConfigs()) { this.solrClientManager.register(solrClientConfig); } this.sqlDataSourceManager = new SQLDataSourceManager(); this.apiFactory = new MarioApiFactory(this.sqlDataSourceManager, this.schedulerFactory, hazelcast, this.solrClientManager); for (SQLDataSourceConfig dataSourceConfig : this.extensionManager.getDataSourceConfigs()) { this.sqlDataSourceManager.registerDataSource(dataSourceConfig.getName(), dataSourceConfig.getProperties()); } this.entityManager = new EntityManager(this.extensionManager, this.apiFactory); this.entityManager.start(); this.requestController = new RequestController(); this.requestController.start(this.entityManager.getGatewayToWorkersMap()); this.gatewayManager = new GatewayManager(this.extensionManager, this.requestController); this.gatewayManager.start(); this.running = true; } private void stop() { if (this.running) { this.gatewayManager.stop(); } try { this.entityManager.stop(); } catch (Exception e) { System.err.println("error while trying to stop entity manager"); e.printStackTrace(); } try { this.solrClientManager.shutdown(); } catch (Exception ex) { ex.printStackTrace(); } try { this.requestController.stop(); } catch (Exception e) { e.printStackTrace(); } try { this.schedulerFactory.stop(); } catch (Exception e) { e.printStackTrace(); } try { this.hazelcast.shutdown(); } catch (Exception e) { e.printStackTrace(); } } }
3,892
0.760021
0.759764
137
27.40876
25.819292
112
false
false
0
0
0
0
0
0
2.058394
false
false
11
d0019ade7e4bcf65bd770881775425e19c717519
128,849,069,770
37ee454db747c050cdb174088036371b69e33f63
/CharBoolean.java
cdda0f8459ae0e64f71543f4b1d01d996ada2327
[]
no_license
trhoades259/CompSci
https://github.com/trhoades259/CompSci
7184fe6ac7fc0a0b0d6e09ab12a6d043735073a8
5a558eb2e1dfbefb2de39c2028e03ea9f7f86476
refs/heads/master
2021-09-17T06:54:56.802000
2018-06-29T00:44:57
2018-06-29T00:44:57
110,592,561
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class CharBoolean { private boolean bln=false; private char chr='a'; private String alpha = "abcdefghijklmnopqrstuvwxyz"; CharBoolean() {} CharBoolean(char in, boolean state){ chr = in; bln = state; } CharBoolean(int in, boolean state){ chr = alpha.charAt(in-1); bln = state; } public void isFalse() { bln = false; } public void isTrue() { bln = true; } public void changeChar(char in) { chr = in; } public void changeChar(int in) { chr = alpha.charAt(in-1); } public char getChar() { return chr; } public boolean getState() { return bln; } }
UTF-8
Java
588
java
CharBoolean.java
Java
[]
null
[]
class CharBoolean { private boolean bln=false; private char chr='a'; private String alpha = "abcdefghijklmnopqrstuvwxyz"; CharBoolean() {} CharBoolean(char in, boolean state){ chr = in; bln = state; } CharBoolean(int in, boolean state){ chr = alpha.charAt(in-1); bln = state; } public void isFalse() { bln = false; } public void isTrue() { bln = true; } public void changeChar(char in) { chr = in; } public void changeChar(int in) { chr = alpha.charAt(in-1); } public char getChar() { return chr; } public boolean getState() { return bln; } }
588
0.646259
0.642857
37
14.918919
13.45137
53
false
false
0
0
0
0
0
0
1.513514
false
false
11
8c184bcbd622337d74c15cf35412d93f50cc21f8
29,781,303,280,319
e70845f503dcdb77b097917f991a6339ffcce4af
/module-1/10_Classes_Encapsulation/student-lecture/java/src/main/java/com/techelevator/overloadingexample/CalcApp.java
6701364a80fc083bc1fe57214d2781bce91786d9
[]
no_license
willsb93/Tech-Elevator
https://github.com/willsb93/Tech-Elevator
43f5f4a351b102b73dbb1c52a6123bb7469f7e72
e2bd87b20be964d43c9ad0a38f67ae319ab680dc
refs/heads/master
2021-01-05T00:06:01.826000
2020-04-19T20:33:47
2020-04-19T20:33:47
255,645,166
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.techelevator.overloadingexample; public class CalcApp { public static void main(String[] args) { Calculator calc = new Calculator(); int rs = calc.add(2, 3); System.out.println("Answer is: " + rs); int rs1 = calc.add(1, 2, 3); System.out.println("Answer is: " + rs1); int[] nums1 = new int[] {2,3,4,5,6,7,8,9}; int rs2 = calc.add(nums1); System.out.println("Answer is: " + rs2); int[] nums2Array = new int[] {2,3,4,5,6}; int rs3 = calc.add(nums2Array); System.out.println("Answer is: " + rs3); } }
UTF-8
Java
554
java
CalcApp.java
Java
[]
null
[]
package com.techelevator.overloadingexample; public class CalcApp { public static void main(String[] args) { Calculator calc = new Calculator(); int rs = calc.add(2, 3); System.out.println("Answer is: " + rs); int rs1 = calc.add(1, 2, 3); System.out.println("Answer is: " + rs1); int[] nums1 = new int[] {2,3,4,5,6,7,8,9}; int rs2 = calc.add(nums1); System.out.println("Answer is: " + rs2); int[] nums2Array = new int[] {2,3,4,5,6}; int rs3 = calc.add(nums2Array); System.out.println("Answer is: " + rs3); } }
554
0.611913
0.561372
25
21.16
18.449238
44
false
false
0
0
0
0
0
0
2.44
false
false
11
8a3a074896951661397a26cd3fa28442e25e4786
9,689,446,264,615
cfc44deebe3b0e8f9887034c1f579bae4b1f1a79
/databases/hibernate-annotations/src/main/java/com/letstalkdata/iscream/service/IngredientService.java
1dfa88da704bafd248edca19603c691730268008
[]
no_license
phillipjohnson/java-for-the-real-world-code
https://github.com/phillipjohnson/java-for-the-real-world-code
100fe4022f62534deb1f53672c2226454be065ee
b723a0fa96ae709d6e18c43403443feedadeda79
refs/heads/master
2021-12-23T00:31:12.771000
2021-12-22T05:13:35
2021-12-22T05:13:35
89,743,131
3
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.letstalkdata.iscream.service; import com.letstalkdata.iscream.domain.Ingredient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.persistence.EntityManager; import java.util.List; @Service public class IngredientService { private EntityManager em; @Autowired public IngredientService(EntityManager em) { this.em = em; } public List<Ingredient> getFlavors() { return getIngredients(Ingredient.Type.ICE_CREAM); } public List<Ingredient> getToppings() { return getIngredients(Ingredient.Type.TOPPING); } private List<Ingredient> getIngredients(Ingredient.Type type) { var sql = "select i from Ingredient i where type =:type"; var query = em.createQuery(sql); query.setParameter("type", type); @SuppressWarnings("unchecked") var ingredients = (List<Ingredient>) query.getResultList(); return ingredients; } public Ingredient getIngredientById(int id) { return em.find(Ingredient.class, id); } }
UTF-8
Java
1,114
java
IngredientService.java
Java
[]
null
[]
package com.letstalkdata.iscream.service; import com.letstalkdata.iscream.domain.Ingredient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.persistence.EntityManager; import java.util.List; @Service public class IngredientService { private EntityManager em; @Autowired public IngredientService(EntityManager em) { this.em = em; } public List<Ingredient> getFlavors() { return getIngredients(Ingredient.Type.ICE_CREAM); } public List<Ingredient> getToppings() { return getIngredients(Ingredient.Type.TOPPING); } private List<Ingredient> getIngredients(Ingredient.Type type) { var sql = "select i from Ingredient i where type =:type"; var query = em.createQuery(sql); query.setParameter("type", type); @SuppressWarnings("unchecked") var ingredients = (List<Ingredient>) query.getResultList(); return ingredients; } public Ingredient getIngredientById(int id) { return em.find(Ingredient.class, id); } }
1,114
0.702873
0.702873
40
26.85
23.062469
67
false
false
0
0
0
0
0
0
0.45
false
false
11
6f6d5938a9ba8f8171e977020483ed587f87d050
3,934,190,097,250
294e77c56a3ced3d230a948873feee4d48fe53fa
/jims-api/src/main/java/com/jims/asepsis/api/OrgSysDictApi.java
2b46bd470c5877a8f2037b6f980e9ff271cddc92
[]
no_license
zyg58979008/hrm
https://github.com/zyg58979008/hrm
c5ecad2217b7ea10d3c09389e079442ce4c8e75e
c53b2205f3f44926f5ee9378dd9e8fd9d47fec9e
refs/heads/master
2020-05-23T17:38:05.871000
2017-03-13T04:03:18
2017-03-13T04:03:18
84,775,991
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jims.asepsis.api; import com.jims.asepsis.entity.OrgSysDict; import com.jims.common.persistence.Page; import com.jims.sys.entity.OrgDeptPropertyDict; import com.jims.sys.vo.BeanChangeVo; import java.util.List; /** * 包单位维护Api * @author yangruidong * @version 2016-06-28 */ public interface OrgSysDictApi { /** * 异步加载页面左侧表格:机构字典表的类型和描述列表 * @param orgId 组织机构ID * @return * @author fengyuguang */ public List<OrgSysDict> leftList(String orgId); /** * 异步加载页面右侧表格:机构字典表的键值列表 * @param type 类型 * @param orgId 组织机构ID * @return * @author fengyuguang */ public List<OrgSysDict> rightList(String type,String orgId); /** * 保存多条增删改数据 * @param beanChangeVo 多条增删改数据的集合 * @return * @author fengyuguang */ public String merge(BeanChangeVo<OrgSysDict> beanChangeVo); /** * 根据类型或描述查询某个组织机构的字典数据 * @param type 类型 * @param description 描述 * @param orgId 组织机构ID * @return * @author fengyuguang */ public List<OrgSysDict> search(String type,String description,String orgId); /** * 根据ID检索 * @param id * @return */ public OrgSysDict get(String id); /** * 检索 * @param entity * @return */ public List<OrgSysDict> findList(OrgSysDict entity); /** * 根据类型查询包单位 * @param entity * @return */ public List<OrgSysDict> findUnits(OrgSysDict entity); /** * 分页检索 * @param page 分页对象 * @param entity * @return */ public Page<OrgSysDict> findPage(Page<OrgSysDict> page, OrgSysDict entity); /** * 保存(插入或更新) * @param entity * @return 0 失败,1成功 */ public String save(OrgSysDict entity) ; /** * 批量保存(插入或更新) * @param list * @return 0 失败,1成功 */ public String save(List<OrgSysDict> list); /** * 删除数据 * @param ids,多个id以逗号(,)隔开 * @return 0 失败,1成功 */ public String delete(String ids) ; }
UTF-8
Java
2,336
java
OrgSysDictApi.java
Java
[ { "context": "\n\nimport java.util.List;\n\n/**\n* 包单位维护Api\n* @author yangruidong\n* @version 2016-06-28\n*/\npublic interface OrgSysD", "end": 261, "score": 0.9995564222335815, "start": 250, "tag": "USERNAME", "value": "yangruidong" }, { "context": " @param orgId 组织机构ID\n * @return\n * @author fengyuguang\n */\n public List<OrgSysDict> leftList(Stri", "end": 429, "score": 0.8303890228271484, "start": 418, "tag": "USERNAME", "value": "fengyuguang" }, { "context": " @param orgId 组织机构ID\n * @return\n * @author fengyuguang\n */\n public List<OrgSysDict> rightList(Str", "end": 619, "score": 0.9827389717102051, "start": 608, "tag": "USERNAME", "value": "fengyuguang" }, { "context": "nChangeVo 多条增删改数据的集合\n * @return\n * @author fengyuguang\n */\n public String merge(BeanChangeVo<OrgS", "end": 798, "score": 0.9670208692550659, "start": 787, "tag": "USERNAME", "value": "fengyuguang" }, { "context": " @param orgId 组织机构ID\n * @return\n * @author fengyuguang\n */\n public List<OrgSysDict> search(String", "end": 1027, "score": 0.7807791233062744, "start": 1016, "tag": "USERNAME", "value": "fengyuguang" } ]
null
[]
package com.jims.asepsis.api; import com.jims.asepsis.entity.OrgSysDict; import com.jims.common.persistence.Page; import com.jims.sys.entity.OrgDeptPropertyDict; import com.jims.sys.vo.BeanChangeVo; import java.util.List; /** * 包单位维护Api * @author yangruidong * @version 2016-06-28 */ public interface OrgSysDictApi { /** * 异步加载页面左侧表格:机构字典表的类型和描述列表 * @param orgId 组织机构ID * @return * @author fengyuguang */ public List<OrgSysDict> leftList(String orgId); /** * 异步加载页面右侧表格:机构字典表的键值列表 * @param type 类型 * @param orgId 组织机构ID * @return * @author fengyuguang */ public List<OrgSysDict> rightList(String type,String orgId); /** * 保存多条增删改数据 * @param beanChangeVo 多条增删改数据的集合 * @return * @author fengyuguang */ public String merge(BeanChangeVo<OrgSysDict> beanChangeVo); /** * 根据类型或描述查询某个组织机构的字典数据 * @param type 类型 * @param description 描述 * @param orgId 组织机构ID * @return * @author fengyuguang */ public List<OrgSysDict> search(String type,String description,String orgId); /** * 根据ID检索 * @param id * @return */ public OrgSysDict get(String id); /** * 检索 * @param entity * @return */ public List<OrgSysDict> findList(OrgSysDict entity); /** * 根据类型查询包单位 * @param entity * @return */ public List<OrgSysDict> findUnits(OrgSysDict entity); /** * 分页检索 * @param page 分页对象 * @param entity * @return */ public Page<OrgSysDict> findPage(Page<OrgSysDict> page, OrgSysDict entity); /** * 保存(插入或更新) * @param entity * @return 0 失败,1成功 */ public String save(OrgSysDict entity) ; /** * 批量保存(插入或更新) * @param list * @return 0 失败,1成功 */ public String save(List<OrgSysDict> list); /** * 删除数据 * @param ids,多个id以逗号(,)隔开 * @return 0 失败,1成功 */ public String delete(String ids) ; }
2,336
0.602823
0.595766
101
18.653465
17.415956
80
false
false
0
0
0
0
0
0
0.227723
false
false
11
048a72783394899c76ff8c1a1706310383f61db9
1,460,288,915,150
27cbbecc564d5e06b87c816d5d308650fddf9179
/src/main/java/com/eberhart/spending/dao/TransactionDAO.java
aedddf24d8b8bd4c720bdeed4836d23b7cc944a5
[]
no_license
christophereber/spending
https://github.com/christophereber/spending
3c1c77326e1fdcc616e197e25d8a6b8e907f288f
afb2622c326120bc2de59a96cf28ffb6eb9e8293
refs/heads/master
2020-05-04T17:56:13.442000
2019-12-11T21:03:28
2019-12-11T21:03:28
179,329,889
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.eberhart.spending.dao; import com.eberhart.spending.data.Transaction; import org.springframework.data.repository.CrudRepository; public interface TransactionDAO extends CrudRepository <Transaction, Integer> { }
UTF-8
Java
226
java
TransactionDAO.java
Java
[]
null
[]
package com.eberhart.spending.dao; import com.eberhart.spending.data.Transaction; import org.springframework.data.repository.CrudRepository; public interface TransactionDAO extends CrudRepository <Transaction, Integer> { }
226
0.836283
0.836283
8
27.25
29.448048
79
false
false
0
0
0
0
0
0
0.5
false
false
11
c748d5f7f1314582c197a1fdb92c95eca8c82206
2,869,038,199,934
f66fc1aca1c2ed178ac3f8c2cf5185b385558710
/reladomoserial/src/main/java/com/gs/reladomo/serial/gson/GsonRelodomoSerialContext.java
c1934f2d8ce8fce7c728dc2de96d7fb28a1463ca
[ "Apache-2.0", "BSD-3-Clause", "MIT", "LicenseRef-scancode-public-domain" ]
permissive
goldmansachs/reladomo
https://github.com/goldmansachs/reladomo
9cd3e60e92dbc6b0eb59ea24d112244ffe01bc35
a4f4e39290d8012573f5737a4edc45d603be07a5
refs/heads/master
2023-09-04T10:30:12.542000
2023-07-20T09:29:44
2023-07-20T09:29:44
68,020,885
431
122
Apache-2.0
false
2023-07-07T21:29:52
2016-09-12T15:17:34
2023-06-17T09:53:43
2023-07-07T21:29:51
10,739
366
95
17
Java
false
false
/* Copyright 2016 Goldman Sachs. 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. */ // Portions copyright Hiroshi Ito. Licensed under Apache 2.0 license package com.gs.reladomo.serial.gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.gs.fw.common.mithra.util.serializer.ReladomoSerializationContext; import com.gs.fw.common.mithra.util.serializer.SerialWriter; import com.gs.fw.common.mithra.util.serializer.SerializationConfig; import org.eclipse.collections.impl.list.mutable.FastList; import java.util.List; public class GsonRelodomoSerialContext extends ReladomoSerializationContext { private List<JsonElement> stack = FastList.newList(); private JsonSerializationContext gsonContext; private JsonObject result; public GsonRelodomoSerialContext(SerializationConfig serializationConfig, SerialWriter writer, JsonSerializationContext gsonContext) { super(serializationConfig, writer); this.gsonContext = gsonContext; } public JsonObject getCurrentResultAsObject() { return (JsonObject) stack.get(stack.size() - 1); } public JsonObject pushNewObject(String name) { JsonObject newObj = new JsonObject(); if (name == null) { if (stack.size() == 0) { result = newObj; stack.add(newObj); } else { JsonElement jsonElement = stack.get(stack.size() - 1); if (jsonElement instanceof JsonArray) { ((JsonArray)jsonElement).add(newObj); stack.add(newObj); } } } else { getCurrentResultAsObject().add(name, newObj); stack.add(newObj); } return newObj; } public JsonElement pop() { return stack.remove(stack.size() - 1); } public JsonArray pushNewArray(String name) { JsonArray newObj = new JsonArray(); getCurrentResultAsObject().add(name, newObj); stack.add(newObj); return newObj; } public JsonObject getResult() { return result; } public JsonSerializationContext getGsonContext() { return gsonContext; } }
UTF-8
Java
2,900
java
GsonRelodomoSerialContext.java
Java
[ { "context": "/*\n Copyright 2016 Goldman Sachs.\n Licensed under the Apache License, Version 2.0", "end": 33, "score": 0.9997451901435852, "start": 20, "tag": "NAME", "value": "Goldman Sachs" }, { "context": "ons\n under the License.\n */\n// Portions copyright Hiroshi Ito. Licensed under Apache 2.0 license\n\npackage com.g", "end": 615, "score": 0.9996959567070007, "start": 604, "tag": "NAME", "value": "Hiroshi Ito" } ]
null
[]
/* Copyright 2016 <NAME>. 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. */ // Portions copyright <NAME>. Licensed under Apache 2.0 license package com.gs.reladomo.serial.gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.gs.fw.common.mithra.util.serializer.ReladomoSerializationContext; import com.gs.fw.common.mithra.util.serializer.SerialWriter; import com.gs.fw.common.mithra.util.serializer.SerializationConfig; import org.eclipse.collections.impl.list.mutable.FastList; import java.util.List; public class GsonRelodomoSerialContext extends ReladomoSerializationContext { private List<JsonElement> stack = FastList.newList(); private JsonSerializationContext gsonContext; private JsonObject result; public GsonRelodomoSerialContext(SerializationConfig serializationConfig, SerialWriter writer, JsonSerializationContext gsonContext) { super(serializationConfig, writer); this.gsonContext = gsonContext; } public JsonObject getCurrentResultAsObject() { return (JsonObject) stack.get(stack.size() - 1); } public JsonObject pushNewObject(String name) { JsonObject newObj = new JsonObject(); if (name == null) { if (stack.size() == 0) { result = newObj; stack.add(newObj); } else { JsonElement jsonElement = stack.get(stack.size() - 1); if (jsonElement instanceof JsonArray) { ((JsonArray)jsonElement).add(newObj); stack.add(newObj); } } } else { getCurrentResultAsObject().add(name, newObj); stack.add(newObj); } return newObj; } public JsonElement pop() { return stack.remove(stack.size() - 1); } public JsonArray pushNewArray(String name) { JsonArray newObj = new JsonArray(); getCurrentResultAsObject().add(name, newObj); stack.add(newObj); return newObj; } public JsonObject getResult() { return result; } public JsonSerializationContext getGsonContext() { return gsonContext; } }
2,888
0.656552
0.651724
98
28.591837
25.396383
136
false
false
0
0
0
0
0
0
0.428571
false
false
11
f761bc5d2d631c01d9be4a1966c01fba19bec0e3
6,339,371,785,068
ceaf9fdd1e2b767c86bc0e3b055bd665c782ad98
/app/src/main/java/ke/co/besure/besure/fragment/HIVFactsFragment.java
2dfff593fb1967636598fe013e2c08e89a1e9fd1
[]
no_license
johnotaalo/BesureV2
https://github.com/johnotaalo/BesureV2
f354bfd15fa1ffd34bb43831d946e7f9a8a9c9d0
d1991a6e28de7d5b6c5044a5466bcb4b2797f3b7
refs/heads/master
2021-06-24T22:10:44.535000
2020-11-30T10:50:08
2020-11-30T10:50:08
155,746,205
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ke.co.besure.besure.fragment; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import ke.co.besure.besure.Database.DB; import ke.co.besure.besure.R; import ke.co.besure.besure.activity.HIVFactActivity; import ke.co.besure.besure.adapter.VideoAdapter; import ke.co.besure.besure.model.HIVFact; import ke.co.besure.besure.model.Video; import ke.co.besure.besure.provider.HIVFactProvider; public class HIVFactsFragment extends Fragment implements View.OnClickListener { private DB mDB; CardView testingBtn, disclosureBtn, treatmentBtn, preventionBtn, hivTbBtn, hivFamilyBtn, supportGroupsBtn; HIVFact fact; public HIVFactsFragment() { } public static HIVFactsFragment newInstance() { HIVFactsFragment fragment = new HIVFactsFragment(); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_hivfacts, container, false); mDB = new DB(getContext()); testingBtn = root.findViewById(R.id.testingBtn); disclosureBtn = root.findViewById(R.id.disclosureBtn); treatmentBtn = root.findViewById(R.id.treatmentBtn); preventionBtn = root.findViewById(R.id.preventionBtn); hivTbBtn = root.findViewById(R.id.hivTb); hivFamilyBtn = root.findViewById(R.id.hivFamilyBtn); supportGroupsBtn = root.findViewById(R.id.supportGroupsBtn); testingBtn.setOnClickListener(this); disclosureBtn.setOnClickListener(this); treatmentBtn.setOnClickListener(this); preventionBtn.setOnClickListener(this); hivTbBtn.setOnClickListener(this); hivFamilyBtn.setOnClickListener(this); supportGroupsBtn.setOnClickListener(this); return root; } @Override public void onClick(View v) { Intent intent = new Intent(getContext(), HIVFactActivity.class); String section = "testing"; switch (v.getId()){ case R.id.testingBtn: section = "testing"; break; case R.id.disclosureBtn: section = "disclosure"; break; case R.id.treatmentBtn: section = "treatment"; break; case R.id.preventionBtn: section = "prevention"; break; case R.id.hivTb: section = "hiv-tb"; break; case R.id.hivFamilyBtn: section = "hiv-family"; break; case R.id.supportGroupsBtn: section = "support-group"; break; } intent.putExtra("section", section); startActivity(intent); } }
UTF-8
Java
3,218
java
HIVFactsFragment.java
Java
[]
null
[]
package ke.co.besure.besure.fragment; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import ke.co.besure.besure.Database.DB; import ke.co.besure.besure.R; import ke.co.besure.besure.activity.HIVFactActivity; import ke.co.besure.besure.adapter.VideoAdapter; import ke.co.besure.besure.model.HIVFact; import ke.co.besure.besure.model.Video; import ke.co.besure.besure.provider.HIVFactProvider; public class HIVFactsFragment extends Fragment implements View.OnClickListener { private DB mDB; CardView testingBtn, disclosureBtn, treatmentBtn, preventionBtn, hivTbBtn, hivFamilyBtn, supportGroupsBtn; HIVFact fact; public HIVFactsFragment() { } public static HIVFactsFragment newInstance() { HIVFactsFragment fragment = new HIVFactsFragment(); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_hivfacts, container, false); mDB = new DB(getContext()); testingBtn = root.findViewById(R.id.testingBtn); disclosureBtn = root.findViewById(R.id.disclosureBtn); treatmentBtn = root.findViewById(R.id.treatmentBtn); preventionBtn = root.findViewById(R.id.preventionBtn); hivTbBtn = root.findViewById(R.id.hivTb); hivFamilyBtn = root.findViewById(R.id.hivFamilyBtn); supportGroupsBtn = root.findViewById(R.id.supportGroupsBtn); testingBtn.setOnClickListener(this); disclosureBtn.setOnClickListener(this); treatmentBtn.setOnClickListener(this); preventionBtn.setOnClickListener(this); hivTbBtn.setOnClickListener(this); hivFamilyBtn.setOnClickListener(this); supportGroupsBtn.setOnClickListener(this); return root; } @Override public void onClick(View v) { Intent intent = new Intent(getContext(), HIVFactActivity.class); String section = "testing"; switch (v.getId()){ case R.id.testingBtn: section = "testing"; break; case R.id.disclosureBtn: section = "disclosure"; break; case R.id.treatmentBtn: section = "treatment"; break; case R.id.preventionBtn: section = "prevention"; break; case R.id.hivTb: section = "hiv-tb"; break; case R.id.hivFamilyBtn: section = "hiv-family"; break; case R.id.supportGroupsBtn: section = "support-group"; break; } intent.putExtra("section", section); startActivity(intent); } }
3,218
0.661591
0.660348
99
31.515152
22.801455
110
false
false
0
0
0
0
0
0
0.747475
false
false
11
5f4ab26204a163af0683470208d09beedddb6dee
27,702,539,061,054
bab90e565f5ab713c8bd8d43ee051ba87f795632
/src/main/java/com/markerhub/service/mar/MarTypesService.java
971be1c90077f02f2827132ba889b8074f84b8bb
[]
no_license
Skipper-lee/vueadmin-java
https://github.com/Skipper-lee/vueadmin-java
83c47a18845dbab9b055ad89db68035896743c61
8b149f6e161aa2651aa74d43f79cfcb56088ff87
refs/heads/master
2023-08-04T12:22:35.100000
2021-09-11T01:39:57
2021-09-11T01:39:57
405,123,132
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.markerhub.service.mar; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.IService; import com.markerhub.entity.mar.MarBrands; import com.markerhub.entity.mar.MarTypes; import org.springframework.stereotype.Service; import java.util.List; /** * *@author lichong *@description: *@date 9:45 PM 11/08/2021 **/ @Service public interface MarTypesService extends IService<MarTypes> { }
UTF-8
Java
466
java
MarTypesService.java
Java
[ { "context": ".Service;\n\nimport java.util.List;\n\n/**\n*\n*@author lichong\n*@description:\n*@date 9:45 PM 11/08/2021\n**/\n@Ser", "end": 343, "score": 0.9991997480392456, "start": 336, "tag": "USERNAME", "value": "lichong" } ]
null
[]
package com.markerhub.service.mar; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.IService; import com.markerhub.entity.mar.MarBrands; import com.markerhub.entity.mar.MarTypes; import org.springframework.stereotype.Service; import java.util.List; /** * *@author lichong *@description: *@date 9:45 PM 11/08/2021 **/ @Service public interface MarTypesService extends IService<MarTypes> { }
466
0.799569
0.775862
20
22.200001
22.714752
67
false
false
0
0
0
0
0
0
0.35
false
false
11
c76a69dc4a685db6f6dfdceff84116b93ecef6bf
27,702,539,063,018
014905253f94e45169fc14584a6865a344836f79
/src/main/java/com/avaya/springjpaoracledemo/controller/OptionsByMenuController.java
fea832fb597fac9b14e50d5d7808a7e71f9a3d51
[]
no_license
nipusan/api-rest-admin-web
https://github.com/nipusan/api-rest-admin-web
badacf4c7f85cd3ebf1a5a29c7078d17716adeb8
4b69a1721b06b44257fa51f17e4c06b483ed39ce
refs/heads/master
2022-04-08T09:14:15.377000
2019-08-12T15:53:47
2019-08-12T15:53:47
219,840,809
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.avaya.springjpaoracledemo.controller; import com.avaya.springjpaoracledemo.entity.OptionsByMenu; import com.avaya.springjpaoracledemo.service.OptionsByMenuService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; import java.time.LocalDateTime; @RestController @CrossOrigin(origins = "*", methods={RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT, RequestMethod.DELETE}) @RequestMapping("/optionsByMenu") public class OptionsByMenuController { @Autowired OptionsByMenuService optionsByMenuService; @RequestMapping(value = "/all", method = RequestMethod.GET) public List<OptionsByMenu> getAllOptionsByMenus() { return this.optionsByMenuService.getAllOptionsByMenus(); } @RequestMapping(value = "/addoptionsByMenu", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public OptionsByMenu addOptionsByMenu(@RequestBody OptionsByMenu optionsByMenu) { return this.optionsByMenuService.addOptionsByMenu(optionsByMenu); } @RequestMapping(value = "/updateoptionsByMenu", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public OptionsByMenu updateOptionsByMenu(@RequestBody OptionsByMenu optionsByMenu) { LocalDateTime time = LocalDateTime.now(); optionsByMenu.setModificationDate(time); return this.optionsByMenuService.updateOptionsByMenu(optionsByMenu); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public Optional<OptionsByMenu> getOptionsByMenu(@PathVariable String id) { return this.optionsByMenuService.getOptionsByMenuById(Integer.parseInt(id)); } @RequestMapping(value = "/all", method = RequestMethod.DELETE) public void deleteAllOptionsByMenus() { this.optionsByMenuService.deleteAllOptionsByMenus(); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public void deleteOptionsByMenu(@PathVariable int id) { this.optionsByMenuService.deleteOptionsByMenuById(id); } @Autowired MessageSource messageSource; @RequestMapping(value = "/get-greeting", method = RequestMethod.GET) public String greeting() { /** * @LocaleContextHolder.getLocale() * Return the Locale associated with the given optionsByMenu context,if any, or the system default Locale otherwise. * This is effectively a replacement for Locale.getDefault(), able to optionally respect a optionsByMenu-level Locale setting. */ return messageSource.getMessage("good.morning", null, LocaleContextHolder.getLocale()); } @RequestMapping(value = "/get-greeting-name", method = RequestMethod.GET) public String greetingWithName() { String[] params = new String[]{"Ikhiavaya", "today"}; return messageSource.getMessage("good.morning.name", params, LocaleContextHolder.getLocale()); } }
UTF-8
Java
3,287
java
OptionsByMenuController.java
Java
[ { "context": "hName() {\n String[] params = new String[]{\"Ikhiavaya\", \"today\"};\n return messageSource.getMessa", "end": 3161, "score": 0.9984085559844971, "start": 3152, "tag": "NAME", "value": "Ikhiavaya" } ]
null
[]
package com.avaya.springjpaoracledemo.controller; import com.avaya.springjpaoracledemo.entity.OptionsByMenu; import com.avaya.springjpaoracledemo.service.OptionsByMenuService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; import java.time.LocalDateTime; @RestController @CrossOrigin(origins = "*", methods={RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT, RequestMethod.DELETE}) @RequestMapping("/optionsByMenu") public class OptionsByMenuController { @Autowired OptionsByMenuService optionsByMenuService; @RequestMapping(value = "/all", method = RequestMethod.GET) public List<OptionsByMenu> getAllOptionsByMenus() { return this.optionsByMenuService.getAllOptionsByMenus(); } @RequestMapping(value = "/addoptionsByMenu", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public OptionsByMenu addOptionsByMenu(@RequestBody OptionsByMenu optionsByMenu) { return this.optionsByMenuService.addOptionsByMenu(optionsByMenu); } @RequestMapping(value = "/updateoptionsByMenu", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public OptionsByMenu updateOptionsByMenu(@RequestBody OptionsByMenu optionsByMenu) { LocalDateTime time = LocalDateTime.now(); optionsByMenu.setModificationDate(time); return this.optionsByMenuService.updateOptionsByMenu(optionsByMenu); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public Optional<OptionsByMenu> getOptionsByMenu(@PathVariable String id) { return this.optionsByMenuService.getOptionsByMenuById(Integer.parseInt(id)); } @RequestMapping(value = "/all", method = RequestMethod.DELETE) public void deleteAllOptionsByMenus() { this.optionsByMenuService.deleteAllOptionsByMenus(); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public void deleteOptionsByMenu(@PathVariable int id) { this.optionsByMenuService.deleteOptionsByMenuById(id); } @Autowired MessageSource messageSource; @RequestMapping(value = "/get-greeting", method = RequestMethod.GET) public String greeting() { /** * @LocaleContextHolder.getLocale() * Return the Locale associated with the given optionsByMenu context,if any, or the system default Locale otherwise. * This is effectively a replacement for Locale.getDefault(), able to optionally respect a optionsByMenu-level Locale setting. */ return messageSource.getMessage("good.morning", null, LocaleContextHolder.getLocale()); } @RequestMapping(value = "/get-greeting-name", method = RequestMethod.GET) public String greetingWithName() { String[] params = new String[]{"Ikhiavaya", "today"}; return messageSource.getMessage("good.morning.name", params, LocaleContextHolder.getLocale()); } }
3,287
0.746577
0.745969
80
40.087502
35.996246
135
false
false
0
0
0
0
0
0
0.6
false
false
11
5ef6ce348b7c4d942825fa7bf868fb415f4089a4
10,479,720,251,448
2c5f94d5a85a1aae50c6342d4c169e7e44889e23
/src/test/java/space/symplectic/divan/ApcoTest.java
10d66a73ace12cf804457efe9f08d528c30db7b9
[ "BSD-2-Clause", "MIT" ]
permissive
symplectic-space/divan
https://github.com/symplectic-space/divan
446afe93d7669847911e2a579824ef45a05a988a
7fc1bab8f3f99b47b41aead17dd0a179568a4940
refs/heads/master
2020-11-25T04:14:37.914000
2020-01-22T19:01:44
2020-02-18T11:56:43
228,496,966
1
0
NOASSERTION
false
2020-02-18T11:48:14
2019-12-16T23:57:21
2020-01-21T01:59:56
2020-02-18T11:48:13
1,289
1
0
1
Java
false
false
package space.symplectic.divan; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import space.symplectic.divan.types.Astrom; /** * Unit tests for {@link Apco}. */ public class ApcoTest { /** * Runs the tests from ERFA. */ @Test public void runErfaTests() { double date1 = 2456384.5; double date2 = 0.970031644; double[][] ebpv = {{-0.974170438, -0.211520082, -0.0917583024}, {0.00364365824, -0.0154287319, -0.00668922024}}; double[] ehp = {-0.973458265, -0.209215307, -0.0906996477}; double x = 0.0013122272; double y = -2.92808623e-5; double s = 3.05749468e-8; double theta = 3.14540971; double elong = -0.527800806; double phi = -1.2345856; double hm = 2738.0; double xp = 2.47230737e-7; double yp = 1.82640464e-6; double sp = -3.01974337e-11; double refa = 0.000201418779; double refb = -2.36140831e-7; Astrom astrom = new Astrom(); Apco.apco(date1, date2, ebpv, ehp, x, y, s, theta, elong, phi, hm, xp, yp, sp, refa, refb, astrom); assertEquals(13.25248468622587269, astrom.pmt, 1e-11); assertEquals(-0.9741827110630322720, astrom.eb[0], 1e-12); assertEquals(-0.2115130190135344832, astrom.eb[1], 1e-12); assertEquals(-0.09179840186949532298, astrom.eb[2], 1e-12); assertEquals(-0.9736425571689739035, astrom.eh[0], 1e-12); assertEquals(-0.2092452125849330936, astrom.eh[1], 1e-12); assertEquals(-0.09075578152243272599, astrom.eh[2], 1e-12); assertEquals(0.9998233241709957653, astrom.em, 1e-12); assertEquals(0.2078704992916728762e-4, astrom.v[0], 1e-16); assertEquals(-0.8955360107151952319e-4, astrom.v[1], 1e-16); assertEquals(-0.3863338994288951082e-4, astrom.v[2], 1e-16); assertEquals(0.9999999950277561236, astrom.bm1, 1e-12); assertEquals(0.9999991390295159156, astrom.bpn[0][0], 1e-12); assertEquals(0.4978650072505016932e-7, astrom.bpn[1][0], 1e-12); assertEquals(0.1312227200000000000e-2, astrom.bpn[2][0], 1e-12); assertEquals(-0.1136336653771609630e-7, astrom.bpn[0][1], 1e-12); assertEquals(0.9999999995713154868, astrom.bpn[1][1], 1e-12); assertEquals(-0.2928086230000000000e-4, astrom.bpn[2][1], 1e-12); assertEquals(-0.1312227200895260194e-2, astrom.bpn[0][2], 1e-12); assertEquals(0.2928082217872315680e-4, astrom.bpn[1][2], 1e-12); assertEquals(0.9999991386008323373, astrom.bpn[2][2], 1e-12); assertEquals(-0.5278008060301974337, astrom.along, 1e-12); assertEquals(0.1133427418174939329e-5, astrom.xpl, 1e-17); assertEquals(0.1453347595745898629e-5, astrom.ypl, 1e-17); assertEquals(-0.9440115679003211329, astrom.sphi, 1e-12); assertEquals(0.3299123514971474711, astrom.cphi, 1e-12); assertEquals(0, astrom.diurab, 0); assertEquals(2.617608903969802566, astrom.eral, 1e-12); assertEquals(0.2014187790000000000e-3, astrom.refa, 1e-15); assertEquals(-0.2361408310000000000e-6, astrom.refb, 1e-18); } }
UTF-8
Java
2,989
java
ApcoTest.java
Java
[]
null
[]
package space.symplectic.divan; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import space.symplectic.divan.types.Astrom; /** * Unit tests for {@link Apco}. */ public class ApcoTest { /** * Runs the tests from ERFA. */ @Test public void runErfaTests() { double date1 = 2456384.5; double date2 = 0.970031644; double[][] ebpv = {{-0.974170438, -0.211520082, -0.0917583024}, {0.00364365824, -0.0154287319, -0.00668922024}}; double[] ehp = {-0.973458265, -0.209215307, -0.0906996477}; double x = 0.0013122272; double y = -2.92808623e-5; double s = 3.05749468e-8; double theta = 3.14540971; double elong = -0.527800806; double phi = -1.2345856; double hm = 2738.0; double xp = 2.47230737e-7; double yp = 1.82640464e-6; double sp = -3.01974337e-11; double refa = 0.000201418779; double refb = -2.36140831e-7; Astrom astrom = new Astrom(); Apco.apco(date1, date2, ebpv, ehp, x, y, s, theta, elong, phi, hm, xp, yp, sp, refa, refb, astrom); assertEquals(13.25248468622587269, astrom.pmt, 1e-11); assertEquals(-0.9741827110630322720, astrom.eb[0], 1e-12); assertEquals(-0.2115130190135344832, astrom.eb[1], 1e-12); assertEquals(-0.09179840186949532298, astrom.eb[2], 1e-12); assertEquals(-0.9736425571689739035, astrom.eh[0], 1e-12); assertEquals(-0.2092452125849330936, astrom.eh[1], 1e-12); assertEquals(-0.09075578152243272599, astrom.eh[2], 1e-12); assertEquals(0.9998233241709957653, astrom.em, 1e-12); assertEquals(0.2078704992916728762e-4, astrom.v[0], 1e-16); assertEquals(-0.8955360107151952319e-4, astrom.v[1], 1e-16); assertEquals(-0.3863338994288951082e-4, astrom.v[2], 1e-16); assertEquals(0.9999999950277561236, astrom.bm1, 1e-12); assertEquals(0.9999991390295159156, astrom.bpn[0][0], 1e-12); assertEquals(0.4978650072505016932e-7, astrom.bpn[1][0], 1e-12); assertEquals(0.1312227200000000000e-2, astrom.bpn[2][0], 1e-12); assertEquals(-0.1136336653771609630e-7, astrom.bpn[0][1], 1e-12); assertEquals(0.9999999995713154868, astrom.bpn[1][1], 1e-12); assertEquals(-0.2928086230000000000e-4, astrom.bpn[2][1], 1e-12); assertEquals(-0.1312227200895260194e-2, astrom.bpn[0][2], 1e-12); assertEquals(0.2928082217872315680e-4, astrom.bpn[1][2], 1e-12); assertEquals(0.9999991386008323373, astrom.bpn[2][2], 1e-12); assertEquals(-0.5278008060301974337, astrom.along, 1e-12); assertEquals(0.1133427418174939329e-5, astrom.xpl, 1e-17); assertEquals(0.1453347595745898629e-5, astrom.ypl, 1e-17); assertEquals(-0.9440115679003211329, astrom.sphi, 1e-12); assertEquals(0.3299123514971474711, astrom.cphi, 1e-12); assertEquals(0, astrom.diurab, 0); assertEquals(2.617608903969802566, astrom.eral, 1e-12); assertEquals(0.2014187790000000000e-3, astrom.refa, 1e-15); assertEquals(-0.2361408310000000000e-6, astrom.refb, 1e-18); } }
2,989
0.693878
0.377384
70
41.700001
26.540186
116
false
false
0
0
0
0
0
0
1.928571
false
false
11
f84d7ca4c78542b720fc7d112ffe7b46acc71048
31,404,800,915,348
f180c19c95ca8c7620f2d1bf88d75eeb27a8937e
/app/src/main/java/com/rocktech/boarddriver/coremodule/lockcontrol/handleresult/customized/ThreeColumns.java
9a0f78f0955d0d1a838c4a0ea50fa825f54622ca
[]
no_license
xuemeng1992/BoardDriverMiddleware
https://github.com/xuemeng1992/BoardDriverMiddleware
fd8155cdc6c13c679a659d33045f9e9965f0ce00
565691ceb1580a63222ba2226a8155a0287d3bd4
refs/heads/master
2023-04-22T09:05:34.210000
2021-05-10T07:14:34
2021-05-10T07:14:34
339,987,287
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rocktech.boarddriver.coremodule.lockcontrol.handleresult.customized; import android.content.Context; import android.text.TextUtils; import android.util.Log; import com.rocktech.boarddriver.R; import com.rocktech.boarddriver.bean.AssetCodeBean; import com.rocktech.boarddriver.bean.AssetCodeDao; import com.rocktech.boarddriver.coremodule.lockcontrol.HandleFactory; import com.rocktech.boarddriver.coremodule.lockcontrol.ILocker; import com.rocktech.boarddriver.tools.ConfigureTools; import com.rocktech.boarddriver.tools.Constant; import com.rocktech.boarddriver.tools.DaoTools; import com.rocktech.boarddriver.tools.Tools; import com.rocktech.boarddriver.ui.adapter.BaseAdapter; import com.rocktech.boarddriver.ui.adapter.CommonAssetCodeAdapter; import java.util.ArrayList; import java.util.List; public class ThreeColumns implements ICustomized { @Override public boolean checkLockState(byte[] LISHIZHI, String boxId, String assetCode, Context context) { return HandleFactory.produceHandle(ConfigureTools.getBoardTypeBean(context).getId()).stateOpenSingleLock(LISHIZHI, boxId, context); } @Override public String[] getAllCheckStateLock(String assetCode, String boxIndex) { String[] batchBoxs; int length; if (boxIndex.substring(0, 1).equals("Z")) { length = 8; } else { if (assetCode.substring(9, 11).equals("03") || assetCode.substring(9, 11).equals("04")) { length = 45; } else { length = 22; } } batchBoxs = new String[length]; for (int i = 0; i < batchBoxs.length; i++) { batchBoxs[i] = boxIndex.substring(0, 1) + String.format("%02d", i + 1); } return batchBoxs; } @Override public String[] getAllOpenLock(String assetCode, String boxIndex) { String[] batchBoxs; int length; if (boxIndex.substring(0, 1).equals("Z")) { length = 8; } else { if (assetCode.substring(9, 11).equals("03") || assetCode.substring(9, 11).equals("04")) { length = 45; } else { length = 22; } } batchBoxs = new String[length]; for (int i = 0; i < batchBoxs.length; i++) { batchBoxs[i] = boxIndex.substring(0, 1) + String.format("%02d", i + 1); } return batchBoxs; } @Override public List<AssetCodeBean> assetCodeSort(List<AssetCodeBean> assetCodeArrays) { return assetCodeArrays; } @Override public BaseAdapter getAssetCodeAdapter() { return new CommonAssetCodeAdapter(R.layout.item_assetcode, new ArrayList<>()); } @Override public int getAssetCodeLength() { return 18; } @Override public int getAssetCodeDaoIndex(int index) { return index; } @Override public List<AssetCodeBean> handleAssetCode(List<AssetCodeBean> assetCodeArrays) { return assetCodeArrays; } public static String getRealBoxName(String boxName) { return getLockId(boxName); } //add by xuemeng private static String getLockId(String boxName) { //板id String BId = boxName.substring(0, 1); //锁id String LId = boxName.substring(1, 3); //Z主柜 if (BId.equals("Z")) { return boxName; } //副柜 List<AssetCodeDao> boxIdArrays = DaoTools.getAssetCodes(); if (boxIdArrays.size() == 0) { return boxName; } int BIndex = getIndex(BId, boxIdArrays); if (BIndex == -1) { return boxName; } String newBid; if (Integer.parseInt(LId) <= 22) { newBid = Tools.numberToLetter(BIndex) + LId; } else { if (getBoxCount(BId, boxIdArrays) == 2) { int newLid = Integer.parseInt(LId) - 22; newBid = Tools.numberToLetter(BIndex + 1) + String.format("%02d", newLid); } else { newBid = Tools.numberToLetter(BIndex) + String.format("%02d", Integer.parseInt(LId)); } } Log.e("getRealBoxName", newBid); return newBid; } //add by xuemeng private static int getIndex(String BId, List<AssetCodeDao> boxIdArrays) { for (int i = 0; i < boxIdArrays.size(); i++) { if (boxIdArrays.get(i).getBoxId().contains(BId)) { return i; } } return -1; } private static int getBoxCount(String BId, List<AssetCodeDao> boxIdArrays) { int count = 0; for (int i = 0; i < boxIdArrays.size(); i++) { if (boxIdArrays.get(i).getBoxId().contains(BId)) { count++; } } return count; } public static List<AssetCodeBean> rmRepeatAssetCode(List<AssetCodeBean> list) { List<AssetCodeBean> newlist = new ArrayList<>(); newlist.addAll(list); for (int i = 0; i < newlist.size() - 1; i++) { for (int j = newlist.size() - 1; j > i; j--) { if (newlist.get(j).getBoxId().equals(newlist.get(i).getBoxId())) { newlist.remove(j); } } } return newlist; } @Override public boolean configureCheck(Context context, ILocker locker, boolean isNeedLoadAssetCode) { String qrcode = ConfigureTools.getQrCode(context); if (TextUtils.isEmpty(qrcode)) { ConfigureTools.setQrCode(context, Constant.ScannerTYPE.DEWO); } String qrcodeCom = ConfigureTools.getQrCodeTty(context); if (TextUtils.isEmpty(qrcodeCom)) { if (ConfigureTools.getQrCode(context).equals(Constant.ScannerTYPE.HONEYWELL_USB) || ConfigureTools.getQrCode(context).equals(Constant.ScannerTYPE._4102S) || ConfigureTools.getQrCode(context).equals(Constant.ScannerTYPE.FM50)) { ConfigureTools.setQrCodeTty(context, "/dev/ttyACM0"); } else { ConfigureTools.setQrCodeTty(context, "/dev/ttymxc2"); } } String printer = ConfigureTools.getPrinter(context); if (TextUtils.isEmpty(printer)) { ConfigureTools.setPrinter(context, Constant.PrinterTYPE.QR); } String printerCom = ConfigureTools.getPrinterTty(context); if (TextUtils.isEmpty(printerCom)) { ConfigureTools.setPrinterTty(context, "/dev/ttymxc4"); } if (isNeedLoadAssetCode) { if (DaoTools.getAssetCodes().size() == 0) { locker.saveCodes(); } } return true; } }
UTF-8
Java
6,761
java
ThreeColumns.java
Java
[ { "context": " return getLockId(boxName);\n }\n\n //add by xuemeng\n private static String getLockId(String boxNam", "end": 3160, "score": 0.9996525049209595, "start": 3153, "tag": "USERNAME", "value": "xuemeng" }, { "context": "ewBid);\n return newBid;\n }\n\n //add by xuemeng\n private static int getIndex(String BId, List<", "end": 4270, "score": 0.9994218945503235, "start": 4263, "tag": "USERNAME", "value": "xuemeng" } ]
null
[]
package com.rocktech.boarddriver.coremodule.lockcontrol.handleresult.customized; import android.content.Context; import android.text.TextUtils; import android.util.Log; import com.rocktech.boarddriver.R; import com.rocktech.boarddriver.bean.AssetCodeBean; import com.rocktech.boarddriver.bean.AssetCodeDao; import com.rocktech.boarddriver.coremodule.lockcontrol.HandleFactory; import com.rocktech.boarddriver.coremodule.lockcontrol.ILocker; import com.rocktech.boarddriver.tools.ConfigureTools; import com.rocktech.boarddriver.tools.Constant; import com.rocktech.boarddriver.tools.DaoTools; import com.rocktech.boarddriver.tools.Tools; import com.rocktech.boarddriver.ui.adapter.BaseAdapter; import com.rocktech.boarddriver.ui.adapter.CommonAssetCodeAdapter; import java.util.ArrayList; import java.util.List; public class ThreeColumns implements ICustomized { @Override public boolean checkLockState(byte[] LISHIZHI, String boxId, String assetCode, Context context) { return HandleFactory.produceHandle(ConfigureTools.getBoardTypeBean(context).getId()).stateOpenSingleLock(LISHIZHI, boxId, context); } @Override public String[] getAllCheckStateLock(String assetCode, String boxIndex) { String[] batchBoxs; int length; if (boxIndex.substring(0, 1).equals("Z")) { length = 8; } else { if (assetCode.substring(9, 11).equals("03") || assetCode.substring(9, 11).equals("04")) { length = 45; } else { length = 22; } } batchBoxs = new String[length]; for (int i = 0; i < batchBoxs.length; i++) { batchBoxs[i] = boxIndex.substring(0, 1) + String.format("%02d", i + 1); } return batchBoxs; } @Override public String[] getAllOpenLock(String assetCode, String boxIndex) { String[] batchBoxs; int length; if (boxIndex.substring(0, 1).equals("Z")) { length = 8; } else { if (assetCode.substring(9, 11).equals("03") || assetCode.substring(9, 11).equals("04")) { length = 45; } else { length = 22; } } batchBoxs = new String[length]; for (int i = 0; i < batchBoxs.length; i++) { batchBoxs[i] = boxIndex.substring(0, 1) + String.format("%02d", i + 1); } return batchBoxs; } @Override public List<AssetCodeBean> assetCodeSort(List<AssetCodeBean> assetCodeArrays) { return assetCodeArrays; } @Override public BaseAdapter getAssetCodeAdapter() { return new CommonAssetCodeAdapter(R.layout.item_assetcode, new ArrayList<>()); } @Override public int getAssetCodeLength() { return 18; } @Override public int getAssetCodeDaoIndex(int index) { return index; } @Override public List<AssetCodeBean> handleAssetCode(List<AssetCodeBean> assetCodeArrays) { return assetCodeArrays; } public static String getRealBoxName(String boxName) { return getLockId(boxName); } //add by xuemeng private static String getLockId(String boxName) { //板id String BId = boxName.substring(0, 1); //锁id String LId = boxName.substring(1, 3); //Z主柜 if (BId.equals("Z")) { return boxName; } //副柜 List<AssetCodeDao> boxIdArrays = DaoTools.getAssetCodes(); if (boxIdArrays.size() == 0) { return boxName; } int BIndex = getIndex(BId, boxIdArrays); if (BIndex == -1) { return boxName; } String newBid; if (Integer.parseInt(LId) <= 22) { newBid = Tools.numberToLetter(BIndex) + LId; } else { if (getBoxCount(BId, boxIdArrays) == 2) { int newLid = Integer.parseInt(LId) - 22; newBid = Tools.numberToLetter(BIndex + 1) + String.format("%02d", newLid); } else { newBid = Tools.numberToLetter(BIndex) + String.format("%02d", Integer.parseInt(LId)); } } Log.e("getRealBoxName", newBid); return newBid; } //add by xuemeng private static int getIndex(String BId, List<AssetCodeDao> boxIdArrays) { for (int i = 0; i < boxIdArrays.size(); i++) { if (boxIdArrays.get(i).getBoxId().contains(BId)) { return i; } } return -1; } private static int getBoxCount(String BId, List<AssetCodeDao> boxIdArrays) { int count = 0; for (int i = 0; i < boxIdArrays.size(); i++) { if (boxIdArrays.get(i).getBoxId().contains(BId)) { count++; } } return count; } public static List<AssetCodeBean> rmRepeatAssetCode(List<AssetCodeBean> list) { List<AssetCodeBean> newlist = new ArrayList<>(); newlist.addAll(list); for (int i = 0; i < newlist.size() - 1; i++) { for (int j = newlist.size() - 1; j > i; j--) { if (newlist.get(j).getBoxId().equals(newlist.get(i).getBoxId())) { newlist.remove(j); } } } return newlist; } @Override public boolean configureCheck(Context context, ILocker locker, boolean isNeedLoadAssetCode) { String qrcode = ConfigureTools.getQrCode(context); if (TextUtils.isEmpty(qrcode)) { ConfigureTools.setQrCode(context, Constant.ScannerTYPE.DEWO); } String qrcodeCom = ConfigureTools.getQrCodeTty(context); if (TextUtils.isEmpty(qrcodeCom)) { if (ConfigureTools.getQrCode(context).equals(Constant.ScannerTYPE.HONEYWELL_USB) || ConfigureTools.getQrCode(context).equals(Constant.ScannerTYPE._4102S) || ConfigureTools.getQrCode(context).equals(Constant.ScannerTYPE.FM50)) { ConfigureTools.setQrCodeTty(context, "/dev/ttyACM0"); } else { ConfigureTools.setQrCodeTty(context, "/dev/ttymxc2"); } } String printer = ConfigureTools.getPrinter(context); if (TextUtils.isEmpty(printer)) { ConfigureTools.setPrinter(context, Constant.PrinterTYPE.QR); } String printerCom = ConfigureTools.getPrinterTty(context); if (TextUtils.isEmpty(printerCom)) { ConfigureTools.setPrinterTty(context, "/dev/ttymxc4"); } if (isNeedLoadAssetCode) { if (DaoTools.getAssetCodes().size() == 0) { locker.saveCodes(); } } return true; } }
6,761
0.595347
0.583346
197
33.258884
28.270611
139
false
false
0
0
0
0
0
0
0.649746
false
false
11
822c0cbd110882435f931049fa97525bfb41caba
343,597,438,065
0d059f6be160768bac4df678794bf81f179a89ff
/src/poly101/Poly10101.java
fe9d2aa117469c896af71d52ff279a7de0561ce7
[]
no_license
urgyen/H2
https://github.com/urgyen/H2
765c351ed8fe9732d3bd56afc98058b70ba926c0
b21d9e31a2764f57626795bcebadafca7f049e14
refs/heads/master
2022-09-03T20:08:43.763000
2020-05-26T04:06:26
2020-05-26T04:06:26
263,232,554
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package poly101; public class Poly10101 { public static void main(String[] args) { // TODO Auto-generated method stub // addNumbers(1,2,3,4,5); // addNumbers(5,5,5,5); // addNumbers(3,4); // addNumbers(5.5, 7.5); // // printName("Pratikshya"); // System.out.println("------"); // // String names[] = {"Urgyen", "Adarsh","Pratikshya","Abash" ,"Nisha"}; // // printName(names); // Puppy p1= new Puppy(); // p1.bark(); // } //addtwoIntNumbers //addtwoDoubleNumbers //add threeIntNumbers //addthreeDoubleNumbers //.. //.. //Polymorphism? //Method Overloading //on the basis no of argument //on the basis of data type //Method Overriding //Inheritance // // static void addNumbers(int a, int b) { // System.out.println(a+b); // } // // static void addNumbers(double a, double b) { // System.out.println(a+b); // } // // static void addNumbers(int a, int b, int c, int d) { // System.out.println(a+b); // } // static void addNumbers(int a, int b,int c,int d,int e) { // System.out.println(a+b+c+d+e); // } //eutai method bata, single name, group of name static void printName(String name) { System.out.println(name); } static void printName(String nameList[]) { for(String name : nameList) { System.out.println(name); } } }
UTF-8
Java
1,320
java
Poly10101.java
Java
[ { "context": "3,4);\n//\t\taddNumbers(5.5, 7.5);\n//\n//\t\tprintName(\"Pratikshya\");\n//\t\tSystem.out.println(\"------\");\n//\t\t\n//\t\tStr", "end": 253, "score": 0.9997901916503906, "start": 243, "tag": "NAME", "value": "Pratikshya" }, { "context": "ut.println(\"------\");\n//\t\t\n//\t\tString names[] = {\"Urgyen\", \"Adarsh\",\"Pratikshya\",\"Abash\" ,\"Nisha\"};\n//\t\t\n/", "end": 325, "score": 0.9998224377632141, "start": 319, "tag": "NAME", "value": "Urgyen" }, { "context": "(\"------\");\n//\t\t\n//\t\tString names[] = {\"Urgyen\", \"Adarsh\",\"Pratikshya\",\"Abash\" ,\"Nisha\"};\n//\t\t\n//\t\tprintNa", "end": 335, "score": 0.9998109340667725, "start": 329, "tag": "NAME", "value": "Adarsh" }, { "context": ");\n//\t\t\n//\t\tString names[] = {\"Urgyen\", \"Adarsh\",\"Pratikshya\",\"Abash\" ,\"Nisha\"};\n//\t\t\n//\t\tprintName(names);\n\t\t", "end": 348, "score": 0.9997986555099487, "start": 338, "tag": "NAME", "value": "Pratikshya" }, { "context": "tring names[] = {\"Urgyen\", \"Adarsh\",\"Pratikshya\",\"Abash\" ,\"Nisha\"};\n//\t\t\n//\t\tprintName(names);\n\t\t\n\t\t\n//\t\t", "end": 356, "score": 0.9997901916503906, "start": 351, "tag": "NAME", "value": "Abash" }, { "context": "es[] = {\"Urgyen\", \"Adarsh\",\"Pratikshya\",\"Abash\" ,\"Nisha\"};\n//\t\t\n//\t\tprintName(names);\n\t\t\n\t\t\n//\t\tPuppy p1=", "end": 365, "score": 0.9997553825378418, "start": 360, "tag": "NAME", "value": "Nisha" } ]
null
[]
package poly101; public class Poly10101 { public static void main(String[] args) { // TODO Auto-generated method stub // addNumbers(1,2,3,4,5); // addNumbers(5,5,5,5); // addNumbers(3,4); // addNumbers(5.5, 7.5); // // printName("Pratikshya"); // System.out.println("------"); // // String names[] = {"Urgyen", "Adarsh","Pratikshya","Abash" ,"Nisha"}; // // printName(names); // Puppy p1= new Puppy(); // p1.bark(); // } //addtwoIntNumbers //addtwoDoubleNumbers //add threeIntNumbers //addthreeDoubleNumbers //.. //.. //Polymorphism? //Method Overloading //on the basis no of argument //on the basis of data type //Method Overriding //Inheritance // // static void addNumbers(int a, int b) { // System.out.println(a+b); // } // // static void addNumbers(double a, double b) { // System.out.println(a+b); // } // // static void addNumbers(int a, int b, int c, int d) { // System.out.println(a+b); // } // static void addNumbers(int a, int b,int c,int d,int e) { // System.out.println(a+b+c+d+e); // } //eutai method bata, single name, group of name static void printName(String name) { System.out.println(name); } static void printName(String nameList[]) { for(String name : nameList) { System.out.println(name); } } }
1,320
0.608333
0.589394
76
16.368422
16.749582
72
false
false
0
0
0
0
0
0
1.894737
false
false
11
f74024669049186737424a039cdae22882af3383
4,011,499,502,806
f92cb4e687a5bbb4497239e616280288eadc52c1
/FeatDiag/trunk/src/com/eclipse/featdiag/figures/FieldFigure.java
cbacbcf8d59b5853398723ba068ceeb037b1bbf8
[ "BSD-3-Clause" ]
permissive
ebenh/featdiag
https://github.com/ebenh/featdiag
7f1d6f2966f99c9d2ff040f767929c718fc01ff6
95939a96068340cc2cce0ae99dffc2a226ffee0b
refs/heads/master
2021-12-27T10:52:35.267000
2021-12-13T20:25:06
2021-12-13T20:25:06
38,296,512
0
0
null
false
2021-12-13T20:25:07
2015-06-30T08:13:40
2021-12-13T20:18:58
2021-12-13T20:25:06
352
0
0
0
Java
false
false
package com.eclipse.featdiag.figures; import org.eclipse.draw2d.Ellipse; import org.eclipse.draw2d.geometry.Dimension; import com.eclipse.featdiag.models.MemberModel; /** * An ellipse figure representing a field in a class. * @author nic * */ public class FieldFigure extends Ellipse { private String name; public FieldFigure(MemberModel model) { this.name = model.toString(); FigureInitializer.initialize(this, model); Dimension size = getPreferredSize(); setPreferredSize(size.width + 20, size.height + 10); setBounds(model.getBounds()); } /** * Returns the name of this class member image. * The name is the string representation of * the member. * @return */ public String toString() { return name; } }
UTF-8
Java
782
java
FieldFigure.java
Java
[ { "context": "igure representing a field in a class.\r\n * @author nic\r\n *\r\n */\r\npublic class FieldFigure extends Ellips", "end": 255, "score": 0.9911437034606934, "start": 252, "tag": "USERNAME", "value": "nic" } ]
null
[]
package com.eclipse.featdiag.figures; import org.eclipse.draw2d.Ellipse; import org.eclipse.draw2d.geometry.Dimension; import com.eclipse.featdiag.models.MemberModel; /** * An ellipse figure representing a field in a class. * @author nic * */ public class FieldFigure extends Ellipse { private String name; public FieldFigure(MemberModel model) { this.name = model.toString(); FigureInitializer.initialize(this, model); Dimension size = getPreferredSize(); setPreferredSize(size.width + 20, size.height + 10); setBounds(model.getBounds()); } /** * Returns the name of this class member image. * The name is the string representation of * the member. * @return */ public String toString() { return name; } }
782
0.690537
0.682864
35
20.342857
19.181751
54
false
false
0
0
0
0
0
0
1.057143
false
false
11
3724a7f643bbf34f70f899167f21bf26da1097a3
23,974,507,478,904
3361c09ef5ae8cd2de6d3d2bf4b9f3cade3b3b5a
/CashRegisterApp/app/src/main/java/com/example/cashregisterapp/RestockActivity.java
cdb6392d17b322a98d6199a65ad4f2a5d55a8693
[]
no_license
AJDaouda/CashRegisterApp_Version2
https://github.com/AJDaouda/CashRegisterApp_Version2
e94e2466013d48b590075b17c86dbae0f65c4fa9
bdb4f27487a298d9fbac79027fe74e4bf3e5388d
refs/heads/master
2023-09-04T16:32:49.302000
2021-11-19T05:26:44
2021-11-19T05:26:44
428,512,647
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.cashregisterapp; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class RestockActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_restock); } }
UTF-8
Java
346
java
RestockActivity.java
Java
[]
null
[]
package com.example.cashregisterapp; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class RestockActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_restock); } }
346
0.768786
0.768786
14
23.785715
22.552094
56
false
false
0
0
0
0
0
0
0.357143
false
false
11
a8448fa3b2995d072835df7174818fea36489ede
33,105,607,982,194
5611ec0e175ea74f4c23629ee2976c2a7c49b714
/src/strings/Groups.java
b2f2e7f4080954c44e19c2bc0972cdf5b91f16f0
[]
no_license
WYonghui/javaLearning
https://github.com/WYonghui/javaLearning
5d25343dcdedd4eddb9ba6728847755cc4c46ac9
3f652fb1d1d43ac6645efec8ff4aa72f1bb39699
refs/heads/master
2021-08-06T16:21:13.599000
2017-11-06T13:21:03
2017-11-06T13:21:03
109,201,998
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package strings; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by 10564 on 2017-10-26. */ public class Groups { public static final String poem = "Twas briling, and the slithy toves\n" + "Did gyre and gimble in the wabe.\n" + "All mimsy were the borogoves,\n" + "And the mome raths outgrabe.\n\n" + "Beware the Jabberwock, my son,\n" + "The jaws that bite, the claws that catch.\n" + "Beware the Jubjub bird, and shun\n" + "The frumious Bandersnach."; public static void main(String[] args) { Pattern pattern = Pattern.compile("(?m)((\\S+)\\s+(\\S+)\\s+(\\S+))$"); // Pattern pattern = Pattern.compile("(^|\\s)[a-z][\\w&&\\D]*\\b"); Matcher matcher = pattern.matcher(poem); // HashMap<String, Integer> hashMap = new HashMap<>(); while (matcher.find()){ // String m = matcher.group(); // if (hashMap.containsKey(m)){ // hashMap.put(m, hashMap.get(m)+1); // } // else // hashMap.put(m, 1); System.out.println("matched string : "+ matcher.group()); for (int i = 0; i < matcher.groupCount(); i++) { System.out.print("[" + matcher.group(i) + "]"); } System.out.println(); } // System.out.println(hashMap.toString()); } }
UTF-8
Java
1,538
java
Groups.java
Java
[ { "context": "mport java.util.regex.Pattern;\n\n/**\n * Created by 10564 on 2017-10-26.\n */\npublic class Groups {\n\n pub", "end": 132, "score": 0.9986923336982727, "start": 127, "tag": "USERNAME", "value": "10564" } ]
null
[]
package strings; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by 10564 on 2017-10-26. */ public class Groups { public static final String poem = "Twas briling, and the slithy toves\n" + "Did gyre and gimble in the wabe.\n" + "All mimsy were the borogoves,\n" + "And the mome raths outgrabe.\n\n" + "Beware the Jabberwock, my son,\n" + "The jaws that bite, the claws that catch.\n" + "Beware the Jubjub bird, and shun\n" + "The frumious Bandersnach."; public static void main(String[] args) { Pattern pattern = Pattern.compile("(?m)((\\S+)\\s+(\\S+)\\s+(\\S+))$"); // Pattern pattern = Pattern.compile("(^|\\s)[a-z][\\w&&\\D]*\\b"); Matcher matcher = pattern.matcher(poem); // HashMap<String, Integer> hashMap = new HashMap<>(); while (matcher.find()){ // String m = matcher.group(); // if (hashMap.containsKey(m)){ // hashMap.put(m, hashMap.get(m)+1); // } // else // hashMap.put(m, 1); System.out.println("matched string : "+ matcher.group()); for (int i = 0; i < matcher.groupCount(); i++) { System.out.print("[" + matcher.group(i) + "]"); } System.out.println(); } // System.out.println(hashMap.toString()); } }
1,538
0.5013
0.490897
45
33.177776
24.221468
79
false
false
0
0
0
0
0
0
0.622222
false
false
11
0911af8134d6f25e7e52d7dd937b2ed8e1038032
14,405,320,358,360
a343dc8ff4fa861e10f4165efe70953b002a3238
/service1WithFlux/src/main/java/ru/seuslab/service/fluxservice1/service/RestServiceImpl.java
94e72db694e842ad8abbda1887d6991a3172e6ae
[]
no_license
Zloymen/seuslab
https://github.com/Zloymen/seuslab
83808dd62e88635a490c5ac0eb772001907d7733
f9d50f7c559444e3e7d2422d256798febdc6676f
refs/heads/master
2020-04-03T07:41:34.980000
2018-11-30T08:00:43
2018-11-30T08:00:43
155,110,395
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.seuslab.service.fluxservice1.service; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import ru.seuslab.service.fluxservice1.dto.AnswerDto; import ru.seuslab.service.fluxservice1.dto.DetailDto; import javax.annotation.PostConstruct; import java.time.Duration; import static org.springframework.web.util.UriComponentsBuilder.fromHttpUrl; @Service @RequiredArgsConstructor @Slf4j public class RestServiceImpl implements RestService { @Value("${service2.url}") private String url; private WebClient client; @PostConstruct private void post(){ client = WebClient.create(); } @Override public Flux<DetailDto> getAsyncData(String projectName, long millsecond){ return client.get().uri(builder -> fromHttpUrl(url).queryParam("name", projectName).build().toUri()) .exchange() //.take(Duration.ofMillis(millsecond)) .timeout(Duration.ofMillis(millsecond)) .flatMap(item -> item.bodyToMono(AnswerDto.class)) .flatMap(item -> Mono.just(item.getItems())) .flatMapMany(Flux::fromIterable); } }
UTF-8
Java
1,445
java
RestServiceImpl.java
Java
[]
null
[]
package ru.seuslab.service.fluxservice1.service; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import ru.seuslab.service.fluxservice1.dto.AnswerDto; import ru.seuslab.service.fluxservice1.dto.DetailDto; import javax.annotation.PostConstruct; import java.time.Duration; import static org.springframework.web.util.UriComponentsBuilder.fromHttpUrl; @Service @RequiredArgsConstructor @Slf4j public class RestServiceImpl implements RestService { @Value("${service2.url}") private String url; private WebClient client; @PostConstruct private void post(){ client = WebClient.create(); } @Override public Flux<DetailDto> getAsyncData(String projectName, long millsecond){ return client.get().uri(builder -> fromHttpUrl(url).queryParam("name", projectName).build().toUri()) .exchange() //.take(Duration.ofMillis(millsecond)) .timeout(Duration.ofMillis(millsecond)) .flatMap(item -> item.bodyToMono(AnswerDto.class)) .flatMap(item -> Mono.just(item.getItems())) .flatMapMany(Flux::fromIterable); } }
1,445
0.711419
0.706574
47
29.74468
25.183132
89
false
false
0
0
0
0
0
0
0.404255
false
false
11
cd99ccb631ffbc0c3f9b8c83f31c6ed3d69b0f11
30,039,001,282,252
6186a84f9d09c6b68302501d3feb245cfc77c323
/src/main/java/com/example/helloworld/core/Template.java
7483bb09bdcdf9634784937fe6bb42681f4d6fa4
[]
no_license
ybudweiser/dropwizard-example
https://github.com/ybudweiser/dropwizard-example
e8bd4b4ddca8b64bcbc8e1fea878f2138dc3bf61
dccaf200b44a0039927e21fcfc5573dd66fd0d75
refs/heads/master
2020-09-09T14:29:48.328000
2019-11-22T14:19:58
2019-11-22T14:19:58
221,471,716
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.helloworld.core; import lombok.AllArgsConstructor; import java.util.Optional; import static java.lang.String.format; @AllArgsConstructor public class Template { private final String content; private final String defaultName; public String render(Optional<String> name) { return format(content, name.orElse(defaultName)); } }
UTF-8
Java
374
java
Template.java
Java
[]
null
[]
package com.example.helloworld.core; import lombok.AllArgsConstructor; import java.util.Optional; import static java.lang.String.format; @AllArgsConstructor public class Template { private final String content; private final String defaultName; public String render(Optional<String> name) { return format(content, name.orElse(defaultName)); } }
374
0.754011
0.754011
17
21
18.83676
57
false
false
0
0
0
0
0
0
0.470588
false
false
11
d40e86b4eb7aac6002db8cc4d252af6c025d0c8a
17,540,646,472,233
2b6e70470567692d2e32a8b109be355c9a7bdb00
/colormipsearch-tools/src/main/java/org/janelia/colormipsearch/cmd/TagNeuronMetadataCmd.java
a1a966fd385061381108d8b08f8e86ba9be6a160
[ "BSD-3-Clause" ]
permissive
JaneliaSciComp/colormipsearch
https://github.com/JaneliaSciComp/colormipsearch
3896c7f6546fa7e3f74f475e4b3a71df974092d9
d630475bade9f2050307f75ed20c114c4f073796
refs/heads/main
2023-07-20T14:33:46.790000
2023-07-13T21:13:50
2023-07-13T21:13:50
98,349,943
0
0
BSD-3-Clause
false
2023-07-07T18:46:33
2017-07-25T21:05:18
2022-05-27T18:20:37
2023-07-07T18:46:32
3,635
0
0
1
Java
false
false
package org.janelia.colormipsearch.cmd; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.google.common.collect.ImmutableMap; import org.janelia.colormipsearch.dao.AppendFieldValueHandler; import org.janelia.colormipsearch.dao.DaosProvider; import org.janelia.colormipsearch.dao.NeuronSelector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class TagNeuronMetadataCmd extends AbstractCmd { private static final Logger LOG = LoggerFactory.getLogger(TagNeuronMetadataCmd.class); @Parameters(commandDescription = "Tag neuron metadata") static class TagNeuronMetadataArgs extends AbstractCmdArgs { @Parameter(names = {"-as", "--alignment-space"}, description = "Alignment space") String alignmentSpace; @Parameter(names = {"-l", "--library"}, description = "Library names from which mips or matches are selected for export", variableArity = true) List<String> libraries = new ArrayList<>(); @Parameter(names = {"--processing-tags"}, variableArity = true, converter = NameValueArg.NameArgConverter.class, description = "Processing tags to select") List<NameValueArg> processingTags = new ArrayList<>(); @Parameter(names = {"--data-tags"}, variableArity = true, description = "Data tags to select") List<String> dataTags = new ArrayList<>(); @Parameter(names = {"--excluded-data-tags"}, variableArity = true, description = "If any of these tags is present do not assign the new tag") List<String> excludedDataTags = new ArrayList<>(); @Parameter(names = {"--tag"}, required = true, description = "Tag to assign") String tag; TagNeuronMetadataArgs(CommonArgs commonArgs) { super(commonArgs); } } private final TagNeuronMetadataArgs args; TagNeuronMetadataCmd(String commandName, CommonArgs commonArgs) { super(commandName); this.args = new TagNeuronMetadataArgs(commonArgs); } @Override TagNeuronMetadataArgs getArgs() { return args; } @Override void execute() { updateNeuronMetadataTags(); } private void updateNeuronMetadataTags() { NeuronSelector neuronSelector = new NeuronSelector() .setAlignmentSpace(args.alignmentSpace) .addLibraries(args.libraries) .addTags(args.dataTags) .addExcludedTags(args.excludedDataTags); args.processingTags.forEach(nv -> neuronSelector.addNewProcessedTagsSelection(nv.argName, nv.argValues)); DaosProvider daosProvider = getDaosProvider(); long nUpdates = daosProvider.getNeuronMetadataDao().updateAll( neuronSelector, ImmutableMap.of("tags", new AppendFieldValueHandler<>(Collections.singleton(args.tag)))); LOG.info("Tagged {} entries with {}", nUpdates, args.tag); } }
UTF-8
Java
3,049
java
TagNeuronMetadataCmd.java
Java
[]
null
[]
package org.janelia.colormipsearch.cmd; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.google.common.collect.ImmutableMap; import org.janelia.colormipsearch.dao.AppendFieldValueHandler; import org.janelia.colormipsearch.dao.DaosProvider; import org.janelia.colormipsearch.dao.NeuronSelector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class TagNeuronMetadataCmd extends AbstractCmd { private static final Logger LOG = LoggerFactory.getLogger(TagNeuronMetadataCmd.class); @Parameters(commandDescription = "Tag neuron metadata") static class TagNeuronMetadataArgs extends AbstractCmdArgs { @Parameter(names = {"-as", "--alignment-space"}, description = "Alignment space") String alignmentSpace; @Parameter(names = {"-l", "--library"}, description = "Library names from which mips or matches are selected for export", variableArity = true) List<String> libraries = new ArrayList<>(); @Parameter(names = {"--processing-tags"}, variableArity = true, converter = NameValueArg.NameArgConverter.class, description = "Processing tags to select") List<NameValueArg> processingTags = new ArrayList<>(); @Parameter(names = {"--data-tags"}, variableArity = true, description = "Data tags to select") List<String> dataTags = new ArrayList<>(); @Parameter(names = {"--excluded-data-tags"}, variableArity = true, description = "If any of these tags is present do not assign the new tag") List<String> excludedDataTags = new ArrayList<>(); @Parameter(names = {"--tag"}, required = true, description = "Tag to assign") String tag; TagNeuronMetadataArgs(CommonArgs commonArgs) { super(commonArgs); } } private final TagNeuronMetadataArgs args; TagNeuronMetadataCmd(String commandName, CommonArgs commonArgs) { super(commandName); this.args = new TagNeuronMetadataArgs(commonArgs); } @Override TagNeuronMetadataArgs getArgs() { return args; } @Override void execute() { updateNeuronMetadataTags(); } private void updateNeuronMetadataTags() { NeuronSelector neuronSelector = new NeuronSelector() .setAlignmentSpace(args.alignmentSpace) .addLibraries(args.libraries) .addTags(args.dataTags) .addExcludedTags(args.excludedDataTags); args.processingTags.forEach(nv -> neuronSelector.addNewProcessedTagsSelection(nv.argName, nv.argValues)); DaosProvider daosProvider = getDaosProvider(); long nUpdates = daosProvider.getNeuronMetadataDao().updateAll( neuronSelector, ImmutableMap.of("tags", new AppendFieldValueHandler<>(Collections.singleton(args.tag)))); LOG.info("Tagged {} entries with {}", nUpdates, args.tag); } }
3,049
0.683175
0.682519
78
38.089745
33.395142
149
false
false
0
0
0
0
0
0
0.641026
false
false
11
8124bd2794cf059714466cf966ddac6d7ef5db0a
15,247,133,905,813
0c2aa69aece23013ec328b2ac2666681bc1b4451
/imageloader/src/main/java/com/xpf/android/imageloader/config/LoaderConfig.java
44e86eb80b4f9b7a81b92968a2f466565bc29fdd
[]
no_license
xinpengfei520/MyImageLoader
https://github.com/xinpengfei520/MyImageLoader
84e857338c5ba2f8396a7e0e30359bf96bc46d9b
a023fb88bd80d5d284da437d2ed9304b982904b6
refs/heads/master
2022-06-23T10:27:17.250000
2019-06-12T07:29:52
2019-06-12T07:29:52
107,878,972
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xpf.android.imageloader.config; import com.xpf.android.imageloader.cache.ImageCache; import com.xpf.android.imageloader.cache.MemoryCache; import com.xpf.android.imageloader.policy.LoadPolicy; import com.xpf.android.imageloader.policy.SerialPolicy; /** * Created by xpf on 2017/10/22 :) * Function:ImageLoader 配置类 */ public class LoaderConfig { /** * 缓存策略,默认为内存缓存 */ public ImageCache mImageCache = new MemoryCache(); /** * 加载图片时的 loading 和加载失败的图片配置对象 */ public DisplayConfig mDisplayConfig = new DisplayConfig(); /** * 加载策略 */ public LoadPolicy mLoadPolicy = new SerialPolicy(); /** * 线程数,默认为 CPU 核心数 + 1 */ public int mThreadCount = Runtime.getRuntime().availableProcessors() + 1; /** * 设置线程数,最小为1,使用 max 防止当用户设置了小于 1 的线程数 * * @param count * @return */ public LoaderConfig setThreadCount(int count) { mThreadCount = Math.max(1, count); return this; } /** * 设置缓存策略 * * @param cache * @return */ public LoaderConfig setCache(ImageCache cache) { mImageCache = cache; return this; } /** * 设置占位图 * * @param resId * @return */ public LoaderConfig setLoadPlaceholder(int resId) { mDisplayConfig.loadingResId = resId; return this; } /** * 设置加载失败的图片 * * @param resId * @return */ public LoaderConfig setFailedPlaceholder(int resId) { mDisplayConfig.failedResId = resId; return this; } /** * 设置加载策略 * * @param policy * @return */ public LoaderConfig setLoadPolicy(LoadPolicy policy) { if (policy != null) { mLoadPolicy = policy; } return this; } }
UTF-8
Java
2,018
java
LoaderConfig.java
Java
[ { "context": "mageloader.policy.SerialPolicy;\n\n/**\n * Created by xpf on 2017/10/22 :)\n * Function:ImageLoader 配置类\n */\n", "end": 284, "score": 0.9993906021118164, "start": 281, "tag": "USERNAME", "value": "xpf" } ]
null
[]
package com.xpf.android.imageloader.config; import com.xpf.android.imageloader.cache.ImageCache; import com.xpf.android.imageloader.cache.MemoryCache; import com.xpf.android.imageloader.policy.LoadPolicy; import com.xpf.android.imageloader.policy.SerialPolicy; /** * Created by xpf on 2017/10/22 :) * Function:ImageLoader 配置类 */ public class LoaderConfig { /** * 缓存策略,默认为内存缓存 */ public ImageCache mImageCache = new MemoryCache(); /** * 加载图片时的 loading 和加载失败的图片配置对象 */ public DisplayConfig mDisplayConfig = new DisplayConfig(); /** * 加载策略 */ public LoadPolicy mLoadPolicy = new SerialPolicy(); /** * 线程数,默认为 CPU 核心数 + 1 */ public int mThreadCount = Runtime.getRuntime().availableProcessors() + 1; /** * 设置线程数,最小为1,使用 max 防止当用户设置了小于 1 的线程数 * * @param count * @return */ public LoaderConfig setThreadCount(int count) { mThreadCount = Math.max(1, count); return this; } /** * 设置缓存策略 * * @param cache * @return */ public LoaderConfig setCache(ImageCache cache) { mImageCache = cache; return this; } /** * 设置占位图 * * @param resId * @return */ public LoaderConfig setLoadPlaceholder(int resId) { mDisplayConfig.loadingResId = resId; return this; } /** * 设置加载失败的图片 * * @param resId * @return */ public LoaderConfig setFailedPlaceholder(int resId) { mDisplayConfig.failedResId = resId; return this; } /** * 设置加载策略 * * @param policy * @return */ public LoaderConfig setLoadPolicy(LoadPolicy policy) { if (policy != null) { mLoadPolicy = policy; } return this; } }
2,018
0.586264
0.579121
87
19.91954
18.917982
77
false
false
0
0
0
0
0
0
0.229885
false
false
11
9580410768a5b31db17893c7d5bf2e3a6931fe6a
32,289,564,195,198
7b850fde80d14cd6dfe1eeeff5f401745a77764c
/chapter_002/src/main/java/ru/job4j/tracker/ValidateInput.java
e55c9c0b922bd889b8db7faba9c24cb02bcf849c
[ "Apache-2.0" ]
permissive
AlekseyKarpov/akarpov
https://github.com/AlekseyKarpov/akarpov
11b077ea9528d477c300dabc1d3f72070236ca5b
41e9d704cfea8fff87ad207c6f3e8a725f824ad4
refs/heads/master
2020-02-27T07:48:34.749000
2017-12-11T18:15:07
2017-12-11T18:15:07
83,635,548
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.job4j.tracker; /** * Created by Екатерина on 13.08.2017. */ public class ValidateInput { }
UTF-8
Java
114
java
ValidateInput.java
Java
[ { "context": "package ru.job4j.tracker;\n\n/**\n * Created by Екатерина on 13.08.2017.\n */\npublic class ValidateInput {\n}", "end": 54, "score": 0.9998031258583069, "start": 45, "tag": "NAME", "value": "Екатерина" } ]
null
[]
package ru.job4j.tracker; /** * Created by Екатерина on 13.08.2017. */ public class ValidateInput { }
114
0.695238
0.609524
7
14
14.638501
38
false
false
0
0
0
0
0
0
0.142857
false
false
11
6a7ddaa352ce5e462c67d230b1c778b563b3d108
22,514,218,623,822
79f93f5228b8e000f52a8b93be5c18dbd39ea708
/src/main/java/br/net/luana/sistema/resources/materiaPrimaResources/ColcheteResourceImpl.java
aba7035c67a65baa05253b16db5f26f4b47f8ce2
[]
no_license
Luan-Ferrari/br.net.luana.SistemaEstoque
https://github.com/Luan-Ferrari/br.net.luana.SistemaEstoque
c5d79bb91cdb76e0baabd922fcc398574c8ca408
ac3e3e5a117033dc5229d4c7fe5da552b24451c0
refs/heads/master
2023-07-18T20:45:36.080000
2021-09-28T11:03:53
2021-09-28T11:03:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.net.luana.sistema.resources.materiaPrimaResources; import br.net.luana.sistema.domain.materiasprimas.Colchete; import br.net.luana.sistema.dto.materiaPrimaDTOs.ColcheteDTO; import br.net.luana.sistema.services.materiaPrimaService.ColcheteService; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/colchete") public class ColcheteResourceImpl extends MateriaPrimaResourceImpl<Colchete, ColcheteDTO, Integer> implements ColcheteResource { private ColcheteService colcheteService; public ColcheteResourceImpl(ColcheteService colcheteService) { super(colcheteService); } }
UTF-8
Java
647
java
ColcheteResourceImpl.java
Java
[]
null
[]
package br.net.luana.sistema.resources.materiaPrimaResources; import br.net.luana.sistema.domain.materiasprimas.Colchete; import br.net.luana.sistema.dto.materiaPrimaDTOs.ColcheteDTO; import br.net.luana.sistema.services.materiaPrimaService.ColcheteService; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/colchete") public class ColcheteResourceImpl extends MateriaPrimaResourceImpl<Colchete, ColcheteDTO, Integer> implements ColcheteResource { private ColcheteService colcheteService; public ColcheteResourceImpl(ColcheteService colcheteService) { super(colcheteService); } }
647
0.814529
0.814529
19
33.052631
30.049911
98
false
false
0
0
0
0
0
0
0.473684
false
false
11
c017c42d8aa277c01d30e50d06ffc954b6305342
22,943,715,318,600
104e808eb69257e74342f74f04e3afc0f8724c7d
/swing/contabilita/src/main/java/it/eurotn/panjea/contabilita/rich/editors/riepilogoblacklist/ParametriRicercaRiepilogoBlacklist.java
779bd7d87d6e7251cd5be0af0d583a439fe51d6d
[]
no_license
glarentis/panjea
https://github.com/glarentis/panjea
2ce1e58650571ef84a01a9c7b02ceaeedddae185
fec3b3d85aa6737c9d95a684542f71844877b663
refs/heads/master
2021-01-17T19:19:57.625000
2016-05-30T10:14:05
2016-05-30T10:14:05
60,000,690
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package it.eurotn.panjea.contabilita.rich.editors.riepilogoblacklist; import java.util.Date; /** * @author fattazzo * */ public class ParametriRicercaRiepilogoBlacklist { private Date dataIniziale; private Date dataFinale; /** * @return the dataFinale */ public Date getDataFinale() { return dataFinale; } /** * @return the dataIniziale */ public Date getDataIniziale() { return dataIniziale; } /** * @param dataFinale * the dataFinale to set */ public void setDataFinale(Date dataFinale) { this.dataFinale = dataFinale; } /** * @param dataIniziale * the dataIniziale to set */ public void setDataIniziale(Date dataIniziale) { this.dataIniziale = dataIniziale; } }
UTF-8
Java
754
java
ParametriRicercaRiepilogoBlacklist.java
Java
[ { "context": "blacklist;\n\nimport java.util.Date;\n\n/**\n * @author fattazzo\n * \n */\npublic class ParametriRicercaRiepilogoBla", "end": 130, "score": 0.9991500377655029, "start": 122, "tag": "USERNAME", "value": "fattazzo" } ]
null
[]
/** * */ package it.eurotn.panjea.contabilita.rich.editors.riepilogoblacklist; import java.util.Date; /** * @author fattazzo * */ public class ParametriRicercaRiepilogoBlacklist { private Date dataIniziale; private Date dataFinale; /** * @return the dataFinale */ public Date getDataFinale() { return dataFinale; } /** * @return the dataIniziale */ public Date getDataIniziale() { return dataIniziale; } /** * @param dataFinale * the dataFinale to set */ public void setDataFinale(Date dataFinale) { this.dataFinale = dataFinale; } /** * @param dataIniziale * the dataIniziale to set */ public void setDataIniziale(Date dataIniziale) { this.dataIniziale = dataIniziale; } }
754
0.668435
0.668435
48
14.708333
16.934874
69
false
false
0
0
0
0
0
0
0.833333
false
false
11
95501a4d28948ace1ca422c85cd43e9d344d1fca
5,626,407,181,539
760c4d09f15e9e8dd5b6d52a976b4eecaffbe34e
/src/main/java/com/squib/clgame/clworld/InventoryItem.java
463f21bde121f46eb41d385536a36de6c5e07a9f
[ "MIT" ]
permissive
thesquib/clparser
https://github.com/thesquib/clparser
91b4d9620dba66f0e6c9f7ae887f86f20fb7125f
5b8548e3ee2880ac6104ea43145360598fd60ce1
refs/heads/master
2016-08-07T04:28:38.756000
2015-09-23T09:09:06
2015-09-23T09:09:06
26,483,055
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.squib.clgame.clworld; /** * Created by thesquib on 2/11/14. * * Contains the information read from a frame which relates to Inventory: * InventoryId, equipped status, custom strings. */ public class InventoryItem { private int inventoryPosition; private int inventoryId; private int sameItemCount; private boolean isEquipped; private String customString; private int settings; private int settingsMultivalues;// ? public int getSettings() { return settings; } public void setSettings(int settings) { this.settings = settings; } public int getSettingsMultivalues() { return settingsMultivalues; } public void setSettingsMultivalues(int settingsMultivalues) { this.settingsMultivalues = settingsMultivalues; } public InventoryItem(int pos, int id, boolean equipped) { this.inventoryPosition = pos; this.inventoryId = id; this.isEquipped = equipped; customString = null; sameItemCount = 0; } public InventoryItem(int pos, int id, boolean equipped, String customString){ this(pos,id,equipped); this.customString = customString; } public void incrementItemCount() { sameItemCount ++; } public void decrementItemCount() { sameItemCount --; } public void setSameItemCount(int i){ sameItemCount = i; } public int getSameItemCount() { return sameItemCount; } public int getInventoryId() { return inventoryId; } public void setInventoryId(int inventoryId) { this.inventoryId = inventoryId; } public int getInventoryPosition() { return inventoryPosition; } public void setInventoryPosition(int inventoryPosition) { this.inventoryPosition = inventoryPosition; } public boolean isEquipped() { return isEquipped; } public void setEquipped(boolean isEquipped) { this.isEquipped = isEquipped; } public String getCustomString() { return customString; } public void setCustomString(String customString) { this.customString = customString; } }
UTF-8
Java
1,949
java
InventoryItem.java
Java
[ { "context": "ckage com.squib.clgame.clworld;\n\n/**\n * Created by thesquib on 2/11/14.\n *\n * Contains the information read f", "end": 61, "score": 0.9995024800300598, "start": 53, "tag": "USERNAME", "value": "thesquib" } ]
null
[]
package com.squib.clgame.clworld; /** * Created by thesquib on 2/11/14. * * Contains the information read from a frame which relates to Inventory: * InventoryId, equipped status, custom strings. */ public class InventoryItem { private int inventoryPosition; private int inventoryId; private int sameItemCount; private boolean isEquipped; private String customString; private int settings; private int settingsMultivalues;// ? public int getSettings() { return settings; } public void setSettings(int settings) { this.settings = settings; } public int getSettingsMultivalues() { return settingsMultivalues; } public void setSettingsMultivalues(int settingsMultivalues) { this.settingsMultivalues = settingsMultivalues; } public InventoryItem(int pos, int id, boolean equipped) { this.inventoryPosition = pos; this.inventoryId = id; this.isEquipped = equipped; customString = null; sameItemCount = 0; } public InventoryItem(int pos, int id, boolean equipped, String customString){ this(pos,id,equipped); this.customString = customString; } public void incrementItemCount() { sameItemCount ++; } public void decrementItemCount() { sameItemCount --; } public void setSameItemCount(int i){ sameItemCount = i; } public int getSameItemCount() { return sameItemCount; } public int getInventoryId() { return inventoryId; } public void setInventoryId(int inventoryId) { this.inventoryId = inventoryId; } public int getInventoryPosition() { return inventoryPosition; } public void setInventoryPosition(int inventoryPosition) { this.inventoryPosition = inventoryPosition; } public boolean isEquipped() { return isEquipped; } public void setEquipped(boolean isEquipped) { this.isEquipped = isEquipped; } public String getCustomString() { return customString; } public void setCustomString(String customString) { this.customString = customString; } }
1,949
0.746537
0.743458
93
19.956989
19.184959
78
false
false
0
0
0
0
0
0
1.387097
false
false
11
651071a3bcd81514e86d0b51078b7fbacb8117ba
17,523,466,569,821
03153c8417ad34d92921a4c5dbcced3f28d8bc37
/src/main/java/com/faforever/moderatorclient/api/domain/events/MessagesChangedEvent.java
fc6a86b8527eebcdd2b5f7674a8984113d5e8605
[ "MIT" ]
permissive
FAForever/faf-moderator-client
https://github.com/FAForever/faf-moderator-client
22a5edad52558948ee71fe3d1595a0732cd0d465
42359d161db36df24c30e0e0863ce7e76f6ba1c2
refs/heads/develop
2023-03-03T14:57:37.376000
2022-07-29T00:34:23
2022-07-29T00:34:23
110,305,246
4
13
MIT
false
2023-08-25T03:25:34
2017-11-11T00:24:48
2023-08-19T13:36:02
2023-08-25T03:25:34
1,185
3
9
7
Java
false
false
package com.faforever.moderatorclient.api.domain.events; public class MessagesChangedEvent { }
UTF-8
Java
96
java
MessagesChangedEvent.java
Java
[]
null
[]
package com.faforever.moderatorclient.api.domain.events; public class MessagesChangedEvent { }
96
0.833333
0.833333
4
23
23.695992
56
false
false
0
0
0
0
0
0
0.25
false
false
11
56530bca9bb36225b78e66f087fb560280437820
13,477,607,375,640
2e5fb39b2fa60918d8ce2de1597984a6e5354763
/src/main/java/elec332/core/util/EnumHelper.java
e717c05850ec77b306411af4f00e9d410506d91e
[]
no_license
asiekierka/ElecCore
https://github.com/asiekierka/ElecCore
00855c2b305e6282a0b7566e8dc9ffa7f5567d39
151c0756f9625f6f5173c1e425fe9f0b9bbc4cf6
refs/heads/master
2021-06-22T21:56:31.598000
2017-08-16T17:21:14
2017-08-16T17:21:14
100,284,369
1
0
null
true
2017-08-14T15:49:23
2017-08-14T15:49:23
2017-04-10T14:18:32
2017-08-12T10:57:46
1,516
0
0
0
null
null
null
package elec332.core.util; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import net.minecraft.util.EnumFacing; import java.util.List; import java.util.Map; /** * Created by Elec332 on 14-1-2016. */ public class EnumHelper { private static final Map<Class<? extends Enum>, IEnumHandler<?>> registry; private static final List<IEnumHandler> internalHandlers; public static <E extends Enum> void registerHandler(IEnumHandler<E> handler){ registry.put(handler.getHandlerClass(), handler); } @SuppressWarnings("unchecked") /* -_- */ public static <E extends Enum> IEnumHandler<E> getHandlerFor(E e){ return (IEnumHandler<E>) getHandlerFor(e.getClass()); } @SuppressWarnings("unchecked") public static <E extends Enum> IEnumHandler<E> getHandlerFor(Class<E> c){ return (IEnumHandler<E>) registry.get(c); } private static <E extends Enum> boolean hasHandler(Class<E> c){ return registry.keySet().contains(c); } private static <E extends Enum> void checkIsMC(Class<E> c){ if (c.getName().startsWith("net.minecraft")) throw new IllegalStateException(); } public static <E extends Enum> String getName(E e){ if (hasHandler(e.getClass())){ return getHandlerFor(e).getName(e); } checkIsMC(e.getClass()); return e.toString(); } public static <E extends Enum> int getOrdinal(E e){ if (hasHandler(e.getClass())){ return getHandlerFor(e).getOrdinal(e); } checkIsMC(e.getClass()); return e.ordinal(); } @SuppressWarnings("all") public static <E extends Enum> E fromString(String s, Class<E> c){ if (hasHandler(c)){ return getHandlerFor(c).fromString(s); } checkIsMC(c); return (E) /* <-- Compiler cries if I do not do that... */ Enum.valueOf(c, s); } public static <E extends Enum> E fromOrdinal(int ordinal, Class<E> c){ if (hasHandler(c)){ return getHandlerFor(c).fromOrdinal(ordinal); } checkIsMC(c); return c.getEnumConstants()[ordinal]; } public interface IEnumHandler <E extends Enum> { public Class<E> getHandlerClass(); public String getName(E e); public E fromString(String s); public int getOrdinal(E e); public E fromOrdinal(int i); } static { registry = Maps.newHashMap(); internalHandlers = Lists.newArrayList(); internalHandlers.add(new IEnumHandler<EnumFacing>() { @Override public Class<EnumFacing> getHandlerClass() { return EnumFacing.class; } @Override public String getName(EnumFacing facing) { switch (facing){ case DOWN: return "DOWN"; case UP: return "UP"; case NORTH: return "NORTH"; case SOUTH: return "SOUTH"; case WEST: return "WEST"; case EAST: return "EAST"; default: throw new IllegalArgumentException(); } } @Override public EnumFacing fromString(String s) { if (s.equals("DOWN")){ return EnumFacing.DOWN; } else if (s.equals("UP")){ return EnumFacing.UP; } else if (s.equals("NORTH")){ return EnumFacing.NORTH; } else if (s.equals("SOUTH")){ return EnumFacing.SOUTH; } else if (s.equals("WEST")){ return EnumFacing.WEST; } else if (s.equals("EAST")){ return EnumFacing.EAST; } throw new IllegalArgumentException(); } @Override public int getOrdinal(EnumFacing facing) { switch (facing){ case DOWN: return 0; case UP: return 1; case NORTH: return 2; case SOUTH: return 3; case WEST: return 4; case EAST: return 5; default: throw new IllegalArgumentException(); } } @Override public EnumFacing fromOrdinal(int i) { switch (i){ case 0: return EnumFacing.DOWN; case 1: return EnumFacing.UP; case 2: return EnumFacing.NORTH; case 3: return EnumFacing.SOUTH; case 4: return EnumFacing.WEST; case 5: return EnumFacing.EAST; default: throw new IllegalArgumentException(); } } }); for (IEnumHandler handler : internalHandlers){ registerHandler(handler); } } }
UTF-8
Java
5,531
java
EnumHelper.java
Java
[ { "context": "til.List;\nimport java.util.Map;\n\n/**\n * Created by Elec332 on 14-1-2016.\n */\npublic class EnumHelper {\n\n ", "end": 217, "score": 0.9995485544204712, "start": 210, "tag": "USERNAME", "value": "Elec332" } ]
null
[]
package elec332.core.util; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import net.minecraft.util.EnumFacing; import java.util.List; import java.util.Map; /** * Created by Elec332 on 14-1-2016. */ public class EnumHelper { private static final Map<Class<? extends Enum>, IEnumHandler<?>> registry; private static final List<IEnumHandler> internalHandlers; public static <E extends Enum> void registerHandler(IEnumHandler<E> handler){ registry.put(handler.getHandlerClass(), handler); } @SuppressWarnings("unchecked") /* -_- */ public static <E extends Enum> IEnumHandler<E> getHandlerFor(E e){ return (IEnumHandler<E>) getHandlerFor(e.getClass()); } @SuppressWarnings("unchecked") public static <E extends Enum> IEnumHandler<E> getHandlerFor(Class<E> c){ return (IEnumHandler<E>) registry.get(c); } private static <E extends Enum> boolean hasHandler(Class<E> c){ return registry.keySet().contains(c); } private static <E extends Enum> void checkIsMC(Class<E> c){ if (c.getName().startsWith("net.minecraft")) throw new IllegalStateException(); } public static <E extends Enum> String getName(E e){ if (hasHandler(e.getClass())){ return getHandlerFor(e).getName(e); } checkIsMC(e.getClass()); return e.toString(); } public static <E extends Enum> int getOrdinal(E e){ if (hasHandler(e.getClass())){ return getHandlerFor(e).getOrdinal(e); } checkIsMC(e.getClass()); return e.ordinal(); } @SuppressWarnings("all") public static <E extends Enum> E fromString(String s, Class<E> c){ if (hasHandler(c)){ return getHandlerFor(c).fromString(s); } checkIsMC(c); return (E) /* <-- Compiler cries if I do not do that... */ Enum.valueOf(c, s); } public static <E extends Enum> E fromOrdinal(int ordinal, Class<E> c){ if (hasHandler(c)){ return getHandlerFor(c).fromOrdinal(ordinal); } checkIsMC(c); return c.getEnumConstants()[ordinal]; } public interface IEnumHandler <E extends Enum> { public Class<E> getHandlerClass(); public String getName(E e); public E fromString(String s); public int getOrdinal(E e); public E fromOrdinal(int i); } static { registry = Maps.newHashMap(); internalHandlers = Lists.newArrayList(); internalHandlers.add(new IEnumHandler<EnumFacing>() { @Override public Class<EnumFacing> getHandlerClass() { return EnumFacing.class; } @Override public String getName(EnumFacing facing) { switch (facing){ case DOWN: return "DOWN"; case UP: return "UP"; case NORTH: return "NORTH"; case SOUTH: return "SOUTH"; case WEST: return "WEST"; case EAST: return "EAST"; default: throw new IllegalArgumentException(); } } @Override public EnumFacing fromString(String s) { if (s.equals("DOWN")){ return EnumFacing.DOWN; } else if (s.equals("UP")){ return EnumFacing.UP; } else if (s.equals("NORTH")){ return EnumFacing.NORTH; } else if (s.equals("SOUTH")){ return EnumFacing.SOUTH; } else if (s.equals("WEST")){ return EnumFacing.WEST; } else if (s.equals("EAST")){ return EnumFacing.EAST; } throw new IllegalArgumentException(); } @Override public int getOrdinal(EnumFacing facing) { switch (facing){ case DOWN: return 0; case UP: return 1; case NORTH: return 2; case SOUTH: return 3; case WEST: return 4; case EAST: return 5; default: throw new IllegalArgumentException(); } } @Override public EnumFacing fromOrdinal(int i) { switch (i){ case 0: return EnumFacing.DOWN; case 1: return EnumFacing.UP; case 2: return EnumFacing.NORTH; case 3: return EnumFacing.SOUTH; case 4: return EnumFacing.WEST; case 5: return EnumFacing.EAST; default: throw new IllegalArgumentException(); } } }); for (IEnumHandler handler : internalHandlers){ registerHandler(handler); } } }
5,531
0.48418
0.47966
184
29.059782
20.974407
86
false
false
0
0
0
0
0
0
0.369565
false
false
11
0527b3f6f5d7f45650c171566b6d2f5c3f4f4b8c
11,158,325,059,960
928db3d25f900f82cdc3b39fe95dc4be1bfde5d4
/src/main/java/com/champak/plus/service/GoogleSheetsService.java
d0c460a5bb2e593ef6f8e7cd63c981266011ff4d
[]
no_license
virusneeraj/ChampakPlusAPI
https://github.com/virusneeraj/ChampakPlusAPI
85047b16fc47fa770354e64f97ff009efc09b811
7f0624e8f549c0f39aff97ae2045e4b388fe694e
refs/heads/master
2021-06-07T13:06:23.843000
2019-11-10T09:01:43
2019-11-10T09:01:43
147,071,204
0
0
null
false
2021-06-04T01:29:45
2018-09-02T09:18:48
2019-11-10T09:01:46
2021-06-04T01:29:45
35
0
0
1
Java
false
false
package com.champak.plus.service; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.champak.plus.util.GoogleBuilderUtil; import com.google.api.services.drive.Drive; import com.google.api.services.sheets.v4.Sheets; import com.google.api.services.sheets.v4.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; ///https://github.com/eugenp/tutorials/blob/master/libraries/src/test/java/com/baeldung/google/sheets/GoogleSheetsIntegrationTest.java @Service public class GoogleSheetsService { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Value("${scuapi.google.sheet.spreadsheet_id}") static String SPREADSHEET_ID; private static Sheets sheetsService; @Autowired GooglePermissionService googlePermissionService; private static Drive driveService; // this id can be replaced with your spreadsheet id // otherwise be advised that multiple people may run this test and update the public spreadsheet //private static final String SPREADSHEET_ID = "1sILuxZUnyl_7-MlNThjt765oWshN3Xs-PPLfqYe4DhI"; public static void setup() throws GeneralSecurityException, IOException { sheetsService = GoogleBuilderUtil.getSheetsService(); driveService = GoogleBuilderUtil.getDriveService(); } public AppendValuesResponse whenWriteSheet_thenReadSheetOk(String SPREADSHEET_ID, List rowData) throws IOException, GeneralSecurityException { setup(); logger.info("inserting record"); ValueRange appendBody = new ValueRange().setValues(Arrays.asList(rowData)); AppendValuesResponse appendResult = sheetsService.spreadsheets().values().append(SPREADSHEET_ID, "A1", appendBody).setValueInputOption("USER_ENTERED").setInsertDataOption("INSERT_ROWS").setIncludeValuesInResponse(true).execute(); logger.info("inserting record - done"); logger.info("setting perm"); googlePermissionService.insertPermission(driveService, appendResult.getSpreadsheetId()); logger.info("setting perm - done"); return appendResult; } private UpdateValuesResponse whenWriteSheet_thenReadSheetOk(String SPREADSHEET_ID) throws IOException, GeneralSecurityException { setup(); ValueRange body = new ValueRange().setValues(Arrays.asList(Arrays.asList("Expenses January"), Arrays.asList("books", "30"), Arrays.asList("pens", "10"), Arrays.asList("Expenses February"), Arrays.asList("clothes", "20"), Arrays.asList("shoes", "5"))); UpdateValuesResponse result = sheetsService.spreadsheets().values().update(SPREADSHEET_ID, "A1", body).setValueInputOption("RAW").execute(); List<ValueRange> data = new ArrayList<>(); data.add(new ValueRange().setRange("D1").setValues(Arrays.asList(Arrays.asList("January Total", "=B2+B3")))); data.add(new ValueRange().setRange("D4").setValues(Arrays.asList(Arrays.asList("February Total", "=B5+B6")))); BatchUpdateValuesRequest batchBody = new BatchUpdateValuesRequest().setValueInputOption("USER_ENTERED").setData(data); BatchUpdateValuesResponse batchResult = sheetsService.spreadsheets().values().batchUpdate(SPREADSHEET_ID, batchBody).execute(); List<String> ranges = Arrays.asList("E1", "E4"); BatchGetValuesResponse readResult = sheetsService.spreadsheets().values().batchGet(SPREADSHEET_ID).setRanges(ranges).execute(); ValueRange januaryTotal = readResult.getValueRanges().get(0); ValueRange febTotal = readResult.getValueRanges().get(1); ValueRange appendBody = new ValueRange().setValues(Arrays.asList(Arrays.asList("Total", "=E1+E4"))); AppendValuesResponse appendResult = sheetsService.spreadsheets().values().append(SPREADSHEET_ID, "A1", appendBody).setValueInputOption("USER_ENTERED").setInsertDataOption("INSERT_ROWS").setIncludeValuesInResponse(true).execute(); ValueRange total = appendResult.getUpdates().getUpdatedData(); return result; } public BatchUpdateSpreadsheetResponse whenUpdateSpreadSheetTitle_thenOk(String SPREADSHEET_ID, String title) throws IOException, GeneralSecurityException { setup(); UpdateSpreadsheetPropertiesRequest updateRequest = new UpdateSpreadsheetPropertiesRequest().setFields("*").setProperties(new SpreadsheetProperties().setTitle(title)); CopyPasteRequest copyRequest = new CopyPasteRequest().setSource(new GridRange().setSheetId(0).setStartColumnIndex(0).setEndColumnIndex(2).setStartRowIndex(0).setEndRowIndex(1)) .setDestination(new GridRange().setSheetId(1).setStartColumnIndex(0).setEndColumnIndex(2).setStartRowIndex(0).setEndRowIndex(1)).setPasteType("PASTE_VALUES"); List<Request> requests = new ArrayList<>(); requests.add(new Request().setCopyPaste(copyRequest)); requests.add(new Request().setUpdateSpreadsheetProperties(updateRequest)); BatchUpdateSpreadsheetRequest body = new BatchUpdateSpreadsheetRequest().setRequests(requests); return sheetsService.spreadsheets().batchUpdate(SPREADSHEET_ID, body).execute(); } public Spreadsheet whenCreateSpreadSheet_thenIdOk(String spreadSheetName) throws IOException, GeneralSecurityException { setup(); Spreadsheet spreadSheet = new Spreadsheet().setProperties(new SpreadsheetProperties().setTitle(spreadSheetName)); Spreadsheet result = sheetsService.spreadsheets().create(spreadSheet).execute(); return result; } }
UTF-8
Java
5,753
java
GoogleSheetsService.java
Java
[ { "context": "mework.stereotype.Service;\n\n///https://github.com/eugenp/tutorials/blob/master/libraries/src/test/java/com", "end": 634, "score": 0.9991899728775024, "start": 628, "tag": "USERNAME", "value": "eugenp" } ]
null
[]
package com.champak.plus.service; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.champak.plus.util.GoogleBuilderUtil; import com.google.api.services.drive.Drive; import com.google.api.services.sheets.v4.Sheets; import com.google.api.services.sheets.v4.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; ///https://github.com/eugenp/tutorials/blob/master/libraries/src/test/java/com/baeldung/google/sheets/GoogleSheetsIntegrationTest.java @Service public class GoogleSheetsService { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Value("${scuapi.google.sheet.spreadsheet_id}") static String SPREADSHEET_ID; private static Sheets sheetsService; @Autowired GooglePermissionService googlePermissionService; private static Drive driveService; // this id can be replaced with your spreadsheet id // otherwise be advised that multiple people may run this test and update the public spreadsheet //private static final String SPREADSHEET_ID = "1sILuxZUnyl_7-MlNThjt765oWshN3Xs-PPLfqYe4DhI"; public static void setup() throws GeneralSecurityException, IOException { sheetsService = GoogleBuilderUtil.getSheetsService(); driveService = GoogleBuilderUtil.getDriveService(); } public AppendValuesResponse whenWriteSheet_thenReadSheetOk(String SPREADSHEET_ID, List rowData) throws IOException, GeneralSecurityException { setup(); logger.info("inserting record"); ValueRange appendBody = new ValueRange().setValues(Arrays.asList(rowData)); AppendValuesResponse appendResult = sheetsService.spreadsheets().values().append(SPREADSHEET_ID, "A1", appendBody).setValueInputOption("USER_ENTERED").setInsertDataOption("INSERT_ROWS").setIncludeValuesInResponse(true).execute(); logger.info("inserting record - done"); logger.info("setting perm"); googlePermissionService.insertPermission(driveService, appendResult.getSpreadsheetId()); logger.info("setting perm - done"); return appendResult; } private UpdateValuesResponse whenWriteSheet_thenReadSheetOk(String SPREADSHEET_ID) throws IOException, GeneralSecurityException { setup(); ValueRange body = new ValueRange().setValues(Arrays.asList(Arrays.asList("Expenses January"), Arrays.asList("books", "30"), Arrays.asList("pens", "10"), Arrays.asList("Expenses February"), Arrays.asList("clothes", "20"), Arrays.asList("shoes", "5"))); UpdateValuesResponse result = sheetsService.spreadsheets().values().update(SPREADSHEET_ID, "A1", body).setValueInputOption("RAW").execute(); List<ValueRange> data = new ArrayList<>(); data.add(new ValueRange().setRange("D1").setValues(Arrays.asList(Arrays.asList("January Total", "=B2+B3")))); data.add(new ValueRange().setRange("D4").setValues(Arrays.asList(Arrays.asList("February Total", "=B5+B6")))); BatchUpdateValuesRequest batchBody = new BatchUpdateValuesRequest().setValueInputOption("USER_ENTERED").setData(data); BatchUpdateValuesResponse batchResult = sheetsService.spreadsheets().values().batchUpdate(SPREADSHEET_ID, batchBody).execute(); List<String> ranges = Arrays.asList("E1", "E4"); BatchGetValuesResponse readResult = sheetsService.spreadsheets().values().batchGet(SPREADSHEET_ID).setRanges(ranges).execute(); ValueRange januaryTotal = readResult.getValueRanges().get(0); ValueRange febTotal = readResult.getValueRanges().get(1); ValueRange appendBody = new ValueRange().setValues(Arrays.asList(Arrays.asList("Total", "=E1+E4"))); AppendValuesResponse appendResult = sheetsService.spreadsheets().values().append(SPREADSHEET_ID, "A1", appendBody).setValueInputOption("USER_ENTERED").setInsertDataOption("INSERT_ROWS").setIncludeValuesInResponse(true).execute(); ValueRange total = appendResult.getUpdates().getUpdatedData(); return result; } public BatchUpdateSpreadsheetResponse whenUpdateSpreadSheetTitle_thenOk(String SPREADSHEET_ID, String title) throws IOException, GeneralSecurityException { setup(); UpdateSpreadsheetPropertiesRequest updateRequest = new UpdateSpreadsheetPropertiesRequest().setFields("*").setProperties(new SpreadsheetProperties().setTitle(title)); CopyPasteRequest copyRequest = new CopyPasteRequest().setSource(new GridRange().setSheetId(0).setStartColumnIndex(0).setEndColumnIndex(2).setStartRowIndex(0).setEndRowIndex(1)) .setDestination(new GridRange().setSheetId(1).setStartColumnIndex(0).setEndColumnIndex(2).setStartRowIndex(0).setEndRowIndex(1)).setPasteType("PASTE_VALUES"); List<Request> requests = new ArrayList<>(); requests.add(new Request().setCopyPaste(copyRequest)); requests.add(new Request().setUpdateSpreadsheetProperties(updateRequest)); BatchUpdateSpreadsheetRequest body = new BatchUpdateSpreadsheetRequest().setRequests(requests); return sheetsService.spreadsheets().batchUpdate(SPREADSHEET_ID, body).execute(); } public Spreadsheet whenCreateSpreadSheet_thenIdOk(String spreadSheetName) throws IOException, GeneralSecurityException { setup(); Spreadsheet spreadSheet = new Spreadsheet().setProperties(new SpreadsheetProperties().setTitle(spreadSheetName)); Spreadsheet result = sheetsService.spreadsheets().create(spreadSheet).execute(); return result; } }
5,753
0.752303
0.744829
111
50.828831
58.135578
259
false
false
0
0
0
0
111
0.019294
0.801802
false
false
11
14c91bb6deb7212ea645a6a4267c91e686f09dd3
6,571,300,029,582
aa1fcbfc3a91423f4be661b84ce4c0547fd19631
/src/net/jitse/simplefactions/listeners/WorldListener.java
1a6317ddd02d523615812fe2119baf7b924e4f6e
[ "MIT" ]
permissive
JitseB/SimpleFactions
https://github.com/JitseB/SimpleFactions
e2b24da5ff2752d51ee54f26b1e4f1de607bb917
218f7f11ca04c47f6a837f706672fd519af29f0e
refs/heads/master
2021-03-30T16:22:44.614000
2018-01-03T21:29:17
2018-01-03T21:29:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.jitse.simplefactions.listeners; import net.jitse.simplefactions.SimpleFactions; import net.jitse.simplefactions.commands.subcommands.AdminCommand; import net.jitse.simplefactions.factions.*; import net.jitse.simplefactions.managers.Settings; import net.jitse.simplefactions.utilities.Chat; import org.bukkit.Chunk; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.*; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.event.player.PlayerInteractEvent; import java.util.List; import java.util.UUID; /** * Created by Jitse on 23-6-2017. */ public class WorldListener implements Listener { @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntitySpawn(CreatureSpawnEvent event){ if(event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.DEFAULT){ Faction faction = SimpleFactions.getInstance().getFactionsManager().getFaction(event.getLocation().getChunk()); if(faction != null && (faction.getName().equals(Settings.SPAWN_NAME) || faction.getName().equals(Settings.WARZONE_NAME))){ event.setCancelled(true); } } } @EventHandler (priority = EventPriority.HIGHEST) public void onPlayerBlockBreak(BlockBreakEvent event){ Player player = event.getPlayer(); if(AdminCommand.getBypassing().contains(player.getUniqueId())){ return; } Chunk chunk = event.getBlock().getChunk(); Faction fplayer = SimpleFactions.getInstance().getFactionsManager().getFaction(player); Faction fchunk = SimpleFactions.getInstance().getFactionsManager().getFaction(chunk); if(fchunk != null){ // Permission settings logic. if(fplayer == null){ if(fchunk.getSetting(PermCategory.NEU, PermSetting.BUILD)) return; else if(fchunk.getSetting(PermCategory.NEU, PermSetting.PAINBUILD)){ player.damage(Settings.PAINBUILD_DAMAGE); return; } else event.setCancelled(true); } else if(fchunk.equals(fplayer)){ Role role = SimpleFactions.getInstance().getFactionsManager().getMember(player).getRole(); switch (role){ case MEMBER: if(fplayer.getSetting(PermCategory.MEM, PermSetting.BUILD)) return; else if(fplayer.getSetting(PermCategory.MEM, PermSetting.PAINBUILD)){ player.damage(Settings.PAINBUILD_DAMAGE); return; } else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } case MOD: if(fplayer.getSetting(PermCategory.MOD, PermSetting.BUILD)) return; else if(fplayer.getSetting(PermCategory.MOD, PermSetting.PAINBUILD)){ player.damage(Settings.PAINBUILD_DAMAGE); return; } else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } default: return; // Owner role. } } else{ if((fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.BUILD)) || (fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.BUILD)) || (!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.BUILD))){ return; } else if((fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.PAINBUILD)) || (fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.PAINBUILD)) || (!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.PAINBUILD))){ player.damage(Settings.PAINBUILD_DAMAGE); return; } else event.setCancelled(true); } // Partner logic. List<Partner> partnerList = fchunk.getPartners(chunk); if(partnerList == null){ if(fchunk.equals(fplayer)) event.setCancelled(false); else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } return; } else{ for(Partner partner : partnerList){ if(!(partner.getData() instanceof UUID)) continue; if(partner.getData().equals(player.getUniqueId())) { event.setCancelled(false); return; // Allowed standalone partner. } } if(!fchunk.equals(fplayer)) { for(Partner partner : partnerList){ if(!(partner.getData() instanceof Faction)) continue; if(((Faction) partner.getData()).getName().equals(fplayer.getName())) { event.setCancelled(false); return; // Allowed faction partner. } } if(fchunk != fplayer) { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } return; } } event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } } @EventHandler (priority = EventPriority.HIGHEST) public void onPlayerBlockPlace(BlockPlaceEvent event){ Player player = event.getPlayer(); if(AdminCommand.getBypassing().contains(player.getUniqueId())){ return; } Chunk chunk = event.getBlock().getChunk(); Faction fplayer = SimpleFactions.getInstance().getFactionsManager().getFaction(player); Faction fchunk = SimpleFactions.getInstance().getFactionsManager().getFaction(chunk); if(fchunk != null){ // Permission settings logic. if(fplayer == null){ if(fchunk.getSetting(PermCategory.NEU, PermSetting.BUILD)) return; else if(fchunk.getSetting(PermCategory.NEU, PermSetting.PAINBUILD)){ player.damage(Settings.PAINBUILD_DAMAGE); return; } else event.setCancelled(true); } else if(fchunk.equals(fplayer)){ Role role = SimpleFactions.getInstance().getFactionsManager().getMember(player).getRole(); switch (role){ case MEMBER: if(fplayer.getSetting(PermCategory.MEM, PermSetting.BUILD)) return; else if(fplayer.getSetting(PermCategory.MEM, PermSetting.PAINBUILD)){ player.damage(Settings.PAINBUILD_DAMAGE); return; } else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } case MOD: if(fplayer.getSetting(PermCategory.MOD, PermSetting.BUILD)) return; else if(fplayer.getSetting(PermCategory.MOD, PermSetting.PAINBUILD)){ player.damage(Settings.PAINBUILD_DAMAGE); return; } else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } default: return; // Owner role. } } else{ if((fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.BUILD)) || (fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.BUILD)) || (!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.BUILD))){ return; } else if((fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.PAINBUILD)) || (fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.PAINBUILD)) || (!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.PAINBUILD))){ player.damage(Settings.PAINBUILD_DAMAGE); return; } else event.setCancelled(true); } // Partner logic. List<Partner> partnerList = fchunk.getPartners(chunk); if(partnerList == null){ if(fchunk.equals(fplayer)) event.setCancelled(false); else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } return; } else{ for(Partner partner : partnerList){ if(!(partner.getData() instanceof UUID)) continue; if(partner.getData().equals(player.getUniqueId())) { event.setCancelled(false); return; // Allowed standalone partner. } } if(!fchunk.equals(fplayer)) { for(Partner partner : partnerList){ if(!(partner.getData() instanceof Faction)) continue; if(((Faction) partner.getData()).getName().equals(fplayer.getName())) { event.setCancelled(false); return; // Allowed faction partner. } } if(fchunk != fplayer) { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } return; } } event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } } @EventHandler public void onPlayerBucketUse(PlayerBucketEmptyEvent event){ boolean approved = false; if(event.getBlockClicked() != null){ Player player = event.getPlayer(); if(AdminCommand.getBypassing().contains(player.getUniqueId())){ return; } Chunk chunk = event.getBlockClicked().getChunk(); Faction fplayer = SimpleFactions.getInstance().getFactionsManager().getFaction(player); Faction fchunk = SimpleFactions.getInstance().getFactionsManager().getFaction(chunk); // Guarantee function. heh. if(fchunk != null && fplayer != null){ if(fchunk.equals(fplayer)){ Role role = SimpleFactions.getInstance().getFactionsManager().getMember(player).getRole(); switch (role){ case MEMBER: if(fplayer.getSetting(PermCategory.MEM, PermSetting.BUILD)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } case MOD: if(fplayer.getSetting(PermCategory.MOD, PermSetting.BUILD)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } default: return; // Owner role. } } else if(fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.BUILD)) return; else if(fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.BUILD)) return; else if(!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.BUILD)) return; } if(fchunk != null){ if(fchunk.getSetting(PermCategory.NEU, PermSetting.DOOR) && fplayer == null) return; // Partner logic. List<Partner> partnerList = fchunk.getPartners(chunk); if(partnerList == null){ if(fchunk.equals(fplayer)) event.setCancelled(false); else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } return; } else{ for(Partner partner : partnerList){ if(!(partner.getData() instanceof UUID)) continue; if(partner.getData().equals(player.getUniqueId())) { event.setCancelled(false); return; // Allowed standalone partner. } } if(!fchunk.equals(fplayer)) { for(Partner partner : partnerList){ if(!(partner.getData() instanceof Faction)) continue; if(((Faction) partner.getData()).getName().equals(fplayer.getName())) { event.setCancelled(false); return; // Allowed faction partner. } } if(fchunk != fplayer) { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } return; } } event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } } } @EventHandler (priority = EventPriority.HIGHEST) public void onPlayerInteract(PlayerInteractEvent event){ boolean approved = false; if(event.getAction() == Action.PHYSICAL && (event.getClickedBlock().getType() == Material.GOLD_PLATE || event.getClickedBlock().getType() == Material.IRON_PLATE || event.getClickedBlock().getType() == Material.STONE_PLATE || event.getClickedBlock().getType() == Material.WOOD_PLATE)){ approved = true; } if(event.getAction() == Action.LEFT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_BLOCK || approved){ Player player = event.getPlayer(); if(AdminCommand.getBypassing().contains(player.getUniqueId())){ return; } Chunk chunk = event.getClickedBlock().getChunk(); Faction fplayer = SimpleFactions.getInstance().getFactionsManager().getFaction(player); Faction fchunk = SimpleFactions.getInstance().getFactionsManager().getFaction(chunk); if(fchunk != null){ // Spawn & Warzone logic. if(fchunk.getName().equals(Settings.SPAWN_NAME) || fchunk.getName().equals(Settings.WARZONE_NAME)){ if(event.getPlayer().getItemOnCursor() != null && event.getPlayer().getItemOnCursor().getType() == Material.MONSTER_EGG /*|| event.getItemInHand().getType() == Material.ENDER_PEARL*/){ player.sendMessage(Chat.format(Settings.NOT_ALLOWED_IN_SPAWN_OR_WARZONE)); event.setCancelled(true); } else return; } // Partner logic. List<Partner> partnerList = fchunk.getPartners(chunk); if(partnerList == null){ if(fchunk.equals(fplayer)) event.setCancelled(false); else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } return; } else{ for(Partner partner : partnerList){ if(!(partner.getData() instanceof UUID)) continue; if(partner.getData().equals(player.getUniqueId())) { event.setCancelled(false); return; // Allowed standalone partner. } } if(!fchunk.equals(fplayer)) { for(Partner partner : partnerList){ if(!(partner.getData() instanceof Faction)) continue; if(((Faction) partner.getData()).getName().equals(fplayer.getName())) { event.setCancelled(false); return; // Allowed faction partner. } } if(fchunk != fplayer) { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } return; } } // Permission logic. Block block = event.getClickedBlock(); if(block.getType() == Material.WOOD_DOOR || block.getType() == Material.ACACIA_DOOR || block.getType() == Material.BIRCH_DOOR || block.getType() == Material.DARK_OAK_DOOR || block.getType() == Material.JUNGLE_DOOR || block.getType() == Material.SPRUCE_DOOR || block.getType() == Material.TRAP_DOOR || block.getType() == Material.WOODEN_DOOR){ // Door permission logic. if(fchunk.equals(fplayer)){ Role role = SimpleFactions.getInstance().getFactionsManager().getMember(player).getRole(); switch (role){ case MEMBER: if(fplayer.getSetting(PermCategory.MEM, PermSetting.DOOR)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } case MOD: if(fplayer.getSetting(PermCategory.MOD, PermSetting.DOOR)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } default: return; // Owner role. } } else if(fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.DOOR)) return; else if(fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.DOOR)) return; else if(!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.DOOR)) return; else if(fchunk.getSetting(PermCategory.NEU, PermSetting.DOOR) && fplayer == null) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } } else if(block.getType() == Material.STONE_BUTTON || block.getType() == Material.WOOD_BUTTON){ // Button permission logic. if(fchunk.equals(fplayer)){ Role role = SimpleFactions.getInstance().getFactionsManager().getMember(player).getRole(); switch (role){ case MEMBER: if(fplayer.getSetting(PermCategory.MEM, PermSetting.BUTTON)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } case MOD: if(fplayer.getSetting(PermCategory.MOD, PermSetting.BUTTON)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } default: return; // Owner role. } } else if(fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.BUTTON)) return; else if(fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.BUTTON)) return; else if(!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.BUTTON)) return; else if(fchunk.getSetting(PermCategory.NEU, PermSetting.BUTTON) && fplayer == null) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } } else if(block.getType() == Material.LEVER){ // Lever permission logic. if(fchunk.equals(fplayer)){ Role role = SimpleFactions.getInstance().getFactionsManager().getMember(player).getRole(); switch (role){ case MEMBER: if(fplayer.getSetting(PermCategory.MEM, PermSetting.LEVER)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } case MOD: if(fplayer.getSetting(PermCategory.MOD, PermSetting.LEVER)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } default: return; // Owner role. } } else if(fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.LEVER)) return; else if(fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.LEVER)) return; else if(!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.LEVER)) return; else if(fchunk.getSetting(PermCategory.NEU, PermSetting.LEVER) && fplayer == null) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } } else if(block.getType() == Material.GOLD_PLATE || block.getType() == Material.IRON_PLATE || block.getType() == Material.STONE_PLATE || block.getType() == Material.WOOD_PLATE){ // Pressure plate permission logic. if(fchunk.equals(fplayer)){ Role role = SimpleFactions.getInstance().getFactionsManager().getMember(player).getRole(); switch (role){ case MEMBER: if(fplayer.getSetting(PermCategory.MEM, PermSetting.PRESSUREPLATES)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } case MOD: if(fplayer.getSetting(PermCategory.MOD, PermSetting.PRESSUREPLATES)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } default: return; // Owner role. } } else if(fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.PRESSUREPLATES)) return; else if(fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.PRESSUREPLATES)) return; else if(!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.PRESSUREPLATES)) return; else if(fchunk.getSetting(PermCategory.NEU, PermSetting.PRESSUREPLATES) && fplayer == null) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } } else { if(fplayer != null){ if(fchunk.equals(fplayer)){ Role role = SimpleFactions.getInstance().getFactionsManager().getMember(player).getRole(); switch (role){ case MEMBER: if(fplayer.getSetting(PermCategory.MEM, PermSetting.BUILD)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } case MOD: if(fplayer.getSetting(PermCategory.MOD, PermSetting.BUILD)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } default: return; // Owner role. } } else if(fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.BUILD)) return; else if(fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.BUILD)) return; else if(!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.BUILD)) return; } if(fchunk.getSetting(PermCategory.NEU, PermSetting.BUILD) && fplayer == null) return; } event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } } } private void sendLandAlreadyClaimedMessage(Player player, Faction faction){ player.sendMessage(Chat.format(Settings.LAND_CLAIMED.replace("{faction}", faction.getName()))); } }
UTF-8
Java
29,491
java
WorldListener.java
Java
[ { "context": "il.List;\nimport java.util.UUID;\n\n/**\n * Created by Jitse on 23-6-2017.\n */\npublic class WorldListener impl", "end": 793, "score": 0.9995977282524109, "start": 788, "tag": "USERNAME", "value": "Jitse" } ]
null
[]
package net.jitse.simplefactions.listeners; import net.jitse.simplefactions.SimpleFactions; import net.jitse.simplefactions.commands.subcommands.AdminCommand; import net.jitse.simplefactions.factions.*; import net.jitse.simplefactions.managers.Settings; import net.jitse.simplefactions.utilities.Chat; import org.bukkit.Chunk; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.*; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.event.player.PlayerInteractEvent; import java.util.List; import java.util.UUID; /** * Created by Jitse on 23-6-2017. */ public class WorldListener implements Listener { @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntitySpawn(CreatureSpawnEvent event){ if(event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.DEFAULT){ Faction faction = SimpleFactions.getInstance().getFactionsManager().getFaction(event.getLocation().getChunk()); if(faction != null && (faction.getName().equals(Settings.SPAWN_NAME) || faction.getName().equals(Settings.WARZONE_NAME))){ event.setCancelled(true); } } } @EventHandler (priority = EventPriority.HIGHEST) public void onPlayerBlockBreak(BlockBreakEvent event){ Player player = event.getPlayer(); if(AdminCommand.getBypassing().contains(player.getUniqueId())){ return; } Chunk chunk = event.getBlock().getChunk(); Faction fplayer = SimpleFactions.getInstance().getFactionsManager().getFaction(player); Faction fchunk = SimpleFactions.getInstance().getFactionsManager().getFaction(chunk); if(fchunk != null){ // Permission settings logic. if(fplayer == null){ if(fchunk.getSetting(PermCategory.NEU, PermSetting.BUILD)) return; else if(fchunk.getSetting(PermCategory.NEU, PermSetting.PAINBUILD)){ player.damage(Settings.PAINBUILD_DAMAGE); return; } else event.setCancelled(true); } else if(fchunk.equals(fplayer)){ Role role = SimpleFactions.getInstance().getFactionsManager().getMember(player).getRole(); switch (role){ case MEMBER: if(fplayer.getSetting(PermCategory.MEM, PermSetting.BUILD)) return; else if(fplayer.getSetting(PermCategory.MEM, PermSetting.PAINBUILD)){ player.damage(Settings.PAINBUILD_DAMAGE); return; } else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } case MOD: if(fplayer.getSetting(PermCategory.MOD, PermSetting.BUILD)) return; else if(fplayer.getSetting(PermCategory.MOD, PermSetting.PAINBUILD)){ player.damage(Settings.PAINBUILD_DAMAGE); return; } else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } default: return; // Owner role. } } else{ if((fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.BUILD)) || (fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.BUILD)) || (!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.BUILD))){ return; } else if((fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.PAINBUILD)) || (fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.PAINBUILD)) || (!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.PAINBUILD))){ player.damage(Settings.PAINBUILD_DAMAGE); return; } else event.setCancelled(true); } // Partner logic. List<Partner> partnerList = fchunk.getPartners(chunk); if(partnerList == null){ if(fchunk.equals(fplayer)) event.setCancelled(false); else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } return; } else{ for(Partner partner : partnerList){ if(!(partner.getData() instanceof UUID)) continue; if(partner.getData().equals(player.getUniqueId())) { event.setCancelled(false); return; // Allowed standalone partner. } } if(!fchunk.equals(fplayer)) { for(Partner partner : partnerList){ if(!(partner.getData() instanceof Faction)) continue; if(((Faction) partner.getData()).getName().equals(fplayer.getName())) { event.setCancelled(false); return; // Allowed faction partner. } } if(fchunk != fplayer) { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } return; } } event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } } @EventHandler (priority = EventPriority.HIGHEST) public void onPlayerBlockPlace(BlockPlaceEvent event){ Player player = event.getPlayer(); if(AdminCommand.getBypassing().contains(player.getUniqueId())){ return; } Chunk chunk = event.getBlock().getChunk(); Faction fplayer = SimpleFactions.getInstance().getFactionsManager().getFaction(player); Faction fchunk = SimpleFactions.getInstance().getFactionsManager().getFaction(chunk); if(fchunk != null){ // Permission settings logic. if(fplayer == null){ if(fchunk.getSetting(PermCategory.NEU, PermSetting.BUILD)) return; else if(fchunk.getSetting(PermCategory.NEU, PermSetting.PAINBUILD)){ player.damage(Settings.PAINBUILD_DAMAGE); return; } else event.setCancelled(true); } else if(fchunk.equals(fplayer)){ Role role = SimpleFactions.getInstance().getFactionsManager().getMember(player).getRole(); switch (role){ case MEMBER: if(fplayer.getSetting(PermCategory.MEM, PermSetting.BUILD)) return; else if(fplayer.getSetting(PermCategory.MEM, PermSetting.PAINBUILD)){ player.damage(Settings.PAINBUILD_DAMAGE); return; } else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } case MOD: if(fplayer.getSetting(PermCategory.MOD, PermSetting.BUILD)) return; else if(fplayer.getSetting(PermCategory.MOD, PermSetting.PAINBUILD)){ player.damage(Settings.PAINBUILD_DAMAGE); return; } else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } default: return; // Owner role. } } else{ if((fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.BUILD)) || (fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.BUILD)) || (!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.BUILD))){ return; } else if((fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.PAINBUILD)) || (fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.PAINBUILD)) || (!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.PAINBUILD))){ player.damage(Settings.PAINBUILD_DAMAGE); return; } else event.setCancelled(true); } // Partner logic. List<Partner> partnerList = fchunk.getPartners(chunk); if(partnerList == null){ if(fchunk.equals(fplayer)) event.setCancelled(false); else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } return; } else{ for(Partner partner : partnerList){ if(!(partner.getData() instanceof UUID)) continue; if(partner.getData().equals(player.getUniqueId())) { event.setCancelled(false); return; // Allowed standalone partner. } } if(!fchunk.equals(fplayer)) { for(Partner partner : partnerList){ if(!(partner.getData() instanceof Faction)) continue; if(((Faction) partner.getData()).getName().equals(fplayer.getName())) { event.setCancelled(false); return; // Allowed faction partner. } } if(fchunk != fplayer) { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } return; } } event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } } @EventHandler public void onPlayerBucketUse(PlayerBucketEmptyEvent event){ boolean approved = false; if(event.getBlockClicked() != null){ Player player = event.getPlayer(); if(AdminCommand.getBypassing().contains(player.getUniqueId())){ return; } Chunk chunk = event.getBlockClicked().getChunk(); Faction fplayer = SimpleFactions.getInstance().getFactionsManager().getFaction(player); Faction fchunk = SimpleFactions.getInstance().getFactionsManager().getFaction(chunk); // Guarantee function. heh. if(fchunk != null && fplayer != null){ if(fchunk.equals(fplayer)){ Role role = SimpleFactions.getInstance().getFactionsManager().getMember(player).getRole(); switch (role){ case MEMBER: if(fplayer.getSetting(PermCategory.MEM, PermSetting.BUILD)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } case MOD: if(fplayer.getSetting(PermCategory.MOD, PermSetting.BUILD)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } default: return; // Owner role. } } else if(fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.BUILD)) return; else if(fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.BUILD)) return; else if(!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.BUILD)) return; } if(fchunk != null){ if(fchunk.getSetting(PermCategory.NEU, PermSetting.DOOR) && fplayer == null) return; // Partner logic. List<Partner> partnerList = fchunk.getPartners(chunk); if(partnerList == null){ if(fchunk.equals(fplayer)) event.setCancelled(false); else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } return; } else{ for(Partner partner : partnerList){ if(!(partner.getData() instanceof UUID)) continue; if(partner.getData().equals(player.getUniqueId())) { event.setCancelled(false); return; // Allowed standalone partner. } } if(!fchunk.equals(fplayer)) { for(Partner partner : partnerList){ if(!(partner.getData() instanceof Faction)) continue; if(((Faction) partner.getData()).getName().equals(fplayer.getName())) { event.setCancelled(false); return; // Allowed faction partner. } } if(fchunk != fplayer) { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } return; } } event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } } } @EventHandler (priority = EventPriority.HIGHEST) public void onPlayerInteract(PlayerInteractEvent event){ boolean approved = false; if(event.getAction() == Action.PHYSICAL && (event.getClickedBlock().getType() == Material.GOLD_PLATE || event.getClickedBlock().getType() == Material.IRON_PLATE || event.getClickedBlock().getType() == Material.STONE_PLATE || event.getClickedBlock().getType() == Material.WOOD_PLATE)){ approved = true; } if(event.getAction() == Action.LEFT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_BLOCK || approved){ Player player = event.getPlayer(); if(AdminCommand.getBypassing().contains(player.getUniqueId())){ return; } Chunk chunk = event.getClickedBlock().getChunk(); Faction fplayer = SimpleFactions.getInstance().getFactionsManager().getFaction(player); Faction fchunk = SimpleFactions.getInstance().getFactionsManager().getFaction(chunk); if(fchunk != null){ // Spawn & Warzone logic. if(fchunk.getName().equals(Settings.SPAWN_NAME) || fchunk.getName().equals(Settings.WARZONE_NAME)){ if(event.getPlayer().getItemOnCursor() != null && event.getPlayer().getItemOnCursor().getType() == Material.MONSTER_EGG /*|| event.getItemInHand().getType() == Material.ENDER_PEARL*/){ player.sendMessage(Chat.format(Settings.NOT_ALLOWED_IN_SPAWN_OR_WARZONE)); event.setCancelled(true); } else return; } // Partner logic. List<Partner> partnerList = fchunk.getPartners(chunk); if(partnerList == null){ if(fchunk.equals(fplayer)) event.setCancelled(false); else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } return; } else{ for(Partner partner : partnerList){ if(!(partner.getData() instanceof UUID)) continue; if(partner.getData().equals(player.getUniqueId())) { event.setCancelled(false); return; // Allowed standalone partner. } } if(!fchunk.equals(fplayer)) { for(Partner partner : partnerList){ if(!(partner.getData() instanceof Faction)) continue; if(((Faction) partner.getData()).getName().equals(fplayer.getName())) { event.setCancelled(false); return; // Allowed faction partner. } } if(fchunk != fplayer) { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } return; } } // Permission logic. Block block = event.getClickedBlock(); if(block.getType() == Material.WOOD_DOOR || block.getType() == Material.ACACIA_DOOR || block.getType() == Material.BIRCH_DOOR || block.getType() == Material.DARK_OAK_DOOR || block.getType() == Material.JUNGLE_DOOR || block.getType() == Material.SPRUCE_DOOR || block.getType() == Material.TRAP_DOOR || block.getType() == Material.WOODEN_DOOR){ // Door permission logic. if(fchunk.equals(fplayer)){ Role role = SimpleFactions.getInstance().getFactionsManager().getMember(player).getRole(); switch (role){ case MEMBER: if(fplayer.getSetting(PermCategory.MEM, PermSetting.DOOR)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } case MOD: if(fplayer.getSetting(PermCategory.MOD, PermSetting.DOOR)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } default: return; // Owner role. } } else if(fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.DOOR)) return; else if(fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.DOOR)) return; else if(!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.DOOR)) return; else if(fchunk.getSetting(PermCategory.NEU, PermSetting.DOOR) && fplayer == null) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } } else if(block.getType() == Material.STONE_BUTTON || block.getType() == Material.WOOD_BUTTON){ // Button permission logic. if(fchunk.equals(fplayer)){ Role role = SimpleFactions.getInstance().getFactionsManager().getMember(player).getRole(); switch (role){ case MEMBER: if(fplayer.getSetting(PermCategory.MEM, PermSetting.BUTTON)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } case MOD: if(fplayer.getSetting(PermCategory.MOD, PermSetting.BUTTON)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } default: return; // Owner role. } } else if(fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.BUTTON)) return; else if(fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.BUTTON)) return; else if(!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.BUTTON)) return; else if(fchunk.getSetting(PermCategory.NEU, PermSetting.BUTTON) && fplayer == null) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } } else if(block.getType() == Material.LEVER){ // Lever permission logic. if(fchunk.equals(fplayer)){ Role role = SimpleFactions.getInstance().getFactionsManager().getMember(player).getRole(); switch (role){ case MEMBER: if(fplayer.getSetting(PermCategory.MEM, PermSetting.LEVER)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } case MOD: if(fplayer.getSetting(PermCategory.MOD, PermSetting.LEVER)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } default: return; // Owner role. } } else if(fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.LEVER)) return; else if(fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.LEVER)) return; else if(!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.LEVER)) return; else if(fchunk.getSetting(PermCategory.NEU, PermSetting.LEVER) && fplayer == null) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } } else if(block.getType() == Material.GOLD_PLATE || block.getType() == Material.IRON_PLATE || block.getType() == Material.STONE_PLATE || block.getType() == Material.WOOD_PLATE){ // Pressure plate permission logic. if(fchunk.equals(fplayer)){ Role role = SimpleFactions.getInstance().getFactionsManager().getMember(player).getRole(); switch (role){ case MEMBER: if(fplayer.getSetting(PermCategory.MEM, PermSetting.PRESSUREPLATES)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } case MOD: if(fplayer.getSetting(PermCategory.MOD, PermSetting.PRESSUREPLATES)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } default: return; // Owner role. } } else if(fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.PRESSUREPLATES)) return; else if(fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.PRESSUREPLATES)) return; else if(!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.PRESSUREPLATES)) return; else if(fchunk.getSetting(PermCategory.NEU, PermSetting.PRESSUREPLATES) && fplayer == null) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } } else { if(fplayer != null){ if(fchunk.equals(fplayer)){ Role role = SimpleFactions.getInstance().getFactionsManager().getMember(player).getRole(); switch (role){ case MEMBER: if(fplayer.getSetting(PermCategory.MEM, PermSetting.BUILD)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } case MOD: if(fplayer.getSetting(PermCategory.MOD, PermSetting.BUILD)) return; else { event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); return; } default: return; // Owner role. } } else if(fchunk.getAllies().contains(fplayer) && fchunk.getSetting(PermCategory.ALL, PermSetting.BUILD)) return; else if(fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.ENE, PermSetting.BUILD)) return; else if(!fchunk.getAllies().contains(fplayer) && !fchunk.getEnemies().contains(fplayer) && fchunk.getSetting(PermCategory.NEU, PermSetting.BUILD)) return; } if(fchunk.getSetting(PermCategory.NEU, PermSetting.BUILD) && fplayer == null) return; } event.setCancelled(true); sendLandAlreadyClaimedMessage(player, fchunk); } } } private void sendLandAlreadyClaimedMessage(Player player, Faction faction){ player.sendMessage(Chat.format(Settings.LAND_CLAIMED.replace("{faction}", faction.getName()))); } }
29,491
0.492354
0.492116
539
53.714287
36.524929
204
false
false
0
0
0
0
0
0
0.745826
false
false
11
7c9508bc1a09e4afd255099b74cc508ea2ae2474
25,975,962,269,969
3f0d15d3a8cc78de093716edc7140552a119522f
/api-clients/src/main/java/io/nsu/hire/apiclients/rest.controller/dto/ClientDTO.java
78786cf91fc85e72ea073d18ddae0645e6e4d99c
[ "Apache-2.0" ]
permissive
sebastian-bogado/Hire
https://github.com/sebastian-bogado/Hire
e852c10cd5b50a832733e412129b1935c4620a38
a29893e991e7277b60d968681033604115e3a2b0
refs/heads/master
2020-03-18T14:53:22.601000
2018-05-26T03:56:11
2018-05-26T03:56:11
134,873,292
0
0
null
true
2018-05-25T15:22:30
2018-05-25T15:22:29
2018-05-25T15:22:09
2018-05-25T15:22:07
185
0
0
0
null
false
null
package io.nsu.hire.apiclients.rest.controller.dto; import lombok.Data; @Data public class ClientDTO { }
UTF-8
Java
108
java
ClientDTO.java
Java
[]
null
[]
package io.nsu.hire.apiclients.rest.controller.dto; import lombok.Data; @Data public class ClientDTO { }
108
0.768519
0.768519
8
12.5
17.007351
51
false
false
0
0
0
0
0
0
0.25
false
false
11
14a04a2370d564bc56142d0030d184c16ef6bd59
25,202,868,094,424
c38a0fe3b6e96f0b6fdd32f75f5986465b6e7cd6
/src/test/java/seedu/address/testutil/TypicalRecipes.java
a1fb729e0fc25963eb19fe200a7046986086538b
[ "MIT" ]
permissive
Rahul0506/tp
https://github.com/Rahul0506/tp
eb701307f100cc50e840de5f29ce94618921bab5
9f375e113e4cd692f40099fd9c551bc8c4850e87
refs/heads/master
2023-01-24T13:23:42.484000
2020-11-09T06:56:58
2020-11-09T06:56:58
296,511,116
0
0
NOASSERTION
true
2020-09-18T04:13:43
2020-09-18T04:13:42
2020-09-12T10:22:16
2020-09-17T17:16:47
11,420
0
0
0
null
false
false
package seedu.address.testutil; import static seedu.address.testutil.TypicalIngredients.getTypicalSecondIngredientList; import static seedu.address.testutil.TypicalItems.APPLE; import static seedu.address.testutil.TypicalItems.APPLE_PIE_ITEM; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import seedu.address.model.RecipeList; import seedu.address.model.recipe.Recipe; public class TypicalRecipes { public static final Recipe APPLE_PIE = new RecipeBuilder().withId(1) .withDescription("Apple-y!") .withQuantity("1") .withProduct(APPLE_PIE_ITEM) .build(); //apple pie public static final Recipe BANANA_PIE = new RecipeBuilder().withId(2) .withDescription("Banana-y!") // banana pie .withQuantity("1").build(); public static final Recipe FOUND_APPLE = new RecipeBuilder().withId(3) .withDescription("Make Apple.inc") .withIngredients(getTypicalSecondIngredientList()) .withProduct(APPLE) .withQuantity("1") .build(); private TypicalRecipes() {} // prevents instantiation /** * Returns an {@code RecipeList} with all the typical recipes. */ public static RecipeList getTypicalRecipeList() { RecipeList recipeList = new RecipeList(); for (Recipe recipe : getTypicalRecipes()) { recipeList.addRecipe(new RecipeBuilder(recipe).build()); } return recipeList; } public static List<Recipe> getTypicalRecipes() { return new ArrayList<>(Arrays.asList(APPLE_PIE, BANANA_PIE, FOUND_APPLE)); } }
UTF-8
Java
1,651
java
TypicalRecipes.java
Java
[]
null
[]
package seedu.address.testutil; import static seedu.address.testutil.TypicalIngredients.getTypicalSecondIngredientList; import static seedu.address.testutil.TypicalItems.APPLE; import static seedu.address.testutil.TypicalItems.APPLE_PIE_ITEM; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import seedu.address.model.RecipeList; import seedu.address.model.recipe.Recipe; public class TypicalRecipes { public static final Recipe APPLE_PIE = new RecipeBuilder().withId(1) .withDescription("Apple-y!") .withQuantity("1") .withProduct(APPLE_PIE_ITEM) .build(); //apple pie public static final Recipe BANANA_PIE = new RecipeBuilder().withId(2) .withDescription("Banana-y!") // banana pie .withQuantity("1").build(); public static final Recipe FOUND_APPLE = new RecipeBuilder().withId(3) .withDescription("Make Apple.inc") .withIngredients(getTypicalSecondIngredientList()) .withProduct(APPLE) .withQuantity("1") .build(); private TypicalRecipes() {} // prevents instantiation /** * Returns an {@code RecipeList} with all the typical recipes. */ public static RecipeList getTypicalRecipeList() { RecipeList recipeList = new RecipeList(); for (Recipe recipe : getTypicalRecipes()) { recipeList.addRecipe(new RecipeBuilder(recipe).build()); } return recipeList; } public static List<Recipe> getTypicalRecipes() { return new ArrayList<>(Arrays.asList(APPLE_PIE, BANANA_PIE, FOUND_APPLE)); } }
1,651
0.67232
0.668686
47
34.127659
25.791815
87
false
false
0
0
0
0
0
0
0.382979
false
false
11
8684fd4a489c8bea81999f2788da4da0d0e5c075
4,621,384,824,055
67527bec7f8452b1f38fdd385aae90fc249a7dd2
/taskmanager/src/main/java/it/uniroma3/siw/taskmanager/model/Tag.java
e7fa7270a22123766e7538d0d58d6764e100240b
[]
no_license
Zoccanic-Corporation/GestoreProgetti
https://github.com/Zoccanic-Corporation/GestoreProgetti
92f55424b5a72cd9f26a896495f3a9e93e8e8f3e
4991be4dc35a7419349e03b5075dc3a8be4190b9
refs/heads/master
2022-11-05T07:09:28.172000
2020-06-18T17:03:07
2020-06-18T17:03:07
269,143,671
0
0
null
false
2020-06-18T15:52:58
2020-06-03T16:50:19
2020-06-18T15:52:03
2020-06-18T15:52:57
347
0
0
0
Java
false
false
package it.uniroma3.siw.taskmanager.model; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; @Entity public class Tag { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; @Column(nullable = false, length = 50, unique=true) private String nome; @Column(length = 20) private String colore; @Column(length = 100) private String descrizione; @ManyToMany(mappedBy="tags")//da controllare # tab di join private List<Task> tasks; @ManyToMany(mappedBy="tags") private List<Project> projects; public Tag() { this.tasks=new ArrayList<Task>(); } public Tag(String nome,String colore,String descrizione) { this(); this.nome=nome; this.colore=colore; this.descrizione=descrizione; } //GETTERS AND SETTERS public List<Project> getProjects() { return projects; } public void setProjects(List<Project> projects) { this.projects = projects; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return this.nome; } public void setNome(String nome) { this.nome=nome; } public String getColore() { return this.colore; } public void setColore(String colore) { this.colore=colore; } public String getDescrizione() { return this.descrizione; } public void setDescrizione(String desc) { this.descrizione=desc; } public List<Task> getTasks() { return tasks; } public void setTasks(List<Task> tasks) { this.tasks = tasks; } public void addTask(Task task) { this.tasks.add(task); } //riguardo override di equals e hashCode per ora si suppone non ci siano bisogno di mappe etc.. }
UTF-8
Java
1,860
java
Tag.java
Java
[]
null
[]
package it.uniroma3.siw.taskmanager.model; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; @Entity public class Tag { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; @Column(nullable = false, length = 50, unique=true) private String nome; @Column(length = 20) private String colore; @Column(length = 100) private String descrizione; @ManyToMany(mappedBy="tags")//da controllare # tab di join private List<Task> tasks; @ManyToMany(mappedBy="tags") private List<Project> projects; public Tag() { this.tasks=new ArrayList<Task>(); } public Tag(String nome,String colore,String descrizione) { this(); this.nome=nome; this.colore=colore; this.descrizione=descrizione; } //GETTERS AND SETTERS public List<Project> getProjects() { return projects; } public void setProjects(List<Project> projects) { this.projects = projects; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return this.nome; } public void setNome(String nome) { this.nome=nome; } public String getColore() { return this.colore; } public void setColore(String colore) { this.colore=colore; } public String getDescrizione() { return this.descrizione; } public void setDescrizione(String desc) { this.descrizione=desc; } public List<Task> getTasks() { return tasks; } public void setTasks(List<Task> tasks) { this.tasks = tasks; } public void addTask(Task task) { this.tasks.add(task); } //riguardo override di equals e hashCode per ora si suppone non ci siano bisogno di mappe etc.. }
1,860
0.717742
0.713441
95
18.578947
17.916519
96
false
false
0
0
0
0
0
0
1.242105
false
false
11
9c4f7a540ac8904b8e4b21e5921af99b01efe473
30,554,397,390,868
76852b1b29410436817bafa34c6dedaedd0786cd
/sources-2020-07-19-tempmail/sources/com/tempmail/db/i.java
3422c6132cdd3aa30459daf62cab63e61f433a2d
[]
no_license
zteeed/tempmail-apks
https://github.com/zteeed/tempmail-apks
040e64e07beadd8f5e48cd7bea8b47233e99611c
19f8da1993c2f783b8847234afb52d94b9d1aa4c
refs/heads/master
2023-01-09T06:43:40.830000
2020-11-04T18:55:05
2020-11-04T18:55:05
310,075,224
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tempmail.db; /* compiled from: MailTextTable */ public class i { /* renamed from: a reason: collision with root package name */ private String f12304a; /* renamed from: b reason: collision with root package name */ private String f12305b; public i() { } public String a() { return this.f12305b; } public String b() { return this.f12304a; } public i(String str, String str2) { this.f12304a = str; this.f12305b = str2; } }
UTF-8
Java
522
java
i.java
Java
[]
null
[]
package com.tempmail.db; /* compiled from: MailTextTable */ public class i { /* renamed from: a reason: collision with root package name */ private String f12304a; /* renamed from: b reason: collision with root package name */ private String f12305b; public i() { } public String a() { return this.f12305b; } public String b() { return this.f12304a; } public i(String str, String str2) { this.f12304a = str; this.f12305b = str2; } }
522
0.595785
0.534483
27
18.333334
18.624954
67
false
false
0
0
0
0
0
0
0.296296
false
false
11
14fc8284c5f2fadbdeec5033ade80bd4cb60e5c9
33,973,191,317,975
9fa0a598b29c2102c0ce6b6f75690a44871a8f68
/src/medium/FindFirstAndLastPositionOfElementInSortedArray.java
c2445acb132521bfaf4ab2773b38ab6174866133
[]
no_license
XiaoyiHuang/LeetCode
https://github.com/XiaoyiHuang/LeetCode
03d169e54b080ee14bb94b7b1760159027c54d42
6cfe2611d6da7c3af1fd5c6dcca41479f2a0be9d
refs/heads/master
2022-04-13T14:23:24.004000
2020-03-15T18:11:58
2020-03-15T18:11:58
233,219,177
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package medium; import helper.Printer; /** * [34] Find First and Last Position of Element in Sorted Array * * Description: * Given an array of integers nums sorted in ascending order, find the * starting and ending position of a given target value. * * Your algorithm's runtime complexity must be in the order of O(log n). * If the target is not found in the array, return [-1, -1]. * * Example 1: * Input: nums = [5,7,7,8,8,10], target = 8 * Output: [3,4] * * Example 2: * Input: nums = [5,7,7,8,8,10], target = 6 * Output: [-1,-1] * * Result: Accepted (0ms) */ public class FindFirstAndLastPositionOfElementInSortedArray { public int[] searchRange(int[] nums, int target) { if (nums.length == 0) { return new int[]{-1, -1}; } int rangeFrom = -1, rangeTo = -1; // Locate the start of the range int lPtr = 0, rPtr = nums.length - 1; while (lPtr < rPtr) { int mPtr = lPtr + ((rPtr - lPtr) >> 1); if (nums[mPtr] < target) { lPtr = mPtr + 1; } else { rPtr = mPtr; } } if (lPtr < nums.length && nums[lPtr] == target) { rangeFrom = lPtr; } else { return new int[]{-1, -1}; } // Locate the end of the range rPtr = nums.length - 1; while (lPtr < rPtr) { int mPtr = lPtr + ((rPtr - lPtr) >> 1); if (nums[mPtr] > target) { rPtr = mPtr - 1; } else { lPtr = mPtr + 1; } } if (lPtr < nums.length && nums[lPtr] == target) { rangeTo = lPtr; } else if (lPtr - 1 < nums.length && nums[lPtr - 1] == target) { rangeTo = lPtr - 1; } return new int[]{rangeFrom, rangeTo}; } public static void main(String[] args) { Printer.printArray(new FindFirstAndLastPositionOfElementInSortedArray() .searchRange(new int[]{5,7,7,8,8,10}, 8)); Printer.printArray(new FindFirstAndLastPositionOfElementInSortedArray() .searchRange(new int[]{5,7,7,8,8,10}, 6)); Printer.printArray(new FindFirstAndLastPositionOfElementInSortedArray() .searchRange(new int[]{7,7,7}, 7)); Printer.printArray(new FindFirstAndLastPositionOfElementInSortedArray() .searchRange(new int[]{1,2,3}, 2)); } }
UTF-8
Java
2,445
java
FindFirstAndLastPositionOfElementInSortedArray.java
Java
[]
null
[]
package medium; import helper.Printer; /** * [34] Find First and Last Position of Element in Sorted Array * * Description: * Given an array of integers nums sorted in ascending order, find the * starting and ending position of a given target value. * * Your algorithm's runtime complexity must be in the order of O(log n). * If the target is not found in the array, return [-1, -1]. * * Example 1: * Input: nums = [5,7,7,8,8,10], target = 8 * Output: [3,4] * * Example 2: * Input: nums = [5,7,7,8,8,10], target = 6 * Output: [-1,-1] * * Result: Accepted (0ms) */ public class FindFirstAndLastPositionOfElementInSortedArray { public int[] searchRange(int[] nums, int target) { if (nums.length == 0) { return new int[]{-1, -1}; } int rangeFrom = -1, rangeTo = -1; // Locate the start of the range int lPtr = 0, rPtr = nums.length - 1; while (lPtr < rPtr) { int mPtr = lPtr + ((rPtr - lPtr) >> 1); if (nums[mPtr] < target) { lPtr = mPtr + 1; } else { rPtr = mPtr; } } if (lPtr < nums.length && nums[lPtr] == target) { rangeFrom = lPtr; } else { return new int[]{-1, -1}; } // Locate the end of the range rPtr = nums.length - 1; while (lPtr < rPtr) { int mPtr = lPtr + ((rPtr - lPtr) >> 1); if (nums[mPtr] > target) { rPtr = mPtr - 1; } else { lPtr = mPtr + 1; } } if (lPtr < nums.length && nums[lPtr] == target) { rangeTo = lPtr; } else if (lPtr - 1 < nums.length && nums[lPtr - 1] == target) { rangeTo = lPtr - 1; } return new int[]{rangeFrom, rangeTo}; } public static void main(String[] args) { Printer.printArray(new FindFirstAndLastPositionOfElementInSortedArray() .searchRange(new int[]{5,7,7,8,8,10}, 8)); Printer.printArray(new FindFirstAndLastPositionOfElementInSortedArray() .searchRange(new int[]{5,7,7,8,8,10}, 6)); Printer.printArray(new FindFirstAndLastPositionOfElementInSortedArray() .searchRange(new int[]{7,7,7}, 7)); Printer.printArray(new FindFirstAndLastPositionOfElementInSortedArray() .searchRange(new int[]{1,2,3}, 2)); } }
2,445
0.534969
0.506748
76
31.171053
23.438267
79
false
false
0
0
0
0
0
0
0.815789
false
false
11
9e5f64afa96b1f1f74af546f1c44bb89607096f7
9,491,877,766,401
39e49e8aa4c38cb24214e7ec44251ea3aba415db
/网络/7.登录案例_网络版_asyncHttpClient/src/com/itheima/login/MainActivity.java
91d3a6ef2c267fad28e0e4285b358ed6777d6c6d
[]
no_license
xfhy/Usually-learn-Android
https://github.com/xfhy/Usually-learn-Android
624dba4ed0aa5979be88425de139034e45ec9941
d2c6467912974572e702507400978af3282bc195
refs/heads/master
2021-01-19T09:37:06.183000
2017-04-13T04:03:52
2017-04-13T04:03:52
82,137,554
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.itheima.login; import java.util.Map; import java.util.Random; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; import com.itheima.login.net.HttpLoginUtils; import com.itheima.login.util.UserInfoUtil; import com.itheima.login_asynchttpclient.R; /** * 2017年1月14日16:52:28 * * @author XFHY 登录练习 */ public class MainActivity extends Activity implements OnClickListener { private EditText et_username; private EditText et_password; private CheckBox cb_reme; private Button btn_login; private boolean isrem; private String userpassword; private String username; private Context mContext; // 在Activity中定义一个属性private Context mContext; // 然后在setContentView之后将这个属性初始化(设置为当前的Activity.this),很多地方需要用到Context对象(比如Toast等), // 这样很方便.在公司,有经验的人都这样写,so... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = this; // a.找到相应控件 et_username = (EditText) findViewById(R.id.et_username); et_password = (EditText) findViewById(R.id.et_password); cb_reme = (CheckBox) findViewById(R.id.cb_reme); btn_login = (Button) findViewById(R.id.btn_login); // b.设置按钮的点击事件 btn_login.setOnClickListener(this); // f.回显用户名密码 Map<String, String> map = UserInfoUtil.readUserInfo(mContext); // 获取用户名和密码 if (map != null) { et_username.setText(map.get("username")); // 设置用户名和密码 et_password.setText(map.get("password")); cb_reme.setChecked(true); // 设置为记住密码 } } /** * 登录按钮执行逻辑 */ private void login() { username = et_username.getText().toString().trim(); userpassword = et_password.getText().toString().trim(); isrem = cb_reme.isChecked(); // d.判断用户名密码是否为空,不为空请求服务器(省略,默认请求成功) if (TextUtils.isEmpty(username) || TextUtils.isEmpty(userpassword)) { Toast.makeText(mContext, "用户名或密码为空", Toast.LENGTH_SHORT).show(); } // 访问服务器,查看是否登录成功 通过handler进行返回 数据 // Random random = new Random(); // int nextInt = random.nextInt(10); // if (nextInt > 3) { // HttpLoginUtils.requestNetForGetLogin(mContext, username, // userpassword); // GET方式 // } else { HttpLoginUtils.requestNetForPostLogin(mContext, username, userpassword); // POST方式 // } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_login: login(); break; default: break; } } }
UTF-8
Java
3,000
java
MainActivity.java
Java
[ { "context": "lient.R;\n\n/**\n * 2017年1月14日16:52:28\n * \n * @author XFHY 登录练习\n */\npublic class MainActivity extends Activi", "end": 592, "score": 0.9995109438896179, "start": 588, "tag": "USERNAME", "value": "XFHY" } ]
null
[]
package com.itheima.login; import java.util.Map; import java.util.Random; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; import com.itheima.login.net.HttpLoginUtils; import com.itheima.login.util.UserInfoUtil; import com.itheima.login_asynchttpclient.R; /** * 2017年1月14日16:52:28 * * @author XFHY 登录练习 */ public class MainActivity extends Activity implements OnClickListener { private EditText et_username; private EditText et_password; private CheckBox cb_reme; private Button btn_login; private boolean isrem; private String userpassword; private String username; private Context mContext; // 在Activity中定义一个属性private Context mContext; // 然后在setContentView之后将这个属性初始化(设置为当前的Activity.this),很多地方需要用到Context对象(比如Toast等), // 这样很方便.在公司,有经验的人都这样写,so... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = this; // a.找到相应控件 et_username = (EditText) findViewById(R.id.et_username); et_password = (EditText) findViewById(R.id.et_password); cb_reme = (CheckBox) findViewById(R.id.cb_reme); btn_login = (Button) findViewById(R.id.btn_login); // b.设置按钮的点击事件 btn_login.setOnClickListener(this); // f.回显用户名密码 Map<String, String> map = UserInfoUtil.readUserInfo(mContext); // 获取用户名和密码 if (map != null) { et_username.setText(map.get("username")); // 设置用户名和密码 et_password.setText(map.get("password")); cb_reme.setChecked(true); // 设置为记住密码 } } /** * 登录按钮执行逻辑 */ private void login() { username = et_username.getText().toString().trim(); userpassword = et_password.getText().toString().trim(); isrem = cb_reme.isChecked(); // d.判断用户名密码是否为空,不为空请求服务器(省略,默认请求成功) if (TextUtils.isEmpty(username) || TextUtils.isEmpty(userpassword)) { Toast.makeText(mContext, "用户名或密码为空", Toast.LENGTH_SHORT).show(); } // 访问服务器,查看是否登录成功 通过handler进行返回 数据 // Random random = new Random(); // int nextInt = random.nextInt(10); // if (nextInt > 3) { // HttpLoginUtils.requestNetForGetLogin(mContext, username, // userpassword); // GET方式 // } else { HttpLoginUtils.requestNetForPostLogin(mContext, username, userpassword); // POST方式 // } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_login: login(); break; default: break; } } }
3,000
0.72555
0.719484
106
23.886793
21.194214
81
false
false
0
0
0
0
0
0
1.707547
false
false
11
7e6861e88d94bf06b8c1aef1ecba0c16fc6b8bad
1,331,439,897,051
6843dd18535eae83ec6282b3c4cdddd648e5ffc9
/TestBasicFile.java
6262072994096aeb83cee4970251d96ade92ae1e
[]
no_license
livanjimenez/files_streams
https://github.com/livanjimenez/files_streams
0a35024f454904d77fab5f1d812ad23a14764a94
46722192c80b6b2b2368e44131972aa2de813726
refs/heads/master
2020-04-27T20:08:04.109000
2019-03-11T00:06:47
2019-03-11T00:06:47
174,646,699
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import javax.swing.*; import java.io.*; public class TestBasicFile { static void showMessage(String s, String data, int t) { JTextArea txt = new JTextArea(s, 25, 45); JScrollPane p = new JScrollPane(txt); JOptionPane.showMessageDialog(null, p, data, t); } public static void main(String args[]) throws IOException { BasicFile f = new BasicFile(); boolean process = false; String menu = "Menu" + "\n1.Select file\n2.View file selected\n3.File size & path" + "\n4.Files & directory \n" + "5.Number of line(s) found in the file \n6.Search \n7.Overwrite file \n8.Copy file \n9.Exit"; while (!process) { try { int i = Integer.parseInt(JOptionPane.showInputDialog(menu)); switch (i) { case 1: f.f_select(); if (f.exists()) { JOptionPane.showMessageDialog(null, "File has been selected", "", JOptionPane.INFORMATION_MESSAGE); } else { f.f_select(); } break; case 2: showMessage(f.f_content(f.getFile()), "File", JOptionPane.INFORMATION_MESSAGE); break; case 3: showMessage(f.getPath() + f.getSize(), "File", JOptionPane.INFORMATION_MESSAGE); break; case 4: showMessage(f.list(f.getFile()), "File", JOptionPane.INFORMATION_MESSAGE); break; case 5: showMessage(f.tokenize(), "File", JOptionPane.INFORMATION_MESSAGE); break; case 6: String word = JOptionPane.showInputDialog("Enter word(s)"); showMessage(f.f_search(word), "Search: " + word, JOptionPane.INFORMATION_MESSAGE); break; case 7: f.overwrite(); if (f.exists()) { JOptionPane.showMessageDialog(null, "File has been overwritten", "Press enter to overwrite", JOptionPane.INFORMATION_MESSAGE); showMessage(f.f_content(f.getFile()), "File", JOptionPane.INFORMATION_MESSAGE); } else { f.overwrite(); } break; case 8: f.f_select(); f.f_backup(); break; case 9: process = true; break; default: break; } } catch (NumberFormatException | NullPointerException e) { System.exit(0); } } } }
UTF-8
Java
2,911
java
TestBasicFile.java
Java
[]
null
[]
import javax.swing.*; import java.io.*; public class TestBasicFile { static void showMessage(String s, String data, int t) { JTextArea txt = new JTextArea(s, 25, 45); JScrollPane p = new JScrollPane(txt); JOptionPane.showMessageDialog(null, p, data, t); } public static void main(String args[]) throws IOException { BasicFile f = new BasicFile(); boolean process = false; String menu = "Menu" + "\n1.Select file\n2.View file selected\n3.File size & path" + "\n4.Files & directory \n" + "5.Number of line(s) found in the file \n6.Search \n7.Overwrite file \n8.Copy file \n9.Exit"; while (!process) { try { int i = Integer.parseInt(JOptionPane.showInputDialog(menu)); switch (i) { case 1: f.f_select(); if (f.exists()) { JOptionPane.showMessageDialog(null, "File has been selected", "", JOptionPane.INFORMATION_MESSAGE); } else { f.f_select(); } break; case 2: showMessage(f.f_content(f.getFile()), "File", JOptionPane.INFORMATION_MESSAGE); break; case 3: showMessage(f.getPath() + f.getSize(), "File", JOptionPane.INFORMATION_MESSAGE); break; case 4: showMessage(f.list(f.getFile()), "File", JOptionPane.INFORMATION_MESSAGE); break; case 5: showMessage(f.tokenize(), "File", JOptionPane.INFORMATION_MESSAGE); break; case 6: String word = JOptionPane.showInputDialog("Enter word(s)"); showMessage(f.f_search(word), "Search: " + word, JOptionPane.INFORMATION_MESSAGE); break; case 7: f.overwrite(); if (f.exists()) { JOptionPane.showMessageDialog(null, "File has been overwritten", "Press enter to overwrite", JOptionPane.INFORMATION_MESSAGE); showMessage(f.f_content(f.getFile()), "File", JOptionPane.INFORMATION_MESSAGE); } else { f.overwrite(); } break; case 8: f.f_select(); f.f_backup(); break; case 9: process = true; break; default: break; } } catch (NumberFormatException | NullPointerException e) { System.exit(0); } } } }
2,911
0.454827
0.446925
71
40.014084
29.909956
119
false
false
0
0
0
0
0
0
0.873239
false
false
11
fa7d8510860befb46583a1ed452975085c5c7af4
18,537,078,863,892
65ed42c67a3bc91a27c547beeb6466f8546828c3
/src/main/java/nl/quintor/rc/web/soap/dto/aanmakengebruiker/ObjectFactory.java
d91219d431282e248f813926f7786494494567ce
[]
no_license
openrory/rekening-courant
https://github.com/openrory/rekening-courant
1d750e25856ca1f9a8448b5801f8b285177f3076
882c9f4aab3ad7bf6875f08bf1f890899e76c67e
refs/heads/master
2020-05-21T01:36:27.522000
2017-03-10T14:46:29
2017-03-10T14:46:29
84,552,096
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package nl.quintor.rc.web.soap.dto.aanmakengebruiker; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the nl.quintor.rc.web.soap.dto.aanmakengebruiker package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _AanmakenGebruikerException_QNAME = new QName("http://www.quintor.nl/rc/gebruikeraanmaken/1.0", "AanmakenGebruikerException"); private final static QName _AanmakenGebruikerResponse_QNAME = new QName("http://www.quintor.nl/rc/gebruikeraanmaken/1.0", "AanmakenGebruikerResponse"); private final static QName _AanmakenGebruikerRequest_QNAME = new QName("http://www.quintor.nl/rc/gebruikeraanmaken/1.0", "AanmakenGebruikerRequest"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: nl.quintor.rc.web.soap.dto.aanmakengebruiker * */ public ObjectFactory() { } /** * Create an instance of {@link AanmakenGebruikerResponse } * */ public AanmakenGebruikerResponse createAanmakenGebruikerResponse() { return new AanmakenGebruikerResponse(); } /** * Create an instance of {@link AanmakenGebruikerRequest } * */ public AanmakenGebruikerRequest createAanmakenGebruikerRequest() { return new AanmakenGebruikerRequest(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://www.quintor.nl/rc/gebruikeraanmaken/1.0", name = "AanmakenGebruikerException") public JAXBElement<String> createAanmakenGebruikerException(String value) { return new JAXBElement<String>(_AanmakenGebruikerException_QNAME, String.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AanmakenGebruikerResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://www.quintor.nl/rc/gebruikeraanmaken/1.0", name = "AanmakenGebruikerResponse") public JAXBElement<AanmakenGebruikerResponse> createAanmakenGebruikerResponse(AanmakenGebruikerResponse value) { return new JAXBElement<AanmakenGebruikerResponse>(_AanmakenGebruikerResponse_QNAME, AanmakenGebruikerResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AanmakenGebruikerRequest }{@code >}} * */ @XmlElementDecl(namespace = "http://www.quintor.nl/rc/gebruikeraanmaken/1.0", name = "AanmakenGebruikerRequest") public JAXBElement<AanmakenGebruikerRequest> createAanmakenGebruikerRequest(AanmakenGebruikerRequest value) { return new JAXBElement<AanmakenGebruikerRequest>(_AanmakenGebruikerRequest_QNAME, AanmakenGebruikerRequest.class, null, value); } }
UTF-8
Java
3,394
java
ObjectFactory.java
Java
[]
null
[]
package nl.quintor.rc.web.soap.dto.aanmakengebruiker; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the nl.quintor.rc.web.soap.dto.aanmakengebruiker package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _AanmakenGebruikerException_QNAME = new QName("http://www.quintor.nl/rc/gebruikeraanmaken/1.0", "AanmakenGebruikerException"); private final static QName _AanmakenGebruikerResponse_QNAME = new QName("http://www.quintor.nl/rc/gebruikeraanmaken/1.0", "AanmakenGebruikerResponse"); private final static QName _AanmakenGebruikerRequest_QNAME = new QName("http://www.quintor.nl/rc/gebruikeraanmaken/1.0", "AanmakenGebruikerRequest"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: nl.quintor.rc.web.soap.dto.aanmakengebruiker * */ public ObjectFactory() { } /** * Create an instance of {@link AanmakenGebruikerResponse } * */ public AanmakenGebruikerResponse createAanmakenGebruikerResponse() { return new AanmakenGebruikerResponse(); } /** * Create an instance of {@link AanmakenGebruikerRequest } * */ public AanmakenGebruikerRequest createAanmakenGebruikerRequest() { return new AanmakenGebruikerRequest(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://www.quintor.nl/rc/gebruikeraanmaken/1.0", name = "AanmakenGebruikerException") public JAXBElement<String> createAanmakenGebruikerException(String value) { return new JAXBElement<String>(_AanmakenGebruikerException_QNAME, String.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AanmakenGebruikerResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://www.quintor.nl/rc/gebruikeraanmaken/1.0", name = "AanmakenGebruikerResponse") public JAXBElement<AanmakenGebruikerResponse> createAanmakenGebruikerResponse(AanmakenGebruikerResponse value) { return new JAXBElement<AanmakenGebruikerResponse>(_AanmakenGebruikerResponse_QNAME, AanmakenGebruikerResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AanmakenGebruikerRequest }{@code >}} * */ @XmlElementDecl(namespace = "http://www.quintor.nl/rc/gebruikeraanmaken/1.0", name = "AanmakenGebruikerRequest") public JAXBElement<AanmakenGebruikerRequest> createAanmakenGebruikerRequest(AanmakenGebruikerRequest value) { return new JAXBElement<AanmakenGebruikerRequest>(_AanmakenGebruikerRequest_QNAME, AanmakenGebruikerRequest.class, null, value); } }
3,394
0.733058
0.729523
80
41.412498
46.478409
158
false
false
0
0
0
0
0
0
0.3625
false
false
11
ae1690c40b997197771bdfb06bafc19c1e849c1f
532,575,986,967
8f0402c94fd984d5845db4660514b80365afa470
/Assignments_java Training/Projects/HibernateBook/src/com/sd/Book.java
b345540dd397a9432a2eb65881cf9c59d290aca3
[]
no_license
sakshi-dashore/Assignment_JavaTraining
https://github.com/sakshi-dashore/Assignment_JavaTraining
b050c61b5650a604eb9ed6c818962ff0005cf1bc
b7fd2e61c0ccff34224ba5b4d78421e2af8e50fa
refs/heads/master
2023-04-23T04:46:35.602000
2021-04-26T17:49:13
2021-04-26T17:49:13
361,839,305
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sd; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="Book") public class Book { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) int id; String title; String author; String price; String genre; public Book(int id, String title, String author, String price, String genre) { super(); this.id = id; this.title = title; this.author = author; this.price = price; this.genre = genre; } public Book( String title, String author, String price, String genre) { super(); this.title = title; this.author = author; this.price = price; this.genre = genre; } public Book() { super(); // TODO Auto-generated constructor stub } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } @Override public String toString() { return "Book [id=" + id + ", title=" + title + ", author=" + author + ", price=" + price + ", genre=" + genre + "]"; } }
UTF-8
Java
1,575
java
Book.java
Java
[]
null
[]
package com.sd; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="Book") public class Book { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) int id; String title; String author; String price; String genre; public Book(int id, String title, String author, String price, String genre) { super(); this.id = id; this.title = title; this.author = author; this.price = price; this.genre = genre; } public Book( String title, String author, String price, String genre) { super(); this.title = title; this.author = author; this.price = price; this.genre = genre; } public Book() { super(); // TODO Auto-generated constructor stub } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } @Override public String toString() { return "Book [id=" + id + ", title=" + title + ", author=" + author + ", price=" + price + ", genre=" + genre + "]"; } }
1,575
0.668571
0.668571
88
16.897728
18.506781
111
false
false
0
0
0
0
0
0
1.647727
false
false
11
bbe10c151df6ba8316dbdaacb2a29b72af1e7751
8,014,408,982,459
417d3adad9f87226c463a0950d74063fd1631fdd
/app/src/main/java/woo/com/wakeup/ui/menu/DrinkItem.java
b75a7e6bdf4c170aa338343d919ac505d500c444
[]
no_license
Jesse0722/WakeUp
https://github.com/Jesse0722/WakeUp
dd5866022de16f41a90177fbdf3f1d58b86782c4
37ed2c17109c8a7b7734b2dcb068de76f14e5242
refs/heads/master
2021-01-12T21:43:57.500000
2016-03-14T10:23:16
2016-03-14T10:23:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package woo.com.wakeup.ui.menu; /** * DrinkItem * Desc: * Team: InHand * User: Wooxxx * Date: 2015-10-30 * Time: 22:04 */ public class DrinkItem { // 原图,为选中的图 private int image, imageUnselected; // 饮品描述 private String desc; // Id private int id; public DrinkItem() { } public DrinkItem(int image, int imageUnselected, String desc, int id) { this.image = image; this.imageUnselected = imageUnselected; this.desc = desc; this.id = id; } public int getImage() { return image; } public void setImage(int image) { this.image = image; } public int getImageUnselected() { return imageUnselected; } public void setImageUnselected(int imageUnselected) { this.imageUnselected = imageUnselected; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
UTF-8
Java
1,107
java
DrinkItem.java
Java
[ { "context": "/**\n * DrinkItem\n * Desc:\n * Team: InHand\n * User: Wooxxx\n * Date: 2015-10-30\n * Time: 22:04\n */\npublic cla", "end": 91, "score": 0.9995014071464539, "start": 85, "tag": "USERNAME", "value": "Wooxxx" } ]
null
[]
package woo.com.wakeup.ui.menu; /** * DrinkItem * Desc: * Team: InHand * User: Wooxxx * Date: 2015-10-30 * Time: 22:04 */ public class DrinkItem { // 原图,为选中的图 private int image, imageUnselected; // 饮品描述 private String desc; // Id private int id; public DrinkItem() { } public DrinkItem(int image, int imageUnselected, String desc, int id) { this.image = image; this.imageUnselected = imageUnselected; this.desc = desc; this.id = id; } public int getImage() { return image; } public void setImage(int image) { this.image = image; } public int getImageUnselected() { return imageUnselected; } public void setImageUnselected(int imageUnselected) { this.imageUnselected = imageUnselected; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
1,107
0.575254
0.564174
62
16.467741
16.047026
75
false
false
0
0
0
0
0
0
0.322581
false
false
11
d075b3305586231469b493a6b5e4bb02f1b8fa95
8,014,408,982,843
ff7ca960c341f70dcbe565f1e9a2e4101b5e32ed
/clinica/src/clinic/external/Patient.java
d6a86dbb09e24b464eb6bc81ee5ee061236f5559
[]
no_license
beavanzi/clinica-oop
https://github.com/beavanzi/clinica-oop
c153680a448b571a94e6091e5c75dc713f4dd3d8
48a0fa5c8bb855bc5295cf85d654df3af7b8ea30
refs/heads/main
2023-04-29T12:42:32.287000
2021-05-23T00:46:05
2021-05-23T00:46:05
352,216,939
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 clinic.external; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * * @author biaav */ @Entity public class Patient { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column (name="name", length=100, nullable=false, unique=true) private String name; @Column (name="docnumber", length=17, nullable=false, unique=true) private String docNumber; @Column (name="birthdate", length=11, nullable=false, unique=false) private String birthDate; @Column (name="address", length=100, nullable=false, unique=false) private String address; private String phone; private String email; @Column (name="healthinsurance", length=100, nullable=false, unique=false) private String healthInsurance; public Patient() { } public Patient(String name, String docNumber, String birthDate, String address, String phone, String email, String healthInsurance) { this.name = name; this.docNumber = docNumber; this.birthDate = birthDate; this.address = address; this.phone = phone; this.email = email; this.healthInsurance = healthInsurance; } public Integer getId(){ return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDocNumber() { return docNumber; } public void setDocNumber(String docNumber) { this.docNumber = docNumber; } public String getBirthDate() { return birthDate; } public void setBirthDate(String birthDate) { this.birthDate = birthDate; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getHealthInsurance() { return healthInsurance; } public void setHealthInsurance(String healthInsurance) { this.healthInsurance = healthInsurance; } }
UTF-8
Java
2,641
java
Patient.java
Java
[ { "context": "e;\nimport javax.persistence.Id;\n\n/**\n *\n * @author biaav\n */\n\n@Entity\npublic class Patient {\n @Id @Gene", "end": 412, "score": 0.994744062423706, "start": 407, "tag": "USERNAME", "value": "biaav" } ]
null
[]
/* * 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 clinic.external; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * * @author biaav */ @Entity public class Patient { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column (name="name", length=100, nullable=false, unique=true) private String name; @Column (name="docnumber", length=17, nullable=false, unique=true) private String docNumber; @Column (name="birthdate", length=11, nullable=false, unique=false) private String birthDate; @Column (name="address", length=100, nullable=false, unique=false) private String address; private String phone; private String email; @Column (name="healthinsurance", length=100, nullable=false, unique=false) private String healthInsurance; public Patient() { } public Patient(String name, String docNumber, String birthDate, String address, String phone, String email, String healthInsurance) { this.name = name; this.docNumber = docNumber; this.birthDate = birthDate; this.address = address; this.phone = phone; this.email = email; this.healthInsurance = healthInsurance; } public Integer getId(){ return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDocNumber() { return docNumber; } public void setDocNumber(String docNumber) { this.docNumber = docNumber; } public String getBirthDate() { return birthDate; } public void setBirthDate(String birthDate) { this.birthDate = birthDate; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getHealthInsurance() { return healthInsurance; } public void setHealthInsurance(String healthInsurance) { this.healthInsurance = healthInsurance; } }
2,641
0.65089
0.645967
110
23.00909
22.813671
137
true
false
0
0
0
0
0
0
0.545455
false
false
11
222a3dc482f300282e32f6da0539e462c0486371
22,789,096,539,455
6f3cf9d2eaaded996271a0fd1a165b1df216655a
/java_certification/static_scope_gc/this_examples/this_incorrect2/Car.java
89d06e61b5c982eb5f67953ed769b26b7e6d6707
[]
no_license
nislamovs/Playground
https://github.com/nislamovs/Playground
45529ff52407c90280fe30351d86b9b048a0f415
a5b6158e89b96dbe99306a313576ab4ee6a1259d
refs/heads/master
2023-07-21T14:29:34.927000
2022-11-09T14:11:01
2022-11-09T14:11:01
178,099,445
0
0
null
false
2023-07-07T21:39:10
2019-03-28T01:03:27
2022-09-19T03:57:47
2023-07-07T21:39:06
8,403
0
0
12
Shell
false
false
public class Car { String color = "default"; String model = "default"; int vin; static int count; Car() { count++; vin = count; } Car(String color, String model, int vin) { this(); //calling constructor // count++; //this() constructor calling should be called first // vin = count; this.color = color; //this(); //illegal usage - should be called first this.model = model; } void printDescription() { //this(); //illegal usage - cannot be called from method System.out.println("this is " + color + " " + model); } public String toString() { return "Color: " + color + ", model: " + model + ", vin: " + String.valueOf(vin) + ", total number: " + String.valueOf(count); } public static void main(String[] args) { Car car = new Car("blue", "bmw", 123); Car car1 = new Car("blue", "bmw", 123); Car car2 = new Car("blue", "bmw", 123); System.out.println(car.toString()); } }
UTF-8
Java
1,273
java
Car.java
Java
[]
null
[]
public class Car { String color = "default"; String model = "default"; int vin; static int count; Car() { count++; vin = count; } Car(String color, String model, int vin) { this(); //calling constructor // count++; //this() constructor calling should be called first // vin = count; this.color = color; //this(); //illegal usage - should be called first this.model = model; } void printDescription() { //this(); //illegal usage - cannot be called from method System.out.println("this is " + color + " " + model); } public String toString() { return "Color: " + color + ", model: " + model + ", vin: " + String.valueOf(vin) + ", total number: " + String.valueOf(count); } public static void main(String[] args) { Car car = new Car("blue", "bmw", 123); Car car1 = new Car("blue", "bmw", 123); Car car2 = new Car("blue", "bmw", 123); System.out.println(car.toString()); } }
1,273
0.445405
0.436764
38
32.526318
37.180031
135
false
false
0
0
0
0
0
0
0.789474
false
false
11
3d15f4896203a3addbca325100bc010a3cbe016d
23,476,291,250,654
e44b6d0dd79279e9be56d835b2010bc663baa363
/eGs_epro_sbdc/src/main/java/com/eunwoosoft/frwk/pel/mybatis/interceptor/FwkSqlLogInterceptor.java
23ac11ab3e53383203ae4e01d88db835ec8f4c92
[]
no_license
son99you/cloud_test
https://github.com/son99you/cloud_test
7d17248cd08f72584316f65b32131924020bfef8
61908c06f1be209daf619bbfb3a1c36c2d363d08
refs/heads/master
2023-09-05T00:46:13.831000
2021-11-23T07:18:00
2021-11-23T07:18:00
430,992,584
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * <pre> * Copyright (c) 2014 KOICA. * All rights reserved. * * This software is the confidential and proprietary information * * </pre> */ package com.eunwoosoft.frwk.pel.mybatis.interceptor; import java.lang.reflect.Field; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import org.apache.ibatis.cache.CacheKey; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.ParameterMapping; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.plugin.Intercepts; import org.apache.ibatis.plugin.Invocation; import org.apache.ibatis.plugin.Plugin; import org.apache.ibatis.plugin.Signature; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Mybatis SQL 로그를 가독성있게 재구성해주는 Interceptor 클래스 * * @author : * @date : 2014. 11. 13. * @version : 1.0 */ @Intercepts({ @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}) ,@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}) ,@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}) }) public class FwkSqlLogInterceptor implements Interceptor { private static final Logger LOG = LoggerFactory.getLogger("SQL_LOG"); public Object intercept(Invocation invocation) throws Throwable { Object[] args = invocation.getArgs(); MappedStatement ms = (MappedStatement)args[0]; Object param = (Object)args[1]; BoundSql boundSql = ms.getBoundSql(param); String sql = replaceSql(boundSql, param); LOG.debug("====================================================================="); LOG.debug("SQL Id : " + ms.getId()); LOG.debug("orgiSql : " + boundSql.getSql()); LOG.debug("params : " + param); LOG.debug("bindSql : " + sql); LOG.debug("====================================================================="); return invocation.proceed(); // 쿼리 실행 } public Object plugin(Object target) { return Plugin.wrap(target, this); } public void setProperties(Properties arg0) { } private static String replaceSql(BoundSql boundSql, Object param) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String sql = boundSql.getSql(); if(param == null) { sql = sql.replaceFirst("\\?", "''"); } else { if(param instanceof Integer || param instanceof Long || param instanceof Float || param instanceof Double) { sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(param.toString())); } else if(param instanceof String ) { sql = sql.replaceFirst("\\?", "'" + Matcher.quoteReplacement((String)param) + "''"); } else if(param instanceof Map ) { sql = replaceSqlByMap(boundSql, param); } else { List<ParameterMapping> paramMapping = boundSql.getParameterMappings(); Class<? extends Object> paramClass = param.getClass(); for(ParameterMapping mapping : paramMapping) { String propValue = mapping.getProperty(); Field field = paramClass.getDeclaredField(propValue); field.setAccessible(true); Class<?> javaType = mapping.getJavaType(); if(String.class == javaType) { sql = sql.replaceFirst("\\?", "" + field.get(param) + "'"); } else { sql = sql.replaceFirst("\\?", "" + Matcher.quoteReplacement(field.get(param).toString()) + ""); } } } } return sql; } private static String replaceSqlByMap(BoundSql boundSql, Object param) { String sql = boundSql.getSql(); List<ParameterMapping> paramMapping = boundSql.getParameterMappings(); for(ParameterMapping mapping : paramMapping) { String propValue = mapping.getProperty(); @SuppressWarnings("rawtypes") Object value = ((Map) param).get(propValue); if(value == null ){ sql = sql.replaceFirst("\\?", "" + value + ""); } else { if(value instanceof String) { sql = sql.replaceFirst("\\?", "'" + Matcher.quoteReplacement(value.toString()) + "'"); } else { sql = sql.replaceFirst("\\?", "'" + Matcher.quoteReplacement(value.toString()) + "'"); } } } return sql; } }
UTF-8
Java
4,810
java
FwkSqlLogInterceptor.java
Java
[]
null
[]
/* * <pre> * Copyright (c) 2014 KOICA. * All rights reserved. * * This software is the confidential and proprietary information * * </pre> */ package com.eunwoosoft.frwk.pel.mybatis.interceptor; import java.lang.reflect.Field; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import org.apache.ibatis.cache.CacheKey; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.ParameterMapping; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.plugin.Intercepts; import org.apache.ibatis.plugin.Invocation; import org.apache.ibatis.plugin.Plugin; import org.apache.ibatis.plugin.Signature; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Mybatis SQL 로그를 가독성있게 재구성해주는 Interceptor 클래스 * * @author : * @date : 2014. 11. 13. * @version : 1.0 */ @Intercepts({ @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}) ,@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}) ,@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}) }) public class FwkSqlLogInterceptor implements Interceptor { private static final Logger LOG = LoggerFactory.getLogger("SQL_LOG"); public Object intercept(Invocation invocation) throws Throwable { Object[] args = invocation.getArgs(); MappedStatement ms = (MappedStatement)args[0]; Object param = (Object)args[1]; BoundSql boundSql = ms.getBoundSql(param); String sql = replaceSql(boundSql, param); LOG.debug("====================================================================="); LOG.debug("SQL Id : " + ms.getId()); LOG.debug("orgiSql : " + boundSql.getSql()); LOG.debug("params : " + param); LOG.debug("bindSql : " + sql); LOG.debug("====================================================================="); return invocation.proceed(); // 쿼리 실행 } public Object plugin(Object target) { return Plugin.wrap(target, this); } public void setProperties(Properties arg0) { } private static String replaceSql(BoundSql boundSql, Object param) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String sql = boundSql.getSql(); if(param == null) { sql = sql.replaceFirst("\\?", "''"); } else { if(param instanceof Integer || param instanceof Long || param instanceof Float || param instanceof Double) { sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(param.toString())); } else if(param instanceof String ) { sql = sql.replaceFirst("\\?", "'" + Matcher.quoteReplacement((String)param) + "''"); } else if(param instanceof Map ) { sql = replaceSqlByMap(boundSql, param); } else { List<ParameterMapping> paramMapping = boundSql.getParameterMappings(); Class<? extends Object> paramClass = param.getClass(); for(ParameterMapping mapping : paramMapping) { String propValue = mapping.getProperty(); Field field = paramClass.getDeclaredField(propValue); field.setAccessible(true); Class<?> javaType = mapping.getJavaType(); if(String.class == javaType) { sql = sql.replaceFirst("\\?", "" + field.get(param) + "'"); } else { sql = sql.replaceFirst("\\?", "" + Matcher.quoteReplacement(field.get(param).toString()) + ""); } } } } return sql; } private static String replaceSqlByMap(BoundSql boundSql, Object param) { String sql = boundSql.getSql(); List<ParameterMapping> paramMapping = boundSql.getParameterMappings(); for(ParameterMapping mapping : paramMapping) { String propValue = mapping.getProperty(); @SuppressWarnings("rawtypes") Object value = ((Map) param).get(propValue); if(value == null ){ sql = sql.replaceFirst("\\?", "" + value + ""); } else { if(value instanceof String) { sql = sql.replaceFirst("\\?", "'" + Matcher.quoteReplacement(value.toString()) + "'"); } else { sql = sql.replaceFirst("\\?", "'" + Matcher.quoteReplacement(value.toString()) + "'"); } } } return sql; } }
4,810
0.628565
0.624581
149
30
32.859676
176
false
false
0
0
0
0
69
0.028943
2.536913
false
false
11
91621cb3844cb755008d93a284c5cdc5c9c4ab73
31,868,657,353,192
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/11/11_7e93dffb988aebfcf20ac8980ac01e531f22cec4/App/11_7e93dffb988aebfcf20ac8980ac01e531f22cec4_App_s.java
8b97781c6f44022276073b6875f1846c53c70144
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
package com.yoharnu.newontv.android; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.LinkedList; import java.util.Scanner; import java.util.concurrent.ExecutionException; import com.yoharnu.newontv.android.shows.Series; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.os.Environment; import android.preference.PreferenceManager; public class App extends Application { public static final String MIRRORPATH = "http://thetvdb.com"; public static final String LANGUAGE = "en"; public static final String API_KEY = "768A3A72ACDABC4A"; protected static Context context; public static SharedPreferences preferences; public static LinkedList<Series> shows; private static boolean mExternalStorageAvailable = false; private static boolean mExternalStorageWriteable = false; public void onCreate() { super.onCreate(); context = getApplicationContext(); preferences = PreferenceManager.getDefaultSharedPreferences(context); shows = new LinkedList<Series>(); checkPermissions(); load(); } public static Context getContext() { return context; } public static void add(String seriesId) { Series temp = new Series(seriesId, Series.ID); try { if (temp.task != null) temp.task.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } boolean present = false; for (int i = 0; i < shows.size(); i++) { if (shows.get(i).getSeriesId().equals(seriesId)) { present = true; } } if (!present) { shows.add(temp); save(); } } public static void add(Series series) { boolean present = false; for (int i = 0; i < shows.size(); i++) { if (shows.get(i).getSeriesId().equals(series.getSeriesId())) { present = true; } } if (!present) { shows.add(series); save(); } } public static void save() { try { PrintStream out = new PrintStream(new File(context.getFilesDir(), "shows")); for (int i = 0; i < shows.size(); i++) { out.println(shows.get(i).getSeriesId()); } } catch (FileNotFoundException e) { } } private static void load() { try { Scanner s = new Scanner(new File(context.getFilesDir(), "shows")); shows.clear(); while (s.hasNextLine()) { add(s.nextLine()); } if (s != null) { s.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void sort() { for (int i = 0; i < App.shows.size(); i++) { Series temp = App.shows.get(i); int iHole = i; while (iHole > 0 && App.shows.get(iHole - 1).getSeriesName() .compareTo(temp.getSeriesName()) > 0) { App.shows.set(iHole, App.shows.get(iHole - 1)); iHole--; } App.shows.set(iHole, temp); } } protected void checkPermissions() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageAvailable = true; mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { // Something else is wrong. It may be one of many other states, but // all we need // to know is we can neither read nor write mExternalStorageAvailable = false; mExternalStorageWriteable = false; } } public static boolean isExternalStorageWriteable() { return mExternalStorageWriteable; } public static boolean isExternalStorageAvailable() { return mExternalStorageAvailable; } }
UTF-8
Java
3,846
java
11_7e93dffb988aebfcf20ac8980ac01e531f22cec4_App_s.java
Java
[ { "context": "E = \"en\";\n \tpublic static final String API_KEY = \"768A3A72ACDABC4A\";\n \tprotected static Context context;\n \tpublic st", "end": 687, "score": 0.999686598777771, "start": 671, "tag": "KEY", "value": "768A3A72ACDABC4A" } ]
null
[]
package com.yoharnu.newontv.android; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.LinkedList; import java.util.Scanner; import java.util.concurrent.ExecutionException; import com.yoharnu.newontv.android.shows.Series; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.os.Environment; import android.preference.PreferenceManager; public class App extends Application { public static final String MIRRORPATH = "http://thetvdb.com"; public static final String LANGUAGE = "en"; public static final String API_KEY = "<KEY>"; protected static Context context; public static SharedPreferences preferences; public static LinkedList<Series> shows; private static boolean mExternalStorageAvailable = false; private static boolean mExternalStorageWriteable = false; public void onCreate() { super.onCreate(); context = getApplicationContext(); preferences = PreferenceManager.getDefaultSharedPreferences(context); shows = new LinkedList<Series>(); checkPermissions(); load(); } public static Context getContext() { return context; } public static void add(String seriesId) { Series temp = new Series(seriesId, Series.ID); try { if (temp.task != null) temp.task.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } boolean present = false; for (int i = 0; i < shows.size(); i++) { if (shows.get(i).getSeriesId().equals(seriesId)) { present = true; } } if (!present) { shows.add(temp); save(); } } public static void add(Series series) { boolean present = false; for (int i = 0; i < shows.size(); i++) { if (shows.get(i).getSeriesId().equals(series.getSeriesId())) { present = true; } } if (!present) { shows.add(series); save(); } } public static void save() { try { PrintStream out = new PrintStream(new File(context.getFilesDir(), "shows")); for (int i = 0; i < shows.size(); i++) { out.println(shows.get(i).getSeriesId()); } } catch (FileNotFoundException e) { } } private static void load() { try { Scanner s = new Scanner(new File(context.getFilesDir(), "shows")); shows.clear(); while (s.hasNextLine()) { add(s.nextLine()); } if (s != null) { s.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void sort() { for (int i = 0; i < App.shows.size(); i++) { Series temp = App.shows.get(i); int iHole = i; while (iHole > 0 && App.shows.get(iHole - 1).getSeriesName() .compareTo(temp.getSeriesName()) > 0) { App.shows.set(iHole, App.shows.get(iHole - 1)); iHole--; } App.shows.set(iHole, temp); } } protected void checkPermissions() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageAvailable = true; mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { // Something else is wrong. It may be one of many other states, but // all we need // to know is we can neither read nor write mExternalStorageAvailable = false; mExternalStorageWriteable = false; } } public static boolean isExternalStorageWriteable() { return mExternalStorageWriteable; } public static boolean isExternalStorageAvailable() { return mExternalStorageAvailable; } }
3,835
0.661726
0.657826
145
25.517241
19.705103
72
false
false
0
0
0
0
0
0
2.324138
false
false
11
d3268f4af236589837d340c36e30325ae9e40f8d
20,014,547,626,107
02388bc6f632ded81c4b34a81c4b6d2433e90c74
/MonzoCalorieTracker/src/java/com/monzoct/model/Comida.java
230050c85fc6a9d9c103a6699d0c9e521662d390
[]
no_license
ivanoba/Monzo
https://github.com/ivanoba/Monzo
85410de91dfcaba318bf14f862e31c5d7b32e4a9
1531478d0e20f95a679c6a7bc230df17f0238323
refs/heads/master
2021-08-08T20:04:11.215000
2017-11-11T02:22:33
2017-11-11T02:22:33
109,361,698
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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.monzoct.model; /** * * @author M I C I F U S */ public class Comida { //vic private Integer codigoComida; private String nombreComida; private String serving; private double servingSize; private double calorias; private double carbohidratos; private double grasas; private double proteinas; private double sodio; private double azucar; private CalorieTracker codigoTracker; //Constructores public Comida() { codigoComida = 0; nombreComida = ""; serving = ""; servingSize = 0; calorias = 0; carbohidratos = 0; grasas = 0; proteinas = 0; sodio = 0; azucar = 0; codigoTracker = new CalorieTracker(); } public Comida(Integer codigoComida, String nombreComida, String serving, double servingSize, int calorias, double carbohidratos, double grasas, double proteinas, double sodio, double azucar, CalorieTracker idCalorieTracker) { this.codigoComida = codigoComida; this.nombreComida = nombreComida; this.servingSize = servingSize; this.calorias = calorias; this.carbohidratos = carbohidratos; this.grasas = grasas; this.proteinas = proteinas; this.sodio = sodio; this.azucar = azucar; this.codigoTracker = idCalorieTracker; } //Getters public Integer getCodigoComida() { return codigoComida; } public String getNombreComida() { return nombreComida; } public String getServing() { return serving; } public double getServingSize() { return servingSize; } public double getCalorias() { return calorias; } public double getCarbohidratos() { return carbohidratos; } public double getGrasas() { return grasas; } public double getProteinas() { return proteinas; } public double getSodio() { return sodio; } public double getAzucar() { return azucar; } public CalorieTracker getCodigoTracker() { return codigoTracker; } //Setters public void setCodigoComida(Integer codigoComida) { this.codigoComida = codigoComida; } public void setNombreComida(String nombreComida) { this.nombreComida = nombreComida; } public void setServing(String serving) { this.serving = serving; } public void setServingSize(double servingSize) { this.servingSize = servingSize; } public void setCalorias(double calorias) { this.calorias = calorias; } public void setCarbohidratos(double carbohidratos) { this.carbohidratos = carbohidratos; } public void setGrasas(double grasas) { this.grasas = grasas; } public void setProteinas(double proteinas) { this.proteinas = proteinas; } public void setSodio(double sodio) { this.sodio = sodio; } public void setAzucar(double azucar) { this.azucar = azucar; } public void setCodigoTracker(CalorieTracker codigoTracker) { this.codigoTracker = codigoTracker; } }
UTF-8
Java
3,570
java
Comida.java
Java
[ { "context": "\npackage com.monzoct.model;\r\n\r\n/**\r\n *\r\n * @author M I C I F U S\r\n */\r\npublic class Comida {\r\n //vic\r\n priva", "end": 253, "score": 0.9992061257362366, "start": 240, "tag": "NAME", "value": "M I C I F U S" } ]
null
[]
/* * 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.monzoct.model; /** * * @author <NAME> */ public class Comida { //vic private Integer codigoComida; private String nombreComida; private String serving; private double servingSize; private double calorias; private double carbohidratos; private double grasas; private double proteinas; private double sodio; private double azucar; private CalorieTracker codigoTracker; //Constructores public Comida() { codigoComida = 0; nombreComida = ""; serving = ""; servingSize = 0; calorias = 0; carbohidratos = 0; grasas = 0; proteinas = 0; sodio = 0; azucar = 0; codigoTracker = new CalorieTracker(); } public Comida(Integer codigoComida, String nombreComida, String serving, double servingSize, int calorias, double carbohidratos, double grasas, double proteinas, double sodio, double azucar, CalorieTracker idCalorieTracker) { this.codigoComida = codigoComida; this.nombreComida = nombreComida; this.servingSize = servingSize; this.calorias = calorias; this.carbohidratos = carbohidratos; this.grasas = grasas; this.proteinas = proteinas; this.sodio = sodio; this.azucar = azucar; this.codigoTracker = idCalorieTracker; } //Getters public Integer getCodigoComida() { return codigoComida; } public String getNombreComida() { return nombreComida; } public String getServing() { return serving; } public double getServingSize() { return servingSize; } public double getCalorias() { return calorias; } public double getCarbohidratos() { return carbohidratos; } public double getGrasas() { return grasas; } public double getProteinas() { return proteinas; } public double getSodio() { return sodio; } public double getAzucar() { return azucar; } public CalorieTracker getCodigoTracker() { return codigoTracker; } //Setters public void setCodigoComida(Integer codigoComida) { this.codigoComida = codigoComida; } public void setNombreComida(String nombreComida) { this.nombreComida = nombreComida; } public void setServing(String serving) { this.serving = serving; } public void setServingSize(double servingSize) { this.servingSize = servingSize; } public void setCalorias(double calorias) { this.calorias = calorias; } public void setCarbohidratos(double carbohidratos) { this.carbohidratos = carbohidratos; } public void setGrasas(double grasas) { this.grasas = grasas; } public void setProteinas(double proteinas) { this.proteinas = proteinas; } public void setSodio(double sodio) { this.sodio = sodio; } public void setAzucar(double azucar) { this.azucar = azucar; } public void setCodigoTracker(CalorieTracker codigoTracker) { this.codigoTracker = codigoTracker; } }
3,563
0.601681
0.59944
146
22.452055
19.369898
111
false
false
0
0
0
0
0
0
0.465753
false
false
11
63d4027f598952139385e066e6e83173a103e29e
11,570,641,911,561
a401970f3a4842494c17eb5dd4dd9340e5411759
/app/src/main/java/com/oneflaretech/kiakia/fragment/ServiceAddressFragment.java
57d42527711b6ebf5bf0d10f54e66cc171751bfd
[]
no_license
BlackHades/ServiZone
https://github.com/BlackHades/ServiZone
1f4f14e9da6df93320ad11e56f940ee812ec7285
9899fc86d7a042458e4ddd14f1fdb10d62f4670a
refs/heads/master
2018-11-08T10:50:06.914000
2018-10-25T18:41:15
2018-10-25T18:41:15
143,432,255
1
1
null
false
2018-09-04T08:36:44
2018-08-03T13:41:44
2018-08-20T17:12:06
2018-09-04T08:36:44
37,983
1
1
0
Java
false
null
package com.oneflaretech.kiakia.fragment; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v7.widget.AppCompatButton; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import com.example.circulardialog.extras.CDConstants; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.oneflaretech.kiakia.R; import com.oneflaretech.kiakia.activities.ServiceRegistrationActivity; import com.oneflaretech.kiakia.activities.ViewServicesActivity; import com.oneflaretech.kiakia.googleAddress.MapAddressModel; import com.oneflaretech.kiakia.https.NetworkHelper; import com.oneflaretech.kiakia.https.RetrofitClient; import com.oneflaretech.kiakia.models.ResponseObjectModel; import com.oneflaretech.kiakia.models.ServiceModel; import com.oneflaretech.kiakia.utils.AppConstants; import com.oneflaretech.kiakia.utils.AppSettings; import com.oneflaretech.kiakia.utils.CustomLoadingDialog; import com.oneflaretech.kiakia.utils.Notification; import com.shashank.sony.fancygifdialoglib.FancyGifDialog; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.ArrayList; import retrofit2.adapter.rxjava.HttpException; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class ServiceAddressFragment extends Fragment implements OnMapReadyCallback { private GoogleMap mMap; EditText mAddress; private RetrofitClient retrofit; private Notification notification; private NetworkHelper net; SharedPreferences.Editor editor; AppCompatButton searchBtn; AppSettings app; final String TAG = ServiceAddressFragment.class.getSimpleName(); Double lat, lng; String formatedAddress; ServiceRegistrationActivity rsa; FloatingActionButton next, prev; public ServiceAddressFragment() { } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.serviceaddress_fragment, container, false); SupportMapFragment mapFragment = (SupportMapFragment)getChildFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); app = new AppSettings(getContext()); notification = new Notification(getContext()); net = new NetworkHelper(getContext()); mAddress = view.findViewById(R.id.address_edit); searchBtn = view.findViewById(R.id.search_map_btn); next = view.findViewById(R.id.next); prev = view.findViewById(R.id.prev); rsa = (ServiceRegistrationActivity) getActivity(); // serviceModel = app.getTempService(); searchBtn.setOnClickListener(v -> { if(mAddress.getText().toString().isEmpty()){ Snackbar.make(v, "Address Field is empty", Snackbar.LENGTH_SHORT).show(); return; } getLatLng(); }); mAddress.setOnEditorActionListener((textView, actionId, keyEvent) -> { if(actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || keyEvent.getAction() == KeyEvent.ACTION_DOWN || keyEvent.getAction() == KeyEvent.KEYCODE_ENTER){ } return false; }); prev.setOnClickListener(v -> rsa.moveBackward()); next.setOnClickListener(v -> goToNext()); return view; } public void goToNext() { rsa.serviceModel.setAddress(mAddress.getText().toString()); // rsa.serviceModel.setAddress("19, olorunkemi street, bariga, lagos"); // rsa.serviceModel.setLongitude(rsa.app.getLongitude()); // rsa.serviceModel.setLatitude(rsa.app.getLatitude()); if (rsa.serviceModel.getAddress() == null || rsa.serviceModel.getAddress().isEmpty()) { rsa.showAlert("Service Address not confirmed", CDConstants.ERROR); }else { app.setTempServices(rsa.serviceModel); registerService(); } } public void registerService(){ NetworkHelper net = new NetworkHelper(getContext()); RetrofitClient retrofit; if (net.haveNetworkConnection()) { rsa.loader.show(); retrofit = new RetrofitClient(getContext(), AppConstants.getHost()); retrofit.getApiService().registerService(rsa.user.getToken(), rsa.serviceModel.getName(),rsa.serviceModel.getEmail(), rsa.serviceModel.getAddress(), rsa.serviceModel.getMobile(), String.valueOf(rsa.serviceModel.getProfessionId()), rsa.serviceModel.getAbout(), rsa.serviceModel.getLatitude(), rsa.serviceModel.getLongitude()) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<ResponseObjectModel>() { @Override public void onCompleted() { rsa.loader.dismiss(); } @Override public void onError(Throwable e) { String msg = rsa.checkError(e); notification.setMessage(msg); notification.setAnchor(mAddress); notification.show(); AppConstants.log(TAG, e.toString()); rsa.loader.dismiss(); } @Override public void onNext(ResponseObjectModel responseModel) { if(responseModel.getStatus().equals(AppConstants.STATUS_SUCCESS)) { ArrayList<ServiceModel> services = rsa.app.getMyServices(); AppConstants.log(TAG, "PRe-Reg/" + rsa.serviceModel); rsa.serviceModel = rsa.gson.fromJson(responseModel.getData(), ServiceModel.class); services.add(rsa.serviceModel); rsa.app.setMyServices(services); Log.e(TAG, app.getMyServices().toString()); finishedDialog(); }else{ notification.setMessage(responseModel.getData()); notification.show(); rsa.showAlert(responseModel.getData(), CDConstants.ERROR); rsa.loader.dismiss(); } } }); } else { notification.setMessage("No Internet Connection"); notification.show(); rsa.loader.dismiss(); } } @Override public void onMapReady(GoogleMap googleMap) { formatedAddress = app.getTempAddress(); mMap = googleMap; lat = app.getLatitude(); lng = app.getLongitude(); setMarker(lat,lng, formatedAddress); } public void setMarker(double lat, double lng, String address){ mMap.clear(); formatedAddress = app.getTempAddress(); LatLng latLng = new LatLng(lat, lng); Marker addressMarker = mMap.addMarker(new MarkerOptions() .position(latLng) .anchor(0.5f, 0.5f) .title(rsa.serviceModel.getName() == null ? "Current Location" : rsa.serviceModel.getName()) .snippet(address) .icon(BitmapDescriptorFactory.fromResource(R.drawable.place_marker))); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18 )); addressMarker.showInfoWindow(); } void getLatLng(){ CustomLoadingDialog loader = new CustomLoadingDialog(getContext()); loader.show(); AppConstants.log(TAG, getResources().getString(R.string.API_KEY)); if (net.haveNetworkConnection()) { String address = mAddress.getText().toString(); String API_KEY = getResources().getString(R.string.API_KEY); String country = "country:NG"; // String full_url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + URLEncoder.encode(address, "UTF-8") + "&key=" + URLEncoder.encode(API_KEY, "UTF-8"); // AppConstants.log(TAG, full_url); retrofit = new RetrofitClient(getContext(), "https://maps.googleapis.com/maps/api/geocode/"); retrofit.getApiService().getLotLng(address,country) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<MapAddressModel>() { @Override public void onCompleted() { loader.dismiss(); } @Override public void onError(Throwable e) { String msg = "An Error Occurred. Please Try Again"; if (e instanceof HttpException) msg = "A Server Error occurred. Please Try Again"; if (e instanceof SocketException || e instanceof SocketTimeoutException) msg = "No Internet Connection"; if(e instanceof IllegalStateException) msg = "Invalid Data"; rsa.showAlert(msg, CDConstants.ERROR); AppConstants.log(TAG, e.toString()); loader.dismiss(); } @Override public void onNext(MapAddressModel responseModel) { AppConstants.log(TAG, responseModel.toString()); if(responseModel.getStatus().equals("OK")) { Double lat = responseModel.getResults().get(0).getGeometry().getLocation().getLat(); Double lng = responseModel.getResults().get(0).getGeometry().getLocation().getLng(); String formated_address = responseModel.getResults().get(0).getFormattedAddress(); rsa.serviceModel.setLatitude(lat); rsa.serviceModel.setLongitude(lng); rsa.serviceModel.setAddress(formated_address); app.setTempServices(rsa.serviceModel); setMarker(lat,lng, formated_address); Log.e(TAG,"Lat = " + lat + "/ lng = " + lng ); rsa.showAlert("Valid Address", CDConstants.SUCCESS); }else if(responseModel.getStatus().equals("OVER_QUERY_LIMIT") || responseModel.getStatus().equals("REQUEST_DENIED")){ rsa.showAlert("Please try again later", CDConstants.ERROR); }else{ rsa.showAlert("Invalid Address", CDConstants.ERROR); } loader.dismiss(); } }); } else { loader.dismiss(); rsa.showAlert("No Internet Connection", CDConstants.ERROR); } } void finishedDialog(){ new FancyGifDialog.Builder(getActivity()) .setTitle("Success") .setMessage("Your service has been registered successfully. Do you want to proceed to Service Profile? ") .setNegativeBtnText("No") .setPositiveBtnBackground("#FF4081") .setPositiveBtnText("Proceed") .setNegativeBtnBackground("#FFA9A7A8") .setGifResource(R.drawable.dialog_check) .isCancellable(true) .OnPositiveClicked(() -> { startActivity(new Intent(getContext(), ViewServicesActivity.class).putExtra("service", rsa.gson.toJson(rsa.serviceModel, ServiceModel.class))); rsa.finish(); }) .OnNegativeClicked(() -> rsa.finish()) .build(); } }
UTF-8
Java
13,348
java
ServiceAddressFragment.java
Java
[ { "context": "flaretech.kiakia.utils.Notification;\nimport com.shashank.sony.fancygifdialoglib.FancyGifDialog;\n\nimport ja", "end": 1812, "score": 0.8503388166427612, "start": 1806, "tag": "USERNAME", "value": "ashank" }, { "context": "kiakia.utils.Notification;\nimport com.shashank.sony.fancygifdialoglib.FancyGifDialog;\n\nimport java.ne", "end": 1817, "score": 0.6704665422439575, "start": 1816, "tag": "USERNAME", "value": "y" } ]
null
[]
package com.oneflaretech.kiakia.fragment; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v7.widget.AppCompatButton; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import com.example.circulardialog.extras.CDConstants; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.oneflaretech.kiakia.R; import com.oneflaretech.kiakia.activities.ServiceRegistrationActivity; import com.oneflaretech.kiakia.activities.ViewServicesActivity; import com.oneflaretech.kiakia.googleAddress.MapAddressModel; import com.oneflaretech.kiakia.https.NetworkHelper; import com.oneflaretech.kiakia.https.RetrofitClient; import com.oneflaretech.kiakia.models.ResponseObjectModel; import com.oneflaretech.kiakia.models.ServiceModel; import com.oneflaretech.kiakia.utils.AppConstants; import com.oneflaretech.kiakia.utils.AppSettings; import com.oneflaretech.kiakia.utils.CustomLoadingDialog; import com.oneflaretech.kiakia.utils.Notification; import com.shashank.sony.fancygifdialoglib.FancyGifDialog; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.ArrayList; import retrofit2.adapter.rxjava.HttpException; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class ServiceAddressFragment extends Fragment implements OnMapReadyCallback { private GoogleMap mMap; EditText mAddress; private RetrofitClient retrofit; private Notification notification; private NetworkHelper net; SharedPreferences.Editor editor; AppCompatButton searchBtn; AppSettings app; final String TAG = ServiceAddressFragment.class.getSimpleName(); Double lat, lng; String formatedAddress; ServiceRegistrationActivity rsa; FloatingActionButton next, prev; public ServiceAddressFragment() { } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.serviceaddress_fragment, container, false); SupportMapFragment mapFragment = (SupportMapFragment)getChildFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); app = new AppSettings(getContext()); notification = new Notification(getContext()); net = new NetworkHelper(getContext()); mAddress = view.findViewById(R.id.address_edit); searchBtn = view.findViewById(R.id.search_map_btn); next = view.findViewById(R.id.next); prev = view.findViewById(R.id.prev); rsa = (ServiceRegistrationActivity) getActivity(); // serviceModel = app.getTempService(); searchBtn.setOnClickListener(v -> { if(mAddress.getText().toString().isEmpty()){ Snackbar.make(v, "Address Field is empty", Snackbar.LENGTH_SHORT).show(); return; } getLatLng(); }); mAddress.setOnEditorActionListener((textView, actionId, keyEvent) -> { if(actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || keyEvent.getAction() == KeyEvent.ACTION_DOWN || keyEvent.getAction() == KeyEvent.KEYCODE_ENTER){ } return false; }); prev.setOnClickListener(v -> rsa.moveBackward()); next.setOnClickListener(v -> goToNext()); return view; } public void goToNext() { rsa.serviceModel.setAddress(mAddress.getText().toString()); // rsa.serviceModel.setAddress("19, olorunkemi street, bariga, lagos"); // rsa.serviceModel.setLongitude(rsa.app.getLongitude()); // rsa.serviceModel.setLatitude(rsa.app.getLatitude()); if (rsa.serviceModel.getAddress() == null || rsa.serviceModel.getAddress().isEmpty()) { rsa.showAlert("Service Address not confirmed", CDConstants.ERROR); }else { app.setTempServices(rsa.serviceModel); registerService(); } } public void registerService(){ NetworkHelper net = new NetworkHelper(getContext()); RetrofitClient retrofit; if (net.haveNetworkConnection()) { rsa.loader.show(); retrofit = new RetrofitClient(getContext(), AppConstants.getHost()); retrofit.getApiService().registerService(rsa.user.getToken(), rsa.serviceModel.getName(),rsa.serviceModel.getEmail(), rsa.serviceModel.getAddress(), rsa.serviceModel.getMobile(), String.valueOf(rsa.serviceModel.getProfessionId()), rsa.serviceModel.getAbout(), rsa.serviceModel.getLatitude(), rsa.serviceModel.getLongitude()) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<ResponseObjectModel>() { @Override public void onCompleted() { rsa.loader.dismiss(); } @Override public void onError(Throwable e) { String msg = rsa.checkError(e); notification.setMessage(msg); notification.setAnchor(mAddress); notification.show(); AppConstants.log(TAG, e.toString()); rsa.loader.dismiss(); } @Override public void onNext(ResponseObjectModel responseModel) { if(responseModel.getStatus().equals(AppConstants.STATUS_SUCCESS)) { ArrayList<ServiceModel> services = rsa.app.getMyServices(); AppConstants.log(TAG, "PRe-Reg/" + rsa.serviceModel); rsa.serviceModel = rsa.gson.fromJson(responseModel.getData(), ServiceModel.class); services.add(rsa.serviceModel); rsa.app.setMyServices(services); Log.e(TAG, app.getMyServices().toString()); finishedDialog(); }else{ notification.setMessage(responseModel.getData()); notification.show(); rsa.showAlert(responseModel.getData(), CDConstants.ERROR); rsa.loader.dismiss(); } } }); } else { notification.setMessage("No Internet Connection"); notification.show(); rsa.loader.dismiss(); } } @Override public void onMapReady(GoogleMap googleMap) { formatedAddress = app.getTempAddress(); mMap = googleMap; lat = app.getLatitude(); lng = app.getLongitude(); setMarker(lat,lng, formatedAddress); } public void setMarker(double lat, double lng, String address){ mMap.clear(); formatedAddress = app.getTempAddress(); LatLng latLng = new LatLng(lat, lng); Marker addressMarker = mMap.addMarker(new MarkerOptions() .position(latLng) .anchor(0.5f, 0.5f) .title(rsa.serviceModel.getName() == null ? "Current Location" : rsa.serviceModel.getName()) .snippet(address) .icon(BitmapDescriptorFactory.fromResource(R.drawable.place_marker))); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18 )); addressMarker.showInfoWindow(); } void getLatLng(){ CustomLoadingDialog loader = new CustomLoadingDialog(getContext()); loader.show(); AppConstants.log(TAG, getResources().getString(R.string.API_KEY)); if (net.haveNetworkConnection()) { String address = mAddress.getText().toString(); String API_KEY = getResources().getString(R.string.API_KEY); String country = "country:NG"; // String full_url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + URLEncoder.encode(address, "UTF-8") + "&key=" + URLEncoder.encode(API_KEY, "UTF-8"); // AppConstants.log(TAG, full_url); retrofit = new RetrofitClient(getContext(), "https://maps.googleapis.com/maps/api/geocode/"); retrofit.getApiService().getLotLng(address,country) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<MapAddressModel>() { @Override public void onCompleted() { loader.dismiss(); } @Override public void onError(Throwable e) { String msg = "An Error Occurred. Please Try Again"; if (e instanceof HttpException) msg = "A Server Error occurred. Please Try Again"; if (e instanceof SocketException || e instanceof SocketTimeoutException) msg = "No Internet Connection"; if(e instanceof IllegalStateException) msg = "Invalid Data"; rsa.showAlert(msg, CDConstants.ERROR); AppConstants.log(TAG, e.toString()); loader.dismiss(); } @Override public void onNext(MapAddressModel responseModel) { AppConstants.log(TAG, responseModel.toString()); if(responseModel.getStatus().equals("OK")) { Double lat = responseModel.getResults().get(0).getGeometry().getLocation().getLat(); Double lng = responseModel.getResults().get(0).getGeometry().getLocation().getLng(); String formated_address = responseModel.getResults().get(0).getFormattedAddress(); rsa.serviceModel.setLatitude(lat); rsa.serviceModel.setLongitude(lng); rsa.serviceModel.setAddress(formated_address); app.setTempServices(rsa.serviceModel); setMarker(lat,lng, formated_address); Log.e(TAG,"Lat = " + lat + "/ lng = " + lng ); rsa.showAlert("Valid Address", CDConstants.SUCCESS); }else if(responseModel.getStatus().equals("OVER_QUERY_LIMIT") || responseModel.getStatus().equals("REQUEST_DENIED")){ rsa.showAlert("Please try again later", CDConstants.ERROR); }else{ rsa.showAlert("Invalid Address", CDConstants.ERROR); } loader.dismiss(); } }); } else { loader.dismiss(); rsa.showAlert("No Internet Connection", CDConstants.ERROR); } } void finishedDialog(){ new FancyGifDialog.Builder(getActivity()) .setTitle("Success") .setMessage("Your service has been registered successfully. Do you want to proceed to Service Profile? ") .setNegativeBtnText("No") .setPositiveBtnBackground("#FF4081") .setPositiveBtnText("Proceed") .setNegativeBtnBackground("#FFA9A7A8") .setGifResource(R.drawable.dialog_check) .isCancellable(true) .OnPositiveClicked(() -> { startActivity(new Intent(getContext(), ViewServicesActivity.class).putExtra("service", rsa.gson.toJson(rsa.serviceModel, ServiceModel.class))); rsa.finish(); }) .OnNegativeClicked(() -> rsa.finish()) .build(); } }
13,348
0.593048
0.591325
288
45.347221
34.988949
336
false
false
0
0
0
0
0
0
0.791667
false
false
11
a7b67379e3641bbf2346ab46228ae55f748bc50e
28,673,201,726,428
9d611c1460ca338b36c1cd4031f8d1445b36e6e4
/src/main/java/com/banking/serviceImpl/ServiceTransactionImpl.java
4621125746a2a3f42acc099fabb9c1864e2a5299
[]
no_license
bhaskaruradi/BankOracle
https://github.com/bhaskaruradi/BankOracle
1e42f6d223f5ced5eebd309b4746ea5560da627c
5d1068d994bf4a0a3f783280273456e7e0e987a5
refs/heads/master
2020-04-28T22:30:54.890000
2019-03-15T10:58:53
2019-03-15T10:58:53
175,620,397
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.banking.serviceImpl; import com.banking.dao.Transaction; import com.banking.daoImpl.TransationImpl; import com.banking.service.Service; import com.banking.service.ServiceTransaction; import com.banking.ui.Customer; import com.banking.ui.TransationPojo; public class ServiceTransactionImpl implements ServiceTransaction { Transaction t = new TransationImpl(); Customer cd = new Customer(); public Customer deposit(Customer customer) { // TODO Auto-generated method stub return t.deposit(customer); } public Customer withDraw(Customer customer) { // TODO Auto-generated method stub return t.withDraw(customer); } public Customer showBalance(Customer customer) { // TODO Auto-generated method stub return t.showBalance(customer); } public int fundTransfer(long fromAccountNo,long toAccountNo,long balance,long amount) { // TODO Auto-generated method stub return t.fundTransfer(fromAccountNo,toAccountNo,balance,amount); } }
UTF-8
Java
974
java
ServiceTransactionImpl.java
Java
[]
null
[]
package com.banking.serviceImpl; import com.banking.dao.Transaction; import com.banking.daoImpl.TransationImpl; import com.banking.service.Service; import com.banking.service.ServiceTransaction; import com.banking.ui.Customer; import com.banking.ui.TransationPojo; public class ServiceTransactionImpl implements ServiceTransaction { Transaction t = new TransationImpl(); Customer cd = new Customer(); public Customer deposit(Customer customer) { // TODO Auto-generated method stub return t.deposit(customer); } public Customer withDraw(Customer customer) { // TODO Auto-generated method stub return t.withDraw(customer); } public Customer showBalance(Customer customer) { // TODO Auto-generated method stub return t.showBalance(customer); } public int fundTransfer(long fromAccountNo,long toAccountNo,long balance,long amount) { // TODO Auto-generated method stub return t.fundTransfer(fromAccountNo,toAccountNo,balance,amount); } }
974
0.780287
0.780287
40
23.35
23.161983
88
false
false
0
0
0
0
0
0
1.125
false
false
11
6512871506e58cf0301b6144ffb3a8595af3fb53
28,673,201,725,172
82a820fc263415afa6681fe2a69f398e0369e8d3
/src/org/samples/SimpleWiring.java
56269fd605c3bc226a22c929b62db94681236d5d
[ "Apache-2.0" ]
permissive
haint/jgentle
https://github.com/haint/jgentle
8b8e05909f91c6187149e9f7b5ea176eed6cbea2
898ba402808763637b358f7a3be334de17a5a926
refs/heads/master
2020-06-01T10:51:18.765000
2011-06-09T08:40:43
2011-06-09T08:40:43
1,869,753
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2007-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Project: JGentleFramework */ package org.samples; import java.lang.reflect.Field; import java.util.Map; import org.jgentleframework.configure.Configurable; import org.jgentleframework.configure.annotation.Inject; import org.jgentleframework.configure.enums.Scope; import org.jgentleframework.context.JGentle; import org.jgentleframework.context.beans.Filter; import org.jgentleframework.context.injecting.Provider; public class SimpleWiring { public static void main(String[] args) { Provider provider = JGentle.buildProvider(ConfigModule.class); KnightElf knight = (KnightElf) provider.getBean(KnightElf.class); KnightElf knightBind = (KnightElf) provider .getBeanBoundToDefinition("bean1"); knight.showInfo(); knightBind.showInfo(); System.out.println(knight.type); // Definition def = // provider.getDefinitionManager().getDefinition("bean1"); // System.out.println(def.getMemberDefinitionOfField("type")[0] // .getAnnotation(Inject.class).value()); } } abstract class ConfigModule implements Configurable { @Override public void configure() { attach(KnightType.class).to(SwordSinger.class).scope(Scope.SINGLETON); bind( new Object[][] { { "type", refMapping(TempleKnight.class) }, { "level", 55 }, }).in(KnightElf.class).id("bean1"); attachConstant("level").to(45); } } class KnightElf implements Filter { @Inject(invocation = true) public KnightType type; @Inject("level") int level = 0; public KnightType getType() { return type; } public int getLevel() { return level; } public void showInfo() { System.out.println("Class type: " + this.getType().getName()); System.out.println("Level: " + this.getLevel() + " <---"); System.out.println("Defence: " + this.getType().getDef()); System.out.println("Strength: " + this.getType().getStr()); System.out.println(); } /* * (non-Javadoc) * @see * org.jgentleframework.context.beans.FactoryFilter#filters(java.util.Map) */ @Override public void filters(Map<Field, Object> map) { // for (Field field : map.keySet()) { // if (field.getName().equals("level") // && ((Integer) map.get(field)).intValue() == 0) { // this.level = 60; // } // } } } interface KnightType { public String getName(); public int getDef(); public int getStr(); } class TempleKnight implements KnightType { String name = "TempleKnight"; int def = 1000; int str = 400; public String getName() { return name; } public int getDef() { return def; } public int getStr() { return str; } } class SwordSinger implements KnightType { String name = "SwordSinger"; int def = 800; int str = 400; public String getName() { return name; } public int getDef() { return def; } public int getStr() { return str; } }
UTF-8
Java
3,573
java
SimpleWiring.java
Java
[ { "context": "rdSinger implements KnightType {\r\n\tString\tname\t= \"SwordSinger\";\r\n\r\n\tint\t\tdef\t\t= 800;\r\n\r\n\tint\t\tstr\t\t= 400;\r\n\r\n\tp", "end": 3378, "score": 0.6358910799026489, "start": 3367, "tag": "NAME", "value": "SwordSinger" } ]
null
[]
/* * Copyright 2007-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Project: JGentleFramework */ package org.samples; import java.lang.reflect.Field; import java.util.Map; import org.jgentleframework.configure.Configurable; import org.jgentleframework.configure.annotation.Inject; import org.jgentleframework.configure.enums.Scope; import org.jgentleframework.context.JGentle; import org.jgentleframework.context.beans.Filter; import org.jgentleframework.context.injecting.Provider; public class SimpleWiring { public static void main(String[] args) { Provider provider = JGentle.buildProvider(ConfigModule.class); KnightElf knight = (KnightElf) provider.getBean(KnightElf.class); KnightElf knightBind = (KnightElf) provider .getBeanBoundToDefinition("bean1"); knight.showInfo(); knightBind.showInfo(); System.out.println(knight.type); // Definition def = // provider.getDefinitionManager().getDefinition("bean1"); // System.out.println(def.getMemberDefinitionOfField("type")[0] // .getAnnotation(Inject.class).value()); } } abstract class ConfigModule implements Configurable { @Override public void configure() { attach(KnightType.class).to(SwordSinger.class).scope(Scope.SINGLETON); bind( new Object[][] { { "type", refMapping(TempleKnight.class) }, { "level", 55 }, }).in(KnightElf.class).id("bean1"); attachConstant("level").to(45); } } class KnightElf implements Filter { @Inject(invocation = true) public KnightType type; @Inject("level") int level = 0; public KnightType getType() { return type; } public int getLevel() { return level; } public void showInfo() { System.out.println("Class type: " + this.getType().getName()); System.out.println("Level: " + this.getLevel() + " <---"); System.out.println("Defence: " + this.getType().getDef()); System.out.println("Strength: " + this.getType().getStr()); System.out.println(); } /* * (non-Javadoc) * @see * org.jgentleframework.context.beans.FactoryFilter#filters(java.util.Map) */ @Override public void filters(Map<Field, Object> map) { // for (Field field : map.keySet()) { // if (field.getName().equals("level") // && ((Integer) map.get(field)).intValue() == 0) { // this.level = 60; // } // } } } interface KnightType { public String getName(); public int getDef(); public int getStr(); } class TempleKnight implements KnightType { String name = "TempleKnight"; int def = 1000; int str = 400; public String getName() { return name; } public int getDef() { return def; } public int getStr() { return str; } } class SwordSinger implements KnightType { String name = "SwordSinger"; int def = 800; int str = 400; public String getName() { return name; } public int getDef() { return def; } public int getStr() { return str; } }
3,573
0.666387
0.656031
154
21.201298
22.683702
75
false
false
0
0
0
0
0
0
1.37013
false
false
11
0ac0b762ce96174e2089ec4cf2f694f1c202a16b
20,916,490,738,120
f5611a90eab852de5b6e639e11334715a820b594
/Java学习过程中写的文件/第十章/awt/eventadapterTest.java
f96f918aa7c4f2c38c4564fd86c3515e2edf699b
[]
no_license
shougeY/Java-
https://github.com/shougeY/Java-
346760dc36adb4d7c2cb0e4f6e99cc4d5464ef52
00e422c82ab124ce41a5936a24316cdec1e32f5f
refs/heads/master
2022-12-06T08:03:07.351000
2020-08-20T16:16:48
2020-08-20T16:16:48
288,687,132
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package 第十章.awt; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class eventadapterTest { private Frame frame; public eventadapterTest() { frame=new Frame(); } public void showMe() { frame.addWindowListener(new WindowCloseHandler()); frame.setBounds(100, 100,200, 200); frame.setVisible(true); } private class WindowCloseHandler extends WindowAdapter{ @Override public void windowClosing(WindowEvent e) { System.exit(0); } } public static void main(String []args) { new eventadapterTest().showMe(); } }
UTF-8
Java
598
java
eventadapterTest.java
Java
[]
null
[]
package 第十章.awt; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class eventadapterTest { private Frame frame; public eventadapterTest() { frame=new Frame(); } public void showMe() { frame.addWindowListener(new WindowCloseHandler()); frame.setBounds(100, 100,200, 200); frame.setVisible(true); } private class WindowCloseHandler extends WindowAdapter{ @Override public void windowClosing(WindowEvent e) { System.exit(0); } } public static void main(String []args) { new eventadapterTest().showMe(); } }
598
0.731419
0.709459
30
18.733334
17.040997
56
false
false
0
0
0
0
0
0
1.433333
false
false
11
7dacd81670c168230d18108ae5c1a61ab8248f99
20,916,490,740,270
9bb4c2515b2029fa3441669d967ace6e21a1a2ea
/app/src/main/java/taipei/zoo/adapter/ZooAdapter.java
ed8400900ca35f0e7f67fd568537bc65b02b1136
[]
no_license
cynthia-pan/TaipeiZoo
https://github.com/cynthia-pan/TaipeiZoo
559459c37d2f09e2c5866c24c421d12c2425709f
917dfcf017b9455d1911a73a47d85f73deb0fce8
refs/heads/master
2020-06-16T19:18:19.952000
2019-07-07T17:19:29
2019-07-07T17:19:29
195,676,523
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package taipei.zoo.adapter; import android.content.Context; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import java.util.List; import taipei.zoo.R; import taipei.zoo.data.ZooData; import taipei.zoo.fragment.ZooDetailFragment; public class ZooAdapter extends RecyclerView.Adapter<ZooAdapter.ViewHolder> { private Context mContext; private List<ZooData> mData; public ZooAdapter(Context context, List<ZooData> data) { this.mContext = context; this.mData = data; } public void updateList(List<ZooData> data) { this.mData = data; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.cell_zoo, parent, false); ViewHolder holder = new ViewHolder(view); holder.layoutTitle = view.findViewById(R.id.layoutTitle); holder.ivZooThumbnail = view.findViewById(R.id.ivZooThumbnail); holder.tvZooName = view.findViewById(R.id.tvZooName); holder.tvZooInfo = view.findViewById(R.id.tvZooInfo); holder.tvZooMemo = view.findViewById(R.id.tvZooMemo); return holder; } @Override public void onBindViewHolder(ViewHolder holder, final int position) { ZooData zoo = mData.get(position); holder.layoutTitle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AppCompatActivity activity = (AppCompatActivity) mContext; ZooDetailFragment fragment = new ZooDetailFragment(); Bundle bundle = new Bundle(); bundle.putInt("index", position); fragment.setArguments(bundle); FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction(); ft.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right); ft.replace(R.id.content_fragment, fragment); ft.addToBackStack(null); ft.commit(); } }); holder.tvZooName.setText(zoo.zooName); holder.tvZooInfo.setText(zoo.zooInfo); if (zoo.zooMemo.equals("")) { holder.tvZooMemo.setText(R.string.default_memo); } else { holder.tvZooMemo.setText(zoo.zooMemo); } Glide.with(mContext) .load(zoo.zooPicUrl) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(holder.ivZooThumbnail); } @Override public int getItemCount() { return mData.size(); } class ViewHolder extends RecyclerView.ViewHolder { public LinearLayout layoutTitle; public ImageView ivZooThumbnail; public TextView tvZooName; public TextView tvZooInfo; public TextView tvZooMemo; public ViewHolder(View itemView) { super(itemView); } } }
UTF-8
Java
3,521
java
ZooAdapter.java
Java
[]
null
[]
package taipei.zoo.adapter; import android.content.Context; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import java.util.List; import taipei.zoo.R; import taipei.zoo.data.ZooData; import taipei.zoo.fragment.ZooDetailFragment; public class ZooAdapter extends RecyclerView.Adapter<ZooAdapter.ViewHolder> { private Context mContext; private List<ZooData> mData; public ZooAdapter(Context context, List<ZooData> data) { this.mContext = context; this.mData = data; } public void updateList(List<ZooData> data) { this.mData = data; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.cell_zoo, parent, false); ViewHolder holder = new ViewHolder(view); holder.layoutTitle = view.findViewById(R.id.layoutTitle); holder.ivZooThumbnail = view.findViewById(R.id.ivZooThumbnail); holder.tvZooName = view.findViewById(R.id.tvZooName); holder.tvZooInfo = view.findViewById(R.id.tvZooInfo); holder.tvZooMemo = view.findViewById(R.id.tvZooMemo); return holder; } @Override public void onBindViewHolder(ViewHolder holder, final int position) { ZooData zoo = mData.get(position); holder.layoutTitle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AppCompatActivity activity = (AppCompatActivity) mContext; ZooDetailFragment fragment = new ZooDetailFragment(); Bundle bundle = new Bundle(); bundle.putInt("index", position); fragment.setArguments(bundle); FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction(); ft.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right); ft.replace(R.id.content_fragment, fragment); ft.addToBackStack(null); ft.commit(); } }); holder.tvZooName.setText(zoo.zooName); holder.tvZooInfo.setText(zoo.zooInfo); if (zoo.zooMemo.equals("")) { holder.tvZooMemo.setText(R.string.default_memo); } else { holder.tvZooMemo.setText(zoo.zooMemo); } Glide.with(mContext) .load(zoo.zooPicUrl) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(holder.ivZooThumbnail); } @Override public int getItemCount() { return mData.size(); } class ViewHolder extends RecyclerView.ViewHolder { public LinearLayout layoutTitle; public ImageView ivZooThumbnail; public TextView tvZooName; public TextView tvZooInfo; public TextView tvZooMemo; public ViewHolder(View itemView) { super(itemView); } } }
3,521
0.642147
0.641295
101
32.881187
24.520466
97
false
false
0
0
0
0
0
0
0.643564
false
false
11
449736681fbd41cf59ee04f1dca185b938937945
7,112,465,861,910
27511a2f9b0abe76e3fcef6d70e66647dd15da96
/src/com/instagram/common/a/b/e.java
167b534801b28bbc34cee99a6e78729da72cf3a2
[]
no_license
biaolv/com.instagram.android
https://github.com/biaolv/com.instagram.android
7edde43d5a909ae2563cf104acfc6891f2a39ebe
3fcd3db2c3823a6d29a31ec0f6abcf5ceca995de
refs/heads/master
2022-05-09T15:05:05.412000
2016-07-21T03:48:36
2016-07-21T03:48:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.instagram.common.a.b; import com.instagram.common.a.a.f; enum e { e() { super(paramString, 1, (byte)0); } final com.instagram.common.a.a.g<Object> a() { return f.a; } final <K, V> q<K, V> a(ai<K, V> paramai, s<K, V> params, V paramV) { return new ag(h, paramV, params); } } /* Location: * Qualified Name: com.instagram.common.a.b.e * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
UTF-8
Java
453
java
e.java
Java
[]
null
[]
package com.instagram.common.a.b; import com.instagram.common.a.a.f; enum e { e() { super(paramString, 1, (byte)0); } final com.instagram.common.a.a.g<Object> a() { return f.a; } final <K, V> q<K, V> a(ai<K, V> paramai, s<K, V> params, V paramV) { return new ag(h, paramV, params); } } /* Location: * Qualified Name: com.instagram.common.a.b.e * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
453
0.580574
0.560706
27
15.814815
18.745937
68
false
false
0
0
0
0
0
0
0.555556
false
false
11
1addcb38f7a974aa734658e964b343eeca0c000d
4,320,737,154,249
e46aa3aee7d10533808c9fe68311207aaa7f46ac
/Java/Classwork/Week 5/cs3544_project5/WordLists.java
d4d52af309282fcd36fc1eb98d0f28c8c6daf758
[]
no_license
ConderShou/myhub
https://github.com/ConderShou/myhub
102eba36511c47703d2b00a4ad8d550668bf4757
8e1c8aadfd7ef65f54c4655d2450a00a6f2cb321
refs/heads/master
2023-04-02T20:28:26.560000
2017-09-03T17:35:24
2017-09-03T17:35:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Conder Shou * cs3544 * Intro to Java * * WordLists.java * * Generates useful word lists for scrabble players using the included * dictionary file */ import java.util.Scanner; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; public class WordLists { private Scanner in; private ArrayList<String> dictionary = new ArrayList<>(); //Transfers dictionary to an ArrayList public WordLists(String fileName) throws FileNotFoundException { in = new Scanner(new BufferedReader( new FileReader(fileName)));; while (in.hasNext()) { dictionary.add(in.next()); } } //Returns an array of words of length n public String[] lengthN(int n) { ArrayList<String> tempList = new ArrayList<>(); //Enhanced for loop to traverse through dictionary file for (String word : dictionary) { //Checking for the proper word length if (word.length() == n) tempList.add(word); } //Creating a new array to contain the tempList arraylist String[] array = new String[tempList.size()]; for (int i = 0; i < array.length; i++) array[i] = tempList.get(i); return array; } //Returns an array of words of length n // beginning with the letter firstletter public String[] startsWith(int n, char firstLetter) { ArrayList<String> tempList = new ArrayList<>(); for (String word : dictionary) { //Splitting word into its individual characters String[] wordArray = word.split(""); String letter = Character.toString(firstLetter); //Checking if the first letter is the desired letter if (wordArray[0].equals(letter) && word.length() == n) tempList.add(word); } String[] array = new String[tempList.size()]; for (int i = 0; i < array.length; i++) array[i] = tempList.get(i); return array; } //Returns an array of words of length n containing the letter included // but not beginning with it public String[] containsLetter(int n, char included) { ArrayList<String> tempList = new ArrayList<>(); boolean hasVowel = false; for (String word : dictionary) { String[] wordArray = word.split(""); String letter = Character.toString(included); //Going through the word in all positions except beginning // to find if it has the desired letter for (int i = 1; i < wordArray.length; i++) { String elem = wordArray[i]; if (elem.equals(letter)) hasVowel = true; } if (hasVowel && word.length() == n) tempList.add(word); //Reset hasVowel for the next word hasVowel = false; } String[] array = new String[tempList.size()]; for (int i = 0; i < array.length; i++) array[i] = tempList.get(i); return array; } //Returns an array of words of length n containing at least m vowels public String[] vowelHeavy(int n, int m) { ArrayList<String> tempList = new ArrayList<>(); int numOfVowels = 0; for (String word : dictionary) { String[] wordArray = word.split(""); for (int i = 0; i < wordArray.length; i++) { String elem = wordArray[i]; //Increments the counter for the number of vowels when // a vowel is found in the word if (elem.equals("a") || elem.equals("e") || elem.equals("i") || elem.equals("o") || elem.equals("u")) numOfVowels++; } if (numOfVowels >= m && word.length() == n) tempList.add(word); //Resets numOfVowels for the next word numOfVowels = 0; } String[] array = new String[tempList.size()]; for (int i = 0; i < array.length; i++) array[i] = tempList.get(i); return array; } //Returns an array of words with at least m occurrences // of the letter included public String[] multiLetter(int m, char included) { ArrayList<String> tempList = new ArrayList<>(); String letter = Character.toString(included); int numOfLetter = 0; for (String word : dictionary) { String[] wordArray = word.split(""); for (int i = 0; i < wordArray.length; i++) { String elem = wordArray[i]; //Increments the counter for the number of vowels when // a vowel is found in the word if (elem.equals(letter)) numOfLetter++; } if (numOfLetter >= m) tempList.add(word); //Resets numOfVowels for the next word numOfLetter = 0; } String[] array = new String[tempList.size()]; for (int i = 0; i < array.length; i++) array[i] = tempList.get(i); return array; } }
UTF-8
Java
4,711
java
WordLists.java
Java
[ { "context": "/*\r\n * Conder Shou\r\n * cs3544\r\n * Intro to Java\r\n * \r\n * WordLists.j", "end": 18, "score": 0.9998706579208374, "start": 7, "tag": "NAME", "value": "Conder Shou" } ]
null
[]
/* * <NAME> * cs3544 * Intro to Java * * WordLists.java * * Generates useful word lists for scrabble players using the included * dictionary file */ import java.util.Scanner; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; public class WordLists { private Scanner in; private ArrayList<String> dictionary = new ArrayList<>(); //Transfers dictionary to an ArrayList public WordLists(String fileName) throws FileNotFoundException { in = new Scanner(new BufferedReader( new FileReader(fileName)));; while (in.hasNext()) { dictionary.add(in.next()); } } //Returns an array of words of length n public String[] lengthN(int n) { ArrayList<String> tempList = new ArrayList<>(); //Enhanced for loop to traverse through dictionary file for (String word : dictionary) { //Checking for the proper word length if (word.length() == n) tempList.add(word); } //Creating a new array to contain the tempList arraylist String[] array = new String[tempList.size()]; for (int i = 0; i < array.length; i++) array[i] = tempList.get(i); return array; } //Returns an array of words of length n // beginning with the letter firstletter public String[] startsWith(int n, char firstLetter) { ArrayList<String> tempList = new ArrayList<>(); for (String word : dictionary) { //Splitting word into its individual characters String[] wordArray = word.split(""); String letter = Character.toString(firstLetter); //Checking if the first letter is the desired letter if (wordArray[0].equals(letter) && word.length() == n) tempList.add(word); } String[] array = new String[tempList.size()]; for (int i = 0; i < array.length; i++) array[i] = tempList.get(i); return array; } //Returns an array of words of length n containing the letter included // but not beginning with it public String[] containsLetter(int n, char included) { ArrayList<String> tempList = new ArrayList<>(); boolean hasVowel = false; for (String word : dictionary) { String[] wordArray = word.split(""); String letter = Character.toString(included); //Going through the word in all positions except beginning // to find if it has the desired letter for (int i = 1; i < wordArray.length; i++) { String elem = wordArray[i]; if (elem.equals(letter)) hasVowel = true; } if (hasVowel && word.length() == n) tempList.add(word); //Reset hasVowel for the next word hasVowel = false; } String[] array = new String[tempList.size()]; for (int i = 0; i < array.length; i++) array[i] = tempList.get(i); return array; } //Returns an array of words of length n containing at least m vowels public String[] vowelHeavy(int n, int m) { ArrayList<String> tempList = new ArrayList<>(); int numOfVowels = 0; for (String word : dictionary) { String[] wordArray = word.split(""); for (int i = 0; i < wordArray.length; i++) { String elem = wordArray[i]; //Increments the counter for the number of vowels when // a vowel is found in the word if (elem.equals("a") || elem.equals("e") || elem.equals("i") || elem.equals("o") || elem.equals("u")) numOfVowels++; } if (numOfVowels >= m && word.length() == n) tempList.add(word); //Resets numOfVowels for the next word numOfVowels = 0; } String[] array = new String[tempList.size()]; for (int i = 0; i < array.length; i++) array[i] = tempList.get(i); return array; } //Returns an array of words with at least m occurrences // of the letter included public String[] multiLetter(int m, char included) { ArrayList<String> tempList = new ArrayList<>(); String letter = Character.toString(included); int numOfLetter = 0; for (String word : dictionary) { String[] wordArray = word.split(""); for (int i = 0; i < wordArray.length; i++) { String elem = wordArray[i]; //Increments the counter for the number of vowels when // a vowel is found in the word if (elem.equals(letter)) numOfLetter++; } if (numOfLetter >= m) tempList.add(word); //Resets numOfVowels for the next word numOfLetter = 0; } String[] array = new String[tempList.size()]; for (int i = 0; i < array.length; i++) array[i] = tempList.get(i); return array; } }
4,706
0.618765
0.615156
193
22.409327
19.989462
71
false
false
0
0
0
0
0
0
2.373057
false
false
11
bde691c172e05b7a2312566a22653c3b95a6a000
28,286,654,629,388
e49da654f99e3429dc743799b9d2690973202652
/src/com/facebook/rebound/SpringSystemFrameCallbackWrapper.java
52feb0136006cca8e13816346eb46d236bc2e8d7
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
andraskindler/rebound
https://github.com/andraskindler/rebound
6c05c5a13b67bc117052f6d6f007a94e69a11187
68064fa4b061246d43e79b6b67a4f791ab593192
refs/heads/master
2021-01-22T15:22:51.793000
2014-01-17T17:25:34
2014-01-17T17:25:34
16,054,586
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2013, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ package com.facebook.rebound; /** * SpringSystemFrameCallbackWrapper is a FrameCallbackWrapper that can be configured to work on a * specific SpringSystem. This improves testability by allowing an outside caller to manipulate the * PhysicsSystem that is acted on when resolving a non-idle system. Specifically this improves our * ability to use mock/spy objects to verify SpringSystem functionality while iterating. */ public class SpringSystemFrameCallbackWrapper extends FrameCallbackWrapper { private SpringSystem mSpringSystem; /** * Set a SpringSystem for the physics loop to run on. * @param springSystem the SpringSystem to use */ public void setSpringSystem(SpringSystem springSystem) { mSpringSystem = springSystem; } /** * Run the PhysicsSystem run loop. */ @Override public void doFrame(long frameTimeNanos) { mSpringSystem.loop(); } }
UTF-8
Java
1,205
java
SpringSystemFrameCallbackWrapper.java
Java
[]
null
[]
/* * Copyright (c) 2013, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ package com.facebook.rebound; /** * SpringSystemFrameCallbackWrapper is a FrameCallbackWrapper that can be configured to work on a * specific SpringSystem. This improves testability by allowing an outside caller to manipulate the * PhysicsSystem that is acted on when resolving a non-idle system. Specifically this improves our * ability to use mock/spy objects to verify SpringSystem functionality while iterating. */ public class SpringSystemFrameCallbackWrapper extends FrameCallbackWrapper { private SpringSystem mSpringSystem; /** * Set a SpringSystem for the physics loop to run on. * @param springSystem the SpringSystem to use */ public void setSpringSystem(SpringSystem springSystem) { mSpringSystem = springSystem; } /** * Run the PhysicsSystem run loop. */ @Override public void doFrame(long frameTimeNanos) { mSpringSystem.loop(); } }
1,205
0.748548
0.745228
38
30.68421
33.265366
99
false
false
0
0
0
0
0
0
0.157895
false
false
11
df4ce59e5da755427d7a98697d220d639808bdd6
22,393,959,500,783
75d169c715e7b8b7071d6cc9c09624b78e7f0fec
/src/main/java/com/slawek/wordlearning/server/db/repositories/LessonRawDataRepository.java
bc47f693a80ab368a4816d7e627bad02e8906ae7
[]
no_license
devcateu/wordlearning-server
https://github.com/devcateu/wordlearning-server
1109de57868030f6bbeaf3f8280e1495edd22c24
73e2aac7130707db3f351497e191474e0589e685
refs/heads/master
2021-05-31T19:08:54.851000
2016-06-08T21:00:23
2016-06-08T21:00:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.slawek.wordlearning.server.db.repositories; import com.mongodb.Block; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.mongodb.client.model.Projections; import com.slawek.wordlearning.server.db.model.Lesson; import org.bson.Document; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.List; @Component public class LessonRawDataRepository { private MongoDatabase db; @Value(value = "${spring.data.mongodb.uri}") private String mongoURI; @PostConstruct public void init() { MongoClientURI uri = new MongoClientURI(mongoURI); MongoClient mongoClient = new MongoClient(uri); db = mongoClient.getDatabase(uri.getDatabase()); } public List<String> getAllLessonIds() { FindIterable<Document> cursor = db.getCollection(Lesson.COLLECTION_NAME) .find() .projection(Projections.include("_id")); ArrayList<String> lessonIds = new ArrayList<>(); for (Document docu : cursor) { lessonIds.add(docu.get("_id").toString()); } return lessonIds; } public String query(String id) { MongoCollection<Document> coll = db.getCollection(Lesson.COLLECTION_NAME); FindIterable<Document> documents = coll.find(Filters.eq("_id", new ObjectId(id))); List<String> value = new ArrayList<>(); documents.forEach((Block<Document>) document -> { value.add(document.toJson()); }); if (value.size() == 1) { return value.get(0); } else { return "kupa"; } } }
UTF-8
Java
1,774
java
LessonRawDataRepository.java
Java
[]
null
[]
package com.slawek.wordlearning.server.db.repositories; import com.mongodb.Block; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.mongodb.client.model.Projections; import com.slawek.wordlearning.server.db.model.Lesson; import org.bson.Document; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.List; @Component public class LessonRawDataRepository { private MongoDatabase db; @Value(value = "${spring.data.mongodb.uri}") private String mongoURI; @PostConstruct public void init() { MongoClientURI uri = new MongoClientURI(mongoURI); MongoClient mongoClient = new MongoClient(uri); db = mongoClient.getDatabase(uri.getDatabase()); } public List<String> getAllLessonIds() { FindIterable<Document> cursor = db.getCollection(Lesson.COLLECTION_NAME) .find() .projection(Projections.include("_id")); ArrayList<String> lessonIds = new ArrayList<>(); for (Document docu : cursor) { lessonIds.add(docu.get("_id").toString()); } return lessonIds; } public String query(String id) { MongoCollection<Document> coll = db.getCollection(Lesson.COLLECTION_NAME); FindIterable<Document> documents = coll.find(Filters.eq("_id", new ObjectId(id))); List<String> value = new ArrayList<>(); documents.forEach((Block<Document>) document -> { value.add(document.toJson()); }); if (value.size() == 1) { return value.get(0); } else { return "kupa"; } } }
1,774
0.749718
0.748591
64
26.71875
21.789812
84
false
false
0
0
0
0
0
0
1.5
false
false
11
3a0426fe66f8d5602bb1c865169bc9075864d5ef
6,579,889,955,619
ef0c1514e9af6de3ba4a20e0d01de7cc3a915188
/sdk/databoxedge/azure-resourcemanager-databoxedge/src/test/java/com/azure/resourcemanager/databoxedge/generated/SkuLocationInfoTests.java
d80764a96e338832b1b1adbabaa6b1c16b2c7733
[ "LicenseRef-scancode-generic-cla", "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-or-later", "CC0-1.0", "BSD-3-Clause", "UPL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
Azure/azure-sdk-for-java
https://github.com/Azure/azure-sdk-for-java
0902d584b42d3654b4ce65b1dad8409f18ddf4bc
789bdc6c065dc44ce9b8b630e2f2e5896b2a7616
refs/heads/main
2023-09-04T09:36:35.821000
2023-09-02T01:53:56
2023-09-02T01:53:56
2,928,948
2,027
2,084
MIT
false
2023-09-14T21:37:15
2011-12-06T23:33:56
2023-09-14T17:19:10
2023-09-14T21:37:14
3,043,660
1,994
1,854
1,435
Java
false
false
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.databoxedge.generated; import com.azure.core.util.BinaryData; import com.azure.resourcemanager.databoxedge.models.SkuLocationInfo; public final class SkuLocationInfoTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SkuLocationInfo model = BinaryData .fromString( "{\"location\":\"cvydypatdoo\",\"zones\":[\"kniod\",\"oo\"],\"sites\":[\"nuj\",\"emmsbvdkc\",\"odtji\",\"fw\"]}") .toObject(SkuLocationInfo.class); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { SkuLocationInfo model = new SkuLocationInfo(); model = BinaryData.fromObject(model).toObject(SkuLocationInfo.class); } }
UTF-8
Java
950
java
SkuLocationInfoTests.java
Java
[]
null
[]
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.databoxedge.generated; import com.azure.core.util.BinaryData; import com.azure.resourcemanager.databoxedge.models.SkuLocationInfo; public final class SkuLocationInfoTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SkuLocationInfo model = BinaryData .fromString( "{\"location\":\"cvydypatdoo\",\"zones\":[\"kniod\",\"oo\"],\"sites\":[\"nuj\",\"emmsbvdkc\",\"odtji\",\"fw\"]}") .toObject(SkuLocationInfo.class); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { SkuLocationInfo model = new SkuLocationInfo(); model = BinaryData.fromObject(model).toObject(SkuLocationInfo.class); } }
950
0.672632
0.672632
25
37
30.488031
133
false
false
0
0
0
0
0
0
0.48
false
false
11
eaff93a17110490633f7d0131b1fb0ce465e793c
18,399,639,963,078
9657d82b2082af7e68e6e574cf2f0c939d780ddd
/account-dao/src/main/java/ua/procamp/dao/AccountDaoImpl.java
2b6adb031286932185ae164b5395eab5207a2065
[]
no_license
Shtramak/java-persistence-exercises
https://github.com/Shtramak/java-persistence-exercises
773f87d3a0aa4e3ee5e35c0446a1462573d20eff
c740c1337612431362f1dd93723ebef894c486ab
refs/heads/master
2020-05-04T17:07:29.819000
2019-04-13T19:51:36
2019-04-13T19:51:36
179,299,269
0
0
null
true
2019-04-03T13:46:03
2019-04-03T13:46:02
2019-03-31T16:02:09
2019-04-03T13:39:31
59
0
0
0
null
false
null
package ua.procamp.dao; import ua.procamp.exception.AccountDaoException; import ua.procamp.model.Account; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import java.util.List; import java.util.function.Consumer; import java.util.function.Function; public class AccountDaoImpl implements AccountDao { private EntityManagerFactory emf; public AccountDaoImpl(EntityManagerFactory emf) { this.emf = emf; } @Override public void save(Account account) { executeWithinTransaction(entityManager -> entityManager.persist(account)); } @Override public Account findById(Long id) { return executeWithinTransactionReturningResult(entityManager -> entityManager.find(Account.class, id)); } @Override public Account findByEmail(String email) { return executeWithinTransactionReturningResult(entityManager -> entityManager.createQuery("SELECT a FROM Account a WHERE a.email=:email", Account.class) .setParameter("email", email) .getSingleResult()); } @Override public List<Account> findAll() { return executeWithinTransactionReturningResult(entityManager -> entityManager.createQuery("from Account", Account.class) .getResultList()); } @Override public void update(Account account) { executeWithinTransaction(entityManager -> entityManager.merge(account)); } @Override public void remove(Account account) { executeWithinTransaction(entityManager -> { Account managedAccount = entityManager.merge(account); entityManager.remove(managedAccount); }); } private void executeWithinTransaction(Consumer<EntityManager> emConsumer) { EntityManager entityManager = emf.createEntityManager(); entityManager.getTransaction().begin(); try { emConsumer.accept(entityManager); entityManager.getTransaction().commit(); } catch (Exception e) { entityManager.getTransaction().rollback(); throw new AccountDaoException("Exception occurred while executing transaction", e); } finally { entityManager.close(); } } private <T> T executeWithinTransactionReturningResult(Function<EntityManager, T> emFunction) { EntityManager entityManager = emf.createEntityManager(); entityManager.getTransaction().begin(); try { T result = emFunction.apply(entityManager); entityManager.getTransaction().commit(); return result; } catch (Exception e) { entityManager.getTransaction().rollback(); throw new AccountDaoException("Exception occurred while executing transaction", e); } finally { entityManager.close(); } } }
UTF-8
Java
2,941
java
AccountDaoImpl.java
Java
[]
null
[]
package ua.procamp.dao; import ua.procamp.exception.AccountDaoException; import ua.procamp.model.Account; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import java.util.List; import java.util.function.Consumer; import java.util.function.Function; public class AccountDaoImpl implements AccountDao { private EntityManagerFactory emf; public AccountDaoImpl(EntityManagerFactory emf) { this.emf = emf; } @Override public void save(Account account) { executeWithinTransaction(entityManager -> entityManager.persist(account)); } @Override public Account findById(Long id) { return executeWithinTransactionReturningResult(entityManager -> entityManager.find(Account.class, id)); } @Override public Account findByEmail(String email) { return executeWithinTransactionReturningResult(entityManager -> entityManager.createQuery("SELECT a FROM Account a WHERE a.email=:email", Account.class) .setParameter("email", email) .getSingleResult()); } @Override public List<Account> findAll() { return executeWithinTransactionReturningResult(entityManager -> entityManager.createQuery("from Account", Account.class) .getResultList()); } @Override public void update(Account account) { executeWithinTransaction(entityManager -> entityManager.merge(account)); } @Override public void remove(Account account) { executeWithinTransaction(entityManager -> { Account managedAccount = entityManager.merge(account); entityManager.remove(managedAccount); }); } private void executeWithinTransaction(Consumer<EntityManager> emConsumer) { EntityManager entityManager = emf.createEntityManager(); entityManager.getTransaction().begin(); try { emConsumer.accept(entityManager); entityManager.getTransaction().commit(); } catch (Exception e) { entityManager.getTransaction().rollback(); throw new AccountDaoException("Exception occurred while executing transaction", e); } finally { entityManager.close(); } } private <T> T executeWithinTransactionReturningResult(Function<EntityManager, T> emFunction) { EntityManager entityManager = emf.createEntityManager(); entityManager.getTransaction().begin(); try { T result = emFunction.apply(entityManager); entityManager.getTransaction().commit(); return result; } catch (Exception e) { entityManager.getTransaction().rollback(); throw new AccountDaoException("Exception occurred while executing transaction", e); } finally { entityManager.close(); } } }
2,941
0.66406
0.66406
85
33.588234
28.545647
111
false
false
0
0
0
0
0
0
0.470588
false
false
11
da5b9de08c0c25c819cbf42d60bcd6185baf288a
24,395,414,302,514
cf73ac08271f30ba1438f81786a0bd4b862acc23
/Challenge 1/MyFirstJavaProject/src/myfirstjavaproject/MyFirstJavaProject.java
a0d08af8374db40e3040114d9a3d96278d04ca23
[]
no_license
gregryterski/CS3330-Object-Oriented-Programming
https://github.com/gregryterski/CS3330-Object-Oriented-Programming
d5167c6f18e40f0420a4fe8e8226019789f3b6cf
b24380f8f90a2af5270323ada75f3b4d55c33207
refs/heads/master
2023-02-20T15:18:18.534000
2021-01-18T20:01:07
2021-01-18T20:01:07
297,465,538
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 myfirstjavaproject; /** * * @author Gregory Ryterski */ public class MyFirstJavaProject { /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("Hello World!"); for(int i = 0; i < 100; i++){ // System.out.println(i); if(i == 99){ System.out.print(i); } else { System.out.print(i + ","); } } System.out.println(); System.out.println(weAreHungry()); } public static String weAreHungry(){ String firstString = "Yo yo yo"; String concat = firstString.concat(" we are hungry"); //System.out.println(concat); String replace = " ladies and gentlemen".replace("and", "/"); String result = concat.concat(replace); return result; //return concat.concat(replace); } }
UTF-8
Java
1,227
java
MyFirstJavaProject.java
Java
[ { "context": " */\npackage myfirstjavaproject;\n\n/**\n *\n * @author Gregory Ryterski\n */\npublic class MyFirstJavaProject {\n\n /**\n ", "end": 248, "score": 0.9997949600219727, "start": 232, "tag": "NAME", "value": "Gregory Ryterski" } ]
null
[]
/* * 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 myfirstjavaproject; /** * * @author <NAME> */ public class MyFirstJavaProject { /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("Hello World!"); for(int i = 0; i < 100; i++){ // System.out.println(i); if(i == 99){ System.out.print(i); } else { System.out.print(i + ","); } } System.out.println(); System.out.println(weAreHungry()); } public static String weAreHungry(){ String firstString = "Yo yo yo"; String concat = firstString.concat(" we are hungry"); //System.out.println(concat); String replace = " ladies and gentlemen".replace("and", "/"); String result = concat.concat(replace); return result; //return concat.concat(replace); } }
1,217
0.517522
0.512632
51
23.058823
20.070866
79
false
false
0
0
0
0
0
0
0.411765
false
false
11
62ae28286a090b723f8d74cdd396550bb96129cc
28,381,143,910,554
c08051e29820bb9136ed5f1a9981e8203a2b5baf
/Concept/src/exception/Execution.java
8399ddb91c5c5bab672fe297daced12274c59c9a
[]
no_license
vivyad1208/JavaConcept
https://github.com/vivyad1208/JavaConcept
9565200e6e7cfbf21806a779f062a5a93e48c243
d4a8ac69f0d689e43c3e2441598a0aea2d29bd0d
refs/heads/master
2020-03-21T19:37:56.846000
2018-07-24T01:07:08
2018-07-24T01:07:08
138,960,901
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package exception; public class Execution { public static void main(String[] args) { try { throw new ExceptionDemo(); } catch (ExceptionDemo ex) { ex.printStackTrace(); } } @SuppressWarnings("serial") static class ExceptionDemo extends Exception { public ExceptionDemo() { System.out.println("Inside '"+this.toString()+"' Constructor"); } public String method() throws Exception { return ""; } } @SuppressWarnings("serial") static class NewExceptionDemo extends ExceptionDemo { @Override public String method() throws Exception { return ""; } } }
UTF-8
Java
636
java
Execution.java
Java
[]
null
[]
package exception; public class Execution { public static void main(String[] args) { try { throw new ExceptionDemo(); } catch (ExceptionDemo ex) { ex.printStackTrace(); } } @SuppressWarnings("serial") static class ExceptionDemo extends Exception { public ExceptionDemo() { System.out.println("Inside '"+this.toString()+"' Constructor"); } public String method() throws Exception { return ""; } } @SuppressWarnings("serial") static class NewExceptionDemo extends ExceptionDemo { @Override public String method() throws Exception { return ""; } } }
636
0.641509
0.641509
36
15.666667
18.289341
66
false
false
0
0
0
0
0
0
1.361111
false
false
11
2b931af195a75ddbf2cb65006b2604e586b5023f
28,381,143,909,519
a427816a99fce0b43ff5a135b4de405470130e4f
/parser-experiment/parboiled-experiment/src/test/java/me/loki2302/LiteralTest.java
ca5b26f0a43a4176c9e6de71af9c7ef2c9807c27
[]
no_license
agibalov/java-library-experiments
https://github.com/agibalov/java-library-experiments
41b93ec57b8df4177367f376ae7fafaebfc80df2
ba403e77e80ef9f9abaf612f10fc0a1b472f3666
refs/heads/master
2021-12-12T12:25:01.719000
2021-11-29T20:14:13
2021-11-29T20:14:13
112,420,117
1
2
null
false
2021-11-29T20:14:14
2017-11-29T03:13:19
2021-11-29T03:36:59
2021-11-29T20:14:13
11,288
1
0
19
Java
false
false
package me.loki2302; import java.util.ArrayList; import java.util.Collection; import java.util.List; import me.loki2302.ParseResult; import me.loki2302.dom.DOMLiteralType; import me.loki2302.expectations.element.ElementExpectation; import me.loki2302.expectations.element.expression.literal.LiteralExpressionExpectation; import me.loki2302.expectations.parser.ParseResultExpectation; import me.loki2302.parser.ExpressionParser; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import static me.loki2302.expectations.ParserTestDsl.*; @RunWith(Parameterized.class) public class LiteralTest { private final String expression; private final ExpressionParser parser; private final ParseResultExpectation parseResultExpectation; public LiteralTest( String expression, ExpressionParser parser, ParseResultExpectation parseResultExpectation) { this.expression = expression; this.parser = parser; this.parseResultExpectation = parseResultExpectation; } @Parameters(name = "#{index}: Parse \"{0}\"") public static Collection<Object[]> makeTestData() { List<Object[]> parameters = new ArrayList<Object[]>(); parameters.add(new Object[] {"123", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Int), havingValueOf("123"))) }); parameters.add(new Object[] {" 123", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Int), havingValueOf("123"))) }); parameters.add(new Object[] {"123 ", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Int), havingValueOf("123"))) }); parameters.add(new Object[] {" 123 ", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Int), havingValueOf("123"))) }); parameters.add(new Object[] {"3.14", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Double), havingValueOf("3.14"))) }); parameters.add(new Object[] {"3.", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Double), havingValueOf("3."))) }); parameters.add(new Object[] {".14", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Double), havingValueOf(".14"))) }); parameters.add(new Object[] {" 3.14", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Double), havingValueOf("3.14"))) }); parameters.add(new Object[] {"3.14 ", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Double), havingValueOf("3.14"))) }); parameters.add(new Object[] {" 3.14 ", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Double), havingValueOf("3.14"))) }); parameters.add(new Object[] {".", parseExpression(), fail() }); parameters.add(new Object[] {"true", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Bool), havingValueOf("true"))) }); parameters.add(new Object[] {"false", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Bool), havingValueOf("false"))) }); parameters.add(new Object[] {" true", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Bool), havingValueOf("true"))) }); parameters.add(new Object[] {"true ", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Bool), havingValueOf("true"))) }); parameters.add(new Object[] {" true ", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Bool), havingValueOf("true"))) }); parameters.add(new Object[] {" false", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Bool), havingValueOf("false"))) }); parameters.add(new Object[] {"false ", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Bool), havingValueOf("false"))) }); parameters.add(new Object[] {" false ", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Bool), havingValueOf("false"))) }); parameters.add(new Object[] {"true", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Bool), havingValueOf("true"))) }); parameters.add(new Object[] {"123", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Int), havingValueOf("123"))) }); parameters.add(new Object[] {"123.", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Double), havingValueOf("123."))) }); return parameters; } @Test public void testLiteralParseResult() { ParseResult parseResult = parser.parse(expression); parseResultExpectation.check(parseResult); } private static ElementExpectation isLiteralExpression(LiteralExpressionExpectation... expectations) { return isExpression(isLiteral(expectations)); } }
UTF-8
Java
4,647
java
LiteralTest.java
Java
[]
null
[]
package me.loki2302; import java.util.ArrayList; import java.util.Collection; import java.util.List; import me.loki2302.ParseResult; import me.loki2302.dom.DOMLiteralType; import me.loki2302.expectations.element.ElementExpectation; import me.loki2302.expectations.element.expression.literal.LiteralExpressionExpectation; import me.loki2302.expectations.parser.ParseResultExpectation; import me.loki2302.parser.ExpressionParser; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import static me.loki2302.expectations.ParserTestDsl.*; @RunWith(Parameterized.class) public class LiteralTest { private final String expression; private final ExpressionParser parser; private final ParseResultExpectation parseResultExpectation; public LiteralTest( String expression, ExpressionParser parser, ParseResultExpectation parseResultExpectation) { this.expression = expression; this.parser = parser; this.parseResultExpectation = parseResultExpectation; } @Parameters(name = "#{index}: Parse \"{0}\"") public static Collection<Object[]> makeTestData() { List<Object[]> parameters = new ArrayList<Object[]>(); parameters.add(new Object[] {"123", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Int), havingValueOf("123"))) }); parameters.add(new Object[] {" 123", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Int), havingValueOf("123"))) }); parameters.add(new Object[] {"123 ", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Int), havingValueOf("123"))) }); parameters.add(new Object[] {" 123 ", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Int), havingValueOf("123"))) }); parameters.add(new Object[] {"3.14", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Double), havingValueOf("3.14"))) }); parameters.add(new Object[] {"3.", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Double), havingValueOf("3."))) }); parameters.add(new Object[] {".14", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Double), havingValueOf(".14"))) }); parameters.add(new Object[] {" 3.14", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Double), havingValueOf("3.14"))) }); parameters.add(new Object[] {"3.14 ", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Double), havingValueOf("3.14"))) }); parameters.add(new Object[] {" 3.14 ", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Double), havingValueOf("3.14"))) }); parameters.add(new Object[] {".", parseExpression(), fail() }); parameters.add(new Object[] {"true", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Bool), havingValueOf("true"))) }); parameters.add(new Object[] {"false", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Bool), havingValueOf("false"))) }); parameters.add(new Object[] {" true", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Bool), havingValueOf("true"))) }); parameters.add(new Object[] {"true ", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Bool), havingValueOf("true"))) }); parameters.add(new Object[] {" true ", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Bool), havingValueOf("true"))) }); parameters.add(new Object[] {" false", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Bool), havingValueOf("false"))) }); parameters.add(new Object[] {"false ", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Bool), havingValueOf("false"))) }); parameters.add(new Object[] {" false ", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Bool), havingValueOf("false"))) }); parameters.add(new Object[] {"true", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Bool), havingValueOf("true"))) }); parameters.add(new Object[] {"123", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Int), havingValueOf("123"))) }); parameters.add(new Object[] {"123.", parseExpression(), result(isLiteralExpression(ofType(DOMLiteralType.Double), havingValueOf("123."))) }); return parameters; } @Test public void testLiteralParseResult() { ParseResult parseResult = parser.parse(expression); parseResultExpectation.check(parseResult); } private static ElementExpectation isLiteralExpression(LiteralExpressionExpectation... expectations) { return isExpression(isLiteral(expectations)); } }
4,647
0.759845
0.738541
78
58.589745
54.691544
145
false
false
0
0
0
0
0
0
2.794872
false
false
11
de7f767b95d4ebdd2582dd43181bdab550ce5eb1
29,918,742,216,647
d88697f71d350443e89822edb4f00a7be2d57e6d
/1-actions/app/src/main/java/codelab/fit/com/wear101/MainActivity.java
1351252bb3271afac16a2d44969924923106014d
[ "MIT" ]
permissive
diegofigueroa/fit-wear-lab
https://github.com/diegofigueroa/fit-wear-lab
63c1cd421e053e45a628e88892c392a39cfb3ed5
ed9d6009f6fc39d26d54ca157165046571dd899c
refs/heads/master
2016-09-05T09:37:34.442000
2014-10-09T02:25:10
2014-10-09T02:25:10
24,869,681
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package codelab.fit.com.wear101; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.view.Menu; import android.view.MenuItem; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void showSimpleNotification(final View button) { createSimpleNotification("Test", "Hi I'm a simple notification, you should be able to se mee on your watch!"); } public void showSimpleNotificationWithAction(final View button) { createNotificationWithAction("Test", "Hi I'm a simple notification, with some actions."); } private void createSimpleNotification(final String title, final String content) { // An id for the notification to be showed, it should be unique. final int notificationId = 001; // Build intent for notification content final Intent viewIntent = new Intent(this, MainActivity.class); final PendingIntent viewPendingIntent = PendingIntent.getActivity(this, 0, viewIntent, 0); final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle(title) .setContentText(content) .setContentIntent(viewPendingIntent); // Get an instance of the NotificationManager service final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); // Builds the notification and issues it with notification manager. notificationManager.notify(notificationId, notificationBuilder.build()); } private void createNotificationWithAction(final String title, final String content) { // An id for the notification to be showed, it should be unique. final int notificationId = 002; // Build an intent for an action to view a map final Intent mapIntent = new Intent(Intent.ACTION_VIEW); final Uri geoUri = Uri.parse("geo:0,0?q="); mapIntent.setData(geoUri); final PendingIntent mapPendingIntent = PendingIntent.getActivity(this, 0, mapIntent, 0); final PendingIntent viewPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle(title) .setContentText(content) .setContentIntent(viewPendingIntent) .setAutoCancel(true) .addAction(R.drawable.ic_launcher, "View map", mapPendingIntent); // Get an instance of the NotificationManager service final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); // Builds the notification and issues it with notification manager. notificationManager.notify(notificationId, notificationBuilder.build()); } }
UTF-8
Java
4,030
java
MainActivity.java
Java
[]
null
[]
package codelab.fit.com.wear101; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.view.Menu; import android.view.MenuItem; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void showSimpleNotification(final View button) { createSimpleNotification("Test", "Hi I'm a simple notification, you should be able to se mee on your watch!"); } public void showSimpleNotificationWithAction(final View button) { createNotificationWithAction("Test", "Hi I'm a simple notification, with some actions."); } private void createSimpleNotification(final String title, final String content) { // An id for the notification to be showed, it should be unique. final int notificationId = 001; // Build intent for notification content final Intent viewIntent = new Intent(this, MainActivity.class); final PendingIntent viewPendingIntent = PendingIntent.getActivity(this, 0, viewIntent, 0); final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle(title) .setContentText(content) .setContentIntent(viewPendingIntent); // Get an instance of the NotificationManager service final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); // Builds the notification and issues it with notification manager. notificationManager.notify(notificationId, notificationBuilder.build()); } private void createNotificationWithAction(final String title, final String content) { // An id for the notification to be showed, it should be unique. final int notificationId = 002; // Build an intent for an action to view a map final Intent mapIntent = new Intent(Intent.ACTION_VIEW); final Uri geoUri = Uri.parse("geo:0,0?q="); mapIntent.setData(geoUri); final PendingIntent mapPendingIntent = PendingIntent.getActivity(this, 0, mapIntent, 0); final PendingIntent viewPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle(title) .setContentText(content) .setContentIntent(viewPendingIntent) .setAutoCancel(true) .addAction(R.drawable.ic_launcher, "View map", mapPendingIntent); // Get an instance of the NotificationManager service final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); // Builds the notification and issues it with notification manager. notificationManager.notify(notificationId, notificationBuilder.build()); } }
4,030
0.699007
0.694293
97
40.546391
33.096241
124
false
false
0
0
0
0
0
0
0.639175
false
false
11
d80494764c0e1b1a212868aa085703ee8468c201
8,126,078,150,440
7a1c0d948c2b914f954b2f2ec5092bab250ad0e8
/app/src/main/java/com/trannguyentanthuan2903/yourfoods/my_cart/model/MyCartAdapter.java
c4c80a44f07ec2c8db795f2626f18d0072ae610d
[]
no_license
Testtaccount/YourFoods-master
https://github.com/Testtaccount/YourFoods-master
649323eb52cb899947db08ddaaf422895682891f
91f09d241d975371e3afbb84a5c6fea13df64d27
refs/heads/master
2020-03-27T11:02:54.590000
2018-08-28T14:41:30
2018-08-28T14:41:30
146,461,615
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.trannguyentanthuan2903.yourfoods.my_cart.model; import android.content.Context; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.bumptech.glide.Glide; import com.trannguyentanthuan2903.yourfoods.R; import com.trannguyentanthuan2903.yourfoods.my_cart.presenter.MyCartPresenter; import java.util.ArrayList; /** * Created by Administrator on 10/17/2017. */ public class MyCartAdapter extends RecyclerView.Adapter<MyCartViewHolder> { private ArrayList<MyCart> arrMyCart; private Context mContext; private MyCartPresenter presenter; private String idUser; private String idStore; public MyCartAdapter(ArrayList<MyCart> arrMyCart, Context mContext, String idUser, String idStore) { this.arrMyCart = arrMyCart; this.mContext = mContext; this.idUser = idUser; this.idStore = idStore; presenter = new MyCartPresenter(); } @Override public MyCartViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater. from(parent.getContext()). inflate(R.layout.item_mycart, parent, false); return new MyCartViewHolder(itemView); } @Override public void onBindViewHolder(final MyCartViewHolder holder, int position) { final MyCart myCart = arrMyCart.get(position); holder.txtProductName.setText(myCart.getProductName()); holder.txtCountProduct.setText(String.valueOf(myCart.getCount())); holder.txtPrice.setText(Math.round(myCart.getPrice()) + " VNĐ"); String linkPhotoProduct = myCart.getLinkPhotoProduct(); if (!linkPhotoProduct.equals("")) { Glide.with(mContext) .load(linkPhotoProduct) .fitCenter() .into(holder.imgPhotoProduct); } //set Click Buy Product holder.txtDeleteProduct.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder aler = new AlertDialog.Builder(mContext); aler.setMessage("Bạn có chắc chắn muốn xóa sản phẩm này?"); aler.setPositiveButton("Có", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { presenter.deleteProductOrder(idUser, myCart.getIdMyOrder(), idStore); Toast.makeText(mContext, "Xóa sản phẩm thành công!", Toast.LENGTH_SHORT).show(); } }); aler.setNegativeButton("Không", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); holder.swipeLayout.close(); } }); aler.show(); } }); } @Override public int getItemCount() { return arrMyCart.size(); } }
UTF-8
Java
3,319
java
MyCartAdapter.java
Java
[]
null
[]
package com.trannguyentanthuan2903.yourfoods.my_cart.model; import android.content.Context; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.bumptech.glide.Glide; import com.trannguyentanthuan2903.yourfoods.R; import com.trannguyentanthuan2903.yourfoods.my_cart.presenter.MyCartPresenter; import java.util.ArrayList; /** * Created by Administrator on 10/17/2017. */ public class MyCartAdapter extends RecyclerView.Adapter<MyCartViewHolder> { private ArrayList<MyCart> arrMyCart; private Context mContext; private MyCartPresenter presenter; private String idUser; private String idStore; public MyCartAdapter(ArrayList<MyCart> arrMyCart, Context mContext, String idUser, String idStore) { this.arrMyCart = arrMyCart; this.mContext = mContext; this.idUser = idUser; this.idStore = idStore; presenter = new MyCartPresenter(); } @Override public MyCartViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater. from(parent.getContext()). inflate(R.layout.item_mycart, parent, false); return new MyCartViewHolder(itemView); } @Override public void onBindViewHolder(final MyCartViewHolder holder, int position) { final MyCart myCart = arrMyCart.get(position); holder.txtProductName.setText(myCart.getProductName()); holder.txtCountProduct.setText(String.valueOf(myCart.getCount())); holder.txtPrice.setText(Math.round(myCart.getPrice()) + " VNĐ"); String linkPhotoProduct = myCart.getLinkPhotoProduct(); if (!linkPhotoProduct.equals("")) { Glide.with(mContext) .load(linkPhotoProduct) .fitCenter() .into(holder.imgPhotoProduct); } //set Click Buy Product holder.txtDeleteProduct.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder aler = new AlertDialog.Builder(mContext); aler.setMessage("Bạn có chắc chắn muốn xóa sản phẩm này?"); aler.setPositiveButton("Có", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { presenter.deleteProductOrder(idUser, myCart.getIdMyOrder(), idStore); Toast.makeText(mContext, "Xóa sản phẩm thành công!", Toast.LENGTH_SHORT).show(); } }); aler.setNegativeButton("Không", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); holder.swipeLayout.close(); } }); aler.show(); } }); } @Override public int getItemCount() { return arrMyCart.size(); } }
3,319
0.632969
0.62629
88
36.43182
27.236671
104
false
false
0
0
0
0
0
0
0.647727
false
false
11
5dc1066030d40942b02d38cf20e1ef2e0296d882
23,252,952,947,374
b86e7df70e547f898082cc83660af3030be00c85
/ntagentura/src/main/java/lt/entities/Objektas.java
763412739b36ecd55718131c4f0547161bf15c2e
[]
no_license
notconst/ntagentura
https://github.com/notconst/ntagentura
3f6cff4717477babba3f1194bf5a274936e11d98
51a1d9649e9775fc45cc47ef35d79593bc25167a
refs/heads/master
2021-01-10T05:45:08.455000
2016-03-03T07:08:39
2016-03-03T07:08:39
51,989,245
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 lt.entities; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.ArrayList; /** * * @author AsusPC */ @Entity @Table(name = "OBJEKTAS") @NamedQueries({ @NamedQuery(name = "Objektas.findAll", query = "SELECT o FROM Objektas o"), @NamedQuery(name = "Objektas.findByNr", query = "SELECT o FROM Objektas o WHERE o.nr = :nr"), @NamedQuery(name = "Objektas.findByVienetokaina", query = "SELECT o FROM Objektas o WHERE o.vienetokaina = :vienetokaina"), @NamedQuery(name = "Objektas.findByMatavimovienetas", query = "SELECT o FROM Objektas o WHERE o.matavimovienetas = :matavimovienetas"), @NamedQuery(name = "Objektas.findByPlotas", query = "SELECT o FROM Objektas o WHERE o.plotas = :plotas"), @NamedQuery(name = "Objektas.findByMiestas", query = "SELECT o FROM Objektas o WHERE o.miestas = :miestas"), @NamedQuery(name = "Objektas.findByAdresas", query = "SELECT o FROM Objektas o WHERE o.adresas = :adresas"), @NamedQuery(name = "Objektas.findByKategorija", query = "SELECT o FROM Objektas o WHERE o.kategorija = :kategorija"), @NamedQuery(name = "Objektas.findByTipas", query = "SELECT o FROM Objektas o WHERE o.tipas = :tipas")}) public class Objektas implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "NR") private Integer nr; @Basic(optional = false) @NotNull @Column(name = "VIENETOKAINA") private float vienetokaina; @Basic(optional = false) @NotNull @Size(min = 1, max = 20) @Column(name = "MATAVIMOVIENETAS") private String matavimovienetas; @Basic(optional = false) @NotNull @Column(name = "PLOTAS") private float plotas; @Size(max = 20) @Column(name = "MIESTAS") private String miestas; @Size(max = 50) @Column(name = "ADRESAS") private String adresas; @Basic(optional = false) @NotNull @Size(min = 1, max = 20) @Column(name = "KATEGORIJA") private String kategorija; @Basic(optional = false) @NotNull @Size(min = 1, max = 20) @Column(name = "TIPAS") private String tipas; @ManyToMany(mappedBy = "objektasList") private List<Brokeris> brokerisList= new ArrayList<>(); @JoinColumn(name = "SAVININKONR", referencedColumnName = "NR") @ManyToOne(optional = false) private Savininkas savininkonr; public Objektas() { } public Objektas(Integer nr) { this.nr = nr; } public Objektas(Integer nr, float vienetokaina, String matavimovienetas, float plotas, String kategorija, String tipas) { this.nr = nr; this.vienetokaina = vienetokaina; this.matavimovienetas = matavimovienetas; this.plotas = plotas; this.kategorija = kategorija; this.tipas = tipas; } public Integer getNr() { return nr; } public void setNr(Integer nr) { this.nr = nr; } public float getVienetokaina() { return vienetokaina; } public void setVienetokaina(float vienetokaina) { this.vienetokaina = vienetokaina; } public String getMatavimovienetas() { return matavimovienetas; } public void setMatavimovienetas(String matavimovienetas) { this.matavimovienetas = matavimovienetas; } public float getPlotas() { return plotas; } public void setPlotas(float plotas) { this.plotas = plotas; } public String getMiestas() { return miestas; } public void setMiestas(String miestas) { this.miestas = miestas; } public String getAdresas() { return adresas; } public void setAdresas(String adresas) { this.adresas = adresas; } public String getKategorija() { return kategorija; } public void setKategorija(String kategorija) { this.kategorija = kategorija; } public String getTipas() { return tipas; } public void setTipas(String tipas) { this.tipas = tipas; } public List<Brokeris> getBrokerisList() { return brokerisList; } public void setBrokerisList(List<Brokeris> brokerisList) { this.brokerisList = brokerisList; } public Savininkas getSavininkonr() { return savininkonr; } public void setSavininkonr(Savininkas savininkonr) { this.savininkonr = savininkonr; } @Override public int hashCode() { int hash = 0; hash += (nr != null ? nr.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Objektas)) { return false; } Objektas other = (Objektas) object; if ((this.nr == null && other.nr != null) || (this.nr != null && !this.nr.equals(other.nr))) { return false; } return true; } @Override public String toString() { return "lt.entities.Objektas[ nr=" + nr + " ]"; } }
UTF-8
Java
6,092
java
Objektas.java
Java
[ { "context": "import java.util.ArrayList;\r\n\r\n/**\r\n *\r\n * @author AsusPC\r\n */\r\n@Entity\r\n@Table(name = \"OBJEKTAS\")\r\n@NamedQ", "end": 853, "score": 0.9961590766906738, "start": 847, "tag": "USERNAME", "value": "AsusPC" } ]
null
[]
/* * 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 lt.entities; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.ArrayList; /** * * @author AsusPC */ @Entity @Table(name = "OBJEKTAS") @NamedQueries({ @NamedQuery(name = "Objektas.findAll", query = "SELECT o FROM Objektas o"), @NamedQuery(name = "Objektas.findByNr", query = "SELECT o FROM Objektas o WHERE o.nr = :nr"), @NamedQuery(name = "Objektas.findByVienetokaina", query = "SELECT o FROM Objektas o WHERE o.vienetokaina = :vienetokaina"), @NamedQuery(name = "Objektas.findByMatavimovienetas", query = "SELECT o FROM Objektas o WHERE o.matavimovienetas = :matavimovienetas"), @NamedQuery(name = "Objektas.findByPlotas", query = "SELECT o FROM Objektas o WHERE o.plotas = :plotas"), @NamedQuery(name = "Objektas.findByMiestas", query = "SELECT o FROM Objektas o WHERE o.miestas = :miestas"), @NamedQuery(name = "Objektas.findByAdresas", query = "SELECT o FROM Objektas o WHERE o.adresas = :adresas"), @NamedQuery(name = "Objektas.findByKategorija", query = "SELECT o FROM Objektas o WHERE o.kategorija = :kategorija"), @NamedQuery(name = "Objektas.findByTipas", query = "SELECT o FROM Objektas o WHERE o.tipas = :tipas")}) public class Objektas implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "NR") private Integer nr; @Basic(optional = false) @NotNull @Column(name = "VIENETOKAINA") private float vienetokaina; @Basic(optional = false) @NotNull @Size(min = 1, max = 20) @Column(name = "MATAVIMOVIENETAS") private String matavimovienetas; @Basic(optional = false) @NotNull @Column(name = "PLOTAS") private float plotas; @Size(max = 20) @Column(name = "MIESTAS") private String miestas; @Size(max = 50) @Column(name = "ADRESAS") private String adresas; @Basic(optional = false) @NotNull @Size(min = 1, max = 20) @Column(name = "KATEGORIJA") private String kategorija; @Basic(optional = false) @NotNull @Size(min = 1, max = 20) @Column(name = "TIPAS") private String tipas; @ManyToMany(mappedBy = "objektasList") private List<Brokeris> brokerisList= new ArrayList<>(); @JoinColumn(name = "SAVININKONR", referencedColumnName = "NR") @ManyToOne(optional = false) private Savininkas savininkonr; public Objektas() { } public Objektas(Integer nr) { this.nr = nr; } public Objektas(Integer nr, float vienetokaina, String matavimovienetas, float plotas, String kategorija, String tipas) { this.nr = nr; this.vienetokaina = vienetokaina; this.matavimovienetas = matavimovienetas; this.plotas = plotas; this.kategorija = kategorija; this.tipas = tipas; } public Integer getNr() { return nr; } public void setNr(Integer nr) { this.nr = nr; } public float getVienetokaina() { return vienetokaina; } public void setVienetokaina(float vienetokaina) { this.vienetokaina = vienetokaina; } public String getMatavimovienetas() { return matavimovienetas; } public void setMatavimovienetas(String matavimovienetas) { this.matavimovienetas = matavimovienetas; } public float getPlotas() { return plotas; } public void setPlotas(float plotas) { this.plotas = plotas; } public String getMiestas() { return miestas; } public void setMiestas(String miestas) { this.miestas = miestas; } public String getAdresas() { return adresas; } public void setAdresas(String adresas) { this.adresas = adresas; } public String getKategorija() { return kategorija; } public void setKategorija(String kategorija) { this.kategorija = kategorija; } public String getTipas() { return tipas; } public void setTipas(String tipas) { this.tipas = tipas; } public List<Brokeris> getBrokerisList() { return brokerisList; } public void setBrokerisList(List<Brokeris> brokerisList) { this.brokerisList = brokerisList; } public Savininkas getSavininkonr() { return savininkonr; } public void setSavininkonr(Savininkas savininkonr) { this.savininkonr = savininkonr; } @Override public int hashCode() { int hash = 0; hash += (nr != null ? nr.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Objektas)) { return false; } Objektas other = (Objektas) object; if ((this.nr == null && other.nr != null) || (this.nr != null && !this.nr.equals(other.nr))) { return false; } return true; } @Override public String toString() { return "lt.entities.Objektas[ nr=" + nr + " ]"; } }
6,092
0.631976
0.62935
206
27.572815
26.789217
139
false
false
0
0
0
0
0
0
0.461165
false
false
11
3c23cb7ae078c881f4c9a2a961cc0ba989e26fb0
23,252,952,946,746
24d0e7175e2f42683758842ef81907decaef4c0d
/changeElement.java
a847f749820aea44f6e73b5f55c37a3281f320bf
[]
no_license
Daniel1987Daniel/Daniel1987Daniel
https://github.com/Daniel1987Daniel/Daniel1987Daniel
e23dea6dc3b839d171ccf22d4904e6886885e3b5
5cc4b6af06397b609bb1d36229f46e88c8d4f39c
refs/heads/main
2023-05-14T04:31:21.203000
2022-05-15T19:19:32
2022-05-15T19:19:32
375,824,959
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ExpressionsAndControlFlow; public class changeElement { public static void main(String[] args) { // - Create an array variable named `numbers` with the following content: `[1, 2, 3, 8, 5, 6]`. int[] numbers1 = {1, 2, 3, 8, 5, 6}; // - Change the value of the fourth element (8) to 4 int[] numbers2 = {1, 2, 3, 4, 5, 6}; System.out.println("Fourth element is: " + numbers1[3]); // - Print the fourth element System.out.println("Fourth element is: " + numbers2[3]); } }
UTF-8
Java
568
java
changeElement.java
Java
[]
null
[]
package ExpressionsAndControlFlow; public class changeElement { public static void main(String[] args) { // - Create an array variable named `numbers` with the following content: `[1, 2, 3, 8, 5, 6]`. int[] numbers1 = {1, 2, 3, 8, 5, 6}; // - Change the value of the fourth element (8) to 4 int[] numbers2 = {1, 2, 3, 4, 5, 6}; System.out.println("Fourth element is: " + numbers1[3]); // - Print the fourth element System.out.println("Fourth element is: " + numbers2[3]); } }
568
0.56162
0.515845
19
27.789474
29.798586
103
false
false
0
0
0
0
0
0
1.052632
false
false
11
6b153269a9394b90e2ca6bb32f9ac22bbfd361b8
13,692,355,799,610
4786ac04c721488f0b85491d46dc0fc0f39f5e18
/src/main/java/lexek/wschat/proxy/goodgame/GoodGameProxyProvider.java
e09a078dfb41a2b71fdbbc9001bad1772001870b
[ "MIT" ]
permissive
lexek/chat
https://github.com/lexek/chat
3b0cb41cec346374ea00e2cc6c35843a8d315a8b
dbc115eb8a1441fa2fc6f0728303ed266d631f24
refs/heads/master
2021-01-23T13:49:44.177000
2017-07-10T22:25:49
2017-07-10T22:25:49
35,291,454
3
1
null
false
2016-07-14T20:27:46
2015-05-08T17:04:22
2016-06-28T09:25:12
2016-07-14T20:27:46
5,541
2
1
93
Java
null
null
package lexek.wschat.proxy.goodgame; import com.google.common.collect.ImmutableSet; import io.netty.channel.EventLoopGroup; import lexek.wschat.chat.MessageBroadcaster; import lexek.wschat.chat.msg.DefaultMessageProcessingService; import lexek.wschat.chat.msg.EmoticonMessageProcessor; import lexek.wschat.proxy.*; import lexek.wschat.services.NotificationService; import org.jvnet.hk2.annotations.Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Named; import java.util.EnumSet; import java.util.List; import java.util.concurrent.atomic.AtomicLong; @Service public class GoodGameProxyProvider extends ProxyProvider { private final Logger logger = LoggerFactory.getLogger(GoodGameProxyProvider.class); private final NotificationService notificationService; private final ProxyAuthService proxyAuthService; private final EventLoopGroup eventLoopGroup; private final MessageBroadcaster messageBroadcaster; private final AtomicLong messsageId; private final GoodGameApiClient apiClient; private final DefaultMessageProcessingService messageProcessingService; @Inject public GoodGameProxyProvider( NotificationService notificationService, ProxyAuthService proxyAuthService, @Named("proxyEventLoopGroup") EventLoopGroup eventLoopGroup, MessageBroadcaster messageBroadcaster, @Named("messageId") AtomicLong messsageId, GoodGameApiClient apiClient, ProxyEmoticonProviderFactory proxyEmoticonProviderFactory ) { super("goodgame", true, false, false, true, ImmutableSet.of("goodgame"), EnumSet.of(ModerationOperation.BAN)); this.notificationService = notificationService; this.proxyAuthService = proxyAuthService; this.eventLoopGroup = eventLoopGroup; this.messageBroadcaster = messageBroadcaster; this.messsageId = messsageId; this.apiClient = apiClient; this.messageProcessingService = new DefaultMessageProcessingService(); this.messageProcessingService.addProcessor(new EmoticonMessageProcessor( proxyEmoticonProviderFactory.getProvider(this.getName()), "/emoticons/goodgame" )); } @Override public Proxy newProxy(ProxyDescriptor descriptor) { return new GoodGameChatProxy( descriptor, messageProcessingService, notificationService, messageBroadcaster, eventLoopGroup, messsageId, apiClient, proxyAuthService ); } @Override public boolean validateRemoteRoom(String remoteRoom, Long authId) { try { return apiClient.getChannelId(remoteRoom) != null; } catch (Exception e) { logger.warn("unable to get channel id", e); return false; } } @Override public List<ProxyEmoticonDescriptor> fetchEmoticonDescriptors() throws Exception { return apiClient.getEmoticons(); } }
UTF-8
Java
3,056
java
GoodGameProxyProvider.java
Java
[]
null
[]
package lexek.wschat.proxy.goodgame; import com.google.common.collect.ImmutableSet; import io.netty.channel.EventLoopGroup; import lexek.wschat.chat.MessageBroadcaster; import lexek.wschat.chat.msg.DefaultMessageProcessingService; import lexek.wschat.chat.msg.EmoticonMessageProcessor; import lexek.wschat.proxy.*; import lexek.wschat.services.NotificationService; import org.jvnet.hk2.annotations.Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Named; import java.util.EnumSet; import java.util.List; import java.util.concurrent.atomic.AtomicLong; @Service public class GoodGameProxyProvider extends ProxyProvider { private final Logger logger = LoggerFactory.getLogger(GoodGameProxyProvider.class); private final NotificationService notificationService; private final ProxyAuthService proxyAuthService; private final EventLoopGroup eventLoopGroup; private final MessageBroadcaster messageBroadcaster; private final AtomicLong messsageId; private final GoodGameApiClient apiClient; private final DefaultMessageProcessingService messageProcessingService; @Inject public GoodGameProxyProvider( NotificationService notificationService, ProxyAuthService proxyAuthService, @Named("proxyEventLoopGroup") EventLoopGroup eventLoopGroup, MessageBroadcaster messageBroadcaster, @Named("messageId") AtomicLong messsageId, GoodGameApiClient apiClient, ProxyEmoticonProviderFactory proxyEmoticonProviderFactory ) { super("goodgame", true, false, false, true, ImmutableSet.of("goodgame"), EnumSet.of(ModerationOperation.BAN)); this.notificationService = notificationService; this.proxyAuthService = proxyAuthService; this.eventLoopGroup = eventLoopGroup; this.messageBroadcaster = messageBroadcaster; this.messsageId = messsageId; this.apiClient = apiClient; this.messageProcessingService = new DefaultMessageProcessingService(); this.messageProcessingService.addProcessor(new EmoticonMessageProcessor( proxyEmoticonProviderFactory.getProvider(this.getName()), "/emoticons/goodgame" )); } @Override public Proxy newProxy(ProxyDescriptor descriptor) { return new GoodGameChatProxy( descriptor, messageProcessingService, notificationService, messageBroadcaster, eventLoopGroup, messsageId, apiClient, proxyAuthService ); } @Override public boolean validateRemoteRoom(String remoteRoom, Long authId) { try { return apiClient.getChannelId(remoteRoom) != null; } catch (Exception e) { logger.warn("unable to get channel id", e); return false; } } @Override public List<ProxyEmoticonDescriptor> fetchEmoticonDescriptors() throws Exception { return apiClient.getEmoticons(); } }
3,056
0.727421
0.72644
83
35.819279
24.413183
118
false
false
0
0
0
0
0
0
0.722892
false
false
11
a90d7525f582bc301027116051dc1965e5b29d23
14,663,018,384,915
08787a354d7726e8961489a5e392dc6cd0490ce7
/app/src/main/java/com/example/akopylov/helloworld/dictionary/DictCallback.java
547974429d54f0efc5b8b29a97f2bc4f2637c098
[]
no_license
qalekop/Android
https://github.com/qalekop/Android
05ec87c31ad083d709cd86df08293956f03155e7
6912f059732235cc2c9d784346b8447e14ffe101
refs/heads/master
2017-05-08T04:39:47.271000
2017-04-19T16:00:41
2017-04-19T16:00:41
82,187,584
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.akopylov.helloworld.dictionary; import android.util.Log; import com.squareup.otto.Bus; import javax.inject.Inject; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by akopylov on 16/02/2017. */ public class DictCallback implements Callback<String> { private Bus bus; @Inject public DictCallback(Bus bus) { this.bus = bus; } @Override public void onResponse(Call<String> call, Response<String> response) { bus.post(new DictResponse.DictResponseBuilder() .successful(response.isSuccessful()) .withDescription(response.body()) .build()); } @Override public void onFailure(Call<String> call, Throwable t) { Log.e("DIctCallback", "failure with ajax", t); bus.post(new DictResponse.DictResponseBuilder() .successful(false) .withDescription(t.getLocalizedMessage()) .build()); } }
UTF-8
Java
1,015
java
DictCallback.java
Java
[ { "context": "package com.example.akopylov.helloworld.dictionary;\n\nimport android.util.Log;\n", "end": 28, "score": 0.8655368685722351, "start": 20, "tag": "USERNAME", "value": "akopylov" }, { "context": "ack;\nimport retrofit2.Response;\n\n/**\n * Created by akopylov on 16/02/2017.\n */\n\npublic class DictCallback imp", "end": 243, "score": 0.9987509846687317, "start": 235, "tag": "USERNAME", "value": "akopylov" } ]
null
[]
package com.example.akopylov.helloworld.dictionary; import android.util.Log; import com.squareup.otto.Bus; import javax.inject.Inject; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by akopylov on 16/02/2017. */ public class DictCallback implements Callback<String> { private Bus bus; @Inject public DictCallback(Bus bus) { this.bus = bus; } @Override public void onResponse(Call<String> call, Response<String> response) { bus.post(new DictResponse.DictResponseBuilder() .successful(response.isSuccessful()) .withDescription(response.body()) .build()); } @Override public void onFailure(Call<String> call, Throwable t) { Log.e("DIctCallback", "failure with ajax", t); bus.post(new DictResponse.DictResponseBuilder() .successful(false) .withDescription(t.getLocalizedMessage()) .build()); } }
1,015
0.640394
0.629557
41
23.756098
21.674736
74
false
false
0
0
0
0
0
0
0.390244
false
false
11