method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
ede3f14c-abb4-4487-9b8a-1a6d8417ca7f | 4 | public void testConstructor_int_int_Chronology() throws Throwable {
YearMonth test = new YearMonth(1970, 6, GREGORIAN_PARIS);
assertEquals(GREGORIAN_UTC, test.getChronology());
assertEquals(1970, test.getYear());
assertEquals(6, test.getMonthOfYear());
try {
new YearMonth(Integer.MIN_VALUE, 6, GREGORIAN_PARIS);
fail();
} catch (IllegalArgumentException ex) {}
try {
new YearMonth(Integer.MAX_VALUE, 6, GREGORIAN_PARIS);
fail();
} catch (IllegalArgumentException ex) {}
try {
new YearMonth(1970, 0, GREGORIAN_PARIS);
fail();
} catch (IllegalArgumentException ex) {}
try {
new YearMonth(1970, 13, GREGORIAN_PARIS);
fail();
} catch (IllegalArgumentException ex) {}
} |
bfb3bf61-e252-4a1b-800e-2254654371e5 | 5 | private boolean hasSameProperties(ObjectRepresentation other)
{
// different size
if (props.size() != other.props.size())
{
return false;
}
for (int x = 0; x < props.size(); x++)
{
String fromProp = props.get(x);
int toIndex = other.props.indexOf(fromProp);
if (toIndex < 0)
{
// other object does not have property
return false;
}
// check that the return type is the same
if (!returnTypes.get(x).equals(other.returnTypes.get(toIndex)))
{
// return types differ
return false;
}
if(getColumnSize(fromProp) != other.getColumnSize(fromProp) )
{
//sizes differ
return false;
}
}
// all properties and return types match
return true;
} |
94868ad2-6807-4363-ad53-64f1e38b6d74 | 7 | public void act() {
if(!end){
if(state == -1) {
ActionFactory.wait(1000, "", true);
}
else if(state == 0) {
float res = Robot.getInstance().getSonar().getMinDist();
if(res>20 && res<80){
System.out.println("deja la");
stop();
}
else {
Robot.getInstance().getMotion().getPilot().setRotateSpeed(30);
//ActionFactory.rotate(180, true);
state++;
ActionFactory.wait(5, "", true);
}
}
else if(state == 1) {
System.out.println("distance : "+Robot.getInstance().getSonar().getMinDist());
ActionFactory.wait(1000, "", true);
/*float res = Robot.getInstance().getSonar().getMinDist();
if(res>20 && res<50){
System.out.println("distance : "+res);
ActionFactory.goForward(100.f, true);
state=2;
}
else
ActionFactory.wait(5, "", true);*/
}
else if(state == 3){
ActionFactory.stopMotion(true);
ActionFactory.useClaws(0.0f, true);
state++;
}
}
else
stop();
} |
62f8e22b-7d4c-46d6-a36c-db6a364060dd | 7 | public void setSubscribed(String newsgroup, boolean flag)
{
if (subs == null)
{
load();
}
if (flag && !groups.contains(newsgroup))
{
groups.add(newsgroup);
}
boolean subscribed = subs.contains(newsgroup);
if (flag && !subscribed)
{
subs.add(newsgroup);
dirty = true;
}
else if (!flag && subscribed)
{
subs.remove(newsgroup);
dirty = true;
}
} |
448e5d9b-48d5-40bd-8889-4e866a4f0e97 | 8 | public static String getOption()
{
String option = "gui";
try
{
BufferedReader r = new BufferedReader(new FileReader("config.txt"));
String line = r.readLine();
while (line != null)
{
if (line.startsWith("Option="))
{
String[] tokens = line.split("=");
if (tokens[1].equalsIgnoreCase("gui")) option = "gui";
if (tokens[1].equalsIgnoreCase("sim")) option = "sim";
if (tokens[1].equalsIgnoreCase("simulator")) option = "sim";
if (tokens[1].equalsIgnoreCase("simdb")) option = "simdb";
if (tokens[1].equalsIgnoreCase("simulatordb")) option = "simdb";
}
line = r.readLine();
}
r.close();
}
catch (Exception ex)
{
option = "gui";
}
return option;
} |
95b87a6e-9b90-451e-a20d-655f80d6e238 | 4 | public PrimevalIsle(String name, String descr)
{
super(name, descr);
for (L2Spawn npc : SpawnTable.getInstance().getSpawnTable())
if (Util.contains(MOBIDS, npc.getNpcId()) && npc.getLastSpawn() != null && npc.getLastSpawn() instanceof L2Attackable)
((L2Attackable) npc.getLastSpawn()).seeThroughSilentMove(true);
registerMobs(_sprigants, QuestEventType.ON_AGGRO_RANGE_ENTER, QuestEventType.ON_KILL);
addAttackId(ANCIENT_EGG);
addSpawnId(MOBIDS);
} |
b5cd27f3-ca3f-48b9-9753-c63a132df365 | 1 | InformGraphPrimitive(int x, int y, int width, int height, int widthDest, int heightDest, String name) {
super(x, y, width, height, widthDest, heightDest, name);
if(name.contains("_"))
setTexture(name.substring(0,name.indexOf("_")) + subName);
else
setTexture(name + subName);
} |
4ee01f29-a035-4c7f-948e-c67b7c9199e1 | 0 | public static void main(String args[])
{
new StartScreen();
} |
d42c7891-06fb-4e8a-87c7-f7a59ba60abb | 6 | public static String removeDups(String s)
{
char[] arr = s.toCharArray();
if (arr == null) return null;
if (arr.length < 2) return s;
int end = 1;
for(int i = 0; i<arr.length; i++)
{
int j = 0;
for(; j<end; j++)
{
if(arr[i] == arr[j])
{
break;
}
}
if (j==end)
{
arr[end] = arr[i];
end++;
}
}
return new String(arr, 0, end);
} |
d1871051-0af6-4329-8cf6-18a200f83848 | 1 | private static LinkedList<Video> videoListFromResultSet(ResultSet resultSet) throws SQLException {
LinkedList<Video> videos = new LinkedList<Video>();
while (resultSet.next()) {
videos.add(new Video(resultSet.getString(1), resultSet.getString(2), resultSet.getDate(3),
resultSet.getString(4), resultSet.getString(5), resultSet.getDouble(6), resultSet.getInt(7),
Arrays.asList(resultSet.getString(8).split(",")), Arrays.asList(resultSet.getString(9).split(",")),
Arrays.asList(resultSet.getString(10).split(",")),
Arrays.asList(resultSet.getString(11).split(","))));
}
return videos;
} |
51ba4aca-f0c9-409f-8f43-491bdf16333f | 7 | public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
public void run() {
try {
// This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the server owner decided to opt-out
if (isOptOut() && task != null) {
task.cancel();
task = null;
// Tell all plotters to stop gathering information.
for (Graph graph : graphs) {
graph.onOptOut();
}
}
}
// We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
} |
f8912c4f-5835-48bb-8764-062ba46bde19 | 6 | public static void addPublicationsIntoDatabase(List<Publication> plist) {
try {
if (conn == null || conn.isClosed()) {
init();
}
if (statement == null || statement.isClosed()) {
statement = conn.createStatement();
}
StringBuffer sb = new StringBuffer(
"INSERT INTO soc.publications VALUES");
for (Publication p : plist) {
sb.append(p.toString());
}
sb.deleteCharAt(sb.length() - 1);
// System.out.println(sb.toString());
statement.execute(sb.toString());
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
} |
cde0197d-b452-4b7e-b98e-486db675ec03 | 5 | public String toStringAsciiArt() {
char art[] = new char[size()];
for (int i = start, j = 0; i <= end; i++, j++) {
Utr utr = findUtr(i);
if (utr != null) art[j] = utr.isUtr5prime() ? '5' : '3';
else {
Exon exon = findExon(i);
if (exon != null) art[j] = exon.isStrandPlus() ? '>' : '<';
else art[j] = '-';
}
}
return new String(art);
} |
4d3d86a3-b7e0-440c-b4a6-bcd335c31907 | 2 | public String[] getMafiaPlayers() {
ArrayList<String> mafiaPlayer = new ArrayList<String>();
for (Player player : players) {
if (player.getRole().equals(Role.Mafia.toString()))
mafiaPlayer.add(player.getName());
}
return mafiaPlayer.toArray(new String[mafiaPlayer.size()]);
} |
a32af3b0-8f8a-4671-bce0-c3d6fff183a3 | 3 | public static void deleteDirectory(final File directory) throws IOException {
if (!directory.exists()) {
return;
}
if (!isSymbolicLink(directory.toPath())) {
cleanDirectory(directory);
}
if (!directory.delete()) {
final String message = "Unable to delete directory " + directory + ".";
throw new IOException(message);
}
} |
9f4fcdcb-192f-4a7c-9394-973718f51d43 | 3 | public static OSMHighwayType fromString(String name) {
if (name != null) {
for (OSMHighwayType h : OSMHighwayType.values()) {
if (name.equalsIgnoreCase(h.name)) {
return h;
}
}
}
return null;
//throw new IllegalArgumentException("No constant with name " + name + " found");
} |
57a464ca-c70f-44ea-90fb-91b5abfd68b0 | 9 | public final void para() throws RecognitionException {
try {
// fontes/g/CanecaSemantico.g:852:2: ( ^( PARA_ . . . . ) )
// fontes/g/CanecaSemantico.g:852:4: ^( PARA_ . . . . )
{
match(input,PARA_,FOLLOW_PARA__in_para2333); if (state.failed) return ;
match(input, Token.DOWN, null); if (state.failed) return ;
matchAny(input); if (state.failed) return ;
matchAny(input); if (state.failed) return ;
matchAny(input); if (state.failed) return ;
matchAny(input); if (state.failed) return ;
match(input, Token.UP, null); if (state.failed) return ;
if ( state.backtracking==1 ) {
mostrar("para");
InstrucaoPara instrucao = new InstrucaoPara(escopoAtual);
escopoAtual.definirInstrucao(instrucao);
escopoAtual = instrucao;
}
}
}
catch (RecognitionException erro) {
throw erro;
}
finally {
// do for sure before leaving
}
return ;
} |
402922e2-bae7-4411-a94a-8cc9febb84b3 | 3 | public void draw(Graphics2D g) {
bg.draw(g);
tileMap.draw(g);
player.draw(g);
teleport.draw(g);
// draw ememies
for (int i = 0; i < enemys.size(); i++) {
enemys.get(i).draw(g);
}
teleport.draw(g);
// draw Explostion
for (int i = 0; i < explosions.size(); i++) {
explosions.get(i).setMapPosition((int) tileMap.getx(), (int) tileMap.gety());
explosions.get(i).draw(g);
}
// HUD DRAW
hud.draw(g);
// DRAW TITLE
if (title != null)
title.draw(g);
} |
9f0e07a5-9fde-4d27-964a-c6603f6fd477 | 5 | public static void EM(Instances data, Instances originalData) throws Exception {
// Create EM Clusterer
EM em = new EM();
em.setNumClusters(3);
em.buildClusterer(data);
// evaluate the EM clusterer
ClusterEvaluation emEvaluation = new ClusterEvaluation();
emEvaluation.setClusterer(em);
emEvaluation.evaluateClusterer(data);
System.out.println(emEvaluation.clusterResultsToString());
// get class data as an array of doubles
double[] classes = originalData.attributeToDoubleArray(0);
double[] clusters = emEvaluation.getClusterAssignments();
// compare classes and clusters
int a = 0;
int b = 0;
int c = 0;
int d = 0;
for(int i = 0; i < classes.length; i++) {
for(int j = i + 1; j < classes.length; j++) {
if(classes[i] == classes[j]) {
if(clusters[i] == clusters[j])
a++;
else
b++;
} else {
if(clusters[i] == clusters[j])
c++;
else
d++;
}
}
}
System.out.println("a: " + a + " b: " + b + " c: " + c + " d: " + d);
double rand = (double) (a + d) / (double) (a + b + c + d);
System.out.println("Rand: " + rand);
} |
559cb80a-96b5-4ca0-aa1b-6e341c62f957 | 8 | protected void setActiveEntryPage(EntryPage page) {
// Have the currently displayed page save its changes
if (activePage != null) {
activePage.apply();
}
if (page == null) {
// No page available to display, so hide the panel container
propertiesPanelContainer.setVisible(false);
} else {
// Show the page and grow the shell, if necessary, so that the page
// is
// completely visible
Point oldSize = getShell().getSize();
propertiesPanelContainer.showPage(page.getControl());
/*
* Fix for bug #34748 There's no need to resize the Shell if
* initializeBounds() hasn't been called yet. It will automatically
* resize the Shell so that everything fits in the Dialog. After
* that, we can resize the Shell whenever there's an entry page that
* cannot fit in the dialog.
*/
if (!isSetup) {
Point newSize = getShell().computeSize(SWT.DEFAULT,
SWT.DEFAULT, true);
int x = newSize.x - oldSize.x;
x = (x < 0) ? 0 : x;
int y = newSize.y - oldSize.y;
y = (y < 0) ? 0 : y;
if (x > 0 || y > 0) {
getShell().setSize(oldSize.x + x, oldSize.y + y);
}
}
// Show the property panel container if it was hidden
if (!propertiesPanelContainer.isVisible()) {
propertiesPanelContainer.setVisible(true);
}
}
activePage = page;
} |
a9a440e7-d28b-4d6e-8af8-5af59e2af8cf | 7 | private String fixText (String s, DocumentFilter.FilterBypass fb) throws BadLocationException
{
if (s == null) {
return null;
}
int currentLength = fb.getDocument().getLength();
int l = fb.getDocument().getLength();
char prevChar = (l < 1) ? ' ' : fb.getDocument().getText(l-1, 1).charAt(0);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); ++i)
{
boolean doubleSpace = prevChar == ' ' && s.charAt(i) == ' ';
if (!isIllegalFileNameChar (s.charAt (i)) &&
!doubleSpace &&
currentLength < 25) //hard coded 25 char max
sb.append (s.charAt (i));
}
return sb.toString();
} |
6c94e8c4-a7ec-4c96-b066-ba80971fafd6 | 1 | @Override
public float contains( int x, int y ) {
if( boundaries.contains( x, y ) ){
return 1.f;
}
else{
return 0.f;
}
} |
9ac9909a-481d-405c-bdaf-8d71a3c09900 | 8 | public void kiemTraFileChunk(String tenFile, int soLuongChunkToiDa) {
try {
socket = new DatagramSocket(Bittorrent.portlisten + port);
socket.setSoTimeout(3000);
for (int i = 0; i < Bittorrent.danhSachPeer.size(); i++) {
String duLieuGui = "GET_CHUNK=>" + tenFile + "=>" + soLuongChunkToiDa;
String dc = Bittorrent.danhSachPeer.get(i).getIpAddresss().getHostAddress();
sendPacket = new DatagramPacket(duLieuGui.getBytes(), duLieuGui.getBytes().length,
Bittorrent.danhSachPeer.get(i).getIpAddresss(), Bittorrent.portlisten);
try {
socket.send(sendPacket);
LogFile.Write("Gui yeu cau vi tri file chunks: " + duLieuGui);
buffer = new byte[2048];
rcvPacket = new DatagramPacket(buffer, buffer.length);
socket.receive(rcvPacket);
//Lay so file chunk co trong peer
//Dinh dang: 192.168.5.20=>1,3,4,
String gt = new String(rcvPacket.getData(), 0, rcvPacket.getLength());
LogFile.Write("Nhan vi tri file chunks: " + gt);
if (gt != null) {
Bittorrent.danhSachPeer.get(i).setStatus(true);
//Lay dia chi IP
String _ip = gt.split("=>")[0];
//Lay danh sach chunk id
String[] _chunks = gt.split("=>")[1].split(",");
//Lay danh sach chunk cua _ip
List<Integer> dsChunk = new ArrayList<>();
for (int j = 0; j < _chunks.length; j++)
{
try
{
int chunkID = Integer.parseInt(_chunks[j]);
dsChunk.add(chunkID);
} catch (Exception ex) {
}
}
//Cap nhat danh sach chunk cho peer
for (int j = 0; j < Bittorrent.danhSachPeer.size(); j++)
{
String peerIP = Bittorrent.danhSachPeer.get(j).getIpAddresss().getHostAddress();
if(_ip.contains(peerIP))
{
Bittorrent.danhSachPeer.get(j).setDanhSachChunk(dsChunk);
break;
}
}
}
} catch (IOException ex) {
}
}
socket.close();
} catch (SocketException ex) {
socket.close();
}
} |
a7009735-4794-479e-bf2d-9e61396939c5 | 7 | static final CellEditable startEditing(CellRenderer self, Event event, Widget widget, String path, Rectangle backgroundArea, Rectangle cellArea, CellRendererState flags) {
long result;
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
if (event == null) {
throw new IllegalArgumentException("event can't be null");
}
if (widget == null) {
throw new IllegalArgumentException("widget can't be null");
}
if (path == null) {
throw new IllegalArgumentException("path can't be null");
}
if (backgroundArea == null) {
throw new IllegalArgumentException("backgroundArea can't be null");
}
if (cellArea == null) {
throw new IllegalArgumentException("cellArea can't be null");
}
if (flags == null) {
throw new IllegalArgumentException("flags can't be null");
}
synchronized (lock) {
result = gtk_cell_renderer_start_editing(pointerOf(self), pointerOf(event), pointerOf(widget), path, pointerOf(backgroundArea), pointerOf(cellArea), numOf(flags));
return (CellEditable) objectFor(result);
}
} |
0ef871e8-f5d1-40f8-8941-72690823afc1 | 7 | public static void main(String[] args) throws Exception {
String host="localhost";
int port=8787;
String user=null;
for(int i=0; i < args.length; i++) {
if(args[i].equals("-host") || args[i].equals("-h")) {
host=args[++i];
continue;
}
if(args[i].equals("-port") || args[i].equals("-p")) {
port=Integer.parseInt(args[++i]);
continue;
}
if(args[i].equals("-user") || args[i].equals("-name")) {
user=args[++i];
continue;
}
help();
return;
}
StompChat instance=new StompChat(host, port, user);
instance.start();
} |
8ab816c2-5f55-4339-b335-d9b325d62fd6 | 6 | public static void addMovie(TravelAgent agent){
System.out.print("Plese enter in movie name: ");
input.nextLine();
String name = input.nextLine();
System.out.print("Please enter in movie running time in minutes: ");
int length = input.nextInt();
// create a movie object that can be added to a flight
Movie m = new Movie(name, length);
// tests if there is any flights and alerts if there isn't
if (agent.economyFlightList.isEmpty() && agent.businessFlightList.isEmpty()){
System.out.println("Sorry - No Flights available to add, please add a flight to continue...");
addFlight(agent);
}
System.out.print("Please enter in the flight ID to add this movie to the flight : ");
int id = input.nextInt();
// for every business flight within the Travel Agent add the created movie object into the matching flight
for (BusinessFlight b: agent.businessFlightList){
if(b.getFlightNumber() == id){
b.addMovie(m);
System.out.print("Added to Business Flight " + id);
}
}
// we must repeat for the economy class as well to check for both
for (EconomyFlight e: agent.economyFlightList){
if(e.getFlightNumber() == id){
e.addMovie(m);
System.out.print("Added to Economy Flight " + id);
}
}
System.out.println();
addMenu(agent);
} |
11ee44b9-eb81-421f-830e-111a3d17f5e6 | 5 | protected <T> boolean isSameSetPrivate(Set<T> obj1, Set<T> obj2) {
// make sure both sets have the same size number of elements
if (obj1.size() != obj2.size())
return false;
// return obj1.containsAll(obj2);
// the sets have the same size - pick one
for (T item1 : obj1) {
boolean match = false; // did we find a match for this item?
// make sure each item of the first set matches an item in the
// second set
for (T item2 : obj2) {
// now compare the corresponding values using 'equals' as
// required
// for the Set interface
if (item1.equals(item2))
match = true; // match found
}
// no match found for this item
if (match == false) {
System.out.println("Mismatch for " + obj1 + " and " + obj2);
return false;
}
}
// all tests passed
return true;
} |
59e21ef8-dfdb-40c8-9b59-41727cce958d | 3 | public boolean deleteTopic(int id) {
Connection connection = ConnectionManager.getConnection();
if (connection == null) {
logger.log(Level.SEVERE, "Couln't establish a connection to database");
return false;
}
MessageManager messageManager = new MessageManager();
List<MessageManager.Message> messageList = messageManager.getAllChildrenMessages(id);
for (MessageManager.Message message : messageList) {
messageManager.deleteMessage(message.getId());
}
try {
PreparedStatement ps = connection.prepareStatement(DELETE_TOPIC_BY_ID_QUERY);
ps.setInt(1, id);
return ps.execute();
} catch (SQLException ex) {
logger.log(Level.SEVERE, null, ex);
return false;
}
} |
9df65ab5-f9e7-462d-9225-f57ed91052ae | 7 | @Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
String data;
try {
ArrayList<FilterBean> alFilter = new ArrayList<>();
if (request.getParameter("filter") != null) {
if (request.getParameter("filteroperator") != null) {
if (request.getParameter("filtervalue") != null) {
FilterBean oFilterBean = new FilterBean();
oFilterBean.setFilter(request.getParameter("filter"));
oFilterBean.setFilterOperator(request.getParameter("filteroperator"));
oFilterBean.setFilterValue(request.getParameter("filtervalue"));
oFilterBean.setFilterOrigin("user");
alFilter.add(oFilterBean);
}
}
}
if (request.getParameter("systemfilter") != null) {
if (request.getParameter("systemfilteroperator") != null) {
if (request.getParameter("systemfiltervalue") != null) {
FilterBean oFilterBean = new FilterBean();
oFilterBean.setFilter(request.getParameter("systemfilter"));
oFilterBean.setFilterOperator(request.getParameter("systemfilteroperator"));
oFilterBean.setFilterValue(request.getParameter("systemfiltervalue"));
oFilterBean.setFilterOrigin("system");
alFilter.add(oFilterBean);
}
}
}
InscritosDao oInscritosDAO = new InscritosDao(Conexion.getConection());
int pages = oInscritosDAO.getCount(alFilter);
data = "{\"data\":\"" + Integer.toString(pages) + "\"}";
return data;
} catch (Exception e) {
throw new ServletException("InscritosGetregistersJson: View Error: " + e.getMessage());
}
} |
a0db45ac-40df-49e1-b10f-d29b400744d7 | 4 | private String[] parseCoordinates(final JSONObject json) throws NameResolverException {
try {
//final JSONArray jsonArray = json.getJSONArray("data");
final JSONArray jsonArray = json.getJSONArray("features");
final JSONArray coords = jsonArray.getJSONObject(0).getJSONObject("geometry").getJSONArray("coordinates");
if (jsonArray.length() != 1) {
throw new NameResolverException(Status.CLIENT_ERROR_NOT_FOUND, "Not found");
}
if (coords.get(0).equals("") || coords.get(1).toString().equals("")) {
throw new NameResolverException(Status.CLIENT_ERROR_NOT_FOUND, "Not found");
}
return new String[]{coords.get(0).toString(),coords.get(1).toString()};
} catch (JSONException ex) {
throw new NameResolverException(Status.SERVER_ERROR_INTERNAL, "cannot parse the coordinates");
}
} |
134f4eae-d672-4f73-a5f9-d982956b2492 | 4 | private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
Notice N = new Notice();
if(!"".equals(TextField_Titulo.getText()) && !"".equals(TextArea_Texto.getText()) && !"".equals(TextFild_Assuntos.getText()))
{
N.setTitle(TextField_Titulo.getText());
N.setText(TextArea_Texto.getText());
String Assuntos[] = TextFild_Assuntos.getText().split(";");
ArrayList<String> List = new ArrayList<>();
List.addAll(Arrays.asList(Assuntos));
N.setSubjects(List);
try
{
Server.addNotice(N);
JOptionPane.showMessageDialog(this, "Noticia enviada com sucesso!");
Clear_Texts();
}
catch (RemoteException ex)
{
JOptionPane.showMessageDialog(this, "Falha ao enviar a notícia");
Logger.getLogger(ClienteInterface.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{
JOptionPane.showMessageDialog(this, "Não deixe campos em branco!");
}
}//GEN-LAST:event_jButton3ActionPerformed |
1969f964-fa01-4e01-bf39-750a3809e1d3 | 1 | public boolean addVertice(Point p) {
HashSet<Point> adjacent = graph.get(p);
if(adjacent == null) {
adjacent = new HashSet<Point>();
return true;
}
return false;
} |
166ad2f6-1a55-4331-986d-f523af218dd3 | 3 | private boolean jj_3R_22()
{
if (jj_3R_24()) return true;
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_25()) { jj_scanpos = xsp; break; }
}
return false;
} |
b1b54900-e97f-470d-874d-56f28b30fb07 | 1 | private static void outOfMemory() {
Vector v = new Vector();
while (true) {
v.add(new Object());
}
} |
360b4d88-0f92-4402-a027-57e6a88523d9 | 3 | public void rotateEditingShip()
{
Ship testShip = new Ship(editingShip);
testShip.rotate();
if(myTurnEditing)
{
if(mySea.shipInBounds(testShip))
editingShip.rotate();
}
else
{
if(theirSea.shipInBounds(testShip))
editingShip.rotate();
}
} |
27fdc9b5-886e-48af-8279-ab5c25303f31 | 7 | public void visitDeclaration(FieldDeclaration decl)
{
// On regarde si la déclaration possède une annotation Note
Note note = decl.getAnnotation(Note.class);
// Et on l'affiche eventuellement :
if(note != null)
printMessage(decl, note);
if(decl instanceof Map<?, ?>)
{
if(((Map<?, ?>) decl).containsKey("FORCE"))
printMessage(decl, note);
}
} |
db171a29-c851-4b01-95e8-a662e7938836 | 8 | public int[][][] getMapData() {
ensureCapacity();
if (mapData != null) {
return mapData;
}
FileInputStream dataStream = null;
try {
dataStream = new FileInputStream(DATA);
mapData = new int[4][64][64];
if (regionData != null) {
dataStream.skip(regionData.getIndex());
byte[] data = new byte[regionData.getSize()];
dataStream.read(data);
ByteBuffer buffer = ByteBuffer.wrap(data);
for (int plane = 0; plane < 4; plane++) {
for (int tx = 0; tx < 64; tx++) {
for (int ty = 0; ty < 64; ty++) {
mapData[plane][tx][ty] = buffer.getInt();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dataStream != null) {
try {
dataStream.close();
} catch (IOException e) {
}
}
}
return mapData;
} |
396963a6-3564-4287-99d1-de40c23130f2 | 9 | @Override
public int strstr( char[] pattern, char[] string ) {
if( pattern.length > string.length )
return -1;
int ret = -1;
int hashP = 0;
for( int i = 0; i < pattern.length; i++ ) {
hashP += Character.valueOf( pattern[i] ).hashCode();
}
int[] hashS = new int[ string.length - pattern.length + 1 ];
for( int i=0; i<string.length-pattern.length+1; i++ ) {
for( int j=0; j<pattern.length; j++ ) {
hashS[i] += Character.valueOf( string[i+j] ).hashCode();
}
}
for( int i=0; i<hashS.length; i++ ) {
if( hashS[i] == hashP ) {
for( int j=0; j<pattern.length; j++ ) {
if( string[ i + j ] != pattern[j] )
break;
if( j == pattern.length -1 ) {
ret = i;
return ret;
}
}
}
}
return ret;
} |
7fb8e65b-7483-46c7-86cd-e59cae08f7bb | 1 | public static CommandLineArgs toCommand(String _string)
{
try {
return valueOf(_string);
}
catch (Exception ex) {
return NOVALUE;
}
} |
47675d1f-3fb9-4373-b39c-667e86b469e2 | 5 | public void showMenu()
{
/** Prints "Battleships" in Kick-Ass ASCII Art */
System.out.println(" ____ _______ _______ _ ______ _____ _ _ _____ _____ _____ _ \r\n | _ \\ /\\|__ __|__ __| | | ____|/ ____| | | |_ _| __ \\ / ____| |\r\n | |_) | / \\ | | | | | | | |__ | (___ | |__| | | | | |__) | (___ | |\r\n | _ < / /\\ \\ | | | | | | | __| \\___ \\| __ | | | | ___/ \\___ \\| |\r\n | |_) / ____ \\| | | | | |____| |____ ____) | | | |_| |_| | ____) |_|\r\n |____/_/ \\_\\_| |_| |______|______|_____/|_| |_|_____|_| |_____/(_)\r\n \r\n ");
/** Displays the menu */
System.out.println("Please type your choice (1-3) and press enter to begin");
System.out.println("1. Start a New Game");
System.out.println("2. View Results");
System.out.println("3. Exit the Game");
/** Get the user's choice */
Scanner choice = new Scanner(System.in);
/** Take the user's choice, ensuring it is a valid integer */
boolean done = false; // Loop is not finished
while (!done) {
while(!choice.hasNextInt()) { // While user enters invalid input
System.out.println("Invalid input");
choice.next();
}
int i = choice.nextInt(); // Save the user's choice as int i
/** Ensure that the integer is a valid option and call the correct method */
switch(i) {
default :
System.out.println("Invalid Input"); // Error - try again
break;
case 1 :
newGame(); // Call newGame method
break;
case 2 :
viewResults(); // Call viewResults method
break;
case 3 :
done = true; // If user quits, the loop is done
quitGame(); // Call quitGame method
break;
}
}
} |
ba426fc1-fe26-4b94-9ab2-2c44f0edb476 | 7 | public final BufferedImage extractImageSegment(
BufferedImage sourceImage, int x, int y, int width, int height) {
BufferedImage extractedImage = null;
if (sourceImage == null)
throw new NullPointerException(
"AssetLoader.extractImageSegement: NULL source image specified.");
// Test to ensure the image segment is valid
if (x < 0 || y < 0 || width <= 0 || height <= 0)
throw new IllegalArgumentException(
"AssetLoader.extractImageSegment: Invalid image segment " +
"x =" + x + " y =" + y + " width = " + width + " height = " + height);
// Test to ensure the image segment can be extracted from the source image
if (x + width > sourceImage.getWidth() || y + height > sourceImage.getHeight())
throw new IllegalArgumentException(
"AssetLoader.extractImageSegment: " +
"Segment cannot be extracted from source image" + "Segment x =" +
x + " y =" + y + " width = " + width + " height = " + height +
": Image width = " + sourceImage.getWidth() + " height = " +
sourceImage.getHeight());
// Create a compatible image to store the extracted image segment
extractedImage = graphicsConfiguration.createCompatibleImage(
width, height, sourceImage.getColorModel().getTransparency());
// Extract and store the image segment within the comptiable image
Graphics2D graphics2D = extractedImage.createGraphics();
graphics2D.drawImage(
sourceImage, 0, 0, width, height, x, y, x + width, y + height, null);
graphics2D.dispose();
return extractedImage;
} |
6d509015-be9a-4252-a028-9719f336a153 | 1 | private static byte[] checksumToByteArray(int value) {
byte[] b = new byte[2];
for (int i = 0; i < 2; i++) {
int offset = (b.length - 1 - i) * 8;
b[i] = (byte) ((value >>> offset) & 0xFF);
}
return b;
} |
59874eca-16ca-4879-8aba-4ac51c6df59d | 0 | public String getDescription() {
return description;
} |
3f1af60f-e553-420f-9fc0-c9c21cc9d5b8 | 0 | @Test
public void testSetAnt() throws IOException {
System.out.println("setAnt");
Cell instance = new Cell(0,0);
Ant expResult = null;
Ant result = instance.getAnt();
assertEquals(expResult, result);
AntBrain ab = new AntBrain("cleverbrain1.brain");
Ant ant = new Ant(ab, true, 0);
instance.setAnt(ant);
expResult = ant;
result = instance.getAnt();
assertEquals(expResult, result);
} |
f9d69eb5-3bb8-40d4-8f83-8e2a14631016 | 6 | @Override
protected void doAction(int option)
{
switch (option)
{
case 1:
listAllTeams();
break;
case 2:
addTeam();
break;
case 3:
updateTeam();
break;
case 4:
deleteTeam();
break;
case 5:
assignToGroups();
break;
case EXIT_VALUE:
doActionExit();
}
} |
d40c2162-a586-460c-a697-840084b41be3 | 2 | public String decrypt(byte[] encondeMessage) {
int[] intText = byte2int(encondeMessage);
int i, v0, v1, sum, n;
i = 0;
while (i < intText.length - 1) {
n = numCycles;
v0 = intText[i];
v1 = intText[i + 1];
sum = delta * numCycles;
for (int ind = 0; ind < n; ind++) {
v1 -= ((v0 << 4 ) + key[2] ^ v0) + (sum ^ (v0 >>> 5)) + key[3];
v0 -= ((v1 << 4 ) + key[0] ^ v1) + (sum ^ (v1 >>> 5)) + key[1];
sum -= delta;
}
intText[i] = v0;
intText[i + 1] = v1;
i += 2;
}
return new String(int2byte(intText));
} |
fbdd08f0-4636-47e0-a303-4958a67d7c77 | 5 | @SuppressWarnings("unchecked")
private void readFile() {
FileInputStream
sfis = null,
rfis = null;
ObjectInputStream
sois = null,
rois = null;
try {
sfis = new FileInputStream(sendURL);
rfis = new FileInputStream(reportURL);
if(sfis.available() > 0) sois = new ObjectInputStream(sfis);
if(rfis.available() > 0) rois = new ObjectInputStream(rfis);
sendList = (ArrayList<SendCommodityPO>) sois.readObject();
reportList = (ArrayList<ReportCommodityPO>) rois.readObject();
} catch (FileNotFoundException e) {
System.out.println("sendCommodityPO or ReportCommodityPO.out not found");
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println(".out读取问题");
}
} |
87f5da4a-5fcf-41be-9615-08a8556344e6 | 7 | @Override
public Protein getProteinFromFile(File f)
{
Protein protein = new Protein();
BufferedReader br;
try
{
br = new BufferedReader(new FileReader(f));
String line = null;
try
{
while((line=br.readLine()) != null)
{
if(line.contains("/protein"))
{
br.close();
break;
}
else if(line.contains("name"))
{
int start = line.indexOf(QUOTE);
int stop = line.indexOf(QUOTE, start+1);
protein.setName(line.substring(start+1, stop));
}
else if(line.contains("acid"))
{
int start = line.indexOf(QUOTE);
int stop = line.indexOf(QUOTE, start+1);
protein.add(AminoAcid.getAminoAcidByName(line.substring(start+1, stop)));
}
}
//br.close();
}
catch(IOException ioe)
{
throw new RuntimeException("Error reading protein from file.");
}
finally
{
try
{
br.close();
}
catch(IOException i)
{
throw new RuntimeException("Error reading file.");
}
}
}
catch(FileNotFoundException fnfe)
{
throw new RuntimeException("Error reading protein from file. Could not find file.");
}
return protein;
} |
7aeb8539-9511-4280-b66f-075cfae72a2e | 9 | public final void setPos(int i, int j, boolean flag)
{
if(anim != -1 && Animation.anims[anim].anInt364 == 1)
anim = -1;
if(!flag)
{
int k = i - smallX[0];
int l = j - smallY[0];
if(k >= -8 && k <= 8 && l >= -8 && l <= 8)
{
if(smallXYIndex < 9)
smallXYIndex++;
for(int i1 = smallXYIndex; i1 > 0; i1--)
{
smallX[i1] = smallX[i1 - 1];
smallY[i1] = smallY[i1 - 1];
aBooleanArray1553[i1] = aBooleanArray1553[i1 - 1];
}
smallX[0] = i;
smallY[0] = j;
aBooleanArray1553[0] = false;
return;
}
}
smallXYIndex = 0;
anInt1542 = 0;
anInt1503 = 0;
smallX[0] = i;
smallY[0] = j;
x = smallX[0] * 128 + anInt1540 * 64;
y = smallY[0] * 128 + anInt1540 * 64;
} |
f9976d8b-5c59-428e-9c0d-f089d287ef22 | 8 | public void testPeutMarquerDame(){
Tablier t1 = new Tablier();
t1.initialiserCase();
assertFalse(t1.peutMarquerDame(CouleurCase.BLANC));
assertFalse(t1.peutMarquerDame(CouleurCase.NOIR));
// deplacement de toute les dames blanches
for (int i=0;i<2;i++)
t1.deplacerDame(t1.getListeCase().get(0), t1.getListeCase().get(22));
for (int i=0;i<5;i++)
t1.deplacerDame(t1.getListeCase().get(11), t1.getListeCase().get(21));
for (int i=0;i<3;i++)
t1.deplacerDame(t1.getListeCase().get(16), t1.getListeCase().get(20));
System.out.println("TABLIER : ");
for(int i=0;i<t1.getListeCase().size();i++)
System.out.println(t1.getListeCase().get(i).getPosition()
+" : "+t1.getListeCase().get(i).getCouleurDame()
+" _ "+t1.getListeCase().get(i).getNbDame());
System.out.println("CASE BARRE : ");
for(int i=0;i<t1.getCaseBarre().size();i++)
System.out.println(t1.getCaseBarre().get(i).getPosition()
+" : "+t1.getCaseBarre().get(i).getCouleurDame()
+" _ "+t1.getCaseBarre().get(i).getNbDame());
assertTrue(t1.peutMarquerDame(CouleurCase.BLANC));
assertFalse(t1.peutMarquerDame(CouleurCase.NOIR));
// deplacement de toute les dames noires
t1.initialiserCase();
for (int i=0;i<2;i++)
t1.deplacerDame(t1.getListeCase().get(23), t1.getListeCase().get(1));
for (int i=0;i<5;i++)
t1.deplacerDame(t1.getListeCase().get(12), t1.getListeCase().get(4));
for (int i=0;i<3;i++)
t1.deplacerDame(t1.getListeCase().get(7), t1.getListeCase().get(2));
assertTrue(t1.peutMarquerDame(CouleurCase.NOIR));
assertFalse(t1.peutMarquerDame(CouleurCase.BLANC));
} |
2b3a0fa3-f034-4eb6-af4b-005442ed7d63 | 4 | @Override
protected void drawLine(Graphics2D g, AZeit t1, float posPercent,
float sizePercent)
{
if(posPercent>1 || posPercent<0 || sizePercent>1 || sizePercent<0)
throw new IllegalArgumentException();
g.setStroke(new BasicStroke());
final double angle=timeToAngle(t1);
final double sin=Math.sin(angle);
final double cos=Math.cos(angle);
g.drawLine(
(int)(radius+cos*(1-posPercent)*radius),
(int)(radius+sin*(1-posPercent)*radius),
(int)(radius+cos*(1-posPercent-sizePercent)*radius),
(int)(radius+sin*(1-posPercent-sizePercent)*radius)
);
} |
3923e0a6-00ed-4039-881d-89e71e508f1a | 1 | public void test_DateTime_new_Gaza() {
try {
new DateTime(2007, 4, 1, 0, 0, 0, 0, MOCK_GAZA);
fail();
} catch (IllegalInstantException ex) {
assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0);
}
} |
b5d2a0d7-bca7-47f6-a5a7-73cf12b3674f | 4 | @Override
public boolean onCommand(CommandSender sender, Command cmd,
String commandLabel, String[] args) {
try {
if (sender instanceof Player) {
Player player = (Player) sender;
if (cmd.getName().equalsIgnoreCase("talk")) {
player.sendMessage(ChatColor.GREEN
+ "Welcome to the Hunger Games TalkArea Mod");
player.sendMessage(ChatColor.YELLOW
+ "There are 4 commands; whisper, say, yell, ooc");
player.sendMessage(ChatColor.GREEN
+ "Usage: type in chat [cmd] [message]. e.g. ooc Hello. For the say command you just type your message");
player.sendMessage(ChatColor.RED
+ "whisper"
+ ChatColor.YELLOW
+ ": This will send your text to those within a short range");
player.sendMessage(ChatColor.RED
+ "say"
+ ChatColor.YELLOW
+ ": This will send your text to those within a medium range, for this command you do not append anything");
player.sendMessage(ChatColor.RED
+ "yell"
+ ChatColor.YELLOW
+ ": This will shout out your message to a large distance");
player.sendMessage(ChatColor.RED
+ "ooc"
+ ChatColor.YELLOW
+ ": This will send your message to everyone in the server");
return true;
} else if (cmd.getName().equalsIgnoreCase("welcome")) {
player.sendMessage(ChatColor.YELLOW
+ "Welcome to the Hunger Games");
player.sendMessage(ChatColor.YELLOW
+ "There are 4 Phases to the Hunger Games");
player.sendMessage(ChatColor.YELLOW
+ "During Phase 1 and 3 people can use the "
+ ChatColor.RED + "/timeleft" + ChatColor.YELLOW
+ " command to see how long left");
player.sendMessage(ChatColor.GREEN
+ "Phase 1: Registration : 5 mins");
player.sendMessage(ChatColor.YELLOW
+ "At this stage you are able to use "
+ ChatColor.RED + "/register" + ChatColor.YELLOW
+ " command to signup");
player.sendMessage(ChatColor.GREEN
+ "Phase 2: Preparing : 60 seconds");
player.sendMessage(ChatColor.YELLOW
+ "People who have registered will be teleported into position.");
player.sendMessage(ChatColor.YELLOW
+ "During this phase you cannot move away from your spawn point. You will be killed.");
player.sendMessage(ChatColor.GREEN
+ "Phase 3: Battle : 30 mins");
player.sendMessage(ChatColor.YELLOW
+ "Currently there is no end game code so if more then one person is alive. no one wins and its gameover.");
player.sendMessage(ChatColor.GREEN
+ "Phase 4: Finish : Resets the map and loops back to registration ");
}
return true;
}
} catch (Exception e) {
Log.severe(e.getMessage() + "\n");
e.printStackTrace();
}
return false;
} |
dd1bef6f-0f80-4062-91e8-35d7d34cfc77 | 2 | @Override
public void setCredits(double credits) {
if(credits < 0.5 || credits > 4.0) {
JOptionPane.showMessageDialog(null,
"Error: credits must be in the range 0.5 to 4.0");
System.exit(0);
}
this.credits = credits;
} |
3999ccab-e082-4562-aa12-d1d641ba79ad | 8 | private double closest(Point2D[] pointsByX, Point2D[] pointsByY, Point2D[] aux, int lo, int hi) {
if (hi <= lo) return Double.POSITIVE_INFINITY;
int mid = lo + (hi - lo) / 2;
Point2D median = pointsByX[mid];
// compute closest pair with both endpoints in left subarray or both in right subarray
double delta1 = closest(pointsByX, pointsByY, aux, lo, mid);
double delta2 = closest(pointsByX, pointsByY, aux, mid+1, hi);
double delta = Math.min(delta1, delta2);
// merge back so that pointsByY[lo..hi] are sorted by y-coordinate
Merge.merge(pointsByY, aux, lo, mid, hi);
// aux[0..M-1] = sequence of points closer than delta, sorted by y-coordinate
int M = 0;
for (int i = lo; i <= hi; i++) {
if (Math.abs(pointsByY[i].x() - median.x()) < delta)
aux[M++] = pointsByY[i];
}
// compare each point to its neighbors with y-coordinate closer than delta
for (int i = 0; i < M; i++) {
// a geometric packing argument shows that this loop iterates at most 7 times
for (int j = i+1; (j < M) && (aux[j].y() - aux[i].y() < delta); j++) {
double distance = aux[i].distanceTo(aux[j]);
if (distance < delta) {
delta = distance;
if (distance < bestDistance) {
bestDistance = delta;
best1 = aux[i];
best2 = aux[j];
// StdOut.println("better distance = " + delta + " from " + best1 + " to " + best2);
}
}
}
}
return delta;
} |
c550de57-b8d7-49b9-9701-e1d85268eae1 | 5 | private void drawols(GOut g, Coord sc) {
synchronized (map.grids) {
for (Coord gc : map.grids.keySet()) {
Grid grid = map.grids.get(gc);
for (Overlay lol : grid.ols) {
int id = getolid(lol.mask);
if (visol[id] < 1) {
continue;
}
Coord c0 = gc.mul(cmaps);
drawol2(g, id, c0.add(lol.c1), c0.add(lol.c2), sc);
}
}
}
for (Overlay lol : map.ols) {
int id = getolid(lol.mask);
if (visol[id] < 1) {
continue;
}
drawol2(g, id, lol.c1, lol.c2, sc);
}
g.chcolor();
} |
e9b1eef6-8ad9-45c8-b127-f2e046b21cef | 9 | public void testSentenceParts() throws Exception {
ReadEngine engine = new ReadEngine();
Conversation conversation;
ArrayList<String> predicates = new ArrayList<>();
ArrayList<String> subjects = new ArrayList<>();
for (int i = 0; i < conversationsStory.length; i++) {
engine.readFromDB(conversationsStory[i]);
Assert.assertEquals(0, engine.getErrorsCount());
conversation = engine.getConversation();
predicates.clear();
subjects.clear();
for (Sentence sentence : conversation.getSentences()) {
for (Clause clause : sentence.getClauseList()) {
predicates.add(clause.getPredicate().getWord());
subjects.add(clause.getSubject().getWord());
}
}
/** Checking predicates **/
for (int j = 0; j < sentencePredicates[i].length; j++) {
if (sentencePredicates[i][j] != null && !sentencePredicates[i][j].equals("")) {
Assert.assertEquals(sentencePredicates[i][j], predicates.get(j));
}
}
/** Checking subject **/
for (int j = 0; j < sentenceSubject[i].length; j++) {
if (sentenceSubject[i][j] != null && !sentenceSubject[i][j].equals("")) {
Assert.assertEquals(sentenceSubject[i][j], subjects.get(j));
}
}
}
} |
ed7f9e38-b19b-4e9c-bb99-ba580b6000ab | 5 | public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
out = new StringBuilder();
boolean noFirst = false;
while ((line = in.readLine()) != null && line.length() != 0) {
int n = Integer.parseInt(line);
if (n == 0)
break;
if(noFirst)
out.append("\n");
noFirst = true;
if(!cs(1234, n))
out.append("There are no solutions for "+n+".\n");
}
System.out.print(out);
} |
987a6d1a-5d6d-4462-a043-09b315fb93ea | 6 | public void checkNeighbours(Map map, ArrayList<Node> openlist, ArrayList<Node> closedlist){
openlist.remove(this);
closedlist.add(this);
if(posX == goal.x && posY == goal.y){
finalNode = this;
return;
}
for(Direction dir: directions){
Point newPosition = dir.nextPoint(posX, posY);
if(!map.isSolid(newPosition)){
/*
* if(newPosition.equals(goal)) { finalNode = new Node(this,
* newPosition); break; }
*/
Node newNode = new Node(this, newPosition.x, newPosition.y);
//if(getEqualNode(closedlist, newNode) != null) continue;
Node openNode = getEqualNode(openlist, newNode);
if(openNode != null){
if(openNode.g > newNode.g){
openNode.parent = this;
openNode.calculateG();
openNode.calculateH();
}
}else{
openlist.add(new Node(this, newPosition.x, newPosition.y));
}
}
}
} |
26ff1b7e-4f95-4ad7-b347-995609c860f9 | 4 | private Koordinate getMin(WarMachine warMachine, Koordinate koord,
Ausrichtung ausrichtung) {
switch (ausrichtung) {
case XPLUS:
return koord;
case XMINUS:
return new Koordinate(koord.getX() - warMachine.getLaenge() + 1,
koord.getY() - warMachine.getBreite() + 1);
case YPLUS:
return new Koordinate(koord.getX() - warMachine.getBreite() + 1,
koord.getY());
case YMINUS:
return new Koordinate(koord.getX(), koord.getY()
- warMachine.getLaenge() + 1);
default:
break;
}
return null;
} |
c1f45876-5436-4ef8-b0e4-0b721e4c9a1a | 6 | private static void performStep17(BotState state) {
for (Region opponentBorderingRegion : state.getVisibleMap().getOpponentBorderingRegions(state)) {
List<Region> opponentNeighbors = opponentBorderingRegion.getEnemyNeighbors(state);
List<Region> sortedOpponentNeighbors = RegionValueCalculator.sortRegionsByAttackRegionValue(state,
opponentNeighbors);
for (Region opponentNeighbor : sortedOpponentNeighbors) {
// check whether we attack this neighbor.
AttackTransferMove theMove = null;
for (AttackTransferMove receivingMove : opponentNeighbor.getIncomingMoves()) {
if (receivingMove.getFromRegion().equals(opponentBorderingRegion)) {
theMove = receivingMove;
}
}
if (theMove != null && opponentBorderingRegion.getIdleArmies() > 0) {
theMove.setArmies(theMove.getArmies() + opponentBorderingRegion.getIdleArmies());
}
}
}
} |
9a8c3cb8-d87c-491e-83c4-923368ee344a | 5 | void createExampleWidgets () {
/* Compute the widget style */
int style = getDefaultStyle();
if (horizontalButton.getSelection ()) style |= SWT.HORIZONTAL;
if (verticalButton.getSelection ()) style |= SWT.VERTICAL;
if (smoothButton.getSelection ()) style |= SWT.SMOOTH;
if (borderButton.getSelection ()) style |= SWT.BORDER;
if (indeterminateButton.getSelection ()) style |= SWT.INDETERMINATE;
/* Create the example widgets */
progressBar1 = new ProgressBar (progressBarGroup, style);
} |
b3f28f8c-8457-4fb6-846c-88537fa3a919 | 2 | private static String[] readFile(String file, int lines, String language) throws IOException
{
String encoding = getEncodingForLanguage(language);
BufferedReader in;
if (encoding == null)
in = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
else
in = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
String str;
StringBuilder ret = new StringBuilder();
while ((str = in.readLine()) != null)
{
ret.append(str).append("\n");
}
in.close();
return ret.toString().split("\n");
} |
f8de4dc3-0534-49b8-a2a5-5b361df38814 | 3 | public void dealerStand() {
if (player.ifBusted() == true) {
player.playerBust();
} else if (dealerHand.getHandValue() < player.getHand().getHandValue()) {
dealerLost();
} else if (dealerHand.getHandValue() > player.getHand().getHandValue()) {
dealerWon();
} else {
dealerPush();
}
} |
bd7dcf27-4c0d-4c1d-bfc0-fe865d46f863 | 5 | public void heapIncKey(int indeksi, int arvo) {
if (indeksi >= 0 && indeksi < keko.size()) {
if (arvo > keko.get(indeksi)) {
keko.set(indeksi, arvo);
}
while (indeksi > 0 && keko.get(parent(indeksi)) < arvo) {
int apuluku = keko.get(parent(indeksi));
keko.set(indeksi, apuluku);
keko.set(parent(indeksi), arvo);
indeksi = parent(indeksi);
}
}
} |
813f9d4f-5ef8-4630-a5a0-5bed7c97f624 | 0 | public void alustaIkkuna(int i) {
alustaTaso(i);
SwingUtilities.invokeLater(ikkuna);
} |
35519936-4e64-4275-ae46-1ff20211ba75 | 4 | public LoadImage(String s) {
//img = ImageIO.read(new File(s));
//img = Toolkit.getDefaultToolkit().createImage(s);
img = Toolkit.getDefaultToolkit().createImage(s);
imageTracker = new MediaTracker(this);
imageTracker.addImage(img,0);
if(false == imageTracker.checkID(0))
{
try {
if(Debug.shimmy)System.out.println("loading");
imageTracker.waitForID(0); //This line loads the image
if(Debug.shimmy)System.out.println("loaded");
} catch (InterruptedException e) {
System.out.println("originalImage loading interrupted");
e.printStackTrace();
}
}
} |
1555349a-e9e5-47ed-bcd2-ad3f0d5853cd | 3 | @Override
public void setValue (final List<Value<?>> value) {
if (value == null) {
throw new NullPointerException();
}
this.value = new ArrayList<Value<?>>(value);
} |
38852368-405c-4517-b397-79dacb49ce15 | 8 | public void keyPressed(int k) {
if(k == KeyEvent.VK_LEFT) {
player.setLeft(true);
}
if(k == KeyEvent.VK_RIGHT) {
player.setRight(true);
}
if(k == KeyEvent.VK_UP) {
player.setUp(true);
}
if(k == KeyEvent.VK_DOWN) {
player.setDown(true);
}
if(k == KeyEvent.VK_W) {
player.setJumping(true);
}
if(k == KeyEvent.VK_E) {
player.setGliding(true);
}
if(k == KeyEvent.VK_R) {
player.setScratching();
}
if(k == KeyEvent.VK_F) {
player.setFiring();
}
} |
ad12ce95-bf5d-4a5b-bdcc-5117ff6df7ce | 8 | public final Level loadOnline(String var1, String var2, int var3) {
if(this.progressBar != null) {
this.progressBar.setTitle("Loading level");
}
try {
if(this.progressBar != null) {
this.progressBar.setText("Connecting..");
}
HttpURLConnection var6;
(var6 = (HttpURLConnection)(new URL("http://" + var1 + "/level/load.html?id=" + var3 + "&user=" + var2)).openConnection()).setDoInput(true);
if(this.progressBar != null) {
this.progressBar.setText("Loading..");
}
DataInputStream var7;
if((var7 = new DataInputStream(var6.getInputStream())).readUTF().equalsIgnoreCase("ok")) {
return this.load((InputStream)var7);
} else {
if(this.progressBar != null) {
this.progressBar.setText("Failed: " + var7.readUTF());
}
var7.close();
Thread.sleep(1000L);
return null;
}
} catch (Exception var5) {
var5.printStackTrace();
if(this.progressBar != null) {
this.progressBar.setText("Failed!");
}
try {
Thread.sleep(3000L);
} catch (InterruptedException var4) {
;
}
return null;
}
} |
97fb0a7b-8702-4d79-9b70-6d3b71bbefbc | 8 | short addUtf8(String k)
{
int theIndex = itsUtf8Hash.get(k, -1);
if (theIndex == -1) {
int strLen = k.length();
boolean tooBigString;
if (strLen > MAX_UTF_ENCODING_SIZE) {
tooBigString = true;
} else {
tooBigString = false;
// Ask for worst case scenario buffer when each char takes 3
// bytes
ensure(1 + 2 + strLen * 3);
int top = itsTop;
itsPool[top++] = CONSTANT_Utf8;
top += 2; // skip length
char[] chars = cfw.getCharBuffer(strLen);
k.getChars(0, strLen, chars, 0);
for (int i = 0; i != strLen; i++) {
int c = chars[i];
if (c != 0 && c <= 0x7F) {
itsPool[top++] = (byte)c;
} else if (c > 0x7FF) {
itsPool[top++] = (byte)(0xE0 | (c >> 12));
itsPool[top++] = (byte)(0x80 | ((c >> 6) & 0x3F));
itsPool[top++] = (byte)(0x80 | (c & 0x3F));
} else {
itsPool[top++] = (byte)(0xC0 | (c >> 6));
itsPool[top++] = (byte)(0x80 | (c & 0x3F));
}
}
int utfLen = top - (itsTop + 1 + 2);
if (utfLen > MAX_UTF_ENCODING_SIZE) {
tooBigString = true;
} else {
// Write back length
itsPool[itsTop + 1] = (byte)(utfLen >>> 8);
itsPool[itsTop + 2] = (byte)utfLen;
itsTop = top;
theIndex = itsTopIndex++;
itsUtf8Hash.put(k, theIndex);
}
}
if (tooBigString) {
throw new IllegalArgumentException("Too big string");
}
}
return (short)theIndex;
} |
61fc8040-17a1-4088-a0a0-41286b87505f | 1 | private String buildJsonUsername() {
Iterator<String> iterator = getUserName().iterator();
JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
while (iterator.hasNext()) {
jsonArrayBuilder.add((String) iterator.next());
}
System.out.println("User Array " + Json.createObjectBuilder().add("users", jsonArrayBuilder).build().toString());
return Json.createObjectBuilder().add("users", jsonArrayBuilder).build().toString();
} |
67b0498d-fee0-4180-a18b-5c564ecf011d | 6 | public ArrayList<ArrayList<ArrayList<String>>> erstelleBlockelementListAll(
ArrayList<Umlaufplan> umlaufplanliste) {
ArrayList<ArrayList<ArrayList<String>>> ListPlaeneGesamt = new ArrayList<ArrayList<ArrayList<String>>>();
int zaehler = 0;
for (int i = 0; i < umlaufplanliste.size(); i++) {
ArrayList<ArrayList<String>> ListPlan = new ArrayList<ArrayList<String>>();
zaehler = 0;
for (int j = 0; j < umlaufplanliste.get(i).getUmlauf().size(); j++) {
ArrayList<String> serviceJourneyList = new ArrayList<String>();
for (int j2 = zaehler; j2 < umlaufplanliste.get(i)
.getFahrtZuUmlauf().size(); j2++) {
int blockID = umlaufplanliste.get(i).getUmlauf().get(j)
.getId();
if (umlaufplanliste.get(i).getFahrtZuUmlauf().get(j2)
.getElementType() == 1) {
if (umlaufplanliste.get(i).getFahrtZuUmlauf().get(j2)
.getBlockID() == (blockID)) {
serviceJourneyList.add(umlaufplanliste.get(i)
.getFahrtZuUmlauf().get(j2)
.getServiceJourneyID());
} else {
ListPlan.add(serviceJourneyList);
break;
}
}
zaehler++;
if (zaehler == umlaufplanliste.get(i).getFahrtZuUmlauf()
.size()) {
ListPlan.add(serviceJourneyList);
}
}
}
ListPlaeneGesamt.add(ListPlan);
}
return ListPlaeneGesamt;
} |
3b06cfa2-4cf0-4ac6-961a-5eea7b6abf4e | 5 | public boolean intersectWith(BlockArea ba) {
if (this.l == null || ba.getLocation() == null) return false;
for (BlockPosition bp : blocks) {
BlockPosition bp1 = bp.bind(l);
for (BlockPosition bp2 : ba.blocks) {
if (bp2.bind(ba.l).equals(bp1)) return true;
}
}
return false;
} |
6a49cec6-fd69-44b1-b000-6391990a0a07 | 1 | public static void apropos() {
if (fenetreApropos != null) {
fenetreApropos.dispose();
}
fenetreApropos = new WindowApropos();
} |
4c78481b-e3c3-4e89-906a-5a31884c020c | 7 | int setHandValue()
{
int handValue = this.handType * 0x100000;
int i = 0;
int n = 0x10000;
ArrayList < PlayingCard > reverseUsedList = this.usedCards;
Collections.sort( reverseUsedList, PlayingCard.Comparators.ACEHIGH );
Collections.reverse( reverseUsedList );
while ( i < reverseUsedList.size() )
{
int currentNumber = reverseUsedList.get( i ).getNumber();
if ( currentNumber == 1 && !( this.checkForStraightAceLow() ) )
{
handValue += 0xe * n;
}
else
{
handValue += currentNumber * n;
}
i++;
n /= 0x10;
}
if ( this.unusedCards != null )
{
ArrayList < PlayingCard > reverseUnusedList = this.unusedCards;
Collections.sort( reverseUnusedList, PlayingCard.Comparators.ACEHIGH );
Collections.reverse( reverseUnusedList );
i = 0;
while ( i < reverseUnusedList.size() )
{
int currentNumber = reverseUnusedList.get( i ).getNumber();
if ( currentNumber == 1 && !( this.checkForStraightAceLow() ) )
{
handValue += 0xe * n;
}
else
{
handValue += currentNumber * n;
}
i++;
n /= 0x10;
}
}
this.value = handValue;
return handValue;
} |
9aebf881-1684-456e-956c-2520f78ab3e2 | 4 | private void loadText(){
textPane.setText("");
StyledDocument doc = textPane.getStyledDocument();
for ( RecipeSection section: recipe.getSections() ){
try{
String headline = section.getHeadline();
if( headline != null && ! headline.equals("") ){
doc.insertString(doc.getLength(), headline + "\n", doc.getStyle("bold"));
}
doc.insertString(doc.getLength(), section.getText() + "\n\n", null);
} catch (BadLocationException e){
//As long as we use doc.getLength() this exception should not be possible
e.printStackTrace();
}
}
textPane.setCaretPosition(0);
} |
d154b983-440c-45bd-8bb0-f4d15bbd599d | 4 | private void processOpenFrame(int channelPtr,
int ctype,
int flag,
ByteBuffer data) {
OpenRequest request;
Channel channel;
synchronized (this) {
request = m_pendingOpenRequest;
}
if (request == null) {
destroy(new ChannelError("The server sent a invalid open frame"));
return;
}
channel = request.getChannel();
synchronized (this) {
m_pendingOpenRequest = null;
}
if (flag == Frame.OPEN_ALLOW) {
m_openChannels.put(channelPtr, channel);
if (HydnaDebug.HYDNADEBUG) {
DebugHelper.debugPrint("Connection", channelPtr, "A new channel was added");
DebugHelper.debugPrint("Connection", channelPtr, "The size of openChannels is now " + m_openChannels.size());
}
channel.openSuccess(channelPtr, ctype, data);
return;
}
if (HydnaDebug.HYDNADEBUG) {
DebugHelper.debugPrint("Connection", channelPtr, "The server rejected the open request, errorcode " + flag);
}
ChannelError error = ChannelError.fromOpenError(flag, ctype, data);
channel.destroy(error);
} |
601cb133-dc70-469b-865c-def10f0370a7 | 0 | @Test
public void simpleWithWanFilter() throws Exception {
final byte[] input = new byte[15];
final byte[] zeroes = new byte[input.length];
Arrays.fill(zeroes, (byte) 0);
final int pipe_buf_size = 20;
new Random().nextBytes(input);
final Properties[] filter_configs = new Properties[]{
new Properties(),
new Properties(),
};
final ByteArrayOutputStream output = new ByteArrayOutputStream(input.length);
final long latency = 1000;
filter_configs[0].setProperty("type", "Zero");
filter_configs[1].setProperty("type", "Wan");
filter_configs[1].setProperty("median_latency", "" + latency);
final ConnectionProcessorPipe pipe = new ConnectionProcessorPipe(new ByteArrayInputStream(input),
new FilterFactory(filter_configs).getInstances(new MockConnectionProcessor()),
output,
new DevnullLogger(),
pipe_buf_size);
pipe.run();
print(input, "input");
print(output.toByteArray(), "output");
Assert.assertArrayEquals(zeroes, output.toByteArray());
final Map<String, Long> stat = pipe.getStatistics();
Assert.assertNull(pipe.getException());
Assert.assertEquals(stat.get("exception_at").intValue(), 0);
Assert.assertEquals(stat.get("bytes_in").intValue(), input.length);
Assert.assertEquals(stat.get("bytes_out").intValue(), input.length);
Assert.assertEquals(stat.get("read_count").intValue(), (pipe_buf_size / input.length) + 1); // one read results in -1
Assert.assertEquals(stat.get("write_count").intValue(), pipe_buf_size / input.length);
Assert.assertEquals(stat.size(), 9);
Assert.assertTrue(Math.abs(stat.get("read_ms").intValue()) * 1.00 >= latency*0.90);
Assert.assertTrue(stat.get("write_ms").longValue() < 10);
Assert.assertTrue(stat.get("ended_at").longValue() - stat.get("began_at").longValue() * 1.00 >= latency * 0.90);
} |
5ff689a0-f865-4f22-8829-41607334989e | 4 | public Client(String ip,String playerName,String tankName,int tankSpeed,int bulletSpeed,int bulletDamage){
Client.ip = ip;
imageInit();
this.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
Dimension scrSize=Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(scrSize.width/2-SCREEN_WIDTH/2, scrSize.height/2-SCREEN_HEIGHT/2);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.addKeyListener(this);
this.addWindowListener(this);
this.setVisible(true);
try {
socket = new Socket(ip, SERVER_PORT);
// ois = new ObjectInputStream(socket.getInputStream());
// oos = new ObjectOutputStream(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
id = Integer.parseInt(in.readLine());
System.out.println("ӷյid="+id);
this.setTitle("[´]̹˴սͻ ["+id+"]");
//̹˳ʼ
clientTank = new Tank(randomPoint(), id,playerName);
if( tankName.trim().equals("OZTANK") ){
clientTank.setType(Tank.OZ_TANK);
}
this.tankSpeed = tankSpeed;
this.bulletSpeed = bulletSpeed;
this.bulletDamage = bulletDamage;
System.out.println(clientTank);
} catch (UnknownHostException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "ӷȷǽѹرգ");
System.exit(0);
System.out.println("ӳ1");
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "ӷȷǽѹرգ");
System.exit(0);
System.out.println("ӳ2");
} catch (NumberFormatException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "ӷȷǽѹرգ");
System.exit(0);
System.out.println("ӳ3");
}
} |
bf3fa051-0c35-4d43-8e40-bd79fe884136 | 2 | public static Float parseSpeed(String data) {
String[] lines = data.split("\n");
for (String line : lines) {
String[] parts = line.split(":", 2);
if (parts[0].equals("s")) {
return Float.parseFloat( parts[1].replace(",",".") );
}
}
return null;
} |
0a673e2f-d65d-41fc-bae8-f5823823d415 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Frm_CadLinks.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frm_CadLinks.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frm_CadLinks.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frm_CadLinks.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Frm_CadLinks().setVisible(true);
}
});
} |
38aa7d68-fc18-4b05-9022-0166f7c20fea | 8 | public void run() {
try {
InputStream stream = socket.getInputStream();
connected=true;
while(connected){
int byteCount = stream.available();
if(byteCount>0){
logger.debug(byteCount+" bytes are available for reading");
byte[] oldByteBuffer = byteBuffer;
//int oldByteBufferLength = oldByteBuffer==null?0:oldByteBuffer.length;
int currentBufferLength = oldByteBuffer==null?0:oldByteBuffer.length;
byteBuffer = new byte[currentBufferLength+byteCount];
byte[] newBytes = new byte[byteCount];
stream.read(newBytes, 0, byteCount);
logger.debug(new String(newBytes, Charset.forName("UTF-8")));
logger.debug("old byte buffer length: "+currentBufferLength);
for (int i=0;i<currentBufferLength;i++){
byteBuffer[i]=oldByteBuffer[i];
}
int newBufferLength=newBytes.length;
logger.debug(new String(byteBuffer, Charset.forName("UTF-8")));
for (int i=0;i<newBufferLength;i++){
byteBuffer[currentBufferLength+i]=newBytes[i];
}
logger.debug(new String(byteBuffer, Charset.forName("UTF-8")));
if(websocketImpl==null){
handshake();
}else{
byte[] unusedBytes = websocketImpl.processFrame(byteBuffer);
byteBuffer = unusedBytes;
}
//logger.debug(new String(byteBuffer));
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (IOException ioe) {
logger.debug("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
} |
367b68ee-4715-48b2-8d61-0ae79c0bff3e | 4 | @Override
public ReturnStruct parse(String[] lines) throws InterpreterException {
int i = 0;
code_ = lines;
Block b = null;
while (i < lines.length) {
String line = Parser.clean(lines[i]);
String copy[] = new String[lines.length - i];
System.arraycopy(lines, i, copy, 0, copy.length);
ReturnStruct rs = Parser.parseLine(this, line, copy, getLine() + i);
if (rs.block != null) {
rs.block.setLine(i + 1 + getLine());
if (b == null) {
b = rs.block;
this.setBody(b);
} else {
b.setNext(rs.block);
b = rs.block;
}
}
i += rs.lines;
if (b instanceof ENDBlock) {
this.setNext(b);
break;
}
}
return new ReturnStruct(this, i + 1);
} |
c83ec210-4650-43c4-a3c4-cc3f2cd6d11b | 1 | public MethodAnalyzer getMethodAnalyzer() {
ClassAnalyzer ana = getClassAnalyzer();
if (ana == null)
return null;
return ana.getMethod(methodName, methodType);
} |
339707e5-20b2-4a21-b4b4-951bccbcbe8c | 3 | @Override
public void run() {
TcpSender packetSender = new TcpSender();
while (true) {
// A spin wait is super resource heavy
// TODO: not this
while (ccl.isEmpty()) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Packet p = ccl.remove();
String ip = MeshNetworkManager.getIPForClient(p.getMac());
packetSender.sendPacket(ip, Configuration.GO_RECEIVE_PORT, p.serialize());
}
} |
ade925c4-2c0d-4ac5-a2e0-4d02314c360d | 7 | public File getFile()
{
if (file == null)
{
String searchPath = Util.minecraftDirectory + "/libraries/";
String[] pathSplit = name.split(":");
pathSplit[0] = pathSplit[0].replace('.', '/');
for (int i = 0; i < pathSplit.length; i++)
{
searchPath += pathSplit[i] + "/";
}
File searchPathFile = new File(searchPath);
if (!searchPathFile.exists())
{
Log.w("Failed attempt to load library at: " + searchPathFile);
return null;
}
File[] libraryFiles = searchPathFile.listFiles();
for (int i = 0; i < libraryFiles.length; i++)
{
String extension = "";
String fileName = libraryFiles[i].getName();
int q = fileName.lastIndexOf('.');
if (q > 0)
{
extension = fileName.substring(q + 1);
}
if (extension.equals("jar"))
{
file = libraryFiles[i];
}
}
if (file == null)
{
Log.w("Attempted to search for file at path: " + searchPath + " but found nothing. Skipping.");
}
}
return file;
} |
db76e406-6b61-4f35-9f99-79ac4c682806 | 0 | public String GenerateLinkID(){
return DateUtil.GetTimeString() + getTTenNum();
} |
c3dd1786-f59f-4164-b6de-c1e52869f740 | 1 | private void loadDriver()
{
try
{
d = (Driver)Class.forName(driver).newInstance();
DriverManager.registerDriver(d);
}
catch (Exception e)
{
System.out.println("Error loading database driver: " + e.toString());
}
} |
c5d9c2a5-cde9-4d87-905f-f02a9fdcde1c | 8 | @Override
public void paint(Graphics g, RsTransform gt){
int i, j;
int ix, iy, iRadius;
int w, h;
double [] xPlacement = null;
double [] yPlacement = null;
int [] xWall;
int [] yWall;
xWall = new int[6];
yWall = new int[6];
// TO DO: once I settle on decent values for the placement
// I need to hard-wire these values as a static final
// rather than computing them this way. incidentally,
// there's nothing particularly virtuous about these values,
// they're mainly just the result of trial and error.
if(xPlacement==null){
xPlacement = new double[6];
yPlacement = new double[6];
xPlacement[0] = 1;
yPlacement[0] = 0;
xPlacement[1] = Math.cos(60*Math.PI/180)*1.2;
yPlacement[1] = Math.sin(45*Math.PI/180)*1.2;
xPlacement[2] = Math.cos(135*Math.PI/180)*1.2;
yPlacement[2] = Math.sin(135*Math.PI/180)*1.2;
xPlacement[3] = Math.cos(-135*Math.PI/180)*1.2;
yPlacement[3] = Math.sin(-135*Math.PI/180)*1.2;
xPlacement[4] = Math.cos(-60*Math.PI/180)*1.2;
yPlacement[4] = Math.sin(-45*Math.PI/180)*1.2;
xPlacement[5] = xPlacement[0];
yPlacement[5] = yPlacement[0];
}
RsPoint p0, p1;
p0=gt.map(x, y);
p1=gt.map(x+radius, y);
ix=(int)(p0.x+0.5);
iy=(int)(p0.y+0.5);
iRadius=(int)(Math.abs(p1.x-p0.x)+0.5);
g.setColor(lineColor);
if(iRadius>0){
double ax, ay; // the "x basis vector"
double bx, by; // the "y basis vector", negated due to pixel-upside-down factor
double s;
s = iRadius;
ax = s*Math.cos(orientation);
ay = -s*Math.sin(orientation);
bx = s*Math.cos(orientation+Math.PI/2);
by = -s*Math.sin(orientation+Math.PI/2);
if(lineWidth>=2 && iRadius>4*lineWidth){
for(j=0; j<2; j++){
for(i=0; i<6; i++){
xWall[i] = ix+(int)(xPlacement[i]*ax+yPlacement[i]*bx+0.5);
yWall[i] = iy+(int)(xPlacement[i]*ay+yPlacement[i]*by+0.5);
}
g.fillPolygon(xWall, yWall, 6);
g.setColor(Color.white);
s = iRadius-lineWidth;
ax = s*Math.cos(orientation);
ay = -s*Math.sin(orientation);
bx = s*Math.cos(orientation+Math.PI/2);
by = -s*Math.sin(orientation+Math.PI/2);
}
}else{
for(i=0; i<6; i++){
xWall[i] = ix+(int)(xPlacement[i]*ax+yPlacement[i]*bx+0.5);
yWall[i] = iy+(int)(xPlacement[i]*ay+yPlacement[i]*by+0.5);
}
g.drawPolygon(xWall, yWall, 6);
}
g.setColor(lineColor);
if(label==null){
g.drawLine(ix, iy-4, ix, iy+4);
g.drawLine(ix-4, iy, ix+4, iy);
}else{
FontMetrics fontMetrics = g.getFontMetrics(g.getFont());
w=fontMetrics.stringWidth(label);
h=fontMetrics.getAscent();
g.drawString(label, ix-w/2, iy+h/2);
}
}
} |
01642dd3-1171-401c-bcb5-0a7ed55c2daa | 0 | private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
System.exit(0);
}//GEN-LAST:event_formWindowClosed |
de654018-7fe6-4849-a58d-824ef5d1c5c4 | 2 | public void testPropertyCompareToHour() {
LocalTime test1 = new LocalTime(TEST_TIME1);
LocalTime test2 = new LocalTime(TEST_TIME2);
assertEquals(true, test1.hourOfDay().compareTo(test2) < 0);
assertEquals(true, test2.hourOfDay().compareTo(test1) > 0);
assertEquals(true, test1.hourOfDay().compareTo(test1) == 0);
try {
test1.hourOfDay().compareTo((ReadablePartial) null);
fail();
} catch (IllegalArgumentException ex) {}
DateTime dt1 = new DateTime(TEST_TIME1);
DateTime dt2 = new DateTime(TEST_TIME2);
assertEquals(true, test1.hourOfDay().compareTo(dt2) < 0);
assertEquals(true, test2.hourOfDay().compareTo(dt1) > 0);
assertEquals(true, test1.hourOfDay().compareTo(dt1) == 0);
try {
test1.hourOfDay().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
} |
f4893961-09bc-406c-8c93-0bfb86996ec5 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CreateQuestionFRM.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CreateQuestionFRM.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CreateQuestionFRM.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CreateQuestionFRM.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CreateQuestionFRM().setVisible(true);
}
});
} |
f5725a7b-4488-42ec-a401-0ccee723813f | 4 | public static void shutdown() {
boolean gotSQLExc = false;
try {
try{
Class.forName(DRIVER_NAME);
}catch (Exception e) {
//Nothing
}
DriverManager.getConnection(SHUTDOWN_URL);
} catch (SQLException se) {
if ( se.getSQLState().equals("XJ015") ) {
gotSQLExc = true;
}
}
if (!gotSQLExc) {
Loggin.logConnectionFactory("embedded database did not shut down normally");
} else {
Loggin.logConnectionFactory("embedded database shut down normally");
}
} |
ecb08b19-9f58-4779-99e1-c9affa974abd | 5 | public void remove(){
if (current == null)
throw new NoSuchElementException();
if (current == first){
first = first.link;
current = (LinkedListNode<T>) first;
previous = null;
if (first == null)
last = null;
}else{
previous.link = current.link;
if (current == last)
{
last = first;
while (last.link != null)
last = last.link;
}
current = current.link;
}
count--;
} |
c0785abb-7164-49bb-8152-3c4f3f7b936f | 8 | @Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:
return listpharmacie.get(rowIndex).getId_pharmacie();
case 1:
return listpharmacie.get(rowIndex).getNom_pharmacie();
case 2:
return listpharmacie.get(rowIndex).getAdresse_pharmacie();
case 3:
return listpharmacie.get(rowIndex).getMail_pharmacie();
case 4:
return listpharmacie.get(rowIndex).getTelephone_pharmacie();
case 5:
return listpharmacie.get(rowIndex).getNumero_patente();
case 6:
return listpharmacie.get(rowIndex).getGouvernaurat();
case 7:
return listpharmacie.get(rowIndex).getJour_de_garde();
default:
return null;
}
} |
e925ab04-a149-4cea-9f81-287efaeb592b | 3 | public void paintExpBar(Graphics g)
{
g.setColor(Color.CYAN);
//g.drawImage(battleImages[4],415,385,150,12,this);
if(allowedToPaintExp)
{
int prevLev=Battle.getLevel(userSelected)-1;
int nextLev=prevLev+1;
if(nextLev>100)
nextLev=100;
int expOver=Battle.getExp(userSelected)-(prevLev*prevLev*prevLev);
int expBetween=(nextLev*nextLev*nextLev)-(prevLev*prevLev*prevLev);
double percent = (double) expOver / (double) expBetween;
double placeHolder = percent * 174.0;
int lengthBar = (int) placeHolder;
if(lengthBar>174)
lengthBar=174;
g.fillRect(406,391,lengthBar,6);
}
} |
5726edef-060a-4563-b242-7f9944051095 | 9 | private void saveConnections(){
HashSet<String> roomSet = new HashSet<String>();
ExitDirection dir = null;
String rooms = "";
String connections = "";
String xml = "<?xml version=\"1.0\"?>\n<game name=\"";
xml = xml + name.getText()+"\">\n<description>\n\"";
xml = xml + desc.getText()+"\"\n</description>\n";
xml = xml + "<rooms>\n";
for(int i=0; i<buildPanel.getComponentCount(); i++){
if(i%3==0){
JTextField room1 = (JTextField)buildPanel.getComponent(i);
connections = connections + "<connect>\n<room1 name=\""+room1.getText()+"\">\n";
roomSet.add(room1.getText());
}else if(i%3==1){
JComboBox<String> direc = (JComboBox<String>)buildPanel.getComponent(i);
String direction = direc.getSelectedItem().toString();
dir = ExitDirection.parse(direction);
connections = connections + "<exit type=\""+dir+"\">\n";
connections = connections + "</exit>\n</room1>\n";
}else{
ExitDirection dirRe = null;
switch(dir){
case north:
dirRe = ExitDirection.south;
break;
case south:
dirRe = ExitDirection.north;
break;
case east:
dirRe = ExitDirection.west;
break;
case west:
dirRe = ExitDirection.east;
break;
}
JTextField room2 = (JTextField)buildPanel.getComponent(i);
connections = connections + "<room2 name=\""+room2.getText()+"\">\n";
connections = connections + "<exit type=\""+dirRe.toString()+"\">\n";
connections = connections + "</exit>\n</room2>\n</connect>\n";
roomSet.add(room2.getText());
}
}
for (String s:roomSet){
rooms = rooms + "<room>res/game/"+s+".xml</room>\n";
}
xml = xml + rooms;
xml = xml + "</rooms>\n<connections>\n";
xml = xml + connections;
xml = xml + "</connections>\n";
xml = xml + "<players>\n<player sprite=\"res/SingleGeorge.png\" startRoom=\"Outside\">\n<health>20</health>\n<attack>1</attack>\n<defence>1</defence>\n<xloc>75</xloc>\n<yloc>150</yloc>\n</player>\n</players>\n";
xml = xml + "</game>\n";
BufferedWriter out;
try{
out = new BufferedWriter(new FileWriter("res/game/Game.xml"));
out.write(xml);
out.close();
}catch (IOException e){
return;
}
} |
5193e5b9-34e8-408e-b616-5129ac9c2823 | 8 | public static String unescapeTokenString(String token, char escapechar, boolean upcaseP) {
{ int nofescapes = 0;
int cursor = 0;
int cursor2 = 0;
int size = token.length();
StringBuffer result = null;
boolean escapeP = false;
while (cursor < size) {
if (token.charAt(cursor) == escapechar) {
nofescapes = nofescapes + 1;
cursor = cursor + 1;
}
cursor = cursor + 1;
}
if (nofescapes == 0) {
return (token);
}
result = Stella.makeRawMutableString(size - nofescapes);
cursor = 0;
while (cursor < size) {
if ((token.charAt(cursor) == escapechar) &&
(!escapeP)) {
escapeP = true;
}
else if (upcaseP &&
(!escapeP)) {
edu.isi.stella.javalib.Native.mutableString_nthSetter(result, (Stella.$CHARACTER_UPCASE_TABLE$.charAt(((int) (token.charAt(cursor))))), cursor2);
cursor2 = cursor2 + 1;
}
else {
edu.isi.stella.javalib.Native.mutableString_nthSetter(result, (token.charAt(cursor)), cursor2);
escapeP = false;
cursor2 = cursor2 + 1;
}
cursor = cursor + 1;
}
return (result.toString());
}
} |
833e6c55-f6d8-4a90-add1-78fbd52887f6 | 6 | final int method1187(String string, boolean bool, int i,
RasterToolkit[] class105s) {
try {
anInt1984++;
int i_22_
= method1188(string, new int[] { i },
Class186.aStringArray2494, (byte) 87, class105s);
int i_23_ = 0;
if (bool != false)
((BitmapFont) this).anInt1988 = -58;
for (int i_24_ = 0; (i_24_ ^ 0xffffffff) > (i_22_ ^ 0xffffffff);
i_24_++) {
int i_25_ = method1186(Class186.aStringArray2494[i_24_],
class105s, false);
if (i_25_ > i_23_)
i_23_ = i_25_;
}
return i_23_;
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("oea.K("
+ (string != null ? "{...}"
: "null")
+ ',' + bool + ',' + i + ','
+ (class105s != null ? "{...}"
: "null")
+ ')'));
}
} |
Subsets and Splits