method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
78efb85f-1616-4fc1-891a-822df6b4d194
| 4
|
public boolean toggleInitWithMouse(MouseEvent mouse) {
Tool tool = GUI.controls.getTool();
Object o = getObject(mouseGetX(mouse), mouseGetY(mouse), tool);
if (o == null)
return false;
if (o instanceof RandomInit) {
((RandomInit) o).toggleInitial();
return true;
} else if (o instanceof Vertex) {
if (player.state == RunState.stopped) {
((Vertex) o).toggleInitial();
return true;
}
}
return false;
}
|
f3b47956-cd12-45ae-9282-14ebc0623e5d
| 5
|
public static boolean getBooleanProperty(Properties properties, Object key) {
String string = (String)properties.get(key);
if(string == null) {
System.err.println("WARN: couldn't find boolean value under '" +
key + "'");
return false;
}
if(string.toLowerCase().equals("true") ||
string.toLowerCase().equals("on") ||
string.toLowerCase().equals("yes") ||
string.toLowerCase().equals("1"))
return true;
else
return false;
}
|
f4141b67-d62d-4a73-bea8-af86fbd7507f
| 2
|
private void loginSession(String address, int port, String username, String password) {
msgSocket = new MessageSocket(address, port);
ServiceCommands service = new ServiceCommands(msgSocket);
AccessControlCommands access = new AccessControlCommands(msgSocket);
TransferParameterCommands transfer = new TransferParameterCommands(msgSocket);
OptionalCommands optional = new OptionalCommands(msgSocket);
ServerMessagesAnswer servAnsw = new ServerMessagesAnswer(msgSocket);
/*
* initialize ftp-connection
*/
msgSocket.startSocket();
access.sendUserName(username);
servAnsw.readInputStream();
access.sendPassword(password);
servAnsw.readInputStream();
service.sendSystem();
servAnsw.readInputStream();
service.sendFEAT();
try {
Thread.sleep(1000); // wait for server answere
} catch (InterruptedException e1) {
e1.printStackTrace();
}
servAnsw.readInputStream();
service.sendPrintWorkingdirectory();
servAnsw.readInputStream();
transfer.sendPASV();
ServerDataAnswer dataMsg = new ServerDataAnswer(msgSocket);
try {
dataMsg.readPasvAnswer();
} catch (PassivModeException e) {
e.printStackTrace();
}
DataSocket data = new DataSocket(dataMsg.getRETURN_IP(),
dataMsg.getRETURN_PORT());
data.startSocket();
service.sendLIST(); // server sends a port
servAnsw.readInputStream();
//dataMsg.awaitsLISTanswer();
servAnsw.readInputStream();
FtpServiceComImpl fserver = new FtpServiceComImpl(data, dataMsg, msgSocket);
UserInterface userInterface = new UserInterface(fserver,msgSocket);
userInterface.Interface();
System.out.println("Client: Closing Connection");
msgSocket.closeMessageSocket();
data.closeDataSocket();
}
|
600bae65-cd17-455c-a493-5a87323f30c3
| 1
|
public static byte[] downloadFile(String url) throws IOException {
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
connection = (HttpURLConnection)new URL(url).openConnection();
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setConnectTimeout(5 * 1000);
connection.setAllowUserInteraction(false);
connection.setRequestProperty("Connection", "close");
inputStream = new BufferedInputStream(connection.getInputStream());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
IOUtils.copy(inputStream, outputStream);
return outputStream.toByteArray();
}
finally {
IOUtils.closeQuietly(inputStream);
if (connection != null) {
connection.disconnect();
}
}
}
|
63c5b7a4-d1b3-4898-b770-c0139f9c0e51
| 2
|
public void mu() {
System.out.println("Enter range of numbers to print their multiplication table");
a = in.nextInt();
b = in.nextInt();
for (c = a; c <= b; c++) {
System.out.println("Multiplication table of " + c);
for (d = 1; d <= 10; d++) {
System.out.println(c + "*" + d + " = " + (c * d));
}
}
}
|
55b6b17a-ccde-4da5-8af9-2d31dc03d1dc
| 8
|
public boolean matches(InventoryCrafting var1) {
ArrayList var2 = new ArrayList(this.recipeItems);
for(int var3 = 0; var3 < 3; ++var3) {
for(int var4 = 0; var4 < 3; ++var4) {
ItemStack var5 = var1.getStackInRowAndColumn(var4, var3);
if(var5 != null) {
boolean var6 = false;
Iterator var7 = var2.iterator();
while(var7.hasNext()) {
ItemStack var8 = (ItemStack)var7.next();
if(var5.itemID == var8.itemID && (var8.getItemDamage() == -1 || var5.getItemDamage() == var8.getItemDamage())) {
var6 = true;
var2.remove(var8);
break;
}
}
if(!var6) {
return false;
}
}
}
}
return var2.isEmpty();
}
|
8e975e72-9cca-4899-82fb-7d86de076c9c
| 1
|
public void analyze() {
while (!toAnalyze.isEmpty()) {
Identifier ident = (Identifier) toAnalyze.iterator().next();
toAnalyze.remove(ident);
ident.analyze();
}
}
|
be088d54-762c-4b85-9caa-1b8a9bf370e2
| 0
|
public Turn(direction lr, int state) {
this.lr = lr;
this.state = state;
}
|
7bbf076c-a94e-49dc-88e1-5c9fd44cb833
| 1
|
@Override
public List<Integer> update(Criteria beans, Criteria criteria, GenericUpdateQuery updateGeneric, Connection conn) throws DaoQueryException {
List paramList1 = new ArrayList<>();
List paramList2 = new ArrayList<>();
StringBuilder sb = new StringBuilder(UPDATE_QUERY);
String queryStr = new QueryMapper() {
@Override
public String mapQuery() {
Appender.append(DAO_ID_COUNTRY, DB_DIRCOUNTRY_ID_COUNTRY, criteria, paramList1, sb, COMMA);
sb.append(WHERE);
Appender.append(DAO_ID_DIRECTION, DB_DIRCOUNTRY_ID_DIRECTION, beans, paramList2, sb, AND);
return sb.toString();
}
}.mapQuery();
paramList1.addAll(paramList2);
try {
return updateGeneric.sendQuery(queryStr, paramList1.toArray(), conn);
} catch (DaoException ex) {
throw new DaoQueryException(ERR_DIR_COUNTRY_UPDATE, ex);
}
}
|
6621b9b2-9f1f-4571-9cd7-3930d8c46c83
| 1
|
@Override
public void initTrans() throws Exception {
try {
oConexionMySQL.setAutoCommit(false);
} catch (SQLException e) {
throw new Exception("Mysql.initTrans: Error al iniciar transacci�n: " + e.getMessage());
}
}
|
85b97f50-604a-422c-b796-5b7070d0453a
| 1
|
public void test_other() throws Exception {
assertEquals(1, DateTimeFieldType.class.getDeclaredClasses().length);
Class cls = DateTimeFieldType.class.getDeclaredClasses()[0];
assertEquals(1, cls.getDeclaredConstructors().length);
Constructor con = cls.getDeclaredConstructors()[0];
Object[] params = new Object[] {
"other", new Byte((byte) 128), DurationFieldType.hours(), DurationFieldType.months()};
con.setAccessible(true); // for Apache Harmony JVM
DateTimeFieldType type = (DateTimeFieldType) con.newInstance(params);
assertEquals("other", type.getName());
assertSame(DurationFieldType.hours(), type.getDurationType());
assertSame(DurationFieldType.months(), type.getRangeDurationType());
try {
type.getField(CopticChronology.getInstanceUTC());
fail();
} catch (InternalError ex) {}
DateTimeFieldType result = doSerialization(type);
assertEquals(type.getName(), result.getName());
assertNotSame(type, result);
}
|
6b08fa19-e7f3-4791-a7ef-566a7ea98e3c
| 4
|
@Override
public Item generateRandomStartItem(IGameMap game) {
Item[] items = game.getStartItems().toArray(new Item[game.getStartItems().size()]);
for (int i = 0; i < items.length; i++) {
for (Item item : game.getItemsOnMap()) {
if(item.getX() != items[i].getX() && item.getY() != items[i].getY())
return new Item(item.getX(), item.getY(), item.getType());
}
}
return null;
}
|
ee2aff30-cafc-429f-b3b2-f4ad79c80971
| 1
|
private VideoListVO addSearchMessageToVO(VideoListVO videoListVO, Locale locale, String actionMessageKey, Object[] args) {
if (StringUtils.isEmpty(actionMessageKey)) {
return videoListVO;
}
videoListVO.setSearchMessage(messageSource.getMessage(actionMessageKey, args, null, locale));
return videoListVO;
}
|
c7c0f07e-c080-4f15-b55f-02a2b677d230
| 7
|
public Vector<Item> resourceHere(Room R, int material)
{
final Vector<Item> here=new Vector<Item>();
for(int i=0;i<R.numItems();i++)
{
final Item I2=R.getItem(i);
if((I2!=null)
&&(I2.container()==null)
&&(I2 instanceof RawMaterial)
&&(((I2.material()&RawMaterial.RESOURCE_MASK)==material)
||(((I2.material())&RawMaterial.MATERIAL_MASK)==material))
&&(!CMLib.flags().isEnchanted(I2)))
here.addElement(I2);
}
return here;
}
|
b4b7b865-096a-4718-824c-99bad02c71c5
| 9
|
synchronized Hashtable getProperties()
{
if ((props == null) && (getText() != null))
{
Hashtable props = new Hashtable();
int off = 0;
while (off < getText().length)
{
// length of the next key value pair
int len = getText()[off++] & 0xFF;
if ((len == 0) || (off + len > getText().length))
{
props.clear();
break;
}
// look for the '='
int i = 0;
for (; (i < len) && (getText()[off + i] != '='); i++)
{
;
}
// get the property name
String name = readUTF(getText(), off, i);
if (name == null)
{
props.clear();
break;
}
if (i == len)
{
props.put(name, NO_VALUE);
}
else
{
byte value[] = new byte[len - ++i];
System.arraycopy(getText(), off + i, value, 0, len - i);
props.put(name, value);
off += len;
}
}
this.props = props;
}
return props;
}
|
b7ce0eb3-ab5e-4a32-bd90-364258254efe
| 0
|
public void changeColor() {
this.trackImg = trackImg1;
}
|
86334e73-664b-44d1-a50d-4b64eb218642
| 9
|
public static void writeShape(final Shape shape,
final ObjectOutputStream stream)
throws IOException {
if (stream == null) {
throw new IllegalArgumentException("Null 'stream' argument.");
}
if (shape != null) {
stream.writeBoolean(false);
if (shape instanceof Line2D) {
final Line2D line = (Line2D) shape;
stream.writeObject(Line2D.class);
stream.writeDouble(line.getX1());
stream.writeDouble(line.getY1());
stream.writeDouble(line.getX2());
stream.writeDouble(line.getY2());
}
else if (shape instanceof Rectangle2D) {
final Rectangle2D rectangle = (Rectangle2D) shape;
stream.writeObject(Rectangle2D.class);
stream.writeDouble(rectangle.getX());
stream.writeDouble(rectangle.getY());
stream.writeDouble(rectangle.getWidth());
stream.writeDouble(rectangle.getHeight());
}
else if (shape instanceof Ellipse2D) {
final Ellipse2D ellipse = (Ellipse2D) shape;
stream.writeObject(Ellipse2D.class);
stream.writeDouble(ellipse.getX());
stream.writeDouble(ellipse.getY());
stream.writeDouble(ellipse.getWidth());
stream.writeDouble(ellipse.getHeight());
}
else if (shape instanceof Arc2D) {
final Arc2D arc = (Arc2D) shape;
stream.writeObject(Arc2D.class);
stream.writeDouble(arc.getX());
stream.writeDouble(arc.getY());
stream.writeDouble(arc.getWidth());
stream.writeDouble(arc.getHeight());
stream.writeDouble(arc.getAngleStart());
stream.writeDouble(arc.getAngleExtent());
stream.writeInt(arc.getArcType());
}
else if (shape instanceof GeneralPath) {
stream.writeObject(GeneralPath.class);
final PathIterator pi = shape.getPathIterator(null);
final float[] args = new float[6];
stream.writeBoolean(pi.isDone());
while (!pi.isDone()) {
final int type = pi.currentSegment(args);
stream.writeInt(type);
// TODO: could write this to only stream the values
// required for the segment type
for (int i = 0; i < 6; i++) {
stream.writeFloat(args[i]);
}
stream.writeInt(pi.getWindingRule());
pi.next();
stream.writeBoolean(pi.isDone());
}
}
else {
stream.writeObject(shape.getClass());
stream.writeObject(shape);
}
}
else {
stream.writeBoolean(true);
}
}
|
fa9e4c73-7e72-4f9a-ae23-5cf08b2d4521
| 4
|
public void fitToScreen() {
if (vertices.size() == 0 || canvas.getWidth() <= 0 || canvas.getHeight() <= 0) {
canvas.offX = canvas.getWidth() / 2;
canvas.offY = canvas.getHeight() / 2;
canvas.zoom = 1.0;
return;
}
double minx = vertices.get(0).getX(), maxx = vertices.get(0).getX(), miny = vertices.get(0)
.getY(), maxy = vertices.get(0).getY();
for (Vertex v : vertices) {
minx = Math.min(minx, v.getX());
maxx = Math.max(maxx, v.getX());
miny = Math.min(miny, v.getY());
maxy = Math.max(maxy, v.getY());
}
double border = 20.0;
double w = maxx - minx + 2 * border, h = maxy - miny + 2 * border;
canvas.zoom = Math.min(canvas.getWidth() / w, canvas.getHeight() / h);
canvas.offX = -(minx + maxx) / 2.0 * canvas.zoom + canvas.getWidth() / 2;
canvas.offY = -(miny + maxy) / 2.0 * canvas.zoom + canvas.getHeight() / 2;
}
|
7fc90e45-edc1-4b90-8abe-508ac49b55ea
| 3
|
@Override
public void paintComponent(Graphics g){
Paint paint;
Graphics2D g2d;
if (g instanceof Graphics2D) {
g2d = (Graphics2D) g;
}
else {
System.out.println("Error");
return;
}
paint = new GradientPaint(0,0, getBackground(), getWidth(), getHeight(), getForeground());
g2d.setPaint(paint);
g.fillRect(0, 0, getWidth(), getHeight());
if(position!=0){
g.setColor(Color.GRAY);
String prefix = (position<10)?"O":"";
g.drawString(prefix+position,getWidth()-17,getHeight()-3);
}
}
|
095ac3bc-f7e3-482d-a1ea-a1f4892850ca
| 3
|
void intialiseWithInfected(int N, int initI) {
for (IndividualStateType state : allowedStates) {
if (state.equals(IndividualStateType.SUSCEPTIBLE)) {
createIndividualAgentsInState(state, (N-initI));
} else if (state.equals(IndividualStateType.INFECTED)) {
createIndividualAgentsInState(state, initI);
} else {
createIndividualAgentsInState(state, 0);
}
}
}
|
841fb155-c200-4002-ade3-f270a706af76
| 6
|
public String authenticate() throws Exception {
logger.info("Authenticating to Rackspace API...");
HttpGet request = new HttpGet(API_AUTH_URL);
request.addHeader("X-Auth-User", username);
request.addHeader("X-Auth-Key", apiKey);
try{
HttpResponse response = getHttpClient().execute(request);
int statusCode = response.getStatusLine().getStatusCode();
switch (statusCode) {
case 204:
if (response.getFirstHeader("X-Server-Management-Url") != null)
serverManagementURL = response.getFirstHeader("X-Server-Management-Url").getValue();
if (response.getFirstHeader("X-Storage-Url") != null)
storageURL = response.getFirstHeader("X-Storage-Url").getValue();
if (response.getFirstHeader("X-CDN-Management-Url") != null)
cdnManagementURL = response.getFirstHeader("X-CDN-Management-Url").getValue();
authToken = response.getFirstHeader("X-Auth-Token").getValue();
authenticated = true;
logger.log(Level.INFO, "Correct Authentication");
return authToken;
case 401:
throw new Exception("Invalid credentials: " + response.getStatusLine().getReasonPhrase());
default:
throw new Exception("Unexpected HTTP response");
}
} catch(javax.net.ssl.SSLException ex){
throw new Exception(ex.toString());
}
}
|
4686588c-410b-4017-b1ba-4062dbb2122c
| 1
|
private static int sgn(int x) {
return x < 0 ? -1 : 1;
}
|
a4647ac4-098c-45cd-b9d8-059104880d58
| 6
|
public synchronized boolean moveItem(FieldItem item, Position fromPosition, Position toPosition) {
if (insideBounds(fromPosition) && insideBounds(toPosition)) {
int transcurredTime = 0;
while (getItemType(toPosition) != ' ') {
try {
long time = System.nanoTime();
wait(0, 999999 - transcurredTime);
transcurredTime += System.nanoTime() - time;
if (transcurredTime > 1000000) {
return false;
}
} catch (InterruptedException ex) {
}
}
if (item == field[fromPosition.getX()][fromPosition.getY()]) {
field[fromPosition.getX()][fromPosition.getY()] = null;
field[toPosition.getX()][toPosition.getY()] = item;
notifyAll();
return true;
}
}
return false;
}
|
6ad81458-e1eb-4d8a-8db8-902e1dfdfe13
| 6
|
public void loadFromConfig(){
try {
BufferedReader reader = new BufferedReader(new FileReader("config.txt"));
//S2 path
s2Path = reader.readLine();
if (s2Path == null)
s2Path = "";
//Developer mode
if (reader.readLine().equals("1"))
isDeveloper = true;
else
isDeveloper = false;
//applied mods
appliedMods = reader.readLine();
if (appliedMods == null)
appliedMods = "";
reader.close();
} catch (FileNotFoundException e1) {
gui.showMessage("Welcome to Strife ModMan!\nPlease select your strife folder.",
"Welcome!", JOptionPane.PLAIN_MESSAGE);
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
s2Path = chooser.getSelectedFile().getAbsolutePath();
saveConfig();
}else
System.exit(0);
} catch (IOException e1) {
e1.printStackTrace();
}
}
|
6899cdd4-2eb7-4e81-b1c7-a40e290f1d48
| 7
|
protected String getTypeName(){
switch(this.eventType){
case(EVENT_MESSAGE_C):
return "Message_Client";
case(EVENT_MESSAGE):
return "Message";
case(EVENT_UPDATE_C):
return "Update_Client";
case(EVENT_UPDATE):
return "Update";
case(EVENT_DESTROY):
return "Destroy";
case(EVENT_INTERACT_C):
return "Interact_Client";
case(EVENT_INTERACT):
return "Interact";
default:
return "UNKNOWN_TYPE";
}
}
|
74270310-edc6-44b1-9671-48f672b470a7
| 6
|
public boolean solution(Node root, int sum) {
if (root == null) {
if (sum <= 0) {
return true;
} else {
return false;
}
}
termNode = root;
sum = sum - root.value;
boolean lValue = solution(root.leftChild, sum);
boolean rValue = solution(root.rightChild, sum);
if (!lValue) {
root.leftChild = null;
}
if (!rValue) {
root.rightChild = null;
}
if (!lValue && !rValue) {
return false;
} else {
return true;
}
}
|
9339e312-5484-41bd-a74a-1e71f6e1aa33
| 5
|
@Override
public void run(){
try (
InputStream inputStream = socket.getInputStream();
Scanner in = new Scanner(inputStream)
) {
boolean done = false;
while (!done && in.hasNextLine()) {
String line = in.nextLine();
Output.println(line);
if (line.trim().equals(Constants.SHUTDOWN_MESSAGE)) {
done = true;
}
}
} catch (IOException e){
throw new RuntimeException("Can't read data", e);
} finally {
try {
socket.close();
} catch (IOException e) {
// ignored
}
}
}
|
1e2b076e-d603-47fc-9f8b-39de6a2d0d74
| 5
|
public BTURL2(String loc, String ...params) throws Exception {
if((params.length % 2) != 0) {
throw new Exception("Parameters should be key, value array, length is not divisible by 2");
}
String p = "";
if(params.length > 0) {
p += "?";
for (int i = 0; i < params.length; i += 2) {
if(params[i+1].indexOf(NOENCODE) != -1) {
p += params[i] + "=" + params[i+1].substring(NOENCODE.length()) + "&";
} else {
p += params[i] + "=" + URLEncoder.encode(params[i+1], "UTF-8") + "&";
}
}
p = p.substring(0, p.length() - 1);
}
url = new URL(loc + p);
if(loc.indexOf("https") != -1) {
conn = (HttpsURLConnection)url.openConnection();
} else {
conn = (HttpURLConnection)url.openConnection();
}
//
conn.setUseCaches(false);
}
|
071e9429-da0b-4e60-a3b8-df0f585cd0e4
| 7
|
@Override
public void paint(Graphics g) {
super.paint(g); // paint background
//Drawing
Font f=new Font(Font.SANS_SERIF,Font.BOLD,12);
g.setFont(f);
g.setColor(Color.WHITE);
//Get space dimensions.
//Betting bar
//Betting bar line
g.drawLine(bettingW, 0, bettingW, HEIGHT);
//Betting bar buttons
g.fillOval(0, (HEIGHT-(3*betButtonH)), bettingW, betButtonH);
g.fillOval(0, (HEIGHT-(2*betButtonH)), bettingW, betButtonH);
g.fillOval(0, (HEIGHT-betButtonH), bettingW, betButtonH);
g.drawString("Check",bettingW+3,HEIGHT-((betButtonH*2)+3));
g.drawString("Bet",bettingW+3,HEIGHT-(betButtonH+3));
g.drawString("Fold",bettingW+3,(HEIGHT-3));
//make minBet button
g.setColor(Color.YELLOW);
g.fillRect(0, 0, bettingW, minBetH);
g.setColor(Color.WHITE);
//Betting bar bet meter
int[] triangleX={0,(bettingW/2),bettingW};
int[] triangleY={(HEIGHT-((3*betButtonH)+allInH+padding)),minBetH,(HEIGHT-((3*betButtonH)+allInH+padding))};
g.fillPolygon(triangleX, triangleY, 3);
//make All In button
g.setColor(Color.RED);
g.fillRect(0, (HEIGHT-((3*betButtonH)+allInH+padding)), bettingW, allInH);
g.setColor(Color.WHITE);
//Hand section with bars inbetween cards
g.drawLine(bettingW+(padding/2), HEIGHT-(cardH+(padding)), WIDTH-(padding/2), HEIGHT-(cardH+(padding)));
for(int w=bettingW+(padding/2); w<WIDTH; w+=(cardW+padding))
g.drawLine(w, HEIGHT-(2*(cardH+(padding/2))), w, HEIGHT-(cardH+padding));
//display current player's hand
int x=WIDTH-(playerHandSize*(cardW+padding));
int y=HEIGHT-(cardH+(padding/2));
for(Card card : table.getCurrentPlayer().getHand().getCards()){
paintCard(g,card,x,y);
x+=(cardW+padding);
}
//display community cards
x=bettingW+padding;
y=HEIGHT-((2*cardH)+padding);
for(Card card : table.getCommunity().getCards()){
paintCard(g,card,x,y);
x+=(cardW+padding);
}
//draw messages
g.setColor(Color.RED);
g.drawString(message,bettingW+padding,HEIGHT-(cardH-5));
g.drawString("Player "+table.getCurrentPlayerNum()+"'s turn.",bettingW+padding+15,15);
g.setColor(Color.GREEN);
g.drawString("Wallet: $"+table.getCurrentPlayer().getWallet().getBalance(),bettingW+padding+150,15);
g.setColor(Color.RED);
g.drawString("Pot: $"+table.getPot().getAmount(),WIDTH-100,15);
g.drawString("Minimum Bet: $"+table.getPot().getMinBet(),WIDTH-125,30);
g.drawString("Maximum Bet: $"+table.getPot().getMaxBet(),WIDTH-125,45);
//make bet tokin
g.setColor(Color.GREEN);
g.fillOval(((bettingW-betTokinW)/2),(betTokinY-(betTokinH/2)),betTokinW,betTokinH);
if(betTokinY>0){
if(allIn){
//draw "ALL IN!"
g.drawString("ALL IN!",(bettingW+2),(betTokinY+3));
}
else{
//draw current bet amount
g.drawString("$"+table.getCurrentPlayer().getHoldingBet(),(bettingW+2),(betTokinY+3));
}
}
//Check if new game
if(showNewGameAlert){
g.drawString("New Game!",bettingW+padding+160,100);
}
//Check if game is over.
if(table.gameIsOver()){
gameOverShown=true;
//Draw "game over" text
Player winner=table.getWinner();
g.drawString("Game over. Player "+winner.getHand().getOwner()+" wins $"+table.getPot().getAmount()+" with a "+winner.getHandType(),bettingW+padding+50,100);
g.drawString("Click anywhere to start a new game.",bettingW+padding+75,115);
winner.getWallet().addFunds(table.getPot().takeAll());
}
}
|
c828aa39-3e60-4314-938e-6134c9ff30c7
| 2
|
public int[] getIntArray(String key) {
try {
if(hasKey(key))
return ((NBTReturnable<int[]>) get(key)).getValue();
return new int[]{};
} catch (ClassCastException e) {
return new int[]{};
}
}
|
90c945ec-04a1-4e8e-8b03-0ab3c699650c
| 5
|
public void renderGradientQuad(float x, float y, float width, float height, ColorHelper color, SideHelper... sides) {
for (SideHelper side : sides) {
switch (side) {
case TOP:
gradientTop.setOverwriteColor(color);
bindMaterial(gradientTop);
break;
case BOTTOM:
gradientBottom.setOverwriteColor(color);
bindMaterial(gradientBottom);
break;
case LEFT:
gradientLeft.setOverwriteColor(color);
bindMaterial(gradientLeft);
break;
case RIGHT:
gradientRight.setOverwriteColor(color);
bindMaterial(gradientRight);
break;
}
renderQuad(x, y, width, height);
}
}
|
7136e617-a8dd-4f6c-a3b6-e5ceb9c9c93f
| 6
|
synchronized public Color[][] getColorTab(boolean withPiece) {
if (!withPiece) {
return super.getColorTab();
} else {
Color[][] tab = super.getColorTab();
TetrisShape shape = (TetrisShape) getCurrentPiece().getShape(getCurrentPiece().getCurrentRotation());
Color c = this.getCurrentPiece().getColor();
Position p = getCurrentPiece().getPosition();
for (int i = 0; i < TetrisShape.NB_ROW; i++) {
for (int j = 0; j < TetrisShape.NB_COL; j++) {
if (p.getX() + i < TetrisGrid.NB_ROW && p.getY() + j < TetrisGrid.NB_COL && shape.getShape(i, j) == 1) {
tab[p.getX() + i][p.getY() + j] = c;
}
}
}
return tab;
}
}
|
901e825d-86c3-4059-8720-30b7cb5380c1
| 0
|
public HyperbolicEquation(float a, float b, float h, float k) {
this.a = a;
this.b = b;
this.h = h;
this.k = k;
}
|
c684f37a-d09b-4c01-aaf9-95870b0ad73f
| 9
|
public static byte[] hexStringToByteArray(String s) throws NumberFormatException {
byte[] data = new byte[0];
if (s != null && s.length() > 0) {
String[] split;
if (s.length() > 2) {
if (s.length() >= 3 && s.contains("x")) {
s = s.startsWith("x") ? s.substring(1) : s;
s = s.endsWith("x") ? s.substring(0, s.length() - 1) : s;
split = s.split("x");
} else {
split = s.split("(?<=\\G..)");
}
data = new byte[split.length];
for (int i = 0; i < split.length; i++) {
data[i] = Byte.parseByte(split[i], 16);
}
} else if (s.length() == 2) {
data = new byte[]{Byte.parseByte(s)};
}
}
return data;
}
|
42325280-eceb-47e4-8879-79caee9328e6
| 2
|
public List<Token> tokenize(String code) {
final List<Token> tokens = new LinkedList<>();
for (char c : code.toCharArray()) {
if (mapping.containsToken(c)) {
tokens.add(new Token(c, mapping.getType(c)));
}
}
return tokens;
}
|
5c4f0679-92ee-4638-881e-1344e6859484
| 5
|
private int date_to_index(int date) {
//System.out.println("date_to_index : date = " + date);
//algorithme de recherche par dichotomie (a chaque fois on divise le tableau en 2)
boolean fin_iteration = false;
int debut = 0;
int fin = filemessages.size();
int milieu=-1;
if(date > filemessages.get(0).date) {
while(!fin_iteration) {
milieu = (debut+fin)/2;
if((filemessages.get(milieu).date) == date) {
fin_iteration = true;
}
else {
if((filemessages.get(milieu).date) > date) {
fin = milieu;
}
else {
debut = milieu;
}
//System.out.println("milieu = " + milieu + " ; debut = " + debut + " ; fin = " +fin);
}
if((fin - debut) <= 1){
milieu = debut; //prend la valeur min.
fin_iteration = true;
}
}
}
//System.out.println("index trouve" + milieu);
//si la date a trouver est 0, milieu = -1, car a la date 0 aucun message n'a pu àtre reàu
return milieu;
}
|
b2cd8be3-9131-407c-af56-c5a470f77797
| 4
|
public void launch()
{
// Load URLs
final List<URL> urls = new ArrayList<URL>();
mods.fill(urls);
File natives = new File(main.getApi().getMinecraftDirectory(), "bin/");
for (final UpdaterWorker.GameFile gameFile : main.getUpdater()
.getGameFiles())
{
if (gameFile.getType() == Type.LIBRARY)
{
try
{
final URL url = gameFile.getFile().toURI().toURL();
urls.add(url);
}
catch (final MalformedURLException e)
{
e.printStackTrace();
}
}
if (gameFile.getType() == Type.NATIVE)
{
natives = gameFile.getDest();
}
}
System.out.println("Set natives dir to '" + natives.getAbsolutePath()
+ "'");
// Add System env values
System.setProperty("org.lwjgl.librarypath", natives.getAbsolutePath());
System.setProperty("net.java.games.input.librarypath",
natives.getAbsolutePath());
// Start Minecraft
classLoader = new URLClassLoader(urls.toArray(new URL[0]));
applet = new LauncherApplet(main.getApi());
applet.init();
main.getFrame().getMainPanel().add(applet, "Center");
main.getFrame().validate();
applet.start();
final Thread t = new Thread(this);
t.start();
}
|
b1785b3f-73bb-465f-a7f3-b8266a3b1f59
| 3
|
public int compare(Object o1, Object o2) {
Color first = (Color) o1;
Color second = (Color) o2;
if (first.getAlpha() != second.getAlpha())
return (second.getAlpha() - first.getAlpha());
// Extract the HSB, and impose the ordering.
float[] firstHSB = Color.RGBtoHSB(first.getRed(), first.getGreen(),
first.getBlue(), null);
float[] secondHSB = Color.RGBtoHSB(second.getRed(), second.getGreen(),
second.getBlue(), null);
int[] comp = new int[3];
// First saturation...
comp[0] = -compareFloat(firstHSB[1], secondHSB[1]);
// Then brightness...
comp[1] = -compareFloat(firstHSB[2], secondHSB[2]);
// Then hue...
comp[2] = compareFloat(firstHSB[0], secondHSB[0]);
// Run through the comparisons, return if not zero.
for (int i = 0; i < 3; i++)
if (comp[i] != 0)
return comp[i];
return 0;
}
|
859a1ef3-47ed-4b2d-afc7-ad20d275b445
| 7
|
protected boolean fix_with_precedence(
production p,
int term_index,
parse_action_row table_row,
parse_action act)
throws internal_error {
terminal term = terminal.find(term_index);
/* if the production has a precedence number, it can be fixed */
if (p.precedence_num() > assoc.no_prec) {
/* if production precedes terminal, put reduce in table */
if (p.precedence_num() > term.precedence_num()) {
table_row.under_term[term_index] =
insert_reduce(table_row.under_term[term_index],act);
return true;
}
/* if terminal precedes rule, put shift in table */
else if (p.precedence_num() < term.precedence_num()) {
table_row.under_term[term_index] =
insert_shift(table_row.under_term[term_index],act);
return true;
}
else { /* they are == precedence */
/* equal precedences have equal sides, so only need to
look at one: if it is right, put shift in table */
if (term.precedence_side() == assoc.right) {
table_row.under_term[term_index] =
insert_shift(table_row.under_term[term_index],act);
return true;
}
/* if it is left, put reduce in table */
else if (term.precedence_side() == assoc.left) {
table_row.under_term[term_index] =
insert_reduce(table_row.under_term[term_index],act);
return true;
}
/* if it is nonassoc, we're not allowed to have two nonassocs
of equal precedence in a row, so put in NONASSOC */
else if (term.precedence_side() == assoc.nonassoc) {
table_row.under_term[term_index] = new nonassoc_action();
return true;
} else {
/* something really went wrong */
throw new internal_error("Unable to resolve conflict correctly");
}
}
}
/* check if terminal has precedence, if so, shift, since
rule does not have precedence */
else if (term.precedence_num() > assoc.no_prec) {
table_row.under_term[term_index] =
insert_shift(table_row.under_term[term_index],act);
return true;
}
/* otherwise, neither the rule nor the terminal has a precedence,
so it can't be fixed. */
return false;
}
|
28d7f40c-9256-4569-b1cc-b6b5cec3a5a7
| 8
|
private int addNeighbours(Point p, List<Point> list) {
int c = 0;
if (p.x - 1 != 0) if (this.maze[p.x - 1][p.y] == true) {list.add(new Point(p.x - 1, p.y));c++;}
if (p.x + 1 != this.width - 1) if (this.maze[p.x + 1][p.y] == true) {list.add(new Point(p.x + 1, p.y));c++;}
if (p.y - 1 != 0) if (this.maze[p.x][p.y - 1] == true) {list.add(new Point(p.x, p.y - 1));c++;}
if (p.y + 1 != this.length - 1) if (this.maze[p.x][p.y + 1] == true) {list.add(new Point(p.x, p.y + 1));c++;}
return c;
}
|
6b263d16-74db-4910-a43f-63308a1606d1
| 2
|
@Override
public boolean matches(String[] input) {
for (String word: input) {
matcher.reset(word);
if (matcher.find()) {
return true;
}
}
return false;
}
|
101d8448-3419-4ffa-a80f-a696a4472ad9
| 1
|
private void saveSettings() {
try {
myMode = mySettingsSWT.getSelectedMode();
myBoardType = mySettingsSWT.getSelectedBoardType();
myBoardFile = mySettingsSWT.getFile();
myFileParser = new FileParser(myBoardFile);
myFileParser.parse();
validBean = new ValidBean(true, null);
} catch (Exception e) {
validBean = new ValidBean(false, e);
}
}
|
2cb6cbaa-2421-4476-b523-50b951e1c8b8
| 3
|
public void apply() throws XPathExpressionException {
if(!this.isSelected()) {
return;
}
Element e = editor.getXMLElementByString(this.xmlPath);
if(e != null) {
Node child = null;
MessageUtil.debug("Remove all "+ this.name);
while((child = e.getFirstChild()) != null) {
e.removeChild(child);
}
}
}
|
98f0f672-88bb-4bdb-811f-d0c2e8b359e5
| 9
|
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto)|CMMsg.MASK_MALICIOUS,auto?"":L("^S<S-NAME> chant(s) at <T-NAMESELF>!^?"));
final CMMsg msg2=CMClass.getMsg(mob,target,this,CMMsg.MASK_MALICIOUS|CMMsg.TYP_DISEASE,null);
if(mob.location().okMessage(mob,msg)||mob.location().okMessage(mob,msg2))
{
mob.location().send(mob,msg);
mob.location().send(mob,msg2);
if((msg.value()<=0)&&(msg2.value()<=0))
{
final Ability A=CMClass.getAbility("Disease_Plague");
if(A!=null)
return A.invoke(mob,target,true,asLevel);
}
}
}
else
return maliciousFizzle(mob,target,L("<S-NAME> chant(s) at <T-NAMESELF>, but nothing happens."));
// return whether it worked
return success;
}
|
fb12e1cc-7e8e-40b5-aebe-0b03ee1fdbbb
| 1
|
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(6868);
while(true)
{
Socket socket = serverSocket.accept();
//启动读写线程
new ServerInputThread(socket).start();
new ServerOutputThread(socket).start();
}
}
|
894810f3-e2bf-4f88-b3e3-8644b6d3cfed
| 3
|
private LaunchProxy(File... files) {
StringBuilder buffer = new StringBuilder();
mFiles = new ArrayList<>();
mTimeStamp = System.currentTimeMillis();
buffer.append(LAUNCH_ID);
buffer.append(' ');
buffer.append(mTimeStamp);
buffer.append(' ');
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (i != 0) {
buffer.append(',');
}
buffer.append(files[i].getAbsolutePath().replaceAll(AT, AT_MARKER).replaceAll(SPACE, SPACE_MARKER).replaceAll(COMMA, COMMA_MARKER));
}
}
mConduit = new Conduit(this, false);
mConduit.send(new ConduitMessage(BundleInfo.getDefault().getName(), buffer.toString()));
}
|
b6e60608-f064-4af5-a4f9-763f6292e68b
| 8
|
private synchronized void processNetPacket(Sim_event ev, int tag)
{
double nextTime = 0;
Packet pkt = (Packet) ev.get_data();
PacketScheduler sched = getScheduler(pkt);
// if a packet scheduler is not found, then try reschedule this packet
// in the future
if (sched == null)
{
System.out.println(super.get_name() + ".processNetPacket(): " +
"Warning - can't find a packet scheduler for " + pkt);
System.out.println("-> Will reschedule it again in the future.");
super.sim_schedule(super.get_id(), Router.DELAY, tag, pkt);
return;
}
// process ping() request
if (pkt instanceof InfoPacket)
{
((InfoPacket) pkt).addHop(id);
((InfoPacket) pkt).addEntryTime( GridSim.clock() );
((InfoPacket) pkt).addBaudRate(sched.getBaudRate());
}
// check downlink MTU, and split accordingly
String linkName = getLinkName( pkt.getDestID() );
Link downLink = (Link) Sim_system.get_entity(linkName);
int MTU = downLink.getMTU();
int numPackets = (int) Math.ceil(pkt.getSize() / (MTU * 1.0));
// if no packets at the moment
if (sched.size() == 0)
{
if (numPackets == 1) {
nextTime = (pkt.getSize() * NetIO.BITS) / sched.getBaudRate();
}
else {
nextTime = (MTU * NetIO.BITS * 1.0) / sched.getBaudRate();
}
sendInternalEvent(nextTime, sched);
}
// log / record ....
if (super.reportWriter_ != null)
{
super.write("");
super.write("receive incoming, " + pkt + ", delay, " + nextTime);
super.write("break this packet into, " + numPackets);
}
// break a large packet into smaller ones that fit into MTU
// by making null or empty packets except for the last one
for (int i = 0; i < numPackets - 1; i++)
{
NetPacket np = new NetPacket(null, pkt.getID(), MTU, tag,
pkt.getSrcID(), pkt.getDestID(),
pkt.getNetServiceType(),i+1,numPackets);
np.setLast(id);
if (super.reportWriter_ != null) {
super.write("enqueing, " + np);
}
sched.enque(np); // put the packet into the scheduler
}
// put the actual packet into the last one and resize it accordingly
pkt.setLast(id);
pkt.setSize(pkt.getSize() - MTU * (numPackets - 1));
if (super.reportWriter_ != null) {
super.write("enqueing, " + pkt);
}
sched.enque(pkt); // put the packet into the scheduler
}
|
81e5c496-e3db-4dde-8ff5-0bd47b93df85
| 0
|
@Basic
@Column(name = "payment_type")
public String getPaymentType() {
return paymentType;
}
|
b0390c82-bcb2-40a9-9474-76da1fd4ebf7
| 9
|
protected MD3_Surface( MD3_File parent_reader, int index) throws Exception{
this.parent_reader = parent_reader;
this.byter = this.parent_reader.byter;
INDEX = index;
start_pos = byter.getPos();
S32_IDENT = byter.getInteger(0);
STR_IDENT = byter.backward(4).getString(0, 4);
byter.byte_reading_counter -=4;
STR_NAME = byter.getString(0, MAX_QPATH);
STR_NAME = STR_NAME.substring(0, STR_NAME.indexOf(0));
S32_FLAGS = byter.getInteger(0);
S32_NUM_FRAMES = byter.getInteger(0);
S32_NUM_SHADERS = byter.getInteger(0);
S32_NUM_VERTS = byter.getInteger(0);
S32_NUM_TRIANGLES = byter.getInteger(0);
S32_OFS_TRIANGLES = byter.getInteger(0);
S32_OFS_SHADERS = byter.getInteger(0);
S32_OFS_ST = byter.getInteger(0);
S32_OFS_XYZNORMAL = byter.getInteger(0);
S32_OFS_END = byter.getInteger(0);
end_pos = byter.getPos();
logToConsole();
if( S32_NUM_FRAMES != this.parent_reader.header.S32_NUM_FRAMES ) throw new Exception("(!CORRPUT MD3!) number of frames incorrect = "+ S32_NUM_FRAMES);
if( S32_NUM_SHADERS < 0 | S32_NUM_SHADERS > MD3_MAX_SHADERS ) throw new Exception("(!CORRPUT MD3!) S32_NUM_SHADERS = "+ S32_NUM_SHADERS +" ... min/max = 0/"+MD3_MAX_SHADERS);
if( S32_NUM_VERTS < 0 | S32_NUM_VERTS > MD3_MAX_VERTS ) throw new Exception("(!CORRPUT MD3!) S32_NUM_VERTS = "+ S32_NUM_VERTS +" ... min/max = 0/"+MD3_MAX_VERTS);
if( S32_NUM_TRIANGLES < 0 | S32_NUM_TRIANGLES > MD3_MAX_TRIANGLES ) throw new Exception("(!CORRPUT MD3!) S32_NUM_TRIANGLES = "+S32_NUM_TRIANGLES+" ... min/max = 0/"+MD3_MAX_TRIANGLES);
pos_shaders = start_pos+S32_OFS_SHADERS;
pos_triangles = start_pos+S32_OFS_TRIANGLES;
pos_texcoords = start_pos+S32_OFS_ST;
pos_xyznormals = start_pos+S32_OFS_XYZNORMAL;
byter.setPos(pos_shaders);
shaders = new MD3_Shader[S32_NUM_SHADERS];
for(int i = 0; i < S32_NUM_SHADERS; i++)
shaders[i] = new MD3_Shader(this, i);
byter.setPos(pos_triangles);
triangles = new MD3_Triangle[S32_NUM_TRIANGLES];
for(int i = 0; i < S32_NUM_TRIANGLES; i++)
triangles[i] = new MD3_Triangle(this, i);
byter.setPos(pos_texcoords);
tex_coords = new MD3_TexCoord[S32_NUM_VERTS];
for(int i = 0; i < S32_NUM_VERTS; i++)
tex_coords[i] = new MD3_TexCoord(this, i);
byter.setPos(pos_xyznormals);
surface_frames = new MD3_SurfaceFrame[S32_NUM_FRAMES];
for(int i = 0; i < S32_NUM_FRAMES; i++)
surface_frames[i] = new MD3_SurfaceFrame(this, i);
if( (S32_OFS_END+start_pos) != byter.getPos()){
throw new Exception("(!CORRPUT MD3!): surface size (number of bytes) incorrect");
}
}
|
9ce2490a-bfb3-4ecf-ba72-7b6d5996bab0
| 9
|
private void runExperiment(int runType) {
int[] query = convertObjectArrayToIntegerArray(chooseQuery());
if (query == null || query.length == 0) {
ERROR("Query choose error.");
return;
}
switch (runType) {
case 0:
debug(query);
break;
case 1:
runExperiment1(query);
break;
case 2:
break;
case 3:
break;
case 4:
runExperiment4("THETA");
break;
case 5:
// runExperiment5(round);
break;
case 6:
// runExperiment6(round);
break;
default:
System.out.println("Bye.");
}
}
|
4049cfd4-c271-4fd7-8133-f42a8fb4be16
| 3
|
public Item getItem(int slot) {
if(slot >= 0 && slot < items.length && items[slot] != null)
return items[slot];
return null;
}
|
c6faa598-83b9-4358-b174-3436b19623a7
| 5
|
public InteractiveObject getInteractiveObject(int x, int y, int z) {
GroundTile groundTile = groundTiles[z][x][y];
if (groundTile == null) {
return null;
}
for (int l = 0; l < groundTile.anInt1317; l++) {
InteractiveObject interactiveObject = groundTile.interactiveObjects[l];
if ((interactiveObject.uid >> 29 & 3) == 2 && interactiveObject.x == x && interactiveObject.y == y) {
return interactiveObject;
}
}
return null;
}
|
59d59a5b-920b-4aff-b892-2152d7914a34
| 4
|
public Gui_Settings2(Gui_StreamRipStar mainGui)
{
super(mainGui, "Preferences");
this.mainGui = mainGui;
this.setModalityType(ModalityType.APPLICATION_MODAL);
Object elements[][] = {
{"Look And Feel",commonPrefIcon},
{"Audio and Programs",pathPrefIcon},
{"Language and Log",audioPlayerPrefIcon}};
list = new JList(elements);
list.setCellRenderer(new IconCellRenderer());
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(-1);
list.addMouseListener(new ClickOnListListener());
//create rest of components at runtime
lookAndFeelInfos = UIManager.getInstalledLookAndFeels();
lookAndFeelList = new String[lookAndFeelInfos.length];
for(int i=0; i < lookAndFeelInfos.length; i++)
{
lookAndFeelList[i] = lookAndFeelInfos[i].getName();
}
LookAndFeelBox = new JComboBox(lookAndFeelList);
translationTA.setEditable(false);
//pack the basic layout
setLayout(new BorderLayout());
add(new JScrollPane(list), BorderLayout.WEST);
add(mainSP, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
//Set Layouts for JPanels
pathAudioPanel.setLayout(new GridBagLayout());
pathPanel.setLayout(new GridBagLayout());
internalaudioPanel.setLayout(new GridBagLayout());
lookAndFeelPanel.setLayout(new GridBagLayout());
sysTrayIconPanel.setLayout(new GridBagLayout());
otherLookAndFeelPanel.setLayout(new GridBagLayout());
actionPanel.setLayout(new GridBagLayout());
langLogPanel.setLayout(new GridBagLayout());
languagePanel.setLayout(new GridBagLayout());
logPanel.setLayout(new GridBagLayout());
buttonPanel.setLayout(new GridBagLayout());
commonPanel.setLayout(new GridBagLayout());
//set borders
sysTrayIconPanel.setBorder(sysTrayTabTitle);
otherLookAndFeelPanel.setBorder(lookAndFeelTabTitle);
actionPanel.setBorder(actionsTabTitle);
languagePanel.setBorder(languageTabTitle);
logPanel.setBorder(logTabTitle);
internalaudioPanel.setBorder(internalAudioTitle);
pathPanel.setBorder(pathTitle);
//now pack them together
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets( 1, 1, 1, 1);
c.anchor = GridBagConstraints.PAGE_START;
//TAB 1: lookAndFeelPanel
c.gridx = 0;
c.gridy = 0;
c.weighty = 0;
c.weightx = 1;
lookAndFeelPanel.add(sysTrayIconPanel,c);
c.gridy = 1;
lookAndFeelPanel.add(otherLookAndFeelPanel,c);
c.gridy = 2;
lookAndFeelPanel.add(actionPanel,c);
c.gridy = 3;
c.weighty = 1;
lookAndFeelPanel.add(new JLabel(""),c);
//TAB 1 - Panel 1: sysTrayIconPanel
c.gridy = 0;
c.gridx = 0;
c.weighty = 0;
sysTrayIconPanel.add(activeTrayIcon,c);
c.gridy = 1;
sysTrayIconPanel.add(windowClosing,c);
c.gridy = 2;
c.gridx = 1;
c.gridwidth=2;
sysTrayIconPanel.add(windowActionBox,c);
//TAB 1 - Panel 2: otherLookAndFeelPanel
c.gridy = 0;
c.gridx = 0;
c.weightx = 1;
c.weighty = 0;
c.gridwidth=2;
otherLookAndFeelPanel.add(useAnotherLnfBox,c);
c.weightx = 0;
c.gridy = 1;
c.gridwidth=1;
otherLookAndFeelPanel.add(lnfLabel,c);
c.gridx = 1;
otherLookAndFeelPanel.add(LookAndFeelBox,c);
c.gridy = 2;
c.gridx = 0;
otherLookAndFeelPanel.add(showTextCheckBox,c);
//TAB 1 - Panel 3: actionPanel
//1. Line: explain what you are doing
c.insets = new Insets( 5, 5, 10, 5);
c.weightx = 0.0;
c.gridy = 0;
c.gridx = 0;
c.gridwidth = 7;
actionPanel.add(explainActionLabel,c);
c.gridx = 0;
c.weightx = 1;
actionPanel.add(new JLabel(""),c);
//2. Line: click on status
c.insets = new Insets( 2, 30, 2, 5);
c.weightx = 0;
c.gridwidth = 1;
c.gridy = 1;
c.gridx = 0;
actionPanel.add(statusLabel,c);
c.gridx = 1;
actionPanel.add(statusBox,c);
//3. Line: click on Name
c.gridy = 2;
c.gridx = 0;
actionPanel.add(nameLabel,c);
c.gridx = 1;
actionPanel.add(nameBox,c);
//4. Line: click on current Track
c.gridy = 3;
c.gridx = 0;
actionPanel.add(currentTrackLabel,c);
c.gridx = 1;
actionPanel.add(currentTrackBox,c);
//TAB 2: Path and Audio
c.insets = new Insets( 1, 1, 1, 1);
c.gridy = 0;
c.gridx = 0;
c.weightx = 1;
c.weighty = 0;
pathAudioPanel.add(internalaudioPanel,c);
c.weightx = 0;
c.gridy = 1;
pathAudioPanel.add(pathPanel,c);
c.gridy = 2;
c.weighty = 1;
pathAudioPanel.add(new JLabel(""),c);
//TAB 2 - Panel 1: Internal Audio
c.gridy = 0;
c.gridx = 0;
c.weighty = 0;
c.gridwidth = 3;
c.insets = new Insets( 1, 1, 4, 1);
internalaudioPanel.add(useInternalAudioPlayerCB,c);
c.insets = new Insets( 1, 1, 1, 1);
c.gridwidth = 1;
c.gridy = 1;
c.gridx = 0;
internalaudioPanel.add(mediaPlayer,c);
c.gridx = 1;
c.weightx = 1.0;
internalaudioPanel.add(shoutcastPlayer,c);
c.gridx = 2;
c.weightx = 0.0;
internalaudioPanel.add(browseMP3Player,c);
//TAB 2 - Panel 2: Paths
//1. line: Path to streamripper
c.gridy = 0;
c.gridx = 0;
c.weighty = 0;
pathPanel.add(ripLabel,c);
c.gridx = 1;
c.weightx = 1.0;
pathPanel.add(ripperPathField,c);
c.gridx = 2;
c.weightx = 0.0;
pathPanel.add(browseRipper,c);
//3. line: path to generall savepath for the stream
c.gridy = 1;
c.gridx = 0;
pathPanel.add(generellPathLabel,c);
c.gridx = 1;
c.weightx = 1.0;
pathPanel.add(generellPathField,c);
c.gridx = 2;
c.weightx = 0.0;
pathPanel.add(browseGenerellPath,c);
//4. line: path ot webbrowser
c.gridy = 2;
c.gridx = 0;
pathPanel.add(webBrowserLabel,c);
c.gridx = 1;
c.weightx = 1.0;
pathPanel.add(webBrowserField,c);
c.gridx = 2;
c.weightx = 0.0;
pathPanel.add(browseWebBrowserPath,c);
//5. line: path ot fielbrowser
c.gridy = 3;
c.gridx = 0;
pathPanel.add(fileBrowserLabel,c);
c.gridx = 1;
c.weightx = 1.0;
pathPanel.add(fileBrowserField,c);
c.gridx = 2;
c.weightx = 0.0;
pathPanel.add(browseFileBrowserPath,c);
//TAB 3: Language and Logging
c.gridy = 0;
c.weighty = 0;
langLogPanel.add(languagePanel,c);
c.gridy = 1;
c.weightx = 1.0;
langLogPanel.add(logPanel,c);
c.gridy = 2;
c.weighty = 1;
langLogPanel.add(new JLabel(""),c);
//TAB 1 - Panel 1: languagePanel
//1. line on lang: langchange
c.weightx = 0.0;
c.gridy = 0;
c.gridx = 0;
languagePanel.add(langMenu, c);
c.weightx = 1.0;
c.gridx = 1;
languagePanel.add(new JLabel(""), c);
//2. line on lang: langchange
c.weightx = 0.0;
c.gridy = 1;
c.gridx = 0;
c.gridwidth = 2;
languagePanel.add(reqRestart,c);
//3. line on lang: langchange
c.weightx = 0.0;
c.gridy = 2;
c.gridx = 0;
c.gridwidth = 2;
languagePanel.add(new JLabel(" "),c);
//4. line on lang: langchange
c.weightx = 0.0;
c.weighty = 0.0;
c.gridy = 3;
c.gridx = 0;
c.gridwidth = 2;
languagePanel.add(translationSP,c);
//TAB 1 - Panel 1: Logpanel
c.gridy = 0;
c.gridx = 0;
c.gridwidth = 1;
logPanel.add(logLabel,c);
c.gridx = 1;
c.weightx = 1.0;
logPanel.add(logLevelBox,c);
//BUTTONPANEL
c.insets = new Insets( 5, 5,5 ,5 );
c.weightx = 0;
c.gridy = 0;
c.gridx = 0;
c.gridwidth = 1;
buttonPanel.add(saveAndExitButton,c);
c.gridx = 1;
buttonPanel.add(saveButton,c);
c.weightx = 1.0;
c.gridx = 2;
buttonPanel.add(new JLabel(""),c);
c.weightx = 0.0;
c.gridx = 3;
buttonPanel.add(abortButton,c);
dirChooser = new JFileChooser();
dirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
abortButton.addActionListener(new ExitListener());
saveButton.addActionListener(new SaveListener());
saveAndExitButton.addActionListener(new SaveAndExitListener());
browseMP3Player.addActionListener(new MP3Listener());
browseRipper.addActionListener(new RipperPathListener());
browseGenerellPath.addActionListener(new BrowseListener());
browseWebBrowserPath.addActionListener(new WebBrowserListener());
browseFileBrowserPath.addActionListener(new FileBrowserListener());
activeTrayIcon.addActionListener(new ChangeTrayFields());
useAnotherLnfBox.addActionListener(new ChangeTrayFields());
useInternalAudioPlayerCB.addActionListener(new ChangeTrayFields());
//set new language
setLanguage();
//load the old settings from file and set the right components active
load();
//look for the right index in combobox, if the old value was != null
if(lookAndFeelBox_className != null) {
for(int i=0; i < lookAndFeelInfos.length; i++) {
if(lookAndFeelInfos[i].getClassName().equals(lookAndFeelBox_className)) {
LookAndFeelBox.setSelectedIndex(i);
break;
}
}
}
statusBox.setSelectedIndex(4);
nameBox.setSelectedIndex(4);
currentTrackBox.setSelectedIndex(4);
//set default panel when start
mainPanel.add(lookAndFeelPanel);
list.setSelectedIndex(0);
repaintCommon();
//get new dimension of the window
Dimension frameDim = new Dimension(800,440);
setSize(frameDim);
//get resolution
Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
//calculates the app. values
int x = (screenDim.width - frameDim.width)/2;
int y = (screenDim.height - frameDim.height)/2;
//set location
setLocation(x, y);
setVisible(true);
//escape for exit
KeyStroke escStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true);
//register all Strokes
getRootPane().registerKeyboardAction(new ExitListener(), escStroke,
JComponent.WHEN_IN_FOCUSED_WINDOW);
}
|
391e25b3-4496-4d67-9639-9c8e40c2b414
| 4
|
private void addTeam()
{
clear();
System.out.println("Add a new team:");
System.out.println();
try
{
int counter = teammgr.showCount();
int maxId = teammgr.maxTeamId();
Team tm = teammgr.getById(maxId);
if (tm == null || tm.getGroupId() == 0)
{
if (counter <= 16)
{
Scanner sc = new Scanner(System.in, "iso-8859-1");
System.out.println("School: ");
String school = sc.nextLine();
System.out.println("Team Captain: ");
String teamCaptain = sc.nextLine();
System.out.println("Email: ");
String email = sc.nextLine();
Team team = new Team(-1, school, teamCaptain, email, -1, -1);
teammgr.add(team);
System.out.println();
System.out.println("Team succesfully added!");
}
else
{
System.out.println("Teams are limited to a total of 16 teams! Limit reached!");
}
}
else
{
System.out.println("Groups have been assigned, therefore it's not possible to add more teams!");
}
}
catch (Exception e)
{
System.out.println("ERROR - " + e.getMessage());
}
pause();
}
|
c82dd8a3-6fb4-4571-9037-b3669385aaee
| 5
|
void Move_Send_Serial() {
// send updates to hexapod?
ByteBuffer buffer = ByteBuffer.allocate(64);
int used=0;
int i;
for(i=0;i<6;++i) {
Leg leg=legs[i];
// update pan
leg.pan_joint.angle=Math.max(Math.min(leg.pan_joint.angle,(float)leg.pan_joint.angle_max),(float)leg.pan_joint.angle_min);
if(leg.pan_joint.last_angle!=(int)leg.pan_joint.angle)
{
leg.pan_joint.last_angle=(int)leg.pan_joint.angle;
buffer.put(used++,(byte)leg.pan_joint.servo_address);
buffer.put(used++,(byte)leg.pan_joint.angle);
//Log3("%d=%d ",buffer[used-2],buffer[used-1]);
}
// update tilt
leg.tilt_joint.angle=Math.max(Math.min(leg.tilt_joint.angle,(float)leg.tilt_joint.angle_max),(float)leg.tilt_joint.angle_min);
if(leg.tilt_joint.last_angle!=(int)leg.tilt_joint.angle)
{
leg.tilt_joint.last_angle=(int)leg.tilt_joint.angle;
buffer.put(used++,(byte)leg.tilt_joint.servo_address);
buffer.put(used++,(byte)leg.tilt_joint.angle);
//Log3("%d=%d ",buffer[used-2],buffer[used-1]);
}
// update knee
leg.knee_joint.angle=Math.max(Math.min(leg.knee_joint.angle,(float)leg.knee_joint.angle_max),(float)leg.knee_joint.angle_min);
if(leg.knee_joint.last_angle!=(int)leg.knee_joint.angle)
{
leg.knee_joint.last_angle=(int)leg.knee_joint.angle;
buffer.put(used++,(byte)leg.knee_joint.servo_address);
buffer.put(used++,(byte)leg.knee_joint.angle);
//Log3("%d=%d ",buffer[used-2],buffer[used-1]);
}
}
if(used>0) {
Instruct('U',buffer);
}
}
|
39dcd8a4-c639-4640-9c75-5f631cfb08c7
| 9
|
public boolean execute(CommandSender sender, String[] args) {
if(!(sender instanceof Player)){
return true;
}
String groupName = args[0];
String targetName = args[1];
GroupManager groupManager = Citadel.getGroupManager();
Faction group = groupManager.getGroup(groupName);
if(group == null){
sendMessage(sender, ChatColor.RED, "Group doesn't exist");
return true;
}
String founderName = sender.getName();
if(!group.isFounder(founderName)){
sendMessage(sender, ChatColor.RED, "Invalid permission to modify this group");
return true;
}
if(group.isPersonalGroup()){
sendMessage(sender, ChatColor.RED, "You cannot allow moderators to your default group");
return true;
}
if(group.isFounder(targetName)){
sendMessage(sender, ChatColor.RED, "You are already owner of this group");
return true;
}
if(group.isModerator(targetName)){
sendMessage(sender, ChatColor.RED, "%s is already a moderator of %s", targetName, groupName);
return true;
}
if(group.isMember(targetName)){
groupManager.removeMemberFromGroup(groupName, targetName);
}
MemberManager memberManager = Citadel.getMemberManager();
Member member = memberManager.getMember(targetName);
if(member == null){
member = new Member(targetName);
memberManager.addMember(member);
}
groupManager.addModeratorToGroup(groupName, targetName);
sendMessage(sender, ChatColor.GREEN, "%s has been added as a moderator to %s", targetName, groupName);
if(memberManager.isOnline(targetName)){
sendMessage(memberManager.getOnlinePlayer(targetName), ChatColor.GREEN, "You have been added as " +
"moderator to %s by %s", groupName, founderName);
}
return true;
}
|
1c2e64e7-491b-4b34-9a20-89c263610dbf
| 4
|
@Override
public void mousePressed(MouseEvent e)
{
if (graphComponent.isEnabled() && isEnabled() && !e.isConsumed()
&& isStartEvent(e))
{
start(e);
e.consume();
}
}
|
8d762c18-d1c8-4be8-a40f-1fb4af35b262
| 5
|
@Override
public void epoch(Player p) {
//Save the network
if (model_mimic != null){
if (drawNet_file != null)
drawNet.export(drawNet_file);
if (playNet_file != null)
playNet.export(playNet_file);
//Deep learning stopping criteria
//If no improvement, add another deep learning layer
if (DL_layers <= DL_maxlayers && DL_stop.epoch(p)){
DL_stop.reset();
p.resetModel();
deepLearn();
}
}
}
|
e3423437-ec01-47e3-9da8-d11de46925de
| 2
|
private void setGroupNames(String username, String[] groups) {
Vector<String> v = null;
if (groups == null) {
v = emptyVector;
} else {
v = new Vector<String>(groups.length + 1);
for (int i = 0; i < groups.length; i++) {
v.add(groups[i]);
}
}
synchronized (this) {
groupCache.put(username, v);
}
}
|
84e906b7-f933-46c9-a7fb-f096eb8ee2f8
| 5
|
public void init() {
// TODO Auto-generated method stub
try {
//setCurMap(new TiledMap("assets/grassmap.tmx"));
setCurMap(new TiledMap(map));
}
catch (SlickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// could not find the map brooo!!! BBOOOOMMMMM!!!!!
}
// Build MapCollision Array based on tile properties in the TileD map
blocked = new boolean[getCurMap().getWidth()][getCurMap().getHeight()];
// Create an Array of MapNodes for the nodeMap
nodeMap = new MapNode[getCurMap().getWidth()][getCurMap().getHeight()];
// Assign tempX/Y Values for the starting positions (These should be half the tile size)
int tempX = (TILESIZE/2), tempY = (TILESIZE/2);
// Loop through the map and begin filling our arrays.
for (int xAxis=0;xAxis<getCurMap().getWidth(); xAxis++) {
// Set the initial position for the yAxis
tempY = (TILESIZE/2);
// Loop through the yAxis
for (int yAxis=0;yAxis<getCurMap().getHeight(); yAxis++) {
// Assign a tile ID based on the x/yAxis CoOrds of the Map
int tileID = getCurMap().getTileId(xAxis, yAxis, 0);
// set the value of blocked as false if tileID matches
String value = getCurMap().getTileProperty(tileID, "blocked", "false");
// Create a new mapNode & initialize it at this location using tempX/Y
//TODO Fuck yeah looks like i fixed the nodes spawning erry where.
if (getCurMap().getTileImage(xAxis, yAxis, 0) != null) {
nodeMap[xAxis][yAxis] = new MapNode();
nodeMap[xAxis][yAxis].initMapNode(tempX, tempY, tileID);
}
// if the value of blocked matches true, change from false to true
if ("true".equals(value)) {
blocked[xAxis][yAxis] = true;
nodeMap[xAxis][yAxis].setBlocked(true);
}
// Increment the y Axis
tempY += (TILESIZE);
}
// Increment the x Axis
tempX += (TILESIZE);
}
}
|
dc98e8aa-dd65-4155-a513-cf24ed5a4f1d
| 1
|
public void visit_lushr(final Instruction inst) {
stackHeight -= 3;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += 2;
}
|
8539c196-7ac5-4eef-a4b3-fcb7a3132f43
| 0
|
public void addFind(int i, String s) {
this.finds.add(i, s);
}
|
71e32417-452e-4876-8467-1758882ba872
| 5
|
@Override
protected boolean evaluateLayer(final T baseValue, final T testValue) {
if (baseValue instanceof Integer) {
return testValue.intValue() < baseValue.intValue();
} else if (baseValue instanceof Float) {
return testValue.floatValue() < baseValue.floatValue();
} else if (baseValue instanceof Double) {
return testValue.doubleValue() < baseValue.doubleValue();
} else if (baseValue instanceof Long) {
return testValue.longValue() < baseValue.longValue();
} else if (baseValue instanceof Short) {
return testValue.shortValue() < baseValue.shortValue();
} else {
throw new IllegalArgumentException("API cannot compare type " + baseValue.getClass());
}
}
|
b072d4c3-bf1f-43f0-b031-a36f01ffece8
| 1
|
public void delegateLoadingOf(String classname) {
if (classname.endsWith("."))
notDefinedPackages.addElement(classname);
else
notDefinedHere.put(classname, this);
}
|
44564e54-2a3a-4816-9bce-61786d5b1bdd
| 0
|
@EventHandler
public void init(FMLInitializationEvent event)
{
}
|
41fdff1e-affb-43bd-abc6-cd1a73dd31da
| 8
|
private void crearMazo(){
for(int x=0; x<40; x++){
//condicionales que asigna distintos palos a las cartas
if(x<10){
if(x<7){
mazo[x] = new Carta(x+1,"Espada");
}else{
mazo[x] = new Carta(x+3,"Espada");
}
}else if(x < 20){
if(x<17){
mazo[x] = new Carta((x-10)+1,"Oro");
}else{
mazo[x] = new Carta((x-10)+3,"Oro");
}
}else if(x < 30){
if(x<27){
mazo[x] = new Carta((x-20)+1,"Basto");
}else{
mazo[x] = new Carta((x-20)+3,"Basto");
}
}else{
if(x<37){
mazo[x] = new Carta((x-30)+1,"Copa");
}else{
mazo[x] = new Carta((x-30)+3,"Copa");
}
}
}
}
|
bdda7397-fb51-4ac8-a4cb-93293cc0ce8b
| 0
|
public SimpleFileFormat() {}
|
30aa46b7-dfd1-4584-8e88-48af497672e3
| 2
|
public final void useType(Type type) {
if (type instanceof ArrayType)
useType(((ArrayType) type).getElementType());
else if (type instanceof ClassInterfacesType)
useClass(((ClassInterfacesType) type).getClassInfo());
}
|
75594df1-4304-47ec-9641-6267227097f3
| 8
|
public boolean isContinuousForRC(int curRes, int curAA, int curRC){
//Check if the DOF can be continuously minimized in the given RC,
//i.e. there is an interval of nonzero width compatible with the RC
if( intervals == null )
return false;
//Convert curRes (numbered among all flexible residues) to numbering among
//affected residue
int ares = -1;
for(int a=0; a<flexResAffected.length; a++){
if(flexResAffected[a] == curRes){
ares = a;
break;
}
}
if(ares==-1)//This DOF doesn't affect curRes so the effect can't be continuous
return false;
for( int intNum=0; intNum<intervals.length; intNum++ ){
double[] interval = intervals[intNum];
if(interval != null){
if( interval[1] != interval[0] ){
if(compatibleRCs[intNum][ares][curAA].get(curRC))
return true;
}
}
}
return false;
}
|
6a2dbc76-1d1e-4b08-998c-04e480df17d7
| 1
|
@Test
public void testGetValue() {
Genotype g = new Genotype(1, 1);
Agent a;
try {
a = new Agent(g, 0, 0, 0);
HungerInputNeuron neuron = new HungerInputNeuron(a);
assertEquals("New agent should have 0 hunger.", 0.0, neuron.getValue(), 0);
} catch (WeigthNumberNotMatchException e) {
fail("Error while creating owner agent.");
};
}
|
5e18296a-ae21-4ae2-bb51-f828e62c64b4
| 0
|
private DeviceType(String name) {
this.name = name;
}
|
4d9fba94-7f76-4f43-96de-b42b4950613d
| 4
|
private int calculateOffset(int original, int watermark, Alignment alignment) {
if (alignment == HorizontalAlignment.LEFT || alignment == VerticalAlignment.TOP) {
return 0;
}
if (alignment == HorizontalAlignment.RIGHT || alignment == VerticalAlignment.BOTTOM) {
return original - watermark;
}
return original / 2 - watermark / 2;
}
|
0fbf3d3d-db9e-44c6-a34c-ed474535d6fc
| 9
|
public StringBuffer format(double number, StringBuffer toAppendTo,
FieldPosition pos) {
StringBuffer s = new StringBuffer( nf.format(number) );
if( s.length() > width ) {
if( s.charAt(0) == ' ' && s.length() == width + 1 ) {
s.deleteCharAt(0);
}
else {
s.setLength( width );
for( int i = 0; i < width; i ++ )
s.setCharAt(i, '*');
}
}
else {
for (int i = 0; i < width - s.length(); i++) // padding
s.insert(0,' ');
}
if( !trailing && decimal > 0 ) { // delete trailing zeros
while( s.charAt( s.length()-1 ) == '0' )
s.deleteCharAt( s.length()-1 );
if( s.charAt( s.length()-1 ) == '.' )
s.deleteCharAt( s.length()-1 );
}
return toAppendTo.append( s );
}
|
caa5785d-5e14-4e2d-a81b-5010e576f5eb
| 8
|
public void printTree() throws CloneNotSupportedException {
int korkeus = laskeKorkeus(this.getRoot());
int tamanHetkinenKorkeus = korkeus;
int solmujenMaara = 1;
int korkeudenLaskemisraja = 1;
boolean tulostetaankoEkatValit = true;
// Tehdään puusta "täydellinen" puu
Binarytree copyTree = (Binarytree) this.clone();
Binarytree binarytree = teePuustaTaydellinen(copyTree, korkeus);
LinkedList list = new LinkedList(binarytree.getRoot());
Node nykyinen = list.getHeadNode();
while (list.getSize() != 0) {
if (tulostetaankoEkatValit) {
tulostaValeja(getValienMaara(tamanHetkinenKorkeus));
}
if (!tulostetaankoEkatValit) {
tulostaValeja(getValienMaara(tamanHetkinenKorkeus + 1));
}
tulostetaankoEkatValit = false;
if (list.getHeadNode().onkoNull == false) {
System.out.print(list.getHeadKey());
}
if (list.getHeadNode().onkoNull == true) {
System.out.print(" ");
}
// Jos jonon päällä on vasen lapsi, laitetaan se jonoon
if (nykyinen.left != null) {
list.add(nykyinen.left);
}
// Jos jonon päällä on oikea lapsi, laitetaan se jonoon
if (nykyinen.right != null) {
list.add(nykyinen.right);
}
list.removeHead();
nykyinen = list.getHeadNode();
if (korkeudenLaskemisraja <= solmujenMaara) {
System.out.println("");
tulostetaankoEkatValit = true;
korkeudenLaskemisraja = korkeudenLaskemisraja * 2 + 1;
tamanHetkinenKorkeus--;
}
solmujenMaara++;
}
}
|
12319529-d7da-436a-a4fc-cafac7e3def2
| 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(gayan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(gayan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(gayan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(gayan.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 gayan().setVisible(true);
}
});
}
|
41bab783-99de-482c-b0ae-f9fdbbc3afe9
| 3
|
public OximataAdd(int editId) {
/*
* parathiro gia prosthiki oximatos an to editId einai 0 i epe3ergasia an einai megaluterao tou 0
*/
con = new Mysql();
id=editId;
if(id==0) //emfanizei ton katalilo titlo analoga thn leitourgia pou exei epilex8ei
setTitle("Prosthiki Oxhmatos");
else
setTitle("Epe3ergasia Oxhmatos");
/* vgazei to para8uro sto kedro tis othonis me diastaseis 300x220 */
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setBounds(dim.width/2-150, dim.height/2-110, 300, 220);
/*--------------*/
this.setResizable(false);
getContentPane().setBackground(Color.WHITE);
getContentPane().setLayout(null);
JLabel kodikosLabel = new JLabel("Kwdikos:");
kodikosLabel.setBounds(10, 11, 70, 14);
getContentPane().add(kodikosLabel);
JLabel diadromiLabel = new JLabel("Diadromi:");
diadromiLabel.setBounds(10, 36, 70, 14);
getContentPane().add(diadromiLabel);
kodikos = new JTextField();
kodikos.setBounds(101, 8, 125, 20);
getContentPane().add(kodikos);
kodikos.setColumns(10);
diadromi = new JTextField();
diadromi.setBounds(101, 33, 125, 20);
getContentPane().add(diadromi);
diadromi.setColumns(10);
JButton saveButton = new JButton("Save");
saveButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
/*
* apothikeuei sthn vash ta stoixia tou oximatos afou kanei elegxo se auta prwta
*/
String kodikosValue=kodikos.getText();
String diadromiValue=diadromi.getText();
if(checkData(kodikosValue,diadromiValue))
save(kodikosValue,diadromiValue);
}
});
saveButton.setBounds(101, 141, 125, 40);
getContentPane().add(saveButton);
if(id!=0){
getOximaForEdit(id);
}
}
|
d262e3d6-b3b8-4cf1-93e9-93a6876fdcdd
| 9
|
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(numberStorage != null)
{
Set<Integer> keys = numberStorage.getKeys();
int maxCount = numberStorage.getMaxValue();
int minCount = numberStorage.getMinValue();
int totalCount = numberStorage.getTotalCount();
int numbKeys = keys.size();
double expectedCount = (double)totalCount/numbKeys;
int widthPerKey = this.getWidth()/numbKeys;
int horizOffset = 0;
int currValue, currHeight;
double squaredDeviation, variance = 0;
DecimalFormat df;
if(totalCount <= 100)
df = new DecimalFormat("#.##");
else
df = new DecimalFormat("#.####");
Color boxColor, textColor;
for( int currKey : keys )
{
currValue = numberStorage.getCountForKey(currKey);
currHeight = currValue*this.getHeight()/maxCount;
squaredDeviation = (currValue - expectedCount)*(currValue - expectedCount);
variance += squaredDeviation;
int clr = 120 + (int)((currValue - expectedCount)*300/expectedCount);
if( clr > 220 )
clr = 220;
else if ( clr < 30 )
clr = 30;
if( currValue < expectedCount )
boxColor = new Color(0, clr, 0 );
else
boxColor = new Color(0, 0, clr);
if(currValue == maxCount)
boxColor = Color.red;
else if (currValue == minCount)
boxColor = Color.yellow;
g.setColor(boxColor);
g.fillRect(horizOffset, this.getHeight() - currHeight - 20,
widthPerKey, currHeight - 20);
g.setColor(Color.black);
g.drawRect(horizOffset, this.getHeight() - currHeight - 20,
widthPerKey, currHeight - 20);
textColor = Color.white;
if( boxColor.equals(Color.yellow))
textColor = Color.black;
g.setColor(textColor);
g.drawString(""+currValue, horizOffset+2,this.getHeight() - 60);
g.drawString(df.format((currValue - expectedCount)/expectedCount), horizOffset+2,this.getHeight() - 40);
horizOffset += widthPerKey;
}
variance /= (numbKeys - 1);
g.setColor(Color.black);
g.drawString("variance is: " + df.format(variance) + " and standard deviation is: " + df.format(Math.sqrt(variance)), 20, this.getHeight() - 20);
}
}
|
e69ea8a5-6e29-4f6e-b215-93a9580e101d
| 9
|
public Set<Action> actions(Object state) {
Sudoku sudoku = (Sudoku) state;
int grille[][] = sudoku.getGrille();
Set<Action> actions = new LinkedHashSet<Action>();
// boolean positionTrouve = false;
// // Genere exception Java heap space
// for(int i = 0; i < 9 ; i++){
// for(int j = 0; j < 9 ; j++){
// if(grille[i][j] == 0 && !positionTrouve){
// for(int k = 1 ; k <= 9 ; k++){
// Action casse = new DynamicAction(""+k);
// actions.add(casse);
// }
// positionTrouve = true;
// }
// }
// }
// //mieux que avant mais trop de temps
// boolean positionTrouve = false;
// LinkedList<String> numbers = new LinkedList<String>();
// for(int i = 1 ; i <=9 ; i++ ){
// numbers.add(i+"");
// }
//
// for(int i = 0; i < 9 ; i++){
// for(int j = 0; j < 9 ; j++){
//
// if(grille[i][j] == 0 && !positionTrouve){
//
// positionTrouve = true;
//
// //Elimination de numbers dans les lignes et colonnes
// for(int k = 0 ; k < 9 ; k++ ){
// numbers.remove(grille[i][k]+"");
// numbers.remove(grille[k][j]+"");
// }
//
// //Elimination de numbers dans la sous-grille 3x3
// for(int m = 0 ; m < 3 ; m++){
// for(int n = 0 ; n < 3 ; n++ ){
// int p = (i/3)*3 + m;
// int q = (j/3)*3 + n;
// numbers.remove(grille[p][q]+"");
// }
// }
//
// //Creation des actions
// for(String number : numbers){
// Action casse = new DynamicAction(i+""+j+""+number);
// actions.add(casse);
// }
// }
// }
// }
//Bonne implementation
int min = 9;
for(int i = 0; i < 9 ; i++){
for(int j = 0; j < 9 ; j++){
if(grille[i][j] == 0 ){
Set<String> numbers = new LinkedHashSet<String>();
for(int n = 1 ; n <=9 ; n++ ){
numbers.add(n+"");
}
//Elimination de numbers dans les lignes et colonnes
for(int k = 0 ; k < 9 ; k++ ){
numbers.remove(grille[i][k]+"");
numbers.remove(grille[k][j]+"");
}
//Elimination de numbers dans la sous-grille 3x3
for(int m = 0 ; m < 3 ; m++){
for(int n = 0 ; n < 3 ; n++ ){
int p = (i/3)*3 + m;
int q = (j/3)*3 + n;
numbers.remove(grille[p][q]+"");
}
}
if(numbers.size() < min ){
min = numbers.size();
actions.clear();
for(String number : numbers){
Action casse = Sudoku.actions.get(i+""+j+""+number);
actions.add(casse);
}
}
}
}
}
// //profondeur d'abord bad bad
// int min = 9;
//
// for(int i = 0; i < 9 ; i++){
// for(int j = 0; j < 9 ; j++){
//
// if(grille[i][j] == 0 ){
//
// Set<String> numbers = new LinkedHashSet<String>();
// for(int n = 1 ; n <=9 ; n++ ){
// numbers.add(n+"");
// }
//
// //Elimination de numbers dans les lignes et colonnes
// for(int k = 0 ; k < 9 ; k++ ){
// numbers.remove(grille[i][k]+"");
// numbers.remove(grille[k][j]+"");
// }
//
// //Elimination de numbers dans la sous-grille 3x3
// for(int m = 0 ; m < 3 ; m++){
// for(int n = 0 ; n < 3 ; n++ ){
// int p = (i/3)*3 + m;
// int q = (j/3)*3 + n;
// numbers.remove(grille[p][q]+"");
// }
// }
//
// for(String number : numbers){
// Action casse = Sudoku.actions.get(i+""+j+""+number);
// actions.add(casse);
// }
// }
// }
// }
return actions;
}
|
ba221025-5595-4c4d-806a-073b067961a7
| 4
|
public void createPanel(JPanel mainPanel) {
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
mainPanel.add(contentPane);
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
JPanel panel = new JPanel();
contentPane.add(panel);
panel.setLayout(null);
JList list;
final DefaultListModel model;
model = new DefaultListModel();
list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
JScrollPane pane = new JScrollPane(list);
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent mouseEvent) {
JList MessageList = (JList) mouseEvent.getSource();
if (mouseEvent.getClickCount() == 2) {
int index = MessageList.locationToIndex(mouseEvent.getPoint());
if (index >= 0) {
Message message = mLogic.getMessage(index);
SingleMessage popUp = new SingleMessage(message);
popUp.setVisible(true);
}
}
}
};
list.addMouseListener(mouseListener);
int length = mLogic.getLength();
for (int i = 0; i < length; i++) {
Message message = mLogic.getMessage(i);
model.addElement(message.toString());
}
contentPane.add(pane);
JButton btnNewButton = new JButton("Refresh");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int length = mLogic.getLength();
model.clear();
for (int i = 0; i < length; i++) {
Message message = mLogic.getMessage(i);
model.addElement(message.toString());
}
}
});
contentPane.add(Box.createRigidArea(new Dimension(0, 10)));
contentPane.add(btnNewButton);
}
|
5b8387b4-7dd2-4be8-9d08-cac95084f1ca
| 1
|
public void update(float dt) {
for(Letter letter: this.lettersOnTheTable){
letter.update(dt);
}
checkingPlatform.update(dt);
hero.update(dt);
monster.update(dt);
timer.update(dt);
checkForBodiesToDelete();
}
|
1d0eda9e-3102-449f-954b-b849cc1806d9
| 7
|
public EditorData(int index,String header,String dataUrl){
this.url=dataUrl;
this.id=index;
HorizontalPanel upPanel=new HorizontalPanel();
add(upPanel);
HorizontalPanel downPanel=new HorizontalPanel();
add(downPanel);
String[] headerValues=header.split("\t");
title = new Label(headerValues[0]);
title.setWidth("120px");
upPanel.add(title);
Button rename=new Button("rename");
rename.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
String newName=Window.prompt("new name", title.getText());
if(newName!=null){
title.setText(newName);
saveValue();
}
}
});
upPanel.add(rename);
Button delate=new Button("delate");
delate.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
//confirm
boolean result=Window.confirm("delate sound:"+title.getText()+"?");
if(!result){
return;
}
storageDataList.clearData(id);
updateEditorDatas();
updatePlayerDatas();
}
});
upPanel.add(delate);
loop = new CheckBox("Loop");
downPanel.add(loop);
if(headerValues.length>1){
try{
boolean checked=Boolean.parseBoolean(headerValues[1]);
loop.setValue(checked);
}catch(Exception e){}
}
loop.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
saveValue();
}
});
downPanel.add(new Label("Vol:"));
volume = new VolumeRadioboxes();
downPanel.add(volume);
if(headerValues.length>2){
try{
double v=Double.parseDouble(headerValues[2]);
volume.setVolume(v);
}catch(Exception e){}
}
volume.addListener(new VolumeRadioboxesListener() {
@Override
public void changed(int newValue) {
saveValue();
}
});
PushButton play=new PushButton(new Image(Bundles.instance.play()));
play.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
AudioResourceParameter param=AudioResource.params().loop(loop.getValue()).volume(volume.getVolume());
sound = SoundUtils.createPlayableSound(url,param);
sound.play();
}
});
downPanel.add(play);
PushButton stop=new PushButton(new Image(Bundles.instance.stop2()));
stop.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if(sound!=null){
sound.stop();
}
}
});
downPanel.add(stop);
}
|
388a9292-344f-4e33-9cb8-673427d1e3ee
| 0
|
public void onMessage(IMessage message) throws JFException {
}
|
a5cc44ae-e6db-4b02-a4cb-5427fd843c0a
| 9
|
@Override
public HeightMap applyTo(HeightMap... heightMaps){
double[][] finalHeights = heightMaps[0].getHeights().clone();
double[][] newHeights = heightMaps[0].getHeights();
int xSize = finalHeights.length;
int ySize = finalHeights[0].length;
for(int iteration = 0; iteration<numIterations; iteration++) {
if (iteration % 10 == 0) System.out.println("AverageFilter " + 100 * iteration / numIterations + "% complete");
finalHeights = newHeights;
for (int x = 0; x < xSize; x++) {
for (int y = 0; y < ySize; y++) {
//for non-reversed, move a quantity equal to (maxDifference-tAngle)/2
double heightDifference = maxDifference(
finalHeights[x][y],
finalHeights[(x+xSize-1)%xSize][(y+ySize-1)%ySize],
finalHeights[(x+xSize-1)%xSize][(y+1)%ySize],
finalHeights[(x+1)%xSize][(y+ySize-1)%ySize],
finalHeights[(x+1)%xSize][(y+1)%ySize]
);
//if the maximum difference is less than the talus angle,
//find the neighbor with the most difference and give it some of the center's soil
if(heightDifference<tAngle){
//System.out.println("\nHeight difference: "+heightDifference);
//System.out.println("Height before: "+finalHeights[x][y]);
if(abs(finalHeights[(x+xSize-1)%xSize][(y+ySize-1)%ySize] - finalHeights[x][y]) == heightDifference){
newHeights[x][y] -= heightDifference*solubility;
newHeights[(x+xSize-1)%xSize][(y+ySize-1)%ySize]+=heightDifference*solubility;
}
else if(abs(finalHeights[(x+xSize-1)%xSize][(y+ySize+1)%ySize] - finalHeights[x][y]) == heightDifference){
newHeights[x][y] -= heightDifference*solubility;
newHeights[(x+xSize-1)%xSize][(y+1)%ySize]+=heightDifference*solubility;
}
else if(abs(finalHeights[(x+xSize+1)%xSize][(y+ySize-1)%ySize] - finalHeights[x][y]) == heightDifference){
newHeights[x][y] -= heightDifference*solubility;
newHeights[(x+1)%xSize][(y+ySize-1)%ySize]+=heightDifference*solubility;
}
else if(abs(finalHeights[(x+xSize+1)%xSize][(y+ySize+1)%ySize] - finalHeights[x][y]) == heightDifference){
newHeights[x][y] -= heightDifference*solubility;
newHeights[(x+1)%xSize][(y+1)%ySize]+=heightDifference*solubility;
}
//System.out.println("Height after: "+finalHeights[x][y]);
}
}
}
}
return new HeightMap(finalHeights);
}
|
0e9f56a7-5632-4875-94b7-1c582035a4cb
| 3
|
public void InsertaMedio (int ElemInser,int Posicion)
{
if (VaciaLista())
{
PrimerNodo = new NodosProcesos (ElemInser);
PrimerNodo.siguiente = PrimerNodo;
}
else
{
if (Posicion<=1)
InsertaInicio(ElemInser);
else
{
NodosProcesos Aux = PrimerNodo;
int i = 2;
while ( (i != Posicion) & (Aux.siguiente != PrimerNodo))
{
i++;
Aux = Aux.siguiente;
}
NodosProcesos Nuevo = new NodosProcesos(ElemInser);
Nuevo.siguiente = Aux.siguiente;
Aux.siguiente =Nuevo;
}
}
}
|
3cdadfc5-fc03-4f76-9adf-65e5fed5fade
| 3
|
public void loadMap() {
try {
InputStream in = getClass().getResourceAsStream(src);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
numCols = Integer.parseInt(br.readLine());
numRows = Integer.parseInt(br.readLine());
width = numCols * tileSize;
height = numRows * tileSize;
xmin = 0;
xmax = width - GamePanel.WIDTH;
ymin = 0;
ymax = height - GamePanel.HEIGHT;
map = new int[numCols][numRows];
for(int row = 0; row < numRows; row++) {
String line = br.readLine();
String [] tokens = line.split("\\s+");
for(int col = 0; col < numCols; col++) {
map[col][row] = Integer.parseInt(tokens[col]);
}
}
}
catch(Exception e) {
e.printStackTrace();
}
}
|
19be62c4-77a2-4f9d-9f79-27357e347a19
| 7
|
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
for (int i = 0; i < n; i++) {
int len = Integer.parseInt(br.readLine());
String[] in = br.readLine().split(" ");
int pred = Integer.MAX_VALUE;
int count = 0;
for (int j = 0; j < len; j++) {
if (Integer.parseInt(in[j]) == pred) {
count++;
} else {
count--;
if (count <= 0) {
count = 0;
pred = Integer.parseInt(in[j]);
}
}
}
count = 0;
for (int j = 0; j < len; j++) {
if (Integer.parseInt(in[j]) == pred) {
count++;
}
}
if (count > len / 2)
System.out.println("Yes " + pred);
else
System.out.println("No");
}
}
|
53a28d2e-5c30-481c-8d92-ee8c13897e9e
| 2
|
private void increasePoolSizePercent(int increment) throws SQLException
{
synchronized (this.mutex)
{
double percincr = 1 + (increment / 100.0);
int newsize = (int) (pool.size() * percincr);
if (newsize <= pool.size())
{
newsize = pool.size() + 1;
}
LOGGER.fine("Increasing pool size from " + pool.size() + " to " + newsize + " connections.");
while (pool.size() < newsize)
{
pool.add(new ConnectionWrapper(DriverManager.getConnection(this.dataBase, this.userName, this.password)));
}
}
}
|
0c89f5c1-f82c-4ea0-9bb6-446bb5f9b86f
| 6
|
private void drawLines(int[][] lines, Graphics2D g, boolean addToX)
{
for (int line = 0; line < lines.length; line++)
{
for (int i = 0; i < lines[line].length; i += 2)
{
int grid = 30;
int p1 = xTop + lines[line][i] * grid;
int p2 = yTop + line * grid;
int x1 = addToX ? p1 : p2;
int y1 = addToX ? p2 : p1;
int length = lines[line][i + 1] * grid;
int x2 = addToX ? x1 + length : x1;
int y2 = addToX ? y1 : y1 + length;
g.draw(new Line2D.Double(x1, y1, x2, y2));
}
}
}
|
2cfa851a-a808-4a49-b025-7e38e80137c5
| 8
|
private int findIndexByKeyEvent(KeyEvent keyEvent) {
for (int i = 0; i < icons.size(); i++) {
IconInformation info = (IconInformation) icons.get(i);
final KeyStroke iconKeyStroke = info.getKeyStroke();
if (iconKeyStroke != null
&& (keyEvent.getKeyCode() == iconKeyStroke.getKeyCode()
&& keyEvent.getKeyCode() != 0
&& (iconKeyStroke.getModifiers() & KeyEvent.SHIFT_MASK) == (keyEvent
.getModifiers() & KeyEvent.SHIFT_MASK) || keyEvent
.getKeyChar() == iconKeyStroke.getKeyChar())
&& keyEvent.getKeyChar() != 0
&& keyEvent.getKeyChar() != KeyEvent.CHAR_UNDEFINED) {
return i;
}
}
return -1;
}
|
93214263-a3a7-408c-99d2-6280c02651ce
| 5
|
private String read() throws IOException, EOFException, InterruptedIOException
{
StringBuffer buffer = new StringBuffer();
int codePoint;
boolean zeroByteRead=false;
if (DEBUG) System.out.println("Reading...");
do
{
codePoint=_socketIn.read();
if (codePoint==0) zeroByteRead=true;
else buffer.appendCodePoint( codePoint );
}
while (!zeroByteRead && buffer.length()<100);
if (DEBUG) System.out.println("Read: "+buffer.toString());
return buffer.toString();
}
|
aebd73d9-3f85-416e-887b-852197f5534a
| 9
|
public void submit() {
String Benutzername = nameTextPane.getText();
if (Benutzername.length() <= 0) {
JOptionPane.showMessageDialog(this, "Your username must have at least one character.", "Oh, come on...", JOptionPane.WARNING_MESSAGE);
} else if (Benutzername.length() > 16) {
JOptionPane.showMessageDialog(this, "Your username must be shorter than 16 characters.", "Now hold on there...", JOptionPane.WARNING_MESSAGE);
} else if (selectedPlanet == 0) {
JOptionPane.showMessageDialog(this, "You must select a planet.", "Hold your horses...", JOptionPane.WARNING_MESSAGE);
} else {
// send data to XML file
String character = "Earth"; //default
// 1=Ora Uhlsax, 2 = Neslaou, 3 = Earth, 4 = Gigolo
if(selectedPlanet == 1){
character = "OraUhlsax";
} else if(selectedPlanet == 2){
character = "Neslaou";
} else if(selectedPlanet == 3){
character = "Earth";
} else if(selectedPlanet == 4){
character = "Gigolo";
}
String rec = Client.sendMsg("CREATE_PLAYER "+Benutzername+" "+character);
if(rec.contains("SUCCESS")){
new JoinGameGUI();
new Chat();
this.dispose();
} else if(rec.contains("XML")){
JOptionPane.showMessageDialog(this, "DataBase error. Please contact your server.", "Uh oh...", JOptionPane.WARNING_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "Your username is taken. Choose a different one.", "Dangit "+Benutzername+"!", JOptionPane.WARNING_MESSAGE);
}
}
}
|
80b24506-25f3-415e-8f56-cd4e3971d5a0
| 7
|
public static void test(Class<?> surroundingClass){
for(Class<?> type : surroundingClass.getClasses()){
System.out.println(type.getSimpleName() + ": ");
try{
Generator<?> g = (Generator<?>) type.newInstance();
for(int i = 0 ; i < size; i++)
System.out.println(g.next() + " ");
System.out.println();
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
|
a115779e-6602-498d-b74c-2547d2915b50
| 2
|
public Transition addIncomingTransition(Transition t) {
if(t != null && !incomingTransitions.contains(t)) {
incomingTransitions.add(t);
return t;
}
return null;
}
|
de29fde5-de2f-4903-b461-7583b3af854b
| 8
|
public static void main(String[] args) throws Throwable{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
for(int c = 0, C = parseInt(in.readLine().trim()); c++ < C; ){
StringTokenizer st = new StringTokenizer(in.readLine());
int W = abs(parseInt(st.nextToken()) - parseInt(st.nextToken()));
int N = parseInt(in.readLine());
int[][] coins = new int[N][2];
for(int i = 0; i < N; i++){
st = new StringTokenizer(in.readLine());
coins[i][0] = parseInt(st.nextToken());
coins[i][1] = parseInt(st.nextToken());
}
long[] mem = new long[W+1];
Arrays.fill(mem, MAX_VALUE);
mem[0] = 0;
for(int[] coin: coins)
for(int i = 0; i < W+1; i++)
if(mem[i]!=MAX_VALUE&&i+coin[1]<W+1&&mem[i+coin[1]]>mem[i]+coin[0])
mem[i+coin[1]]=mem[i]+coin[0];
sb.append(mem[W]==MAX_VALUE?"This is impossible.\n":("The minimum amount of money in the piggy-bank is " + mem[W] + ".\n"));
}
System.out.print(new String(sb));
}
|
60eab88b-252b-40d5-bfbc-3759df63f59d
| 7
|
private void handle(Object input) {
if (input instanceof Datagram) {
TransitionEvent event = getTransitionEventFromDatagram((Datagram) input);
try {
this.fsm.handleEvent(event);
if(this.fsm.getCurrentState() != null && "acked".equals(this.fsm.getCurrentState().getIdentifier())) {
if(Statics.RX_HELI.equals(this.mode)) {
this.fsm.handleEvent(new TransitionEvent("sendMode_receive"));
} else {
this.fsm.handleEvent(new TransitionEvent("sendMode_send"));
}
}
if(this.fsm.getCurrentState() != null && "finished".equals(this.fsm.getCurrentState().getIdentifier())) {
this.fsm.handleEvent(new TransitionEvent(Statics.SHUTDOWN));
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.err.println("Unknown type " + input.getClass() + " discarding package");
}
}
|
1a680442-3ba4-4149-9b45-59a81a928665
| 1
|
@Override
public String execute(HttpServletRequest request) {
String text = request.getParameter("text");
Text nText = Parser.parseText(text);
List<Sentence> sentences = new ArrayList<>();
for (int i = 0; i < nText.getElements().size(); i++) {
sentences.addAll(nText.getElements().get(i).getElements());
}
request.setAttribute("text", nText);
request.setAttribute("paragraph", nText.getElements());
request.setAttribute("sentence", sentences);
return "/WEB-INF/result.jsp";
}
|
0899e163-a157-48c9-b8e4-e46587d5e284
| 8
|
private void langSelector_settingsListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_langSelector_settingsListValueChanged
if (langSelector_settingsList.getSelectedValue() == null)
return;
String oldLang = String.valueOf(settings.getLanguage());
String newLang = langSelector_settingsList.getSelectedValue().toString();
try {
if (debug && !oldLang.equals(newLang))
logger.log(Level.DEBUG, "Setting preference \"language\" from " + settings.getLanguage() + " to " + newLang);
settings.setLanguage(newLang);
parser.parse(settings.getLanguage(), logger, debug);
loadTranslation();
deviceManager.loadTranslations();
switch (Language.valueOf(newLang)) {
case en_gb:
this.setSize(800, 500);
return;
case sp_la:
this.setSize(990, 500);
case de_de:
setSize(850, 500);
}
if (SHOW_LANG_MSG)
JOptionPane.showMessageDialog(null, parser.parse("langChangedMsg"), parser.parse("langChangedMsgTitle"), JOptionPane.INFORMATION_MESSAGE);
else
SHOW_LANG_MSG = true;
} catch (IOException ex) {
logger.log(Level.ERROR, "An error occurred while loading the new language: " + ex.toString() + "\n"
+ "Please save the settings and restart Universal Android Toolkit.\n"
+ "The error stack trace will be printed to the console...");
ex.printStackTrace(System.err);
}
}//GEN-LAST:event_langSelector_settingsListValueChanged
|
020c2b37-cf74-44af-8a57-3b81fe0c9151
| 5
|
private static String intArrayToString(int[] sa) throws Exception
{
StringBuffer res=new StringBuffer();
for(int i=0;i<sa.length;i++)
{
int ii=sa[i];
char ch0=(char) (ii& 0xFF);
char ch1=(char) (ii>>>8& 0xFF);
char ch2=(char) (ii>>>16& 0xFF);
char ch3=(char) (ii>>>24& 0xFF);
if(ch0!=0)
res.append(ch0);
if(ch1!=0)
res.append(ch1);
if(ch2!=0)
res.append(ch2);
if(ch3!=0)
res.append(ch3);
}
return res.toString();
}
|
29a6e87d-903f-4cfc-9560-8c17fa82362e
| 2
|
public static void main(String[] args) {
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ClientGUI frame = new ClientGUI();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
|
e0e19314-4959-41ca-9451-6ff9cd2e327a
| 3
|
private void determineOrbits() {
int maxPerOrbit = Math.min((int) (baseOrbit.getCircumference() / componentSize), this.getNumSubComponents());
componentTheta = Math.PI*2/maxPerOrbit;
int numOrbits = (int)Math.ceil((double)this.getNumSubComponents() / maxPerOrbit);
orbitCounts = new int[numOrbits];
orbits = new Orbit[numOrbits];
for (int i = 0; i < numOrbits - 1; i++) {
orbitCounts[i] = maxPerOrbit;
}
orbitCounts[orbitCounts.length - 1] = (this.getNumSubComponents() % maxPerOrbit == 0) ? maxPerOrbit : this.getNumSubComponents() % maxPerOrbit;
orbits[0] = baseOrbit;
for (int i = 1; i < numOrbits; i++) {
orbits[i] = new Orbit(baseOrbit.cX, baseOrbit.cY, orbits[i - 1].w + (int)Math.round((1.0 / Math.sqrt(0.8*i))*componentSize*1.5), orbits[i - 1].h + (int)Math.round((1.0 / Math.sqrt(0.8*i))*componentSize*1.5));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.